From eb53eb83d8fee1a07b32b0d1eb02c9915de1aa5b Mon Sep 17 00:00:00 2001 From: Stuart Date: Tue, 22 Sep 2026 18:33:43 +1000 Subject: [PATCH 01/11] feat: wire the redesigned prompt composer, attachments and local suggestions MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The redesigned hero shell shipped the composer markup but never wired it: #hero-send invoked runThinkingPipeline through an inline handler while the pipeline still dereferenced the retired #btn-run-pipeline button outside its try block, so every submission crashed silently and left pipelineState.isRunning stuck true. Chips only copied their prompt, and the ghost layer, tab hint and live announcement were inert markup. Add src/composerAdapter.js and bind it from app.js (initComposer replaces bindHeroChips): the ghost layer mirrors the textarea and surfaces the 13 local prototype suggestion patterns after the prototype's 220ms debounce and six-character gate — no completion provider, credential or network request is involved. Tab accepts only an active suggestion and otherwise moves focus; Escape dismisses; Enter submits unless Shift is held or an IME is composing, so Shift+Enter keeps its newline. Acceptance records the accepted text and cannot re-trigger on it in a loop. Submission goes through the existing pipeline exactly once per action: send follows canSubmit (non-whitespace prompt, idle pipeline), hands its arrow to the spinner while in flight, blocks duplicate submission, and never touches the prompt or attached images, so an error preserves the user's work. Attach and settings keep their existing wiring — the size/count validation in handlePromptImageSelect is untouched and the settings icon still opens the real generation settings. Chips fill their full source prompt behind the demo caret with a settled aria-pressed state, exactly as the prototype specifies. Also define .sr-only inline (the composer label and live region leaned on the Tailwind CDN for it), port the demo caret and busy-field styles with their reduced-motion handling, and guard the legacy run button so surfaces without it stay functional. Cover the wiring with unit tests for the patterns, gates and the tab-accept/escape-dismiss state machine, and a browser suite exercising typing, Tab/Escape, chips, whitespace and duplicate-submission guards, settings, attachment validation and touch controls at 360px and desktop. STU-376 --- app.js | 40 ++-- dist/assets/index-BoEiUhsl.js | 320 +++++++++++++++++++++++++++++++ dist/assets/index-DBT7sHov.js | 320 ------------------------------- dist/index.html | 20 +- e2e/stu376-composer.spec.js | 352 ++++++++++++++++++++++++++++++++++ index.html | 18 +- src/composerAdapter.js | 350 +++++++++++++++++++++++++++++++++ src/composerAdapter.test.js | 169 ++++++++++++++++ 8 files changed, 1244 insertions(+), 345 deletions(-) create mode 100644 dist/assets/index-BoEiUhsl.js delete mode 100644 dist/assets/index-DBT7sHov.js create mode 100644 e2e/stu376-composer.spec.js create mode 100644 src/composerAdapter.js create mode 100644 src/composerAdapter.test.js diff --git a/app.js b/app.js index 3d7cd2f..51b6ece 100644 --- a/app.js +++ b/app.js @@ -61,6 +61,7 @@ import { highlightCode, renderMarkdownAudit, } from "./src/auditRenderer.js"; +import { initComposer } from "./src/composerAdapter.js"; // --- CONFIGURATION --- const IS_DEV = import.meta.env.DEV @@ -3708,11 +3709,15 @@ async function runThinkingPipeline() { pipelineState.isRunning = true; resetPipelineResults(); - btn.disabled = true; - btn.innerHTML = ` - - - Running...`; + // The redesigned hero shell drives the pipeline from #hero-send, so the + // legacy run button is optional; only a surface that has it can show it. + if (btn) { + btn.disabled = true; + btn.innerHTML = ` + + + Running...`; + } // Update model info updateModelInfo(effectiveModel); @@ -3860,11 +3865,13 @@ async function runThinkingPipeline() { updateStepIndicator(errorStep, "error"); } finally { pipelineState.isRunning = false; - btn.disabled = false; - btn.innerHTML = ` - - - Run Pipeline`; + if (btn) { + btn.disabled = false; + btn.innerHTML = ` + + + Run Pipeline`; + } updateDeployButtonVisibility(); } @@ -5143,7 +5150,7 @@ document.addEventListener("DOMContentLoaded", async () => { } }); - bindHeroChips(); + initComposer({ onSubmit: runThinkingPipeline }); restoreViewFromHash(); }); @@ -6531,17 +6538,6 @@ window.addEventListener("hashchange", () => { restoreViewFromHash(); }); -function bindHeroChips() { - const chips = document.querySelectorAll("#example-chips .chip"); - const input = document.getElementById("pipeline-input"); - chips.forEach((chip) => { - chip.addEventListener("click", () => { - if (input) input.value = chip.dataset.prompt || ""; - input?.focus(); - }); - }); -} - window.copyResultsCode = copyResultsCode; window.selectArtifact = selectArtifact; window.selectResultsSummary = selectResultsSummary; diff --git a/dist/assets/index-BoEiUhsl.js b/dist/assets/index-BoEiUhsl.js new file mode 100644 index 0000000..0695d14 --- /dev/null +++ b/dist/assets/index-BoEiUhsl.js @@ -0,0 +1,320 @@ +(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const s of document.querySelectorAll('link[rel="modulepreload"]'))i(s);new MutationObserver(s=>{for(const r of s)if(r.type==="childList")for(const o of r.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&i(o)}).observe(document,{childList:!0,subtree:!0});function n(s){const r={};return s.integrity&&(r.integrity=s.integrity),s.referrerPolicy&&(r.referrerPolicy=s.referrerPolicy),s.crossOrigin==="use-credentials"?r.credentials="include":s.crossOrigin==="anonymous"?r.credentials="omit":r.credentials="same-origin",r}function i(s){if(s.ep)return;s.ep=!0;const r=n(s);fetch(s.href,r)}})();var _=typeof window<"u"?window:void 0,we=typeof globalThis<"u"?globalThis:_,ke=we?.navigator,C=we?.document,se=we?.location,Ko=we?.fetch,Wr=we!=null&&we.XMLHttpRequest&&"withCredentials"in new we.XMLHttpRequest?we.XMLHttpRequest:void 0,Ka=we?.AbortController,Ih=we?.CompressionStream,Fe=ke?.userAgent;function Dc(){return!(!_||_.navigator.onLine===!1)}var Tn=typeof globalThis<"u"?globalThis:_;Tn&&typeof self>"u"&&(Tn.self=Tn),Tn&&typeof File>"u"&&(Tn.File=function(){});var R=_??{},Y={DEBUG:!1,LIB_VERSION:"0.5.0",LIB_NAME:"browser-common"};function Ja(t,e,n,i,s,r,o){try{var a=t[r](o),l=a.value}catch(u){return void n(u)}a.done?e(l):Promise.resolve(l).then(i,s)}function X(t){return function(){var e=this,n=arguments;return new Promise((function(i,s){var r=t.apply(e,n);function o(l){Ja(r,i,s,o,a,"next",l)}function a(l){Ja(r,i,s,o,a,"throw",l)}o(void 0)}))}}function E(){return E=Object.assign?Object.assign.bind():function(t){for(var e=1;arguments.length>e;e++){var n=arguments[e];for(var i in n)({}).hasOwnProperty.call(n,i)&&(t[i]=n[i])}return t},E.apply(null,arguments)}function jc(t,e){if(t==null)return{};var n={};for(var i in t)if({}.hasOwnProperty.call(t,i)){if(e.indexOf(i)!==-1)continue;n[i]=t[i]}return n}var Ya=t=>{if(typeof t!="string")return t;try{return JSON.parse(t)}catch{return t}};function Za(t){return typeof t=="string"||t}function Xa(t){return typeof t=="string"?t:void 0}var Rn,Ch=["$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","irclid","_kx","$session_id","$window_id","$lib","$lib_version","$device_id","$is_server"],pt=(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.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.SurveysSeen="surveys_seen",t.Surveys="surveys",t.RemoteConfig="remote_config",t.FlagsEndpointWasHit="flags_endpoint_was_hit",t.DeviceId="device_id",t})({}),Qa=(function(t){return t.GZipJS="gzip-js",t.Base64="base64",t})({}),Ah=["$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"],Fh=["token"],Uc="NativeGzipValidationError",zr=t=>t.length>=2&&t[0]===31&&t[1]===139,el=(t,e)=>t===Qa.GZipJS||e===Qa.GZipJS||e==="gzip",tl=t=>!(!t||typeof t!="object")&&("name"in t?String(t.name):"")==="NotReadableError",ki=t=>{var e=new Error("Native gzip produced invalid output: "+t);throw e.name=Uc,e},Ph=(function(){var t=X((function*(e,n){18>e.size&&ki("too-short");var i=new Uint8Array(yield e.slice(0,10).arrayBuffer());zr(i)&&i[2]===8||ki("invalid-header");var s=new DataView(yield e.slice(e.size-8).arrayBuffer());s.getUint32(0,!0)!==(o=>{for(var a=(()=>{if(Rn)return Rn;Rn=[];for(var c=0;256>c;c++){for(var d=c,h=0;8>h;h++)d=1&d?3988292384^d>>>1:d>>>1;Rn[c]=d>>>0}return Rn})(),l=4294967295,u=0;o.length>u;u++)l=a[255&(l^o[u])]^l>>>8;return(4294967295^l)>>>0})(n)&&ki("invalid-crc");var r=n.length>>>0;s.getUint32(4,!0)!==r&&ki("invalid-size")}));return function(e,n){return t.apply(this,arguments)}})();function qr(){return qr=X((function*(t,e,n){e===void 0&&(e=!0);try{var i=new TextEncoder().encode(t),s=new globalThis.CompressionStream("gzip"),r=s.writable.getWriter(),o=r.write(i).then((()=>r.close())).catch((function(){var u=X((function*(c){try{yield r.abort(c)}catch{}throw c}));return function(c){return u.apply(this,arguments)}})()),a=new Response(s.readable).blob(),l=(yield Promise.all([a,o]))[0];return yield Ph(l,i),l}catch(u){if(n!=null&&n.rethrow)throw u;return e&&console.error("Failed to gzip compress data",u),null}})),qr.apply(this,arguments)}var $h=["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","pinterest","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"],nl=function(t,e){if(e===void 0&&(e=[]),!t)return!1;var n=t.toLowerCase();return $h.concat(e).some((i=>{var s=i.toLowerCase();return n.indexOf(s)!==-1}))};function L(t,e){return t.indexOf(e)!==-1}var Bs=function(t){return t.trim()},Vr=function(t){return t.replace(/^\$/,"")};function Hc(t){var e,n=[];return(e=JSON.stringify(t,(function(i,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"}var Wc=Object.prototype,zc=Wc.hasOwnProperty,Ds=Wc.toString,O=Array.isArray||function(t){return Ds.call(t)==="[object Array]"},Se=t=>typeof t=="function",ne=t=>t===Object(t)&&!O(t),yt=t=>{if(ne(t)){for(var e in t)if(zc.call(t,e))return!1;return!0}return!1},x=t=>t===void 0,q=t=>Ds.call(t)=="[object String]",Gr=t=>q(t)&&t.trim().length===0,$e=t=>t===null,B=t=>x(t)||$e(t),he=t=>Ds.call(t)=="[object Number]"&&t==t,dt=t=>he(t)&&t>0,Ye=t=>Ds.call(t)==="[object Boolean]",Th=t=>t instanceof FormData,Rh=t=>L(Ah,t),Nh=t=>L(Fh,t);function qc(t){return t===null||typeof t!="object"}function es(t,e){return{}.toString.call(t)==="[object "+e+"]"}function Jo(t){return typeof Event<"u"&&Vc(t,Event)}function Vc(t,e){try{return t instanceof e}catch{return!1}}var Mh=[!0,"true",1,"1","yes"],cr=t=>L(Mh,t),Lh=[!1,"false",0,"0","no"];function ot(t,e,n,i,s){return e>n&&(i.warn("min cannot be greater than max."),e=n),he(t)?t>n?(i.warn(" cannot be greater than max: "+n+". Using max value instead."),n):e>t?(i.warn(" cannot be less than min: "+e+". Using min value instead."),e):t:(i.warn(" must be a number. using max or fallback. max: "+n+", fallback: "+s),ot(s||n,e,n,i))}class Oh{constructor(e){this.tt={},this.et=e.et,this.it=ot(e.bucketSize,0,100,e.rt),this.nt=ot(e.refillRate,0,this.it,e.rt),this.st=ot(e.refillInterval,0,864e5,e.rt)}ot(e,n){var i=Math.floor((n-e.lastAccess)/this.st);i>0&&(e.tokens=Math.min(e.tokens+i*this.nt,this.it),e.lastAccess=e.lastAccess+i*this.st)}consumeRateLimit(e){var n,i=Date.now(),s=String(e),r=this.tt[s];return r?this.ot(r,i):this.tt[s]=r={tokens:this.it,lastAccess:i},r.tokens===0||(r.tokens--,r.tokens===0&&((n=this.et)==null||n.call(this,e)),r.tokens===0)}stop(){this.tt={}}}var Oe="Mobile",ts="iOS",wt="Android",vn="Tablet",Gc=wt+" "+vn,Kc="iPad",Jc="Apple",Yc=Jc+" Watch",Yn="Safari",_n="BlackBerry",Zc="Samsung",Xc=Zc+"Browser",Qc=Zc+" Internet",Yt="Chrome",Bh=Yt+" OS",eu=Yt+" "+ts,Yo="Internet Explorer",tu=Yo+" "+Oe,Zo="Opera",Dh=Zo+" Mini",Xo="Edge",nu="Microsoft "+Xo,fn="Firefox",iu=fn+" "+ts,ri="Nintendo",oi="PlayStation",gn="Xbox",su=wt+" "+Oe,ru=Oe+" "+Yn,Wn="Windows",Kr=Wn+" Phone",il="Nokia",Jr="Ouya",ou="Generic",jh=ou+" "+Oe.toLowerCase(),au=ou+" "+vn.toLowerCase(),Yr="Konqueror",lu="Oculus Browser",ns="Vivaldi",cu="Yandex",is="Whale",Zr="DuckDuckGo",uu="Pale Moon",ss="Waterfox",Zn="Brave",du="Google Search App",le="(\\d+(\\.\\d+)?)",ur=new RegExp("Version/"+le),Uh=new RegExp(gn,"i"),Hh=new RegExp(oi+" \\w+","i"),Wh=new RegExp(ri+" \\w+","i"),Qo=new RegExp(_n+"|PlayBook|BB10","i"),zh={"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"},hu=function(t,e,n,i){e=e||"";var s=(function(r){return r!=null&&r.brave?Zn:null})(n);return s||(i!=null&&i.detectGoogleSearchApp&&L(t,"GSA/")?du:L(t," OPR/")&&L(t,"Mini")?Dh:L(t," OPR/")?Zo:Qo.test(t)?_n:L(t,"IE"+Oe)||L(t,"WPDesktop")?tu:L(t,"OculusBrowser")?lu:L(t,Xc)?Qc:L(t,Xo)||L(t,"Edg/")?nu:L(t,ns+"/")?ns:L(t,"YaBrowser/")?cu:L(t,is+"/")?is:L(t,Zr+"/")||L(t,"Ddg/")?Zr:L(t,"FBIOS")?"Facebook "+Oe:L(t,"UCWEB")||L(t,"UCBrowser")?"UC Browser":L(t,"CriOS")?eu:L(t,"CrMo")||L(t,Yt)?Yt:L(t,wt)&&L(t,Yn)?su:L(t,"FxiOS")?iu:L(t.toLowerCase(),Yr.toLowerCase())?Yr:L(t,Zn+"/")?Zn:((r,o)=>o&&L(o,Jc)||(function(a){return L(a,Yn)&&!L(a,Yt)&&!L(a,wt)})(r))(t,e)?L(t,Oe)?ru:Yn:L(t,"PaleMoon/")?uu:L(t,ss+"/")?ss:L(t,fn)?fn:L(t,"MSIE")||L(t,"Trident/")?Yo:L(t,"Gecko")?fn:"")},qh={[tu]:[new RegExp("rv:"+le)],[nu]:[new RegExp(Xo+"?\\/"+le)],[Yt]:[new RegExp("("+Yt+"|CrMo)\\/"+le)],[eu]:[new RegExp("CriOS\\/"+le)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+le)],[Yn]:[ur],[ru]:[ur],[Zo]:[new RegExp("(Opera|OPR)\\/"+le)],[fn]:[new RegExp(fn+"\\/"+le)],[iu]:[new RegExp("FxiOS\\/"+le)],[Yr]:[new RegExp("Konqueror[:/]?"+le,"i")],[_n]:[new RegExp(_n+" "+le),ur],[su]:[new RegExp("android\\s"+le,"i")],[Qc]:[new RegExp(Xc+"\\/"+le)],[lu]:[new RegExp("OculusBrowser\\/"+le)],[ns]:[new RegExp(ns+"\\/"+le)],[cu]:[new RegExp("YaBrowser\\/"+le)],[is]:[new RegExp(is+"\\/"+le)],[Zn]:[new RegExp(Zn+"\\/"+le)],[Zr]:[new RegExp("(DuckDuckGo|Ddg)\\/"+le)],[uu]:[new RegExp("PaleMoon\\/"+le)],[ss]:[new RegExp(ss+"\\/"+le)],[du]:[new RegExp("GSA\\/"+le)],[Yo]:[new RegExp("(rv:|MSIE )"+le)],Mozilla:[new RegExp("rv:"+le)]},Vh=function(t,e,n,i){var s=hu(t,e,n,i),r=qh[s];if(x(r))return null;for(var o=0;r.length>o;o++){var a=t.match(r[o]);if(a)return parseFloat(a[a.length-2])}return null},sl=[[new RegExp(gn+"; "+gn+" (.*?)[);]","i"),t=>[gn,t&&t[1]||""]],[new RegExp(ri,"i"),[ri,""]],[new RegExp(oi,"i"),[oi,""]],[Qo,[_n,""]],[new RegExp(Wn,"i"),(t,e)=>{if(/Phone/.test(e)||/WPDesktop/.test(e))return[Kr,""];if(new RegExp(Oe).test(e)&&!/IEMobile\b/.test(e))return[Wn+" "+Oe,""];var n=/Windows NT ([0-9.]+)/i.exec(e);if(n&&n[1]){var i=zh[n[1]]||"";return/arm/i.test(e)&&(i="RT"),[Wn,i]}return[Wn,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,t=>t&&t[3]?[ts,[t[3],t[4],t[5]||"0"].join(".")]:[ts,""]],[/(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i,t=>{var e="";return t&&t.length>=3&&(e=x(t[2])?t[3]:t[2]),["watchOS",e]}],[new RegExp("("+wt+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+wt+")","i"),t=>t&&t[2]?[wt,[t[2],t[3],t[4]||"0"].join(".")]:[wt,""]],[/Mac OS X (\d+)[_.](\d+)[_.]?(\d+)?/i,t=>{var 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/,[Bh,""]],[/Linux|debian/i,["Linux",""]]],rl=function(t){return Wh.test(t)?ri:Hh.test(t)?oi:Uh.test(t)?gn:new RegExp(Jr,"i").test(t)?Jr:new RegExp("("+Kr+"|WPDesktop)","i").test(t)?Kr:/iPad/.test(t)?Kc:/iPod/.test(t)?"iPod Touch":/iPhone/.test(t)?"iPhone":/(watch)(?: ?os[,/]|\d,\d\/)[\d.]+/i.test(t)?Yc:Qo.test(t)?_n:/(kobo)\s(ereader|touch)/i.test(t)?"Kobo":new RegExp(il,"i").test(t)?il:/(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(Oe).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)?wt:Gc:new RegExp("(pda|"+Oe+")","i").test(t)?jh:new RegExp(vn,"i").test(t)&&!new RegExp(vn+" pc","i").test(t)?au:""},Gh=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function ol(t,e){return typeof(n=t)=="string"&&Gh.test(n)?t:e();var n}function Pt(t){return t&&t.split("#")[0]}function ea(t,e){var n=setTimeout(t,e);return n?.unref&&n?.unref(),n}function al(t,e,n){return pu.apply(this,arguments)}function pu(){return(pu=X((function*(t,e,n){var i;try{return yield Promise.race([t,new Promise(((s,r)=>{i=ea((()=>{try{n?.(),s()}catch(o){r(o)}}),e)}))])}finally{clearTimeout(i)}}))).apply(this,arguments)}var Kh=t=>t instanceof Error,fu={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}},Jh=fu.info;function gu(t){if(Ye(t))return{boolValue:t};if(typeof t=="number")return Number.isFinite(t)?Number.isInteger(t)?{intValue:t}:{doubleValue:t}:{stringValue:String(t)};if(typeof t=="string")return{stringValue:t};if(O(t))return{arrayValue:{values:t.map((e=>gu(e)))}};try{return{stringValue:JSON.stringify(t)}}catch{return{stringValue:String(t)}}}function rs(t){var e=[];for(var n in t){var i=t[n];$e(i)||x(i)||e.push({key:n,value:gu(i)})}return e}function Yh(t,e){var n=fu[t.level||"info"]||Jh,i=n.text,s=n.number,r=String(Date.now())+"000000",o={};e.distinctId&&(o.posthogDistinctId=e.distinctId),e.sessionId&&(o.sessionId=e.sessionId),e.windowId&&(o["window.id"]=e.windowId),B(e.sessionStartTimestamp)||(o.sessionStartTimestamp=String(e.sessionStartTimestamp)),B(e.lastActivityTimestamp)||(o.lastActivityTimestamp=String(e.lastActivityTimestamp)),e.currentUrl&&(o["url.full"]=e.currentUrl),e.screenName&&(o["screen.name"]=e.screenName),e.appState&&(o["app.state"]=e.appState),e.activeFeatureFlags&&e.activeFeatureFlags.length>0&&(o.feature_flags=e.activeFeatureFlags);var a=E({},o,t.attributes||{}),l={timeUnixNano:r,observedTimeUnixNano:r,severityNumber:s,severityText:i,body:{stringValue:t.body},attributes:rs(a)};return t.trace_id&&(l.traceId=t.trace_id),t.span_id&&(l.spanId=t.span_id),x(t.trace_flags)||(l.flags=t.trace_flags),l}function mu(t,e,n){return E({},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})}function vu(t,e,n,i){return{resourceLogs:[{resource:{attributes:rs(e)},scopeLogs:[{scope:{name:n,version:i},logRecords:t}]}]}}let Zh=class{constructor(t,e,n,i,s,r,o){var a;r===void 0&&(r=()=>Promise.resolve()),this._instance=t,this.Ne=e,this.rt=n,this.ut=i,this.ht=s,this.dt=r,this.vt=o,this.ct=null,this.ft=0,this.yt=0,this.bt=0,this._t=0,this.wt=!1,this.kt=e.maxBufferSize,this.xt=Math.max((a=e.maxQueueSize)!==null&&a!==void 0?a:e.maxBufferSize,e.maxBufferSize),this.St=e.flushIntervalMs,this.Ct=e.maxBatchRecordsPerPost,this.Mt=e.rateCapWindowMs,this.Tt=e.maxLogsPerInterval}reset(){this.Et(),this.ct=null,this.bt=0,this._t=0,this.wt=!1,this.ft=0,this.yt=0,this.Ct=this.Ne.maxBatchRecordsPerPost}onReconnect(){this.yt=0,this.It()}captureLog(t){if(!this._instance.isDisabled&&!this._instance.optedOut&&t!=null&&t.body){var e=this.Pt(t);if(e!==null)if(e.body){if(this.Rt()){var n={record:Yh(e,this.ut())};this.ht((()=>this.At(n)))}}else this.rt.info("Log was rejected in beforeSend function")}}Pt(t){var e=this.Ne.beforeSend;if(!e)return t;var n=O(e)?e:[e],i=t;for(var s of n)try{var r=s(i);if(!r)return this.rt.info("Log was rejected in beforeSend function"),null;i=r}catch(o){return this.rt.error("Error in beforeSend function for log:",o),null}return i}Rt(){if(this.Tt===void 0)return!0;var t=Date.now(),e=t-this.bt;return this.Mt>e&&e>=0||(this.bt=t,this._t=0,this.wt=!1),this.Tt>this._t?(this._t++,!0):(this.wt||(this.rt.warn("captureLog dropping logs: exceeded "+this.Tt+" logs per "+this.Mt+"ms"),this.wt=!0),!1)}flush(){var t=this;return X((function*(){if(!t._instance.isDisabled)return t.ct||(t.ct=t.Ft().finally((()=>{t.ct=null}))),t.ct}))()}Ft(){var t=this;return X((function*(){var e;t.Et();var n=(e=t._instance.getPersistedProperty(pt.LogsQueue))!==null&&e!==void 0?e:[];if(n.length!==0)for(var i=n.length,s=0;n.length>0&&i>s;){var r,o;t.ft=0;var a=Math.min(n.length,t.Ct),l=n.slice(0,a),u=vu(l.map((d=>d.record)),t.Lt(),(r=t.vt)!==null&&r!==void 0?r:t._instance.getLibraryId(),t._instance.getLibraryVersion()),c=yield t._instance.Ot(u);if(c.kind==="too-large"&&l.length>1)t.Ct=Math.max(1,Math.floor(l.length/2)),t.rt.warn("Received 413 when sending logs batch of size "+l.length+", reducing batch size to "+t.Ct);else if(c.kind==="retry-later"||(c.kind==="too-large"?t.rt.warn("Dropping a single log record after 413 with batch size 1 — the record is larger than the server cap and cannot be split further."):c.kind==="ok"&&t.Ne.maxBatchRecordsPerPost>t.Ct&&(t.Ct=Math.min(t.Ne.maxBatchRecordsPerPost,t.Ct+1)),yield t.Dt(l.length),n=(o=t._instance.getPersistedProperty(pt.LogsQueue))!==null&&o!==void 0?o:[],s+=l.length,c.kind==="fatal"))throw c.error}}))()}Dt(t){var e=this;return X((function*(){var n,i=Math.max(0,t-e.ft),s=(n=e._instance.getPersistedProperty(pt.LogsQueue))!==null&&n!==void 0?n:[];e._instance.setPersistedProperty(pt.LogsQueue,s.slice(i)),yield e.dt()}))()}Lt(){return mu(this.Ne,this._instance.getLibraryId(),this._instance.getLibraryVersion())}At(t){var e;if(!this._instance.optedOut){var n=(e=this._instance.getPersistedProperty(pt.LogsQueue))!==null&&e!==void 0?e:[];this.xt>n.length||(n.shift(),this.ft++,this.rt.info("Logs queue is full, dropping oldest record.")),n.push(t),this._instance.setPersistedProperty(pt.LogsQueue,n),this.kt>n.length?this.$t():this.It()}}$t(t){t===void 0&&(t=this.St),this.Nt||(this.Nt=ea((()=>{this.Nt=void 0,this.It()}),t))}qt(){var t=Math.min(Math.max(0,this.yt-1),6);return this.St*Math.pow(2,t)}jt(){var t=this._instance.getPersistedProperty(pt.LogsQueue);return!!t&&t.length>0}shutdown(t){var e=this;return X((function*(){e.Et();var n=e.flush().catch((()=>{}));t!==void 0?yield al(n,t):yield n}))()}flushWithTimeout(t){var e=this;return X((function*(){var n=e.flush();yield al(n,t,(()=>{n.catch((()=>{}))}))}))()}It(){this.flush().then((()=>{this.yt=0}),(t=>{this.yt++,this.rt.error("PostHog logs flush failed:",t)})).finally((()=>{!this._instance.isDisabled&&this.jt()&&this.$t(this.qt())}))}Et(){this.Nt&&(clearTimeout(this.Nt),this.Nt=void 0)}};var dr=[0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4];function ll(t){return String(t)+"000000"}function cl(t,e,n,i){var s="";return i&&(s=Object.keys(i).sort().map((r=>JSON.stringify(r)+":"+JSON.stringify(i[r]))).join(",")),t+"\0"+e+"\0"+(n??"")+"\0"+s}let Xh=class{constructor(t,e,n){this._instance=t,this.Ne=e,this.rt=n,this.Bt=new Map,this.ct=null,this.Ht=!1,this.Ut=new Map,this.zt=new Set,this.Wt=0}count(t,e,n){e===void 0&&(e=1),this.Vt({name:t,type:"count",value:e,unit:n?.unit,attributes:n?.attributes})}gauge(t,e,n){this.Vt({name:t,type:"gauge",value:e,unit:n?.unit,attributes:n?.attributes})}histogram(t,e,n){this.Vt({name:t,type:"histogram",value:e,unit:n?.unit,attributes:n?.attributes})}flush(){var t=this,e=this.ct,n=(function(){var s=X((function*(){e&&(yield e.catch((()=>{}))),yield t.Zt()}));return function(){return s.apply(this,arguments)}})(),i=n().finally((()=>{this.ct===i&&(this.ct=null)}));return this.ct=i,i}drainWindow(){if(this.Bt.size===0)return null;var t=this.Bt;return this.Bt=new Map,this.Ht=!1,this.Ut=new Map,this.zt=new Set,this.Gt(t)}reset(){this.Wt++,this.Et(),this.Bt=new Map,this.ct=null,this.Ht=!1,this.Ut=new Map,this.zt=new Set}Vt(t){if(!this._instance.isDisabled&&!this._instance.optedOut){var e=this.Pt(t);if(e!==null)if(e.name&&typeof e.name=="string")if(typeof e.value=="number"&&Number.isFinite(e.value))if(e.type==="count"&&0>e.value)this.rt.warn("Dropping count '"+e.name+"': counters are monotonic, value must be >= 0");else{var n,i;try{n=e.attributes?E({},e.attributes):void 0,i=cl(e.type,e.name,e.unit,n)}catch(o){return void this.rt.warn("Dropping metric '"+e.name+"': attributes could not be serialized",o)}var s=this.Bt.get(i);if(!s){if(!this.Qt())return;s={name:e.name,type:e.type,unit:e.unit,attributes:n,windowStartMs:Date.now()},this.Bt.set(i,s)}var r=this.Ut.get(e.name);r===void 0?this.Ut.set(e.name,e.type):r===e.type||this.zt.has(e.name)||(this.zt.add(e.name),this.rt.warn("Metric name '"+e.name+"' is already used as a "+r+"; recording it as a "+e.type+" too will blend both series in charts. Use a distinct name.")),this.Kt(s,e.value),this.$t()}else this.rt.warn("Dropping metric '"+e.name+"': value must be a finite number");else this.rt.warn("Dropping metric with empty name")}}Qt(){return this.Ne.maxSeriesPerFlush>this.Bt.size||(this.Ht||(this.Ht=!0,this.rt.warn("Metric series cap reached ("+this.Ne.maxSeriesPerFlush+" per flush window); dropping new series until the next flush. Reduce attribute cardinality.")),!1)}Kt(t,e){var n;switch(t.type){case"count":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(dr.length+1).fill(0)});var i=t.hist;i.count+=1,i.sum+=e,i.min=Math.min(i.min,e),i.max=Math.max(i.max,e),i.bucketCounts[(function(s,r){for(var o=0;r.length>o;o++)if(r[o]>=s)return o;return r.length})(e,dr)]+=1}}Pt(t){var e=this.Ne.beforeSend;if(!e)return t;var n=O(e)?e:[e],i=t;for(var s of n)try{var r=s(i);if(!r)return this.rt.info("Metric was rejected in beforeSend function"),null;i=r}catch(o){return this.rt.error("Error in beforeSend function for metric:",o),null}return i}$t(){this.Nt||(this.Nt=ea((()=>{this.Nt=void 0,this.flush().catch((t=>{this.rt.error("Metrics flush failed:",t)}))}),this.Ne.flushIntervalMs))}Et(){this.Nt&&(clearTimeout(this.Nt),this.Nt=void 0)}Zt(){var t=this;return X((function*(){if(t.Bt.size!==0){var e=t.Bt;t.Bt=new Map,t.Ht=!1,t.Ut=new Map,t.zt=new Set;var n=t.Wt,i=yield t._instance.Jt(t.Gt(e));if(n===t.Wt)switch(i.kind){case"ok":return;case"retry-later":return t.Yt(e),void t.$t();case"too-large":return void t.rt.warn("Metrics batch exceeded the server size limit and was dropped");case"fatal":return void t.rt.error("Failed to send metrics batch:",i.error)}}}))()}Gt(t){return e=this.Xt(t),n=(function(r,o,a){return E({},r.resourceAttributes,{"service.name":r.serviceName||"unknown_service"},r.environment&&{"deployment.environment":r.environment},r.serviceVersion&&{"service.version":r.serviceVersion},{"telemetry.sdk.name":o,"telemetry.sdk.version":a})})(this.Ne,this._instance.getLibraryId(),this._instance.getLibraryVersion()),i=this._instance.getLibraryId(),s=this._instance.getLibraryVersion(),{resourceMetrics:[{resource:{attributes:rs(n)},scopeMetrics:[{scope:{name:i,version:s},metrics:e}]}]};var e,n,i,s}Xt(t){var e=ll(Date.now()),n=new Map;for(var i of t.values()){var s,r=cl(i.type,i.name,i.unit,void 0),o=n.get(r);o||(o=E({name:i.name},i.unit&&{unit:i.unit}),i.type==="count"?o.sum={aggregationTemporality:1,isMonotonic:!0,dataPoints:[]}:i.type==="gauge"?o.gauge={dataPoints:[]}:o.histogram={aggregationTemporality:1,dataPoints:[]},n.set(r,o));var a=rs((s=i.attributes)!==null&&s!==void 0?s:{}),l=ll(i.windowStartMs);if(i.type==="count"){var u,c={attributes:a,startTimeUnixNano:l,timeUnixNano:e,asDouble:(u=i.total)!==null&&u!==void 0?u:0};o.sum.dataPoints.push(c)}else if(i.type==="gauge"){var d,h={attributes:a,timeUnixNano:e,asDouble:(d=i.last)!==null&&d!==void 0?d:0};o.gauge.dataPoints.push(h)}else i.hist&&o.histogram.dataPoints.push({attributes:a,startTimeUnixNano:l,timeUnixNano:e,count:i.hist.count,sum:i.hist.sum,min:i.hist.min,max:i.hist.max,bucketCounts:i.hist.bucketCounts,explicitBounds:dr})}return Array.from(n.values())}Yt(t){var e,n;for(var i of t){var s=i[0],r=i[1],o=this.Bt.get(s);if(o)switch(o.windowStartMs=Math.min(o.windowStartMs,r.windowStartMs),o.type){case"count":o.total=((e=o.total)!==null&&e!==void 0?e:0)+((n=r.total)!==null&&n!==void 0?n:0);break;case"gauge":break;case"histogram":if(r.hist)if(o.hist){o.hist.count+=r.hist.count,o.hist.sum+=r.hist.sum,o.hist.min=Math.min(o.hist.min,r.hist.min),o.hist.max=Math.max(o.hist.max,r.hist.max);for(var a=0;o.hist.bucketCounts.length>a;a++)o.hist.bucketCounts[a]+=r.hist.bucketCounts[a]}else o.hist=r.hist}else this.Qt()&&this.Bt.set(s,r)}}};var Ii,ul,hr;function Qh(t){var e=globalThis._posthogChunkIds;if(e){var n=Object.keys(e);return hr&&n.length===ul||(ul=n.length,hr=n.reduce(((i,s)=>{Ii||(Ii={});var r=Ii[s];if(r)i[r[0]]=r[1];else for(var o=t(s),a=o.length-1;a>=0;a--){var l=o[a],u=l?.filename,c=e[s];if(u&&c){i[u]=c,Ii[s]=[u,c];break}}return i}),{})),hr}}class ep{constructor(e,n,i){i===void 0&&(i=[]),this.coercers=e,this.stackParser=n,this.modifiers=i}buildFromUnknown(e,n){n===void 0&&(n={});var i=n&&n.mechanism||{handled:!0,type:"generic"},s=this.buildCoercingContext(i,n,0).apply(e),r=this.buildParsingContext(n),o=this.parseStacktrace(s,r);return{$exception_list:this.convertToExceptionList(o,i),$exception_level:"error"}}modifyFrames(e){var n=this;return X((function*(){for(var i of e)i.stacktrace&&i.stacktrace.frames&&O(i.stacktrace.frames)&&(i.stacktrace.frames=yield n.applyModifiers(i.stacktrace.frames));return e}))()}coerceFallback(e){var n;return{type:"Error",value:"Unknown error",stack:(n=e.syntheticException)==null?void 0:n.stack,synthetic:!0}}parseStacktrace(e,n){var i,s;return e.cause!=null&&(i=this.parseStacktrace(e.cause,n)),e.stack!=""&&e.stack!=null&&(s=this.applyChunkIds(this.stackParser(e.stack,e.synthetic?n.skipFirstLines:0),n.chunkIdMap)),E({},e,{cause:i,stack:s})}applyChunkIds(e,n){return e.map((i=>(i.filename&&n&&(i.chunk_id=n[i.filename]),i)))}applyCoercers(e,n){for(var i of this.coercers)if(i.match(e))return i.coerce(e,n);return this.coerceFallback(n)}applyModifiers(e){var n=this;return X((function*(){var i=e;for(var s of n.modifiers)i=yield s(i);return i}))()}convertToExceptionList(e,n){var i,s,r,o={type:e.type,value:e.value,mechanism:{type:(i=n.type)!==null&&i!==void 0?i:"generic",handled:(s=n.handled)===null||s===void 0||s,synthetic:(r=e.synthetic)!==null&&r!==void 0&&r}};e.stack&&(o.stacktrace={type:"raw",frames:e.stack});var a=[o];return e.cause!=null&&a.push(...this.convertToExceptionList(e.cause,E({},n,{handled:!0}))),a}buildParsingContext(e){var n;return{chunkIdMap:Qh(this.stackParser),skipFirstLines:(n=e.skipFirstLines)!==null&&n!==void 0?n:1}}buildCoercingContext(e,n,i){i===void 0&&(i=0);var s=(r,o)=>{if(4>=o){var a=this.buildCoercingContext(e,n,o);return this.applyCoercers(r,a)}};return E({},n,{syntheticException:i==0?n.syntheticException:void 0,mechanism:e,apply:r=>s(r,i),next:r=>s(r,i+1)})}}var yn="?";function Xr(t,e,n,i,s){var r={platform:t,filename:e,function:n===""?yn:n,in_app:!0};return x(i)||(r.lineno=i),x(s)||(r.colno=s),r}var _u=(t,e)=>{var n=t.indexOf("safari-extension")!==-1,i=t.indexOf("safari-web-extension")!==-1;return n||i?[t.indexOf("@")!==-1?t.split("@")[0]:yn,n?"safari-extension:"+e:"safari-web-extension:"+e]:[t,e]},tp=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,np=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,ip=/\((\S*)(?::(\d+))(?::(\d+))\)/,sp=(t,e)=>{var n=tp.exec(t);if(n)return Xr(e,n[1],yn,+n[2],+n[3]);var i=np.exec(t);if(i){if(i[2]&&i[2].indexOf("eval")===0){var s=ip.exec(i[2]);s&&(i[2]=s[1],i[3]=s[2],i[4]=s[3])}var r=_u(i[1]||yn,i[2]);return Xr(e,r[1],r[0],i[3]?+i[3]:void 0,i[4]?+i[4]:void 0)}},rp=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,op=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,ap=(t,e)=>{var n=rp.exec(t);if(n){if(n[3]&&n[3].indexOf(" > eval")>-1){var i=op.exec(n[3]);i&&(n[1]=n[1]||"eval",n[3]=i[1],n[4]=i[2],n[5]="")}var s=n[3],r=n[1]||yn,o=_u(r,s);return Xr(e,s=o[1],r=o[0],n[4]?+n[4]:void 0,n[5]?+n[5]:void 0)}},dl=/\(error: (.*)\)/;class lp{match(e){return this.isDOMException(e)||this.isDOMError(e)}coerce(e,n){var i=q(e.stack);return{type:this.getType(e),value:this.getValue(e),stack:i?e.stack:void 0,cause:e.cause?n.next(e.cause):void 0,synthetic:!1}}getType(e){return this.isDOMError(e)?"DOMError":"DOMException"}getValue(e){var n=e.name||(this.isDOMError(e)?"DOMError":"DOMException");return e.message?n+": "+e.message:n}isDOMException(e){return es(e,"DOMException")}isDOMError(e){return es(e,"DOMError")}}class cp{match(e){return(function(n){switch({}.toString.call(n)){case"[object Error]":case"[object Exception]":case"[object DOMException]":case"[object DOMError]":case"[object WebAssembly.Exception]":return!0;default:return Vc(n,Error)}})(e)}coerce(e,n){return{type:this.getType(e),value:this.getMessage(e,n),stack:this.getStack(e),cause:e.cause?n.next(e.cause):void 0,synthetic:!1}}getType(e){return e.name||e.constructor.name}getMessage(e,n){var i=e.message;return String(i.error&&typeof i.error.message=="string"?i.error.message:i)}getStack(e){return e.stacktrace||e.stack||void 0}}class up{constructor(){}match(e){return!!es(e,"ErrorEvent")&&(e.error!=null||this.fe(e))}coerce(e,n){var i;if(e.error!=null)return n.apply(e.error);var s=n.apply(e.message);return E({},s,{stack:(i=this.pe(e))!==null&&i!==void 0?i:s.stack,synthetic:!0})}fe(e){return q(e.message)&&e.message.length>0}pe(e){var n=e;if(q(n.filename)&&n.filename.length>0){var i,s,r=(i=n.lineno)!==null&&i!==void 0?i:0,o=(s=n.colno)!==null&&s!==void 0?s:0;return`Error + at `+n.filename+":"+r+":"+o}}}var dp=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;class hp{match(e){return typeof e=="string"}coerce(e,n){var i,s=this.getInfos(e),r=s[0],o=s[1];return{type:r??"Error",value:o??e,stack:(i=n.syntheticException)==null?void 0:i.stack,synthetic:!0}}getInfos(e){var n="Error",i=e,s=e.match(dp);return s&&(n=s[1],i=s[2]),[n,i]}}var pp=["fatal","error","warning","log","info","debug"];function yu(t,e){e===void 0&&(e=40);var n=Object.keys(t);if(n.sort(),!n.length)return"[object has no keys]";for(var i=n.length;i>0;i--){var s=n.slice(0,i).join(", ");if(e>=s.length)return i===n.length?s:s.length>e?s.slice(0,e)+"...":s}return""}class fp{match(e){return typeof e=="object"&&e!==null}coerce(e,n){var i,s,r=this.getErrorPropertyFromObject(e);return r?n.apply(r):{type:this.getType(e),value:this.getValue(e),stack:(i=this.getStack(e))!==null&&i!==void 0?i:(s=n.syntheticException)==null?void 0:s.stack,level:this.isSeverityLevel(e.level)?e.level:"error",synthetic:!0}}getType(e){return Jo(e)?e.constructor.name:"Error"}getValue(e){if("name"in e&&typeof e.name=="string"){var n="'"+e.name+"' captured as exception";return"message"in e&&typeof e.message=="string"&&(n+=" with message: '"+e.message+"'"),n}if("message"in e&&typeof e.message=="string")return e.message;var i=this.getObjectClassName(e);return(i&&i!=="Object"?"'"+i+"'":"Object")+" captured as exception with keys: "+yu(e)}isSeverityLevel(e){return q(e)&&!Gr(e)&&pp.indexOf(e)>=0}getStack(e){try{return q(e.stacktrace)&&e.stacktrace.length>0?e.stacktrace:q(e.stack)&&e.stack.length>0?e.stack:void 0}catch{return}}getErrorPropertyFromObject(e){for(var n in e)if({}.hasOwnProperty.call(e,n)){var i=e[n];if(Kh(i))return i}}getObjectClassName(e){try{var n=Object.getPrototypeOf(e);return n?n.constructor.name:void 0}catch{return}}}class gp{match(e){return Jo(e)}coerce(e,n){var i,s=e.constructor.name;return{type:s,value:s+" captured as exception with keys: "+yu(e),stack:(i=n.syntheticException)==null?void 0:i.stack,synthetic:!0}}}class mp{match(e){return qc(e)}coerce(e,n){var i;return{type:"Error",value:"Primitive value captured as exception: "+String(e),stack:(i=n.syntheticException)==null?void 0:i.stack,synthetic:!0}}}class vp{match(e){return es(e,"PromiseRejectionEvent")||this.isCustomEventWrappingRejection(e)}isCustomEventWrappingRejection(e){if(!Jo(e))return!1;try{var n=e.detail;return n!=null&&typeof n=="object"&&"reason"in n}catch{return!1}}coerce(e,n){var i,s=this.getUnhandledRejectionReason(e);return qc(s)?{type:"UnhandledRejection",value:"Non-Error promise rejection captured with value: "+String(s),stack:(i=n.syntheticException)==null?void 0:i.stack,synthetic:!0}:n.apply(s)}getUnhandledRejectionReason(e){try{if("reason"in e)return e.reason;if("detail"in e&&e.detail!=null&&typeof e.detail=="object"&&"reason"in e.detail)return e.detail.reason}catch{}return e}}var os="$message",as="$timestamp",_p=new Set([os,as]),pr={enabled:!0,max_bytes:32768};function ls(t){var e;return t?{enabled:(e=t.enabled)!==null&&e!==void 0?e:pr.enabled,max_bytes:wp(t.max_bytes,pr.max_bytes)}:E({},pr)}class yp{constructor(e){this.Ke=[],this.Je=0,this.Ne=ls(e)}setConfig(e){this.Ne=ls(e),this.Xe()}add(e){var n=(function(s){var r;try{r=Hc(s)}catch{return}try{var o=JSON.parse(r);if(!ne(o))return;var a=o,l=a[os],u=a[as];return!q(l)||l.trim().length===0||!q(u)&&!he(u)?void 0:{step:a,json:r}}catch{return}})(e);if(n){var i=(function(s){if(typeof TextEncoder<"u")return new TextEncoder().encode(s).length;for(var r=encodeURIComponent(s),o=0,a=0;r.length>a;a++)r[a]==="%"?(o+=1,a+=2):o+=1;return o})(n.json);i>this.Ne.max_bytes||(this.Ke.push({step:n.step,bytes:i}),this.Je+=i,this.Xe())}}getAttachable(){return this.Ke.map((e=>e.step))}clear(){this.Ke=[],this.Je=0}size(){return this.Ke.length}Xe(){for(;this.Je>this.Ne.max_bytes&&this.Ke.length>0;){var e=this.Ke.shift();e&&(this.Je-=e.bytes)}}}function wp(t,e){if(!he(t)||t===1/0||t===-1/0)return e;var n=Math.floor(t);return 0>n?e:n}var wu=function(t,e){var n=(e===void 0?{}:e).debugEnabled,i={k(s){if(_&&(Y.DEBUG||_.POSTHOG_DEBUG||n)&&!x(_.console)&&_.console){for(var r=("__rrweb_original__"in _.console[s])?_.console[s].__rrweb_original__:_.console[s],o=arguments.length,a=new Array(o>1?o-1:0),l=1;o>l;l++)a[l-1]=arguments[l];r(t,...a)}},debug(){for(var s=arguments.length,r=new Array(s),o=0;s>o;o++)r[o]=arguments[o];i.k("debug",...r)},info(){for(var s=arguments.length,r=new Array(s),o=0;s>o;o++)r[o]=arguments[o];i.k("log",...r)},warn(){for(var s=arguments.length,r=new Array(s),o=0;s>o;o++)r[o]=arguments[o];i.k("warn",...r)},error(){for(var s=arguments.length,r=new Array(s),o=0;s>o;o++)r[o]=arguments[o];i.k("error",...r)},critical(){for(var s=arguments.length,r=new Array(s),o=0;s>o;o++)r[o]=arguments[o];console.error(t,...r)},uninitializedWarning(s){i.error("You must initialize PostHog before calling "+s)},createLogger:(s,r)=>wu(t+" "+s,r)};return i},k=wu("[PostHog.js]"),ie=k.createLogger,bp=ie("[ExternalScriptsLoader]"),fr=(t,e,n)=>{if(t.config.disable_external_dependency_loading)return bp.warn(e+" was requested but loading of external scripts is disabled."),n("Loading of external scripts is disabled");var i=C?.querySelectorAll("script");if(i){for(var s,r=function(){if(i[o].src===e){var l=i[o];return l.__posthog_loading_callback_fired?{v:n()}:(l.addEventListener("load",(u=>{l.__posthog_loading_callback_fired=!0,n(void 0,u)})),l.onerror=u=>n(u),{v:void 0})}},o=0;i.length>o;o++)if(s=r())return s.v}var a=()=>{if(!C)return n("document not found");var l=C.createElement("script");if(l.type="text/javascript",l.crossOrigin="anonymous",l.src=e,l.onload=d=>{l.__posthog_loading_callback_fired=!0,n(void 0,d)},l.onerror=d=>n(d),t.config.prepare_external_dependency_script&&(l=t.config.prepare_external_dependency_script(l)),!l)return n("prepare_external_dependency_script returned null");if(t.config.external_scripts_inject_target==="head")C.head.appendChild(l);else{var u,c=C.querySelectorAll("body > script");c.length>0?(u=c[0].parentNode)==null||u.insertBefore(l,c[0]):C.body.appendChild(l)}};C!=null&&C.body?a():C?.addEventListener("DOMContentLoaded",a)};R.__PosthogExtensions__=R.__PosthogExtensions__||{},R.__PosthogExtensions__.loadExternalDependency=(t,e,n)=>{if(e!=="remote-config"){var i;if(t.config.strict_script_versioning)i=t.requestRouter.endpointFor("assets","/static/"+t.version+"/"+e+".js");else{var s="/static/"+e+".js?v="+t.version;if(e==="toolbar"){var r=3e5;s=s+"&t="+Math.floor(Date.now()/r)*r}i=t.requestRouter.endpointFor("assets",s)}fr(t,i,n)}else{var o=t.requestRouter.endpointFor("assets","/array/"+t.config.token+"/config.js");fr(t,o,n)}},R.__PosthogExtensions__.loadSiteApp=(t,e,n)=>{var i=t.requestRouter.endpointFor("api",e);fr(t,i,n)};Y.DEBUG=!1,Y.LIB_VERSION="1.415.7",Y.LIB_NAME="web";var bu="$people_distinct_id",ai="$device_id",gr="$device_model",zn="__alias",qn="__timers",Qr="$autocapture_disabled_server_side",eo="$heatmaps_enabled_server_side",to="$exception_capture_enabled_server_side",no="$error_tracking_suppression_rules",io="$error_tracking_capture_extension_exceptions",so="$web_vitals_enabled_server_side",ta="$dead_clicks_enabled_server_side",na="$product_tours_enabled_server_side",ro="$web_vitals_allowed_metrics",Jt="$session_recording_remote_config",Eu="$replay_sample_rate",Su="$replay_override_sampling",xu="$replay_override_linked_flag",ku="$replay_override_url_trigger",Iu="$replay_override_event_trigger",hn="$sesid",ia="$session_is_sampled",Wt="$enabled_feature_flags",Vn="$active_feature_flags",ji="$early_access_features",oo="$feature_flag_details",Gn="$feature_flag_payloads",Ui="$feature_flag_request_id",cs="$minimal_flag_called_events",it="$override_feature_flags",zt="$override_feature_flag_payloads",ht="$stored_person_properties",qt="$stored_group_properties",ao="$surveys",us="$surveys_loaded_at",lo="$surveys_activated",Hi="$surveys_activated_session",Wi="$surveys_activated_timestamps",Kn="ph_product_tours",Gt="$flag_call_reported",Jn="$flag_call_reported_session_id",zi="$feature_flag_errors",Xn="$feature_flag_evaluated_at",He="$user_state",co="$client_session_props",uo="$capture_rate_limit",ho="$initial_campaign_params",po="$initial_referrer_info",ds="$initial_person_info",hs="$epp",Ci="$posthog_cookieless",Cu="$cookieless_mode",Au="$sdk_debug_extensions_init_method",Fu="$sdk_debug_extensions_init_time_ms",Pu="$sdk_debug_recording_script_not_loaded",sa="PostHog loadExternalDependency extension not found.",Vt="on_reject",gt="always",sn="anonymous",Ot="identified",fo="identified_only",ps="visibilitychange",fs="beforeunload",cn="$pageview",mr="$pageleave",vr="$identify",hl="$groupidentify";function Ai(t,e){O(t)&&t.forEach(e)}function Z(t,e){if(!B(t))if(O(t))t.forEach(e);else if(Th(t))t.forEach(((i,s)=>e(i,s)));else for(var n in t)zc.call(t,n)&&e(t[n],n)}var te=function(t){for(var e=arguments.length,n=new Array(e>1?e-1:0),i=1;e>i;i++)n[i-1]=arguments[i];for(var s of n)for(var r in s)s[r]!==void 0&&(t[r]=s[r]);return t};function qi(t){for(var e=Object.keys(t),n=e.length,i=new Array(n);n--;)i[n]=[e[n],t[e[n]]];return i}var pl=function(t){try{return t()}catch{return}},Ep=function(t){return function(){try{for(var e=arguments.length,n=new Array(e),i=0;e>i;i++)n[i]=arguments[i];return t.apply(this,n)}catch(s){k.critical("Implementation error. Please turn on debug mode and open a ticket on https://app.posthog.com/home#panel=support%3Asupport%3A."),k.critical(s)}}},ra=function(t){var e={};return Z(t,(function(n,i){(q(n)&&n.length>0||he(n))&&(e[i]=n)})),e},Sp=["herokuapp.com","vercel.app","netlify.app"];function xp(t){var e=t?.hostname;if(!q(e))return!1;var n=e.split(".").slice(-2).join(".");for(var i of Sp)if(n===i)return!1;return!0}function re(t,e,n,i){var s=i??{},r=s.capture,o=s.passive;t?.addEventListener(e,n,{capture:r!==void 0&&r,passive:o===void 0||o})}function go(t){return t.name==="ph_toolbar_internal"}var $u=t=>{if(C){try{for(var e=t+"=",n=C.cookie.split(";").filter((r=>r.length)),i=0;n.length>i;i++){for(var s=n[i];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}};Math.trunc||(Math.trunc=function(t){return 0>t?Math.ceil(t):Math.floor(t)}),Number.isInteger||(Number.isInteger=function(t){return he(t)&&isFinite(t)&&Math.floor(t)===t});class gs{constructor(e){if(this.bytes=e,e.length!==16)throw new TypeError("not 128-bit length")}static fromFieldsV7(e,n,i,s){if(!Number.isInteger(e)||!Number.isInteger(n)||!Number.isInteger(i)||!Number.isInteger(s)||0>e||0>n||0>i||0>s||e>0xffffffffffff||n>4095||i>1073741823||s>4294967295)throw new RangeError("invalid field value");var r=new Uint8Array(16);return r[0]=e/Math.pow(2,40),r[1]=e/Math.pow(2,32),r[2]=e/Math.pow(2,24),r[3]=e/Math.pow(2,16),r[4]=e/256,r[5]=e,r[6]=112|n>>>8,r[7]=n,r[8]=128|i>>>24,r[9]=i>>>16,r[10]=i>>>8,r[11]=i,r[12]=s>>>24,r[13]=s>>>16,r[14]=s>>>8,r[15]=s,new gs(r)}toString(){for(var e="",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 gs(this.bytes.slice(0))}equals(e){return this.compareTo(e)===0}compareTo(e){for(var n=0;16>n;n++){var i=this.bytes[n]-e.bytes[n];if(i!==0)return Math.sign(i)}return 0}}class kp{generate(){var e=this.generateOrAbort();if(!x(e))return e;this.S=0;var n=this.generateOrAbort();if(x(n))throw new Error("Could not generate UUID after timestamp reset");return n}generateOrAbort(){var e=Date.now();if(e>this.S)this.S=e,this.C();else{if(this.S>=e+1e4)return;this.I++,this.I>4398046511103&&(this.S++,this.C())}return gs.fromFieldsV7(this.S,Math.trunc(this.I/Math.pow(2,30)),this.I&Math.pow(2,30)-1,this.A.nextUint32())}C(){this.I=1024*this.A.nextUint32()+(1023&this.A.nextUint32())}constructor(){this.S=0,this.I=0,this.A=new Ip}}var fl,Tu=t=>{if(typeof UUIDV7_DENY_WEAK_RNG<"u"&&UUIDV7_DENY_WEAK_RNG)throw new Error("no cryptographically strong RNG available");for(var e=0;t.length>e;e++)t[e]=65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random());return t};_&&!x(_.crypto)&&crypto.getRandomValues&&(Tu=t=>crypto.getRandomValues(t));class Ip{nextUint32(){return this.R.length>this.O||(Tu(this.R),this.O=0),this.R[this.O++]}constructor(){this.R=new Uint32Array(8),this.O=1/0}}var ft=()=>Cp().toString(),Cp=()=>(fl||(fl=new kp)).generate(),Nn="",Ap=/[a-z0-9][a-z0-9-]+\.[a-z]{2,}$/i,mt={N:()=>!!C,j(t){k.error("cookieStore error: "+t)},P:$u,H(t){var e;try{e=JSON.parse(mt.P(t))||{}}catch{}return e},F(t,e,n,i,s){if(!C)return!1;try{var r="",o="",a=(function(c,d){if(d){var h=(function(f,g){if(g===void 0&&(g=C),Nn)return Nn;if(!g||["localhost","127.0.0.1"].includes(f))return"";for(var m=f.split("."),v=Math.min(m.length,8),b="dmn_chk_"+ft();!Nn&&v--;){var w=m.slice(v).join("."),I=b+"=1;domain=."+w+";path=/";g.cookie=I+";max-age=3",g.cookie.includes(b)&&(g.cookie=I+";max-age=0",Nn=w)}return Nn})(c);if(!h){var p=(f=>{var g=f.match(Ap);return g?g[0]:""})(c);p!==h&&k.info("Warning: cookie subdomain discovery mismatch",p,h),h=p}return h?"; domain=."+h:""}return""})(C.location.hostname,i);if(n){var l=new Date;l.setTime(l.getTime()+864e5*n),r="; expires="+l.toUTCString()}s&&(o="; secure");var u=t+"="+encodeURIComponent(JSON.stringify(e))+r+"; SameSite=Lax; path=/"+a+o;return u.length>3686.4&&k.warn("cookieStore warning: large cookie, len="+u.length),C.cookie=u,!0}catch{return!1}},q(t,e){if(C!=null&&C.cookie)try{mt.F(t,"",-1,e)}catch{return}}},_r=null,ee={N(){if(!$e(_r))return _r;var t=!0;if(x(_))t=!1;else try{var e="__mplssupport__";ee.F(e,"xyz"),ee.P(e)!=='"xyz"'&&(t=!1),ee.q(e)}catch{t=!1}return t||k.error("localStorage unsupported; falling back to cookie store"),_r=t,t},j(t){k.error("localStorage error: "+t)},P(t){try{return _?.localStorage.getItem(t)}catch(e){ee.j(e)}return null},H(t){try{return JSON.parse(ee.P(t))||{}}catch{}return null},F(t,e){try{return _?.localStorage.setItem(t,JSON.stringify(e)),!0}catch(n){ee.j(n)}return!1},q(t){try{_?.localStorage.removeItem(t)}catch(e){ee.j(e)}}},Fp=[ai,"distinct_id",hn,ia,hs,ds,He],Fi={},Pp={N:()=>!0,j(t){k.error("memoryStorage error: "+t)},P:t=>Fi[t]||null,H:t=>Fi[t]||null,F:(t,e)=>(Fi[t]=e,!0),q(t){delete Fi[t]}},Bt=null,ce={N(){if(!$e(Bt))return Bt;if(Bt=!0,x(_))Bt=!1;else try{var t="__support__";ce.F(t,"xyz"),ce.P(t)!=='"xyz"'&&(Bt=!1),ce.q(t)}catch{Bt=!1}return Bt},j(t){k.error("sessionStorage error: ",t)},P(t){try{return _?.sessionStorage.getItem(t)}catch(e){ce.j(e)}return null},H(t){try{return JSON.parse(ce.P(t))||null}catch{}return null},F(t,e){try{return _?.sessionStorage.setItem(t,JSON.stringify(e)),!0}catch(n){ce.j(n)}return!1},q(t){try{_?.sessionStorage.removeItem(t)}catch(e){ce.j(e)}}};class $p{constructor(e){this._instance=e}get Ne(){return this._instance.config}get consent(){return this.ti()?0:this.ei}isOptedOut(){return this.Ne.cookieless_mode===gt||this.isRejected()||this.consent===-1&&this.Ne.cookieless_mode===Vt}isOptedIn(){return!this.isOptedOut()}isExplicitlyOptedOut(){return this.consent===0}isRejected(){return this.consent===0||this.consent===-1&&this.Ne.opt_out_capturing_by_default}optInOut(e){this.ii.F(this.ri,e?1:0,this.Ne.cookie_expiration,this.Ne.cross_subdomain_cookie,this.Ne.secure_cookie)}reset(){this.ii.q(this.ri,this.Ne.cross_subdomain_cookie)}get ri(){var e=this._instance.config,n=e.token,i=e.opt_out_capturing_cookie_prefix;return e.consent_persistence_name||(i?i+n:"__ph_opt_in_out_"+n)}get ei(){var e=this.ii.P(this.ri);return cr(e)?1:L(Lh,e)?0:-1}get ii(){var e=this.Ne.opt_out_capturing_persistence_type,n=e==="localStorage"?ee:mt;if(!this.ni||this.ni!==n){this.ni=n;var i=e==="localStorage"?mt:ee;i.P(this.ri)&&(this.ni.P(this.ri)||this.optInOut(cr(i.P(this.ri))),i.q(this.ri,this.Ne.cross_subdomain_cookie))}return this.ni}ti(){return!!this.Ne.respect_dnt&&[ke?.doNotTrack,ke?.msDoNotTrack,R.doNotTrack].some((e=>cr(e)))}}function Ru(t,e){var n,i=t==null||(n=t.config)==null?void 0:n.get_current_url;if(!Se(i))return e;try{var s=i(e);return q(s)&&s?s:e}catch(r){return k.error("Error in get_current_url, falling back to window.location.href",r),e}}var Nu="__POSTHOG_TOOLBAR__",Tp=1,Rp=3,Np=11;function gl(t){return t instanceof Element&&(t.id===Nu||!(t.closest==null||!t.closest(".toolbar-global-fade-container")))}function $t(t){return!!t&&t.nodeType===Tp}function Me(t,e){return!!t&&!!t.tagName&&t.tagName.toLowerCase()===e.toLowerCase()}function Mu(t){return!!t&&t.nodeType===Rp}function Lu(t){return!!t&&t.nodeType===Np&&$t(t.host)}var Ou=1e3;function oa(t){return t?Bs(t).split(/\s+/):[]}function ml(t,e){var n=(function(i){var s,r=_==null||(s=_.location)==null?void 0:s.href;return x(r)?void 0:Ru(i,r)})(e);return!!(n&&t&&t.some((i=>n.match(i))))}function ms(t){var 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 oa(e)}function Bu(t){return B(t)?null:Bs(t).split(/(\s+)/).filter((e=>Qn(e))).join("").replace(/[\r\n]/g," ").replace(/[ ]+/g," ").substring(0,255)}function li(t){var e="";return vo(t)&&!Hu(t)&&t.childNodes&&t.childNodes.length&&Z(t.childNodes,(function(n){var i;Mu(n)&&n.textContent&&(e+=(i=Bu(n.textContent))!==null&&i!==void 0?i:"")})),Bs(e)}function yr(t){var e;return x(t.target)?t.srcElement||null:(e=t.target)!=null&&e.shadowRoot?t.composedPath()[0]||null:t.target||null}var aa=["a","button","form","input","select","textarea","label"];function mo(t,e){if(x(e))return!0;var n,i=function(r){if(e.some((o=>(function(a,l){var u=a.matches||a.matchesSelector||a.msMatchesSelector||a.mozMatchesSelector||a.webkitMatchesSelector||a.oMatchesSelector;try{return!!u&&u.call(a,l)}catch{return!1}})(r,o))))return{v:!0}};for(var s of t)if(n=i(s))return n.v;return!1}function Du(t){var e=t.parentNode;return!(!e||!$t(e))&&e}var Mp=[".ph-no-autocapture","[data-ph-no-autocapture]"],ju=["next","previous","prev",">","<"],Lp=[...ju,"+","-","−","–"],vl=(t,e)=>/[a-z0-9]/i.test(e)?t.includes(e):t===e,_l=[".ph-no-rageclick",".ph-no-capture"],Op=["","text","search","email","password","url","tel","number"];function yl(t,e){if(!_||la(t))return!1;var n,i,s,r,o;if(Ye(e)?(n=!!e&&_l,i=void 0,s=!1):(n=(r=e?.css_selector_ignorelist)!==null&&r!==void 0?r:_l,i=e?.content_ignorelist,s=(o=e?.ignore_text_selection)!==null&&o!==void 0&&o),n===!1||s&&(function(l){return!(!l||!$t(l))&&(!!Me(l,"textarea")||(Me(l,"input")?L(Op,(l.getAttribute("type")||"").toLowerCase()):(function(u){if(u.isContentEditable)return!0;var c=u.getAttribute==null?void 0:u.getAttribute("contenteditable");return c==="true"||c===""})(l)))})(t))return!1;var a=Uu(t,!1).targetElementList;return!(function(l,u){if(l===!1||x(l))return!1;var c;if(l===!0)c=ju;else{if(!O(l))return!1;if(l.length>10)return k.error("[PostHog] content_ignorelist array cannot exceed 10 items. Use css_selector_ignorelist for more complex matching."),!1;c=l.map((d=>d.toLowerCase()))}return u.some((d=>{var h=d.safeText,p=d.ariaLabel;return c.some((f=>vl(h,f)||vl(p,f)))}))})(i,a.map((l=>{var u;return{safeText:li(l).toLowerCase(),ariaLabel:((u=l.getAttribute("aria-label"))==null?void 0:u.toLowerCase().trim())||""}})))&&!mo(a,n)}var la=t=>!t||Me(t,"html")||!$t(t),Uu=(t,e)=>{if(!_||la(t))return{parentIsUsefulElement:!1,targetElementList:[]};for(var n=!1,i=[t],s=t;s.parentNode&&!Me(s,"body");)if(Lu(s.parentNode))i.push(s.parentNode.host),s=s.parentNode.host;else{var r=Du(s);if(!r)break;if(e||aa.indexOf(r.tagName.toLowerCase())>-1)n=!0;else try{var o=_.getComputedStyle(r);o&&o.getPropertyValue("cursor")==="pointer"&&(n=!0)}catch{}i.push(r),s=r}return{parentIsUsefulElement:n,targetElementList:i}};function vo(t){for(var e=new Set,n=0,i=t;i.parentNode&&!Me(i,"body");i=i.parentNode){if(n++>=Ou||e.has(i))return!1;e.add(i);var s=ms(i);if(L(s,"ph-sensitive")||L(s,"ph-no-capture"))return!1}if(L(ms(t),"ph-include"))return!0;var r=t.type||"";if(q(r))switch(r.toLowerCase()){case"hidden":case"password":return!1}var o=t.name||t.id||"";return!q(o)||!/^cc|cardnum|ccnum|creditcard|csc|cvc|cvv|exp|pass|pwd|routing|seccode|securitycode|securitynum|socialsec|socsec|ssn/i.test(o.replace(/[^a-zA-Z0-9]/g,""))}function Hu(t){return!!(Me(t,"input")&&!["button","checkbox","submit","reset"].includes(t.type)||Me(t,"select")||Me(t,"textarea")||t.getAttribute("contenteditable")==="true")}var wl=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}))$"),bl=/(^|[^0-9A-Za-z_])([0-9][0-9 -]*[0-9])(?=$|[^0-9A-Za-z_])/g,Bp=[16,15,14,13],Dp=new RegExp("^(\\d{3}-?\\d{2}-?\\d{4})$"),El=new RegExp("(^|[^0-9])((?!000|666)[0-9]{3}-?(?!00)[0-9]{2}-?(?!0000)[0-9]{4})(?=$|([^0-9]))","g"),Sl=/[0-9A-Za-z_]/;function jp(t){for(var e=0,n=!1,i=t.length-1;i>=0;i--){var s=t.charCodeAt(i)-48;n&&(s*=2)>9&&(s-=9),e+=s,n=!n}return e%10==0}function Qn(t,e){if(e===void 0&&(e=!0),B(t))return!1;if(q(t)){t=Bs(t);var n=e?wl.test((t||"").replace(/[- ]/g,"")):(function(s){var r;for(bl.lastIndex=0;r=bl.exec(s);){var o=r[2];if(o)for(var a=o.replace(/[- ]/g,""),l=0;a.length>l;l++)for(var u of Bp){var c=l+u;if(a.length>=c){var d=a.slice(l,c);if(wl.test(d)&&jp(d))return!0}}}return!1})(t);if(n)return!1;var i=e?Dp.test(t):(function(s){var r;for(El.lastIndex=0;r=El.exec(s);){var o=r[1],a=r[3];if(!(o&&a&&Sl.test(o)&&Sl.test(a)))return!0}return!1})(t);if(i)return!1}return!0}function xl(t){var e=li(t);return Qn(e=(e+" "+Wu(t)).trim())?e:""}function Wu(t){var e="";return t&&t.childNodes&&t.childNodes.length&&Z(t.childNodes,(function(n){var i;if(n&&((i=n.tagName)==null?void 0:i.toLowerCase())==="span")try{var s=li(n);e=(e+" "+s).trim(),n.childNodes&&n.childNodes.length&&(e=(e+" "+Wu(n)).trim())}catch(r){k.error("[AutoCapture]",r)}})),e}function kl(t){return t.replace(/"|\\"/g,'\\"')}function Up(t){var e=t.attr__class;if(e)return O(e)?e:oa(e)}var Pi=ie("[Dead Clicks]"),Hp=()=>!0,Wp=t=>{var e,n=!((e=t.instance.persistence)==null||!e.get_property(ta)),i=t.instance.config.capture_dead_clicks;return Ye(i)?i:!!ne(i)||n};class Il{get lazyLoadedDeadClicksAutocapture(){return this.si}constructor(e,n,i){this.instance=e,this.isEnabled=n,this.onCapture=i,this.startIfEnabledOrStop()}onRemoteConfig(e){if(e.ok){var n=e.config;"captureDeadClicks"in n&&(this.instance.persistence&&this.instance.persistence.register({[ta]:n.captureDeadClicks}),this.startIfEnabledOrStop())}}startIfEnabledOrStop(){this.isEnabled(this)?this.ai((()=>{this.oi()})):this.stop()}ai(e){var n,i;(n=R.__PosthogExtensions__)!=null&&n.initDeadClicksAutocapture?e():(i=R.__PosthogExtensions__)==null||i.loadExternalDependency==null||i.loadExternalDependency(this.instance,"dead-clicks-autocapture",(s=>{s?Pi.error("failed to load script",s):e()}))}oi(){var e;if(C){if(!this.si&&(e=R.__PosthogExtensions__)!=null&&e.initDeadClicksAutocapture){var n=ne(this.instance.config.capture_dead_clicks)?E({},this.instance.config.capture_dead_clicks):{};n.__onCapture=this.onCapture,this.onCapture&&(n.capture_dead_swipes=!1),this.si=R.__PosthogExtensions__.initDeadClicksAutocapture(this.instance,n),this.si.start(C),Pi.info("starting...")}}else Pi.error("`document` not found. Cannot start.")}stop(){this.si&&(this.si.stop(),this.si=void 0,Pi.info("stopping..."))}}var wr=ie("[SegmentIntegration]"),zu="posthog-js";function qu(t,e){var n=e===void 0?{}:e,i=n.organization,s=n.projectId,r=n.prefix,o=n.severityAllowList,a=o===void 0?["error"]:o,l=n.sendExceptionsToPostHog,u=l===void 0||l;return c=>{var d,h,p,f,g;if(a!=="*"&&!a.includes(c.level)||!t.__loaded)return c;c.tags||(c.tags={});var m=t.requestRouter.endpointFor("ui","/project/"+t.config.token+"/person/"+t.get_distinct_id());c.tags["PostHog Person URL"]=m,t.sessionRecordingStarted()&&(c.tags["PostHog Recording URL"]=t.get_session_replay_url({withTimestamp:!0}));var v,b=((d=c.exception)==null?void 0:d.values)||[],w=b.map((A=>E({},A,{stacktrace:A.stacktrace?E({},A.stacktrace,{type:"raw",frames:(A.stacktrace.frames||[]).map((F=>E({},F,{platform:"web:javascript"})))}):void 0}))),I={$exception_message:((h=b[0])==null?void 0:h.value)||c.message,$exception_type:(p=b[0])==null?void 0:p.type,$exception_level:c.level,$exception_list:w,$sentry_event_id:c.event_id,$sentry_exception:c.exception,$sentry_exception_message:((f=b[0])==null?void 0:f.value)||c.message,$sentry_exception_type:(g=b[0])==null?void 0:g.type,$sentry_tags:c.tags};return i&&s&&(I.$sentry_url=(r||"https://sentry.io/organizations/")+i+"/issues/?project="+s+"&query="+c.event_id),u&&((v=t.exceptions)==null||v.sendExceptionEvent(I)),c}}class zp{constructor(e,n,i,s,r,o){this.name=zu,this.setupOnce=function(a){a(qu(e,{organization:n,projectId:i,prefix:s,severityAllowList:r,sendExceptionsToPostHog:o==null||o}))}}}class Cl{constructor(e){this.li=(n,i,s)=>{s&&(s.noSessionId||s.activityTimeout||s.sessionPastMaximumLength||s.crossTabAdoption)&&(k.info("[PageViewManager] Session rotated, clearing pageview state",{sessionId:n,changeReason:s}),this.ui=void 0,this._instance.scrollManager.resetContext())},this._instance=e,this.hi()}hi(){var e;this.di=(e=this._instance.sessionManager)==null?void 0:e.onSessionId(this.li)}destroy(){var e;(e=this.di)==null||e.call(this),this.di=void 0}doPageView(e,n){var i,s=this.vi(e,n);return this.ui={pathname:(i=_?.location.pathname)!==null&&i!==void 0?i:"",pageViewId:n,timestamp:e},this._instance.scrollManager.resetContext(),s}doPageLeave(e){var n;return this.vi(e,(n=this.ui)==null?void 0:n.pageViewId)}doEvent(){var e;return{$pageview_id:(e=this.ui)==null?void 0:e.pageViewId}}vi(e,n){var i=this.ui;if(!i)return{$pageview_id:n};var s={$pageview_id:n,$prev_pageview_id:i.pageViewId},r=this._instance.scrollManager.getContext();if(r&&!this._instance.config.disable_scroll_properties){var o=r.maxScrollHeight,a=r.lastScrollY,l=r.maxScrollY,u=r.maxContentHeight,c=r.lastContentY,d=r.maxContentY;if(!(x(o)||x(a)||x(l)||x(u)||x(c)||x(d))){o=Math.ceil(o),a=Math.ceil(a),l=Math.ceil(l),u=Math.ceil(u),c=Math.ceil(c),d=Math.ceil(d);var h=o>1?ot(a/o,0,1,k):1,p=o>1?ot(l/o,0,1,k):1,f=u>1?ot(c/u,0,1,k):1,g=u>1?ot(d/u,0,1,k):1;s=te(s,{$prev_pageview_last_scroll:a,$prev_pageview_last_scroll_percentage:h,$prev_pageview_max_scroll:l,$prev_pageview_max_scroll_percentage:p,$prev_pageview_last_content:c,$prev_pageview_last_content_percentage:f,$prev_pageview_max_content:d,$prev_pageview_max_content_percentage:g})}}return i.pathname&&(s.$prev_pageview_pathname=i.pathname),i.timestamp&&(s.$prev_pageview_duration=(e.getTime()-i.timestamp.getTime())/1e3),s}}var br=["flags","surveys"],qp={[bu]:{exposure:"hidden"},[zn]:{exposure:"hidden"},__cmpns:{exposure:"hidden"},[qn]:{exposure:"hidden"},[Qr]:{exposure:"event"},[eo]:{exposure:"hidden"},[to]:{exposure:"event"},[no]:{exposure:"hidden"},[io]:{exposure:"event"},[so]:{exposure:"event"},[ta]:{exposure:"event"},[na]:{exposure:"hidden"},[ro]:{exposure:"event"},[Jt]:{exposure:"hidden"},$session_recording_enabled_server_side:{exposure:"hidden"},[hn]:{exposure:"hidden"},[ia]:{exposure:"event"},[Eu]:{exposure:"event",shouldSkipFromEventProperties:t=>$e(t)},$session_past_minimum_duration:{exposure:"event"},$session_recording_url_trigger_activated_session:{exposure:"event"},$session_recording_event_trigger_activated_session:{exposure:"event"},$debug_first_full_snapshot_timestamp:{exposure:"event"},$sess_rec_flush_size:{exposure:"hidden"},[Wt]:{exposure:"hidden",storageGroup:"flags"},[Vn]:{exposure:"hidden",storageGroup:"flags"},[ji]:{exposure:"hidden"},[oo]:{exposure:"hidden",storageGroup:"flags"},[Gn]:{exposure:"hidden",storageGroup:"flags"},[Ui]:{exposure:"hidden",storageGroup:"flags",volatile:!0},[cs]:{exposure:"hidden",storageGroup:"flags"},[it]:{exposure:"hidden"},[zt]:{exposure:"hidden"},[ht]:{exposure:"hidden"},[qt]:{exposure:"hidden"},[ao]:{exposure:"hidden",storageGroup:"surveys"},[us]:{exposure:"hidden",storageGroup:"surveys",volatile:!0},[lo]:{exposure:"event"},[Hi]:{exposure:"hidden"},[Wi]:{exposure:"hidden"},[Kn]:{exposure:"hidden"},$product_tours_activated:{exposure:"hidden"},$product_tours_activated_session:{exposure:"hidden"},$conversations_widget_session_id:{exposure:"event"},$conversations_ticket_id:{exposure:"event"},$conversations_widget_state:{exposure:"event"},$conversations_user_traits:{exposure:"event"},[Gt]:{exposure:"hidden"},[Jn]:{exposure:"hidden"},[zi]:{exposure:"hidden"},[Xn]:{exposure:"hidden",storageGroup:"flags",volatile:!0},[He]:{exposure:"hidden"},[co]:{exposure:"hidden"},[uo]:{exposure:"hidden"},[ho]:{exposure:"hidden"},[po]:{exposure:"hidden"},[ds]:{exposure:"hidden"},[hs]:{exposure:"hidden"},[Su]:{exposure:"event"},[xu]:{exposure:"event"},[ku]:{exposure:"event"},[Iu]:{exposure:"event"},[Au]:{exposure:"event"},[Fu]:{exposure:"event"},[Pu]:{exposure:"event"},$sdk_debug_replay_event_trigger_status:{exposure:"event"},$sdk_debug_replay_linked_flag_trigger_status:{exposure:"event"},$sdk_debug_replay_matched_recording_trigger_groups:{exposure:"event"},$sdk_debug_replay_remote_trigger_matching_config:{exposure:"event"},$sdk_debug_replay_trigger_groups_count:{exposure:"event"},$sdk_debug_replay_url_trigger_status:{exposure:"event"},$session_recording_start_reason:{exposure:"event"}},Vp=[["$posthog_sr_group_event_trigger_",{exposure:"hidden"}],["$posthog_sr_group_url_trigger_",{exposure:"hidden"}],["$posthog_sr_group_sampling_",{exposure:"hidden"}]],Dt=t=>{var e=qp[t];if(e)return e;for(var n of Vp){var i=n[1];if(t.indexOf(n[0])===0)return i}},pn=(t,e)=>{try{return JSON.stringify(t,((n,i)=>typeof i=="bigint"?i.toString():i),e)}catch{return Hc(t)}},vs=t=>{var e=C?.createElement("a");return x(e)?null:(e.href=t,e)},wn=function(t,e){for(var n,i=((t.split("#")[0]||"").split(/\?(.*)/)[1]||"").replace(/^\?+/g,"").split("&"),s=0;i.length>s;s++){var r=i[s].split("=");if(r[0]===e){n=r;break}}if(!O(n)||2>n.length)return"";var o=n[1];try{o=decodeURIComponent(o)}catch{k.error("Skipping decoding for malformed query param: "+o)}return o.replace(/\+/g," ")},ci=function(t,e,n){if(!t||!e||!e.length)return t;for(var i=t.split("#"),s=i[1],r=(i[0]||"").split("?"),o=r[1],a=r[0],l=(o||"").split("&"),u=[],c=0;l.length>c;c++){var d=l[c].split("=");O(d)&&(e.includes(d[0])?u.push(d[0]+"="+n):u.push(l[c]))}var h=a;return o!=null&&(h+="?"+u.join("&")),s!=null&&(h+="#"+s),h},_s=function(t,e){var n=t.match(new RegExp(e+"=([^&]*)"));return n?n[1]:null},Vu=(t,e)=>t>=e&&Dc(),Gu=(t,e,n,i)=>{if(t===0){if(Dc()){var s=e+1;return s===n&&i(),s}return e}return 0},$i="https?://(.*)",bn=["gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","irclid","_kx"],Gp=["utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid",...bn],ui="",Kp=["li_fat_id"];function Ku(t,e,n){if(!C)return{};var i,s=e?[...bn,...n||[]]:[],r=Ju(ci(C.URL,s,ui),t),o=(i={},Z(Kp,(function(a){var l=$u(a);i[a]=l||null})),i);return te(o,r)}function Ju(t,e){var n=Gp.concat(e||[]),i={};return Z(n,(function(s){var r=wn(t,s);i[s]=r||null})),i}function Yu(t){var e=(function(r){return r?r.search($i+"google.([^/?]*)")===0?"google":r.search($i+"bing.com")===0?"bing":r.search($i+"yahoo.com")===0?"yahoo":r.search($i+"duckduckgo.com")===0?"duckduckgo":null:null})(t),n=e!="yahoo"?"q":"p",i={};if(!$e(e)){i.$search_engine=e;var s=C?wn(C.referrer,n):"";s.length&&(i.ph_keyword=s)}return i}function Al(){return navigator.language||navigator.userLanguage}var ys="$direct";function Zu(){return C?.referrer||ys}function Xu(t,e,n){n===void 0&&(n=!1);var i=t?[...bn,...e||[]]:[],s=n?Pt(se?.href):se?.href,r=s?.substring(0,1e3);return{r:Zu().substring(0,1e3),u:r?ci(r,i,ui):void 0}}function Qu(t,e){var n;e===void 0&&(e=!1);var i=t.r,s=t.u,r=e?Pt(s):s,o={$referrer:i,$referring_domain:i==null?void 0:i==ys?ys:(n=vs(i))==null?void 0:n.host};if(r){o.$current_url=r;var a=vs(r);o.$host=a?.host,o.$pathname=a?.pathname;var l=Ju(r);te(o,l)}if(i){var u=Yu(i);te(o,u)}return o}function ed(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return}}function Jp(){try{return new Date().getTimezoneOffset()}catch{return}}var Yp={flags:Xn,surveys:us},Zp=["cookie","localstorage","localstorage+cookie","sessionstorage","memory"],rn="main";class Er{constructor(e,n,i){if(i===void 0&&(i=!0),this.ci={},this.fi=!1,this.pi=!1,this.Ne=e,this.gi=i,this.props={},this.mi=void 0,this.yi=(r=>{var o="";return r.token&&(o=r.token.replace(/\+/g,"PL").replace(/\//g,"SL").replace(/=/g,"EQ")),r.persistence_name?"ph_"+r.persistence_name:"ph_"+o+"_posthog"})(e),this.ii=this.bi(e),this.pi=this.wi(e),this.load(),e.debug&&k.info("Persistence loaded",e.persistence,E({},this.props)),this.update_config(e,e,n),this.save(),_){var s=()=>this.flush();re(_,"beforeunload",s,{capture:!1}),re(_,"pagehide",s,{capture:!1})}}ki(){var e,n=(e=this.Ne)==null?void 0:e.persistence_save_debounce_ms;return he(n)&&n>0?n:0}isDisabled(){return!!this.xi}bi(e){Zp.indexOf(e.persistence.toLowerCase())===-1&&(k.critical("Unknown persistence type "+e.persistence+"; falling back to localStorage+cookie"),e.persistence="localStorage+cookie");var n,i=(function(o,a){o===void 0&&(o=[]),a===void 0&&(a=!1);var l=[...Fp,...o];return E({},ee,{H(u){try{var c={};try{c=mt.H(u)||{}}catch{}var d,h=JSON.parse(ee.P(u)||"{}");if(a){var p={};for(var f in c){var g=c[f];$e(g)||g===""||(p[f]=g)}d=te(h,p)}else d=te(c,h);return ee.F(u,d),d}catch{}return null},F(u,c,d,h,p,f){var g=ee.F(u,c,void 0,void 0,f);try{var m={};l.forEach((v=>{c[v]&&(m[v]=c[v])})),Object.keys(m).length&&mt.F(u,m,d,h,p,f)}catch(v){ee.j(v)}return g},q(u,c){try{_?.localStorage.removeItem(u),mt.q(u,c)}catch(d){ee.j(d)}}})})(e.cookie_persisted_properties||[],e.__preview_cookie_wins_on_conflict||!1),s=!1,r=e.persistence.toLowerCase();return r==="localstorage"&&ee.N()?(n=ee,s=!0):r==="localstorage+cookie"&&i.N()?(n=i,s=!0):r==="sessionstorage"&&ce.N()?n=ce:r==="memory"?n=Pp:r==="cookie"?n=mt:i.N()?(n=i,s=!0):n=mt,this.fi=s,n}Si(e){return this.yi+"__"+e}wi(e){return this.fi&&!!e.split_storage}properties(){var e={};return Z(this.props,((n,i)=>{var s=Dt(i);if(!s||s.exposure==="event"){if(s!=null&&s.shouldSkipFromEventProperties!=null&&s.shouldSkipFromEventProperties(n))return;e[i]=n}})),e}load(){if(!this.xi){var e=this.ii.H(this.yi);e&&(this.props=te({},e)),this.pi&&this.Ci()}}Ci(){for(var e of br){var n=ee.H(this.Si(e));if(n&&!yt(n)){var i=this.Mi(e);i.persisted=!0,this.Ti(e)||(i.fingerprint=this.Ei(n,e)),this.Ii(e,n)||te(this.props,n)}}}Ti(e){return Object.keys(this.props).some((n=>{var i;return((i=Dt(n))==null?void 0:i.storageGroup)===e}))}Ii(e,n){var i=Yp[e];if(!i)return!1;var s=n[i],r=this.props[i];return he(s)&&he(r)&&r>s}refreshKey(e){var n;if(!this.xi){var i=this.pi?(n=Dt(e))==null?void 0:n.storageGroup:void 0,s=i?ee.H(this.Si(i)):this.ii.H(this.yi);if(s&&e in s)this.Pi(e,s[e]);else{if(i){var r=this.ii.H(this.yi);if(r&&e in r)return void this.Pi(e,r[e])}this.Ri(e)}}}save(){if(!this.xi){var e=this.ki();e>0?x(this.Ai)&&(this.Ai=setTimeout((()=>{this.Ai=void 0,this.Fi()}),e)):this.Fi()}}flush(){x(this.Ai)||(clearTimeout(this.Ai),this.Ai=void 0,this.Fi())}Fi(){this.xi||(this.pi?this.Li():this.Oi(this.ii,this.yi,this.props,rn))}Li(){var e=this.Di(),n=e.main,i=e.groups;for(var s of(this.Oi(this.ii,this.yi,n,rn),br)){var r,o=i[s];(!yt(o)||(r=this.ci[s])!=null&&r.persisted)&&this.Oi(ee,this.Si(s),o,s)}}Di(){var e={},n={flags:{},surveys:{}};return Z(this.props,((i,s)=>{var r,o=(r=Dt(s))==null?void 0:r.storageGroup;o?n[o][s]=i:e[s]=i})),{main:e,groups:n}}Ei(e,n){if(n===rn)return JSON.stringify(e)+"|"+this.$i+"|"+this.Ni+"|"+this.qi;var i={};return Z(e,((s,r)=>{var o;i[r]=(o=Dt(r))!=null&&o.volatile?"__volatile__":s})),JSON.stringify(i)}Oi(e,n,i,s){var r=this.Mi(s);if(s===rn||r.dirty||x(r.fingerprint)){var o;try{if((o=this.Ei(i,s))===r.fingerprint)return void(r.dirty=!1)}catch{o=void 0}e.F(n,i,this.$i,this.Ni,this.qi,this.Ne.debug)?(r.dirty=!1,s!==rn&&(r.persisted=!0),x(o)||(r.fingerprint=o)):this.Ne.debug&&k.warn('failed to persist storage entry "'+n+'"; will retry on next save')}}remove(e){var n=(e===void 0?{}:e).keepGroupEntries,i=n!==void 0&&n;if(x(this.Ai)||(clearTimeout(this.Ai),this.Ai=void 0),this.ii.q(this.yi,!1),this.ii.q(this.yi,!0),!i&&this.gi)for(var s of br)ee.q(this.Si(s));i?delete this.ci[rn]:this.ci={}}clear(){this.remove(),this.props={}}register_once(e,n,i){if(ne(e)){x(n)&&(n="None"),this.$i=x(i)?this.ji:i;var s=!1;if(Z(e,((r,o)=>{this.props.hasOwnProperty(o)&&this.props[o]!==n||(this.Pi(o,r),s=!0)})),s)return this.save(),!0}return!1}register(e,n){if(ne(e)){this.$i=x(n)?this.ji:n;var i=!1;if(Z(e,((s,r)=>{e.hasOwnProperty(r)&&(this.props[r]!==s||ne(s)||O(s))&&(this.Pi(r,s),i=!0)})),i)return this.save(),!0}return!1}unregister(e){var n=typeof e=="string"?[e]:e,i=!1;for(var s of n)s in this.props&&(this.Ri(s),i=!0);i&&this.save()}update_campaign_params(){var e=C?.URL;if(e!==this.mi){var n=Ku(this.Ne.custom_campaign_params,this.Ne.mask_personal_data_properties,this.Ne.custom_personal_data_properties);yt(ra(n))||this.register(n),this.mi=e}}update_search_keyword(){var e;this.register((e=C?.referrer)?Yu(e):{})}update_referrer_info(){var e;this.register_once({$referrer:Zu(),$referring_domain:C!=null&&C.referrer&&((e=vs(C.referrer))==null?void 0:e.host)||ys},void 0)}set_initial_person_info(){this.props[ho]||this.props[po]||this.register_once({[ds]:Xu(this.Ne.mask_personal_data_properties,this.Ne.custom_personal_data_properties,this.Ne.disable_capture_url_hashes)},void 0)}get_initial_props(){var e={};Z([po,ho],(s=>{var r=this.props[s];r&&Z(r,(function(o,a){e["$initial_"+Vr(a)]=o}))}));var n=this.props[ds];if(n){var i=(function(s,r){r===void 0&&(r=!1);var o=Qu(s,r),a={};return Z(o,(function(l,u){a["$initial_"+Vr(u)]=l})),a})(n,this.Ne.disable_capture_url_hashes);te(e,i)}return e}safe_merge(e){return Z(this.props,(function(n,i){i in e||(e[i]=n)})),e}update_config(e,n,i){this.ji=this.$i=e.cookie_expiration,this.set_disabled(e.disable_persistence||!!i),this.set_cross_subdomain(e.cross_subdomain_cookie),this.set_secure(e.secure_cookie);var s=e.persistence!==n.persistence||!((l,u)=>{if(l.length!==u.length)return!1;var c=[...l].sort(),d=[...u].sort();return c.every(((h,p)=>h===d[p]))})(e.cookie_persisted_properties||[],n.cookie_persisted_properties||[]),r=s?this.bi(e):this.ii,o=this.wi(e);if(s||o!==this.pi){var a=this.props;this.clear(),this.ii=r,this.pi=o,this.props=a,this.save()}}set_disabled(e){this.xi=e,this.xi?this.remove():this.save()}set_cross_subdomain(e){e!==this.Ni&&(this.Ni=e,this.remove({keepGroupEntries:!0}),this.save())}set_secure(e){e!==this.qi&&(this.qi=e,this.remove({keepGroupEntries:!0}),this.save())}set_event_timer(e,n){var i=this.props[qn]||{};i[e]=n,this.Pi(qn,i),this.save()}remove_event_timer(e){var n=this.props[qn]||{},i=n[e];return x(i)||(delete n[e],this.Pi(qn,n),this.save()),i}get_property(e){return this.props[e]}set_property(e,n){this.Pi(e,n),this.save()}Pi(e,n){var i;this.props[e]=n,(i=Dt(e))!=null&&i.volatile||this.Bi(e)}Ri(e){delete this.props[e],this.Bi(e)}Bi(e){var n,i=(n=Dt(e))==null?void 0:n.storageGroup;i&&(this.Mi(i).dirty=!0)}Mi(e){return this.ci[e]||(this.ci[e]={})}}function Ti(t){var e=!0;return{dispose(){if(e){e=!1;var n=t();n&&Se(n.then)&&n.then(void 0,(()=>{}))}}}}var xe={GZipJS:"gzip-js",Base64:"base64"},Mn={Activation:"events",Cancellation:"cancelEvents"},Sr={Popover:"popover",API:"api",Widget:"widget"},vt={SHOWN:"survey shown",DISMISSED:"survey dismissed",SENT:"survey sent"},xr={SURVEY_ID:"$survey_id",SURVEY_ITERATION:"$survey_iteration",SURVEY_LAST_SEEN_DATE:"$survey_last_seen_date"},_o={Popover:"popover",Inline:"inline"},Xp={SHOWN:"product tour shown"},Fl={TOUR_LAST_SEEN_DATE:"$product_tour_last_seen_date",TOUR_TYPE:"$product_tour_type"},Pl=ie("[RateLimiter]");class Qp{constructor(e){this.serverLimits={},this.lastEventRateLimited=!1,this.checkForLimiting=n=>{var i=n.text;if(i&&i.length)try{(JSON.parse(i).quota_limited||[]).forEach((s=>{Pl.info((s||"events")+" is quota limited."),this.serverLimits[s]=new Date().getTime()+6e4}))}catch(s){return void Pl.warn('could not rate limit - continuing. Error: "'+s?.message+'"',{text:i})}},this.instance=e,this.lastEventRateLimited=this.clientRateLimitContext(!0).isRateLimited}get captureEventsPerSecond(){var e;return((e=this.instance.config.rate_limiting)==null?void 0:e.events_per_second)||10}get captureEventsBurstLimit(){var e;return Math.max(((e=this.instance.config.rate_limiting)==null?void 0:e.events_burst_limit)||10*this.captureEventsPerSecond,this.captureEventsPerSecond)}clientRateLimitContext(e){var n,i,s;e===void 0&&(e=!1);var r=this.captureEventsBurstLimit,o=this.captureEventsPerSecond,a=new Date().getTime(),l=(n=(i=this.instance.persistence)==null?void 0:i.get_property(uo))!==null&&n!==void 0?n:{tokens:r,last:a};l.tokens+=(a-l.last)/1e3*o,l.last=a,l.tokens>r&&(l.tokens=r);var u=1>l.tokens;if(u||e||(l.tokens=Math.max(0,l.tokens-1)),u&&!e){var c=(he(l.dropped)?l.dropped:0)+1;l.dropped=c,!this.lastEventRateLimited&&this.Hi(c)&&(l.dropped=0)}return this.lastEventRateLimited=u,(s=this.instance.persistence)==null||s.set_property(uo,l),{isRateLimited:u,remainingTokens:l.tokens}}Ui(e){var n=this.instance.config.property_denylist;return!O(n)||!n.includes(e)}zi(){var e;if(this.Ui("$current_url")&&this.Ui("$pathname")&&se!=null&&se.pathname)return""+((e=se.origin)!==null&&e!==void 0?e:"")+se.pathname}Hi(e){var n,i,s=this.captureEventsBurstLimit,r=this.captureEventsPerSecond,o=this.zi(),a=this.Ui("$session_id")?(n=(i=this.instance).get_session_id)==null?void 0:n.call(i):void 0,l=[e+" event(s) dropped since the last warning",o?"triggered on "+o:void 0,a?"session "+a: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 "+r+" events per second and "+s+" events burst limit."},{skip_client_rate_limiting:!0})}isServerRateLimited(e){var n=this.serverLimits[e||"events"]||!1;return n!==!1&&new Date().getTime()e(this.remoteConfig))):e()}Vi(e){this._instance._send_request({method:"GET",url:this._instance.requestRouter.endpointFor("assets","/array/"+this._instance.config.token+"/config"),callback:e})}load(){try{if(this.remoteConfig)return Ct.info("Using preloaded remote config",this.remoteConfig),this.Zi(this.remoteConfig),void this.Gi();if(this._instance.Qi())return void Ct.warn("Remote config is disabled. Falling back to local config.");this.Wi((e=>{if(!e)return Ct.info("No config found after loading remote JS config. Falling back to JSON."),void this.Vi((n=>{this.Zi(n.json,n),this.Gi()}));this.Zi(e),this.Gi()}))}catch(e){Ct.error("Error loading remote config",e),this.Zi()}}stop(){this.Ki&&(clearInterval(this.Ki),this.Ki=void 0)}refresh(){!this._instance.Qi()&&C&&C.visibilityState!=="hidden"&&this._instance.reloadFeatureFlags()}Gi(){var e;if(!this.Ki){var n=(e=this._instance.config.remote_config_refresh_interval_ms)!==null&&e!==void 0?e:3e5;n!==0&&(this.Ki=setInterval((()=>{this.refresh()}),n))}}Zi(e,n){!e&&n&&(n.statusCode===0?n.error||Ct.warn("Failed to fetch remote config from PostHog."):Ct.error("Failed to fetch remote config from PostHog."));try{this._instance.Zi(e?{ok:!0,config:e}:{ok:!1})}catch(s){Ct.error("Error applying remote config",s)}if(e?.hasFeatureFlags!==!1&&!this._instance.config.advanced_disable_feature_flags_on_first_load)try{var i;(i=this._instance.featureFlags)==null||i.ensureFlagsLoaded()}catch(s){Ct.error("Error loading feature flags",s)}}}var qe=Uint8Array,Pe=Uint16Array,En=Uint32Array,ca=new qe([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]),ua=new qe([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]),$l=new qe([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),nd=function(t,e){for(var n=new Pe(31),i=0;31>i;++i)n[i]=e+=1<i;++i)for(var r=n[i];n[i+1]>r;++r)s[r]=r-n[i]<<5|i;return[n,s]},id=nd(ca,2),yo=id[1];id[0][28]=258,yo[258]=28;for(var Tl=nd(ua,0)[1],sd=new Pe(32768),oe=0;32768>oe;++oe){var on=(43690&oe)>>>1|(21845&oe)<<1;sd[oe]=((65280&(on=(61680&(on=(52428&on)>>>2|(13107&on)<<2))>>>4|(3855&on)<<4))>>>8|(255&on)<<8)>>>1}var ei=function(t,e,n){for(var i=t.length,s=0,r=new Pe(e);i>s;++s)++r[t[s]-1];var o,a=new Pe(e);for(s=0;e>s;++s)a[s]=a[s-1]+r[s-1]<<1;for(o=new Pe(i),s=0;i>s;++s)o[s]=sd[a[t[s]-1]++]>>>15-t[s];return o},Xt=new qe(288);for(oe=0;144>oe;++oe)Xt[oe]=8;for(oe=144;256>oe;++oe)Xt[oe]=9;for(oe=256;280>oe;++oe)Xt[oe]=7;for(oe=280;288>oe;++oe)Xt[oe]=8;var ws=new qe(32);for(oe=0;32>oe;++oe)ws[oe]=5;var ef=ei(Xt,9),tf=ei(ws,5),rd=function(t){return(t/8>>0)+(7&t&&1)},od=function(t,e,n){(n==null||n>t.length)&&(n=t.length);var i=new(t instanceof Pe?Pe:t instanceof En?En:qe)(n-e);return i.set(t.subarray(e,n)),i},ct=function(t,e,n){var i=e/8>>0;t[i]|=n<<=7&e,t[i+1]|=n>>>8},Ln=function(t,e,n){var i=e/8>>0;t[i]|=n<<=7&e,t[i+1]|=n>>>8,t[i+2]|=n>>>16},kr=function(t,e){for(var n=[],i=0;t.length>i;++i)t[i]&&n.push({s:i,f:t[i]});var s=n.length,r=n.slice();if(!s)return[new qe(0),0];if(s==1){var o=new qe(n[0].s+1);return o[n[0].s]=1,[o,1]}n.sort((function(A,F){return A.f-F.f})),n.push({s:-1,f:25001});var a=n[0],l=n[1],u=0,c=1,d=2;for(n[0]={s:-1,f:a.f+l.f,l:a,r:l};c!=s-1;)a=n[n[d].f>n[u].f?u++:d++],l=n[u!=c&&n[d].f>n[u].f?u++:d++],n[c++]={s:-1,f:a.f+l.f,l:a,r:l};var h=r[0].s;for(i=1;s>i;++i)r[i].s>h&&(h=r[i].s);var p=new Pe(h+1),f=wo(n[c-1],p,0);if(f>e){i=0;var g=0,m=f-e,v=1<i;++i){var b=r[i].s;if(e>=p[b])break;g+=v-(1<>>=m;g>0;){var w=r[i].s;e>p[w]?g-=1<=0&&g;--i){var I=r[i].s;p[I]==e&&(--p[I],++g)}f=e}return[new qe(p),f]},wo=function(t,e,n){return t.s==-1?Math.max(wo(t.l,e,n+1),wo(t.r,e,n+1)):e[t.s]=n},Rl=function(t){for(var e=t.length;e&&!t[--e];);for(var n=new Pe(++e),i=0,s=t[0],r=1,o=function(l){n[i++]=l},a=1;e>=a;++a)if(t[a]==s&&a!=e)++r;else{if(!s&&r>2){for(;r>138;r-=138)o(32754);r>2&&(o(r>10?r-11<<5|28690:r-3<<5|12305),r=0)}else if(r>3){for(o(s),--r;r>6;r-=6)o(8304);r>2&&(o(r-3<<5|8208),r=0)}for(;r--;)o(s);r=1,s=t[a]}return[n.subarray(0,i),e]},On=function(t,e){for(var n=0,i=0;e.length>i;++i)n+=t[i]*e[i];return n},bo=function(t,e,n){var i=n.length,s=rd(e+2);t[s]=255&i,t[s+1]=i>>>8,t[s+2]=255^t[s],t[s+3]=255^t[s+1];for(var r=0;i>r;++r)t[s+r+4]=n[r];return 8*(s+4+i)},Nl=function(t,e,n,i,s,r,o,a,l,u,c){ct(e,c++,n),++s[256];for(var d=kr(s,15),h=d[0],p=d[1],f=kr(r,15),g=f[0],m=f[1],v=Rl(h),b=v[0],w=v[1],I=Rl(g),A=I[0],F=I[1],D=new Pe(19),S=0;b.length>S;++S)D[31&b[S]]++;for(S=0;A.length>S;++S)D[31&A[S]]++;for(var $=kr(D,7),T=$[0],M=$[1],N=19;N>4&&!T[$l[N-1]];--N);var P,z,H,U,Q=u+5<<3,fe=On(s,Xt)+On(r,ws)+o,Ie=On(s,h)+On(r,g)+o+14+3*N+On(D,T)+(2*D[16]+3*D[17]+7*D[18]);if(fe>=Q&&Ie>=Q)return bo(e,c,t.subarray(l,l+u));if(ct(e,c,1+(fe>Ie)),c+=2,fe>Ie){P=ei(h,p),z=h,H=ei(g,m),U=g;var _e=ei(T,M);for(ct(e,c,w-257),ct(e,c+5,F-1),ct(e,c+10,N-4),c+=14,S=0;N>S;++S)ct(e,c+3*S,T[$l[S]]);c+=3*N;for(var Ce=[b,A],Te=0;2>Te;++Te){var ae=Ce[Te];for(S=0;ae.length>S;++S)ct(e,c,_e[me=31&ae[S]]),c+=T[me],me>15&&(ct(e,c,ae[S]>>>5&127),c+=ae[S]>>>12)}}else P=ef,z=Xt,H=tf,U=ws;for(S=0;a>S;++S)if(i[S]>255){var me;Ln(e,c,P[257+(me=i[S]>>>18&31)]),c+=z[me+257],me>7&&(ct(e,c,i[S]>>>23&31),c+=ca[me]);var ge=31&i[S];Ln(e,c,H[ge]),c+=U[ge],ge>3&&(Ln(e,c,i[S]>>>5&8191),c+=ua[ge])}else Ln(e,c,P[i[S]]),c+=z[i[S]];return Ln(e,c,P[256]),c+z[256]},nf=new En([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),sf=(function(){for(var t=new En(256),e=0;256>e;++e){for(var n=e,i=9;--i;)n=(1&n&&3988292384)^n>>>1;t[e]=n}return t})(),Ir=function(t,e,n){for(;n;++e)t[e]=n,n>>>=8};function rf(t,e){e===void 0&&(e={});var n=(function(){var d=4294967295;return{p(h){for(var p=d,f=0;h.length>f;++f)p=sf[255&p^h[f]]^p>>>8;d=p},d(){return 4294967295^d}}})(),i=t.length;n.p(t);var s,r,o,a,l,u=(a=10+((s=e).filename&&s.filename.length+1||0),l=8,(function(d,h,p,f,g,m){var v=d.length,b=new qe(f+v+5*(1+Math.floor(v/7e3))+g),w=b.subarray(f,b.length-g),I=0;if(!h||8>v)for(var A=0;v>=A;A+=65535){var F=A+65535;v>F?I=bo(w,I,d.subarray(A,F)):(w[A]=!0,I=bo(w,I,d.subarray(A,v)))}else{for(var D=nf[h-1],S=D>>>13,$=8191&D,T=(1<A;++A){var me=H(A),ge=32767&A,Qe=N[me];if(M[ge]=Qe,N[me]=ge,A>=Te){var Lt=v-A;if((Ie>7e3||Ce>24576)&&Lt>423){I=Nl(d,w,0,U,Q,fe,_e,Ce,ae,A-ae,I),Ce=Ie=_e=0,ae=A;for(var de=0;286>de;++de)Q[de]=0;for(de=0;30>de;++de)fe[de]=0}var Ge=2,It=0,Pn=$,De=ge-Qe&32767;if(Lt>2&&me==H(A-De))for(var Ae=Math.min(S,Lt)-1,Ei=Math.min(32767,A),Si=Math.min(258,Lt);Ei>=De&&--Pn&&ge!=Qe;){if(d[A+Ge]==d[A+Ge-De]){for(var je=0;Si>je&&d[A+je]==d[A+je-De];++je);if(je>Ge){if(Ge=je,It=De,je>Ae)break;var xi=Math.min(De,je-2),tn=0;for(de=0;xi>de;++de){var nn=A-De+de+32768&32767,$n=nn-M[nn]+32768&32767;$n>tn&&(tn=$n,Qe=nn)}}}De+=(ge=Qe)-(Qe=M[ge])+32768&32767}if(It){U[Ce++]=268435456|yo[Ge]<<18|Tl[It];var Va=31&yo[Ge],Ga=31&Tl[It];_e+=ca[Va]+ua[Ga],++Q[257+Va],++fe[Ga],Te=A+Ge,++Ie}else U[Ce++]=d[A],++Q[d[A]]}}I=Nl(d,w,!0,U,Q,fe,_e,Ce,ae,A-ae,I)}return od(b,0,f+rd(I)+g)})(r=t,(o=e).level==null?6:o.level,o.mem==null?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(r.length)))):12+o.mem,a,l)),c=u.length;return(function(d,h){var p=h.filename;if(d[0]=31,d[1]=139,d[2]=8,d[8]=2>h.level?4:h.level==9?2:0,d[9]=3,h.mtime!=0&&Ir(d,4,Math.floor(new Date(h.mtime||Date.now())/1e3)),p){d[3]=8;for(var f=0;p.length>=f;++f)d[f+10]=p.charCodeAt(f)}})(u,e),Ir(u,c-8,n.d()),Ir(u,c-4,i),u}var of=!!Wr||!!Ko,ad="text/plain",Vi=!1,ld=(t,e)=>{var n=t.split("#"),i=n[1],s=n[0].split("?"),r=s[0],o=s[1];if(!o)return t;var a=o.split("&").filter((l=>l.split("=")[0]!==e)).join("&");return r+(a?"?"+a:"")+(i?"#"+i:"")},js=function(t,e,n){var i;n===void 0&&(n=!0);var s=t.split("?"),r=s[0],o=s[1],a=E({},e),l=(i=o?.split("&").map((c=>{var d,h=c.split("="),p=h[0],f=n&&(d=a[p])!==null&&d!==void 0?d:h[1];return delete a[p],p+"="+f})))!==null&&i!==void 0?i:[],u=(function(c,d){var h,p;d===void 0&&(d="&");var f=[];return Z(c,(function(g,m){x(g)||x(m)||m==="undefined"||(h=encodeURIComponent((v=>v instanceof File)(g)?g.name:g.toString()),p=encodeURIComponent(m),f[f.length]=p+"="+h)})),f.join(d)})(a);return u&&l.push(u),l.length>0?r+"?"+l.join("&"):r},Cr=t=>{if(t.Ji)return t.Ji;var e=t.data,n=t.compression;if(e){if(n===xe.GZipJS){var i=rf((function(a,l){var u=a.length;if(typeof TextEncoder<"u")return new TextEncoder().encode(a);for(var c=new qe(a.length+(a.length>>>1)),d=0,h=function(m){c[d++]=m},p=0;u>p;++p){if(d+5>c.length){var f=new qe(d+8+(u-p<<1));f.set(c),c=f}var g=a.charCodeAt(p);128>g?h(g):2048>g?(h(192|g>>>6),h(128|63&g)):g>55295&&57344>g?(h(240|(g=65536+(1047552&g)|1023&a.charCodeAt(++p))>>>18),h(128|g>>>12&63),h(128|g>>>6&63),h(128|63&g)):(h(224|g>>>12),h(128|g>>>6&63),h(128|63&g))}return od(c,0,d)})(pn(e)),{mtime:0});return{contentType:ad,body:i.buffer.slice(i.byteOffset,i.byteOffset+i.byteLength),estimatedSize:i.byteLength}}if(n===xe.Base64){var s=(function(a){return a&&btoa(encodeURIComponent(a).replace(/%([0-9A-F]{2})/g,((l,u)=>String.fromCharCode(parseInt(u,16)))))})(pn(e)),r=(a=>"data="+encodeURIComponent(typeof a=="string"?a:pn(a)))(s);return{contentType:"application/x-www-form-urlencoded",body:r,estimatedSize:new Blob([r]).size}}var o=pn(e);return{contentType:"application/json",body:o,estimatedSize:new Blob([o]).size}}},cd=t=>{var e,n,i=()=>t.transport==="sendBeacon"?{url:js(t.url,{compression:xe.Base64}),encodedBody:Cr(E({},t,{compression:xe.Base64,Ji:void 0}))}:{url:ld(t.url,"compression"),encodedBody:Cr(E({},t,{compression:void 0,Ji:void 0}))};try{e=Cr(t)}catch(s){if(el(t.compression,wn(t.url,"compression")))return k.error("Failed to gzip request body, sending uncompressed payload",s),i();throw s}return e&&el(t.compression,wn(t.url,"compression"))&&!((n=e.body)instanceof ArrayBuffer?zr(new Uint8Array(n)):ArrayBuffer.isView(n)&&zr(new Uint8Array(n.buffer,n.byteOffset,n.byteLength)))?(Vi=!0,i()):{url:t.url,encodedBody:e}},ud=t=>{try{return cd(t)}catch(e){return k.error(e),void(t.callback==null||t.callback({statusCode:0,error:e}))}},af=(function(){var t=X((function*(e){var n=pn(e.data),i=yield(function(r,o,a){return qr.apply(this,arguments)})(n,Y.DEBUG,{rethrow:!0});if(!i)return e;var s=yield i.arrayBuffer();return E({},e,{Ji:{contentType:ad,body:s,estimatedSize:s.byteLength}})}));return function(e){return t.apply(this,arguments)}})(),lf=/Failed to fetch|NetworkError|Load failed/i,dd=t=>t?.name==="TypeError"&&lf.test(t?.message||""),hd=t=>{var e=ud(t);if(e){var n=e.url,i=e.encodedBody,s=i??{},r=s.contentType,o=s.body,a=s.estimatedSize,l=new Headers;Z(t.headers,(function(f,g){l.append(g,f)})),r&&l.append("Content-Type",r);var u=null,c=!1;if(Ka){var d=new Ka;u={signal:d.signal,timeout:setTimeout((()=>{var f,g;c=!0,d.abort((f=t.timeout,(g=new Error("PostHog request timed out"+(f?" after "+f+"ms":""))).name="AbortError",g))}),t.timeout)}}var h=f=>{c&&f?.name==="AbortError"||dd(f)?k.warn(f):k.error(f),t.callback==null||t.callback({statusCode:0,error:f})};try{var p;Ko(n,E({method:t?.method||"GET",headers:l,keepalive:t.method==="POST"&&!t.Yi&&52428.8>(a||0),body:o,signal:(p=u)==null?void 0:p.signal},t.fetchOptions)).then((f=>f.text().then((g=>{var m={statusCode:f.status,text:g};if(f.status===200)try{m.json=JSON.parse(g)}catch(v){k.error(v)}t.callback==null||t.callback(m)})))).catch(h).finally((()=>u?clearTimeout(u.timeout):null))}catch(f){u&&clearTimeout(u.timeout),h(f)}}},Eo=t=>{try{var e,n=cd(t),i=n.url,s=n.encodedBody,r=s??{},o=r.body,a=r.estimatedSize;if(!o)return;var l=o instanceof Blob?o:new Blob([o],{type:r.contentType});if(ke.sendBeacon(i,l))return;var u=O(t.data)?t.data:(e=t.data)==null?void 0:e.batch;if(O(u)&&u.length>1&&(a??0)>16384){var c=Math.ceil(u.length/2),d=h=>O(t.data)?h:E({},t.data,{batch:h});return Eo(E({},t,{data:d(u.slice(0,c))})),void Eo(E({},t,{data:d(u.slice(c))}))}k.warn("Beacon of ~"+(a??0)+" bytes was rejected by the browser, falling back to fetch"),hd(E({},t,{Yi:!0}))}catch(h){k.warn("Beacon send failed",h)}},Ml=(t,e,n,i)=>{var s=i==="query"?e==="POST"?"sent_at":"_":void 0;return js(n===xe.GZipJS?ld(t,"compression"):t,E({},s?{[s]:Date.now().toString()}:{},n===xe.GZipJS?{}:{compression:n}))},Gi=[];Ko&&Gi.push({transport:"fetch",method:hd}),Wr&&Gi.push({transport:"XHR",method(t){var e=ud(t);if(e){var n=new Wr,i=e.encodedBody;n.open(t.method||"GET",e.url,!0);var s=i??{},r=s.contentType,o=s.body;Z(t.headers,(function(a,l){n.setRequestHeader(l,a)})),r&&n.setRequestHeader("Content-Type",r),t.timeout&&(n.timeout=t.timeout),n.onreadystatechange=()=>{if(n.readyState===4){var a={statusCode:n.status,text:n.responseText};if(n.status===200)try{a.json=JSON.parse(n.responseText)}catch{}t.callback==null||t.callback(a)}},n.send(o)}}}),ke!=null&&ke.sendBeacon&&Gi.push({transport:"sendBeacon",method:Eo});var So=3e3;class cf{constructor(e,n){this.Xi=!0,this.tr=[],this.er=ot(n?.flush_interval_ms||So,250,5e3,k.createLogger("flush interval"),So),this.ir=e}enqueue(e){this.tr.push(e),this.rr||this.nr()}unload(){this.sr();var e=this.tr.length>0?this.ar():{},n=Object.values(e);[...n.filter((i=>i.url.indexOf("/e")===0)),...n.filter((i=>i.url.indexOf("/e")!==0))].map((i=>{this.lr(E({},i,{transport:"sendBeacon"}))}))}enable(){this.Xi=!1,this.nr()}nr(){var e=this;this.Xi||(this.rr=setTimeout((()=>{if(this.sr(),this.tr.length>0){var n=this.ar(),i=function(){var r=n[s],o=new Date().getTime();r.data&&O(r.data)&&Z(r.data,(a=>{a.offset=Math.abs(a.timestamp-o),delete a.timestamp})),e.lr(r)};for(var s in n)i()}}),this.er))}lr(e){try{this.ir(e)}catch(n){k.error(n)}}sr(){clearTimeout(this.rr),this.rr=void 0}ar(){var e={};return Z(this.tr,(n=>{var i,s=n,r=(s?s.batchKey:null)||s.url;x(e[r])&&(e[r]=E({},s,{data:[]})),(i=e[r].data)==null||i.push(s.data)})),this.tr=[],e}}var uf=["retriesPerformedSoFar"];class df{constructor(e){this.ur=!1,this.hr=3e3,this.tr=[],this._instance=e,this.tr=[],this.dr=!0,!x(_)&&"onLine"in _.navigator&&(this.dr=_.navigator.onLine,this.vr=()=>{this.dr=!0,this.cr()},this.pr=()=>{this.dr=!1},re(_,"online",this.vr),re(_,"offline",this.pr))}get length(){return this.tr.length}retriableRequest(e){var n=e.retriesPerformedSoFar,i=jc(e,uf);dt(n)&&(i.url=js(i.url,{retry_count:n})),this._instance._send_request(E({},i,{callback:s=>{if(s.statusCode!==200&&(400>s.statusCode||s.statusCode>=500)){if((s.statusCode===0?3:10)>(n??0))return void this.At(E({retriesPerformedSoFar:n},i));s.statusCode===0&&k.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.")}i.callback==null||i.callback(s)}}))}At(e){var n=e.retriesPerformedSoFar||0;e.retriesPerformedSoFar=n+1;var i=(function(o){var a=3e3*Math.pow(2,o),l=a/2,u=Math.min(18e5,a),c=Math.random()-.5;return Math.ceil(u+c*(u-l))})(n),s=Date.now()+i;this.tr.push({retryAt:s,requestOptions:e});var r="Enqueued failed request for retry in "+i;navigator.onLine||(r+=" (Browser is offline)"),k.warn(r),this.ur||(this.ur=!0,this.gr())}gr(){if(this.mr&&clearTimeout(this.mr),this.tr.length===0)return this.ur=!1,void(this.mr=void 0);this.mr=setTimeout((()=>{this.dr&&this.tr.length>0&&this.cr(),this.gr()}),this.hr)}cr(){var e=Date.now(),n=[],i=this.tr.filter((r=>e>r.retryAt||(n.push(r),!1)));if(this.tr=n,i.length>0)for(var s of i)this.retriableRequest(s.requestOptions)}unload(){for(var e of(this.mr&&(clearTimeout(this.mr),this.mr=void 0),this.ur=!1,x(_)||(this.vr&&(_.removeEventListener("online",this.vr),this.vr=void 0),this.pr&&(_.removeEventListener("offline",this.pr),this.pr=void 0)),this.tr)){var n=e.requestOptions;try{this._instance._send_request(E({},n,{transport:"sendBeacon"}))}catch(i){k.error(i)}}this.tr=[]}}class hf{constructor(e){this.yr=()=>{var n,i,s,r;this.br||(this.br={});var o=this.scrollElement(),a=this.scrollY(),l=o?Math.max(0,o.scrollHeight-o.clientHeight):0,u=a+(o?.clientHeight||0),c=o?.scrollHeight||0;this.br.lastScrollY=Math.ceil(a),this.br.maxScrollY=Math.max(a,(n=this.br.maxScrollY)!==null&&n!==void 0?n:0),this.br.maxScrollHeight=Math.max(l,(i=this.br.maxScrollHeight)!==null&&i!==void 0?i:0),this.br.lastContentY=u,this.br.maxContentY=Math.max(u,(s=this.br.maxContentY)!==null&&s!==void 0?s:0),this.br.maxContentHeight=Math.max(c,(r=this.br.maxContentHeight)!==null&&r!==void 0?r:0)},this._instance=e}get _r(){return this._instance.config.scroll_root_selector}getContext(){return this.br}resetContext(){var e=this.br;return setTimeout(this.yr,0),e}startMeasuringScrollPosition(){re(_,"scroll",this.yr,{capture:!0}),re(_,"scrollend",this.yr,{capture:!0}),re(_,"resize",this.yr)}scrollElement(){if(!this._r)return _?.document.documentElement;var e=O(this._r)?this._r:[this._r];for(var n of e){var i=_?.document.querySelector(n);if(i)return i}}wr(e){var n=e==="y"?"scrollTop":"scrollLeft";if(this._r){var i=this.scrollElement();return i&&i[n]||0}return _?e==="y"?_.scrollY||_.pageYOffset||_.document.documentElement.scrollTop||0:_.scrollX||_.pageXOffset||_.document.documentElement.scrollLeft||0:0}scrollY(){return this.wr("y")}scrollX(){return this.wr("x")}}var pf=t=>Xu(t?.config.mask_personal_data_properties,t?.config.custom_personal_data_properties,t?.config.disable_capture_url_hashes);class Ll{constructor(e,n,i,s){this.kr=r=>{var o=this.Sr();if(!o||o.sessionId!==r){var a={sessionId:r,props:this.Cr(this._instance)};this.Mr.register({[co]:a})}},this._instance=e,this.Tr=n,this.Mr=i,this.Cr=s||pf,this.Tr.onSessionId(this.kr)}Sr(){return this.Mr.props[co]}getSetOnceProps(){var e,n=(e=this.Sr())==null?void 0:e.props;return n?"r"in n?Qu(n,this._instance.config.disable_capture_url_hashes):{$referring_domain:n.referringDomain,$pathname:n.initialPathName,utm_source:n.utm_source,utm_campaign:n.utm_campaign,utm_medium:n.utm_medium,utm_content:n.utm_content,utm_term:n.utm_term}:{}}getSessionProps(){var e={};return Z(ra(this.getSetOnceProps()),((n,i)=>{i==="$current_url"&&(i="url"),e["$session_entry_"+Vr(i)]=n})),e}}class da{on(e,n){return this.Er[e]||(this.Er[e]=[]),this.Er[e].push(n),()=>{this.Er[e]=this.Er[e].filter((i=>i!==n))}}emit(e,n){for(var i of this.Er[e]||[])i(n);for(var s of this.Er["*"]||[])s(e,n)}constructor(){this.Er={}}}var Bn=ie("[SessionId]");class Ol{on(e,n){return this.Ir.on(e,n)}constructor(e,n,i){var s;if(this.Pr=null,this.Rr=[],this.Ar=void 0,this.Fr=!1,this.Ir=new da,this.Lr=(u,c)=>!(!dt(u)||!dt(c))&&Math.abs(u-c)>this.sessionTimeoutMs,!e.persistence)throw new Error("SessionIdManager requires a PostHogPersistence instance");if(e.config.cookieless_mode===gt)throw new Error('SessionIdManager cannot be used with cookieless_mode="always"');this.Ne=e.config,this.Mr=e.persistence,this.Or=void 0,this.Dr=void 0,this._sessionStartTimestamp=null,this._sessionActivityTimestamp=null,this.$r=n||ft,this.Nr=i||ft;var r=this.Ne.persistence_name||this.Ne.token;if(this._sessionTimeoutMs=1e3*ot(this.Ne.session_idle_timeout_seconds||1800,60,36e3,Bn.createLogger("session_idle_timeout_seconds"),1800),e.register({$configured_session_timeout_ms:this._sessionTimeoutMs}),this.qr(),this.jr="ph_"+r+"_window_id",this.Br="ph_"+r+"_primary_window_exists",this.Hr()){var o=ce.H(this.jr),a=ce.H(this.Br);o&&!a?this.Or=o:ce.q(this.jr),ce.F(this.Br,!0)}if((s=this.Ne.bootstrap)!=null&&s.sessionID)try{var l=(u=>{var c=this.Ne.bootstrap.sessionID.replace(/-/g,"");if(c.length!==32)throw new Error("Not a valid UUID");if(c[12]!=="7")throw new Error("Not a UUIDv7");return parseInt(c.substring(0,12),16)})();this.Ur(this.Ne.bootstrap.sessionID,new Date().getTime(),l)}catch(u){Bn.error("Invalid sessionID in bootstrap",u)}this.zr()}get sessionTimeoutMs(){return this._sessionTimeoutMs}onSessionId(e){return x(this.Rr)&&(this.Rr=[]),this.Rr.push(e),this.Dr&&e(this.Dr,this.Or),()=>{this.Rr=this.Rr.filter((n=>n!==e))}}Hr(){return this.Ne.persistence!=="memory"&&!this.Mr.xi&&ce.N()}Wr(e){e!==this.Or&&(this.Or=e,this.Hr()&&ce.F(this.jr,e))}Vr(){return this.Or?this.Or:this.Hr()?ce.H(this.jr):null}Zr(e){var n=this.Pr;return!$e(n)&&!$e(e)&&5e3>Math.abs(e-n)}Ur(e,n,i){var s=n!==this._sessionActivityTimestamp,r=!(e!==this.Dr||i!==this._sessionStartTimestamp);this._sessionStartTimestamp=i,this._sessionActivityTimestamp=n,this.Dr=e,r&&!s||r&&this.Zr(n)||(this.Pr=n,this.Mr.register({[hn]:[n,e,i]}))}Gr(){var e,n=(e=this.Ne)==null?void 0:e.persistence_save_debounce_ms;return dt(n)&&n>0}Qr(){this.Gr()?this.Mr.refreshKey(hn):(this.Mr.flush(),this.Mr.load())}Kr(){var e;if(!$e(this._sessionActivityTimestamp)&&this._sessionActivityTimestamp!==this.Pr){this.Qr();var n=this.Jr();n[1]===this.Dr&&n[2]===this._sessionStartTimestamp&&(this.Pr=this._sessionActivityTimestamp,this.Mr.register({[hn]:[this._sessionActivityTimestamp,(e=this.Dr)!==null&&e!==void 0?e:null,this._sessionStartTimestamp]}),this.Mr.flush())}}Yr(){var e=this.Jr()[0],n=dt(e)?e:0,i=dt(this._sessionActivityTimestamp)?this._sessionActivityTimestamp:0;return Math.max(n,i)}Xr(e){return this.Qr(),this.Lr(e,this.Yr())}Jr(){var e=this.Mr.props[hn];return O(e)&&e.length===2&&e.push(e[0]),e||[0,null,0]}resetSessionId(){this.Pr=null,clearTimeout(this.tn),this.tn=void 0,this.Ur(null,null,null)}destroy(){this.Fr=!0,this.Kr(),clearTimeout(this.tn),this.tn=void 0,this.Ar&&_&&(_.removeEventListener(fs,this.Ar,{capture:!1}),this.Ar=void 0),this.Rr=[]}zr(){this.Ar=()=>{this.Kr(),this.Hr()&&ce.q(this.Br)},re(_,fs,this.Ar,{capture:!1})}checkAndGetSessionAndWindowId(e,n){if(e===void 0&&(e=!1),n===void 0&&(n=null),this.Ne.cookieless_mode===gt)throw new Error('checkAndGetSessionAndWindowId should not be called with cookieless_mode="always"');var i=n||new Date().getTime(),s=this.Jr(),r=s[1],o=s[2],a=this.Yr(),l=this.Vr(),u=dt(o)&&Math.abs(i-o)>864e5,c=!1,d=!1,h=!r,p=r,f=!h&&!e&&this.Lr(i,a);if(f){(f=this.Xr(i))||Bn.info("cross-tab refresh kept the session alive",{sessionId:r});var g=this.Jr();r=g[1],o=g[2]}h||f||u?(r=this.$r(),l=this.Nr(),Bn.info("new session ID generated",{sessionId:r,windowId:l,changeReason:{noSessionId:h,activityTimeout:f,sessionPastMaximumLength:u}}),o=i,c=!0):(l||(l=this.Nr(),c=!0),(d=r!==p)&&(Bn.info("adopted cross-tab session id",{sessionId:r,windowId:l}),c=!0));var m=dt(a)&&e&&!u?a:i,v=dt(o)?o:new Date().getTime();this.Wr(l),this.Ur(r,m,v),e||this.qr();var b={noSessionId:h,activityTimeout:f,sessionPastMaximumLength:u,crossTabAdoption:d};return c&&this.Rr.forEach((w=>w(r,l,b))),{sessionId:r,windowId:l,sessionStartTimestamp:v,changeReason:c?b:void 0,lastActivityTimestamp:a}}qr(){this.Fr||(clearTimeout(this.tn),this.tn=setTimeout((()=>{if(!this.Fr)if(this.Xr(new Date().getTime())){var e=this.Dr;this.resetSessionId(),this.Ir.emit("forcedIdleReset",{idleSessionId:e})}else this.qr()}),1.1*this.sessionTimeoutMs))}}var pd=function(t,e){if(!t)return!1;var n=t.userAgent;if(n&&nl(n,e))return!0;try{var i=t?.userAgentData;if(i!=null&&i.brands&&i.brands.some((s=>nl(s?.brand,e))))return!0}catch{}return!!t.webdriver};function fd(){return(fd=X((function*(){var t=ke?.userAgentData;if(t!=null&&t.getHighEntropyValues)try{var e=yield t.getHighEntropyValues(["model"]),n=e?.model;return q(n)&&n.length>0?n:void 0}catch(i){return void k.info("Unable to resolve $device_model from userAgentData.getHighEntropyValues",i)}}))).apply(this,arguments)}var bs=function(t,e){if(!(function(n){try{new RegExp(n)}catch{return!1}return!0})(e))return!1;try{return new RegExp(e).test(t)}catch{return!1}};function Ar(t,e,n){return pn({distinct_id:t,userPropertiesToSet:e,userPropertiesToSetOnce:n})}var gd={exact:(t,e)=>e.some((n=>t.some((i=>n===i)))),is_not:(t,e)=>e.every((n=>t.every((i=>n!==i)))),regex:(t,e)=>e.some((n=>t.some((i=>bs(n,i))))),not_regex:(t,e)=>e.every((n=>t.every((i=>!bs(n,i))))),icontains:(t,e)=>e.map(Ri).some((n=>t.map(Ri).some((i=>n.includes(i))))),not_icontains:(t,e)=>e.map(Ri).every((n=>t.map(Ri).every((i=>!n.includes(i))))),gt:(t,e)=>e.some((n=>{var i=parseFloat(n);return!isNaN(i)&&t.some((s=>i>parseFloat(s)))})),lt:(t,e)=>e.some((n=>{var i=parseFloat(n);return!isNaN(i)&&t.some((s=>it.toLowerCase();function md(t,e){return!t||Object.entries(t).every((n=>{var i=n[1],s=e?.[n[0]];if(x(s)||$e(s))return!1;var r=[String(s)],o=gd[i.operator];return!!o&&o(i.values,r)}))}var xo="custom",Bl="i.posthog.com",ff=/^\/static\//;class gf{constructor(e){this.en={},this.instance=e}get apiHost(){var e=this.instance.config.api_host.trim().replace(/\/$/,"");return e==="https://app.posthog.com"?"https://us.i.posthog.com":e}get flagsApiHost(){var e=this.instance.config.flags_api_host;return e?e.trim().replace(/\/$/,""):this.apiHost}get uiHost(){var e,n=(e=this.instance.config.ui_host)==null?void 0:e.replace(/\/$/,"");return n||(n=this.apiHost.replace("."+Bl,".posthog.com")),n==="https://app.posthog.com"?"https://us.posthog.com":n}get region(){return this.en[this.apiHost]||(this.en[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":xo),this.en[this.apiHost]}rn(e){if(ff.test(e)){var n=this.instance.config.asset_host;if(typeof n=="string")return n.trim().replace(/\/$/,"")||void 0}}endpointFor(e,n){if(n===void 0&&(n=""),n&&(n=n[0]==="/"?n:"/"+n),e==="ui")return this.uiHost+n;if(e==="flags")return this.flagsApiHost+n;if(e==="assets"){var i=this.rn(n);if(i)return""+i+n}if(this.region===xo)return this.apiHost+n;var s=Bl+n;switch(e){case"assets":return"https://"+this.region+"-assets."+s;case"api":return"https://"+this.region+"."+s}}}function vd(t){var e;return!((e=t.conditions)==null||(e=e.events)==null||(e=e.values)==null||!e.length)}var G=ie("[Surveys]"),_d="seenSurvey_",yd=t=>{try{var e=(n=>((i,s)=>""+_d+(function(r){return r.current_iteration&&r.current_iteration>0?r.id+"_"+r.current_iteration:r.id})(s))(0,n))(t);if(localStorage.getItem(e))return;localStorage.setItem(e,"true")}catch(n){G.error("Failed to persist survey seen state",n)}},mf=[Sr.Popover,Sr.Widget,Sr.API],vf={ignoreConditions:!1,ignoreDelay:!1,displayType:_o.Popover},_f=ie("[PostHog ExternalIntegrations]"),yf={intercom:"intercom-integration",crispChat:"crisp-chat-integration"};class wf{constructor(e){this._instance=e}ai(e,n){var i;(i=R.__PosthogExtensions__)==null||i.loadExternalDependency==null||i.loadExternalDependency(this._instance,e,(s=>{if(s)return _f.error("failed to load script",s);n()}))}startIfEnabledOrStop(){var e=this,n=function(){var r,o,a,l=i[0],u=i[1];!u||(r=R.__PosthogExtensions__)!=null&&(r=r.integrations)!=null&&r[l]||e.ai(yf[l],(()=>{var c;(c=R.__PosthogExtensions__)==null||(c=c.integrations)==null||(c=c[l])==null||c.start(e._instance)})),!u&&(o=R.__PosthogExtensions__)!=null&&(o=o.integrations)!=null&&o[l]&&((a=R.__PosthogExtensions__)==null||(a=a.integrations)==null||(a=a[l])==null||a.stop())};for(var i of Object.entries((s=this._instance.config.integrations)!==null&&s!==void 0?s:{})){var s;n()}}}class bf{constructor(e,n){this.rt=e,this.nn=n,this.sn=new Map,this.an=!1}add(e){var n=this;return X((function*(){if(n.an)throw new Error("Cannot add an extension to a disposed ExtensionRuntime");if(n.sn.has(e.name))throw new Error('Browser extension "'+e.name+'" is already registered');n.sn.set(e.name,e);try{var i=e.setup(n.nn);i&&(yield i)}catch(r){var s=n.sn.get(e.name)===e;s&&n.sn.delete(e.name),n.rt.error('Failed to set up browser extension "'+e.name+'"',r),s&&n.ln(e)}}))()}dispose(){if(!this.an){this.an=!0;var e=Array.from(this.sn.values()).reverse();for(var n of(this.sn.clear(),e))this.ln(n)}}ln(e){try{var n=e.dispose==null?void 0:e.dispose();n&&Se(n.then)&&n.then(void 0,(i=>{this.rt.error('Failed to dispose browser extension "'+e.name+'"',i)}))}catch(i){this.rt.error('Failed to dispose browser extension "'+e.name+'"',i)}}}class Ef{constructor(e){this._instance=e}initialize(){}get(e){var n=this._instance.persistence;if(typeof e=="string")return n?.get_property(e);var i={};for(var s of e){var r=n?.get_property(s);x(r)||(i[s]=r)}return i}set(e,n){var i;(i=this._instance.persistence)==null||i.register(typeof e=="string"?{[e]:n}:e)}remove(e){var n;(n=this._instance.persistence)==null||n.unregister(e)}}var Dl="extensionsRemoteConfig";class Sf{constructor(e){this.an=!1,this.instance=e,this.rt=k,this.un=e.hn,this.kv=new Ef(e),this.onEvent=n=>Ti(this.instance.on("eventCaptured",(i=>{try{n({event:i.event,properties:i.properties})}catch(s){this.rt.error("Browser extension event listener failed",s)}}))),this.onRemoteConfig=n=>{if(this.an)return Ti((()=>{}));var i=r=>{try{n(r)}catch(o){this.rt.error("Browser extension remote config listener failed",o)}},s=this.instance.dn.on(Dl,i);return this.un&&i(this.un),Ti(s)},this.vn=new bf(k.createLogger("[BrowserExtensions]"),this)}get logger(){return this.rt}get distinctId(){return this.instance.get_distinct_id()}get anonymousId(){var e;return(e=this.instance.get_property(ai))!==null&&e!==void 0?e:this.distinctId}get deviceId(){var e=this.instance.get_property(ai);return typeof e=="string"?e:void 0}get library(){return{name:Y.LIB_NAME,version:Y.LIB_VERSION}}get initialPersonProperties(){var e,n;return(e=(n=this.instance.persistence)==null?void 0:n.get_initial_props())!==null&&e!==void 0?e:{}}get groups(){return this.instance.getGroups()}get session(){try{var e,n,i,s,r=(e=this.instance.sessionManager)==null?void 0:e.checkAndGetSessionAndWindowId(!0);return{sessionId:(n=r?.sessionId)!==null&&n!==void 0?n:"",windowId:(i=r?.windowId)!==null&&i!==void 0?i:"",sessionStartTimestamp:(s=r?.sessionStartTimestamp)!==null&&s!==void 0?s:0}}catch{return{sessionId:"",windowId:"",sessionStartTimestamp:0}}}get projectToken(){return this.instance.config.token}add(e){return this.vn.add(e)}capture(e,n,i){var s=this;return X((function*(){i?s.instance.capture(e,n,{timestamp:i.timestamp,uuid:i.uuid,$set:i.set,$set_once:i.setOnce}):s.instance.capture(e,n)}))()}registerDynamicEventProperties(e){return Ti(this.instance.cn(e))}handleRemoteConfig(e){this.an||(this.un=e,this.instance.dn.emit(Dl,e))}sendRequest(e,n){var i=this;return X((function*(){var s;n===void 0&&(n={});var r=i.instance.requestRouter.endpointFor((s=n.target)!==null&&s!==void 0?s:"api",e),o={method:n.method,url:n.query?js(r,n.query):r,data:n.body,headers:n.headers,timeout:n.timeoutMs,fireCallbackOnDrop:!0,transport:n.transport,compression:n.compression,timestampMode:n.sentAt};return n.transport==="sendBeacon"?(i.instance._send_request(o),{statusCode:202}):new Promise((a=>{o.callback=a,i.instance._send_request(o)}))}))()}dispose(){this.an||(this.an=!0,this.vn.dispose())}}var ti={},Fr=0,Es=()=>{},jl='Consent opt in/out is not valid with cookieless_mode="always" and will be ignored',Dn="Surveys module not available",Ul="sanitize_properties is deprecated. Use before_send instead",wd="Invalid value for property_denylist config: ",xf=["token","distinct_id",Cu],un="posthog",bd=!of&&Fe?.indexOf("MSIE")===-1&&Fe?.indexOf("Mozilla")===-1,Pr=t=>{var e;return E({api_host:"https://us.i.posthog.com",flags_api_host:null,ui_host:null,asset_host:null,token:"",autocapture:!0,cross_subdomain_cookie:xp(C?.location),persistence:"localStorage+cookie",persistence_name:"",cookie_persisted_properties:[],loaded:Es,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_external_dependency_versioned_paths:!1,__preview_cookie_wins_on_conflict:!1,debug:se&&q(se?.search)&&se.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,disable_external_dependency_loading:!1,strict_script_versioning:!1,enable_recording_console_log:void 0,secure_cookie:(_==null||(e=_.location)==null?void 0:e.protocol)==="https:",ip:!1,opt_out_capturing_by_default:!1,opt_out_persistence_by_default:!1,opt_out_useragent_filter:!1,opt_out_capturing_persistence_type:"localStorage",consent_persistence_name:null,opt_out_capturing_cookie_prefix:null,opt_in_site_apps:!1,property_denylist:[],respect_dnt:!1,sanitize_properties:null,request_headers:{},request_batching:!0,properties_string_max_length:65535,mask_all_element_attributes:!1,mask_all_text:!1,mask_personal_data_properties:!1,custom_personal_data_properties:[],advanced_disable_flags:!1,advanced_disable_decide:!1,advanced_disable_feature_flags:!1,advanced_disable_feature_flags_on_first_load:!1,advanced_only_evaluate_survey_feature_flags:!1,advanced_feature_flags_dedup_per_session:!1,advanced_enable_surveys:!1,advanced_disable_toolbar_metrics:!1,feature_flag_request_timeout_ms:3e3,surveys_request_timeout_ms:1e4,on_request_error(n){k.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:fo,before_send:void 0,get_current_url:void 0,request_queue_config:{flush_interval_ms:So},error_tracking:{},_onCapture:Es},(n=>({rageclick:n&&n>="2026-05-30"?{content_ignorelist:Lp,ignore_text_selection:!0}:!n||"2025-11-30">n||{content_ignorelist:!0},capture_pageview:!n||"2025-05-24">n||"history_change",session_recording:n&&n>="2026-06-25"?{strictMinimumDuration:!0,canvasCapture:{resolutionScale:.6},streamNetworkBody:!0}:n&&n>="2026-05-30"?{strictMinimumDuration:!0,canvasCapture:{resolutionScale:.6}}:n&&n>="2025-11-30"?{strictMinimumDuration:!0}:{},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)}))(t))},kf=[["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"]],Hl=t=>{var e={};for(var n of kf){var i=n[0],s=n[1];x(t[i])||(e[s]=t[i])}var r=te({},e,t),o=t.__preview_external_dependency_versioned_paths;return x(o)||(x(t.strict_script_versioning)&&(r.strict_script_versioning=!!o),q(o)&&x(t.asset_host)&&(r.asset_host=o)),O(t.property_blacklist)&&(x(t.property_denylist)?r.property_denylist=t.property_blacklist:O(t.property_denylist)?r.property_denylist=[...t.property_blacklist,...t.property_denylist]:k.error(wd+t.property_denylist)),r};class If{constructor(){this.__forceAllowLocalhost=!1}get fn(){return this.__forceAllowLocalhost}set fn(e){k.error("WebPerformanceObserver is deprecated and has no impact on network capture. Use `_forceAllowLocalhostNetworkCapture` on `posthog.sessionRecording`"),this.__forceAllowLocalhost=e}}class Re{pn(e,n){if(e){var i=this.sn.indexOf(e);i!==-1&&this.sn.splice(i,1)}return this.sn.push(n),n.initialize==null||n.initialize(),n}gn(){return this.config.cookieless_mode===gt||this.config.cookieless_mode===Vt&&this.consent.isRejected()}get decideEndpointWasHit(){var e,n;return(e=(n=this.featureFlags)==null?void 0:n.hasLoadedFlags)!==null&&e!==void 0&&e}get flagsEndpointWasHit(){var e,n;return(e=(n=this.featureFlags)==null?void 0:n.hasLoadedFlags)!==null&&e!==void 0&&e}constructor(){var e;this.webPerformance=new If,this.mn=!1,this.version=Y.LIB_VERSION,this.yn=new Set,this.bn="",this.dn=new da,this.sn=[],this._n=[],this._calculate_event_properties=this.calculateEventProperties.bind(this),this.config=Pr(),this.SentryIntegration=zp,this.sentryIntegration=i=>(function(s,r){var o=qu(s,r);return{name:zu,processEvent:a=>o(a)}})(this,i),this.__request_queue=[],this.__loaded=!1,this.analyticsDefaultEndpoint="/e/",this.wn=!1,this.kn=null,this.xn=null,this.Sn=null,this.scrollManager=new hf(this),this.pageViewManager=new Cl(this),this.rateLimiter=new Qp(this),this.requestRouter=new gf(this),this.consent=new $p(this),this.externalIntegrations=new wf(this);var n=(e=Re.__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:(i,s,r)=>{var o=q(i)?{[i]:s}:i;this.setPersonProperties(o),r?.({})},set_once:(i,s,r)=>{var o=q(i)?{[i]:s}:i;this.setPersonProperties(void 0,o),r?.({})}},this.on("eventCaptured",(i=>k.info('send "'+i?.event+'"',i)))}init(e,n,i){if(i&&i!==un){var s,r=(s=ti[i])!==null&&s!==void 0?s:new Re;return r._init(e,n,i),ti[i]=r,ti[un][i]=r,r}return this._init(e,n,i)}_init(e,n,i){var s,r;n===void 0&&(n={});var o,a=q(e)?e.trim():"";if(!a)return k.critical("PostHog was initialized without a token. This likely indicates a misconfiguration. Please check the first argument passed to posthog.init()"),this;if(this.__loaded)return a!==((o=this.config)==null?void 0:o.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('"+a+"', { ... }, 'project2')"):console.warn("[PostHog.js]","You have already initialized PostHog! Re-initializing is a no-op"),this;this.__loaded=!0,this.config=Pr(n.defaults),n.debug=this.Cn(n.debug),this.Mn=n,this.Tn=[],n.person_profiles?this.xn=n.person_profiles:n.process_person&&(this.xn=n.process_person);var l=Pr(n.defaults),u=Hl(n),c=te({},l,u,{name:i,token:a});ne(l.rageclick)&&ne(u.rageclick)&&(c.rageclick=te({},l.rageclick,u.rageclick)),ne(l.session_recording)&&ne(u.session_recording)&&(c.session_recording=te({},l.session_recording,u.session_recording)),this.set_config(c),this.config.on_xhr_error&&k.error("on_xhr_error is deprecated. Use on_request_error instead"),this.compression=n.disable_compression?void 0:xe.GZipJS;var d=this.En();if(this.persistence=new Er(this.config,d),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new Er(E({},this.config,{persistence:"sessionStorage"}),d,!1),this.bn="ph_"+(this.config.persistence_name||this.config.token)+"_session_registered_properties",this.config.persistence!=="memory"&&!d&&ce.N()){var h=ce.H(this.bn);O(h)&&h.forEach((F=>{q(F)&&this.yn.add(F)}))}else ce.q(this.bn);var p=E({},this.persistence.props),f=E({},this.sessionPersistence.props);this.register({$initialization_time:new Date().toISOString()}),this.In=new cf((F=>this.Pn(F)),this.config.request_queue_config),this.Rn=new df(this),this.__request_queue=[];var g=this.gn();if(g||(this.sessionManager=new Ol(this),this.sessionPropsManager=new Ll(this,this.sessionManager,this.persistence),this.sessionManager.onSessionId(((F,D,S)=>{(S!=null&&S.activityTimeout||S!=null&&S.sessionPastMaximumLength||S!=null&&S.crossTabAdoption)&&this.An()}))),this.Fn(),this.config.__preview_deferred_init_extensions?(k.info("Deferring extension initialization to improve startup performance"),setTimeout((()=>{this.Ln(g)}),0)):(k.info("Initializing extensions synchronously"),this.Ln(g)),Y.DEBUG=Y.DEBUG||this.config.debug,Y.DEBUG&&k.info("Starting in debug mode",{this:this,config:n,thisC:E({},this.config),p,s:f}),!this.config.identity_distinct_id||(s=n.bootstrap)!=null&&s.distinctID||(n.bootstrap=E({},n.bootstrap,{distinctID:this.config.identity_distinct_id,isIdentifiedID:!0})),((r=n.bootstrap)==null?void 0:r.distinctID)!==void 0){var m=n.bootstrap.distinctID,v=this.get_distinct_id(),b=this.persistence.get_property(He);if(n.bootstrap.isIdentifiedID&&v!=null&&v!==m&&b===sn)this.identify(m);else if(n.bootstrap.isIdentifiedID&&v!=null&&v!==m&&b===Ot)k.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{var w=this.config.get_device_id(ft()),I=n.bootstrap.isIdentifiedID?w:m;this.persistence.set_property(He,n.bootstrap.isIdentifiedID?Ot:sn),this.register({distinct_id:m,$device_id:I})}}if(g)this.register_once({distinct_id:Ci,$device_id:null},"");else if(!this.get_distinct_id()){var A=this.config.get_device_id(ft());this.register_once({distinct_id:A,$device_id:A},""),this.persistence.set_property(He,sn)}return re(_,"onpagehide"in self?"pagehide":"unload",this._handle_unload.bind(this),{passive:!1}),n.segment?(function(F,D){var S=F.config.segment;if(!S)return D();(function($,T){var M=$.config.segment;if(!M)return T();var N=z=>{var H=()=>z.anonymousId()||ft();$.config.get_device_id=H,z.id()&&($.register({distinct_id:z.id(),$device_id:H()}),$.persistence.set_property(He,Ot)),T()},P=M.user();"then"in P&&Se(P.then)?P.then(N):N(P)})(F,(()=>{S.register(($=>{typeof Promise<"u"&&Promise.resolve||wr.warn("This browser does not have Promise support, and can not use the segment integration");var T=(M,N)=>{if(!N)return M;M.event.userId||M.event.anonymousId===$.get_distinct_id()||(wr.info("No userId set, resetting PostHog"),$.reset()),M.event.userId&&M.event.userId!==$.get_distinct_id()&&(wr.info("UserId set, identifying with PostHog"),$.identify(M.event.userId));var P=$.calculateEventProperties(N,M.event.properties);return M.event.properties=Object.assign({},P,M.event.properties),M};return{name:"PostHog JS",type:"enrichment",version:"1.0.0",isLoaded:()=>!0,load:()=>Promise.resolve(),track:M=>T(M,M.event.event),page:M=>T(M,cn),identify:M=>T(M,vr),screen:M=>T(M,"$screen")}})(F)).then((()=>{D()}))}))})(this,(()=>this.On())):this.On(),Se(this.config._onCapture)&&this.config._onCapture!==Es&&(k.warn("onCapture is deprecated. Please use `before_send` instead"),this.on("eventCaptured",(F=>this.config._onCapture(F.event,F)))),this.config.ip&&k.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 fd.apply(this,arguments)})().then((F=>{F&&this.register({[gr]:F})})).catch(Es),this}Fn(){var e,n,i,s,r,o,a=(e=(n=this.config.__extensionClasses)==null?void 0:n.featureFlags)!==null&&e!==void 0?e:(i=Re.__defaultExtensionClasses)==null?void 0:i.featureFlags;a&&(this.featureFlags&&this.featureFlags instanceof a||((s=this.Dn)==null||s.call(this),this.Dn=void 0,this.featureFlags=new a(this)),Se(this.featureFlags.onReloading)&&Se(this.featureFlags.setup)?this.Dn||(this.Dn=this.featureFlags.onReloading((()=>{this.dn.emit("featureFlagsReloading",!0)})),this.$n().add(this.featureFlags)):(r=(o=this.featureFlags).initialize)==null||r.call(o))}Ln(e){var n,i,s,r,o,a,l,u=performance.now(),c=E({},Re.__defaultExtensionClasses,this.config.__extensionClasses),d=[];c.exceptions&&this.sn.push(this.exceptions=(n=this.exceptions)!==null&&n!==void 0?n:new c.exceptions(this)),c.historyAutocapture&&this.sn.push(this.historyAutocapture=new c.historyAutocapture(this)),c.tracingHeaders&&this.sn.push(this.tracingHeaders=new c.tracingHeaders(this)),c.siteApps&&this.sn.push(this.siteApps=new c.siteApps(this)),c.sessionRecording&&!e&&this.sn.push(this.sessionRecording=new c.sessionRecording(this)),this.config.disable_scroll_properties||d.push((()=>{this.scrollManager.startMeasuringScrollPosition()})),c.autocapture&&this.sn.push(this.autocapture=new c.autocapture(this)),c.surveys&&this.sn.push(this.surveys=(i=this.surveys)!==null&&i!==void 0?i:new c.surveys(this)),c.logs&&this.sn.push(this.logs=(s=this.logs)!==null&&s!==void 0?s:new c.logs(this)),c.metrics&&this.sn.push(this.metrics=(r=this.metrics)!==null&&r!==void 0?r:new c.metrics(this)),c.conversations&&this.sn.push(this.conversations=(o=this.conversations)!==null&&o!==void 0?o:new c.conversations(this)),c.productTours&&this.sn.push(this.productTours=new c.productTours(this)),c.heatmaps&&this.sn.push(this.heatmaps=new c.heatmaps(this)),c.webVitalsAutocapture&&this.sn.push(this.webVitalsAutocapture=new c.webVitalsAutocapture(this)),c.exceptionObserver&&this.sn.push(this.exceptionObserver=new c.exceptionObserver(this)),c.deadClicksAutocapture&&this.sn.push(this.deadClicksAutocapture=new c.deadClicksAutocapture(this,Wp)),c.toolbar&&this.sn.push(this.toolbar=(a=this.toolbar)!==null&&a!==void 0?a:new c.toolbar(this)),c.experiments&&this.sn.push(this.experiments=(l=this.experiments)!==null&&l!==void 0?l:new c.experiments(this)),this.sn.forEach((h=>{h.initialize&&d.push((()=>{h.initialize==null||h.initialize()}))})),d.push((()=>{if(this.Nn){var h=this.Nn;this.Nn=void 0,this.sn.forEach((p=>p.onRemoteConfig==null?void 0:p.onRemoteConfig(h)))}})),this.qn(d,u)}qn(e,n){for(;e.length>0;){if(this.config.__preview_deferred_init_extensions&&performance.now()-n>=30&&e.length>0)return void setTimeout((()=>{this.qn(e,n)}),0);var i=e.shift();if(i)try{i()}catch(r){k.error("Error initializing extension:",r)}}var s=Math.round(performance.now()-n);this.register_for_session({[Au]:this.config.__preview_deferred_init_extensions?"deferred":"synchronous",[Fu]:s}),this.config.__preview_deferred_init_extensions&&k.info("PostHog extensions initialized ("+s+"ms)")}Zi(e){var n;if(!C||!C.body)return k.info("document not ready yet, trying again in 500 milliseconds..."),void setTimeout((()=>{this.Zi(e)}),500);if(this.config.__preview_deferred_init_extensions&&(this.Nn=e),this.hn=e,this.compression=void 0,e.ok){var i,s=e.config;s.supportedCompression&&!this.config.disable_compression&&(this.compression=L(s.supportedCompression,xe.GZipJS)?xe.GZipJS:L(s.supportedCompression,xe.Base64)?xe.Base64:void 0),(i=s.analytics)!=null&&i.endpoint&&(this.analyticsDefaultEndpoint=s.analytics.endpoint)}this.set_config({person_profiles:this.xn?this.xn:fo}),(n=this.jn)==null||n.handleRemoteConfig(e),this.sn.forEach((r=>r.onRemoteConfig==null?void 0:r.onRemoteConfig(e)))}On(){try{this.config.loaded(this)}catch(i){k.critical("`loaded` function failed",i)}if(this.Bn(),this.config.internal_or_test_user_hostname&&se!=null&&se.hostname){var e=se.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.gn())&&this.Hn()}),1),this.Un=new td(this),this.Un.load()}Bn(){var e;this.is_capturing()&&this.config.request_batching&&((e=this.In)==null||e.enable())}_dom_loaded(){this.is_capturing()&&Ai(this.__request_queue,(e=>this.Pn(e))),this.__request_queue=[],this.Bn()}_handle_unload(){var e,n,i,s,r;(e=this.surveys)==null||e.handlePageUnload==null||e.handlePageUnload(),(n=this.metrics)==null||n.flush("sendBeacon"),this.config.request_batching?(this.zn()&&this.capture(mr),(i=this.logs)==null||i.flushLogs("sendBeacon"),(s=this.In)==null||s.unload(),(r=this.Rn)==null||r.unload()):this.zn()&&this.capture(mr,null,{transport:"sendBeacon"})}_send_request(e){this.__loaded?bd?this.__request_queue.push(e):this.rateLimiter.isServerRateLimited(e.batchKey)?e.fireCallbackOnDrop&&(e.callback==null||e.callback({statusCode:429})):(e.transport=e.transport||this.config.api_transport,e.headers=E({},this.config.request_headers,e.headers),e.compression=e.compression==="best-available"?this.compression:e.compression,(x(this.config.disable_beacon)?this.config.__preview_disable_beacon:this.config.disable_beacon)&&(e.disableTransport=["sendBeacon"]),e.fetchOptions=e.fetchOptions||this.config.fetch_options,(n=>{var i,s,r,o=E({},n);o.timeout=o.timeout||6e4;var a,l,u,c,d,h=(i=o.transport)!==null&&i!==void 0?i:"fetch";h==="sendBeacon"&&x(o.compression)&&o.data&&(o.compression=xe.Base64),o.method==="POST"&&o.data&&(o.timestampMode==="capture-body"?o.data={api_key:(l=(d=(c=O(a=o.data)?a:[a])[0])==null||(u=d.properties)==null?void 0:u.token)!==null&&l!==void 0?l:d?.token,batch:c,sent_at:new Date().toISOString()}:o.timestampMode==="body"&&(o.data=(function(m,v){return v===void 0&&(v=new Date().toISOString()),O(m)?m.map((b=>E({},b,{sent_at:v}))):E({},m,{sent_at:v})})(o.data))),o.url=Ml(o.url,o.method,o.compression,o.timestampMode);var p=Gi.filter((m=>!o.disableTransport||!m.transport||!o.disableTransport.includes(m.transport))),f=(s=(r=(function(m,v){for(var b=0;m.length>b;b++)if(m[b].transport===h)return m[b]})(p))==null?void 0:r.method)!==null&&s!==void 0?s:p[0].method;if(!f)throw new Error("No available transport method");var g=m=>{try{f(m)}catch(v){dd(v)?k.warn(v):k.error(v),o.callback==null||o.callback({statusCode:0,error:v})}};h!=="sendBeacon"&&o.data&&o.compression===xe.GZipJS&&Ih&&typeof Promise<"u"&&!Vi?af(o).then((m=>{g(m)})).catch((m=>{if(tl(m))return Vi=!0,void g(E({},o,{compression:void 0,url:Ml(n.url,n.method,void 0,n.timestampMode)}));(v=>{if(!v||typeof v!="object")return!1;var b="name"in v?String(v.name):"";return tl(v)||b===Uc})(m)&&(Vi=!0),g(o)})):f(o)})(E({},e,{callback:n=>{var i,s;this.rateLimiter.checkForLimiting(n),400>n.statusCode||(i=(s=this.config).on_request_error)==null||i.call(s,n),e.callback==null||e.callback(n)}}))):e.fireCallbackOnDrop&&(e.callback==null||e.callback({statusCode:0}))}Pn(e){this.Rn?this.Rn.retriableRequest(e):this._send_request(e)}_execute_array(e){Fr++;try{var n,i=[],s=[],r=[];Ai(e,(a=>{if(a)if(O(n=a[0]))r.push(a);else if(Se(a))try{a.call(this)}catch(l){k.error("Error executing queued PostHog call",a,l)}else O(a)&&n==="alias"?i.push(a):O(a)&&n.indexOf("capture")!==-1&&Se(this[n])?r.push(a):s.push(a)}));var o=function(a,l){Ai(a,(function(u){try{if(O(u[0])){var c=l;Z(u,(function(d){c=c[d[0]].apply(c,d.slice(1))}))}else l[u[0]].apply(l,u.slice(1))}catch(d){k.error("Error executing queued PostHog call",u,d)}}))};o(i,this),o(s,this),o(r,this)}finally{Fr--}}push(e){if(Fr>0&&O(e)&&q(e[0])){var n=Re.prototype[e[0]];Se(n)&&n.apply(this,e.slice(1))}else this._execute_array([e])}capture(e,n,i){var s,r,o,a,l;if(this.__loaded&&this.persistence&&this.sessionPersistence&&this.In){if(this.is_capturing())if(!x(e)&&q(e)){var u=!this.config.opt_out_useragent_filter&&this._is_bot();if(!u||this.config.__preview_capture_bot_pageviews){var c=i!=null&&i.skip_client_rate_limiting?void 0:this.rateLimiter.clientRateLimitContext();if(c==null||!c.isRateLimited){n!=null&&n.$current_url&&!q(n?.$current_url)&&(k.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"||i!=null&&i.Wn||k.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&&this.sessionPersistence.update_campaign_params(),this.config.save_referrer&&this.sessionPersistence.update_referrer_info(),(this.config.save_campaign_params||this.config.save_referrer)&&this.persistence.set_initial_person_info();var d=new Date,h=i?.timestamp||d,p=ol(i?.uuid,ft),f={uuid:p,event:e,properties:this.calculateEventProperties(e,n||{},h,p)};e===cn&&this.config.__preview_capture_bot_pageviews&&u&&(f.event="$bot_pageview",f.properties.$browser_type="bot"),c&&(f.properties.$lib_rate_limit_remaining_tokens=c.remainingTokens);var g=e==="$feature_flag_called"&&f.properties.$feature_flag_has_experiment===!1&&this.get_property(cs)===!0;i?.$set&&!g&&(f.$set=i?.$set);var m=i?.$unset;m&&(f.$unset=m);var v,b,w,I=g?void 0:this.Vn(i?.$set_once,e!==hl,e===vr);if(I&&(f.$set_once=I),i!=null&&i._noTruncate||(r=this.config.properties_string_max_length,o=f,a=N=>q(N)?N.slice(0,r):N,l=new Set,f=(function N(P,z){if(P!==Object(P))return a?a(P):P;if(!l.has(P)){var H;if(l.add(P),O(P))H=[],Ai(P,(Q=>{H.push(N(Q))}));else{var U={};Z(P,((Q,fe)=>{l.has(Q)||(U[fe]=N(Q))})),H=U}return H}})(o)),f.timestamp=h,x(i?.timestamp)||(f.properties.$event_time_override_provided=!0,f.properties.$event_time_override_system_time=d),g&&(f.properties=(function(N,P){P===void 0&&(P=[]);var z={},H=U=>{N[U]!==void 0&&(z[U]=N[U])};return Ch.forEach(H),P.forEach(H),z})(f.properties,xf)),e===vt.DISMISSED||e===vt.SENT){var A=n?.[xr.SURVEY_ID],F=n?.[xr.SURVEY_ITERATION];yd({id:A,current_iteration:F}),f.$set=E({},f.$set,{[(v={id:A,current_iteration:F},b=e===vt.SENT?"responded":"dismissed",w="$survey_"+b+"/"+v.id,v.current_iteration&&v.current_iteration>0&&(w="$survey_"+b+"/"+v.id+"/"+v.current_iteration),w)]:!0})}else e===vt.SHOWN&&(f.$set=E({},f.$set,{[xr.SURVEY_LAST_SEEN_DATE]:new Date().toISOString()}));if(e===Xp.SHOWN){var D=n?.[Fl.TOUR_TYPE];D&&(f.$set=E({},f.$set,{[Fl.TOUR_LAST_SEEN_DATE+"/"+D]:new Date().toISOString()}))}var S=E({},f.properties.$set,f.$set);if(yt(S)||this.setPersonPropertiesForFlags(S),!B(this.config.before_send)){var $=this.Pt(f);if(!$)return;(f=$).uuid=ol(f.uuid,ft)}this.dn.emit("eventCaptured",f);var T=(s=i?._url)!==null&&s!==void 0?s:this.requestRouter.endpointFor("api",this.analyticsDefaultEndpoint),M={method:"POST",url:T,data:f,compression:"best-available",timestampMode:i?._batchKey==="recordings"||/\/s\/(?:\?|$)/.test(T)?"body":"capture-body",batchKey:i?._batchKey,transport:i?.transport};return!this.config.request_batching||i&&(i==null||!i._batchKey)||i!=null&&i.send_instantly?this.Pn(M):this.In.enqueue(M),f}k.critical("This capture call is ignored due to client rate limiting.")}}else k.error("No event name provided to posthog.capture")}else k.uninitializedWarning("posthog.capture")}_addCaptureHook(e){return this.on("eventCaptured",(n=>e(n.event,n)))}$n(){var e;return(e=this.jn)!==null&&e!==void 0?e:this.jn=new Sf(this)}cn(e){this._n.push(e);var n=!0;return()=>{if(n){n=!1;var i=this._n.indexOf(e);i!==-1&&this._n.splice(i,1)}}}calculateEventProperties(e,n,i,s,r){if(i=i||new Date,!this.persistence||!this.sessionPersistence)return n;var o=r?void 0:this.persistence.remove_event_timer(e),a=E({},n);if(a.token=this.config.token,a.$config_defaults=this.config.defaults,this.gn()&&(a[Cu]=!0),e==="$snapshot"){var l=E({},this.persistence.properties(),this.sessionPersistence.properties());return a.distinct_id=l.distinct_id,(!q(a.distinct_id)&&!he(a.distinct_id)||Gr(a.distinct_id))&&k.error("Invalid distinct_id for replay event. This indicates a bug in your implementation"),a}var u,c=(function(A,F,D,S){var $,T,M,N;if(S===void 0&&(S=!1),!Fe)return{};var P,z=A?[...bn,...F||[]]:[],H=(function(Si){for(var je=0;sl.length>je;je++){var xi=sl[je],tn=xi[1],nn=xi[0].exec(Si),$n=nn&&(Se(tn)?tn(nn,Si):tn);if($n)return $n}return["",""]})(Fe),U=H[0],Q=H[1],fe=(P=typeof navigator<"u"?navigator:void 0)!=null&&P.brave?{brave:!0}:{},Ie={};x(D)||(Ie.detectGoogleSearchApp=D);var _e={},Ce=($=navigator)==null||($=$.userAgentData)==null?void 0:$.platform,Te=(T=navigator)==null?void 0:T.maxTouchPoints,ae=_==null||(M=_.screen)==null?void 0:M.width,me=_==null||(N=_.screen)==null?void 0:N.height,ge=_?.devicePixelRatio;x(Ce)||(_e.userAgentDataPlatform=Ce),x(Te)||(_e.maxTouchPoints=Te),x(ae)||(_e.screenWidth=ae),x(me)||(_e.screenHeight=me),x(ge)||(_e.devicePixelRatio=ge);var Qe,Lt,de,Ge,It,Pn,De,Ae,Ei=te(ra({$os:U,$os_version:Q,$browser:hu(Fe,navigator.vendor,fe,Ie),$device:rl(Fe),$device_type:(Lt=Fe,de=_e,Ae=rl(Lt),Ae===Kc||Ae===Gc||Ae==="Kobo"||Ae==="Kindle Fire"||Ae===au?vn:Ae===ri||Ae===gn||Ae===oi||Ae===Jr?"Console":Ae===Yc?"Wearable":Ae?Oe:de?.userAgentDataPlatform==="Android"&&((Ge=de?.maxTouchPoints)!==null&&Ge!==void 0?Ge:0)>0?600>Math.min((It=de?.screenWidth)!==null&&It!==void 0?It:0,(Pn=de?.screenHeight)!==null&&Pn!==void 0?Pn:0)/((De=de?.devicePixelRatio)!==null&&De!==void 0?De:1)?Oe:vn:"Desktop"),$timezone:ed(),$timezone_offset:Jp()}),{$current_url:ci(S?Pt(se?.href):se?.href,z,ui),$host:se?.host,$pathname:se?.pathname,$raw_user_agent:Fe.length>1e3?Fe.substring(0,997)+"...":Fe,$browser_version:Vh(Fe,navigator.vendor,fe,Ie),$browser_language:Al(),$browser_language_prefix:(Qe=Al(),typeof Qe=="string"?Qe.split("-")[0]:void 0),$screen_height:_?.screen.height,$screen_width:_?.screen.width,$viewport_height:_?.innerHeight,$viewport_width:_?.innerWidth,$lib:Y.LIB_NAME,$lib_version:Y.LIB_VERSION,$insert_id:Math.random().toString(36).substring(2,10)+Math.random().toString(36).substring(2,10),$time:Date.now()/1e3});return Y.SDK_DIST_CHANNEL&&(Ei.$sdk_dist_channel=Y.SDK_DIST_CHANNEL),Ei})(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){var d=this.sessionManager.checkAndGetSessionAndWindowId(r,i.getTime()),h=d.windowId;a.$session_id=d.sessionId,a.$window_id=h}this.sessionPropsManager&&te(a,this.sessionPropsManager.getSessionProps());try{var p;this.sessionRecording&&te(a,this.sessionRecording.sdkDebugProperties),a.$sdk_debug_retry_queue_size=(p=this.Rn)==null?void 0:p.length}catch(A){a.$sdk_debug_error_capturing_properties=String(A)}if(this.requestRouter.region===xo&&(a.$lib_custom_api_host=this.config.api_host),u=e!==cn||r?e!==mr||r?this.pageViewManager.doEvent():this.pageViewManager.doPageLeave(i):this.pageViewManager.doPageView(i,s),a=te(a,u),e===cn&&C&&(a.title=C.title),!x(o)){var f=i.getTime()-o;a.$duration=parseFloat((f/1e3).toFixed(3))}Fe&&this.config.opt_out_useragent_filter&&(a.$browser_type=this._is_bot()?"bot":"browser");var g=this.persistence.properties(),m=this.sessionPersistence.properties();Z(["$referrer","$referring_domain"],(A=>{A in g&&delete m[A]}));var v={};if(this._n.length>0)for(var b of this._n.slice())try{te(v,b())}catch(A){k.error("Failed to produce browser extension event properties",A)}(a=te({},c,g,m,E({},v,a))).$is_identified=this._isIdentified(),O(this.config.property_denylist)?Z(this.config.property_denylist,(function(A){delete a[A]})):k.error(wd+this.config.property_denylist+" or property_blacklist config: "+this.config.property_blacklist);var w=this.config.sanitize_properties;w&&(k.error(Ul),a=w(a,e));var I=this.Zn();return a.$process_person_profile=I,I&&!r&&this.Gn("_calculate_event_properties"),a}Vn(e,n,i){var s;if(n===void 0&&(n=!0),i===void 0&&(i=!1),!this.persistence||!this.Zn()||this.mn&&!i)return e;var r=this.persistence.get_initial_props(),o=(s=this.sessionPropsManager)==null?void 0:s.getSetOnceProps(),a=te({},r,o||{},e||{}),l=this.config.sanitize_properties;return l&&(k.error(Ul),a=l(a,"$set_once")),n&&(this.mn=!0),yt(a)?void 0:a}register(e,n){var i;(i=this.persistence)==null||i.register(e,n)}register_once(e,n,i){var s;(s=this.persistence)==null||s.register_once(e,n,i)}register_for_session(e){var n;(n=this.sessionPersistence)==null||n.register(e),Object.keys(e).forEach((i=>this.yn.add(i))),this.Qn()}unregister(e){var n;(n=this.persistence)==null||n.unregister(e)}unregister_for_session(e){var n;(n=this.sessionPersistence)==null||n.unregister(e),this.yn.delete(e),this.Qn()}Kn(e,n){this.register({[e]:n})}An(){this.yn.forEach((e=>{var n;(n=this.sessionPersistence)==null||n.unregister(e)})),this.yn.clear(),this.Qn()}Qn(){var e;if(this.bn)if(this.config.persistence==="memory"||(e=this.sessionPersistence)!=null&&e.xi||!ce.N())ce.q(this.bn);else{var n=[];this.yn.forEach((i=>n.push(i))),n.length>0?ce.F(this.bn,n):ce.q(this.bn)}}getFeatureFlag(e,n){var i;return(i=this.featureFlags)==null?void 0:i.getFeatureFlag(e,n)}getFeatureFlagPayload(e){var n;return(n=this.featureFlags)==null?void 0:n.getFeatureFlagPayload(e)}getFeatureFlagResult(e,n){var i;return(i=this.featureFlags)==null?void 0:i.getFeatureFlagResult(e,n)}getAllFeatureFlags(){var e,n;return(e=(n=this.featureFlags)==null?void 0:n.getAllFeatureFlags())!==null&&e!==void 0?e:[]}isFeatureEnabled(e,n){var i,s;return(i=(s=this.featureFlags)==null?void 0:s.isFeatureEnabled(e,n))!==null&&i!==void 0?i:n?.defaultValue}reloadFeatureFlags(){var e;(e=this.featureFlags)==null||e.reloadFeatureFlags()}updateFlags(e,n,i){var s;(s=this.featureFlags)==null||s.updateFlags(e,n,i)}updateEarlyAccessFeatureEnrollment(e,n,i){var s;(s=this.featureFlags)==null||s.updateEarlyAccessFeatureEnrollment(e,n,i)}getEarlyAccessFeatures(e,n,i){var s;return n===void 0&&(n=!1),(s=this.featureFlags)==null?void 0:s.getEarlyAccessFeatures(e,n,i)}on(e,n){return this.dn.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:Dn}),()=>{})}onSessionId(e){var n,i;return(n=(i=this.sessionManager)==null?void 0:i.onSessionId(e))!==null&&n!==void 0?n:()=>{}}getSurveys(e,n){n===void 0&&(n=!1),this.surveys?this.surveys.getSurveys(e,n):e([],{isLoaded:!1,error:Dn})}getActiveMatchingSurveys(e,n){n===void 0&&(n=!1),this.surveys?this.surveys.getActiveMatchingSurveys(e,n):e([],{isLoaded:!1,error:Dn})}renderSurvey(e,n){var i;(i=this.surveys)==null||i.renderSurvey(e,n)}displaySurvey(e,n){var i;n===void 0&&(n=vf),(i=this.surveys)==null||i.displaySurvey(e,n)}cancelPendingSurvey(e){var n;(n=this.surveys)==null||n.cancelPendingSurvey(e)}canRenderSurvey(e){var n,i;return(n=(i=this.surveys)==null?void 0:i.canRenderSurvey(e))!==null&&n!==void 0?n:{visible:!1,disabledReason:Dn}}canRenderSurveyAsync(e,n){var i,s;return n===void 0&&(n=!1),(i=(s=this.surveys)==null?void 0:s.canRenderSurveyAsync(e,n))!==null&&i!==void 0?i:Promise.resolve({visible:!1,disabledReason:Dn})}Jn(e){return!e||Gr(e)?(k.critical("Unique user id has not been set in posthog.identify"),!1):e===Ci?(k.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())||(k.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,i){if(!this.__loaded||!this.persistence)return k.uninitializedWarning("posthog.identify");if(he(e)&&(e=e.toString(),k.warn("The first argument to posthog.identify was a number, but it should be a string. It has been converted to a string.")),this.Jn(e)&&this.Gn("posthog.identify")){var s=this.get_distinct_id();this.register({$user_id:e}),this.get_property(ai)||this.register_once({$had_persisted_distinct_id:!0,$device_id:s},""),e!==s&&e!==this.get_property(zn)&&(this.unregister(zn),this.register({distinct_id:e}));var r,o=(this.persistence.get_property(He)||sn)===sn,a=e!==s,l=!a&&o;if(a&&o)this.persistence.set_property(He,Ot),this.setPersonPropertiesForFlags({$set:n||{},$set_once:i||{}},!1),this.capture(vr,{distinct_id:e,$anon_distinct_id:s},{$set:n||{},$set_once:i||{}}),this.Sn=Ar(e,n,i),(r=this.featureFlags)==null||r.setAnonymousDistinctId(s);else if(l){this.persistence.set_property(He,Ot);var u=n||{},c=i||{};this.setPersonPropertiesForFlags({$set:u,$set_once:c},!1),this.capture("$set",{$set:u,$set_once:c}),this.Sn=Ar(e,n,i)}else(n||i)&&this.setPersonProperties(n,i);a?(this.reloadFeatureFlags(),this.featureFlags?this.featureFlags.resetFlagCallReported():this.unregister(Gt)):l&&(n||i)&&this.reloadFeatureFlags()}}setPersonProperties(e,n){if((e||n)&&this.Gn("posthog.setPersonProperties")){var i=Ar(this.get_distinct_id(),e,n);this.Sn!==i?(this.setPersonPropertiesForFlags({$set:e||{},$set_once:n||{}},!0),this.capture("$set",{$set:e||{},$set_once:n||{}}),this.Sn=i):k.info("A duplicate setPersonProperties call was made with the same properties. It has been ignored.")}}unsetPersonProperties(e){var n,i=(O(e)?e:[e]).filter((s=>q(s)&&s.length>0));i.length!==0&&this.Gn("posthog.unsetPersonProperties")&&((n=this.featureFlags)==null||n.unsetPersonPropertiesForFlags(i,!0),this.capture("$set",{$unset:i}),this.Sn=null)}group(e,n,i){if(e&&n){var s=this.getGroups(),r=s[e]!==n;if(r&&this.resetGroupPropertiesForFlags(e),this.register({$groups:E({},s,{[e]:n})}),r||i){var o={$group_type:e,$group_key:n};i&&(o.$group_set=i),this.capture(hl,o)}i&&this.setGroupPropertiesForFlags({[e]:i}),r&&!i&&this.reloadFeatureFlags()}else k.error("posthog.group requires a group type and group key")}resetGroups(){this.register({$groups:{}}),this.resetGroupPropertiesForFlags(),this.reloadFeatureFlags()}setPersonPropertiesForFlags(e,n){var i;n===void 0&&(n=!0),(i=this.featureFlags)==null||i.setPersonPropertiesForFlags(e,n)}resetPersonPropertiesForFlags(e){var n;e===void 0&&(e=!0),(n=this.featureFlags)==null||n.resetPersonPropertiesForFlags(e)}setGroupPropertiesForFlags(e,n){var i;n===void 0&&(n=!0),this.Gn("posthog.setGroupPropertiesForFlags")&&((i=this.featureFlags)==null||i.setGroupPropertiesForFlags(e,n))}resetGroupPropertiesForFlags(e){var n;(n=this.featureFlags)==null||n.resetGroupPropertiesForFlags(e)}reset(e){this.Yn(e)}Yn(e,n){var i,s,r,o,a,l,u,c,d,h;if(n===void 0&&(n=!1),k.info("reset"),!this.__loaded)return k.uninitializedWarning("posthog.reset");var p,f=this.get_property(ai),g=this.get_property(gr),m=this.get_property(Jt),v=this.is_capturing();if(this.consent.reset(),n||!v||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."),(i=this.persistence)==null||i.clear(),(s=this.sessionPersistence)==null||s.clear(),this.yn.clear(),this.Qn(),x(m)||(p=this.persistence)==null||p.register({[Jt]:m}),(r=this.surveys)==null||r.reset(),(o=this.Un)==null||o.stop(),(a=this.featureFlags)==null||a.reset(),(l=this.conversations)==null||l.reset(),(u=this.logs)==null||u.reset(),(c=this.metrics)==null||c.reset(),(d=this.persistence)==null||d.set_property(He,sn),(h=this.sessionManager)==null||h.resetSessionId(),this.Sn=null,this.config.cookieless_mode===gt)this.register_once({distinct_id:Ci,$device_id:null},"");else{var b=this.config.get_device_id(ft());this.register_once({distinct_id:b,$device_id:e?b:f},""),e||x(g)||this.register({[gr]:g})}this.register({$last_posthog_reset:new Date().toISOString()},1),delete this.config.identity_distinct_id,delete this.config.identity_hash,this.reloadFeatureFlags()}shutdown(e){var n=this;return X((function*(){var i,s,r,o,a,l,u;if(n.__loaded){(i=n.Un)==null||i.stop(),(s=n.jn)==null||s.dispose(),(r=n.sessionRecording)==null||r.dispose(),(o=n.logs)==null||o.flushLogs("sendBeacon"),(a=n.metrics)==null||a.flush("sendBeacon"),(l=n.In)==null||l.unload(),(u=n.Rn)==null||u.unload();try{var c;(c=n.featureFlags)==null||c.destroy()}catch(d){k.error("Error while destroying feature flags",d)}}else k.uninitializedWarning("posthog.shutdown")}))()}setIdentity(e,n){var i;this.config.identity_distinct_id=e,this.config.identity_hash=n,this.alias(e),(i=this.conversations)==null||i.Xn()}clearIdentity(){var e;delete this.config.identity_distinct_id,delete this.config.identity_hash,(e=this.conversations)==null||e.ts()}get_distinct_id(){return this.get_property("distinct_id")}getGroups(){return this.get_property("$groups")||{}}get_session_id(){var e,n;return(e=(n=this.sessionManager)==null?void 0:n.checkAndGetSessionAndWindowId(!0).sessionId)!==null&&e!==void 0?e:""}get_session_replay_url(e){if(!this.sessionManager)return"";var n=this.sessionManager.checkAndGetSessionAndWindowId(!0),i=n.sessionStartTimestamp,s=this.requestRouter.endpointFor("ui","/project/"+this.config.token+"/replay/"+n.sessionId);if(e!=null&&e.withTimestamp&&i){var r,o=(r=e.timestampLookBack)!==null&&r!==void 0?r:10;if(!i)return s;s+="?t="+Math.max(Math.floor((new Date().getTime()-i)/1e3)-o,0)}return s}alias(e,n){return e===this.get_property(bu)?(k.critical("Attempting to create alias for existing People user - aborting."),-2):this.Gn("posthog.alias")?(x(n)&&(n=this.get_distinct_id()),e!==n?(this.Kn(zn,e),this.capture("$create_alias",{alias:e,distinct_id:n})):(k.warn("alias matches current distinct_id - skipping api call."),this.identify(e),-1)):void 0}set_config(e){var n=E({},this.config);if(ne(e)){var i,s,r,o,a,l,u,c,d,h,p,f;te(this.config,Hl(e));var g=this.En();(i=this.persistence)==null||i.update_config(this.config,n,g),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new Er(E({},this.config,{persistence:"sessionStorage"}),g,!1);var m=this.Cn(this.config.debug);Ye(m)&&(this.config.debug=m),Ye(this.config.debug)&&(this.config.debug?(Y.DEBUG=!0,ee.N()&&ee.F("ph_debug",!0),k.info("set_config",{config:e,oldConfig:n,newConfig:E({},this.config)})):(Y.DEBUG=!1,ee.N()&&ee.q("ph_debug"))),(s=this.featureFlags)==null||s.updateConfig==null||s.updateConfig(this.config,this.Qi()),(r=this.exceptionObserver)==null||r.onConfigChange(),(o=this.exceptions)==null||o.onConfigChange(),(a=this.sessionRecording)==null||a.startIfEnabledOrStop(),(l=this.tracingHeaders)==null||l.startIfEnabledOrStop(),(u=this.autocapture)==null||u.startIfEnabled(),(c=this.heatmaps)==null||c.startIfEnabled(),(d=this.exceptionObserver)==null||d.startIfEnabledOrStop(),(h=this.deadClicksAutocapture)==null||h.startIfEnabledOrStop(),(p=this.surveys)==null||p.loadIfEnabled(),this.es(),(f=this.externalIntegrations)==null||f.startIfEnabledOrStop()}}_overrideSDKInfo(e,n){Y.LIB_NAME=e,Y.LIB_VERSION=n}startSessionRecording(e){var n,i,s,r,o,a=e===!0,l={sampling:a||!(e==null||!e.sampling),linked_flag:a||!(e==null||!e.linked_flag),url_trigger:a||!(e==null||!e.url_trigger),event_trigger:a||!(e==null||!e.event_trigger)};Object.values(l).some(Boolean)&&((n=this.sessionManager)==null||n.checkAndGetSessionAndWindowId(),l.sampling&&((i=this.sessionRecording)==null||i.overrideSampling()),l.linked_flag&&((s=this.sessionRecording)==null||s.overrideLinkedFlag()),l.url_trigger&&((r=this.sessionRecording)==null||r.overrideTrigger("url")),l.event_trigger&&((o=this.sessionRecording)==null||o.overrideTrigger("event"))),this.set_config({disable_session_recording:!1})}stopSessionRecording(){this.set_config({disable_session_recording:!0})}sessionRecordingStarted(){var e;return!((e=this.sessionRecording)==null||!e.started)}captureException(e,n){if(this.exceptions){var i=new Error("PostHog syntheticException"),s=this.exceptions.buildProperties(e,{handled:!0,syntheticException:i});return this.exceptions.sendExceptionEvent(E({},s,n))}}addExceptionStep(e,n){var i;(i=this.exceptions)==null||i.addExceptionStep(e,n)}captureLog(e){var n;(n=this.logs)==null||n.captureLog(e)}get logger(){var e,n;return(e=(n=this.logs)==null?void 0:n.logger)!==null&&e!==void 0?e:Re.rs}startExceptionAutocapture(e){this.set_config({capture_exceptions:e==null||e})}stopExceptionAutocapture(){this.set_config({capture_exceptions:!1})}loadToolbar(e){var n,i;return(n=(i=this.toolbar)==null?void 0:i.loadToolbar(e))!==null&&n!==void 0&&n}get_property(e){var n;return(n=this.persistence)==null?void 0:n.props[e]}getSessionProperty(e){var n;return(n=this.sessionPersistence)==null?void 0:n.props[e]}toString(){var e,n=(e=this.config.name)!==null&&e!==void 0?e:un;return n!==un&&(n=un+"."+n),n}_isIdentified(){var e,n;return((e=this.persistence)==null?void 0:e.get_property(He))===Ot||((n=this.sessionPersistence)==null?void 0:n.get_property(He))===Ot}Zn(){var e,n;return!(this.config.person_profiles==="never"||this.config.person_profiles===fo&&!this._isIdentified()&&yt(this.getGroups())&&((e=this.persistence)==null||(e=e.props)==null||!e[zn])&&((n=this.persistence)==null||(n=n.props)==null||!n[hs]))}zn(){return this.config.capture_pageleave===!0||this.config.capture_pageleave==="if_capture_pageview"&&(this.config.capture_pageview===!0||this.config.capture_pageview==="history_change")}createPersonProfile(){this.Zn()||this.Gn("posthog.createPersonProfile")&&this.setPersonProperties({},{})}setInternalOrTestUser(){this.Gn("posthog.setInternalOrTestUser")&&this.setPersonProperties({$internal_or_test_user:!0})}Gn(e){return this.config.person_profiles==="never"?(k.error(e+' was called, but process_person is set to "never". This call will be ignored.'),!1):(this.Kn(hs,!0),!0)}En(){if(this.config.cookieless_mode==="always")return!0;var e=this.consent.isOptedOut();return this.config.disable_persistence||e&&!(!this.config.opt_out_persistence_by_default&&this.config.cookieless_mode!==Vt)}es(){var e,n,i,s,r=this.En();return((e=this.persistence)==null?void 0:e.xi)!==r&&((i=this.persistence)==null||i.set_disabled(r)),((n=this.sessionPersistence)==null?void 0:n.xi)!==r&&((s=this.sessionPersistence)==null||s.set_disabled(r)),r&&(this.yn.clear(),this.Qn()),r}opt_in_capturing(e){var n;if(this.config.cookieless_mode!==gt){if(this.gn()){var i,s,r,o,a;this.Yn(!0,!0),(i=this.sessionManager)==null||i.destroy(),(s=this.pageViewManager)==null||s.destroy(),this.sessionManager=new Ol(this),this.pageViewManager=new Cl(this),this.persistence&&(this.sessionPropsManager=new Ll(this,this.sessionManager,this.persistence));var l,u=(r=(o=this.config.__extensionClasses)==null?void 0:o.sessionRecording)!==null&&r!==void 0?r:(a=Re.__defaultExtensionClasses)==null?void 0:a.sessionRecording;u&&(this.sessionRecording=this.pn(this.sessionRecording,new u(this)),this.hn&&((l=this.sessionRecording)==null||l.onRemoteConfig==null||l.onRemoteConfig(this.hn)))}var c,d;this.consent.optInOut(!0),this.es(),this.Bn(),(n=this.sessionRecording)==null||n.startIfEnabledOrStop(),this.config.cookieless_mode==Vt&&((c=this.surveys)==null||c.loadIfEnabled()),(x(e?.captureEventName)||e!=null&&e.captureEventName)&&this.capture((d=e?.captureEventName)!==null&&d!==void 0?d:"$opt_in",e?.captureProperties,{send_instantly:!0}),this.config.capture_pageview&&this.Hn()}else k.warn(jl)}opt_out_capturing(){var e,n,i;this.config.cookieless_mode!==gt?(this.config.cookieless_mode===Vt&&this.consent.isOptedIn()&&this.Yn(!0,!0),this.consent.optInOut(!1),this.es(),this.config.cookieless_mode===Vt&&(this.register({distinct_id:Ci,$device_id:null}),(e=this.sessionRecording)==null||e.stopRecording(),this.sessionRecording=void 0,(n=this.sessionManager)==null||n.destroy(),(i=this.pageViewManager)==null||i.destroy(),this.sessionManager=void 0,this.sessionPropsManager=void 0,this.config.capture_pageview&&this.Hn(),this.Bn())):k.warn(jl)}has_opted_in_capturing(){return this.consent.isOptedIn()}has_opted_out_capturing(){return this.consent.isOptedOut()}get_explicit_consent_status(){var e=this.consent.consent;return e===1?"granted":e===0?"denied":"pending"}is_capturing(){return this.config.cookieless_mode===gt||(this.config.cookieless_mode===Vt?this.consent.isRejected()||this.consent.isOptedIn():!this.has_opted_out_capturing())}clear_opt_in_out_capturing(){this.consent.reset(),this.es()}_is_bot(){return ke?pd(ke,this.config.custom_blocked_useragents):void 0}Hn(){C&&(C.visibilityState==="visible"?this.wn||(this.wn=!0,this.capture(cn,{title:C.title},{send_instantly:!0}),this.kn&&(C.removeEventListener(ps,this.kn),this.kn=null)):this.kn||(this.kn=this.Hn.bind(this),re(C,ps,this.kn)))}debug(e){e===!1?(_?.console.log("You've disabled debug mode."),this.set_config({debug:!1})):(_?.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}))}Qi(){var e=this.Mn||{};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?(k.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,i,s,r,o){var a=i in n&&!B(n[i]),l=s in n&&!B(n[s]);return a?n[i]:!!l&&(o&&o.warn("Config field '"+s+"' is deprecated. Please use '"+i+"' instead. The old field will be removed in a future major version."),n[s])})(e,"advanced_disable_flags","advanced_disable_decide",0,k)}Pt(e){var n;if(B(this.config.before_send))return e;var i=Object.keys((n=e.properties)!==null&&n!==void 0?n:{}).filter(Nh),s=O(this.config.before_send)?this.config.before_send:[this.config.before_send],r=e;for(var o of s){if(r=o(r),B(r)){var a="Event '"+e.event+"' was rejected in beforeSend function";return Rh(e.event)?k.warn(a+". This can cause unexpected behavior."):k.info(a),null}r.properties&&!yt(r.properties)||k.warn("Event '"+e.event+"' has no properties after beforeSend function, this is likely an error.")}for(var l of i)if(r.properties&&B(r.properties[l]))return k.warn("Event '"+e.event+"' had its '"+l+"' property removed in a beforeSend function. This property is required for ingestion, so the event will be dropped."),null;return r}getPageViewId(){var e;return(e=this.pageViewManager.ui)==null?void 0:e.pageViewId}captureTraceFeedback(e,n){this.capture("$ai_feedback",{$ai_trace_id:String(e),$ai_feedback_text:n})}captureTraceMetric(e,n,i){this.capture("$ai_metric",{$ai_trace_id:String(e),$ai_metric_name:n,$ai_metric_value:String(i)})}Cn(e){var n=Ye(e)&&!e,i=ee.N()&&ee.P("ph_debug")==="true";return!n&&(!!i||e)}}Re.__defaultExtensionClasses={},Re.rs=(()=>{var t=()=>{};return{trace:t,debug:t,info:t,warn:t,error:t,fatal:t}})(),(function(t,e){for(var n=0;e.length>n;n++)t.prototype[e[n]]=Ep(t.prototype[e[n]])})(Re,["identify"]);class Wl{constructor(e){this.disabled=e===!1;var n=ne(e)?e:{};this.thresholdPx=n.threshold_px||30,this.timeoutMs=n.timeout_ms||1e3,this.clickCount=n.click_count||3,this.clicks=[]}isRageClick(e,n,i){if(this.disabled)return!1;var s=this.clicks[this.clicks.length-1];if(s&&Math.abs(e-s.x)+Math.abs(n-s.y)i-s.timestamp){if(this.clicks.push({x:e,y:n,timestamp:i}),this.clicks.length===this.clickCount)return!0}else this.clicks=[{x:e,y:n,timestamp:i}];return!1}}var $r="$copy_autocapture",Tr=ie("[AutoCapture]");function Rr(t,e){return e.length>t?e.slice(0,t)+"...":e}function Cf(t){if(t.previousElementSibling)return t.previousElementSibling;var e=t;do e=e.previousSibling;while(e&&!$t(e));return e}function Af(t,e){var n,i,s=e.e,r=e.maskAllElementAttributes,o=e.maskAllText,a=e.elementAttributeIgnoreList,l=e.elementsChainAsString,u=e.disableCaptureUrlHashes;if(!$t(t))return{props:{}};for(var c=[t],d=new Set([t]),h=t;h.parentNode&&!Me(h,"body")&&Ou>c.length;)if(Lu(h.parentNode)){var p=h.parentNode.host;if(d.has(p))break;d.add(p),c.push(p),h=p}else{if(!$t(h.parentNode)||d.has(h.parentNode))break;d.add(h.parentNode),c.push(h.parentNode),h=h.parentNode}var f,g,m=[],v={},b=!1,w=!1;if(Z(c,(S=>{var $=vo(S);if(Me(S,"a")){var T=S.getAttribute("href");b=!!($&&T&&Qn(T))&&(u?Pt(T):T)}L(ms(S),"ph-no-capture")&&(w=!0),m.push((function(N,P,z,H,U){U===void 0&&(U=!1);var Q=N.tagName.toLowerCase(),fe={tag_name:Q};aa.indexOf(Q)>-1&&!z&&(fe.$el_text=Q.toLowerCase()==="a"||Q.toLowerCase()==="button"?Rr(1024,xl(N)):Rr(1024,li(N)));var Ie=ms(N);Ie.length>0&&(fe.classes=Ie.filter((function(ae){return ae!==""}))),Z(N.attributes,(function(ae){var me;if((!Hu(N)||["name","id","class","aria-label"].indexOf(ae.name)!==-1)&&(H==null||!H.includes(ae.name))&&!P&&Qn(ae.value)&&(!q(me=ae.name)||me.substring(0,10)!=="_ngcontent"&&me.substring(0,7)!=="_nghost")){var ge=ae.value;ae.name==="class"&&(ge=oa(ge).join(" ")),fe["attr__"+ae.name]=Rr(1024,ae.name==="href"&&U?Pt(ge):ge)}}));for(var _e=1,Ce=1,Te=N;Te=Cf(Te);)_e++,Te.tagName===N.tagName&&Ce++;return fe.nth_child=_e,fe.nth_of_type=Ce,fe})(S,r,o,a,u));var M=(function(N){if(!vo(N))return{};var P={};return Z(N.attributes,(function(z){if(z.name&&z.name.indexOf("data-ph-capture-attribute")===0){var H=z.name.replace("data-ph-capture-attribute-",""),U=z.value;H&&U&&Qn(U)&&(P[H]=U)}})),P})(S);te(v,M)})),w)return{props:{},explicitNoCapture:w};if(o||(m[0].$el_text=Me(t,"a")||Me(t,"button")?xl(t):li(t)),b){var I,A;m[0].attr__href=b;var F=(I=vs(b))==null?void 0:I.host,D=_==null||(A=_.location)==null?void 0:A.host;F&&D&&F!==D&&(f=b)}return{props:te({$event_type:s.type,$ce_version:1},l?{}:{$elements:m},{$elements_chain:(g=m,(function(S){return S.map(($=>{var T,M,N="";if($.tag_name&&(N+=$.tag_name),$.attr_class)for(var P of($.attr_class.sort(),$.attr_class))N+="."+P.replace(/"/g,"");var z=E({},$.text?{text:$.text}:{},{"nth-child":(T=$.nth_child)!==null&&T!==void 0?T:0,"nth-of-type":(M=$.nth_of_type)!==null&&M!==void 0?M:0},$.href?{href:$.href}:{},$.attr_id?{attr_id:$.attr_id}:{},$.attributes),H={};return qi(z).sort(((U,Q)=>U[0].localeCompare(Q[0]))).forEach((U=>{var Q=U[1];return H[kl(U[0].toString())]=kl(Q.toString())})),(N+=":")+qi(H).map((U=>U[0]+'="'+U[1]+'"')).join("")})).join(";")})((function(S){return S.map(($=>{var T,M,N={text:(T=$.$el_text)==null?void 0:T.slice(0,400),tag_name:$.tag_name,href:(M=$.attr__href)==null?void 0:M.slice(0,2048),attr_class:Up($),attr_id:$.attr__id,nth_child:$.nth_child,nth_of_type:$.nth_of_type,attributes:{}};return qi($).filter((P=>P[0].indexOf("attr__")===0)).forEach((P=>N.attributes[P[0]]=P[1])),N}))})(g)))},(n=m[0])!=null&&n.$el_text?{$el_text:(i=m[0])==null?void 0:i.$el_text}:{},f&&s.type==="click"?{$external_click_url:f}:{},v)}}var jn=ie("[ExceptionAutocapture]"),zl=()=>{},Ff=ie("[TracingHeaders]"),jt=ie("[Web Vitals]"),ql=9e5,Vl="disabled",Gl="lazy_loading",Un="awaiting_config",Ni="missing_config";ie("[SessionRecording]"),ie("[SessionRecording]");var ko="[SessionRecording]",ut=ie(ko),Pf=ie("[Heatmaps]");function Nr(t){return ne(t)&&"clientX"in t&&"clientY"in t&&he(t.clientX)&&he(t.clientY)}var Mi=ie("[Product Tours]"),Mr=t=>{var e;return!t.config.disable_product_tours&&!((e=t.persistence)==null||!e.get_property(na))},$f=["$set_once","$set"],et=ie("[SiteApps]"),Kl="Error while initializing PostHog app with config id ";function an(t,e,n){if(B(t))return!1;switch(n){case"exact":return t===e;case"contains":var i=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/_/g,".").replace(/%/g,".*");return new RegExp(i,"i").test(t);case"regex":try{return new RegExp(e).test(t)}catch{return!1}default:return!1}}class Tf{constructor(e){this.ns=new da,this.ss=(n,i)=>this.os(n,i)&&this.ls(n,i)&&this.us(n,i)&&this.hs(n,i),this.os=(n,i)=>i==null||!i.event||n?.event===i?.event,this._instance=e,this.ds=new Set,this.vs=new Set}init(){var e,n;x((e=this._instance)==null?void 0:e._addCaptureHook)||(n=this._instance)==null||n._addCaptureHook(((i,s)=>{this.on(i,s)}))}register(e){var n,i;if(!x((n=this._instance)==null?void 0:n._addCaptureHook)&&(e.forEach((o=>{var a,l;(a=this.vs)==null||a.add(o),(l=o.steps)==null||l.forEach((u=>{var c;(c=this.ds)==null||c.add(u?.event||"")}))})),(i=this._instance)!=null&&i.autocapture)){var s,r=new Set;e.forEach((o=>{var a;(a=o.steps)==null||a.forEach((l=>{l!=null&&l.selector&&r.add(l?.selector)}))})),(s=this._instance)==null||s.autocapture.setElementSelectors(r)}}on(e,n){var i;n!=null&&e.length!=0&&(this.ds.has(e)||this.ds.has(n.event))&&this.vs&&((i=this.vs)==null?void 0:i.size)>0&&this.vs.forEach((s=>{this.cs(n,s)&&this.ns.emit("actionCaptured",s.name)}))}fs(e){this.onAction("actionCaptured",(n=>e(n)))}cs(e,n){if(n?.steps==null)return!1;for(var i of n.steps)if(this.ss(e,i))return!0;return!1}onAction(e,n){return this.ns.on(e,n)}ls(e,n){if(n!=null&&n.url){var i,s=e==null||(i=e.properties)==null?void 0:i.$current_url;if(!s||typeof s!="string"||!an(s,n.url,n.url_matching||"contains"))return!1}return!0}us(e,n){return!!this.ps(e,n)&&!!this.gs(e,n)&&!!this.ys(e,n)}ps(e,n){var i;if(n==null||!n.href)return!0;var s=this.bs(e);if(s.length>0)return s.some((a=>an(a.href,n.href,n.href_matching||"exact")));var r,o=(e==null||(i=e.properties)==null?void 0:i.$elements_chain)||"";return!!o&&an((r=o.match(/(?::|")href="(.*?)"/))?r[1]:"",n.href,n.href_matching||"exact")}gs(e,n){var i;if(n==null||!n.text)return!0;var s=this.bs(e);if(s.length>0)return s.some((u=>an(u.text,n.text,n.text_matching||"exact")||an(u.$el_text,n.text,n.text_matching||"exact")));var r,o,a,l=(e==null||(i=e.properties)==null?void 0:i.$elements_chain)||"";return!!l&&(r=(function(u){for(var c,d=[],h=/(?::|")text="(.*?)"/g;!B(c=h.exec(u));)d.includes(c[1])||d.push(c[1]);return d})(l),o=n.text,a=n.text_matching||"exact",r.some((u=>an(u,o,a))))}ys(e,n){var i,s;if(n==null||!n.selector)return!0;var r=e==null||(i=e.properties)==null?void 0:i.$element_selectors;if(r!=null&&r.includes(n.selector))return!0;var o=(e==null||(s=e.properties)==null?void 0:s.$elements_chain)||"";if(n.selector_regex&&o)try{return new RegExp(n.selector_regex).test(o)}catch{return!1}return!1}bs(e){var n;return(e==null||(n=e.properties)==null?void 0:n.$elements)==null?[]:e?.properties.$elements}hs(e,n){return n==null||!n.properties||n.properties.length===0||md(n.properties.reduce(((i,s)=>{var r=O(s.value)?s.value.map(String):s.value!=null?[String(s.value)]:[];return i[s.key]={values:r,operator:s.operator||"exact"},i}),{}),e?.properties)}}class Rf{constructor(e){var n;this._s=[],this._instance=e,this.ws=new Map,this.ks=new Map,this.xs=new Map,(n=this._instance)==null||n.onSessionId==null||n.onSessionId((i=>this.Ss(i)))}Cs(e){return!1}Ms(){return null}Ts(e){}Es(){}Is(e,n){return!!e&&md(e.propertyFilters,n?.properties)}Ps(e,n){var i=new Map;return e.forEach((s=>{var r;(r=s.conditions)==null||(r=r[n])==null||(r=r.values)==null||r.forEach((o=>{if(o!=null&&o.name){var a=i.get(o.name)||[];a.push(s.id),i.set(o.name,a)}}))})),i}Rs(e,n,i){var s=(i===Mn.Activation?this.ws:this.ks).get(e),r=[];return this.As((o=>{r=o.filter((a=>s?.includes(a.id)))})),r.filter((o=>{var a,l=(a=o.conditions)==null||(a=a[i])==null||(a=a.values)==null?void 0:a.find((u=>u.name===e));return this.Is(l,n)}))}register(e){var n;x((n=this._instance)==null?void 0:n._addCaptureHook)||(this.Fs(e),this.Ls(e))}Ls(e){var n=e.filter((i=>{var s,r;return((s=i.conditions)==null?void 0:s.actions)&&((r=i.conditions)==null||(r=r.actions)==null||(r=r.values)==null?void 0:r.length)>0}));n.length!==0&&(this.Os==null&&(this.Os=new Tf(this._instance),this.Os.init(),this.Os.fs((i=>{this.onAction(i)}))),n.forEach((i=>{var s,r,o,a,l;i.conditions&&(s=i.conditions)!=null&&s.actions&&(r=i.conditions)!=null&&(r=r.actions)!=null&&r.values&&((o=i.conditions)==null||(o=o.actions)==null||(o=o.values)==null?void 0:o.length)>0&&((a=this.Os)==null||a.register(i.conditions.actions.values),(l=i.conditions)==null||(l=l.actions)==null||(l=l.values)==null||l.forEach((u=>{if(u&&u.name){var c=this.xs.get(u.name);c&&c.push(i.id),this.xs.set(u.name,c||[i.id])}})))})))}Fs(e){var n,i=e.filter((r=>{var o,a;return((o=r.conditions)==null?void 0:o.events)&&((a=r.conditions)==null||(a=a.events)==null||(a=a.values)==null?void 0:a.length)>0})),s=e.filter((r=>{var o,a;return((o=r.conditions)==null?void 0:o.cancelEvents)&&((a=r.conditions)==null||(a=a.cancelEvents)==null||(a=a.values)==null?void 0:a.length)>0}));i.length===0&&s.length===0||((n=this._instance)==null||n._addCaptureHook(((r,o)=>{this.onEvent(r,o)})),this.ws=this.Ps(e,Mn.Activation),this.ks=this.Ps(e,Mn.Cancellation))}onEvent(e,n){var i,s,r=this.Ds(),o=(n==null||(i=n.properties)==null?void 0:i.$survey_id)||(n==null||(s=n.properties)==null?void 0:s.$product_tour_id);if(o&&this.getActivatedIds().includes(o)){var a=this.$s(e,o);if(a==="consume")return r.info("event consumed activated item, removing it",{event:e,itemId:o}),void this.Ns([o]);if(a==="persist")return r.info("shown item promoted to persisted activation",{event:e,itemId:o}),this.qs(o),void this.js([o])}if(this.ks.has(e)){var l=this.Rs(e,n,Mn.Cancellation);l.length>0&&(r.info("cancel event matched, cancelling items",{event:e,itemsToCancel:l.map((c=>c.id))}),this.Ns(l.map((c=>c.id))),l.forEach((c=>this.Bs(c.id))))}if(this.ws.has(e)){r.info("event name matched",{event:e,eventPayload:n,items:this.ws.get(e)});var u=this.Rs(e,n,Mn.Activation);this.Hs(u.map((c=>c.id)))}}onAction(e){this.xs.has(e)&&this.Hs(this.xs.get(e)||[])}Hs(e){var n;if(e.length!==0){var i=!((n=this._instance)==null||n.get_session_id==null||!n.get_session_id()),s=[];for(var r of e)i&&this.Cs(r)?this.qs(r)&&this.Us(r):s.push(r);s.length>0&&(this._s=[...new Set([...this._s,...s])]),this.Ds().info("updating activated items",{activatedItems:this.getActivatedIds()})}}qs(e){this._s=this._s.filter((i=>i!==e));var n=this.zs();return!n.includes(e)&&(this.Ws([...n,e]),this.Vs(),!0)}Ns(e){var n=new Set(e);this._s=this._s.filter((r=>!n.has(r)));var i=this.Zs(),s=i.filter((r=>!n.has(r)));s.length!==i.length&&(this.Ws(s),s.length===0&&this.Gs()),this.js(e)}Qs(){var e,n=this.Ms();if(!n)return{};var i=(e=this._instance)==null||(e=e.persistence)==null?void 0:e.props[n];return i&&typeof i=="object"?i:{}}Us(e){if(this.Ms()){var n=this.Qs();this.Ts(E({},n,{[e]:Date.now()}))}}js(e){if(this.Ms()){var n=this.Qs(),i={},s=!1;for(var r of Object.entries(n)){var o=r[0],a=r[1];e.includes(o)?s=!0:i[o]=a}s&&(yt(i)?this.Es():this.Ts(i))}}Ks(){this.Ms()&&this.Es()}getActivationTimestamp(e){if(this.zs().includes(e)){var n=this.Qs()[e];return he(n)?n:void 0}}Zs(){var e,n=this.Js();return((e=this._instance)==null||(e=e.persistence)==null?void 0:e.props[n])||[]}zs(){var e,n,i=this.Zs();if(i.length===0)return[];var s=(e=this._instance)==null||(e=e.persistence)==null?void 0:e.props[this.Ys()],r=(n=this._instance)==null||n.get_session_id==null?void 0:n.get_session_id();return r&&s===r?i:[]}Vs(){var e,n=(e=this._instance)==null||e.get_session_id==null?void 0:e.get_session_id();n&&this.Xs(n)}Gs(){this.ta()}Ss(e){var n,i=(n=this._instance)==null||(n=n.persistence)==null?void 0:n.props[this.Ys()];if(i&&i!==e){var s=this.Zs(),r=this.Qs();s.length>0&&(this.Ws([]),s.filter((o=>he(r[o]))).forEach((o=>this.Bs(o)))),this.Gs(),this.Ks()}}getActivatedIds(){return[...new Set([...this.zs(),...this._s])].filter((e=>!this.ea(e)))}reset(){this._s=[],this.Zs().length>0&&this.Ws([]),this.Gs(),this.Ks()}getEventToItemsMap(){return this.ws}ia(){return this.Os}}class Nf extends Rf{constructor(e){super(e)}Js(){return lo}Ys(){return Hi}Ms(){return Wi}Ts(e){var n;(n=this._instance)==null||(n=n.persistence)==null||n.register({[Wi]:e})}Es(){var e;(e=this._instance)==null||(e=e.persistence)==null||e.unregister(Wi)}Cs(e){var n,i;this.As((r=>{i=r.find((o=>o.id===e))}));var s=(n=i)==null||(n=n.appearance)==null?void 0:n.surveyPopupDelaySeconds;return he(s)&&s>0}ra(){return vt.SHOWN}As(e){var n;(n=this._instance)==null||n.getSurveys(e)}Bs(e){var n;(n=this._instance)==null||n.cancelPendingSurvey(e)}Ds(){return G}Ws(e){var n;(n=this._instance)==null||(n=n.persistence)==null||n.register({[lo]:e})}Xs(e){var n;(n=this._instance)==null||(n=n.persistence)==null||n.register({[Hi]:e})}ta(){var e;(e=this._instance)==null||(e=e.persistence)==null||e.unregister(Hi)}ea(){return!1}$s(e,n){var i;this.As((r=>{i=r.find((o=>o.id===n))}));var s=!i||(function(r){var o;return vd(r)&&!((o=r.conditions)==null||(o=o.events)==null||!o.repeatedActivation)||r.schedule==="always"})(i);return s?e===vt.SHOWN?"consume":"ignore":e===vt.SHOWN?"persist":e===vt.DISMISSED||e===vt.SENT?"consume":"ignore"}getSurveys(){return this.getActivatedIds()}getEventToSurveys(){return this.getEventToItemsMap()}}var Li="SDK is not enabled or survey functionality is not yet loaded",Jl="Disabled. Not loading surveys.",Mf=_!=null&&_.location?_s(_.location.hash,"__posthog")||_s(location.hash,"state"):null,Yl="_postHogToolbarParams",Zl=ie("[Toolbar]"),Xl=ie("[FeatureFlags]");class Lf{constructor(e,n){n===void 0&&(n=!1),this.na=!1,this.update(e,n)}update(e,n){this.sa=((i,s)=>{var r,o,a,l;return{bootstrap:{featureFlags:(r=i.bootstrap)==null?void 0:r.featureFlags,featureFlagPayloads:(o=i.bootstrap)==null?void 0:o.featureFlagPayloads},remoteRequestsDisabled:s,featureFlagsDisabled:!!i.advanced_disable_feature_flags,onlyEvaluateSurveyFeatureFlags:!!i.advanced_only_evaluate_survey_feature_flags,deduplicateCallsPerSession:!!i.advanced_feature_flags_dedup_per_session,cacheTtlMs:i.feature_flag_cache_ttl_ms,requestTimeoutMs:i.feature_flag_request_timeout_ms,compression:i.disable_compression?"none":"base64",evaluationContexts:(a=(l=i.evaluation_contexts)!==null&&l!==void 0?l:i.evaluation_environments)!==null&&a!==void 0?a:[],flagKeys:O(i.flag_keys)?i.flag_keys:void 0}})(e,n),!e.evaluation_environments||e.evaluation_contexts||this.na||(Xl.warn("evaluation_environments is deprecated. Use evaluation_contexts instead. evaluation_environments will be removed in a future version."),this.na=!0),x(e.flag_keys)||O(e.flag_keys)||Xl.error("Invalid flag_keys found:",e.flag_keys,"Expected array of non-empty strings")}get(){return this.sa}}var Ql=ie("[FeatureFlags]"),Ut=ie("[FeatureFlags]",{debugEnabled:!0}),Lr=`" failed. Feature flags didn't load in time.`,ec="connection_error",tc=t=>{for(var e={},n=0;t.length>n;n++)e[t[n]]=!0;return e},nc=t=>{var e={};for(var n of qi(t||{})){var i=n[1];i&&(e[n[0]]=i)}return e},tt=ie("[Error tracking]"),ic="Refusing to render web experiment since the viewer is a likely bot",Of={icontains:(t,e)=>e.toLowerCase().indexOf(t.toLowerCase())>-1,not_icontains:(t,e)=>e.toLowerCase().indexOf(t.toLowerCase())===-1,regex:(t,e)=>bs(e,t),not_regex:(t,e)=>!bs(e,t),exact:(t,e)=>e===t,is_not:(t,e)=>e!==t};class ye{get Ne(){return this._instance.config}constructor(e){var n=this;this.getWebExperimentsAndEvaluateDisplayLogic=function(i){i===void 0&&(i=!1),n.getWebExperiments((s=>{ye.aa("retrieved web experiments from the server"),n.oa=new Map,s.forEach((r=>{if(r.feature_flag_key){var o;n.oa&&(ye.aa("setting flag key ",r.feature_flag_key," to web experiment ",r),(o=n.oa)==null||o.set(r.feature_flag_key,r));var a=n._instance.getFeatureFlag(r.feature_flag_key);q(a)&&r.variants[a]&&n.la(r.name,a,r.variants[a].transforms)}else if(r.variants)for(var l in r.variants){var u=r.variants[l];ye.ua(u,n._instance)&&n.la(r.name,l,u.transforms)}}))}),i)},this._instance=e,this._instance.onFeatureFlags((i=>{this.onFeatureFlags(i)}))}initialize(){}onFeatureFlags(e){if(this._is_bot())ye.aa(ic);else if(!this.Ne.disable_web_experiments){if(B(this.oa))return this.oa=new Map,this.loadIfEnabled(),void this.previewWebExperiment();ye.aa("applying feature flags",e),e.forEach((n=>{var i;if(this.oa&&(i=this.oa)!=null&&i.has(n)){var s,r=this._instance.getFeatureFlag(n),o=(s=this.oa)==null?void 0:s.get(n);r&&o!=null&&o.variants[r]&&this.la(o.name,r,o.variants[r].transforms)}}))}}previewWebExperiment(){var e=ye.getWindowLocation();if(e!=null&&e.search){var n=wn(e?.search,"__experiment_id"),i=wn(e?.search,"__experiment_variant");n&&i&&(ye.aa("previewing web experiments "+n+" && "+i),this.getWebExperiments((s=>{this.ha(parseInt(n),i,s)}),!1,!0))}}loadIfEnabled(){this.Ne.disable_web_experiments||this.getWebExperimentsAndEvaluateDisplayLogic()}getWebExperiments(e,n,i){if(this.Ne.disable_web_experiments&&!i)return e([]);var 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.Ne.token),method:"GET",timestampMode:"query",callback:r=>e(r.statusCode===200&&r.json&&r.json.experiments||[])})}ha(e,n,i){var s=i.filter((r=>r.id===e));s&&s.length>0&&(ye.aa("Previewing web experiment ["+s[0].name+"] with variant ["+n+"]"),this.la(s[0].name,n,s[0].variants[n].transforms))}static ua(e,n){return!B(e.conditions)&&ye.da(e,n)&&ye.va(e)}static da(e,n){var i;if(B(e.conditions)||B((i=e.conditions)==null?void 0:i.url))return!0;var s=ye.getWindowLocation();if(s){var r,o,a,l=Ru(n,s.href);return(r=e.conditions)==null||!r.url||Of[(o=(a=e.conditions)==null?void 0:a.urlMatchType)!==null&&o!==void 0?o:"icontains"](e.conditions.url,l)}return!1}static getWindowLocation(){return _?.location}static va(e){var n;if(B(e.conditions)||B((n=e.conditions)==null?void 0:n.utm))return!0;var i=Ku();if(i.utm_source){var s,r,o,a,l,u,c,d,h=(s=e.conditions)==null||(s=s.utm)==null||!s.utm_campaign||((r=e.conditions)==null||(r=r.utm)==null?void 0:r.utm_campaign)==i.utm_campaign,p=(o=e.conditions)==null||(o=o.utm)==null||!o.utm_source||((a=e.conditions)==null||(a=a.utm)==null?void 0:a.utm_source)==i.utm_source,f=(l=e.conditions)==null||(l=l.utm)==null||!l.utm_medium||((u=e.conditions)==null||(u=u.utm)==null?void 0:u.utm_medium)==i.utm_medium,g=(c=e.conditions)==null||(c=c.utm)==null||!c.utm_term||((d=e.conditions)==null||(d=d.utm)==null?void 0:d.utm_term)==i.utm_term;return h&&f&&g&&p}return!1}static aa(e){for(var n=arguments.length,i=new Array(n>1?n-1:0),s=1;n>s;s++)i[s-1]=arguments[s];k.info("[WebExperiments] "+e,i)}la(e,n,i){this._is_bot()?ye.aa(ic):n!=="control"?i.forEach((s=>{if(s.selector){var r;ye.aa("applying transform of variant "+n+" for experiment "+e+" ",s);var o=(r=document)==null?void 0:r.querySelectorAll(s.selector);o?.forEach((a=>{var l=a;s.html&&(l.innerHTML=s.html),s.css&&l.setAttribute("style",s.css)}))}})):ye.aa("Control variants leave the page unmodified.")}_is_bot(){return ke&&this._instance?pd(ke,this.Ne.custom_blocked_useragents):void 0}}var Ue=ie("[Conversations]"),Ht="Conversations not available yet.",sc="console",Ed="__posthogHandledLogsRequestError",Or=(t,e)=>{var n=t instanceof Error?t:new Error(e);return n[Ed]=!0,n},rc=t=>!!t&&typeof t=="object"&&t[Ed]===!0,Us={featureFlags:class{constructor(t){this.name="featureFlags",this.ca=!1,this.featureFlagEventHandlers=[],this.rt=Ql,this.fa={},this.pa={},this.ga=[],this.ma=!1,this.ya=!1,this.ba=0,this._a=!1,this.wa=!1,this.ka=!1,this.xa=!1,this.Sa=0,this.Ca=()=>{var e=this.Ma();this.Sa=0,e&&this.reloadFeatureFlags()},"get"in t?this.Ta=t:(this.Ea=new Lf(t.config,t.Qi()),this.Ta=this.Ea)}updateConfig(t,e){var n;(n=this.Ea)==null||n.update(t,e)}setup(t){return this.Ia=t,this.rt=t.logger.createLogger("[FeatureFlags]"),n=()=>{this.Ia===t&&(this.Ia=void 0,this.nn=t,this.Pa(t))},(e=t.kv.initialize())!=null&&e.then?e.then(n):n();var e,n}Pa(t){if(this.nn===t)return _&&re(_,"online",this.Ca),this.Ra=t.registerDynamicEventProperties((()=>this.Aa()?this.fa:this.pa)),this.Fa(),this.initialize()}destroy(){_?.removeEventListener("online",this.Ca)}dispose(){var t;this.ba++,this.wa=!1,this.Ia=void 0,this.nn&&(this.La(),(t=this.Ra)==null||t.dispose(),this.Ra=void 0,this.ga=[],_?.removeEventListener("online",this.Ca),this.nn=void 0)}get Ne(){return this.Ta.get()}Oa(t){var e;return(e=this.nn)==null?void 0:e.kv.get(t)}F(t){this.Da((()=>{var e;return(e=this.nn)==null?void 0:e.kv.set(t)}))}q(t){this.Da((()=>{var e;return(e=this.nn)==null?void 0:e.kv.remove(t)}))}Da(t){try{t()}catch(e){this.rt.error("Failed to update feature flag persistence",e)}}Fa(){var t={};for(var e of[Vn,Gn,Ui,it]){var n=this.Oa(e);x(n)||(t[e]=n)}this.fa=t;var i=E({},t),s=this.Oa(Wt);if(s)for(var r of Object.entries(s))i["$feature/"+r[0]]=r[1];this.pa=i}Aa(){var t=this.Ne.cacheTtlMs;if(!t||0>=t)return!1;var e=this.Oa(Xn);return typeof e!="number"||Date.now()-e>t}$a(){return!!this.Aa()&&(this.xa||this.ya||(this.xa=!0,this.rt.warn("Feature flag cache is stale, triggering refresh..."),this.reloadFeatureFlags()),!0)}Na(){var t=this.Ne.evaluationContexts;return t!=null&&t.length?t.filter((e=>{var n=e&&typeof e=="string"&&e.trim().length>0;return n||this.rt.error("Invalid evaluation context found:",e,"Expected non-empty string"),n})):[]}qa(){var t=this.Ne.flagKeys;if(!x(t))return t.filter((e=>{var n=e&&typeof e=="string"&&e.trim().length>0;return n||this.rt.error("Invalid flag key found:",e,"Expected non-empty string"),n}))}initialize(){var t,e,n=this.Ne,i=(t=(e=n.bootstrap)==null?void 0:e.featureFlags)!==null&&t!==void 0?t:{};if(Object.keys(i).length){var s,r,o=(s=(r=n.bootstrap)==null?void 0:r.featureFlagPayloads)!==null&&s!==void 0?s:{},a=Object.keys(i).filter((u=>!!i[u])).reduce(((u,c)=>(u[c]=i[c]||!1,u)),{}),l=Object.keys(o).filter((u=>a[u])).reduce(((u,c)=>(o[c]&&(u[c]=o[c]),u)),{});return this.ja({featureFlags:a,featureFlagPayloads:l})}}updateFlags(t,e,n){var i,s,r=n!=null&&n.merge&&(i=this.Oa(Wt))!==null&&i!==void 0?i:{},o=n!=null&&n.merge&&(s=this.Oa(Gn))!==null&&s!==void 0?s:{},a=E({},r,t),l=E({},o,e),u={};for(var c of Object.entries(a)){var d=c[0],h=c[1];u[d]={key:d,enabled:Za(h),variant:Xa(h),reason:void 0,metadata:x(l?.[d])?void 0:{id:0,version:void 0,description:void 0,payload:l[d]}}}this.ja({flags:u})}get hasLoadedFlags(){return this.ma}getFlags(){return Object.keys(this.getFlagVariants())}getFlagsWithDetails(){var t=this.Oa(oo),e=this.Oa(it),n=this.Oa(zt);if(!n&&!e)return t||{};var i=te({},t||{}),s=[...new Set([...Object.keys(n||{}),...Object.keys(e||{})])];for(var r of s){var o,a,l=i[r],u=e?.[r],c=x(u)?(o=l?.enabled)!==null&&o!==void 0&&o:!!u,d=x(u)?l?.variant:typeof u=="string"?u:void 0,h=n?.[r],p=E({},l,{enabled:c,variant:c?d??l?.variant:void 0});c!==l?.enabled&&(p.original_enabled=l?.enabled),d!==l?.variant&&(p.original_variant=l?.variant),h&&(p.metadata=E({},l?.metadata,{payload:h,original_payload:l==null||(a=l.metadata)==null?void 0:a.payload})),i[r]=p}return this.ca||(this.rt.warn(" Overriding feature flag details!",{flagDetails:t,overriddenPayloads:n,finalDetails:i}),this.ca=!0),i}getAllFeatureFlags(){var t=this.getFlagVariants(),e=this.getFlagPayloads();return Object.keys(t).map((n=>{var i=t[n];return{key:n,enabled:Za(i),variant:Xa(i),payload:Ya(e[n])}}))}getFlagVariants(){var t=this.Oa(Wt),e=this.Oa(it);if(!e)return t||{};for(var n=te({},t||{}),i=Object.keys(e),s=0;i.length>s;s++)n[i[s]]=e[i[s]];return this.ca||(this.rt.warn(" Overriding feature flags!",{enabledFlags:t,overriddenFlags:e,finalFlags:n}),this.ca=!0),n}getFlagPayloads(){var t=this.Oa(Gn),e=this.Oa(zt);if(!e)return t||{};for(var n=te({},t||{}),i=Object.keys(e),s=0;i.length>s;s++)n[i[s]]=e[i[s]];return this.ca||(this.rt.warn(" Overriding feature flag payloads!",{flagPayloads:t,overriddenPayloads:e,finalPayloads:n}),this.ca=!0),n}reloadFeatureFlags(){this._a||this.Ne.featureFlagsDisabled||this.Ma()||this.Ba||(this.ga.slice().forEach((t=>{try{t()}catch(e){this.rt.error("Error while running feature flags reloading callback",e)}})),this.Ba=setTimeout((()=>{this.Ha()}),5))}La(){clearTimeout(this.Ba),this.Ba=void 0}onReloading(t){return this.ga.push(t),()=>{this.ga=this.ga.filter((e=>e!==t))}}ensureFlagsLoaded(){this.ma||this.ya||this.Ba||this.reloadFeatureFlags()}setAnonymousDistinctId(t){this.$anon_distinct_id=t}setReloadingPaused(t){this._a=t}resetFlagCallReported(){this.q(Gt)}Ha(t){this.La();var e=this.nn;if(e&&!this.Ne.remoteRequestsDisabled&&!this.Ma())if(this.ya)this.wa=!0;else{var n={token:e.projectToken,distinct_id:e.distinctId,groups:e.groups,$anon_distinct_id:this.$anon_distinct_id,person_properties:E({},e.initialPersonProperties,this.Oa(ht)||{},{$lib:e.library.name,$lib_version:e.library.version}),group_properties:this.Oa(qt),timezone:ed()};x(e.deviceId)||(n.$device_id=e.deviceId),(t!=null&&t.disableFlags||this.Ne.featureFlagsDisabled)&&(n.disable_flags=!0);var i=this.Na();i.length&&(n.evaluation_contexts=i);var s=this.qa();x(s)||(n.flag_keys=s);var r=this.Ne.onlyEvaluateSurveyFeatureFlags,o="/flags/?v=2"+(r?"&only_evaluate_survey_feature_flags=true":""),a=this.ba;this.ya=!0;var l=()=>{this.wa&&(this.wa=!1,this.Ha())},u=c=>{this.ya=!1,a===this.ba&&(this.F({[zi]:[ec]}),this.rt.error("Feature flag request failed",c)),l()};try{e.sendRequest(o,{target:"flags",method:"POST",body:n,compression:this.Ne.compression==="base64"?xe.Base64:void 0,sentAt:"body",timeoutMs:this.Ne.requestTimeoutMs}).then((c=>{var d,h,p=(d=c.json)!==null&&d!==void 0?d:{},f=c.statusCode!==200;if(this.ya=!1,a===this.ba){if(this.Ua(c.statusCode),f||this.wa||(this.$anon_distinct_id=void 0),!n.disable_flags||this.wa){this.ka=!f;var g=[];c.error?g.push(c.error instanceof Error&&c.error.name==="AbortError"?"timeout":c.error instanceof Error?ec:"unknown_error"):c.statusCode!==200&&g.push("api_error_"+c.statusCode),p.errorsWhileComputingFlags&&g.push("errors_while_computing_flags");var m=!((h=p.quotaLimited)==null||!h.includes("feature_flags"));m&&g.push("quota_limited"),this.F({[zi]:g}),m?this.rt.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."):n.disable_flags||this.ja(p,f,{partialResponse:r}),l()}}else l()})).catch(u)}catch(c){u(c)}}}Ma(){return Vu(this.Sa,3)}Ua(t){this.Sa=Gu(t,this.Sa,3,(()=>this.rt.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===void 0&&(e={}),!e.fresh||this.ka)if(this.ma||this.getFlags()&&this.getFlags().length>0){if(!this.$a()){var i=this.getFeatureFlagResult(t,e);return(n=i?.variant)!==null&&n!==void 0?n:i?.enabled}}else this.rt.warn('getFeatureFlag for key "'+t+Lr)}getFeatureFlagDetails(t){return this.getFlagsWithDetails()[t]}getFeatureFlagPayload(t){var e=this.getFeatureFlagResult(t,{send_event:!1});return e?.payload}getFeatureFlagResult(t,e){if(e===void 0&&(e={}),!e.fresh||this.ka)if(this.ma||this.getFlags()&&this.getFlags().length>0){if(!this.$a()){var n,i=this.getFlagVariants(),s=t in i,r=i[t],o=this.getFlagPayloads()[t],a=String(r),l=this.Oa(Ui)||void 0,u=this.Oa(Xn)||void 0,c=this.Oa(Gt)||{};if(this.Ne.deduplicateCallsPerSession){var d,h=(d=this.nn)==null?void 0:d.session.sessionId,p=this.Oa(Jn);h&&h!==p&&(c={},n=h)}if(e.send_event||!("send_event"in e))if(t in c&&c[t].includes(a))n&&this.F({[Gt]:c,[Jn]:n});else{var f,g,m,v,b,w,I,A,F,D;O(c[t])?c[t].push(a):c[t]=[a],this.F(E({[Gt]:c},n?{[Jn]:n}:{}));var S=this.getFeatureFlagDetails(t),$=[...(f=this.Oa(zi))!==null&&f!==void 0?f:[]];x(r)&&$.push("flag_missing");var T={$feature_flag:t,$feature_flag_response:r,$feature_flag_payload:o||null,$feature_flag_request_id:l,$feature_flag_evaluated_at:u,$feature_flag_bootstrapped_response:((g=this.Ne.bootstrap)==null||(g=g.featureFlags)==null?void 0:g[t])||null,$feature_flag_bootstrapped_payload:((m=this.Ne.bootstrap)==null||(m=m.featureFlagPayloads)==null?void 0:m[t])||null,$used_bootstrap_value:!this.ka};x(S==null||(v=S.metadata)==null?void 0:v.has_experiment)||(T.$feature_flag_has_experiment=S.metadata.has_experiment),x(S==null||(b=S.metadata)==null?void 0:b.version)||(T.$feature_flag_version=S.metadata.version);var M,N=(w=S==null||(I=S.reason)==null?void 0:I.description)!==null&&w!==void 0?w:S==null||(A=S.reason)==null?void 0:A.code;N&&(T.$feature_flag_reason=N),S!=null&&(F=S.metadata)!=null&&F.id&&(T.$feature_flag_id=S.metadata.id),x(S?.original_variant)&&x(S?.original_enabled)||(T.$feature_flag_original_response=x(S.original_variant)?S.original_enabled:S.original_variant),S!=null&&(D=S.metadata)!=null&&D.original_payload&&(T.$feature_flag_original_payload=S==null||(M=S.metadata)==null?void 0:M.original_payload),$.length&&(T.$feature_flag_error=$.join(",")),this.za(T)}else n&&this.F({[Gt]:c,[Jn]:n});if(s)return{key:t,enabled:!!r,variant:typeof r=="string"?r:void 0,payload:Ya(o)}}}else this.rt.warn('getFeatureFlagResult for key "'+t+Lr)}za(t){try{var e;(e=this.nn)==null||e.capture("$feature_flag_called",t).catch((n=>{this.rt.error("Failed to capture feature flag call",n)}))}catch(n){this.rt.error("Failed to capture feature flag call",n)}}getRemoteConfigPayload(t,e){this.Wa(t,e)}Wa(t,e){var n=this;return X((function*(){var i=n.nn;if(i){var s={distinct_id:i.distinctId,token:i.projectToken,person_properties:{$lib:i.library.name,$lib_version:i.library.version}},r=n.Na();r.length&&(s.evaluation_contexts=r);var o,a=n.qa();x(a)||(s.flag_keys=a);try{var l,u=(l=(yield i.sendRequest("/flags/?v=2",{target:"flags",method:"POST",body:s,compression:n.Ne.compression==="base64"?xe.Base64:void 0,sentAt:"body",timeoutMs:n.Ne.requestTimeoutMs})).json)==null?void 0:l.featureFlagPayloads;o=u?.[t]||void 0}catch(c){return void n.rt.error("Remote config feature flag request failed",c)}try{e(o)}catch(c){n.rt.error("Remote config feature flag callback failed",c)}}}))()}isFeatureEnabled(t,e){if(e===void 0&&(e={}),e.fresh&&!this.ka)return e.defaultValue;if(!(this.ma||this.getFlags()&&this.getFlags().length>0))return this.rt.warn('isFeatureEnabled for key "'+t+Lr),e.defaultValue;var n=this.getFeatureFlag(t,e);return x(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.ja(t,e,n)}ja(t,e,n){if(this.nn){this.ma=!0;var i=(function(s,r,o,a,l,u){r===void 0&&(r={}),o===void 0&&(o={}),a===void 0&&(a={}),u===void 0&&(u=Ql);var c=((F,D)=>{var S=F.flags;return S?E({},F,{featureFlags:Object.fromEntries(Object.keys(S).map(($=>{var T;return[$,(T=S[$].variant)!==null&&T!==void 0?T:S[$].enabled]}))),featureFlagPayloads:Object.fromEntries(Object.keys(S).filter(($=>S[$].enabled)).filter(($=>{var T;return(T=S[$].metadata)==null?void 0:T.payload})).map(($=>{var T;return[$,(T=S[$].metadata)==null?void 0:T.payload]})))}):(F.featureFlags&&D.warn("Using an older version of the feature flags endpoint. Please upgrade your PostHog server to the latest version"),F)})(s,u),d=c.flags,h=c.featureFlags,p=c.featureFlagPayloads;if(h){var f=s.requestId,g=s.evaluatedAt;if(O(h)){u.warn("v1 of the feature flags endpoint is deprecated. Please use the latest version.");var m={};if(h)for(var v=0;h.length>v;v++)m[h[v]]=!0;return{[Vn]:h,[Wt]:m,[cs]:!1}}var b=h,w=p,I=d;if(l!=null&&l.partialResponse)b=E({},r,b),w=E({},o,w),I=E({},a,I);else if(s.errorsWhileComputingFlags)if(d){var A=new Set(Object.keys(d).filter((F=>{var D;return!((D=d[F])!=null&&D.failed)})));b=E({},r,Object.fromEntries(Object.entries(b).filter((F=>A.has(F[0]))))),w=E({},o,Object.fromEntries(Object.entries(w||{}).filter((F=>A.has(F[0]))))),I=E({},a,Object.fromEntries(Object.entries(I||{}).filter((F=>A.has(F[0])))))}else b=E({},r,b),w=E({},o,w),I=E({},a,I);return E({[Vn]:Object.keys(nc(b)),[Wt]:b||{},[Gn]:w||{},[oo]:I||{},[cs]:s.minimalFlagCalledEvents===!0},f?{[Ui]:f}:{},g?{[Xn]:g}:{})}})(t,this.getFlagVariants(),this.getFlagPayloads(),this.getFlagsWithDetails(),n,this.rt);i&&this.F(i),e||(this.xa=!1),this.Va(e)}}override(t,e){e===void 0&&(e=!1),this.rt.warn("override is deprecated. Please use overrideFeatureFlags instead."),this.overrideFeatureFlags({flags:t,suppressWarning:e})}overrideFeatureFlags(t){this.Za(t)}Za(t){if(this.nn){if(t===!1)return this.q([it,zt]),this.Va(),void Ut.info("All overrides cleared");if(O(t))return this.F({[it]:tc(t)}),this.Va(),void Ut.info("Flag overrides set",{flags:t});if(t&&typeof t=="object"&&("flags"in t||"payloads"in t)){var e,n=t;this.ca=!!((e=n.suppressWarning)!==null&&e!==void 0&&e);var i={},s=n.flags,r=n.payloads;return s&&(i[it]=O(s)?tc(s):s),r&&(i[zt]=r),Object.keys(i).length&&this.F(i),s===!1&&r===!1?this.q([it,zt]):s===!1?this.q(it):r===!1&&this.q(zt),this.Va(),s===!1?Ut.info("Flag overrides cleared"):s&&Ut.info("Flag overrides set",{flags:s}),void(r===!1?Ut.info("Payload overrides cleared"):r&&Ut.info("Payload overrides set",{payloads:r}))}if(t&&typeof t=="object")return this.F({[it]:t}),this.Va(),void Ut.info("Flag overrides set",{flags:t});this.rt.warn("Invalid overrideOptions provided to overrideFeatureFlags",{overrideOptions:t})}else this.rt.warn("posthog.featureFlags.overrideFeatureFlags called before feature flags were ready")}onFeatureFlags(t){if(this.addFeatureFlagsHandler(t),this.ma){var e=this.Ga(),n=e.flags,i=e.flagVariants;try{t(n,i)}catch(s){this.rt.error("Error while running feature flags callback",s)}}return()=>this.removeFeatureFlagsHandler(t)}updateEarlyAccessFeatureEnrollment(t,e,n){var i=(this.Oa(ji)||[]).find((l=>l.flagKey===t)),s={["$feature_enrollment/"+t]:e},r={$feature_flag:t,$feature_enrollment:e,$set:s};i&&(r.$early_access_feature_name=i.name),n&&(r.$feature_enrollment_stage=n);var o=E({},this.getFlagVariants(),{[t]:e});this.F({[Vn]:Object.keys(nc(o)),[Wt]:o,[ht]:E({},this.Oa(ht)||{},s)}),this.Va();try{var a;(a=this.nn)==null||a.capture("$feature_enrollment_update",r).catch((l=>{this.rt.error("Failed to capture early access feature enrollment",l)}))}catch(l){this.rt.error("Failed to capture early access feature enrollment",l)}}getEarlyAccessFeatures(t,e,n){e===void 0&&(e=!1);var i=this.Oa(ji);!i||e?this.Qa(t,n):t(i)}Qa(t,e){var n=this;return X((function*(){var i=n.nn;if(i){var s,r=e?"&"+e.map((a=>"stage="+a)).join("&"):"";try{var o=yield i.sendRequest("/api/early_access_features/?token="+i.projectToken+r,{target:"api",method:"GET",sentAt:"query"});if(!o.json)return;n.F({[ji]:s=o.json.earlyAccessFeatures})}catch(a){return void n.rt.error("Early access feature request failed",a)}try{t(s)}catch(a){n.rt.error("Early access feature callback failed",a)}}}))()}Ga(){var t=this.getFlags(),e=this.getFlagVariants();return{flags:t.filter((n=>e[n])),flagVariants:Object.keys(e).filter((n=>e[n])).reduce(((n,i)=>(n[i]=e[i],n)),{})}}Va(t){this.Fa();var e=this.Ga(),n=e.flags,i=e.flagVariants;this.featureFlagEventHandlers.forEach((s=>{try{s(n,i,{errorsLoading:t})}catch(r){this.rt.error("Error while running feature flags callback",r)}}))}setPersonPropertiesForFlags(t,e){e===void 0&&(e=!0),this.Ka(t,e)}Ka(t,e){e===void 0&&(e=!0);var n=this.Oa(ht)||{},i=t?.$set||(t!=null&&t.$set_once?{}:t),s=t?.$set_once,r={};if(s)for(var o in s)({}).hasOwnProperty.call(s,o)&&(o in n||(r[o]=s[o]));this.F({[ht]:E({},n,r,i)}),e&&this.reloadFeatureFlags()}unsetPersonPropertiesForFlags(t,e){e===void 0&&(e=!0);var n=E({},this.Oa(ht)||{});t.forEach((i=>{delete n[i]})),this.F({[ht]:n}),e&&this.reloadFeatureFlags()}resetPersonPropertiesForFlags(t){t===void 0&&(t=!0),this.q(ht),t&&this.reloadFeatureFlags()}setGroupPropertiesForFlags(t,e){e===void 0&&(e=!0);var n=this.Oa(qt)||{},i=E({},n);for(var s of Object.keys(t))i[s]=E({},n[s],t[s]);this.F({[qt]:i}),e&&this.reloadFeatureFlags()}resetGroupPropertiesForFlags(t){if(t){var e=this.Oa(qt)||{};this.F({[qt]:E({},e,{[t]:{}})})}else this.q(qt)}reset(){this.ba++,this.wa=!1,this.Fa(),this.ma=!1,this._a=!1,this.ka=!1,this.$anon_distinct_id=void 0,this.La(),this.ca=!1,this.Sa=0}}},Bf={sessionRecording:class{get Ne(){return this._instance.config}get Mr(){return this._instance.persistence}get started(){var t;return!((t=this.Ja)==null||!t.isStarted)}get status(){var t,e;return this.Ya===Un||this.Ya===Ni?this.Ya:(t=(e=this.Ja)==null?void 0:e.status)!==null&&t!==void 0?t:this.Ya}constructor(t){if(this._forceAllowLocalhostNetworkCapture=!1,this.Ya=Vl,this.Xa=void 0,this.eo=!1,this.io=(()=>{var e;if(C==null||!C.visibilityState||C.visibilityState==="visible")return!0;var n=_==null||(e=_.performance)==null||e.getEntriesByType==null?void 0:e.getEntriesByType("visibility-state");return!(n!=null&&n.length)||n.some((i=>i.name==="visible"))})(),this.Ie=()=>{var e;C?.visibilityState==="visible"&&(this.io=!0,(e=this.Ja)==null||e.setDocumentWasEverVisible==null||e.setDocumentWasEverVisible(!0))},this._instance=t,!this._instance.sessionManager)throw ut.error("started without valid sessionManager"),new Error(ko+" started without valid sessionManager. This is a bug.");if(this.Ne.cookieless_mode===gt)throw new Error(ko+' cannot be used with cookieless_mode="always"');C!=null&&C.addEventListener&&re(C,"visibilitychange",this.Ie)}initialize(){this.startIfEnabledOrStop()}dispose(){this.eo=!0,C==null||C.removeEventListener==null||C.removeEventListener("visibilitychange",this.Ie),this.stopRecording()}get ro(){var t,e=!((t=this._instance.get_property(Jt))==null||!t.enabled),n=!this.Ne.disable_session_recording,i=this.Ne.disable_session_recording||this._instance.consent.isOptedOut();return _&&e&&n&&!i}startIfEnabledOrStop(t){var e;if(!(this.eo||this.ro&&(e=this.Ja)!=null&&e.isStarted)){var n=!x(Object.assign)&&!x(Array.from);this.ro&&n?(this.no(t),ut.info("starting")):(this.Ya=Vl,this.stopRecording())}}no(t){var e,n,i;this.ro&&(this.Ya!==Un&&this.Ya!==Ni&&(this.Ya=Gl),R!=null&&(e=R.__PosthogExtensions__)!=null&&(e=e.rrweb)!=null&&e.record&&(n=R.__PosthogExtensions__)!=null&&n.initSessionRecording?this.so(t):(i=R.__PosthogExtensions__)==null||i.loadExternalDependency==null||i.loadExternalDependency(this._instance,this.ao,(s=>{if(s)return ut.error("could not load recorder",s);this.so(t)})))}stopRecording(){var t,e;(t=this.Xa)==null||t.call(this),this.Xa=void 0,(e=this.Ja)==null||e.stop()}oo(){var t,e;(t=this.Xa)==null||t.call(this),this.Xa=void 0,(e=this.Ja)==null||e.discard()}lo(){var t,e;(t=this.Mr)==null||t.unregister(ia),(e=this.Mr)==null||e.unregister(Eu)}uo(t,e){if(B(t))return null;var n,i=he(t)?t:parseFloat(t);return typeof(n=i)!="number"||!Number.isFinite(n)||0>n||n>1?(ut.warn(e+" must be between 0 and 1. Ignoring invalid value:",t),null):i}ho(t){if(this.Mr){var e,n,i=this.Mr,s=()=>{var r,o=t.sessionRecording===!1?void 0:t.sessionRecording,a=this.uo((r=this.Ne.session_recording)==null?void 0:r.sampleRate,"session_recording.sampleRate"),l=this.uo(o?.sampleRate,"remote config sampleRate"),u=a??l;B(u)&&this.lo();var c=o?.minimumDurationMilliseconds;i.register({[Jt]:E({cache_timestamp:Date.now(),enabled:!!o},o,{networkPayloadCapture:E({capturePerformance:t.capturePerformance},o?.networkPayloadCapture),canvasRecording:{enabled:o?.recordCanvas,fps:o?.canvasFps,quality:o?.canvasQuality},sampleRate:u,minimumDurationMilliseconds:x(c)?null:c,endpoint:o?.endpoint,triggerMatchType:o?.triggerMatchType,masking:o?.masking,urlTriggers:o?.urlTriggers,version:o?.version,triggerGroups:o?.triggerGroups})})};s(),(e=this.Xa)==null||e.call(this),this.Xa=(n=this._instance.sessionManager)==null?void 0:n.onSessionId(s)}}onRemoteConfig(t){var e=t.ok?t.config:void 0;return e&&"sessionRecording"in e?e.sessionRecording===!1?(this.ho(e),void this.oo()):(this.ho(e),void this.startIfEnabledOrStop()):(this.Ya===Un&&(this.Ya=Ni,ut.warn("config refresh failed, recording will not start until page reload")),void this.startIfEnabledOrStop())}log(t,e){var n;e===void 0&&(e="log"),(n=this.Ja)!=null&&n.log?this.Ja.log(t,e):ut.warn("log called before recorder was ready")}get ao(){var t,e,n=(t=this._instance)==null||(t=t.persistence)==null?void 0:t.get_property(Jt);return(n==null||(e=n.scriptConfig)==null?void 0:e.script)||"lazy-recorder"}do(){var t,e=this._instance.get_property(Jt);if(!e)return!1;try{t=typeof e=="object"?e:JSON.parse(e)}catch(n){return ut.warn("persisted remote config for session recording is invalid and will be ignored",n),!1}return!B(t.cache_timestamp)&&36e5>=Date.now()-t.cache_timestamp}so(t){var e,n,i;if(!this.eo){if((e=R.__PosthogExtensions__)==null||!e.initSessionRecording)return ut.warn("Called on script loaded before session recording is available. This can be caused by adblockers."),void this._instance.register_for_session({[Pu]:!0});var s;if(this.Ja||(this.Ja=(s=R.__PosthogExtensions__)==null?void 0:s.initSessionRecording(this._instance,this.io),this.Ja._forceAllowLocalhostNetworkCapture=this._forceAllowLocalhostNetworkCapture),!this.do())return this.Ya===Ni||this.Ya===Un?void 0:(this.Ya=Un,ut.info("persisted remote config is stale, requesting fresh config before starting"),void new td(this._instance).load());this.Ya=Gl,(n=(i=this.Ja).setDocumentWasEverVisible)==null||n.call(i,this.io),this.Ja.start(t)}}onRRwebEmit(t){var e;(e=this.Ja)==null||e.onRRwebEmit==null||e.onRRwebEmit(t)}overrideLinkedFlag(){var t,e;this.Ja||(e=this.Mr)==null||e.register({[xu]:!0}),(t=this.Ja)==null||t.overrideLinkedFlag()}overrideSampling(){var t,e;this.Ja||(e=this.Mr)==null||e.register({[Su]:!0}),(t=this.Ja)==null||t.overrideSampling()}overrideTrigger(t){var e,n;this.Ja||(n=this.Mr)==null||n.register({[t==="url"?ku:Iu]:!0}),(e=this.Ja)==null||e.overrideTrigger(t)}get sdkDebugProperties(){var t;return((t=this.Ja)==null?void 0:t.sdkDebugProperties)||{$recording_status:this.status}}tryAddCustomEvent(t,e){var n;return!((n=this.Ja)==null||!n.tryAddCustomEvent(t,e))}}},Df={autocapture:class{constructor(t){this.vo=!1,this.co=null,this.fo=!1,this.po=!1,this.instance=t,this.rageclicks=new Wl(t.config.rageclick),this.mo=null}initialize(){this.startIfEnabled()}get Ne(){var t,e,n=ne(this.instance.config.autocapture)?this.instance.config.autocapture:{};return n.url_allowlist=(t=n.url_allowlist)==null?void 0:t.map((i=>new RegExp(i))),n.url_ignorelist=(e=n.url_ignorelist)==null?void 0:e.map((i=>new RegExp(i))),n}yo(){if(this.isBrowserSupported()){if(_&&C){var t=n=>{n=n||_?.event;try{this.bo(n)}catch(i){Tr.error("Failed to capture event",i)}};if(re(C,"submit",t,{capture:!0}),re(C,"change",t,{capture:!0}),re(C,"click",t,{capture:!0}),this.Ne.capture_copied_text){var e=n=>{n=n||_?.event;try{this.bo(n,$r)}catch(i){Tr.error("Failed to capture copy/cut event",i)}};re(C,"copy",e,{capture:!0}),re(C,"cut",e,{capture:!0})}}}else Tr.info("Disabling Automatic Event Collection because this browser is not supported")}startIfEnabled(){this.isEnabled&&!this.vo&&(this.yo(),this.vo=!0)}onRemoteConfig(t){if(this.fo=!0,t.ok){var e=t.config;e.elementsChainAsString&&(this.po=e.elementsChainAsString);var n=e.autocapture_opt_out;Ye(n)&&(this.instance.persistence&&this.instance.persistence.register({[Qr]:n}),this.co=n),this.startIfEnabled()}else this.startIfEnabled()}setElementSelectors(t){this.mo=t}getElementSelectors(t){var e,n=[];return(e=this.mo)==null||e.forEach((i=>{var s=C?.querySelectorAll(i);s?.forEach((r=>{t===r&&n.push(i)}))})),n}get isEnabled(){var t,e,n=(t=this.instance.persistence)==null?void 0:t.props[Qr],i=this.co,s=this.instance.Qi()&&!this.fo;if($e(i)&&!Ye(n)&&!s)return!1;var r=(e=this.co)!==null&&e!==void 0?e:!!n;return!!this.instance.config.autocapture&&!r}bo(t,e){if(e===void 0&&(e="$autocapture"),this.isEnabled){var n,i=yr(t);Mu(i)&&(i=i.parentNode||null),e==="$autocapture"&&t.type==="click"&&t instanceof MouseEvent&&this.instance.config.rageclick&&(n=this.rageclicks)!=null&&n.isRageClick(t.clientX,t.clientY,t.timeStamp||new Date().getTime())&&yl(i,this.instance.config.rageclick)&&this.bo(t,"$rageclick");var s=e===$r;if(i&&(function(d,h,p,f,g,m){var v;if(!_||la(d)||p!=null&&p.url_allowlist&&!ml(p.url_allowlist,m)||p!=null&&p.url_ignorelist&&ml(p.url_ignorelist,m))return!1;if(p!=null&&p.dom_event_allowlist){var b=p.dom_event_allowlist;if(b&&!b.some((S=>h.type===S)))return!1}var w=Uu(d,f),I=w.parentIsUsefulElement,A=w.targetElementList;if(!(function(S,$){var T=$?.element_allowlist;if(x(T))return!0;var M,N=function(z){if(T.some((H=>z.tagName.toLowerCase()===H)))return{v:!0}};for(var P of S)if(M=N(P))return M.v;return!1})(A,p)||!mo(A,p?.css_selector_allowlist)||mo(A,(v=p?.css_selector_ignorelist)!==null&&v!==void 0?v:Mp))return!1;try{var F=_.getComputedStyle(d);if(F&&F.getPropertyValue("cursor")==="pointer"&&h.type==="click")return!0}catch{}var D=d.tagName.toLowerCase();switch(D){case"html":return!1;case"form":return(g||["submit"]).indexOf(h.type)>=0;case"input":case"select":case"textarea":return(g||["change","click"]).indexOf(h.type)>=0;default:return I?(g||["click"]).indexOf(h.type)>=0:(g||["click"]).indexOf(h.type)>=0&&(aa.indexOf(D)>-1||d.getAttribute("contenteditable")==="true")}})(i,t,this.Ne,s,s?["copy","cut"]:void 0,this.instance)){var r=Af(i,{e:t,maskAllElementAttributes:this.instance.config.mask_all_element_attributes,maskAllText:this.instance.config.mask_all_text,elementAttributeIgnoreList:this.Ne.element_attribute_ignorelist,elementsChainAsString:this.po,disableCaptureUrlHashes:this.instance.config.disable_capture_url_hashes}),o=r.props;if(r.explicitNoCapture)return!1;var a=this.getElementSelectors(i);if(a&&a.length>0&&(o.$element_selectors=a),e===$r){var l,u=Bu(_==null||(l=_.getSelection())==null?void 0:l.toString()),c=t.type||"clipboard";if(!u)return!1;o.$selected_content=u,o.$copy_type=c}return this.instance.capture(e,o),!0}}}isBrowserSupported(){return Se(C?.querySelectorAll)}},historyAutocapture:class{constructor(t){var e;this._instance=t,this._o=(_==null||(e=_.location)==null?void 0:e.pathname)||""}initialize(){this.startIfEnabled()}get isEnabled(){return this._instance.config.capture_pageview==="history_change"}startIfEnabled(){this.isEnabled&&(k.info("History API monitoring enabled, starting..."),this.monitorHistoryChanges())}stop(){this.wo&&this.wo(),this.wo=void 0,k.info("History API monitoring stopped")}monitorHistoryChanges(){_&&_.history&&(this.ko("pushState"),this.ko("replaceState"),this.xo())}ko(t){var e;if(_&&((e=_.history[t])==null||!e.__posthog_wrapped__)){var n=this;(function(i,s,r){try{if(!(s in i))return zl;var o={next:i[s]},a=r((function(){for(var l=arguments.length,u=new Array(l),c=0;l>c;c++)u[c]=arguments[c];return o.next.apply(this,u)}));return Se(a)&&(a.prototype=a.prototype||{},Object.defineProperties(a,{__posthog_wrapped__:{enumerable:!1,value:!0},__posthog_layer__:{enumerable:!1,value:o}})),i[s]=a,()=>{if(i[s]!==a)for(var l=i[s];Se(l)&&l.__posthog_layer__;){var u=l.__posthog_layer__;if(u.next===a)return void(u.next=o.next);l=u.next}else i[s]=o.next}}catch{return zl}})(_.history,t,(i=>function(s,r,o){i.call(this,s,r,o),n.So(t)}))}}So(t){try{var e,n=_==null||(e=_.location)==null?void 0:e.pathname;if(!n)return;n!==this._o&&this.isEnabled&&this._instance.capture(cn,{navigation_type:t}),this._o=n}catch(i){k.error("Error capturing "+t+" pageview",i)}}xo(){if(!this.wo){var t=()=>{this.So("popstate")};re(_,"popstate",t),this.wo=()=>{_&&_.removeEventListener("popstate",t)}}}},heatmaps:class{get Ne(){return this.instance.config}constructor(t){var e;this.Co=!1,this.vo=!1,this.Mo=null,this.instance=t,this.Co=!((e=this.instance.persistence)==null||!e.props[eo]),this.rageclicks=new Wl(t.config.rageclick)}initialize(){this.startIfEnabled()}get flushIntervalMilliseconds(){var t=5e3;return ne(this.Ne.capture_heatmaps)&&this.Ne.capture_heatmaps.flush_interval_milliseconds&&(t=this.Ne.capture_heatmaps.flush_interval_milliseconds),t}get isEnabled(){return B(this.Ne.capture_heatmaps)?B(this.Ne.enable_heatmaps)?this.Co:this.Ne.enable_heatmaps:this.Ne.capture_heatmaps!==!1}startIfEnabled(){if(this.isEnabled){if(this.vo)return;Pf.info("starting..."),this.To(),this.Ie()}else{var t;clearInterval((t=this.Mo)!==null&&t!==void 0?t:void 0),this.Eo(),this.getAndClearBuffer()}}onRemoteConfig(t){if(t.ok){var e=t.config;if("heatmaps"in e){var n=!!e.heatmaps;this.instance.persistence&&this.instance.persistence.register({[eo]:n}),this.Co=n,this.startIfEnabled()}}}getAndClearBuffer(){var t=this.R;return this.R=void 0,t}Io(t){Nr(t.originalEvent)&&this.ke(t.originalEvent,"deadclick")}Ie(){this.Mo&&clearInterval(this.Mo),this.Mo=C?.visibilityState==="visible"?setInterval(this.cr.bind(this),this.flushIntervalMilliseconds):null}To(){_&&C&&(this.Po=this.cr.bind(this),re(_,fs,this.Po),this.Ro=t=>this.ke(t||_?.event),re(C,"click",this.Ro,{capture:!0}),this.Ao=t=>this.Fo(t||_?.event),re(C,"mousemove",this.Ao,{capture:!0}),this.Lo=new Il(this.instance,Hp,this.Io.bind(this)),this.Lo.startIfEnabledOrStop(),this.Oo=this.Ie.bind(this),re(C,ps,this.Oo),this.vo=!0)}Eo(){var t;_&&C&&(this.Po&&_.removeEventListener(fs,this.Po),this.Ro&&C.removeEventListener("click",this.Ro,{capture:!0}),this.Ao&&C.removeEventListener("mousemove",this.Ao,{capture:!0}),this.Oo&&C.removeEventListener(ps,this.Oo),clearTimeout(this.Do),(t=this.Lo)==null||t.stop(),this.vo=!1)}$o(t,e){var n=this.instance.scrollManager.scrollY(),i=this.instance.scrollManager.scrollX(),s=this.instance.scrollManager.scrollElement(),r=(function(o,a,l){for(var u=o;u&&$t(u)&&!Me(u,"body");){if(u===l)return!1;var c=void 0;try{var d,h,p;c=(d=(h=(p=u.ownerDocument)==null?void 0:p.defaultView)!==null&&h!==void 0?h:_)==null?void 0:d.getComputedStyle(u).position}catch{return!1}if(L(a,c))return!0;u=Du(u)}return!1})(yr(t),["fixed","sticky"],s);return{x:t.clientX+(r?0:i),y:t.clientY+(r?0:n),target_fixed:r,type:e}}ke(t,e){var n;if(e===void 0&&(e="click"),!gl(t.target)&&Nr(t)){var i=this.$o(t,e);(n=this.rageclicks)!=null&&n.isRageClick(t.clientX,t.clientY,new Date().getTime())&&yl(yr(t),this.instance.config.rageclick)&&this.Vt(E({},i,{type:"rageclick"})),this.Vt(i)}}Fo(t){!gl(t.target)&&Nr(t)&&(clearTimeout(this.Do),this.Do=setTimeout((()=>{this.Vt(this.$o(t,"mousemove"))}),500))}Vt(t){if(_){var e=this.Ne.disable_capture_url_hashes?Pt(_.location.href):_.location.href,n=this.Ne.custom_personal_data_properties,i=this.Ne.mask_personal_data_properties?[...bn,...n||[]]:[],s=ci(e,i,ui);this.R=this.R||{},this.R[s]||(this.R[s]=[]),this.R[s].push(t)}}cr(){this.R&&!yt(this.R)&&this.instance.capture("$$heatmap",{$heatmap_data:this.getAndClearBuffer()})}},deadClicksAutocapture:Il,webVitalsAutocapture:class{constructor(t){var e;this.Co=!1,this.vo=!1,this.R={navigationKey:void 0,url:void 0,metrics:[],firstMetricTimestamp:void 0},this.No=()=>{clearTimeout(this.qo),this.qo=void 0,this.R.metrics.length!==0&&(this._instance.capture("$web_vitals",E({$current_url:this.R.url},this.R.metrics.reduce(((n,i)=>E({},n,{["$web_vitals_"+i.name+"_event"]:E({},i),["$web_vitals_"+i.name+"_value"]:i.value})),{}))),this.R={navigationKey:void 0,url:void 0,metrics:[],firstMetricTimestamp:void 0})},this.jo=n=>{var i;if(this.R=this.R||{navigationKey:void 0,url:void 0,metrics:[],firstMetricTimestamp:void 0},B(n?.name)||B(n?.value))jt.error("Invalid metric received",n);else{var s=typeof n.navigationURL=="string"?n.navigationURL:void 0,r=this.Bo(s);if(!x(r)){var o=he(n.navigationId)||typeof n.navigationId=="string"?"navigation:"+n.navigationId:"url:"+r;if(!this.Ho||this.Ho>n.value){this.R.navigationKey!==o&&(this.No(),this.qo=setTimeout(this.No,this.flushToCaptureTimeoutMs)),x(this.R.navigationKey)&&(this.R.navigationKey=o,this.R.url=r),this.R.firstMetricTimestamp=x(this.R.firstMetricTimestamp)?Date.now():this.R.firstMetricTimestamp,n.attribution&&n.attribution.interactionTargetElement&&(n.attribution.interactionTargetElement=void 0);var a=(i=this._instance.sessionManager)==null?void 0:i.checkAndGetSessionAndWindowId(!0),l=E({},n,s?{navigationURL:r}:{},{$current_url:r,timestamp:Date.now()});x(a)||(l.$session_id=a.sessionId,l.$window_id=a.windowId),this.R.metrics.push(l),this.R.metrics.length===this.allowedMetrics.length&&this.No()}else jt.error("Ignoring metric with value >= "+this.Ho,n)}}},this.Uo=()=>{if(!this.vo){var n,i,s,r,o=R.__PosthogExtensions__,a=o?.postHogWebVitalsCallbacksByFlavor,l=a?.[this.zo]||(this.zo==="web-vitals"&&x(a)?o?.postHogWebVitalsCallbacks:void 0);if(x(l)||(n=l.onLCP,i=l.onCLS,s=l.onFCP,r=l.onINP),n&&i&&s&&r){var u={reportSoftNavs:this.useSoftNavs};this.allowedMetrics.indexOf("LCP")>-1&&n(this.jo.bind(this),u),this.allowedMetrics.indexOf("CLS")>-1&&i(this.jo.bind(this),u),this.allowedMetrics.indexOf("FCP")>-1&&s(this.jo.bind(this),u),this.allowedMetrics.indexOf("INP")>-1&&r(this.jo.bind(this),u),this.vo=!0}else jt.error("web vitals callbacks not loaded - not starting")}},this._instance=t,this.Co=!((e=this._instance.persistence)==null||!e.props[so]),this.startIfEnabled()}get Wo(){return this._instance.config.capture_performance}get allowedMetrics(){var t,e,n=ne(this.Wo)?(t=this.Wo)==null?void 0:t.web_vitals_allowed_metrics:void 0;return B(n)?((e=this._instance.persistence)==null?void 0:e.props[ro])||["CLS","FCP","INP","LCP"]:n}get flushToCaptureTimeoutMs(){return(ne(this.Wo)?this.Wo.web_vitals_delayed_flush_ms:void 0)||5e3}get useAttribution(){var t=ne(this.Wo)?this.Wo.web_vitals_attribution:void 0;return t!=null&&t}get useSoftNavs(){var t=ne(this.Wo)?this.Wo.__preview_web_vitals_soft_navs:void 0;return t!=null&&t}get Ho(){var t=ne(this.Wo)&&he(this.Wo.__web_vitals_max_value)?this.Wo.__web_vitals_max_value:ql;return t>0&&6e4>=t?ql:t}get isEnabled(){var t=se?.protocol;if(t!=="http:"&&t!=="https:")return jt.info("Web Vitals are disabled on non-http/https protocols"),!1;var e=ne(this.Wo)?this.Wo.web_vitals:Ye(this.Wo)?this.Wo:void 0;return Ye(e)?e:this.Co}startIfEnabled(){this.isEnabled&&!this.vo&&(jt.info("enabled, starting..."),this.ai(this.Uo))}onRemoteConfig(t){if(t.ok){var e=t.config;if("capturePerformance"in e){var n=ne(e.capturePerformance)&&!!e.capturePerformance.web_vitals,i=ne(e.capturePerformance)?e.capturePerformance.web_vitals_allowed_metrics:void 0;this._instance.persistence&&(this._instance.persistence.register({[so]:n}),this._instance.persistence.register({[ro]:i})),this.Co=n,this.startIfEnabled()}}}get zo(){return this.useSoftNavs?this.useAttribution?"web-vitals-with-attribution-soft-navs":"web-vitals-soft-navs":this.useAttribution?"web-vitals-with-attribution":"web-vitals"}ai(t){var e=R.__PosthogExtensions__,n=this.zo,i=e?.postHogWebVitalsCallbacksByFlavor;i!=null&&i[n]||n==="web-vitals"&&x(i)&&e!=null&&e.postHogWebVitalsCallbacks?t():e==null||e.loadExternalDependency==null||e.loadExternalDependency(this._instance,n,(s=>{s?jt.error("failed to load script",s):t()}))}Bo(t){var e=t||_?.location.href;if(e){var n=this._instance.config.disable_capture_url_hashes?Pt(e):e,i=this._instance.config.custom_personal_data_properties,s=this._instance.config.mask_personal_data_properties?[...bn,...i||[]]:[];return ci(n,s,ui)}jt.error("Could not determine current URL")}}},jf={exceptionObserver:class{constructor(t){var e;this.Uo=()=>{var n;if(_&&this.isEnabled&&(n=R.__PosthogExtensions__)!=null&&n.errorWrappingFunctions){var i=R.__PosthogExtensions__.errorWrappingFunctions.wrapOnError,s=R.__PosthogExtensions__.errorWrappingFunctions.wrapUnhandledRejection,r=R.__PosthogExtensions__.errorWrappingFunctions.wrapConsoleError;try{!this.Vo&&this.Ne.capture_unhandled_errors&&(this.Vo=i(this.captureException.bind(this))),!this.Zo&&this.Ne.capture_unhandled_rejections&&(this.Zo=s(this.captureException.bind(this))),!this.Go&&this.Ne.capture_console_errors&&(this.Go=r(this.captureException.bind(this)))}catch(o){jn.error("failed to start",o),this.Qo()}}},this._instance=t,this.Ko=!((e=this._instance.persistence)==null||!e.props[to]),this.Jo=new Oh(E({},(function(n){var i,s,r,o;return n===void 0&&(n={}),{refillRate:(i=(s=n.exceptionRateLimiterRefillRate)!==null&&s!==void 0?s:n.__exceptionRateLimiterRefillRate)!==null&&i!==void 0?i:1,bucketSize:(r=(o=n.exceptionRateLimiterBucketSize)!==null&&o!==void 0?o:n.__exceptionRateLimiterBucketSize)!==null&&r!==void 0?r:10}})(this._instance.config.error_tracking),{refillInterval:1e4,rt:jn})),this.Ne=this.Yo(),this.startIfEnabledOrStop()}Yo(){var t=this._instance.config.capture_exceptions,e={capture_unhandled_errors:!1,capture_unhandled_rejections:!1,capture_console_errors:!1};return ne(t)?e=E({},e,t):(x(t)?this.Ko:t)&&(e=E({},e,{capture_unhandled_errors:!0,capture_unhandled_rejections:!0})),e}get isEnabled(){return this.Ne.capture_console_errors||this.Ne.capture_unhandled_errors||this.Ne.capture_unhandled_rejections}startIfEnabledOrStop(){this.isEnabled?(jn.info("enabled"),this.Qo(),this.ai(this.Uo)):this.Qo()}ai(t){var e,n;(e=R.__PosthogExtensions__)!=null&&e.errorWrappingFunctions?t():(n=R.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,"exception-autocapture",(i=>{if(i)return jn.error("failed to load script",i);t()}))}Qo(){var t,e,n;(t=this.Vo)==null||t.call(this),this.Vo=void 0,(e=this.Zo)==null||e.call(this),this.Zo=void 0,(n=this.Go)==null||n.call(this),this.Go=void 0}onRemoteConfig(t){if(t.ok){var e=t.config;"autocaptureExceptions"in e&&(this.Ko=!!e.autocaptureExceptions||!1,this._instance.persistence&&this._instance.persistence.register({[to]:this.Ko}),this.Ne=this.Yo(),this.startIfEnabledOrStop())}}onConfigChange(){this.Ne=this.Yo()}captureException(t){var e,n,i,s=(e=t==null||(n=t.$exception_list)==null||(n=n[0])==null?void 0:n.type)!==null&&e!==void 0?e:"Exception";this.Jo.consumeRateLimit(s)?jn.info("Skipping exception capture because of client rate limiting.",{exception:s}):(i=this._instance.exceptions)==null||i.sendExceptionEvent(t)}},exceptions:class{constructor(t){var e,n;this.Xo=[],this.tl=new ep([new lp,new vp,new up,new cp,new gp,new fp,new hp,new mp],(function(i){for(var s=arguments.length,r=new Array(s>1?s-1:0),o=1;s>o;o++)r[o-1]=arguments[o];return function(a,l){l===void 0&&(l=0);for(var u=[],c=a.split(` +`),d=l;c.length>d;d++){var h=c[d];if(1024>=h.length){var p=dl.test(h)?h.replace(dl,"$1"):h;if(!p.match(/\S*Error: /)){for(var f of r){var g=f(p,i);if(g){u.push(g);break}}if(u.length>=50)break}}}return(function(m){if(!m.length)return[];var v=Array.from(m);return v.reverse(),v.slice(0,50).map((b=>{return E({},b,{filename:b.filename||(w=v,w[w.length-1]||{}).filename,function:b.function||yn});var w}))})(u)}})("web:javascript",sp,ap)),this._instance=t,this.Xo=(e=(n=this._instance.persistence)==null?void 0:n.get_property(no))!==null&&e!==void 0?e:[],this.el=ls(this.il()),this.rl=new yp(this.el)}onConfigChange(){this.el=ls(this.il()),this.rl.setConfig(this.el)}onRemoteConfig(t){var e,n,i;if(t.ok){var s=t.config;if("errorTracking"in s){var r=(e=(n=s.errorTracking)==null?void 0:n.suppressionRules)!==null&&e!==void 0?e:[],o=(i=s.errorTracking)==null?void 0:i.captureExtensionExceptions;this.Xo=r,this._instance.persistence&&this._instance.persistence.register({[no]:this.Xo,[io]:o})}}}get nl(){var t,e=!!this._instance.get_property(io),n=this._instance.config.error_tracking.captureExtensionExceptions;return(t=n??e)!==null&&t!==void 0&&t}buildProperties(t,e){return this.tl.buildFromUnknown(t,{syntheticException:e?.syntheticException,mechanism:{handled:e?.handled}})}addExceptionStep(t,e){if(this.el.enabled)try{if(!q(t)||t.trim().length===0)return void tt.warn("Ignoring exception step because message must be a non-empty string");var n=(function(r){if(!r)return{sanitizedProperties:{},droppedKeys:[]};var o=[];return{sanitizedProperties:Object.keys(r).reduce(((a,l)=>_p.has(l)?(o.push(l),a):(a[l]=r[l],a)),{}),droppedKeys:o}})(this.sl(e)),i=n.sanitizedProperties,s=n.droppedKeys;s.length>0&&tt.warn("Ignoring reserved exception step fields",{droppedKeys:s}),this.rl.add(E({[os]:t,[as]:new Date().toISOString()},i))}catch(r){tt.error("Failed to add exception step. Ignoring breadcrumb.",r)}}sendExceptionEvent(t){try{var e=t.$exception_list;if(this.al(e)){if(this.ol(e))return this.ll("Exception dropped: matched a suppression rule"),void tt.info("Skipping exception capture because a suppression rule matched");if(!this.nl&&this.ul(e))return this.ll("Exception dropped: thrown by a browser extension"),void tt.info("Skipping exception capture because it was thrown by an extension");if(!this._instance.config.error_tracking.__capturePostHogExceptions&&this.hl(e))return this.ll("Exception dropped: thrown by the PostHog SDK"),void tt.info("Skipping exception capture because it was thrown by the PostHog SDK")}var n=this.el.enabled&&B(t.$exception_steps)?this.dl(t):t,i=typeof(r=globalThis._posthogReleaseId)=="string"&&r.length>0?r:void 0;i&&(n.$release_id=i);try{var s=this._instance.capture("$exception",n,{_noTruncate:!0,_batchKey:"exceptionEvent",Wn:!0});return s&&this.rl.clear(),s}catch(o){return tt.error("Failed to capture exception event. Dropping this exception.",o),void this.rl.clear()}}catch(o){return void tt.error("Failed to process exception event. Ignoring this exception.",o)}var r}dl(t){try{var e=this.rl.getAttachable();return e.length===0?t:E({},t,{$exception_steps:e})}catch(n){return tt.error("Failed to read buffered exception steps. Capturing exception without steps.",n),t}}ll(t){this.el.enabled&&this.rl.add({[os]:t,[as]:new Date().toISOString()})}sl(t){return ne(t)?E({},t):{}}il(){var t,e;return(t=(e=this._instance.config.error_tracking)==null?void 0:e.exception_steps)!==null&&t!==void 0?t:{}}ol(t){if(t.length===0)return!1;try{var e=t.reduce(((n,i)=>{var s=i.type,r=i.value;return q(s)&&s.length>0&&n.$exception_types.push(s),q(r)&&r.length>0&&n.$exception_values.push(r),n}),{$exception_types:[],$exception_values:[]});return this.Xo.some((n=>{var i=n.values.map((s=>{var r=gd[s.operator],o=e[s.key];if(!r||!o)return!1;var a=O(s.value)?s.value:[s.value];return a.length>0&&r(a,o)}));return n.type==="OR"?i.some(Boolean):i.every(Boolean)}))}catch(n){return tt.warn("Failed to evaluate suppression rules. Capturing the exception.",n),!1}}ul(t){return t.flatMap((e=>{var n,i;return(n=(i=e.stacktrace)==null?void 0:i.frames)!==null&&n!==void 0?n:[]})).some((e=>e.filename&&e.filename.startsWith("chrome-extension://")))}hl(t){if(t.length>0){var e,n,i,s,r=(e=(n=t[0].stacktrace)==null?void 0:n.frames)!==null&&e!==void 0?e:[],o=r[r.length-1];return(i=o==null||(s=o.filename)==null?void 0:s.includes("posthog.com/static"))!==null&&i!==void 0&&i}return!1}al(t){return!B(t)&&O(t)}}},Uf=E({productTours:class{get Mr(){return this._instance.persistence}constructor(t){this.vl=null,this.cl=null,this._instance=t}initialize(){this.loadIfEnabled()}onRemoteConfig(t){if(t.ok){var e=t.config;if("productTours"in e){var n,i;if(this.Mr&&this.Mr.register({[na]:!!e.productTours}),!Mr(this._instance))return!this.vl&&B((n=this.Mr)==null?void 0:n.props[Kn])||Mi.info("product tours disabled; stopping and clearing cached tours"),(i=this.vl)==null||i.stop(),this.vl=null,void this.clearCache();this.loadIfEnabled()}}}loadIfEnabled(){!this.vl&&Mr(this._instance)&&this.ai((()=>this.fl()))}ai(t){var e,n;(e=R.__PosthogExtensions__)!=null&&e.generateProductTours?t():(n=R.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,"product-tours",(i=>{i?Mi.error("Could not load product tours script",i):t()}))}fl(){var t;!this.vl&&(t=R.__PosthogExtensions__)!=null&&t.generateProductTours&&(this.vl=R.__PosthogExtensions__.generateProductTours(this._instance,!0))}getProductTours(t,e){if(e===void 0&&(e=!1),!O(this.cl)||e){var n=this.Mr;if(n){var i=n.props[Kn];if(O(i)&&!e)return this.cl=i,void t(i,{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:s=>{if(Mr(this._instance)){var r=s.statusCode;if(r!==200||!s.json){var o="Product Tours API could not be loaded, status: "+r;return r===0?s.error||Mi.warn(o):Mi.error(o),void t([],{isLoaded:!1,error:o})}var a=O(s.json.product_tours)?s.json.product_tours:[];this.cl=a,n&&n.register({[Kn]:a}),t(a,{isLoaded:!0})}else t([],{isLoaded:!0})}})}else t(this.cl,{isLoaded:!0})}getActiveProductTours(t){B(this.vl)?t([],{isLoaded:!1,error:"Product tours not loaded"}):this.vl.getActiveProductTours(t)}showProductTour(t){var e;(e=this.vl)==null||e.showTourById(t)}previewTour(t){this.vl?this.vl.previewTour(t):this.ai((()=>{var e;this.fl(),(e=this.vl)==null||e.previewTour(t)}))}dismissProductTour(){var t;(t=this.vl)==null||t.dismissTour("user_clicked_skip")}nextStep(){var t;(t=this.vl)==null||t.nextStep()}previousStep(){var t;(t=this.vl)==null||t.previousStep()}clearCache(){var t;this.cl=null,(t=this.Mr)==null||t.unregister(Kn)}resetTour(t){var e;(e=this.vl)==null||e.resetTour(t)}resetAllTours(){var t;(t=this.vl)==null||t.resetAllTours()}cancelPendingTour(t){var e;(e=this.vl)==null||e.cancelPendingTour(t)}}},Us),Hf={siteApps:class{constructor(t){this.pl=0,this._instance=t,this.gl=[],this.apps={}}get isEnabled(){return!!this._instance.config.opt_in_site_apps}ml(t,e){if(e){var n=this.globalsForEvent(e);this.gl.push(n),this.gl.length>1e3&&(this.gl=this.gl.slice(10))}}get siteAppLoaders(){var t;return(t=R._POSTHOG_REMOTE_CONFIG)==null||(t=t[this._instance.config.token])==null?void 0:t.siteApps}initialize(){if(this.isEnabled){var t=this._instance._addCaptureHook(this.ml.bind(this));this.yl=()=>{t(),this.gl=[],this.yl=void 0}}}globalsForEvent(t){var e,n,i,s,r,o,a;if(!t)throw new Error("Event payload is required");var l={},u=this._instance.get_property("$groups")||[],c=this._instance.get_property("$stored_group_properties")||{};for(var d of Object.entries(c)){var h=d[0];l[h]={id:u[h],type:h,properties:d[1]}}var p=t.$set_once,f=t.$set;return{event:E({},jc(t,$f),{properties:E({},t.properties,f?{$set:E({},(e=(n=t.properties)==null?void 0:n.$set)!==null&&e!==void 0?e:{},f)}:{},p?{$set_once:E({},(i=(s=t.properties)==null?void 0:s.$set_once)!==null&&i!==void 0?i:{},p)}:{}),elements_chain:(r=(o=t.properties)==null?void 0:o.$elements_chain)!==null&&r!==void 0?r:"",distinct_id:(a=t.properties)==null?void 0:a.distinct_id}),person:{properties:this._instance.get_property("$stored_person_properties")},groups:l}}bl(t){var e,n=(e=t.tagName)==null?void 0:e.toLowerCase();return n==="style"&&this._instance.config.prepare_external_dependency_stylesheet?this._instance.config.prepare_external_dependency_stylesheet(t)||(et.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)||(et.error("prepare_external_dependency_script returned null"),null):t}_l(){var t,e,n,i,s,r,o,a;if(!this._instance.config.prepare_external_dependency_stylesheet&&!this._instance.config.prepare_external_dependency_script)return()=>{};var l=C?.defaultView,u=l==null||(t=l.Node)==null?void 0:t.prototype;if(!l||!u)return()=>{};if(this.pl++,this.wl)return this.kl();var c=[],d=this,h=new WeakSet,p=(m,v,b)=>{if(m!=null&&m[v]){var w=m[v];m[v]=b(w),c.push((()=>{m[v]=w}))}},f=m=>{if(h.has(m))return m;var v=d.bl(m);return v&&h.add(v),v},g=m=>m.map((v=>typeof v=="string"?v:f(v))).filter((v=>!$e(v)));return p(u,"appendChild",(m=>function(v){var b=f(v);return b?m.call(this,b):v})),p(u,"insertBefore",(m=>function(v,b){var w=f(v);return w?m.call(this,w,b):v})),p(u,"replaceChild",(m=>function(v,b){var w=f(v);return w?m.call(this,w,b):b})),[(e=l.Element)==null?void 0:e.prototype,(n=l.Document)==null?void 0:n.prototype,(i=l.DocumentFragment)==null?void 0:i.prototype].forEach((m=>{p(m,"append",(v=>function(){for(var b=arguments.length,w=new Array(b),I=0;b>I;I++)w[I]=arguments[I];return v.apply(this,g(w))})),p(m,"prepend",(v=>function(){for(var b=arguments.length,w=new Array(b),I=0;b>I;I++)w[I]=arguments[I];return v.apply(this,g(w))}))})),[(s=l.Element)==null?void 0:s.prototype,(r=l.CharacterData)==null?void 0:r.prototype,(o=l.DocumentType)==null?void 0:o.prototype].forEach((m=>{p(m,"before",(v=>function(){for(var b=arguments.length,w=new Array(b),I=0;b>I;I++)w[I]=arguments[I];return v.apply(this,g(w))})),p(m,"after",(v=>function(){for(var b=arguments.length,w=new Array(b),I=0;b>I;I++)w[I]=arguments[I];return v.apply(this,g(w))})),p(m,"replaceWith",(v=>function(){for(var b=arguments.length,w=new Array(b),I=0;b>I;I++)w[I]=arguments[I];var A=g(w);return w.length&&!A.length?void 0:v.apply(this,A)}))})),p((a=l.Element)==null?void 0:a.prototype,"insertAdjacentElement",(m=>function(v,b){var w=f(b);return w?m.call(this,v,w):null})),this.wl=()=>{c.forEach((m=>m())),this.wl=void 0},this.kl()}kl(){var t=!1;return()=>{var e;t||(t=!0,this.pl--,this.pl===0&&((e=this.wl)==null||e.call(this)))}}xl(t,e){e===void 0&&(e=!0);var n=this._l();try{var i=t(n);return e&&n(),i}catch(s){throw n(),s}}setupSiteApp(t){var e=this.apps[t.id],n=()=>{var o;!e.errored&&this.gl.length&&(et.info("Processing "+this.gl.length+" events for site app with id "+t.id),this.gl.forEach((a=>this.xl((()=>e.processEvent==null?void 0:e.processEvent(a))))),e.processedBuffer=!0),Object.values(this.apps).every((a=>a.processedBuffer||a.errored))&&((o=this.yl)==null||o.call(this))},i=!1,s=o=>{e.errored=!o,e.loaded=!0,et.info("Site app with id "+t.id+" "+(o?"loaded":"errored")),i&&n()};try{var r=this.xl((o=>t.init({posthog:this._instance,callback(a){o(),s(a)}})),!1).processEvent;r&&(e.processEvent=r),i=!0}catch(o){et.error(Kl+t.id,o),s(!1)}if(i&&e.loaded)try{n()}catch(o){et.error("Error while processing buffered events PostHog app with config id "+t.id,o),e.errored=!0}}Sl(){var t=this.siteAppLoaders||[];for(var e of t)this.apps[e.id]={id:e.id,loaded:!1,errored:!1,processedBuffer:!1};for(var n of t)this.setupSiteApp(n)}Cl(t){var e=this;if(Object.keys(this.apps).length!==0){var n=this.globalsForEvent(t),i=function(r){try{e.xl((()=>r.processEvent==null?void 0:r.processEvent(n)))}catch(o){et.error("Error while processing event "+t.event+" for site app "+r.id,o)}};for(var s of Object.values(this.apps))i(s)}}onRemoteConfig(t){var e,n,i,s=this;if((e=this.siteAppLoaders)!=null&&e.length)return this.isEnabled?(this.Sl(),void this._instance.on("eventCaptured",(l=>this.Cl(l)))):void et.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.');if((n=this.yl)==null||n.call(this),t.ok){var r=t.config;if((i=r.siteApps)!=null&&i.length)if(this.isEnabled){var o=function(){var l,u=a.id,c=a.url;R["__$$ph_site_app_"+u]=s._instance,(l=R.__PosthogExtensions__)==null||l.loadSiteApp==null||l.loadSiteApp(s._instance,c,(d=>{if(d)return et.error(Kl+u,d)}))};for(var a of r.siteApps)o()}else et.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.')}}}},Wf={tracingHeaders:class{constructor(t){this.Ml=void 0,this.Tl=void 0,this.El=void 0,this.Uo=()=>{var e,n,i=this.Il();i?(x(this.Ml)&&(this.Ml=(e=R.__PosthogExtensions__)==null||(e=e.tracingHeadersPatchFns)==null?void 0:e._patchXHR(i,(()=>this._instance.get_distinct_id()),this._instance.sessionManager)),x(this.Tl)&&(this.Tl=(n=R.__PosthogExtensions__)==null||(n=n.tracingHeadersPatchFns)==null?void 0:n._patchFetch(i,(()=>this._instance.get_distinct_id()),this._instance.sessionManager))):this.Qo()},this._instance=t}initialize(){this.startIfEnabledOrStop()}ai(t){var e,n;(e=R.__PosthogExtensions__)!=null&&e.tracingHeadersPatchFns?t():(n=R.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,"tracing-headers",(i=>{if(i)return Ff.error("failed to load script",i);t()}))}Pl(){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}Il(){var t=this.Pl();return O(t)?(O(this.El)?this.El.splice(0,this.El.length,...t):this.El=[...t],t.length>0?this.El:void 0):(O(this.El)&&this.El.splice(0),this.El=t||void 0,this.El)}Qo(){var t,e;(t=this.Ml)==null||t.call(this),(e=this.Tl)==null||e.call(this),this.Ml=void 0,this.Tl=void 0}startIfEnabledOrStop(){this.Il()?this.ai(this.Uo):this.Qo()}}},zf=E({surveys:class{get Ne(){return this._instance.config}constructor(t){this.Rl=void 0,this._surveyManager=null,this.Al=!1,this.Fl=[],this.Ll=null,this.Ol=null,this._instance=t,this._surveyEventReceiver=null}initialize(){this.loadIfEnabled()}onRemoteConfig(t){if(!this.Ne.disable_surveys){if(!t.ok)return G.warn("Remote config unavailable. Not loading surveys.");var e=t.config.surveys;if(B(e))return G.warn("Flags not loaded yet. Not loading surveys.");var n=O(e);this.Rl=n?e.length>0:e,G.info("flags response received, isSurveysEnabled: "+this.Rl),this.loadIfEnabled()}}reset(){try{var t;(t=this._surveyEventReceiver)==null||t.reset(),localStorage.removeItem("lastSeenSurveyDate");for(var e=[],n=0;nlocalStorage.removeItem(s)))}catch{}}loadIfEnabled(){if(!this._surveyManager)if(this.Al)G.info("Already initializing surveys, skipping...");else if(this.Ne.disable_surveys)G.info(Jl);else if(this.Ne.cookieless_mode&&this._instance.consent.isOptedOut())G.info("Not loading surveys in cookieless mode without consent.");else{var t=R?.__PosthogExtensions__;if(t){if(!x(this.Rl)||this.Ne.advanced_enable_surveys){var e=this.Rl||this.Ne.advanced_enable_surveys;this.Al=!0;try{var n=t.generateSurveys;if(n)return void this.Dl(n,e);var i=t.loadExternalDependency;if(!i)return void this.$l(sa);i(this._instance,"surveys",(s=>{s||!t.generateSurveys?this.$l("Could not load surveys script",s):this.Dl(t.generateSurveys,e)}))}catch(s){throw this.$l("Error initializing surveys",s),s}finally{this.Al=!1}}}else G.error("PostHog Extensions not found.")}}Dl(t,e){this._surveyManager=t(this._instance,e),this._surveyEventReceiver=new Nf(this._instance),G.info("Surveys loaded successfully"),this.Nl({isLoaded:!0})}$l(t,e){G.error(t,e),this.Nl({isLoaded:!1,error:t})}onSurveysLoaded(t){return this.Fl.push(t),this._surveyManager&&this.Nl({isLoaded:!0}),()=>{this.Fl=this.Fl.filter((e=>e!==t))}}getSurveys(t,e){if(e===void 0&&(e=!1),this.Ne.disable_surveys)return G.info(Jl),t([]);var n,i=this._instance.get_property(ao);if(i&&!e)return t(i,{isLoaded:!0}),void(this.ql()&&this.getSurveys((()=>{}),!0));typeof Promise<"u"&&this.Ll?this.Ll.then((s=>t(s.surveys,s.context))):(typeof Promise<"u"&&(this.Ll=new Promise((s=>{n=s}))),this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/surveys/?token="+this.Ne.token),method:"GET",timestampMode:"query",timeout:this.Ne.surveys_request_timeout_ms,callback:s=>{var r;this.Ll=null;var o=s.statusCode;if(o!==200||!s.json){var a="Surveys API could not be loaded, status: "+o;o!==0?G.error(a):s.error||G.warn(a),this.Ol=Date.now();var l={isLoaded:!1,error:a};return t([],l),void(n==null||n({surveys:[],context:l}))}this.Ol=null;var u,c=s.json.surveys||[],d=c.filter((p=>(function(f){return!(!f.start_date||f.end_date)})(p)&&(vd(p)||(function(f){var g;return!((g=f.conditions)==null||(g=g.actions)==null||(g=g.values)==null||!g.length)})(p))));d.length>0&&((u=this._surveyEventReceiver)==null||u.register(d)),(r=this._instance.persistence)==null||r.register({[ao]:c,[us]:Date.now()});var h={isLoaded:!0};t(c,h),n?.({surveys:c,context:h})}}))}ql(){return this.jl()&&!this.Ll&&!this.Bl()}jl(){var t=this._instance.get_property(us);return he(t)&&Date.now()-t>3e5}Bl(){return he(this.Ol)&&3e5>Date.now()-this.Ol}markSurveyAsSeen(t,e){var n,i={id:t,current_iteration:(n=e?.iteration)!==null&&n!==void 0?n:null};yd(i);try{localStorage.setItem("lastSeenSurveyDate",new Date().toISOString())}catch{}}Nl(t){for(var e of this.Fl)try{if(!t.isLoaded)return e([],t);this.getSurveys(e)}catch(n){G.error("Error in survey callback",n)}}getActiveMatchingSurveys(t,e){if(e===void 0&&(e=!1),!B(this._surveyManager))return this._surveyManager.getActiveMatchingSurveys(t,e);G.warn("init was not called")}Hl(t){var e=null;return this.getSurveys((n=>{var i;e=(i=n.find((s=>s.id===t)))!==null&&i!==void 0?i:null})),e}Ul(t){if(B(this._surveyManager))return{eligible:!1,reason:Li};var e=typeof t=="string"?this.Hl(t):t;return e?this._surveyManager.checkSurveyEligibility(e):{eligible:!1,reason:"Survey not found"}}zl(t){if(B(this._surveyManager))return{eligible:!1,reason:Li};var e=typeof t=="string"?this.Hl(t):t;return e?this._surveyManager.checkSurveyRenderability(e):{eligible:!1,reason:"Survey not found"}}canRenderSurvey(t){if(B(this._surveyManager))return G.warn("init was not called"),{visible:!1,disabledReason:Li};var e=this.zl(t);return{visible:e.eligible,disabledReason:e.reason}}canRenderSurveyAsync(t,e){return B(this._surveyManager)?(G.warn("init was not called"),Promise.resolve({visible:!1,disabledReason:Li})):new Promise((n=>{this.getSurveys((i=>{var s,r=(s=i.find((a=>a.id===t)))!==null&&s!==void 0?s:null;if(r){var o=this.zl(r);n({visible:o.eligible,disabledReason:o.reason})}else n({visible:!1,disabledReason:"Survey not found"})}),e)}))}renderSurvey(t,e,n){var i;if(B(this._surveyManager))G.warn("init was not called");else{var s=typeof t=="string"?this.Hl(t):t;if(s!=null&&s.id)if(mf.includes(s.type)){var r=C?.querySelector(e);if(r)return(i=s.appearance)!=null&&i.surveyPopupDelaySeconds?(G.info("Rendering survey "+s.id+" with delay of "+s.appearance.surveyPopupDelaySeconds+" seconds"),void setTimeout((()=>{var o,a;G.info("Rendering survey "+s.id+" with delay of "+((o=s.appearance)==null?void 0:o.surveyPopupDelaySeconds)+" seconds"),(a=this._surveyManager)==null||a.renderSurvey(s,r,n),G.info("Survey "+s.id+" rendered")}),1e3*s.appearance.surveyPopupDelaySeconds)):void this._surveyManager.renderSurvey(s,r,n);G.warn("Survey element not found")}else G.warn("Surveys of type "+s.type+" cannot be rendered in the app");else G.warn("Survey not found")}}displaySurvey(t,e){var n;if(B(this._surveyManager))G.warn("init was not called");else{var i=this.Hl(t);if(i){var s=i;if((n=i.appearance)!=null&&n.surveyPopupDelaySeconds&&e.ignoreDelay&&(s=E({},i,{appearance:E({},i.appearance,{surveyPopupDelaySeconds:0})})),e.displayType!==_o.Popover&&e.initialResponses&&G.warn("initialResponses is only supported for popover surveys. prefill will not be applied."),e.ignoreConditions===!1){var r=this.Ul(i);if(!r.eligible)return void G.warn("Survey is not eligible to be displayed: ",r.reason)}e.displayType!==_o.Inline?this._surveyManager.handlePopoverSurvey(s,e):this.renderSurvey(s,e.selector,e.properties)}else G.warn("Survey not found")}}cancelPendingSurvey(t){B(this._surveyManager)?G.warn("init was not called"):this._surveyManager.cancelSurvey(t)}handlePageUnload(){var t;(t=this._surveyManager)==null||t.handlePageUnload==null||t.handlePageUnload()}}},Us),qf={toolbar:class{constructor(t){this.instance=t}Wl(t){R.ph_toolbar_state=t}Vl(){var t;return(t=R.ph_toolbar_state)!==null&&t!==void 0?t:0}initialize(){return this.maybeLoadToolbar()}maybeLoadToolbar(t,e,n){if(t===void 0&&(t=void 0),e===void 0&&(e=void 0),n===void 0&&(n=void 0),go(this.instance.config)||!_||!C)return!1;t=t??_.location,n=n??_.history;try{if(!e){try{_.localStorage.setItem("test","test"),_.localStorage.removeItem("test")}catch{return!1}e=_?.localStorage}var i,s=Mf||_s(t.hash,"__posthog")||_s(t.hash,"state"),r=s?pl((()=>JSON.parse(atob(decodeURIComponent(s)))))||pl((()=>JSON.parse(decodeURIComponent(s)))):null;return r&&r.action==="ph_authorize"?((i=r).source="url",i&&Object.keys(i).length>0&&(r.desiredHash?t.hash=r.desiredHash:n?n.replaceState(n.state,"",t.pathname+t.search):t.hash="")):((i=JSON.parse(e.getItem(Yl)||"{}")).source="localstorage",delete i.userIntent),!(!i.token||this.instance.config.token!==i.token||(this.loadToolbar(i),0))}catch{return!1}}Zl(t){var e=R.ph_load_toolbar||R.ph_load_editor;!B(e)&&Se(e)?e(t,this.instance):Zl.warn("No toolbar load function found")}loadToolbar(t){var e=!(C==null||!C.getElementById(Nu));if(!_||e)return!1;var n=this.instance.requestRouter.region==="custom"&&this.instance.config.advanced_disable_toolbar_metrics,i=E({token:this.instance.config.token},t,{apiURL:this.instance.requestRouter.endpointFor("ui")},n?{instrument:!1}:{});if(_.localStorage.setItem(Yl,JSON.stringify(E({},i,{source:void 0}))),this.Vl()===2)this.Zl(i);else if(this.Vl()===0){var s;this.Wl(1),(s=R.__PosthogExtensions__)==null||s.loadExternalDependency==null||s.loadExternalDependency(this.instance,"toolbar",(r=>{if(r)return Zl.error("[Toolbar] Failed to load",r),void this.Wl(0);this.Wl(2),this.Zl(i)})),re(_,"turbolinks:load",(()=>{this.Wl(0),this.loadToolbar(i)}))}return!0}Gl(t){return this.loadToolbar(t)}maybeLoadEditor(t,e,n){return t===void 0&&(t=void 0),e===void 0&&(e=void 0),n===void 0&&(n=void 0),this.maybeLoadToolbar(t,e,n)}}},Vf=E({experiments:ye},Us),Gf={conversations:class{constructor(t){this.Ql=void 0,this._conversationsManager=null,this.Kl=!1,this.Jl=null,this.Yl=!1,this._instance=t}initialize(){this.loadIfEnabled()}onRemoteConfig(t){if(!this._instance.config.disable_conversations&&(this.Xl=t.ok,t.ok)){var e=t.config.conversations;B(e)||(Ye(e)?this.Ql=e:(this.Ql=e.enabled,this.Jl=e),this.loadIfEnabled())}}reset(){var t;(t=this._conversationsManager)==null||t.reset(),this._conversationsManager=null,this.Ql=void 0,this.Jl=null,this.Xl=void 0,this.Yl=!1}loadIfEnabled(){if(!(this._conversationsManager||this.Kl||this._instance.config.disable_conversations||go(this._instance.config)||this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut())){var t=R?.__PosthogExtensions__;if(t&&!x(this.Ql)&&this.Ql)if(this.Jl&&this.Jl.token){this.Kl=!0;try{var e=t.initConversations;if(e)return this.tu(e),void(this.Kl=!1);var n=t.loadExternalDependency;if(!n)return void this.eu(sa);n(this._instance,"conversations",(i=>{i||!t.initConversations?this.eu("Could not load conversations script",i):this.tu(t.initConversations),this.Kl=!1}))}catch(i){this.eu("Error initializing conversations",i),this.Kl=!1}}else Ue.error("Conversations enabled but missing token in remote config.")}}tu(t){if(this.Jl)try{this._conversationsManager=t(this.Jl,this._instance),this.Yl=!1,Ue.info("Conversations loaded successfully")}catch(e){this.eu("Error completing conversations initialization",e)}else Ue.error("Cannot complete initialization: remote config is null")}eu(t,e){Ue.error(t,e),this._conversationsManager=null,this.Kl=!1,this.Yl=!0}show(){this._conversationsManager?this._conversationsManager.show():Ue.warn("Conversations not loaded yet.")}hide(){this._conversationsManager&&this._conversationsManager.hide()}isAvailable(){return this.Ql===!0&&!$e(this._conversationsManager)}getUnavailableReason(){return this.isAvailable()?null:this._instance.config.disable_conversations?"disabled_by_config":go(this._instance.config)?"disabled_for_toolbar":this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut()?"consent_opted_out":this.Xl===!1?"remote_config_failed":x(this.Ql)?this.Xl?"disabled_in_project":"remote_config_pending":this.Ql?B(this.Jl)||!this.Jl.token?"missing_token":R!=null&&R.__PosthogExtensions__?this.Kl?"initializing":this.Yl?"load_failed":"not_loaded":"extensions_unavailable":"disabled_in_project"}isVisible(){var t,e;return(t=(e=this._conversationsManager)==null?void 0:e.isVisible())!==null&&t!==void 0&&t}sendMessage(t,e,n){var i=this;return X((function*(){return i._conversationsManager?i._conversationsManager.sendMessage(t,e,n):(Ue.warn(Ht),null)}))()}getMessages(t,e){var n=this;return X((function*(){return n._conversationsManager?n._conversationsManager.getMessages(t,e):(Ue.warn(Ht),null)}))()}markAsRead(t){var e=this;return X((function*(){return e._conversationsManager?e._conversationsManager.markAsRead(t):(Ue.warn(Ht),null)}))()}getTickets(t){var e=this;return X((function*(){return e._conversationsManager?e._conversationsManager.getTickets(t):(Ue.warn(Ht),null)}))()}requestRestoreLink(t){var e=this;return X((function*(){return e._conversationsManager?e._conversationsManager.requestRestoreLink(t):(Ue.warn(Ht),null)}))()}restoreFromToken(t){var e=this;return X((function*(){return e._conversationsManager?e._conversationsManager.restoreFromToken(t):(Ue.warn(Ht),null)}))()}restoreFromUrlToken(){var t=this;return X((function*(){return t._conversationsManager?t._conversationsManager.restoreFromUrlToken():(Ue.warn(Ht),null)}))()}getCurrentTicketId(){var t,e;return(t=(e=this._conversationsManager)==null?void 0:e.getCurrentTicketId())!==null&&t!==void 0?t:null}getWidgetSessionId(){var t,e;return(t=(e=this._conversationsManager)==null?void 0:e.getWidgetSessionId())!==null&&t!==void 0?t:null}Xn(){var t;(t=this._conversationsManager)==null||t.setIdentity()}ts(){var t;(t=this._conversationsManager)==null||t.clearIdentity()}}},Kf={logs:class{constructor(t){var e,n=this;this.iu=!1,this.ru=!1,this.rt=ie("[logs]"),this.nu=E({},this.rt,{error(){for(var i=arguments.length,s=new Array(i),r=0;i>r;r++)s[r]=arguments[r];s.some(rc)||n.rt.error(...s)}}),this.tr=[],this.su=[],this.Sa=0,this.au=()=>{var i,s;this.Sa=0,(i=this.ou)==null||i.onReconnect(),(s=this.lu)==null||s.onReconnect()},this._instance=t,this._instance&&(e=this._instance.config.logs)!=null&&e.captureConsoleLogs&&(this.iu=!0),_&&re(_,"online",this.au)}uu(t,e,n,i){var s,r=(function(o,a){var l,u,c,d,h,p,f,g=(l=o?.flushIntervalMs)!==null&&l!==void 0?l:3e3,m=(u=o?.maxBufferSize)!==null&&u!==void 0?u:100,v=a!=null&&a.consoleCapture?void 0:(c=o?.maxLogsPerInterval)!==null&&c!==void 0?c:1e3,b=x(v)?Math.max(m,2048):Math.max(m,v),w=o?.resourceAttributes;return{serviceName:(d=(h=w?.["service.name"])!==null&&h!==void 0?h:o?.serviceName)!==null&&d!==void 0?d:a?.serviceNameDefault,serviceVersion:(p=w?.["service.version"])!==null&&p!==void 0?p:o?.serviceVersion,environment:(f=w?.["deployment.environment"])!==null&&f!==void 0?f:o?.environment,resourceAttributes:w,beforeSend:o?.beforeSend,flushIntervalMs:g,maxBufferSize:m,maxQueueSize:b,maxBatchRecordsPerPost:100,rateCapWindowMs:g,maxLogsPerInterval:v,backgroundFlushBudgetMs:0,terminationFlushBudgetMs:0}})((s=this._instance)==null||(s=s.config)==null?void 0:s.logs,n);return[new Zh(this.hu(t,e),r,this.nu,(()=>this.du()),(o=>o()),void 0,i),r]}vu(){var t,e=(t=this._instance)==null||(t=t.config)==null?void 0:t.logs;if(!this.ou||this.cu!==e){var n;(n=this.ou)==null||n.reset(),this.cu=e;var i=this.uu((()=>this.tr),(s=>{this.tr=s}));this.ou=i[0],this.fu=i[1]}return this.ou}pu(){var t,e=(t=this._instance)==null||(t=t.config)==null?void 0:t.logs;if(!this.lu||this.gu!==e){var n;(n=this.lu)==null||n.reset(),this.gu=e;var i=this.uu((()=>this.su),(s=>{this.su=s}),{serviceNameDefault:"posthog-browser-logs",consoleCapture:!0},sc);this.lu=i[0],this.mu=i[1]}return this.lu}initialize(){this.loadIfEnabled()}onRemoteConfig(t){var e;if(t.ok){var n=(e=t.config.logs)==null?void 0:e.captureConsoleLogs;!B(n)&&n&&(this.iu=!0,this.loadIfEnabled())}}reset(){var t,e;this.tr=[],(t=this.ou)==null||t.reset(),this.su=[],(e=this.lu)==null||e.reset(),this.Sa=0}captureLog(t){this.vu().captureLog(t)}he(t){this.pu().captureLog(t)}get logger(){return this.yu||(this.yu={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.yu}flushLogs(t){t?this.bu(t):(this.ou&&this.ou.flush().catch((e=>this._u(e))),this.lu&&this.lu.flush().catch((e=>this._u(e))))}_u(t){rc(t)||this.rt.error("PostHog logs flush failed:",t)}loadIfEnabled(){if(this.iu&&!this.ru){var t=R?.__PosthogExtensions__;if(t){var e=t.loadExternalDependency;e?e(this._instance,"logs",(n=>{var i;n||(i=t.logs)==null||!i.initializeLogs?this.rt.error("Could not load logs script",n):(t.logs.initializeLogs(this._instance),this.ru=!0)})):this.rt.error(sa)}else this.rt.error("PostHog Extensions not found.")}}hu(t,e){var n=this._instance;return{get isDisabled(){return!1},get optedOut(){return!n.is_capturing()},getPersistedProperty:i=>i===pt.LogsQueue?t():void 0,setPersistedProperty(i,s){var r;i===pt.LogsQueue&&e((r=s)!==null&&r!==void 0?r:[])},Ot:i=>this.Ot(i),getLibraryId:()=>Y.LIB_NAME,getLibraryVersion:()=>Y.LIB_VERSION}}Ot(t){return new Promise((e=>{if(Vu(this.Sa,3))e({kind:"fatal",error:Or(void 0,"logs endpoint is unreachable, dropping batch")});else{var n=!1,i=r=>{n||(n=!0,clearTimeout(s),e(r))},s=setTimeout((()=>{this.rt.warn("Logs request timed out before receiving a response"),i({kind:"retry-later",error:Or(void 0,"logs request timed out")})}),9e4);this._instance._send_request({method:"POST",url:this.wu(),data:t,compression:"best-available",batchKey:"logs",fireCallbackOnDrop:!0,callback:r=>{var o=r.statusCode;if(this.ku(o),o>=200&&300>o)i({kind:"ok"});else if(o===413)i({kind:"too-large"});else if(o!==0&&o!==429&&500>o)i({kind:"fatal",error:new Error("logs request failed with status "+o)});else{var a;o===0?(r.error||this.rt.warn("Logs request failed before receiving an HTTP response"),i({kind:"retry-later",error:Or(r.error,"logs request failed before receiving an HTTP response")})):i({kind:"retry-later",error:(a=r.error)!==null&&a!==void 0?a:new Error("logs request failed with status "+o)})}}})}}))}ku(t){(t!==0||this._instance.__loaded)&&(this.Sa=Gu(t,this.Sa,3,(()=>this.rt.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."))))}bu(t){this.tr.length>0&&this.xu(t,this.tr,this.fu,Y.LIB_NAME,(e=>{this.tr=e})),this.su.length>0&&this.xu(t,this.su,this.mu,sc,(e=>{this.su=e}))}xu(t,e,n,i,s){if(e.length!==0){var r=e.map((a=>a.record));s([]);var o=vu(r,mu(n,Y.LIB_NAME,Y.LIB_VERSION),i,Y.LIB_VERSION);this._instance._send_request({method:"POST",url:this.wu(),data:o,compression:"best-available",batchKey:"logs",transport:t})}}wu(){return this._instance.requestRouter.endpointFor("api","/i/v1/logs")+"?token="+encodeURIComponent(this._instance.config.token)}du(){var t,e={};if(e.distinctId=this._instance.get_distinct_id(),this._instance.sessionManager){var n=this._instance.sessionManager.checkAndGetSessionAndWindowId(!0),i=n.windowId,s=n.sessionStartTimestamp,r=n.lastActivityTimestamp;e.sessionId=n.sessionId,e.windowId=i,B(s)||(e.sessionStartTimestamp=s),B(r)||(e.lastActivityTimestamp=r)}if(R!=null&&(t=R.location)!=null&&t.href&&(e.currentUrl=this._instance.config.disable_capture_url_hashes?Pt(R.location.href):R.location.href),this._instance.featureFlags){var o=this._instance.featureFlags.getFlags();o&&o.length>0&&(e.activeFeatureFlags=o)}return e}}},Jf={metrics:class{constructor(t){this.rt=ie("[metrics]"),this._instance=t}initialize(){}vu(){var t,e,n=(t=this._instance)==null||(t=t.config)==null?void 0:t.metrics;return this.ou&&this.cu===n||((e=this.ou)==null||e.reset(),this.cu=n,this.ou=new Xh(this.hu(),(function(i){var s,r,o,a,l,u=i?.resourceAttributes;return{serviceName:(s=u?.["service.name"])!==null&&s!==void 0?s:i?.serviceName,serviceVersion:(r=u?.["service.version"])!==null&&r!==void 0?r:i?.serviceVersion,environment:(o=u?.["deployment.environment"])!==null&&o!==void 0?o:i?.environment,resourceAttributes:u,beforeSend:i?.beforeSend,flushIntervalMs:(a=i?.flushIntervalMs)!==null&&a!==void 0?a:1e4,maxSeriesPerFlush:(l=i?.maxSeriesPerFlush)!==null&&l!==void 0?l:1e3}})(n),this.rt)),this.ou}count(t,e,n){e===void 0&&(e=1),this.vu().count(t,e,n)}gauge(t,e,n){this.vu().gauge(t,e,n)}histogram(t,e,n){this.vu().histogram(t,e,n)}flush(t){if(!this.ou)return Promise.resolve();if(t){var e=this.ou.drainWindow();return e&&this.Jt(e,t),Promise.resolve()}return this.ou.flush().catch((n=>this.rt.error("PostHog metrics flush failed:",n)))}reset(){var t;(t=this.ou)==null||t.reset()}hu(){var t=this._instance,e=this;return{get isDisabled(){return!1},get optedOut(){return!t.is_capturing()},Jt:n=>e.Jt(n),getLibraryId:()=>Y.LIB_NAME,getLibraryVersion:()=>Y.LIB_VERSION}}Jt(t,e){return new Promise((n=>{var i=!1,s=o=>{i||(i=!0,clearTimeout(r),n(o))},r=setTimeout((()=>s({kind:"retry-later",error:new Error("metrics request timed out")})),9e4);this._instance._send_request(E({method:"POST",url:this.Su(),data:t,compression:"best-available",batchKey:"metrics"},e&&{transport:e},{fireCallbackOnDrop:!0,callback(o){var a=o.statusCode;if(a>=200&&300>a)s({kind:"ok"});else if(a===413)s({kind:"too-large"});else if(a!==0&&a!==429&&500>a)s({kind:"fatal",error:new Error("metrics request failed with status "+a)});else{var l;s({kind:"retry-later",error:(l=o.error)!==null&&l!==void 0?l:new Error("metrics request failed with status "+a)})}}}))}))}Su(){return this._instance.requestRouter.endpointFor("api","/i/v1/metrics")+"?token="+encodeURIComponent(this._instance.config.token)}}},Yf=E({},Us,Bf,Df,jf,Uf,Hf,zf,Wf,qf,Vf,Gf,Kf,Jf);Re.__defaultExtensionClasses=E({},Yf);(function(){Y.SDK_DIST_CHANNEL="npm";var t=ti[un]=new Re;return(function(){function e(){e.done||(e.done=!0,bd=!1,Z(ti,(function(n){n._dom_loaded()})))}C!=null&&C.addEventListener?C.readyState==="complete"?e():re(C,"DOMContentLoaded",e,{capture:!1}):_&&k.error("Browser doesn't support `document.addEventListener` so PostHog couldn't be initialized")})(),t})();const Zf=["a[href]","button:not([disabled])","input:not([disabled]):not([type='hidden'])","select:not([disabled])","textarea:not([disabled])","[tabindex]:not([tabindex='-1'])"].join(",");let Je=null,Io=null,Sd="";const Co=new Map;function xd(t){return[...t.querySelectorAll(Zf)].filter(e=>!e.hidden&&e.getAttribute("aria-hidden")!=="true"&&e.getClientRects().length>0)}function Xf(t){for(const e of document.body.children)e===t||e.tagName==="SCRIPT"||(Co.set(e,{inert:e.inert,ariaHidden:e.getAttribute("aria-hidden")}),e.inert=!0,e.setAttribute("aria-hidden","true"))}function Qf(){for(const[t,e]of Co)t.inert=e.inert,e.ariaHidden===null?t.removeAttribute("aria-hidden"):t.setAttribute("aria-hidden",e.ariaHidden);Co.clear()}function kd(t){return t?.dataset.modalDismissible!=="false"&&t?.getAttribute("aria-busy")!=="true"}function Ve(t,e={}){const n=typeof t=="string"?document.getElementById(t):t;if(!n)return!1;Je&&Je!==n&&Xe(Je,{restoreFocus:!1,force:!0}),Io=e.trigger||document.activeElement,Je=n,Sd=document.body.style.overflow,Xf(n),document.body.style.overflow="hidden",n.classList.add("open"),n.setAttribute("aria-hidden","false");const i=n.querySelector(".modal-content");i&&(i.style.transform="scale(1) translateY(0)");const s=()=>{if(Je!==n)return;((e.initialFocus?n.querySelector(e.initialFocus):n.querySelector("[data-modal-initial-focus]"))||xd(n)[0]||n.querySelector(".modal-content")||n).focus({preventScroll:!0})};return requestAnimationFrame(s),setTimeout(s,260),!0}function Xe(t,e={}){const n=typeof t=="string"?document.getElementById(t):t;if(!n||!e.force&&!kd(n))return!1;n.classList.remove("open"),n.setAttribute("aria-hidden","true"),Qf(),document.body.style.overflow=Sd,Je=null;const i=Io;return Io=null,e.restoreFocus!==!1&&i?.isConnected&&i.focus({preventScroll:!0}),!0}function oc(t,e,n="Operation in progress"){const i=typeof t=="string"?document.getElementById(t):t;i&&(i.dataset.modalDismissible=e?"false":"true",i.setAttribute("aria-busy",String(!!e)),e?i.setAttribute("aria-label",n):i.removeAttribute("aria-label"))}function eg(t){if(!kd(t))return;const e=t.dataset.modalCloseHandler;e&&typeof window[e]=="function"?window[e]():Xe(t)}document.addEventListener("keydown",t=>{if(!Je)return;if(t.key==="Escape"){t.preventDefault(),t.stopImmediatePropagation(),eg(Je);return}if(t.key!=="Tab"){t.stopPropagation();return}const e=xd(Je);if(!e.length){t.preventDefault(),(Je.querySelector(".modal-content")||Je).focus();return}const n=e[0],i=e[e.length-1];t.shiftKey&&document.activeElement===n?(t.preventDefault(),i.focus()):!t.shiftKey&&document.activeElement===i&&(t.preventDefault(),n.focus())},!0);function tg(){document.querySelectorAll(".modal-overlay").forEach(t=>{t.setAttribute("role","dialog"),t.setAttribute("aria-modal","true"),t.setAttribute("aria-hidden",t.classList.contains("open")?"false":"true");const e=t.querySelector(".modal-content");e&&!e.hasAttribute("tabindex")&&(e.tabIndex=-1);const n=t.querySelector("h1, h2, h3");n&&(n.id||(n.id=`${t.id}-title`),t.setAttribute("aria-labelledby",n.id)),t.querySelectorAll(".modal-close").forEach(i=>{i.getAttribute("aria-label")||i.setAttribute("aria-label","Close dialog")})})}const Id="CodeFile",Cd="GeneratedCode",ng={CustomAction:"A",CustomWidget:"W",CustomFunction:"F",CustomClass:"C",CodeFile:"C"};function At(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function Ao(t){return String(t||"").trim().replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function ig(t={},e=0){const n=Ao(t.artifactType||t.type||Id),i=Ao(t.artifactName||t.name||t.fileName||`${Cd}-${e+1}`);return`${n||"artifact"}-${i||e+1}`}function Ad(t={},e=0){const n=At(t),i=n.artifactType||n.type||Id,s=n.artifactName||n.name||Cd;let r=n.fileName||s;return r.endsWith(".dart")||(r+=".dart"),{id:Ao(n.id)||ig({...n,artifactType:i,artifactName:s,fileName:r},e),artifactType:i,artifactName:s,fileName:r,deployPath:n.deployPath||"",description:n.description||"",code:n.code||n.content||"",dependencies:Fd(n.dependencies),imports:Array.isArray(n.imports)?n.imports:[],publicApi:Array.isArray(n.publicApi)?n.publicApi:[],relationships:Pd(n.relationships),deployStatus:n.deployStatus||"pending",review:n.review||null,metadata:At(n.metadata),codeType:n.codeType||ng[i]||"O"}}function Fd(t){return t?Array.isArray(t)?t.map(e=>{if(typeof e=="string")return{name:e,version:null,inferred:!1};const n=At(e),i=n.name||n.package;return i?{name:i,version:n.version||null,versionRequired:!!(n.versionRequired||n.required),inferred:!!n.inferred,...n.reason?{reason:n.reason}:{}}:null}).filter(Boolean):Object.entries(At(t)).map(([e,n])=>({name:e,version:n||null,inferred:!1})):[]}function Pd(t){return t?(Array.isArray(t)?t:[t]).map(e=>{const n=At(e);return!n.from&&!n.to?null:{from:n.from||null,to:n.to||null,type:n.type||"uses",description:n.description||""}}).filter(Boolean):[]}function Fo(t){if(typeof t!="string")return null;const e=t.trim();if(!e)return null;try{return JSON.parse(e)}catch{const n=e.match(/```(?:json)?\s*([\s\S]*?)```/i);if(!n)return null;try{return JSON.parse(n[1].trim())}catch{return null}}}function di(t,e={}){const n=[],i=typeof t=="string"?Fo(t):t,r=At(i||{});!i&&typeof t=="string"&&n.push("Structured bundle parse failed; using legacy single-artifact fallback.");const o=Array.isArray(r.artifacts)?r.artifacts:[{artifactType:r.artifactType||e.artifactType,artifactName:r.artifactName||e.artifactName,fileName:r.fileName||e.fileName,description:r.description,code:r.code||e.code||(typeof t=="string"?t:""),dependencies:r.dependencies||e.dependencies,relationships:r.relationships||e.relationships}];o.forEach((d,h)=>{!d?.artifactType&&!d?.type&&n.push(`Artifact ${h+1} has no artifactType; it will deploy as a standalone code file under lib/custom_code/ root.`)});const a=o.map((d,h)=>Ad(d,h)),l=new Map(o.map((d,h)=>[At(d).id,a[h]?.id]).filter(([d,h])=>d&&h)),u=d=>l.get(d)||d,c=Pd(r.relationships||e.relationships).map(d=>({...d,from:d.from?u(d.from):d.from,to:d.to?u(d.to):d.to}));return{schemaVersion:r.schemaVersion||e.schemaVersion||null,id:r.id||e.id||"bundle-current",title:r.title||r.name||e.title||"Generated artifact bundle",description:r.description||e.description||"",artifacts:a,dependencies:Fd(r.dependencies||e.dependencies),relationships:c,deployOrder:Array.isArray(r.deployOrder)?r.deployOrder.map(u):a.map(d=>d.id),warnings:[...n,...Array.isArray(r.warnings)?r.warnings:[]],metadata:At(r.metadata)}}function Ss(t){return di(t).artifacts[0]||Ad()}function Et(t){if(typeof t!="string")return t??"";const e=t.trim();if(!e)return"";try{return JSON.parse(e)}catch{return t}}function Sn(t){return JSON.stringify(t,null,2)}function sg(t){return Sn({task:"architect",userRequest:String(t??"")})}function rg(t){const e=Et(t);return e&&typeof e=="object"&&typeof e.task=="string"?Sn(e):Sn({task:"generate_bundle",bundleSpec:e})}function og(t){return Sn({task:"review_bundle",generatedBundle:Et(t),outputRequirements:{bundleReview:["status","score","summary","manualActions","findings"],scoreRange:[0,100],eachArtifact:["id","review.status","review.findings"],manualActions:{definition:"Setup the developer must perform by hand in the FlutterFlow editor that FlutterFlow will NOT do for them.",exclude:["creating the Custom Action, Widget or Code File itself - deploying the code creates it","declaring parameters or return values FlutterFlow derives from the function signature","anything that resolves as a side effect of using the action or widget in the editor","generic advice such as testing, reviewing or rebuilding the app"],preferEmpty:"Return an empty array when nothing qualifies - an empty list is the expected result for most bundles."}}})}function ha(t,e=null){const n={stage:t};return e!=null&&(n.bundle=Et(e)),n}function ag({bundleSpec:t,artifactBundle:e,bundleReview:n,artifactId:i,userFeedback:s}){return Sn({task:"regenerate_artifact",artifactId:i,bundleSpec:Et(t),artifactBundle:Et(e),bundleReview:Et(n),userFeedback:String(s)})}function $d({bundleSpec:t,artifactBundle:e,bundleReview:n,userFeedback:i}){return Sn({task:"regenerate_bundle",bundleSpec:Et(t),artifactBundle:Et(e),bundleReview:Et(n),userFeedback:String(i??"")})}const ac={csam:"child-safety content",dangerous:"dangerous content",harassment:"harassment",hate_speech:"hate speech",maliciousUrls:"a potentially malicious URL",malicious_uris:"a potentially malicious URL",pi_and_jailbreak:"prompt-injection or jailbreak instructions",promptInjection:"prompt-injection or jailbreak instructions",rai:"restricted content",sdp:"sensitive personal data",sexually_explicit:"sexually explicit content",virus_scan:"potentially malicious file content"},lg=["sanitizationResult","modelArmor","modelArmorResult","data","result","error"];function Le(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function cg(t){return Le(t)?typeof t.filterMatchState=="string"||typeof t.invocationResult=="string"||Array.isArray(t.matchedFilters)||Le(t.filterSummary)||Le(t.filterResults):!1}function Td(t,e=0){if(!Le(t)||e>3)return null;if(cg(t))return t;for(const n of lg){const i=t[n];if(Le(i)){const s=Td(i,e+1);if(s)return s}}return null}function xs(t){return Array.isArray(t)?t.some(xs):Le(t)?t.matched===!0||t.matchState==="MATCH_FOUND"?!0:Object.values(t).some(xs):!1}function Po(t){return Array.isArray(t)?t.some(Po):Le(t)?typeof t.executionState=="string"&&t.executionState!=="EXECUTION_SUCCESS"?!0:Object.values(t).some(Po):!1}function Rd(t){return{csamFilterFilterResult:"csam",maliciousUriFilterResult:"malicious_uris",piAndJailbreakFilterResult:"pi_and_jailbreak",raiFilterResult:"rai",sdpFilterResult:"sdp",virusScanFilterResult:"virus_scan"}[t]||t}function ug(t,e){if(Le(t))for(const[n,i]of Object.entries(t)){if(!Le(i))continue;const s=Le(i.categories)?i.categories:{},r=Object.entries(s).filter(([,o])=>Le(o)&&o.matched===!0).map(([o])=>o);r.length>0?r.forEach(o=>e.add(o)):i.matched===!0&&e.add(Rd(n))}}function dg(t,e){if(!t)return;const n=Array.isArray(t)?t.flatMap(i=>Le(i)?Object.entries(i):[]):Object.entries(t);for(const[i,s]of n){if(!xs(s))continue;const r=Rd(i),o=s?.raiFilterResult?.raiFilterTypeResults||(r==="rai"?s?.raiFilterTypeResults:null),a=Le(o)?Object.entries(o).filter(([,l])=>xs(l)).map(([l])=>l):[];a.length>0?a.forEach(l=>e.add(l)):e.add(r)}}function hg(t){return ac[t]?ac[t]:String(t).replace(/([a-z])([A-Z])/g,"$1 $2").replace(/_/g," ").toLowerCase()}function lc(t){return t.length<=1?t[0]||"content that did not pass":t.length===2?`${t[0]} and ${t[1]}`:`${t.slice(0,-1).join(", ")}, and ${t.at(-1)}`}function pg(t){const e=Td(t);if(!e)return null;const n=new Set(Array.isArray(e.matchedFilters)?e.matchedFilters:[]);ug(e.filterSummary,n),dg(e.filterResults,n);const i=e.blocked===!0||e.filterMatchState==="MATCH_FOUND"||n.size>0,s=e.invocationResult||null,r=Po(e.filterSummary||e.filterResults);return!i&&!r&&!["PARTIAL","FAILURE"].includes(s)?null:{kind:i?"blocked":"unavailable",invocationResult:s,matchedFilters:[...n]}}function fg(t,e){const n=pg(t);if(!n)return null;const i=[...new Set(n.matchedFilters.map(hg))],s=n.kind==="blocked",r=new Error(s?`Safety screening blocked this pipeline step for ${lc(i)}.`:"Safety screening could not be completed. Please try again.");return r.name="ModelArmorError",r.code=s?"MODEL_ARMOR_BLOCKED":"MODEL_ARMOR_UNAVAILABLE",r.isModelArmor=!0,r.pipelineStep=e,r.userTitle=s?"Request blocked for safety":"Safety check unavailable",r.userMessage=s?`The safety check detected ${lc(i)}. Edit your request to remove or rephrase the flagged content, then run the pipeline again.`:"The safety service did not finish all of its checks. Please wait a moment and run the pipeline again.",r.retryExplanation=s?"Trying another model would not change this safety decision.":"A fallback model was not attempted because safety screening must complete first.",r.matchedFilters=n.matchedFilters,r}function gg(t){return String(t||"").replace(/\/\*[\s\S]*?\*\//g,"").replace(/\/\/[^\n]*/g,"")}function cc(t){const e=/^(import|export|part|library|class|enum|extension|typedef|mixin|abstract|const|final|var|late)\b/,n=[];for(const i of gg(t).split(` +`)){if(!/^[A-Za-z_$]/.test(i)||e.test(i))continue;const s=i.match(/^[\w$<>,?\s[\]]+?\s([a-zA-Z_$][\w$]*)\s*\(/);s&&n.push(s[1])}return n}function pa(t,e){const n=t.replace(/\.dart$/,"");if(e==="W")return n.replace(/(^|_)(\w)/g,(i,s,r)=>r.toUpperCase());if(e==="A"){const i=n.replace(/(^|_)(\w)/g,(s,r,o)=>o.toUpperCase());return i.charAt(0).toLowerCase()+i.slice(1)}return e==="F"?"CustomFunctions":e==="C"?t.endsWith(".dart")?t:`${t}.dart`:n}async function uc(t){const e=new TextEncoder().encode(String(t||"")),n=await globalThis.crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(n),i=>i.toString(16).padStart(2,"0")).join("")}async function mg(t,e=new Map){const n={},i=new Set;for(const[o,a]of t.entries()){if(a.type==="D"||a.type==="O")continue;const l=pa(o,a.type),u={old_identifier_name:l,new_identifier_name:l,type:a.type,is_deleted:!1,current_checksum:await uc(a.content)},c=e.get(a.path);if(c!==void 0&&(u.original_checksum=await uc(c)),n[o]=u,a.type==="F"){const d=cc(a.content);(d.length>0?d:[a.functionName].filter(Boolean)).forEach(p=>i.add(p))}}const s=new Set(cc(e.get("lib/flutter_flow/custom_functions.dart")||"")),r={functions_to_rename:[],functions_to_delete:[],functions_to_add:Array.from(i).filter(o=>!s.has(o))};return{fileMapContents:JSON.stringify(n),functionsMapContents:JSON.stringify(r)}}const vg=new Set(["CustomWidget","CustomAction","CustomFunction","CustomClass","CodeFile"]),dc={CustomWidget:"custom_code/widgets/",CustomAction:"custom_code/actions/",CustomFunction:"flutter_flow/custom_functions.dart",CustomClass:"custom_code/",CodeFile:"custom_code/"},_g=new Set(["void","dynamic","String","int","double","num","bool","Color","DateTime","DateTimeRange","LatLng","FFPlace","FFUploadedFile","DocumentReference","List"]),yg=["Struct","Record"],wg=[{id:"required-public-param",severity:"error",message:"CustomWidget constructor uses `required` on a parameter FlutterFlow can leave unset. FlutterFlow omits unset Define Parameters fields from the constructor call, so the widget will not compile when placed. Make the parameter optional and nullable (`this.value` with `final double? value`), or give it a constructor default (`this.value = 0.0`).",detect:t=>Br(t).some(e=>/\brequired\s+this\.\w+/.test(e)),pos:"class W extends StatefulWidget { const W({required this.value}); final double value; }",neg:`class _P { const _P({required this.t}); final double t; } +class W extends StatefulWidget { const W({this.value}); final double? value; }`},{id:"non-nullable-public-field",severity:"error",message:"CustomWidget declares a non-nullable field with no constructor default. FlutterFlow omits unset Define Parameters fields, so the emitted call cannot supply it. Make the field nullable (`final double? value`) or give the parameter a default (`this.value = 0.0`).",detect:t=>Br(t).some(e=>{const n=/^\s*final\s+(?:double|int|String|bool|Color|num)\s+(\w+)\s*;/gm;let i;for(;(i=n.exec(e))!==null;){const s=i[1];if(!(new RegExp(`this\\.${s}\\s*=(?!=)`).test(e)||new RegExp(`[:,]\\s*${s}\\s*=(?!=)`).test(e)))return!0}return!1}),pos:`class W extends StatefulWidget { + const W({required this.value}); + final double value; +}`,neg:`class _P { + const _P({required this.t}); + final double t; +} +class W extends StatefulWidget { + const W({this.value = 1.0}); + final double value; +}`},{id:"asset-without-anchor",severity:"warning",message:'CustomWidget calls Image.asset with a path arriving as a String parameter. An asset reaches the build only when a FlutterFlow widget NODE references it - a filename passed as a parameter does not count, so the image renders as a broken-image icon on device. "Download Unused Project Assets" does not fix it (FlutterFlow issues 522, 2271, 3799). Keep something in the UI referencing the file, or load it over the network instead.',detect:t=>/Image\.asset\s*\(/.test(t)&&/final\s+String\??\s+\w*[Pp]ath\b/.test(t),pos:`class W extends StatefulWidget { final String? imagePath; } +var x = Image.asset(widget.imagePath);`,neg:`class W extends StatefulWidget { final String? imagePath; } +var x = Image.network(widget.imagePath);`},{id:"unsupported-param-type",severity:"error",message:"CustomWidget exposes a Flutter data type FlutterFlow cannot express as a Define Parameter: TextStyle, BoxShadow, FontWeight, FontStyle, TextDirection, TextAlign, EdgeInsets, Offset, Alignment/AlignmentGeometry, Border, BorderRadius, BoxDecoration, BoxConstraints, BorderSide, Gradient, or ThemeData. FlutterFlow's supported data types (docs.flutterflow.io/resources/data-representation/data-types) are only int, double, bool, string, Color, Image, DateTime, Json, LatLng, and the FF objects, so this parameter cannot be configured in the editor and the widget will not place or compile. Expose primitives instead (color, fontSize as double?, fontWeight via a custom enum, doubles for spacing).",detect:t=>Br(t).some(e=>/final\s+(TextStyle|BoxShadow|FontWeight|FontStyle|TextDirection|TextAlign|EdgeInsets|Offset|Alignment(?:Geometry)?|Border(?:Radius|Side)?|BoxDecoration|BoxConstraints|Gradient|LinearGradient|RadialGradient|ThemeData)\??\s+\w+\s*;/.test(e)),pos:`class W extends StatefulWidget { + const W({this.textStyle}); + final TextStyle? textStyle; + @override _S createState() => _S(); +} +class _S extends State { @override Widget build(BuildContext c) => const SizedBox(); }`,neg:`class W extends StatefulWidget { + const W({this.width}); + final double? width; + @override _S createState() => _S(); +} +class _S extends State { @override Widget build(BuildContext c) => Padding(padding: const EdgeInsets.all(8), child: const SizedBox()); }`}];function nt(t,e,n){return{artifactId:t.id,artifactName:t.artifactName,artifactType:t.artifactType,severity:e,message:n}}function hi(t){let e="",n=0;for(;n"&&(n--,n===0))return{inner:t.slice(e+1,i),end:i+1};return null}function Eg(t,e){const n=new RegExp(`class\\s+${e}\\b[^{]*\\{`).exec(t);if(!n)return null;let i=0;for(let s=n.index+n[0].length-1;sSg(t).usable);function kg(t=""){const e=hi(t);return xg.filter(n=>n.detect(e)).map(({id:n,severity:i,message:s})=>({id:n,severity:i,message:s}))}function Ig(t){const e=[],n=t.matchAll(/\bFuture\b/g);for(const i of n){let s=i.index+6,r=null;const o=s;for(;so;if(t[s]==="<"){const u=bg(t,s);if(!u||(r=u.inner.replace(/\s+/g," ").trim(),s=u.end,!/\s/.test(t[s]||"")))continue;for(;shc(o.functionName)===i);if(s)return s;const r=o=>!o.functionName.startsWith("_");return n.find(r)||n[0]}function Hs(t=""){return Array.from(hi(t).matchAll(/\b(?:class|enum)\s+([A-Za-z_]\w*)/g),e=>e[1])}function Cg(t="",e=""){return fa(t,e)?.returnType||null}function pc(t){return String(t||"").replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2").toLowerCase()}function Ag(t,e){const n=Hs(e);if(n.length===0)return null;const s=String(t||"").split("/").pop().replace(/\.dart$/,"");if(n.some(l=>pc(l)===s)||n.length>1)return null;const[o]=n,a=`${pc(o)}.dart`;return`File name "${t}" does not match declared class "${o}". FlutterFlow accepts this, but naming the file "${a}" keeps the Code File recognisable in the editor.`}function ga(t){return String(t||"").replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,"")}function Fg(t,e,n=""){const i=fa(e,n)?.functionName;if(!i)return null;const s=String(t||"").split("/").pop(),r=pa(s,"A");if(r===i)return null;const o=`${ga(i)}.dart`;return`File name "${s}" does not match Action "${i}". FlutterFlow derives the action from the file name, so it looks for "${r}" and reports Action "${r}" declaration not found. Rename the file to "${o}" - FlutterFlow puts an underscore before every capital - or rename the function to "${r}".`}function Pg(t="",e=""){return fa(t,e)!==null}function $g(t,e=new Set){return(t?.match(/[A-Za-z_]\w*/g)||[]).filter(i=>_g.has(i)?!1:!yg.some(r=>i.endsWith(r))||e.has(i))}function Tg(t,{functionName:e="",declaredTypes:n=new Set}={}){const i=Cg(t,e),s=$g(i,n);if(s.length===0)return null;const[r]=s;let o;return n.has(r)?o=`uses Code File type "${r}", which FlutterFlow cannot process as an Action Return Value`:i===r?o="is not a FlutterFlow Action Return Value":o=`uses type "${r}", which is not a FlutterFlow Action Return Value`,`CustomAction return type "${i}" ${o}. Return JSON (Future) or an existing FlutterFlow Data Type (*Struct) instead.`}function Rg(t,e={}){const n=[],i=t.fileName||"",s=t.code||"";if(vg.has(t.artifactType)||n.push(nt(t,"error",`Unsupported artifact type "${t.artifactType}".`)),i.endsWith(".dart")||n.push(nt(t,"error","FlutterFlow custom code artifacts must use .dart files.")),!s.trim())return n.push(nt(t,"warning","Generated artifact has no Dart code yet.")),n;if(t.artifactType==="CustomWidget"){/class\s+\w+\s+extends\s+(StatelessWidget|StatefulWidget)/.test(s)||n.push(nt(t,"warning","CustomWidget code should declare a widget class extending StatelessWidget or StatefulWidget."));for(const r of kg(s))n.push(nt(t,r.severity,r.message))}if(t.artifactType==="CustomAction"&&!Pg(s,t.artifactName)&&n.push(nt(t,"warning","CustomAction code should expose an async Future function callable from FlutterFlow.")),t.artifactType==="CustomAction"){const r=e.declaredTypes||new Set(Hs(s)),o=Tg(s,{functionName:t.artifactName,declaredTypes:r});o&&n.push(nt(t,"error",o));const a=Fg(i,s,t.artifactName);a&&n.push(nt(t,"error",a))}if(t.artifactType==="CustomFunction"&&/class\s+\w+\s+extends\s+(StatelessWidget|StatefulWidget)/.test(s)&&n.push(nt(t,"warning","CustomFunction should be a callable function, not a widget class.")),t.artifactType==="CustomClass"||t.artifactType==="CodeFile"){const r=Ag(i,s);r&&n.push(nt(t,"info",r))}return n}function Ng(t){const e=Array.isArray(t?.artifacts)?t.artifacts:[],n=new Set(e.flatMap(r=>Hs(r.code||""))),i=e.flatMap(r=>Rg(r,{declaredTypes:n})),s=e.map(r=>({artifactId:r.id,fileName:r.fileName,pathHint:dc[r.artifactType]||dc.CodeFile}));return{valid:i.every(r=>r.severity!=="error"),findings:i,deployHints:s}}const fc="// DO NOT REMOVE OR MODIFY THE CODE ABOVE!";function gc(t){return(/^\s*import\s+['"]([^'"]+)['"]/.exec(t)||[])[1]||null}function Mg(t=""){const e=t.indexOf(fc);return e===-1?t:t.slice(e+fc.length).replace(/^\s*\n/,"")}const Lg=/^\s*import\s+['"][^'"]+['"]\s*;\s*(?:\/\/.*)?$/;function Og(t="",e=""){const n=Mg(t),i=new Set((e.match(/^\s*import .*$/gm)||[]).map(gc).filter(Boolean)),s=n.split(` +`).filter(r=>{const o=gc(r);return o===null||!i.has(o)?!0:!Lg.test(r)}).join(` +`).replace(/^\s*\/\/ Automatic FlutterFlow imports\s*$/m,"").replace(/^\s*\n+/,"");return e+s}const Bg=new Set(["flutter","flutter_test","flutter_driver","flutter_localizations"]);function Nd(t){let e="",n=0;for(;n{const i=n.name||n.package;if(!i||i==="flutter")return e;const s=n.versionRequired||n.required;return e[i]=s&&n.version||"",e},{})}function Wg(t){const e=new Map,n=new Map,i=[];for(const s of t)e.has(s.fileName)?i.push(`Duplicate deploy file name "${s.fileName}" for artifacts "${e.get(s.fileName)}" and "${s.artifactId}".`):e.set(s.fileName,s.artifactId),n.has(s.path)?i.push(`Duplicate deploy path "${s.path}" for artifacts "${n.get(s.path)}" and "${s.artifactId}".`):n.set(s.path,s.artifactId);return i}function zg(t,e={}){const n=Array.isArray(t?.artifacts)?t.artifacts:[],s=(e.selectedArtifactIds||t?.deployOrder||n.map(p=>p.id)).map(p=>n.find(f=>f.id===p)).filter(Boolean),r=[...t?.warnings||[]];let o=[];s.forEach(p=>{const f=Hg(p),g=p.fixedCode||p.code||"",m=p.codeType||jg[p.artifactType]||Ne.OTHER;g.trim()||r.push(`${p.artifactName||p.id} has no generated code.`),o.push({artifactId:p.id,artifactName:p.artifactName,artifactType:p.artifactType,fileName:f,content:g,type:m,path:p.deployPath||Ug(f,m),deployPath:p.deployPath||"",deployMode:"customCodeSync"})});const a="lib/flutter_flow/custom_functions.dart",l=o.map((p,f)=>({entry:p,index:f})).filter(({entry:p})=>p.type===Ne.FUNCTION&&p.path===a);if(l.length>1){const p=l[0],f={...p.entry,artifactId:l.map(({entry:m})=>m.artifactId).join("+"),artifactName:p.entry.artifactName,content:l.map(({entry:m})=>`// ${m.artifactId} +${m.content}`).join(` + +`)},g=new Set(l.slice(1).map(({index:m})=>m));o=o.filter((m,v)=>!g.has(v)),o[p.index]=f}const u={...mc(t?.dependencies),...s.reduce((p,f)=>({...p,...mc(f.dependencies)}),{})},c={};s.forEach(p=>{ma(p.code||"").forEach(f=>{f in u||(c[f]="")})});const d={...c,...u},h=Wg(o);return{bundleId:t?.id||"bundle-current",title:t?.title||"Generated artifact bundle",fileEntries:o,dependencies:d,relationships:t?.relationships||[],warnings:r,errors:h}}function qg(t){return String(t||"").match(/\bclass\s+([A-Z][A-Za-z0-9_]*)\b/)?.[1]}function Vg(t){return String(t||"").split("/").pop().replace(/\.dart$/,"").split(/[^A-Za-z0-9]+/).filter(Boolean).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join("")}function Gg(t,e){const i=[Vg(t),qg(e.content),e.artifactName].find(s=>/^[A-Z][A-Za-z0-9_]*$/.test(String(s||"")));if(!i)throw new Error(`Cannot derive a FlutterFlow custom class name for ${t}.`);return i}function Kg(t,e=new Map){const n=[];for(const[i,s]of t.entries())s.type!=="C"||e.has(s.path)||n.push({artifactId:s.artifactId||i,className:Gg(i,s),content:s.content,fileName:i,path:s.path});return n}function Jg(t,e){const n=new Set(e.map(i=>i.path));return new Map(Array.from(t.entries()).filter(([,i])=>!n.has(i.path)))}const vc={pass:0,warning:1,fail:2},Yg=["manualActions"];function Be(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function _t(...t){for(const e of t){if(typeof e=="string"&&e.trim())return e.trim();if(Array.isArray(e)&&e.length>0){const n=e.filter(i=>typeof i=="string").join(` +`);if(n)return n}}return""}function st(t){return t==null?[]:Array.isArray(t)?t:[t]}function Zg(t){const e=Be(t).value??t;if(e==null||typeof e=="string"&&e.trim()==="")return null;const n=Number(e);if(Number.isFinite(n))return n;const i=String(t||"").match(/\bscore\b[^\d]{0,12}(\d{1,3})(?:\s*\/\s*100)?/i);return i?Number(i[1]):null}function We(t){return String(t||"").trim().replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function va(t){const e=String(t||"").toLowerCase();return/(fail|error|critical|block|reject|invalid)/.test(e)?"fail":/(warn|attention|manual|partial|incomplete|concern)/.test(e)?"warning":/(pass|success|ready|approve|valid|clean|info|notice)/.test(e)?"pass":null}function $o(...t){return t.filter(Boolean).reduce((e,n)=>vc[n]>vc[e]?n:e,"pass")}function Md(t,e="warning",n="review"){if(typeof t=="string")return{severity:e,message:t,suggestion:"",source:n};const i=Be(t),s=_t(i.message,i.title,i.issue,i.description,i.summary);return s?{severity:va(i.severity||i.status||i.level)||e,message:s,suggestion:_t(i.suggestion,i.fix,i.recommendation,i.action),source:i.source||n}:null}function To(t,e="review"){const n=Be(t);return[["findings","warning"],["issues","warning"],["criticalIssues","fail"],["errors","fail"],["warnings","warning"],["recommendations","warning"],["requiredFixes","fail"],["suggestions","warning"]].flatMap(([s,r])=>st(n[s]).map(o=>Md(o,r,e)).filter(Boolean))}function Xg(t,e,n=null){if(typeof t=="string")return{id:`${n||"bundle"}-manual-${e+1}`,title:t,detail:"",location:"",timing:"unspecified",artifactId:n,source:"Code Review"};const i=Be(t),s=_t(i.title,i.action,i.step,i.message,i.name,i.description);return s?{id:i.id||`${n||"bundle"}-manual-${e+1}`,title:s,detail:_t(i.detail,i.instructions,i.description),location:_t(i.location,i.flutterFlowPath,i.path),timing:_t(i.timing,i.phase)||"unspecified",artifactId:n,source:_t(i.source)||"Code Review"}:null}function Ro(t,e=null){const n=Be(t);return Yg.flatMap(i=>st(n[i])).map((i,s)=>Xg(i,s,e)).filter(Boolean)}function Qg(t){let e=typeof t=="string"?Fo(t):t;if(!e&&typeof t=="string")return{rawText:t,root:{}};const n=Be(e);typeof n.content=="string"&&(e=Fo(n.content)||e);const i=Be(e),s=Be(i.reviewResult||i.codeReview||i.result);return{rawText:"",root:Object.keys(s).length?s:i}}function em(t,e){const n=[e.id,e.fileName,e.artifactName].map(We);return t.find(i=>{const s=Be(i);return[s.id,s.fileName,s.artifactName,s.name].map(We).some(r=>r&&n.includes(r))})||null}function tm(t,e){return st(t?.metadata?.compatibility?.deployHints).find(s=>We(s?.artifactId)===We(e.id)||We(s?.fileName)===We(e.fileName))?.pathHint||""}function nm(t,e){return st(t?.relationships).filter(n=>We(n?.from)===We(e.id)||We(n?.to)===We(e.id))}function im(t,e){return st(t?.metadata?.compatibility?.findings).filter(n=>!n?.artifactId||We(n.artifactId)===We(e.id)).map(n=>Md(n,"warning","Compatibility check")).filter(Boolean)}function sm(t,e,n,i){const s=em(e,n),r=Be(s?.review||s||n.review),o=Object.keys(r).length>0,a=[...To(r),...im(t,n)],l=Ro(r,n.id),u=va(r.status||r.verdict||r.outcome||r.result),c=a.length?$o(...a.map(h=>h.severity)):null,d=$o(u,c,o?null:"warning");return{...n,index:i,status:d,statusReason:o?_t(r.summary,r.overview,r.assessment,r.conclusion)||(a.length?`${a.length} review finding${a.length===1?"":"s"}`:"No file-level findings"):"No file-level verdict was returned",reviewComplete:o,findings:a,manualSteps:l,fixedSource:typeof r.fixedSource=="string"&&r.fixedSource.trim()?r.fixedSource.trim():null,pathHint:tm(t,n),relationships:nm(t,n)}}function rm({status:t,score:e,artifactPresentations:n,manualSteps:i}){const s=n.length;if(s===0&&i.length===0)return e==null?"Code review returned no overall summary and no score.":`Reviewed bundle with score ${e}/100.`;const r=n.reduce((a,l)=>(a[l.status]+=1,a),{pass:0,warning:0,fail:0}),o=[];return t&&o.push(`Overall verdict: ${t}.`),s&&o.push(`${s} artifact${s===1?"":"s"}: ${r.pass} pass, ${r.warning} warn, ${r.fail} fail.`),i.length&&o.push(`Do before deploy: ${i.map(a=>a.title).join("; ")}.`),e==null&&o.push("No numeric score (0-100) was returned."),o.join(" ")}function om({bundle:t,reviewResult:e}){const n=Be(t),i=st(n.artifacts),{root:s,rawText:r}=Qg(e),o=[s.bundleReview,s.overallReview,s.overall,s.bundleSummary,s.summaryReview,s.review].map(Be).find(w=>Object.keys(w).length)||{},a=st(s.artifacts||s.files||s.reviews),l=i.map((w,I)=>sm(n,a,w,I)),u=To(s),d=[...To(o),...u],h=[...Ro(o),...Ro(s),...l.flatMap(w=>w.manualSteps)].filter((w,I,A)=>A.findIndex(F=>F.title===w.title&&F.artifactId===w.artifactId)===I),p=va(o.status||o.verdict||o.overallStatus||s.status||s.verdict||s.overallStatus||s.outcome),f=$o(p,...d.map(w=>w.severity),...l.map(w=>w.status)),g=o.score??s.score??s.overallScore??r,m=Zg(g),v=_t(o.headline,o.summary,o.executiveSummary,o.overview,o.assessment,o.conclusion,s.overallSummary,s.headline,s.summary,s.executiveSummary,s.overview,s.assessment,s.conclusion,r)||rm({status:f,score:m,artifactPresentations:l,manualSteps:h}),b=l.reduce((w,I)=>(w[I.status]+=1,w),{pass:0,warning:0,fail:0});return{title:n.title||"Generated artifact bundle",description:n.description||"",status:f,score:m,summary:v,findings:d,manualSteps:h,artifacts:l,counts:b,reviewCoverage:{reviewed:l.filter(w=>w.reviewComplete).length,total:l.length},deployOrder:st(n.deployOrder),relationships:st(n.relationships),warnings:st(n.warnings),compatibility:Be(n.metadata?.compatibility)}}const am=/^\uFEFF/;function Hn(t){let e=0,n=t.length;for(;ee&&!t[n-1].trim();)n--;return t.slice(e,n).join(` +`)}function lm(t){const e=String(t??"").replace(am,"");if(!e.trim())return"";const n=e.split(` +`),i=c=>{const d=c.trim();return/^`{3,}[A-Za-z0-9+#_.-]*$/.test(d)?c.length-c.trimStart().length:-1};let s=0,r=-1;const o=[];{let c=0;for(let d=0;d=0&&(s++,r<0&&(r=d),o.push(c+h)),c+=n[d].length+1}}if(s===0)return Hn(n);{const c=No(e);if(!c.error&&o.every(h=>yc(h,c.commentAndStringRanges)))return Hn(n)}if(s===1){const c=Hn(n.slice(0,r)),d=Hn(n.slice(r+1));return d.length>=c.length?d:c}const a=[];let l=null;for(let c=0;cc.length>0);return u.length===0?"":u.join(` + +`)}function cm(t){return String(t??"").replace(/\/\*[\s\S]*?\*\//g," ").replace(/\/\/[^\n]*/g,"").replace(/'''[\s\S]*?'''/g,'""').replace(/"""[\s\S]*?"""/g,'""').replace(/'(?:\\.|[^'\\\n])*'/g,'""').replace(/"(?:\\.|[^"\\\n])*"/g,'""')}function Ld(t){const e=cm(t);return Array.from(e.matchAll(/class\s+([A-Z]\w*)\s+extends\s+[A-Za-z_]\w*Widget\b/g),n=>n[1])}function Od(t){return`${ga(t)}.dart`}function um(t){return pa(t,"W")}const _c={"(":")","[":"]","{":"}"},dm={")":"(","]":"[","}":"{"},hm=/[A-Za-z0-9_]/;function No(t){const e=[{kind:"code",opener:null,openedLine:0}],n=[];let i=1,s=0;const r=(c,d)=>{(c===` +`||c==="\r"&&d!==` +`)&&i++};let o=null;const a=()=>{for(const c of e)(c.kind==="string"||c.kind==="block-comment"||c.kind==="line-comment")&&n.push({start:c.startIndex,end:t.length})};for(;s0?t[s-1]:"",f=s>1?t[s-2]:"",g=(p==="r"||p==="R")&&!hm.test(f);e.push({kind:"string",quote:c,triple:h,raw:g,startIndex:s,openedLine:i}),s+=h?3:1;continue}if(_c[c]){e.push({kind:"code",opener:c,openedLine:i}),s++;continue}if(dm[c]){if(d.interpolation&&c==="}"){e.pop(),s++;continue}if(d.opener&&_c[d.opener]===c){e.pop(),s++;continue}return d.opener?(a(),{error:o??`line ${i}: "${c}" closes nothing - "${d.opener}" opened on line ${d.openedLine} is still open`,commentAndStringRanges:n}):(a(),{error:o??`line ${i}: unexpected "${c}" with no matching opener`,commentAndStringRanges:n})}r(c,t[s+1]),s++}a();let l=e.length-1;for(;l>0&&e[l].kind==="line-comment";)l--;let u=o;if(!u){const c=e[l];if(!(c.kind==="code"&&!c.opener&&!c.interpolation))if(c.kind==="string")u=`unclosed ${c.triple?"triple-quoted ":""}string starting on line ${c.openedLine} was never closed`;else if(c.kind==="block-comment")u=`unterminated /* comment starting on line ${c.openedLine}`;else if(c.interpolation){const d=e.findLast(p=>p.opener);u=`unclosed "\${" expression${d?` opened on line ${d.openedLine}`:""} was never closed`}else u=`"${c.opener}" opened on line ${c.openedLine} is never closed`}return{error:u,commentAndStringRanges:n}}function pm(t){return No(String(t??"")).error}function yc(t,e){return e.some(({start:n,end:i})=>t>=n&&ttypeof n=="string"?n:n?.errorMessage).filter(Boolean);return e.length>0?e.join("; "):JSON.stringify(t)}return t&&typeof t=="object"?t.errorMessage||JSON.stringify(t):String(t??"")}const fm=["gmail.com","googlemail.com","outlook.com","hotmail.com","live.com","msn.com"],gm="MAGIC_LINK_SENT",mm="PLUS_ALIAS_REJECTED",vm="Please enter your primary email address. Plus aliases (such as {email}) are not allowed for {domain} accounts.",Ws={allowlistedDomains:fm,successCode:gm,validationCode:mm,messageTemplate:vm},_m=new Set(Ws.allowlistedDomains),ym=Ws.successCode,Ki=Ws.validationCode;function zs(t){return typeof t=="string"?t.trim():""}function wm(t){const e=zs(t),n=e.lastIndexOf("@");if(n<=0||n===e.length-1)return!1;const i=e.slice(0,n),s=e.slice(n+1).toLowerCase();return _m.has(s)?i.includes("+"):!1}function bm(t,e){return Ws.messageTemplate.replaceAll("{email}",t).replaceAll("{domain}",e)}function Dd(t){if(!wm(t))return null;const e=zs(t),n=e.lastIndexOf("@"),i=e.slice(n+1).toLowerCase();return bm(e,i)}function Em(t,e){return t?.code===Ki?t.message||Dd(e)||"Please enter your primary email address.":t?.code===ym||!t?.code?`Check your email — we sent a link to ${zs(e)}`:t.message||"Something went wrong. Please try again."}const Sm=/^dependencies\s*:\s*(?:#.*)?$/,xm=/^(?:"([^"]+)"|'([^']+)'|([A-Za-z_][A-Za-z0-9_-]*))\s*:/;function qs(t){const e=t.match(xm);return e?e[1]??e[2]??e[3]:null}function _i(t){const e=t.trim();return e===""||e.startsWith("#")}function Fn(t){const e=t.match(/^(\s*)/);return e?e[1].length:0}function _a(t,e){const n=t.findIndex(r=>e.test(r));if(n===-1)return null;let i=n,s=null;for(let r=n+1;r=0.0.0"}`}function Am(t,e={}){const n=String(t||""),i=Object.entries(e).filter(([u])=>u&&u!=="flutter");if(i.length===0)return{yaml:n,added:[],alreadyPresent:[]};const s=n.split(` +`),r=new Set(Ud(n)),o=[],a=[];for(const[u,c]of i)r.has(u)?a.push(u):(o.push([u,c]),r.add(u));if(o.length===0)return{yaml:n,added:[],alreadyPresent:a};const l=ya(s);if(l){const u=o.map(([c,d])=>wc(l.childIndent,c,d));s.splice(l.endIndex,0,...u)}else s.length>0&&s[s.length-1].trim()!==""&&s.push(""),s.push("dependencies:"),o.forEach(([u,c])=>{s.push(wc(" ",u,c))});return{yaml:s.join(` +`),added:o.map(([u])=>u),alreadyPresent:a}}function Fm(t,e={}){const n=String(t||""),i=Object.entries(e).filter(([l])=>l&&l!=="flutter");if(i.length===0)return{yaml:n,overridden:[],skipped:[]};const s=n.split(` +`),r=Gs(n),o=[],a=[];for(const[l,u]of i){const c=r.get(l);if(!c||!c.isScalar||!String(u||"").trim()){a.push(l);continue}const d=" ".repeat(Fn(s[c.lineIndex]));s[c.lineIndex]=`${d}${l}: ${Wd(String(u).trim())}${c.comment}`,o.push({name:l,from:c.constraint,to:u})}return{yaml:s.join(` +`),overridden:o,skipped:a}}function zd(t){const e=String(t||""),n=[];return e.trim()?(/^name:\s*\S+/m.test(e)||n.push("pubspec.yaml missing name field"),ya(e.split(` +`))||n.push("pubspec.yaml missing dependencies section"),Ud(e).includes("flutter")||n.push("pubspec.yaml missing Flutter SDK dependency"),{valid:n.length===0,errors:n}):(n.push("pubspec.yaml is empty"),{valid:!1,errors:n})}const Pm=">=3.0.0 <4.0.0";function Mo(t){const e=String(t||"").trim(),n=e[0];return n!=="'"&&n!=='"'||e[e.length-1]!==n?e:e.slice(1,-1).replaceAll(`${n}${n}`,n)}function $m(t=""){const e=Dg(t).filter(n=>!n.startsWith("dart:")&&!n.startsWith("package:"));return{selfContained:e.length===0,unresolvableImports:e}}function bc(t,e,n){const i=[];for(const[s,r]of t){if(r.isScalar){e[s]=Mo(r.constraint);continue}if(r.sourceKey==="sdk"){n.add(s);continue}if(r.sourceKey===null&&r.version){e[s]=Mo(r.version);continue}i.push(s)}return i}function Tm(t){const e=new Set,n={},i={},s=bc(Gs(t),n,e);s.push(...bc(Im(t,"dependency_overrides"),i,e));const r=new Set([...Object.keys(n),...e]),{sdk:o}=Hd(t);return{sdkConstraint:Mo(o)||Pm,dependencies:n,overrides:i,sdkPackages:[...e].sort(),availablePackages:r,unrepresentable:s}}function Rm(t,e,n){return e.length>0?`${t} imports ${e.join(", ")}, which FlutterFlow only generates once the app is built, so it could not be compiled before the deploy.`:`${t} imports ${n.join(", ")}, which your project's pubspec.yaml does not declare with a version constraint, so it could not be compiled before the deploy.`}function Nm(t,e){const{sdkConstraint:n,dependencies:i,overrides:s,sdkPackages:r,availablePackages:o,unrepresentable:a}=Tm(e),l={sdkConstraint:n,dependencies:i,overrides:s,sdkPackages:r},u=[],c=[],d=a.map(h=>`Your project declares ${h} from a source that cannot be reproduced outside it, so the pre-deploy compile check runs against a scratch package graph that omits ${h}. Classes that do not import ${h} directly are still checked, but against that reduced graph, so their transitive package resolution may differ from your project's and the check is approximate for them.`);for(const h of t){const{className:p,content:f}=h,g=ma(f),m=g.filter(w=>a.includes(w));if(m.length>0){c.push({className:p,reason:`${p} was not compiled before deploying: it imports ${m.join(", ")}, which your project declares from a source that cannot be reproduced outside it, so package resolution could not be matched exactly.`});continue}const{unresolvableImports:v}=$m(f),b=g.filter(w=>!o.has(w));if(v.length>0||b.length>0){c.push({className:p,reason:Rm(p,v,b)});continue}u.push({fileName:`${ga(p)}.dart`,content:f})}return{manifest:l,sources:u,skipped:c,approximate:d}}function Ec(t,e){const n=`${t}${e}`.split(` +`),i=n.pop()??"",s=[];for(const r of n){const o=qd(r);o&&s.push(o)}return{events:s,buffer:i}}function Mm(t){const e=qd(t);return e?[e]:[]}function qd(t){const e=t.trim();if(!e)return null;try{const n=JSON.parse(e);return n&&typeof n=="object"&&!Array.isArray(n)?n:null}catch{return null}}async function Lm(t,e={}){const{onPhase:n,onLog:i}=e;let s=null,r="";const o=a=>{if(a.event==="phase"){a.message&&n&&n(a.message);return}if(a.event==="log"){a.message&&i&&i(a.message);return}s=a};if(t.body?.getReader){const a=t.body.getReader(),l=new TextDecoder;for(;;){const{done:u,value:c}=await a.read();if(u)break;const d=Ec(r,l.decode(c,{stream:!0}));r=d.buffer,d.events.forEach(o)}}else{const a=Ec("",await t.text());r=a.buffer,a.events.forEach(o)}return Mm(r).forEach(o),s?{...s,success:s.success===!0||s.success===void 0&&t.ok}:{success:!1,error:t.ok?"The FlutterFlow deploy runner closed the connection before it finished.":`FlutterFlow custom class provisioning failed (HTTP ${t.status}).`}}const Om=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;function St(t){const e=String(t||"").trim().match(Om);return e?{major:Number(e[1]),minor:Number(e[2]),patch:Number(e[3]),prerelease:e[4]?e[4].split("."):[]}:null}function Bm(t,e){if(t.length===0&&e.length===0)return 0;if(t.length===0)return 1;if(e.length===0)return-1;for(let n=0;n0)}function jm(t){const e=St(t);return e?e.major>0?`${e.major+1}.0.0`:`0.${e.minor+1}.0`:null}function wa(t){let e=String(t??"").trim();if((e.startsWith("'")||e.startsWith('"'))&&(e=e.slice(1,-1).trim()),e===""||e==="any"||e==="*")return{min:null,minInclusive:!1,max:null,maxInclusive:!1};if(e.startsWith("^")){const o=e.slice(1).trim();return St(o)?{min:o,minInclusive:!0,max:jm(o),maxInclusive:!1}:null}if(St(e))return{min:e,minInclusive:!0,max:e,maxInclusive:!0};const n={min:null,minInclusive:!1,max:null,maxInclusive:!1},i=/(>=|<=|>|<)\s*([0-9][0-9A-Za-z.+-]*)/g;let s=!1,r;for(;(r=i.exec(e))!==null;){const[,o,a]=r;if(!St(a))return null;s=!0,o===">="||o===">"?(n.min=a,n.minInclusive=o===">="):(n.max=a,n.maxInclusive=o==="<=")}return s?n:null}function Sc(t,e){const n=wa(t);if(!n||!St(e))return!1;if(n.min!==null){const i=ks(e,n.min);if(i<0||i===0&&!n.minInclusive)return!1}if(n.max!==null){const i=ks(e,n.max);if(i>0||i===0&&!n.maxInclusive)return!1}return!0}function Um(t,e){const n=wa(t);if(!n||!St(e))return!1;if(n.max===null)return!0;const i=ks(n.max,e);return i>0?!0:i===0&&n.maxInclusive}function ln(t){const e=wa(t);return e?e.min:null}const Hm="https://pub.dev/api/packages/",Wm=8e3;function zm(t,e={}){const{dartSdkFloor:n=null,flutterSdkFloor:i=null}=e,s=Array.isArray(t?.versions)?t.versions:[];let r=null;for(const o of s){const a=o?.version;if(!a||o.retracted||Dm(a))continue;const l=o.pubspec?.environment||{};n&&l.sdk&&!Sc(l.sdk,n)||i&&l.flutter&&!Sc(l.flutter,i)||(!r||ks(a,r)>0)&&(r=a)}return r?{version:r,constraint:`^${r}`}:null}async function qm(t,e={}){const{dartSdkFloor:n=null,flutterSdkFloor:i=null,fetchImpl:s=fetch}=e;let r;try{const a=await s(`${Hm}${encodeURIComponent(t)}`,{signal:AbortSignal.timeout(Wm)});if(!a.ok)return{name:t,constraint:null,version:null,error:a.status===404?`"${t}" was not found on pub.dev`:`pub.dev returned ${a.status} for "${t}"`};r=await a.json()}catch(a){return{name:t,constraint:null,version:null,error:`could not reach pub.dev for "${t}" (${a.message})`}}const o=zm(r,{dartSdkFloor:n,flutterSdkFloor:i});return o?{name:t,...o,error:null}:{name:t,constraint:null,version:null,error:n?`no published "${t}" release supports Dart ${n}`:`no published "${t}" release could be read`}}async function Vm(t,e={}){const n=await Promise.all(t.map(i=>qm(i,e)));return new Map(n.map(({name:i,...s})=>[i,s]))}async function Gm(t,e={},n={}){const{resolveVersions:i=Vm}=n,s=Object.entries(e).filter(([c])=>c&&c!=="flutter"),r=Hd(t),o={dartSdkFloor:ln(r.sdk),flutterSdkFloor:ln(r.flutter)},a={additions:{},overrides:{},kept:[],warnings:[],sdk:o};if(s.length===0)return a;const l=Gs(t),u=[];for(const[c,d]of s){const h=l.get(c);if(!h){u.push(c);continue}const p=ln(d);if(!p){a.kept.push({name:c,constraint:h.constraint});continue}if(!h.isScalar){a.warnings.push(`"${c}" is declared in your project from a git, path, or SDK source, but the generated code needs at least ${p}. Left as-is — update it yourself if the build fails.`),a.kept.push({name:c,constraint:h.constraint});continue}if(Um(h.constraint,p)){a.kept.push({name:c,constraint:h.constraint});continue}a.overrides[c]=`^${p}`,a.warnings.push(`"${c}" was pinned to ${h.constraint} in your project, which cannot resolve the ${p} the generated code needs. Raising it to ^${p} — this changes a dependency the rest of your app also uses.`)}if(u.length>0){const c=await i(u,o);for(const d of u){const h=c.get(d);if(h?.constraint){a.additions[d]=h.constraint;continue}const p=e[d]||"";if(ln(p)){a.additions[d]=`^${ln(p)}`,a.warnings.push(`Could not confirm "${d}" version on pub.dev (${h?.error||"lookup failed"}). Using ^${ln(p)} from the AI's recommendation — verify this is current.`);continue}a.additions[d]=">=0.0.0",a.warnings.push(`Could not determine a version for "${d}" (${h?.error||"lookup failed"}) and the AI supplied none. Added with a wide-open >=0.0.0 constraint — pin a concrete version in FlutterFlow before deploying.`)}}return a}const Km={"&":"&","<":"<",">":">",'"':""","'":"'"};function xt(t){return String(t??"").replace(/[&<>"']/g,e=>Km[e])}function j(t){return t?xt(t).replace(/\n/g,"
"):""}function Ft(t){return xt(t).replace(/\r?\n/g," ")}function Jm(t,e={}){const n=t?.pipelineStep;if(n!=null&&e[n]!=null)return e[n];const i=t?.message||"";return i.includes("Code Generator")?2:i.includes("Code Review")?3:1}function Ym(t){const e={"Integration Audit Report":"📋","Critical Issues":"❌",Warnings:"⚠️",Recommendations:"✅","Overall Score":"📊"};for(const[n,i]of Object.entries(e))if(t.toLowerCase().includes(n.toLowerCase()))return i;return"📄"}function Zm(t){const e={critical:"❌",warning:"⚠️",recommendation:"✅",score:"📊",issue:"🔍",fix:"🔧"};for(const[n,i]of Object.entries(e))if(t.toLowerCase().includes(n.toLowerCase()))return i;return"📝"}function Xm(t){return t.includes("class ")&&t.includes("extends ")||t.includes("StatelessWidget")||t.includes("StatefulWidget")||t.includes("import 'package:flutter/")?"dart":t.includes("def ")||t.includes("import ")||t.includes("print(")?"python":t.includes("function ")||t.includes("const ")||t.includes("console.")?"javascript":"dart"}function xn(t){if(!t)return"";if(typeof t!="string")return String(t);const e=/```(?:\w+)?\n?([\s\S]*?)```/,n=t.match(e);return n?n[1].trim():t.trim()}function xc(t){return t=xt(t),t=t.replace(/\*\*(.*?)\*\*/g,'$1'),t=t.replace(/\*(.*?)\*/g,'$1'),t=t.replace(/`(.*?)`/g,'$1'),t=t.replace(/\b(FAIL|ERROR|CRITICAL)\b/g,'$1'),t=t.replace(/\b(WARN|WARNING)\b/g,'$1'),t=t.replace(/\b(PASS|SUCCESS|OK)\b/g,'$1'),t}function Vd(t,e="dart",n=globalThis.hljs){if(!t)return"";const i=xn(t);try{return n.highlight(i,{language:e}).value}catch(s){console.warn("Syntax highlighting failed:",s);try{return n.highlight(i,{language:"json"}).value}catch{return xt(i)}}}function Ks(t,e={}){const{highlighter:n=globalThis.hljs}=e;let i='
';const s=String(t??"").split(` +`);let r=!1,o="";for(const a of s){if(a.startsWith("```")){if(r){const l=Xm(o),u=Vd(o.trim(),l,n);i+=`
+
${u}
+
`,o="",r=!1}else r=!0;continue}if(r){o+=a+` +`;continue}if(a.startsWith("# ")){const l=a.substring(2).trim();i+=`
+

+ ${Ym(l)} + ${xt(l)} +

+
`;continue}if(a.startsWith("## ")){const l=a.substring(3).trim();i+=`
+

+ ${Zm(l)} + ${xt(l)} +

+
`;continue}if(/^[-*+]\s+/.test(a)||/^\d+\.\s+/.test(a)){const l=a.replace(/^([-*+]|\d+\.)\s+/,"").trim();i+=`
+ • + ${xc(l)} +
`;continue}a.trim()!==""&&(i+=`

${xc(a)}

`)}return i+="
",` +
+
+
+ Live Audit Report +
+ ${i} +
+ `}const Qm=[[/gradient stroke\s*$/i," and an animated percentage label"],[/gauge\s*$/i," with a gradient stroke and animated fill"],[/rating\s*(bar|widget)?\s*$/i," with half-star support and haptic feedback"],[/list\s*$/i," with swipe-to-delete and an undo snackbar"],[/pad\s*$/i," that exports a transparent PNG"],[/carousel\s*$/i," with parallax cards and page indicators"],[/(button|cta)\s*$/i," with a loading spinner and success state"],[/(chart|graph)\s*$/i," that animates from a Firestore stream"],[/action\s*(that|to)?\s*$/i," uploads an image to Firebase Storage and returns the URL"],[/timer\s*$/i," with pause, resume and a completion callback"],[/map\s*$/i," with clustered markers and a custom info window"],[/^a\s+\w*$/i," widget that"],[/(picker|selector)\s*$/i," with search and multi-select"]],ev=220,tv=6;function kc(t,e){return!!(t&&t.trim())&&!e}function nv(t,e=""){if(typeof t!="string"||!t||t===e||t.trim().lengthi.test(t));return n?n[1]:null}function iv(){let t="",e="";return{get active(){return t},resolve(n){return t=nv(n,e)??"",t},dismiss(){t=""},accept(n){if(!t)return null;const i=n+t;return e=i,t="",i}}}function sv({onSubmit:t}){const e=document.getElementById("composer"),n=document.getElementById("pipeline-input"),i=document.getElementById("hero-send");if(!e||!n||!i||typeof t!="function")return;const s=e.querySelector(".ghost .typed"),r=e.querySelector(".ghost .suggest"),o=document.getElementById("tab-hint"),a=document.getElementById("suggest-status"),l=Array.from(document.querySelectorAll("#example-chips .chip")),u=window.matchMedia("(prefers-reduced-motion: reduce)"),c=iv();let d=!1,h=!1,p=null,f=null;function g(){i.disabled=!kc(n.value,h)}function m(){s&&(s.textContent=n.value)}function v(){r&&(r.textContent=""),m(),e.classList.remove("has-suggest"),o&&(o.hidden=!0,o.tabIndex=-1),a&&(a.textContent="")}function b(P){r&&(r.textContent=P),m(),e.classList.add("has-suggest"),o&&(o.hidden=!1,o.tabIndex=0,o.setAttribute("aria-label","Accept suggestion: "+P.trim())),a&&(a.textContent="Suggestion: "+P+". Press Tab to accept.")}function w(){c.dismiss(),v()}function I(){if(d||h)return;const P=c.resolve(n.value);P&&b(P)}function A(){clearTimeout(p),!d&&(p=setTimeout(I,ev))}function F(){const P=c.accept(n.value);return P===null?!1:(n.value=P,v(),g(),!0)}function D(P){h=P,e.classList.toggle("is-busy",P),i.classList.toggle("is-busy",P),i.setAttribute("aria-label",P?"Generating":"Generate"),g()}async function S(){if(kc(n.value,h)){w(),D(!0);try{await t()}finally{D(!1)}}}function $(){f&&(clearInterval(f),f=null),e.classList.remove("is-demo-typing")}function T(){l.forEach(P=>{P.classList.remove("is-active"),P.setAttribute("aria-pressed","false")})}function M(){try{n.focus({preventScroll:!0}),n.setSelectionRange(n.value.length,n.value.length)}catch{}}function N(P){const z=P.dataset.prompt||"";if($(),w(),l.forEach(U=>{const Q=U===P;U.classList.toggle("is-active",Q),U.setAttribute("aria-pressed",String(Q))}),u.matches||!z){n.value=z,m(),g(),M();return}n.value="",m(),g(),e.classList.add("is-demo-typing");let H=0;f=setInterval(()=>{H+=1,n.value=z.slice(0,H),m(),g(),H>=z.length&&($(),M())},22)}l.forEach(P=>{P.setAttribute("aria-pressed","false"),P.addEventListener("click",()=>N(P))}),n.addEventListener("keydown",P=>{$(),P.key==="Tab"&&!P.shiftKey&&c.active?(P.preventDefault(),F()):P.key==="Escape"?w():P.key==="Enter"&&!P.shiftKey&&!P.isComposing&&!d&&(P.preventDefault(),S())}),n.addEventListener("input",()=>{$(),T(),w(),g(),A()}),n.addEventListener("compositionstart",()=>{d=!0}),n.addEventListener("compositionend",()=>{d=!1,w(),g(),A()}),n.addEventListener("scroll",()=>{s&&s.parentNode&&(s.parentNode.scrollTop=n.scrollTop)}),o&&o.addEventListener("click",()=>{F(),n.focus({preventScroll:!0})}),i.addEventListener("click",S),n.addEventListener("pointerdown",()=>{$(),T()}),m(),g()}const rv="https://ccc-ffai-runner-y5cyj3473a-uw.a.run.app/deployCustomClasses";const Ze="https://4tgke4.buildship.run",Gd={professional:"price_1T2ldCKszA2slvDXatdeCpbI",power:"price_1T2le9KszA2slvDXR4mPvw7M"},Is="ccc_auth_session",Ic=new WeakSet;let V={email:null,sessionToken:null,isVerified:!1};function kn(t={}){return{tier:"free",status:"none",periodEnd:null,isLoading:!1,isResolved:!1,error:null,...t}}let pe=kn({isResolved:!0});const ov=`${Ze}/service/runpipeline`,av="bs_user_id",lv="bs_identity_token",cv=`${Ze}/authUserCheck`;let Ke={userId:null,token:null,status:null,resolved:!1};const Cs={free:2,professional:50,power:2e3},As="ccc_subscription",Cc=3,uv=new Set(["active","trialing","paid"]),pi="google/gemini-3.7-flash",Ji=["anthropic/claude-opus-5","openai/gpt-5.6-sol","z-ai/glm-5.2","moonshotai/kimi-k3","openrouter/auto-beta","openrouter/free","openrouter/deepseek/deepseek-v4-pro"],dv={"google/gemini-3.7-flash":"Gemini 3.7 Flash","anthropic/claude-opus-5":"Claude Opus 5","openai/gpt-5.6-sol":"GPT-5.6 Sol","z-ai/glm-5.2":"GLM 5.2","moonshotai/kimi-k3":"Kimi K3","openrouter/auto-beta":"OpenRouter: Auto Router","openrouter/free":"OpenRouter: Free Models","openrouter/deepseek/deepseek-v4-pro":"DeepSeek v4 Pro"};function Kt(t){return dv[t]||t}const hv=new Set(["google/gemini-3.7-flash","anthropic/claude-opus-5","openai/gpt-5.6-sol","z-ai/glm-5.2","moonshotai/kimi-k3","openrouter/auto-beta"]);function Kd(t){return hv.has(t)}const Lo=4,Dr=8*1024*1024,pv="https://4tgke4.buildship.run/service/runpipeline-image";let Tt=[];function fv(t){return new Promise(e=>{const n=new FileReader;n.onload=()=>e(n.result),n.onerror=()=>e(null),n.readAsDataURL(t)})}async function gv(t){const e=new FormData;return e.append("file",t),(await fetch(pv,{method:"POST",body:e})).json()}function mv(t){if(Array.isArray(t)){const e=t[0];if(e&&typeof e=="object")for(const n of Object.keys(e)){if(n==="item"||n==="index")continue;const i=e[n];if(i&&typeof i=="object"){if(typeof i.file=="string")return i.file;if(typeof i.url=="string")return i.url}if(typeof i=="string")return i}return""}return typeof t=="string"?t:t&&typeof t=="object"&&(t.url||t.fileUrl||t.file_url||t.downloadUrl||t.imageUrl||t.image_url||t.file)||""}async function vv(t){const e=Array.from(t.target.files||[]);if(!e.length)return;const n=e.filter(l=>l.size>Dr);n.length&&ue(`Skipped ${n.length} image(s) over the ${(Dr/1024/1024).toFixed(0)} MB limit.`,"warning");const i=e.filter(l=>l.size<=Dr);if(!i.length){t.target.value="";return}const s=Lo-Tt.length,o=i.slice(0,s).map(async l=>{const u=await fv(l);if(!u)return null;let c="";try{c=mv(await gv(l))}catch{c=""}return{dataUrl:u,name:l.name,url:c}}),a=(await Promise.all(o)).filter(Boolean);t.target.value="",!(a.length&&!Kd(document.getElementById("code-generator-model")?.value))&&(Tt.push(...a),i.length>s&&ue(`You can attach up to ${Lo} images.`,"info"),ba())}function _v(t){Tt.splice(t,1),ba()}function ba(){const t=document.getElementById("prompt-image-thumbnails"),e=document.getElementById("prompt-image-btn-label");t&&(t.innerHTML="",Tt.forEach((n,i)=>{const s=document.createElement("div");s.className="prompt-img-thumb",s.innerHTML=`Prompt image`,t.appendChild(s)}),e&&(e.textContent=Tt.length>=Lo?"Image limit reached":"Add images"))}function Jd(){const t=document.getElementById("prompt-image-upload");if(!t)return;const e=document.getElementById("code-generator-model"),n=Kd(e?.value);t.classList.toggle("hidden",!n),!n&&Tt.length&&(Tt=[],ba())}const Zt="ccc_usage",Yd="google/gemini-3.7-flash",Zd="google/gemini-3.7-flash",jr="google/gemini-3.7-flash",Oi={professional:11,power:49},Oo={en_US:"USD",en_GB:"GBP",en_AU:"AUD",en_NZ:"NZD",en_CA:"CAD",en_IN:"INR",en_SG:"SGD",en_HK:"HKD",en_PH:"PHP",en_ZA:"ZAR",en:"USD",de:"EUR",fr:"EUR",es:"EUR",it:"EUR",nl:"EUR",pt_PT:"EUR",pt_BR:"BRL",pt:"BRL",ja:"JPY",ko:"KRW",zh_CN:"CNY",zh_TW:"TWD",zh:"CNY",th:"THB",vi:"VND",id:"IDR",ms_MY:"MYR",ms:"MYR",sv:"SEK",nb:"NOK",da:"DKK",pl:"PLN",cs:"CZK",hu:"HUF",ro:"RON",tr:"TRY",ar:"AED",he:"ILS",ru:"RUB",uk:"UAH"},Yi={AUD:1,USD:.65,EUR:.6,GBP:.52,CAD:.88,NZD:1.08,JPY:97,KRW:870,INR:54,SGD:.87,HKD:5.08,BRL:3.18,CNY:4.7,TWD:20.5,THB:22.5,VND:16200,IDR:10200,MYR:2.88,SEK:6.8,NOK:6.95,DKK:4.48,PLN:2.6,CZK:15.2,HUF:238,RON:2.98,TRY:20.9,AED:2.39,ILS:2.38,PHP:36.4,ZAR:11.8,RUB:58,UAH:26.8,CHF:.57,MXN:11.1,ARS:580,CLP:610,COP:2700,PEN:2.44};let Zi={...Yi};async function yv(){const t=new AbortController,e=setTimeout(()=>t.abort(),5e3);try{const n=await fetch("https://open.er-api.com/v6/latest/AUD",{signal:t.signal});if(!n.ok)return;const i=await n.json();if(i.result!=="success"||!i.rates)return;const s=i.rates,r={AUD:1},o=new Set([...Object.keys(Yi),...Object.values(Bo),...Object.values(Oo)]);for(const a of o)a!=="AUD"&&(typeof s[a]=="number"&&s[a]>0?r[a]=s[a]:Yi[a]&&(r[a]=Yi[a]));Zi=r}catch{}finally{clearTimeout(e)}}const Bo={"America/Sao_Paulo":"BRL","America/Fortaleza":"BRL","America/Recife":"BRL","America/Bahia":"BRL","America/Belem":"BRL","America/Manaus":"BRL","America/Cuiaba":"BRL","America/Campo_Grande":"BRL","America/Araguaina":"BRL","America/Noronha":"BRL","America/Rio_Branco":"BRL","America/Porto_Velho":"BRL","America/Boa_Vista":"BRL","America/Maceio":"BRL","America/Santarem":"BRL","America/Eirunepe":"BRL","Europe/London":"GBP","Europe/Paris":"EUR","Europe/Berlin":"EUR","Europe/Madrid":"EUR","Europe/Rome":"EUR","Europe/Amsterdam":"EUR","Europe/Brussels":"EUR","Europe/Vienna":"EUR","Europe/Lisbon":"EUR","Europe/Dublin":"EUR","Europe/Helsinki":"EUR","Europe/Athens":"EUR","Europe/Bucharest":"RON","Europe/Budapest":"HUF","Europe/Warsaw":"PLN","Europe/Prague":"CZK","Europe/Copenhagen":"DKK","Europe/Stockholm":"SEK","Europe/Oslo":"NOK","Europe/Zurich":"CHF","Europe/Istanbul":"TRY","Europe/Moscow":"RUB","Europe/Kiev":"UAH","Europe/Kyiv":"UAH","Asia/Tokyo":"JPY","Asia/Seoul":"KRW","Asia/Shanghai":"CNY","Asia/Taipei":"TWD","Asia/Hong_Kong":"HKD","Asia/Singapore":"SGD","Asia/Kolkata":"INR","Asia/Calcutta":"INR","Asia/Bangkok":"THB","Asia/Ho_Chi_Minh":"VND","Asia/Jakarta":"IDR","Asia/Kuala_Lumpur":"MYR","Asia/Dubai":"AED","Asia/Jerusalem":"ILS","Asia/Tel_Aviv":"ILS","Asia/Manila":"PHP","Pacific/Auckland":"NZD","Australia/Sydney":"AUD","Australia/Melbourne":"AUD","Australia/Brisbane":"AUD","Australia/Perth":"AUD","Australia/Adelaide":"AUD","Australia/Hobart":"AUD","Australia/Darwin":"AUD","Australia/Lord_Howe":"AUD","America/Toronto":"CAD","America/Vancouver":"CAD","America/Edmonton":"CAD","America/Winnipeg":"CAD","America/Halifax":"CAD","America/St_Johns":"CAD","America/Regina":"CAD","America/New_York":"USD","America/Chicago":"USD","America/Denver":"USD","America/Los_Angeles":"USD","America/Phoenix":"USD","America/Anchorage":"USD","Pacific/Honolulu":"USD","America/Mexico_City":"MXN","America/Cancun":"MXN","America/Tijuana":"MXN","America/Argentina/Buenos_Aires":"ARS","America/Santiago":"CLP","America/Bogota":"COP","America/Lima":"PEN","Africa/Johannesburg":"ZAR"};function Xd(){try{const r=Intl.DateTimeFormat().resolvedOptions().timeZone;if(r&&Bo[r])return Bo[r]}catch{}const e=(navigator.language||"en-US").replace("-","_"),n=Oo[e];if(n)return n;const i=e.split("_")[0],s=Oo[i];return s||"USD"}function Bi(t,e){const n=Zi[e]??Zi.USD,i=t*n,s=Math.round(i*100)/100;try{return new Intl.NumberFormat("en-US",{style:"currency",currency:e,minimumFractionDigits:0,maximumFractionDigits:s>=100||s%1===0?0:2}).format(s)}catch{return new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",minimumFractionDigits:0,maximumFractionDigits:2}).format(t*Zi.USD)}}const rt="ccc_api_key_",bt="ccc_session_api_key_",lt="ccc_encryption_key",fi="ccc_encryption_key_scope",wv="ccc_keystore",Fs="keys",gi="ccc_encryption_key_version";let Do=null,Ps=null,mi=!1,$s=!1,Ac=!1;class Ts extends Error{constructor(){super("Secure browser key storage is unavailable."),this.name="CredentialStorageUnavailableError"}}function Fc(){if(Ac)return;Ac=!0;const t="Secure browser key storage is unavailable. Existing credentials were left untouched; new credentials will be available only in this tab session.";console.warn(t),document.body&&ue(t,"warning")}function Qd(){return localStorage.getItem(gi)||""}function jo(){return crypto.randomUUID?.()||th(crypto.getRandomValues(new Uint8Array(16)))}function bv(){const t=Qd();if(t)return t;const e=jo();return localStorage.setItem(gi,e),e}function In(){Do=null,Ps=null,mi=!1,$s=!1}window.addEventListener("storage",t=>{t.key===gi&&In()});function Ev(){return new Promise((t,e)=>{const n=indexedDB.open(wv,1);n.onupgradeneeded=()=>{const i=n.result;i.objectStoreNames.contains(Fs)||i.createObjectStore(Fs)},n.onsuccess=()=>t(n.result),n.onerror=()=>e(n.error)})}async function Ea(t,e){const n=await Ev();return new Promise((i,s)=>{const r=n.transaction(Fs,t);let o;try{o=e(r.objectStore(Fs))}catch(l){n.close(),s(l);return}let a;o.onsuccess=()=>{a=o.result},o.onerror=()=>s(o.error),r.oncomplete=()=>{n.close(),i(a)},r.onerror=()=>{n.close(),s(r.error||new Error("Encryption key transaction failed."))},r.onabort=()=>{n.close(),s(r.error||new Error("Encryption key transaction aborted."))}})}function Sv(t){return t instanceof CryptoKey&&t.algorithm?.name==="AES-GCM"&&t.extractable===!1&&t.usages.includes("encrypt")&&t.usages.includes("decrypt")}async function xv(){const t=await Ea("readonly",e=>e.get(lt));return Sv(t)?t:null}async function eh(t){await Ea("readwrite",e=>e.put(t,lt))}async function kv(){In();try{await Ea("readwrite",t=>t.delete(lt))}catch(t){console.warn("Could not delete the stored encryption key:",t)}}async function Iv(){const t=sessionStorage.getItem(lt);if(!t)return null;const e=await crypto.subtle.importKey("jwk",JSON.parse(t),{name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);return await eh(e),sessionStorage.removeItem(lt),sessionStorage.removeItem(fi),localStorage.removeItem(rt+"salt"),e}async function Pc(t){const e=sessionStorage.getItem(lt);if(e)return $s=sessionStorage.getItem(fi)!=="session",crypto.subtle.importKey("jwk",JSON.parse(e),{name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);if(!t)throw new Ts;const n=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!0,["encrypt","decrypt"]),i=await crypto.subtle.exportKey("jwk",n);return sessionStorage.setItem(lt,JSON.stringify(i)),sessionStorage.setItem(fi,"session"),$s=!1,crypto.subtle.importKey("jwk",i,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}async function Cv(t){if(sessionStorage.getItem(fi)==="session"&&sessionStorage.getItem(lt))return Fc(),mi=!0,Pc(t);try{const e=await xv();if(e)return e;const n=await Iv();if(n)return n;const i=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);return await eh(i),i}catch(e){return console.warn("IndexedDB encryption-key storage failed:",e),Fc(),mi=!0,Pc(t)}}async function Sa(t={}){const{allowSessionFallbackCreation:e=!0}=t,n=bv();Ps!==n&&In();const i=Do||Cv(e);Do=i,Ps=n;try{return await i}catch(s){throw In(),s}}async function Av(t){const e=await Sa(),n=Ps,i=new TextEncoder,s=crypto.getRandomValues(new Uint8Array(12)),r=await crypto.subtle.encrypt({name:"AES-GCM",iv:s},e,i.encode(t)),o=new Uint8Array(s.length+r.byteLength);return o.set(s),o.set(new Uint8Array(r),s.length),{ciphertext:th(o),keyVersion:n,sessionFallback:mi}}async function Fv(t,e={}){const{isSessionCredential:n=!1}=e;try{const i=await Sa({allowSessionFallbackCreation:!1});if(mi&&!n&&!$s)throw new Ts;const s=Pv(t),r=s.slice(0,12),o=s.slice(12),a=await crypto.subtle.decrypt({name:"AES-GCM",iv:r},i,o);return new TextDecoder().decode(a)}catch(i){if(i instanceof Ts)throw i;return console.error("Decryption failed:",i),null}}function th(t){const e=new Uint8Array(t);let n="";for(let i=0;i0}let vi="",Rs="",ni=null,Tc=0;async function xa(){sessionStorage.getItem(lt)&&await Sa(),vi=await Ee("flutterflow"),Rs=await Ee("flutterflow_project_id"),Mv(),en()}function ka(){const t=document.getElementById("api-keys-modal");Ve(t),Ca(),vi&&rh(vi)}function nh(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("api-keys-modal");e&&Xe(e);const n=document.getElementById("walkthrough-modal");n&&(Ia(),Ve(n))}let kt=1;function ih(){const t=document.querySelector(".wt-steps");return t?Array.from(t.querySelectorAll(".wt-step-card")):[]}function Js(){const t=ih();t.length&&t.forEach((e,n)=>{const i=n+1;if(i===kt){e.classList.remove("opacity-60","bg-gray-50","border-gray-200"),e.classList.add("bg-blue-50","border-blue-200");const s=e.querySelector("div:first-child");s&&(s.classList.remove("bg-gray-400"),s.classList.add("bg-blue-500"),s.innerHTML=i)}else if(i0&&kt<=t&&(kt++,Js())}function Tv(){const t=document.getElementById("walkthrough-modal");t&&(kt=1,Js(),Ve(t))}function Rv(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("walkthrough-modal");e&&Xe(e);const n=document.getElementById("walkthrough-dont-show");n&&n.checked&&localStorage.setItem("hasSeenWalkthrough","true")}function sh(){if(V.isVerified&&Nt()&&pe.tier!=="free")return;if(!localStorage.getItem("hasSeenWalkthrough")){const e=document.getElementById("walkthrough-modal");e&&(kt=1,Js(),Ve(e))}}async function Ca(){const t=document.getElementById("flutterflow-api-key-input");vi?(t.value="",t.placeholder="Key saved (enter new to replace)"):t.placeholder="Enter your FlutterFlow API key",Nv()}function Nv(){Rc("flutterflow","flutterflow-key-status"),Rc("flutterflow_project_id","flutterflow-project-status")}function Rc(t,e){const n=document.getElementById(e);if(!n)return;const i=n.querySelector(".key-status-dot"),s=n.querySelector("span");dn(t)?(i.className="key-status-dot configured",s.className="text-green-600",s.textContent="User key configured"):(i.className="key-status-dot missing",s.className="text-gray-500",s.textContent="Not configured")}function en(){const t=y.step2Result&&y.step2Result.length>0,e=document.getElementById("btn-deploy-to-ff"),n=document.getElementById("btn-run-pipeline");n&&n.classList.remove("hidden"),e&&e.classList.toggle("hidden",!t)}function Mv(){const t=document.getElementById("api-keys-status");if(!t)return;const e=t.querySelectorAll(".key-status-dot"),n=["flutterflow"];e.forEach((i,s)=>{const r=n[s];r==="flutterflow"?dn("flutterflow")&&dn("flutterflow_project_id")?(i.className="key-status-dot configured",i.title="FlutterFlow (Fully configured)"):dn("flutterflow")||dn("flutterflow_project_id")?(i.className="key-status-dot env",i.title="FlutterFlow (Partially configured)"):(i.className="key-status-dot missing",i.title="FlutterFlow (Not configured)"):dn(r)?(i.className="key-status-dot configured",i.title=r.charAt(0).toUpperCase()+r.slice(1)+" (User key)"):(i.className="key-status-dot missing",i.title=r.charAt(0).toUpperCase()+r.slice(1)+" (Not configured)")}),en()}async function Lv(){const t=document.getElementById("flutterflow-api-key-input"),e=document.getElementById("flutterflow-projects-select");t.value.trim()&&await $c("flutterflow",t.value);const n=e?.value.trim()||"";if(n){if(!Ys(n)){ue("The selected FlutterFlow project has an unexpected ID format.","error"),e.focus();return}await $c("flutterflow_project_id",n)}await xa(),Ca();const i=document.querySelector("#api-keys-modal .bg-blue-500"),s=i.textContent;i.textContent="Saved!",i.classList.remove("bg-blue-500","hover:bg-blue-600"),i.classList.add("bg-green-500"),setTimeout(()=>{i.textContent=s,i.classList.remove("bg-green-500"),i.classList.add("bg-blue-500","hover:bg-blue-600"),nh()},1e3)}async function Ov(){if(!confirm("Are you sure you want to clear all stored API keys?"))return;localStorage.setItem(gi,jo()),In(),localStorage.removeItem(rt+"flutterflow"),localStorage.removeItem(rt+"flutterflow_project_id"),sessionStorage.removeItem(bt+"flutterflow"),sessionStorage.removeItem(bt+"flutterflow_project_id"),sessionStorage.removeItem(lt),sessionStorage.removeItem(fi),localStorage.removeItem(rt+"salt"),await kv(),localStorage.setItem(gi,jo()),localStorage.removeItem(rt+"flutterflow"),localStorage.removeItem(rt+"flutterflow_project_id"),sessionStorage.removeItem(bt+"flutterflow"),sessionStorage.removeItem(bt+"flutterflow_project_id"),await xa();const t=document.getElementById("flutterflow-projects-select");t&&(t.innerHTML=''),Ca()}function Ys(t){return!t||t.trim().length<5||t.includes(" ")?!1:/^[a-zA-Z0-9-]+$/.test(t)}function Bv(t,e){const n=document.getElementById(t);n&&(n.value?e?n.style.borderColor="#22c55e":n.style.borderColor="#ef4444":n.style.borderColor="")}function Dv(){const t=document.getElementById("flutterflow-api-key-input");t&&(t.addEventListener("input",e=>{const n=e.target.value.trim().length>0;Bv("flutterflow-api-key-input",n)}),t.addEventListener("blur",jv(async e=>{const n=e.target.value.trim();n&&await rh(n)},500)))}function jv(t,e){let n;return function(...s){const r=()=>{clearTimeout(n),t(...s)};clearTimeout(n),n=setTimeout(r,e)}}async function rh(t){const e=document.getElementById("flutterflow-projects-select"),n=document.getElementById("flutterflow-projects-error");if(!e){console.error("Projects dropdown element not found");return}e.innerHTML='',n&&n.classList.add("hidden");try{const s=await new wi(t,"").listProjects();if(!s||s.length===0){e.innerHTML='';return}e.innerHTML='',s.forEach(r=>{const o=document.createElement("option");o.value=r.id||r.projectId||"",o.textContent=r.name||r.projectName||`Project ${r.id}`,e.appendChild(o)}),Rs&&(e.value=Rs)}catch(i){console.error("Failed to fetch projects:",i),e.innerHTML='',n&&(n.textContent=`Failed to load projects: ${i.message}`,n.classList.remove("hidden"))}}function Uv(t){const e=document.getElementById(t),i=e.nextElementSibling.querySelector("svg");e.type==="password"?(e.type="text",i.innerHTML=` + + `):(e.type="password",i.innerHTML=` + + + `)}let y={step1Result:null,step2Result:null,step3Result:null,bundleSpec:null,artifactBundle:null,bundleReview:null,selectedArtifactId:null,resultsViewMode:"summary",currentStep:0,isRunning:!1};function Hv(){y.step1Result=null,y.step2Result=null,y.step3Result=null,y.bundleSpec=null,y.artifactBundle=null,y.bundleReview=null,y.selectedArtifactId=null,y.resultsViewMode="summary"}function Wv(){y.bundleSpec=di(y.step1Result,{artifactType:"CustomWidget",artifactName:"GeneratedWidget"})}function Zs(){const t=Ss(y.bundleSpec);y.artifactBundle=di(y.step2Result,{id:y.bundleSpec?.id,title:y.bundleSpec?.title,description:y.bundleSpec?.description,artifactType:t.artifactType,artifactName:t.artifactName,fileName:t.fileName,dependencies:t.dependencies,relationships:y.bundleSpec?.relationships,code:y.step2Result||""});const e=Ng(y.artifactBundle);y.artifactBundle={...y.artifactBundle,warnings:[...y.artifactBundle.warnings,...e.findings.map(n=>n.message)],metadata:{...y.artifactBundle.metadata,compatibility:e}},y.selectedArtifactId=Ss(y.artifactBundle).id}function Xs(){const t=di(y.step3Result,{id:y.artifactBundle?.id,title:y.artifactBundle?.title}),e=new Map(t.artifacts.map(i=>[i.id,i.review])),n=new Map(t.artifacts.filter(i=>{const s=i.review;return s&&typeof s.fixedSource=="string"&&s.fixedSource.trim()}).map(i=>[i.id,i.review.fixedSource.trim()]));y.bundleReview=di({id:y.artifactBundle?.id,title:y.artifactBundle?.title,artifacts:y.artifactBundle?.artifacts?.map(i=>{const s=n.get(i.id)||null;return{...i,review:e.get(i.id)||i.review||y.step3Result||null,...s?{fixedCode:s}:{}}})||[],relationships:y.artifactBundle?.relationships,warnings:y.artifactBundle?.warnings})}function oh(){const t=Aa();return{artifactType:t.artifactType||"CustomWidget",artifactName:t.artifactName||"GeneratedWidget",fileName:t.fileName||""}}function Aa(){const t=y.artifactBundle||y.bundleSpec||null;return(Array.isArray(t?.artifacts)?t.artifacts:[]).find(n=>n.id===y.selectedArtifactId)||Ss(t)}function Fa(){return Aa().code||y.step2Result||""}async function zv(){try{await xa()}catch(t){return console.error("checkConnection: initializeApiKeys failed:",t),!1}return!0}const Xi={production:"https://api.flutterflow.io/v2/",staging:"https://api.flutterflow.io/v2-staging/"};function qv(t,e){const n=e?.trim()?` (${e.trim().slice(0,200)})`:"";return t===401?`Your FlutterFlow API key was rejected (401 Unauthorized)${n}. Re-enter a current key under API Keys settings, then try again.`:`Listing FlutterFlow projects was denied (403)${n}. The key may be scoped to sync a single project without list permission - verify the key's access in FlutterFlow, re-enter it under API Keys settings, then retry.`}class wi{constructor(e,n,i="main",s=Xi.production){this.apiKey=e,this.baseUrl=s,this._projectId=n,this._branchName=i,this._endpoint=s}get projectId(){return this._projectId}get branchName(){return this._branchName==="main"?"":this._branchName}async exportProjectZip(){console.log(`Exporting code from FlutterFlow project: ${this.projectId}, branch: ${this.branchName||"main"}`);const e=[{project:{path:`projects/${this.projectId}`},...this.branchName?{branch_name:this.branchName}:{},export_as_module:!1,include_assets_map:!1,format:!1,export_as_debug:!1},{project_id:this.projectId,branch_name:this.branchName,include_assets:!1,export_as_module:!1}];let n=null;for(const i of e)try{const s=await fetch(`${this.baseUrl}exportCode`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify(i)});if(!s.ok){const a=await s.text();n=new Error(`Export failed: ${s.status} - ${a}`);continue}const r=await s.json(),o=r?.value?.project_zip||r?.project_zip;if(!o){n=new Error("Export response did not include project source.");continue}return o}catch(s){n=s}throw n||new Error("Export failed for an unknown reason.")}async fetchProjectSource(){const e=await this.exportProjectZip(),n=await JSZip.loadAsync(e,{base64:!0}),i=Object.keys(n.files).filter(a=>!n.files[a].dir&&(a==="pubspec.yaml"||a.endsWith("/pubspec.yaml"))).sort((a,l)=>a.split("/").length-l.split("/").length)[0];if(!i)throw new Error("Export did not contain a pubspec.yaml.");const s=i.slice(0,i.length-12),r=new Map,o=Object.keys(n.files).filter(a=>{if(n.files[a].dir||!a.startsWith(s))return!1;const l=a.slice(s.length);return l==="lib/flutter_flow/custom_functions.dart"||l.startsWith("lib/custom_code/")&&l.endsWith(".dart")});return await Promise.all(o.map(async a=>{r.set(a.slice(s.length),await n.files[a].async("string"))})),{pubspecYaml:await n.files[i].async("string"),files:r}}async pushCodeWithRetry(e,n=3){const i=[Xi.production,Xi.staging],s=Math.max(0,i.indexOf(this._endpoint));for(let r=0;rsetTimeout(d,1e3*(r+1)));continue}return l}catch(l){console.warn(`Push to ${a} failed: ${l.message}, trying next...`),await new Promise(u=>setTimeout(u,1e3*(r+1)))}}throw new Error("All API endpoints failed after retries")}async pushCode(e){return this.pushCodeWithRetry(e)}parseProjectsResponse(e){if(e?.success&&typeof e.value=="string")try{const i=JSON.parse(e.value);if(i&&Array.isArray(i.entries))return i.entries.map(s=>({id:s.id,name:s.project?.name||s.id}))}catch(i){console.error("Failed to parse stringified project value:",i)}const n=e?.projects||e?.items||e?.entries||(Array.isArray(e)?e:[]);return Array.isArray(n)?n:[]}async listProjects(){console.log("Listing projects for API key");const e=[`${this.baseUrl}listProjects`,"https://api.flutterflow.io/v2/l/listProjects"];let n=0,i="";for(const s of e){const r=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify({project_type:"ALL",deserialize_response:!0})});if(r.ok)return s!==e[0]&&console.log(`listProjects answered on legacy path ${s}`),this.parseProjectsResponse(await r.json());if(n=r.status,i=await r.text(),console.warn(`listProjects via ${s} returned ${n}: ${i}`),r.status===401||r.status===403)throw new Error(qv(r.status,i));if(r.status!==404)throw new Error(`List projects failed: ${r.status} - ${i}`)}throw new Error(`List projects failed: ${n} - ${i}`)}}async function Pa(t){const e=t.clone();let n;try{n=await t.json()}catch{const r=await e.text();if(!t.ok)return{success:!1,responseCode:t.status,errorMessage:r||`HTTP ${t.status}`,errorMap:new Map};throw new Error(`Invalid JSON response: ${r}`)}if(!t.ok){let s=n.message||`HTTP ${t.status}`,r=new Map;if(n.errors)r=new Map(Object.entries(n.errors));else if(!n.message&&typeof n=="object"){const o=Object.keys(n).filter(a=>a.endsWith(".dart")&&Array.isArray(n[a]));o.length>0&&(r=new Map(Object.entries(n)),s=o.flatMap(l=>n[l].map(u=>`${l}: ${u.errorMessage}`)).join(` +`)||`HTTP ${t.status}`)}return{success:!1,responseCode:t.status,errorMessage:s,errorMap:r}}let i={};if(n.value)try{i=typeof n.value=="string"?JSON.parse(n.value):n.value}catch(s){console.warn("Ignoring malformed push response value:",s)}return{success:!0,responseCode:t.status,errorMap:new Map(Object.entries(i))}}function $a(t,e){return{401:"Authentication failed. Please check your FlutterFlow API key.",403:"Access denied. You may not have permission to modify this project.",404:"Project not found. Please check your Project ID.",409:"Conflict detected. The project may have been modified elsewhere.",422:"Validation failed: Invalid request format",429:"Rate limit exceeded. Please try again in a few minutes.",500:"FlutterFlow server error. Please try again later.",503:"FlutterFlow service temporarily unavailable."}[t]||`FlutterFlow API error: ${`HTTP ${t}`}`}const W={ACTION:"A",WIDGET:"W",FUNCTION:"F",CODE_FILE:"C",DEPENDENCIES:"D",OTHER:"O"},ah=/class\s+\w+\s+extends\s+(?:StatelessWidget|StatefulWidget)\b/,lh=/extends\s+State<\w+>/;function Vv(t,e=""){if(t==="pubspec.yaml")return W.DEPENDENCIES;if(!t.endsWith(".dart")||t.endsWith("index.dart"))return W.OTHER;if(t==="custom_functions.dart")return W.FUNCTION;if(e){const n=ah.test(e),i=lh.test(e);if(n||i)return W.WIDGET;if(/^\s*Future(?:<[^>]+>)?\s+\w+\s*\(/m.test(e))return W.ACTION;if(e.match(/^\s*(String|int|double|bool|List|Map|dynamic|void)\s+\w+\s*\(/m))return W.FUNCTION}return W.CODE_FILE}function ch(t,e){switch(e){case W.ACTION:return`lib/custom_code/actions/${t}`;case W.WIDGET:return`lib/custom_code/widgets/${t}`;case W.FUNCTION:return"lib/flutter_flow/custom_functions.dart";case W.CODE_FILE:return`lib/custom_code/${t}`;case W.DEPENDENCIES:return"pubspec.yaml";case W.OTHER:return`lib/custom_code/${t}`;default:return t}}async function Ta(t,e=new Map){return mg(t,e)}const Uo=new Map;function uh(t){return`${t.baseUrl}|${t.projectId}|${t.branchName}`}function Qs(t){Uo.delete(uh(t))}async function Ra(t,e,n,i,s=""){const r=Kg(e,n);if(r.length===0)return{remoteFiles:n,syncFileMap:e,unverified:[],approximate:[]};const o=Nm(r,s),a={...o.manifest,sources:o.sources},l=o.skipped.map(h=>h.reason);l.forEach(h=>console.warn(`[custom class deploy] ${h}`));const u=o.approximate;u.forEach(h=>console.warn(`[custom class deploy] ${h}`)),console.log(`Provisioning ${r.length} new FlutterFlow custom code file(s) before sync.`),be.set("provision");const c=await fetch(rv,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:t.apiKey,projectId:t.projectId,baseUrl:t.baseUrl,commitMessage:i,customClasses:r,verification:a,stream:!0})}),d=await Lm(c,{onPhase:h=>be.setSubstatus(h),onLog:h=>console.log(`[custom class deploy] ${h}`)});if(!d.success){const h=d.details?` ${d.details}`:"";throw new Error(`${d.error||"FlutterFlow custom class provisioning failed."}${h}`)}return Qs(t),d.verificationSkipped&&(console.warn(`[custom class deploy] ${d.verificationSkipped}`),l.push(d.verificationSkipped)),{remoteFiles:n,syncFileMap:Jg(e,r),unverified:l,approximate:u}}async function Na(t,e={}){const n=uh(t);let i=Uo.get(n);if(i===void 0){try{i=await t.fetchProjectSource()}catch(l){throw new Error(`Could not read your project's pubspec.yaml (${l.message}). Deploy was stopped so your existing package dependencies aren't overwritten. Check your FlutterFlow API key and project, then try again.`)}const a=zd(i.pubspecYaml);if(!a.valid)throw new Error(`Your project's pubspec.yaml could not be read reliably (${a.errors.join("; ")}). Deploy was stopped so your existing package dependencies aren't overwritten.`);Uo.set(n,i)}const s=await Gm(i.pubspecYaml,e),r=Fm(i.pubspecYaml,s.overrides),o=Am(r.yaml,s.additions);return s.warnings.forEach(a=>console.warn(`[pubspec] ${a}`)),o.added.length>0&&console.log("Adding dependencies:",o.added.map(a=>`${a}: ${s.additions[a]||"any"}`).join(", "),s.sdk.dartSdkFloor?`(resolved for Dart ${s.sdk.dartSdkFloor})`:""),s.kept.forEach(({name:a,constraint:l})=>console.log(`Keeping your existing ${a}: ${l||"(non-version source)"}`)),{...o,overridden:r.overridden,warnings:s.warnings,remoteFiles:i.files}}function Gv(t){const e=[],n=[];t.content.length>5e4&&n.push("Code file is large (>50KB). This may take longer to commit."),t.content.length>1e5&&e.push("Code file is too large (>100KB). Consider splitting into smaller components.");const i=t.content.split(` +`).length;i>500&&n.push(`Code has ${i} lines. Consider breaking it into smaller widgets.`),t.content.includes("setState")&&t.codeType===W.ACTION&&n.push("Using setState in a Custom Action may not work as expected. Consider using a Custom Widget."),t.content.includes("dynamic")&&!t.content.includes("?")&&n.push('Code uses "dynamic" types. Consider adding explicit types for better null safety.'),t.content.match(/Color\(0xFF[0-9A-Fa-f]{6}\)/)&&n.push("Code contains hardcoded colors. Consider using FlutterFlowTheme.of(context) for theme consistency.");const s=t.content.match(/print\s*\(/g);s&&s.length>3&&n.push(`Code contains ${s.length} print statements. Consider removing debug prints before committing.`);const r=pm(t.content);if(r&&e.push(`FlutterFlow cannot format this code - ${r}. Fix or regenerate before committing.`),t.codeType===W.WIDGET){const o=Ld(t.content),a=um(t.fileName);if(o.length===0)e.push("No public widget class found (must extend StatelessWidget or StatefulWidget).");else if(!o.includes(a)){const l=`${Od(o[0])}`;e.push(`Widget class name "${o[0]}" does not match the file name "${t.fileName}". FlutterFlow derives the widget from the file name, so it will report "No widget ${a} found". Rename the file to "${l}" or the class to match before committing.`)}}return{canProceed:e.length===0,issues:e,warnings:n}}function dh(t,e={}){const{artifactType:n="CustomWidget",artifactName:i="GeneratedCode",fileName:s}=e,r=lm(t);let o=s||i;if(n==="CustomFunction")o="custom_functions.dart";else if(n==="CustomWidget"){const u=Ld(r)[0],c=u?Od(u):null;c&&o!==c?(console.warn(`Commit file name "${o}" does not match declared widget class "${u}"; renaming to "${c}" so FlutterFlow can find the widget.`),o=c):o.endsWith(".dart")||(o+=".dart")}else o.endsWith(".dart")||(o+=".dart");let a=W.CODE_FILE;switch(n){case"CustomAction":a=W.ACTION;break;case"CustomWidget":a=W.WIDGET;break;case"CustomFunction":a=W.FUNCTION;break;case"CustomClass":case"CodeFile":a=W.CODE_FILE;break}let l="";return a===W.WIDGET?l=`// Automatic FlutterFlow imports +import '/flutter_flow/flutter_flow_theme.dart'; +import '/flutter_flow/flutter_flow_util.dart'; +import 'package:flutter/material.dart'; +// Begin custom widget code +// DO NOT REMOVE OR MODIFY THE CODE ABOVE! + +`:a===W.ACTION?l=`// Automatic FlutterFlow imports +import '/flutter_flow/flutter_flow_theme.dart'; +import '/flutter_flow/flutter_flow_util.dart'; +import 'package:flutter/material.dart'; +// Begin custom action code +// DO NOT REMOVE OR MODIFY THE CODE ABOVE! + +`:a===W.FUNCTION&&(l=`// Automatic FlutterFlow imports +import 'dart:convert'; +import 'dart:math' as math; + +import 'package:flutter/material.dart'; +import 'package:google_fonts/google_fonts.dart'; +import 'package:intl/intl.dart'; +import 'package:timeago/timeago.dart' as timeago; +import '/flutter_flow/lat_lng.dart'; +import '/flutter_flow/place.dart'; +import '/flutter_flow/uploaded_file.dart'; + +`),{content:Og(r,l),fileName:o,codeType:a,artifactType:n,artifactName:i}}function Kv(t){const e={};for(const n of ma(t))e[n]="";return e}function Jv(t,e={}){return{timestamp:new Date().toISOString(),artifactType:t.artifactType,artifactName:t.artifactName,codeType:t.codeType,fileName:t.fileName,generatedFrom:e.step1Result?"pipeline":"direct",model:e.selectedModel||"unknown",codeSize:t.content.length}}function Yv(t,e,n,i=new Set,s=""){const r=[],o=ah.test(e),a=lh.test(e);return n===W.WIDGET&&!o&&!a&&r.push("No widget class definition found (must extend StatelessWidget or StatefulWidget)"),{valid:r.length===0,errors:r}}function er(t){const e=[],n=[];if(!t||t.size===0)return e.push("No files to commit"),{valid:!1,errors:e,warnings:n};const i=new Set(Array.from(t.values()).flatMap(s=>Hs(s.content||"")));for(const[s,r]of t.entries()){if((!r.content||r.content.trim().length===0)&&e.push(`File ${s} is empty`),r.content&&r.content.length>1e5&&n.push(`File ${s} is very large (>100KB)`),s.endsWith(".dart")){const o=Yv(s,r.content,r.type,i,r.artifactName);o.valid||e.push(...o.errors.map(a=>`${s}: ${a}`))}if(s==="pubspec.yaml"){const o=zd(r.content);o.valid||e.push(...o.errors)}}return{valid:e.length===0,errors:e,warnings:n}}const K={IDLE:"IDLE",PREPARING:"PREPARING",VALIDATING:"VALIDATING",PUSHING:"PUSHING",SUCCESS:"SUCCESS",ERROR:"ERROR"},J={currentState:K.IDLE,startTime:null,endTime:null,error:null,result:null,filesProcessed:0,totalFiles:0,reset(){this.currentState=K.IDLE,this.startTime=null,this.endTime=null,this.error=null,this.result=null,this.filesProcessed=0,this.totalFiles=0},setState(t){if(!Object.values(K).includes(t)){console.error(`Invalid commit state: ${t}`);return}this.currentState=t,t===K.PREPARING&&(this.startTime=Date.now()),(t===K.SUCCESS||t===K.ERROR)&&(this.endTime=Date.now()),typeof window<"u"&&window.dispatchEvent&&window.dispatchEvent(new CustomEvent("commitStateChange",{detail:{state:t,commitState:this}})),console.log(`Commit state changed to: ${t}`)},setError(t){this.error=t,this.setState(K.ERROR)},setSuccess(t){this.result=t,this.setState(K.SUCCESS)},setProgress(t,e){this.filesProcessed=t,this.totalFiles=e},getElapsedTime(){return this.startTime?(this.endTime||Date.now())-this.startTime:null},isInProgress(){return this.currentState===K.PREPARING||this.currentState===K.VALIDATING||this.currentState===K.PUSHING}};async function Zv(t,e,n={}){let{codeType:i="W"}=n;const{pubspecDeps:s={},artifactName:r=e}=n;i==="CustomWidget"&&(i=W.WIDGET),i==="CustomAction"&&(i=W.ACTION),i==="CustomFunction"&&(i=W.FUNCTION),i==="CustomClass"&&(i=W.CODE_FILE),i==="CodeFile"&&(i=W.CODE_FILE),J.reset(),J.setState(K.PREPARING);try{const o=await Ee("flutterflow"),a=await Ee("flutterflow_project_id");if(!o||!a)throw new Error("FlutterFlow credentials not configured. Please set your API key and Project ID in the API Keys settings.");if(!Ys(a))throw new Error("Invalid FlutterFlow Project ID format.");const l=yi(),u=new wi(o,a,"main",l);J.setState(K.VALIDATING);const c=new Map,d=i||Vv(e,t),h=ch(e,d);c.set(e,{artifactName:r,content:t,type:d,path:h}),J.setProgress(0,c.size);const p=er(c);if(!p.valid)throw new Error(`Validation failed: +${p.errors.join(` +`)}`);const f=await Na(u,s),g=f.yaml,m=await Ra(u,c,f.remoteFiles,`Provision ${r} custom class`,g),v=await Ta(m.syncFileMap,m.remoteFiles),b=new Map(m.syncFileMap);b.set("pubspec.yaml",{content:g,type:"D",path:"pubspec.yaml"}),be.set("package");const w=await Ma(b),I={project_id:a,zipped_custom_code:w,uid:`web_${Date.now()}`,branch_name:u.branchName,serialized_yaml:g,file_map:v.fileMapContents,functions_map:v.functionsMapContents};J.setState(K.PUSHING),J.setProgress(1,c.size),Qs(u),be.set("push");const A=await u.pushCode(I),F=await Pa(A);if(F.success)J.setSuccess({fileCount:c.size,projectId:a,warnings:F.errorMap&&F.errorMap.size>0?Array.from(F.errorMap.entries()):[]});else{const D=F.errorMessage||$a(F.responseCode);throw new Error(D)}return{success:!0,message:`Successfully committed ${e} to FlutterFlow project ${a}`,addedDependencies:f.added,unverified:m.unverified,approximate:m.approximate,warnings:F.errorMap?Array.from(F.errorMap.entries()):[]}}catch(o){return console.error("Commit failed:",o),J.setError(o),{success:!1,error:o.message,state:J.currentState}}}async function Ma(t){const e=new JSZip;for(const[n,i]of t.entries())e.file(n,i.content);return e.generateAsync({type:"base64",compression:"DEFLATE",compressionOptions:{level:6}})}async function Xv(t,e={}){const{artifactType:n,artifactName:i,fileName:s,pipelineResult:r}=e;console.log(`Starting commit for ${i} (${n})`);try{J.setState(K.PREPARING);const o=dh(t,{artifactType:n,artifactName:i,fileName:s}),a=Kv(o.content);console.log("Detected dependencies:",a),J.setState(K.VALIDATING);const l=await Ee("flutterflow"),u=ni||await Ee("flutterflow_project_id");if(!l)throw new Error("FlutterFlow API Key not configured. Please add it in API Keys settings.");if(!u)throw new Error("FlutterFlow Project ID not configured. Please add it in API Keys settings.");if(!Ys(u))throw new Error("Invalid FlutterFlow Project ID format.");const c=new Map;c.set(o.fileName,{artifactName:i,content:o.content,type:o.codeType,path:ch(o.fileName,o.codeType),functionName:o.codeType===W.FUNCTION?i:void 0}),J.setProgress(0,c.size);const d=er(c);if(!d.valid)throw new Error(`File validation failed: +${d.errors.join(` +`)}`);d.warnings.length>0&&console.warn("Validation warnings:",d.warnings),J.setState(K.PUSHING);const h=yi(),p=new wi(l,u,"main",h),f=await Na(p,a),g=f.yaml,m=await Ra(p,c,f.remoteFiles,`Provision ${i} custom class`,g),v=await Ta(m.syncFileMap,m.remoteFiles),b=new Map(m.syncFileMap);b.set("pubspec.yaml",{content:g,type:W.DEPENDENCIES,path:"pubspec.yaml"}),be.set("package");const w=await Ma(b),I={project_id:u,zipped_custom_code:w,uid:`web_${Date.now()}`,branch_name:p.branchName,serialized_yaml:g,file_map:v.fileMapContents,functions_map:v.functionsMapContents};J.setProgress(1,c.size),Qs(p),be.set("push");const A=await p.pushCode(I),F=await Pa(A);if(F.success){const D={...Jv(o,r),projectId:u};return J.setSuccess({...D,fileCount:c.size,warnings:F.errorMap?Array.from(F.errorMap.entries()):[]}),{success:!0,message:`Successfully committed ${o.fileName} to FlutterFlow`,metadata:D,addedDependencies:f.added,unverified:m.unverified,approximate:m.approximate,warnings:F.errorMap?Array.from(F.errorMap.entries()):[],elapsedTime:J.getElapsedTime()}}else{const D=F.errorMessage||$a(F.responseCode),S=new Error(D);throw S.errorMap=F.errorMap,S}}catch(o){console.error("Commit execution failed:",o),J.setError(o);let a=new Map;if(o.errorMap)a=o.errorMap;else if(o.message&&o.message.includes("{"))try{const l=o.message.match(/\{[\s\S]*\}/);if(l){const u=JSON.parse(l[0]);a=new Map(Object.entries(u))}}catch(l){console.warn("Failed to parse error map from commit response:",l)}return{success:!1,error:o.message,errorMap:a,state:J.currentState,elapsedTime:J.getElapsedTime()}}}async function Qv(t,e={}){const{pipelineResult:n}=e;try{if(J.setState(K.PREPARING),t.errors?.length>0)throw new Error(`Bundle validation failed: +${t.errors.join(` +`)}`);const i=new Map(t.fileEntries.map(I=>[I.fileName,{artifactId:I.artifactId,artifactName:I.artifactName,content:I.content,type:I.type,path:I.path,functionName:I.type===W.FUNCTION?I.artifactName:void 0}]));J.setProgress(0,i.size);const s=er(i);if(!s.valid)throw new Error(`File validation failed: +${s.errors.join(` +`)}`);J.setState(K.VALIDATING);const r=await Ee("flutterflow"),o=ni||await Ee("flutterflow_project_id");if(!r)throw new Error("FlutterFlow API Key not configured. Please add it in API Keys settings.");if(!o)throw new Error("FlutterFlow Project ID not configured. Please add it in API Keys settings.");if(!Ys(o))throw new Error("Invalid FlutterFlow Project ID format.");J.setState(K.PUSHING);const a=yi(),l=new wi(r,o,"main",a),u=await Na(l,t.dependencies),c=u.yaml,d=await Ra(l,i,u.remoteFiles,`Provision ${t.title} custom classes`,c),h=await Ta(d.syncFileMap,d.remoteFiles),p=new Map(d.syncFileMap);p.set("pubspec.yaml",{content:c,type:W.DEPENDENCIES,path:"pubspec.yaml"}),be.set("package");const f=await Ma(p),g={project_id:o,zipped_custom_code:f,uid:`web_${Date.now()}`,branch_name:l.branchName,serialized_yaml:c,file_map:h.fileMapContents,functions_map:h.functionsMapContents};J.setProgress(1,i.size),Qs(l),be.set("push");const m=await l.pushCode(g),v=await Pa(m);if(v.success){const I={...n,artifactType:"Bundle",artifactName:t.title,fileName:`${t.fileEntries.length} artifacts`,codeSize:t.fileEntries.reduce((A,F)=>A+F.content.length,0),projectId:o};return J.setSuccess({...I,fileCount:i.size,warnings:v.errorMap?Array.from(v.errorMap.entries()):[]}),{success:!0,message:`Successfully committed ${t.fileEntries.length} artifacts to FlutterFlow`,metadata:I,addedDependencies:u.added,unverified:d.unverified,approximate:d.approximate,warnings:v.errorMap?Array.from(v.errorMap.entries()):[],elapsedTime:J.getElapsedTime()}}const b=v.errorMessage||$a(v.responseCode),w=new Error(b);throw w.errorMap=v.errorMap,w}catch(i){return console.error("Bundle commit execution failed:",i),J.setError(i),{success:!1,error:i.message,errorMap:i.errorMap||new Map,state:J.currentState,elapsedTime:J.getElapsedTime()}}}async function e_(t,e=[]){const n=ha("architect");try{return await Ms("architect",Yd,sg(t),n,e)}catch(i){throw i.isModelArmor?i:new Error(`Prompt Architect failed: ${i.message}`)}}async function tr(t,e,n=[]){const i=rg(t),s=ha("generator",y.bundleSpec);try{return await Ms("generator",e,i,s,n)}catch(r){if(r.isModelArmor)throw r;if(e!==jr){console.warn(`Code Generator failed with ${e}, retrying with fallback model:`,r.message);try{return await Ms("generator",jr,i,s,n)}catch(o){throw o.isModelArmor?o:new Error(`Code Generator failed: primary (${e}): ${r.message} | fallback (${jr}): ${o.message}`)}}throw new Error(`Code Generator failed: ${r.message}`)}}async function nr(t,e=null){const n={...ha("review",y.artifactBundle||y.bundleSpec),architect_output:e};try{return await Ms("review",Zd,og(t),n)}catch(i){throw i.isModelArmor?i:new Error(`Code Review failed: ${i.message}`)}}function La(t,e){return t.isModelArmor?`${t.userTitle}: ${t.userMessage}`:`${e}: ${t.message}`}function Ho(t,e){const n=document.getElementById(`step${t}-item`),i=document.getElementById(`step${t}-status`);!n||!i||(n.classList.remove("active","completed","error"),i.classList.remove("running","completed","error"),e==="active"?(n.classList.add("active"),i.classList.add("running"),i.innerHTML=` + + `):e==="completed"?(n.classList.add("completed"),i.classList.add("completed"),i.innerHTML=` + + `):e==="error"?(n.classList.add("error"),i.classList.add("error"),i.innerHTML=` + + `):i.innerHTML=` + + `)}function ve(t,e){const n=document.getElementById(`step${t}-loading`),i=document.getElementById(`step${t}-result`);e?(n.classList.remove("hidden"),i.classList.add("hidden"),Ho(t,"active")):(n.classList.add("hidden"),i.classList.remove("hidden"),Ho(t,"completed"))}function t_(t){const e=document.getElementById(`${t}-content`),n=document.getElementById(`${t}-chevron`);e.classList.contains("open")?(e.classList.remove("open"),n&&(n.style.transform="rotate(0deg)")):(e.classList.add("open"),n&&(n.style.transform="rotate(180deg)"))}function n_(t){ze(parseInt(t.replace("step","")))}function ze(t){for(let o=1;o<=3;o++){const a=document.getElementById(`step${o}-item`);a&&a.classList.remove("active")}const e=document.getElementById(`step${t}-item`);e&&e.classList.add("active"),Qt();const n=document.getElementById("ready-state");n&&n.classList.add("hidden");for(let o=1;o<=3;o++){const a=document.getElementById(`step${o}-content`);a&&a.classList.add("hidden")}const i=document.getElementById(`step${t}-content`);i&&i.classList.remove("hidden");const s=document.getElementById("stage-title"),r={1:"Prompt Architect",2:"Code Generator",3:"Code Review"};s&&(s.textContent=r[t]||"Active Workflow Stage")}function i_(t){const e=document.getElementById(t);if(!e)return;const n=e.dataset.raw||e.textContent;navigator.clipboard.writeText(n).then(()=>{const s=e.closest(".code-container")?.querySelector(".copy-btn");s&&(s.classList.add("copied"),s.innerHTML=' Copied!',setTimeout(()=>{s.classList.remove("copied"),s.innerHTML=' Copy'},2e3))}).catch(i=>{console.warn("Failed to copy to clipboard:",i)})}function Wo(t){const e=zo(t);console.log(`Step 1 (Prompt Architect): ${Kt(Yd)}`),console.log(e!==t?`Step 2 (Code Generator): ${Kt(t)} → ${Kt(e)} (Free Tier fallback)`:`Step 2 (Code Generator): ${Kt(t)}`),console.log(`Step 3 (Code Review): ${Kt(Zd)}`)}async function s_(){if(console.log("runRefinement called"),y.isRunning)return;const t=document.getElementById("code-generator-model").value;y.isRunning=!0,Oa("standardRegenerate",y.step2Result,y.step1Result);const e=document.querySelectorAll(".btn-refine-action");e.forEach(n=>{n.disabled=!0,n.innerHTML=` + + + Refining...`});try{const n=Aa(),i=ag({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,artifactId:n.id,userFeedback:"Fix the issues listed in the audit report."});or(),at(2),ze(2),ve(2,!0),y.step2Result=await tr(i,t),Zs();const s=document.getElementById("step2-output"),r=xn(y.step2Result);s.textContent=r,s.dataset.raw=r,ve(2,!1),ze(3),at(3),ve(3,!0),y.step3Result=await nr(y.step2Result,y.step1Result),Xs();const o=document.getElementById("step3-output");o.textContent=y.step3Result,ve(3,!1),Mt();const a=Ks(y.step3Result);ar(r,a)}catch(n){console.error("Refinement failed:",n),Mt(),ue(La(n,"Refinement failed"),"error")}finally{y.isRunning=!1,e.forEach(n=>{n.disabled=!1,n.textContent="Refine & Regenerate"}),en()}}async function Oa(t,e,n){const i=`${Ze}/connectFeedback`,s={type:t,code:e,input:n};try{const r=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)});if(!r.ok){const a=await r.text();return console.error(`callEndpoint failed: ${r.status} ${r.statusText}`,a),{success:!1,status:r.status,error:a}}const o=await r.json();return console.log("Telemetry success:",o),o}catch(r){return console.error("callEndpoint failed:",r),{success:!1,error:r.message}}}function r_(){const t=document.getElementById("ff-error-paste-input");t&&(t.value="")}async function o_(){const t=document.getElementById("ff-error-paste-input"),e=t?.value?.trim();if(!e){t?.focus(),t?.classList.add("ring-2","ring-red-400","border-red-300"),setTimeout(()=>t?.classList.remove("ring-2","ring-red-400","border-red-300"),2e3);return}if(!y.step2Result){ue("No generated code found. Please run the full pipeline first.","warning");return}if(y.isRunning)return;const n=document.getElementById("code-generator-model").value;y.isRunning=!0,Oa("flutterflowError",y.step2Result,e);const i=document.getElementById("btn-fix-from-errors");i&&(i.disabled=!0,i.innerHTML=` + + Fixing…`);try{const s=$d({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,userFeedback:e});Sh(),or(),at(2),ze(2),ve(2,!0),y.step2Result=await tr(s,n),Zs();const r=document.getElementById("step2-output"),o=xn(y.step2Result);r.textContent=o,r.dataset.raw=o,ve(2,!1),ze(3),at(3),ve(3,!0),y.step3Result=await nr(y.step2Result,y.step1Result),Xs();const a=document.getElementById("step3-output");a.textContent=y.step3Result,ve(3,!1),Mt();const l=Ks(y.step3Result);ar(o,l),t&&(t.value="")}catch(s){console.error("Fix from errors failed:",s),Mt(),ue(La(s,"Failed to fix errors"),"error")}finally{y.isRunning=!1,i&&(i.disabled=!1,i.textContent="Fix Errors & Regenerate"),en()}}async function Ns(){if(console.log("runThinkingPipeline called"),y.isRunning)return;localStorage.setItem("hasSeenWalkthrough","true");const t=document.getElementById("pipeline-input").value,e=document.getElementById("code-generator-model").value;if(!t.trim()){ue("Please describe your FlutterFlow widget first.","warning");return}if(!await I_())return;await w_();const n=zo(e);t.length;const i=document.getElementById("btn-run-pipeline");y.isRunning=!0,Hv(),i&&(i.disabled=!0,i.innerHTML=` + + + Running...`),Wo(n);try{Qt();const s=document.getElementById("ready-state");s&&s.classList.add("hidden");const r=document.getElementById("paywall-exhausted");r&&r.classList.add("hidden"),or(),ze(1),at(1),ve(1,!0);const o=Tt.filter(p=>p.url).map(p=>({url:p.url}));y.step1Result=await e_(t,o),Wv();const a=document.getElementById("step1-output"),l=xn(y.step1Result);a.textContent=l,a.dataset.raw=l,ve(1,!1),ze(2),at(2),ve(2,!0),y.step2Result=await tr(y.step1Result,n,o),Zs();const u=document.getElementById("step2-output"),c=xn(y.step2Result);u.textContent=c,u.dataset.raw=c,ve(2,!1),ze(3),at(3),ve(3,!0),y.step3Result=await nr(y.step2Result,y.step1Result),Xs();const d=document.getElementById("step3-output");d.textContent=y.step3Result,ve(3,!1),Mt();const h=Ks(y.step3Result);ar(c,h)}catch(s){if(console.error("Pipeline failed:",s),Mt(),s.isUsageLimit){const{count:c}=bi();Ua(c,sr(),{openModal:!0});return}s.message,zo(document.getElementById("code-generator-model").value);const o=Jm(s,{architect:1,generator:2,review:3});ze(o);const a=document.getElementById(`step${o}-result`),l=document.getElementById(`step${o}-loading`),u=document.getElementById(`step${o}-output`);if(l&&l.classList.add("hidden"),a&&a.classList.remove("hidden"),u)if(s.isModelArmor)u.innerHTML=``;else{let c=s.message;s.message.includes("image input")?c=`This model doesn't support image input. Please use ${Kt(pi)} for image-based requests or remove image references from your prompt.`:(s.message.includes("Load failed")||s.message.includes("CORS"))&&(c="API connection failed. This might be due to CORS restrictions or network issues. Please check your API key and try again."),u.innerHTML=`
+

Connection Error

+

${j(c)}

+
+

Check if API key is valid

+

Try using a different model

+

Ensure network allows API calls

+
+
`}Ho(o,"error")}finally{y.isRunning=!1,i&&(i.disabled=!1,i.innerHTML=` + + + Run Pipeline`),en()}}function a_(){const t=document.getElementById("code-generator-model").value,e=[pi,"anthropic/claude-opus-5","openai/gpt-5.6-sol"].filter(i=>i!==t),n=prompt(`Retry with different model? + +Current: ${t} + +Options: +1. ${e[0]} +2. ${e[1]} + +Enter 1 or 2:`);n==="1"?(document.getElementById("code-generator-model").value=e[0],Ns()):n==="2"&&(document.getElementById("code-generator-model").value=e[1],Ns())}async function l_(){const t=Fa();if(!t){ue("No code to commit. Please run the pipeline first.","warning");return}const e=await Ee("flutterflow"),n=await Ee("flutterflow_project_id");if(!e||!n){ue("FlutterFlow credentials not configured. Add your API Key and Project ID in settings.","warning"),ka();return}if(y.artifactBundle?.artifacts?.length>1){await c_();return}const{artifactType:i,artifactName:s,fileName:r}=oh(),o=dh(t,{artifactType:i,artifactName:s,fileName:r}),a=Gv(o);if(!a.canProceed){ue(`Pre-commit checks failed: ${a.issues.join("; ")}`,"error");return}Wa(o,a,null,null)}async function c_(){const t=await Ee("flutterflow"),e=await Ee("flutterflow_project_id");if(!t||!e){ue("FlutterFlow credentials not configured. Add your API Key and Project ID in settings.","warning"),ka();return}const n=zg(y.artifactBundle);if(n.errors.length>0){ue(`Bundle validation failed: ${n.errors.join("; ")}`,"error");return}const i=new Map(n.fileEntries.map(a=>[a.fileName,{content:a.content,type:a.type,path:a.path}])),s=er(i),r={canProceed:s.valid&&n.errors.length===0,issues:[...n.errors,...s.errors],warnings:[...n.warnings,...s.warnings]};if(!r.canProceed){ue(`Bundle validation failed: ${r.issues.join("; ")}`,"error");return}const o={content:n.fileEntries.map(a=>`// ${a.fileName} +${a.content}`).join(` + +`),fileName:`${n.fileEntries.length} files`,codeType:"bundle",artifactType:"Bundle",artifactName:n.title};Wa(o,r,n.dependencies,n)}function u_(t){let e=t.errorMap||new Map;!(e instanceof Map)&&typeof e=="object"&&(e=new Map(Object.entries(e)));let n=`
+

FlutterFlow Commit Failed

+

${j(t.error)}

`;if(e&&e.size>0){n+=`
+

Errors:

+
    `;for(const[s,r]of e.entries()){const o=Bd(r);n+=`
  • + ${j(s)}: ${j(o)} +
  • `}n+="
"}n+="
",n+=`
+ +
`;const i=document.getElementById("step3-output");i&&(i.innerHTML=n,document.getElementById("btn-regenerate-from-error")?.addEventListener("click",()=>{d_(t.error,e)}))}async function d_(t,e){if(y.isRunning)return;const n=document.getElementById("code-generator-model").value;y.isRunning=!0;const i=document.getElementById("btn-regenerate-from-error");i&&(i.disabled=!0,i.innerHTML=` + + Fixing...`);try{let s=`The previous code had the following errors when committing to FlutterFlow: + +`;if(e&&e.size>0)for(const[c,d]of e.entries()){const h=Bd(d);s+=`File: ${c} +Error: ${h} + +`}else s+=`${t} +`;const r=$d({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,userFeedback:s});or(),at(2),ze(2),ve(2,!0),y.step2Result=await tr(r,n),Zs();const o=document.getElementById("step2-output"),a=xn(y.step2Result);o.textContent=a,o.dataset.raw=a,ve(2,!1),ze(3),at(3),ve(3,!0),y.step3Result=await nr(y.step2Result,y.step1Result),Xs();const l=document.getElementById("step3-output");l.textContent=y.step3Result,ve(3,!1),Mt();const u=Ks(y.step3Result);ar(a,u)}catch(s){console.error("Regeneration failed:",s),Mt(),ue(La(s,"Regeneration failed"),"error")}finally{y.isRunning=!1,i&&(i.disabled=!1,i.textContent="Fix Errors & Regenerate"),en()}}async function h_(){const t=document.getElementById("ff-status-dot"),e=document.getElementById("ff-status-text");if(!t||!e)return;const n=await Ee("flutterflow"),i=await Ee("flutterflow_project_id");n&&i?(t.className="w-2 h-2 rounded-full bg-green-500",e.textContent="FlutterFlow credentials configured",e.className="text-green-600"):n||i?(t.className="w-2 h-2 rounded-full bg-yellow-500",e.textContent="FlutterFlow credentials incomplete",e.className="text-yellow-600"):(t.className="w-2 h-2 rounded-full bg-red-500",e.textContent="FlutterFlow credentials not configured",e.className="text-red-600")}async function p_(t){try{const e=await fetch(`${Ze}/auth/send-magic-link`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:t})});if(!e.ok)throw new Error(`Failed to send magic link: HTTP ${e.status}`);return e.json()}catch(e){throw console.error("sendMagicLink failed:",{email:t,message:e.message,stack:e.stack}),e}}async function f_(t){try{const n=await(await fetch(`${Ze}/auth/verify-magic-link`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:t})})).json();if(n.error||!n.email||!n.sessionToken)throw new Error(n.error||"Invalid or expired link");return n}catch(e){throw console.error("verifyMagicLink failed:",{message:e.message,stack:e.stack}),e}}async function g_(t){try{const e=await fetch(`${Ze}/auth/refresh-session`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:t})});if(!e.ok)return console.error("refreshSession: non-OK response",{url:`${Ze}/auth/refresh-session`,status:e.status}),null;const n=await e.json();return n.error||!n.email||!n.sessionToken?(console.warn("refreshSession: validation failed",{error:n.error,hasEmail:!!n.email,hasToken:!!n.sessionToken}),null):n}catch(e){return console.error("refreshSession: fetch failed",{url:`${Ze}/auth/refresh-session`,message:e.message,stack:e.stack}),null}}function Nc(t,e){const n=hh(),i=(V.email||n.email)!==t;V.email=t,V.sessionToken=e,V.isVerified=!0,pe=kn({isLoading:!0}),localStorage.setItem(Is,JSON.stringify({email:t,sessionToken:e})),i&&Ha()}function Ba(){V.email=null,V.sessionToken=null,V.isVerified=!1,pe=kn({isResolved:!0}),localStorage.removeItem(Is),localStorage.removeItem(As)}function hh(){try{const t=localStorage.getItem(Is);if(!t)return{email:null,sessionToken:null};const e=JSON.parse(t);return!e.email||!e.sessionToken?{email:null,sessionToken:null}:e}catch(t){return console.warn("getStoredSession: failed to parse auth session:",t),localStorage.removeItem(Is),{email:null,sessionToken:null}}}async function m_(){const e=new URLSearchParams(window.location.search).get("token");if(e){window.history.replaceState({},"",window.location.pathname+window.location.hash);try{const{email:n,sessionToken:i}=await f_(e);Nc(n,i)}catch(n){ue(n.message||"Sign-in link invalid or expired.","error")}}else{const{email:n,sessionToken:i}=hh();if(n&&i){const s=await g_(i);s?Nc(s.email,s.sessionToken):Ba()}}ja()}function Da(){const t=document.getElementById("signin-modal");t&&Ve(t)}function v_(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("signin-modal");e&&Xe(e)}async function __(){const t=document.getElementById("signin-email-input"),e=document.getElementById("signin-submit-btn"),n=document.getElementById("signin-message"),i=zs(t?.value);if(!i||!/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/.test(i)||i.length>254){n&&(n.textContent="Please enter a valid email address.");return}e&&(e.disabled=!0,e.textContent="Sending…");const r=Dd(i);n&&r&&(n.textContent=r);try{const o=await p_(i);t&&o?.code!==Ki&&(t.value=""),n&&(n.textContent=Em(o,i)),e&&(e.textContent=o?.code===Ki?"Send Link":"Sent!"),e&&o?.code===Ki&&(e.disabled=!1)}catch(o){console.error("handleMagicLinkRequest: sendMagicLink failed",{email:i,err:o}),n&&(n.textContent="Something went wrong. Please try again."),e&&(e.disabled=!1,e.textContent="Send Link")}}function y_(){Ba(),Ha(),ja(),rr()}function ja(){const t=V.isVerified&&!!V.email,e=document.getElementById("auth-signedout"),n=document.getElementById("auth-signedin"),i=document.getElementById("auth-guest-usage");e&&e.classList.toggle("hidden",t),n&&n.classList.toggle("hidden",!t),i&&i.classList.toggle("hidden",t);const s=document.getElementById("auth-user-email");s&&(s.textContent=V.email||""),Qi(),rr()}async function ph(){try{if(typeof FingerprintJS>"u"){console.warn("resolveIdentity: FingerprintJS not loaded, skipping");return}const e=await(await FingerprintJS.load()).get(),n=e.visitorId,i=await fetch(cv,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({fingerprint:e.visitorId,cookie_id:n})});if(!i.ok)throw new Error(`Identity check HTTP ${i.status}`);const s=await i.json();if(Ke.userId=s.user_id,Ke.token=s.identity_token||null,Ke.status=s.status,Ke.resolved=!0,sessionStorage.setItem(av,s.user_id),Ke.token&&sessionStorage.setItem(lv,Ke.token),s.usage_count!==void 0){const r=Rt(),a=(s.usage_month||r)===r?s.usage_count:0;localStorage.setItem(Zt,JSON.stringify({count:a,month:r})),ii()}console.log(`Identity resolved: ${s.status} (${s.user_id.slice(0,8)}...) usage: ${s.usage_count??"n/a"}`)}catch(t){console.error("resolveIdentity failed:",t)}}let Ur=null;function w_(t=5e3){return Ke.resolved?Promise.resolve():(Ur||(Ur=ph().catch(e=>{console.warn("ensureIdentityReady: identity resolution failed",e)})),Promise.race([Ur,new Promise(e=>setTimeout(e,t))]))}function fh(){const t=Rt();try{const e=localStorage.getItem(Zt);return e?JSON.parse(e):{count:0,month:t}}catch(e){return console.warn("getUsageData: failed to parse usage storage",{key:Zt,month:t,err:e}),localStorage.removeItem(Zt),{count:0,month:t}}}function Rt(){const t=new Date;return`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,"0")}`}function bi(){const t=fh();return t.month!==Rt()?{count:0,month:Rt()}:t}function b_(){const e={count:bi().count+1,month:Rt()};return localStorage.setItem(Zt,JSON.stringify(e)),e}function ir(){return!!pe.isLoading}function Nt(){return!!pe.isResolved}function E_(t){if(!t)return null;const e=String(t).toLowerCase().replace(/[^a-z0-9]+/g,"_");return e==="pro"||e==="professional_plan"?"professional":e==="power_developer"||e==="power_plan"?"power":Object.prototype.hasOwnProperty.call(Cs,e)?e:null}function S_(t){return t&&Object.entries(Gd).find(([,e])=>e===t)?.[0]||null}function Di(...t){return t.find(e=>e!=null&&e!=="")}function x_(...t){return t.find(e=>e&&typeof e=="object")||{}}function k_(t){const e=t.data&&typeof t.data=="object"?t.data:t,n=x_(e.subscription,e.stripeSubscription,e.currentSubscription,e.customer?.subscriptions?.data?.[0],e.subscriptions?.data?.[0],e.subscriptions?.[0]),i=e.metadata||n.metadata||e.customer?.metadata||{},s=Di(e.priceId,e.price_id,e.stripePriceId,e.stripe_price_id,n.priceId,n.price_id,n.plan?.id,n.price?.id,n.items?.data?.[0]?.price?.id,n.items?.[0]?.price?.id,n.lines?.data?.[0]?.price?.id),r=Di(e.status,e.subscriptionStatus,e.subscription_status,n.status,"none"),o=E_(Di(e.tier,e.plan,e.planId,e.plan_id,e.subscriptionTier,e.subscription_tier,e.product,e.productName,n.tier,n.plan,i.tier,i.plan)),a=uv.has(String(r).toLowerCase()),l=e.active===!0||e.isSubscribed===!0||e.subscribed===!0||e.hasSubscription===!0,u=o||S_(s)||(a||l?"professional":"free");return kn({tier:u,status:r,periodEnd:Di(e.periodEnd,e.currentPeriodEnd,e.current_period_end,n.current_period_end,n.periodEnd,null),isResolved:!0})}function sr(){return Cs[pe.tier]??Cs.free}async function I_(){if(V.isVerified&&(!Nt()||ir())&&(await gh({force:!0}),rr()),V.isVerified&&!Nt())return ue("Could not verify your subscription. Please refresh or try Manage billing.","error"),!1;const{count:t}=bi(),e=sr();if(t>=e)return Ua(t,e,{openModal:!0}),!1;const n=Math.floor(e*.8);if(t>=n){const i=e-t;ue(`${i} run${i===1?"":"s"} remaining this month.`,"warning")}return!0}function Hr(){const t=document.getElementById("paywall-exhausted");t&&t.classList.add("hidden")}function Ua(t,e,n={}){An(!0);const i=document.getElementById("walkthrough-modal");i&&Xe(i,{restoreFocus:!1});const s=document.getElementById("ready-state");s&&s.classList.add("hidden");const r=document.getElementById("preview-frame-container");r&&(r.style.display="none");const o=document.getElementById("main-stage-container");o&&o.classList.add("visible");const a=document.getElementById("results-view");a&&a.classList.remove("visible"),document.body.classList.remove("results-fullscreen","results-with-sidebar");const l=document.getElementById("pipeline-progress");l&&l.classList.remove("visible");const u=document.getElementById("paywall-exhausted");if(!u){ue(`You've used all ${e} runs for this month. Upgrade to continue.`,"error"),Ls();return}const c=document.getElementById("paywall-exhausted-text");if(c){const h=pe.tier;h==="free"?c.textContent=`You've used all ${e} free generations this month. Upgrade to Pro for 50 generations/month and access to all AI models.`:c.textContent=`You've used all ${e} generations this month on your ${h} plan. Your limit resets next month.`}const d=document.getElementById("paywall-signin-btn");d&&d.classList.toggle("hidden",V.isVerified),u.classList.remove("hidden"),n.openModal&&Ls()}function zo(t){return pe.tier==="free"&&Ji.includes(t)?pi:t}function C_(){const t=document.getElementById("code-options-content"),e=document.getElementById("code-generator-model");if(!t||!e)return;const n=pe.tier,s=!(V.isVerified&&!Nt())&&n==="free";Array.from(e.options).forEach(o=>{const a=Kt(o.value),l=Ji.includes(o.value);o.textContent=l&&s?`${a} (PRO)`:a,o.disabled=!1}),s&&Ji.includes(e.value)&&(e.value=pi),e.disabled=!1,Ic.has(e)||(e.addEventListener("change",()=>{Nt()&&pe.tier==="free"&&Ji.includes(e.value)&&(e.value=pi,Ls()),Wo(e.value),Jd()}),Ic.add(e));let r=document.getElementById("model-selector-free-notice");s?(r||(r=document.createElement("p"),r.id="model-selector-free-notice",r.className="text-xs text-gray-400 mt-1",t.appendChild(r)),r.innerHTML='Free plan — Gemini only. '):r&&r.remove(),Wo(e.value)}function ii(){const t=document.getElementById("usage-counter");if(!t)return;if(V.isVerified&&ir()){t.textContent="Checking plan…",t.className="text-xs text-gray-500",Qi(),Hr();return}if(V.isVerified&&!Nt()){t.textContent="Plan check failed",t.className="text-xs text-red-600 font-medium",Qi(),Hr();return}const{count:e}=bi(),n=sr();t.textContent=`${e} / ${n} runs this month`;const i=n>0?e/n:0;t.className=i>=1?"text-xs text-red-600 font-medium":i>=.8?"text-xs text-yellow-600 font-medium":"text-xs text-gray-500",Qi(),e>=n&&!y.isRunning?Ua(e,n):Hr()}function Qi(){const t=document.getElementById("guest-usage-text");if(!t)return;const e=fh(),n=e.month===Rt()?e.count??0:0,i=Cs.free;t.textContent=`${n} / ${i} generations used`}async function gh(t={}){const e=t.force===!0;if(!V.isVerified||!V.sessionToken){pe=kn({isResolved:!0});return}pe={...pe,isLoading:!0,error:null};const n=localStorage.getItem(As);if(!e&&n)try{const{data:i,email:s,ts:r,version:o}=JSON.parse(n);if(o===Cc&&s===V.email&&Date.now()-r<300*1e3){pe={...i,isLoading:!1,isResolved:i.isResolved!==!1};return}}catch(i){console.warn("Failed to parse subscription cache:",i,"| raw value:",n)}try{const s=await(await fetch(`${Ze}/stripe/get-subscription`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:V.sessionToken,user_id:Ke.userId})})).json();if(s.error){if(["unauthorized","invalid session","expired session"].some(o=>String(s.error).toLowerCase().includes(o))){Ba(),ja();return}pe=kn({isResolved:!1,error:s.error});return}pe=k_(s),localStorage.setItem(As,JSON.stringify({version:Cc,data:pe,email:V.email,ts:Date.now()}))}catch(i){console.error("fetchSubscription failed:",i),pe={...pe,isLoading:!1,isResolved:!1,error:i.message}}}function Ha(){localStorage.removeItem(As)}async function A_(t){if(!V.isVerified||!V.sessionToken){mh(),Da();return}if(!Gd[t]){ue("Invalid plan selected.","error");return}const e=document.getElementById(`checkout-btn-${t}`);e&&(e.disabled=!0,e.textContent="Redirecting…");try{const i=await(await fetch(`${Ze}/stripe/create-checkout-session-intl`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tierId:t,sessionToken:V.sessionToken,currency:Xd()})})).json();if(i.error||!i.url)throw new Error(i.error||"Failed to create checkout session");const{url:s}=i;window.location.href=s}catch(n){console.error("startCheckout failed:",n),e&&(e.disabled=!1,e.textContent="Subscribe"),ue("Could not start checkout. Please try again.","error")}}async function F_(){if(!V.isVerified||!V.sessionToken){Da();return}const t=document.getElementById("manage-billing-btn");t&&(t.disabled=!0,t.textContent="Loading…");try{const n=await(await fetch(`${Ze}/stripe/create-portal-session`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:V.sessionToken})})).json();if(n.error||!n.url)throw new Error(n.error||"Failed to open billing portal");const{url:i}=n;window.location.href=i}catch(e){console.error("openCustomerPortal failed:",e),t&&(t.disabled=!1,t.textContent="Manage billing"),ue("Could not open billing portal. Please try again.","error")}}async function Ms(t,e,n,i={},s=[]){const o=new AbortController,a=setTimeout(()=>o.abort(),12e4);try{const l=await fetch(ov,{method:"POST",headers:{"Content-Type":"application/json",...Ke.token?{Authorization:`Bearer ${Ke.token}`}:{}},signal:o.signal,body:JSON.stringify({user_id:Ke.userId,step:t,model:e,prompt:n,images:s,context:i})}),u=await l.text();let c={};try{c=u?JSON.parse(u):{}}catch{c={}}if(l.status===429){c.serverCount!==void 0&&(localStorage.setItem(Zt,JSON.stringify({count:c.serverCount,month:Rt()})),ii());const p=new Error(c.message||"Monthly usage limit reached. Upgrade to continue.");throw p.isUsageLimit=!0,p}const d=fg(c,t);if(d)throw d;if(console.log(`[BuildShip] ${t} response keys:`,Object.keys(c),"content type:",typeof c.content),!l.ok)throw new Error(`${c.message||c.error||"BuildShip pipeline error"} (HTTP ${l.status})`);if(t==="generator")if(c.usage_status==="success"&&Number.isFinite(c.usage_count)){const p=Rt();(c.usage_month||p)===p&&(localStorage.setItem(Zt,JSON.stringify({count:c.usage_count,month:p})),ii())}else b_(),ii();let h=c.output||c.content;if(!h){const p=u?` (body: ${u.slice(0,120)})`:"";throw new Error(`BuildShip returned no output for step "${t}"${p}`)}return Array.isArray(h)&&(h=h.map(p=>typeof p=="string"?p:p.text||"").join("")),typeof h!="string"&&(h=JSON.stringify(h)),h}catch(l){throw l.name==="AbortError"?new Error(`BuildShip ${t} timed out after ${12e4/1e3}s`):l instanceof TypeError?new Error(`BuildShip unreachable: ${l.message}`):l}finally{clearTimeout(a)}}function P_(){const e=new URLSearchParams(window.location.search).get("checkout");e==="success"?(window.history.replaceState({},"",window.location.pathname+window.location.hash),Ha(),ue("Subscription active! Welcome aboard.","success")):e==="cancel"&&(window.history.replaceState({},"",window.location.pathname+window.location.hash),ue("Checkout cancelled.","info"))}function rr(){const t=V.isVerified&&!!V.email,e=pe.tier,n=t&&ir(),i=!t||Nt(),s=document.getElementById("subscription-tier-badge");if(s){const a={free:"Free",professional:"Professional",power:"Power Developer"},l={free:"bg-gray-100 text-gray-600",professional:"bg-indigo-100 text-indigo-700",power:"bg-purple-100 text-purple-700",unresolved:"bg-red-50 text-red-600"};s.textContent=n?"Checking…":i?a[e]||"Free":"Plan unavailable",s.className=`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${i?l[e]||l.free:l.unresolved}`}const r=document.getElementById("upgrade-prompt");r&&r.classList.toggle("hidden",!t||n||!i||e!=="free");const o=document.getElementById("manage-billing-btn");o&&o.classList.toggle("hidden",!t||n||i&&e==="free"),$_(i?e:null),C_(),Jd(),ii(),xh()}function $_(t){const e=["bg-gray-100","text-gray-500","cursor-default"];Object.entries({professional:{btnId:"checkout-btn-professional",defaultText:"Subscribe"},power:{btnId:"checkout-btn-power",defaultText:"Subscribe"}}).forEach(([s,{btnId:r,defaultText:o}])=>{const a=document.getElementById(r);a&&(s===t?(a.disabled=!0,a.textContent="Current plan",a.classList.add(...e)):(a.disabled=!1,a.textContent=o,a.classList.remove(...e)))});const i=document.getElementById("free-tier-current");i&&i.classList.toggle("hidden",t!=="free")}function qo(){const t=Xd(),e=document.getElementById("pro-price"),n=document.getElementById("power-price"),i=document.getElementById("plans-pro-price"),s=document.getElementById("plans-power-price"),r=document.getElementById("pro-price-note"),o=document.getElementById("power-price-note"),a=document.getElementById("plans-pro-price-note"),l=document.getElementById("plans-power-price-note");e&&(e.textContent=Bi(Oi.professional,t)),n&&(n.textContent=Bi(Oi.power,t)),i&&(i.textContent=Bi(Oi.professional,t)),s&&(s.textContent=Bi(Oi.power,t));const u="billed monthly";r&&(r.textContent=u),o&&(o.textContent=u),a&&(a.textContent=u),l&&(l.textContent=u)}function Ls(){qo();const t=document.getElementById("pricing-modal");t&&Ve(t),yv().then(()=>qo())}function mh(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("pricing-modal");e&&Xe(e)}function ue(t,e="info"){const n={success:"bg-green-600 text-white",error:"bg-red-600 text-white",warning:"bg-amber-500 text-white",info:"bg-gray-800 text-white"},i=document.createElement("div");i.className=`fixed bottom-6 left-1/2 -translate-x-1/2 px-5 py-3 rounded-lg text-sm font-medium shadow-lg z-50 transition-opacity duration-300 ${n[e]||n.info}`,i.textContent=t,document.body.appendChild(i),setTimeout(()=>{i.style.opacity="0",setTimeout(()=>i.remove(),300)},3500)}document.addEventListener("DOMContentLoaded",async()=>{tg(),hljs.configure({tabReplace:" ",classPrefix:"hljs-"}),T_(),await m_(),P_(),await gh(),rr(),qo(),await zv(),Dv();const t=document.getElementById("flutterflow-endpoint-select");if(t){const n=yi();t.value=n}sh(),ph();const e=document.getElementById("pipeline-input");e&&(e.addEventListener("input",()=>{kt===2&&e.value.trim().length>0&&(Ia(),Js())}),e.addEventListener("blur",()=>{const n=document.getElementById("walkthrough-modal");kt===2&&n&&Ve(n)}),e.addEventListener("keydown",n=>{if(n.key==="Tab"){const i=document.getElementById("walkthrough-modal");kt===2&&i&&setTimeout(()=>{Ve(i)},100)}})),window.addEventListener("commitStateChange",n=>{const{state:i}=n.detail;i===K.PREPARING||i===K.VALIDATING||i===K.PUSHING?(be.phaseId||_h(),Lc(i)):(i===K.SUCCESS||i===K.ERROR)&&(Lc(i),setTimeout(Os,1e3))}),sv({onSubmit:Ns}),qa()});function T_(){const t=document.getElementById("preview-frame-container");t&&(t.style.display="")}function R_(){const t=document.getElementById("welcome-video-player");t&&(t.addEventListener("click",Qt),document.addEventListener("keydown",Qt))}function Qt(){const t=document.getElementById("preview-frame-container"),e=document.getElementById("main-stage-container"),n=document.getElementById("ready-state");t&&(t.style.display="none"),e&&e.classList.add("visible"),n&&n.classList.remove("hidden");const i=document.getElementById("welcome-video-player");i&&i.removeEventListener("click",Qt),document.removeEventListener("keydown",Qt),sh()}let si=null;async function N_(){const t=document.getElementById("confirm-project-select");if(!t)return;const e=++Tc,n=()=>e===Tc,i=await Ee("flutterflow"),s=await Ee("flutterflow_project_id");if(n()){if(!i){t.innerHTML='',t.disabled=!0;return}t.disabled=!1,t.innerHTML='';try{const o=await new wi(i,"").listProjects();if(!n())return;if(!o||o.length===0){t.innerHTML='';return}t.innerHTML='',o.forEach(a=>{const l=document.createElement("option");l.value=a.id||a.projectId||"",l.textContent=a.name||a.projectName||`Project ${a.id}`,t.appendChild(l)}),s&&(t.value=s)}catch(r){if(!n())return;console.error("Failed to load projects for deploy:",r),t.innerHTML=''}}}function M_(){return document.getElementById("confirm-project-select")?.value?.trim()||null}function Wa(t,e,n,i=null){si={codeInfo:t,checks:e,deps:n,bundlePlan:i},document.getElementById("confirm-file-name").textContent=t.fileName,document.getElementById("confirm-artifact-type").textContent=t.artifactType,document.getElementById("confirm-file-size").textContent=`${(t.content.length/1024).toFixed(1)} KB`,document.getElementById("confirm-line-count").textContent=i?`${i.fileEntries.length} files`:t.content.split(` +`).length,N_();const s=document.getElementById("confirm-deps-list"),r=document.getElementById("confirm-deps-section");n&&Object.keys(n).length>0?(s.innerHTML=Object.entries(n).map(([u,c])=>{const d=c?`at least ${xt(c)}`:"version resolved from your project";return`
  • • ${xt(u)}: ${d}
  • `}).join(""),r.classList.remove("hidden")):r.classList.add("hidden");const o=document.getElementById("confirm-warnings-list"),a=document.getElementById("confirm-warnings-section");e.warnings&&e.warnings.length>0?(o.innerHTML=e.warnings.map(u=>`
  • • ${xt(u)}
  • `).join(""),a.classList.remove("hidden")):a.classList.add("hidden"),document.getElementById("confirm-code-preview").textContent=t.content,document.getElementById("code-preview-content").classList.add("hidden"),document.getElementById("code-preview-chevron").style.transform="rotate(0deg)";const l=document.getElementById("commit-confirm-modal");l&&Ve(l)}function vh(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("commit-confirm-modal");e&&Xe(e),si=null}function L_(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("commit-success-modal");e&&Xe(e);const n=["success-message","success-project-id","success-file-name","success-artifact-type","success-time","success-size"];for(const r of n){const o=document.getElementById(r);o&&(o.textContent="")}const i=document.getElementById("success-warnings-section");i&&i.classList.add("hidden");const s=document.getElementById("success-warnings-list");s&&(s.innerHTML="")}function Vo(t){const e=(m,v)=>{const b=document.getElementById(m);b&&(b.textContent=v||"")},n=t.metadata?.fileName||"",i=t.metadata?.projectId||"",s=t.metadata?.artifactType||"",r=t.elapsedTime?`${(t.elapsedTime/1e3).toFixed(1)}s`:"",o=t.metadata?.codeSize?`${(t.metadata.codeSize/1024).toFixed(1)} KB`:"";e("success-message",t.message||"Code committed successfully!"),e("success-project-id",i),e("success-file-name",n),e("success-artifact-type",s),e("success-time",r),e("success-size",o);const a=t.addedDependencies||[],l=document.getElementById("success-deps-row");l&&l.classList.toggle("hidden",a.length===0),e("success-deps",a.join(", "));const u=document.getElementById("success-open-ff-link");u&&i&&(u.href=`https://app.flutterflow.io/project/${i}`);const c=document.getElementById("success-warnings-section"),d=document.getElementById("success-warnings-list"),h=t.unverified||[],p=t.approximate||[],f=t.warnings||[];(f.length>0||h.length>0||p.length>0)&&c&&d&&(d.innerHTML=[...h.map(m=>`
  • Not verified before deploying: ${j(String(m))}
  • `),...p.map(m=>`
  • Verified approximately: ${j(String(m))}
  • `),...f.map(([m,v])=>`
  • ${j(m)}: ${j(String(v))}
  • `)].join(""),c.classList.remove("hidden"));const g=document.getElementById("commit-success-modal");g&&Ve(g)}function Go(t){Os(),u_(t)}function O_(){const t=document.getElementById("code-preview-content"),e=document.getElementById("code-preview-chevron");t.classList.contains("hidden")?(t.classList.remove("hidden"),e.style.transform="rotate(90deg)"):(t.classList.add("hidden"),e.style.transform="rotate(0deg)")}const Mc={prepare:{message:"Preparing your code...",start:4,end:14},validate:{message:"Checking FlutterFlow credentials...",start:14,end:22},project:{message:"Reading your FlutterFlow project...",start:22,end:40},provision:{message:"Creating custom classes in FlutterFlow...",start:40,end:82},package:{message:"Packaging files for upload...",start:82,end:88},push:{message:"Pushing to FlutterFlow...",start:88,end:97},done:{message:"Complete!",start:100,end:100}},B_=[{after:0,text:"Starting a FlutterFlow build runner..."},{after:12,text:"Preparing the FlutterFlow AI workspace..."},{after:35,text:"Uploading your custom classes..."},{after:60,text:"FlutterFlow is applying the changes..."},{after:100,text:"Still working — this can take a couple of minutes..."}],be={sequence:[],phaseId:null,phaseStartedAt:null,timer:null,substatus:null,liveSubstatus:!1,start({withProvisioning:t=!1}={}){this.sequence=["prepare","validate","project"],t&&this.sequence.push("provision"),this.sequence.push("package","push","done");const e=document.getElementById("commit-progress-overlay");e&&(oc(e,!0,"Deploying to FlutterFlow"),Ve(e)),this.set("prepare")},set(t,e=null){if(!(!Mc[t]||t===this.phaseId)){if(!this.sequence.includes(t)){const n=this.sequence.indexOf("package");this.sequence.splice(n===-1?this.sequence.length:n,0,t)}this.phaseId=t,this.phaseStartedAt=Date.now(),this.substatus=e,this.liveSubstatus=!1,this.render(),this.timer&&clearInterval(this.timer),t!=="done"&&(this.timer=setInterval(()=>this.render(),500))}},setSubstatus(t){t&&(this.liveSubstatus=!0,this.substatus=t,this.render())},render(){const t=Mc[this.phaseId];if(!t)return;const e=(Date.now()-this.phaseStartedAt)/1e3,n=t.start+(t.end-t.start)*(1-Math.exp(-e/25));if(this.phaseId==="provision"&&!this.liveSubstatus){const o=B_.filter(a=>e>=a.after).pop();o&&(this.substatus=o.text)}const i=this.sequence.indexOf(this.phaseId),r=[`Step ${i===-1?1:i+1} of ${this.sequence.length}`];e>=5&&r.push(D_(e)),yh(this.phaseId==="done"?100:n,t.message,r.join(" · "),this.substatus)},stop(){this.timer&&clearInterval(this.timer),this.timer=null,this.phaseId=null;const t=document.getElementById("commit-progress-overlay");t&&(oc(t,!1),Xe(t,{force:!0,restoreFocus:!1}))}};function D_(t){const e=Math.floor(t);return e<60?`${e}s elapsed`:`${Math.floor(e/60)}m ${String(e%60).padStart(2,"0")}s elapsed`}function _h(t){be.start(t)}function Os(){be.stop()}function yh(t,e,n,i=null){const s=document.getElementById("commit-progress-bar"),r=document.getElementById("progress-message"),o=document.getElementById("progress-detail"),a=document.getElementById("progress-substatus");s&&(s.style.width=`${Math.round(t*10)/10}%`),r&&(r.textContent=e),o&&(o.textContent=n),a&&(a.textContent=i||"",a.classList.toggle("hidden",!i))}function Lc(t){const e={[K.PREPARING]:"prepare",[K.VALIDATING]:"validate",[K.PUSHING]:"project",[K.SUCCESS]:"done"};if(t===K.ERROR){be.timer&&clearInterval(be.timer),be.timer=null,yh(100,"Failed","Error occurred");return}const n=e[t];n&&be.set(n)}function j_(t){return t.bundlePlan?t.bundlePlan.fileEntries.some(e=>e.type===W.CODE_FILE):t.codeInfo?.codeType===W.CODE_FILE}async function U_(){if(!si){console.error("No pending commit data");return}const t=si;if(si=null,ni=M_(),vh(),_h({withProvisioning:j_(t)}),t.bundlePlan){const o=await Qv(t.bundlePlan,{pipelineResult:{step1Result:y.step1Result,selectedModel:document.getElementById("code-generator-model")?.value}});ni=null,Os(),o.success?Vo(o):Go(o);return}const{codeInfo:e}=t,{artifactType:n,artifactName:i,fileName:s}=oh(),r=await Xv(e.content,{artifactType:n,artifactName:i,fileName:s,pipelineResult:{step1Result:y.step1Result,selectedModel:document.getElementById("code-generator-model")?.value}});ni=null,Os(),r.success?Vo(r):Go(r)}window.runThinkingPipeline=Ns;window.toggleStep=n_;window.toggleSection=t_;window.selectWorkflowStep=ze;window.copyCode=i_;window.retryWithDifferentModel=a_;window.openApiKeysModal=ka;window.closeApiKeysModal=nh;window.closeWalkthroughModal=Rv;window.openWalkthroughModal=Tv;window.advanceWalkthrough=Ia;window.commitToFlutterFlow=Zv;function H_(){const t=document.getElementById("pipeline-input");t&&t.focus()}function W_(){const t=document.getElementById("advanced-settings");t&&(t.open=!0);const e=document.getElementById("code-generator-model");e&&(e.scrollIntoView({behavior:"smooth",block:"center"}),e.focus(),e.click())}window.focusPromptInput=H_;window.openModelSelector=W_;window.handlePromptImageSelect=vv;window.removePromptImage=_v;window.saveApiKeys=Lv;window.clearAllApiKeys=Ov;window.toggleKeyVisibility=Uv;window.handleWelcomeVideoEnd=R_;window.dismissWelcomeVideo=Qt;window.initiateCommitToFlutterFlow=l_;window.updateFlutterFlowCredentialStatus=h_;window.openCommitConfirmModal=Wa;window.closeCommitConfirmModal=vh;window.closeCommitSuccessModal=L_;window.showCommitSuccessModal=Vo;window.showCommitFailureModal=Go;window.toggleCodePreview=O_;window.confirmCommitToFlutterFlow=U_;window.runRefinement=s_;window.regenerateFromPastedErrors=o_;window.clearErrorInput=r_;window.setFlutterFlowEndpoint=$v;window.getFlutterFlowEndpoint=yi;window.commitProgress=be;window.openSignInModal=Da;window.closeSignInModal=v_;window.handleMagicLinkRequest=__;window.handleSignOut=y_;window.startCheckout=A_;window.openCustomerPortal=F_;window.openPricingModal=Ls;window.closePricingModal=mh;let mn=null,wh=null;const Oc=120;function or(){An(!0);const t=document.getElementById("pipeline-progress"),e=document.getElementById("results-view"),n=document.getElementById("ready-state");n&&n.classList.add("hidden"),e&&e.classList.remove("visible"),document.body.classList.remove("results-fullscreen","results-with-sidebar"),t&&t.classList.add("visible"),wh=Date.now();for(let i=1;i<=3;i++){const s=document.getElementById(`pdot-${i}`);s&&(s.className="progress-dot")}at(1),z_()}function at(t){const e={1:"Analyzing your prompt...",2:"Generating Dart code...",3:"Running code audit..."},n={1:"Step 1 of 3 — Prompt Architect",2:"Step 2 of 3 — Code Generator",3:"Step 3 of 3 — Code Review"},i=document.getElementById("progress-title-text"),s=document.getElementById("progress-substep-text");i&&(i.textContent=e[t]||e[1]),s&&(s.textContent=n[t]||n[1]);for(let r=1;r<=3;r++){const o=document.getElementById(`pdot-${r}`);o&&(r{const t=(Date.now()-wh)/1e3,e=document.getElementById("progress-elapsed"),n=document.getElementById("pipeline-progress-fill");e&&(e.textContent=`${Math.floor(t)}s`);const i=t/Oc*100,s=Math.min(95,i*(1-Math.exp(-t/(Oc*.6)))*1.2);n&&(n.style.width=`${s}%`)},250)}function Mt(){mn&&(clearInterval(mn),mn=null);const t=document.getElementById("pipeline-progress-fill");t&&(t.style.width="100%");for(let e=1;e<=3;e++){const n=document.getElementById(`pdot-${e}`);n&&(n.className="progress-dot completed")}setTimeout(()=>{const e=document.getElementById("pipeline-progress");e&&e.classList.remove("visible"),t&&(t.style.width="0%")},400)}function Cn(t,e=""){const n={pass:'',warning:'',fail:'',info:''};return``}function bh(t){return{pass:"Passed review",warning:"Needs attention",fail:"Blocking issues"}[t]||"Needs attention"}function q_(){return om({bundle:y.artifactBundle,reviewResult:y.step3Result})}function V_(t){return` +
    + ${Cn(t.severity)} +
    +
    ${j(t.message)}
    + ${t.suggestion?`
    ${j(t.suggestion)}
    `:""} + ${j(t.source)} +
    +
    + `}function G_(t){return` +
  • +
    + ${j(t.title)} + ${t.detail&&t.detail!==t.title?`

    ${j(t.detail)}

    `:""} +
    +
  • + `}function K_(t){const e=document.getElementById("results-summary-detail"),n=document.getElementById("results-title");if(!e)return;n&&(n.textContent=t.title);const i=t.score,s=i==null?"neutral":i>=80?"pass":i>=60?"warning":"fail",r=i==null?"":i>=80?"Strong":i>=60?"Needs work":"High risk",o=t.findings.length?` +
      + ${t.findings.map(l=>` +
    • + ${Cn(l.severity)} + + ${j(l.message)} + ${l.suggestion?`${j(l.suggestion)}`:""} + +
    • + `).join("")} +
    + `:"",a=t.manualSteps.length?` +
    +

    ${Cn("info")} Complete in FlutterFlow

    +

    For your information — these don't block the deploy. Finish them by hand in the FlutterFlow editor once the code is pushed.

    +
      + ${t.manualSteps.map(l=>` +
    • + ${j(l.title)} + ${l.detail&&l.detail!==l.title?`${j(l.detail)}`:""} +
    • + `).join("")} +
    +
    + `:"";e.innerHTML=` +
    +
    +

    ${j(t.summary)}

    + ${o} + ${a} +
    +
    + +
    + Is the generated code correct? +
    + + +
    +
    +
    +
    + `}function J_(t){const e=t.artifacts.find(l=>l.id===y.selectedArtifactId)||t.artifacts[0];if(!e)return"";const n={pass:{icon:"pass",message:"No file-specific issues were found."},warning:{icon:"warning",message:"This file needs attention, but Code Review did not return a specific finding."},fail:{icon:"fail",message:"This file is blocked, but Code Review did not return a specific finding."}}[e.status],i=e.findings.length?e.findings.map(V_).join(""):`
    ${Cn(n.icon)} ${j(n.message)}
    `,s=e.dependencies?.length?e.dependencies.map(l=>` +
  • ${j(l.name)}${l.version?` ${j(l.version)}`:""}${l.reason?`

    ${j(l.reason)}

    `:""}
  • + `).join(""):'
  • No external packages
  • ',r=e.imports?.length?e.imports.map(l=>`${j(l)}`).join(""):'No imports returned',o=e.publicApi?.length?e.publicApi.map(l=>`${j(l)}`).join(""):'No public API signature returned',a=e.relationships.length?e.relationships.map(l=>` +
  • ${j(l.from||"Bundle")} ${j(l.type)} ${j(l.to||"Bundle")}${l.description?`

    ${j(l.description)}

    `:""}
  • + `).join(""):'
  • No relationships for this file
  • ';return` +
    +
    + ${Cn(e.status)} ${j(bh(e.status))} +

    ${j(e.artifactName)}

    + ${e.description?`

    ${j(e.description)}

    `:""} +
    +
    + ${j(e.artifactType)} + ${j(e.fileName)} +
    +
    +
    +

    Code Review findings

    + ${i} +
    + ${e.manualSteps.length?` +
    +

    Manual FlutterFlow steps for this file

    +
      ${e.manualSteps.map(G_).join("")}
    +
    + `:""} +
    + File details +
    +
    +

    Dependencies

    +
      ${s}
    +
    +
    +

    Deployment

    +
    +
    Status
    ${j(e.deployStatus||"pending")}
    +
    Order
    ${e.index+1} of ${t.artifacts.length}
    +
    Path hint
    ${j(e.pathHint||"Not returned")}
    +
    +
    +
    +
    +

    Public API

    +
    ${o}
    +
    +
    +

    Imports

    +
    ${r}
    +
    +
    +

    Relationships

    +
      ${a}
    +
    +
    + `}function Y_(t){const e=document.getElementById("bundle-strip"),n=document.getElementById("results-summary-tab"),i=document.getElementById("artifact-tabs"),s=document.getElementById("results-file-count");if(n&&n.classList.toggle("active",y.resultsViewMode==="summary"),!t.artifacts.length){s&&(s.textContent="0 files"),e&&e.classList.remove("visible"),i&&(i.innerHTML="");return}if(s){const r=t.artifacts.length;s.textContent=`${r} ${r===1?"file":"files"}`}i&&(i.innerHTML=t.artifacts.map(r=>` + + `).join(""),i.onclick=r=>{const o=r.target.closest(".artifact-tab");o?.dataset?.artifactId&&Eh(o.dataset.artifactId)}),e&&e.classList.add("visible")}function za(){document.body.classList.add("results-fullscreen"),document.body.classList.add("results-with-sidebar");const t=document.getElementById("results-view"),e=document.getElementById("results-code-output"),n=document.getElementById("results-audit-output"),i=document.getElementById("results-summary-detail"),s=document.getElementById("artifact-results-split"),r=q_(),o=Fa();if(K_(r),Y_(r),e&&(e.textContent=""),e){const a=Vd(o);e.innerHTML=a}n&&(n.innerHTML=J_(r)),i&&i.classList.toggle("hidden",y.resultsViewMode!=="summary"),s&&s.classList.toggle("hidden",y.resultsViewMode!=="file"),t&&t.classList.add("visible")}function ar(t,e){An(!0),y.selectedArtifactId||(y.selectedArtifactId=Ss(y.artifactBundle).id),y.resultsViewMode="summary",document.body.classList.add("results-fullscreen");const n=document.getElementById("step3-output");n&&(n.textContent=""),za(),en();const i=document.getElementById("btn-feedback-up"),s=document.getElementById("btn-feedback-down");i&&(i.className="feedback-btn"),s&&(s.className="feedback-btn")}function Eh(t){y.selectedArtifactId=t,y.resultsViewMode="file",za()}function Z_(){y.resultsViewMode="summary",za()}function X_(){const t=document.getElementById("btn-copy-results"),e=Fa();navigator.clipboard.writeText(e).then(()=>{if(t){t.classList.add("copied");const n=t.querySelector("span");if(n){const i=n.textContent;n.textContent="Copied!",setTimeout(()=>{t.classList.remove("copied"),n.textContent=i},2e3)}}})}function Q_(t){const e=document.getElementById("btn-feedback-up"),n=document.getElementById("btn-feedback-down");t==="up"?(e.classList.toggle("active-up"),n.classList.remove("active-down")):(n.classList.toggle("active-down"),e.classList.remove("active-up")),Oa(t==="up"?"thumbsUp":"thumbsDown",y.step2Result,y.step1Result)}function ey(){const t=document.getElementById("error-input-panel");if(t){t.classList.remove("hidden"),t.style.display="flex";const e=document.getElementById("ff-error-paste-input");e&&setTimeout(()=>e.focus(),100)}}function Sh(){const t=document.getElementById("error-input-panel");t&&(t.classList.add("hidden"),t.style.display="none")}function An(t){const e=document.getElementById("generation-stage");e&&(t?(e.hidden=!1,e.inert=!1,requestAnimationFrame(()=>e.classList.add("is-active"))):(e.classList.remove("is-active"),e.inert=!0,setTimeout(()=>{e.classList.contains("is-active")||(e.hidden=!0)},260)))}function xh(){const t=V.isVerified&&!!V.email,e=pe.tier||"free",n=t&&ir(),i=!t||Nt(),r=n?"Checking…":i?{free:"Free",professional:"Pro",power:"Power"}[e]||"Free":"—",o=document.getElementById("topbar-plan");o&&(o.textContent=r);const a=document.getElementById("topbar-avatar");a&&(a.textContent=(V.email||"?")[0].toUpperCase());const l=bi(),u=`${l.count} / ${sr()} runs this month`,c=document.getElementById("topbar-credits-count");c&&(c.textContent=String(l.count));const d=document.getElementById("credits-balance");d&&(d.textContent=u);const h=document.getElementById("plans-free-current");h&&h.classList.toggle("hidden",e!=="free"||!i);const p=document.getElementById("plans-checkout-btn-professional");if(p){const g=e==="professional"&&i;p.disabled=g,p.textContent=g?"Current plan":"Subscribe"}const f=document.getElementById("plans-checkout-btn-power");if(f){const g=e==="power"&&i;f.disabled=g,f.textContent=g?"Current plan":"Subscribe"}}function ty(){xh();const t=document.getElementById("credits-modal");t&&Ve(t)}function ny(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("credits-modal");e&&Xe(e)}function kh(t,e=!0,n=!0){if(t=["home","account","plans"].includes(t)?t:"home",document.querySelectorAll(".view[data-view]").forEach(s=>{s.dataset.view===t?(s.hidden=!1,s.removeAttribute("inert"),requestAnimationFrame(()=>{s.classList.add("is-active"),n&&s.focus({preventScroll:!0})})):(s.classList.remove("is-active"),s.setAttribute("inert","true"),setTimeout(()=>{s.classList.contains("is-active")||(s.hidden=!0)},260))}),t!=="home")An(!1);else{const s=document.getElementById("main-stage-container");s&&s.classList.contains("visible")&&An(!0)}if(document.querySelectorAll(".nav-link[data-view]").forEach(s=>{const r=s.dataset.view===t;s.setAttribute("aria-current",r?"page":null),r||s.removeAttribute("aria-current")}),e){const s=t==="home"?"":`#${t}`;window.location.hash!==s&&window.history.pushState({view:t},"",s||"#")}}let Bc=!1;function qa(){const t=window.location.hash.replace(/^#/,"");kh(t||"home",!1,Bc),Bc=!0}window.addEventListener("popstate",t=>{qa()});window.addEventListener("hashchange",()=>{qa()});window.copyResultsCode=X_;window.selectArtifact=Eh;window.selectResultsSummary=Z_;window.submitResultsFeedback=Q_;window.showErrorInputPanel=ey;window.hideErrorInputPanel=Sh;window.setGenerationStageVisible=An;window.switchView=kh;window.openCreditsModal=ty;window.closeCreditsModal=ny; diff --git a/dist/assets/index-DBT7sHov.js b/dist/assets/index-DBT7sHov.js deleted file mode 100644 index ac31fd9..0000000 --- a/dist/assets/index-DBT7sHov.js +++ /dev/null @@ -1,320 +0,0 @@ -(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const i of document.querySelectorAll('link[rel="modulepreload"]'))r(i);new MutationObserver(i=>{for(const s of i)if(s.type==="childList")for(const o of s.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&r(o)}).observe(document,{childList:!0,subtree:!0});function n(i){const s={};return i.integrity&&(s.integrity=i.integrity),i.referrerPolicy&&(s.referrerPolicy=i.referrerPolicy),i.crossOrigin==="use-credentials"?s.credentials="include":i.crossOrigin==="anonymous"?s.credentials="omit":s.credentials="same-origin",s}function r(i){if(i.ep)return;i.ep=!0;const s=n(i);fetch(i.href,s)}})();var v=typeof window<"u"?window:void 0,we=typeof globalThis<"u"?globalThis:v,ke=we?.navigator,C=we?.document,re=we?.location,Jo=we?.fetch,Ws=we!=null&&we.XMLHttpRequest&&"withCredentials"in new we.XMLHttpRequest?we.XMLHttpRequest:void 0,Ja=we?.AbortController,Ch=we?.CompressionStream,Ae=ke?.userAgent;function Dc(){return!(!v||v.navigator.onLine===!1)}var Tn=typeof globalThis<"u"?globalThis:v;Tn&&typeof self>"u"&&(Tn.self=Tn),Tn&&typeof File>"u"&&(Tn.File=function(){});var $=v??{},Y={DEBUG:!1,LIB_VERSION:"0.5.0",LIB_NAME:"browser-common"};function Ya(t,e,n,r,i,s,o){try{var a=t[s](o),l=a.value}catch(u){return void n(u)}a.done?e(l):Promise.resolve(l).then(r,i)}function X(t){return function(){var e=this,n=arguments;return new Promise((function(r,i){var s=t.apply(e,n);function o(l){Ya(s,r,i,o,a,"next",l)}function a(l){Ya(s,r,i,o,a,"throw",l)}o(void 0)}))}}function E(){return E=Object.assign?Object.assign.bind():function(t){for(var e=1;arguments.length>e;e++){var n=arguments[e];for(var r in n)({}).hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t},E.apply(null,arguments)}function jc(t,e){if(t==null)return{};var n={};for(var r in t)if({}.hasOwnProperty.call(t,r)){if(e.indexOf(r)!==-1)continue;n[r]=t[r]}return n}var Za=t=>{if(typeof t!="string")return t;try{return JSON.parse(t)}catch{return t}};function Xa(t){return typeof t=="string"||t}function Qa(t){return typeof t=="string"?t:void 0}var Mn,Fh=["$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","irclid","_kx","$session_id","$window_id","$lib","$lib_version","$device_id","$is_server"],pt=(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.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.SurveysSeen="surveys_seen",t.Surveys="surveys",t.RemoteConfig="remote_config",t.FlagsEndpointWasHit="flags_endpoint_was_hit",t.DeviceId="device_id",t})({}),el=(function(t){return t.GZipJS="gzip-js",t.Base64="base64",t})({}),Ah=["$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"],Ph=["token"],Uc="NativeGzipValidationError",zs=t=>t.length>=2&&t[0]===31&&t[1]===139,tl=(t,e)=>t===el.GZipJS||e===el.GZipJS||e==="gzip",nl=t=>!(!t||typeof t!="object")&&("name"in t?String(t.name):"")==="NotReadableError",Ir=t=>{var e=new Error("Native gzip produced invalid output: "+t);throw e.name=Uc,e},$h=(function(){var t=X((function*(e,n){18>e.size&&Ir("too-short");var r=new Uint8Array(yield e.slice(0,10).arrayBuffer());zs(r)&&r[2]===8||Ir("invalid-header");var i=new DataView(yield e.slice(e.size-8).arrayBuffer());i.getUint32(0,!0)!==(o=>{for(var a=(()=>{if(Mn)return Mn;Mn=[];for(var c=0;256>c;c++){for(var d=c,h=0;8>h;h++)d=1&d?3988292384^d>>>1:d>>>1;Mn[c]=d>>>0}return Mn})(),l=4294967295,u=0;o.length>u;u++)l=a[255&(l^o[u])]^l>>>8;return(4294967295^l)>>>0})(n)&&Ir("invalid-crc");var s=n.length>>>0;i.getUint32(4,!0)!==s&&Ir("invalid-size")}));return function(e,n){return t.apply(this,arguments)}})();function qs(){return qs=X((function*(t,e,n){e===void 0&&(e=!0);try{var r=new TextEncoder().encode(t),i=new globalThis.CompressionStream("gzip"),s=i.writable.getWriter(),o=s.write(r).then((()=>s.close())).catch((function(){var u=X((function*(c){try{yield s.abort(c)}catch{}throw c}));return function(c){return u.apply(this,arguments)}})()),a=new Response(i.readable).blob(),l=(yield Promise.all([a,o]))[0];return yield $h(l,r),l}catch(u){if(n!=null&&n.rethrow)throw u;return e&&console.error("Failed to gzip compress data",u),null}})),qs.apply(this,arguments)}var Rh=["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","pinterest","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"],rl=function(t,e){if(e===void 0&&(e=[]),!t)return!1;var n=t.toLowerCase();return Rh.concat(e).some((r=>{var i=r.toLowerCase();return n.indexOf(i)!==-1}))};function N(t,e){return t.indexOf(e)!==-1}var Bi=function(t){return t.trim()},Vs=function(t){return t.replace(/^\$/,"")};function Hc(t){var e,n=[];return(e=JSON.stringify(t,(function(r,i){if(typeof i=="bigint")return i.toString();if(typeof i!="function"&&typeof i!="symbol"){if(i instanceof Error)return{name:i.name,message:i.message,stack:i.stack};if(i&&typeof i=="object"){for(;n.length>0&&n[n.length-1]!==this;)n.pop();if(n.includes(i))return"[Circular]";n.push(i)}return i}})))!==null&&e!==void 0?e:"null"}var Wc=Object.prototype,zc=Wc.hasOwnProperty,Di=Wc.toString,L=Array.isArray||function(t){return Di.call(t)==="[object Array]"},Se=t=>typeof t=="function",te=t=>t===Object(t)&&!L(t),yt=t=>{if(te(t)){for(var e in t)if(zc.call(t,e))return!1;return!0}return!1},x=t=>t===void 0,W=t=>Di.call(t)=="[object String]",Gs=t=>W(t)&&t.trim().length===0,$e=t=>t===null,B=t=>x(t)||$e(t),he=t=>Di.call(t)=="[object Number]"&&t==t,dt=t=>he(t)&&t>0,Ye=t=>Di.call(t)==="[object Boolean]",Th=t=>t instanceof FormData,Mh=t=>N(Ah,t),Nh=t=>N(Ph,t);function qc(t){return t===null||typeof t!="object"}function ti(t,e){return{}.toString.call(t)==="[object "+e+"]"}function Yo(t){return typeof Event<"u"&&Vc(t,Event)}function Vc(t,e){try{return t instanceof e}catch{return!1}}var Lh=[!0,"true",1,"1","yes"],cs=t=>N(Lh,t),Oh=[!1,"false",0,"0","no"];function ot(t,e,n,r,i){return e>n&&(r.warn("min cannot be greater than max."),e=n),he(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: "+i),ot(i||n,e,n,r))}class Bh{constructor(e){this.tt={},this.et=e.et,this.it=ot(e.bucketSize,0,100,e.rt),this.nt=ot(e.refillRate,0,this.it,e.rt),this.st=ot(e.refillInterval,0,864e5,e.rt)}ot(e,n){var r=Math.floor((n-e.lastAccess)/this.st);r>0&&(e.tokens=Math.min(e.tokens+r*this.nt,this.it),e.lastAccess=e.lastAccess+r*this.st)}consumeRateLimit(e){var n,r=Date.now(),i=String(e),s=this.tt[i];return s?this.ot(s,r):this.tt[i]=s={tokens:this.it,lastAccess:r},s.tokens===0||(s.tokens--,s.tokens===0&&((n=this.et)==null||n.call(this,e)),s.tokens===0)}stop(){this.tt={}}}var Oe="Mobile",ni="iOS",wt="Android",_n="Tablet",Gc=wt+" "+_n,Kc="iPad",Jc="Apple",Yc=Jc+" Watch",Zn="Safari",yn="BlackBerry",Zc="Samsung",Xc=Zc+"Browser",Qc=Zc+" Internet",Zt="Chrome",Dh=Zt+" OS",eu=Zt+" "+ni,Zo="Internet Explorer",tu=Zo+" "+Oe,Xo="Opera",jh=Xo+" Mini",Qo="Edge",nu="Microsoft "+Qo,gn="Firefox",ru=gn+" "+ni,or="Nintendo",ar="PlayStation",mn="Xbox",iu=wt+" "+Oe,su=Oe+" "+Zn,zn="Windows",Ks=zn+" Phone",il="Nokia",Js="Ouya",ou="Generic",Uh=ou+" "+Oe.toLowerCase(),au=ou+" "+_n.toLowerCase(),Ys="Konqueror",lu="Oculus Browser",ri="Vivaldi",cu="Yandex",ii="Whale",Zs="DuckDuckGo",uu="Pale Moon",si="Waterfox",Xn="Brave",du="Google Search App",le="(\\d+(\\.\\d+)?)",us=new RegExp("Version/"+le),Hh=new RegExp(mn,"i"),Wh=new RegExp(ar+" \\w+","i"),zh=new RegExp(or+" \\w+","i"),ea=new RegExp(yn+"|PlayBook|BB10","i"),qh={"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"},hu=function(t,e,n,r){e=e||"";var i=(function(s){return s!=null&&s.brave?Xn:null})(n);return i||(r!=null&&r.detectGoogleSearchApp&&N(t,"GSA/")?du:N(t," OPR/")&&N(t,"Mini")?jh:N(t," OPR/")?Xo:ea.test(t)?yn:N(t,"IE"+Oe)||N(t,"WPDesktop")?tu:N(t,"OculusBrowser")?lu:N(t,Xc)?Qc:N(t,Qo)||N(t,"Edg/")?nu:N(t,ri+"/")?ri:N(t,"YaBrowser/")?cu:N(t,ii+"/")?ii:N(t,Zs+"/")||N(t,"Ddg/")?Zs:N(t,"FBIOS")?"Facebook "+Oe:N(t,"UCWEB")||N(t,"UCBrowser")?"UC Browser":N(t,"CriOS")?eu:N(t,"CrMo")||N(t,Zt)?Zt:N(t,wt)&&N(t,Zn)?iu:N(t,"FxiOS")?ru:N(t.toLowerCase(),Ys.toLowerCase())?Ys:N(t,Xn+"/")?Xn:((s,o)=>o&&N(o,Jc)||(function(a){return N(a,Zn)&&!N(a,Zt)&&!N(a,wt)})(s))(t,e)?N(t,Oe)?su:Zn:N(t,"PaleMoon/")?uu:N(t,si+"/")?si:N(t,gn)?gn:N(t,"MSIE")||N(t,"Trident/")?Zo:N(t,"Gecko")?gn:"")},Vh={[tu]:[new RegExp("rv:"+le)],[nu]:[new RegExp(Qo+"?\\/"+le)],[Zt]:[new RegExp("("+Zt+"|CrMo)\\/"+le)],[eu]:[new RegExp("CriOS\\/"+le)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+le)],[Zn]:[us],[su]:[us],[Xo]:[new RegExp("(Opera|OPR)\\/"+le)],[gn]:[new RegExp(gn+"\\/"+le)],[ru]:[new RegExp("FxiOS\\/"+le)],[Ys]:[new RegExp("Konqueror[:/]?"+le,"i")],[yn]:[new RegExp(yn+" "+le),us],[iu]:[new RegExp("android\\s"+le,"i")],[Qc]:[new RegExp(Xc+"\\/"+le)],[lu]:[new RegExp("OculusBrowser\\/"+le)],[ri]:[new RegExp(ri+"\\/"+le)],[cu]:[new RegExp("YaBrowser\\/"+le)],[ii]:[new RegExp(ii+"\\/"+le)],[Xn]:[new RegExp(Xn+"\\/"+le)],[Zs]:[new RegExp("(DuckDuckGo|Ddg)\\/"+le)],[uu]:[new RegExp("PaleMoon\\/"+le)],[si]:[new RegExp(si+"\\/"+le)],[du]:[new RegExp("GSA\\/"+le)],[Zo]:[new RegExp("(rv:|MSIE )"+le)],Mozilla:[new RegExp("rv:"+le)]},Gh=function(t,e,n,r){var i=hu(t,e,n,r),s=Vh[i];if(x(s))return null;for(var o=0;s.length>o;o++){var a=t.match(s[o]);if(a)return parseFloat(a[a.length-2])}return null},sl=[[new RegExp(mn+"; "+mn+" (.*?)[);]","i"),t=>[mn,t&&t[1]||""]],[new RegExp(or,"i"),[or,""]],[new RegExp(ar,"i"),[ar,""]],[ea,[yn,""]],[new RegExp(zn,"i"),(t,e)=>{if(/Phone/.test(e)||/WPDesktop/.test(e))return[Ks,""];if(new RegExp(Oe).test(e)&&!/IEMobile\b/.test(e))return[zn+" "+Oe,""];var n=/Windows NT ([0-9.]+)/i.exec(e);if(n&&n[1]){var r=qh[n[1]]||"";return/arm/i.test(e)&&(r="RT"),[zn,r]}return[zn,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,t=>t&&t[3]?[ni,[t[3],t[4],t[5]||"0"].join(".")]:[ni,""]],[/(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i,t=>{var e="";return t&&t.length>=3&&(e=x(t[2])?t[3]:t[2]),["watchOS",e]}],[new RegExp("("+wt+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+wt+")","i"),t=>t&&t[2]?[wt,[t[2],t[3],t[4]||"0"].join(".")]:[wt,""]],[/Mac OS X (\d+)[_.](\d+)[_.]?(\d+)?/i,t=>{var 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/,[Dh,""]],[/Linux|debian/i,["Linux",""]]],ol=function(t){return zh.test(t)?or:Wh.test(t)?ar:Hh.test(t)?mn:new RegExp(Js,"i").test(t)?Js:new RegExp("("+Ks+"|WPDesktop)","i").test(t)?Ks:/iPad/.test(t)?Kc:/iPod/.test(t)?"iPod Touch":/iPhone/.test(t)?"iPhone":/(watch)(?: ?os[,/]|\d,\d\/)[\d.]+/i.test(t)?Yc:ea.test(t)?yn:/(kobo)\s(ereader|touch)/i.test(t)?"Kobo":new RegExp(il,"i").test(t)?il:/(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(Oe).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)?wt:Gc:new RegExp("(pda|"+Oe+")","i").test(t)?Uh:new RegExp(_n,"i").test(t)&&!new RegExp(_n+" pc","i").test(t)?au:""},Kh=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function al(t,e){return typeof(n=t)=="string"&&Kh.test(n)?t:e();var n}function Pt(t){return t&&t.split("#")[0]}function ta(t,e){var n=setTimeout(t,e);return n?.unref&&n?.unref(),n}function ll(t,e,n){return pu.apply(this,arguments)}function pu(){return(pu=X((function*(t,e,n){var r;try{return yield Promise.race([t,new Promise(((i,s)=>{r=ta((()=>{try{n?.(),i()}catch(o){s(o)}}),e)}))])}finally{clearTimeout(r)}}))).apply(this,arguments)}var Jh=t=>t instanceof Error,fu={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}},Yh=fu.info;function gu(t){if(Ye(t))return{boolValue:t};if(typeof t=="number")return Number.isFinite(t)?Number.isInteger(t)?{intValue:t}:{doubleValue:t}:{stringValue:String(t)};if(typeof t=="string")return{stringValue:t};if(L(t))return{arrayValue:{values:t.map((e=>gu(e)))}};try{return{stringValue:JSON.stringify(t)}}catch{return{stringValue:String(t)}}}function oi(t){var e=[];for(var n in t){var r=t[n];$e(r)||x(r)||e.push({key:n,value:gu(r)})}return e}function Zh(t,e){var n=fu[t.level||"info"]||Yh,r=n.text,i=n.number,s=String(Date.now())+"000000",o={};e.distinctId&&(o.posthogDistinctId=e.distinctId),e.sessionId&&(o.sessionId=e.sessionId),e.windowId&&(o["window.id"]=e.windowId),B(e.sessionStartTimestamp)||(o.sessionStartTimestamp=String(e.sessionStartTimestamp)),B(e.lastActivityTimestamp)||(o.lastActivityTimestamp=String(e.lastActivityTimestamp)),e.currentUrl&&(o["url.full"]=e.currentUrl),e.screenName&&(o["screen.name"]=e.screenName),e.appState&&(o["app.state"]=e.appState),e.activeFeatureFlags&&e.activeFeatureFlags.length>0&&(o.feature_flags=e.activeFeatureFlags);var a=E({},o,t.attributes||{}),l={timeUnixNano:s,observedTimeUnixNano:s,severityNumber:i,severityText:r,body:{stringValue:t.body},attributes:oi(a)};return t.trace_id&&(l.traceId=t.trace_id),t.span_id&&(l.spanId=t.span_id),x(t.trace_flags)||(l.flags=t.trace_flags),l}function mu(t,e,n){return E({},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})}function vu(t,e,n,r){return{resourceLogs:[{resource:{attributes:oi(e)},scopeLogs:[{scope:{name:n,version:r},logRecords:t}]}]}}let Xh=class{constructor(t,e,n,r,i,s,o){var a;s===void 0&&(s=()=>Promise.resolve()),this._instance=t,this.Ne=e,this.rt=n,this.ut=r,this.ht=i,this.dt=s,this.vt=o,this.ct=null,this.ft=0,this.yt=0,this.bt=0,this._t=0,this.wt=!1,this.kt=e.maxBufferSize,this.xt=Math.max((a=e.maxQueueSize)!==null&&a!==void 0?a:e.maxBufferSize,e.maxBufferSize),this.St=e.flushIntervalMs,this.Ct=e.maxBatchRecordsPerPost,this.Mt=e.rateCapWindowMs,this.Tt=e.maxLogsPerInterval}reset(){this.Et(),this.ct=null,this.bt=0,this._t=0,this.wt=!1,this.ft=0,this.yt=0,this.Ct=this.Ne.maxBatchRecordsPerPost}onReconnect(){this.yt=0,this.It()}captureLog(t){if(!this._instance.isDisabled&&!this._instance.optedOut&&t!=null&&t.body){var e=this.Pt(t);if(e!==null)if(e.body){if(this.Rt()){var n={record:Zh(e,this.ut())};this.ht((()=>this.At(n)))}}else this.rt.info("Log was rejected in beforeSend function")}}Pt(t){var e=this.Ne.beforeSend;if(!e)return t;var n=L(e)?e:[e],r=t;for(var i of n)try{var s=i(r);if(!s)return this.rt.info("Log was rejected in beforeSend function"),null;r=s}catch(o){return this.rt.error("Error in beforeSend function for log:",o),null}return r}Rt(){if(this.Tt===void 0)return!0;var t=Date.now(),e=t-this.bt;return this.Mt>e&&e>=0||(this.bt=t,this._t=0,this.wt=!1),this.Tt>this._t?(this._t++,!0):(this.wt||(this.rt.warn("captureLog dropping logs: exceeded "+this.Tt+" logs per "+this.Mt+"ms"),this.wt=!0),!1)}flush(){var t=this;return X((function*(){if(!t._instance.isDisabled)return t.ct||(t.ct=t.Ft().finally((()=>{t.ct=null}))),t.ct}))()}Ft(){var t=this;return X((function*(){var e;t.Et();var n=(e=t._instance.getPersistedProperty(pt.LogsQueue))!==null&&e!==void 0?e:[];if(n.length!==0)for(var r=n.length,i=0;n.length>0&&r>i;){var s,o;t.ft=0;var a=Math.min(n.length,t.Ct),l=n.slice(0,a),u=vu(l.map((d=>d.record)),t.Lt(),(s=t.vt)!==null&&s!==void 0?s:t._instance.getLibraryId(),t._instance.getLibraryVersion()),c=yield t._instance.Ot(u);if(c.kind==="too-large"&&l.length>1)t.Ct=Math.max(1,Math.floor(l.length/2)),t.rt.warn("Received 413 when sending logs batch of size "+l.length+", reducing batch size to "+t.Ct);else if(c.kind==="retry-later"||(c.kind==="too-large"?t.rt.warn("Dropping a single log record after 413 with batch size 1 — the record is larger than the server cap and cannot be split further."):c.kind==="ok"&&t.Ne.maxBatchRecordsPerPost>t.Ct&&(t.Ct=Math.min(t.Ne.maxBatchRecordsPerPost,t.Ct+1)),yield t.Dt(l.length),n=(o=t._instance.getPersistedProperty(pt.LogsQueue))!==null&&o!==void 0?o:[],i+=l.length,c.kind==="fatal"))throw c.error}}))()}Dt(t){var e=this;return X((function*(){var n,r=Math.max(0,t-e.ft),i=(n=e._instance.getPersistedProperty(pt.LogsQueue))!==null&&n!==void 0?n:[];e._instance.setPersistedProperty(pt.LogsQueue,i.slice(r)),yield e.dt()}))()}Lt(){return mu(this.Ne,this._instance.getLibraryId(),this._instance.getLibraryVersion())}At(t){var e;if(!this._instance.optedOut){var n=(e=this._instance.getPersistedProperty(pt.LogsQueue))!==null&&e!==void 0?e:[];this.xt>n.length||(n.shift(),this.ft++,this.rt.info("Logs queue is full, dropping oldest record.")),n.push(t),this._instance.setPersistedProperty(pt.LogsQueue,n),this.kt>n.length?this.$t():this.It()}}$t(t){t===void 0&&(t=this.St),this.Nt||(this.Nt=ta((()=>{this.Nt=void 0,this.It()}),t))}qt(){var t=Math.min(Math.max(0,this.yt-1),6);return this.St*Math.pow(2,t)}jt(){var t=this._instance.getPersistedProperty(pt.LogsQueue);return!!t&&t.length>0}shutdown(t){var e=this;return X((function*(){e.Et();var n=e.flush().catch((()=>{}));t!==void 0?yield ll(n,t):yield n}))()}flushWithTimeout(t){var e=this;return X((function*(){var n=e.flush();yield ll(n,t,(()=>{n.catch((()=>{}))}))}))()}It(){this.flush().then((()=>{this.yt=0}),(t=>{this.yt++,this.rt.error("PostHog logs flush failed:",t)})).finally((()=>{!this._instance.isDisabled&&this.jt()&&this.$t(this.qt())}))}Et(){this.Nt&&(clearTimeout(this.Nt),this.Nt=void 0)}};var ds=[0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4];function cl(t){return String(t)+"000000"}function ul(t,e,n,r){var i="";return r&&(i=Object.keys(r).sort().map((s=>JSON.stringify(s)+":"+JSON.stringify(r[s]))).join(",")),t+"\0"+e+"\0"+(n??"")+"\0"+i}let Qh=class{constructor(t,e,n){this._instance=t,this.Ne=e,this.rt=n,this.Bt=new Map,this.ct=null,this.Ht=!1,this.Ut=new Map,this.zt=new Set,this.Wt=0}count(t,e,n){e===void 0&&(e=1),this.Vt({name:t,type:"count",value:e,unit:n?.unit,attributes:n?.attributes})}gauge(t,e,n){this.Vt({name:t,type:"gauge",value:e,unit:n?.unit,attributes:n?.attributes})}histogram(t,e,n){this.Vt({name:t,type:"histogram",value:e,unit:n?.unit,attributes:n?.attributes})}flush(){var t=this,e=this.ct,n=(function(){var i=X((function*(){e&&(yield e.catch((()=>{}))),yield t.Zt()}));return function(){return i.apply(this,arguments)}})(),r=n().finally((()=>{this.ct===r&&(this.ct=null)}));return this.ct=r,r}drainWindow(){if(this.Bt.size===0)return null;var t=this.Bt;return this.Bt=new Map,this.Ht=!1,this.Ut=new Map,this.zt=new Set,this.Gt(t)}reset(){this.Wt++,this.Et(),this.Bt=new Map,this.ct=null,this.Ht=!1,this.Ut=new Map,this.zt=new Set}Vt(t){if(!this._instance.isDisabled&&!this._instance.optedOut){var e=this.Pt(t);if(e!==null)if(e.name&&typeof e.name=="string")if(typeof e.value=="number"&&Number.isFinite(e.value))if(e.type==="count"&&0>e.value)this.rt.warn("Dropping count '"+e.name+"': counters are monotonic, value must be >= 0");else{var n,r;try{n=e.attributes?E({},e.attributes):void 0,r=ul(e.type,e.name,e.unit,n)}catch(o){return void this.rt.warn("Dropping metric '"+e.name+"': attributes could not be serialized",o)}var i=this.Bt.get(r);if(!i){if(!this.Qt())return;i={name:e.name,type:e.type,unit:e.unit,attributes:n,windowStartMs:Date.now()},this.Bt.set(r,i)}var s=this.Ut.get(e.name);s===void 0?this.Ut.set(e.name,e.type):s===e.type||this.zt.has(e.name)||(this.zt.add(e.name),this.rt.warn("Metric name '"+e.name+"' is already used as a "+s+"; recording it as a "+e.type+" too will blend both series in charts. Use a distinct name.")),this.Kt(i,e.value),this.$t()}else this.rt.warn("Dropping metric '"+e.name+"': value must be a finite number");else this.rt.warn("Dropping metric with empty name")}}Qt(){return this.Ne.maxSeriesPerFlush>this.Bt.size||(this.Ht||(this.Ht=!0,this.rt.warn("Metric series cap reached ("+this.Ne.maxSeriesPerFlush+" per flush window); dropping new series until the next flush. Reduce attribute cardinality.")),!1)}Kt(t,e){var n;switch(t.type){case"count":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(ds.length+1).fill(0)});var 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(i,s){for(var o=0;s.length>o;o++)if(s[o]>=i)return o;return s.length})(e,ds)]+=1}}Pt(t){var e=this.Ne.beforeSend;if(!e)return t;var n=L(e)?e:[e],r=t;for(var i of n)try{var s=i(r);if(!s)return this.rt.info("Metric was rejected in beforeSend function"),null;r=s}catch(o){return this.rt.error("Error in beforeSend function for metric:",o),null}return r}$t(){this.Nt||(this.Nt=ta((()=>{this.Nt=void 0,this.flush().catch((t=>{this.rt.error("Metrics flush failed:",t)}))}),this.Ne.flushIntervalMs))}Et(){this.Nt&&(clearTimeout(this.Nt),this.Nt=void 0)}Zt(){var t=this;return X((function*(){if(t.Bt.size!==0){var e=t.Bt;t.Bt=new Map,t.Ht=!1,t.Ut=new Map,t.zt=new Set;var n=t.Wt,r=yield t._instance.Jt(t.Gt(e));if(n===t.Wt)switch(r.kind){case"ok":return;case"retry-later":return t.Yt(e),void t.$t();case"too-large":return void t.rt.warn("Metrics batch exceeded the server size limit and was dropped");case"fatal":return void t.rt.error("Failed to send metrics batch:",r.error)}}}))()}Gt(t){return e=this.Xt(t),n=(function(s,o,a){return E({},s.resourceAttributes,{"service.name":s.serviceName||"unknown_service"},s.environment&&{"deployment.environment":s.environment},s.serviceVersion&&{"service.version":s.serviceVersion},{"telemetry.sdk.name":o,"telemetry.sdk.version":a})})(this.Ne,this._instance.getLibraryId(),this._instance.getLibraryVersion()),r=this._instance.getLibraryId(),i=this._instance.getLibraryVersion(),{resourceMetrics:[{resource:{attributes:oi(n)},scopeMetrics:[{scope:{name:r,version:i},metrics:e}]}]};var e,n,r,i}Xt(t){var e=cl(Date.now()),n=new Map;for(var r of t.values()){var i,s=ul(r.type,r.name,r.unit,void 0),o=n.get(s);o||(o=E({name:r.name},r.unit&&{unit:r.unit}),r.type==="count"?o.sum={aggregationTemporality:1,isMonotonic:!0,dataPoints:[]}:r.type==="gauge"?o.gauge={dataPoints:[]}:o.histogram={aggregationTemporality:1,dataPoints:[]},n.set(s,o));var a=oi((i=r.attributes)!==null&&i!==void 0?i:{}),l=cl(r.windowStartMs);if(r.type==="count"){var u,c={attributes:a,startTimeUnixNano:l,timeUnixNano:e,asDouble:(u=r.total)!==null&&u!==void 0?u:0};o.sum.dataPoints.push(c)}else if(r.type==="gauge"){var d,h={attributes:a,timeUnixNano:e,asDouble:(d=r.last)!==null&&d!==void 0?d:0};o.gauge.dataPoints.push(h)}else r.hist&&o.histogram.dataPoints.push({attributes:a,startTimeUnixNano:l,timeUnixNano:e,count:r.hist.count,sum:r.hist.sum,min:r.hist.min,max:r.hist.max,bucketCounts:r.hist.bucketCounts,explicitBounds:ds})}return Array.from(n.values())}Yt(t){var e,n;for(var r of t){var i=r[0],s=r[1],o=this.Bt.get(i);if(o)switch(o.windowStartMs=Math.min(o.windowStartMs,s.windowStartMs),o.type){case"count":o.total=((e=o.total)!==null&&e!==void 0?e:0)+((n=s.total)!==null&&n!==void 0?n:0);break;case"gauge":break;case"histogram":if(s.hist)if(o.hist){o.hist.count+=s.hist.count,o.hist.sum+=s.hist.sum,o.hist.min=Math.min(o.hist.min,s.hist.min),o.hist.max=Math.max(o.hist.max,s.hist.max);for(var a=0;o.hist.bucketCounts.length>a;a++)o.hist.bucketCounts[a]+=s.hist.bucketCounts[a]}else o.hist=s.hist}else this.Qt()&&this.Bt.set(i,s)}}};var Cr,dl,hs;function ep(t){var e=globalThis._posthogChunkIds;if(e){var n=Object.keys(e);return hs&&n.length===dl||(dl=n.length,hs=n.reduce(((r,i)=>{Cr||(Cr={});var s=Cr[i];if(s)r[s[0]]=s[1];else for(var o=t(i),a=o.length-1;a>=0;a--){var l=o[a],u=l?.filename,c=e[i];if(u&&c){r[u]=c,Cr[i]=[u,c];break}}return r}),{})),hs}}class tp{constructor(e,n,r){r===void 0&&(r=[]),this.coercers=e,this.stackParser=n,this.modifiers=r}buildFromUnknown(e,n){n===void 0&&(n={});var r=n&&n.mechanism||{handled:!0,type:"generic"},i=this.buildCoercingContext(r,n,0).apply(e),s=this.buildParsingContext(n),o=this.parseStacktrace(i,s);return{$exception_list:this.convertToExceptionList(o,r),$exception_level:"error"}}modifyFrames(e){var n=this;return X((function*(){for(var r of e)r.stacktrace&&r.stacktrace.frames&&L(r.stacktrace.frames)&&(r.stacktrace.frames=yield n.applyModifiers(r.stacktrace.frames));return e}))()}coerceFallback(e){var n;return{type:"Error",value:"Unknown error",stack:(n=e.syntheticException)==null?void 0:n.stack,synthetic:!0}}parseStacktrace(e,n){var r,i;return e.cause!=null&&(r=this.parseStacktrace(e.cause,n)),e.stack!=""&&e.stack!=null&&(i=this.applyChunkIds(this.stackParser(e.stack,e.synthetic?n.skipFirstLines:0),n.chunkIdMap)),E({},e,{cause:r,stack:i})}applyChunkIds(e,n){return e.map((r=>(r.filename&&n&&(r.chunk_id=n[r.filename]),r)))}applyCoercers(e,n){for(var r of this.coercers)if(r.match(e))return r.coerce(e,n);return this.coerceFallback(n)}applyModifiers(e){var n=this;return X((function*(){var r=e;for(var i of n.modifiers)r=yield i(r);return r}))()}convertToExceptionList(e,n){var r,i,s,o={type:e.type,value:e.value,mechanism:{type:(r=n.type)!==null&&r!==void 0?r:"generic",handled:(i=n.handled)===null||i===void 0||i,synthetic:(s=e.synthetic)!==null&&s!==void 0&&s}};e.stack&&(o.stacktrace={type:"raw",frames:e.stack});var a=[o];return e.cause!=null&&a.push(...this.convertToExceptionList(e.cause,E({},n,{handled:!0}))),a}buildParsingContext(e){var n;return{chunkIdMap:ep(this.stackParser),skipFirstLines:(n=e.skipFirstLines)!==null&&n!==void 0?n:1}}buildCoercingContext(e,n,r){r===void 0&&(r=0);var i=(s,o)=>{if(4>=o){var a=this.buildCoercingContext(e,n,o);return this.applyCoercers(s,a)}};return E({},n,{syntheticException:r==0?n.syntheticException:void 0,mechanism:e,apply:s=>i(s,r),next:s=>i(s,r+1)})}}var wn="?";function Xs(t,e,n,r,i){var s={platform:t,filename:e,function:n===""?wn:n,in_app:!0};return x(r)||(s.lineno=r),x(i)||(s.colno=i),s}var _u=(t,e)=>{var n=t.indexOf("safari-extension")!==-1,r=t.indexOf("safari-web-extension")!==-1;return n||r?[t.indexOf("@")!==-1?t.split("@")[0]:wn,n?"safari-extension:"+e:"safari-web-extension:"+e]:[t,e]},np=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,rp=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,ip=/\((\S*)(?::(\d+))(?::(\d+))\)/,sp=(t,e)=>{var n=np.exec(t);if(n)return Xs(e,n[1],wn,+n[2],+n[3]);var r=rp.exec(t);if(r){if(r[2]&&r[2].indexOf("eval")===0){var i=ip.exec(r[2]);i&&(r[2]=i[1],r[3]=i[2],r[4]=i[3])}var s=_u(r[1]||wn,r[2]);return Xs(e,s[1],s[0],r[3]?+r[3]:void 0,r[4]?+r[4]:void 0)}},op=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,ap=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,lp=(t,e)=>{var n=op.exec(t);if(n){if(n[3]&&n[3].indexOf(" > eval")>-1){var r=ap.exec(n[3]);r&&(n[1]=n[1]||"eval",n[3]=r[1],n[4]=r[2],n[5]="")}var i=n[3],s=n[1]||wn,o=_u(s,i);return Xs(e,i=o[1],s=o[0],n[4]?+n[4]:void 0,n[5]?+n[5]:void 0)}},hl=/\(error: (.*)\)/;class cp{match(e){return this.isDOMException(e)||this.isDOMError(e)}coerce(e,n){var r=W(e.stack);return{type:this.getType(e),value:this.getValue(e),stack:r?e.stack:void 0,cause:e.cause?n.next(e.cause):void 0,synthetic:!1}}getType(e){return this.isDOMError(e)?"DOMError":"DOMException"}getValue(e){var n=e.name||(this.isDOMError(e)?"DOMError":"DOMException");return e.message?n+": "+e.message:n}isDOMException(e){return ti(e,"DOMException")}isDOMError(e){return ti(e,"DOMError")}}class up{match(e){return(function(n){switch({}.toString.call(n)){case"[object Error]":case"[object Exception]":case"[object DOMException]":case"[object DOMError]":case"[object WebAssembly.Exception]":return!0;default:return Vc(n,Error)}})(e)}coerce(e,n){return{type:this.getType(e),value:this.getMessage(e,n),stack:this.getStack(e),cause:e.cause?n.next(e.cause):void 0,synthetic:!1}}getType(e){return e.name||e.constructor.name}getMessage(e,n){var r=e.message;return String(r.error&&typeof r.error.message=="string"?r.error.message:r)}getStack(e){return e.stacktrace||e.stack||void 0}}class dp{constructor(){}match(e){return!!ti(e,"ErrorEvent")&&(e.error!=null||this.fe(e))}coerce(e,n){var r;if(e.error!=null)return n.apply(e.error);var i=n.apply(e.message);return E({},i,{stack:(r=this.pe(e))!==null&&r!==void 0?r:i.stack,synthetic:!0})}fe(e){return W(e.message)&&e.message.length>0}pe(e){var n=e;if(W(n.filename)&&n.filename.length>0){var r,i,s=(r=n.lineno)!==null&&r!==void 0?r:0,o=(i=n.colno)!==null&&i!==void 0?i:0;return`Error - at `+n.filename+":"+s+":"+o}}}var hp=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;class pp{match(e){return typeof e=="string"}coerce(e,n){var r,i=this.getInfos(e),s=i[0],o=i[1];return{type:s??"Error",value:o??e,stack:(r=n.syntheticException)==null?void 0:r.stack,synthetic:!0}}getInfos(e){var n="Error",r=e,i=e.match(hp);return i&&(n=i[1],r=i[2]),[n,r]}}var fp=["fatal","error","warning","log","info","debug"];function yu(t,e){e===void 0&&(e=40);var n=Object.keys(t);if(n.sort(),!n.length)return"[object has no keys]";for(var r=n.length;r>0;r--){var i=n.slice(0,r).join(", ");if(e>=i.length)return r===n.length?i:i.length>e?i.slice(0,e)+"...":i}return""}class gp{match(e){return typeof e=="object"&&e!==null}coerce(e,n){var r,i,s=this.getErrorPropertyFromObject(e);return s?n.apply(s):{type:this.getType(e),value:this.getValue(e),stack:(r=this.getStack(e))!==null&&r!==void 0?r:(i=n.syntheticException)==null?void 0:i.stack,level:this.isSeverityLevel(e.level)?e.level:"error",synthetic:!0}}getType(e){return Yo(e)?e.constructor.name:"Error"}getValue(e){if("name"in e&&typeof e.name=="string"){var n="'"+e.name+"' captured as exception";return"message"in e&&typeof e.message=="string"&&(n+=" with message: '"+e.message+"'"),n}if("message"in e&&typeof e.message=="string")return e.message;var r=this.getObjectClassName(e);return(r&&r!=="Object"?"'"+r+"'":"Object")+" captured as exception with keys: "+yu(e)}isSeverityLevel(e){return W(e)&&!Gs(e)&&fp.indexOf(e)>=0}getStack(e){try{return W(e.stacktrace)&&e.stacktrace.length>0?e.stacktrace:W(e.stack)&&e.stack.length>0?e.stack:void 0}catch{return}}getErrorPropertyFromObject(e){for(var n in e)if({}.hasOwnProperty.call(e,n)){var r=e[n];if(Jh(r))return r}}getObjectClassName(e){try{var n=Object.getPrototypeOf(e);return n?n.constructor.name:void 0}catch{return}}}class mp{match(e){return Yo(e)}coerce(e,n){var r,i=e.constructor.name;return{type:i,value:i+" captured as exception with keys: "+yu(e),stack:(r=n.syntheticException)==null?void 0:r.stack,synthetic:!0}}}class vp{match(e){return qc(e)}coerce(e,n){var r;return{type:"Error",value:"Primitive value captured as exception: "+String(e),stack:(r=n.syntheticException)==null?void 0:r.stack,synthetic:!0}}}class _p{match(e){return ti(e,"PromiseRejectionEvent")||this.isCustomEventWrappingRejection(e)}isCustomEventWrappingRejection(e){if(!Yo(e))return!1;try{var n=e.detail;return n!=null&&typeof n=="object"&&"reason"in n}catch{return!1}}coerce(e,n){var r,i=this.getUnhandledRejectionReason(e);return qc(i)?{type:"UnhandledRejection",value:"Non-Error promise rejection captured with value: "+String(i),stack:(r=n.syntheticException)==null?void 0:r.stack,synthetic:!0}:n.apply(i)}getUnhandledRejectionReason(e){try{if("reason"in e)return e.reason;if("detail"in e&&e.detail!=null&&typeof e.detail=="object"&&"reason"in e.detail)return e.detail.reason}catch{}return e}}var ai="$message",li="$timestamp",yp=new Set([ai,li]),ps={enabled:!0,max_bytes:32768};function ci(t){var e;return t?{enabled:(e=t.enabled)!==null&&e!==void 0?e:ps.enabled,max_bytes:bp(t.max_bytes,ps.max_bytes)}:E({},ps)}class wp{constructor(e){this.Ke=[],this.Je=0,this.Ne=ci(e)}setConfig(e){this.Ne=ci(e),this.Xe()}add(e){var n=(function(i){var s;try{s=Hc(i)}catch{return}try{var o=JSON.parse(s);if(!te(o))return;var a=o,l=a[ai],u=a[li];return!W(l)||l.trim().length===0||!W(u)&&!he(u)?void 0:{step:a,json:s}}catch{return}})(e);if(n){var r=(function(i){if(typeof TextEncoder<"u")return new TextEncoder().encode(i).length;for(var s=encodeURIComponent(i),o=0,a=0;s.length>a;a++)s[a]==="%"?(o+=1,a+=2):o+=1;return o})(n.json);r>this.Ne.max_bytes||(this.Ke.push({step:n.step,bytes:r}),this.Je+=r,this.Xe())}}getAttachable(){return this.Ke.map((e=>e.step))}clear(){this.Ke=[],this.Je=0}size(){return this.Ke.length}Xe(){for(;this.Je>this.Ne.max_bytes&&this.Ke.length>0;){var e=this.Ke.shift();e&&(this.Je-=e.bytes)}}}function bp(t,e){if(!he(t)||t===1/0||t===-1/0)return e;var n=Math.floor(t);return 0>n?e:n}var wu=function(t,e){var n=(e===void 0?{}:e).debugEnabled,r={k(i){if(v&&(Y.DEBUG||v.POSTHOG_DEBUG||n)&&!x(v.console)&&v.console){for(var s=("__rrweb_original__"in v.console[i])?v.console[i].__rrweb_original__:v.console[i],o=arguments.length,a=new Array(o>1?o-1:0),l=1;o>l;l++)a[l-1]=arguments[l];s(t,...a)}},debug(){for(var i=arguments.length,s=new Array(i),o=0;i>o;o++)s[o]=arguments[o];r.k("debug",...s)},info(){for(var i=arguments.length,s=new Array(i),o=0;i>o;o++)s[o]=arguments[o];r.k("log",...s)},warn(){for(var i=arguments.length,s=new Array(i),o=0;i>o;o++)s[o]=arguments[o];r.k("warn",...s)},error(){for(var i=arguments.length,s=new Array(i),o=0;i>o;o++)s[o]=arguments[o];r.k("error",...s)},critical(){for(var i=arguments.length,s=new Array(i),o=0;i>o;o++)s[o]=arguments[o];console.error(t,...s)},uninitializedWarning(i){r.error("You must initialize PostHog before calling "+i)},createLogger:(i,s)=>wu(t+" "+i,s)};return r},k=wu("[PostHog.js]"),ne=k.createLogger,Ep=ne("[ExternalScriptsLoader]"),fs=(t,e,n)=>{if(t.config.disable_external_dependency_loading)return Ep.warn(e+" was requested but loading of external scripts is disabled."),n("Loading of external scripts is disabled");var r=C?.querySelectorAll("script");if(r){for(var i,s=function(){if(r[o].src===e){var l=r[o];return l.__posthog_loading_callback_fired?{v:n()}:(l.addEventListener("load",(u=>{l.__posthog_loading_callback_fired=!0,n(void 0,u)})),l.onerror=u=>n(u),{v:void 0})}},o=0;r.length>o;o++)if(i=s())return i.v}var a=()=>{if(!C)return n("document not found");var l=C.createElement("script");if(l.type="text/javascript",l.crossOrigin="anonymous",l.src=e,l.onload=d=>{l.__posthog_loading_callback_fired=!0,n(void 0,d)},l.onerror=d=>n(d),t.config.prepare_external_dependency_script&&(l=t.config.prepare_external_dependency_script(l)),!l)return n("prepare_external_dependency_script returned null");if(t.config.external_scripts_inject_target==="head")C.head.appendChild(l);else{var u,c=C.querySelectorAll("body > script");c.length>0?(u=c[0].parentNode)==null||u.insertBefore(l,c[0]):C.body.appendChild(l)}};C!=null&&C.body?a():C?.addEventListener("DOMContentLoaded",a)};$.__PosthogExtensions__=$.__PosthogExtensions__||{},$.__PosthogExtensions__.loadExternalDependency=(t,e,n)=>{if(e!=="remote-config"){var r;if(t.config.strict_script_versioning)r=t.requestRouter.endpointFor("assets","/static/"+t.version+"/"+e+".js");else{var i="/static/"+e+".js?v="+t.version;if(e==="toolbar"){var s=3e5;i=i+"&t="+Math.floor(Date.now()/s)*s}r=t.requestRouter.endpointFor("assets",i)}fs(t,r,n)}else{var o=t.requestRouter.endpointFor("assets","/array/"+t.config.token+"/config.js");fs(t,o,n)}},$.__PosthogExtensions__.loadSiteApp=(t,e,n)=>{var r=t.requestRouter.endpointFor("api",e);fs(t,r,n)};Y.DEBUG=!1,Y.LIB_VERSION="1.415.7",Y.LIB_NAME="web";var bu="$people_distinct_id",lr="$device_id",gs="$device_model",qn="__alias",Vn="__timers",Qs="$autocapture_disabled_server_side",eo="$heatmaps_enabled_server_side",to="$exception_capture_enabled_server_side",no="$error_tracking_suppression_rules",ro="$error_tracking_capture_extension_exceptions",io="$web_vitals_enabled_server_side",na="$dead_clicks_enabled_server_side",ra="$product_tours_enabled_server_side",so="$web_vitals_allowed_metrics",Yt="$session_recording_remote_config",Eu="$replay_sample_rate",Su="$replay_override_sampling",xu="$replay_override_linked_flag",ku="$replay_override_url_trigger",Iu="$replay_override_event_trigger",pn="$sesid",ia="$session_is_sampled",Wt="$enabled_feature_flags",Gn="$active_feature_flags",Ur="$early_access_features",oo="$feature_flag_details",Kn="$feature_flag_payloads",Hr="$feature_flag_request_id",ui="$minimal_flag_called_events",rt="$override_feature_flags",zt="$override_feature_flag_payloads",ht="$stored_person_properties",qt="$stored_group_properties",ao="$surveys",di="$surveys_loaded_at",lo="$surveys_activated",Wr="$surveys_activated_session",zr="$surveys_activated_timestamps",Jn="ph_product_tours",Gt="$flag_call_reported",Yn="$flag_call_reported_session_id",qr="$feature_flag_errors",Qn="$feature_flag_evaluated_at",He="$user_state",co="$client_session_props",uo="$capture_rate_limit",ho="$initial_campaign_params",po="$initial_referrer_info",hi="$initial_person_info",pi="$epp",Fr="$posthog_cookieless",Cu="$cookieless_mode",Fu="$sdk_debug_extensions_init_method",Au="$sdk_debug_extensions_init_time_ms",Pu="$sdk_debug_recording_script_not_loaded",sa="PostHog loadExternalDependency extension not found.",Vt="on_reject",gt="always",sn="anonymous",Ot="identified",fo="identified_only",fi="visibilitychange",gi="beforeunload",un="$pageview",ms="$pageleave",vs="$identify",pl="$groupidentify";function Ar(t,e){L(t)&&t.forEach(e)}function Z(t,e){if(!B(t))if(L(t))t.forEach(e);else if(Th(t))t.forEach(((r,i)=>e(r,i)));else for(var n in t)zc.call(t,n)&&e(t[n],n)}var ee=function(t){for(var e=arguments.length,n=new Array(e>1?e-1:0),r=1;e>r;r++)n[r-1]=arguments[r];for(var i of n)for(var s in i)i[s]!==void 0&&(t[s]=i[s]);return t};function Vr(t){for(var e=Object.keys(t),n=e.length,r=new Array(n);n--;)r[n]=[e[n],t[e[n]]];return r}var fl=function(t){try{return t()}catch{return}},Sp=function(t){return function(){try{for(var e=arguments.length,n=new Array(e),r=0;e>r;r++)n[r]=arguments[r];return t.apply(this,n)}catch(i){k.critical("Implementation error. Please turn on debug mode and open a ticket on https://app.posthog.com/home#panel=support%3Asupport%3A."),k.critical(i)}}},oa=function(t){var e={};return Z(t,(function(n,r){(W(n)&&n.length>0||he(n))&&(e[r]=n)})),e},xp=["herokuapp.com","vercel.app","netlify.app"];function kp(t){var e=t?.hostname;if(!W(e))return!1;var n=e.split(".").slice(-2).join(".");for(var r of xp)if(n===r)return!1;return!0}function ie(t,e,n,r){var i=r??{},s=i.capture,o=i.passive;t?.addEventListener(e,n,{capture:s!==void 0&&s,passive:o===void 0||o})}function go(t){return t.name==="ph_toolbar_internal"}var $u=t=>{if(C){try{for(var e=t+"=",n=C.cookie.split(";").filter((s=>s.length)),r=0;n.length>r;r++){for(var i=n[r];i.charAt(0)==" ";)i=i.substring(1,i.length);if(i.indexOf(e)===0)return decodeURIComponent(i.substring(e.length,i.length))}}catch{}return null}};Math.trunc||(Math.trunc=function(t){return 0>t?Math.ceil(t):Math.floor(t)}),Number.isInteger||(Number.isInteger=function(t){return he(t)&&isFinite(t)&&Math.floor(t)===t});class mi{constructor(e){if(this.bytes=e,e.length!==16)throw new TypeError("not 128-bit length")}static fromFieldsV7(e,n,r,i){if(!Number.isInteger(e)||!Number.isInteger(n)||!Number.isInteger(r)||!Number.isInteger(i)||0>e||0>n||0>r||0>i||e>0xffffffffffff||n>4095||r>1073741823||i>4294967295)throw new RangeError("invalid field value");var s=new Uint8Array(16);return s[0]=e/Math.pow(2,40),s[1]=e/Math.pow(2,32),s[2]=e/Math.pow(2,24),s[3]=e/Math.pow(2,16),s[4]=e/256,s[5]=e,s[6]=112|n>>>8,s[7]=n,s[8]=128|r>>>24,s[9]=r>>>16,s[10]=r>>>8,s[11]=r,s[12]=i>>>24,s[13]=i>>>16,s[14]=i>>>8,s[15]=i,new mi(s)}toString(){for(var e="",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 mi(this.bytes.slice(0))}equals(e){return this.compareTo(e)===0}compareTo(e){for(var n=0;16>n;n++){var r=this.bytes[n]-e.bytes[n];if(r!==0)return Math.sign(r)}return 0}}class Ip{generate(){var e=this.generateOrAbort();if(!x(e))return e;this.S=0;var n=this.generateOrAbort();if(x(n))throw new Error("Could not generate UUID after timestamp reset");return n}generateOrAbort(){var e=Date.now();if(e>this.S)this.S=e,this.C();else{if(this.S>=e+1e4)return;this.I++,this.I>4398046511103&&(this.S++,this.C())}return mi.fromFieldsV7(this.S,Math.trunc(this.I/Math.pow(2,30)),this.I&Math.pow(2,30)-1,this.A.nextUint32())}C(){this.I=1024*this.A.nextUint32()+(1023&this.A.nextUint32())}constructor(){this.S=0,this.I=0,this.A=new Cp}}var gl,Ru=t=>{if(typeof UUIDV7_DENY_WEAK_RNG<"u"&&UUIDV7_DENY_WEAK_RNG)throw new Error("no cryptographically strong RNG available");for(var e=0;t.length>e;e++)t[e]=65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random());return t};v&&!x(v.crypto)&&crypto.getRandomValues&&(Ru=t=>crypto.getRandomValues(t));class Cp{nextUint32(){return this.R.length>this.O||(Ru(this.R),this.O=0),this.R[this.O++]}constructor(){this.R=new Uint32Array(8),this.O=1/0}}var ft=()=>Fp().toString(),Fp=()=>(gl||(gl=new Ip)).generate(),Nn="",Ap=/[a-z0-9][a-z0-9-]+\.[a-z]{2,}$/i,mt={N:()=>!!C,j(t){k.error("cookieStore error: "+t)},P:$u,H(t){var e;try{e=JSON.parse(mt.P(t))||{}}catch{}return e},F(t,e,n,r,i){if(!C)return!1;try{var s="",o="",a=(function(c,d){if(d){var h=(function(f,g){if(g===void 0&&(g=C),Nn)return Nn;if(!g||["localhost","127.0.0.1"].includes(f))return"";for(var m=f.split("."),_=Math.min(m.length,8),w="dmn_chk_"+ft();!Nn&&_--;){var b=m.slice(_).join("."),I=w+"=1;domain=."+b+";path=/";g.cookie=I+";max-age=3",g.cookie.includes(w)&&(g.cookie=I+";max-age=0",Nn=b)}return Nn})(c);if(!h){var p=(f=>{var g=f.match(Ap);return g?g[0]:""})(c);p!==h&&k.info("Warning: cookie subdomain discovery mismatch",p,h),h=p}return h?"; domain=."+h:""}return""})(C.location.hostname,r);if(n){var l=new Date;l.setTime(l.getTime()+864e5*n),s="; expires="+l.toUTCString()}i&&(o="; secure");var u=t+"="+encodeURIComponent(JSON.stringify(e))+s+"; SameSite=Lax; path=/"+a+o;return u.length>3686.4&&k.warn("cookieStore warning: large cookie, len="+u.length),C.cookie=u,!0}catch{return!1}},q(t,e){if(C!=null&&C.cookie)try{mt.F(t,"",-1,e)}catch{return}}},_s=null,Q={N(){if(!$e(_s))return _s;var t=!0;if(x(v))t=!1;else try{var e="__mplssupport__";Q.F(e,"xyz"),Q.P(e)!=='"xyz"'&&(t=!1),Q.q(e)}catch{t=!1}return t||k.error("localStorage unsupported; falling back to cookie store"),_s=t,t},j(t){k.error("localStorage error: "+t)},P(t){try{return v?.localStorage.getItem(t)}catch(e){Q.j(e)}return null},H(t){try{return JSON.parse(Q.P(t))||{}}catch{}return null},F(t,e){try{return v?.localStorage.setItem(t,JSON.stringify(e)),!0}catch(n){Q.j(n)}return!1},q(t){try{v?.localStorage.removeItem(t)}catch(e){Q.j(e)}}},Pp=[lr,"distinct_id",pn,ia,pi,hi,He],Pr={},$p={N:()=>!0,j(t){k.error("memoryStorage error: "+t)},P:t=>Pr[t]||null,H:t=>Pr[t]||null,F:(t,e)=>(Pr[t]=e,!0),q(t){delete Pr[t]}},Bt=null,ce={N(){if(!$e(Bt))return Bt;if(Bt=!0,x(v))Bt=!1;else try{var t="__support__";ce.F(t,"xyz"),ce.P(t)!=='"xyz"'&&(Bt=!1),ce.q(t)}catch{Bt=!1}return Bt},j(t){k.error("sessionStorage error: ",t)},P(t){try{return v?.sessionStorage.getItem(t)}catch(e){ce.j(e)}return null},H(t){try{return JSON.parse(ce.P(t))||null}catch{}return null},F(t,e){try{return v?.sessionStorage.setItem(t,JSON.stringify(e)),!0}catch(n){ce.j(n)}return!1},q(t){try{v?.sessionStorage.removeItem(t)}catch(e){ce.j(e)}}};class Rp{constructor(e){this._instance=e}get Ne(){return this._instance.config}get consent(){return this.ti()?0:this.ei}isOptedOut(){return this.Ne.cookieless_mode===gt||this.isRejected()||this.consent===-1&&this.Ne.cookieless_mode===Vt}isOptedIn(){return!this.isOptedOut()}isExplicitlyOptedOut(){return this.consent===0}isRejected(){return this.consent===0||this.consent===-1&&this.Ne.opt_out_capturing_by_default}optInOut(e){this.ii.F(this.ri,e?1:0,this.Ne.cookie_expiration,this.Ne.cross_subdomain_cookie,this.Ne.secure_cookie)}reset(){this.ii.q(this.ri,this.Ne.cross_subdomain_cookie)}get ri(){var e=this._instance.config,n=e.token,r=e.opt_out_capturing_cookie_prefix;return e.consent_persistence_name||(r?r+n:"__ph_opt_in_out_"+n)}get ei(){var e=this.ii.P(this.ri);return cs(e)?1:N(Oh,e)?0:-1}get ii(){var e=this.Ne.opt_out_capturing_persistence_type,n=e==="localStorage"?Q:mt;if(!this.ni||this.ni!==n){this.ni=n;var r=e==="localStorage"?mt:Q;r.P(this.ri)&&(this.ni.P(this.ri)||this.optInOut(cs(r.P(this.ri))),r.q(this.ri,this.Ne.cross_subdomain_cookie))}return this.ni}ti(){return!!this.Ne.respect_dnt&&[ke?.doNotTrack,ke?.msDoNotTrack,$.doNotTrack].some((e=>cs(e)))}}function Tu(t,e){var n,r=t==null||(n=t.config)==null?void 0:n.get_current_url;if(!Se(r))return e;try{var i=r(e);return W(i)&&i?i:e}catch(s){return k.error("Error in get_current_url, falling back to window.location.href",s),e}}var Mu="__POSTHOG_TOOLBAR__",Tp=1,Mp=3,Np=11;function ml(t){return t instanceof Element&&(t.id===Mu||!(t.closest==null||!t.closest(".toolbar-global-fade-container")))}function $t(t){return!!t&&t.nodeType===Tp}function Ne(t,e){return!!t&&!!t.tagName&&t.tagName.toLowerCase()===e.toLowerCase()}function Nu(t){return!!t&&t.nodeType===Mp}function Lu(t){return!!t&&t.nodeType===Np&&$t(t.host)}var Ou=1e3;function aa(t){return t?Bi(t).split(/\s+/):[]}function vl(t,e){var n=(function(r){var i,s=v==null||(i=v.location)==null?void 0:i.href;return x(s)?void 0:Tu(r,s)})(e);return!!(n&&t&&t.some((r=>n.match(r))))}function vi(t){var 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 aa(e)}function Bu(t){return B(t)?null:Bi(t).split(/(\s+)/).filter((e=>er(e))).join("").replace(/[\r\n]/g," ").replace(/[ ]+/g," ").substring(0,255)}function cr(t){var e="";return vo(t)&&!Hu(t)&&t.childNodes&&t.childNodes.length&&Z(t.childNodes,(function(n){var r;Nu(n)&&n.textContent&&(e+=(r=Bu(n.textContent))!==null&&r!==void 0?r:"")})),Bi(e)}function ys(t){var e;return x(t.target)?t.srcElement||null:(e=t.target)!=null&&e.shadowRoot?t.composedPath()[0]||null:t.target||null}var la=["a","button","form","input","select","textarea","label"];function mo(t,e){if(x(e))return!0;var n,r=function(s){if(e.some((o=>(function(a,l){var u=a.matches||a.matchesSelector||a.msMatchesSelector||a.mozMatchesSelector||a.webkitMatchesSelector||a.oMatchesSelector;try{return!!u&&u.call(a,l)}catch{return!1}})(s,o))))return{v:!0}};for(var i of t)if(n=r(i))return n.v;return!1}function Du(t){var e=t.parentNode;return!(!e||!$t(e))&&e}var Lp=[".ph-no-autocapture","[data-ph-no-autocapture]"],ju=["next","previous","prev",">","<"],Op=[...ju,"+","-","−","–"],_l=(t,e)=>/[a-z0-9]/i.test(e)?t.includes(e):t===e,yl=[".ph-no-rageclick",".ph-no-capture"],Bp=["","text","search","email","password","url","tel","number"];function wl(t,e){if(!v||ca(t))return!1;var n,r,i,s,o;if(Ye(e)?(n=!!e&&yl,r=void 0,i=!1):(n=(s=e?.css_selector_ignorelist)!==null&&s!==void 0?s:yl,r=e?.content_ignorelist,i=(o=e?.ignore_text_selection)!==null&&o!==void 0&&o),n===!1||i&&(function(l){return!(!l||!$t(l))&&(!!Ne(l,"textarea")||(Ne(l,"input")?N(Bp,(l.getAttribute("type")||"").toLowerCase()):(function(u){if(u.isContentEditable)return!0;var c=u.getAttribute==null?void 0:u.getAttribute("contenteditable");return c==="true"||c===""})(l)))})(t))return!1;var a=Uu(t,!1).targetElementList;return!(function(l,u){if(l===!1||x(l))return!1;var c;if(l===!0)c=ju;else{if(!L(l))return!1;if(l.length>10)return k.error("[PostHog] content_ignorelist array cannot exceed 10 items. Use css_selector_ignorelist for more complex matching."),!1;c=l.map((d=>d.toLowerCase()))}return u.some((d=>{var h=d.safeText,p=d.ariaLabel;return c.some((f=>_l(h,f)||_l(p,f)))}))})(r,a.map((l=>{var u;return{safeText:cr(l).toLowerCase(),ariaLabel:((u=l.getAttribute("aria-label"))==null?void 0:u.toLowerCase().trim())||""}})))&&!mo(a,n)}var ca=t=>!t||Ne(t,"html")||!$t(t),Uu=(t,e)=>{if(!v||ca(t))return{parentIsUsefulElement:!1,targetElementList:[]};for(var n=!1,r=[t],i=t;i.parentNode&&!Ne(i,"body");)if(Lu(i.parentNode))r.push(i.parentNode.host),i=i.parentNode.host;else{var s=Du(i);if(!s)break;if(e||la.indexOf(s.tagName.toLowerCase())>-1)n=!0;else try{var o=v.getComputedStyle(s);o&&o.getPropertyValue("cursor")==="pointer"&&(n=!0)}catch{}r.push(s),i=s}return{parentIsUsefulElement:n,targetElementList:r}};function vo(t){for(var e=new Set,n=0,r=t;r.parentNode&&!Ne(r,"body");r=r.parentNode){if(n++>=Ou||e.has(r))return!1;e.add(r);var i=vi(r);if(N(i,"ph-sensitive")||N(i,"ph-no-capture"))return!1}if(N(vi(t),"ph-include"))return!0;var s=t.type||"";if(W(s))switch(s.toLowerCase()){case"hidden":case"password":return!1}var o=t.name||t.id||"";return!W(o)||!/^cc|cardnum|ccnum|creditcard|csc|cvc|cvv|exp|pass|pwd|routing|seccode|securitycode|securitynum|socialsec|socsec|ssn/i.test(o.replace(/[^a-zA-Z0-9]/g,""))}function Hu(t){return!!(Ne(t,"input")&&!["button","checkbox","submit","reset"].includes(t.type)||Ne(t,"select")||Ne(t,"textarea")||t.getAttribute("contenteditable")==="true")}var bl=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}))$"),El=/(^|[^0-9A-Za-z_])([0-9][0-9 -]*[0-9])(?=$|[^0-9A-Za-z_])/g,Dp=[16,15,14,13],jp=new RegExp("^(\\d{3}-?\\d{2}-?\\d{4})$"),Sl=new RegExp("(^|[^0-9])((?!000|666)[0-9]{3}-?(?!00)[0-9]{2}-?(?!0000)[0-9]{4})(?=$|([^0-9]))","g"),xl=/[0-9A-Za-z_]/;function Up(t){for(var e=0,n=!1,r=t.length-1;r>=0;r--){var i=t.charCodeAt(r)-48;n&&(i*=2)>9&&(i-=9),e+=i,n=!n}return e%10==0}function er(t,e){if(e===void 0&&(e=!0),B(t))return!1;if(W(t)){t=Bi(t);var n=e?bl.test((t||"").replace(/[- ]/g,"")):(function(i){var s;for(El.lastIndex=0;s=El.exec(i);){var o=s[2];if(o)for(var a=o.replace(/[- ]/g,""),l=0;a.length>l;l++)for(var u of Dp){var c=l+u;if(a.length>=c){var d=a.slice(l,c);if(bl.test(d)&&Up(d))return!0}}}return!1})(t);if(n)return!1;var r=e?jp.test(t):(function(i){var s;for(Sl.lastIndex=0;s=Sl.exec(i);){var o=s[1],a=s[3];if(!(o&&a&&xl.test(o)&&xl.test(a)))return!0}return!1})(t);if(r)return!1}return!0}function kl(t){var e=cr(t);return er(e=(e+" "+Wu(t)).trim())?e:""}function Wu(t){var e="";return t&&t.childNodes&&t.childNodes.length&&Z(t.childNodes,(function(n){var r;if(n&&((r=n.tagName)==null?void 0:r.toLowerCase())==="span")try{var i=cr(n);e=(e+" "+i).trim(),n.childNodes&&n.childNodes.length&&(e=(e+" "+Wu(n)).trim())}catch(s){k.error("[AutoCapture]",s)}})),e}function Il(t){return t.replace(/"|\\"/g,'\\"')}function Hp(t){var e=t.attr__class;if(e)return L(e)?e:aa(e)}var $r=ne("[Dead Clicks]"),Wp=()=>!0,zp=t=>{var e,n=!((e=t.instance.persistence)==null||!e.get_property(na)),r=t.instance.config.capture_dead_clicks;return Ye(r)?r:!!te(r)||n};class Cl{get lazyLoadedDeadClicksAutocapture(){return this.si}constructor(e,n,r){this.instance=e,this.isEnabled=n,this.onCapture=r,this.startIfEnabledOrStop()}onRemoteConfig(e){if(e.ok){var n=e.config;"captureDeadClicks"in n&&(this.instance.persistence&&this.instance.persistence.register({[na]:n.captureDeadClicks}),this.startIfEnabledOrStop())}}startIfEnabledOrStop(){this.isEnabled(this)?this.ai((()=>{this.oi()})):this.stop()}ai(e){var n,r;(n=$.__PosthogExtensions__)!=null&&n.initDeadClicksAutocapture?e():(r=$.__PosthogExtensions__)==null||r.loadExternalDependency==null||r.loadExternalDependency(this.instance,"dead-clicks-autocapture",(i=>{i?$r.error("failed to load script",i):e()}))}oi(){var e;if(C){if(!this.si&&(e=$.__PosthogExtensions__)!=null&&e.initDeadClicksAutocapture){var n=te(this.instance.config.capture_dead_clicks)?E({},this.instance.config.capture_dead_clicks):{};n.__onCapture=this.onCapture,this.onCapture&&(n.capture_dead_swipes=!1),this.si=$.__PosthogExtensions__.initDeadClicksAutocapture(this.instance,n),this.si.start(C),$r.info("starting...")}}else $r.error("`document` not found. Cannot start.")}stop(){this.si&&(this.si.stop(),this.si=void 0,$r.info("stopping..."))}}var ws=ne("[SegmentIntegration]"),zu="posthog-js";function qu(t,e){var n=e===void 0?{}:e,r=n.organization,i=n.projectId,s=n.prefix,o=n.severityAllowList,a=o===void 0?["error"]:o,l=n.sendExceptionsToPostHog,u=l===void 0||l;return c=>{var d,h,p,f,g;if(a!=="*"&&!a.includes(c.level)||!t.__loaded)return c;c.tags||(c.tags={});var m=t.requestRouter.endpointFor("ui","/project/"+t.config.token+"/person/"+t.get_distinct_id());c.tags["PostHog Person URL"]=m,t.sessionRecordingStarted()&&(c.tags["PostHog Recording URL"]=t.get_session_replay_url({withTimestamp:!0}));var _,w=((d=c.exception)==null?void 0:d.values)||[],b=w.map((F=>E({},F,{stacktrace:F.stacktrace?E({},F.stacktrace,{type:"raw",frames:(F.stacktrace.frames||[]).map((A=>E({},A,{platform:"web:javascript"})))}):void 0}))),I={$exception_message:((h=w[0])==null?void 0:h.value)||c.message,$exception_type:(p=w[0])==null?void 0:p.type,$exception_level:c.level,$exception_list:b,$sentry_event_id:c.event_id,$sentry_exception:c.exception,$sentry_exception_message:((f=w[0])==null?void 0:f.value)||c.message,$sentry_exception_type:(g=w[0])==null?void 0:g.type,$sentry_tags:c.tags};return r&&i&&(I.$sentry_url=(s||"https://sentry.io/organizations/")+r+"/issues/?project="+i+"&query="+c.event_id),u&&((_=t.exceptions)==null||_.sendExceptionEvent(I)),c}}class qp{constructor(e,n,r,i,s,o){this.name=zu,this.setupOnce=function(a){a(qu(e,{organization:n,projectId:r,prefix:i,severityAllowList:s,sendExceptionsToPostHog:o==null||o}))}}}class Fl{constructor(e){this.li=(n,r,i)=>{i&&(i.noSessionId||i.activityTimeout||i.sessionPastMaximumLength||i.crossTabAdoption)&&(k.info("[PageViewManager] Session rotated, clearing pageview state",{sessionId:n,changeReason:i}),this.ui=void 0,this._instance.scrollManager.resetContext())},this._instance=e,this.hi()}hi(){var e;this.di=(e=this._instance.sessionManager)==null?void 0:e.onSessionId(this.li)}destroy(){var e;(e=this.di)==null||e.call(this),this.di=void 0}doPageView(e,n){var r,i=this.vi(e,n);return this.ui={pathname:(r=v?.location.pathname)!==null&&r!==void 0?r:"",pageViewId:n,timestamp:e},this._instance.scrollManager.resetContext(),i}doPageLeave(e){var n;return this.vi(e,(n=this.ui)==null?void 0:n.pageViewId)}doEvent(){var e;return{$pageview_id:(e=this.ui)==null?void 0:e.pageViewId}}vi(e,n){var r=this.ui;if(!r)return{$pageview_id:n};var i={$pageview_id:n,$prev_pageview_id:r.pageViewId},s=this._instance.scrollManager.getContext();if(s&&!this._instance.config.disable_scroll_properties){var o=s.maxScrollHeight,a=s.lastScrollY,l=s.maxScrollY,u=s.maxContentHeight,c=s.lastContentY,d=s.maxContentY;if(!(x(o)||x(a)||x(l)||x(u)||x(c)||x(d))){o=Math.ceil(o),a=Math.ceil(a),l=Math.ceil(l),u=Math.ceil(u),c=Math.ceil(c),d=Math.ceil(d);var h=o>1?ot(a/o,0,1,k):1,p=o>1?ot(l/o,0,1,k):1,f=u>1?ot(c/u,0,1,k):1,g=u>1?ot(d/u,0,1,k):1;i=ee(i,{$prev_pageview_last_scroll:a,$prev_pageview_last_scroll_percentage:h,$prev_pageview_max_scroll:l,$prev_pageview_max_scroll_percentage:p,$prev_pageview_last_content:c,$prev_pageview_last_content_percentage:f,$prev_pageview_max_content:d,$prev_pageview_max_content_percentage:g})}}return r.pathname&&(i.$prev_pageview_pathname=r.pathname),r.timestamp&&(i.$prev_pageview_duration=(e.getTime()-r.timestamp.getTime())/1e3),i}}var bs=["flags","surveys"],Vp={[bu]:{exposure:"hidden"},[qn]:{exposure:"hidden"},__cmpns:{exposure:"hidden"},[Vn]:{exposure:"hidden"},[Qs]:{exposure:"event"},[eo]:{exposure:"hidden"},[to]:{exposure:"event"},[no]:{exposure:"hidden"},[ro]:{exposure:"event"},[io]:{exposure:"event"},[na]:{exposure:"event"},[ra]:{exposure:"hidden"},[so]:{exposure:"event"},[Yt]:{exposure:"hidden"},$session_recording_enabled_server_side:{exposure:"hidden"},[pn]:{exposure:"hidden"},[ia]:{exposure:"event"},[Eu]:{exposure:"event",shouldSkipFromEventProperties:t=>$e(t)},$session_past_minimum_duration:{exposure:"event"},$session_recording_url_trigger_activated_session:{exposure:"event"},$session_recording_event_trigger_activated_session:{exposure:"event"},$debug_first_full_snapshot_timestamp:{exposure:"event"},$sess_rec_flush_size:{exposure:"hidden"},[Wt]:{exposure:"hidden",storageGroup:"flags"},[Gn]:{exposure:"hidden",storageGroup:"flags"},[Ur]:{exposure:"hidden"},[oo]:{exposure:"hidden",storageGroup:"flags"},[Kn]:{exposure:"hidden",storageGroup:"flags"},[Hr]:{exposure:"hidden",storageGroup:"flags",volatile:!0},[ui]:{exposure:"hidden",storageGroup:"flags"},[rt]:{exposure:"hidden"},[zt]:{exposure:"hidden"},[ht]:{exposure:"hidden"},[qt]:{exposure:"hidden"},[ao]:{exposure:"hidden",storageGroup:"surveys"},[di]:{exposure:"hidden",storageGroup:"surveys",volatile:!0},[lo]:{exposure:"event"},[Wr]:{exposure:"hidden"},[zr]:{exposure:"hidden"},[Jn]:{exposure:"hidden"},$product_tours_activated:{exposure:"hidden"},$product_tours_activated_session:{exposure:"hidden"},$conversations_widget_session_id:{exposure:"event"},$conversations_ticket_id:{exposure:"event"},$conversations_widget_state:{exposure:"event"},$conversations_user_traits:{exposure:"event"},[Gt]:{exposure:"hidden"},[Yn]:{exposure:"hidden"},[qr]:{exposure:"hidden"},[Qn]:{exposure:"hidden",storageGroup:"flags",volatile:!0},[He]:{exposure:"hidden"},[co]:{exposure:"hidden"},[uo]:{exposure:"hidden"},[ho]:{exposure:"hidden"},[po]:{exposure:"hidden"},[hi]:{exposure:"hidden"},[pi]:{exposure:"hidden"},[Su]:{exposure:"event"},[xu]:{exposure:"event"},[ku]:{exposure:"event"},[Iu]:{exposure:"event"},[Fu]:{exposure:"event"},[Au]:{exposure:"event"},[Pu]:{exposure:"event"},$sdk_debug_replay_event_trigger_status:{exposure:"event"},$sdk_debug_replay_linked_flag_trigger_status:{exposure:"event"},$sdk_debug_replay_matched_recording_trigger_groups:{exposure:"event"},$sdk_debug_replay_remote_trigger_matching_config:{exposure:"event"},$sdk_debug_replay_trigger_groups_count:{exposure:"event"},$sdk_debug_replay_url_trigger_status:{exposure:"event"},$session_recording_start_reason:{exposure:"event"}},Gp=[["$posthog_sr_group_event_trigger_",{exposure:"hidden"}],["$posthog_sr_group_url_trigger_",{exposure:"hidden"}],["$posthog_sr_group_sampling_",{exposure:"hidden"}]],Dt=t=>{var e=Vp[t];if(e)return e;for(var n of Gp){var r=n[1];if(t.indexOf(n[0])===0)return r}},fn=(t,e)=>{try{return JSON.stringify(t,((n,r)=>typeof r=="bigint"?r.toString():r),e)}catch{return Hc(t)}},_i=t=>{var e=C?.createElement("a");return x(e)?null:(e.href=t,e)},bn=function(t,e){for(var n,r=((t.split("#")[0]||"").split(/\?(.*)/)[1]||"").replace(/^\?+/g,"").split("&"),i=0;r.length>i;i++){var s=r[i].split("=");if(s[0]===e){n=s;break}}if(!L(n)||2>n.length)return"";var o=n[1];try{o=decodeURIComponent(o)}catch{k.error("Skipping decoding for malformed query param: "+o)}return o.replace(/\+/g," ")},ur=function(t,e,n){if(!t||!e||!e.length)return t;for(var r=t.split("#"),i=r[1],s=(r[0]||"").split("?"),o=s[1],a=s[0],l=(o||"").split("&"),u=[],c=0;l.length>c;c++){var d=l[c].split("=");L(d)&&(e.includes(d[0])?u.push(d[0]+"="+n):u.push(l[c]))}var h=a;return o!=null&&(h+="?"+u.join("&")),i!=null&&(h+="#"+i),h},yi=function(t,e){var n=t.match(new RegExp(e+"=([^&]*)"));return n?n[1]:null},Vu=(t,e)=>t>=e&&Dc(),Gu=(t,e,n,r)=>{if(t===0){if(Dc()){var i=e+1;return i===n&&r(),i}return e}return 0},Rr="https?://(.*)",En=["gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","irclid","_kx"],Kp=["utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid",...En],dr="",Jp=["li_fat_id"];function Ku(t,e,n){if(!C)return{};var r,i=e?[...En,...n||[]]:[],s=Ju(ur(C.URL,i,dr),t),o=(r={},Z(Jp,(function(a){var l=$u(a);r[a]=l||null})),r);return ee(o,s)}function Ju(t,e){var n=Kp.concat(e||[]),r={};return Z(n,(function(i){var s=bn(t,i);r[i]=s||null})),r}function Yu(t){var e=(function(s){return s?s.search(Rr+"google.([^/?]*)")===0?"google":s.search(Rr+"bing.com")===0?"bing":s.search(Rr+"yahoo.com")===0?"yahoo":s.search(Rr+"duckduckgo.com")===0?"duckduckgo":null:null})(t),n=e!="yahoo"?"q":"p",r={};if(!$e(e)){r.$search_engine=e;var i=C?bn(C.referrer,n):"";i.length&&(r.ph_keyword=i)}return r}function Al(){return navigator.language||navigator.userLanguage}var wi="$direct";function Zu(){return C?.referrer||wi}function Xu(t,e,n){n===void 0&&(n=!1);var r=t?[...En,...e||[]]:[],i=n?Pt(re?.href):re?.href,s=i?.substring(0,1e3);return{r:Zu().substring(0,1e3),u:s?ur(s,r,dr):void 0}}function Qu(t,e){var n;e===void 0&&(e=!1);var r=t.r,i=t.u,s=e?Pt(i):i,o={$referrer:r,$referring_domain:r==null?void 0:r==wi?wi:(n=_i(r))==null?void 0:n.host};if(s){o.$current_url=s;var a=_i(s);o.$host=a?.host,o.$pathname=a?.pathname;var l=Ju(s);ee(o,l)}if(r){var u=Yu(r);ee(o,u)}return o}function ed(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return}}function Yp(){try{return new Date().getTimezoneOffset()}catch{return}}var Zp={flags:Qn,surveys:di},Xp=["cookie","localstorage","localstorage+cookie","sessionstorage","memory"],on="main";class Es{constructor(e,n,r){if(r===void 0&&(r=!0),this.ci={},this.fi=!1,this.pi=!1,this.Ne=e,this.gi=r,this.props={},this.mi=void 0,this.yi=(s=>{var o="";return s.token&&(o=s.token.replace(/\+/g,"PL").replace(/\//g,"SL").replace(/=/g,"EQ")),s.persistence_name?"ph_"+s.persistence_name:"ph_"+o+"_posthog"})(e),this.ii=this.bi(e),this.pi=this.wi(e),this.load(),e.debug&&k.info("Persistence loaded",e.persistence,E({},this.props)),this.update_config(e,e,n),this.save(),v){var i=()=>this.flush();ie(v,"beforeunload",i,{capture:!1}),ie(v,"pagehide",i,{capture:!1})}}ki(){var e,n=(e=this.Ne)==null?void 0:e.persistence_save_debounce_ms;return he(n)&&n>0?n:0}isDisabled(){return!!this.xi}bi(e){Xp.indexOf(e.persistence.toLowerCase())===-1&&(k.critical("Unknown persistence type "+e.persistence+"; falling back to localStorage+cookie"),e.persistence="localStorage+cookie");var n,r=(function(o,a){o===void 0&&(o=[]),a===void 0&&(a=!1);var l=[...Pp,...o];return E({},Q,{H(u){try{var c={};try{c=mt.H(u)||{}}catch{}var d,h=JSON.parse(Q.P(u)||"{}");if(a){var p={};for(var f in c){var g=c[f];$e(g)||g===""||(p[f]=g)}d=ee(h,p)}else d=ee(c,h);return Q.F(u,d),d}catch{}return null},F(u,c,d,h,p,f){var g=Q.F(u,c,void 0,void 0,f);try{var m={};l.forEach((_=>{c[_]&&(m[_]=c[_])})),Object.keys(m).length&&mt.F(u,m,d,h,p,f)}catch(_){Q.j(_)}return g},q(u,c){try{v?.localStorage.removeItem(u),mt.q(u,c)}catch(d){Q.j(d)}}})})(e.cookie_persisted_properties||[],e.__preview_cookie_wins_on_conflict||!1),i=!1,s=e.persistence.toLowerCase();return s==="localstorage"&&Q.N()?(n=Q,i=!0):s==="localstorage+cookie"&&r.N()?(n=r,i=!0):s==="sessionstorage"&&ce.N()?n=ce:s==="memory"?n=$p:s==="cookie"?n=mt:r.N()?(n=r,i=!0):n=mt,this.fi=i,n}Si(e){return this.yi+"__"+e}wi(e){return this.fi&&!!e.split_storage}properties(){var e={};return Z(this.props,((n,r)=>{var i=Dt(r);if(!i||i.exposure==="event"){if(i!=null&&i.shouldSkipFromEventProperties!=null&&i.shouldSkipFromEventProperties(n))return;e[r]=n}})),e}load(){if(!this.xi){var e=this.ii.H(this.yi);e&&(this.props=ee({},e)),this.pi&&this.Ci()}}Ci(){for(var e of bs){var n=Q.H(this.Si(e));if(n&&!yt(n)){var r=this.Mi(e);r.persisted=!0,this.Ti(e)||(r.fingerprint=this.Ei(n,e)),this.Ii(e,n)||ee(this.props,n)}}}Ti(e){return Object.keys(this.props).some((n=>{var r;return((r=Dt(n))==null?void 0:r.storageGroup)===e}))}Ii(e,n){var r=Zp[e];if(!r)return!1;var i=n[r],s=this.props[r];return he(i)&&he(s)&&s>i}refreshKey(e){var n;if(!this.xi){var r=this.pi?(n=Dt(e))==null?void 0:n.storageGroup:void 0,i=r?Q.H(this.Si(r)):this.ii.H(this.yi);if(i&&e in i)this.Pi(e,i[e]);else{if(r){var s=this.ii.H(this.yi);if(s&&e in s)return void this.Pi(e,s[e])}this.Ri(e)}}}save(){if(!this.xi){var e=this.ki();e>0?x(this.Ai)&&(this.Ai=setTimeout((()=>{this.Ai=void 0,this.Fi()}),e)):this.Fi()}}flush(){x(this.Ai)||(clearTimeout(this.Ai),this.Ai=void 0,this.Fi())}Fi(){this.xi||(this.pi?this.Li():this.Oi(this.ii,this.yi,this.props,on))}Li(){var e=this.Di(),n=e.main,r=e.groups;for(var i of(this.Oi(this.ii,this.yi,n,on),bs)){var s,o=r[i];(!yt(o)||(s=this.ci[i])!=null&&s.persisted)&&this.Oi(Q,this.Si(i),o,i)}}Di(){var e={},n={flags:{},surveys:{}};return Z(this.props,((r,i)=>{var s,o=(s=Dt(i))==null?void 0:s.storageGroup;o?n[o][i]=r:e[i]=r})),{main:e,groups:n}}Ei(e,n){if(n===on)return JSON.stringify(e)+"|"+this.$i+"|"+this.Ni+"|"+this.qi;var r={};return Z(e,((i,s)=>{var o;r[s]=(o=Dt(s))!=null&&o.volatile?"__volatile__":i})),JSON.stringify(r)}Oi(e,n,r,i){var s=this.Mi(i);if(i===on||s.dirty||x(s.fingerprint)){var o;try{if((o=this.Ei(r,i))===s.fingerprint)return void(s.dirty=!1)}catch{o=void 0}e.F(n,r,this.$i,this.Ni,this.qi,this.Ne.debug)?(s.dirty=!1,i!==on&&(s.persisted=!0),x(o)||(s.fingerprint=o)):this.Ne.debug&&k.warn('failed to persist storage entry "'+n+'"; will retry on next save')}}remove(e){var n=(e===void 0?{}:e).keepGroupEntries,r=n!==void 0&&n;if(x(this.Ai)||(clearTimeout(this.Ai),this.Ai=void 0),this.ii.q(this.yi,!1),this.ii.q(this.yi,!0),!r&&this.gi)for(var i of bs)Q.q(this.Si(i));r?delete this.ci[on]:this.ci={}}clear(){this.remove(),this.props={}}register_once(e,n,r){if(te(e)){x(n)&&(n="None"),this.$i=x(r)?this.ji:r;var i=!1;if(Z(e,((s,o)=>{this.props.hasOwnProperty(o)&&this.props[o]!==n||(this.Pi(o,s),i=!0)})),i)return this.save(),!0}return!1}register(e,n){if(te(e)){this.$i=x(n)?this.ji:n;var r=!1;if(Z(e,((i,s)=>{e.hasOwnProperty(s)&&(this.props[s]!==i||te(i)||L(i))&&(this.Pi(s,i),r=!0)})),r)return this.save(),!0}return!1}unregister(e){var n=typeof e=="string"?[e]:e,r=!1;for(var i of n)i in this.props&&(this.Ri(i),r=!0);r&&this.save()}update_campaign_params(){var e=C?.URL;if(e!==this.mi){var n=Ku(this.Ne.custom_campaign_params,this.Ne.mask_personal_data_properties,this.Ne.custom_personal_data_properties);yt(oa(n))||this.register(n),this.mi=e}}update_search_keyword(){var e;this.register((e=C?.referrer)?Yu(e):{})}update_referrer_info(){var e;this.register_once({$referrer:Zu(),$referring_domain:C!=null&&C.referrer&&((e=_i(C.referrer))==null?void 0:e.host)||wi},void 0)}set_initial_person_info(){this.props[ho]||this.props[po]||this.register_once({[hi]:Xu(this.Ne.mask_personal_data_properties,this.Ne.custom_personal_data_properties,this.Ne.disable_capture_url_hashes)},void 0)}get_initial_props(){var e={};Z([po,ho],(i=>{var s=this.props[i];s&&Z(s,(function(o,a){e["$initial_"+Vs(a)]=o}))}));var n=this.props[hi];if(n){var r=(function(i,s){s===void 0&&(s=!1);var o=Qu(i,s),a={};return Z(o,(function(l,u){a["$initial_"+Vs(u)]=l})),a})(n,this.Ne.disable_capture_url_hashes);ee(e,r)}return e}safe_merge(e){return Z(this.props,(function(n,r){r in e||(e[r]=n)})),e}update_config(e,n,r){this.ji=this.$i=e.cookie_expiration,this.set_disabled(e.disable_persistence||!!r),this.set_cross_subdomain(e.cross_subdomain_cookie),this.set_secure(e.secure_cookie);var i=e.persistence!==n.persistence||!((l,u)=>{if(l.length!==u.length)return!1;var c=[...l].sort(),d=[...u].sort();return c.every(((h,p)=>h===d[p]))})(e.cookie_persisted_properties||[],n.cookie_persisted_properties||[]),s=i?this.bi(e):this.ii,o=this.wi(e);if(i||o!==this.pi){var a=this.props;this.clear(),this.ii=s,this.pi=o,this.props=a,this.save()}}set_disabled(e){this.xi=e,this.xi?this.remove():this.save()}set_cross_subdomain(e){e!==this.Ni&&(this.Ni=e,this.remove({keepGroupEntries:!0}),this.save())}set_secure(e){e!==this.qi&&(this.qi=e,this.remove({keepGroupEntries:!0}),this.save())}set_event_timer(e,n){var r=this.props[Vn]||{};r[e]=n,this.Pi(Vn,r),this.save()}remove_event_timer(e){var n=this.props[Vn]||{},r=n[e];return x(r)||(delete n[e],this.Pi(Vn,n),this.save()),r}get_property(e){return this.props[e]}set_property(e,n){this.Pi(e,n),this.save()}Pi(e,n){var r;this.props[e]=n,(r=Dt(e))!=null&&r.volatile||this.Bi(e)}Ri(e){delete this.props[e],this.Bi(e)}Bi(e){var n,r=(n=Dt(e))==null?void 0:n.storageGroup;r&&(this.Mi(r).dirty=!0)}Mi(e){return this.ci[e]||(this.ci[e]={})}}function Tr(t){var e=!0;return{dispose(){if(e){e=!1;var n=t();n&&Se(n.then)&&n.then(void 0,(()=>{}))}}}}var xe={GZipJS:"gzip-js",Base64:"base64"},Ln={Activation:"events",Cancellation:"cancelEvents"},Ss={Popover:"popover",API:"api",Widget:"widget"},vt={SHOWN:"survey shown",DISMISSED:"survey dismissed",SENT:"survey sent"},xs={SURVEY_ID:"$survey_id",SURVEY_ITERATION:"$survey_iteration",SURVEY_LAST_SEEN_DATE:"$survey_last_seen_date"},_o={Popover:"popover",Inline:"inline"},Qp={SHOWN:"product tour shown"},Pl={TOUR_LAST_SEEN_DATE:"$product_tour_last_seen_date",TOUR_TYPE:"$product_tour_type"},$l=ne("[RateLimiter]");class ef{constructor(e){this.serverLimits={},this.lastEventRateLimited=!1,this.checkForLimiting=n=>{var r=n.text;if(r&&r.length)try{(JSON.parse(r).quota_limited||[]).forEach((i=>{$l.info((i||"events")+" is quota limited."),this.serverLimits[i]=new Date().getTime()+6e4}))}catch(i){return void $l.warn('could not rate limit - continuing. Error: "'+i?.message+'"',{text:r})}},this.instance=e,this.lastEventRateLimited=this.clientRateLimitContext(!0).isRateLimited}get captureEventsPerSecond(){var e;return((e=this.instance.config.rate_limiting)==null?void 0:e.events_per_second)||10}get captureEventsBurstLimit(){var e;return Math.max(((e=this.instance.config.rate_limiting)==null?void 0:e.events_burst_limit)||10*this.captureEventsPerSecond,this.captureEventsPerSecond)}clientRateLimitContext(e){var n,r,i;e===void 0&&(e=!1);var s=this.captureEventsBurstLimit,o=this.captureEventsPerSecond,a=new Date().getTime(),l=(n=(r=this.instance.persistence)==null?void 0:r.get_property(uo))!==null&&n!==void 0?n:{tokens:s,last:a};l.tokens+=(a-l.last)/1e3*o,l.last=a,l.tokens>s&&(l.tokens=s);var u=1>l.tokens;if(u||e||(l.tokens=Math.max(0,l.tokens-1)),u&&!e){var c=(he(l.dropped)?l.dropped:0)+1;l.dropped=c,!this.lastEventRateLimited&&this.Hi(c)&&(l.dropped=0)}return this.lastEventRateLimited=u,(i=this.instance.persistence)==null||i.set_property(uo,l),{isRateLimited:u,remainingTokens:l.tokens}}Ui(e){var n=this.instance.config.property_denylist;return!L(n)||!n.includes(e)}zi(){var e;if(this.Ui("$current_url")&&this.Ui("$pathname")&&re!=null&&re.pathname)return""+((e=re.origin)!==null&&e!==void 0?e:"")+re.pathname}Hi(e){var n,r,i=this.captureEventsBurstLimit,s=this.captureEventsPerSecond,o=this.zi(),a=this.Ui("$session_id")?(n=(r=this.instance).get_session_id)==null?void 0:n.call(r):void 0,l=[e+" event(s) dropped since the last warning",o?"triggered on "+o:void 0,a?"session "+a: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 "+i+" events burst limit."},{skip_client_rate_limiting:!0})}isServerRateLimited(e){var n=this.serverLimits[e||"events"]||!1;return n!==!1&&new Date().getTime()e(this.remoteConfig))):e()}Vi(e){this._instance._send_request({method:"GET",url:this._instance.requestRouter.endpointFor("assets","/array/"+this._instance.config.token+"/config"),callback:e})}load(){try{if(this.remoteConfig)return Ct.info("Using preloaded remote config",this.remoteConfig),this.Zi(this.remoteConfig),void this.Gi();if(this._instance.Qi())return void Ct.warn("Remote config is disabled. Falling back to local config.");this.Wi((e=>{if(!e)return Ct.info("No config found after loading remote JS config. Falling back to JSON."),void this.Vi((n=>{this.Zi(n.json,n),this.Gi()}));this.Zi(e),this.Gi()}))}catch(e){Ct.error("Error loading remote config",e),this.Zi()}}stop(){this.Ki&&(clearInterval(this.Ki),this.Ki=void 0)}refresh(){!this._instance.Qi()&&C&&C.visibilityState!=="hidden"&&this._instance.reloadFeatureFlags()}Gi(){var e;if(!this.Ki){var n=(e=this._instance.config.remote_config_refresh_interval_ms)!==null&&e!==void 0?e:3e5;n!==0&&(this.Ki=setInterval((()=>{this.refresh()}),n))}}Zi(e,n){!e&&n&&(n.statusCode===0?n.error||Ct.warn("Failed to fetch remote config from PostHog."):Ct.error("Failed to fetch remote config from PostHog."));try{this._instance.Zi(e?{ok:!0,config:e}:{ok:!1})}catch(i){Ct.error("Error applying remote config",i)}if(e?.hasFeatureFlags!==!1&&!this._instance.config.advanced_disable_feature_flags_on_first_load)try{var r;(r=this._instance.featureFlags)==null||r.ensureFlagsLoaded()}catch(i){Ct.error("Error loading feature flags",i)}}}var qe=Uint8Array,Pe=Uint16Array,Sn=Uint32Array,ua=new qe([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]),da=new qe([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]),Rl=new qe([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),nd=function(t,e){for(var n=new Pe(31),r=0;31>r;++r)n[r]=e+=1<r;++r)for(var s=n[r];n[r+1]>s;++s)i[s]=s-n[r]<<5|r;return[n,i]},rd=nd(ua,2),yo=rd[1];rd[0][28]=258,yo[258]=28;for(var Tl=nd(da,0)[1],id=new Pe(32768),se=0;32768>se;++se){var an=(43690&se)>>>1|(21845&se)<<1;id[se]=((65280&(an=(61680&(an=(52428&an)>>>2|(13107&an)<<2))>>>4|(3855&an)<<4))>>>8|(255&an)<<8)>>>1}var tr=function(t,e,n){for(var r=t.length,i=0,s=new Pe(e);r>i;++i)++s[t[i]-1];var o,a=new Pe(e);for(i=0;e>i;++i)a[i]=a[i-1]+s[i-1]<<1;for(o=new Pe(r),i=0;r>i;++i)o[i]=id[a[t[i]-1]++]>>>15-t[i];return o},Qt=new qe(288);for(se=0;144>se;++se)Qt[se]=8;for(se=144;256>se;++se)Qt[se]=9;for(se=256;280>se;++se)Qt[se]=7;for(se=280;288>se;++se)Qt[se]=8;var bi=new qe(32);for(se=0;32>se;++se)bi[se]=5;var tf=tr(Qt,9),nf=tr(bi,5),sd=function(t){return(t/8>>0)+(7&t&&1)},od=function(t,e,n){(n==null||n>t.length)&&(n=t.length);var r=new(t instanceof Pe?Pe:t instanceof Sn?Sn:qe)(n-e);return r.set(t.subarray(e,n)),r},ct=function(t,e,n){var r=e/8>>0;t[r]|=n<<=7&e,t[r+1]|=n>>>8},On=function(t,e,n){var r=e/8>>0;t[r]|=n<<=7&e,t[r+1]|=n>>>8,t[r+2]|=n>>>16},ks=function(t,e){for(var n=[],r=0;t.length>r;++r)t[r]&&n.push({s:r,f:t[r]});var i=n.length,s=n.slice();if(!i)return[new qe(0),0];if(i==1){var o=new qe(n[0].s+1);return o[n[0].s]=1,[o,1]}n.sort((function(F,A){return F.f-A.f})),n.push({s:-1,f:25001});var a=n[0],l=n[1],u=0,c=1,d=2;for(n[0]={s:-1,f:a.f+l.f,l:a,r:l};c!=i-1;)a=n[n[d].f>n[u].f?u++:d++],l=n[u!=c&&n[d].f>n[u].f?u++:d++],n[c++]={s:-1,f:a.f+l.f,l:a,r:l};var h=s[0].s;for(r=1;i>r;++r)s[r].s>h&&(h=s[r].s);var p=new Pe(h+1),f=wo(n[c-1],p,0);if(f>e){r=0;var g=0,m=f-e,_=1<r;++r){var w=s[r].s;if(e>=p[w])break;g+=_-(1<>>=m;g>0;){var b=s[r].s;e>p[b]?g-=1<=0&&g;--r){var I=s[r].s;p[I]==e&&(--p[I],++g)}f=e}return[new qe(p),f]},wo=function(t,e,n){return t.s==-1?Math.max(wo(t.l,e,n+1),wo(t.r,e,n+1)):e[t.s]=n},Ml=function(t){for(var e=t.length;e&&!t[--e];);for(var n=new Pe(++e),r=0,i=t[0],s=1,o=function(l){n[r++]=l},a=1;e>=a;++a)if(t[a]==i&&a!=e)++s;else{if(!i&&s>2){for(;s>138;s-=138)o(32754);s>2&&(o(s>10?s-11<<5|28690:s-3<<5|12305),s=0)}else if(s>3){for(o(i),--s;s>6;s-=6)o(8304);s>2&&(o(s-3<<5|8208),s=0)}for(;s--;)o(i);s=1,i=t[a]}return[n.subarray(0,r),e]},Bn=function(t,e){for(var n=0,r=0;e.length>r;++r)n+=t[r]*e[r];return n},bo=function(t,e,n){var r=n.length,i=sd(e+2);t[i]=255&r,t[i+1]=r>>>8,t[i+2]=255^t[i],t[i+3]=255^t[i+1];for(var s=0;r>s;++s)t[i+s+4]=n[s];return 8*(i+4+r)},Nl=function(t,e,n,r,i,s,o,a,l,u,c){ct(e,c++,n),++i[256];for(var d=ks(i,15),h=d[0],p=d[1],f=ks(s,15),g=f[0],m=f[1],_=Ml(h),w=_[0],b=_[1],I=Ml(g),F=I[0],A=I[1],j=new Pe(19),S=0;w.length>S;++S)j[31&w[S]]++;for(S=0;F.length>S;++S)j[31&F[S]]++;for(var P=ks(j,7),R=P[0],M=P[1],T=19;T>4&&!R[Rl[T-1]];--T);var O,J,q,H,oe=u+5<<3,fe=Bn(i,Qt)+Bn(s,bi)+o,Ie=Bn(i,h)+Bn(s,g)+o+14+3*T+Bn(j,R)+(2*j[16]+3*j[17]+7*j[18]);if(fe>=oe&&Ie>=oe)return bo(e,c,t.subarray(l,l+u));if(ct(e,c,1+(fe>Ie)),c+=2,fe>Ie){O=tr(h,p),J=h,q=tr(g,m),H=g;var _e=tr(R,M);for(ct(e,c,b-257),ct(e,c+5,A-1),ct(e,c+10,T-4),c+=14,S=0;T>S;++S)ct(e,c+3*S,R[Rl[S]]);c+=3*T;for(var Ce=[w,F],Re=0;2>Re;++Re){var ae=Ce[Re];for(S=0;ae.length>S;++S)ct(e,c,_e[me=31&ae[S]]),c+=R[me],me>15&&(ct(e,c,ae[S]>>>5&127),c+=ae[S]>>>12)}}else O=tf,J=Qt,q=nf,H=bi;for(S=0;a>S;++S)if(r[S]>255){var me;On(e,c,O[257+(me=r[S]>>>18&31)]),c+=J[me+257],me>7&&(ct(e,c,r[S]>>>23&31),c+=ua[me]);var ge=31&r[S];On(e,c,q[ge]),c+=H[ge],ge>3&&(On(e,c,r[S]>>>5&8191),c+=da[ge])}else On(e,c,O[r[S]]),c+=J[r[S]];return On(e,c,O[256]),c+J[256]},rf=new Sn([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),sf=(function(){for(var t=new Sn(256),e=0;256>e;++e){for(var n=e,r=9;--r;)n=(1&n&&3988292384)^n>>>1;t[e]=n}return t})(),Is=function(t,e,n){for(;n;++e)t[e]=n,n>>>=8};function of(t,e){e===void 0&&(e={});var n=(function(){var d=4294967295;return{p(h){for(var p=d,f=0;h.length>f;++f)p=sf[255&p^h[f]]^p>>>8;d=p},d(){return 4294967295^d}}})(),r=t.length;n.p(t);var i,s,o,a,l,u=(a=10+((i=e).filename&&i.filename.length+1||0),l=8,(function(d,h,p,f,g,m){var _=d.length,w=new qe(f+_+5*(1+Math.floor(_/7e3))+g),b=w.subarray(f,w.length-g),I=0;if(!h||8>_)for(var F=0;_>=F;F+=65535){var A=F+65535;_>A?I=bo(b,I,d.subarray(F,A)):(b[F]=!0,I=bo(b,I,d.subarray(F,_)))}else{for(var j=rf[h-1],S=j>>>13,P=8191&j,R=(1<F;++F){var me=q(F),ge=32767&F,Qe=T[me];if(M[ge]=Qe,T[me]=ge,F>=Re){var Lt=_-F;if((Ie>7e3||Ce>24576)&&Lt>423){I=Nl(d,b,0,H,oe,fe,_e,Ce,ae,F-ae,I),Ce=Ie=_e=0,ae=F;for(var de=0;286>de;++de)oe[de]=0;for(de=0;30>de;++de)fe[de]=0}var Ge=2,It=0,$n=P,De=ge-Qe&32767;if(Lt>2&&me==q(F-De))for(var Fe=Math.min(S,Lt)-1,Sr=Math.min(32767,F),xr=Math.min(258,Lt);Sr>=De&&--$n&&ge!=Qe;){if(d[F+Ge]==d[F+Ge-De]){for(var je=0;xr>je&&d[F+je]==d[F+je-De];++je);if(je>Ge){if(Ge=je,It=De,je>Fe)break;var kr=Math.min(De,je-2),nn=0;for(de=0;kr>de;++de){var rn=F-De+de+32768&32767,Rn=rn-M[rn]+32768&32767;Rn>nn&&(nn=Rn,Qe=rn)}}}De+=(ge=Qe)-(Qe=M[ge])+32768&32767}if(It){H[Ce++]=268435456|yo[Ge]<<18|Tl[It];var Ga=31&yo[Ge],Ka=31&Tl[It];_e+=ua[Ga]+da[Ka],++oe[257+Ga],++fe[Ka],Re=F+Ge,++Ie}else H[Ce++]=d[F],++oe[d[F]]}}I=Nl(d,b,!0,H,oe,fe,_e,Ce,ae,F-ae,I)}return od(w,0,f+sd(I)+g)})(s=t,(o=e).level==null?6:o.level,o.mem==null?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(s.length)))):12+o.mem,a,l)),c=u.length;return(function(d,h){var p=h.filename;if(d[0]=31,d[1]=139,d[2]=8,d[8]=2>h.level?4:h.level==9?2:0,d[9]=3,h.mtime!=0&&Is(d,4,Math.floor(new Date(h.mtime||Date.now())/1e3)),p){d[3]=8;for(var f=0;p.length>=f;++f)d[f+10]=p.charCodeAt(f)}})(u,e),Is(u,c-8,n.d()),Is(u,c-4,r),u}var af=!!Ws||!!Jo,ad="text/plain",Gr=!1,ld=(t,e)=>{var n=t.split("#"),r=n[1],i=n[0].split("?"),s=i[0],o=i[1];if(!o)return t;var a=o.split("&").filter((l=>l.split("=")[0]!==e)).join("&");return s+(a?"?"+a:"")+(r?"#"+r:"")},ji=function(t,e,n){var r;n===void 0&&(n=!0);var i=t.split("?"),s=i[0],o=i[1],a=E({},e),l=(r=o?.split("&").map((c=>{var d,h=c.split("="),p=h[0],f=n&&(d=a[p])!==null&&d!==void 0?d:h[1];return delete a[p],p+"="+f})))!==null&&r!==void 0?r:[],u=(function(c,d){var h,p;d===void 0&&(d="&");var f=[];return Z(c,(function(g,m){x(g)||x(m)||m==="undefined"||(h=encodeURIComponent((_=>_ instanceof File)(g)?g.name:g.toString()),p=encodeURIComponent(m),f[f.length]=p+"="+h)})),f.join(d)})(a);return u&&l.push(u),l.length>0?s+"?"+l.join("&"):s},Cs=t=>{if(t.Ji)return t.Ji;var e=t.data,n=t.compression;if(e){if(n===xe.GZipJS){var r=of((function(a,l){var u=a.length;if(typeof TextEncoder<"u")return new TextEncoder().encode(a);for(var c=new qe(a.length+(a.length>>>1)),d=0,h=function(m){c[d++]=m},p=0;u>p;++p){if(d+5>c.length){var f=new qe(d+8+(u-p<<1));f.set(c),c=f}var g=a.charCodeAt(p);128>g?h(g):2048>g?(h(192|g>>>6),h(128|63&g)):g>55295&&57344>g?(h(240|(g=65536+(1047552&g)|1023&a.charCodeAt(++p))>>>18),h(128|g>>>12&63),h(128|g>>>6&63),h(128|63&g)):(h(224|g>>>12),h(128|g>>>6&63),h(128|63&g))}return od(c,0,d)})(fn(e)),{mtime:0});return{contentType:ad,body:r.buffer.slice(r.byteOffset,r.byteOffset+r.byteLength),estimatedSize:r.byteLength}}if(n===xe.Base64){var i=(function(a){return a&&btoa(encodeURIComponent(a).replace(/%([0-9A-F]{2})/g,((l,u)=>String.fromCharCode(parseInt(u,16)))))})(fn(e)),s=(a=>"data="+encodeURIComponent(typeof a=="string"?a:fn(a)))(i);return{contentType:"application/x-www-form-urlencoded",body:s,estimatedSize:new Blob([s]).size}}var o=fn(e);return{contentType:"application/json",body:o,estimatedSize:new Blob([o]).size}}},cd=t=>{var e,n,r=()=>t.transport==="sendBeacon"?{url:ji(t.url,{compression:xe.Base64}),encodedBody:Cs(E({},t,{compression:xe.Base64,Ji:void 0}))}:{url:ld(t.url,"compression"),encodedBody:Cs(E({},t,{compression:void 0,Ji:void 0}))};try{e=Cs(t)}catch(i){if(tl(t.compression,bn(t.url,"compression")))return k.error("Failed to gzip request body, sending uncompressed payload",i),r();throw i}return e&&tl(t.compression,bn(t.url,"compression"))&&!((n=e.body)instanceof ArrayBuffer?zs(new Uint8Array(n)):ArrayBuffer.isView(n)&&zs(new Uint8Array(n.buffer,n.byteOffset,n.byteLength)))?(Gr=!0,r()):{url:t.url,encodedBody:e}},ud=t=>{try{return cd(t)}catch(e){return k.error(e),void(t.callback==null||t.callback({statusCode:0,error:e}))}},lf=(function(){var t=X((function*(e){var n=fn(e.data),r=yield(function(s,o,a){return qs.apply(this,arguments)})(n,Y.DEBUG,{rethrow:!0});if(!r)return e;var i=yield r.arrayBuffer();return E({},e,{Ji:{contentType:ad,body:i,estimatedSize:i.byteLength}})}));return function(e){return t.apply(this,arguments)}})(),cf=/Failed to fetch|NetworkError|Load failed/i,dd=t=>t?.name==="TypeError"&&cf.test(t?.message||""),hd=t=>{var e=ud(t);if(e){var n=e.url,r=e.encodedBody,i=r??{},s=i.contentType,o=i.body,a=i.estimatedSize,l=new Headers;Z(t.headers,(function(f,g){l.append(g,f)})),s&&l.append("Content-Type",s);var u=null,c=!1;if(Ja){var d=new Ja;u={signal:d.signal,timeout:setTimeout((()=>{var f,g;c=!0,d.abort((f=t.timeout,(g=new Error("PostHog request timed out"+(f?" after "+f+"ms":""))).name="AbortError",g))}),t.timeout)}}var h=f=>{c&&f?.name==="AbortError"||dd(f)?k.warn(f):k.error(f),t.callback==null||t.callback({statusCode:0,error:f})};try{var p;Jo(n,E({method:t?.method||"GET",headers:l,keepalive:t.method==="POST"&&!t.Yi&&52428.8>(a||0),body:o,signal:(p=u)==null?void 0:p.signal},t.fetchOptions)).then((f=>f.text().then((g=>{var m={statusCode:f.status,text:g};if(f.status===200)try{m.json=JSON.parse(g)}catch(_){k.error(_)}t.callback==null||t.callback(m)})))).catch(h).finally((()=>u?clearTimeout(u.timeout):null))}catch(f){u&&clearTimeout(u.timeout),h(f)}}},Eo=t=>{try{var e,n=cd(t),r=n.url,i=n.encodedBody,s=i??{},o=s.body,a=s.estimatedSize;if(!o)return;var l=o instanceof Blob?o:new Blob([o],{type:s.contentType});if(ke.sendBeacon(r,l))return;var u=L(t.data)?t.data:(e=t.data)==null?void 0:e.batch;if(L(u)&&u.length>1&&(a??0)>16384){var c=Math.ceil(u.length/2),d=h=>L(t.data)?h:E({},t.data,{batch:h});return Eo(E({},t,{data:d(u.slice(0,c))})),void Eo(E({},t,{data:d(u.slice(c))}))}k.warn("Beacon of ~"+(a??0)+" bytes was rejected by the browser, falling back to fetch"),hd(E({},t,{Yi:!0}))}catch(h){k.warn("Beacon send failed",h)}},Ll=(t,e,n,r)=>{var i=r==="query"?e==="POST"?"sent_at":"_":void 0;return ji(n===xe.GZipJS?ld(t,"compression"):t,E({},i?{[i]:Date.now().toString()}:{},n===xe.GZipJS?{}:{compression:n}))},Kr=[];Jo&&Kr.push({transport:"fetch",method:hd}),Ws&&Kr.push({transport:"XHR",method(t){var e=ud(t);if(e){var n=new Ws,r=e.encodedBody;n.open(t.method||"GET",e.url,!0);var i=r??{},s=i.contentType,o=i.body;Z(t.headers,(function(a,l){n.setRequestHeader(l,a)})),s&&n.setRequestHeader("Content-Type",s),t.timeout&&(n.timeout=t.timeout),n.onreadystatechange=()=>{if(n.readyState===4){var a={statusCode:n.status,text:n.responseText};if(n.status===200)try{a.json=JSON.parse(n.responseText)}catch{}t.callback==null||t.callback(a)}},n.send(o)}}}),ke!=null&&ke.sendBeacon&&Kr.push({transport:"sendBeacon",method:Eo});var So=3e3;class uf{constructor(e,n){this.Xi=!0,this.tr=[],this.er=ot(n?.flush_interval_ms||So,250,5e3,k.createLogger("flush interval"),So),this.ir=e}enqueue(e){this.tr.push(e),this.rr||this.nr()}unload(){this.sr();var e=this.tr.length>0?this.ar():{},n=Object.values(e);[...n.filter((r=>r.url.indexOf("/e")===0)),...n.filter((r=>r.url.indexOf("/e")!==0))].map((r=>{this.lr(E({},r,{transport:"sendBeacon"}))}))}enable(){this.Xi=!1,this.nr()}nr(){var e=this;this.Xi||(this.rr=setTimeout((()=>{if(this.sr(),this.tr.length>0){var n=this.ar(),r=function(){var s=n[i],o=new Date().getTime();s.data&&L(s.data)&&Z(s.data,(a=>{a.offset=Math.abs(a.timestamp-o),delete a.timestamp})),e.lr(s)};for(var i in n)r()}}),this.er))}lr(e){try{this.ir(e)}catch(n){k.error(n)}}sr(){clearTimeout(this.rr),this.rr=void 0}ar(){var e={};return Z(this.tr,(n=>{var r,i=n,s=(i?i.batchKey:null)||i.url;x(e[s])&&(e[s]=E({},i,{data:[]})),(r=e[s].data)==null||r.push(i.data)})),this.tr=[],e}}var df=["retriesPerformedSoFar"];class hf{constructor(e){this.ur=!1,this.hr=3e3,this.tr=[],this._instance=e,this.tr=[],this.dr=!0,!x(v)&&"onLine"in v.navigator&&(this.dr=v.navigator.onLine,this.vr=()=>{this.dr=!0,this.cr()},this.pr=()=>{this.dr=!1},ie(v,"online",this.vr),ie(v,"offline",this.pr))}get length(){return this.tr.length}retriableRequest(e){var n=e.retriesPerformedSoFar,r=jc(e,df);dt(n)&&(r.url=ji(r.url,{retry_count:n})),this._instance._send_request(E({},r,{callback:i=>{if(i.statusCode!==200&&(400>i.statusCode||i.statusCode>=500)){if((i.statusCode===0?3:10)>(n??0))return void this.At(E({retriesPerformedSoFar:n},r));i.statusCode===0&&k.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.")}r.callback==null||r.callback(i)}}))}At(e){var n=e.retriesPerformedSoFar||0;e.retriesPerformedSoFar=n+1;var r=(function(o){var a=3e3*Math.pow(2,o),l=a/2,u=Math.min(18e5,a),c=Math.random()-.5;return Math.ceil(u+c*(u-l))})(n),i=Date.now()+r;this.tr.push({retryAt:i,requestOptions:e});var s="Enqueued failed request for retry in "+r;navigator.onLine||(s+=" (Browser is offline)"),k.warn(s),this.ur||(this.ur=!0,this.gr())}gr(){if(this.mr&&clearTimeout(this.mr),this.tr.length===0)return this.ur=!1,void(this.mr=void 0);this.mr=setTimeout((()=>{this.dr&&this.tr.length>0&&this.cr(),this.gr()}),this.hr)}cr(){var e=Date.now(),n=[],r=this.tr.filter((s=>e>s.retryAt||(n.push(s),!1)));if(this.tr=n,r.length>0)for(var i of r)this.retriableRequest(i.requestOptions)}unload(){for(var e of(this.mr&&(clearTimeout(this.mr),this.mr=void 0),this.ur=!1,x(v)||(this.vr&&(v.removeEventListener("online",this.vr),this.vr=void 0),this.pr&&(v.removeEventListener("offline",this.pr),this.pr=void 0)),this.tr)){var n=e.requestOptions;try{this._instance._send_request(E({},n,{transport:"sendBeacon"}))}catch(r){k.error(r)}}this.tr=[]}}class pf{constructor(e){this.yr=()=>{var n,r,i,s;this.br||(this.br={});var o=this.scrollElement(),a=this.scrollY(),l=o?Math.max(0,o.scrollHeight-o.clientHeight):0,u=a+(o?.clientHeight||0),c=o?.scrollHeight||0;this.br.lastScrollY=Math.ceil(a),this.br.maxScrollY=Math.max(a,(n=this.br.maxScrollY)!==null&&n!==void 0?n:0),this.br.maxScrollHeight=Math.max(l,(r=this.br.maxScrollHeight)!==null&&r!==void 0?r:0),this.br.lastContentY=u,this.br.maxContentY=Math.max(u,(i=this.br.maxContentY)!==null&&i!==void 0?i:0),this.br.maxContentHeight=Math.max(c,(s=this.br.maxContentHeight)!==null&&s!==void 0?s:0)},this._instance=e}get _r(){return this._instance.config.scroll_root_selector}getContext(){return this.br}resetContext(){var e=this.br;return setTimeout(this.yr,0),e}startMeasuringScrollPosition(){ie(v,"scroll",this.yr,{capture:!0}),ie(v,"scrollend",this.yr,{capture:!0}),ie(v,"resize",this.yr)}scrollElement(){if(!this._r)return v?.document.documentElement;var e=L(this._r)?this._r:[this._r];for(var n of e){var r=v?.document.querySelector(n);if(r)return r}}wr(e){var n=e==="y"?"scrollTop":"scrollLeft";if(this._r){var r=this.scrollElement();return r&&r[n]||0}return v?e==="y"?v.scrollY||v.pageYOffset||v.document.documentElement.scrollTop||0:v.scrollX||v.pageXOffset||v.document.documentElement.scrollLeft||0:0}scrollY(){return this.wr("y")}scrollX(){return this.wr("x")}}var ff=t=>Xu(t?.config.mask_personal_data_properties,t?.config.custom_personal_data_properties,t?.config.disable_capture_url_hashes);class Ol{constructor(e,n,r,i){this.kr=s=>{var o=this.Sr();if(!o||o.sessionId!==s){var a={sessionId:s,props:this.Cr(this._instance)};this.Mr.register({[co]:a})}},this._instance=e,this.Tr=n,this.Mr=r,this.Cr=i||ff,this.Tr.onSessionId(this.kr)}Sr(){return this.Mr.props[co]}getSetOnceProps(){var e,n=(e=this.Sr())==null?void 0:e.props;return n?"r"in n?Qu(n,this._instance.config.disable_capture_url_hashes):{$referring_domain:n.referringDomain,$pathname:n.initialPathName,utm_source:n.utm_source,utm_campaign:n.utm_campaign,utm_medium:n.utm_medium,utm_content:n.utm_content,utm_term:n.utm_term}:{}}getSessionProps(){var e={};return Z(oa(this.getSetOnceProps()),((n,r)=>{r==="$current_url"&&(r="url"),e["$session_entry_"+Vs(r)]=n})),e}}class ha{on(e,n){return this.Er[e]||(this.Er[e]=[]),this.Er[e].push(n),()=>{this.Er[e]=this.Er[e].filter((r=>r!==n))}}emit(e,n){for(var r of this.Er[e]||[])r(n);for(var i of this.Er["*"]||[])i(e,n)}constructor(){this.Er={}}}var Dn=ne("[SessionId]");class Bl{on(e,n){return this.Ir.on(e,n)}constructor(e,n,r){var i;if(this.Pr=null,this.Rr=[],this.Ar=void 0,this.Fr=!1,this.Ir=new ha,this.Lr=(u,c)=>!(!dt(u)||!dt(c))&&Math.abs(u-c)>this.sessionTimeoutMs,!e.persistence)throw new Error("SessionIdManager requires a PostHogPersistence instance");if(e.config.cookieless_mode===gt)throw new Error('SessionIdManager cannot be used with cookieless_mode="always"');this.Ne=e.config,this.Mr=e.persistence,this.Or=void 0,this.Dr=void 0,this._sessionStartTimestamp=null,this._sessionActivityTimestamp=null,this.$r=n||ft,this.Nr=r||ft;var s=this.Ne.persistence_name||this.Ne.token;if(this._sessionTimeoutMs=1e3*ot(this.Ne.session_idle_timeout_seconds||1800,60,36e3,Dn.createLogger("session_idle_timeout_seconds"),1800),e.register({$configured_session_timeout_ms:this._sessionTimeoutMs}),this.qr(),this.jr="ph_"+s+"_window_id",this.Br="ph_"+s+"_primary_window_exists",this.Hr()){var o=ce.H(this.jr),a=ce.H(this.Br);o&&!a?this.Or=o:ce.q(this.jr),ce.F(this.Br,!0)}if((i=this.Ne.bootstrap)!=null&&i.sessionID)try{var l=(u=>{var c=this.Ne.bootstrap.sessionID.replace(/-/g,"");if(c.length!==32)throw new Error("Not a valid UUID");if(c[12]!=="7")throw new Error("Not a UUIDv7");return parseInt(c.substring(0,12),16)})();this.Ur(this.Ne.bootstrap.sessionID,new Date().getTime(),l)}catch(u){Dn.error("Invalid sessionID in bootstrap",u)}this.zr()}get sessionTimeoutMs(){return this._sessionTimeoutMs}onSessionId(e){return x(this.Rr)&&(this.Rr=[]),this.Rr.push(e),this.Dr&&e(this.Dr,this.Or),()=>{this.Rr=this.Rr.filter((n=>n!==e))}}Hr(){return this.Ne.persistence!=="memory"&&!this.Mr.xi&&ce.N()}Wr(e){e!==this.Or&&(this.Or=e,this.Hr()&&ce.F(this.jr,e))}Vr(){return this.Or?this.Or:this.Hr()?ce.H(this.jr):null}Zr(e){var n=this.Pr;return!$e(n)&&!$e(e)&&5e3>Math.abs(e-n)}Ur(e,n,r){var i=n!==this._sessionActivityTimestamp,s=!(e!==this.Dr||r!==this._sessionStartTimestamp);this._sessionStartTimestamp=r,this._sessionActivityTimestamp=n,this.Dr=e,s&&!i||s&&this.Zr(n)||(this.Pr=n,this.Mr.register({[pn]:[n,e,r]}))}Gr(){var e,n=(e=this.Ne)==null?void 0:e.persistence_save_debounce_ms;return dt(n)&&n>0}Qr(){this.Gr()?this.Mr.refreshKey(pn):(this.Mr.flush(),this.Mr.load())}Kr(){var e;if(!$e(this._sessionActivityTimestamp)&&this._sessionActivityTimestamp!==this.Pr){this.Qr();var n=this.Jr();n[1]===this.Dr&&n[2]===this._sessionStartTimestamp&&(this.Pr=this._sessionActivityTimestamp,this.Mr.register({[pn]:[this._sessionActivityTimestamp,(e=this.Dr)!==null&&e!==void 0?e:null,this._sessionStartTimestamp]}),this.Mr.flush())}}Yr(){var e=this.Jr()[0],n=dt(e)?e:0,r=dt(this._sessionActivityTimestamp)?this._sessionActivityTimestamp:0;return Math.max(n,r)}Xr(e){return this.Qr(),this.Lr(e,this.Yr())}Jr(){var e=this.Mr.props[pn];return L(e)&&e.length===2&&e.push(e[0]),e||[0,null,0]}resetSessionId(){this.Pr=null,clearTimeout(this.tn),this.tn=void 0,this.Ur(null,null,null)}destroy(){this.Fr=!0,this.Kr(),clearTimeout(this.tn),this.tn=void 0,this.Ar&&v&&(v.removeEventListener(gi,this.Ar,{capture:!1}),this.Ar=void 0),this.Rr=[]}zr(){this.Ar=()=>{this.Kr(),this.Hr()&&ce.q(this.Br)},ie(v,gi,this.Ar,{capture:!1})}checkAndGetSessionAndWindowId(e,n){if(e===void 0&&(e=!1),n===void 0&&(n=null),this.Ne.cookieless_mode===gt)throw new Error('checkAndGetSessionAndWindowId should not be called with cookieless_mode="always"');var r=n||new Date().getTime(),i=this.Jr(),s=i[1],o=i[2],a=this.Yr(),l=this.Vr(),u=dt(o)&&Math.abs(r-o)>864e5,c=!1,d=!1,h=!s,p=s,f=!h&&!e&&this.Lr(r,a);if(f){(f=this.Xr(r))||Dn.info("cross-tab refresh kept the session alive",{sessionId:s});var g=this.Jr();s=g[1],o=g[2]}h||f||u?(s=this.$r(),l=this.Nr(),Dn.info("new session ID generated",{sessionId:s,windowId:l,changeReason:{noSessionId:h,activityTimeout:f,sessionPastMaximumLength:u}}),o=r,c=!0):(l||(l=this.Nr(),c=!0),(d=s!==p)&&(Dn.info("adopted cross-tab session id",{sessionId:s,windowId:l}),c=!0));var m=dt(a)&&e&&!u?a:r,_=dt(o)?o:new Date().getTime();this.Wr(l),this.Ur(s,m,_),e||this.qr();var w={noSessionId:h,activityTimeout:f,sessionPastMaximumLength:u,crossTabAdoption:d};return c&&this.Rr.forEach((b=>b(s,l,w))),{sessionId:s,windowId:l,sessionStartTimestamp:_,changeReason:c?w:void 0,lastActivityTimestamp:a}}qr(){this.Fr||(clearTimeout(this.tn),this.tn=setTimeout((()=>{if(!this.Fr)if(this.Xr(new Date().getTime())){var e=this.Dr;this.resetSessionId(),this.Ir.emit("forcedIdleReset",{idleSessionId:e})}else this.qr()}),1.1*this.sessionTimeoutMs))}}var pd=function(t,e){if(!t)return!1;var n=t.userAgent;if(n&&rl(n,e))return!0;try{var r=t?.userAgentData;if(r!=null&&r.brands&&r.brands.some((i=>rl(i?.brand,e))))return!0}catch{}return!!t.webdriver};function fd(){return(fd=X((function*(){var t=ke?.userAgentData;if(t!=null&&t.getHighEntropyValues)try{var e=yield t.getHighEntropyValues(["model"]),n=e?.model;return W(n)&&n.length>0?n:void 0}catch(r){return void k.info("Unable to resolve $device_model from userAgentData.getHighEntropyValues",r)}}))).apply(this,arguments)}var Ei=function(t,e){if(!(function(n){try{new RegExp(n)}catch{return!1}return!0})(e))return!1;try{return new RegExp(e).test(t)}catch{return!1}};function Fs(t,e,n){return fn({distinct_id:t,userPropertiesToSet:e,userPropertiesToSetOnce:n})}var gd={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=>Ei(n,r))))),not_regex:(t,e)=>e.every((n=>t.every((r=>!Ei(n,r))))),icontains:(t,e)=>e.map(Mr).some((n=>t.map(Mr).some((r=>n.includes(r))))),not_icontains:(t,e)=>e.map(Mr).every((n=>t.map(Mr).every((r=>!n.includes(r))))),gt:(t,e)=>e.some((n=>{var r=parseFloat(n);return!isNaN(r)&&t.some((i=>r>parseFloat(i)))})),lt:(t,e)=>e.some((n=>{var r=parseFloat(n);return!isNaN(r)&&t.some((i=>rt.toLowerCase();function md(t,e){return!t||Object.entries(t).every((n=>{var r=n[1],i=e?.[n[0]];if(x(i)||$e(i))return!1;var s=[String(i)],o=gd[r.operator];return!!o&&o(r.values,s)}))}var xo="custom",Dl="i.posthog.com",gf=/^\/static\//;class mf{constructor(e){this.en={},this.instance=e}get apiHost(){var e=this.instance.config.api_host.trim().replace(/\/$/,"");return e==="https://app.posthog.com"?"https://us.i.posthog.com":e}get flagsApiHost(){var e=this.instance.config.flags_api_host;return e?e.trim().replace(/\/$/,""):this.apiHost}get uiHost(){var e,n=(e=this.instance.config.ui_host)==null?void 0:e.replace(/\/$/,"");return n||(n=this.apiHost.replace("."+Dl,".posthog.com")),n==="https://app.posthog.com"?"https://us.posthog.com":n}get region(){return this.en[this.apiHost]||(this.en[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":xo),this.en[this.apiHost]}rn(e){if(gf.test(e)){var n=this.instance.config.asset_host;if(typeof n=="string")return n.trim().replace(/\/$/,"")||void 0}}endpointFor(e,n){if(n===void 0&&(n=""),n&&(n=n[0]==="/"?n:"/"+n),e==="ui")return this.uiHost+n;if(e==="flags")return this.flagsApiHost+n;if(e==="assets"){var r=this.rn(n);if(r)return""+r+n}if(this.region===xo)return this.apiHost+n;var i=Dl+n;switch(e){case"assets":return"https://"+this.region+"-assets."+i;case"api":return"https://"+this.region+"."+i}}}function vd(t){var e;return!((e=t.conditions)==null||(e=e.events)==null||(e=e.values)==null||!e.length)}var V=ne("[Surveys]"),_d="seenSurvey_",yd=t=>{try{var e=(n=>((r,i)=>""+_d+(function(s){return s.current_iteration&&s.current_iteration>0?s.id+"_"+s.current_iteration:s.id})(i))(0,n))(t);if(localStorage.getItem(e))return;localStorage.setItem(e,"true")}catch(n){V.error("Failed to persist survey seen state",n)}},vf=[Ss.Popover,Ss.Widget,Ss.API],_f={ignoreConditions:!1,ignoreDelay:!1,displayType:_o.Popover},yf=ne("[PostHog ExternalIntegrations]"),wf={intercom:"intercom-integration",crispChat:"crisp-chat-integration"};class bf{constructor(e){this._instance=e}ai(e,n){var r;(r=$.__PosthogExtensions__)==null||r.loadExternalDependency==null||r.loadExternalDependency(this._instance,e,(i=>{if(i)return yf.error("failed to load script",i);n()}))}startIfEnabledOrStop(){var e=this,n=function(){var s,o,a,l=r[0],u=r[1];!u||(s=$.__PosthogExtensions__)!=null&&(s=s.integrations)!=null&&s[l]||e.ai(wf[l],(()=>{var c;(c=$.__PosthogExtensions__)==null||(c=c.integrations)==null||(c=c[l])==null||c.start(e._instance)})),!u&&(o=$.__PosthogExtensions__)!=null&&(o=o.integrations)!=null&&o[l]&&((a=$.__PosthogExtensions__)==null||(a=a.integrations)==null||(a=a[l])==null||a.stop())};for(var r of Object.entries((i=this._instance.config.integrations)!==null&&i!==void 0?i:{})){var i;n()}}}class Ef{constructor(e,n){this.rt=e,this.nn=n,this.sn=new Map,this.an=!1}add(e){var n=this;return X((function*(){if(n.an)throw new Error("Cannot add an extension to a disposed ExtensionRuntime");if(n.sn.has(e.name))throw new Error('Browser extension "'+e.name+'" is already registered');n.sn.set(e.name,e);try{var r=e.setup(n.nn);r&&(yield r)}catch(s){var i=n.sn.get(e.name)===e;i&&n.sn.delete(e.name),n.rt.error('Failed to set up browser extension "'+e.name+'"',s),i&&n.ln(e)}}))()}dispose(){if(!this.an){this.an=!0;var e=Array.from(this.sn.values()).reverse();for(var n of(this.sn.clear(),e))this.ln(n)}}ln(e){try{var n=e.dispose==null?void 0:e.dispose();n&&Se(n.then)&&n.then(void 0,(r=>{this.rt.error('Failed to dispose browser extension "'+e.name+'"',r)}))}catch(r){this.rt.error('Failed to dispose browser extension "'+e.name+'"',r)}}}class Sf{constructor(e){this._instance=e}initialize(){}get(e){var n=this._instance.persistence;if(typeof e=="string")return n?.get_property(e);var r={};for(var i of e){var s=n?.get_property(i);x(s)||(r[i]=s)}return r}set(e,n){var r;(r=this._instance.persistence)==null||r.register(typeof e=="string"?{[e]:n}:e)}remove(e){var n;(n=this._instance.persistence)==null||n.unregister(e)}}var jl="extensionsRemoteConfig";class xf{constructor(e){this.an=!1,this.instance=e,this.rt=k,this.un=e.hn,this.kv=new Sf(e),this.onEvent=n=>Tr(this.instance.on("eventCaptured",(r=>{try{n({event:r.event,properties:r.properties})}catch(i){this.rt.error("Browser extension event listener failed",i)}}))),this.onRemoteConfig=n=>{if(this.an)return Tr((()=>{}));var r=s=>{try{n(s)}catch(o){this.rt.error("Browser extension remote config listener failed",o)}},i=this.instance.dn.on(jl,r);return this.un&&r(this.un),Tr(i)},this.vn=new Ef(k.createLogger("[BrowserExtensions]"),this)}get logger(){return this.rt}get distinctId(){return this.instance.get_distinct_id()}get anonymousId(){var e;return(e=this.instance.get_property(lr))!==null&&e!==void 0?e:this.distinctId}get deviceId(){var e=this.instance.get_property(lr);return typeof e=="string"?e:void 0}get library(){return{name:Y.LIB_NAME,version:Y.LIB_VERSION}}get initialPersonProperties(){var e,n;return(e=(n=this.instance.persistence)==null?void 0:n.get_initial_props())!==null&&e!==void 0?e:{}}get groups(){return this.instance.getGroups()}get session(){try{var e,n,r,i,s=(e=this.instance.sessionManager)==null?void 0:e.checkAndGetSessionAndWindowId(!0);return{sessionId:(n=s?.sessionId)!==null&&n!==void 0?n:"",windowId:(r=s?.windowId)!==null&&r!==void 0?r:"",sessionStartTimestamp:(i=s?.sessionStartTimestamp)!==null&&i!==void 0?i:0}}catch{return{sessionId:"",windowId:"",sessionStartTimestamp:0}}}get projectToken(){return this.instance.config.token}add(e){return this.vn.add(e)}capture(e,n,r){var i=this;return X((function*(){r?i.instance.capture(e,n,{timestamp:r.timestamp,uuid:r.uuid,$set:r.set,$set_once:r.setOnce}):i.instance.capture(e,n)}))()}registerDynamicEventProperties(e){return Tr(this.instance.cn(e))}handleRemoteConfig(e){this.an||(this.un=e,this.instance.dn.emit(jl,e))}sendRequest(e,n){var r=this;return X((function*(){var i;n===void 0&&(n={});var s=r.instance.requestRouter.endpointFor((i=n.target)!==null&&i!==void 0?i:"api",e),o={method:n.method,url:n.query?ji(s,n.query):s,data:n.body,headers:n.headers,timeout:n.timeoutMs,fireCallbackOnDrop:!0,transport:n.transport,compression:n.compression,timestampMode:n.sentAt};return n.transport==="sendBeacon"?(r.instance._send_request(o),{statusCode:202}):new Promise((a=>{o.callback=a,r.instance._send_request(o)}))}))()}dispose(){this.an||(this.an=!0,this.vn.dispose())}}var nr={},As=0,Si=()=>{},Ul='Consent opt in/out is not valid with cookieless_mode="always" and will be ignored',jn="Surveys module not available",Hl="sanitize_properties is deprecated. Use before_send instead",wd="Invalid value for property_denylist config: ",kf=["token","distinct_id",Cu],dn="posthog",bd=!af&&Ae?.indexOf("MSIE")===-1&&Ae?.indexOf("Mozilla")===-1,Ps=t=>{var e;return E({api_host:"https://us.i.posthog.com",flags_api_host:null,ui_host:null,asset_host:null,token:"",autocapture:!0,cross_subdomain_cookie:kp(C?.location),persistence:"localStorage+cookie",persistence_name:"",cookie_persisted_properties:[],loaded:Si,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_external_dependency_versioned_paths:!1,__preview_cookie_wins_on_conflict:!1,debug:re&&W(re?.search)&&re.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,disable_external_dependency_loading:!1,strict_script_versioning:!1,enable_recording_console_log:void 0,secure_cookie:(v==null||(e=v.location)==null?void 0:e.protocol)==="https:",ip:!1,opt_out_capturing_by_default:!1,opt_out_persistence_by_default:!1,opt_out_useragent_filter:!1,opt_out_capturing_persistence_type:"localStorage",consent_persistence_name:null,opt_out_capturing_cookie_prefix:null,opt_in_site_apps:!1,property_denylist:[],respect_dnt:!1,sanitize_properties:null,request_headers:{},request_batching:!0,properties_string_max_length:65535,mask_all_element_attributes:!1,mask_all_text:!1,mask_personal_data_properties:!1,custom_personal_data_properties:[],advanced_disable_flags:!1,advanced_disable_decide:!1,advanced_disable_feature_flags:!1,advanced_disable_feature_flags_on_first_load:!1,advanced_only_evaluate_survey_feature_flags:!1,advanced_feature_flags_dedup_per_session:!1,advanced_enable_surveys:!1,advanced_disable_toolbar_metrics:!1,feature_flag_request_timeout_ms:3e3,surveys_request_timeout_ms:1e4,on_request_error(n){k.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:fo,before_send:void 0,get_current_url:void 0,request_queue_config:{flush_interval_ms:So},error_tracking:{},_onCapture:Si},(n=>({rageclick:n&&n>="2026-05-30"?{content_ignorelist:Op,ignore_text_selection:!0}:!n||"2025-11-30">n||{content_ignorelist:!0},capture_pageview:!n||"2025-05-24">n||"history_change",session_recording:n&&n>="2026-06-25"?{strictMinimumDuration:!0,canvasCapture:{resolutionScale:.6},streamNetworkBody:!0}:n&&n>="2026-05-30"?{strictMinimumDuration:!0,canvasCapture:{resolutionScale:.6}}:n&&n>="2025-11-30"?{strictMinimumDuration:!0}:{},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)}))(t))},If=[["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"]],Wl=t=>{var e={};for(var n of If){var r=n[0],i=n[1];x(t[r])||(e[i]=t[r])}var s=ee({},e,t),o=t.__preview_external_dependency_versioned_paths;return x(o)||(x(t.strict_script_versioning)&&(s.strict_script_versioning=!!o),W(o)&&x(t.asset_host)&&(s.asset_host=o)),L(t.property_blacklist)&&(x(t.property_denylist)?s.property_denylist=t.property_blacklist:L(t.property_denylist)?s.property_denylist=[...t.property_blacklist,...t.property_denylist]:k.error(wd+t.property_denylist)),s};class Cf{constructor(){this.__forceAllowLocalhost=!1}get fn(){return this.__forceAllowLocalhost}set fn(e){k.error("WebPerformanceObserver is deprecated and has no impact on network capture. Use `_forceAllowLocalhostNetworkCapture` on `posthog.sessionRecording`"),this.__forceAllowLocalhost=e}}class Te{pn(e,n){if(e){var r=this.sn.indexOf(e);r!==-1&&this.sn.splice(r,1)}return this.sn.push(n),n.initialize==null||n.initialize(),n}gn(){return this.config.cookieless_mode===gt||this.config.cookieless_mode===Vt&&this.consent.isRejected()}get decideEndpointWasHit(){var e,n;return(e=(n=this.featureFlags)==null?void 0:n.hasLoadedFlags)!==null&&e!==void 0&&e}get flagsEndpointWasHit(){var e,n;return(e=(n=this.featureFlags)==null?void 0:n.hasLoadedFlags)!==null&&e!==void 0&&e}constructor(){var e;this.webPerformance=new Cf,this.mn=!1,this.version=Y.LIB_VERSION,this.yn=new Set,this.bn="",this.dn=new ha,this.sn=[],this._n=[],this._calculate_event_properties=this.calculateEventProperties.bind(this),this.config=Ps(),this.SentryIntegration=qp,this.sentryIntegration=r=>(function(i,s){var o=qu(i,s);return{name:zu,processEvent:a=>o(a)}})(this,r),this.__request_queue=[],this.__loaded=!1,this.analyticsDefaultEndpoint="/e/",this.wn=!1,this.kn=null,this.xn=null,this.Sn=null,this.scrollManager=new pf(this),this.pageViewManager=new Fl(this),this.rateLimiter=new ef(this),this.requestRouter=new mf(this),this.consent=new Rp(this),this.externalIntegrations=new bf(this);var n=(e=Te.__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,i,s)=>{var o=W(r)?{[r]:i}:r;this.setPersonProperties(o),s?.({})},set_once:(r,i,s)=>{var o=W(r)?{[r]:i}:r;this.setPersonProperties(void 0,o),s?.({})}},this.on("eventCaptured",(r=>k.info('send "'+r?.event+'"',r)))}init(e,n,r){if(r&&r!==dn){var i,s=(i=nr[r])!==null&&i!==void 0?i:new Te;return s._init(e,n,r),nr[r]=s,nr[dn][r]=s,s}return this._init(e,n,r)}_init(e,n,r){var i,s;n===void 0&&(n={});var o,a=W(e)?e.trim():"";if(!a)return k.critical("PostHog was initialized without a token. This likely indicates a misconfiguration. Please check the first argument passed to posthog.init()"),this;if(this.__loaded)return a!==((o=this.config)==null?void 0:o.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('"+a+"', { ... }, 'project2')"):console.warn("[PostHog.js]","You have already initialized PostHog! Re-initializing is a no-op"),this;this.__loaded=!0,this.config=Ps(n.defaults),n.debug=this.Cn(n.debug),this.Mn=n,this.Tn=[],n.person_profiles?this.xn=n.person_profiles:n.process_person&&(this.xn=n.process_person);var l=Ps(n.defaults),u=Wl(n),c=ee({},l,u,{name:r,token:a});te(l.rageclick)&&te(u.rageclick)&&(c.rageclick=ee({},l.rageclick,u.rageclick)),te(l.session_recording)&&te(u.session_recording)&&(c.session_recording=ee({},l.session_recording,u.session_recording)),this.set_config(c),this.config.on_xhr_error&&k.error("on_xhr_error is deprecated. Use on_request_error instead"),this.compression=n.disable_compression?void 0:xe.GZipJS;var d=this.En();if(this.persistence=new Es(this.config,d),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new Es(E({},this.config,{persistence:"sessionStorage"}),d,!1),this.bn="ph_"+(this.config.persistence_name||this.config.token)+"_session_registered_properties",this.config.persistence!=="memory"&&!d&&ce.N()){var h=ce.H(this.bn);L(h)&&h.forEach((A=>{W(A)&&this.yn.add(A)}))}else ce.q(this.bn);var p=E({},this.persistence.props),f=E({},this.sessionPersistence.props);this.register({$initialization_time:new Date().toISOString()}),this.In=new uf((A=>this.Pn(A)),this.config.request_queue_config),this.Rn=new hf(this),this.__request_queue=[];var g=this.gn();if(g||(this.sessionManager=new Bl(this),this.sessionPropsManager=new Ol(this,this.sessionManager,this.persistence),this.sessionManager.onSessionId(((A,j,S)=>{(S!=null&&S.activityTimeout||S!=null&&S.sessionPastMaximumLength||S!=null&&S.crossTabAdoption)&&this.An()}))),this.Fn(),this.config.__preview_deferred_init_extensions?(k.info("Deferring extension initialization to improve startup performance"),setTimeout((()=>{this.Ln(g)}),0)):(k.info("Initializing extensions synchronously"),this.Ln(g)),Y.DEBUG=Y.DEBUG||this.config.debug,Y.DEBUG&&k.info("Starting in debug mode",{this:this,config:n,thisC:E({},this.config),p,s:f}),!this.config.identity_distinct_id||(i=n.bootstrap)!=null&&i.distinctID||(n.bootstrap=E({},n.bootstrap,{distinctID:this.config.identity_distinct_id,isIdentifiedID:!0})),((s=n.bootstrap)==null?void 0:s.distinctID)!==void 0){var m=n.bootstrap.distinctID,_=this.get_distinct_id(),w=this.persistence.get_property(He);if(n.bootstrap.isIdentifiedID&&_!=null&&_!==m&&w===sn)this.identify(m);else if(n.bootstrap.isIdentifiedID&&_!=null&&_!==m&&w===Ot)k.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{var b=this.config.get_device_id(ft()),I=n.bootstrap.isIdentifiedID?b:m;this.persistence.set_property(He,n.bootstrap.isIdentifiedID?Ot:sn),this.register({distinct_id:m,$device_id:I})}}if(g)this.register_once({distinct_id:Fr,$device_id:null},"");else if(!this.get_distinct_id()){var F=this.config.get_device_id(ft());this.register_once({distinct_id:F,$device_id:F},""),this.persistence.set_property(He,sn)}return ie(v,"onpagehide"in self?"pagehide":"unload",this._handle_unload.bind(this),{passive:!1}),n.segment?(function(A,j){var S=A.config.segment;if(!S)return j();(function(P,R){var M=P.config.segment;if(!M)return R();var T=J=>{var q=()=>J.anonymousId()||ft();P.config.get_device_id=q,J.id()&&(P.register({distinct_id:J.id(),$device_id:q()}),P.persistence.set_property(He,Ot)),R()},O=M.user();"then"in O&&Se(O.then)?O.then(T):T(O)})(A,(()=>{S.register((P=>{typeof Promise<"u"&&Promise.resolve||ws.warn("This browser does not have Promise support, and can not use the segment integration");var R=(M,T)=>{if(!T)return M;M.event.userId||M.event.anonymousId===P.get_distinct_id()||(ws.info("No userId set, resetting PostHog"),P.reset()),M.event.userId&&M.event.userId!==P.get_distinct_id()&&(ws.info("UserId set, identifying with PostHog"),P.identify(M.event.userId));var O=P.calculateEventProperties(T,M.event.properties);return M.event.properties=Object.assign({},O,M.event.properties),M};return{name:"PostHog JS",type:"enrichment",version:"1.0.0",isLoaded:()=>!0,load:()=>Promise.resolve(),track:M=>R(M,M.event.event),page:M=>R(M,un),identify:M=>R(M,vs),screen:M=>R(M,"$screen")}})(A)).then((()=>{j()}))}))})(this,(()=>this.On())):this.On(),Se(this.config._onCapture)&&this.config._onCapture!==Si&&(k.warn("onCapture is deprecated. Please use `before_send` instead"),this.on("eventCaptured",(A=>this.config._onCapture(A.event,A)))),this.config.ip&&k.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 fd.apply(this,arguments)})().then((A=>{A&&this.register({[gs]:A})})).catch(Si),this}Fn(){var e,n,r,i,s,o,a=(e=(n=this.config.__extensionClasses)==null?void 0:n.featureFlags)!==null&&e!==void 0?e:(r=Te.__defaultExtensionClasses)==null?void 0:r.featureFlags;a&&(this.featureFlags&&this.featureFlags instanceof a||((i=this.Dn)==null||i.call(this),this.Dn=void 0,this.featureFlags=new a(this)),Se(this.featureFlags.onReloading)&&Se(this.featureFlags.setup)?this.Dn||(this.Dn=this.featureFlags.onReloading((()=>{this.dn.emit("featureFlagsReloading",!0)})),this.$n().add(this.featureFlags)):(s=(o=this.featureFlags).initialize)==null||s.call(o))}Ln(e){var n,r,i,s,o,a,l,u=performance.now(),c=E({},Te.__defaultExtensionClasses,this.config.__extensionClasses),d=[];c.exceptions&&this.sn.push(this.exceptions=(n=this.exceptions)!==null&&n!==void 0?n:new c.exceptions(this)),c.historyAutocapture&&this.sn.push(this.historyAutocapture=new c.historyAutocapture(this)),c.tracingHeaders&&this.sn.push(this.tracingHeaders=new c.tracingHeaders(this)),c.siteApps&&this.sn.push(this.siteApps=new c.siteApps(this)),c.sessionRecording&&!e&&this.sn.push(this.sessionRecording=new c.sessionRecording(this)),this.config.disable_scroll_properties||d.push((()=>{this.scrollManager.startMeasuringScrollPosition()})),c.autocapture&&this.sn.push(this.autocapture=new c.autocapture(this)),c.surveys&&this.sn.push(this.surveys=(r=this.surveys)!==null&&r!==void 0?r:new c.surveys(this)),c.logs&&this.sn.push(this.logs=(i=this.logs)!==null&&i!==void 0?i:new c.logs(this)),c.metrics&&this.sn.push(this.metrics=(s=this.metrics)!==null&&s!==void 0?s:new c.metrics(this)),c.conversations&&this.sn.push(this.conversations=(o=this.conversations)!==null&&o!==void 0?o:new c.conversations(this)),c.productTours&&this.sn.push(this.productTours=new c.productTours(this)),c.heatmaps&&this.sn.push(this.heatmaps=new c.heatmaps(this)),c.webVitalsAutocapture&&this.sn.push(this.webVitalsAutocapture=new c.webVitalsAutocapture(this)),c.exceptionObserver&&this.sn.push(this.exceptionObserver=new c.exceptionObserver(this)),c.deadClicksAutocapture&&this.sn.push(this.deadClicksAutocapture=new c.deadClicksAutocapture(this,zp)),c.toolbar&&this.sn.push(this.toolbar=(a=this.toolbar)!==null&&a!==void 0?a:new c.toolbar(this)),c.experiments&&this.sn.push(this.experiments=(l=this.experiments)!==null&&l!==void 0?l:new c.experiments(this)),this.sn.forEach((h=>{h.initialize&&d.push((()=>{h.initialize==null||h.initialize()}))})),d.push((()=>{if(this.Nn){var h=this.Nn;this.Nn=void 0,this.sn.forEach((p=>p.onRemoteConfig==null?void 0:p.onRemoteConfig(h)))}})),this.qn(d,u)}qn(e,n){for(;e.length>0;){if(this.config.__preview_deferred_init_extensions&&performance.now()-n>=30&&e.length>0)return void setTimeout((()=>{this.qn(e,n)}),0);var r=e.shift();if(r)try{r()}catch(s){k.error("Error initializing extension:",s)}}var i=Math.round(performance.now()-n);this.register_for_session({[Fu]:this.config.__preview_deferred_init_extensions?"deferred":"synchronous",[Au]:i}),this.config.__preview_deferred_init_extensions&&k.info("PostHog extensions initialized ("+i+"ms)")}Zi(e){var n;if(!C||!C.body)return k.info("document not ready yet, trying again in 500 milliseconds..."),void setTimeout((()=>{this.Zi(e)}),500);if(this.config.__preview_deferred_init_extensions&&(this.Nn=e),this.hn=e,this.compression=void 0,e.ok){var r,i=e.config;i.supportedCompression&&!this.config.disable_compression&&(this.compression=N(i.supportedCompression,xe.GZipJS)?xe.GZipJS:N(i.supportedCompression,xe.Base64)?xe.Base64:void 0),(r=i.analytics)!=null&&r.endpoint&&(this.analyticsDefaultEndpoint=i.analytics.endpoint)}this.set_config({person_profiles:this.xn?this.xn:fo}),(n=this.jn)==null||n.handleRemoteConfig(e),this.sn.forEach((s=>s.onRemoteConfig==null?void 0:s.onRemoteConfig(e)))}On(){try{this.config.loaded(this)}catch(r){k.critical("`loaded` function failed",r)}if(this.Bn(),this.config.internal_or_test_user_hostname&&re!=null&&re.hostname){var e=re.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.gn())&&this.Hn()}),1),this.Un=new td(this),this.Un.load()}Bn(){var e;this.is_capturing()&&this.config.request_batching&&((e=this.In)==null||e.enable())}_dom_loaded(){this.is_capturing()&&Ar(this.__request_queue,(e=>this.Pn(e))),this.__request_queue=[],this.Bn()}_handle_unload(){var e,n,r,i,s;(e=this.surveys)==null||e.handlePageUnload==null||e.handlePageUnload(),(n=this.metrics)==null||n.flush("sendBeacon"),this.config.request_batching?(this.zn()&&this.capture(ms),(r=this.logs)==null||r.flushLogs("sendBeacon"),(i=this.In)==null||i.unload(),(s=this.Rn)==null||s.unload()):this.zn()&&this.capture(ms,null,{transport:"sendBeacon"})}_send_request(e){this.__loaded?bd?this.__request_queue.push(e):this.rateLimiter.isServerRateLimited(e.batchKey)?e.fireCallbackOnDrop&&(e.callback==null||e.callback({statusCode:429})):(e.transport=e.transport||this.config.api_transport,e.headers=E({},this.config.request_headers,e.headers),e.compression=e.compression==="best-available"?this.compression:e.compression,(x(this.config.disable_beacon)?this.config.__preview_disable_beacon:this.config.disable_beacon)&&(e.disableTransport=["sendBeacon"]),e.fetchOptions=e.fetchOptions||this.config.fetch_options,(n=>{var r,i,s,o=E({},n);o.timeout=o.timeout||6e4;var a,l,u,c,d,h=(r=o.transport)!==null&&r!==void 0?r:"fetch";h==="sendBeacon"&&x(o.compression)&&o.data&&(o.compression=xe.Base64),o.method==="POST"&&o.data&&(o.timestampMode==="capture-body"?o.data={api_key:(l=(d=(c=L(a=o.data)?a:[a])[0])==null||(u=d.properties)==null?void 0:u.token)!==null&&l!==void 0?l:d?.token,batch:c,sent_at:new Date().toISOString()}:o.timestampMode==="body"&&(o.data=(function(m,_){return _===void 0&&(_=new Date().toISOString()),L(m)?m.map((w=>E({},w,{sent_at:_}))):E({},m,{sent_at:_})})(o.data))),o.url=Ll(o.url,o.method,o.compression,o.timestampMode);var p=Kr.filter((m=>!o.disableTransport||!m.transport||!o.disableTransport.includes(m.transport))),f=(i=(s=(function(m,_){for(var w=0;m.length>w;w++)if(m[w].transport===h)return m[w]})(p))==null?void 0:s.method)!==null&&i!==void 0?i:p[0].method;if(!f)throw new Error("No available transport method");var g=m=>{try{f(m)}catch(_){dd(_)?k.warn(_):k.error(_),o.callback==null||o.callback({statusCode:0,error:_})}};h!=="sendBeacon"&&o.data&&o.compression===xe.GZipJS&&Ch&&typeof Promise<"u"&&!Gr?lf(o).then((m=>{g(m)})).catch((m=>{if(nl(m))return Gr=!0,void g(E({},o,{compression:void 0,url:Ll(n.url,n.method,void 0,n.timestampMode)}));(_=>{if(!_||typeof _!="object")return!1;var w="name"in _?String(_.name):"";return nl(_)||w===Uc})(m)&&(Gr=!0),g(o)})):f(o)})(E({},e,{callback:n=>{var r,i;this.rateLimiter.checkForLimiting(n),400>n.statusCode||(r=(i=this.config).on_request_error)==null||r.call(i,n),e.callback==null||e.callback(n)}}))):e.fireCallbackOnDrop&&(e.callback==null||e.callback({statusCode:0}))}Pn(e){this.Rn?this.Rn.retriableRequest(e):this._send_request(e)}_execute_array(e){As++;try{var n,r=[],i=[],s=[];Ar(e,(a=>{if(a)if(L(n=a[0]))s.push(a);else if(Se(a))try{a.call(this)}catch(l){k.error("Error executing queued PostHog call",a,l)}else L(a)&&n==="alias"?r.push(a):L(a)&&n.indexOf("capture")!==-1&&Se(this[n])?s.push(a):i.push(a)}));var o=function(a,l){Ar(a,(function(u){try{if(L(u[0])){var c=l;Z(u,(function(d){c=c[d[0]].apply(c,d.slice(1))}))}else l[u[0]].apply(l,u.slice(1))}catch(d){k.error("Error executing queued PostHog call",u,d)}}))};o(r,this),o(i,this),o(s,this)}finally{As--}}push(e){if(As>0&&L(e)&&W(e[0])){var n=Te.prototype[e[0]];Se(n)&&n.apply(this,e.slice(1))}else this._execute_array([e])}capture(e,n,r){var i,s,o,a,l;if(this.__loaded&&this.persistence&&this.sessionPersistence&&this.In){if(this.is_capturing())if(!x(e)&&W(e)){var u=!this.config.opt_out_useragent_filter&&this._is_bot();if(!u||this.config.__preview_capture_bot_pageviews){var c=r!=null&&r.skip_client_rate_limiting?void 0:this.rateLimiter.clientRateLimitContext();if(c==null||!c.isRateLimited){n!=null&&n.$current_url&&!W(n?.$current_url)&&(k.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.Wn||k.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&&this.sessionPersistence.update_campaign_params(),this.config.save_referrer&&this.sessionPersistence.update_referrer_info(),(this.config.save_campaign_params||this.config.save_referrer)&&this.persistence.set_initial_person_info();var d=new Date,h=r?.timestamp||d,p=al(r?.uuid,ft),f={uuid:p,event:e,properties:this.calculateEventProperties(e,n||{},h,p)};e===un&&this.config.__preview_capture_bot_pageviews&&u&&(f.event="$bot_pageview",f.properties.$browser_type="bot"),c&&(f.properties.$lib_rate_limit_remaining_tokens=c.remainingTokens);var g=e==="$feature_flag_called"&&f.properties.$feature_flag_has_experiment===!1&&this.get_property(ui)===!0;r?.$set&&!g&&(f.$set=r?.$set);var m=r?.$unset;m&&(f.$unset=m);var _,w,b,I=g?void 0:this.Vn(r?.$set_once,e!==pl,e===vs);if(I&&(f.$set_once=I),r!=null&&r._noTruncate||(s=this.config.properties_string_max_length,o=f,a=T=>W(T)?T.slice(0,s):T,l=new Set,f=(function T(O,J){if(O!==Object(O))return a?a(O):O;if(!l.has(O)){var q;if(l.add(O),L(O))q=[],Ar(O,(oe=>{q.push(T(oe))}));else{var H={};Z(O,((oe,fe)=>{l.has(oe)||(H[fe]=T(oe))})),q=H}return q}})(o)),f.timestamp=h,x(r?.timestamp)||(f.properties.$event_time_override_provided=!0,f.properties.$event_time_override_system_time=d),g&&(f.properties=(function(T,O){O===void 0&&(O=[]);var J={},q=H=>{T[H]!==void 0&&(J[H]=T[H])};return Fh.forEach(q),O.forEach(q),J})(f.properties,kf)),e===vt.DISMISSED||e===vt.SENT){var F=n?.[xs.SURVEY_ID],A=n?.[xs.SURVEY_ITERATION];yd({id:F,current_iteration:A}),f.$set=E({},f.$set,{[(_={id:F,current_iteration:A},w=e===vt.SENT?"responded":"dismissed",b="$survey_"+w+"/"+_.id,_.current_iteration&&_.current_iteration>0&&(b="$survey_"+w+"/"+_.id+"/"+_.current_iteration),b)]:!0})}else e===vt.SHOWN&&(f.$set=E({},f.$set,{[xs.SURVEY_LAST_SEEN_DATE]:new Date().toISOString()}));if(e===Qp.SHOWN){var j=n?.[Pl.TOUR_TYPE];j&&(f.$set=E({},f.$set,{[Pl.TOUR_LAST_SEEN_DATE+"/"+j]:new Date().toISOString()}))}var S=E({},f.properties.$set,f.$set);if(yt(S)||this.setPersonPropertiesForFlags(S),!B(this.config.before_send)){var P=this.Pt(f);if(!P)return;(f=P).uuid=al(f.uuid,ft)}this.dn.emit("eventCaptured",f);var R=(i=r?._url)!==null&&i!==void 0?i:this.requestRouter.endpointFor("api",this.analyticsDefaultEndpoint),M={method:"POST",url:R,data:f,compression:"best-available",timestampMode:r?._batchKey==="recordings"||/\/s\/(?:\?|$)/.test(R)?"body":"capture-body",batchKey:r?._batchKey,transport:r?.transport};return!this.config.request_batching||r&&(r==null||!r._batchKey)||r!=null&&r.send_instantly?this.Pn(M):this.In.enqueue(M),f}k.critical("This capture call is ignored due to client rate limiting.")}}else k.error("No event name provided to posthog.capture")}else k.uninitializedWarning("posthog.capture")}_addCaptureHook(e){return this.on("eventCaptured",(n=>e(n.event,n)))}$n(){var e;return(e=this.jn)!==null&&e!==void 0?e:this.jn=new xf(this)}cn(e){this._n.push(e);var n=!0;return()=>{if(n){n=!1;var r=this._n.indexOf(e);r!==-1&&this._n.splice(r,1)}}}calculateEventProperties(e,n,r,i,s){if(r=r||new Date,!this.persistence||!this.sessionPersistence)return n;var o=s?void 0:this.persistence.remove_event_timer(e),a=E({},n);if(a.token=this.config.token,a.$config_defaults=this.config.defaults,this.gn()&&(a[Cu]=!0),e==="$snapshot"){var l=E({},this.persistence.properties(),this.sessionPersistence.properties());return a.distinct_id=l.distinct_id,(!W(a.distinct_id)&&!he(a.distinct_id)||Gs(a.distinct_id))&&k.error("Invalid distinct_id for replay event. This indicates a bug in your implementation"),a}var u,c=(function(F,A,j,S){var P,R,M,T;if(S===void 0&&(S=!1),!Ae)return{};var O,J=F?[...En,...A||[]]:[],q=(function(xr){for(var je=0;sl.length>je;je++){var kr=sl[je],nn=kr[1],rn=kr[0].exec(xr),Rn=rn&&(Se(nn)?nn(rn,xr):nn);if(Rn)return Rn}return["",""]})(Ae),H=q[0],oe=q[1],fe=(O=typeof navigator<"u"?navigator:void 0)!=null&&O.brave?{brave:!0}:{},Ie={};x(j)||(Ie.detectGoogleSearchApp=j);var _e={},Ce=(P=navigator)==null||(P=P.userAgentData)==null?void 0:P.platform,Re=(R=navigator)==null?void 0:R.maxTouchPoints,ae=v==null||(M=v.screen)==null?void 0:M.width,me=v==null||(T=v.screen)==null?void 0:T.height,ge=v?.devicePixelRatio;x(Ce)||(_e.userAgentDataPlatform=Ce),x(Re)||(_e.maxTouchPoints=Re),x(ae)||(_e.screenWidth=ae),x(me)||(_e.screenHeight=me),x(ge)||(_e.devicePixelRatio=ge);var Qe,Lt,de,Ge,It,$n,De,Fe,Sr=ee(oa({$os:H,$os_version:oe,$browser:hu(Ae,navigator.vendor,fe,Ie),$device:ol(Ae),$device_type:(Lt=Ae,de=_e,Fe=ol(Lt),Fe===Kc||Fe===Gc||Fe==="Kobo"||Fe==="Kindle Fire"||Fe===au?_n:Fe===or||Fe===mn||Fe===ar||Fe===Js?"Console":Fe===Yc?"Wearable":Fe?Oe:de?.userAgentDataPlatform==="Android"&&((Ge=de?.maxTouchPoints)!==null&&Ge!==void 0?Ge:0)>0?600>Math.min((It=de?.screenWidth)!==null&&It!==void 0?It:0,($n=de?.screenHeight)!==null&&$n!==void 0?$n:0)/((De=de?.devicePixelRatio)!==null&&De!==void 0?De:1)?Oe:_n:"Desktop"),$timezone:ed(),$timezone_offset:Yp()}),{$current_url:ur(S?Pt(re?.href):re?.href,J,dr),$host:re?.host,$pathname:re?.pathname,$raw_user_agent:Ae.length>1e3?Ae.substring(0,997)+"...":Ae,$browser_version:Gh(Ae,navigator.vendor,fe,Ie),$browser_language:Al(),$browser_language_prefix:(Qe=Al(),typeof Qe=="string"?Qe.split("-")[0]:void 0),$screen_height:v?.screen.height,$screen_width:v?.screen.width,$viewport_height:v?.innerHeight,$viewport_width:v?.innerWidth,$lib:Y.LIB_NAME,$lib_version:Y.LIB_VERSION,$insert_id:Math.random().toString(36).substring(2,10)+Math.random().toString(36).substring(2,10),$time:Date.now()/1e3});return Y.SDK_DIST_CHANNEL&&(Sr.$sdk_dist_channel=Y.SDK_DIST_CHANNEL),Sr})(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){var d=this.sessionManager.checkAndGetSessionAndWindowId(s,r.getTime()),h=d.windowId;a.$session_id=d.sessionId,a.$window_id=h}this.sessionPropsManager&&ee(a,this.sessionPropsManager.getSessionProps());try{var p;this.sessionRecording&&ee(a,this.sessionRecording.sdkDebugProperties),a.$sdk_debug_retry_queue_size=(p=this.Rn)==null?void 0:p.length}catch(F){a.$sdk_debug_error_capturing_properties=String(F)}if(this.requestRouter.region===xo&&(a.$lib_custom_api_host=this.config.api_host),u=e!==un||s?e!==ms||s?this.pageViewManager.doEvent():this.pageViewManager.doPageLeave(r):this.pageViewManager.doPageView(r,i),a=ee(a,u),e===un&&C&&(a.title=C.title),!x(o)){var f=r.getTime()-o;a.$duration=parseFloat((f/1e3).toFixed(3))}Ae&&this.config.opt_out_useragent_filter&&(a.$browser_type=this._is_bot()?"bot":"browser");var g=this.persistence.properties(),m=this.sessionPersistence.properties();Z(["$referrer","$referring_domain"],(F=>{F in g&&delete m[F]}));var _={};if(this._n.length>0)for(var w of this._n.slice())try{ee(_,w())}catch(F){k.error("Failed to produce browser extension event properties",F)}(a=ee({},c,g,m,E({},_,a))).$is_identified=this._isIdentified(),L(this.config.property_denylist)?Z(this.config.property_denylist,(function(F){delete a[F]})):k.error(wd+this.config.property_denylist+" or property_blacklist config: "+this.config.property_blacklist);var b=this.config.sanitize_properties;b&&(k.error(Hl),a=b(a,e));var I=this.Zn();return a.$process_person_profile=I,I&&!s&&this.Gn("_calculate_event_properties"),a}Vn(e,n,r){var i;if(n===void 0&&(n=!0),r===void 0&&(r=!1),!this.persistence||!this.Zn()||this.mn&&!r)return e;var s=this.persistence.get_initial_props(),o=(i=this.sessionPropsManager)==null?void 0:i.getSetOnceProps(),a=ee({},s,o||{},e||{}),l=this.config.sanitize_properties;return l&&(k.error(Hl),a=l(a,"$set_once")),n&&(this.mn=!0),yt(a)?void 0:a}register(e,n){var r;(r=this.persistence)==null||r.register(e,n)}register_once(e,n,r){var i;(i=this.persistence)==null||i.register_once(e,n,r)}register_for_session(e){var n;(n=this.sessionPersistence)==null||n.register(e),Object.keys(e).forEach((r=>this.yn.add(r))),this.Qn()}unregister(e){var n;(n=this.persistence)==null||n.unregister(e)}unregister_for_session(e){var n;(n=this.sessionPersistence)==null||n.unregister(e),this.yn.delete(e),this.Qn()}Kn(e,n){this.register({[e]:n})}An(){this.yn.forEach((e=>{var n;(n=this.sessionPersistence)==null||n.unregister(e)})),this.yn.clear(),this.Qn()}Qn(){var e;if(this.bn)if(this.config.persistence==="memory"||(e=this.sessionPersistence)!=null&&e.xi||!ce.N())ce.q(this.bn);else{var n=[];this.yn.forEach((r=>n.push(r))),n.length>0?ce.F(this.bn,n):ce.q(this.bn)}}getFeatureFlag(e,n){var r;return(r=this.featureFlags)==null?void 0:r.getFeatureFlag(e,n)}getFeatureFlagPayload(e){var n;return(n=this.featureFlags)==null?void 0:n.getFeatureFlagPayload(e)}getFeatureFlagResult(e,n){var r;return(r=this.featureFlags)==null?void 0:r.getFeatureFlagResult(e,n)}getAllFeatureFlags(){var e,n;return(e=(n=this.featureFlags)==null?void 0:n.getAllFeatureFlags())!==null&&e!==void 0?e:[]}isFeatureEnabled(e,n){var r,i;return(r=(i=this.featureFlags)==null?void 0:i.isFeatureEnabled(e,n))!==null&&r!==void 0?r:n?.defaultValue}reloadFeatureFlags(){var e;(e=this.featureFlags)==null||e.reloadFeatureFlags()}updateFlags(e,n,r){var i;(i=this.featureFlags)==null||i.updateFlags(e,n,r)}updateEarlyAccessFeatureEnrollment(e,n,r){var i;(i=this.featureFlags)==null||i.updateEarlyAccessFeatureEnrollment(e,n,r)}getEarlyAccessFeatures(e,n,r){var i;return n===void 0&&(n=!1),(i=this.featureFlags)==null?void 0:i.getEarlyAccessFeatures(e,n,r)}on(e,n){return this.dn.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:jn}),()=>{})}onSessionId(e){var n,r;return(n=(r=this.sessionManager)==null?void 0:r.onSessionId(e))!==null&&n!==void 0?n:()=>{}}getSurveys(e,n){n===void 0&&(n=!1),this.surveys?this.surveys.getSurveys(e,n):e([],{isLoaded:!1,error:jn})}getActiveMatchingSurveys(e,n){n===void 0&&(n=!1),this.surveys?this.surveys.getActiveMatchingSurveys(e,n):e([],{isLoaded:!1,error:jn})}renderSurvey(e,n){var r;(r=this.surveys)==null||r.renderSurvey(e,n)}displaySurvey(e,n){var r;n===void 0&&(n=_f),(r=this.surveys)==null||r.displaySurvey(e,n)}cancelPendingSurvey(e){var n;(n=this.surveys)==null||n.cancelPendingSurvey(e)}canRenderSurvey(e){var n,r;return(n=(r=this.surveys)==null?void 0:r.canRenderSurvey(e))!==null&&n!==void 0?n:{visible:!1,disabledReason:jn}}canRenderSurveyAsync(e,n){var r,i;return n===void 0&&(n=!1),(r=(i=this.surveys)==null?void 0:i.canRenderSurveyAsync(e,n))!==null&&r!==void 0?r:Promise.resolve({visible:!1,disabledReason:jn})}Jn(e){return!e||Gs(e)?(k.critical("Unique user id has not been set in posthog.identify"),!1):e===Fr?(k.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())||(k.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 k.uninitializedWarning("posthog.identify");if(he(e)&&(e=e.toString(),k.warn("The first argument to posthog.identify was a number, but it should be a string. It has been converted to a string.")),this.Jn(e)&&this.Gn("posthog.identify")){var i=this.get_distinct_id();this.register({$user_id:e}),this.get_property(lr)||this.register_once({$had_persisted_distinct_id:!0,$device_id:i},""),e!==i&&e!==this.get_property(qn)&&(this.unregister(qn),this.register({distinct_id:e}));var s,o=(this.persistence.get_property(He)||sn)===sn,a=e!==i,l=!a&&o;if(a&&o)this.persistence.set_property(He,Ot),this.setPersonPropertiesForFlags({$set:n||{},$set_once:r||{}},!1),this.capture(vs,{distinct_id:e,$anon_distinct_id:i},{$set:n||{},$set_once:r||{}}),this.Sn=Fs(e,n,r),(s=this.featureFlags)==null||s.setAnonymousDistinctId(i);else if(l){this.persistence.set_property(He,Ot);var u=n||{},c=r||{};this.setPersonPropertiesForFlags({$set:u,$set_once:c},!1),this.capture("$set",{$set:u,$set_once:c}),this.Sn=Fs(e,n,r)}else(n||r)&&this.setPersonProperties(n,r);a?(this.reloadFeatureFlags(),this.featureFlags?this.featureFlags.resetFlagCallReported():this.unregister(Gt)):l&&(n||r)&&this.reloadFeatureFlags()}}setPersonProperties(e,n){if((e||n)&&this.Gn("posthog.setPersonProperties")){var r=Fs(this.get_distinct_id(),e,n);this.Sn!==r?(this.setPersonPropertiesForFlags({$set:e||{},$set_once:n||{}},!0),this.capture("$set",{$set:e||{},$set_once:n||{}}),this.Sn=r):k.info("A duplicate setPersonProperties call was made with the same properties. It has been ignored.")}}unsetPersonProperties(e){var n,r=(L(e)?e:[e]).filter((i=>W(i)&&i.length>0));r.length!==0&&this.Gn("posthog.unsetPersonProperties")&&((n=this.featureFlags)==null||n.unsetPersonPropertiesForFlags(r,!0),this.capture("$set",{$unset:r}),this.Sn=null)}group(e,n,r){if(e&&n){var i=this.getGroups(),s=i[e]!==n;if(s&&this.resetGroupPropertiesForFlags(e),this.register({$groups:E({},i,{[e]:n})}),s||r){var o={$group_type:e,$group_key:n};r&&(o.$group_set=r),this.capture(pl,o)}r&&this.setGroupPropertiesForFlags({[e]:r}),s&&!r&&this.reloadFeatureFlags()}else k.error("posthog.group requires a group type and group key")}resetGroups(){this.register({$groups:{}}),this.resetGroupPropertiesForFlags(),this.reloadFeatureFlags()}setPersonPropertiesForFlags(e,n){var r;n===void 0&&(n=!0),(r=this.featureFlags)==null||r.setPersonPropertiesForFlags(e,n)}resetPersonPropertiesForFlags(e){var n;e===void 0&&(e=!0),(n=this.featureFlags)==null||n.resetPersonPropertiesForFlags(e)}setGroupPropertiesForFlags(e,n){var r;n===void 0&&(n=!0),this.Gn("posthog.setGroupPropertiesForFlags")&&((r=this.featureFlags)==null||r.setGroupPropertiesForFlags(e,n))}resetGroupPropertiesForFlags(e){var n;(n=this.featureFlags)==null||n.resetGroupPropertiesForFlags(e)}reset(e){this.Yn(e)}Yn(e,n){var r,i,s,o,a,l,u,c,d,h;if(n===void 0&&(n=!1),k.info("reset"),!this.__loaded)return k.uninitializedWarning("posthog.reset");var p,f=this.get_property(lr),g=this.get_property(gs),m=this.get_property(Yt),_=this.is_capturing();if(this.consent.reset(),n||!_||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."),(r=this.persistence)==null||r.clear(),(i=this.sessionPersistence)==null||i.clear(),this.yn.clear(),this.Qn(),x(m)||(p=this.persistence)==null||p.register({[Yt]:m}),(s=this.surveys)==null||s.reset(),(o=this.Un)==null||o.stop(),(a=this.featureFlags)==null||a.reset(),(l=this.conversations)==null||l.reset(),(u=this.logs)==null||u.reset(),(c=this.metrics)==null||c.reset(),(d=this.persistence)==null||d.set_property(He,sn),(h=this.sessionManager)==null||h.resetSessionId(),this.Sn=null,this.config.cookieless_mode===gt)this.register_once({distinct_id:Fr,$device_id:null},"");else{var w=this.config.get_device_id(ft());this.register_once({distinct_id:w,$device_id:e?w:f},""),e||x(g)||this.register({[gs]:g})}this.register({$last_posthog_reset:new Date().toISOString()},1),delete this.config.identity_distinct_id,delete this.config.identity_hash,this.reloadFeatureFlags()}shutdown(e){var n=this;return X((function*(){var r,i,s,o,a,l,u;if(n.__loaded){(r=n.Un)==null||r.stop(),(i=n.jn)==null||i.dispose(),(s=n.sessionRecording)==null||s.dispose(),(o=n.logs)==null||o.flushLogs("sendBeacon"),(a=n.metrics)==null||a.flush("sendBeacon"),(l=n.In)==null||l.unload(),(u=n.Rn)==null||u.unload();try{var c;(c=n.featureFlags)==null||c.destroy()}catch(d){k.error("Error while destroying feature flags",d)}}else k.uninitializedWarning("posthog.shutdown")}))()}setIdentity(e,n){var r;this.config.identity_distinct_id=e,this.config.identity_hash=n,this.alias(e),(r=this.conversations)==null||r.Xn()}clearIdentity(){var e;delete this.config.identity_distinct_id,delete this.config.identity_hash,(e=this.conversations)==null||e.ts()}get_distinct_id(){return this.get_property("distinct_id")}getGroups(){return this.get_property("$groups")||{}}get_session_id(){var e,n;return(e=(n=this.sessionManager)==null?void 0:n.checkAndGetSessionAndWindowId(!0).sessionId)!==null&&e!==void 0?e:""}get_session_replay_url(e){if(!this.sessionManager)return"";var n=this.sessionManager.checkAndGetSessionAndWindowId(!0),r=n.sessionStartTimestamp,i=this.requestRouter.endpointFor("ui","/project/"+this.config.token+"/replay/"+n.sessionId);if(e!=null&&e.withTimestamp&&r){var s,o=(s=e.timestampLookBack)!==null&&s!==void 0?s:10;if(!r)return i;i+="?t="+Math.max(Math.floor((new Date().getTime()-r)/1e3)-o,0)}return i}alias(e,n){return e===this.get_property(bu)?(k.critical("Attempting to create alias for existing People user - aborting."),-2):this.Gn("posthog.alias")?(x(n)&&(n=this.get_distinct_id()),e!==n?(this.Kn(qn,e),this.capture("$create_alias",{alias:e,distinct_id:n})):(k.warn("alias matches current distinct_id - skipping api call."),this.identify(e),-1)):void 0}set_config(e){var n=E({},this.config);if(te(e)){var r,i,s,o,a,l,u,c,d,h,p,f;ee(this.config,Wl(e));var g=this.En();(r=this.persistence)==null||r.update_config(this.config,n,g),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new Es(E({},this.config,{persistence:"sessionStorage"}),g,!1);var m=this.Cn(this.config.debug);Ye(m)&&(this.config.debug=m),Ye(this.config.debug)&&(this.config.debug?(Y.DEBUG=!0,Q.N()&&Q.F("ph_debug",!0),k.info("set_config",{config:e,oldConfig:n,newConfig:E({},this.config)})):(Y.DEBUG=!1,Q.N()&&Q.q("ph_debug"))),(i=this.featureFlags)==null||i.updateConfig==null||i.updateConfig(this.config,this.Qi()),(s=this.exceptionObserver)==null||s.onConfigChange(),(o=this.exceptions)==null||o.onConfigChange(),(a=this.sessionRecording)==null||a.startIfEnabledOrStop(),(l=this.tracingHeaders)==null||l.startIfEnabledOrStop(),(u=this.autocapture)==null||u.startIfEnabled(),(c=this.heatmaps)==null||c.startIfEnabled(),(d=this.exceptionObserver)==null||d.startIfEnabledOrStop(),(h=this.deadClicksAutocapture)==null||h.startIfEnabledOrStop(),(p=this.surveys)==null||p.loadIfEnabled(),this.es(),(f=this.externalIntegrations)==null||f.startIfEnabledOrStop()}}_overrideSDKInfo(e,n){Y.LIB_NAME=e,Y.LIB_VERSION=n}startSessionRecording(e){var n,r,i,s,o,a=e===!0,l={sampling:a||!(e==null||!e.sampling),linked_flag:a||!(e==null||!e.linked_flag),url_trigger:a||!(e==null||!e.url_trigger),event_trigger:a||!(e==null||!e.event_trigger)};Object.values(l).some(Boolean)&&((n=this.sessionManager)==null||n.checkAndGetSessionAndWindowId(),l.sampling&&((r=this.sessionRecording)==null||r.overrideSampling()),l.linked_flag&&((i=this.sessionRecording)==null||i.overrideLinkedFlag()),l.url_trigger&&((s=this.sessionRecording)==null||s.overrideTrigger("url")),l.event_trigger&&((o=this.sessionRecording)==null||o.overrideTrigger("event"))),this.set_config({disable_session_recording:!1})}stopSessionRecording(){this.set_config({disable_session_recording:!0})}sessionRecordingStarted(){var e;return!((e=this.sessionRecording)==null||!e.started)}captureException(e,n){if(this.exceptions){var r=new Error("PostHog syntheticException"),i=this.exceptions.buildProperties(e,{handled:!0,syntheticException:r});return this.exceptions.sendExceptionEvent(E({},i,n))}}addExceptionStep(e,n){var r;(r=this.exceptions)==null||r.addExceptionStep(e,n)}captureLog(e){var n;(n=this.logs)==null||n.captureLog(e)}get logger(){var e,n;return(e=(n=this.logs)==null?void 0:n.logger)!==null&&e!==void 0?e:Te.rs}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?void 0:r.loadToolbar(e))!==null&&n!==void 0&&n}get_property(e){var n;return(n=this.persistence)==null?void 0:n.props[e]}getSessionProperty(e){var n;return(n=this.sessionPersistence)==null?void 0:n.props[e]}toString(){var e,n=(e=this.config.name)!==null&&e!==void 0?e:dn;return n!==dn&&(n=dn+"."+n),n}_isIdentified(){var e,n;return((e=this.persistence)==null?void 0:e.get_property(He))===Ot||((n=this.sessionPersistence)==null?void 0:n.get_property(He))===Ot}Zn(){var e,n;return!(this.config.person_profiles==="never"||this.config.person_profiles===fo&&!this._isIdentified()&&yt(this.getGroups())&&((e=this.persistence)==null||(e=e.props)==null||!e[qn])&&((n=this.persistence)==null||(n=n.props)==null||!n[pi]))}zn(){return this.config.capture_pageleave===!0||this.config.capture_pageleave==="if_capture_pageview"&&(this.config.capture_pageview===!0||this.config.capture_pageview==="history_change")}createPersonProfile(){this.Zn()||this.Gn("posthog.createPersonProfile")&&this.setPersonProperties({},{})}setInternalOrTestUser(){this.Gn("posthog.setInternalOrTestUser")&&this.setPersonProperties({$internal_or_test_user:!0})}Gn(e){return this.config.person_profiles==="never"?(k.error(e+' was called, but process_person is set to "never". This call will be ignored.'),!1):(this.Kn(pi,!0),!0)}En(){if(this.config.cookieless_mode==="always")return!0;var e=this.consent.isOptedOut();return this.config.disable_persistence||e&&!(!this.config.opt_out_persistence_by_default&&this.config.cookieless_mode!==Vt)}es(){var e,n,r,i,s=this.En();return((e=this.persistence)==null?void 0:e.xi)!==s&&((r=this.persistence)==null||r.set_disabled(s)),((n=this.sessionPersistence)==null?void 0:n.xi)!==s&&((i=this.sessionPersistence)==null||i.set_disabled(s)),s&&(this.yn.clear(),this.Qn()),s}opt_in_capturing(e){var n;if(this.config.cookieless_mode!==gt){if(this.gn()){var r,i,s,o,a;this.Yn(!0,!0),(r=this.sessionManager)==null||r.destroy(),(i=this.pageViewManager)==null||i.destroy(),this.sessionManager=new Bl(this),this.pageViewManager=new Fl(this),this.persistence&&(this.sessionPropsManager=new Ol(this,this.sessionManager,this.persistence));var l,u=(s=(o=this.config.__extensionClasses)==null?void 0:o.sessionRecording)!==null&&s!==void 0?s:(a=Te.__defaultExtensionClasses)==null?void 0:a.sessionRecording;u&&(this.sessionRecording=this.pn(this.sessionRecording,new u(this)),this.hn&&((l=this.sessionRecording)==null||l.onRemoteConfig==null||l.onRemoteConfig(this.hn)))}var c,d;this.consent.optInOut(!0),this.es(),this.Bn(),(n=this.sessionRecording)==null||n.startIfEnabledOrStop(),this.config.cookieless_mode==Vt&&((c=this.surveys)==null||c.loadIfEnabled()),(x(e?.captureEventName)||e!=null&&e.captureEventName)&&this.capture((d=e?.captureEventName)!==null&&d!==void 0?d:"$opt_in",e?.captureProperties,{send_instantly:!0}),this.config.capture_pageview&&this.Hn()}else k.warn(Ul)}opt_out_capturing(){var e,n,r;this.config.cookieless_mode!==gt?(this.config.cookieless_mode===Vt&&this.consent.isOptedIn()&&this.Yn(!0,!0),this.consent.optInOut(!1),this.es(),this.config.cookieless_mode===Vt&&(this.register({distinct_id:Fr,$device_id:null}),(e=this.sessionRecording)==null||e.stopRecording(),this.sessionRecording=void 0,(n=this.sessionManager)==null||n.destroy(),(r=this.pageViewManager)==null||r.destroy(),this.sessionManager=void 0,this.sessionPropsManager=void 0,this.config.capture_pageview&&this.Hn(),this.Bn())):k.warn(Ul)}has_opted_in_capturing(){return this.consent.isOptedIn()}has_opted_out_capturing(){return this.consent.isOptedOut()}get_explicit_consent_status(){var e=this.consent.consent;return e===1?"granted":e===0?"denied":"pending"}is_capturing(){return this.config.cookieless_mode===gt||(this.config.cookieless_mode===Vt?this.consent.isRejected()||this.consent.isOptedIn():!this.has_opted_out_capturing())}clear_opt_in_out_capturing(){this.consent.reset(),this.es()}_is_bot(){return ke?pd(ke,this.config.custom_blocked_useragents):void 0}Hn(){C&&(C.visibilityState==="visible"?this.wn||(this.wn=!0,this.capture(un,{title:C.title},{send_instantly:!0}),this.kn&&(C.removeEventListener(fi,this.kn),this.kn=null)):this.kn||(this.kn=this.Hn.bind(this),ie(C,fi,this.kn)))}debug(e){e===!1?(v?.console.log("You've disabled debug mode."),this.set_config({debug:!1})):(v?.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}))}Qi(){var e=this.Mn||{};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?(k.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,i,s,o){var a=r in n&&!B(n[r]),l=i in n&&!B(n[i]);return a?n[r]:!!l&&(o&&o.warn("Config field '"+i+"' is deprecated. Please use '"+r+"' instead. The old field will be removed in a future major version."),n[i])})(e,"advanced_disable_flags","advanced_disable_decide",0,k)}Pt(e){var n;if(B(this.config.before_send))return e;var r=Object.keys((n=e.properties)!==null&&n!==void 0?n:{}).filter(Nh),i=L(this.config.before_send)?this.config.before_send:[this.config.before_send],s=e;for(var o of i){if(s=o(s),B(s)){var a="Event '"+e.event+"' was rejected in beforeSend function";return Mh(e.event)?k.warn(a+". This can cause unexpected behavior."):k.info(a),null}s.properties&&!yt(s.properties)||k.warn("Event '"+e.event+"' has no properties after beforeSend function, this is likely an error.")}for(var l of r)if(s.properties&&B(s.properties[l]))return k.warn("Event '"+e.event+"' had its '"+l+"' property removed in a beforeSend function. This property is required for ingestion, so the event will be dropped."),null;return s}getPageViewId(){var e;return(e=this.pageViewManager.ui)==null?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)})}Cn(e){var n=Ye(e)&&!e,r=Q.N()&&Q.P("ph_debug")==="true";return!n&&(!!r||e)}}Te.__defaultExtensionClasses={},Te.rs=(()=>{var t=()=>{};return{trace:t,debug:t,info:t,warn:t,error:t,fatal:t}})(),(function(t,e){for(var n=0;e.length>n;n++)t.prototype[e[n]]=Sp(t.prototype[e[n]])})(Te,["identify"]);class zl{constructor(e){this.disabled=e===!1;var n=te(e)?e:{};this.thresholdPx=n.threshold_px||30,this.timeoutMs=n.timeout_ms||1e3,this.clickCount=n.click_count||3,this.clicks=[]}isRageClick(e,n,r){if(this.disabled)return!1;var i=this.clicks[this.clicks.length-1];if(i&&Math.abs(e-i.x)+Math.abs(n-i.y)r-i.timestamp){if(this.clicks.push({x:e,y:n,timestamp:r}),this.clicks.length===this.clickCount)return!0}else this.clicks=[{x:e,y:n,timestamp:r}];return!1}}var $s="$copy_autocapture",Rs=ne("[AutoCapture]");function Ts(t,e){return e.length>t?e.slice(0,t)+"...":e}function Ff(t){if(t.previousElementSibling)return t.previousElementSibling;var e=t;do e=e.previousSibling;while(e&&!$t(e));return e}function Af(t,e){var n,r,i=e.e,s=e.maskAllElementAttributes,o=e.maskAllText,a=e.elementAttributeIgnoreList,l=e.elementsChainAsString,u=e.disableCaptureUrlHashes;if(!$t(t))return{props:{}};for(var c=[t],d=new Set([t]),h=t;h.parentNode&&!Ne(h,"body")&&Ou>c.length;)if(Lu(h.parentNode)){var p=h.parentNode.host;if(d.has(p))break;d.add(p),c.push(p),h=p}else{if(!$t(h.parentNode)||d.has(h.parentNode))break;d.add(h.parentNode),c.push(h.parentNode),h=h.parentNode}var f,g,m=[],_={},w=!1,b=!1;if(Z(c,(S=>{var P=vo(S);if(Ne(S,"a")){var R=S.getAttribute("href");w=!!(P&&R&&er(R))&&(u?Pt(R):R)}N(vi(S),"ph-no-capture")&&(b=!0),m.push((function(T,O,J,q,H){H===void 0&&(H=!1);var oe=T.tagName.toLowerCase(),fe={tag_name:oe};la.indexOf(oe)>-1&&!J&&(fe.$el_text=oe.toLowerCase()==="a"||oe.toLowerCase()==="button"?Ts(1024,kl(T)):Ts(1024,cr(T)));var Ie=vi(T);Ie.length>0&&(fe.classes=Ie.filter((function(ae){return ae!==""}))),Z(T.attributes,(function(ae){var me;if((!Hu(T)||["name","id","class","aria-label"].indexOf(ae.name)!==-1)&&(q==null||!q.includes(ae.name))&&!O&&er(ae.value)&&(!W(me=ae.name)||me.substring(0,10)!=="_ngcontent"&&me.substring(0,7)!=="_nghost")){var ge=ae.value;ae.name==="class"&&(ge=aa(ge).join(" ")),fe["attr__"+ae.name]=Ts(1024,ae.name==="href"&&H?Pt(ge):ge)}}));for(var _e=1,Ce=1,Re=T;Re=Ff(Re);)_e++,Re.tagName===T.tagName&&Ce++;return fe.nth_child=_e,fe.nth_of_type=Ce,fe})(S,s,o,a,u));var M=(function(T){if(!vo(T))return{};var O={};return Z(T.attributes,(function(J){if(J.name&&J.name.indexOf("data-ph-capture-attribute")===0){var q=J.name.replace("data-ph-capture-attribute-",""),H=J.value;q&&H&&er(H)&&(O[q]=H)}})),O})(S);ee(_,M)})),b)return{props:{},explicitNoCapture:b};if(o||(m[0].$el_text=Ne(t,"a")||Ne(t,"button")?kl(t):cr(t)),w){var I,F;m[0].attr__href=w;var A=(I=_i(w))==null?void 0:I.host,j=v==null||(F=v.location)==null?void 0:F.host;A&&j&&A!==j&&(f=w)}return{props:ee({$event_type:i.type,$ce_version:1},l?{}:{$elements:m},{$elements_chain:(g=m,(function(S){return S.map((P=>{var R,M,T="";if(P.tag_name&&(T+=P.tag_name),P.attr_class)for(var O of(P.attr_class.sort(),P.attr_class))T+="."+O.replace(/"/g,"");var J=E({},P.text?{text:P.text}:{},{"nth-child":(R=P.nth_child)!==null&&R!==void 0?R:0,"nth-of-type":(M=P.nth_of_type)!==null&&M!==void 0?M:0},P.href?{href:P.href}:{},P.attr_id?{attr_id:P.attr_id}:{},P.attributes),q={};return Vr(J).sort(((H,oe)=>H[0].localeCompare(oe[0]))).forEach((H=>{var oe=H[1];return q[Il(H[0].toString())]=Il(oe.toString())})),(T+=":")+Vr(q).map((H=>H[0]+'="'+H[1]+'"')).join("")})).join(";")})((function(S){return S.map((P=>{var R,M,T={text:(R=P.$el_text)==null?void 0:R.slice(0,400),tag_name:P.tag_name,href:(M=P.attr__href)==null?void 0:M.slice(0,2048),attr_class:Hp(P),attr_id:P.attr__id,nth_child:P.nth_child,nth_of_type:P.nth_of_type,attributes:{}};return Vr(P).filter((O=>O[0].indexOf("attr__")===0)).forEach((O=>T.attributes[O[0]]=O[1])),T}))})(g)))},(n=m[0])!=null&&n.$el_text?{$el_text:(r=m[0])==null?void 0:r.$el_text}:{},f&&i.type==="click"?{$external_click_url:f}:{},_)}}var Un=ne("[ExceptionAutocapture]"),ql=()=>{},Pf=ne("[TracingHeaders]"),jt=ne("[Web Vitals]"),Vl=9e5,Gl="disabled",Kl="lazy_loading",Hn="awaiting_config",Nr="missing_config";ne("[SessionRecording]"),ne("[SessionRecording]");var ko="[SessionRecording]",ut=ne(ko),$f=ne("[Heatmaps]");function Ms(t){return te(t)&&"clientX"in t&&"clientY"in t&&he(t.clientX)&&he(t.clientY)}var Lr=ne("[Product Tours]"),Ns=t=>{var e;return!t.config.disable_product_tours&&!((e=t.persistence)==null||!e.get_property(ra))},Rf=["$set_once","$set"],et=ne("[SiteApps]"),Jl="Error while initializing PostHog app with config id ";function ln(t,e,n){if(B(t))return!1;switch(n){case"exact":return t===e;case"contains":var r=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/_/g,".").replace(/%/g,".*");return new RegExp(r,"i").test(t);case"regex":try{return new RegExp(e).test(t)}catch{return!1}default:return!1}}class Tf{constructor(e){this.ns=new ha,this.ss=(n,r)=>this.os(n,r)&&this.ls(n,r)&&this.us(n,r)&&this.hs(n,r),this.os=(n,r)=>r==null||!r.event||n?.event===r?.event,this._instance=e,this.ds=new Set,this.vs=new Set}init(){var e,n;x((e=this._instance)==null?void 0:e._addCaptureHook)||(n=this._instance)==null||n._addCaptureHook(((r,i)=>{this.on(r,i)}))}register(e){var n,r;if(!x((n=this._instance)==null?void 0:n._addCaptureHook)&&(e.forEach((o=>{var a,l;(a=this.vs)==null||a.add(o),(l=o.steps)==null||l.forEach((u=>{var c;(c=this.ds)==null||c.add(u?.event||"")}))})),(r=this._instance)!=null&&r.autocapture)){var i,s=new Set;e.forEach((o=>{var a;(a=o.steps)==null||a.forEach((l=>{l!=null&&l.selector&&s.add(l?.selector)}))})),(i=this._instance)==null||i.autocapture.setElementSelectors(s)}}on(e,n){var r;n!=null&&e.length!=0&&(this.ds.has(e)||this.ds.has(n.event))&&this.vs&&((r=this.vs)==null?void 0:r.size)>0&&this.vs.forEach((i=>{this.cs(n,i)&&this.ns.emit("actionCaptured",i.name)}))}fs(e){this.onAction("actionCaptured",(n=>e(n)))}cs(e,n){if(n?.steps==null)return!1;for(var r of n.steps)if(this.ss(e,r))return!0;return!1}onAction(e,n){return this.ns.on(e,n)}ls(e,n){if(n!=null&&n.url){var r,i=e==null||(r=e.properties)==null?void 0:r.$current_url;if(!i||typeof i!="string"||!ln(i,n.url,n.url_matching||"contains"))return!1}return!0}us(e,n){return!!this.ps(e,n)&&!!this.gs(e,n)&&!!this.ys(e,n)}ps(e,n){var r;if(n==null||!n.href)return!0;var i=this.bs(e);if(i.length>0)return i.some((a=>ln(a.href,n.href,n.href_matching||"exact")));var s,o=(e==null||(r=e.properties)==null?void 0:r.$elements_chain)||"";return!!o&&ln((s=o.match(/(?::|")href="(.*?)"/))?s[1]:"",n.href,n.href_matching||"exact")}gs(e,n){var r;if(n==null||!n.text)return!0;var i=this.bs(e);if(i.length>0)return i.some((u=>ln(u.text,n.text,n.text_matching||"exact")||ln(u.$el_text,n.text,n.text_matching||"exact")));var s,o,a,l=(e==null||(r=e.properties)==null?void 0:r.$elements_chain)||"";return!!l&&(s=(function(u){for(var c,d=[],h=/(?::|")text="(.*?)"/g;!B(c=h.exec(u));)d.includes(c[1])||d.push(c[1]);return d})(l),o=n.text,a=n.text_matching||"exact",s.some((u=>ln(u,o,a))))}ys(e,n){var r,i;if(n==null||!n.selector)return!0;var s=e==null||(r=e.properties)==null?void 0:r.$element_selectors;if(s!=null&&s.includes(n.selector))return!0;var o=(e==null||(i=e.properties)==null?void 0:i.$elements_chain)||"";if(n.selector_regex&&o)try{return new RegExp(n.selector_regex).test(o)}catch{return!1}return!1}bs(e){var n;return(e==null||(n=e.properties)==null?void 0:n.$elements)==null?[]:e?.properties.$elements}hs(e,n){return n==null||!n.properties||n.properties.length===0||md(n.properties.reduce(((r,i)=>{var s=L(i.value)?i.value.map(String):i.value!=null?[String(i.value)]:[];return r[i.key]={values:s,operator:i.operator||"exact"},r}),{}),e?.properties)}}class Mf{constructor(e){var n;this._s=[],this._instance=e,this.ws=new Map,this.ks=new Map,this.xs=new Map,(n=this._instance)==null||n.onSessionId==null||n.onSessionId((r=>this.Ss(r)))}Cs(e){return!1}Ms(){return null}Ts(e){}Es(){}Is(e,n){return!!e&&md(e.propertyFilters,n?.properties)}Ps(e,n){var r=new Map;return e.forEach((i=>{var s;(s=i.conditions)==null||(s=s[n])==null||(s=s.values)==null||s.forEach((o=>{if(o!=null&&o.name){var a=r.get(o.name)||[];a.push(i.id),r.set(o.name,a)}}))})),r}Rs(e,n,r){var i=(r===Ln.Activation?this.ws:this.ks).get(e),s=[];return this.As((o=>{s=o.filter((a=>i?.includes(a.id)))})),s.filter((o=>{var a,l=(a=o.conditions)==null||(a=a[r])==null||(a=a.values)==null?void 0:a.find((u=>u.name===e));return this.Is(l,n)}))}register(e){var n;x((n=this._instance)==null?void 0:n._addCaptureHook)||(this.Fs(e),this.Ls(e))}Ls(e){var n=e.filter((r=>{var i,s;return((i=r.conditions)==null?void 0:i.actions)&&((s=r.conditions)==null||(s=s.actions)==null||(s=s.values)==null?void 0:s.length)>0}));n.length!==0&&(this.Os==null&&(this.Os=new Tf(this._instance),this.Os.init(),this.Os.fs((r=>{this.onAction(r)}))),n.forEach((r=>{var i,s,o,a,l;r.conditions&&(i=r.conditions)!=null&&i.actions&&(s=r.conditions)!=null&&(s=s.actions)!=null&&s.values&&((o=r.conditions)==null||(o=o.actions)==null||(o=o.values)==null?void 0:o.length)>0&&((a=this.Os)==null||a.register(r.conditions.actions.values),(l=r.conditions)==null||(l=l.actions)==null||(l=l.values)==null||l.forEach((u=>{if(u&&u.name){var c=this.xs.get(u.name);c&&c.push(r.id),this.xs.set(u.name,c||[r.id])}})))})))}Fs(e){var n,r=e.filter((s=>{var o,a;return((o=s.conditions)==null?void 0:o.events)&&((a=s.conditions)==null||(a=a.events)==null||(a=a.values)==null?void 0:a.length)>0})),i=e.filter((s=>{var o,a;return((o=s.conditions)==null?void 0:o.cancelEvents)&&((a=s.conditions)==null||(a=a.cancelEvents)==null||(a=a.values)==null?void 0:a.length)>0}));r.length===0&&i.length===0||((n=this._instance)==null||n._addCaptureHook(((s,o)=>{this.onEvent(s,o)})),this.ws=this.Ps(e,Ln.Activation),this.ks=this.Ps(e,Ln.Cancellation))}onEvent(e,n){var r,i,s=this.Ds(),o=(n==null||(r=n.properties)==null?void 0:r.$survey_id)||(n==null||(i=n.properties)==null?void 0:i.$product_tour_id);if(o&&this.getActivatedIds().includes(o)){var a=this.$s(e,o);if(a==="consume")return s.info("event consumed activated item, removing it",{event:e,itemId:o}),void this.Ns([o]);if(a==="persist")return s.info("shown item promoted to persisted activation",{event:e,itemId:o}),this.qs(o),void this.js([o])}if(this.ks.has(e)){var l=this.Rs(e,n,Ln.Cancellation);l.length>0&&(s.info("cancel event matched, cancelling items",{event:e,itemsToCancel:l.map((c=>c.id))}),this.Ns(l.map((c=>c.id))),l.forEach((c=>this.Bs(c.id))))}if(this.ws.has(e)){s.info("event name matched",{event:e,eventPayload:n,items:this.ws.get(e)});var u=this.Rs(e,n,Ln.Activation);this.Hs(u.map((c=>c.id)))}}onAction(e){this.xs.has(e)&&this.Hs(this.xs.get(e)||[])}Hs(e){var n;if(e.length!==0){var r=!((n=this._instance)==null||n.get_session_id==null||!n.get_session_id()),i=[];for(var s of e)r&&this.Cs(s)?this.qs(s)&&this.Us(s):i.push(s);i.length>0&&(this._s=[...new Set([...this._s,...i])]),this.Ds().info("updating activated items",{activatedItems:this.getActivatedIds()})}}qs(e){this._s=this._s.filter((r=>r!==e));var n=this.zs();return!n.includes(e)&&(this.Ws([...n,e]),this.Vs(),!0)}Ns(e){var n=new Set(e);this._s=this._s.filter((s=>!n.has(s)));var r=this.Zs(),i=r.filter((s=>!n.has(s)));i.length!==r.length&&(this.Ws(i),i.length===0&&this.Gs()),this.js(e)}Qs(){var e,n=this.Ms();if(!n)return{};var r=(e=this._instance)==null||(e=e.persistence)==null?void 0:e.props[n];return r&&typeof r=="object"?r:{}}Us(e){if(this.Ms()){var n=this.Qs();this.Ts(E({},n,{[e]:Date.now()}))}}js(e){if(this.Ms()){var n=this.Qs(),r={},i=!1;for(var s of Object.entries(n)){var o=s[0],a=s[1];e.includes(o)?i=!0:r[o]=a}i&&(yt(r)?this.Es():this.Ts(r))}}Ks(){this.Ms()&&this.Es()}getActivationTimestamp(e){if(this.zs().includes(e)){var n=this.Qs()[e];return he(n)?n:void 0}}Zs(){var e,n=this.Js();return((e=this._instance)==null||(e=e.persistence)==null?void 0:e.props[n])||[]}zs(){var e,n,r=this.Zs();if(r.length===0)return[];var i=(e=this._instance)==null||(e=e.persistence)==null?void 0:e.props[this.Ys()],s=(n=this._instance)==null||n.get_session_id==null?void 0:n.get_session_id();return s&&i===s?r:[]}Vs(){var e,n=(e=this._instance)==null||e.get_session_id==null?void 0:e.get_session_id();n&&this.Xs(n)}Gs(){this.ta()}Ss(e){var n,r=(n=this._instance)==null||(n=n.persistence)==null?void 0:n.props[this.Ys()];if(r&&r!==e){var i=this.Zs(),s=this.Qs();i.length>0&&(this.Ws([]),i.filter((o=>he(s[o]))).forEach((o=>this.Bs(o)))),this.Gs(),this.Ks()}}getActivatedIds(){return[...new Set([...this.zs(),...this._s])].filter((e=>!this.ea(e)))}reset(){this._s=[],this.Zs().length>0&&this.Ws([]),this.Gs(),this.Ks()}getEventToItemsMap(){return this.ws}ia(){return this.Os}}class Nf extends Mf{constructor(e){super(e)}Js(){return lo}Ys(){return Wr}Ms(){return zr}Ts(e){var n;(n=this._instance)==null||(n=n.persistence)==null||n.register({[zr]:e})}Es(){var e;(e=this._instance)==null||(e=e.persistence)==null||e.unregister(zr)}Cs(e){var n,r;this.As((s=>{r=s.find((o=>o.id===e))}));var i=(n=r)==null||(n=n.appearance)==null?void 0:n.surveyPopupDelaySeconds;return he(i)&&i>0}ra(){return vt.SHOWN}As(e){var n;(n=this._instance)==null||n.getSurveys(e)}Bs(e){var n;(n=this._instance)==null||n.cancelPendingSurvey(e)}Ds(){return V}Ws(e){var n;(n=this._instance)==null||(n=n.persistence)==null||n.register({[lo]:e})}Xs(e){var n;(n=this._instance)==null||(n=n.persistence)==null||n.register({[Wr]:e})}ta(){var e;(e=this._instance)==null||(e=e.persistence)==null||e.unregister(Wr)}ea(){return!1}$s(e,n){var r;this.As((s=>{r=s.find((o=>o.id===n))}));var i=!r||(function(s){var o;return vd(s)&&!((o=s.conditions)==null||(o=o.events)==null||!o.repeatedActivation)||s.schedule==="always"})(r);return i?e===vt.SHOWN?"consume":"ignore":e===vt.SHOWN?"persist":e===vt.DISMISSED||e===vt.SENT?"consume":"ignore"}getSurveys(){return this.getActivatedIds()}getEventToSurveys(){return this.getEventToItemsMap()}}var Or="SDK is not enabled or survey functionality is not yet loaded",Yl="Disabled. Not loading surveys.",Lf=v!=null&&v.location?yi(v.location.hash,"__posthog")||yi(location.hash,"state"):null,Zl="_postHogToolbarParams",Xl=ne("[Toolbar]"),Ql=ne("[FeatureFlags]");class Of{constructor(e,n){n===void 0&&(n=!1),this.na=!1,this.update(e,n)}update(e,n){this.sa=((r,i)=>{var s,o,a,l;return{bootstrap:{featureFlags:(s=r.bootstrap)==null?void 0:s.featureFlags,featureFlagPayloads:(o=r.bootstrap)==null?void 0:o.featureFlagPayloads},remoteRequestsDisabled:i,featureFlagsDisabled:!!r.advanced_disable_feature_flags,onlyEvaluateSurveyFeatureFlags:!!r.advanced_only_evaluate_survey_feature_flags,deduplicateCallsPerSession:!!r.advanced_feature_flags_dedup_per_session,cacheTtlMs:r.feature_flag_cache_ttl_ms,requestTimeoutMs:r.feature_flag_request_timeout_ms,compression:r.disable_compression?"none":"base64",evaluationContexts:(a=(l=r.evaluation_contexts)!==null&&l!==void 0?l:r.evaluation_environments)!==null&&a!==void 0?a:[],flagKeys:L(r.flag_keys)?r.flag_keys:void 0}})(e,n),!e.evaluation_environments||e.evaluation_contexts||this.na||(Ql.warn("evaluation_environments is deprecated. Use evaluation_contexts instead. evaluation_environments will be removed in a future version."),this.na=!0),x(e.flag_keys)||L(e.flag_keys)||Ql.error("Invalid flag_keys found:",e.flag_keys,"Expected array of non-empty strings")}get(){return this.sa}}var ec=ne("[FeatureFlags]"),Ut=ne("[FeatureFlags]",{debugEnabled:!0}),Ls=`" failed. Feature flags didn't load in time.`,tc="connection_error",nc=t=>{for(var e={},n=0;t.length>n;n++)e[t[n]]=!0;return e},rc=t=>{var e={};for(var n of Vr(t||{})){var r=n[1];r&&(e[n[0]]=r)}return e},tt=ne("[Error tracking]"),ic="Refusing to render web experiment since the viewer is a likely bot",Bf={icontains:(t,e)=>e.toLowerCase().indexOf(t.toLowerCase())>-1,not_icontains:(t,e)=>e.toLowerCase().indexOf(t.toLowerCase())===-1,regex:(t,e)=>Ei(e,t),not_regex:(t,e)=>!Ei(e,t),exact:(t,e)=>e===t,is_not:(t,e)=>e!==t};class ye{get Ne(){return this._instance.config}constructor(e){var n=this;this.getWebExperimentsAndEvaluateDisplayLogic=function(r){r===void 0&&(r=!1),n.getWebExperiments((i=>{ye.aa("retrieved web experiments from the server"),n.oa=new Map,i.forEach((s=>{if(s.feature_flag_key){var o;n.oa&&(ye.aa("setting flag key ",s.feature_flag_key," to web experiment ",s),(o=n.oa)==null||o.set(s.feature_flag_key,s));var a=n._instance.getFeatureFlag(s.feature_flag_key);W(a)&&s.variants[a]&&n.la(s.name,a,s.variants[a].transforms)}else if(s.variants)for(var l in s.variants){var u=s.variants[l];ye.ua(u,n._instance)&&n.la(s.name,l,u.transforms)}}))}),r)},this._instance=e,this._instance.onFeatureFlags((r=>{this.onFeatureFlags(r)}))}initialize(){}onFeatureFlags(e){if(this._is_bot())ye.aa(ic);else if(!this.Ne.disable_web_experiments){if(B(this.oa))return this.oa=new Map,this.loadIfEnabled(),void this.previewWebExperiment();ye.aa("applying feature flags",e),e.forEach((n=>{var r;if(this.oa&&(r=this.oa)!=null&&r.has(n)){var i,s=this._instance.getFeatureFlag(n),o=(i=this.oa)==null?void 0:i.get(n);s&&o!=null&&o.variants[s]&&this.la(o.name,s,o.variants[s].transforms)}}))}}previewWebExperiment(){var e=ye.getWindowLocation();if(e!=null&&e.search){var n=bn(e?.search,"__experiment_id"),r=bn(e?.search,"__experiment_variant");n&&r&&(ye.aa("previewing web experiments "+n+" && "+r),this.getWebExperiments((i=>{this.ha(parseInt(n),r,i)}),!1,!0))}}loadIfEnabled(){this.Ne.disable_web_experiments||this.getWebExperimentsAndEvaluateDisplayLogic()}getWebExperiments(e,n,r){if(this.Ne.disable_web_experiments&&!r)return e([]);var i=this._instance.get_property("$web_experiments");if(i&&!n)return e(i);this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/web_experiments/?token="+this.Ne.token),method:"GET",timestampMode:"query",callback:s=>e(s.statusCode===200&&s.json&&s.json.experiments||[])})}ha(e,n,r){var i=r.filter((s=>s.id===e));i&&i.length>0&&(ye.aa("Previewing web experiment ["+i[0].name+"] with variant ["+n+"]"),this.la(i[0].name,n,i[0].variants[n].transforms))}static ua(e,n){return!B(e.conditions)&&ye.da(e,n)&&ye.va(e)}static da(e,n){var r;if(B(e.conditions)||B((r=e.conditions)==null?void 0:r.url))return!0;var i=ye.getWindowLocation();if(i){var s,o,a,l=Tu(n,i.href);return(s=e.conditions)==null||!s.url||Bf[(o=(a=e.conditions)==null?void 0:a.urlMatchType)!==null&&o!==void 0?o:"icontains"](e.conditions.url,l)}return!1}static getWindowLocation(){return v?.location}static va(e){var n;if(B(e.conditions)||B((n=e.conditions)==null?void 0:n.utm))return!0;var r=Ku();if(r.utm_source){var i,s,o,a,l,u,c,d,h=(i=e.conditions)==null||(i=i.utm)==null||!i.utm_campaign||((s=e.conditions)==null||(s=s.utm)==null?void 0:s.utm_campaign)==r.utm_campaign,p=(o=e.conditions)==null||(o=o.utm)==null||!o.utm_source||((a=e.conditions)==null||(a=a.utm)==null?void 0:a.utm_source)==r.utm_source,f=(l=e.conditions)==null||(l=l.utm)==null||!l.utm_medium||((u=e.conditions)==null||(u=u.utm)==null?void 0:u.utm_medium)==r.utm_medium,g=(c=e.conditions)==null||(c=c.utm)==null||!c.utm_term||((d=e.conditions)==null||(d=d.utm)==null?void 0:d.utm_term)==r.utm_term;return h&&f&&g&&p}return!1}static aa(e){for(var n=arguments.length,r=new Array(n>1?n-1:0),i=1;n>i;i++)r[i-1]=arguments[i];k.info("[WebExperiments] "+e,r)}la(e,n,r){this._is_bot()?ye.aa(ic):n!=="control"?r.forEach((i=>{if(i.selector){var s;ye.aa("applying transform of variant "+n+" for experiment "+e+" ",i);var o=(s=document)==null?void 0:s.querySelectorAll(i.selector);o?.forEach((a=>{var l=a;i.html&&(l.innerHTML=i.html),i.css&&l.setAttribute("style",i.css)}))}})):ye.aa("Control variants leave the page unmodified.")}_is_bot(){return ke&&this._instance?pd(ke,this.Ne.custom_blocked_useragents):void 0}}var Ue=ne("[Conversations]"),Ht="Conversations not available yet.",sc="console",Ed="__posthogHandledLogsRequestError",Os=(t,e)=>{var n=t instanceof Error?t:new Error(e);return n[Ed]=!0,n},oc=t=>!!t&&typeof t=="object"&&t[Ed]===!0,Ui={featureFlags:class{constructor(t){this.name="featureFlags",this.ca=!1,this.featureFlagEventHandlers=[],this.rt=ec,this.fa={},this.pa={},this.ga=[],this.ma=!1,this.ya=!1,this.ba=0,this._a=!1,this.wa=!1,this.ka=!1,this.xa=!1,this.Sa=0,this.Ca=()=>{var e=this.Ma();this.Sa=0,e&&this.reloadFeatureFlags()},"get"in t?this.Ta=t:(this.Ea=new Of(t.config,t.Qi()),this.Ta=this.Ea)}updateConfig(t,e){var n;(n=this.Ea)==null||n.update(t,e)}setup(t){return this.Ia=t,this.rt=t.logger.createLogger("[FeatureFlags]"),n=()=>{this.Ia===t&&(this.Ia=void 0,this.nn=t,this.Pa(t))},(e=t.kv.initialize())!=null&&e.then?e.then(n):n();var e,n}Pa(t){if(this.nn===t)return v&&ie(v,"online",this.Ca),this.Ra=t.registerDynamicEventProperties((()=>this.Aa()?this.fa:this.pa)),this.Fa(),this.initialize()}destroy(){v?.removeEventListener("online",this.Ca)}dispose(){var t;this.ba++,this.wa=!1,this.Ia=void 0,this.nn&&(this.La(),(t=this.Ra)==null||t.dispose(),this.Ra=void 0,this.ga=[],v?.removeEventListener("online",this.Ca),this.nn=void 0)}get Ne(){return this.Ta.get()}Oa(t){var e;return(e=this.nn)==null?void 0:e.kv.get(t)}F(t){this.Da((()=>{var e;return(e=this.nn)==null?void 0:e.kv.set(t)}))}q(t){this.Da((()=>{var e;return(e=this.nn)==null?void 0:e.kv.remove(t)}))}Da(t){try{t()}catch(e){this.rt.error("Failed to update feature flag persistence",e)}}Fa(){var t={};for(var e of[Gn,Kn,Hr,rt]){var n=this.Oa(e);x(n)||(t[e]=n)}this.fa=t;var r=E({},t),i=this.Oa(Wt);if(i)for(var s of Object.entries(i))r["$feature/"+s[0]]=s[1];this.pa=r}Aa(){var t=this.Ne.cacheTtlMs;if(!t||0>=t)return!1;var e=this.Oa(Qn);return typeof e!="number"||Date.now()-e>t}$a(){return!!this.Aa()&&(this.xa||this.ya||(this.xa=!0,this.rt.warn("Feature flag cache is stale, triggering refresh..."),this.reloadFeatureFlags()),!0)}Na(){var t=this.Ne.evaluationContexts;return t!=null&&t.length?t.filter((e=>{var n=e&&typeof e=="string"&&e.trim().length>0;return n||this.rt.error("Invalid evaluation context found:",e,"Expected non-empty string"),n})):[]}qa(){var t=this.Ne.flagKeys;if(!x(t))return t.filter((e=>{var n=e&&typeof e=="string"&&e.trim().length>0;return n||this.rt.error("Invalid flag key found:",e,"Expected non-empty string"),n}))}initialize(){var t,e,n=this.Ne,r=(t=(e=n.bootstrap)==null?void 0:e.featureFlags)!==null&&t!==void 0?t:{};if(Object.keys(r).length){var i,s,o=(i=(s=n.bootstrap)==null?void 0:s.featureFlagPayloads)!==null&&i!==void 0?i:{},a=Object.keys(r).filter((u=>!!r[u])).reduce(((u,c)=>(u[c]=r[c]||!1,u)),{}),l=Object.keys(o).filter((u=>a[u])).reduce(((u,c)=>(o[c]&&(u[c]=o[c]),u)),{});return this.ja({featureFlags:a,featureFlagPayloads:l})}}updateFlags(t,e,n){var r,i,s=n!=null&&n.merge&&(r=this.Oa(Wt))!==null&&r!==void 0?r:{},o=n!=null&&n.merge&&(i=this.Oa(Kn))!==null&&i!==void 0?i:{},a=E({},s,t),l=E({},o,e),u={};for(var c of Object.entries(a)){var d=c[0],h=c[1];u[d]={key:d,enabled:Xa(h),variant:Qa(h),reason:void 0,metadata:x(l?.[d])?void 0:{id:0,version:void 0,description:void 0,payload:l[d]}}}this.ja({flags:u})}get hasLoadedFlags(){return this.ma}getFlags(){return Object.keys(this.getFlagVariants())}getFlagsWithDetails(){var t=this.Oa(oo),e=this.Oa(rt),n=this.Oa(zt);if(!n&&!e)return t||{};var r=ee({},t||{}),i=[...new Set([...Object.keys(n||{}),...Object.keys(e||{})])];for(var s of i){var o,a,l=r[s],u=e?.[s],c=x(u)?(o=l?.enabled)!==null&&o!==void 0&&o:!!u,d=x(u)?l?.variant:typeof u=="string"?u:void 0,h=n?.[s],p=E({},l,{enabled:c,variant:c?d??l?.variant:void 0});c!==l?.enabled&&(p.original_enabled=l?.enabled),d!==l?.variant&&(p.original_variant=l?.variant),h&&(p.metadata=E({},l?.metadata,{payload:h,original_payload:l==null||(a=l.metadata)==null?void 0:a.payload})),r[s]=p}return this.ca||(this.rt.warn(" Overriding feature flag details!",{flagDetails:t,overriddenPayloads:n,finalDetails:r}),this.ca=!0),r}getAllFeatureFlags(){var t=this.getFlagVariants(),e=this.getFlagPayloads();return Object.keys(t).map((n=>{var r=t[n];return{key:n,enabled:Xa(r),variant:Qa(r),payload:Za(e[n])}}))}getFlagVariants(){var t=this.Oa(Wt),e=this.Oa(rt);if(!e)return t||{};for(var n=ee({},t||{}),r=Object.keys(e),i=0;r.length>i;i++)n[r[i]]=e[r[i]];return this.ca||(this.rt.warn(" Overriding feature flags!",{enabledFlags:t,overriddenFlags:e,finalFlags:n}),this.ca=!0),n}getFlagPayloads(){var t=this.Oa(Kn),e=this.Oa(zt);if(!e)return t||{};for(var n=ee({},t||{}),r=Object.keys(e),i=0;r.length>i;i++)n[r[i]]=e[r[i]];return this.ca||(this.rt.warn(" Overriding feature flag payloads!",{flagPayloads:t,overriddenPayloads:e,finalPayloads:n}),this.ca=!0),n}reloadFeatureFlags(){this._a||this.Ne.featureFlagsDisabled||this.Ma()||this.Ba||(this.ga.slice().forEach((t=>{try{t()}catch(e){this.rt.error("Error while running feature flags reloading callback",e)}})),this.Ba=setTimeout((()=>{this.Ha()}),5))}La(){clearTimeout(this.Ba),this.Ba=void 0}onReloading(t){return this.ga.push(t),()=>{this.ga=this.ga.filter((e=>e!==t))}}ensureFlagsLoaded(){this.ma||this.ya||this.Ba||this.reloadFeatureFlags()}setAnonymousDistinctId(t){this.$anon_distinct_id=t}setReloadingPaused(t){this._a=t}resetFlagCallReported(){this.q(Gt)}Ha(t){this.La();var e=this.nn;if(e&&!this.Ne.remoteRequestsDisabled&&!this.Ma())if(this.ya)this.wa=!0;else{var n={token:e.projectToken,distinct_id:e.distinctId,groups:e.groups,$anon_distinct_id:this.$anon_distinct_id,person_properties:E({},e.initialPersonProperties,this.Oa(ht)||{},{$lib:e.library.name,$lib_version:e.library.version}),group_properties:this.Oa(qt),timezone:ed()};x(e.deviceId)||(n.$device_id=e.deviceId),(t!=null&&t.disableFlags||this.Ne.featureFlagsDisabled)&&(n.disable_flags=!0);var r=this.Na();r.length&&(n.evaluation_contexts=r);var i=this.qa();x(i)||(n.flag_keys=i);var s=this.Ne.onlyEvaluateSurveyFeatureFlags,o="/flags/?v=2"+(s?"&only_evaluate_survey_feature_flags=true":""),a=this.ba;this.ya=!0;var l=()=>{this.wa&&(this.wa=!1,this.Ha())},u=c=>{this.ya=!1,a===this.ba&&(this.F({[qr]:[tc]}),this.rt.error("Feature flag request failed",c)),l()};try{e.sendRequest(o,{target:"flags",method:"POST",body:n,compression:this.Ne.compression==="base64"?xe.Base64:void 0,sentAt:"body",timeoutMs:this.Ne.requestTimeoutMs}).then((c=>{var d,h,p=(d=c.json)!==null&&d!==void 0?d:{},f=c.statusCode!==200;if(this.ya=!1,a===this.ba){if(this.Ua(c.statusCode),f||this.wa||(this.$anon_distinct_id=void 0),!n.disable_flags||this.wa){this.ka=!f;var g=[];c.error?g.push(c.error instanceof Error&&c.error.name==="AbortError"?"timeout":c.error instanceof Error?tc:"unknown_error"):c.statusCode!==200&&g.push("api_error_"+c.statusCode),p.errorsWhileComputingFlags&&g.push("errors_while_computing_flags");var m=!((h=p.quotaLimited)==null||!h.includes("feature_flags"));m&&g.push("quota_limited"),this.F({[qr]:g}),m?this.rt.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."):n.disable_flags||this.ja(p,f,{partialResponse:s}),l()}}else l()})).catch(u)}catch(c){u(c)}}}Ma(){return Vu(this.Sa,3)}Ua(t){this.Sa=Gu(t,this.Sa,3,(()=>this.rt.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===void 0&&(e={}),!e.fresh||this.ka)if(this.ma||this.getFlags()&&this.getFlags().length>0){if(!this.$a()){var r=this.getFeatureFlagResult(t,e);return(n=r?.variant)!==null&&n!==void 0?n:r?.enabled}}else this.rt.warn('getFeatureFlag for key "'+t+Ls)}getFeatureFlagDetails(t){return this.getFlagsWithDetails()[t]}getFeatureFlagPayload(t){var e=this.getFeatureFlagResult(t,{send_event:!1});return e?.payload}getFeatureFlagResult(t,e){if(e===void 0&&(e={}),!e.fresh||this.ka)if(this.ma||this.getFlags()&&this.getFlags().length>0){if(!this.$a()){var n,r=this.getFlagVariants(),i=t in r,s=r[t],o=this.getFlagPayloads()[t],a=String(s),l=this.Oa(Hr)||void 0,u=this.Oa(Qn)||void 0,c=this.Oa(Gt)||{};if(this.Ne.deduplicateCallsPerSession){var d,h=(d=this.nn)==null?void 0:d.session.sessionId,p=this.Oa(Yn);h&&h!==p&&(c={},n=h)}if(e.send_event||!("send_event"in e))if(t in c&&c[t].includes(a))n&&this.F({[Gt]:c,[Yn]:n});else{var f,g,m,_,w,b,I,F,A,j;L(c[t])?c[t].push(a):c[t]=[a],this.F(E({[Gt]:c},n?{[Yn]:n}:{}));var S=this.getFeatureFlagDetails(t),P=[...(f=this.Oa(qr))!==null&&f!==void 0?f:[]];x(s)&&P.push("flag_missing");var R={$feature_flag:t,$feature_flag_response:s,$feature_flag_payload:o||null,$feature_flag_request_id:l,$feature_flag_evaluated_at:u,$feature_flag_bootstrapped_response:((g=this.Ne.bootstrap)==null||(g=g.featureFlags)==null?void 0:g[t])||null,$feature_flag_bootstrapped_payload:((m=this.Ne.bootstrap)==null||(m=m.featureFlagPayloads)==null?void 0:m[t])||null,$used_bootstrap_value:!this.ka};x(S==null||(_=S.metadata)==null?void 0:_.has_experiment)||(R.$feature_flag_has_experiment=S.metadata.has_experiment),x(S==null||(w=S.metadata)==null?void 0:w.version)||(R.$feature_flag_version=S.metadata.version);var M,T=(b=S==null||(I=S.reason)==null?void 0:I.description)!==null&&b!==void 0?b:S==null||(F=S.reason)==null?void 0:F.code;T&&(R.$feature_flag_reason=T),S!=null&&(A=S.metadata)!=null&&A.id&&(R.$feature_flag_id=S.metadata.id),x(S?.original_variant)&&x(S?.original_enabled)||(R.$feature_flag_original_response=x(S.original_variant)?S.original_enabled:S.original_variant),S!=null&&(j=S.metadata)!=null&&j.original_payload&&(R.$feature_flag_original_payload=S==null||(M=S.metadata)==null?void 0:M.original_payload),P.length&&(R.$feature_flag_error=P.join(",")),this.za(R)}else n&&this.F({[Gt]:c,[Yn]:n});if(i)return{key:t,enabled:!!s,variant:typeof s=="string"?s:void 0,payload:Za(o)}}}else this.rt.warn('getFeatureFlagResult for key "'+t+Ls)}za(t){try{var e;(e=this.nn)==null||e.capture("$feature_flag_called",t).catch((n=>{this.rt.error("Failed to capture feature flag call",n)}))}catch(n){this.rt.error("Failed to capture feature flag call",n)}}getRemoteConfigPayload(t,e){this.Wa(t,e)}Wa(t,e){var n=this;return X((function*(){var r=n.nn;if(r){var i={distinct_id:r.distinctId,token:r.projectToken,person_properties:{$lib:r.library.name,$lib_version:r.library.version}},s=n.Na();s.length&&(i.evaluation_contexts=s);var o,a=n.qa();x(a)||(i.flag_keys=a);try{var l,u=(l=(yield r.sendRequest("/flags/?v=2",{target:"flags",method:"POST",body:i,compression:n.Ne.compression==="base64"?xe.Base64:void 0,sentAt:"body",timeoutMs:n.Ne.requestTimeoutMs})).json)==null?void 0:l.featureFlagPayloads;o=u?.[t]||void 0}catch(c){return void n.rt.error("Remote config feature flag request failed",c)}try{e(o)}catch(c){n.rt.error("Remote config feature flag callback failed",c)}}}))()}isFeatureEnabled(t,e){if(e===void 0&&(e={}),e.fresh&&!this.ka)return e.defaultValue;if(!(this.ma||this.getFlags()&&this.getFlags().length>0))return this.rt.warn('isFeatureEnabled for key "'+t+Ls),e.defaultValue;var n=this.getFeatureFlag(t,e);return x(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.ja(t,e,n)}ja(t,e,n){if(this.nn){this.ma=!0;var r=(function(i,s,o,a,l,u){s===void 0&&(s={}),o===void 0&&(o={}),a===void 0&&(a={}),u===void 0&&(u=ec);var c=((A,j)=>{var S=A.flags;return S?E({},A,{featureFlags:Object.fromEntries(Object.keys(S).map((P=>{var R;return[P,(R=S[P].variant)!==null&&R!==void 0?R:S[P].enabled]}))),featureFlagPayloads:Object.fromEntries(Object.keys(S).filter((P=>S[P].enabled)).filter((P=>{var R;return(R=S[P].metadata)==null?void 0:R.payload})).map((P=>{var R;return[P,(R=S[P].metadata)==null?void 0:R.payload]})))}):(A.featureFlags&&j.warn("Using an older version of the feature flags endpoint. Please upgrade your PostHog server to the latest version"),A)})(i,u),d=c.flags,h=c.featureFlags,p=c.featureFlagPayloads;if(h){var f=i.requestId,g=i.evaluatedAt;if(L(h)){u.warn("v1 of the feature flags endpoint is deprecated. Please use the latest version.");var m={};if(h)for(var _=0;h.length>_;_++)m[h[_]]=!0;return{[Gn]:h,[Wt]:m,[ui]:!1}}var w=h,b=p,I=d;if(l!=null&&l.partialResponse)w=E({},s,w),b=E({},o,b),I=E({},a,I);else if(i.errorsWhileComputingFlags)if(d){var F=new Set(Object.keys(d).filter((A=>{var j;return!((j=d[A])!=null&&j.failed)})));w=E({},s,Object.fromEntries(Object.entries(w).filter((A=>F.has(A[0]))))),b=E({},o,Object.fromEntries(Object.entries(b||{}).filter((A=>F.has(A[0]))))),I=E({},a,Object.fromEntries(Object.entries(I||{}).filter((A=>F.has(A[0])))))}else w=E({},s,w),b=E({},o,b),I=E({},a,I);return E({[Gn]:Object.keys(rc(w)),[Wt]:w||{},[Kn]:b||{},[oo]:I||{},[ui]:i.minimalFlagCalledEvents===!0},f?{[Hr]:f}:{},g?{[Qn]:g}:{})}})(t,this.getFlagVariants(),this.getFlagPayloads(),this.getFlagsWithDetails(),n,this.rt);r&&this.F(r),e||(this.xa=!1),this.Va(e)}}override(t,e){e===void 0&&(e=!1),this.rt.warn("override is deprecated. Please use overrideFeatureFlags instead."),this.overrideFeatureFlags({flags:t,suppressWarning:e})}overrideFeatureFlags(t){this.Za(t)}Za(t){if(this.nn){if(t===!1)return this.q([rt,zt]),this.Va(),void Ut.info("All overrides cleared");if(L(t))return this.F({[rt]:nc(t)}),this.Va(),void Ut.info("Flag overrides set",{flags:t});if(t&&typeof t=="object"&&("flags"in t||"payloads"in t)){var e,n=t;this.ca=!!((e=n.suppressWarning)!==null&&e!==void 0&&e);var r={},i=n.flags,s=n.payloads;return i&&(r[rt]=L(i)?nc(i):i),s&&(r[zt]=s),Object.keys(r).length&&this.F(r),i===!1&&s===!1?this.q([rt,zt]):i===!1?this.q(rt):s===!1&&this.q(zt),this.Va(),i===!1?Ut.info("Flag overrides cleared"):i&&Ut.info("Flag overrides set",{flags:i}),void(s===!1?Ut.info("Payload overrides cleared"):s&&Ut.info("Payload overrides set",{payloads:s}))}if(t&&typeof t=="object")return this.F({[rt]:t}),this.Va(),void Ut.info("Flag overrides set",{flags:t});this.rt.warn("Invalid overrideOptions provided to overrideFeatureFlags",{overrideOptions:t})}else this.rt.warn("posthog.featureFlags.overrideFeatureFlags called before feature flags were ready")}onFeatureFlags(t){if(this.addFeatureFlagsHandler(t),this.ma){var e=this.Ga(),n=e.flags,r=e.flagVariants;try{t(n,r)}catch(i){this.rt.error("Error while running feature flags callback",i)}}return()=>this.removeFeatureFlagsHandler(t)}updateEarlyAccessFeatureEnrollment(t,e,n){var r=(this.Oa(Ur)||[]).find((l=>l.flagKey===t)),i={["$feature_enrollment/"+t]:e},s={$feature_flag:t,$feature_enrollment:e,$set:i};r&&(s.$early_access_feature_name=r.name),n&&(s.$feature_enrollment_stage=n);var o=E({},this.getFlagVariants(),{[t]:e});this.F({[Gn]:Object.keys(rc(o)),[Wt]:o,[ht]:E({},this.Oa(ht)||{},i)}),this.Va();try{var a;(a=this.nn)==null||a.capture("$feature_enrollment_update",s).catch((l=>{this.rt.error("Failed to capture early access feature enrollment",l)}))}catch(l){this.rt.error("Failed to capture early access feature enrollment",l)}}getEarlyAccessFeatures(t,e,n){e===void 0&&(e=!1);var r=this.Oa(Ur);!r||e?this.Qa(t,n):t(r)}Qa(t,e){var n=this;return X((function*(){var r=n.nn;if(r){var i,s=e?"&"+e.map((a=>"stage="+a)).join("&"):"";try{var o=yield r.sendRequest("/api/early_access_features/?token="+r.projectToken+s,{target:"api",method:"GET",sentAt:"query"});if(!o.json)return;n.F({[Ur]:i=o.json.earlyAccessFeatures})}catch(a){return void n.rt.error("Early access feature request failed",a)}try{t(i)}catch(a){n.rt.error("Early access feature callback failed",a)}}}))()}Ga(){var 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)),{})}}Va(t){this.Fa();var e=this.Ga(),n=e.flags,r=e.flagVariants;this.featureFlagEventHandlers.forEach((i=>{try{i(n,r,{errorsLoading:t})}catch(s){this.rt.error("Error while running feature flags callback",s)}}))}setPersonPropertiesForFlags(t,e){e===void 0&&(e=!0),this.Ka(t,e)}Ka(t,e){e===void 0&&(e=!0);var n=this.Oa(ht)||{},r=t?.$set||(t!=null&&t.$set_once?{}:t),i=t?.$set_once,s={};if(i)for(var o in i)({}).hasOwnProperty.call(i,o)&&(o in n||(s[o]=i[o]));this.F({[ht]:E({},n,s,r)}),e&&this.reloadFeatureFlags()}unsetPersonPropertiesForFlags(t,e){e===void 0&&(e=!0);var n=E({},this.Oa(ht)||{});t.forEach((r=>{delete n[r]})),this.F({[ht]:n}),e&&this.reloadFeatureFlags()}resetPersonPropertiesForFlags(t){t===void 0&&(t=!0),this.q(ht),t&&this.reloadFeatureFlags()}setGroupPropertiesForFlags(t,e){e===void 0&&(e=!0);var n=this.Oa(qt)||{},r=E({},n);for(var i of Object.keys(t))r[i]=E({},n[i],t[i]);this.F({[qt]:r}),e&&this.reloadFeatureFlags()}resetGroupPropertiesForFlags(t){if(t){var e=this.Oa(qt)||{};this.F({[qt]:E({},e,{[t]:{}})})}else this.q(qt)}reset(){this.ba++,this.wa=!1,this.Fa(),this.ma=!1,this._a=!1,this.ka=!1,this.$anon_distinct_id=void 0,this.La(),this.ca=!1,this.Sa=0}}},Df={sessionRecording:class{get Ne(){return this._instance.config}get Mr(){return this._instance.persistence}get started(){var t;return!((t=this.Ja)==null||!t.isStarted)}get status(){var t,e;return this.Ya===Hn||this.Ya===Nr?this.Ya:(t=(e=this.Ja)==null?void 0:e.status)!==null&&t!==void 0?t:this.Ya}constructor(t){if(this._forceAllowLocalhostNetworkCapture=!1,this.Ya=Gl,this.Xa=void 0,this.eo=!1,this.io=(()=>{var e;if(C==null||!C.visibilityState||C.visibilityState==="visible")return!0;var n=v==null||(e=v.performance)==null||e.getEntriesByType==null?void 0:e.getEntriesByType("visibility-state");return!(n!=null&&n.length)||n.some((r=>r.name==="visible"))})(),this.Ie=()=>{var e;C?.visibilityState==="visible"&&(this.io=!0,(e=this.Ja)==null||e.setDocumentWasEverVisible==null||e.setDocumentWasEverVisible(!0))},this._instance=t,!this._instance.sessionManager)throw ut.error("started without valid sessionManager"),new Error(ko+" started without valid sessionManager. This is a bug.");if(this.Ne.cookieless_mode===gt)throw new Error(ko+' cannot be used with cookieless_mode="always"');C!=null&&C.addEventListener&&ie(C,"visibilitychange",this.Ie)}initialize(){this.startIfEnabledOrStop()}dispose(){this.eo=!0,C==null||C.removeEventListener==null||C.removeEventListener("visibilitychange",this.Ie),this.stopRecording()}get ro(){var t,e=!((t=this._instance.get_property(Yt))==null||!t.enabled),n=!this.Ne.disable_session_recording,r=this.Ne.disable_session_recording||this._instance.consent.isOptedOut();return v&&e&&n&&!r}startIfEnabledOrStop(t){var e;if(!(this.eo||this.ro&&(e=this.Ja)!=null&&e.isStarted)){var n=!x(Object.assign)&&!x(Array.from);this.ro&&n?(this.no(t),ut.info("starting")):(this.Ya=Gl,this.stopRecording())}}no(t){var e,n,r;this.ro&&(this.Ya!==Hn&&this.Ya!==Nr&&(this.Ya=Kl),$!=null&&(e=$.__PosthogExtensions__)!=null&&(e=e.rrweb)!=null&&e.record&&(n=$.__PosthogExtensions__)!=null&&n.initSessionRecording?this.so(t):(r=$.__PosthogExtensions__)==null||r.loadExternalDependency==null||r.loadExternalDependency(this._instance,this.ao,(i=>{if(i)return ut.error("could not load recorder",i);this.so(t)})))}stopRecording(){var t,e;(t=this.Xa)==null||t.call(this),this.Xa=void 0,(e=this.Ja)==null||e.stop()}oo(){var t,e;(t=this.Xa)==null||t.call(this),this.Xa=void 0,(e=this.Ja)==null||e.discard()}lo(){var t,e;(t=this.Mr)==null||t.unregister(ia),(e=this.Mr)==null||e.unregister(Eu)}uo(t,e){if(B(t))return null;var n,r=he(t)?t:parseFloat(t);return typeof(n=r)!="number"||!Number.isFinite(n)||0>n||n>1?(ut.warn(e+" must be between 0 and 1. Ignoring invalid value:",t),null):r}ho(t){if(this.Mr){var e,n,r=this.Mr,i=()=>{var s,o=t.sessionRecording===!1?void 0:t.sessionRecording,a=this.uo((s=this.Ne.session_recording)==null?void 0:s.sampleRate,"session_recording.sampleRate"),l=this.uo(o?.sampleRate,"remote config sampleRate"),u=a??l;B(u)&&this.lo();var c=o?.minimumDurationMilliseconds;r.register({[Yt]:E({cache_timestamp:Date.now(),enabled:!!o},o,{networkPayloadCapture:E({capturePerformance:t.capturePerformance},o?.networkPayloadCapture),canvasRecording:{enabled:o?.recordCanvas,fps:o?.canvasFps,quality:o?.canvasQuality},sampleRate:u,minimumDurationMilliseconds:x(c)?null:c,endpoint:o?.endpoint,triggerMatchType:o?.triggerMatchType,masking:o?.masking,urlTriggers:o?.urlTriggers,version:o?.version,triggerGroups:o?.triggerGroups})})};i(),(e=this.Xa)==null||e.call(this),this.Xa=(n=this._instance.sessionManager)==null?void 0:n.onSessionId(i)}}onRemoteConfig(t){var e=t.ok?t.config:void 0;return e&&"sessionRecording"in e?e.sessionRecording===!1?(this.ho(e),void this.oo()):(this.ho(e),void this.startIfEnabledOrStop()):(this.Ya===Hn&&(this.Ya=Nr,ut.warn("config refresh failed, recording will not start until page reload")),void this.startIfEnabledOrStop())}log(t,e){var n;e===void 0&&(e="log"),(n=this.Ja)!=null&&n.log?this.Ja.log(t,e):ut.warn("log called before recorder was ready")}get ao(){var t,e,n=(t=this._instance)==null||(t=t.persistence)==null?void 0:t.get_property(Yt);return(n==null||(e=n.scriptConfig)==null?void 0:e.script)||"lazy-recorder"}do(){var t,e=this._instance.get_property(Yt);if(!e)return!1;try{t=typeof e=="object"?e:JSON.parse(e)}catch(n){return ut.warn("persisted remote config for session recording is invalid and will be ignored",n),!1}return!B(t.cache_timestamp)&&36e5>=Date.now()-t.cache_timestamp}so(t){var e,n,r;if(!this.eo){if((e=$.__PosthogExtensions__)==null||!e.initSessionRecording)return ut.warn("Called on script loaded before session recording is available. This can be caused by adblockers."),void this._instance.register_for_session({[Pu]:!0});var i;if(this.Ja||(this.Ja=(i=$.__PosthogExtensions__)==null?void 0:i.initSessionRecording(this._instance,this.io),this.Ja._forceAllowLocalhostNetworkCapture=this._forceAllowLocalhostNetworkCapture),!this.do())return this.Ya===Nr||this.Ya===Hn?void 0:(this.Ya=Hn,ut.info("persisted remote config is stale, requesting fresh config before starting"),void new td(this._instance).load());this.Ya=Kl,(n=(r=this.Ja).setDocumentWasEverVisible)==null||n.call(r,this.io),this.Ja.start(t)}}onRRwebEmit(t){var e;(e=this.Ja)==null||e.onRRwebEmit==null||e.onRRwebEmit(t)}overrideLinkedFlag(){var t,e;this.Ja||(e=this.Mr)==null||e.register({[xu]:!0}),(t=this.Ja)==null||t.overrideLinkedFlag()}overrideSampling(){var t,e;this.Ja||(e=this.Mr)==null||e.register({[Su]:!0}),(t=this.Ja)==null||t.overrideSampling()}overrideTrigger(t){var e,n;this.Ja||(n=this.Mr)==null||n.register({[t==="url"?ku:Iu]:!0}),(e=this.Ja)==null||e.overrideTrigger(t)}get sdkDebugProperties(){var t;return((t=this.Ja)==null?void 0:t.sdkDebugProperties)||{$recording_status:this.status}}tryAddCustomEvent(t,e){var n;return!((n=this.Ja)==null||!n.tryAddCustomEvent(t,e))}}},jf={autocapture:class{constructor(t){this.vo=!1,this.co=null,this.fo=!1,this.po=!1,this.instance=t,this.rageclicks=new zl(t.config.rageclick),this.mo=null}initialize(){this.startIfEnabled()}get Ne(){var t,e,n=te(this.instance.config.autocapture)?this.instance.config.autocapture:{};return n.url_allowlist=(t=n.url_allowlist)==null?void 0:t.map((r=>new RegExp(r))),n.url_ignorelist=(e=n.url_ignorelist)==null?void 0:e.map((r=>new RegExp(r))),n}yo(){if(this.isBrowserSupported()){if(v&&C){var t=n=>{n=n||v?.event;try{this.bo(n)}catch(r){Rs.error("Failed to capture event",r)}};if(ie(C,"submit",t,{capture:!0}),ie(C,"change",t,{capture:!0}),ie(C,"click",t,{capture:!0}),this.Ne.capture_copied_text){var e=n=>{n=n||v?.event;try{this.bo(n,$s)}catch(r){Rs.error("Failed to capture copy/cut event",r)}};ie(C,"copy",e,{capture:!0}),ie(C,"cut",e,{capture:!0})}}}else Rs.info("Disabling Automatic Event Collection because this browser is not supported")}startIfEnabled(){this.isEnabled&&!this.vo&&(this.yo(),this.vo=!0)}onRemoteConfig(t){if(this.fo=!0,t.ok){var e=t.config;e.elementsChainAsString&&(this.po=e.elementsChainAsString);var n=e.autocapture_opt_out;Ye(n)&&(this.instance.persistence&&this.instance.persistence.register({[Qs]:n}),this.co=n),this.startIfEnabled()}else this.startIfEnabled()}setElementSelectors(t){this.mo=t}getElementSelectors(t){var e,n=[];return(e=this.mo)==null||e.forEach((r=>{var i=C?.querySelectorAll(r);i?.forEach((s=>{t===s&&n.push(r)}))})),n}get isEnabled(){var t,e,n=(t=this.instance.persistence)==null?void 0:t.props[Qs],r=this.co,i=this.instance.Qi()&&!this.fo;if($e(r)&&!Ye(n)&&!i)return!1;var s=(e=this.co)!==null&&e!==void 0?e:!!n;return!!this.instance.config.autocapture&&!s}bo(t,e){if(e===void 0&&(e="$autocapture"),this.isEnabled){var n,r=ys(t);Nu(r)&&(r=r.parentNode||null),e==="$autocapture"&&t.type==="click"&&t instanceof MouseEvent&&this.instance.config.rageclick&&(n=this.rageclicks)!=null&&n.isRageClick(t.clientX,t.clientY,t.timeStamp||new Date().getTime())&&wl(r,this.instance.config.rageclick)&&this.bo(t,"$rageclick");var i=e===$s;if(r&&(function(d,h,p,f,g,m){var _;if(!v||ca(d)||p!=null&&p.url_allowlist&&!vl(p.url_allowlist,m)||p!=null&&p.url_ignorelist&&vl(p.url_ignorelist,m))return!1;if(p!=null&&p.dom_event_allowlist){var w=p.dom_event_allowlist;if(w&&!w.some((S=>h.type===S)))return!1}var b=Uu(d,f),I=b.parentIsUsefulElement,F=b.targetElementList;if(!(function(S,P){var R=P?.element_allowlist;if(x(R))return!0;var M,T=function(J){if(R.some((q=>J.tagName.toLowerCase()===q)))return{v:!0}};for(var O of S)if(M=T(O))return M.v;return!1})(F,p)||!mo(F,p?.css_selector_allowlist)||mo(F,(_=p?.css_selector_ignorelist)!==null&&_!==void 0?_:Lp))return!1;try{var A=v.getComputedStyle(d);if(A&&A.getPropertyValue("cursor")==="pointer"&&h.type==="click")return!0}catch{}var j=d.tagName.toLowerCase();switch(j){case"html":return!1;case"form":return(g||["submit"]).indexOf(h.type)>=0;case"input":case"select":case"textarea":return(g||["change","click"]).indexOf(h.type)>=0;default:return I?(g||["click"]).indexOf(h.type)>=0:(g||["click"]).indexOf(h.type)>=0&&(la.indexOf(j)>-1||d.getAttribute("contenteditable")==="true")}})(r,t,this.Ne,i,i?["copy","cut"]:void 0,this.instance)){var s=Af(r,{e:t,maskAllElementAttributes:this.instance.config.mask_all_element_attributes,maskAllText:this.instance.config.mask_all_text,elementAttributeIgnoreList:this.Ne.element_attribute_ignorelist,elementsChainAsString:this.po,disableCaptureUrlHashes:this.instance.config.disable_capture_url_hashes}),o=s.props;if(s.explicitNoCapture)return!1;var a=this.getElementSelectors(r);if(a&&a.length>0&&(o.$element_selectors=a),e===$s){var l,u=Bu(v==null||(l=v.getSelection())==null?void 0:l.toString()),c=t.type||"clipboard";if(!u)return!1;o.$selected_content=u,o.$copy_type=c}return this.instance.capture(e,o),!0}}}isBrowserSupported(){return Se(C?.querySelectorAll)}},historyAutocapture:class{constructor(t){var e;this._instance=t,this._o=(v==null||(e=v.location)==null?void 0:e.pathname)||""}initialize(){this.startIfEnabled()}get isEnabled(){return this._instance.config.capture_pageview==="history_change"}startIfEnabled(){this.isEnabled&&(k.info("History API monitoring enabled, starting..."),this.monitorHistoryChanges())}stop(){this.wo&&this.wo(),this.wo=void 0,k.info("History API monitoring stopped")}monitorHistoryChanges(){v&&v.history&&(this.ko("pushState"),this.ko("replaceState"),this.xo())}ko(t){var e;if(v&&((e=v.history[t])==null||!e.__posthog_wrapped__)){var n=this;(function(r,i,s){try{if(!(i in r))return ql;var o={next:r[i]},a=s((function(){for(var l=arguments.length,u=new Array(l),c=0;l>c;c++)u[c]=arguments[c];return o.next.apply(this,u)}));return Se(a)&&(a.prototype=a.prototype||{},Object.defineProperties(a,{__posthog_wrapped__:{enumerable:!1,value:!0},__posthog_layer__:{enumerable:!1,value:o}})),r[i]=a,()=>{if(r[i]!==a)for(var l=r[i];Se(l)&&l.__posthog_layer__;){var u=l.__posthog_layer__;if(u.next===a)return void(u.next=o.next);l=u.next}else r[i]=o.next}}catch{return ql}})(v.history,t,(r=>function(i,s,o){r.call(this,i,s,o),n.So(t)}))}}So(t){try{var e,n=v==null||(e=v.location)==null?void 0:e.pathname;if(!n)return;n!==this._o&&this.isEnabled&&this._instance.capture(un,{navigation_type:t}),this._o=n}catch(r){k.error("Error capturing "+t+" pageview",r)}}xo(){if(!this.wo){var t=()=>{this.So("popstate")};ie(v,"popstate",t),this.wo=()=>{v&&v.removeEventListener("popstate",t)}}}},heatmaps:class{get Ne(){return this.instance.config}constructor(t){var e;this.Co=!1,this.vo=!1,this.Mo=null,this.instance=t,this.Co=!((e=this.instance.persistence)==null||!e.props[eo]),this.rageclicks=new zl(t.config.rageclick)}initialize(){this.startIfEnabled()}get flushIntervalMilliseconds(){var t=5e3;return te(this.Ne.capture_heatmaps)&&this.Ne.capture_heatmaps.flush_interval_milliseconds&&(t=this.Ne.capture_heatmaps.flush_interval_milliseconds),t}get isEnabled(){return B(this.Ne.capture_heatmaps)?B(this.Ne.enable_heatmaps)?this.Co:this.Ne.enable_heatmaps:this.Ne.capture_heatmaps!==!1}startIfEnabled(){if(this.isEnabled){if(this.vo)return;$f.info("starting..."),this.To(),this.Ie()}else{var t;clearInterval((t=this.Mo)!==null&&t!==void 0?t:void 0),this.Eo(),this.getAndClearBuffer()}}onRemoteConfig(t){if(t.ok){var e=t.config;if("heatmaps"in e){var n=!!e.heatmaps;this.instance.persistence&&this.instance.persistence.register({[eo]:n}),this.Co=n,this.startIfEnabled()}}}getAndClearBuffer(){var t=this.R;return this.R=void 0,t}Io(t){Ms(t.originalEvent)&&this.ke(t.originalEvent,"deadclick")}Ie(){this.Mo&&clearInterval(this.Mo),this.Mo=C?.visibilityState==="visible"?setInterval(this.cr.bind(this),this.flushIntervalMilliseconds):null}To(){v&&C&&(this.Po=this.cr.bind(this),ie(v,gi,this.Po),this.Ro=t=>this.ke(t||v?.event),ie(C,"click",this.Ro,{capture:!0}),this.Ao=t=>this.Fo(t||v?.event),ie(C,"mousemove",this.Ao,{capture:!0}),this.Lo=new Cl(this.instance,Wp,this.Io.bind(this)),this.Lo.startIfEnabledOrStop(),this.Oo=this.Ie.bind(this),ie(C,fi,this.Oo),this.vo=!0)}Eo(){var t;v&&C&&(this.Po&&v.removeEventListener(gi,this.Po),this.Ro&&C.removeEventListener("click",this.Ro,{capture:!0}),this.Ao&&C.removeEventListener("mousemove",this.Ao,{capture:!0}),this.Oo&&C.removeEventListener(fi,this.Oo),clearTimeout(this.Do),(t=this.Lo)==null||t.stop(),this.vo=!1)}$o(t,e){var n=this.instance.scrollManager.scrollY(),r=this.instance.scrollManager.scrollX(),i=this.instance.scrollManager.scrollElement(),s=(function(o,a,l){for(var u=o;u&&$t(u)&&!Ne(u,"body");){if(u===l)return!1;var c=void 0;try{var d,h,p;c=(d=(h=(p=u.ownerDocument)==null?void 0:p.defaultView)!==null&&h!==void 0?h:v)==null?void 0:d.getComputedStyle(u).position}catch{return!1}if(N(a,c))return!0;u=Du(u)}return!1})(ys(t),["fixed","sticky"],i);return{x:t.clientX+(s?0:r),y:t.clientY+(s?0:n),target_fixed:s,type:e}}ke(t,e){var n;if(e===void 0&&(e="click"),!ml(t.target)&&Ms(t)){var r=this.$o(t,e);(n=this.rageclicks)!=null&&n.isRageClick(t.clientX,t.clientY,new Date().getTime())&&wl(ys(t),this.instance.config.rageclick)&&this.Vt(E({},r,{type:"rageclick"})),this.Vt(r)}}Fo(t){!ml(t.target)&&Ms(t)&&(clearTimeout(this.Do),this.Do=setTimeout((()=>{this.Vt(this.$o(t,"mousemove"))}),500))}Vt(t){if(v){var e=this.Ne.disable_capture_url_hashes?Pt(v.location.href):v.location.href,n=this.Ne.custom_personal_data_properties,r=this.Ne.mask_personal_data_properties?[...En,...n||[]]:[],i=ur(e,r,dr);this.R=this.R||{},this.R[i]||(this.R[i]=[]),this.R[i].push(t)}}cr(){this.R&&!yt(this.R)&&this.instance.capture("$$heatmap",{$heatmap_data:this.getAndClearBuffer()})}},deadClicksAutocapture:Cl,webVitalsAutocapture:class{constructor(t){var e;this.Co=!1,this.vo=!1,this.R={navigationKey:void 0,url:void 0,metrics:[],firstMetricTimestamp:void 0},this.No=()=>{clearTimeout(this.qo),this.qo=void 0,this.R.metrics.length!==0&&(this._instance.capture("$web_vitals",E({$current_url:this.R.url},this.R.metrics.reduce(((n,r)=>E({},n,{["$web_vitals_"+r.name+"_event"]:E({},r),["$web_vitals_"+r.name+"_value"]:r.value})),{}))),this.R={navigationKey:void 0,url:void 0,metrics:[],firstMetricTimestamp:void 0})},this.jo=n=>{var r;if(this.R=this.R||{navigationKey:void 0,url:void 0,metrics:[],firstMetricTimestamp:void 0},B(n?.name)||B(n?.value))jt.error("Invalid metric received",n);else{var i=typeof n.navigationURL=="string"?n.navigationURL:void 0,s=this.Bo(i);if(!x(s)){var o=he(n.navigationId)||typeof n.navigationId=="string"?"navigation:"+n.navigationId:"url:"+s;if(!this.Ho||this.Ho>n.value){this.R.navigationKey!==o&&(this.No(),this.qo=setTimeout(this.No,this.flushToCaptureTimeoutMs)),x(this.R.navigationKey)&&(this.R.navigationKey=o,this.R.url=s),this.R.firstMetricTimestamp=x(this.R.firstMetricTimestamp)?Date.now():this.R.firstMetricTimestamp,n.attribution&&n.attribution.interactionTargetElement&&(n.attribution.interactionTargetElement=void 0);var a=(r=this._instance.sessionManager)==null?void 0:r.checkAndGetSessionAndWindowId(!0),l=E({},n,i?{navigationURL:s}:{},{$current_url:s,timestamp:Date.now()});x(a)||(l.$session_id=a.sessionId,l.$window_id=a.windowId),this.R.metrics.push(l),this.R.metrics.length===this.allowedMetrics.length&&this.No()}else jt.error("Ignoring metric with value >= "+this.Ho,n)}}},this.Uo=()=>{if(!this.vo){var n,r,i,s,o=$.__PosthogExtensions__,a=o?.postHogWebVitalsCallbacksByFlavor,l=a?.[this.zo]||(this.zo==="web-vitals"&&x(a)?o?.postHogWebVitalsCallbacks:void 0);if(x(l)||(n=l.onLCP,r=l.onCLS,i=l.onFCP,s=l.onINP),n&&r&&i&&s){var u={reportSoftNavs:this.useSoftNavs};this.allowedMetrics.indexOf("LCP")>-1&&n(this.jo.bind(this),u),this.allowedMetrics.indexOf("CLS")>-1&&r(this.jo.bind(this),u),this.allowedMetrics.indexOf("FCP")>-1&&i(this.jo.bind(this),u),this.allowedMetrics.indexOf("INP")>-1&&s(this.jo.bind(this),u),this.vo=!0}else jt.error("web vitals callbacks not loaded - not starting")}},this._instance=t,this.Co=!((e=this._instance.persistence)==null||!e.props[io]),this.startIfEnabled()}get Wo(){return this._instance.config.capture_performance}get allowedMetrics(){var t,e,n=te(this.Wo)?(t=this.Wo)==null?void 0:t.web_vitals_allowed_metrics:void 0;return B(n)?((e=this._instance.persistence)==null?void 0:e.props[so])||["CLS","FCP","INP","LCP"]:n}get flushToCaptureTimeoutMs(){return(te(this.Wo)?this.Wo.web_vitals_delayed_flush_ms:void 0)||5e3}get useAttribution(){var t=te(this.Wo)?this.Wo.web_vitals_attribution:void 0;return t!=null&&t}get useSoftNavs(){var t=te(this.Wo)?this.Wo.__preview_web_vitals_soft_navs:void 0;return t!=null&&t}get Ho(){var t=te(this.Wo)&&he(this.Wo.__web_vitals_max_value)?this.Wo.__web_vitals_max_value:Vl;return t>0&&6e4>=t?Vl:t}get isEnabled(){var t=re?.protocol;if(t!=="http:"&&t!=="https:")return jt.info("Web Vitals are disabled on non-http/https protocols"),!1;var e=te(this.Wo)?this.Wo.web_vitals:Ye(this.Wo)?this.Wo:void 0;return Ye(e)?e:this.Co}startIfEnabled(){this.isEnabled&&!this.vo&&(jt.info("enabled, starting..."),this.ai(this.Uo))}onRemoteConfig(t){if(t.ok){var e=t.config;if("capturePerformance"in e){var n=te(e.capturePerformance)&&!!e.capturePerformance.web_vitals,r=te(e.capturePerformance)?e.capturePerformance.web_vitals_allowed_metrics:void 0;this._instance.persistence&&(this._instance.persistence.register({[io]:n}),this._instance.persistence.register({[so]:r})),this.Co=n,this.startIfEnabled()}}}get zo(){return this.useSoftNavs?this.useAttribution?"web-vitals-with-attribution-soft-navs":"web-vitals-soft-navs":this.useAttribution?"web-vitals-with-attribution":"web-vitals"}ai(t){var e=$.__PosthogExtensions__,n=this.zo,r=e?.postHogWebVitalsCallbacksByFlavor;r!=null&&r[n]||n==="web-vitals"&&x(r)&&e!=null&&e.postHogWebVitalsCallbacks?t():e==null||e.loadExternalDependency==null||e.loadExternalDependency(this._instance,n,(i=>{i?jt.error("failed to load script",i):t()}))}Bo(t){var e=t||v?.location.href;if(e){var n=this._instance.config.disable_capture_url_hashes?Pt(e):e,r=this._instance.config.custom_personal_data_properties,i=this._instance.config.mask_personal_data_properties?[...En,...r||[]]:[];return ur(n,i,dr)}jt.error("Could not determine current URL")}}},Uf={exceptionObserver:class{constructor(t){var e;this.Uo=()=>{var n;if(v&&this.isEnabled&&(n=$.__PosthogExtensions__)!=null&&n.errorWrappingFunctions){var r=$.__PosthogExtensions__.errorWrappingFunctions.wrapOnError,i=$.__PosthogExtensions__.errorWrappingFunctions.wrapUnhandledRejection,s=$.__PosthogExtensions__.errorWrappingFunctions.wrapConsoleError;try{!this.Vo&&this.Ne.capture_unhandled_errors&&(this.Vo=r(this.captureException.bind(this))),!this.Zo&&this.Ne.capture_unhandled_rejections&&(this.Zo=i(this.captureException.bind(this))),!this.Go&&this.Ne.capture_console_errors&&(this.Go=s(this.captureException.bind(this)))}catch(o){Un.error("failed to start",o),this.Qo()}}},this._instance=t,this.Ko=!((e=this._instance.persistence)==null||!e.props[to]),this.Jo=new Bh(E({},(function(n){var r,i,s,o;return n===void 0&&(n={}),{refillRate:(r=(i=n.exceptionRateLimiterRefillRate)!==null&&i!==void 0?i:n.__exceptionRateLimiterRefillRate)!==null&&r!==void 0?r:1,bucketSize:(s=(o=n.exceptionRateLimiterBucketSize)!==null&&o!==void 0?o:n.__exceptionRateLimiterBucketSize)!==null&&s!==void 0?s:10}})(this._instance.config.error_tracking),{refillInterval:1e4,rt:Un})),this.Ne=this.Yo(),this.startIfEnabledOrStop()}Yo(){var t=this._instance.config.capture_exceptions,e={capture_unhandled_errors:!1,capture_unhandled_rejections:!1,capture_console_errors:!1};return te(t)?e=E({},e,t):(x(t)?this.Ko:t)&&(e=E({},e,{capture_unhandled_errors:!0,capture_unhandled_rejections:!0})),e}get isEnabled(){return this.Ne.capture_console_errors||this.Ne.capture_unhandled_errors||this.Ne.capture_unhandled_rejections}startIfEnabledOrStop(){this.isEnabled?(Un.info("enabled"),this.Qo(),this.ai(this.Uo)):this.Qo()}ai(t){var e,n;(e=$.__PosthogExtensions__)!=null&&e.errorWrappingFunctions?t():(n=$.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,"exception-autocapture",(r=>{if(r)return Un.error("failed to load script",r);t()}))}Qo(){var t,e,n;(t=this.Vo)==null||t.call(this),this.Vo=void 0,(e=this.Zo)==null||e.call(this),this.Zo=void 0,(n=this.Go)==null||n.call(this),this.Go=void 0}onRemoteConfig(t){if(t.ok){var e=t.config;"autocaptureExceptions"in e&&(this.Ko=!!e.autocaptureExceptions||!1,this._instance.persistence&&this._instance.persistence.register({[to]:this.Ko}),this.Ne=this.Yo(),this.startIfEnabledOrStop())}}onConfigChange(){this.Ne=this.Yo()}captureException(t){var e,n,r,i=(e=t==null||(n=t.$exception_list)==null||(n=n[0])==null?void 0:n.type)!==null&&e!==void 0?e:"Exception";this.Jo.consumeRateLimit(i)?Un.info("Skipping exception capture because of client rate limiting.",{exception:i}):(r=this._instance.exceptions)==null||r.sendExceptionEvent(t)}},exceptions:class{constructor(t){var e,n;this.Xo=[],this.tl=new tp([new cp,new _p,new dp,new up,new mp,new gp,new pp,new vp],(function(r){for(var i=arguments.length,s=new Array(i>1?i-1:0),o=1;i>o;o++)s[o-1]=arguments[o];return function(a,l){l===void 0&&(l=0);for(var u=[],c=a.split(` -`),d=l;c.length>d;d++){var h=c[d];if(1024>=h.length){var p=hl.test(h)?h.replace(hl,"$1"):h;if(!p.match(/\S*Error: /)){for(var f of s){var g=f(p,r);if(g){u.push(g);break}}if(u.length>=50)break}}}return(function(m){if(!m.length)return[];var _=Array.from(m);return _.reverse(),_.slice(0,50).map((w=>{return E({},w,{filename:w.filename||(b=_,b[b.length-1]||{}).filename,function:w.function||wn});var b}))})(u)}})("web:javascript",sp,lp)),this._instance=t,this.Xo=(e=(n=this._instance.persistence)==null?void 0:n.get_property(no))!==null&&e!==void 0?e:[],this.el=ci(this.il()),this.rl=new wp(this.el)}onConfigChange(){this.el=ci(this.il()),this.rl.setConfig(this.el)}onRemoteConfig(t){var e,n,r;if(t.ok){var i=t.config;if("errorTracking"in i){var s=(e=(n=i.errorTracking)==null?void 0:n.suppressionRules)!==null&&e!==void 0?e:[],o=(r=i.errorTracking)==null?void 0:r.captureExtensionExceptions;this.Xo=s,this._instance.persistence&&this._instance.persistence.register({[no]:this.Xo,[ro]:o})}}}get nl(){var t,e=!!this._instance.get_property(ro),n=this._instance.config.error_tracking.captureExtensionExceptions;return(t=n??e)!==null&&t!==void 0&&t}buildProperties(t,e){return this.tl.buildFromUnknown(t,{syntheticException:e?.syntheticException,mechanism:{handled:e?.handled}})}addExceptionStep(t,e){if(this.el.enabled)try{if(!W(t)||t.trim().length===0)return void tt.warn("Ignoring exception step because message must be a non-empty string");var n=(function(s){if(!s)return{sanitizedProperties:{},droppedKeys:[]};var o=[];return{sanitizedProperties:Object.keys(s).reduce(((a,l)=>yp.has(l)?(o.push(l),a):(a[l]=s[l],a)),{}),droppedKeys:o}})(this.sl(e)),r=n.sanitizedProperties,i=n.droppedKeys;i.length>0&&tt.warn("Ignoring reserved exception step fields",{droppedKeys:i}),this.rl.add(E({[ai]:t,[li]:new Date().toISOString()},r))}catch(s){tt.error("Failed to add exception step. Ignoring breadcrumb.",s)}}sendExceptionEvent(t){try{var e=t.$exception_list;if(this.al(e)){if(this.ol(e))return this.ll("Exception dropped: matched a suppression rule"),void tt.info("Skipping exception capture because a suppression rule matched");if(!this.nl&&this.ul(e))return this.ll("Exception dropped: thrown by a browser extension"),void tt.info("Skipping exception capture because it was thrown by an extension");if(!this._instance.config.error_tracking.__capturePostHogExceptions&&this.hl(e))return this.ll("Exception dropped: thrown by the PostHog SDK"),void tt.info("Skipping exception capture because it was thrown by the PostHog SDK")}var n=this.el.enabled&&B(t.$exception_steps)?this.dl(t):t,r=typeof(s=globalThis._posthogReleaseId)=="string"&&s.length>0?s:void 0;r&&(n.$release_id=r);try{var i=this._instance.capture("$exception",n,{_noTruncate:!0,_batchKey:"exceptionEvent",Wn:!0});return i&&this.rl.clear(),i}catch(o){return tt.error("Failed to capture exception event. Dropping this exception.",o),void this.rl.clear()}}catch(o){return void tt.error("Failed to process exception event. Ignoring this exception.",o)}var s}dl(t){try{var e=this.rl.getAttachable();return e.length===0?t:E({},t,{$exception_steps:e})}catch(n){return tt.error("Failed to read buffered exception steps. Capturing exception without steps.",n),t}}ll(t){this.el.enabled&&this.rl.add({[ai]:t,[li]:new Date().toISOString()})}sl(t){return te(t)?E({},t):{}}il(){var t,e;return(t=(e=this._instance.config.error_tracking)==null?void 0:e.exception_steps)!==null&&t!==void 0?t:{}}ol(t){if(t.length===0)return!1;try{var e=t.reduce(((n,r)=>{var i=r.type,s=r.value;return W(i)&&i.length>0&&n.$exception_types.push(i),W(s)&&s.length>0&&n.$exception_values.push(s),n}),{$exception_types:[],$exception_values:[]});return this.Xo.some((n=>{var r=n.values.map((i=>{var s=gd[i.operator],o=e[i.key];if(!s||!o)return!1;var a=L(i.value)?i.value:[i.value];return a.length>0&&s(a,o)}));return n.type==="OR"?r.some(Boolean):r.every(Boolean)}))}catch(n){return tt.warn("Failed to evaluate suppression rules. Capturing the exception.",n),!1}}ul(t){return t.flatMap((e=>{var n,r;return(n=(r=e.stacktrace)==null?void 0:r.frames)!==null&&n!==void 0?n:[]})).some((e=>e.filename&&e.filename.startsWith("chrome-extension://")))}hl(t){if(t.length>0){var e,n,r,i,s=(e=(n=t[0].stacktrace)==null?void 0:n.frames)!==null&&e!==void 0?e:[],o=s[s.length-1];return(r=o==null||(i=o.filename)==null?void 0:i.includes("posthog.com/static"))!==null&&r!==void 0&&r}return!1}al(t){return!B(t)&&L(t)}}},Hf=E({productTours:class{get Mr(){return this._instance.persistence}constructor(t){this.vl=null,this.cl=null,this._instance=t}initialize(){this.loadIfEnabled()}onRemoteConfig(t){if(t.ok){var e=t.config;if("productTours"in e){var n,r;if(this.Mr&&this.Mr.register({[ra]:!!e.productTours}),!Ns(this._instance))return!this.vl&&B((n=this.Mr)==null?void 0:n.props[Jn])||Lr.info("product tours disabled; stopping and clearing cached tours"),(r=this.vl)==null||r.stop(),this.vl=null,void this.clearCache();this.loadIfEnabled()}}}loadIfEnabled(){!this.vl&&Ns(this._instance)&&this.ai((()=>this.fl()))}ai(t){var e,n;(e=$.__PosthogExtensions__)!=null&&e.generateProductTours?t():(n=$.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,"product-tours",(r=>{r?Lr.error("Could not load product tours script",r):t()}))}fl(){var t;!this.vl&&(t=$.__PosthogExtensions__)!=null&&t.generateProductTours&&(this.vl=$.__PosthogExtensions__.generateProductTours(this._instance,!0))}getProductTours(t,e){if(e===void 0&&(e=!1),!L(this.cl)||e){var n=this.Mr;if(n){var r=n.props[Jn];if(L(r)&&!e)return this.cl=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:i=>{if(Ns(this._instance)){var s=i.statusCode;if(s!==200||!i.json){var o="Product Tours API could not be loaded, status: "+s;return s===0?i.error||Lr.warn(o):Lr.error(o),void t([],{isLoaded:!1,error:o})}var a=L(i.json.product_tours)?i.json.product_tours:[];this.cl=a,n&&n.register({[Jn]:a}),t(a,{isLoaded:!0})}else t([],{isLoaded:!0})}})}else t(this.cl,{isLoaded:!0})}getActiveProductTours(t){B(this.vl)?t([],{isLoaded:!1,error:"Product tours not loaded"}):this.vl.getActiveProductTours(t)}showProductTour(t){var e;(e=this.vl)==null||e.showTourById(t)}previewTour(t){this.vl?this.vl.previewTour(t):this.ai((()=>{var e;this.fl(),(e=this.vl)==null||e.previewTour(t)}))}dismissProductTour(){var t;(t=this.vl)==null||t.dismissTour("user_clicked_skip")}nextStep(){var t;(t=this.vl)==null||t.nextStep()}previousStep(){var t;(t=this.vl)==null||t.previousStep()}clearCache(){var t;this.cl=null,(t=this.Mr)==null||t.unregister(Jn)}resetTour(t){var e;(e=this.vl)==null||e.resetTour(t)}resetAllTours(){var t;(t=this.vl)==null||t.resetAllTours()}cancelPendingTour(t){var e;(e=this.vl)==null||e.cancelPendingTour(t)}}},Ui),Wf={siteApps:class{constructor(t){this.pl=0,this._instance=t,this.gl=[],this.apps={}}get isEnabled(){return!!this._instance.config.opt_in_site_apps}ml(t,e){if(e){var n=this.globalsForEvent(e);this.gl.push(n),this.gl.length>1e3&&(this.gl=this.gl.slice(10))}}get siteAppLoaders(){var t;return(t=$._POSTHOG_REMOTE_CONFIG)==null||(t=t[this._instance.config.token])==null?void 0:t.siteApps}initialize(){if(this.isEnabled){var t=this._instance._addCaptureHook(this.ml.bind(this));this.yl=()=>{t(),this.gl=[],this.yl=void 0}}}globalsForEvent(t){var e,n,r,i,s,o,a;if(!t)throw new Error("Event payload is required");var l={},u=this._instance.get_property("$groups")||[],c=this._instance.get_property("$stored_group_properties")||{};for(var d of Object.entries(c)){var h=d[0];l[h]={id:u[h],type:h,properties:d[1]}}var p=t.$set_once,f=t.$set;return{event:E({},jc(t,Rf),{properties:E({},t.properties,f?{$set:E({},(e=(n=t.properties)==null?void 0:n.$set)!==null&&e!==void 0?e:{},f)}:{},p?{$set_once:E({},(r=(i=t.properties)==null?void 0:i.$set_once)!==null&&r!==void 0?r:{},p)}:{}),elements_chain:(s=(o=t.properties)==null?void 0:o.$elements_chain)!==null&&s!==void 0?s:"",distinct_id:(a=t.properties)==null?void 0:a.distinct_id}),person:{properties:this._instance.get_property("$stored_person_properties")},groups:l}}bl(t){var e,n=(e=t.tagName)==null?void 0:e.toLowerCase();return n==="style"&&this._instance.config.prepare_external_dependency_stylesheet?this._instance.config.prepare_external_dependency_stylesheet(t)||(et.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)||(et.error("prepare_external_dependency_script returned null"),null):t}_l(){var t,e,n,r,i,s,o,a;if(!this._instance.config.prepare_external_dependency_stylesheet&&!this._instance.config.prepare_external_dependency_script)return()=>{};var l=C?.defaultView,u=l==null||(t=l.Node)==null?void 0:t.prototype;if(!l||!u)return()=>{};if(this.pl++,this.wl)return this.kl();var c=[],d=this,h=new WeakSet,p=(m,_,w)=>{if(m!=null&&m[_]){var b=m[_];m[_]=w(b),c.push((()=>{m[_]=b}))}},f=m=>{if(h.has(m))return m;var _=d.bl(m);return _&&h.add(_),_},g=m=>m.map((_=>typeof _=="string"?_:f(_))).filter((_=>!$e(_)));return p(u,"appendChild",(m=>function(_){var w=f(_);return w?m.call(this,w):_})),p(u,"insertBefore",(m=>function(_,w){var b=f(_);return b?m.call(this,b,w):_})),p(u,"replaceChild",(m=>function(_,w){var b=f(_);return b?m.call(this,b,w):w})),[(e=l.Element)==null?void 0:e.prototype,(n=l.Document)==null?void 0:n.prototype,(r=l.DocumentFragment)==null?void 0:r.prototype].forEach((m=>{p(m,"append",(_=>function(){for(var w=arguments.length,b=new Array(w),I=0;w>I;I++)b[I]=arguments[I];return _.apply(this,g(b))})),p(m,"prepend",(_=>function(){for(var w=arguments.length,b=new Array(w),I=0;w>I;I++)b[I]=arguments[I];return _.apply(this,g(b))}))})),[(i=l.Element)==null?void 0:i.prototype,(s=l.CharacterData)==null?void 0:s.prototype,(o=l.DocumentType)==null?void 0:o.prototype].forEach((m=>{p(m,"before",(_=>function(){for(var w=arguments.length,b=new Array(w),I=0;w>I;I++)b[I]=arguments[I];return _.apply(this,g(b))})),p(m,"after",(_=>function(){for(var w=arguments.length,b=new Array(w),I=0;w>I;I++)b[I]=arguments[I];return _.apply(this,g(b))})),p(m,"replaceWith",(_=>function(){for(var w=arguments.length,b=new Array(w),I=0;w>I;I++)b[I]=arguments[I];var F=g(b);return b.length&&!F.length?void 0:_.apply(this,F)}))})),p((a=l.Element)==null?void 0:a.prototype,"insertAdjacentElement",(m=>function(_,w){var b=f(w);return b?m.call(this,_,b):null})),this.wl=()=>{c.forEach((m=>m())),this.wl=void 0},this.kl()}kl(){var t=!1;return()=>{var e;t||(t=!0,this.pl--,this.pl===0&&((e=this.wl)==null||e.call(this)))}}xl(t,e){e===void 0&&(e=!0);var n=this._l();try{var r=t(n);return e&&n(),r}catch(i){throw n(),i}}setupSiteApp(t){var e=this.apps[t.id],n=()=>{var o;!e.errored&&this.gl.length&&(et.info("Processing "+this.gl.length+" events for site app with id "+t.id),this.gl.forEach((a=>this.xl((()=>e.processEvent==null?void 0:e.processEvent(a))))),e.processedBuffer=!0),Object.values(this.apps).every((a=>a.processedBuffer||a.errored))&&((o=this.yl)==null||o.call(this))},r=!1,i=o=>{e.errored=!o,e.loaded=!0,et.info("Site app with id "+t.id+" "+(o?"loaded":"errored")),r&&n()};try{var s=this.xl((o=>t.init({posthog:this._instance,callback(a){o(),i(a)}})),!1).processEvent;s&&(e.processEvent=s),r=!0}catch(o){et.error(Jl+t.id,o),i(!1)}if(r&&e.loaded)try{n()}catch(o){et.error("Error while processing buffered events PostHog app with config id "+t.id,o),e.errored=!0}}Sl(){var t=this.siteAppLoaders||[];for(var e of t)this.apps[e.id]={id:e.id,loaded:!1,errored:!1,processedBuffer:!1};for(var n of t)this.setupSiteApp(n)}Cl(t){var e=this;if(Object.keys(this.apps).length!==0){var n=this.globalsForEvent(t),r=function(s){try{e.xl((()=>s.processEvent==null?void 0:s.processEvent(n)))}catch(o){et.error("Error while processing event "+t.event+" for site app "+s.id,o)}};for(var i of Object.values(this.apps))r(i)}}onRemoteConfig(t){var e,n,r,i=this;if((e=this.siteAppLoaders)!=null&&e.length)return this.isEnabled?(this.Sl(),void this._instance.on("eventCaptured",(l=>this.Cl(l)))):void et.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.');if((n=this.yl)==null||n.call(this),t.ok){var s=t.config;if((r=s.siteApps)!=null&&r.length)if(this.isEnabled){var o=function(){var l,u=a.id,c=a.url;$["__$$ph_site_app_"+u]=i._instance,(l=$.__PosthogExtensions__)==null||l.loadSiteApp==null||l.loadSiteApp(i._instance,c,(d=>{if(d)return et.error(Jl+u,d)}))};for(var a of s.siteApps)o()}else et.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.')}}}},zf={tracingHeaders:class{constructor(t){this.Ml=void 0,this.Tl=void 0,this.El=void 0,this.Uo=()=>{var e,n,r=this.Il();r?(x(this.Ml)&&(this.Ml=(e=$.__PosthogExtensions__)==null||(e=e.tracingHeadersPatchFns)==null?void 0:e._patchXHR(r,(()=>this._instance.get_distinct_id()),this._instance.sessionManager)),x(this.Tl)&&(this.Tl=(n=$.__PosthogExtensions__)==null||(n=n.tracingHeadersPatchFns)==null?void 0:n._patchFetch(r,(()=>this._instance.get_distinct_id()),this._instance.sessionManager))):this.Qo()},this._instance=t}initialize(){this.startIfEnabledOrStop()}ai(t){var e,n;(e=$.__PosthogExtensions__)!=null&&e.tracingHeadersPatchFns?t():(n=$.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,"tracing-headers",(r=>{if(r)return Pf.error("failed to load script",r);t()}))}Pl(){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}Il(){var t=this.Pl();return L(t)?(L(this.El)?this.El.splice(0,this.El.length,...t):this.El=[...t],t.length>0?this.El:void 0):(L(this.El)&&this.El.splice(0),this.El=t||void 0,this.El)}Qo(){var t,e;(t=this.Ml)==null||t.call(this),(e=this.Tl)==null||e.call(this),this.Ml=void 0,this.Tl=void 0}startIfEnabledOrStop(){this.Il()?this.ai(this.Uo):this.Qo()}}},qf=E({surveys:class{get Ne(){return this._instance.config}constructor(t){this.Rl=void 0,this._surveyManager=null,this.Al=!1,this.Fl=[],this.Ll=null,this.Ol=null,this._instance=t,this._surveyEventReceiver=null}initialize(){this.loadIfEnabled()}onRemoteConfig(t){if(!this.Ne.disable_surveys){if(!t.ok)return V.warn("Remote config unavailable. Not loading surveys.");var e=t.config.surveys;if(B(e))return V.warn("Flags not loaded yet. Not loading surveys.");var n=L(e);this.Rl=n?e.length>0:e,V.info("flags response received, isSurveysEnabled: "+this.Rl),this.loadIfEnabled()}}reset(){try{var t;(t=this._surveyEventReceiver)==null||t.reset(),localStorage.removeItem("lastSeenSurveyDate");for(var e=[],n=0;nlocalStorage.removeItem(i)))}catch{}}loadIfEnabled(){if(!this._surveyManager)if(this.Al)V.info("Already initializing surveys, skipping...");else if(this.Ne.disable_surveys)V.info(Yl);else if(this.Ne.cookieless_mode&&this._instance.consent.isOptedOut())V.info("Not loading surveys in cookieless mode without consent.");else{var t=$?.__PosthogExtensions__;if(t){if(!x(this.Rl)||this.Ne.advanced_enable_surveys){var e=this.Rl||this.Ne.advanced_enable_surveys;this.Al=!0;try{var n=t.generateSurveys;if(n)return void this.Dl(n,e);var r=t.loadExternalDependency;if(!r)return void this.$l(sa);r(this._instance,"surveys",(i=>{i||!t.generateSurveys?this.$l("Could not load surveys script",i):this.Dl(t.generateSurveys,e)}))}catch(i){throw this.$l("Error initializing surveys",i),i}finally{this.Al=!1}}}else V.error("PostHog Extensions not found.")}}Dl(t,e){this._surveyManager=t(this._instance,e),this._surveyEventReceiver=new Nf(this._instance),V.info("Surveys loaded successfully"),this.Nl({isLoaded:!0})}$l(t,e){V.error(t,e),this.Nl({isLoaded:!1,error:t})}onSurveysLoaded(t){return this.Fl.push(t),this._surveyManager&&this.Nl({isLoaded:!0}),()=>{this.Fl=this.Fl.filter((e=>e!==t))}}getSurveys(t,e){if(e===void 0&&(e=!1),this.Ne.disable_surveys)return V.info(Yl),t([]);var n,r=this._instance.get_property(ao);if(r&&!e)return t(r,{isLoaded:!0}),void(this.ql()&&this.getSurveys((()=>{}),!0));typeof Promise<"u"&&this.Ll?this.Ll.then((i=>t(i.surveys,i.context))):(typeof Promise<"u"&&(this.Ll=new Promise((i=>{n=i}))),this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/surveys/?token="+this.Ne.token),method:"GET",timestampMode:"query",timeout:this.Ne.surveys_request_timeout_ms,callback:i=>{var s;this.Ll=null;var o=i.statusCode;if(o!==200||!i.json){var a="Surveys API could not be loaded, status: "+o;o!==0?V.error(a):i.error||V.warn(a),this.Ol=Date.now();var l={isLoaded:!1,error:a};return t([],l),void(n==null||n({surveys:[],context:l}))}this.Ol=null;var u,c=i.json.surveys||[],d=c.filter((p=>(function(f){return!(!f.start_date||f.end_date)})(p)&&(vd(p)||(function(f){var g;return!((g=f.conditions)==null||(g=g.actions)==null||(g=g.values)==null||!g.length)})(p))));d.length>0&&((u=this._surveyEventReceiver)==null||u.register(d)),(s=this._instance.persistence)==null||s.register({[ao]:c,[di]:Date.now()});var h={isLoaded:!0};t(c,h),n?.({surveys:c,context:h})}}))}ql(){return this.jl()&&!this.Ll&&!this.Bl()}jl(){var t=this._instance.get_property(di);return he(t)&&Date.now()-t>3e5}Bl(){return he(this.Ol)&&3e5>Date.now()-this.Ol}markSurveyAsSeen(t,e){var n,r={id:t,current_iteration:(n=e?.iteration)!==null&&n!==void 0?n:null};yd(r);try{localStorage.setItem("lastSeenSurveyDate",new Date().toISOString())}catch{}}Nl(t){for(var e of this.Fl)try{if(!t.isLoaded)return e([],t);this.getSurveys(e)}catch(n){V.error("Error in survey callback",n)}}getActiveMatchingSurveys(t,e){if(e===void 0&&(e=!1),!B(this._surveyManager))return this._surveyManager.getActiveMatchingSurveys(t,e);V.warn("init was not called")}Hl(t){var e=null;return this.getSurveys((n=>{var r;e=(r=n.find((i=>i.id===t)))!==null&&r!==void 0?r:null})),e}Ul(t){if(B(this._surveyManager))return{eligible:!1,reason:Or};var e=typeof t=="string"?this.Hl(t):t;return e?this._surveyManager.checkSurveyEligibility(e):{eligible:!1,reason:"Survey not found"}}zl(t){if(B(this._surveyManager))return{eligible:!1,reason:Or};var e=typeof t=="string"?this.Hl(t):t;return e?this._surveyManager.checkSurveyRenderability(e):{eligible:!1,reason:"Survey not found"}}canRenderSurvey(t){if(B(this._surveyManager))return V.warn("init was not called"),{visible:!1,disabledReason:Or};var e=this.zl(t);return{visible:e.eligible,disabledReason:e.reason}}canRenderSurveyAsync(t,e){return B(this._surveyManager)?(V.warn("init was not called"),Promise.resolve({visible:!1,disabledReason:Or})):new Promise((n=>{this.getSurveys((r=>{var i,s=(i=r.find((a=>a.id===t)))!==null&&i!==void 0?i:null;if(s){var o=this.zl(s);n({visible:o.eligible,disabledReason:o.reason})}else n({visible:!1,disabledReason:"Survey not found"})}),e)}))}renderSurvey(t,e,n){var r;if(B(this._surveyManager))V.warn("init was not called");else{var i=typeof t=="string"?this.Hl(t):t;if(i!=null&&i.id)if(vf.includes(i.type)){var s=C?.querySelector(e);if(s)return(r=i.appearance)!=null&&r.surveyPopupDelaySeconds?(V.info("Rendering survey "+i.id+" with delay of "+i.appearance.surveyPopupDelaySeconds+" seconds"),void setTimeout((()=>{var o,a;V.info("Rendering survey "+i.id+" with delay of "+((o=i.appearance)==null?void 0:o.surveyPopupDelaySeconds)+" seconds"),(a=this._surveyManager)==null||a.renderSurvey(i,s,n),V.info("Survey "+i.id+" rendered")}),1e3*i.appearance.surveyPopupDelaySeconds)):void this._surveyManager.renderSurvey(i,s,n);V.warn("Survey element not found")}else V.warn("Surveys of type "+i.type+" cannot be rendered in the app");else V.warn("Survey not found")}}displaySurvey(t,e){var n;if(B(this._surveyManager))V.warn("init was not called");else{var r=this.Hl(t);if(r){var i=r;if((n=r.appearance)!=null&&n.surveyPopupDelaySeconds&&e.ignoreDelay&&(i=E({},r,{appearance:E({},r.appearance,{surveyPopupDelaySeconds:0})})),e.displayType!==_o.Popover&&e.initialResponses&&V.warn("initialResponses is only supported for popover surveys. prefill will not be applied."),e.ignoreConditions===!1){var s=this.Ul(r);if(!s.eligible)return void V.warn("Survey is not eligible to be displayed: ",s.reason)}e.displayType!==_o.Inline?this._surveyManager.handlePopoverSurvey(i,e):this.renderSurvey(i,e.selector,e.properties)}else V.warn("Survey not found")}}cancelPendingSurvey(t){B(this._surveyManager)?V.warn("init was not called"):this._surveyManager.cancelSurvey(t)}handlePageUnload(){var t;(t=this._surveyManager)==null||t.handlePageUnload==null||t.handlePageUnload()}}},Ui),Vf={toolbar:class{constructor(t){this.instance=t}Wl(t){$.ph_toolbar_state=t}Vl(){var t;return(t=$.ph_toolbar_state)!==null&&t!==void 0?t:0}initialize(){return this.maybeLoadToolbar()}maybeLoadToolbar(t,e,n){if(t===void 0&&(t=void 0),e===void 0&&(e=void 0),n===void 0&&(n=void 0),go(this.instance.config)||!v||!C)return!1;t=t??v.location,n=n??v.history;try{if(!e){try{v.localStorage.setItem("test","test"),v.localStorage.removeItem("test")}catch{return!1}e=v?.localStorage}var r,i=Lf||yi(t.hash,"__posthog")||yi(t.hash,"state"),s=i?fl((()=>JSON.parse(atob(decodeURIComponent(i)))))||fl((()=>JSON.parse(decodeURIComponent(i)))):null;return s&&s.action==="ph_authorize"?((r=s).source="url",r&&Object.keys(r).length>0&&(s.desiredHash?t.hash=s.desiredHash:n?n.replaceState(n.state,"",t.pathname+t.search):t.hash="")):((r=JSON.parse(e.getItem(Zl)||"{}")).source="localstorage",delete r.userIntent),!(!r.token||this.instance.config.token!==r.token||(this.loadToolbar(r),0))}catch{return!1}}Zl(t){var e=$.ph_load_toolbar||$.ph_load_editor;!B(e)&&Se(e)?e(t,this.instance):Xl.warn("No toolbar load function found")}loadToolbar(t){var e=!(C==null||!C.getElementById(Mu));if(!v||e)return!1;var n=this.instance.requestRouter.region==="custom"&&this.instance.config.advanced_disable_toolbar_metrics,r=E({token:this.instance.config.token},t,{apiURL:this.instance.requestRouter.endpointFor("ui")},n?{instrument:!1}:{});if(v.localStorage.setItem(Zl,JSON.stringify(E({},r,{source:void 0}))),this.Vl()===2)this.Zl(r);else if(this.Vl()===0){var i;this.Wl(1),(i=$.__PosthogExtensions__)==null||i.loadExternalDependency==null||i.loadExternalDependency(this.instance,"toolbar",(s=>{if(s)return Xl.error("[Toolbar] Failed to load",s),void this.Wl(0);this.Wl(2),this.Zl(r)})),ie(v,"turbolinks:load",(()=>{this.Wl(0),this.loadToolbar(r)}))}return!0}Gl(t){return this.loadToolbar(t)}maybeLoadEditor(t,e,n){return t===void 0&&(t=void 0),e===void 0&&(e=void 0),n===void 0&&(n=void 0),this.maybeLoadToolbar(t,e,n)}}},Gf=E({experiments:ye},Ui),Kf={conversations:class{constructor(t){this.Ql=void 0,this._conversationsManager=null,this.Kl=!1,this.Jl=null,this.Yl=!1,this._instance=t}initialize(){this.loadIfEnabled()}onRemoteConfig(t){if(!this._instance.config.disable_conversations&&(this.Xl=t.ok,t.ok)){var e=t.config.conversations;B(e)||(Ye(e)?this.Ql=e:(this.Ql=e.enabled,this.Jl=e),this.loadIfEnabled())}}reset(){var t;(t=this._conversationsManager)==null||t.reset(),this._conversationsManager=null,this.Ql=void 0,this.Jl=null,this.Xl=void 0,this.Yl=!1}loadIfEnabled(){if(!(this._conversationsManager||this.Kl||this._instance.config.disable_conversations||go(this._instance.config)||this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut())){var t=$?.__PosthogExtensions__;if(t&&!x(this.Ql)&&this.Ql)if(this.Jl&&this.Jl.token){this.Kl=!0;try{var e=t.initConversations;if(e)return this.tu(e),void(this.Kl=!1);var n=t.loadExternalDependency;if(!n)return void this.eu(sa);n(this._instance,"conversations",(r=>{r||!t.initConversations?this.eu("Could not load conversations script",r):this.tu(t.initConversations),this.Kl=!1}))}catch(r){this.eu("Error initializing conversations",r),this.Kl=!1}}else Ue.error("Conversations enabled but missing token in remote config.")}}tu(t){if(this.Jl)try{this._conversationsManager=t(this.Jl,this._instance),this.Yl=!1,Ue.info("Conversations loaded successfully")}catch(e){this.eu("Error completing conversations initialization",e)}else Ue.error("Cannot complete initialization: remote config is null")}eu(t,e){Ue.error(t,e),this._conversationsManager=null,this.Kl=!1,this.Yl=!0}show(){this._conversationsManager?this._conversationsManager.show():Ue.warn("Conversations not loaded yet.")}hide(){this._conversationsManager&&this._conversationsManager.hide()}isAvailable(){return this.Ql===!0&&!$e(this._conversationsManager)}getUnavailableReason(){return this.isAvailable()?null:this._instance.config.disable_conversations?"disabled_by_config":go(this._instance.config)?"disabled_for_toolbar":this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut()?"consent_opted_out":this.Xl===!1?"remote_config_failed":x(this.Ql)?this.Xl?"disabled_in_project":"remote_config_pending":this.Ql?B(this.Jl)||!this.Jl.token?"missing_token":$!=null&&$.__PosthogExtensions__?this.Kl?"initializing":this.Yl?"load_failed":"not_loaded":"extensions_unavailable":"disabled_in_project"}isVisible(){var t,e;return(t=(e=this._conversationsManager)==null?void 0:e.isVisible())!==null&&t!==void 0&&t}sendMessage(t,e,n){var r=this;return X((function*(){return r._conversationsManager?r._conversationsManager.sendMessage(t,e,n):(Ue.warn(Ht),null)}))()}getMessages(t,e){var n=this;return X((function*(){return n._conversationsManager?n._conversationsManager.getMessages(t,e):(Ue.warn(Ht),null)}))()}markAsRead(t){var e=this;return X((function*(){return e._conversationsManager?e._conversationsManager.markAsRead(t):(Ue.warn(Ht),null)}))()}getTickets(t){var e=this;return X((function*(){return e._conversationsManager?e._conversationsManager.getTickets(t):(Ue.warn(Ht),null)}))()}requestRestoreLink(t){var e=this;return X((function*(){return e._conversationsManager?e._conversationsManager.requestRestoreLink(t):(Ue.warn(Ht),null)}))()}restoreFromToken(t){var e=this;return X((function*(){return e._conversationsManager?e._conversationsManager.restoreFromToken(t):(Ue.warn(Ht),null)}))()}restoreFromUrlToken(){var t=this;return X((function*(){return t._conversationsManager?t._conversationsManager.restoreFromUrlToken():(Ue.warn(Ht),null)}))()}getCurrentTicketId(){var t,e;return(t=(e=this._conversationsManager)==null?void 0:e.getCurrentTicketId())!==null&&t!==void 0?t:null}getWidgetSessionId(){var t,e;return(t=(e=this._conversationsManager)==null?void 0:e.getWidgetSessionId())!==null&&t!==void 0?t:null}Xn(){var t;(t=this._conversationsManager)==null||t.setIdentity()}ts(){var t;(t=this._conversationsManager)==null||t.clearIdentity()}}},Jf={logs:class{constructor(t){var e,n=this;this.iu=!1,this.ru=!1,this.rt=ne("[logs]"),this.nu=E({},this.rt,{error(){for(var r=arguments.length,i=new Array(r),s=0;r>s;s++)i[s]=arguments[s];i.some(oc)||n.rt.error(...i)}}),this.tr=[],this.su=[],this.Sa=0,this.au=()=>{var r,i;this.Sa=0,(r=this.ou)==null||r.onReconnect(),(i=this.lu)==null||i.onReconnect()},this._instance=t,this._instance&&(e=this._instance.config.logs)!=null&&e.captureConsoleLogs&&(this.iu=!0),v&&ie(v,"online",this.au)}uu(t,e,n,r){var i,s=(function(o,a){var l,u,c,d,h,p,f,g=(l=o?.flushIntervalMs)!==null&&l!==void 0?l:3e3,m=(u=o?.maxBufferSize)!==null&&u!==void 0?u:100,_=a!=null&&a.consoleCapture?void 0:(c=o?.maxLogsPerInterval)!==null&&c!==void 0?c:1e3,w=x(_)?Math.max(m,2048):Math.max(m,_),b=o?.resourceAttributes;return{serviceName:(d=(h=b?.["service.name"])!==null&&h!==void 0?h:o?.serviceName)!==null&&d!==void 0?d:a?.serviceNameDefault,serviceVersion:(p=b?.["service.version"])!==null&&p!==void 0?p:o?.serviceVersion,environment:(f=b?.["deployment.environment"])!==null&&f!==void 0?f:o?.environment,resourceAttributes:b,beforeSend:o?.beforeSend,flushIntervalMs:g,maxBufferSize:m,maxQueueSize:w,maxBatchRecordsPerPost:100,rateCapWindowMs:g,maxLogsPerInterval:_,backgroundFlushBudgetMs:0,terminationFlushBudgetMs:0}})((i=this._instance)==null||(i=i.config)==null?void 0:i.logs,n);return[new Xh(this.hu(t,e),s,this.nu,(()=>this.du()),(o=>o()),void 0,r),s]}vu(){var t,e=(t=this._instance)==null||(t=t.config)==null?void 0:t.logs;if(!this.ou||this.cu!==e){var n;(n=this.ou)==null||n.reset(),this.cu=e;var r=this.uu((()=>this.tr),(i=>{this.tr=i}));this.ou=r[0],this.fu=r[1]}return this.ou}pu(){var t,e=(t=this._instance)==null||(t=t.config)==null?void 0:t.logs;if(!this.lu||this.gu!==e){var n;(n=this.lu)==null||n.reset(),this.gu=e;var r=this.uu((()=>this.su),(i=>{this.su=i}),{serviceNameDefault:"posthog-browser-logs",consoleCapture:!0},sc);this.lu=r[0],this.mu=r[1]}return this.lu}initialize(){this.loadIfEnabled()}onRemoteConfig(t){var e;if(t.ok){var n=(e=t.config.logs)==null?void 0:e.captureConsoleLogs;!B(n)&&n&&(this.iu=!0,this.loadIfEnabled())}}reset(){var t,e;this.tr=[],(t=this.ou)==null||t.reset(),this.su=[],(e=this.lu)==null||e.reset(),this.Sa=0}captureLog(t){this.vu().captureLog(t)}he(t){this.pu().captureLog(t)}get logger(){return this.yu||(this.yu={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.yu}flushLogs(t){t?this.bu(t):(this.ou&&this.ou.flush().catch((e=>this._u(e))),this.lu&&this.lu.flush().catch((e=>this._u(e))))}_u(t){oc(t)||this.rt.error("PostHog logs flush failed:",t)}loadIfEnabled(){if(this.iu&&!this.ru){var t=$?.__PosthogExtensions__;if(t){var e=t.loadExternalDependency;e?e(this._instance,"logs",(n=>{var r;n||(r=t.logs)==null||!r.initializeLogs?this.rt.error("Could not load logs script",n):(t.logs.initializeLogs(this._instance),this.ru=!0)})):this.rt.error(sa)}else this.rt.error("PostHog Extensions not found.")}}hu(t,e){var n=this._instance;return{get isDisabled(){return!1},get optedOut(){return!n.is_capturing()},getPersistedProperty:r=>r===pt.LogsQueue?t():void 0,setPersistedProperty(r,i){var s;r===pt.LogsQueue&&e((s=i)!==null&&s!==void 0?s:[])},Ot:r=>this.Ot(r),getLibraryId:()=>Y.LIB_NAME,getLibraryVersion:()=>Y.LIB_VERSION}}Ot(t){return new Promise((e=>{if(Vu(this.Sa,3))e({kind:"fatal",error:Os(void 0,"logs endpoint is unreachable, dropping batch")});else{var n=!1,r=s=>{n||(n=!0,clearTimeout(i),e(s))},i=setTimeout((()=>{this.rt.warn("Logs request timed out before receiving a response"),r({kind:"retry-later",error:Os(void 0,"logs request timed out")})}),9e4);this._instance._send_request({method:"POST",url:this.wu(),data:t,compression:"best-available",batchKey:"logs",fireCallbackOnDrop:!0,callback:s=>{var o=s.statusCode;if(this.ku(o),o>=200&&300>o)r({kind:"ok"});else if(o===413)r({kind:"too-large"});else if(o!==0&&o!==429&&500>o)r({kind:"fatal",error:new Error("logs request failed with status "+o)});else{var a;o===0?(s.error||this.rt.warn("Logs request failed before receiving an HTTP response"),r({kind:"retry-later",error:Os(s.error,"logs request failed before receiving an HTTP response")})):r({kind:"retry-later",error:(a=s.error)!==null&&a!==void 0?a:new Error("logs request failed with status "+o)})}}})}}))}ku(t){(t!==0||this._instance.__loaded)&&(this.Sa=Gu(t,this.Sa,3,(()=>this.rt.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."))))}bu(t){this.tr.length>0&&this.xu(t,this.tr,this.fu,Y.LIB_NAME,(e=>{this.tr=e})),this.su.length>0&&this.xu(t,this.su,this.mu,sc,(e=>{this.su=e}))}xu(t,e,n,r,i){if(e.length!==0){var s=e.map((a=>a.record));i([]);var o=vu(s,mu(n,Y.LIB_NAME,Y.LIB_VERSION),r,Y.LIB_VERSION);this._instance._send_request({method:"POST",url:this.wu(),data:o,compression:"best-available",batchKey:"logs",transport:t})}}wu(){return this._instance.requestRouter.endpointFor("api","/i/v1/logs")+"?token="+encodeURIComponent(this._instance.config.token)}du(){var t,e={};if(e.distinctId=this._instance.get_distinct_id(),this._instance.sessionManager){var n=this._instance.sessionManager.checkAndGetSessionAndWindowId(!0),r=n.windowId,i=n.sessionStartTimestamp,s=n.lastActivityTimestamp;e.sessionId=n.sessionId,e.windowId=r,B(i)||(e.sessionStartTimestamp=i),B(s)||(e.lastActivityTimestamp=s)}if($!=null&&(t=$.location)!=null&&t.href&&(e.currentUrl=this._instance.config.disable_capture_url_hashes?Pt($.location.href):$.location.href),this._instance.featureFlags){var o=this._instance.featureFlags.getFlags();o&&o.length>0&&(e.activeFeatureFlags=o)}return e}}},Yf={metrics:class{constructor(t){this.rt=ne("[metrics]"),this._instance=t}initialize(){}vu(){var t,e,n=(t=this._instance)==null||(t=t.config)==null?void 0:t.metrics;return this.ou&&this.cu===n||((e=this.ou)==null||e.reset(),this.cu=n,this.ou=new Qh(this.hu(),(function(r){var i,s,o,a,l,u=r?.resourceAttributes;return{serviceName:(i=u?.["service.name"])!==null&&i!==void 0?i:r?.serviceName,serviceVersion:(s=u?.["service.version"])!==null&&s!==void 0?s:r?.serviceVersion,environment:(o=u?.["deployment.environment"])!==null&&o!==void 0?o:r?.environment,resourceAttributes:u,beforeSend:r?.beforeSend,flushIntervalMs:(a=r?.flushIntervalMs)!==null&&a!==void 0?a:1e4,maxSeriesPerFlush:(l=r?.maxSeriesPerFlush)!==null&&l!==void 0?l:1e3}})(n),this.rt)),this.ou}count(t,e,n){e===void 0&&(e=1),this.vu().count(t,e,n)}gauge(t,e,n){this.vu().gauge(t,e,n)}histogram(t,e,n){this.vu().histogram(t,e,n)}flush(t){if(!this.ou)return Promise.resolve();if(t){var e=this.ou.drainWindow();return e&&this.Jt(e,t),Promise.resolve()}return this.ou.flush().catch((n=>this.rt.error("PostHog metrics flush failed:",n)))}reset(){var t;(t=this.ou)==null||t.reset()}hu(){var t=this._instance,e=this;return{get isDisabled(){return!1},get optedOut(){return!t.is_capturing()},Jt:n=>e.Jt(n),getLibraryId:()=>Y.LIB_NAME,getLibraryVersion:()=>Y.LIB_VERSION}}Jt(t,e){return new Promise((n=>{var r=!1,i=o=>{r||(r=!0,clearTimeout(s),n(o))},s=setTimeout((()=>i({kind:"retry-later",error:new Error("metrics request timed out")})),9e4);this._instance._send_request(E({method:"POST",url:this.Su(),data:t,compression:"best-available",batchKey:"metrics"},e&&{transport:e},{fireCallbackOnDrop:!0,callback(o){var a=o.statusCode;if(a>=200&&300>a)i({kind:"ok"});else if(a===413)i({kind:"too-large"});else if(a!==0&&a!==429&&500>a)i({kind:"fatal",error:new Error("metrics request failed with status "+a)});else{var l;i({kind:"retry-later",error:(l=o.error)!==null&&l!==void 0?l:new Error("metrics request failed with status "+a)})}}}))}))}Su(){return this._instance.requestRouter.endpointFor("api","/i/v1/metrics")+"?token="+encodeURIComponent(this._instance.config.token)}}},Zf=E({},Ui,Df,jf,Uf,Hf,Wf,qf,zf,Vf,Gf,Kf,Jf,Yf);Te.__defaultExtensionClasses=E({},Zf);var Sd=(function(){Y.SDK_DIST_CHANNEL="npm";var t=nr[dn]=new Te;return(function(){function e(){e.done||(e.done=!0,bd=!1,Z(nr,(function(n){n._dom_loaded()})))}C!=null&&C.addEventListener?C.readyState==="complete"?e():ie(C,"DOMContentLoaded",e,{capture:!1}):v&&k.error("Browser doesn't support `document.addEventListener` so PostHog couldn't be initialized")})(),t})();const Xf=["a[href]","button:not([disabled])","input:not([disabled]):not([type='hidden'])","select:not([disabled])","textarea:not([disabled])","[tabindex]:not([tabindex='-1'])"].join(",");let Je=null,Io=null,xd="";const Co=new Map;function kd(t){return[...t.querySelectorAll(Xf)].filter(e=>!e.hidden&&e.getAttribute("aria-hidden")!=="true"&&e.getClientRects().length>0)}function Qf(t){for(const e of document.body.children)e===t||e.tagName==="SCRIPT"||(Co.set(e,{inert:e.inert,ariaHidden:e.getAttribute("aria-hidden")}),e.inert=!0,e.setAttribute("aria-hidden","true"))}function eg(){for(const[t,e]of Co)t.inert=e.inert,e.ariaHidden===null?t.removeAttribute("aria-hidden"):t.setAttribute("aria-hidden",e.ariaHidden);Co.clear()}function Id(t){return t?.dataset.modalDismissible!=="false"&&t?.getAttribute("aria-busy")!=="true"}function Ve(t,e={}){const n=typeof t=="string"?document.getElementById(t):t;if(!n)return!1;Je&&Je!==n&&Xe(Je,{restoreFocus:!1,force:!0}),Io=e.trigger||document.activeElement,Je=n,xd=document.body.style.overflow,Qf(n),document.body.style.overflow="hidden",n.classList.add("open"),n.setAttribute("aria-hidden","false");const r=n.querySelector(".modal-content");r&&(r.style.transform="scale(1) translateY(0)");const i=()=>{if(Je!==n)return;((e.initialFocus?n.querySelector(e.initialFocus):n.querySelector("[data-modal-initial-focus]"))||kd(n)[0]||n.querySelector(".modal-content")||n).focus({preventScroll:!0})};return requestAnimationFrame(i),setTimeout(i,260),!0}function Xe(t,e={}){const n=typeof t=="string"?document.getElementById(t):t;if(!n||!e.force&&!Id(n))return!1;n.classList.remove("open"),n.setAttribute("aria-hidden","true"),eg(),document.body.style.overflow=xd,Je=null;const r=Io;return Io=null,e.restoreFocus!==!1&&r?.isConnected&&r.focus({preventScroll:!0}),!0}function ac(t,e,n="Operation in progress"){const r=typeof t=="string"?document.getElementById(t):t;r&&(r.dataset.modalDismissible=e?"false":"true",r.setAttribute("aria-busy",String(!!e)),e?r.setAttribute("aria-label",n):r.removeAttribute("aria-label"))}function tg(t){if(!Id(t))return;const e=t.dataset.modalCloseHandler;e&&typeof window[e]=="function"?window[e]():Xe(t)}document.addEventListener("keydown",t=>{if(!Je)return;if(t.key==="Escape"){t.preventDefault(),t.stopImmediatePropagation(),tg(Je);return}if(t.key!=="Tab"){t.stopPropagation();return}const e=kd(Je);if(!e.length){t.preventDefault(),(Je.querySelector(".modal-content")||Je).focus();return}const n=e[0],r=e[e.length-1];t.shiftKey&&document.activeElement===n?(t.preventDefault(),r.focus()):!t.shiftKey&&document.activeElement===r&&(t.preventDefault(),n.focus())},!0);function ng(){document.querySelectorAll(".modal-overlay").forEach(t=>{t.setAttribute("role","dialog"),t.setAttribute("aria-modal","true"),t.setAttribute("aria-hidden",t.classList.contains("open")?"false":"true");const e=t.querySelector(".modal-content");e&&!e.hasAttribute("tabindex")&&(e.tabIndex=-1);const n=t.querySelector("h1, h2, h3");n&&(n.id||(n.id=`${t.id}-title`),t.setAttribute("aria-labelledby",n.id)),t.querySelectorAll(".modal-close").forEach(r=>{r.getAttribute("aria-label")||r.setAttribute("aria-label","Close dialog")})})}const Cd="CodeFile",Fd="GeneratedCode",rg={CustomAction:"A",CustomWidget:"W",CustomFunction:"F",CustomClass:"C",CodeFile:"C"};function Ft(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function Fo(t){return String(t||"").trim().replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function ig(t={},e=0){const n=Fo(t.artifactType||t.type||Cd),r=Fo(t.artifactName||t.name||t.fileName||`${Fd}-${e+1}`);return`${n||"artifact"}-${r||e+1}`}function Ad(t={},e=0){const n=Ft(t),r=n.artifactType||n.type||Cd,i=n.artifactName||n.name||Fd;let s=n.fileName||i;return s.endsWith(".dart")||(s+=".dart"),{id:Fo(n.id)||ig({...n,artifactType:r,artifactName:i,fileName:s},e),artifactType:r,artifactName:i,fileName:s,deployPath:n.deployPath||"",description:n.description||"",code:n.code||n.content||"",dependencies:Pd(n.dependencies),imports:Array.isArray(n.imports)?n.imports:[],publicApi:Array.isArray(n.publicApi)?n.publicApi:[],relationships:$d(n.relationships),deployStatus:n.deployStatus||"pending",review:n.review||null,metadata:Ft(n.metadata),codeType:n.codeType||rg[r]||"O"}}function Pd(t){return t?Array.isArray(t)?t.map(e=>{if(typeof e=="string")return{name:e,version:null,inferred:!1};const n=Ft(e),r=n.name||n.package;return r?{name:r,version:n.version||null,versionRequired:!!(n.versionRequired||n.required),inferred:!!n.inferred,...n.reason?{reason:n.reason}:{}}:null}).filter(Boolean):Object.entries(Ft(t)).map(([e,n])=>({name:e,version:n||null,inferred:!1})):[]}function $d(t){return t?(Array.isArray(t)?t:[t]).map(e=>{const n=Ft(e);return!n.from&&!n.to?null:{from:n.from||null,to:n.to||null,type:n.type||"uses",description:n.description||""}}).filter(Boolean):[]}function Ao(t){if(typeof t!="string")return null;const e=t.trim();if(!e)return null;try{return JSON.parse(e)}catch{const n=e.match(/```(?:json)?\s*([\s\S]*?)```/i);if(!n)return null;try{return JSON.parse(n[1].trim())}catch{return null}}}function hr(t,e={}){const n=[],r=typeof t=="string"?Ao(t):t,s=Ft(r||{});!r&&typeof t=="string"&&n.push("Structured bundle parse failed; using legacy single-artifact fallback.");const o=Array.isArray(s.artifacts)?s.artifacts:[{artifactType:s.artifactType||e.artifactType,artifactName:s.artifactName||e.artifactName,fileName:s.fileName||e.fileName,description:s.description,code:s.code||e.code||(typeof t=="string"?t:""),dependencies:s.dependencies||e.dependencies,relationships:s.relationships||e.relationships}];o.forEach((d,h)=>{!d?.artifactType&&!d?.type&&n.push(`Artifact ${h+1} has no artifactType; it will deploy as a standalone code file under lib/custom_code/ root.`)});const a=o.map((d,h)=>Ad(d,h)),l=new Map(o.map((d,h)=>[Ft(d).id,a[h]?.id]).filter(([d,h])=>d&&h)),u=d=>l.get(d)||d,c=$d(s.relationships||e.relationships).map(d=>({...d,from:d.from?u(d.from):d.from,to:d.to?u(d.to):d.to}));return{schemaVersion:s.schemaVersion||e.schemaVersion||null,id:s.id||e.id||"bundle-current",title:s.title||s.name||e.title||"Generated artifact bundle",description:s.description||e.description||"",artifacts:a,dependencies:Pd(s.dependencies||e.dependencies),relationships:c,deployOrder:Array.isArray(s.deployOrder)?s.deployOrder.map(u):a.map(d=>d.id),warnings:[...n,...Array.isArray(s.warnings)?s.warnings:[]],metadata:Ft(s.metadata)}}function xi(t){return hr(t).artifacts[0]||Ad()}function Et(t){if(typeof t!="string")return t??"";const e=t.trim();if(!e)return"";try{return JSON.parse(e)}catch{return t}}function xn(t){return JSON.stringify(t,null,2)}function sg(t){return xn({task:"architect",userRequest:String(t??"")})}function og(t){const e=Et(t);return e&&typeof e=="object"&&typeof e.task=="string"?xn(e):xn({task:"generate_bundle",bundleSpec:e})}function ag(t){return xn({task:"review_bundle",generatedBundle:Et(t),outputRequirements:{bundleReview:["status","score","summary","manualActions","findings"],scoreRange:[0,100],eachArtifact:["id","review.status","review.findings"],manualActions:{definition:"Setup the developer must perform by hand in the FlutterFlow editor that FlutterFlow will NOT do for them.",exclude:["creating the Custom Action, Widget or Code File itself - deploying the code creates it","declaring parameters or return values FlutterFlow derives from the function signature","anything that resolves as a side effect of using the action or widget in the editor","generic advice such as testing, reviewing or rebuilding the app"],preferEmpty:"Return an empty array when nothing qualifies - an empty list is the expected result for most bundles."}}})}function pa(t,e=null){const n={stage:t};return e!=null&&(n.bundle=Et(e)),n}function lg({bundleSpec:t,artifactBundle:e,bundleReview:n,artifactId:r,userFeedback:i}){return xn({task:"regenerate_artifact",artifactId:r,bundleSpec:Et(t),artifactBundle:Et(e),bundleReview:Et(n),userFeedback:String(i)})}function Rd({bundleSpec:t,artifactBundle:e,bundleReview:n,userFeedback:r}){return xn({task:"regenerate_bundle",bundleSpec:Et(t),artifactBundle:Et(e),bundleReview:Et(n),userFeedback:String(r??"")})}const lc={csam:"child-safety content",dangerous:"dangerous content",harassment:"harassment",hate_speech:"hate speech",maliciousUrls:"a potentially malicious URL",malicious_uris:"a potentially malicious URL",pi_and_jailbreak:"prompt-injection or jailbreak instructions",promptInjection:"prompt-injection or jailbreak instructions",rai:"restricted content",sdp:"sensitive personal data",sexually_explicit:"sexually explicit content",virus_scan:"potentially malicious file content"},cg=["sanitizationResult","modelArmor","modelArmorResult","data","result","error"];function Le(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function ug(t){return Le(t)?typeof t.filterMatchState=="string"||typeof t.invocationResult=="string"||Array.isArray(t.matchedFilters)||Le(t.filterSummary)||Le(t.filterResults):!1}function Td(t,e=0){if(!Le(t)||e>3)return null;if(ug(t))return t;for(const n of cg){const r=t[n];if(Le(r)){const i=Td(r,e+1);if(i)return i}}return null}function ki(t){return Array.isArray(t)?t.some(ki):Le(t)?t.matched===!0||t.matchState==="MATCH_FOUND"?!0:Object.values(t).some(ki):!1}function Po(t){return Array.isArray(t)?t.some(Po):Le(t)?typeof t.executionState=="string"&&t.executionState!=="EXECUTION_SUCCESS"?!0:Object.values(t).some(Po):!1}function Md(t){return{csamFilterFilterResult:"csam",maliciousUriFilterResult:"malicious_uris",piAndJailbreakFilterResult:"pi_and_jailbreak",raiFilterResult:"rai",sdpFilterResult:"sdp",virusScanFilterResult:"virus_scan"}[t]||t}function dg(t,e){if(Le(t))for(const[n,r]of Object.entries(t)){if(!Le(r))continue;const i=Le(r.categories)?r.categories:{},s=Object.entries(i).filter(([,o])=>Le(o)&&o.matched===!0).map(([o])=>o);s.length>0?s.forEach(o=>e.add(o)):r.matched===!0&&e.add(Md(n))}}function hg(t,e){if(!t)return;const n=Array.isArray(t)?t.flatMap(r=>Le(r)?Object.entries(r):[]):Object.entries(t);for(const[r,i]of n){if(!ki(i))continue;const s=Md(r),o=i?.raiFilterResult?.raiFilterTypeResults||(s==="rai"?i?.raiFilterTypeResults:null),a=Le(o)?Object.entries(o).filter(([,l])=>ki(l)).map(([l])=>l):[];a.length>0?a.forEach(l=>e.add(l)):e.add(s)}}function pg(t){return lc[t]?lc[t]:String(t).replace(/([a-z])([A-Z])/g,"$1 $2").replace(/_/g," ").toLowerCase()}function cc(t){return t.length<=1?t[0]||"content that did not pass":t.length===2?`${t[0]} and ${t[1]}`:`${t.slice(0,-1).join(", ")}, and ${t.at(-1)}`}function fg(t){const e=Td(t);if(!e)return null;const n=new Set(Array.isArray(e.matchedFilters)?e.matchedFilters:[]);dg(e.filterSummary,n),hg(e.filterResults,n);const r=e.blocked===!0||e.filterMatchState==="MATCH_FOUND"||n.size>0,i=e.invocationResult||null,s=Po(e.filterSummary||e.filterResults);return!r&&!s&&!["PARTIAL","FAILURE"].includes(i)?null:{kind:r?"blocked":"unavailable",invocationResult:i,matchedFilters:[...n]}}function gg(t,e){const n=fg(t);if(!n)return null;const r=[...new Set(n.matchedFilters.map(pg))],i=n.kind==="blocked",s=new Error(i?`Safety screening blocked this pipeline step for ${cc(r)}.`:"Safety screening could not be completed. Please try again.");return s.name="ModelArmorError",s.code=i?"MODEL_ARMOR_BLOCKED":"MODEL_ARMOR_UNAVAILABLE",s.isModelArmor=!0,s.pipelineStep=e,s.userTitle=i?"Request blocked for safety":"Safety check unavailable",s.userMessage=i?`The safety check detected ${cc(r)}. Edit your request to remove or rephrase the flagged content, then run the pipeline again.`:"The safety service did not finish all of its checks. Please wait a moment and run the pipeline again.",s.retryExplanation=i?"Trying another model would not change this safety decision.":"A fallback model was not attempted because safety screening must complete first.",s.matchedFilters=n.matchedFilters,s}function mg(t){return String(t||"").replace(/\/\*[\s\S]*?\*\//g,"").replace(/\/\/[^\n]*/g,"")}function uc(t){const e=/^(import|export|part|library|class|enum|extension|typedef|mixin|abstract|const|final|var|late)\b/,n=[];for(const r of mg(t).split(` -`)){if(!/^[A-Za-z_$]/.test(r)||e.test(r))continue;const i=r.match(/^[\w$<>,?\s[\]]+?\s([a-zA-Z_$][\w$]*)\s*\(/);i&&n.push(i[1])}return n}function fa(t,e){const n=t.replace(/\.dart$/,"");if(e==="W")return n.replace(/(^|_)(\w)/g,(r,i,s)=>s.toUpperCase());if(e==="A"){const r=n.replace(/(^|_)(\w)/g,(i,s,o)=>o.toUpperCase());return r.charAt(0).toLowerCase()+r.slice(1)}return e==="F"?"CustomFunctions":e==="C"?t.endsWith(".dart")?t:`${t}.dart`:n}async function dc(t){const e=new TextEncoder().encode(String(t||"")),n=await globalThis.crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(n),r=>r.toString(16).padStart(2,"0")).join("")}async function vg(t,e=new Map){const n={},r=new Set;for(const[o,a]of t.entries()){if(a.type==="D"||a.type==="O")continue;const l=fa(o,a.type),u={old_identifier_name:l,new_identifier_name:l,type:a.type,is_deleted:!1,current_checksum:await dc(a.content)},c=e.get(a.path);if(c!==void 0&&(u.original_checksum=await dc(c)),n[o]=u,a.type==="F"){const d=uc(a.content);(d.length>0?d:[a.functionName].filter(Boolean)).forEach(p=>r.add(p))}}const i=new Set(uc(e.get("lib/flutter_flow/custom_functions.dart")||"")),s={functions_to_rename:[],functions_to_delete:[],functions_to_add:Array.from(r).filter(o=>!i.has(o))};return{fileMapContents:JSON.stringify(n),functionsMapContents:JSON.stringify(s)}}const _g=new Set(["CustomWidget","CustomAction","CustomFunction","CustomClass","CodeFile"]),hc={CustomWidget:"custom_code/widgets/",CustomAction:"custom_code/actions/",CustomFunction:"flutter_flow/custom_functions.dart",CustomClass:"custom_code/",CodeFile:"custom_code/"},yg=new Set(["void","dynamic","String","int","double","num","bool","Color","DateTime","DateTimeRange","LatLng","FFPlace","FFUploadedFile","DocumentReference","List"]),wg=["Struct","Record"],bg=[{id:"required-public-param",severity:"error",message:"CustomWidget constructor uses `required` on a parameter FlutterFlow can leave unset. FlutterFlow omits unset Define Parameters fields from the constructor call, so the widget will not compile when placed. Make the parameter optional and nullable (`this.value` with `final double? value`), or give it a constructor default (`this.value = 0.0`).",detect:t=>Bs(t).some(e=>/\brequired\s+this\.\w+/.test(e)),pos:"class W extends StatefulWidget { const W({required this.value}); final double value; }",neg:`class _P { const _P({required this.t}); final double t; } -class W extends StatefulWidget { const W({this.value}); final double? value; }`},{id:"non-nullable-public-field",severity:"error",message:"CustomWidget declares a non-nullable field with no constructor default. FlutterFlow omits unset Define Parameters fields, so the emitted call cannot supply it. Make the field nullable (`final double? value`) or give the parameter a default (`this.value = 0.0`).",detect:t=>Bs(t).some(e=>{const n=/^\s*final\s+(?:double|int|String|bool|Color|num)\s+(\w+)\s*;/gm;let r;for(;(r=n.exec(e))!==null;){const i=r[1];if(!(new RegExp(`this\\.${i}\\s*=(?!=)`).test(e)||new RegExp(`[:,]\\s*${i}\\s*=(?!=)`).test(e)))return!0}return!1}),pos:`class W extends StatefulWidget { - const W({required this.value}); - final double value; -}`,neg:`class _P { - const _P({required this.t}); - final double t; -} -class W extends StatefulWidget { - const W({this.value = 1.0}); - final double value; -}`},{id:"asset-without-anchor",severity:"warning",message:'CustomWidget calls Image.asset with a path arriving as a String parameter. An asset reaches the build only when a FlutterFlow widget NODE references it - a filename passed as a parameter does not count, so the image renders as a broken-image icon on device. "Download Unused Project Assets" does not fix it (FlutterFlow issues 522, 2271, 3799). Keep something in the UI referencing the file, or load it over the network instead.',detect:t=>/Image\.asset\s*\(/.test(t)&&/final\s+String\??\s+\w*[Pp]ath\b/.test(t),pos:`class W extends StatefulWidget { final String? imagePath; } -var x = Image.asset(widget.imagePath);`,neg:`class W extends StatefulWidget { final String? imagePath; } -var x = Image.network(widget.imagePath);`},{id:"unsupported-param-type",severity:"error",message:"CustomWidget exposes a Flutter data type FlutterFlow cannot express as a Define Parameter: TextStyle, BoxShadow, FontWeight, FontStyle, TextDirection, TextAlign, EdgeInsets, Offset, Alignment/AlignmentGeometry, Border, BorderRadius, BoxDecoration, BoxConstraints, BorderSide, Gradient, or ThemeData. FlutterFlow's supported data types (docs.flutterflow.io/resources/data-representation/data-types) are only int, double, bool, string, Color, Image, DateTime, Json, LatLng, and the FF objects, so this parameter cannot be configured in the editor and the widget will not place or compile. Expose primitives instead (color, fontSize as double?, fontWeight via a custom enum, doubles for spacing).",detect:t=>Bs(t).some(e=>/final\s+(TextStyle|BoxShadow|FontWeight|FontStyle|TextDirection|TextAlign|EdgeInsets|Offset|Alignment(?:Geometry)?|Border(?:Radius|Side)?|BoxDecoration|BoxConstraints|Gradient|LinearGradient|RadialGradient|ThemeData)\??\s+\w+\s*;/.test(e)),pos:`class W extends StatefulWidget { - const W({this.textStyle}); - final TextStyle? textStyle; - @override _S createState() => _S(); -} -class _S extends State { @override Widget build(BuildContext c) => const SizedBox(); }`,neg:`class W extends StatefulWidget { - const W({this.width}); - final double? width; - @override _S createState() => _S(); -} -class _S extends State { @override Widget build(BuildContext c) => Padding(padding: const EdgeInsets.all(8), child: const SizedBox()); }`}];function nt(t,e,n){return{artifactId:t.id,artifactName:t.artifactName,artifactType:t.artifactType,severity:e,message:n}}function pr(t){let e="",n=0;for(;n"&&(n--,n===0))return{inner:t.slice(e+1,r),end:r+1};return null}function Sg(t,e){const n=new RegExp(`class\\s+${e}\\b[^{]*\\{`).exec(t);if(!n)return null;let r=0;for(let i=n.index+n[0].length-1;ixg(t).usable);function Ig(t=""){const e=pr(t);return kg.filter(n=>n.detect(e)).map(({id:n,severity:r,message:i})=>({id:n,severity:r,message:i}))}function Cg(t){const e=[],n=t.matchAll(/\bFuture\b/g);for(const r of n){let i=r.index+6,s=null;const o=i;for(;io;if(t[i]==="<"){const u=Eg(t,i);if(!u||(s=u.inner.replace(/\s+/g," ").trim(),i=u.end,!/\s/.test(t[i]||"")))continue;for(;ipc(o.functionName)===r);if(i)return i;const s=o=>!o.functionName.startsWith("_");return n.find(s)||n[0]}function Hi(t=""){return Array.from(pr(t).matchAll(/\b(?:class|enum)\s+([A-Za-z_]\w*)/g),e=>e[1])}function Fg(t="",e=""){return ga(t,e)?.returnType||null}function fc(t){return String(t||"").replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2").toLowerCase()}function Ag(t,e){const n=Hi(e);if(n.length===0)return null;const i=String(t||"").split("/").pop().replace(/\.dart$/,"");if(n.some(l=>fc(l)===i)||n.length>1)return null;const[o]=n,a=`${fc(o)}.dart`;return`File name "${t}" does not match declared class "${o}". FlutterFlow accepts this, but naming the file "${a}" keeps the Code File recognisable in the editor.`}function ma(t){return String(t||"").replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,"")}function Pg(t,e,n=""){const r=ga(e,n)?.functionName;if(!r)return null;const i=String(t||"").split("/").pop(),s=fa(i,"A");if(s===r)return null;const o=`${ma(r)}.dart`;return`File name "${i}" does not match Action "${r}". FlutterFlow derives the action from the file name, so it looks for "${s}" and reports Action "${s}" declaration not found. Rename the file to "${o}" - FlutterFlow puts an underscore before every capital - or rename the function to "${s}".`}function $g(t="",e=""){return ga(t,e)!==null}function Rg(t,e=new Set){return(t?.match(/[A-Za-z_]\w*/g)||[]).filter(r=>yg.has(r)?!1:!wg.some(s=>r.endsWith(s))||e.has(r))}function Tg(t,{functionName:e="",declaredTypes:n=new Set}={}){const r=Fg(t,e),i=Rg(r,n);if(i.length===0)return null;const[s]=i;let o;return n.has(s)?o=`uses Code File type "${s}", which FlutterFlow cannot process as an Action Return Value`:r===s?o="is not a FlutterFlow Action Return Value":o=`uses type "${s}", which is not a FlutterFlow Action Return Value`,`CustomAction return type "${r}" ${o}. Return JSON (Future) or an existing FlutterFlow Data Type (*Struct) instead.`}function Mg(t,e={}){const n=[],r=t.fileName||"",i=t.code||"";if(_g.has(t.artifactType)||n.push(nt(t,"error",`Unsupported artifact type "${t.artifactType}".`)),r.endsWith(".dart")||n.push(nt(t,"error","FlutterFlow custom code artifacts must use .dart files.")),!i.trim())return n.push(nt(t,"warning","Generated artifact has no Dart code yet.")),n;if(t.artifactType==="CustomWidget"){/class\s+\w+\s+extends\s+(StatelessWidget|StatefulWidget)/.test(i)||n.push(nt(t,"warning","CustomWidget code should declare a widget class extending StatelessWidget or StatefulWidget."));for(const s of Ig(i))n.push(nt(t,s.severity,s.message))}if(t.artifactType==="CustomAction"&&!$g(i,t.artifactName)&&n.push(nt(t,"warning","CustomAction code should expose an async Future function callable from FlutterFlow.")),t.artifactType==="CustomAction"){const s=e.declaredTypes||new Set(Hi(i)),o=Tg(i,{functionName:t.artifactName,declaredTypes:s});o&&n.push(nt(t,"error",o));const a=Pg(r,i,t.artifactName);a&&n.push(nt(t,"error",a))}if(t.artifactType==="CustomFunction"&&/class\s+\w+\s+extends\s+(StatelessWidget|StatefulWidget)/.test(i)&&n.push(nt(t,"warning","CustomFunction should be a callable function, not a widget class.")),t.artifactType==="CustomClass"||t.artifactType==="CodeFile"){const s=Ag(r,i);s&&n.push(nt(t,"info",s))}return n}function Ng(t){const e=Array.isArray(t?.artifacts)?t.artifacts:[],n=new Set(e.flatMap(s=>Hi(s.code||""))),r=e.flatMap(s=>Mg(s,{declaredTypes:n})),i=e.map(s=>({artifactId:s.id,fileName:s.fileName,pathHint:hc[s.artifactType]||hc.CodeFile}));return{valid:r.every(s=>s.severity!=="error"),findings:r,deployHints:i}}const gc="// DO NOT REMOVE OR MODIFY THE CODE ABOVE!";function mc(t){return(/^\s*import\s+['"]([^'"]+)['"]/.exec(t)||[])[1]||null}function Lg(t=""){const e=t.indexOf(gc);return e===-1?t:t.slice(e+gc.length).replace(/^\s*\n/,"")}const Og=/^\s*import\s+['"][^'"]+['"]\s*;\s*(?:\/\/.*)?$/;function Bg(t="",e=""){const n=Lg(t),r=new Set((e.match(/^\s*import .*$/gm)||[]).map(mc).filter(Boolean)),i=n.split(` -`).filter(s=>{const o=mc(s);return o===null||!r.has(o)?!0:!Og.test(s)}).join(` -`).replace(/^\s*\/\/ Automatic FlutterFlow imports\s*$/m,"").replace(/^\s*\n+/,"");return e+i}const Dg=new Set(["flutter","flutter_test","flutter_driver","flutter_localizations"]);function Nd(t){let e="",n=0;for(;n{const r=n.name||n.package;if(!r||r==="flutter")return e;const i=n.versionRequired||n.required;return e[r]=i&&n.version||"",e},{})}function zg(t){const e=new Map,n=new Map,r=[];for(const i of t)e.has(i.fileName)?r.push(`Duplicate deploy file name "${i.fileName}" for artifacts "${e.get(i.fileName)}" and "${i.artifactId}".`):e.set(i.fileName,i.artifactId),n.has(i.path)?r.push(`Duplicate deploy path "${i.path}" for artifacts "${n.get(i.path)}" and "${i.artifactId}".`):n.set(i.path,i.artifactId);return r}function qg(t,e={}){const n=Array.isArray(t?.artifacts)?t.artifacts:[],i=(e.selectedArtifactIds||t?.deployOrder||n.map(p=>p.id)).map(p=>n.find(f=>f.id===p)).filter(Boolean),s=[...t?.warnings||[]];let o=[];i.forEach(p=>{const f=Wg(p),g=p.fixedCode||p.code||"",m=p.codeType||Ug[p.artifactType]||Me.OTHER;g.trim()||s.push(`${p.artifactName||p.id} has no generated code.`),o.push({artifactId:p.id,artifactName:p.artifactName,artifactType:p.artifactType,fileName:f,content:g,type:m,path:p.deployPath||Hg(f,m),deployPath:p.deployPath||"",deployMode:"customCodeSync"})});const a="lib/flutter_flow/custom_functions.dart",l=o.map((p,f)=>({entry:p,index:f})).filter(({entry:p})=>p.type===Me.FUNCTION&&p.path===a);if(l.length>1){const p=l[0],f={...p.entry,artifactId:l.map(({entry:m})=>m.artifactId).join("+"),artifactName:p.entry.artifactName,content:l.map(({entry:m})=>`// ${m.artifactId} -${m.content}`).join(` - -`)},g=new Set(l.slice(1).map(({index:m})=>m));o=o.filter((m,_)=>!g.has(_)),o[p.index]=f}const u={...vc(t?.dependencies),...i.reduce((p,f)=>({...p,...vc(f.dependencies)}),{})},c={};i.forEach(p=>{va(p.code||"").forEach(f=>{f in u||(c[f]="")})});const d={...c,...u},h=zg(o);return{bundleId:t?.id||"bundle-current",title:t?.title||"Generated artifact bundle",fileEntries:o,dependencies:d,relationships:t?.relationships||[],warnings:s,errors:h}}function Vg(t){return String(t||"").match(/\bclass\s+([A-Z][A-Za-z0-9_]*)\b/)?.[1]}function Gg(t){return String(t||"").split("/").pop().replace(/\.dart$/,"").split(/[^A-Za-z0-9]+/).filter(Boolean).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join("")}function Kg(t,e){const r=[Gg(t),Vg(e.content),e.artifactName].find(i=>/^[A-Z][A-Za-z0-9_]*$/.test(String(i||"")));if(!r)throw new Error(`Cannot derive a FlutterFlow custom class name for ${t}.`);return r}function Jg(t,e=new Map){const n=[];for(const[r,i]of t.entries())i.type!=="C"||e.has(i.path)||n.push({artifactId:i.artifactId||r,className:Kg(r,i),content:i.content,fileName:r,path:i.path});return n}function Yg(t,e){const n=new Set(e.map(r=>r.path));return new Map(Array.from(t.entries()).filter(([,r])=>!n.has(r.path)))}const _c={pass:0,warning:1,fail:2},Zg=["manualActions"];function Be(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function _t(...t){for(const e of t){if(typeof e=="string"&&e.trim())return e.trim();if(Array.isArray(e)&&e.length>0){const n=e.filter(r=>typeof r=="string").join(` -`);if(n)return n}}return""}function it(t){return t==null?[]:Array.isArray(t)?t:[t]}function Xg(t){const e=Be(t).value??t;if(e==null||typeof e=="string"&&e.trim()==="")return null;const n=Number(e);if(Number.isFinite(n))return n;const r=String(t||"").match(/\bscore\b[^\d]{0,12}(\d{1,3})(?:\s*\/\s*100)?/i);return r?Number(r[1]):null}function We(t){return String(t||"").trim().replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function _a(t){const e=String(t||"").toLowerCase();return/(fail|error|critical|block|reject|invalid)/.test(e)?"fail":/(warn|attention|manual|partial|incomplete|concern)/.test(e)?"warning":/(pass|success|ready|approve|valid|clean|info|notice)/.test(e)?"pass":null}function $o(...t){return t.filter(Boolean).reduce((e,n)=>_c[n]>_c[e]?n:e,"pass")}function Ld(t,e="warning",n="review"){if(typeof t=="string")return{severity:e,message:t,suggestion:"",source:n};const r=Be(t),i=_t(r.message,r.title,r.issue,r.description,r.summary);return i?{severity:_a(r.severity||r.status||r.level)||e,message:i,suggestion:_t(r.suggestion,r.fix,r.recommendation,r.action),source:r.source||n}:null}function Ro(t,e="review"){const n=Be(t);return[["findings","warning"],["issues","warning"],["criticalIssues","fail"],["errors","fail"],["warnings","warning"],["recommendations","warning"],["requiredFixes","fail"],["suggestions","warning"]].flatMap(([i,s])=>it(n[i]).map(o=>Ld(o,s,e)).filter(Boolean))}function Qg(t,e,n=null){if(typeof t=="string")return{id:`${n||"bundle"}-manual-${e+1}`,title:t,detail:"",location:"",timing:"unspecified",artifactId:n,source:"Code Review"};const r=Be(t),i=_t(r.title,r.action,r.step,r.message,r.name,r.description);return i?{id:r.id||`${n||"bundle"}-manual-${e+1}`,title:i,detail:_t(r.detail,r.instructions,r.description),location:_t(r.location,r.flutterFlowPath,r.path),timing:_t(r.timing,r.phase)||"unspecified",artifactId:n,source:_t(r.source)||"Code Review"}:null}function To(t,e=null){const n=Be(t);return Zg.flatMap(r=>it(n[r])).map((r,i)=>Qg(r,i,e)).filter(Boolean)}function em(t){let e=typeof t=="string"?Ao(t):t;if(!e&&typeof t=="string")return{rawText:t,root:{}};const n=Be(e);typeof n.content=="string"&&(e=Ao(n.content)||e);const r=Be(e),i=Be(r.reviewResult||r.codeReview||r.result);return{rawText:"",root:Object.keys(i).length?i:r}}function tm(t,e){const n=[e.id,e.fileName,e.artifactName].map(We);return t.find(r=>{const i=Be(r);return[i.id,i.fileName,i.artifactName,i.name].map(We).some(s=>s&&n.includes(s))})||null}function nm(t,e){return it(t?.metadata?.compatibility?.deployHints).find(i=>We(i?.artifactId)===We(e.id)||We(i?.fileName)===We(e.fileName))?.pathHint||""}function rm(t,e){return it(t?.relationships).filter(n=>We(n?.from)===We(e.id)||We(n?.to)===We(e.id))}function im(t,e){return it(t?.metadata?.compatibility?.findings).filter(n=>!n?.artifactId||We(n.artifactId)===We(e.id)).map(n=>Ld(n,"warning","Compatibility check")).filter(Boolean)}function sm(t,e,n,r){const i=tm(e,n),s=Be(i?.review||i||n.review),o=Object.keys(s).length>0,a=[...Ro(s),...im(t,n)],l=To(s,n.id),u=_a(s.status||s.verdict||s.outcome||s.result),c=a.length?$o(...a.map(h=>h.severity)):null,d=$o(u,c,o?null:"warning");return{...n,index:r,status:d,statusReason:o?_t(s.summary,s.overview,s.assessment,s.conclusion)||(a.length?`${a.length} review finding${a.length===1?"":"s"}`:"No file-level findings"):"No file-level verdict was returned",reviewComplete:o,findings:a,manualSteps:l,fixedSource:typeof s.fixedSource=="string"&&s.fixedSource.trim()?s.fixedSource.trim():null,pathHint:nm(t,n),relationships:rm(t,n)}}function om({status:t,score:e,artifactPresentations:n,manualSteps:r}){const i=n.length;if(i===0&&r.length===0)return e==null?"Code review returned no overall summary and no score.":`Reviewed bundle with score ${e}/100.`;const s=n.reduce((a,l)=>(a[l.status]+=1,a),{pass:0,warning:0,fail:0}),o=[];return t&&o.push(`Overall verdict: ${t}.`),i&&o.push(`${i} artifact${i===1?"":"s"}: ${s.pass} pass, ${s.warning} warn, ${s.fail} fail.`),r.length&&o.push(`Do before deploy: ${r.map(a=>a.title).join("; ")}.`),e==null&&o.push("No numeric score (0-100) was returned."),o.join(" ")}function am({bundle:t,reviewResult:e}){const n=Be(t),r=it(n.artifacts),{root:i,rawText:s}=em(e),o=[i.bundleReview,i.overallReview,i.overall,i.bundleSummary,i.summaryReview,i.review].map(Be).find(b=>Object.keys(b).length)||{},a=it(i.artifacts||i.files||i.reviews),l=r.map((b,I)=>sm(n,a,b,I)),u=Ro(i),d=[...Ro(o),...u],h=[...To(o),...To(i),...l.flatMap(b=>b.manualSteps)].filter((b,I,F)=>F.findIndex(A=>A.title===b.title&&A.artifactId===b.artifactId)===I),p=_a(o.status||o.verdict||o.overallStatus||i.status||i.verdict||i.overallStatus||i.outcome),f=$o(p,...d.map(b=>b.severity),...l.map(b=>b.status)),g=o.score??i.score??i.overallScore??s,m=Xg(g),_=_t(o.headline,o.summary,o.executiveSummary,o.overview,o.assessment,o.conclusion,i.overallSummary,i.headline,i.summary,i.executiveSummary,i.overview,i.assessment,i.conclusion,s)||om({status:f,score:m,artifactPresentations:l,manualSteps:h}),w=l.reduce((b,I)=>(b[I.status]+=1,b),{pass:0,warning:0,fail:0});return{title:n.title||"Generated artifact bundle",description:n.description||"",status:f,score:m,summary:_,findings:d,manualSteps:h,artifacts:l,counts:w,reviewCoverage:{reviewed:l.filter(b=>b.reviewComplete).length,total:l.length},deployOrder:it(n.deployOrder),relationships:it(n.relationships),warnings:it(n.warnings),compatibility:Be(n.metadata?.compatibility)}}const lm=/^\uFEFF/;function Wn(t){let e=0,n=t.length;for(;ee&&!t[n-1].trim();)n--;return t.slice(e,n).join(` -`)}function cm(t){const e=String(t??"").replace(lm,"");if(!e.trim())return"";const n=e.split(` -`),r=c=>{const d=c.trim();return/^`{3,}[A-Za-z0-9+#_.-]*$/.test(d)?c.length-c.trimStart().length:-1};let i=0,s=-1;const o=[];{let c=0;for(let d=0;d=0&&(i++,s<0&&(s=d),o.push(c+h)),c+=n[d].length+1}}if(i===0)return Wn(n);{const c=Mo(e);if(!c.error&&o.every(h=>wc(h,c.commentAndStringRanges)))return Wn(n)}if(i===1){const c=Wn(n.slice(0,s)),d=Wn(n.slice(s+1));return d.length>=c.length?d:c}const a=[];let l=null;for(let c=0;cc.length>0);return u.length===0?"":u.join(` - -`)}function um(t){return String(t??"").replace(/\/\*[\s\S]*?\*\//g," ").replace(/\/\/[^\n]*/g,"").replace(/'''[\s\S]*?'''/g,'""').replace(/"""[\s\S]*?"""/g,'""').replace(/'(?:\\.|[^'\\\n])*'/g,'""').replace(/"(?:\\.|[^"\\\n])*"/g,'""')}function Od(t){const e=um(t);return Array.from(e.matchAll(/class\s+([A-Z]\w*)\s+extends\s+[A-Za-z_]\w*Widget\b/g),n=>n[1])}function Bd(t){return`${ma(t)}.dart`}function dm(t){return fa(t,"W")}const yc={"(":")","[":"]","{":"}"},hm={")":"(","]":"[","}":"{"},pm=/[A-Za-z0-9_]/;function Mo(t){const e=[{kind:"code",opener:null,openedLine:0}],n=[];let r=1,i=0;const s=(c,d)=>{(c===` -`||c==="\r"&&d!==` -`)&&r++};let o=null;const a=()=>{for(const c of e)(c.kind==="string"||c.kind==="block-comment"||c.kind==="line-comment")&&n.push({start:c.startIndex,end:t.length})};for(;i0?t[i-1]:"",f=i>1?t[i-2]:"",g=(p==="r"||p==="R")&&!pm.test(f);e.push({kind:"string",quote:c,triple:h,raw:g,startIndex:i,openedLine:r}),i+=h?3:1;continue}if(yc[c]){e.push({kind:"code",opener:c,openedLine:r}),i++;continue}if(hm[c]){if(d.interpolation&&c==="}"){e.pop(),i++;continue}if(d.opener&&yc[d.opener]===c){e.pop(),i++;continue}return d.opener?(a(),{error:o??`line ${r}: "${c}" closes nothing - "${d.opener}" opened on line ${d.openedLine} is still open`,commentAndStringRanges:n}):(a(),{error:o??`line ${r}: unexpected "${c}" with no matching opener`,commentAndStringRanges:n})}s(c,t[i+1]),i++}a();let l=e.length-1;for(;l>0&&e[l].kind==="line-comment";)l--;let u=o;if(!u){const c=e[l];if(!(c.kind==="code"&&!c.opener&&!c.interpolation))if(c.kind==="string")u=`unclosed ${c.triple?"triple-quoted ":""}string starting on line ${c.openedLine} was never closed`;else if(c.kind==="block-comment")u=`unterminated /* comment starting on line ${c.openedLine}`;else if(c.interpolation){const d=e.findLast(p=>p.opener);u=`unclosed "\${" expression${d?` opened on line ${d.openedLine}`:""} was never closed`}else u=`"${c.opener}" opened on line ${c.openedLine} is never closed`}return{error:u,commentAndStringRanges:n}}function fm(t){return Mo(String(t??"")).error}function wc(t,e){return e.some(({start:n,end:r})=>t>=n&&ttypeof n=="string"?n:n?.errorMessage).filter(Boolean);return e.length>0?e.join("; "):JSON.stringify(t)}return t&&typeof t=="object"?t.errorMessage||JSON.stringify(t):String(t??"")}const gm=["gmail.com","googlemail.com","outlook.com","hotmail.com","live.com","msn.com"],mm="MAGIC_LINK_SENT",vm="PLUS_ALIAS_REJECTED",_m="Please enter your primary email address. Plus aliases (such as {email}) are not allowed for {domain} accounts.",Wi={allowlistedDomains:gm,successCode:mm,validationCode:vm,messageTemplate:_m},ym=new Set(Wi.allowlistedDomains),wm=Wi.successCode,Jr=Wi.validationCode;function zi(t){return typeof t=="string"?t.trim():""}function bm(t){const e=zi(t),n=e.lastIndexOf("@");if(n<=0||n===e.length-1)return!1;const r=e.slice(0,n),i=e.slice(n+1).toLowerCase();return ym.has(i)?r.includes("+"):!1}function Em(t,e){return Wi.messageTemplate.replaceAll("{email}",t).replaceAll("{domain}",e)}function jd(t){if(!bm(t))return null;const e=zi(t),n=e.lastIndexOf("@"),r=e.slice(n+1).toLowerCase();return Em(e,r)}function Sm(t,e){return t?.code===Jr?t.message||jd(e)||"Please enter your primary email address.":t?.code===wm||!t?.code?`Check your email — we sent a link to ${zi(e)}`:t.message||"Something went wrong. Please try again."}const xm=/^dependencies\s*:\s*(?:#.*)?$/,km=/^(?:"([^"]+)"|'([^']+)'|([A-Za-z_][A-Za-z0-9_-]*))\s*:/;function qi(t){const e=t.match(km);return e?e[1]??e[2]??e[3]:null}function yr(t){const e=t.trim();return e===""||e.startsWith("#")}function Pn(t){const e=t.match(/^(\s*)/);return e?e[1].length:0}function ya(t,e){const n=t.findIndex(s=>e.test(s));if(n===-1)return null;let r=n,i=null;for(let s=n+1;s=0.0.0"}`}function Am(t,e={}){const n=String(t||""),r=Object.entries(e).filter(([u])=>u&&u!=="flutter");if(r.length===0)return{yaml:n,added:[],alreadyPresent:[]};const i=n.split(` -`),s=new Set(Hd(n)),o=[],a=[];for(const[u,c]of r)s.has(u)?a.push(u):(o.push([u,c]),s.add(u));if(o.length===0)return{yaml:n,added:[],alreadyPresent:a};const l=wa(i);if(l){const u=o.map(([c,d])=>bc(l.childIndent,c,d));i.splice(l.endIndex,0,...u)}else i.length>0&&i[i.length-1].trim()!==""&&i.push(""),i.push("dependencies:"),o.forEach(([u,c])=>{i.push(bc(" ",u,c))});return{yaml:i.join(` -`),added:o.map(([u])=>u),alreadyPresent:a}}function Pm(t,e={}){const n=String(t||""),r=Object.entries(e).filter(([l])=>l&&l!=="flutter");if(r.length===0)return{yaml:n,overridden:[],skipped:[]};const i=n.split(` -`),s=Gi(n),o=[],a=[];for(const[l,u]of r){const c=s.get(l);if(!c||!c.isScalar||!String(u||"").trim()){a.push(l);continue}const d=" ".repeat(Pn(i[c.lineIndex]));i[c.lineIndex]=`${d}${l}: ${zd(String(u).trim())}${c.comment}`,o.push({name:l,from:c.constraint,to:u})}return{yaml:i.join(` -`),overridden:o,skipped:a}}function qd(t){const e=String(t||""),n=[];return e.trim()?(/^name:\s*\S+/m.test(e)||n.push("pubspec.yaml missing name field"),wa(e.split(` -`))||n.push("pubspec.yaml missing dependencies section"),Hd(e).includes("flutter")||n.push("pubspec.yaml missing Flutter SDK dependency"),{valid:n.length===0,errors:n}):(n.push("pubspec.yaml is empty"),{valid:!1,errors:n})}const $m=">=3.0.0 <4.0.0";function No(t){const e=String(t||"").trim(),n=e[0];return n!=="'"&&n!=='"'||e[e.length-1]!==n?e:e.slice(1,-1).replaceAll(`${n}${n}`,n)}function Rm(t=""){const e=jg(t).filter(n=>!n.startsWith("dart:")&&!n.startsWith("package:"));return{selfContained:e.length===0,unresolvableImports:e}}function Ec(t,e,n){const r=[];for(const[i,s]of t){if(s.isScalar){e[i]=No(s.constraint);continue}if(s.sourceKey==="sdk"){n.add(i);continue}if(s.sourceKey===null&&s.version){e[i]=No(s.version);continue}r.push(i)}return r}function Tm(t){const e=new Set,n={},r={},i=Ec(Gi(t),n,e);i.push(...Ec(Cm(t,"dependency_overrides"),r,e));const s=new Set([...Object.keys(n),...e]),{sdk:o}=Wd(t);return{sdkConstraint:No(o)||$m,dependencies:n,overrides:r,sdkPackages:[...e].sort(),availablePackages:s,unrepresentable:i}}function Mm(t,e,n){return e.length>0?`${t} imports ${e.join(", ")}, which FlutterFlow only generates once the app is built, so it could not be compiled before the deploy.`:`${t} imports ${n.join(", ")}, which your project's pubspec.yaml does not declare with a version constraint, so it could not be compiled before the deploy.`}function Nm(t,e){const{sdkConstraint:n,dependencies:r,overrides:i,sdkPackages:s,availablePackages:o,unrepresentable:a}=Tm(e),l={sdkConstraint:n,dependencies:r,overrides:i,sdkPackages:s},u=[],c=[],d=a.map(h=>`Your project declares ${h} from a source that cannot be reproduced outside it, so the pre-deploy compile check runs against a scratch package graph that omits ${h}. Classes that do not import ${h} directly are still checked, but against that reduced graph, so their transitive package resolution may differ from your project's and the check is approximate for them.`);for(const h of t){const{className:p,content:f}=h,g=va(f),m=g.filter(b=>a.includes(b));if(m.length>0){c.push({className:p,reason:`${p} was not compiled before deploying: it imports ${m.join(", ")}, which your project declares from a source that cannot be reproduced outside it, so package resolution could not be matched exactly.`});continue}const{unresolvableImports:_}=Rm(f),w=g.filter(b=>!o.has(b));if(_.length>0||w.length>0){c.push({className:p,reason:Mm(p,_,w)});continue}u.push({fileName:`${ma(p)}.dart`,content:f})}return{manifest:l,sources:u,skipped:c,approximate:d}}function Sc(t,e){const n=`${t}${e}`.split(` -`),r=n.pop()??"",i=[];for(const s of n){const o=Vd(s);o&&i.push(o)}return{events:i,buffer:r}}function Lm(t){const e=Vd(t);return e?[e]:[]}function Vd(t){const e=t.trim();if(!e)return null;try{const n=JSON.parse(e);return n&&typeof n=="object"&&!Array.isArray(n)?n:null}catch{return null}}async function Om(t,e={}){const{onPhase:n,onLog:r}=e;let i=null,s="";const o=a=>{if(a.event==="phase"){a.message&&n&&n(a.message);return}if(a.event==="log"){a.message&&r&&r(a.message);return}i=a};if(t.body?.getReader){const a=t.body.getReader(),l=new TextDecoder;for(;;){const{done:u,value:c}=await a.read();if(u)break;const d=Sc(s,l.decode(c,{stream:!0}));s=d.buffer,d.events.forEach(o)}}else{const a=Sc("",await t.text());s=a.buffer,a.events.forEach(o)}return Lm(s).forEach(o),i?{...i,success:i.success===!0||i.success===void 0&&t.ok}:{success:!1,error:t.ok?"The FlutterFlow deploy runner closed the connection before it finished.":`FlutterFlow custom class provisioning failed (HTTP ${t.status}).`}}const Bm=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;function St(t){const e=String(t||"").trim().match(Bm);return e?{major:Number(e[1]),minor:Number(e[2]),patch:Number(e[3]),prerelease:e[4]?e[4].split("."):[]}:null}function Dm(t,e){if(t.length===0&&e.length===0)return 0;if(t.length===0)return 1;if(e.length===0)return-1;for(let n=0;n0)}function Um(t){const e=St(t);return e?e.major>0?`${e.major+1}.0.0`:`0.${e.minor+1}.0`:null}function ba(t){let e=String(t??"").trim();if((e.startsWith("'")||e.startsWith('"'))&&(e=e.slice(1,-1).trim()),e===""||e==="any"||e==="*")return{min:null,minInclusive:!1,max:null,maxInclusive:!1};if(e.startsWith("^")){const o=e.slice(1).trim();return St(o)?{min:o,minInclusive:!0,max:Um(o),maxInclusive:!1}:null}if(St(e))return{min:e,minInclusive:!0,max:e,maxInclusive:!0};const n={min:null,minInclusive:!1,max:null,maxInclusive:!1},r=/(>=|<=|>|<)\s*([0-9][0-9A-Za-z.+-]*)/g;let i=!1,s;for(;(s=r.exec(e))!==null;){const[,o,a]=s;if(!St(a))return null;i=!0,o===">="||o===">"?(n.min=a,n.minInclusive=o===">="):(n.max=a,n.maxInclusive=o==="<=")}return i?n:null}function xc(t,e){const n=ba(t);if(!n||!St(e))return!1;if(n.min!==null){const r=Ii(e,n.min);if(r<0||r===0&&!n.minInclusive)return!1}if(n.max!==null){const r=Ii(e,n.max);if(r>0||r===0&&!n.maxInclusive)return!1}return!0}function Hm(t,e){const n=ba(t);if(!n||!St(e))return!1;if(n.max===null)return!0;const r=Ii(n.max,e);return r>0?!0:r===0&&n.maxInclusive}function cn(t){const e=ba(t);return e?e.min:null}const Wm="https://pub.dev/api/packages/",zm=8e3;function qm(t,e={}){const{dartSdkFloor:n=null,flutterSdkFloor:r=null}=e,i=Array.isArray(t?.versions)?t.versions:[];let s=null;for(const o of i){const a=o?.version;if(!a||o.retracted||jm(a))continue;const l=o.pubspec?.environment||{};n&&l.sdk&&!xc(l.sdk,n)||r&&l.flutter&&!xc(l.flutter,r)||(!s||Ii(a,s)>0)&&(s=a)}return s?{version:s,constraint:`^${s}`}:null}async function Vm(t,e={}){const{dartSdkFloor:n=null,flutterSdkFloor:r=null,fetchImpl:i=fetch}=e;let s;try{const a=await i(`${Wm}${encodeURIComponent(t)}`,{signal:AbortSignal.timeout(zm)});if(!a.ok)return{name:t,constraint:null,version:null,error:a.status===404?`"${t}" was not found on pub.dev`:`pub.dev returned ${a.status} for "${t}"`};s=await a.json()}catch(a){return{name:t,constraint:null,version:null,error:`could not reach pub.dev for "${t}" (${a.message})`}}const o=qm(s,{dartSdkFloor:n,flutterSdkFloor:r});return o?{name:t,...o,error:null}:{name:t,constraint:null,version:null,error:n?`no published "${t}" release supports Dart ${n}`:`no published "${t}" release could be read`}}async function Gm(t,e={}){const n=await Promise.all(t.map(r=>Vm(r,e)));return new Map(n.map(({name:r,...i})=>[r,i]))}async function Km(t,e={},n={}){const{resolveVersions:r=Gm}=n,i=Object.entries(e).filter(([c])=>c&&c!=="flutter"),s=Wd(t),o={dartSdkFloor:cn(s.sdk),flutterSdkFloor:cn(s.flutter)},a={additions:{},overrides:{},kept:[],warnings:[],sdk:o};if(i.length===0)return a;const l=Gi(t),u=[];for(const[c,d]of i){const h=l.get(c);if(!h){u.push(c);continue}const p=cn(d);if(!p){a.kept.push({name:c,constraint:h.constraint});continue}if(!h.isScalar){a.warnings.push(`"${c}" is declared in your project from a git, path, or SDK source, but the generated code needs at least ${p}. Left as-is — update it yourself if the build fails.`),a.kept.push({name:c,constraint:h.constraint});continue}if(Hm(h.constraint,p)){a.kept.push({name:c,constraint:h.constraint});continue}a.overrides[c]=`^${p}`,a.warnings.push(`"${c}" was pinned to ${h.constraint} in your project, which cannot resolve the ${p} the generated code needs. Raising it to ^${p} — this changes a dependency the rest of your app also uses.`)}if(u.length>0){const c=await r(u,o);for(const d of u){const h=c.get(d);if(h?.constraint){a.additions[d]=h.constraint;continue}const p=e[d]||"";if(cn(p)){a.additions[d]=`^${cn(p)}`,a.warnings.push(`Could not confirm "${d}" version on pub.dev (${h?.error||"lookup failed"}). Using ^${cn(p)} from the AI's recommendation — verify this is current.`);continue}a.additions[d]=">=0.0.0",a.warnings.push(`Could not determine a version for "${d}" (${h?.error||"lookup failed"}) and the AI supplied none. Added with a wide-open >=0.0.0 constraint — pin a concrete version in FlutterFlow before deploying.`)}}return a}const Jm={"&":"&","<":"<",">":">",'"':""","'":"'"};function xt(t){return String(t??"").replace(/[&<>"']/g,e=>Jm[e])}function D(t){return t?xt(t).replace(/\n/g,"
    "):""}function At(t){return xt(t).replace(/\r?\n/g," ")}function Ym(t,e={}){const n=t?.pipelineStep;if(n!=null&&e[n]!=null)return e[n];const r=t?.message||"";return r.includes("Code Generator")?2:r.includes("Code Review")?3:1}function Zm(t){const e={"Integration Audit Report":"📋","Critical Issues":"❌",Warnings:"⚠️",Recommendations:"✅","Overall Score":"📊"};for(const[n,r]of Object.entries(e))if(t.toLowerCase().includes(n.toLowerCase()))return r;return"📄"}function Xm(t){const e={critical:"❌",warning:"⚠️",recommendation:"✅",score:"📊",issue:"🔍",fix:"🔧"};for(const[n,r]of Object.entries(e))if(t.toLowerCase().includes(n.toLowerCase()))return r;return"📝"}function Qm(t){return t.includes("class ")&&t.includes("extends ")||t.includes("StatelessWidget")||t.includes("StatefulWidget")||t.includes("import 'package:flutter/")?"dart":t.includes("def ")||t.includes("import ")||t.includes("print(")?"python":t.includes("function ")||t.includes("const ")||t.includes("console.")?"javascript":"dart"}function kn(t){if(!t)return"";if(typeof t!="string")return String(t);const e=/```(?:\w+)?\n?([\s\S]*?)```/,n=t.match(e);return n?n[1].trim():t.trim()}function kc(t){return t=xt(t),t=t.replace(/\*\*(.*?)\*\*/g,'$1'),t=t.replace(/\*(.*?)\*/g,'$1'),t=t.replace(/`(.*?)`/g,'$1'),t=t.replace(/\b(FAIL|ERROR|CRITICAL)\b/g,'$1'),t=t.replace(/\b(WARN|WARNING)\b/g,'$1'),t=t.replace(/\b(PASS|SUCCESS|OK)\b/g,'$1'),t}function Gd(t,e="dart",n=globalThis.hljs){if(!t)return"";const r=kn(t);try{return n.highlight(r,{language:e}).value}catch(i){console.warn("Syntax highlighting failed:",i);try{return n.highlight(r,{language:"json"}).value}catch{return xt(r)}}}function Ki(t,e={}){const{highlighter:n=globalThis.hljs}=e;let r='
    ';const i=String(t??"").split(` -`);let s=!1,o="";for(const a of i){if(a.startsWith("```")){if(s){const l=Qm(o),u=Gd(o.trim(),l,n);r+=`
    -
    ${u}
    -
    `,o="",s=!1}else s=!0;continue}if(s){o+=a+` -`;continue}if(a.startsWith("# ")){const l=a.substring(2).trim();r+=`
    -

    - ${Zm(l)} - ${xt(l)} -

    -
    `;continue}if(a.startsWith("## ")){const l=a.substring(3).trim();r+=`
    -

    - ${Xm(l)} - ${xt(l)} -

    -
    `;continue}if(/^[-*+]\s+/.test(a)||/^\d+\.\s+/.test(a)){const l=a.replace(/^([-*+]|\d+\.)\s+/,"").trim();r+=`
    - • - ${kc(l)} -
    `;continue}a.trim()!==""&&(r+=`

    ${kc(a)}

    `)}return r+="
    ",` -
    -
    -
    - Live Audit Report -
    - ${r} -
    - `}const ev="https://ccc-ffai-runner-y5cyj3473a-uw.a.run.app/deployCustomClasses",tv="phc_KoqpBJCIiWMW5I6HKBM092DVXZbMmE4KkPHqI518pF3",nv="https://us.i.posthog.com";Sd.init(tv,{api_host:nv,person_profiles:"identified_only"});function Kt(t,e={}){try{Sd.capture(t,e)}catch(n){console.error("PostHog tracking failed",n)}}const Ze="https://4tgke4.buildship.run",Kd={professional:"price_1T2ldCKszA2slvDXatdeCpbI",power:"price_1T2le9KszA2slvDXR4mPvw7M"},Ci="ccc_auth_session",Ic=new WeakSet;let z={email:null,sessionToken:null,isVerified:!1};function In(t={}){return{tier:"free",status:"none",periodEnd:null,isLoading:!1,isResolved:!1,error:null,...t}}let pe=In({isResolved:!0});const rv=`${Ze}/service/runpipeline`,iv="bs_user_id",sv="bs_identity_token",ov=`${Ze}/authUserCheck`;let Ke={userId:null,token:null,status:null,resolved:!1};const Fi={free:2,professional:50,power:2e3},Ai="ccc_subscription",Cc=3,av=new Set(["active","trialing","paid"]),fr="google/gemini-3.7-flash",Yr=["anthropic/claude-opus-5","openai/gpt-5.6-sol","z-ai/glm-5.2","moonshotai/kimi-k3","openrouter/auto-beta","openrouter/free","openrouter/deepseek/deepseek-v4-pro"],lv={"google/gemini-3.7-flash":"Gemini 3.7 Flash","anthropic/claude-opus-5":"Claude Opus 5","openai/gpt-5.6-sol":"GPT-5.6 Sol","z-ai/glm-5.2":"GLM 5.2","moonshotai/kimi-k3":"Kimi K3","openrouter/auto-beta":"OpenRouter: Auto Router","openrouter/free":"OpenRouter: Free Models","openrouter/deepseek/deepseek-v4-pro":"DeepSeek v4 Pro"};function Jt(t){return lv[t]||t}const cv=new Set(["google/gemini-3.7-flash","anthropic/claude-opus-5","openai/gpt-5.6-sol","z-ai/glm-5.2","moonshotai/kimi-k3","openrouter/auto-beta"]);function Jd(t){return cv.has(t)}const Lo=4,Ds=8*1024*1024,uv="https://4tgke4.buildship.run/service/runpipeline-image";let Rt=[];function dv(t){return new Promise(e=>{const n=new FileReader;n.onload=()=>e(n.result),n.onerror=()=>e(null),n.readAsDataURL(t)})}async function hv(t){const e=new FormData;return e.append("file",t),(await fetch(uv,{method:"POST",body:e})).json()}function pv(t){if(Array.isArray(t)){const e=t[0];if(e&&typeof e=="object")for(const n of Object.keys(e)){if(n==="item"||n==="index")continue;const r=e[n];if(r&&typeof r=="object"){if(typeof r.file=="string")return r.file;if(typeof r.url=="string")return r.url}if(typeof r=="string")return r}return""}return typeof t=="string"?t:t&&typeof t=="object"&&(t.url||t.fileUrl||t.file_url||t.downloadUrl||t.imageUrl||t.image_url||t.file)||""}async function fv(t){const e=Array.from(t.target.files||[]);if(!e.length)return;const n=e.filter(l=>l.size>Ds);n.length&&ue(`Skipped ${n.length} image(s) over the ${(Ds/1024/1024).toFixed(0)} MB limit.`,"warning");const r=e.filter(l=>l.size<=Ds);if(!r.length){t.target.value="";return}const i=Lo-Rt.length,o=r.slice(0,i).map(async l=>{const u=await dv(l);if(!u)return null;let c="";try{c=pv(await hv(l))}catch{c=""}return{dataUrl:u,name:l.name,url:c}}),a=(await Promise.all(o)).filter(Boolean);t.target.value="",!(a.length&&!Jd(document.getElementById("code-generator-model")?.value))&&(Rt.push(...a),r.length>i&&ue(`You can attach up to ${Lo} images.`,"info"),Ea())}function gv(t){Rt.splice(t,1),Ea()}function Ea(){const t=document.getElementById("prompt-image-thumbnails"),e=document.getElementById("prompt-image-btn-label");t&&(t.innerHTML="",Rt.forEach((n,r)=>{const i=document.createElement("div");i.className="prompt-img-thumb",i.innerHTML=`Prompt image`,t.appendChild(i)}),e&&(e.textContent=Rt.length>=Lo?"Image limit reached":"Add images"))}function Yd(){const t=document.getElementById("prompt-image-upload");if(!t)return;const e=document.getElementById("code-generator-model"),n=Jd(e?.value);t.classList.toggle("hidden",!n),!n&&Rt.length&&(Rt=[],Ea())}const Xt="ccc_usage",Zd="google/gemini-3.7-flash",Xd="google/gemini-3.7-flash",js="google/gemini-3.7-flash",Br={professional:11,power:49},Oo={en_US:"USD",en_GB:"GBP",en_AU:"AUD",en_NZ:"NZD",en_CA:"CAD",en_IN:"INR",en_SG:"SGD",en_HK:"HKD",en_PH:"PHP",en_ZA:"ZAR",en:"USD",de:"EUR",fr:"EUR",es:"EUR",it:"EUR",nl:"EUR",pt_PT:"EUR",pt_BR:"BRL",pt:"BRL",ja:"JPY",ko:"KRW",zh_CN:"CNY",zh_TW:"TWD",zh:"CNY",th:"THB",vi:"VND",id:"IDR",ms_MY:"MYR",ms:"MYR",sv:"SEK",nb:"NOK",da:"DKK",pl:"PLN",cs:"CZK",hu:"HUF",ro:"RON",tr:"TRY",ar:"AED",he:"ILS",ru:"RUB",uk:"UAH"},Zr={AUD:1,USD:.65,EUR:.6,GBP:.52,CAD:.88,NZD:1.08,JPY:97,KRW:870,INR:54,SGD:.87,HKD:5.08,BRL:3.18,CNY:4.7,TWD:20.5,THB:22.5,VND:16200,IDR:10200,MYR:2.88,SEK:6.8,NOK:6.95,DKK:4.48,PLN:2.6,CZK:15.2,HUF:238,RON:2.98,TRY:20.9,AED:2.39,ILS:2.38,PHP:36.4,ZAR:11.8,RUB:58,UAH:26.8,CHF:.57,MXN:11.1,ARS:580,CLP:610,COP:2700,PEN:2.44};let Xr={...Zr};async function mv(){const t=new AbortController,e=setTimeout(()=>t.abort(),5e3);try{const n=await fetch("https://open.er-api.com/v6/latest/AUD",{signal:t.signal});if(!n.ok)return;const r=await n.json();if(r.result!=="success"||!r.rates)return;const i=r.rates,s={AUD:1},o=new Set([...Object.keys(Zr),...Object.values(Bo),...Object.values(Oo)]);for(const a of o)a!=="AUD"&&(typeof i[a]=="number"&&i[a]>0?s[a]=i[a]:Zr[a]&&(s[a]=Zr[a]));Xr=s}catch{}finally{clearTimeout(e)}}const Bo={"America/Sao_Paulo":"BRL","America/Fortaleza":"BRL","America/Recife":"BRL","America/Bahia":"BRL","America/Belem":"BRL","America/Manaus":"BRL","America/Cuiaba":"BRL","America/Campo_Grande":"BRL","America/Araguaina":"BRL","America/Noronha":"BRL","America/Rio_Branco":"BRL","America/Porto_Velho":"BRL","America/Boa_Vista":"BRL","America/Maceio":"BRL","America/Santarem":"BRL","America/Eirunepe":"BRL","Europe/London":"GBP","Europe/Paris":"EUR","Europe/Berlin":"EUR","Europe/Madrid":"EUR","Europe/Rome":"EUR","Europe/Amsterdam":"EUR","Europe/Brussels":"EUR","Europe/Vienna":"EUR","Europe/Lisbon":"EUR","Europe/Dublin":"EUR","Europe/Helsinki":"EUR","Europe/Athens":"EUR","Europe/Bucharest":"RON","Europe/Budapest":"HUF","Europe/Warsaw":"PLN","Europe/Prague":"CZK","Europe/Copenhagen":"DKK","Europe/Stockholm":"SEK","Europe/Oslo":"NOK","Europe/Zurich":"CHF","Europe/Istanbul":"TRY","Europe/Moscow":"RUB","Europe/Kiev":"UAH","Europe/Kyiv":"UAH","Asia/Tokyo":"JPY","Asia/Seoul":"KRW","Asia/Shanghai":"CNY","Asia/Taipei":"TWD","Asia/Hong_Kong":"HKD","Asia/Singapore":"SGD","Asia/Kolkata":"INR","Asia/Calcutta":"INR","Asia/Bangkok":"THB","Asia/Ho_Chi_Minh":"VND","Asia/Jakarta":"IDR","Asia/Kuala_Lumpur":"MYR","Asia/Dubai":"AED","Asia/Jerusalem":"ILS","Asia/Tel_Aviv":"ILS","Asia/Manila":"PHP","Pacific/Auckland":"NZD","Australia/Sydney":"AUD","Australia/Melbourne":"AUD","Australia/Brisbane":"AUD","Australia/Perth":"AUD","Australia/Adelaide":"AUD","Australia/Hobart":"AUD","Australia/Darwin":"AUD","Australia/Lord_Howe":"AUD","America/Toronto":"CAD","America/Vancouver":"CAD","America/Edmonton":"CAD","America/Winnipeg":"CAD","America/Halifax":"CAD","America/St_Johns":"CAD","America/Regina":"CAD","America/New_York":"USD","America/Chicago":"USD","America/Denver":"USD","America/Los_Angeles":"USD","America/Phoenix":"USD","America/Anchorage":"USD","Pacific/Honolulu":"USD","America/Mexico_City":"MXN","America/Cancun":"MXN","America/Tijuana":"MXN","America/Argentina/Buenos_Aires":"ARS","America/Santiago":"CLP","America/Bogota":"COP","America/Lima":"PEN","Africa/Johannesburg":"ZAR"};function Qd(){try{const s=Intl.DateTimeFormat().resolvedOptions().timeZone;if(s&&Bo[s])return Bo[s]}catch{}const e=(navigator.language||"en-US").replace("-","_"),n=Oo[e];if(n)return n;const r=e.split("_")[0],i=Oo[r];return i||"USD"}function Dr(t,e){const n=Xr[e]??Xr.USD,r=t*n,i=Math.round(r*100)/100;try{return new Intl.NumberFormat("en-US",{style:"currency",currency:e,minimumFractionDigits:0,maximumFractionDigits:i>=100||i%1===0?0:2}).format(i)}catch{return new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",minimumFractionDigits:0,maximumFractionDigits:2}).format(t*Xr.USD)}}const st="ccc_api_key_",bt="ccc_session_api_key_",lt="ccc_encryption_key",gr="ccc_encryption_key_scope",vv="ccc_keystore",Pi="keys",mr="ccc_encryption_key_version";let Do=null,$i=null,vr=!1,Ri=!1,Fc=!1;class Ti extends Error{constructor(){super("Secure browser key storage is unavailable."),this.name="CredentialStorageUnavailableError"}}function Ac(){if(Fc)return;Fc=!0;const t="Secure browser key storage is unavailable. Existing credentials were left untouched; new credentials will be available only in this tab session.";console.warn(t),document.body&&ue(t,"warning")}function eh(){return localStorage.getItem(mr)||""}function jo(){return crypto.randomUUID?.()||nh(crypto.getRandomValues(new Uint8Array(16)))}function _v(){const t=eh();if(t)return t;const e=jo();return localStorage.setItem(mr,e),e}function Cn(){Do=null,$i=null,vr=!1,Ri=!1}window.addEventListener("storage",t=>{t.key===mr&&Cn()});function yv(){return new Promise((t,e)=>{const n=indexedDB.open(vv,1);n.onupgradeneeded=()=>{const r=n.result;r.objectStoreNames.contains(Pi)||r.createObjectStore(Pi)},n.onsuccess=()=>t(n.result),n.onerror=()=>e(n.error)})}async function Sa(t,e){const n=await yv();return new Promise((r,i)=>{const s=n.transaction(Pi,t);let o;try{o=e(s.objectStore(Pi))}catch(l){n.close(),i(l);return}let a;o.onsuccess=()=>{a=o.result},o.onerror=()=>i(o.error),s.oncomplete=()=>{n.close(),r(a)},s.onerror=()=>{n.close(),i(s.error||new Error("Encryption key transaction failed."))},s.onabort=()=>{n.close(),i(s.error||new Error("Encryption key transaction aborted."))}})}function wv(t){return t instanceof CryptoKey&&t.algorithm?.name==="AES-GCM"&&t.extractable===!1&&t.usages.includes("encrypt")&&t.usages.includes("decrypt")}async function bv(){const t=await Sa("readonly",e=>e.get(lt));return wv(t)?t:null}async function th(t){await Sa("readwrite",e=>e.put(t,lt))}async function Ev(){Cn();try{await Sa("readwrite",t=>t.delete(lt))}catch(t){console.warn("Could not delete the stored encryption key:",t)}}async function Sv(){const t=sessionStorage.getItem(lt);if(!t)return null;const e=await crypto.subtle.importKey("jwk",JSON.parse(t),{name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);return await th(e),sessionStorage.removeItem(lt),sessionStorage.removeItem(gr),localStorage.removeItem(st+"salt"),e}async function Pc(t){const e=sessionStorage.getItem(lt);if(e)return Ri=sessionStorage.getItem(gr)!=="session",crypto.subtle.importKey("jwk",JSON.parse(e),{name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);if(!t)throw new Ti;const n=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!0,["encrypt","decrypt"]),r=await crypto.subtle.exportKey("jwk",n);return sessionStorage.setItem(lt,JSON.stringify(r)),sessionStorage.setItem(gr,"session"),Ri=!1,crypto.subtle.importKey("jwk",r,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}async function xv(t){if(sessionStorage.getItem(gr)==="session"&&sessionStorage.getItem(lt))return Ac(),vr=!0,Pc(t);try{const e=await bv();if(e)return e;const n=await Sv();if(n)return n;const r=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);return await th(r),r}catch(e){return console.warn("IndexedDB encryption-key storage failed:",e),Ac(),vr=!0,Pc(t)}}async function xa(t={}){const{allowSessionFallbackCreation:e=!0}=t,n=_v();$i!==n&&Cn();const r=Do||xv(e);Do=r,$i=n;try{return await r}catch(i){throw Cn(),i}}async function kv(t){const e=await xa(),n=$i,r=new TextEncoder,i=crypto.getRandomValues(new Uint8Array(12)),s=await crypto.subtle.encrypt({name:"AES-GCM",iv:i},e,r.encode(t)),o=new Uint8Array(i.length+s.byteLength);return o.set(i),o.set(new Uint8Array(s),i.length),{ciphertext:nh(o),keyVersion:n,sessionFallback:vr}}async function Iv(t,e={}){const{isSessionCredential:n=!1}=e;try{const r=await xa({allowSessionFallbackCreation:!1});if(vr&&!n&&!Ri)throw new Ti;const i=Cv(t),s=i.slice(0,12),o=i.slice(12),a=await crypto.subtle.decrypt({name:"AES-GCM",iv:s},r,o);return new TextDecoder().decode(a)}catch(r){if(r instanceof Ti)throw r;return console.error("Decryption failed:",r),null}}function nh(t){const e=new Uint8Array(t);let n="";for(let r=0;r0}let _r="",Mi="",rr=null,Rc=0;async function ka(){sessionStorage.getItem(lt)&&await xa(),_r=await Ee("flutterflow"),Mi=await Ee("flutterflow_project_id"),Rv(),tn()}function Ia(){const t=document.getElementById("api-keys-modal");Ve(t),Fa(),_r&&oh(_r)}function rh(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("api-keys-modal");e&&Xe(e);const n=document.getElementById("walkthrough-modal");n&&(Ca(),Ve(n))}let kt=1;function ih(){const t=document.querySelector(".wt-steps");return t?Array.from(t.querySelectorAll(".wt-step-card")):[]}function Ji(){const t=ih();t.length&&t.forEach((e,n)=>{const r=n+1;if(r===kt){e.classList.remove("opacity-60","bg-gray-50","border-gray-200"),e.classList.add("bg-blue-50","border-blue-200");const i=e.querySelector("div:first-child");i&&(i.classList.remove("bg-gray-400"),i.classList.add("bg-blue-500"),i.innerHTML=r)}else if(r0&&kt<=t&&(kt++,Ji())}function Av(){const t=document.getElementById("walkthrough-modal");t&&(kt=1,Ji(),Ve(t))}function Pv(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("walkthrough-modal");e&&Xe(e);const n=document.getElementById("walkthrough-dont-show");n&&n.checked&&localStorage.setItem("hasSeenWalkthrough","true")}function sh(){if(z.isVerified&&Mt()&&pe.tier!=="free")return;if(!localStorage.getItem("hasSeenWalkthrough")){const e=document.getElementById("walkthrough-modal");e&&(kt=1,Ji(),Ve(e))}}async function Fa(){const t=document.getElementById("flutterflow-api-key-input");_r?(t.value="",t.placeholder="Key saved (enter new to replace)"):t.placeholder="Enter your FlutterFlow API key",$v()}function $v(){Tc("flutterflow","flutterflow-key-status"),Tc("flutterflow_project_id","flutterflow-project-status")}function Tc(t,e){const n=document.getElementById(e);if(!n)return;const r=n.querySelector(".key-status-dot"),i=n.querySelector("span");hn(t)?(r.className="key-status-dot configured",i.className="text-green-600",i.textContent="User key configured"):(r.className="key-status-dot missing",i.className="text-gray-500",i.textContent="Not configured")}function tn(){const t=y.step2Result&&y.step2Result.length>0,e=document.getElementById("btn-deploy-to-ff"),n=document.getElementById("btn-run-pipeline");n&&n.classList.remove("hidden"),e&&e.classList.toggle("hidden",!t)}function Rv(){const t=document.getElementById("api-keys-status");if(!t)return;const e=t.querySelectorAll(".key-status-dot"),n=["flutterflow"];e.forEach((r,i)=>{const s=n[i];s==="flutterflow"?hn("flutterflow")&&hn("flutterflow_project_id")?(r.className="key-status-dot configured",r.title="FlutterFlow (Fully configured)"):hn("flutterflow")||hn("flutterflow_project_id")?(r.className="key-status-dot env",r.title="FlutterFlow (Partially configured)"):(r.className="key-status-dot missing",r.title="FlutterFlow (Not configured)"):hn(s)?(r.className="key-status-dot configured",r.title=s.charAt(0).toUpperCase()+s.slice(1)+" (User key)"):(r.className="key-status-dot missing",r.title=s.charAt(0).toUpperCase()+s.slice(1)+" (Not configured)")}),tn()}async function Tv(){const t=document.getElementById("flutterflow-api-key-input"),e=document.getElementById("flutterflow-projects-select");t.value.trim()&&await $c("flutterflow",t.value);const n=e?.value.trim()||"";if(n){if(!Yi(n)){ue("The selected FlutterFlow project has an unexpected ID format.","error"),e.focus();return}await $c("flutterflow_project_id",n)}await ka(),Fa();const r=document.querySelector("#api-keys-modal .bg-blue-500"),i=r.textContent;r.textContent="Saved!",r.classList.remove("bg-blue-500","hover:bg-blue-600"),r.classList.add("bg-green-500"),setTimeout(()=>{r.textContent=i,r.classList.remove("bg-green-500"),r.classList.add("bg-blue-500","hover:bg-blue-600"),rh()},1e3)}async function Mv(){if(!confirm("Are you sure you want to clear all stored API keys?"))return;localStorage.setItem(mr,jo()),Cn(),localStorage.removeItem(st+"flutterflow"),localStorage.removeItem(st+"flutterflow_project_id"),sessionStorage.removeItem(bt+"flutterflow"),sessionStorage.removeItem(bt+"flutterflow_project_id"),sessionStorage.removeItem(lt),sessionStorage.removeItem(gr),localStorage.removeItem(st+"salt"),await Ev(),localStorage.setItem(mr,jo()),localStorage.removeItem(st+"flutterflow"),localStorage.removeItem(st+"flutterflow_project_id"),sessionStorage.removeItem(bt+"flutterflow"),sessionStorage.removeItem(bt+"flutterflow_project_id"),await ka();const t=document.getElementById("flutterflow-projects-select");t&&(t.innerHTML=''),Fa()}function Yi(t){return!t||t.trim().length<5||t.includes(" ")?!1:/^[a-zA-Z0-9-]+$/.test(t)}function Nv(t,e){const n=document.getElementById(t);n&&(n.value?e?n.style.borderColor="#22c55e":n.style.borderColor="#ef4444":n.style.borderColor="")}function Lv(){const t=document.getElementById("flutterflow-api-key-input");t&&(t.addEventListener("input",e=>{const n=e.target.value.trim().length>0;Nv("flutterflow-api-key-input",n)}),t.addEventListener("blur",Ov(async e=>{const n=e.target.value.trim();n&&await oh(n)},500)))}function Ov(t,e){let n;return function(...i){const s=()=>{clearTimeout(n),t(...i)};clearTimeout(n),n=setTimeout(s,e)}}async function oh(t){const e=document.getElementById("flutterflow-projects-select"),n=document.getElementById("flutterflow-projects-error");if(!e){console.error("Projects dropdown element not found");return}e.innerHTML='',n&&n.classList.add("hidden");try{const i=await new br(t,"").listProjects();if(!i||i.length===0){e.innerHTML='';return}e.innerHTML='',i.forEach(s=>{const o=document.createElement("option");o.value=s.id||s.projectId||"",o.textContent=s.name||s.projectName||`Project ${s.id}`,e.appendChild(o)}),Mi&&(e.value=Mi)}catch(r){console.error("Failed to fetch projects:",r),e.innerHTML='',n&&(n.textContent=`Failed to load projects: ${r.message}`,n.classList.remove("hidden"))}}function Bv(t){const e=document.getElementById(t),r=e.nextElementSibling.querySelector("svg");e.type==="password"?(e.type="text",r.innerHTML=` - - `):(e.type="password",r.innerHTML=` - - - `)}let y={step1Result:null,step2Result:null,step3Result:null,bundleSpec:null,artifactBundle:null,bundleReview:null,selectedArtifactId:null,resultsViewMode:"summary",currentStep:0,isRunning:!1};function Dv(){y.step1Result=null,y.step2Result=null,y.step3Result=null,y.bundleSpec=null,y.artifactBundle=null,y.bundleReview=null,y.selectedArtifactId=null,y.resultsViewMode="summary"}function jv(){y.bundleSpec=hr(y.step1Result,{artifactType:"CustomWidget",artifactName:"GeneratedWidget"})}function Zi(){const t=xi(y.bundleSpec);y.artifactBundle=hr(y.step2Result,{id:y.bundleSpec?.id,title:y.bundleSpec?.title,description:y.bundleSpec?.description,artifactType:t.artifactType,artifactName:t.artifactName,fileName:t.fileName,dependencies:t.dependencies,relationships:y.bundleSpec?.relationships,code:y.step2Result||""});const e=Ng(y.artifactBundle);y.artifactBundle={...y.artifactBundle,warnings:[...y.artifactBundle.warnings,...e.findings.map(n=>n.message)],metadata:{...y.artifactBundle.metadata,compatibility:e}},y.selectedArtifactId=xi(y.artifactBundle).id}function Xi(){const t=hr(y.step3Result,{id:y.artifactBundle?.id,title:y.artifactBundle?.title}),e=new Map(t.artifacts.map(r=>[r.id,r.review])),n=new Map(t.artifacts.filter(r=>{const i=r.review;return i&&typeof i.fixedSource=="string"&&i.fixedSource.trim()}).map(r=>[r.id,r.review.fixedSource.trim()]));y.bundleReview=hr({id:y.artifactBundle?.id,title:y.artifactBundle?.title,artifacts:y.artifactBundle?.artifacts?.map(r=>{const i=n.get(r.id)||null;return{...r,review:e.get(r.id)||r.review||y.step3Result||null,...i?{fixedCode:i}:{}}})||[],relationships:y.artifactBundle?.relationships,warnings:y.artifactBundle?.warnings})}function ah(){const t=Aa();return{artifactType:t.artifactType||"CustomWidget",artifactName:t.artifactName||"GeneratedWidget",fileName:t.fileName||""}}function Aa(){const t=y.artifactBundle||y.bundleSpec||null;return(Array.isArray(t?.artifacts)?t.artifacts:[]).find(n=>n.id===y.selectedArtifactId)||xi(t)}function Pa(){return Aa().code||y.step2Result||""}async function Uv(){try{await ka()}catch(t){return console.error("checkConnection: initializeApiKeys failed:",t),!1}return!0}const Qr={production:"https://api.flutterflow.io/v2/",staging:"https://api.flutterflow.io/v2-staging/"};function Hv(t,e){const n=e?.trim()?` (${e.trim().slice(0,200)})`:"";return t===401?`Your FlutterFlow API key was rejected (401 Unauthorized)${n}. Re-enter a current key under API Keys settings, then try again.`:`Listing FlutterFlow projects was denied (403)${n}. The key may be scoped to sync a single project without list permission - verify the key's access in FlutterFlow, re-enter it under API Keys settings, then retry.`}class br{constructor(e,n,r="main",i=Qr.production){this.apiKey=e,this.baseUrl=i,this._projectId=n,this._branchName=r,this._endpoint=i}get projectId(){return this._projectId}get branchName(){return this._branchName==="main"?"":this._branchName}async exportProjectZip(){console.log(`Exporting code from FlutterFlow project: ${this.projectId}, branch: ${this.branchName||"main"}`);const e=[{project:{path:`projects/${this.projectId}`},...this.branchName?{branch_name:this.branchName}:{},export_as_module:!1,include_assets_map:!1,format:!1,export_as_debug:!1},{project_id:this.projectId,branch_name:this.branchName,include_assets:!1,export_as_module:!1}];let n=null;for(const r of e)try{const i=await fetch(`${this.baseUrl}exportCode`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify(r)});if(!i.ok){const a=await i.text();n=new Error(`Export failed: ${i.status} - ${a}`);continue}const s=await i.json(),o=s?.value?.project_zip||s?.project_zip;if(!o){n=new Error("Export response did not include project source.");continue}return o}catch(i){n=i}throw n||new Error("Export failed for an unknown reason.")}async fetchProjectSource(){const e=await this.exportProjectZip(),n=await JSZip.loadAsync(e,{base64:!0}),r=Object.keys(n.files).filter(a=>!n.files[a].dir&&(a==="pubspec.yaml"||a.endsWith("/pubspec.yaml"))).sort((a,l)=>a.split("/").length-l.split("/").length)[0];if(!r)throw new Error("Export did not contain a pubspec.yaml.");const i=r.slice(0,r.length-12),s=new Map,o=Object.keys(n.files).filter(a=>{if(n.files[a].dir||!a.startsWith(i))return!1;const l=a.slice(i.length);return l==="lib/flutter_flow/custom_functions.dart"||l.startsWith("lib/custom_code/")&&l.endsWith(".dart")});return await Promise.all(o.map(async a=>{s.set(a.slice(i.length),await n.files[a].async("string"))})),{pubspecYaml:await n.files[r].async("string"),files:s}}async pushCodeWithRetry(e,n=3){const r=[Qr.production,Qr.staging],i=Math.max(0,r.indexOf(this._endpoint));for(let s=0;ssetTimeout(d,1e3*(s+1)));continue}return l}catch(l){console.warn(`Push to ${a} failed: ${l.message}, trying next...`),await new Promise(u=>setTimeout(u,1e3*(s+1)))}}throw new Error("All API endpoints failed after retries")}async pushCode(e){return this.pushCodeWithRetry(e)}parseProjectsResponse(e){if(e?.success&&typeof e.value=="string")try{const r=JSON.parse(e.value);if(r&&Array.isArray(r.entries))return r.entries.map(i=>({id:i.id,name:i.project?.name||i.id}))}catch(r){console.error("Failed to parse stringified project value:",r)}const n=e?.projects||e?.items||e?.entries||(Array.isArray(e)?e:[]);return Array.isArray(n)?n:[]}async listProjects(){console.log("Listing projects for API key");const e=[`${this.baseUrl}listProjects`,"https://api.flutterflow.io/v2/l/listProjects"];let n=0,r="";for(const i of e){const s=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify({project_type:"ALL",deserialize_response:!0})});if(s.ok)return i!==e[0]&&console.log(`listProjects answered on legacy path ${i}`),this.parseProjectsResponse(await s.json());if(n=s.status,r=await s.text(),console.warn(`listProjects via ${i} returned ${n}: ${r}`),s.status===401||s.status===403)throw new Error(Hv(s.status,r));if(s.status!==404)throw new Error(`List projects failed: ${s.status} - ${r}`)}throw new Error(`List projects failed: ${n} - ${r}`)}}async function $a(t){const e=t.clone();let n;try{n=await t.json()}catch{const s=await e.text();if(!t.ok)return{success:!1,responseCode:t.status,errorMessage:s||`HTTP ${t.status}`,errorMap:new Map};throw new Error(`Invalid JSON response: ${s}`)}if(!t.ok){let i=n.message||`HTTP ${t.status}`,s=new Map;if(n.errors)s=new Map(Object.entries(n.errors));else if(!n.message&&typeof n=="object"){const o=Object.keys(n).filter(a=>a.endsWith(".dart")&&Array.isArray(n[a]));o.length>0&&(s=new Map(Object.entries(n)),i=o.flatMap(l=>n[l].map(u=>`${l}: ${u.errorMessage}`)).join(` -`)||`HTTP ${t.status}`)}return{success:!1,responseCode:t.status,errorMessage:i,errorMap:s}}let r={};if(n.value)try{r=typeof n.value=="string"?JSON.parse(n.value):n.value}catch(i){console.warn("Ignoring malformed push response value:",i)}return{success:!0,responseCode:t.status,errorMap:new Map(Object.entries(r))}}function Ra(t,e){return{401:"Authentication failed. Please check your FlutterFlow API key.",403:"Access denied. You may not have permission to modify this project.",404:"Project not found. Please check your Project ID.",409:"Conflict detected. The project may have been modified elsewhere.",422:"Validation failed: Invalid request format",429:"Rate limit exceeded. Please try again in a few minutes.",500:"FlutterFlow server error. Please try again later.",503:"FlutterFlow service temporarily unavailable."}[t]||`FlutterFlow API error: ${`HTTP ${t}`}`}const U={ACTION:"A",WIDGET:"W",FUNCTION:"F",CODE_FILE:"C",DEPENDENCIES:"D",OTHER:"O"},lh=/class\s+\w+\s+extends\s+(?:StatelessWidget|StatefulWidget)\b/,ch=/extends\s+State<\w+>/;function Wv(t,e=""){if(t==="pubspec.yaml")return U.DEPENDENCIES;if(!t.endsWith(".dart")||t.endsWith("index.dart"))return U.OTHER;if(t==="custom_functions.dart")return U.FUNCTION;if(e){const n=lh.test(e),r=ch.test(e);if(n||r)return U.WIDGET;if(/^\s*Future(?:<[^>]+>)?\s+\w+\s*\(/m.test(e))return U.ACTION;if(e.match(/^\s*(String|int|double|bool|List|Map|dynamic|void)\s+\w+\s*\(/m))return U.FUNCTION}return U.CODE_FILE}function uh(t,e){switch(e){case U.ACTION:return`lib/custom_code/actions/${t}`;case U.WIDGET:return`lib/custom_code/widgets/${t}`;case U.FUNCTION:return"lib/flutter_flow/custom_functions.dart";case U.CODE_FILE:return`lib/custom_code/${t}`;case U.DEPENDENCIES:return"pubspec.yaml";case U.OTHER:return`lib/custom_code/${t}`;default:return t}}async function Ta(t,e=new Map){return vg(t,e)}const Uo=new Map;function dh(t){return`${t.baseUrl}|${t.projectId}|${t.branchName}`}function Qi(t){Uo.delete(dh(t))}async function Ma(t,e,n,r,i=""){const s=Jg(e,n);if(s.length===0)return{remoteFiles:n,syncFileMap:e,unverified:[],approximate:[]};const o=Nm(s,i),a={...o.manifest,sources:o.sources},l=o.skipped.map(h=>h.reason);l.forEach(h=>console.warn(`[custom class deploy] ${h}`));const u=o.approximate;u.forEach(h=>console.warn(`[custom class deploy] ${h}`)),console.log(`Provisioning ${s.length} new FlutterFlow custom code file(s) before sync.`),be.set("provision");const c=await fetch(ev,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:t.apiKey,projectId:t.projectId,baseUrl:t.baseUrl,commitMessage:r,customClasses:s,verification:a,stream:!0})}),d=await Om(c,{onPhase:h=>be.setSubstatus(h),onLog:h=>console.log(`[custom class deploy] ${h}`)});if(!d.success){const h=d.details?` ${d.details}`:"";throw new Error(`${d.error||"FlutterFlow custom class provisioning failed."}${h}`)}return Qi(t),d.verificationSkipped&&(console.warn(`[custom class deploy] ${d.verificationSkipped}`),l.push(d.verificationSkipped)),{remoteFiles:n,syncFileMap:Yg(e,s),unverified:l,approximate:u}}async function Na(t,e={}){const n=dh(t);let r=Uo.get(n);if(r===void 0){try{r=await t.fetchProjectSource()}catch(l){throw new Error(`Could not read your project's pubspec.yaml (${l.message}). Deploy was stopped so your existing package dependencies aren't overwritten. Check your FlutterFlow API key and project, then try again.`)}const a=qd(r.pubspecYaml);if(!a.valid)throw new Error(`Your project's pubspec.yaml could not be read reliably (${a.errors.join("; ")}). Deploy was stopped so your existing package dependencies aren't overwritten.`);Uo.set(n,r)}const i=await Km(r.pubspecYaml,e),s=Pm(r.pubspecYaml,i.overrides),o=Am(s.yaml,i.additions);return i.warnings.forEach(a=>console.warn(`[pubspec] ${a}`)),o.added.length>0&&console.log("Adding dependencies:",o.added.map(a=>`${a}: ${i.additions[a]||"any"}`).join(", "),i.sdk.dartSdkFloor?`(resolved for Dart ${i.sdk.dartSdkFloor})`:""),i.kept.forEach(({name:a,constraint:l})=>console.log(`Keeping your existing ${a}: ${l||"(non-version source)"}`)),{...o,overridden:s.overridden,warnings:i.warnings,remoteFiles:r.files}}function zv(t){const e=[],n=[];t.content.length>5e4&&n.push("Code file is large (>50KB). This may take longer to commit."),t.content.length>1e5&&e.push("Code file is too large (>100KB). Consider splitting into smaller components.");const r=t.content.split(` -`).length;r>500&&n.push(`Code has ${r} lines. Consider breaking it into smaller widgets.`),t.content.includes("setState")&&t.codeType===U.ACTION&&n.push("Using setState in a Custom Action may not work as expected. Consider using a Custom Widget."),t.content.includes("dynamic")&&!t.content.includes("?")&&n.push('Code uses "dynamic" types. Consider adding explicit types for better null safety.'),t.content.match(/Color\(0xFF[0-9A-Fa-f]{6}\)/)&&n.push("Code contains hardcoded colors. Consider using FlutterFlowTheme.of(context) for theme consistency.");const i=t.content.match(/print\s*\(/g);i&&i.length>3&&n.push(`Code contains ${i.length} print statements. Consider removing debug prints before committing.`);const s=fm(t.content);if(s&&e.push(`FlutterFlow cannot format this code - ${s}. Fix or regenerate before committing.`),t.codeType===U.WIDGET){const o=Od(t.content),a=dm(t.fileName);if(o.length===0)e.push("No public widget class found (must extend StatelessWidget or StatefulWidget).");else if(!o.includes(a)){const l=`${Bd(o[0])}`;e.push(`Widget class name "${o[0]}" does not match the file name "${t.fileName}". FlutterFlow derives the widget from the file name, so it will report "No widget ${a} found". Rename the file to "${l}" or the class to match before committing.`)}}return{canProceed:e.length===0,issues:e,warnings:n}}function hh(t,e={}){const{artifactType:n="CustomWidget",artifactName:r="GeneratedCode",fileName:i}=e,s=cm(t);let o=i||r;if(n==="CustomFunction")o="custom_functions.dart";else if(n==="CustomWidget"){const u=Od(s)[0],c=u?Bd(u):null;c&&o!==c?(console.warn(`Commit file name "${o}" does not match declared widget class "${u}"; renaming to "${c}" so FlutterFlow can find the widget.`),o=c):o.endsWith(".dart")||(o+=".dart")}else o.endsWith(".dart")||(o+=".dart");let a=U.CODE_FILE;switch(n){case"CustomAction":a=U.ACTION;break;case"CustomWidget":a=U.WIDGET;break;case"CustomFunction":a=U.FUNCTION;break;case"CustomClass":case"CodeFile":a=U.CODE_FILE;break}let l="";return a===U.WIDGET?l=`// Automatic FlutterFlow imports -import '/flutter_flow/flutter_flow_theme.dart'; -import '/flutter_flow/flutter_flow_util.dart'; -import 'package:flutter/material.dart'; -// Begin custom widget code -// DO NOT REMOVE OR MODIFY THE CODE ABOVE! - -`:a===U.ACTION?l=`// Automatic FlutterFlow imports -import '/flutter_flow/flutter_flow_theme.dart'; -import '/flutter_flow/flutter_flow_util.dart'; -import 'package:flutter/material.dart'; -// Begin custom action code -// DO NOT REMOVE OR MODIFY THE CODE ABOVE! - -`:a===U.FUNCTION&&(l=`// Automatic FlutterFlow imports -import 'dart:convert'; -import 'dart:math' as math; - -import 'package:flutter/material.dart'; -import 'package:google_fonts/google_fonts.dart'; -import 'package:intl/intl.dart'; -import 'package:timeago/timeago.dart' as timeago; -import '/flutter_flow/lat_lng.dart'; -import '/flutter_flow/place.dart'; -import '/flutter_flow/uploaded_file.dart'; - -`),{content:Bg(s,l),fileName:o,codeType:a,artifactType:n,artifactName:r}}function qv(t){const e={};for(const n of va(t))e[n]="";return e}function Vv(t,e={}){return{timestamp:new Date().toISOString(),artifactType:t.artifactType,artifactName:t.artifactName,codeType:t.codeType,fileName:t.fileName,generatedFrom:e.step1Result?"pipeline":"direct",model:e.selectedModel||"unknown",codeSize:t.content.length}}function Gv(t,e,n,r=new Set,i=""){const s=[],o=lh.test(e),a=ch.test(e);return n===U.WIDGET&&!o&&!a&&s.push("No widget class definition found (must extend StatelessWidget or StatefulWidget)"),{valid:s.length===0,errors:s}}function es(t){const e=[],n=[];if(!t||t.size===0)return e.push("No files to commit"),{valid:!1,errors:e,warnings:n};const r=new Set(Array.from(t.values()).flatMap(i=>Hi(i.content||"")));for(const[i,s]of t.entries()){if((!s.content||s.content.trim().length===0)&&e.push(`File ${i} is empty`),s.content&&s.content.length>1e5&&n.push(`File ${i} is very large (>100KB)`),i.endsWith(".dart")){const o=Gv(i,s.content,s.type,r,s.artifactName);o.valid||e.push(...o.errors.map(a=>`${i}: ${a}`))}if(i==="pubspec.yaml"){const o=qd(s.content);o.valid||e.push(...o.errors)}}return{valid:e.length===0,errors:e,warnings:n}}const G={IDLE:"IDLE",PREPARING:"PREPARING",VALIDATING:"VALIDATING",PUSHING:"PUSHING",SUCCESS:"SUCCESS",ERROR:"ERROR"},K={currentState:G.IDLE,startTime:null,endTime:null,error:null,result:null,filesProcessed:0,totalFiles:0,reset(){this.currentState=G.IDLE,this.startTime=null,this.endTime=null,this.error=null,this.result=null,this.filesProcessed=0,this.totalFiles=0},setState(t){if(!Object.values(G).includes(t)){console.error(`Invalid commit state: ${t}`);return}this.currentState=t,t===G.PREPARING&&(this.startTime=Date.now()),(t===G.SUCCESS||t===G.ERROR)&&(this.endTime=Date.now()),typeof window<"u"&&window.dispatchEvent&&window.dispatchEvent(new CustomEvent("commitStateChange",{detail:{state:t,commitState:this}})),console.log(`Commit state changed to: ${t}`)},setError(t){this.error=t,this.setState(G.ERROR)},setSuccess(t){this.result=t,this.setState(G.SUCCESS)},setProgress(t,e){this.filesProcessed=t,this.totalFiles=e},getElapsedTime(){return this.startTime?(this.endTime||Date.now())-this.startTime:null},isInProgress(){return this.currentState===G.PREPARING||this.currentState===G.VALIDATING||this.currentState===G.PUSHING}};async function Kv(t,e,n={}){let{codeType:r="W"}=n;const{pubspecDeps:i={},artifactName:s=e}=n;r==="CustomWidget"&&(r=U.WIDGET),r==="CustomAction"&&(r=U.ACTION),r==="CustomFunction"&&(r=U.FUNCTION),r==="CustomClass"&&(r=U.CODE_FILE),r==="CodeFile"&&(r=U.CODE_FILE),K.reset(),K.setState(G.PREPARING);try{const o=await Ee("flutterflow"),a=await Ee("flutterflow_project_id");if(!o||!a)throw new Error("FlutterFlow credentials not configured. Please set your API key and Project ID in the API Keys settings.");if(!Yi(a))throw new Error("Invalid FlutterFlow Project ID format.");const l=wr(),u=new br(o,a,"main",l);K.setState(G.VALIDATING);const c=new Map,d=r||Wv(e,t),h=uh(e,d);c.set(e,{artifactName:s,content:t,type:d,path:h}),K.setProgress(0,c.size);const p=es(c);if(!p.valid)throw new Error(`Validation failed: -${p.errors.join(` -`)}`);const f=await Na(u,i),g=f.yaml,m=await Ma(u,c,f.remoteFiles,`Provision ${s} custom class`,g),_=await Ta(m.syncFileMap,m.remoteFiles),w=new Map(m.syncFileMap);w.set("pubspec.yaml",{content:g,type:"D",path:"pubspec.yaml"}),be.set("package");const b=await La(w),I={project_id:a,zipped_custom_code:b,uid:`web_${Date.now()}`,branch_name:u.branchName,serialized_yaml:g,file_map:_.fileMapContents,functions_map:_.functionsMapContents};K.setState(G.PUSHING),K.setProgress(1,c.size),Qi(u),be.set("push");const F=await u.pushCode(I),A=await $a(F);if(A.success)K.setSuccess({fileCount:c.size,projectId:a,warnings:A.errorMap&&A.errorMap.size>0?Array.from(A.errorMap.entries()):[]});else{const j=A.errorMessage||Ra(A.responseCode);throw new Error(j)}return{success:!0,message:`Successfully committed ${e} to FlutterFlow project ${a}`,addedDependencies:f.added,unverified:m.unverified,approximate:m.approximate,warnings:A.errorMap?Array.from(A.errorMap.entries()):[]}}catch(o){return console.error("Commit failed:",o),K.setError(o),{success:!1,error:o.message,state:K.currentState}}}async function La(t){const e=new JSZip;for(const[n,r]of t.entries())e.file(n,r.content);return e.generateAsync({type:"base64",compression:"DEFLATE",compressionOptions:{level:6}})}async function Jv(t,e={}){const{artifactType:n,artifactName:r,fileName:i,pipelineResult:s}=e;console.log(`Starting commit for ${r} (${n})`);try{K.setState(G.PREPARING);const o=hh(t,{artifactType:n,artifactName:r,fileName:i}),a=qv(o.content);console.log("Detected dependencies:",a),K.setState(G.VALIDATING);const l=await Ee("flutterflow"),u=rr||await Ee("flutterflow_project_id");if(!l)throw new Error("FlutterFlow API Key not configured. Please add it in API Keys settings.");if(!u)throw new Error("FlutterFlow Project ID not configured. Please add it in API Keys settings.");if(!Yi(u))throw new Error("Invalid FlutterFlow Project ID format.");const c=new Map;c.set(o.fileName,{artifactName:r,content:o.content,type:o.codeType,path:uh(o.fileName,o.codeType),functionName:o.codeType===U.FUNCTION?r:void 0}),K.setProgress(0,c.size);const d=es(c);if(!d.valid)throw new Error(`File validation failed: -${d.errors.join(` -`)}`);d.warnings.length>0&&console.warn("Validation warnings:",d.warnings),K.setState(G.PUSHING);const h=wr(),p=new br(l,u,"main",h),f=await Na(p,a),g=f.yaml,m=await Ma(p,c,f.remoteFiles,`Provision ${r} custom class`,g),_=await Ta(m.syncFileMap,m.remoteFiles),w=new Map(m.syncFileMap);w.set("pubspec.yaml",{content:g,type:U.DEPENDENCIES,path:"pubspec.yaml"}),be.set("package");const b=await La(w),I={project_id:u,zipped_custom_code:b,uid:`web_${Date.now()}`,branch_name:p.branchName,serialized_yaml:g,file_map:_.fileMapContents,functions_map:_.functionsMapContents};K.setProgress(1,c.size),Qi(p),be.set("push");const F=await p.pushCode(I),A=await $a(F);if(A.success){const j={...Vv(o,s),projectId:u};return K.setSuccess({...j,fileCount:c.size,warnings:A.errorMap?Array.from(A.errorMap.entries()):[]}),{success:!0,message:`Successfully committed ${o.fileName} to FlutterFlow`,metadata:j,addedDependencies:f.added,unverified:m.unverified,approximate:m.approximate,warnings:A.errorMap?Array.from(A.errorMap.entries()):[],elapsedTime:K.getElapsedTime()}}else{const j=A.errorMessage||Ra(A.responseCode),S=new Error(j);throw S.errorMap=A.errorMap,S}}catch(o){console.error("Commit execution failed:",o),K.setError(o);let a=new Map;if(o.errorMap)a=o.errorMap;else if(o.message&&o.message.includes("{"))try{const l=o.message.match(/\{[\s\S]*\}/);if(l){const u=JSON.parse(l[0]);a=new Map(Object.entries(u))}}catch(l){console.warn("Failed to parse error map from commit response:",l)}return{success:!1,error:o.message,errorMap:a,state:K.currentState,elapsedTime:K.getElapsedTime()}}}async function Yv(t,e={}){const{pipelineResult:n}=e;try{if(K.setState(G.PREPARING),t.errors?.length>0)throw new Error(`Bundle validation failed: -${t.errors.join(` -`)}`);const r=new Map(t.fileEntries.map(I=>[I.fileName,{artifactId:I.artifactId,artifactName:I.artifactName,content:I.content,type:I.type,path:I.path,functionName:I.type===U.FUNCTION?I.artifactName:void 0}]));K.setProgress(0,r.size);const i=es(r);if(!i.valid)throw new Error(`File validation failed: -${i.errors.join(` -`)}`);K.setState(G.VALIDATING);const s=await Ee("flutterflow"),o=rr||await Ee("flutterflow_project_id");if(!s)throw new Error("FlutterFlow API Key not configured. Please add it in API Keys settings.");if(!o)throw new Error("FlutterFlow Project ID not configured. Please add it in API Keys settings.");if(!Yi(o))throw new Error("Invalid FlutterFlow Project ID format.");K.setState(G.PUSHING);const a=wr(),l=new br(s,o,"main",a),u=await Na(l,t.dependencies),c=u.yaml,d=await Ma(l,r,u.remoteFiles,`Provision ${t.title} custom classes`,c),h=await Ta(d.syncFileMap,d.remoteFiles),p=new Map(d.syncFileMap);p.set("pubspec.yaml",{content:c,type:U.DEPENDENCIES,path:"pubspec.yaml"}),be.set("package");const f=await La(p),g={project_id:o,zipped_custom_code:f,uid:`web_${Date.now()}`,branch_name:l.branchName,serialized_yaml:c,file_map:h.fileMapContents,functions_map:h.functionsMapContents};K.setProgress(1,r.size),Qi(l),be.set("push");const m=await l.pushCode(g),_=await $a(m);if(_.success){const I={...n,artifactType:"Bundle",artifactName:t.title,fileName:`${t.fileEntries.length} artifacts`,codeSize:t.fileEntries.reduce((F,A)=>F+A.content.length,0),projectId:o};return K.setSuccess({...I,fileCount:r.size,warnings:_.errorMap?Array.from(_.errorMap.entries()):[]}),{success:!0,message:`Successfully committed ${t.fileEntries.length} artifacts to FlutterFlow`,metadata:I,addedDependencies:u.added,unverified:d.unverified,approximate:d.approximate,warnings:_.errorMap?Array.from(_.errorMap.entries()):[],elapsedTime:K.getElapsedTime()}}const w=_.errorMessage||Ra(_.responseCode),b=new Error(w);throw b.errorMap=_.errorMap,b}catch(r){return console.error("Bundle commit execution failed:",r),K.setError(r),{success:!1,error:r.message,errorMap:r.errorMap||new Map,state:K.currentState,elapsedTime:K.getElapsedTime()}}}async function Zv(t,e=[]){const n=pa("architect");try{return await Ni("architect",Zd,sg(t),n,e)}catch(r){throw r.isModelArmor?r:new Error(`Prompt Architect failed: ${r.message}`)}}async function ts(t,e,n=[]){const r=og(t),i=pa("generator",y.bundleSpec);try{return await Ni("generator",e,r,i,n)}catch(s){if(s.isModelArmor)throw s;if(e!==js){console.warn(`Code Generator failed with ${e}, retrying with fallback model:`,s.message);try{return await Ni("generator",js,r,i,n)}catch(o){throw o.isModelArmor?o:new Error(`Code Generator failed: primary (${e}): ${s.message} | fallback (${js}): ${o.message}`)}}throw new Error(`Code Generator failed: ${s.message}`)}}async function ns(t,e=null){const n={...pa("review",y.artifactBundle||y.bundleSpec),architect_output:e};try{return await Ni("review",Xd,ag(t),n)}catch(r){throw r.isModelArmor?r:new Error(`Code Review failed: ${r.message}`)}}function Oa(t,e){return t.isModelArmor?`${t.userTitle}: ${t.userMessage}`:`${e}: ${t.message}`}function Ho(t,e){const n=document.getElementById(`step${t}-item`),r=document.getElementById(`step${t}-status`);!n||!r||(n.classList.remove("active","completed","error"),r.classList.remove("running","completed","error"),e==="active"?(n.classList.add("active"),r.classList.add("running"),r.innerHTML=` - - `):e==="completed"?(n.classList.add("completed"),r.classList.add("completed"),r.innerHTML=` - - `):e==="error"?(n.classList.add("error"),r.classList.add("error"),r.innerHTML=` - - `):r.innerHTML=` - - `)}function ve(t,e){const n=document.getElementById(`step${t}-loading`),r=document.getElementById(`step${t}-result`);e?(n.classList.remove("hidden"),r.classList.add("hidden"),Ho(t,"active")):(n.classList.add("hidden"),r.classList.remove("hidden"),Ho(t,"completed"))}function Xv(t){const e=document.getElementById(`${t}-content`),n=document.getElementById(`${t}-chevron`);e.classList.contains("open")?(e.classList.remove("open"),n&&(n.style.transform="rotate(0deg)")):(e.classList.add("open"),n&&(n.style.transform="rotate(180deg)"))}function Qv(t){ze(parseInt(t.replace("step","")))}function ze(t){for(let o=1;o<=3;o++){const a=document.getElementById(`step${o}-item`);a&&a.classList.remove("active")}const e=document.getElementById(`step${t}-item`);e&&e.classList.add("active"),en();const n=document.getElementById("ready-state");n&&n.classList.add("hidden");for(let o=1;o<=3;o++){const a=document.getElementById(`step${o}-content`);a&&a.classList.add("hidden")}const r=document.getElementById(`step${t}-content`);r&&r.classList.remove("hidden");const i=document.getElementById("stage-title"),s={1:"Prompt Architect",2:"Code Generator",3:"Code Review"};i&&(i.textContent=s[t]||"Active Workflow Stage")}function e_(t){const e=document.getElementById(t);if(!e)return;const n=e.dataset.raw||e.textContent;navigator.clipboard.writeText(n).then(()=>{Kt("Code Copied",{elementId:t});const i=e.closest(".code-container")?.querySelector(".copy-btn");i&&(i.classList.add("copied"),i.innerHTML=' Copied!',setTimeout(()=>{i.classList.remove("copied"),i.innerHTML=' Copy'},2e3))}).catch(r=>{console.warn("Failed to copy to clipboard:",r)})}function Wo(t){const e=qo(t);console.log(`Step 1 (Prompt Architect): ${Jt(Zd)}`),console.log(e!==t?`Step 2 (Code Generator): ${Jt(t)} → ${Jt(e)} (Free Tier fallback)`:`Step 2 (Code Generator): ${Jt(t)}`),console.log(`Step 3 (Code Review): ${Jt(Xd)}`)}async function t_(){if(console.log("runRefinement called"),y.isRunning)return;const t=document.getElementById("code-generator-model").value;y.isRunning=!0,Ba("standardRegenerate",y.step2Result,y.step1Result);const e=document.querySelectorAll(".btn-refine-action");e.forEach(n=>{n.disabled=!0,n.innerHTML=` - - - Refining...`});try{const n=Aa(),r=lg({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,artifactId:n.id,userFeedback:"Fix the issues listed in the audit report."});os(),at(2),ze(2),ve(2,!0),y.step2Result=await ts(r,t),Zi();const i=document.getElementById("step2-output"),s=kn(y.step2Result);i.textContent=s,i.dataset.raw=s,ve(2,!1),ze(3),at(3),ve(3,!0),y.step3Result=await ns(y.step2Result,y.step1Result),Xi();const o=document.getElementById("step3-output");o.textContent=y.step3Result,ve(3,!1),Nt();const a=Ki(y.step3Result);as(s,a)}catch(n){console.error("Refinement failed:",n),Nt(),ue(Oa(n,"Refinement failed"),"error")}finally{y.isRunning=!1,e.forEach(n=>{n.disabled=!1,n.textContent="Refine & Regenerate"}),tn()}}async function Ba(t,e,n){const r=`${Ze}/connectFeedback`,i={type:t,code:e,input:n};try{const s=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)});if(!s.ok){const a=await s.text();return console.error(`callEndpoint failed: ${s.status} ${s.statusText}`,a),{success:!1,status:s.status,error:a}}const o=await s.json();return console.log("Telemetry success:",o),o}catch(s){return console.error("callEndpoint failed:",s),{success:!1,error:s.message}}}function n_(){const t=document.getElementById("ff-error-paste-input");t&&(t.value="")}async function r_(){const t=document.getElementById("ff-error-paste-input"),e=t?.value?.trim();if(!e){t?.focus(),t?.classList.add("ring-2","ring-red-400","border-red-300"),setTimeout(()=>t?.classList.remove("ring-2","ring-red-400","border-red-300"),2e3);return}if(!y.step2Result){ue("No generated code found. Please run the full pipeline first.","warning");return}if(y.isRunning)return;const n=document.getElementById("code-generator-model").value;y.isRunning=!0,Ba("flutterflowError",y.step2Result,e);const r=document.getElementById("btn-fix-from-errors");r&&(r.disabled=!0,r.innerHTML=` - - Fixing…`);try{const i=Rd({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,userFeedback:e});xh(),os(),at(2),ze(2),ve(2,!0),y.step2Result=await ts(i,n),Zi();const s=document.getElementById("step2-output"),o=kn(y.step2Result);s.textContent=o,s.dataset.raw=o,ve(2,!1),ze(3),at(3),ve(3,!0),y.step3Result=await ns(y.step2Result,y.step1Result),Xi();const a=document.getElementById("step3-output");a.textContent=y.step3Result,ve(3,!1),Nt();const l=Ki(y.step3Result);as(o,l),t&&(t.value="")}catch(i){console.error("Fix from errors failed:",i),Nt(),ue(Oa(i,"Failed to fix errors"),"error")}finally{y.isRunning=!1,r&&(r.disabled=!1,r.textContent="Fix Errors & Regenerate"),tn()}}async function zo(){if(console.log("runThinkingPipeline called"),y.isRunning)return;localStorage.setItem("hasSeenWalkthrough","true");const t=document.getElementById("pipeline-input").value,e=document.getElementById("code-generator-model").value;if(!t.trim()){ue("Please describe your FlutterFlow widget first.","warning");return}if(!await S_())return;await v_();const n=qo(e);Kt("Pipeline Started",{selectedModel:e,effectiveModel:n,inputLength:t.length});const r=document.getElementById("btn-run-pipeline");y.isRunning=!0,Dv(),r.disabled=!0,r.innerHTML=` - - - Running...`,Wo(n);try{en();const i=document.getElementById("ready-state");i&&i.classList.add("hidden");const s=document.getElementById("paywall-exhausted");s&&s.classList.add("hidden"),os(),ze(1),at(1),ve(1,!0);const o=Rt.filter(p=>p.url).map(p=>({url:p.url}));y.step1Result=await Zv(t,o),jv(),Kt("Prompt Architect Completed");const a=document.getElementById("step1-output"),l=kn(y.step1Result);a.textContent=l,a.dataset.raw=l,ve(1,!1),ze(2),at(2),ve(2,!0),y.step2Result=await ts(y.step1Result,n,o),Zi(),Kt("Code Generator Completed");const u=document.getElementById("step2-output"),c=kn(y.step2Result);u.textContent=c,u.dataset.raw=c,ve(2,!1),ze(3),at(3),ve(3,!0),y.step3Result=await ns(y.step2Result,y.step1Result),Xi(),Kt("Code Review Completed");const d=document.getElementById("step3-output");d.textContent=y.step3Result,ve(3,!1),Nt();const h=Ki(y.step3Result);as(c,h)}catch(i){if(console.error("Pipeline failed:",i),Nt(),i.isUsageLimit){const{count:c}=Er();Ha(c,is(),{openModal:!0});return}Kt("Pipeline Failed",{error:i.message,effectiveModel:qo(document.getElementById("code-generator-model").value)});const o=Ym(i,{architect:1,generator:2,review:3});ze(o);const a=document.getElementById(`step${o}-result`),l=document.getElementById(`step${o}-loading`),u=document.getElementById(`step${o}-output`);if(l&&l.classList.add("hidden"),a&&a.classList.remove("hidden"),u)if(i.isModelArmor)u.innerHTML=``;else{let c=i.message;i.message.includes("image input")?c=`This model doesn't support image input. Please use ${Jt(fr)} for image-based requests or remove image references from your prompt.`:(i.message.includes("Load failed")||i.message.includes("CORS"))&&(c="API connection failed. This might be due to CORS restrictions or network issues. Please check your API key and try again."),u.innerHTML=`
    -

    Connection Error

    -

    ${D(c)}

    -
    -

    Check if API key is valid

    -

    Try using a different model

    -

    Ensure network allows API calls

    -
    -
    `}Ho(o,"error")}finally{y.isRunning=!1,r.disabled=!1,r.innerHTML=` - - - Run Pipeline`,tn()}}function i_(){const t=document.getElementById("code-generator-model").value,e=[fr,"anthropic/claude-opus-5","openai/gpt-5.6-sol"].filter(r=>r!==t),n=prompt(`Retry with different model? - -Current: ${t} - -Options: -1. ${e[0]} -2. ${e[1]} - -Enter 1 or 2:`);n==="1"?(document.getElementById("code-generator-model").value=e[0],zo()):n==="2"&&(document.getElementById("code-generator-model").value=e[1],zo())}async function s_(){const t=Pa();if(!t){ue("No code to commit. Please run the pipeline first.","warning");return}const e=await Ee("flutterflow"),n=await Ee("flutterflow_project_id");if(!e||!n){ue("FlutterFlow credentials not configured. Add your API Key and Project ID in settings.","warning"),Ia();return}if(y.artifactBundle?.artifacts?.length>1){await o_();return}const{artifactType:r,artifactName:i,fileName:s}=ah(),o=hh(t,{artifactType:r,artifactName:i,fileName:s}),a=zv(o);if(!a.canProceed){ue(`Pre-commit checks failed: ${a.issues.join("; ")}`,"error");return}za(o,a,null,null)}async function o_(){const t=await Ee("flutterflow"),e=await Ee("flutterflow_project_id");if(!t||!e){ue("FlutterFlow credentials not configured. Add your API Key and Project ID in settings.","warning"),Ia();return}const n=qg(y.artifactBundle);if(n.errors.length>0){ue(`Bundle validation failed: ${n.errors.join("; ")}`,"error");return}const r=new Map(n.fileEntries.map(a=>[a.fileName,{content:a.content,type:a.type,path:a.path}])),i=es(r),s={canProceed:i.valid&&n.errors.length===0,issues:[...n.errors,...i.errors],warnings:[...n.warnings,...i.warnings]};if(!s.canProceed){ue(`Bundle validation failed: ${s.issues.join("; ")}`,"error");return}const o={content:n.fileEntries.map(a=>`// ${a.fileName} -${a.content}`).join(` - -`),fileName:`${n.fileEntries.length} files`,codeType:"bundle",artifactType:"Bundle",artifactName:n.title};za(o,s,n.dependencies,n)}function a_(t){let e=t.errorMap||new Map;!(e instanceof Map)&&typeof e=="object"&&(e=new Map(Object.entries(e)));let n=`
    -

    FlutterFlow Commit Failed

    -

    ${D(t.error)}

    `;if(e&&e.size>0){n+=`
    -

    Errors:

    -
      `;for(const[i,s]of e.entries()){const o=Dd(s);n+=`
    • - ${D(i)}: ${D(o)} -
    • `}n+="
    "}n+="
    ",n+=`
    - -
    `;const r=document.getElementById("step3-output");r&&(r.innerHTML=n,document.getElementById("btn-regenerate-from-error")?.addEventListener("click",()=>{l_(t.error,e)}))}async function l_(t,e){if(y.isRunning)return;const n=document.getElementById("code-generator-model").value;y.isRunning=!0;const r=document.getElementById("btn-regenerate-from-error");r&&(r.disabled=!0,r.innerHTML=` - - Fixing...`);try{let i=`The previous code had the following errors when committing to FlutterFlow: - -`;if(e&&e.size>0)for(const[c,d]of e.entries()){const h=Dd(d);i+=`File: ${c} -Error: ${h} - -`}else i+=`${t} -`;const s=Rd({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,userFeedback:i});os(),at(2),ze(2),ve(2,!0),y.step2Result=await ts(s,n),Zi();const o=document.getElementById("step2-output"),a=kn(y.step2Result);o.textContent=a,o.dataset.raw=a,ve(2,!1),ze(3),at(3),ve(3,!0),y.step3Result=await ns(y.step2Result,y.step1Result),Xi();const l=document.getElementById("step3-output");l.textContent=y.step3Result,ve(3,!1),Nt();const u=Ki(y.step3Result);as(a,u)}catch(i){console.error("Regeneration failed:",i),Nt(),ue(Oa(i,"Regeneration failed"),"error")}finally{y.isRunning=!1,r&&(r.disabled=!1,r.textContent="Fix Errors & Regenerate"),tn()}}async function c_(){const t=document.getElementById("ff-status-dot"),e=document.getElementById("ff-status-text");if(!t||!e)return;const n=await Ee("flutterflow"),r=await Ee("flutterflow_project_id");n&&r?(t.className="w-2 h-2 rounded-full bg-green-500",e.textContent="FlutterFlow credentials configured",e.className="text-green-600"):n||r?(t.className="w-2 h-2 rounded-full bg-yellow-500",e.textContent="FlutterFlow credentials incomplete",e.className="text-yellow-600"):(t.className="w-2 h-2 rounded-full bg-red-500",e.textContent="FlutterFlow credentials not configured",e.className="text-red-600")}async function u_(t){try{const e=await fetch(`${Ze}/auth/send-magic-link`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:t})});if(!e.ok)throw new Error(`Failed to send magic link: HTTP ${e.status}`);return e.json()}catch(e){throw console.error("sendMagicLink failed:",{email:t,message:e.message,stack:e.stack}),e}}async function d_(t){try{const n=await(await fetch(`${Ze}/auth/verify-magic-link`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:t})})).json();if(n.error||!n.email||!n.sessionToken)throw new Error(n.error||"Invalid or expired link");return n}catch(e){throw console.error("verifyMagicLink failed:",{message:e.message,stack:e.stack}),e}}async function h_(t){try{const e=await fetch(`${Ze}/auth/refresh-session`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:t})});if(!e.ok)return console.error("refreshSession: non-OK response",{url:`${Ze}/auth/refresh-session`,status:e.status}),null;const n=await e.json();return n.error||!n.email||!n.sessionToken?(console.warn("refreshSession: validation failed",{error:n.error,hasEmail:!!n.email,hasToken:!!n.sessionToken}),null):n}catch(e){return console.error("refreshSession: fetch failed",{url:`${Ze}/auth/refresh-session`,message:e.message,stack:e.stack}),null}}function Mc(t,e){const n=ph(),r=(z.email||n.email)!==t;z.email=t,z.sessionToken=e,z.isVerified=!0,pe=In({isLoading:!0}),localStorage.setItem(Ci,JSON.stringify({email:t,sessionToken:e})),r&&Wa()}function Da(){z.email=null,z.sessionToken=null,z.isVerified=!1,pe=In({isResolved:!0}),localStorage.removeItem(Ci),localStorage.removeItem(Ai)}function ph(){try{const t=localStorage.getItem(Ci);if(!t)return{email:null,sessionToken:null};const e=JSON.parse(t);return!e.email||!e.sessionToken?{email:null,sessionToken:null}:e}catch(t){return console.warn("getStoredSession: failed to parse auth session:",t),localStorage.removeItem(Ci),{email:null,sessionToken:null}}}async function p_(){const e=new URLSearchParams(window.location.search).get("token");if(e){window.history.replaceState({},"",window.location.pathname+window.location.hash);try{const{email:n,sessionToken:r}=await d_(e);Mc(n,r)}catch(n){ue(n.message||"Sign-in link invalid or expired.","error")}}else{const{email:n,sessionToken:r}=ph();if(n&&r){const i=await h_(r);i?Mc(i.email,i.sessionToken):Da()}}Ua()}function ja(){const t=document.getElementById("signin-modal");t&&Ve(t)}function f_(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("signin-modal");e&&Xe(e)}async function g_(){const t=document.getElementById("signin-email-input"),e=document.getElementById("signin-submit-btn"),n=document.getElementById("signin-message"),r=zi(t?.value);if(!r||!/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/.test(r)||r.length>254){n&&(n.textContent="Please enter a valid email address.");return}e&&(e.disabled=!0,e.textContent="Sending…");const s=jd(r);n&&s&&(n.textContent=s);try{const o=await u_(r);t&&o?.code!==Jr&&(t.value=""),n&&(n.textContent=Sm(o,r)),e&&(e.textContent=o?.code===Jr?"Send Link":"Sent!"),e&&o?.code===Jr&&(e.disabled=!1)}catch(o){console.error("handleMagicLinkRequest: sendMagicLink failed",{email:r,err:o}),n&&(n.textContent="Something went wrong. Please try again."),e&&(e.disabled=!1,e.textContent="Send Link")}}function m_(){Da(),Wa(),Ua(),ss()}function Ua(){const t=z.isVerified&&!!z.email,e=document.getElementById("auth-signedout"),n=document.getElementById("auth-signedin"),r=document.getElementById("auth-guest-usage");e&&e.classList.toggle("hidden",t),n&&n.classList.toggle("hidden",!t),r&&r.classList.toggle("hidden",t);const i=document.getElementById("auth-user-email");i&&(i.textContent=z.email||""),ei(),ss()}async function fh(){try{if(typeof FingerprintJS>"u"){console.warn("resolveIdentity: FingerprintJS not loaded, skipping");return}const e=await(await FingerprintJS.load()).get(),n=e.visitorId,r=await fetch(ov,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({fingerprint:e.visitorId,cookie_id:n})});if(!r.ok)throw new Error(`Identity check HTTP ${r.status}`);const i=await r.json();if(Ke.userId=i.user_id,Ke.token=i.identity_token||null,Ke.status=i.status,Ke.resolved=!0,sessionStorage.setItem(iv,i.user_id),Ke.token&&sessionStorage.setItem(sv,Ke.token),i.usage_count!==void 0){const s=Tt(),a=(i.usage_month||s)===s?i.usage_count:0;localStorage.setItem(Xt,JSON.stringify({count:a,month:s})),ir()}console.log(`Identity resolved: ${i.status} (${i.user_id.slice(0,8)}...) usage: ${i.usage_count??"n/a"}`)}catch(t){console.error("resolveIdentity failed:",t)}}let Us=null;function v_(t=5e3){return Ke.resolved?Promise.resolve():(Us||(Us=fh().catch(e=>{console.warn("ensureIdentityReady: identity resolution failed",e)})),Promise.race([Us,new Promise(e=>setTimeout(e,t))]))}function gh(){const t=Tt();try{const e=localStorage.getItem(Xt);return e?JSON.parse(e):{count:0,month:t}}catch(e){return console.warn("getUsageData: failed to parse usage storage",{key:Xt,month:t,err:e}),localStorage.removeItem(Xt),{count:0,month:t}}}function Tt(){const t=new Date;return`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,"0")}`}function Er(){const t=gh();return t.month!==Tt()?{count:0,month:Tt()}:t}function __(){const e={count:Er().count+1,month:Tt()};return localStorage.setItem(Xt,JSON.stringify(e)),e}function rs(){return!!pe.isLoading}function Mt(){return!!pe.isResolved}function y_(t){if(!t)return null;const e=String(t).toLowerCase().replace(/[^a-z0-9]+/g,"_");return e==="pro"||e==="professional_plan"?"professional":e==="power_developer"||e==="power_plan"?"power":Object.prototype.hasOwnProperty.call(Fi,e)?e:null}function w_(t){return t&&Object.entries(Kd).find(([,e])=>e===t)?.[0]||null}function jr(...t){return t.find(e=>e!=null&&e!=="")}function b_(...t){return t.find(e=>e&&typeof e=="object")||{}}function E_(t){const e=t.data&&typeof t.data=="object"?t.data:t,n=b_(e.subscription,e.stripeSubscription,e.currentSubscription,e.customer?.subscriptions?.data?.[0],e.subscriptions?.data?.[0],e.subscriptions?.[0]),r=e.metadata||n.metadata||e.customer?.metadata||{},i=jr(e.priceId,e.price_id,e.stripePriceId,e.stripe_price_id,n.priceId,n.price_id,n.plan?.id,n.price?.id,n.items?.data?.[0]?.price?.id,n.items?.[0]?.price?.id,n.lines?.data?.[0]?.price?.id),s=jr(e.status,e.subscriptionStatus,e.subscription_status,n.status,"none"),o=y_(jr(e.tier,e.plan,e.planId,e.plan_id,e.subscriptionTier,e.subscription_tier,e.product,e.productName,n.tier,n.plan,r.tier,r.plan)),a=av.has(String(s).toLowerCase()),l=e.active===!0||e.isSubscribed===!0||e.subscribed===!0||e.hasSubscription===!0,u=o||w_(i)||(a||l?"professional":"free");return In({tier:u,status:s,periodEnd:jr(e.periodEnd,e.currentPeriodEnd,e.current_period_end,n.current_period_end,n.periodEnd,null),isResolved:!0})}function is(){return Fi[pe.tier]??Fi.free}async function S_(){if(z.isVerified&&(!Mt()||rs())&&(await mh({force:!0}),ss()),z.isVerified&&!Mt())return ue("Could not verify your subscription. Please refresh or try Manage billing.","error"),!1;const{count:t}=Er(),e=is();if(t>=e)return Ha(t,e,{openModal:!0}),!1;const n=Math.floor(e*.8);if(t>=n){const r=e-t;ue(`${r} run${r===1?"":"s"} remaining this month.`,"warning")}return!0}function Hs(){const t=document.getElementById("paywall-exhausted");t&&t.classList.add("hidden")}function Ha(t,e,n={}){An(!0);const r=document.getElementById("walkthrough-modal");r&&Xe(r,{restoreFocus:!1});const i=document.getElementById("ready-state");i&&i.classList.add("hidden");const s=document.getElementById("preview-frame-container");s&&(s.style.display="none");const o=document.getElementById("main-stage-container");o&&o.classList.add("visible");const a=document.getElementById("results-view");a&&a.classList.remove("visible"),document.body.classList.remove("results-fullscreen","results-with-sidebar");const l=document.getElementById("pipeline-progress");l&&l.classList.remove("visible");const u=document.getElementById("paywall-exhausted");if(!u){ue(`You've used all ${e} runs for this month. Upgrade to continue.`,"error"),Li();return}const c=document.getElementById("paywall-exhausted-text");if(c){const h=pe.tier;h==="free"?c.textContent=`You've used all ${e} free generations this month. Upgrade to Pro for 50 generations/month and access to all AI models.`:c.textContent=`You've used all ${e} generations this month on your ${h} plan. Your limit resets next month.`}const d=document.getElementById("paywall-signin-btn");d&&d.classList.toggle("hidden",z.isVerified),u.classList.remove("hidden"),n.openModal&&Li()}function qo(t){return pe.tier==="free"&&Yr.includes(t)?fr:t}function x_(){const t=document.getElementById("code-options-content"),e=document.getElementById("code-generator-model");if(!t||!e)return;const n=pe.tier,i=!(z.isVerified&&!Mt())&&n==="free";Array.from(e.options).forEach(o=>{const a=Jt(o.value),l=Yr.includes(o.value);o.textContent=l&&i?`${a} (PRO)`:a,o.disabled=!1}),i&&Yr.includes(e.value)&&(e.value=fr),e.disabled=!1,Ic.has(e)||(e.addEventListener("change",()=>{Mt()&&pe.tier==="free"&&Yr.includes(e.value)&&(e.value=fr,Li()),Wo(e.value),Yd()}),Ic.add(e));let s=document.getElementById("model-selector-free-notice");i?(s||(s=document.createElement("p"),s.id="model-selector-free-notice",s.className="text-xs text-gray-400 mt-1",t.appendChild(s)),s.innerHTML='Free plan — Gemini only. '):s&&s.remove(),Wo(e.value)}function ir(){const t=document.getElementById("usage-counter");if(!t)return;if(z.isVerified&&rs()){t.textContent="Checking plan…",t.className="text-xs text-gray-500",ei(),Hs();return}if(z.isVerified&&!Mt()){t.textContent="Plan check failed",t.className="text-xs text-red-600 font-medium",ei(),Hs();return}const{count:e}=Er(),n=is();t.textContent=`${e} / ${n} runs this month`;const r=n>0?e/n:0;t.className=r>=1?"text-xs text-red-600 font-medium":r>=.8?"text-xs text-yellow-600 font-medium":"text-xs text-gray-500",ei(),e>=n&&!y.isRunning?Ha(e,n):Hs()}function ei(){const t=document.getElementById("guest-usage-text");if(!t)return;const e=gh(),n=e.month===Tt()?e.count??0:0,r=Fi.free;t.textContent=`${n} / ${r} generations used`}async function mh(t={}){const e=t.force===!0;if(!z.isVerified||!z.sessionToken){pe=In({isResolved:!0});return}pe={...pe,isLoading:!0,error:null};const n=localStorage.getItem(Ai);if(!e&&n)try{const{data:r,email:i,ts:s,version:o}=JSON.parse(n);if(o===Cc&&i===z.email&&Date.now()-s<300*1e3){pe={...r,isLoading:!1,isResolved:r.isResolved!==!1};return}}catch(r){console.warn("Failed to parse subscription cache:",r,"| raw value:",n)}try{const i=await(await fetch(`${Ze}/stripe/get-subscription`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:z.sessionToken,user_id:Ke.userId})})).json();if(i.error){if(["unauthorized","invalid session","expired session"].some(o=>String(i.error).toLowerCase().includes(o))){Da(),Ua();return}pe=In({isResolved:!1,error:i.error});return}pe=E_(i),localStorage.setItem(Ai,JSON.stringify({version:Cc,data:pe,email:z.email,ts:Date.now()}))}catch(r){console.error("fetchSubscription failed:",r),pe={...pe,isLoading:!1,isResolved:!1,error:r.message}}}function Wa(){localStorage.removeItem(Ai)}async function k_(t){if(!z.isVerified||!z.sessionToken){vh(),ja();return}if(!Kd[t]){ue("Invalid plan selected.","error");return}const e=document.getElementById(`checkout-btn-${t}`);e&&(e.disabled=!0,e.textContent="Redirecting…");try{const r=await(await fetch(`${Ze}/stripe/create-checkout-session-intl`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tierId:t,sessionToken:z.sessionToken,currency:Qd()})})).json();if(r.error||!r.url)throw new Error(r.error||"Failed to create checkout session");const{url:i}=r;window.location.href=i}catch(n){console.error("startCheckout failed:",n),e&&(e.disabled=!1,e.textContent="Subscribe"),ue("Could not start checkout. Please try again.","error")}}async function I_(){if(!z.isVerified||!z.sessionToken){ja();return}const t=document.getElementById("manage-billing-btn");t&&(t.disabled=!0,t.textContent="Loading…");try{const n=await(await fetch(`${Ze}/stripe/create-portal-session`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:z.sessionToken})})).json();if(n.error||!n.url)throw new Error(n.error||"Failed to open billing portal");const{url:r}=n;window.location.href=r}catch(e){console.error("openCustomerPortal failed:",e),t&&(t.disabled=!1,t.textContent="Manage billing"),ue("Could not open billing portal. Please try again.","error")}}async function Ni(t,e,n,r={},i=[]){const o=new AbortController,a=setTimeout(()=>o.abort(),12e4);try{const l=await fetch(rv,{method:"POST",headers:{"Content-Type":"application/json",...Ke.token?{Authorization:`Bearer ${Ke.token}`}:{}},signal:o.signal,body:JSON.stringify({user_id:Ke.userId,step:t,model:e,prompt:n,images:i,context:r})}),u=await l.text();let c={};try{c=u?JSON.parse(u):{}}catch{c={}}if(l.status===429){c.serverCount!==void 0&&(localStorage.setItem(Xt,JSON.stringify({count:c.serverCount,month:Tt()})),ir());const p=new Error(c.message||"Monthly usage limit reached. Upgrade to continue.");throw p.isUsageLimit=!0,p}const d=gg(c,t);if(d)throw d;if(console.log(`[BuildShip] ${t} response keys:`,Object.keys(c),"content type:",typeof c.content),!l.ok)throw new Error(`${c.message||c.error||"BuildShip pipeline error"} (HTTP ${l.status})`);if(t==="generator")if(c.usage_status==="success"&&Number.isFinite(c.usage_count)){const p=Tt();(c.usage_month||p)===p&&(localStorage.setItem(Xt,JSON.stringify({count:c.usage_count,month:p})),ir())}else __(),ir();let h=c.output||c.content;if(!h){const p=u?` (body: ${u.slice(0,120)})`:"";throw new Error(`BuildShip returned no output for step "${t}"${p}`)}return Array.isArray(h)&&(h=h.map(p=>typeof p=="string"?p:p.text||"").join("")),typeof h!="string"&&(h=JSON.stringify(h)),h}catch(l){throw l.name==="AbortError"?new Error(`BuildShip ${t} timed out after ${12e4/1e3}s`):l instanceof TypeError?new Error(`BuildShip unreachable: ${l.message}`):l}finally{clearTimeout(a)}}function C_(){const e=new URLSearchParams(window.location.search).get("checkout");e==="success"?(window.history.replaceState({},"",window.location.pathname+window.location.hash),Wa(),ue("Subscription active! Welcome aboard.","success")):e==="cancel"&&(window.history.replaceState({},"",window.location.pathname+window.location.hash),ue("Checkout cancelled.","info"))}function ss(){const t=z.isVerified&&!!z.email,e=pe.tier,n=t&&rs(),r=!t||Mt(),i=document.getElementById("subscription-tier-badge");if(i){const a={free:"Free",professional:"Professional",power:"Power Developer"},l={free:"bg-gray-100 text-gray-600",professional:"bg-indigo-100 text-indigo-700",power:"bg-purple-100 text-purple-700",unresolved:"bg-red-50 text-red-600"};i.textContent=n?"Checking…":r?a[e]||"Free":"Plan unavailable",i.className=`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${r?l[e]||l.free:l.unresolved}`}const s=document.getElementById("upgrade-prompt");s&&s.classList.toggle("hidden",!t||n||!r||e!=="free");const o=document.getElementById("manage-billing-btn");o&&o.classList.toggle("hidden",!t||n||r&&e==="free"),F_(r?e:null),x_(),Yd(),ir(),kh()}function F_(t){const e=["bg-gray-100","text-gray-500","cursor-default"];Object.entries({professional:{btnId:"checkout-btn-professional",defaultText:"Subscribe"},power:{btnId:"checkout-btn-power",defaultText:"Subscribe"}}).forEach(([i,{btnId:s,defaultText:o}])=>{const a=document.getElementById(s);a&&(i===t?(a.disabled=!0,a.textContent="Current plan",a.classList.add(...e)):(a.disabled=!1,a.textContent=o,a.classList.remove(...e)))});const r=document.getElementById("free-tier-current");r&&r.classList.toggle("hidden",t!=="free")}function Vo(){const t=Qd(),e=document.getElementById("pro-price"),n=document.getElementById("power-price"),r=document.getElementById("plans-pro-price"),i=document.getElementById("plans-power-price"),s=document.getElementById("pro-price-note"),o=document.getElementById("power-price-note"),a=document.getElementById("plans-pro-price-note"),l=document.getElementById("plans-power-price-note");e&&(e.textContent=Dr(Br.professional,t)),n&&(n.textContent=Dr(Br.power,t)),r&&(r.textContent=Dr(Br.professional,t)),i&&(i.textContent=Dr(Br.power,t));const u="billed monthly";s&&(s.textContent=u),o&&(o.textContent=u),a&&(a.textContent=u),l&&(l.textContent=u)}function Li(){Vo();const t=document.getElementById("pricing-modal");t&&Ve(t),mv().then(()=>Vo())}function vh(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("pricing-modal");e&&Xe(e)}function ue(t,e="info"){const n={success:"bg-green-600 text-white",error:"bg-red-600 text-white",warning:"bg-amber-500 text-white",info:"bg-gray-800 text-white"},r=document.createElement("div");r.className=`fixed bottom-6 left-1/2 -translate-x-1/2 px-5 py-3 rounded-lg text-sm font-medium shadow-lg z-50 transition-opacity duration-300 ${n[e]||n.info}`,r.textContent=t,document.body.appendChild(r),setTimeout(()=>{r.style.opacity="0",setTimeout(()=>r.remove(),300)},3500)}document.addEventListener("DOMContentLoaded",async()=>{ng(),hljs.configure({tabReplace:" ",classPrefix:"hljs-"}),A_(),await p_(),C_(),await mh(),ss(),Vo(),await Uv(),Lv();const t=document.getElementById("flutterflow-endpoint-select");if(t){const n=wr();t.value=n}sh(),fh();const e=document.getElementById("pipeline-input");e&&(e.addEventListener("input",()=>{kt===2&&e.value.trim().length>0&&(Ca(),Ji())}),e.addEventListener("blur",()=>{const n=document.getElementById("walkthrough-modal");kt===2&&n&&Ve(n)}),e.addEventListener("keydown",n=>{if(n.key==="Tab"){const r=document.getElementById("walkthrough-modal");kt===2&&r&&setTimeout(()=>{Ve(r)},100)}})),window.addEventListener("commitStateChange",n=>{const{state:r}=n.detail;r===G.PREPARING||r===G.VALIDATING||r===G.PUSHING?(be.phaseId||yh(),Lc(r)):(r===G.SUCCESS||r===G.ERROR)&&(Lc(r),setTimeout(Oi,1e3))}),ey(),Va()});function A_(){const t=document.getElementById("preview-frame-container");t&&(t.style.display="")}function P_(){const t=document.getElementById("welcome-video-player");t&&(t.addEventListener("click",en),document.addEventListener("keydown",en))}function en(){const t=document.getElementById("preview-frame-container"),e=document.getElementById("main-stage-container"),n=document.getElementById("ready-state");t&&(t.style.display="none"),e&&e.classList.add("visible"),n&&n.classList.remove("hidden");const r=document.getElementById("welcome-video-player");r&&r.removeEventListener("click",en),document.removeEventListener("keydown",en),sh()}let sr=null;async function $_(){const t=document.getElementById("confirm-project-select");if(!t)return;const e=++Rc,n=()=>e===Rc,r=await Ee("flutterflow"),i=await Ee("flutterflow_project_id");if(n()){if(!r){t.innerHTML='',t.disabled=!0;return}t.disabled=!1,t.innerHTML='';try{const o=await new br(r,"").listProjects();if(!n())return;if(!o||o.length===0){t.innerHTML='';return}t.innerHTML='',o.forEach(a=>{const l=document.createElement("option");l.value=a.id||a.projectId||"",l.textContent=a.name||a.projectName||`Project ${a.id}`,t.appendChild(l)}),i&&(t.value=i)}catch(s){if(!n())return;console.error("Failed to load projects for deploy:",s),t.innerHTML=''}}}function R_(){return document.getElementById("confirm-project-select")?.value?.trim()||null}function za(t,e,n,r=null){sr={codeInfo:t,checks:e,deps:n,bundlePlan:r},document.getElementById("confirm-file-name").textContent=t.fileName,document.getElementById("confirm-artifact-type").textContent=t.artifactType,document.getElementById("confirm-file-size").textContent=`${(t.content.length/1024).toFixed(1)} KB`,document.getElementById("confirm-line-count").textContent=r?`${r.fileEntries.length} files`:t.content.split(` -`).length,$_();const i=document.getElementById("confirm-deps-list"),s=document.getElementById("confirm-deps-section");n&&Object.keys(n).length>0?(i.innerHTML=Object.entries(n).map(([u,c])=>{const d=c?`at least ${xt(c)}`:"version resolved from your project";return`
  • • ${xt(u)}: ${d}
  • `}).join(""),s.classList.remove("hidden")):s.classList.add("hidden");const o=document.getElementById("confirm-warnings-list"),a=document.getElementById("confirm-warnings-section");e.warnings&&e.warnings.length>0?(o.innerHTML=e.warnings.map(u=>`
  • • ${xt(u)}
  • `).join(""),a.classList.remove("hidden")):a.classList.add("hidden"),document.getElementById("confirm-code-preview").textContent=t.content,document.getElementById("code-preview-content").classList.add("hidden"),document.getElementById("code-preview-chevron").style.transform="rotate(0deg)";const l=document.getElementById("commit-confirm-modal");l&&Ve(l)}function _h(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("commit-confirm-modal");e&&Xe(e),sr=null}function T_(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("commit-success-modal");e&&Xe(e);const n=["success-message","success-project-id","success-file-name","success-artifact-type","success-time","success-size"];for(const s of n){const o=document.getElementById(s);o&&(o.textContent="")}const r=document.getElementById("success-warnings-section");r&&r.classList.add("hidden");const i=document.getElementById("success-warnings-list");i&&(i.innerHTML="")}function Go(t){const e=(m,_)=>{const w=document.getElementById(m);w&&(w.textContent=_||"")},n=t.metadata?.fileName||"",r=t.metadata?.projectId||"",i=t.metadata?.artifactType||"",s=t.elapsedTime?`${(t.elapsedTime/1e3).toFixed(1)}s`:"",o=t.metadata?.codeSize?`${(t.metadata.codeSize/1024).toFixed(1)} KB`:"";e("success-message",t.message||"Code committed successfully!"),e("success-project-id",r),e("success-file-name",n),e("success-artifact-type",i),e("success-time",s),e("success-size",o);const a=t.addedDependencies||[],l=document.getElementById("success-deps-row");l&&l.classList.toggle("hidden",a.length===0),e("success-deps",a.join(", "));const u=document.getElementById("success-open-ff-link");u&&r&&(u.href=`https://app.flutterflow.io/project/${r}`);const c=document.getElementById("success-warnings-section"),d=document.getElementById("success-warnings-list"),h=t.unverified||[],p=t.approximate||[],f=t.warnings||[];(f.length>0||h.length>0||p.length>0)&&c&&d&&(d.innerHTML=[...h.map(m=>`
  • Not verified before deploying: ${D(String(m))}
  • `),...p.map(m=>`
  • Verified approximately: ${D(String(m))}
  • `),...f.map(([m,_])=>`
  • ${D(m)}: ${D(String(_))}
  • `)].join(""),c.classList.remove("hidden"));const g=document.getElementById("commit-success-modal");g&&Ve(g)}function Ko(t){Oi(),a_(t)}function M_(){const t=document.getElementById("code-preview-content"),e=document.getElementById("code-preview-chevron");t.classList.contains("hidden")?(t.classList.remove("hidden"),e.style.transform="rotate(90deg)"):(t.classList.add("hidden"),e.style.transform="rotate(0deg)")}const Nc={prepare:{message:"Preparing your code...",start:4,end:14},validate:{message:"Checking FlutterFlow credentials...",start:14,end:22},project:{message:"Reading your FlutterFlow project...",start:22,end:40},provision:{message:"Creating custom classes in FlutterFlow...",start:40,end:82},package:{message:"Packaging files for upload...",start:82,end:88},push:{message:"Pushing to FlutterFlow...",start:88,end:97},done:{message:"Complete!",start:100,end:100}},N_=[{after:0,text:"Starting a FlutterFlow build runner..."},{after:12,text:"Preparing the FlutterFlow AI workspace..."},{after:35,text:"Uploading your custom classes..."},{after:60,text:"FlutterFlow is applying the changes..."},{after:100,text:"Still working — this can take a couple of minutes..."}],be={sequence:[],phaseId:null,phaseStartedAt:null,timer:null,substatus:null,liveSubstatus:!1,start({withProvisioning:t=!1}={}){this.sequence=["prepare","validate","project"],t&&this.sequence.push("provision"),this.sequence.push("package","push","done");const e=document.getElementById("commit-progress-overlay");e&&(ac(e,!0,"Deploying to FlutterFlow"),Ve(e)),this.set("prepare")},set(t,e=null){if(!(!Nc[t]||t===this.phaseId)){if(!this.sequence.includes(t)){const n=this.sequence.indexOf("package");this.sequence.splice(n===-1?this.sequence.length:n,0,t)}this.phaseId=t,this.phaseStartedAt=Date.now(),this.substatus=e,this.liveSubstatus=!1,this.render(),this.timer&&clearInterval(this.timer),t!=="done"&&(this.timer=setInterval(()=>this.render(),500))}},setSubstatus(t){t&&(this.liveSubstatus=!0,this.substatus=t,this.render())},render(){const t=Nc[this.phaseId];if(!t)return;const e=(Date.now()-this.phaseStartedAt)/1e3,n=t.start+(t.end-t.start)*(1-Math.exp(-e/25));if(this.phaseId==="provision"&&!this.liveSubstatus){const o=N_.filter(a=>e>=a.after).pop();o&&(this.substatus=o.text)}const r=this.sequence.indexOf(this.phaseId),s=[`Step ${r===-1?1:r+1} of ${this.sequence.length}`];e>=5&&s.push(L_(e)),wh(this.phaseId==="done"?100:n,t.message,s.join(" · "),this.substatus)},stop(){this.timer&&clearInterval(this.timer),this.timer=null,this.phaseId=null;const t=document.getElementById("commit-progress-overlay");t&&(ac(t,!1),Xe(t,{force:!0,restoreFocus:!1}))}};function L_(t){const e=Math.floor(t);return e<60?`${e}s elapsed`:`${Math.floor(e/60)}m ${String(e%60).padStart(2,"0")}s elapsed`}function yh(t){be.start(t)}function Oi(){be.stop()}function wh(t,e,n,r=null){const i=document.getElementById("commit-progress-bar"),s=document.getElementById("progress-message"),o=document.getElementById("progress-detail"),a=document.getElementById("progress-substatus");i&&(i.style.width=`${Math.round(t*10)/10}%`),s&&(s.textContent=e),o&&(o.textContent=n),a&&(a.textContent=r||"",a.classList.toggle("hidden",!r))}function Lc(t){const e={[G.PREPARING]:"prepare",[G.VALIDATING]:"validate",[G.PUSHING]:"project",[G.SUCCESS]:"done"};if(t===G.ERROR){be.timer&&clearInterval(be.timer),be.timer=null,wh(100,"Failed","Error occurred");return}const n=e[t];n&&be.set(n)}function O_(t){return t.bundlePlan?t.bundlePlan.fileEntries.some(e=>e.type===U.CODE_FILE):t.codeInfo?.codeType===U.CODE_FILE}async function B_(){if(!sr){console.error("No pending commit data");return}const t=sr;if(sr=null,rr=R_(),_h(),yh({withProvisioning:O_(t)}),t.bundlePlan){const o=await Yv(t.bundlePlan,{pipelineResult:{step1Result:y.step1Result,selectedModel:document.getElementById("code-generator-model")?.value}});rr=null,Oi(),o.success?Go(o):Ko(o);return}const{codeInfo:e}=t,{artifactType:n,artifactName:r,fileName:i}=ah(),s=await Jv(e.content,{artifactType:n,artifactName:r,fileName:i,pipelineResult:{step1Result:y.step1Result,selectedModel:document.getElementById("code-generator-model")?.value}});rr=null,Oi(),s.success?Go(s):Ko(s)}window.runThinkingPipeline=zo;window.toggleStep=Qv;window.toggleSection=Xv;window.selectWorkflowStep=ze;window.copyCode=e_;window.retryWithDifferentModel=i_;window.openApiKeysModal=Ia;window.closeApiKeysModal=rh;window.closeWalkthroughModal=Pv;window.openWalkthroughModal=Av;window.advanceWalkthrough=Ca;window.commitToFlutterFlow=Kv;function D_(){const t=document.getElementById("pipeline-input");t&&t.focus()}function j_(){const t=document.getElementById("advanced-settings");t&&(t.open=!0);const e=document.getElementById("code-generator-model");e&&(e.scrollIntoView({behavior:"smooth",block:"center"}),e.focus(),e.click())}window.focusPromptInput=D_;window.openModelSelector=j_;window.handlePromptImageSelect=fv;window.removePromptImage=gv;window.saveApiKeys=Tv;window.clearAllApiKeys=Mv;window.toggleKeyVisibility=Bv;window.handleWelcomeVideoEnd=P_;window.dismissWelcomeVideo=en;window.initiateCommitToFlutterFlow=s_;window.updateFlutterFlowCredentialStatus=c_;window.openCommitConfirmModal=za;window.closeCommitConfirmModal=_h;window.closeCommitSuccessModal=T_;window.showCommitSuccessModal=Go;window.showCommitFailureModal=Ko;window.toggleCodePreview=M_;window.confirmCommitToFlutterFlow=B_;window.runRefinement=t_;window.regenerateFromPastedErrors=r_;window.clearErrorInput=n_;window.setFlutterFlowEndpoint=Fv;window.getFlutterFlowEndpoint=wr;window.commitProgress=be;window.openSignInModal=ja;window.closeSignInModal=f_;window.handleMagicLinkRequest=g_;window.handleSignOut=m_;window.startCheckout=k_;window.openCustomerPortal=I_;window.openPricingModal=Li;window.closePricingModal=vh;let vn=null,bh=null;const Oc=120;function os(){An(!0);const t=document.getElementById("pipeline-progress"),e=document.getElementById("results-view"),n=document.getElementById("ready-state");n&&n.classList.add("hidden"),e&&e.classList.remove("visible"),document.body.classList.remove("results-fullscreen","results-with-sidebar"),t&&t.classList.add("visible"),bh=Date.now();for(let r=1;r<=3;r++){const i=document.getElementById(`pdot-${r}`);i&&(i.className="progress-dot")}at(1),U_()}function at(t){const e={1:"Analyzing your prompt...",2:"Generating Dart code...",3:"Running code audit..."},n={1:"Step 1 of 3 — Prompt Architect",2:"Step 2 of 3 — Code Generator",3:"Step 3 of 3 — Code Review"},r=document.getElementById("progress-title-text"),i=document.getElementById("progress-substep-text");r&&(r.textContent=e[t]||e[1]),i&&(i.textContent=n[t]||n[1]);for(let s=1;s<=3;s++){const o=document.getElementById(`pdot-${s}`);o&&(s{const t=(Date.now()-bh)/1e3,e=document.getElementById("progress-elapsed"),n=document.getElementById("pipeline-progress-fill");e&&(e.textContent=`${Math.floor(t)}s`);const r=t/Oc*100,i=Math.min(95,r*(1-Math.exp(-t/(Oc*.6)))*1.2);n&&(n.style.width=`${i}%`)},250)}function Nt(){vn&&(clearInterval(vn),vn=null);const t=document.getElementById("pipeline-progress-fill");t&&(t.style.width="100%");for(let e=1;e<=3;e++){const n=document.getElementById(`pdot-${e}`);n&&(n.className="progress-dot completed")}setTimeout(()=>{const e=document.getElementById("pipeline-progress");e&&e.classList.remove("visible"),t&&(t.style.width="0%")},400)}function Fn(t,e=""){const n={pass:'',warning:'',fail:'',info:''};return``}function Eh(t){return{pass:"Passed review",warning:"Needs attention",fail:"Blocking issues"}[t]||"Needs attention"}function H_(){return am({bundle:y.artifactBundle,reviewResult:y.step3Result})}function W_(t){return` -
    - ${Fn(t.severity)} -
    -
    ${D(t.message)}
    - ${t.suggestion?`
    ${D(t.suggestion)}
    `:""} - ${D(t.source)} -
    -
    - `}function z_(t){return` -
  • -
    - ${D(t.title)} - ${t.detail&&t.detail!==t.title?`

    ${D(t.detail)}

    `:""} -
    -
  • - `}function q_(t){const e=document.getElementById("results-summary-detail"),n=document.getElementById("results-title");if(!e)return;n&&(n.textContent=t.title);const r=t.score,i=r==null?"neutral":r>=80?"pass":r>=60?"warning":"fail",s=r==null?"":r>=80?"Strong":r>=60?"Needs work":"High risk",o=t.findings.length?` -
      - ${t.findings.map(l=>` -
    • - ${Fn(l.severity)} - - ${D(l.message)} - ${l.suggestion?`${D(l.suggestion)}`:""} - -
    • - `).join("")} -
    - `:"",a=t.manualSteps.length?` -
    -

    ${Fn("info")} Complete in FlutterFlow

    -

    For your information — these don't block the deploy. Finish them by hand in the FlutterFlow editor once the code is pushed.

    -
      - ${t.manualSteps.map(l=>` -
    • - ${D(l.title)} - ${l.detail&&l.detail!==l.title?`${D(l.detail)}`:""} -
    • - `).join("")} -
    -
    - `:"";e.innerHTML=` -
    -
    -

    ${D(t.summary)}

    - ${o} - ${a} -
    -
    - -
    - Is the generated code correct? -
    - - -
    -
    -
    -
    - `}function V_(t){const e=t.artifacts.find(l=>l.id===y.selectedArtifactId)||t.artifacts[0];if(!e)return"";const n={pass:{icon:"pass",message:"No file-specific issues were found."},warning:{icon:"warning",message:"This file needs attention, but Code Review did not return a specific finding."},fail:{icon:"fail",message:"This file is blocked, but Code Review did not return a specific finding."}}[e.status],r=e.findings.length?e.findings.map(W_).join(""):`
    ${Fn(n.icon)} ${D(n.message)}
    `,i=e.dependencies?.length?e.dependencies.map(l=>` -
  • ${D(l.name)}${l.version?` ${D(l.version)}`:""}${l.reason?`

    ${D(l.reason)}

    `:""}
  • - `).join(""):'
  • No external packages
  • ',s=e.imports?.length?e.imports.map(l=>`${D(l)}`).join(""):'No imports returned',o=e.publicApi?.length?e.publicApi.map(l=>`${D(l)}`).join(""):'No public API signature returned',a=e.relationships.length?e.relationships.map(l=>` -
  • ${D(l.from||"Bundle")} ${D(l.type)} ${D(l.to||"Bundle")}${l.description?`

    ${D(l.description)}

    `:""}
  • - `).join(""):'
  • No relationships for this file
  • ';return` -
    -
    - ${Fn(e.status)} ${D(Eh(e.status))} -

    ${D(e.artifactName)}

    - ${e.description?`

    ${D(e.description)}

    `:""} -
    -
    - ${D(e.artifactType)} - ${D(e.fileName)} -
    -
    -
    -

    Code Review findings

    - ${r} -
    - ${e.manualSteps.length?` -
    -

    Manual FlutterFlow steps for this file

    -
      ${e.manualSteps.map(z_).join("")}
    -
    - `:""} -
    - File details -
    -
    -

    Dependencies

    -
      ${i}
    -
    -
    -

    Deployment

    -
    -
    Status
    ${D(e.deployStatus||"pending")}
    -
    Order
    ${e.index+1} of ${t.artifacts.length}
    -
    Path hint
    ${D(e.pathHint||"Not returned")}
    -
    -
    -
    -
    -

    Public API

    -
    ${o}
    -
    -
    -

    Imports

    -
    ${s}
    -
    -
    -

    Relationships

    -
      ${a}
    -
    -
    - `}function G_(t){const e=document.getElementById("bundle-strip"),n=document.getElementById("results-summary-tab"),r=document.getElementById("artifact-tabs"),i=document.getElementById("results-file-count");if(n&&n.classList.toggle("active",y.resultsViewMode==="summary"),!t.artifacts.length){i&&(i.textContent="0 files"),e&&e.classList.remove("visible"),r&&(r.innerHTML="");return}if(i){const s=t.artifacts.length;i.textContent=`${s} ${s===1?"file":"files"}`}r&&(r.innerHTML=t.artifacts.map(s=>` - - `).join(""),r.onclick=s=>{const o=s.target.closest(".artifact-tab");o?.dataset?.artifactId&&Sh(o.dataset.artifactId)}),e&&e.classList.add("visible")}function qa(){document.body.classList.add("results-fullscreen"),document.body.classList.add("results-with-sidebar");const t=document.getElementById("results-view"),e=document.getElementById("results-code-output"),n=document.getElementById("results-audit-output"),r=document.getElementById("results-summary-detail"),i=document.getElementById("artifact-results-split"),s=H_(),o=Pa();if(q_(s),G_(s),e&&(e.textContent=""),e){const a=Gd(o);e.innerHTML=a}n&&(n.innerHTML=V_(s)),r&&r.classList.toggle("hidden",y.resultsViewMode!=="summary"),i&&i.classList.toggle("hidden",y.resultsViewMode!=="file"),t&&t.classList.add("visible")}function as(t,e){An(!0),y.selectedArtifactId||(y.selectedArtifactId=xi(y.artifactBundle).id),y.resultsViewMode="summary",document.body.classList.add("results-fullscreen");const n=document.getElementById("step3-output");n&&(n.textContent=""),qa(),tn();const r=document.getElementById("btn-feedback-up"),i=document.getElementById("btn-feedback-down");r&&(r.className="feedback-btn"),i&&(i.className="feedback-btn")}function Sh(t){y.selectedArtifactId=t,y.resultsViewMode="file",qa()}function K_(){y.resultsViewMode="summary",qa()}function J_(){const t=document.getElementById("btn-copy-results"),e=Pa();navigator.clipboard.writeText(e).then(()=>{if(t){t.classList.add("copied");const n=t.querySelector("span");if(n){const r=n.textContent;n.textContent="Copied!",setTimeout(()=>{t.classList.remove("copied"),n.textContent=r},2e3)}}})}function Y_(t){const e=document.getElementById("btn-feedback-up"),n=document.getElementById("btn-feedback-down");t==="up"?(e.classList.toggle("active-up"),n.classList.remove("active-down")):(n.classList.toggle("active-down"),e.classList.remove("active-up"));const r=t==="up"?"thumbsUp":"thumbsDown";Ba(r,y.step2Result,y.step1Result),Kt("Generation Feedback",{feedback:r})}function Z_(){const t=document.getElementById("error-input-panel");if(t){t.classList.remove("hidden"),t.style.display="flex";const e=document.getElementById("ff-error-paste-input");e&&setTimeout(()=>e.focus(),100)}}function xh(){const t=document.getElementById("error-input-panel");t&&(t.classList.add("hidden"),t.style.display="none")}function An(t){const e=document.getElementById("generation-stage");e&&(t?(e.hidden=!1,e.inert=!1,requestAnimationFrame(()=>e.classList.add("is-active"))):(e.classList.remove("is-active"),e.inert=!0,setTimeout(()=>{e.classList.contains("is-active")||(e.hidden=!0)},260)))}function kh(){const t=z.isVerified&&!!z.email,e=pe.tier||"free",n=t&&rs(),r=!t||Mt(),s=n?"Checking…":r?{free:"Free",professional:"Pro",power:"Power"}[e]||"Free":"—",o=document.getElementById("topbar-plan");o&&(o.textContent=s);const a=document.getElementById("topbar-avatar");a&&(a.textContent=(z.email||"?")[0].toUpperCase());const l=Er(),u=`${l.count} / ${is()} runs this month`,c=document.getElementById("topbar-credits-count");c&&(c.textContent=String(l.count));const d=document.getElementById("credits-balance");d&&(d.textContent=u);const h=document.getElementById("plans-free-current");h&&h.classList.toggle("hidden",e!=="free"||!r);const p=document.getElementById("plans-checkout-btn-professional");if(p){const g=e==="professional"&&r;p.disabled=g,p.textContent=g?"Current plan":"Subscribe"}const f=document.getElementById("plans-checkout-btn-power");if(f){const g=e==="power"&&r;f.disabled=g,f.textContent=g?"Current plan":"Subscribe"}}function X_(){kh();const t=document.getElementById("credits-modal");t&&Ve(t)}function Q_(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("credits-modal");e&&Xe(e)}function Ih(t,e=!0,n=!0){if(t=["home","account","plans"].includes(t)?t:"home",document.querySelectorAll(".view[data-view]").forEach(i=>{i.dataset.view===t?(i.hidden=!1,i.removeAttribute("inert"),requestAnimationFrame(()=>{i.classList.add("is-active"),n&&i.focus({preventScroll:!0})})):(i.classList.remove("is-active"),i.setAttribute("inert","true"),setTimeout(()=>{i.classList.contains("is-active")||(i.hidden=!0)},260))}),t!=="home")An(!1);else{const i=document.getElementById("main-stage-container");i&&i.classList.contains("visible")&&An(!0)}if(document.querySelectorAll(".nav-link[data-view]").forEach(i=>{const s=i.dataset.view===t;i.setAttribute("aria-current",s?"page":null),s||i.removeAttribute("aria-current")}),e){const i=t==="home"?"":`#${t}`;window.location.hash!==i&&window.history.pushState({view:t},"",i||"#")}}let Bc=!1;function Va(){const t=window.location.hash.replace(/^#/,"");Ih(t||"home",!1,Bc),Bc=!0}window.addEventListener("popstate",t=>{Va()});window.addEventListener("hashchange",()=>{Va()});function ey(){const t=document.querySelectorAll("#example-chips .chip"),e=document.getElementById("pipeline-input");t.forEach(n=>{n.addEventListener("click",()=>{e&&(e.value=n.dataset.prompt||""),e?.focus()})})}window.copyResultsCode=J_;window.selectArtifact=Sh;window.selectResultsSummary=K_;window.submitResultsFeedback=Y_;window.showErrorInputPanel=Z_;window.hideErrorInputPanel=xh;window.setGenerationStageVisible=An;window.switchView=Ih;window.openCreditsModal=X_;window.closeCreditsModal=Q_; diff --git a/dist/index.html b/dist/index.html index ccc93f5..a01a1e4 100644 --- a/dist/index.html +++ b/dist/index.html @@ -1481,6 +1481,11 @@ .hidden { display: none !important; } + .sr-only { + position: absolute; width: 1px; height: 1px; + padding: 0; margin: -1px; overflow: hidden; + clip: rect(0 0 0 0); white-space: nowrap; border: 0; + } @media (max-width: 980px) { .results-split { grid-template-columns: minmax(0, 1fr); overflow-y: auto; } @@ -2622,6 +2627,15 @@ transition: opacity var(--t-fast) var(--ease); } .composer.has-suggest .ghost .suggest { opacity: 1; } + /* Demo caret (prototype): a real text cursor — hard blink on a 1.05s cadence + with a soft brand afterglow. Shown while a chip fills the prompt. */ + @keyframes caret-blink { 0%,45% { opacity:1; } 46%,100% { opacity:0; } } + .composer.is-demo-typing .ghost .typed::after { + content:""; display:inline-block; width:2px; height:1.05em; margin-right:-2px; vertical-align:-.15em; + background:var(--accent); border-radius:1px; + box-shadow:0 0 7px 1px oklch(from var(--accent) l c h / .5); + animation:caret-blink 1.05s step-end infinite; + } .composer .tab-hint { position: absolute; right: 64px; @@ -2705,6 +2719,7 @@ .send:disabled { background: var(--disabled-bg); color: var(--disabled-fg); box-shadow: none; cursor: not-allowed; } .send.is-busy .send-arrow { display: none; } .send.is-busy .send-spin { display: block; animation: spin 900ms linear infinite; } + .composer.is-busy .field { pointer-events: none; } @keyframes spin { to { transform: rotate(360deg); } } .chips { @@ -2844,9 +2859,10 @@ } @media (prefers-reduced-motion: reduce) { .view, .generation-stage { transition: none; } + .send.is-busy .send-spin { animation: none; opacity: 0.6; } } - + @@ -2903,7 +2919,7 @@

    FlutterFlow custom code.
    - `,t.appendChild(s)}),e&&(e.textContent=Tt.length>=Lo?"Image limit reached":"Add images"))}function Jd(){const t=document.getElementById("prompt-image-upload");if(!t)return;const e=document.getElementById("code-generator-model"),n=Kd(e?.value);t.classList.toggle("hidden",!n),!n&&Tt.length&&(Tt=[],ba())}const Zt="ccc_usage",Yd="google/gemini-3.7-flash",Zd="google/gemini-3.7-flash",jr="google/gemini-3.7-flash",Oi={professional:11,power:49},Oo={en_US:"USD",en_GB:"GBP",en_AU:"AUD",en_NZ:"NZD",en_CA:"CAD",en_IN:"INR",en_SG:"SGD",en_HK:"HKD",en_PH:"PHP",en_ZA:"ZAR",en:"USD",de:"EUR",fr:"EUR",es:"EUR",it:"EUR",nl:"EUR",pt_PT:"EUR",pt_BR:"BRL",pt:"BRL",ja:"JPY",ko:"KRW",zh_CN:"CNY",zh_TW:"TWD",zh:"CNY",th:"THB",vi:"VND",id:"IDR",ms_MY:"MYR",ms:"MYR",sv:"SEK",nb:"NOK",da:"DKK",pl:"PLN",cs:"CZK",hu:"HUF",ro:"RON",tr:"TRY",ar:"AED",he:"ILS",ru:"RUB",uk:"UAH"},Yi={AUD:1,USD:.65,EUR:.6,GBP:.52,CAD:.88,NZD:1.08,JPY:97,KRW:870,INR:54,SGD:.87,HKD:5.08,BRL:3.18,CNY:4.7,TWD:20.5,THB:22.5,VND:16200,IDR:10200,MYR:2.88,SEK:6.8,NOK:6.95,DKK:4.48,PLN:2.6,CZK:15.2,HUF:238,RON:2.98,TRY:20.9,AED:2.39,ILS:2.38,PHP:36.4,ZAR:11.8,RUB:58,UAH:26.8,CHF:.57,MXN:11.1,ARS:580,CLP:610,COP:2700,PEN:2.44};let Zi={...Yi};async function yv(){const t=new AbortController,e=setTimeout(()=>t.abort(),5e3);try{const n=await fetch("https://open.er-api.com/v6/latest/AUD",{signal:t.signal});if(!n.ok)return;const i=await n.json();if(i.result!=="success"||!i.rates)return;const s=i.rates,r={AUD:1},o=new Set([...Object.keys(Yi),...Object.values(Bo),...Object.values(Oo)]);for(const a of o)a!=="AUD"&&(typeof s[a]=="number"&&s[a]>0?r[a]=s[a]:Yi[a]&&(r[a]=Yi[a]));Zi=r}catch{}finally{clearTimeout(e)}}const Bo={"America/Sao_Paulo":"BRL","America/Fortaleza":"BRL","America/Recife":"BRL","America/Bahia":"BRL","America/Belem":"BRL","America/Manaus":"BRL","America/Cuiaba":"BRL","America/Campo_Grande":"BRL","America/Araguaina":"BRL","America/Noronha":"BRL","America/Rio_Branco":"BRL","America/Porto_Velho":"BRL","America/Boa_Vista":"BRL","America/Maceio":"BRL","America/Santarem":"BRL","America/Eirunepe":"BRL","Europe/London":"GBP","Europe/Paris":"EUR","Europe/Berlin":"EUR","Europe/Madrid":"EUR","Europe/Rome":"EUR","Europe/Amsterdam":"EUR","Europe/Brussels":"EUR","Europe/Vienna":"EUR","Europe/Lisbon":"EUR","Europe/Dublin":"EUR","Europe/Helsinki":"EUR","Europe/Athens":"EUR","Europe/Bucharest":"RON","Europe/Budapest":"HUF","Europe/Warsaw":"PLN","Europe/Prague":"CZK","Europe/Copenhagen":"DKK","Europe/Stockholm":"SEK","Europe/Oslo":"NOK","Europe/Zurich":"CHF","Europe/Istanbul":"TRY","Europe/Moscow":"RUB","Europe/Kiev":"UAH","Europe/Kyiv":"UAH","Asia/Tokyo":"JPY","Asia/Seoul":"KRW","Asia/Shanghai":"CNY","Asia/Taipei":"TWD","Asia/Hong_Kong":"HKD","Asia/Singapore":"SGD","Asia/Kolkata":"INR","Asia/Calcutta":"INR","Asia/Bangkok":"THB","Asia/Ho_Chi_Minh":"VND","Asia/Jakarta":"IDR","Asia/Kuala_Lumpur":"MYR","Asia/Dubai":"AED","Asia/Jerusalem":"ILS","Asia/Tel_Aviv":"ILS","Asia/Manila":"PHP","Pacific/Auckland":"NZD","Australia/Sydney":"AUD","Australia/Melbourne":"AUD","Australia/Brisbane":"AUD","Australia/Perth":"AUD","Australia/Adelaide":"AUD","Australia/Hobart":"AUD","Australia/Darwin":"AUD","Australia/Lord_Howe":"AUD","America/Toronto":"CAD","America/Vancouver":"CAD","America/Edmonton":"CAD","America/Winnipeg":"CAD","America/Halifax":"CAD","America/St_Johns":"CAD","America/Regina":"CAD","America/New_York":"USD","America/Chicago":"USD","America/Denver":"USD","America/Los_Angeles":"USD","America/Phoenix":"USD","America/Anchorage":"USD","Pacific/Honolulu":"USD","America/Mexico_City":"MXN","America/Cancun":"MXN","America/Tijuana":"MXN","America/Argentina/Buenos_Aires":"ARS","America/Santiago":"CLP","America/Bogota":"COP","America/Lima":"PEN","Africa/Johannesburg":"ZAR"};function Xd(){try{const r=Intl.DateTimeFormat().resolvedOptions().timeZone;if(r&&Bo[r])return Bo[r]}catch{}const e=(navigator.language||"en-US").replace("-","_"),n=Oo[e];if(n)return n;const i=e.split("_")[0],s=Oo[i];return s||"USD"}function Bi(t,e){const n=Zi[e]??Zi.USD,i=t*n,s=Math.round(i*100)/100;try{return new Intl.NumberFormat("en-US",{style:"currency",currency:e,minimumFractionDigits:0,maximumFractionDigits:s>=100||s%1===0?0:2}).format(s)}catch{return new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",minimumFractionDigits:0,maximumFractionDigits:2}).format(t*Zi.USD)}}const rt="ccc_api_key_",bt="ccc_session_api_key_",lt="ccc_encryption_key",fi="ccc_encryption_key_scope",wv="ccc_keystore",Fs="keys",gi="ccc_encryption_key_version";let Do=null,Ps=null,mi=!1,$s=!1,Ac=!1;class Ts extends Error{constructor(){super("Secure browser key storage is unavailable."),this.name="CredentialStorageUnavailableError"}}function Fc(){if(Ac)return;Ac=!0;const t="Secure browser key storage is unavailable. Existing credentials were left untouched; new credentials will be available only in this tab session.";console.warn(t),document.body&&ue(t,"warning")}function Qd(){return localStorage.getItem(gi)||""}function jo(){return crypto.randomUUID?.()||th(crypto.getRandomValues(new Uint8Array(16)))}function bv(){const t=Qd();if(t)return t;const e=jo();return localStorage.setItem(gi,e),e}function In(){Do=null,Ps=null,mi=!1,$s=!1}window.addEventListener("storage",t=>{t.key===gi&&In()});function Ev(){return new Promise((t,e)=>{const n=indexedDB.open(wv,1);n.onupgradeneeded=()=>{const i=n.result;i.objectStoreNames.contains(Fs)||i.createObjectStore(Fs)},n.onsuccess=()=>t(n.result),n.onerror=()=>e(n.error)})}async function Ea(t,e){const n=await Ev();return new Promise((i,s)=>{const r=n.transaction(Fs,t);let o;try{o=e(r.objectStore(Fs))}catch(l){n.close(),s(l);return}let a;o.onsuccess=()=>{a=o.result},o.onerror=()=>s(o.error),r.oncomplete=()=>{n.close(),i(a)},r.onerror=()=>{n.close(),s(r.error||new Error("Encryption key transaction failed."))},r.onabort=()=>{n.close(),s(r.error||new Error("Encryption key transaction aborted."))}})}function Sv(t){return t instanceof CryptoKey&&t.algorithm?.name==="AES-GCM"&&t.extractable===!1&&t.usages.includes("encrypt")&&t.usages.includes("decrypt")}async function xv(){const t=await Ea("readonly",e=>e.get(lt));return Sv(t)?t:null}async function eh(t){await Ea("readwrite",e=>e.put(t,lt))}async function kv(){In();try{await Ea("readwrite",t=>t.delete(lt))}catch(t){console.warn("Could not delete the stored encryption key:",t)}}async function Iv(){const t=sessionStorage.getItem(lt);if(!t)return null;const e=await crypto.subtle.importKey("jwk",JSON.parse(t),{name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);return await eh(e),sessionStorage.removeItem(lt),sessionStorage.removeItem(fi),localStorage.removeItem(rt+"salt"),e}async function Pc(t){const e=sessionStorage.getItem(lt);if(e)return $s=sessionStorage.getItem(fi)!=="session",crypto.subtle.importKey("jwk",JSON.parse(e),{name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);if(!t)throw new Ts;const n=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!0,["encrypt","decrypt"]),i=await crypto.subtle.exportKey("jwk",n);return sessionStorage.setItem(lt,JSON.stringify(i)),sessionStorage.setItem(fi,"session"),$s=!1,crypto.subtle.importKey("jwk",i,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}async function Cv(t){if(sessionStorage.getItem(fi)==="session"&&sessionStorage.getItem(lt))return Fc(),mi=!0,Pc(t);try{const e=await xv();if(e)return e;const n=await Iv();if(n)return n;const i=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);return await eh(i),i}catch(e){return console.warn("IndexedDB encryption-key storage failed:",e),Fc(),mi=!0,Pc(t)}}async function Sa(t={}){const{allowSessionFallbackCreation:e=!0}=t,n=bv();Ps!==n&&In();const i=Do||Cv(e);Do=i,Ps=n;try{return await i}catch(s){throw In(),s}}async function Av(t){const e=await Sa(),n=Ps,i=new TextEncoder,s=crypto.getRandomValues(new Uint8Array(12)),r=await crypto.subtle.encrypt({name:"AES-GCM",iv:s},e,i.encode(t)),o=new Uint8Array(s.length+r.byteLength);return o.set(s),o.set(new Uint8Array(r),s.length),{ciphertext:th(o),keyVersion:n,sessionFallback:mi}}async function Fv(t,e={}){const{isSessionCredential:n=!1}=e;try{const i=await Sa({allowSessionFallbackCreation:!1});if(mi&&!n&&!$s)throw new Ts;const s=Pv(t),r=s.slice(0,12),o=s.slice(12),a=await crypto.subtle.decrypt({name:"AES-GCM",iv:r},i,o);return new TextDecoder().decode(a)}catch(i){if(i instanceof Ts)throw i;return console.error("Decryption failed:",i),null}}function th(t){const e=new Uint8Array(t);let n="";for(let i=0;i0}let vi="",Rs="",ni=null,Tc=0;async function xa(){sessionStorage.getItem(lt)&&await Sa(),vi=await Ee("flutterflow"),Rs=await Ee("flutterflow_project_id"),Mv(),en()}function ka(){const t=document.getElementById("api-keys-modal");Ve(t),Ca(),vi&&rh(vi)}function nh(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("api-keys-modal");e&&Xe(e);const n=document.getElementById("walkthrough-modal");n&&(Ia(),Ve(n))}let kt=1;function ih(){const t=document.querySelector(".wt-steps");return t?Array.from(t.querySelectorAll(".wt-step-card")):[]}function Js(){const t=ih();t.length&&t.forEach((e,n)=>{const i=n+1;if(i===kt){e.classList.remove("opacity-60","bg-gray-50","border-gray-200"),e.classList.add("bg-blue-50","border-blue-200");const s=e.querySelector("div:first-child");s&&(s.classList.remove("bg-gray-400"),s.classList.add("bg-blue-500"),s.innerHTML=i)}else if(i0&&kt<=t&&(kt++,Js())}function Tv(){const t=document.getElementById("walkthrough-modal");t&&(kt=1,Js(),Ve(t))}function Rv(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("walkthrough-modal");e&&Xe(e);const n=document.getElementById("walkthrough-dont-show");n&&n.checked&&localStorage.setItem("hasSeenWalkthrough","true")}function sh(){if(V.isVerified&&Nt()&&pe.tier!=="free")return;if(!localStorage.getItem("hasSeenWalkthrough")){const e=document.getElementById("walkthrough-modal");e&&(kt=1,Js(),Ve(e))}}async function Ca(){const t=document.getElementById("flutterflow-api-key-input");vi?(t.value="",t.placeholder="Key saved (enter new to replace)"):t.placeholder="Enter your FlutterFlow API key",Nv()}function Nv(){Rc("flutterflow","flutterflow-key-status"),Rc("flutterflow_project_id","flutterflow-project-status")}function Rc(t,e){const n=document.getElementById(e);if(!n)return;const i=n.querySelector(".key-status-dot"),s=n.querySelector("span");dn(t)?(i.className="key-status-dot configured",s.className="text-green-600",s.textContent="User key configured"):(i.className="key-status-dot missing",s.className="text-gray-500",s.textContent="Not configured")}function en(){const t=y.step2Result&&y.step2Result.length>0,e=document.getElementById("btn-deploy-to-ff"),n=document.getElementById("btn-run-pipeline");n&&n.classList.remove("hidden"),e&&e.classList.toggle("hidden",!t)}function Mv(){const t=document.getElementById("api-keys-status");if(!t)return;const e=t.querySelectorAll(".key-status-dot"),n=["flutterflow"];e.forEach((i,s)=>{const r=n[s];r==="flutterflow"?dn("flutterflow")&&dn("flutterflow_project_id")?(i.className="key-status-dot configured",i.title="FlutterFlow (Fully configured)"):dn("flutterflow")||dn("flutterflow_project_id")?(i.className="key-status-dot env",i.title="FlutterFlow (Partially configured)"):(i.className="key-status-dot missing",i.title="FlutterFlow (Not configured)"):dn(r)?(i.className="key-status-dot configured",i.title=r.charAt(0).toUpperCase()+r.slice(1)+" (User key)"):(i.className="key-status-dot missing",i.title=r.charAt(0).toUpperCase()+r.slice(1)+" (Not configured)")}),en()}async function Lv(){const t=document.getElementById("flutterflow-api-key-input"),e=document.getElementById("flutterflow-projects-select");t.value.trim()&&await $c("flutterflow",t.value);const n=e?.value.trim()||"";if(n){if(!Ys(n)){ue("The selected FlutterFlow project has an unexpected ID format.","error"),e.focus();return}await $c("flutterflow_project_id",n)}await xa(),Ca();const i=document.querySelector("#api-keys-modal .bg-blue-500"),s=i.textContent;i.textContent="Saved!",i.classList.remove("bg-blue-500","hover:bg-blue-600"),i.classList.add("bg-green-500"),setTimeout(()=>{i.textContent=s,i.classList.remove("bg-green-500"),i.classList.add("bg-blue-500","hover:bg-blue-600"),nh()},1e3)}async function Ov(){if(!confirm("Are you sure you want to clear all stored API keys?"))return;localStorage.setItem(gi,jo()),In(),localStorage.removeItem(rt+"flutterflow"),localStorage.removeItem(rt+"flutterflow_project_id"),sessionStorage.removeItem(bt+"flutterflow"),sessionStorage.removeItem(bt+"flutterflow_project_id"),sessionStorage.removeItem(lt),sessionStorage.removeItem(fi),localStorage.removeItem(rt+"salt"),await kv(),localStorage.setItem(gi,jo()),localStorage.removeItem(rt+"flutterflow"),localStorage.removeItem(rt+"flutterflow_project_id"),sessionStorage.removeItem(bt+"flutterflow"),sessionStorage.removeItem(bt+"flutterflow_project_id"),await xa();const t=document.getElementById("flutterflow-projects-select");t&&(t.innerHTML=''),Ca()}function Ys(t){return!t||t.trim().length<5||t.includes(" ")?!1:/^[a-zA-Z0-9-]+$/.test(t)}function Bv(t,e){const n=document.getElementById(t);n&&(n.value?e?n.style.borderColor="#22c55e":n.style.borderColor="#ef4444":n.style.borderColor="")}function Dv(){const t=document.getElementById("flutterflow-api-key-input");t&&(t.addEventListener("input",e=>{const n=e.target.value.trim().length>0;Bv("flutterflow-api-key-input",n)}),t.addEventListener("blur",jv(async e=>{const n=e.target.value.trim();n&&await rh(n)},500)))}function jv(t,e){let n;return function(...s){const r=()=>{clearTimeout(n),t(...s)};clearTimeout(n),n=setTimeout(r,e)}}async function rh(t){const e=document.getElementById("flutterflow-projects-select"),n=document.getElementById("flutterflow-projects-error");if(!e){console.error("Projects dropdown element not found");return}e.innerHTML='',n&&n.classList.add("hidden");try{const s=await new wi(t,"").listProjects();if(!s||s.length===0){e.innerHTML='';return}e.innerHTML='',s.forEach(r=>{const o=document.createElement("option");o.value=r.id||r.projectId||"",o.textContent=r.name||r.projectName||`Project ${r.id}`,e.appendChild(o)}),Rs&&(e.value=Rs)}catch(i){console.error("Failed to fetch projects:",i),e.innerHTML='',n&&(n.textContent=`Failed to load projects: ${i.message}`,n.classList.remove("hidden"))}}function Uv(t){const e=document.getElementById(t),i=e.nextElementSibling.querySelector("svg");e.type==="password"?(e.type="text",i.innerHTML=` + `}const Qm=[[/gradient stroke\s*$/i," and an animated percentage label"],[/gauge\s*$/i," with a gradient stroke and animated fill"],[/rating\s*(bar|widget)?\s*$/i," with half-star support and haptic feedback"],[/list\s*$/i," with swipe-to-delete and an undo snackbar"],[/pad\s*$/i," that exports a transparent PNG"],[/carousel\s*$/i," with parallax cards and page indicators"],[/(button|cta)\s*$/i," with a loading spinner and success state"],[/(chart|graph)\s*$/i," that animates from a Firestore stream"],[/action\s*(that|to)?\s*$/i," uploads an image to Firebase Storage and returns the URL"],[/timer\s*$/i," with pause, resume and a completion callback"],[/map\s*$/i," with clustered markers and a custom info window"],[/^a\s+\w*$/i," widget that"],[/(picker|selector)\s*$/i," with search and multi-select"]],ev=220,tv=6;function kc(t,e){return!!(t&&t.trim())&&!e}function nv(t,e=""){if(typeof t!="string"||!t||t===e||t.trim().lengthi.test(t));return n?n[1]:null}function iv(){let t="",e="";return{get active(){return t},resolve(n){return t=nv(n,e)??"",t},dismiss(){t=""},accept(n){if(!t)return null;const i=n+t;return e=i,t="",i}}}function sv({onSubmit:t}){const e=document.getElementById("composer"),n=document.getElementById("pipeline-input"),i=document.getElementById("hero-send");if(!e||!n||!i||typeof t!="function")return;const s=e.querySelector(".ghost .typed"),r=e.querySelector(".ghost .suggest"),o=document.getElementById("tab-hint"),a=document.getElementById("suggest-status"),l=Array.from(document.querySelectorAll("#example-chips .chip")),u=window.matchMedia("(prefers-reduced-motion: reduce)"),c=iv();let d=!1,h=!1,p=null,f=null;function g(){i.disabled=!kc(n.value,h)}function m(){s&&(s.textContent=n.value)}function v(){r&&(r.textContent=""),m(),e.classList.remove("has-suggest"),o&&(o.hidden=!0,o.tabIndex=-1),a&&(a.textContent="")}function E(P){r&&(r.textContent=P),m(),e.classList.add("has-suggest"),o&&(o.hidden=!1,o.tabIndex=0,o.setAttribute("aria-label","Accept suggestion: "+P.trim())),a&&(a.textContent="Suggestion: "+P+". Press Tab to accept.")}function w(){c.dismiss(),v()}function I(){if(d||h)return;const P=c.resolve(n.value);P&&E(P)}function A(){clearTimeout(p),!d&&(p=setTimeout(I,ev))}function F(){const P=c.accept(n.value);return P===null?!1:(n.value=P,v(),g(),!0)}function D(P){h=P,e.classList.toggle("is-busy",P),i.classList.toggle("is-busy",P),i.setAttribute("aria-label",P?"Generating":"Generate"),g()}async function S(){if(kc(n.value,h)){w(),D(!0);try{await t()}finally{D(!1)}}}function $(){f&&(clearInterval(f),f=null),e.classList.remove("is-demo-typing")}function T(){l.forEach(P=>{P.classList.remove("is-active"),P.setAttribute("aria-pressed","false")})}function M(){try{n.focus({preventScroll:!0}),n.setSelectionRange(n.value.length,n.value.length)}catch{}}function N(P){const z=P.dataset.prompt||"";if($(),w(),l.forEach(U=>{const Q=U===P;U.classList.toggle("is-active",Q),U.setAttribute("aria-pressed",String(Q))}),u.matches||!z){n.value=z,m(),g(),M();return}n.value="",m(),g(),e.classList.add("is-demo-typing");let H=0;f=setInterval(()=>{H+=1,n.value=z.slice(0,H),m(),g(),H>=z.length&&($(),M())},22)}l.forEach(P=>{P.setAttribute("aria-pressed","false"),P.addEventListener("click",()=>N(P))}),n.addEventListener("keydown",P=>{$(),P.key==="Tab"&&!P.shiftKey&&c.active?(P.preventDefault(),F()):P.key==="Escape"?w():P.key==="Enter"&&!P.shiftKey&&!P.isComposing&&!d&&(P.preventDefault(),S())}),n.addEventListener("input",()=>{$(),T(),w(),g(),A()}),n.addEventListener("compositionstart",()=>{d=!0}),n.addEventListener("compositionend",()=>{d=!1,w(),g(),A()}),n.addEventListener("scroll",()=>{s&&s.parentNode&&(s.parentNode.scrollTop=n.scrollTop)}),o&&o.addEventListener("click",()=>{F(),n.focus({preventScroll:!0})}),i.addEventListener("click",S),n.addEventListener("pointerdown",()=>{$(),T()}),m(),g()}const rv="https://ccc-ffai-runner-y5cyj3473a-uw.a.run.app/deployCustomClasses";const Ze="https://4tgke4.buildship.run",Gd={professional:"price_1T2ldCKszA2slvDXatdeCpbI",power:"price_1T2le9KszA2slvDXR4mPvw7M"},Is="ccc_auth_session",Ic=new WeakSet;let V={email:null,sessionToken:null,isVerified:!1};function kn(t={}){return{tier:"free",status:"none",periodEnd:null,isLoading:!1,isResolved:!1,error:null,...t}}let pe=kn({isResolved:!0});const ov=`${Ze}/service/runpipeline`,av="bs_user_id",lv="bs_identity_token",cv=`${Ze}/authUserCheck`;let Ke={userId:null,token:null,status:null,resolved:!1};const Cs={free:2,professional:50,power:2e3},As="ccc_subscription",Cc=3,uv=new Set(["active","trialing","paid"]),pi="google/gemini-3.7-flash",Ji=["anthropic/claude-opus-5","openai/gpt-5.6-sol","z-ai/glm-5.2","moonshotai/kimi-k3","openrouter/auto-beta","openrouter/free","openrouter/deepseek/deepseek-v4-pro"],dv={"google/gemini-3.7-flash":"Gemini 3.7 Flash","anthropic/claude-opus-5":"Claude Opus 5","openai/gpt-5.6-sol":"GPT-5.6 Sol","z-ai/glm-5.2":"GLM 5.2","moonshotai/kimi-k3":"Kimi K3","openrouter/auto-beta":"OpenRouter: Auto Router","openrouter/free":"OpenRouter: Free Models","openrouter/deepseek/deepseek-v4-pro":"DeepSeek v4 Pro"};function Kt(t){return dv[t]||t}const hv=new Set(["google/gemini-3.7-flash","anthropic/claude-opus-5","openai/gpt-5.6-sol","z-ai/glm-5.2","moonshotai/kimi-k3","openrouter/auto-beta"]);function Kd(t){return hv.has(t)}const Lo=4,Dr=8*1024*1024,pv="https://4tgke4.buildship.run/service/runpipeline-image";let Tt=[];function fv(t){return new Promise(e=>{const n=new FileReader;n.onload=()=>e(n.result),n.onerror=()=>e(null),n.readAsDataURL(t)})}async function gv(t){const e=new FormData;return e.append("file",t),(await fetch(pv,{method:"POST",body:e})).json()}function mv(t){if(Array.isArray(t)){const e=t[0];if(e&&typeof e=="object")for(const n of Object.keys(e)){if(n==="item"||n==="index")continue;const i=e[n];if(i&&typeof i=="object"){if(typeof i.file=="string")return i.file;if(typeof i.url=="string")return i.url}if(typeof i=="string")return i}return""}return typeof t=="string"?t:t&&typeof t=="object"&&(t.url||t.fileUrl||t.file_url||t.downloadUrl||t.imageUrl||t.image_url||t.file)||""}async function vv(t){const e=Array.from(t.target.files||[]);if(!e.length)return;const n=e.filter(l=>l.size>Dr);n.length&&ue(`Skipped ${n.length} image(s) over the ${(Dr/1024/1024).toFixed(0)} MB limit.`,"warning");const i=e.filter(l=>l.size<=Dr);if(!i.length){t.target.value="";return}const s=Lo-Tt.length,o=i.slice(0,s).map(async l=>{const u=await fv(l);if(!u)return null;let c="";try{c=mv(await gv(l))}catch{c=""}return{dataUrl:u,name:l.name,url:c}}),a=(await Promise.all(o)).filter(Boolean);t.target.value="",!(a.length&&!Kd(document.getElementById("code-generator-model")?.value))&&(Tt.push(...a),i.length>s&&ue(`You can attach up to ${Lo} images.`,"info"),ba())}function _v(t){Tt.splice(t,1),ba()}function ba(){const t=document.getElementById("prompt-image-thumbnails"),e=document.getElementById("prompt-image-btn-label");t&&(t.innerHTML="",Tt.forEach((n,i)=>{const s=document.createElement("div");s.className="prompt-img-thumb",s.innerHTML=`Prompt image`,t.appendChild(s)}),e&&(e.textContent=Tt.length>=Lo?"Image limit reached":"Add images"))}function Jd(){const t=document.getElementById("prompt-image-upload");if(!t)return;const e=document.getElementById("code-generator-model"),n=Kd(e?.value);t.classList.toggle("hidden",!n),!n&&Tt.length&&(Tt=[],ba())}const Zt="ccc_usage",Yd="google/gemini-3.7-flash",Zd="google/gemini-3.7-flash",jr="google/gemini-3.7-flash",Oi={professional:11,power:49},Oo={en_US:"USD",en_GB:"GBP",en_AU:"AUD",en_NZ:"NZD",en_CA:"CAD",en_IN:"INR",en_SG:"SGD",en_HK:"HKD",en_PH:"PHP",en_ZA:"ZAR",en:"USD",de:"EUR",fr:"EUR",es:"EUR",it:"EUR",nl:"EUR",pt_PT:"EUR",pt_BR:"BRL",pt:"BRL",ja:"JPY",ko:"KRW",zh_CN:"CNY",zh_TW:"TWD",zh:"CNY",th:"THB",vi:"VND",id:"IDR",ms_MY:"MYR",ms:"MYR",sv:"SEK",nb:"NOK",da:"DKK",pl:"PLN",cs:"CZK",hu:"HUF",ro:"RON",tr:"TRY",ar:"AED",he:"ILS",ru:"RUB",uk:"UAH"},Yi={AUD:1,USD:.65,EUR:.6,GBP:.52,CAD:.88,NZD:1.08,JPY:97,KRW:870,INR:54,SGD:.87,HKD:5.08,BRL:3.18,CNY:4.7,TWD:20.5,THB:22.5,VND:16200,IDR:10200,MYR:2.88,SEK:6.8,NOK:6.95,DKK:4.48,PLN:2.6,CZK:15.2,HUF:238,RON:2.98,TRY:20.9,AED:2.39,ILS:2.38,PHP:36.4,ZAR:11.8,RUB:58,UAH:26.8,CHF:.57,MXN:11.1,ARS:580,CLP:610,COP:2700,PEN:2.44};let Zi={...Yi};async function yv(){const t=new AbortController,e=setTimeout(()=>t.abort(),5e3);try{const n=await fetch("https://open.er-api.com/v6/latest/AUD",{signal:t.signal});if(!n.ok)return;const i=await n.json();if(i.result!=="success"||!i.rates)return;const s=i.rates,r={AUD:1},o=new Set([...Object.keys(Yi),...Object.values(Bo),...Object.values(Oo)]);for(const a of o)a!=="AUD"&&(typeof s[a]=="number"&&s[a]>0?r[a]=s[a]:Yi[a]&&(r[a]=Yi[a]));Zi=r}catch{}finally{clearTimeout(e)}}const Bo={"America/Sao_Paulo":"BRL","America/Fortaleza":"BRL","America/Recife":"BRL","America/Bahia":"BRL","America/Belem":"BRL","America/Manaus":"BRL","America/Cuiaba":"BRL","America/Campo_Grande":"BRL","America/Araguaina":"BRL","America/Noronha":"BRL","America/Rio_Branco":"BRL","America/Porto_Velho":"BRL","America/Boa_Vista":"BRL","America/Maceio":"BRL","America/Santarem":"BRL","America/Eirunepe":"BRL","Europe/London":"GBP","Europe/Paris":"EUR","Europe/Berlin":"EUR","Europe/Madrid":"EUR","Europe/Rome":"EUR","Europe/Amsterdam":"EUR","Europe/Brussels":"EUR","Europe/Vienna":"EUR","Europe/Lisbon":"EUR","Europe/Dublin":"EUR","Europe/Helsinki":"EUR","Europe/Athens":"EUR","Europe/Bucharest":"RON","Europe/Budapest":"HUF","Europe/Warsaw":"PLN","Europe/Prague":"CZK","Europe/Copenhagen":"DKK","Europe/Stockholm":"SEK","Europe/Oslo":"NOK","Europe/Zurich":"CHF","Europe/Istanbul":"TRY","Europe/Moscow":"RUB","Europe/Kiev":"UAH","Europe/Kyiv":"UAH","Asia/Tokyo":"JPY","Asia/Seoul":"KRW","Asia/Shanghai":"CNY","Asia/Taipei":"TWD","Asia/Hong_Kong":"HKD","Asia/Singapore":"SGD","Asia/Kolkata":"INR","Asia/Calcutta":"INR","Asia/Bangkok":"THB","Asia/Ho_Chi_Minh":"VND","Asia/Jakarta":"IDR","Asia/Kuala_Lumpur":"MYR","Asia/Dubai":"AED","Asia/Jerusalem":"ILS","Asia/Tel_Aviv":"ILS","Asia/Manila":"PHP","Pacific/Auckland":"NZD","Australia/Sydney":"AUD","Australia/Melbourne":"AUD","Australia/Brisbane":"AUD","Australia/Perth":"AUD","Australia/Adelaide":"AUD","Australia/Hobart":"AUD","Australia/Darwin":"AUD","Australia/Lord_Howe":"AUD","America/Toronto":"CAD","America/Vancouver":"CAD","America/Edmonton":"CAD","America/Winnipeg":"CAD","America/Halifax":"CAD","America/St_Johns":"CAD","America/Regina":"CAD","America/New_York":"USD","America/Chicago":"USD","America/Denver":"USD","America/Los_Angeles":"USD","America/Phoenix":"USD","America/Anchorage":"USD","Pacific/Honolulu":"USD","America/Mexico_City":"MXN","America/Cancun":"MXN","America/Tijuana":"MXN","America/Argentina/Buenos_Aires":"ARS","America/Santiago":"CLP","America/Bogota":"COP","America/Lima":"PEN","Africa/Johannesburg":"ZAR"};function Xd(){try{const r=Intl.DateTimeFormat().resolvedOptions().timeZone;if(r&&Bo[r])return Bo[r]}catch{}const e=(navigator.language||"en-US").replace("-","_"),n=Oo[e];if(n)return n;const i=e.split("_")[0],s=Oo[i];return s||"USD"}function Bi(t,e){const n=Zi[e]??Zi.USD,i=t*n,s=Math.round(i*100)/100;try{return new Intl.NumberFormat("en-US",{style:"currency",currency:e,minimumFractionDigits:0,maximumFractionDigits:s>=100||s%1===0?0:2}).format(s)}catch{return new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",minimumFractionDigits:0,maximumFractionDigits:2}).format(t*Zi.USD)}}const rt="ccc_api_key_",bt="ccc_session_api_key_",lt="ccc_encryption_key",fi="ccc_encryption_key_scope",wv="ccc_keystore",Fs="keys",gi="ccc_encryption_key_version";let Do=null,Ps=null,mi=!1,$s=!1,Ac=!1;class Ts extends Error{constructor(){super("Secure browser key storage is unavailable."),this.name="CredentialStorageUnavailableError"}}function Fc(){if(Ac)return;Ac=!0;const t="Secure browser key storage is unavailable. Existing credentials were left untouched; new credentials will be available only in this tab session.";console.warn(t),document.body&&ue(t,"warning")}function Qd(){return localStorage.getItem(gi)||""}function jo(){return crypto.randomUUID?.()||th(crypto.getRandomValues(new Uint8Array(16)))}function bv(){const t=Qd();if(t)return t;const e=jo();return localStorage.setItem(gi,e),e}function In(){Do=null,Ps=null,mi=!1,$s=!1}window.addEventListener("storage",t=>{t.key===gi&&In()});function Ev(){return new Promise((t,e)=>{const n=indexedDB.open(wv,1);n.onupgradeneeded=()=>{const i=n.result;i.objectStoreNames.contains(Fs)||i.createObjectStore(Fs)},n.onsuccess=()=>t(n.result),n.onerror=()=>e(n.error)})}async function Ea(t,e){const n=await Ev();return new Promise((i,s)=>{const r=n.transaction(Fs,t);let o;try{o=e(r.objectStore(Fs))}catch(l){n.close(),s(l);return}let a;o.onsuccess=()=>{a=o.result},o.onerror=()=>s(o.error),r.oncomplete=()=>{n.close(),i(a)},r.onerror=()=>{n.close(),s(r.error||new Error("Encryption key transaction failed."))},r.onabort=()=>{n.close(),s(r.error||new Error("Encryption key transaction aborted."))}})}function Sv(t){return t instanceof CryptoKey&&t.algorithm?.name==="AES-GCM"&&t.extractable===!1&&t.usages.includes("encrypt")&&t.usages.includes("decrypt")}async function xv(){const t=await Ea("readonly",e=>e.get(lt));return Sv(t)?t:null}async function eh(t){await Ea("readwrite",e=>e.put(t,lt))}async function kv(){In();try{await Ea("readwrite",t=>t.delete(lt))}catch(t){console.warn("Could not delete the stored encryption key:",t)}}async function Iv(){const t=sessionStorage.getItem(lt);if(!t)return null;const e=await crypto.subtle.importKey("jwk",JSON.parse(t),{name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);return await eh(e),sessionStorage.removeItem(lt),sessionStorage.removeItem(fi),localStorage.removeItem(rt+"salt"),e}async function Pc(t){const e=sessionStorage.getItem(lt);if(e)return $s=sessionStorage.getItem(fi)!=="session",crypto.subtle.importKey("jwk",JSON.parse(e),{name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);if(!t)throw new Ts;const n=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!0,["encrypt","decrypt"]),i=await crypto.subtle.exportKey("jwk",n);return sessionStorage.setItem(lt,JSON.stringify(i)),sessionStorage.setItem(fi,"session"),$s=!1,crypto.subtle.importKey("jwk",i,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}async function Cv(t){if(sessionStorage.getItem(fi)==="session"&&sessionStorage.getItem(lt))return Fc(),mi=!0,Pc(t);try{const e=await xv();if(e)return e;const n=await Iv();if(n)return n;const i=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);return await eh(i),i}catch(e){return console.warn("IndexedDB encryption-key storage failed:",e),Fc(),mi=!0,Pc(t)}}async function Sa(t={}){const{allowSessionFallbackCreation:e=!0}=t,n=bv();Ps!==n&&In();const i=Do||Cv(e);Do=i,Ps=n;try{return await i}catch(s){throw In(),s}}async function Av(t){const e=await Sa(),n=Ps,i=new TextEncoder,s=crypto.getRandomValues(new Uint8Array(12)),r=await crypto.subtle.encrypt({name:"AES-GCM",iv:s},e,i.encode(t)),o=new Uint8Array(s.length+r.byteLength);return o.set(s),o.set(new Uint8Array(r),s.length),{ciphertext:th(o),keyVersion:n,sessionFallback:mi}}async function Fv(t,e={}){const{isSessionCredential:n=!1}=e;try{const i=await Sa({allowSessionFallbackCreation:!1});if(mi&&!n&&!$s)throw new Ts;const s=Pv(t),r=s.slice(0,12),o=s.slice(12),a=await crypto.subtle.decrypt({name:"AES-GCM",iv:r},i,o);return new TextDecoder().decode(a)}catch(i){if(i instanceof Ts)throw i;return console.error("Decryption failed:",i),null}}function th(t){const e=new Uint8Array(t);let n="";for(let i=0;i0}let vi="",Rs="",ni=null,Tc=0;async function xa(){sessionStorage.getItem(lt)&&await Sa(),vi=await Ee("flutterflow"),Rs=await Ee("flutterflow_project_id"),Mv(),en()}function ka(){const t=document.getElementById("api-keys-modal");Ve(t),Ca(),vi&&rh(vi)}function nh(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("api-keys-modal");e&&Xe(e);const n=document.getElementById("walkthrough-modal");n&&(Ia(),Ve(n))}let kt=1;function ih(){const t=document.querySelector(".wt-steps");return t?Array.from(t.querySelectorAll(".wt-step-card")):[]}function Js(){const t=ih();t.length&&t.forEach((e,n)=>{const i=n+1;if(i===kt){e.classList.remove("opacity-60","bg-gray-50","border-gray-200"),e.classList.add("bg-blue-50","border-blue-200");const s=e.querySelector("div:first-child");s&&(s.classList.remove("bg-gray-400"),s.classList.add("bg-blue-500"),s.innerHTML=i)}else if(i0&&kt<=t&&(kt++,Js())}function Tv(){const t=document.getElementById("walkthrough-modal");t&&(kt=1,Js(),Ve(t))}function Rv(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("walkthrough-modal");e&&Xe(e);const n=document.getElementById("walkthrough-dont-show");n&&n.checked&&localStorage.setItem("hasSeenWalkthrough","true")}function sh(){if(V.isVerified&&Nt()&&pe.tier!=="free")return;if(!localStorage.getItem("hasSeenWalkthrough")){const e=document.getElementById("walkthrough-modal");e&&(kt=1,Js(),Ve(e))}}async function Ca(){const t=document.getElementById("flutterflow-api-key-input");vi?(t.value="",t.placeholder="Key saved (enter new to replace)"):t.placeholder="Enter your FlutterFlow API key",Nv()}function Nv(){Rc("flutterflow","flutterflow-key-status"),Rc("flutterflow_project_id","flutterflow-project-status")}function Rc(t,e){const n=document.getElementById(e);if(!n)return;const i=n.querySelector(".key-status-dot"),s=n.querySelector("span");dn(t)?(i.className="key-status-dot configured",s.className="text-green-600",s.textContent="User key configured"):(i.className="key-status-dot missing",s.className="text-gray-500",s.textContent="Not configured")}function en(){const t=y.step2Result&&y.step2Result.length>0,e=document.getElementById("btn-deploy-to-ff"),n=document.getElementById("btn-run-pipeline");n&&n.classList.remove("hidden"),e&&e.classList.toggle("hidden",!t)}function Mv(){const t=document.getElementById("api-keys-status");if(!t)return;const e=t.querySelectorAll(".key-status-dot"),n=["flutterflow"];e.forEach((i,s)=>{const r=n[s];r==="flutterflow"?dn("flutterflow")&&dn("flutterflow_project_id")?(i.className="key-status-dot configured",i.title="FlutterFlow (Fully configured)"):dn("flutterflow")||dn("flutterflow_project_id")?(i.className="key-status-dot env",i.title="FlutterFlow (Partially configured)"):(i.className="key-status-dot missing",i.title="FlutterFlow (Not configured)"):dn(r)?(i.className="key-status-dot configured",i.title=r.charAt(0).toUpperCase()+r.slice(1)+" (User key)"):(i.className="key-status-dot missing",i.title=r.charAt(0).toUpperCase()+r.slice(1)+" (Not configured)")}),en()}async function Lv(){const t=document.getElementById("flutterflow-api-key-input"),e=document.getElementById("flutterflow-projects-select");t.value.trim()&&await $c("flutterflow",t.value);const n=e?.value.trim()||"";if(n){if(!Ys(n)){ue("The selected FlutterFlow project has an unexpected ID format.","error"),e.focus();return}await $c("flutterflow_project_id",n)}await xa(),Ca();const i=document.querySelector("#api-keys-modal .bg-blue-500"),s=i.textContent;i.textContent="Saved!",i.classList.remove("bg-blue-500","hover:bg-blue-600"),i.classList.add("bg-green-500"),setTimeout(()=>{i.textContent=s,i.classList.remove("bg-green-500"),i.classList.add("bg-blue-500","hover:bg-blue-600"),nh()},1e3)}async function Ov(){if(!confirm("Are you sure you want to clear all stored API keys?"))return;localStorage.setItem(gi,jo()),In(),localStorage.removeItem(rt+"flutterflow"),localStorage.removeItem(rt+"flutterflow_project_id"),sessionStorage.removeItem(bt+"flutterflow"),sessionStorage.removeItem(bt+"flutterflow_project_id"),sessionStorage.removeItem(lt),sessionStorage.removeItem(fi),localStorage.removeItem(rt+"salt"),await kv(),localStorage.setItem(gi,jo()),localStorage.removeItem(rt+"flutterflow"),localStorage.removeItem(rt+"flutterflow_project_id"),sessionStorage.removeItem(bt+"flutterflow"),sessionStorage.removeItem(bt+"flutterflow_project_id"),await xa();const t=document.getElementById("flutterflow-projects-select");t&&(t.innerHTML=''),Ca()}function Ys(t){return!t||t.trim().length<5||t.includes(" ")?!1:/^[a-zA-Z0-9-]+$/.test(t)}function Bv(t,e){const n=document.getElementById(t);n&&(n.value?e?n.style.borderColor="#22c55e":n.style.borderColor="#ef4444":n.style.borderColor="")}function Dv(){const t=document.getElementById("flutterflow-api-key-input");t&&(t.addEventListener("input",e=>{const n=e.target.value.trim().length>0;Bv("flutterflow-api-key-input",n)}),t.addEventListener("blur",jv(async e=>{const n=e.target.value.trim();n&&await rh(n)},500)))}function jv(t,e){let n;return function(...s){const r=()=>{clearTimeout(n),t(...s)};clearTimeout(n),n=setTimeout(r,e)}}async function rh(t){const e=document.getElementById("flutterflow-projects-select"),n=document.getElementById("flutterflow-projects-error");if(!e){console.error("Projects dropdown element not found");return}e.innerHTML='',n&&n.classList.add("hidden");try{const s=await new wi(t,"").listProjects();if(!s||s.length===0){e.innerHTML='';return}e.innerHTML='',s.forEach(r=>{const o=document.createElement("option");o.value=r.id||r.projectId||"",o.textContent=r.name||r.projectName||`Project ${r.id}`,e.appendChild(o)}),Rs&&(e.value=Rs)}catch(i){console.error("Failed to fetch projects:",i),e.innerHTML='',n&&(n.textContent=`Failed to load projects: ${i.message}`,n.classList.remove("hidden"))}}function Uv(t){const e=document.getElementById(t),i=e.nextElementSibling.querySelector("svg");e.type==="password"?(e.type="text",i.innerHTML=` `):(e.type="password",i.innerHTML=` `)}let y={step1Result:null,step2Result:null,step3Result:null,bundleSpec:null,artifactBundle:null,bundleReview:null,selectedArtifactId:null,resultsViewMode:"summary",currentStep:0,isRunning:!1};function Hv(){y.step1Result=null,y.step2Result=null,y.step3Result=null,y.bundleSpec=null,y.artifactBundle=null,y.bundleReview=null,y.selectedArtifactId=null,y.resultsViewMode="summary"}function Wv(){y.bundleSpec=di(y.step1Result,{artifactType:"CustomWidget",artifactName:"GeneratedWidget"})}function Zs(){const t=Ss(y.bundleSpec);y.artifactBundle=di(y.step2Result,{id:y.bundleSpec?.id,title:y.bundleSpec?.title,description:y.bundleSpec?.description,artifactType:t.artifactType,artifactName:t.artifactName,fileName:t.fileName,dependencies:t.dependencies,relationships:y.bundleSpec?.relationships,code:y.step2Result||""});const e=Ng(y.artifactBundle);y.artifactBundle={...y.artifactBundle,warnings:[...y.artifactBundle.warnings,...e.findings.map(n=>n.message)],metadata:{...y.artifactBundle.metadata,compatibility:e}},y.selectedArtifactId=Ss(y.artifactBundle).id}function Xs(){const t=di(y.step3Result,{id:y.artifactBundle?.id,title:y.artifactBundle?.title}),e=new Map(t.artifacts.map(i=>[i.id,i.review])),n=new Map(t.artifacts.filter(i=>{const s=i.review;return s&&typeof s.fixedSource=="string"&&s.fixedSource.trim()}).map(i=>[i.id,i.review.fixedSource.trim()]));y.bundleReview=di({id:y.artifactBundle?.id,title:y.artifactBundle?.title,artifacts:y.artifactBundle?.artifacts?.map(i=>{const s=n.get(i.id)||null;return{...i,review:e.get(i.id)||i.review||y.step3Result||null,...s?{fixedCode:s}:{}}})||[],relationships:y.artifactBundle?.relationships,warnings:y.artifactBundle?.warnings})}function oh(){const t=Aa();return{artifactType:t.artifactType||"CustomWidget",artifactName:t.artifactName||"GeneratedWidget",fileName:t.fileName||""}}function Aa(){const t=y.artifactBundle||y.bundleSpec||null;return(Array.isArray(t?.artifacts)?t.artifacts:[]).find(n=>n.id===y.selectedArtifactId)||Ss(t)}function Fa(){return Aa().code||y.step2Result||""}async function zv(){try{await xa()}catch(t){return console.error("checkConnection: initializeApiKeys failed:",t),!1}return!0}const Xi={production:"https://api.flutterflow.io/v2/",staging:"https://api.flutterflow.io/v2-staging/"};function qv(t,e){const n=e?.trim()?` (${e.trim().slice(0,200)})`:"";return t===401?`Your FlutterFlow API key was rejected (401 Unauthorized)${n}. Re-enter a current key under API Keys settings, then try again.`:`Listing FlutterFlow projects was denied (403)${n}. The key may be scoped to sync a single project without list permission - verify the key's access in FlutterFlow, re-enter it under API Keys settings, then retry.`}class wi{constructor(e,n,i="main",s=Xi.production){this.apiKey=e,this.baseUrl=s,this._projectId=n,this._branchName=i,this._endpoint=s}get projectId(){return this._projectId}get branchName(){return this._branchName==="main"?"":this._branchName}async exportProjectZip(){console.log(`Exporting code from FlutterFlow project: ${this.projectId}, branch: ${this.branchName||"main"}`);const e=[{project:{path:`projects/${this.projectId}`},...this.branchName?{branch_name:this.branchName}:{},export_as_module:!1,include_assets_map:!1,format:!1,export_as_debug:!1},{project_id:this.projectId,branch_name:this.branchName,include_assets:!1,export_as_module:!1}];let n=null;for(const i of e)try{const s=await fetch(`${this.baseUrl}exportCode`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify(i)});if(!s.ok){const a=await s.text();n=new Error(`Export failed: ${s.status} - ${a}`);continue}const r=await s.json(),o=r?.value?.project_zip||r?.project_zip;if(!o){n=new Error("Export response did not include project source.");continue}return o}catch(s){n=s}throw n||new Error("Export failed for an unknown reason.")}async fetchProjectSource(){const e=await this.exportProjectZip(),n=await JSZip.loadAsync(e,{base64:!0}),i=Object.keys(n.files).filter(a=>!n.files[a].dir&&(a==="pubspec.yaml"||a.endsWith("/pubspec.yaml"))).sort((a,l)=>a.split("/").length-l.split("/").length)[0];if(!i)throw new Error("Export did not contain a pubspec.yaml.");const s=i.slice(0,i.length-12),r=new Map,o=Object.keys(n.files).filter(a=>{if(n.files[a].dir||!a.startsWith(s))return!1;const l=a.slice(s.length);return l==="lib/flutter_flow/custom_functions.dart"||l.startsWith("lib/custom_code/")&&l.endsWith(".dart")});return await Promise.all(o.map(async a=>{r.set(a.slice(s.length),await n.files[a].async("string"))})),{pubspecYaml:await n.files[i].async("string"),files:r}}async pushCodeWithRetry(e,n=3){const i=[Xi.production,Xi.staging],s=Math.max(0,i.indexOf(this._endpoint));for(let r=0;rsetTimeout(d,1e3*(r+1)));continue}return l}catch(l){console.warn(`Push to ${a} failed: ${l.message}, trying next...`),await new Promise(u=>setTimeout(u,1e3*(r+1)))}}throw new Error("All API endpoints failed after retries")}async pushCode(e){return this.pushCodeWithRetry(e)}parseProjectsResponse(e){if(e?.success&&typeof e.value=="string")try{const i=JSON.parse(e.value);if(i&&Array.isArray(i.entries))return i.entries.map(s=>({id:s.id,name:s.project?.name||s.id}))}catch(i){console.error("Failed to parse stringified project value:",i)}const n=e?.projects||e?.items||e?.entries||(Array.isArray(e)?e:[]);return Array.isArray(n)?n:[]}async listProjects(){console.log("Listing projects for API key");const e=[`${this.baseUrl}listProjects`,"https://api.flutterflow.io/v2/l/listProjects"];let n=0,i="";for(const s of e){const r=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify({project_type:"ALL",deserialize_response:!0})});if(r.ok)return s!==e[0]&&console.log(`listProjects answered on legacy path ${s}`),this.parseProjectsResponse(await r.json());if(n=r.status,i=await r.text(),console.warn(`listProjects via ${s} returned ${n}: ${i}`),r.status===401||r.status===403)throw new Error(qv(r.status,i));if(r.status!==404)throw new Error(`List projects failed: ${r.status} - ${i}`)}throw new Error(`List projects failed: ${n} - ${i}`)}}async function Pa(t){const e=t.clone();let n;try{n=await t.json()}catch{const r=await e.text();if(!t.ok)return{success:!1,responseCode:t.status,errorMessage:r||`HTTP ${t.status}`,errorMap:new Map};throw new Error(`Invalid JSON response: ${r}`)}if(!t.ok){let s=n.message||`HTTP ${t.status}`,r=new Map;if(n.errors)r=new Map(Object.entries(n.errors));else if(!n.message&&typeof n=="object"){const o=Object.keys(n).filter(a=>a.endsWith(".dart")&&Array.isArray(n[a]));o.length>0&&(r=new Map(Object.entries(n)),s=o.flatMap(l=>n[l].map(u=>`${l}: ${u.errorMessage}`)).join(` -`)||`HTTP ${t.status}`)}return{success:!1,responseCode:t.status,errorMessage:s,errorMap:r}}let i={};if(n.value)try{i=typeof n.value=="string"?JSON.parse(n.value):n.value}catch(s){console.warn("Ignoring malformed push response value:",s)}return{success:!0,responseCode:t.status,errorMap:new Map(Object.entries(i))}}function $a(t,e){return{401:"Authentication failed. Please check your FlutterFlow API key.",403:"Access denied. You may not have permission to modify this project.",404:"Project not found. Please check your Project ID.",409:"Conflict detected. The project may have been modified elsewhere.",422:"Validation failed: Invalid request format",429:"Rate limit exceeded. Please try again in a few minutes.",500:"FlutterFlow server error. Please try again later.",503:"FlutterFlow service temporarily unavailable."}[t]||`FlutterFlow API error: ${`HTTP ${t}`}`}const W={ACTION:"A",WIDGET:"W",FUNCTION:"F",CODE_FILE:"C",DEPENDENCIES:"D",OTHER:"O"},ah=/class\s+\w+\s+extends\s+(?:StatelessWidget|StatefulWidget)\b/,lh=/extends\s+State<\w+>/;function Vv(t,e=""){if(t==="pubspec.yaml")return W.DEPENDENCIES;if(!t.endsWith(".dart")||t.endsWith("index.dart"))return W.OTHER;if(t==="custom_functions.dart")return W.FUNCTION;if(e){const n=ah.test(e),i=lh.test(e);if(n||i)return W.WIDGET;if(/^\s*Future(?:<[^>]+>)?\s+\w+\s*\(/m.test(e))return W.ACTION;if(e.match(/^\s*(String|int|double|bool|List|Map|dynamic|void)\s+\w+\s*\(/m))return W.FUNCTION}return W.CODE_FILE}function ch(t,e){switch(e){case W.ACTION:return`lib/custom_code/actions/${t}`;case W.WIDGET:return`lib/custom_code/widgets/${t}`;case W.FUNCTION:return"lib/flutter_flow/custom_functions.dart";case W.CODE_FILE:return`lib/custom_code/${t}`;case W.DEPENDENCIES:return"pubspec.yaml";case W.OTHER:return`lib/custom_code/${t}`;default:return t}}async function Ta(t,e=new Map){return mg(t,e)}const Uo=new Map;function uh(t){return`${t.baseUrl}|${t.projectId}|${t.branchName}`}function Qs(t){Uo.delete(uh(t))}async function Ra(t,e,n,i,s=""){const r=Kg(e,n);if(r.length===0)return{remoteFiles:n,syncFileMap:e,unverified:[],approximate:[]};const o=Nm(r,s),a={...o.manifest,sources:o.sources},l=o.skipped.map(h=>h.reason);l.forEach(h=>console.warn(`[custom class deploy] ${h}`));const u=o.approximate;u.forEach(h=>console.warn(`[custom class deploy] ${h}`)),console.log(`Provisioning ${r.length} new FlutterFlow custom code file(s) before sync.`),be.set("provision");const c=await fetch(rv,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:t.apiKey,projectId:t.projectId,baseUrl:t.baseUrl,commitMessage:i,customClasses:r,verification:a,stream:!0})}),d=await Lm(c,{onPhase:h=>be.setSubstatus(h),onLog:h=>console.log(`[custom class deploy] ${h}`)});if(!d.success){const h=d.details?` ${d.details}`:"";throw new Error(`${d.error||"FlutterFlow custom class provisioning failed."}${h}`)}return Qs(t),d.verificationSkipped&&(console.warn(`[custom class deploy] ${d.verificationSkipped}`),l.push(d.verificationSkipped)),{remoteFiles:n,syncFileMap:Jg(e,r),unverified:l,approximate:u}}async function Na(t,e={}){const n=uh(t);let i=Uo.get(n);if(i===void 0){try{i=await t.fetchProjectSource()}catch(l){throw new Error(`Could not read your project's pubspec.yaml (${l.message}). Deploy was stopped so your existing package dependencies aren't overwritten. Check your FlutterFlow API key and project, then try again.`)}const a=zd(i.pubspecYaml);if(!a.valid)throw new Error(`Your project's pubspec.yaml could not be read reliably (${a.errors.join("; ")}). Deploy was stopped so your existing package dependencies aren't overwritten.`);Uo.set(n,i)}const s=await Gm(i.pubspecYaml,e),r=Fm(i.pubspecYaml,s.overrides),o=Am(r.yaml,s.additions);return s.warnings.forEach(a=>console.warn(`[pubspec] ${a}`)),o.added.length>0&&console.log("Adding dependencies:",o.added.map(a=>`${a}: ${s.additions[a]||"any"}`).join(", "),s.sdk.dartSdkFloor?`(resolved for Dart ${s.sdk.dartSdkFloor})`:""),s.kept.forEach(({name:a,constraint:l})=>console.log(`Keeping your existing ${a}: ${l||"(non-version source)"}`)),{...o,overridden:r.overridden,warnings:s.warnings,remoteFiles:i.files}}function Gv(t){const e=[],n=[];t.content.length>5e4&&n.push("Code file is large (>50KB). This may take longer to commit."),t.content.length>1e5&&e.push("Code file is too large (>100KB). Consider splitting into smaller components.");const i=t.content.split(` +`)||`HTTP ${t.status}`)}return{success:!1,responseCode:t.status,errorMessage:s,errorMap:r}}let i={};if(n.value)try{i=typeof n.value=="string"?JSON.parse(n.value):n.value}catch(s){console.warn("Ignoring malformed push response value:",s)}return{success:!0,responseCode:t.status,errorMap:new Map(Object.entries(i))}}function $a(t,e){return{401:"Authentication failed. Please check your FlutterFlow API key.",403:"Access denied. You may not have permission to modify this project.",404:"Project not found. Please check your Project ID.",409:"Conflict detected. The project may have been modified elsewhere.",422:"Validation failed: Invalid request format",429:"Rate limit exceeded. Please try again in a few minutes.",500:"FlutterFlow server error. Please try again later.",503:"FlutterFlow service temporarily unavailable."}[t]||`FlutterFlow API error: ${`HTTP ${t}`}`}const W={ACTION:"A",WIDGET:"W",FUNCTION:"F",CODE_FILE:"C",DEPENDENCIES:"D",OTHER:"O"},ah=/class\s+\w+\s+extends\s+(?:StatelessWidget|StatefulWidget)\b/,lh=/extends\s+State<\w+>/;function Vv(t,e=""){if(t==="pubspec.yaml")return W.DEPENDENCIES;if(!t.endsWith(".dart")||t.endsWith("index.dart"))return W.OTHER;if(t==="custom_functions.dart")return W.FUNCTION;if(e){const n=ah.test(e),i=lh.test(e);if(n||i)return W.WIDGET;if(/^\s*Future(?:<[^>]+>)?\s+\w+\s*\(/m.test(e))return W.ACTION;if(e.match(/^\s*(String|int|double|bool|List|Map|dynamic|void)\s+\w+\s*\(/m))return W.FUNCTION}return W.CODE_FILE}function ch(t,e){switch(e){case W.ACTION:return`lib/custom_code/actions/${t}`;case W.WIDGET:return`lib/custom_code/widgets/${t}`;case W.FUNCTION:return"lib/flutter_flow/custom_functions.dart";case W.CODE_FILE:return`lib/custom_code/${t}`;case W.DEPENDENCIES:return"pubspec.yaml";case W.OTHER:return`lib/custom_code/${t}`;default:return t}}async function Ta(t,e=new Map){return mg(t,e)}const Uo=new Map;function uh(t){return`${t.baseUrl}|${t.projectId}|${t.branchName}`}function Qs(t){Uo.delete(uh(t))}async function Ra(t,e,n,i,s=""){const r=Kg(e,n);if(r.length===0)return{remoteFiles:n,syncFileMap:e,unverified:[]};const o=Nm(r,s),a={...o.manifest,sources:o.sources},l=o.skipped.map(d=>d.reason);l.forEach(d=>console.warn(`[custom class deploy] ${d}`)),console.log(`Provisioning ${r.length} new FlutterFlow custom code file(s) before sync.`),be.set("provision");const u=await fetch(rv,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:t.apiKey,projectId:t.projectId,baseUrl:t.baseUrl,commitMessage:i,customClasses:r,verification:a,stream:!0})}),c=await Lm(u,{onPhase:d=>be.setSubstatus(d),onLog:d=>console.log(`[custom class deploy] ${d}`)});if(!c.success){const d=c.details?` ${c.details}`:"";throw new Error(`${c.error||"FlutterFlow custom class provisioning failed."}${d}`)}return Qs(t),c.verificationSkipped&&(console.warn(`[custom class deploy] ${c.verificationSkipped}`),l.push(c.verificationSkipped)),{remoteFiles:n,syncFileMap:Jg(e,r),unverified:l}}async function Na(t,e={}){const n=uh(t);let i=Uo.get(n);if(i===void 0){try{i=await t.fetchProjectSource()}catch(l){throw new Error(`Could not read your project's pubspec.yaml (${l.message}). Deploy was stopped so your existing package dependencies aren't overwritten. Check your FlutterFlow API key and project, then try again.`)}const a=zd(i.pubspecYaml);if(!a.valid)throw new Error(`Your project's pubspec.yaml could not be read reliably (${a.errors.join("; ")}). Deploy was stopped so your existing package dependencies aren't overwritten.`);Uo.set(n,i)}const s=await Gm(i.pubspecYaml,e),r=Fm(i.pubspecYaml,s.overrides),o=Am(r.yaml,s.additions);return s.warnings.forEach(a=>console.warn(`[pubspec] ${a}`)),o.added.length>0&&console.log("Adding dependencies:",o.added.map(a=>`${a}: ${s.additions[a]||"any"}`).join(", "),s.sdk.dartSdkFloor?`(resolved for Dart ${s.sdk.dartSdkFloor})`:""),s.kept.forEach(({name:a,constraint:l})=>console.log(`Keeping your existing ${a}: ${l||"(non-version source)"}`)),{...o,overridden:r.overridden,warnings:s.warnings,remoteFiles:i.files}}function Gv(t){const e=[],n=[];t.content.length>5e4&&n.push("Code file is large (>50KB). This may take longer to commit."),t.content.length>1e5&&e.push("Code file is too large (>100KB). Consider splitting into smaller components.");const i=t.content.split(` `).length;i>500&&n.push(`Code has ${i} lines. Consider breaking it into smaller widgets.`),t.content.includes("setState")&&t.codeType===W.ACTION&&n.push("Using setState in a Custom Action may not work as expected. Consider using a Custom Widget."),t.content.includes("dynamic")&&!t.content.includes("?")&&n.push('Code uses "dynamic" types. Consider adding explicit types for better null safety.'),t.content.match(/Color\(0xFF[0-9A-Fa-f]{6}\)/)&&n.push("Code contains hardcoded colors. Consider using FlutterFlowTheme.of(context) for theme consistency.");const s=t.content.match(/print\s*\(/g);s&&s.length>3&&n.push(`Code contains ${s.length} print statements. Consider removing debug prints before committing.`);const r=pm(t.content);if(r&&e.push(`FlutterFlow cannot format this code - ${r}. Fix or regenerate before committing.`),t.codeType===W.WIDGET){const o=Ld(t.content),a=um(t.fileName);if(o.length===0)e.push("No public widget class found (must extend StatelessWidget or StatefulWidget).");else if(!o.includes(a)){const l=`${Od(o[0])}`;e.push(`Widget class name "${o[0]}" does not match the file name "${t.fileName}". FlutterFlow derives the widget from the file name, so it will report "No widget ${a} found". Rename the file to "${l}" or the class to match before committing.`)}}return{canProceed:e.length===0,issues:e,warnings:n}}function dh(t,e={}){const{artifactType:n="CustomWidget",artifactName:i="GeneratedCode",fileName:s}=e,r=lm(t);let o=s||i;if(n==="CustomFunction")o="custom_functions.dart";else if(n==="CustomWidget"){const u=Ld(r)[0],c=u?Od(u):null;c&&o!==c?(console.warn(`Commit file name "${o}" does not match declared widget class "${u}"; renaming to "${c}" so FlutterFlow can find the widget.`),o=c):o.endsWith(".dart")||(o+=".dart")}else o.endsWith(".dart")||(o+=".dart");let a=W.CODE_FILE;switch(n){case"CustomAction":a=W.ACTION;break;case"CustomWidget":a=W.WIDGET;break;case"CustomFunction":a=W.FUNCTION;break;case"CustomClass":case"CodeFile":a=W.CODE_FILE;break}let l="";return a===W.WIDGET?l=`// Automatic FlutterFlow imports import '/flutter_flow/flutter_flow_theme.dart'; import '/flutter_flow/flutter_flow_util.dart'; @@ -111,13 +111,13 @@ import '/flutter_flow/uploaded_file.dart'; `),{content:Og(r,l),fileName:o,codeType:a,artifactType:n,artifactName:i}}function Kv(t){const e={};for(const n of ma(t))e[n]="";return e}function Jv(t,e={}){return{timestamp:new Date().toISOString(),artifactType:t.artifactType,artifactName:t.artifactName,codeType:t.codeType,fileName:t.fileName,generatedFrom:e.step1Result?"pipeline":"direct",model:e.selectedModel||"unknown",codeSize:t.content.length}}function Yv(t,e,n,i=new Set,s=""){const r=[],o=ah.test(e),a=lh.test(e);return n===W.WIDGET&&!o&&!a&&r.push("No widget class definition found (must extend StatelessWidget or StatefulWidget)"),{valid:r.length===0,errors:r}}function er(t){const e=[],n=[];if(!t||t.size===0)return e.push("No files to commit"),{valid:!1,errors:e,warnings:n};const i=new Set(Array.from(t.values()).flatMap(s=>Hs(s.content||"")));for(const[s,r]of t.entries()){if((!r.content||r.content.trim().length===0)&&e.push(`File ${s} is empty`),r.content&&r.content.length>1e5&&n.push(`File ${s} is very large (>100KB)`),s.endsWith(".dart")){const o=Yv(s,r.content,r.type,i,r.artifactName);o.valid||e.push(...o.errors.map(a=>`${s}: ${a}`))}if(s==="pubspec.yaml"){const o=zd(r.content);o.valid||e.push(...o.errors)}}return{valid:e.length===0,errors:e,warnings:n}}const K={IDLE:"IDLE",PREPARING:"PREPARING",VALIDATING:"VALIDATING",PUSHING:"PUSHING",SUCCESS:"SUCCESS",ERROR:"ERROR"},J={currentState:K.IDLE,startTime:null,endTime:null,error:null,result:null,filesProcessed:0,totalFiles:0,reset(){this.currentState=K.IDLE,this.startTime=null,this.endTime=null,this.error=null,this.result=null,this.filesProcessed=0,this.totalFiles=0},setState(t){if(!Object.values(K).includes(t)){console.error(`Invalid commit state: ${t}`);return}this.currentState=t,t===K.PREPARING&&(this.startTime=Date.now()),(t===K.SUCCESS||t===K.ERROR)&&(this.endTime=Date.now()),typeof window<"u"&&window.dispatchEvent&&window.dispatchEvent(new CustomEvent("commitStateChange",{detail:{state:t,commitState:this}})),console.log(`Commit state changed to: ${t}`)},setError(t){this.error=t,this.setState(K.ERROR)},setSuccess(t){this.result=t,this.setState(K.SUCCESS)},setProgress(t,e){this.filesProcessed=t,this.totalFiles=e},getElapsedTime(){return this.startTime?(this.endTime||Date.now())-this.startTime:null},isInProgress(){return this.currentState===K.PREPARING||this.currentState===K.VALIDATING||this.currentState===K.PUSHING}};async function Zv(t,e,n={}){let{codeType:i="W"}=n;const{pubspecDeps:s={},artifactName:r=e}=n;i==="CustomWidget"&&(i=W.WIDGET),i==="CustomAction"&&(i=W.ACTION),i==="CustomFunction"&&(i=W.FUNCTION),i==="CustomClass"&&(i=W.CODE_FILE),i==="CodeFile"&&(i=W.CODE_FILE),J.reset(),J.setState(K.PREPARING);try{const o=await Ee("flutterflow"),a=await Ee("flutterflow_project_id");if(!o||!a)throw new Error("FlutterFlow credentials not configured. Please set your API key and Project ID in the API Keys settings.");if(!Ys(a))throw new Error("Invalid FlutterFlow Project ID format.");const l=yi(),u=new wi(o,a,"main",l);J.setState(K.VALIDATING);const c=new Map,d=i||Vv(e,t),h=ch(e,d);c.set(e,{artifactName:r,content:t,type:d,path:h}),J.setProgress(0,c.size);const p=er(c);if(!p.valid)throw new Error(`Validation failed: ${p.errors.join(` -`)}`);const f=await Na(u,s),g=f.yaml,m=await Ra(u,c,f.remoteFiles,`Provision ${r} custom class`,g),v=await Ta(m.syncFileMap,m.remoteFiles),b=new Map(m.syncFileMap);b.set("pubspec.yaml",{content:g,type:"D",path:"pubspec.yaml"}),be.set("package");const w=await Ma(b),I={project_id:a,zipped_custom_code:w,uid:`web_${Date.now()}`,branch_name:u.branchName,serialized_yaml:g,file_map:v.fileMapContents,functions_map:v.functionsMapContents};J.setState(K.PUSHING),J.setProgress(1,c.size),Qs(u),be.set("push");const A=await u.pushCode(I),F=await Pa(A);if(F.success)J.setSuccess({fileCount:c.size,projectId:a,warnings:F.errorMap&&F.errorMap.size>0?Array.from(F.errorMap.entries()):[]});else{const D=F.errorMessage||$a(F.responseCode);throw new Error(D)}return{success:!0,message:`Successfully committed ${e} to FlutterFlow project ${a}`,addedDependencies:f.added,unverified:m.unverified,approximate:m.approximate,warnings:F.errorMap?Array.from(F.errorMap.entries()):[]}}catch(o){return console.error("Commit failed:",o),J.setError(o),{success:!1,error:o.message,state:J.currentState}}}async function Ma(t){const e=new JSZip;for(const[n,i]of t.entries())e.file(n,i.content);return e.generateAsync({type:"base64",compression:"DEFLATE",compressionOptions:{level:6}})}async function Xv(t,e={}){const{artifactType:n,artifactName:i,fileName:s,pipelineResult:r}=e;console.log(`Starting commit for ${i} (${n})`);try{J.setState(K.PREPARING);const o=dh(t,{artifactType:n,artifactName:i,fileName:s}),a=Kv(o.content);console.log("Detected dependencies:",a),J.setState(K.VALIDATING);const l=await Ee("flutterflow"),u=ni||await Ee("flutterflow_project_id");if(!l)throw new Error("FlutterFlow API Key not configured. Please add it in API Keys settings.");if(!u)throw new Error("FlutterFlow Project ID not configured. Please add it in API Keys settings.");if(!Ys(u))throw new Error("Invalid FlutterFlow Project ID format.");const c=new Map;c.set(o.fileName,{artifactName:i,content:o.content,type:o.codeType,path:ch(o.fileName,o.codeType),functionName:o.codeType===W.FUNCTION?i:void 0}),J.setProgress(0,c.size);const d=er(c);if(!d.valid)throw new Error(`File validation failed: +`)}`);const f=await Na(u,s),g=f.yaml,m=await Ra(u,c,f.remoteFiles,`Provision ${r} custom class`,g),v=await Ta(m.syncFileMap,m.remoteFiles),E=new Map(m.syncFileMap);E.set("pubspec.yaml",{content:g,type:"D",path:"pubspec.yaml"}),be.set("package");const w=await Ma(E),I={project_id:a,zipped_custom_code:w,uid:`web_${Date.now()}`,branch_name:u.branchName,serialized_yaml:g,file_map:v.fileMapContents,functions_map:v.functionsMapContents};J.setState(K.PUSHING),J.setProgress(1,c.size),Qs(u),be.set("push");const A=await u.pushCode(I),F=await Pa(A);if(F.success)J.setSuccess({fileCount:c.size,projectId:a,warnings:F.errorMap&&F.errorMap.size>0?Array.from(F.errorMap.entries()):[]});else{const D=F.errorMessage||$a(F.responseCode);throw new Error(D)}return{success:!0,message:`Successfully committed ${e} to FlutterFlow project ${a}`,addedDependencies:f.added,unverified:m.unverified,warnings:F.errorMap?Array.from(F.errorMap.entries()):[]}}catch(o){return console.error("Commit failed:",o),J.setError(o),{success:!1,error:o.message,state:J.currentState}}}async function Ma(t){const e=new JSZip;for(const[n,i]of t.entries())e.file(n,i.content);return e.generateAsync({type:"base64",compression:"DEFLATE",compressionOptions:{level:6}})}async function Xv(t,e={}){const{artifactType:n,artifactName:i,fileName:s,pipelineResult:r}=e;console.log(`Starting commit for ${i} (${n})`);try{J.setState(K.PREPARING);const o=dh(t,{artifactType:n,artifactName:i,fileName:s}),a=Kv(o.content);console.log("Detected dependencies:",a),J.setState(K.VALIDATING);const l=await Ee("flutterflow"),u=ni||await Ee("flutterflow_project_id");if(!l)throw new Error("FlutterFlow API Key not configured. Please add it in API Keys settings.");if(!u)throw new Error("FlutterFlow Project ID not configured. Please add it in API Keys settings.");if(!Ys(u))throw new Error("Invalid FlutterFlow Project ID format.");const c=new Map;c.set(o.fileName,{artifactName:i,content:o.content,type:o.codeType,path:ch(o.fileName,o.codeType),functionName:o.codeType===W.FUNCTION?i:void 0}),J.setProgress(0,c.size);const d=er(c);if(!d.valid)throw new Error(`File validation failed: ${d.errors.join(` -`)}`);d.warnings.length>0&&console.warn("Validation warnings:",d.warnings),J.setState(K.PUSHING);const h=yi(),p=new wi(l,u,"main",h),f=await Na(p,a),g=f.yaml,m=await Ra(p,c,f.remoteFiles,`Provision ${i} custom class`,g),v=await Ta(m.syncFileMap,m.remoteFiles),b=new Map(m.syncFileMap);b.set("pubspec.yaml",{content:g,type:W.DEPENDENCIES,path:"pubspec.yaml"}),be.set("package");const w=await Ma(b),I={project_id:u,zipped_custom_code:w,uid:`web_${Date.now()}`,branch_name:p.branchName,serialized_yaml:g,file_map:v.fileMapContents,functions_map:v.functionsMapContents};J.setProgress(1,c.size),Qs(p),be.set("push");const A=await p.pushCode(I),F=await Pa(A);if(F.success){const D={...Jv(o,r),projectId:u};return J.setSuccess({...D,fileCount:c.size,warnings:F.errorMap?Array.from(F.errorMap.entries()):[]}),{success:!0,message:`Successfully committed ${o.fileName} to FlutterFlow`,metadata:D,addedDependencies:f.added,unverified:m.unverified,approximate:m.approximate,warnings:F.errorMap?Array.from(F.errorMap.entries()):[],elapsedTime:J.getElapsedTime()}}else{const D=F.errorMessage||$a(F.responseCode),S=new Error(D);throw S.errorMap=F.errorMap,S}}catch(o){console.error("Commit execution failed:",o),J.setError(o);let a=new Map;if(o.errorMap)a=o.errorMap;else if(o.message&&o.message.includes("{"))try{const l=o.message.match(/\{[\s\S]*\}/);if(l){const u=JSON.parse(l[0]);a=new Map(Object.entries(u))}}catch(l){console.warn("Failed to parse error map from commit response:",l)}return{success:!1,error:o.message,errorMap:a,state:J.currentState,elapsedTime:J.getElapsedTime()}}}async function Qv(t,e={}){const{pipelineResult:n}=e;try{if(J.setState(K.PREPARING),t.errors?.length>0)throw new Error(`Bundle validation failed: +`)}`);d.warnings.length>0&&console.warn("Validation warnings:",d.warnings),J.setState(K.PUSHING);const h=yi(),p=new wi(l,u,"main",h),f=await Na(p,a),g=f.yaml,m=await Ra(p,c,f.remoteFiles,`Provision ${i} custom class`,g),v=await Ta(m.syncFileMap,m.remoteFiles),E=new Map(m.syncFileMap);E.set("pubspec.yaml",{content:g,type:W.DEPENDENCIES,path:"pubspec.yaml"}),be.set("package");const w=await Ma(E),I={project_id:u,zipped_custom_code:w,uid:`web_${Date.now()}`,branch_name:p.branchName,serialized_yaml:g,file_map:v.fileMapContents,functions_map:v.functionsMapContents};J.setProgress(1,c.size),Qs(p),be.set("push");const A=await p.pushCode(I),F=await Pa(A);if(F.success){const D={...Jv(o,r),projectId:u};return J.setSuccess({...D,fileCount:c.size,warnings:F.errorMap?Array.from(F.errorMap.entries()):[]}),{success:!0,message:`Successfully committed ${o.fileName} to FlutterFlow`,metadata:D,addedDependencies:f.added,unverified:m.unverified,warnings:F.errorMap?Array.from(F.errorMap.entries()):[],elapsedTime:J.getElapsedTime()}}else{const D=F.errorMessage||$a(F.responseCode),S=new Error(D);throw S.errorMap=F.errorMap,S}}catch(o){console.error("Commit execution failed:",o),J.setError(o);let a=new Map;if(o.errorMap)a=o.errorMap;else if(o.message&&o.message.includes("{"))try{const l=o.message.match(/\{[\s\S]*\}/);if(l){const u=JSON.parse(l[0]);a=new Map(Object.entries(u))}}catch(l){console.warn("Failed to parse error map from commit response:",l)}return{success:!1,error:o.message,errorMap:a,state:J.currentState,elapsedTime:J.getElapsedTime()}}}async function Qv(t,e={}){const{pipelineResult:n}=e;try{if(J.setState(K.PREPARING),t.errors?.length>0)throw new Error(`Bundle validation failed: ${t.errors.join(` `)}`);const i=new Map(t.fileEntries.map(I=>[I.fileName,{artifactId:I.artifactId,artifactName:I.artifactName,content:I.content,type:I.type,path:I.path,functionName:I.type===W.FUNCTION?I.artifactName:void 0}]));J.setProgress(0,i.size);const s=er(i);if(!s.valid)throw new Error(`File validation failed: ${s.errors.join(` -`)}`);J.setState(K.VALIDATING);const r=await Ee("flutterflow"),o=ni||await Ee("flutterflow_project_id");if(!r)throw new Error("FlutterFlow API Key not configured. Please add it in API Keys settings.");if(!o)throw new Error("FlutterFlow Project ID not configured. Please add it in API Keys settings.");if(!Ys(o))throw new Error("Invalid FlutterFlow Project ID format.");J.setState(K.PUSHING);const a=yi(),l=new wi(r,o,"main",a),u=await Na(l,t.dependencies),c=u.yaml,d=await Ra(l,i,u.remoteFiles,`Provision ${t.title} custom classes`,c),h=await Ta(d.syncFileMap,d.remoteFiles),p=new Map(d.syncFileMap);p.set("pubspec.yaml",{content:c,type:W.DEPENDENCIES,path:"pubspec.yaml"}),be.set("package");const f=await Ma(p),g={project_id:o,zipped_custom_code:f,uid:`web_${Date.now()}`,branch_name:l.branchName,serialized_yaml:c,file_map:h.fileMapContents,functions_map:h.functionsMapContents};J.setProgress(1,i.size),Qs(l),be.set("push");const m=await l.pushCode(g),v=await Pa(m);if(v.success){const I={...n,artifactType:"Bundle",artifactName:t.title,fileName:`${t.fileEntries.length} artifacts`,codeSize:t.fileEntries.reduce((A,F)=>A+F.content.length,0),projectId:o};return J.setSuccess({...I,fileCount:i.size,warnings:v.errorMap?Array.from(v.errorMap.entries()):[]}),{success:!0,message:`Successfully committed ${t.fileEntries.length} artifacts to FlutterFlow`,metadata:I,addedDependencies:u.added,unverified:d.unverified,approximate:d.approximate,warnings:v.errorMap?Array.from(v.errorMap.entries()):[],elapsedTime:J.getElapsedTime()}}const b=v.errorMessage||$a(v.responseCode),w=new Error(b);throw w.errorMap=v.errorMap,w}catch(i){return console.error("Bundle commit execution failed:",i),J.setError(i),{success:!1,error:i.message,errorMap:i.errorMap||new Map,state:J.currentState,elapsedTime:J.getElapsedTime()}}}async function e_(t,e=[]){const n=ha("architect");try{return await Ms("architect",Yd,sg(t),n,e)}catch(i){throw i.isModelArmor?i:new Error(`Prompt Architect failed: ${i.message}`)}}async function tr(t,e,n=[]){const i=rg(t),s=ha("generator",y.bundleSpec);try{return await Ms("generator",e,i,s,n)}catch(r){if(r.isModelArmor)throw r;if(e!==jr){console.warn(`Code Generator failed with ${e}, retrying with fallback model:`,r.message);try{return await Ms("generator",jr,i,s,n)}catch(o){throw o.isModelArmor?o:new Error(`Code Generator failed: primary (${e}): ${r.message} | fallback (${jr}): ${o.message}`)}}throw new Error(`Code Generator failed: ${r.message}`)}}async function nr(t,e=null){const n={...ha("review",y.artifactBundle||y.bundleSpec),architect_output:e};try{return await Ms("review",Zd,og(t),n)}catch(i){throw i.isModelArmor?i:new Error(`Code Review failed: ${i.message}`)}}function La(t,e){return t.isModelArmor?`${t.userTitle}: ${t.userMessage}`:`${e}: ${t.message}`}function Ho(t,e){const n=document.getElementById(`step${t}-item`),i=document.getElementById(`step${t}-status`);!n||!i||(n.classList.remove("active","completed","error"),i.classList.remove("running","completed","error"),e==="active"?(n.classList.add("active"),i.classList.add("running"),i.innerHTML=` +`)}`);J.setState(K.VALIDATING);const r=await Ee("flutterflow"),o=ni||await Ee("flutterflow_project_id");if(!r)throw new Error("FlutterFlow API Key not configured. Please add it in API Keys settings.");if(!o)throw new Error("FlutterFlow Project ID not configured. Please add it in API Keys settings.");if(!Ys(o))throw new Error("Invalid FlutterFlow Project ID format.");J.setState(K.PUSHING);const a=yi(),l=new wi(r,o,"main",a),u=await Na(l,t.dependencies),c=u.yaml,d=await Ra(l,i,u.remoteFiles,`Provision ${t.title} custom classes`,c),h=await Ta(d.syncFileMap,d.remoteFiles),p=new Map(d.syncFileMap);p.set("pubspec.yaml",{content:c,type:W.DEPENDENCIES,path:"pubspec.yaml"}),be.set("package");const f=await Ma(p),g={project_id:o,zipped_custom_code:f,uid:`web_${Date.now()}`,branch_name:l.branchName,serialized_yaml:c,file_map:h.fileMapContents,functions_map:h.functionsMapContents};J.setProgress(1,i.size),Qs(l),be.set("push");const m=await l.pushCode(g),v=await Pa(m);if(v.success){const I={...n,artifactType:"Bundle",artifactName:t.title,fileName:`${t.fileEntries.length} artifacts`,codeSize:t.fileEntries.reduce((A,F)=>A+F.content.length,0),projectId:o};return J.setSuccess({...I,fileCount:i.size,warnings:v.errorMap?Array.from(v.errorMap.entries()):[]}),{success:!0,message:`Successfully committed ${t.fileEntries.length} artifacts to FlutterFlow`,metadata:I,addedDependencies:u.added,unverified:d.unverified,warnings:v.errorMap?Array.from(v.errorMap.entries()):[],elapsedTime:J.getElapsedTime()}}const E=v.errorMessage||$a(v.responseCode),w=new Error(E);throw w.errorMap=v.errorMap,w}catch(i){return console.error("Bundle commit execution failed:",i),J.setError(i),{success:!1,error:i.message,errorMap:i.errorMap||new Map,state:J.currentState,elapsedTime:J.getElapsedTime()}}}async function e_(t,e=[]){const n=ha("architect");try{return await Ms("architect",Yd,sg(t),n,e)}catch(i){throw i.isModelArmor?i:new Error(`Prompt Architect failed: ${i.message}`)}}async function tr(t,e,n=[]){const i=rg(t),s=ha("generator",y.bundleSpec);try{return await Ms("generator",e,i,s,n)}catch(r){if(r.isModelArmor)throw r;if(e!==jr){console.warn(`Code Generator failed with ${e}, retrying with fallback model:`,r.message);try{return await Ms("generator",jr,i,s,n)}catch(o){throw o.isModelArmor?o:new Error(`Code Generator failed: primary (${e}): ${r.message} | fallback (${jr}): ${o.message}`)}}throw new Error(`Code Generator failed: ${r.message}`)}}async function nr(t,e=null){const n={...ha("review",y.artifactBundle||y.bundleSpec),architect_output:e};try{return await Ms("review",Zd,og(t),n)}catch(i){throw i.isModelArmor?i:new Error(`Code Review failed: ${i.message}`)}}function La(t,e){return t.isModelArmor?`${t.userTitle}: ${t.userMessage}`:`${e}: ${t.message}`}function Ho(t,e){const n=document.getElementById(`step${t}-item`),i=document.getElementById(`step${t}-status`);!n||!i||(n.classList.remove("active","completed","error"),i.classList.remove("running","completed","error"),e==="active"?(n.classList.add("active"),i.classList.add("running"),i.innerHTML=` `):e==="completed"?(n.classList.add("completed"),i.classList.add("completed"),i.innerHTML=` @@ -181,7 +181,7 @@ Error: ${h} `}else s+=`${t} `;const r=$d({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,userFeedback:s});or(),at(2),ze(2),ve(2,!0),y.step2Result=await tr(r,n),Zs();const o=document.getElementById("step2-output"),a=xn(y.step2Result);o.textContent=a,o.dataset.raw=a,ve(2,!1),ze(3),at(3),ve(3,!0),y.step3Result=await nr(y.step2Result,y.step1Result),Xs();const l=document.getElementById("step3-output");l.textContent=y.step3Result,ve(3,!1),Mt();const u=Ks(y.step3Result);ar(a,u)}catch(s){console.error("Regeneration failed:",s),Mt(),ue(La(s,"Regeneration failed"),"error")}finally{y.isRunning=!1,i&&(i.disabled=!1,i.textContent="Fix Errors & Regenerate"),en()}}async function h_(){const t=document.getElementById("ff-status-dot"),e=document.getElementById("ff-status-text");if(!t||!e)return;const n=await Ee("flutterflow"),i=await Ee("flutterflow_project_id");n&&i?(t.className="w-2 h-2 rounded-full bg-green-500",e.textContent="FlutterFlow credentials configured",e.className="text-green-600"):n||i?(t.className="w-2 h-2 rounded-full bg-yellow-500",e.textContent="FlutterFlow credentials incomplete",e.className="text-yellow-600"):(t.className="w-2 h-2 rounded-full bg-red-500",e.textContent="FlutterFlow credentials not configured",e.className="text-red-600")}async function p_(t){try{const e=await fetch(`${Ze}/auth/send-magic-link`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:t})});if(!e.ok)throw new Error(`Failed to send magic link: HTTP ${e.status}`);return e.json()}catch(e){throw console.error("sendMagicLink failed:",{email:t,message:e.message,stack:e.stack}),e}}async function f_(t){try{const n=await(await fetch(`${Ze}/auth/verify-magic-link`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:t})})).json();if(n.error||!n.email||!n.sessionToken)throw new Error(n.error||"Invalid or expired link");return n}catch(e){throw console.error("verifyMagicLink failed:",{message:e.message,stack:e.stack}),e}}async function g_(t){try{const e=await fetch(`${Ze}/auth/refresh-session`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:t})});if(!e.ok)return console.error("refreshSession: non-OK response",{url:`${Ze}/auth/refresh-session`,status:e.status}),null;const n=await e.json();return n.error||!n.email||!n.sessionToken?(console.warn("refreshSession: validation failed",{error:n.error,hasEmail:!!n.email,hasToken:!!n.sessionToken}),null):n}catch(e){return console.error("refreshSession: fetch failed",{url:`${Ze}/auth/refresh-session`,message:e.message,stack:e.stack}),null}}function Nc(t,e){const n=hh(),i=(V.email||n.email)!==t;V.email=t,V.sessionToken=e,V.isVerified=!0,pe=kn({isLoading:!0}),localStorage.setItem(Is,JSON.stringify({email:t,sessionToken:e})),i&&Ha()}function Ba(){V.email=null,V.sessionToken=null,V.isVerified=!1,pe=kn({isResolved:!0}),localStorage.removeItem(Is),localStorage.removeItem(As)}function hh(){try{const t=localStorage.getItem(Is);if(!t)return{email:null,sessionToken:null};const e=JSON.parse(t);return!e.email||!e.sessionToken?{email:null,sessionToken:null}:e}catch(t){return console.warn("getStoredSession: failed to parse auth session:",t),localStorage.removeItem(Is),{email:null,sessionToken:null}}}async function m_(){const e=new URLSearchParams(window.location.search).get("token");if(e){window.history.replaceState({},"",window.location.pathname+window.location.hash);try{const{email:n,sessionToken:i}=await f_(e);Nc(n,i)}catch(n){ue(n.message||"Sign-in link invalid or expired.","error")}}else{const{email:n,sessionToken:i}=hh();if(n&&i){const s=await g_(i);s?Nc(s.email,s.sessionToken):Ba()}}ja()}function Da(){const t=document.getElementById("signin-modal");t&&Ve(t)}function v_(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("signin-modal");e&&Xe(e)}async function __(){const t=document.getElementById("signin-email-input"),e=document.getElementById("signin-submit-btn"),n=document.getElementById("signin-message"),i=zs(t?.value);if(!i||!/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/.test(i)||i.length>254){n&&(n.textContent="Please enter a valid email address.");return}e&&(e.disabled=!0,e.textContent="Sending…");const r=Dd(i);n&&r&&(n.textContent=r);try{const o=await p_(i);t&&o?.code!==Ki&&(t.value=""),n&&(n.textContent=Em(o,i)),e&&(e.textContent=o?.code===Ki?"Send Link":"Sent!"),e&&o?.code===Ki&&(e.disabled=!1)}catch(o){console.error("handleMagicLinkRequest: sendMagicLink failed",{email:i,err:o}),n&&(n.textContent="Something went wrong. Please try again."),e&&(e.disabled=!1,e.textContent="Send Link")}}function y_(){Ba(),Ha(),ja(),rr()}function ja(){const t=V.isVerified&&!!V.email,e=document.getElementById("auth-signedout"),n=document.getElementById("auth-signedin"),i=document.getElementById("auth-guest-usage");e&&e.classList.toggle("hidden",t),n&&n.classList.toggle("hidden",!t),i&&i.classList.toggle("hidden",t);const s=document.getElementById("auth-user-email");s&&(s.textContent=V.email||""),Qi(),rr()}async function ph(){try{if(typeof FingerprintJS>"u"){console.warn("resolveIdentity: FingerprintJS not loaded, skipping");return}const e=await(await FingerprintJS.load()).get(),n=e.visitorId,i=await fetch(cv,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({fingerprint:e.visitorId,cookie_id:n})});if(!i.ok)throw new Error(`Identity check HTTP ${i.status}`);const s=await i.json();if(Ke.userId=s.user_id,Ke.token=s.identity_token||null,Ke.status=s.status,Ke.resolved=!0,sessionStorage.setItem(av,s.user_id),Ke.token&&sessionStorage.setItem(lv,Ke.token),s.usage_count!==void 0){const r=Rt(),a=(s.usage_month||r)===r?s.usage_count:0;localStorage.setItem(Zt,JSON.stringify({count:a,month:r})),ii()}console.log(`Identity resolved: ${s.status} (${s.user_id.slice(0,8)}...) usage: ${s.usage_count??"n/a"}`)}catch(t){console.error("resolveIdentity failed:",t)}}let Ur=null;function w_(t=5e3){return Ke.resolved?Promise.resolve():(Ur||(Ur=ph().catch(e=>{console.warn("ensureIdentityReady: identity resolution failed",e)})),Promise.race([Ur,new Promise(e=>setTimeout(e,t))]))}function fh(){const t=Rt();try{const e=localStorage.getItem(Zt);return e?JSON.parse(e):{count:0,month:t}}catch(e){return console.warn("getUsageData: failed to parse usage storage",{key:Zt,month:t,err:e}),localStorage.removeItem(Zt),{count:0,month:t}}}function Rt(){const t=new Date;return`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,"0")}`}function bi(){const t=fh();return t.month!==Rt()?{count:0,month:Rt()}:t}function b_(){const e={count:bi().count+1,month:Rt()};return localStorage.setItem(Zt,JSON.stringify(e)),e}function ir(){return!!pe.isLoading}function Nt(){return!!pe.isResolved}function E_(t){if(!t)return null;const e=String(t).toLowerCase().replace(/[^a-z0-9]+/g,"_");return e==="pro"||e==="professional_plan"?"professional":e==="power_developer"||e==="power_plan"?"power":Object.prototype.hasOwnProperty.call(Cs,e)?e:null}function S_(t){return t&&Object.entries(Gd).find(([,e])=>e===t)?.[0]||null}function Di(...t){return t.find(e=>e!=null&&e!=="")}function x_(...t){return t.find(e=>e&&typeof e=="object")||{}}function k_(t){const e=t.data&&typeof t.data=="object"?t.data:t,n=x_(e.subscription,e.stripeSubscription,e.currentSubscription,e.customer?.subscriptions?.data?.[0],e.subscriptions?.data?.[0],e.subscriptions?.[0]),i=e.metadata||n.metadata||e.customer?.metadata||{},s=Di(e.priceId,e.price_id,e.stripePriceId,e.stripe_price_id,n.priceId,n.price_id,n.plan?.id,n.price?.id,n.items?.data?.[0]?.price?.id,n.items?.[0]?.price?.id,n.lines?.data?.[0]?.price?.id),r=Di(e.status,e.subscriptionStatus,e.subscription_status,n.status,"none"),o=E_(Di(e.tier,e.plan,e.planId,e.plan_id,e.subscriptionTier,e.subscription_tier,e.product,e.productName,n.tier,n.plan,i.tier,i.plan)),a=uv.has(String(r).toLowerCase()),l=e.active===!0||e.isSubscribed===!0||e.subscribed===!0||e.hasSubscription===!0,u=o||S_(s)||(a||l?"professional":"free");return kn({tier:u,status:r,periodEnd:Di(e.periodEnd,e.currentPeriodEnd,e.current_period_end,n.current_period_end,n.periodEnd,null),isResolved:!0})}function sr(){return Cs[pe.tier]??Cs.free}async function I_(){if(V.isVerified&&(!Nt()||ir())&&(await gh({force:!0}),rr()),V.isVerified&&!Nt())return ue("Could not verify your subscription. Please refresh or try Manage billing.","error"),!1;const{count:t}=bi(),e=sr();if(t>=e)return Ua(t,e,{openModal:!0}),!1;const n=Math.floor(e*.8);if(t>=n){const i=e-t;ue(`${i} run${i===1?"":"s"} remaining this month.`,"warning")}return!0}function Hr(){const t=document.getElementById("paywall-exhausted");t&&t.classList.add("hidden")}function Ua(t,e,n={}){An(!0);const i=document.getElementById("walkthrough-modal");i&&Xe(i,{restoreFocus:!1});const s=document.getElementById("ready-state");s&&s.classList.add("hidden");const r=document.getElementById("preview-frame-container");r&&(r.style.display="none");const o=document.getElementById("main-stage-container");o&&o.classList.add("visible");const a=document.getElementById("results-view");a&&a.classList.remove("visible"),document.body.classList.remove("results-fullscreen","results-with-sidebar");const l=document.getElementById("pipeline-progress");l&&l.classList.remove("visible");const u=document.getElementById("paywall-exhausted");if(!u){ue(`You've used all ${e} runs for this month. Upgrade to continue.`,"error"),Ls();return}const c=document.getElementById("paywall-exhausted-text");if(c){const h=pe.tier;h==="free"?c.textContent=`You've used all ${e} free generations this month. Upgrade to Pro for 50 generations/month and access to all AI models.`:c.textContent=`You've used all ${e} generations this month on your ${h} plan. Your limit resets next month.`}const d=document.getElementById("paywall-signin-btn");d&&d.classList.toggle("hidden",V.isVerified),u.classList.remove("hidden"),n.openModal&&Ls()}function zo(t){return pe.tier==="free"&&Ji.includes(t)?pi:t}function C_(){const t=document.getElementById("code-options-content"),e=document.getElementById("code-generator-model");if(!t||!e)return;const n=pe.tier,s=!(V.isVerified&&!Nt())&&n==="free";Array.from(e.options).forEach(o=>{const a=Kt(o.value),l=Ji.includes(o.value);o.textContent=l&&s?`${a} (PRO)`:a,o.disabled=!1}),s&&Ji.includes(e.value)&&(e.value=pi),e.disabled=!1,Ic.has(e)||(e.addEventListener("change",()=>{Nt()&&pe.tier==="free"&&Ji.includes(e.value)&&(e.value=pi,Ls()),Wo(e.value),Jd()}),Ic.add(e));let r=document.getElementById("model-selector-free-notice");s?(r||(r=document.createElement("p"),r.id="model-selector-free-notice",r.className="text-xs text-gray-400 mt-1",t.appendChild(r)),r.innerHTML='Free plan — Gemini only. '):r&&r.remove(),Wo(e.value)}function ii(){const t=document.getElementById("usage-counter");if(!t)return;if(V.isVerified&&ir()){t.textContent="Checking plan…",t.className="text-xs text-gray-500",Qi(),Hr();return}if(V.isVerified&&!Nt()){t.textContent="Plan check failed",t.className="text-xs text-red-600 font-medium",Qi(),Hr();return}const{count:e}=bi(),n=sr();t.textContent=`${e} / ${n} runs this month`;const i=n>0?e/n:0;t.className=i>=1?"text-xs text-red-600 font-medium":i>=.8?"text-xs text-yellow-600 font-medium":"text-xs text-gray-500",Qi(),e>=n&&!y.isRunning?Ua(e,n):Hr()}function Qi(){const t=document.getElementById("guest-usage-text");if(!t)return;const e=fh(),n=e.month===Rt()?e.count??0:0,i=Cs.free;t.textContent=`${n} / ${i} generations used`}async function gh(t={}){const e=t.force===!0;if(!V.isVerified||!V.sessionToken){pe=kn({isResolved:!0});return}pe={...pe,isLoading:!0,error:null};const n=localStorage.getItem(As);if(!e&&n)try{const{data:i,email:s,ts:r,version:o}=JSON.parse(n);if(o===Cc&&s===V.email&&Date.now()-r<300*1e3){pe={...i,isLoading:!1,isResolved:i.isResolved!==!1};return}}catch(i){console.warn("Failed to parse subscription cache:",i,"| raw value:",n)}try{const s=await(await fetch(`${Ze}/stripe/get-subscription`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:V.sessionToken,user_id:Ke.userId})})).json();if(s.error){if(["unauthorized","invalid session","expired session"].some(o=>String(s.error).toLowerCase().includes(o))){Ba(),ja();return}pe=kn({isResolved:!1,error:s.error});return}pe=k_(s),localStorage.setItem(As,JSON.stringify({version:Cc,data:pe,email:V.email,ts:Date.now()}))}catch(i){console.error("fetchSubscription failed:",i),pe={...pe,isLoading:!1,isResolved:!1,error:i.message}}}function Ha(){localStorage.removeItem(As)}async function A_(t){if(!V.isVerified||!V.sessionToken){mh(),Da();return}if(!Gd[t]){ue("Invalid plan selected.","error");return}const e=document.getElementById(`checkout-btn-${t}`);e&&(e.disabled=!0,e.textContent="Redirecting…");try{const i=await(await fetch(`${Ze}/stripe/create-checkout-session-intl`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tierId:t,sessionToken:V.sessionToken,currency:Xd()})})).json();if(i.error||!i.url)throw new Error(i.error||"Failed to create checkout session");const{url:s}=i;window.location.href=s}catch(n){console.error("startCheckout failed:",n),e&&(e.disabled=!1,e.textContent="Subscribe"),ue("Could not start checkout. Please try again.","error")}}async function F_(){if(!V.isVerified||!V.sessionToken){Da();return}const t=document.getElementById("manage-billing-btn");t&&(t.disabled=!0,t.textContent="Loading…");try{const n=await(await fetch(`${Ze}/stripe/create-portal-session`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:V.sessionToken})})).json();if(n.error||!n.url)throw new Error(n.error||"Failed to open billing portal");const{url:i}=n;window.location.href=i}catch(e){console.error("openCustomerPortal failed:",e),t&&(t.disabled=!1,t.textContent="Manage billing"),ue("Could not open billing portal. Please try again.","error")}}async function Ms(t,e,n,i={},s=[]){const o=new AbortController,a=setTimeout(()=>o.abort(),12e4);try{const l=await fetch(ov,{method:"POST",headers:{"Content-Type":"application/json",...Ke.token?{Authorization:`Bearer ${Ke.token}`}:{}},signal:o.signal,body:JSON.stringify({user_id:Ke.userId,step:t,model:e,prompt:n,images:s,context:i})}),u=await l.text();let c={};try{c=u?JSON.parse(u):{}}catch{c={}}if(l.status===429){c.serverCount!==void 0&&(localStorage.setItem(Zt,JSON.stringify({count:c.serverCount,month:Rt()})),ii());const p=new Error(c.message||"Monthly usage limit reached. Upgrade to continue.");throw p.isUsageLimit=!0,p}const d=fg(c,t);if(d)throw d;if(console.log(`[BuildShip] ${t} response keys:`,Object.keys(c),"content type:",typeof c.content),!l.ok)throw new Error(`${c.message||c.error||"BuildShip pipeline error"} (HTTP ${l.status})`);if(t==="generator")if(c.usage_status==="success"&&Number.isFinite(c.usage_count)){const p=Rt();(c.usage_month||p)===p&&(localStorage.setItem(Zt,JSON.stringify({count:c.usage_count,month:p})),ii())}else b_(),ii();let h=c.output||c.content;if(!h){const p=u?` (body: ${u.slice(0,120)})`:"";throw new Error(`BuildShip returned no output for step "${t}"${p}`)}return Array.isArray(h)&&(h=h.map(p=>typeof p=="string"?p:p.text||"").join("")),typeof h!="string"&&(h=JSON.stringify(h)),h}catch(l){throw l.name==="AbortError"?new Error(`BuildShip ${t} timed out after ${12e4/1e3}s`):l instanceof TypeError?new Error(`BuildShip unreachable: ${l.message}`):l}finally{clearTimeout(a)}}function P_(){const e=new URLSearchParams(window.location.search).get("checkout");e==="success"?(window.history.replaceState({},"",window.location.pathname+window.location.hash),Ha(),ue("Subscription active! Welcome aboard.","success")):e==="cancel"&&(window.history.replaceState({},"",window.location.pathname+window.location.hash),ue("Checkout cancelled.","info"))}function rr(){const t=V.isVerified&&!!V.email,e=pe.tier,n=t&&ir(),i=!t||Nt(),s=document.getElementById("subscription-tier-badge");if(s){const a={free:"Free",professional:"Professional",power:"Power Developer"},l={free:"bg-gray-100 text-gray-600",professional:"bg-indigo-100 text-indigo-700",power:"bg-purple-100 text-purple-700",unresolved:"bg-red-50 text-red-600"};s.textContent=n?"Checking…":i?a[e]||"Free":"Plan unavailable",s.className=`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${i?l[e]||l.free:l.unresolved}`}const r=document.getElementById("upgrade-prompt");r&&r.classList.toggle("hidden",!t||n||!i||e!=="free");const o=document.getElementById("manage-billing-btn");o&&o.classList.toggle("hidden",!t||n||i&&e==="free"),$_(i?e:null),C_(),Jd(),ii(),xh()}function $_(t){const e=["bg-gray-100","text-gray-500","cursor-default"];Object.entries({professional:{btnId:"checkout-btn-professional",defaultText:"Subscribe"},power:{btnId:"checkout-btn-power",defaultText:"Subscribe"}}).forEach(([s,{btnId:r,defaultText:o}])=>{const a=document.getElementById(r);a&&(s===t?(a.disabled=!0,a.textContent="Current plan",a.classList.add(...e)):(a.disabled=!1,a.textContent=o,a.classList.remove(...e)))});const i=document.getElementById("free-tier-current");i&&i.classList.toggle("hidden",t!=="free")}function qo(){const t=Xd(),e=document.getElementById("pro-price"),n=document.getElementById("power-price"),i=document.getElementById("plans-pro-price"),s=document.getElementById("plans-power-price"),r=document.getElementById("pro-price-note"),o=document.getElementById("power-price-note"),a=document.getElementById("plans-pro-price-note"),l=document.getElementById("plans-power-price-note");e&&(e.textContent=Bi(Oi.professional,t)),n&&(n.textContent=Bi(Oi.power,t)),i&&(i.textContent=Bi(Oi.professional,t)),s&&(s.textContent=Bi(Oi.power,t));const u="billed monthly";r&&(r.textContent=u),o&&(o.textContent=u),a&&(a.textContent=u),l&&(l.textContent=u)}function Ls(){qo();const t=document.getElementById("pricing-modal");t&&Ve(t),yv().then(()=>qo())}function mh(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("pricing-modal");e&&Xe(e)}function ue(t,e="info"){const n={success:"bg-green-600 text-white",error:"bg-red-600 text-white",warning:"bg-amber-500 text-white",info:"bg-gray-800 text-white"},i=document.createElement("div");i.className=`fixed bottom-6 left-1/2 -translate-x-1/2 px-5 py-3 rounded-lg text-sm font-medium shadow-lg z-50 transition-opacity duration-300 ${n[e]||n.info}`,i.textContent=t,document.body.appendChild(i),setTimeout(()=>{i.style.opacity="0",setTimeout(()=>i.remove(),300)},3500)}document.addEventListener("DOMContentLoaded",async()=>{tg(),hljs.configure({tabReplace:" ",classPrefix:"hljs-"}),T_(),await m_(),P_(),await gh(),rr(),qo(),await zv(),Dv();const t=document.getElementById("flutterflow-endpoint-select");if(t){const n=yi();t.value=n}sh(),ph();const e=document.getElementById("pipeline-input");e&&(e.addEventListener("input",()=>{kt===2&&e.value.trim().length>0&&(Ia(),Js())}),e.addEventListener("blur",()=>{const n=document.getElementById("walkthrough-modal");kt===2&&n&&Ve(n)}),e.addEventListener("keydown",n=>{if(n.key==="Tab"){const i=document.getElementById("walkthrough-modal");kt===2&&i&&setTimeout(()=>{Ve(i)},100)}})),window.addEventListener("commitStateChange",n=>{const{state:i}=n.detail;i===K.PREPARING||i===K.VALIDATING||i===K.PUSHING?(be.phaseId||_h(),Lc(i)):(i===K.SUCCESS||i===K.ERROR)&&(Lc(i),setTimeout(Os,1e3))}),sv({onSubmit:Ns}),qa()});function T_(){const t=document.getElementById("preview-frame-container");t&&(t.style.display="")}function R_(){const t=document.getElementById("welcome-video-player");t&&(t.addEventListener("click",Qt),document.addEventListener("keydown",Qt))}function Qt(){const t=document.getElementById("preview-frame-container"),e=document.getElementById("main-stage-container"),n=document.getElementById("ready-state");t&&(t.style.display="none"),e&&e.classList.add("visible"),n&&n.classList.remove("hidden");const i=document.getElementById("welcome-video-player");i&&i.removeEventListener("click",Qt),document.removeEventListener("keydown",Qt),sh()}let si=null;async function N_(){const t=document.getElementById("confirm-project-select");if(!t)return;const e=++Tc,n=()=>e===Tc,i=await Ee("flutterflow"),s=await Ee("flutterflow_project_id");if(n()){if(!i){t.innerHTML='',t.disabled=!0;return}t.disabled=!1,t.innerHTML='';try{const o=await new wi(i,"").listProjects();if(!n())return;if(!o||o.length===0){t.innerHTML='';return}t.innerHTML='',o.forEach(a=>{const l=document.createElement("option");l.value=a.id||a.projectId||"",l.textContent=a.name||a.projectName||`Project ${a.id}`,t.appendChild(l)}),s&&(t.value=s)}catch(r){if(!n())return;console.error("Failed to load projects for deploy:",r),t.innerHTML=''}}}function M_(){return document.getElementById("confirm-project-select")?.value?.trim()||null}function Wa(t,e,n,i=null){si={codeInfo:t,checks:e,deps:n,bundlePlan:i},document.getElementById("confirm-file-name").textContent=t.fileName,document.getElementById("confirm-artifact-type").textContent=t.artifactType,document.getElementById("confirm-file-size").textContent=`${(t.content.length/1024).toFixed(1)} KB`,document.getElementById("confirm-line-count").textContent=i?`${i.fileEntries.length} files`:t.content.split(` -`).length,N_();const s=document.getElementById("confirm-deps-list"),r=document.getElementById("confirm-deps-section");n&&Object.keys(n).length>0?(s.innerHTML=Object.entries(n).map(([u,c])=>{const d=c?`at least ${xt(c)}`:"version resolved from your project";return`
  • • ${xt(u)}: ${d}
  • `}).join(""),r.classList.remove("hidden")):r.classList.add("hidden");const o=document.getElementById("confirm-warnings-list"),a=document.getElementById("confirm-warnings-section");e.warnings&&e.warnings.length>0?(o.innerHTML=e.warnings.map(u=>`
  • • ${xt(u)}
  • `).join(""),a.classList.remove("hidden")):a.classList.add("hidden"),document.getElementById("confirm-code-preview").textContent=t.content,document.getElementById("code-preview-content").classList.add("hidden"),document.getElementById("code-preview-chevron").style.transform="rotate(0deg)";const l=document.getElementById("commit-confirm-modal");l&&Ve(l)}function vh(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("commit-confirm-modal");e&&Xe(e),si=null}function L_(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("commit-success-modal");e&&Xe(e);const n=["success-message","success-project-id","success-file-name","success-artifact-type","success-time","success-size"];for(const r of n){const o=document.getElementById(r);o&&(o.textContent="")}const i=document.getElementById("success-warnings-section");i&&i.classList.add("hidden");const s=document.getElementById("success-warnings-list");s&&(s.innerHTML="")}function Vo(t){const e=(m,v)=>{const b=document.getElementById(m);b&&(b.textContent=v||"")},n=t.metadata?.fileName||"",i=t.metadata?.projectId||"",s=t.metadata?.artifactType||"",r=t.elapsedTime?`${(t.elapsedTime/1e3).toFixed(1)}s`:"",o=t.metadata?.codeSize?`${(t.metadata.codeSize/1024).toFixed(1)} KB`:"";e("success-message",t.message||"Code committed successfully!"),e("success-project-id",i),e("success-file-name",n),e("success-artifact-type",s),e("success-time",r),e("success-size",o);const a=t.addedDependencies||[],l=document.getElementById("success-deps-row");l&&l.classList.toggle("hidden",a.length===0),e("success-deps",a.join(", "));const u=document.getElementById("success-open-ff-link");u&&i&&(u.href=`https://app.flutterflow.io/project/${i}`);const c=document.getElementById("success-warnings-section"),d=document.getElementById("success-warnings-list"),h=t.unverified||[],p=t.approximate||[],f=t.warnings||[];(f.length>0||h.length>0||p.length>0)&&c&&d&&(d.innerHTML=[...h.map(m=>`
  • Not verified before deploying: ${j(String(m))}
  • `),...p.map(m=>`
  • Verified approximately: ${j(String(m))}
  • `),...f.map(([m,v])=>`
  • ${j(m)}: ${j(String(v))}
  • `)].join(""),c.classList.remove("hidden"));const g=document.getElementById("commit-success-modal");g&&Ve(g)}function Go(t){Os(),u_(t)}function O_(){const t=document.getElementById("code-preview-content"),e=document.getElementById("code-preview-chevron");t.classList.contains("hidden")?(t.classList.remove("hidden"),e.style.transform="rotate(90deg)"):(t.classList.add("hidden"),e.style.transform="rotate(0deg)")}const Mc={prepare:{message:"Preparing your code...",start:4,end:14},validate:{message:"Checking FlutterFlow credentials...",start:14,end:22},project:{message:"Reading your FlutterFlow project...",start:22,end:40},provision:{message:"Creating custom classes in FlutterFlow...",start:40,end:82},package:{message:"Packaging files for upload...",start:82,end:88},push:{message:"Pushing to FlutterFlow...",start:88,end:97},done:{message:"Complete!",start:100,end:100}},B_=[{after:0,text:"Starting a FlutterFlow build runner..."},{after:12,text:"Preparing the FlutterFlow AI workspace..."},{after:35,text:"Uploading your custom classes..."},{after:60,text:"FlutterFlow is applying the changes..."},{after:100,text:"Still working — this can take a couple of minutes..."}],be={sequence:[],phaseId:null,phaseStartedAt:null,timer:null,substatus:null,liveSubstatus:!1,start({withProvisioning:t=!1}={}){this.sequence=["prepare","validate","project"],t&&this.sequence.push("provision"),this.sequence.push("package","push","done");const e=document.getElementById("commit-progress-overlay");e&&(oc(e,!0,"Deploying to FlutterFlow"),Ve(e)),this.set("prepare")},set(t,e=null){if(!(!Mc[t]||t===this.phaseId)){if(!this.sequence.includes(t)){const n=this.sequence.indexOf("package");this.sequence.splice(n===-1?this.sequence.length:n,0,t)}this.phaseId=t,this.phaseStartedAt=Date.now(),this.substatus=e,this.liveSubstatus=!1,this.render(),this.timer&&clearInterval(this.timer),t!=="done"&&(this.timer=setInterval(()=>this.render(),500))}},setSubstatus(t){t&&(this.liveSubstatus=!0,this.substatus=t,this.render())},render(){const t=Mc[this.phaseId];if(!t)return;const e=(Date.now()-this.phaseStartedAt)/1e3,n=t.start+(t.end-t.start)*(1-Math.exp(-e/25));if(this.phaseId==="provision"&&!this.liveSubstatus){const o=B_.filter(a=>e>=a.after).pop();o&&(this.substatus=o.text)}const i=this.sequence.indexOf(this.phaseId),r=[`Step ${i===-1?1:i+1} of ${this.sequence.length}`];e>=5&&r.push(D_(e)),yh(this.phaseId==="done"?100:n,t.message,r.join(" · "),this.substatus)},stop(){this.timer&&clearInterval(this.timer),this.timer=null,this.phaseId=null;const t=document.getElementById("commit-progress-overlay");t&&(oc(t,!1),Xe(t,{force:!0,restoreFocus:!1}))}};function D_(t){const e=Math.floor(t);return e<60?`${e}s elapsed`:`${Math.floor(e/60)}m ${String(e%60).padStart(2,"0")}s elapsed`}function _h(t){be.start(t)}function Os(){be.stop()}function yh(t,e,n,i=null){const s=document.getElementById("commit-progress-bar"),r=document.getElementById("progress-message"),o=document.getElementById("progress-detail"),a=document.getElementById("progress-substatus");s&&(s.style.width=`${Math.round(t*10)/10}%`),r&&(r.textContent=e),o&&(o.textContent=n),a&&(a.textContent=i||"",a.classList.toggle("hidden",!i))}function Lc(t){const e={[K.PREPARING]:"prepare",[K.VALIDATING]:"validate",[K.PUSHING]:"project",[K.SUCCESS]:"done"};if(t===K.ERROR){be.timer&&clearInterval(be.timer),be.timer=null,yh(100,"Failed","Error occurred");return}const n=e[t];n&&be.set(n)}function j_(t){return t.bundlePlan?t.bundlePlan.fileEntries.some(e=>e.type===W.CODE_FILE):t.codeInfo?.codeType===W.CODE_FILE}async function U_(){if(!si){console.error("No pending commit data");return}const t=si;if(si=null,ni=M_(),vh(),_h({withProvisioning:j_(t)}),t.bundlePlan){const o=await Qv(t.bundlePlan,{pipelineResult:{step1Result:y.step1Result,selectedModel:document.getElementById("code-generator-model")?.value}});ni=null,Os(),o.success?Vo(o):Go(o);return}const{codeInfo:e}=t,{artifactType:n,artifactName:i,fileName:s}=oh(),r=await Xv(e.content,{artifactType:n,artifactName:i,fileName:s,pipelineResult:{step1Result:y.step1Result,selectedModel:document.getElementById("code-generator-model")?.value}});ni=null,Os(),r.success?Vo(r):Go(r)}window.runThinkingPipeline=Ns;window.toggleStep=n_;window.toggleSection=t_;window.selectWorkflowStep=ze;window.copyCode=i_;window.retryWithDifferentModel=a_;window.openApiKeysModal=ka;window.closeApiKeysModal=nh;window.closeWalkthroughModal=Rv;window.openWalkthroughModal=Tv;window.advanceWalkthrough=Ia;window.commitToFlutterFlow=Zv;function H_(){const t=document.getElementById("pipeline-input");t&&t.focus()}function W_(){const t=document.getElementById("advanced-settings");t&&(t.open=!0);const e=document.getElementById("code-generator-model");e&&(e.scrollIntoView({behavior:"smooth",block:"center"}),e.focus(),e.click())}window.focusPromptInput=H_;window.openModelSelector=W_;window.handlePromptImageSelect=vv;window.removePromptImage=_v;window.saveApiKeys=Lv;window.clearAllApiKeys=Ov;window.toggleKeyVisibility=Uv;window.handleWelcomeVideoEnd=R_;window.dismissWelcomeVideo=Qt;window.initiateCommitToFlutterFlow=l_;window.updateFlutterFlowCredentialStatus=h_;window.openCommitConfirmModal=Wa;window.closeCommitConfirmModal=vh;window.closeCommitSuccessModal=L_;window.showCommitSuccessModal=Vo;window.showCommitFailureModal=Go;window.toggleCodePreview=O_;window.confirmCommitToFlutterFlow=U_;window.runRefinement=s_;window.regenerateFromPastedErrors=o_;window.clearErrorInput=r_;window.setFlutterFlowEndpoint=$v;window.getFlutterFlowEndpoint=yi;window.commitProgress=be;window.openSignInModal=Da;window.closeSignInModal=v_;window.handleMagicLinkRequest=__;window.handleSignOut=y_;window.startCheckout=A_;window.openCustomerPortal=F_;window.openPricingModal=Ls;window.closePricingModal=mh;let mn=null,wh=null;const Oc=120;function or(){An(!0);const t=document.getElementById("pipeline-progress"),e=document.getElementById("results-view"),n=document.getElementById("ready-state");n&&n.classList.add("hidden"),e&&e.classList.remove("visible"),document.body.classList.remove("results-fullscreen","results-with-sidebar"),t&&t.classList.add("visible"),wh=Date.now();for(let i=1;i<=3;i++){const s=document.getElementById(`pdot-${i}`);s&&(s.className="progress-dot")}at(1),z_()}function at(t){const e={1:"Analyzing your prompt...",2:"Generating Dart code...",3:"Running code audit..."},n={1:"Step 1 of 3 — Prompt Architect",2:"Step 2 of 3 — Code Generator",3:"Step 3 of 3 — Code Review"},i=document.getElementById("progress-title-text"),s=document.getElementById("progress-substep-text");i&&(i.textContent=e[t]||e[1]),s&&(s.textContent=n[t]||n[1]);for(let r=1;r<=3;r++){const o=document.getElementById(`pdot-${r}`);o&&(r{const t=(Date.now()-wh)/1e3,e=document.getElementById("progress-elapsed"),n=document.getElementById("pipeline-progress-fill");e&&(e.textContent=`${Math.floor(t)}s`);const i=t/Oc*100,s=Math.min(95,i*(1-Math.exp(-t/(Oc*.6)))*1.2);n&&(n.style.width=`${s}%`)},250)}function Mt(){mn&&(clearInterval(mn),mn=null);const t=document.getElementById("pipeline-progress-fill");t&&(t.style.width="100%");for(let e=1;e<=3;e++){const n=document.getElementById(`pdot-${e}`);n&&(n.className="progress-dot completed")}setTimeout(()=>{const e=document.getElementById("pipeline-progress");e&&e.classList.remove("visible"),t&&(t.style.width="0%")},400)}function Cn(t,e=""){const n={pass:'',warning:'',fail:'',info:''};return``}function bh(t){return{pass:"Passed review",warning:"Needs attention",fail:"Blocking issues"}[t]||"Needs attention"}function q_(){return om({bundle:y.artifactBundle,reviewResult:y.step3Result})}function V_(t){return` +`).length,N_();const s=document.getElementById("confirm-deps-list"),r=document.getElementById("confirm-deps-section");n&&Object.keys(n).length>0?(s.innerHTML=Object.entries(n).map(([u,c])=>{const d=c?`at least ${xt(c)}`:"version resolved from your project";return`
  • • ${xt(u)}: ${d}
  • `}).join(""),r.classList.remove("hidden")):r.classList.add("hidden");const o=document.getElementById("confirm-warnings-list"),a=document.getElementById("confirm-warnings-section");e.warnings&&e.warnings.length>0?(o.innerHTML=e.warnings.map(u=>`
  • • ${xt(u)}
  • `).join(""),a.classList.remove("hidden")):a.classList.add("hidden"),document.getElementById("confirm-code-preview").textContent=t.content,document.getElementById("code-preview-content").classList.add("hidden"),document.getElementById("code-preview-chevron").style.transform="rotate(0deg)";const l=document.getElementById("commit-confirm-modal");l&&Ve(l)}function vh(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("commit-confirm-modal");e&&Xe(e),si=null}function L_(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("commit-success-modal");e&&Xe(e);const n=["success-message","success-project-id","success-file-name","success-artifact-type","success-time","success-size"];for(const r of n){const o=document.getElementById(r);o&&(o.textContent="")}const i=document.getElementById("success-warnings-section");i&&i.classList.add("hidden");const s=document.getElementById("success-warnings-list");s&&(s.innerHTML="")}function Vo(t){const e=(g,m)=>{const v=document.getElementById(g);v&&(v.textContent=m||"")},n=t.metadata?.fileName||"",i=t.metadata?.projectId||"",s=t.metadata?.artifactType||"",r=t.elapsedTime?`${(t.elapsedTime/1e3).toFixed(1)}s`:"",o=t.metadata?.codeSize?`${(t.metadata.codeSize/1024).toFixed(1)} KB`:"";e("success-message",t.message||"Code committed successfully!"),e("success-project-id",i),e("success-file-name",n),e("success-artifact-type",s),e("success-time",r),e("success-size",o);const a=t.addedDependencies||[],l=document.getElementById("success-deps-row");l&&l.classList.toggle("hidden",a.length===0),e("success-deps",a.join(", "));const u=document.getElementById("success-open-ff-link");u&&i&&(u.href=`https://app.flutterflow.io/project/${i}`);const c=document.getElementById("success-warnings-section"),d=document.getElementById("success-warnings-list"),h=t.unverified||[],p=t.warnings||[];(p.length>0||h.length>0)&&c&&d&&(d.innerHTML=[...h.map(g=>`
  • Not verified before deploying: ${j(String(g))}
  • `),...p.map(([g,m])=>`
  • ${j(g)}: ${j(String(m))}
  • `)].join(""),c.classList.remove("hidden"));const f=document.getElementById("commit-success-modal");f&&Ve(f)}function Go(t){Os(),u_(t)}function O_(){const t=document.getElementById("code-preview-content"),e=document.getElementById("code-preview-chevron");t.classList.contains("hidden")?(t.classList.remove("hidden"),e.style.transform="rotate(90deg)"):(t.classList.add("hidden"),e.style.transform="rotate(0deg)")}const Mc={prepare:{message:"Preparing your code...",start:4,end:14},validate:{message:"Checking FlutterFlow credentials...",start:14,end:22},project:{message:"Reading your FlutterFlow project...",start:22,end:40},provision:{message:"Creating custom classes in FlutterFlow...",start:40,end:82},package:{message:"Packaging files for upload...",start:82,end:88},push:{message:"Pushing to FlutterFlow...",start:88,end:97},done:{message:"Complete!",start:100,end:100}},B_=[{after:0,text:"Starting a FlutterFlow build runner..."},{after:12,text:"Preparing the FlutterFlow AI workspace..."},{after:35,text:"Uploading your custom classes..."},{after:60,text:"FlutterFlow is applying the changes..."},{after:100,text:"Still working — this can take a couple of minutes..."}],be={sequence:[],phaseId:null,phaseStartedAt:null,timer:null,substatus:null,liveSubstatus:!1,start({withProvisioning:t=!1}={}){this.sequence=["prepare","validate","project"],t&&this.sequence.push("provision"),this.sequence.push("package","push","done");const e=document.getElementById("commit-progress-overlay");e&&(oc(e,!0,"Deploying to FlutterFlow"),Ve(e)),this.set("prepare")},set(t,e=null){if(!(!Mc[t]||t===this.phaseId)){if(!this.sequence.includes(t)){const n=this.sequence.indexOf("package");this.sequence.splice(n===-1?this.sequence.length:n,0,t)}this.phaseId=t,this.phaseStartedAt=Date.now(),this.substatus=e,this.liveSubstatus=!1,this.render(),this.timer&&clearInterval(this.timer),t!=="done"&&(this.timer=setInterval(()=>this.render(),500))}},setSubstatus(t){t&&(this.liveSubstatus=!0,this.substatus=t,this.render())},render(){const t=Mc[this.phaseId];if(!t)return;const e=(Date.now()-this.phaseStartedAt)/1e3,n=t.start+(t.end-t.start)*(1-Math.exp(-e/25));if(this.phaseId==="provision"&&!this.liveSubstatus){const o=B_.filter(a=>e>=a.after).pop();o&&(this.substatus=o.text)}const i=this.sequence.indexOf(this.phaseId),r=[`Step ${i===-1?1:i+1} of ${this.sequence.length}`];e>=5&&r.push(D_(e)),yh(this.phaseId==="done"?100:n,t.message,r.join(" · "),this.substatus)},stop(){this.timer&&clearInterval(this.timer),this.timer=null,this.phaseId=null;const t=document.getElementById("commit-progress-overlay");t&&(oc(t,!1),Xe(t,{force:!0,restoreFocus:!1}))}};function D_(t){const e=Math.floor(t);return e<60?`${e}s elapsed`:`${Math.floor(e/60)}m ${String(e%60).padStart(2,"0")}s elapsed`}function _h(t){be.start(t)}function Os(){be.stop()}function yh(t,e,n,i=null){const s=document.getElementById("commit-progress-bar"),r=document.getElementById("progress-message"),o=document.getElementById("progress-detail"),a=document.getElementById("progress-substatus");s&&(s.style.width=`${Math.round(t*10)/10}%`),r&&(r.textContent=e),o&&(o.textContent=n),a&&(a.textContent=i||"",a.classList.toggle("hidden",!i))}function Lc(t){const e={[K.PREPARING]:"prepare",[K.VALIDATING]:"validate",[K.PUSHING]:"project",[K.SUCCESS]:"done"};if(t===K.ERROR){be.timer&&clearInterval(be.timer),be.timer=null,yh(100,"Failed","Error occurred");return}const n=e[t];n&&be.set(n)}function j_(t){return t.bundlePlan?t.bundlePlan.fileEntries.some(e=>e.type===W.CODE_FILE):t.codeInfo?.codeType===W.CODE_FILE}async function U_(){if(!si){console.error("No pending commit data");return}const t=si;if(si=null,ni=M_(),vh(),_h({withProvisioning:j_(t)}),t.bundlePlan){const o=await Qv(t.bundlePlan,{pipelineResult:{step1Result:y.step1Result,selectedModel:document.getElementById("code-generator-model")?.value}});ni=null,Os(),o.success?Vo(o):Go(o);return}const{codeInfo:e}=t,{artifactType:n,artifactName:i,fileName:s}=oh(),r=await Xv(e.content,{artifactType:n,artifactName:i,fileName:s,pipelineResult:{step1Result:y.step1Result,selectedModel:document.getElementById("code-generator-model")?.value}});ni=null,Os(),r.success?Vo(r):Go(r)}window.runThinkingPipeline=Ns;window.toggleStep=n_;window.toggleSection=t_;window.selectWorkflowStep=ze;window.copyCode=i_;window.retryWithDifferentModel=a_;window.openApiKeysModal=ka;window.closeApiKeysModal=nh;window.closeWalkthroughModal=Rv;window.openWalkthroughModal=Tv;window.advanceWalkthrough=Ia;window.commitToFlutterFlow=Zv;function H_(){const t=document.getElementById("pipeline-input");t&&t.focus()}function W_(){const t=document.getElementById("advanced-settings");t&&(t.open=!0);const e=document.getElementById("code-generator-model");e&&(e.scrollIntoView({behavior:"smooth",block:"center"}),e.focus(),e.click())}window.focusPromptInput=H_;window.openModelSelector=W_;window.handlePromptImageSelect=vv;window.removePromptImage=_v;window.saveApiKeys=Lv;window.clearAllApiKeys=Ov;window.toggleKeyVisibility=Uv;window.handleWelcomeVideoEnd=R_;window.dismissWelcomeVideo=Qt;window.initiateCommitToFlutterFlow=l_;window.updateFlutterFlowCredentialStatus=h_;window.openCommitConfirmModal=Wa;window.closeCommitConfirmModal=vh;window.closeCommitSuccessModal=L_;window.showCommitSuccessModal=Vo;window.showCommitFailureModal=Go;window.toggleCodePreview=O_;window.confirmCommitToFlutterFlow=U_;window.runRefinement=s_;window.regenerateFromPastedErrors=o_;window.clearErrorInput=r_;window.setFlutterFlowEndpoint=$v;window.getFlutterFlowEndpoint=yi;window.commitProgress=be;window.openSignInModal=Da;window.closeSignInModal=v_;window.handleMagicLinkRequest=__;window.handleSignOut=y_;window.startCheckout=A_;window.openCustomerPortal=F_;window.openPricingModal=Ls;window.closePricingModal=mh;let mn=null,wh=null;const Oc=120;function or(){An(!0);const t=document.getElementById("pipeline-progress"),e=document.getElementById("results-view"),n=document.getElementById("ready-state");n&&n.classList.add("hidden"),e&&e.classList.remove("visible"),document.body.classList.remove("results-fullscreen","results-with-sidebar"),t&&t.classList.add("visible"),wh=Date.now();for(let i=1;i<=3;i++){const s=document.getElementById(`pdot-${i}`);s&&(s.className="progress-dot")}at(1),z_()}function at(t){const e={1:"Analyzing your prompt...",2:"Generating Dart code...",3:"Running code audit..."},n={1:"Step 1 of 3 — Prompt Architect",2:"Step 2 of 3 — Code Generator",3:"Step 3 of 3 — Code Review"},i=document.getElementById("progress-title-text"),s=document.getElementById("progress-substep-text");i&&(i.textContent=e[t]||e[1]),s&&(s.textContent=n[t]||n[1]);for(let r=1;r<=3;r++){const o=document.getElementById(`pdot-${r}`);o&&(r{const t=(Date.now()-wh)/1e3,e=document.getElementById("progress-elapsed"),n=document.getElementById("pipeline-progress-fill");e&&(e.textContent=`${Math.floor(t)}s`);const i=t/Oc*100,s=Math.min(95,i*(1-Math.exp(-t/(Oc*.6)))*1.2);n&&(n.style.width=`${s}%`)},250)}function Mt(){mn&&(clearInterval(mn),mn=null);const t=document.getElementById("pipeline-progress-fill");t&&(t.style.width="100%");for(let e=1;e<=3;e++){const n=document.getElementById(`pdot-${e}`);n&&(n.className="progress-dot completed")}setTimeout(()=>{const e=document.getElementById("pipeline-progress");e&&e.classList.remove("visible"),t&&(t.style.width="0%")},400)}function Cn(t,e=""){const n={pass:'',warning:'',fail:'',info:''};return``}function bh(t){return{pass:"Passed review",warning:"Needs attention",fail:"Blocking issues"}[t]||"Needs attention"}function q_(){return om({bundle:y.artifactBundle,reviewResult:y.step3Result})}function V_(t){return`
    ${Cn(t.severity)}
    diff --git a/dist/index.html b/dist/index.html index a01a1e4..6edf0d0 100644 --- a/dist/index.html +++ b/dist/index.html @@ -2862,7 +2862,7 @@ .send.is-busy .send-spin { animation: none; opacity: 0.6; } } - + diff --git a/src/customCodeVerification.js b/src/customCodeVerification.js index 6813705..cf6afae 100644 --- a/src/customCodeVerification.js +++ b/src/customCodeVerification.js @@ -170,30 +170,17 @@ function skipReason(className, unresolvableImports, missingPackages) { * * A dependency that cannot be reproduced outside the project - a `git:`, * `path:`, or custom-`hosted:` source - cannot be expressed in the scratch - * manifest, which carries names and version constraints only. Such a - * dependency is handled by scope, not by breadth: - * - * - A class that imports it directly cannot compile without it at all, so it - * is skipped and `skipped` names the import as this class's own problem. - * - Every other class is still verified, against a scratch graph that omits - * the unrepresentable package. A representable import may reach that - * package transitively - knowable only by resolving the graph, which - * cannot happen here - so for those classes the check is approximate. - * `approximate` carries one notice per unrepresentable package stating - * exactly that, so the limitation is disclosed rather than silently - * trusted, and the result is never mistaken for full graph fidelity. A - * class importing only `dart:` never touches package resolution, so the - * approximation does not reach it. - * - * Skipping every class with a `package:` import instead was rejected: one - * unrelated git or path dependency would disable the compile check for - * nearly the whole deployment, and invalid custom code would land unopposed. - * Verifying with a disclosed approximation keeps the check on the code that - * ships while saying plainly what it could not reproduce. + * manifest, which carries names and version constraints only. When one is + * declared, the scratch graph cannot match the project's, so every class + * that imports anything from `package:` is skipped: even a representable + * import may reach the unrepresentable package transitively, and a check + * run against a different graph reports a result that does not describe + * the code that ships. A class importing only `dart:` never touches pub + * resolution, so it is still compiled. * * @param {Array<{className: string, content: string}>} classes - Classes to deploy * @param {string} projectPubspecYaml - The project's merged pubspec.yaml - * @returns {{manifest: Object, sources: Array<{fileName: string, content: string}>, skipped: Array<{className: string, reason: string}>, approximate: string[]}} + * @returns {{manifest: Object, sources: Array<{fileName: string, content: string}>, skipped: Array<{className: string, reason: string}>}} */ export function planCustomCodeVerification(classes, projectPubspecYaml) { const { @@ -209,31 +196,25 @@ export function planCustomCodeVerification(classes, projectPubspecYaml) { const sources = []; const skipped = []; - // The scratch manifest omits every unrepresentable package, so any class - // that does not import one directly is checked against a reduced graph. - // Disclosing that per package - rather than skipping those classes or - // silently trusting the scratch - keeps the check running and the human - // told what it could not reproduce. - const approximate = unrepresentable.map( - (name) => - `Your project declares ${name} from a source that cannot be reproduced outside it, so the pre-deploy compile check runs against a scratch package graph that omits ${name}. Classes that do not import ${name} directly are still checked, but against that reduced graph, so their transitive package resolution may differ from your project's and the check is approximate for them.`, - ); - for (const entry of classes) { const { className, content } = entry; const importedPackages = extractPackageImports(content); - // A direct import of a dependency the manifest cannot express is this - // class's own problem, and the reason names it as such. - const unresolvablePackages = importedPackages.filter((name) => - unrepresentable.includes(name), - ); - - if (unresolvablePackages.length > 0) { + // An unrepresentable dependency means the scratch graph cannot match + // the project's, so no class that imports from `package:` can be + // checked against the graph it will actually compile with. A direct + // import keeps its own reason, naming this class's own import. + if (unrepresentable.length > 0 && importedPackages.length > 0) { + const direct = importedPackages.filter((name) => + unrepresentable.includes(name), + ); skipped.push({ className, - reason: `${className} was not compiled before deploying: it imports ${unresolvablePackages.join(", ")}, which your project declares from a source that cannot be reproduced outside it, so package resolution could not be matched exactly.`, + reason: + direct.length > 0 + ? `${className} was not compiled before deploying: it imports ${direct.join(", ")}, which your project declares from a source that cannot be reproduced outside it, so package resolution could not be matched exactly.` + : `${className} was not compiled before deploying: your project declares ${unrepresentable.join(", ")} from a source that cannot be reproduced outside it, so the package graph ${className} would compile against could not be matched exactly.`, }); continue; } @@ -257,5 +238,5 @@ export function planCustomCodeVerification(classes, projectPubspecYaml) { }); } - return { manifest, sources, skipped, approximate }; + return { manifest, sources, skipped }; } diff --git a/src/customCodeVerification.test.js b/src/customCodeVerification.test.js index baaff8c..09734da 100644 --- a/src/customCodeVerification.test.js +++ b/src/customCodeVerification.test.js @@ -145,28 +145,22 @@ dependencies: assert.equal("hosted_thing" in manifest.dependencies, false); }); -test("a representable import verifies beside an unrelated git dependency, and the plan discloses the approximation", () => { +test("a package import is skipped beside an unrelated git dependency, and the reason names the dependency", () => { const plan = planCustomCodeVerification( [{ className: "BackgroundDownloaderService", content: SELF_CONTAINED }], PROJECT_PUBSPEC, ); // The project declares `private_thing` from git, which the scratch manifest - // cannot express - but this class never imports it, so it is still compiled - // and checked. The check is approximate (whether what it does import - // reaches `private_thing` transitively is knowable only by resolving the - // graph), so `approximate` says so per package instead of skipping the - // class, which would have disabled the check for nearly the whole deploy. - assert.deepEqual(plan.sources, [ - { - fileName: "background_downloader_service.dart", - content: SELF_CONTAINED, - }, - ]); - assert.deepEqual(plan.skipped, []); - assert.equal(plan.approximate.length, 1); - assert.match(plan.approximate[0], /private_thing/); - assert.match(plan.approximate[0], /approximate/); + // cannot express, so the graph cannot be matched exactly. This class never + // imports `private_thing` directly, but it imports `package:` at all, and + // what it imports may reach `private_thing` transitively - so it is skipped + // and the reason names the dependency that broke the match. + assert.deepEqual(plan.sources, []); + assert.equal(plan.skipped.length, 1); + assert.equal(plan.skipped[0].className, "BackgroundDownloaderService"); + assert.match(plan.skipped[0].reason, /private_thing/); + assert.match(plan.skipped[0].reason, /could not be matched exactly/); }); test("a class that imports the unreproducible dependency is skipped, and named as the reason", () => { @@ -185,20 +179,16 @@ class UsesPrivateThing {} // The direct import keeps its own reason: it names this class's own // import, so it says what to do about this class. - assert.deepEqual( - plan.sources.map((source) => source.fileName), - ["background_downloader_service.dart"], - ); - assert.equal(plan.skipped.length, 1); + assert.deepEqual(plan.sources, []); + assert.equal(plan.skipped.length, 2); assert.equal(plan.skipped[0].className, "UsesPrivateThing"); assert.match(plan.skipped[0].reason, /it imports private_thing/); - // The sibling never imports the git package, so it is checked rather than - // skipped - approximately, and the plan-level notice discloses that. - assert.equal(plan.approximate.length, 1); - assert.match(plan.approximate[0], /private_thing/); + // The sibling never imports the git package, but it imports `package:` at + // all, so it is skipped too - its reason names the unreproducible package. + assert.match(plan.skipped[1].reason, /private_thing/); }); -test("a representable import verifies when an override elsewhere is unrepresentable, and the notice names it", () => { +test("a package import is skipped when an override elsewhere is unrepresentable, and the reason names it", () => { const pubspec = `name: my_app environment: @@ -223,19 +213,12 @@ dependency_overrides: // The class imports `background_downloader`, which the manifest can // express, and never touches `intl` - but the git override of `intl` // cannot be carried, and whether `background_downloader` depends on - // `intl` transitively is knowable only by resolving the graph. The class - // is therefore checked rather than skipped, and the plan-level notice - // discloses the approximation the check ran with. - assert.deepEqual(plan.sources, [ - { - fileName: "background_downloader_service.dart", - content: SELF_CONTAINED, - }, - ]); - assert.deepEqual(plan.skipped, []); - assert.equal(plan.approximate.length, 1); - assert.match(plan.approximate[0], /intl/); - assert.match(plan.approximate[0], /approximate/); + // `intl` transitively is knowable only by resolving the graph. The graph + // cannot be matched exactly, so the class is skipped and the reason + // names `intl`. + assert.deepEqual(plan.sources, []); + assert.equal(plan.skipped.length, 1); + assert.match(plan.skipped[0].reason, /intl/); }); test("a class compiled from dart: alone still verifies beside a git dependency", () => { @@ -251,17 +234,13 @@ test("a class compiled from dart: alone still verifies beside a git dependency", // `dart:` libraries come from the SDK rather than pub resolution, so a // class importing nothing from `package:` compiles against exactly what - // the project will, whatever the project's sources are. `approximate` is - // plan-level, so it still carries the notice for the package-importing - // classes this deploy could contain - but nothing about this class's own - // check is approximate. + // the project will, whatever the project's sources are - it is still + // checked even while package-importing siblings are skipped. assert.deepEqual( plan.sources.map((source) => source.fileName), ["pure_dart_service.dart"], ); assert.deepEqual(plan.skipped, []); - assert.equal(plan.approximate.length, 1); - assert.match(plan.approximate[0], /private_thing/); }); test("a project whose sources are all representable verifies with nothing to disclose", () => { @@ -271,11 +250,10 @@ test("a project whose sources are all representable verifies with nothing to dis ); // Every dependency the project declares can be expressed in the scratch - // manifest, so the check runs against the project's own graph and there is - // no approximation to warn about. + // manifest, so the check runs against the project's own graph and nothing + // is skipped. assert.equal(plan.sources.length, 1); assert.deepEqual(plan.skipped, []); - assert.deepEqual(plan.approximate, []); }); test("an SDK package no list has heard of is reproduced from its pubspec source", () => { From 5f8bf04aa7f4f9626e03cabcca52c8989357526f Mon Sep 17 00:00:00 2001 From: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> Date: Wed, 23 Sep 2026 10:03:56 +0000 Subject: [PATCH 03/11] fix: restore attachment thumbnails/model-capability wrapper in the redesigned composer and cancel pending suggestion on Escape Co-Authored-By: bot_apk --- dist/assets/index-C_S2EkEm.js | 320 ---------------------------------- dist/index.html | 32 +++- index.html | 30 +++- src/composerAdapter.js | 2 + 4 files changed, 51 insertions(+), 333 deletions(-) delete mode 100644 dist/assets/index-C_S2EkEm.js diff --git a/dist/assets/index-C_S2EkEm.js b/dist/assets/index-C_S2EkEm.js deleted file mode 100644 index 060ffd3..0000000 --- a/dist/assets/index-C_S2EkEm.js +++ /dev/null @@ -1,320 +0,0 @@ -(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const s of document.querySelectorAll('link[rel="modulepreload"]'))i(s);new MutationObserver(s=>{for(const r of s)if(r.type==="childList")for(const o of r.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&i(o)}).observe(document,{childList:!0,subtree:!0});function n(s){const r={};return s.integrity&&(r.integrity=s.integrity),s.referrerPolicy&&(r.referrerPolicy=s.referrerPolicy),s.crossOrigin==="use-credentials"?r.credentials="include":s.crossOrigin==="anonymous"?r.credentials="omit":r.credentials="same-origin",r}function i(s){if(s.ep)return;s.ep=!0;const r=n(s);fetch(s.href,r)}})();var _=typeof window<"u"?window:void 0,we=typeof globalThis<"u"?globalThis:_,ke=we?.navigator,C=we?.document,se=we?.location,Ko=we?.fetch,Wr=we!=null&&we.XMLHttpRequest&&"withCredentials"in new we.XMLHttpRequest?we.XMLHttpRequest:void 0,Ka=we?.AbortController,Ih=we?.CompressionStream,Fe=ke?.userAgent;function Dc(){return!(!_||_.navigator.onLine===!1)}var Tn=typeof globalThis<"u"?globalThis:_;Tn&&typeof self>"u"&&(Tn.self=Tn),Tn&&typeof File>"u"&&(Tn.File=function(){});var R=_??{},Y={DEBUG:!1,LIB_VERSION:"0.5.0",LIB_NAME:"browser-common"};function Ja(t,e,n,i,s,r,o){try{var a=t[r](o),l=a.value}catch(u){return void n(u)}a.done?e(l):Promise.resolve(l).then(i,s)}function X(t){return function(){var e=this,n=arguments;return new Promise((function(i,s){var r=t.apply(e,n);function o(l){Ja(r,i,s,o,a,"next",l)}function a(l){Ja(r,i,s,o,a,"throw",l)}o(void 0)}))}}function b(){return b=Object.assign?Object.assign.bind():function(t){for(var e=1;arguments.length>e;e++){var n=arguments[e];for(var i in n)({}).hasOwnProperty.call(n,i)&&(t[i]=n[i])}return t},b.apply(null,arguments)}function jc(t,e){if(t==null)return{};var n={};for(var i in t)if({}.hasOwnProperty.call(t,i)){if(e.indexOf(i)!==-1)continue;n[i]=t[i]}return n}var Ya=t=>{if(typeof t!="string")return t;try{return JSON.parse(t)}catch{return t}};function Za(t){return typeof t=="string"||t}function Xa(t){return typeof t=="string"?t:void 0}var Rn,Ch=["$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","irclid","_kx","$session_id","$window_id","$lib","$lib_version","$device_id","$is_server"],pt=(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.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.SurveysSeen="surveys_seen",t.Surveys="surveys",t.RemoteConfig="remote_config",t.FlagsEndpointWasHit="flags_endpoint_was_hit",t.DeviceId="device_id",t})({}),Qa=(function(t){return t.GZipJS="gzip-js",t.Base64="base64",t})({}),Ah=["$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"],Fh=["token"],Uc="NativeGzipValidationError",zr=t=>t.length>=2&&t[0]===31&&t[1]===139,el=(t,e)=>t===Qa.GZipJS||e===Qa.GZipJS||e==="gzip",tl=t=>!(!t||typeof t!="object")&&("name"in t?String(t.name):"")==="NotReadableError",ki=t=>{var e=new Error("Native gzip produced invalid output: "+t);throw e.name=Uc,e},Ph=(function(){var t=X((function*(e,n){18>e.size&&ki("too-short");var i=new Uint8Array(yield e.slice(0,10).arrayBuffer());zr(i)&&i[2]===8||ki("invalid-header");var s=new DataView(yield e.slice(e.size-8).arrayBuffer());s.getUint32(0,!0)!==(o=>{for(var a=(()=>{if(Rn)return Rn;Rn=[];for(var c=0;256>c;c++){for(var d=c,h=0;8>h;h++)d=1&d?3988292384^d>>>1:d>>>1;Rn[c]=d>>>0}return Rn})(),l=4294967295,u=0;o.length>u;u++)l=a[255&(l^o[u])]^l>>>8;return(4294967295^l)>>>0})(n)&&ki("invalid-crc");var r=n.length>>>0;s.getUint32(4,!0)!==r&&ki("invalid-size")}));return function(e,n){return t.apply(this,arguments)}})();function qr(){return qr=X((function*(t,e,n){e===void 0&&(e=!0);try{var i=new TextEncoder().encode(t),s=new globalThis.CompressionStream("gzip"),r=s.writable.getWriter(),o=r.write(i).then((()=>r.close())).catch((function(){var u=X((function*(c){try{yield r.abort(c)}catch{}throw c}));return function(c){return u.apply(this,arguments)}})()),a=new Response(s.readable).blob(),l=(yield Promise.all([a,o]))[0];return yield Ph(l,i),l}catch(u){if(n!=null&&n.rethrow)throw u;return e&&console.error("Failed to gzip compress data",u),null}})),qr.apply(this,arguments)}var $h=["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","pinterest","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"],nl=function(t,e){if(e===void 0&&(e=[]),!t)return!1;var n=t.toLowerCase();return $h.concat(e).some((i=>{var s=i.toLowerCase();return n.indexOf(s)!==-1}))};function L(t,e){return t.indexOf(e)!==-1}var Bs=function(t){return t.trim()},Vr=function(t){return t.replace(/^\$/,"")};function Hc(t){var e,n=[];return(e=JSON.stringify(t,(function(i,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"}var Wc=Object.prototype,zc=Wc.hasOwnProperty,Ds=Wc.toString,O=Array.isArray||function(t){return Ds.call(t)==="[object Array]"},Se=t=>typeof t=="function",ne=t=>t===Object(t)&&!O(t),yt=t=>{if(ne(t)){for(var e in t)if(zc.call(t,e))return!1;return!0}return!1},x=t=>t===void 0,q=t=>Ds.call(t)=="[object String]",Gr=t=>q(t)&&t.trim().length===0,$e=t=>t===null,B=t=>x(t)||$e(t),he=t=>Ds.call(t)=="[object Number]"&&t==t,dt=t=>he(t)&&t>0,Ye=t=>Ds.call(t)==="[object Boolean]",Th=t=>t instanceof FormData,Rh=t=>L(Ah,t),Nh=t=>L(Fh,t);function qc(t){return t===null||typeof t!="object"}function es(t,e){return{}.toString.call(t)==="[object "+e+"]"}function Jo(t){return typeof Event<"u"&&Vc(t,Event)}function Vc(t,e){try{return t instanceof e}catch{return!1}}var Mh=[!0,"true",1,"1","yes"],cr=t=>L(Mh,t),Lh=[!1,"false",0,"0","no"];function ot(t,e,n,i,s){return e>n&&(i.warn("min cannot be greater than max."),e=n),he(t)?t>n?(i.warn(" cannot be greater than max: "+n+". Using max value instead."),n):e>t?(i.warn(" cannot be less than min: "+e+". Using min value instead."),e):t:(i.warn(" must be a number. using max or fallback. max: "+n+", fallback: "+s),ot(s||n,e,n,i))}class Oh{constructor(e){this.tt={},this.et=e.et,this.it=ot(e.bucketSize,0,100,e.rt),this.nt=ot(e.refillRate,0,this.it,e.rt),this.st=ot(e.refillInterval,0,864e5,e.rt)}ot(e,n){var i=Math.floor((n-e.lastAccess)/this.st);i>0&&(e.tokens=Math.min(e.tokens+i*this.nt,this.it),e.lastAccess=e.lastAccess+i*this.st)}consumeRateLimit(e){var n,i=Date.now(),s=String(e),r=this.tt[s];return r?this.ot(r,i):this.tt[s]=r={tokens:this.it,lastAccess:i},r.tokens===0||(r.tokens--,r.tokens===0&&((n=this.et)==null||n.call(this,e)),r.tokens===0)}stop(){this.tt={}}}var Oe="Mobile",ts="iOS",wt="Android",vn="Tablet",Gc=wt+" "+vn,Kc="iPad",Jc="Apple",Yc=Jc+" Watch",Yn="Safari",_n="BlackBerry",Zc="Samsung",Xc=Zc+"Browser",Qc=Zc+" Internet",Yt="Chrome",Bh=Yt+" OS",eu=Yt+" "+ts,Yo="Internet Explorer",tu=Yo+" "+Oe,Zo="Opera",Dh=Zo+" Mini",Xo="Edge",nu="Microsoft "+Xo,fn="Firefox",iu=fn+" "+ts,ri="Nintendo",oi="PlayStation",gn="Xbox",su=wt+" "+Oe,ru=Oe+" "+Yn,Wn="Windows",Kr=Wn+" Phone",il="Nokia",Jr="Ouya",ou="Generic",jh=ou+" "+Oe.toLowerCase(),au=ou+" "+vn.toLowerCase(),Yr="Konqueror",lu="Oculus Browser",ns="Vivaldi",cu="Yandex",is="Whale",Zr="DuckDuckGo",uu="Pale Moon",ss="Waterfox",Zn="Brave",du="Google Search App",le="(\\d+(\\.\\d+)?)",ur=new RegExp("Version/"+le),Uh=new RegExp(gn,"i"),Hh=new RegExp(oi+" \\w+","i"),Wh=new RegExp(ri+" \\w+","i"),Qo=new RegExp(_n+"|PlayBook|BB10","i"),zh={"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"},hu=function(t,e,n,i){e=e||"";var s=(function(r){return r!=null&&r.brave?Zn:null})(n);return s||(i!=null&&i.detectGoogleSearchApp&&L(t,"GSA/")?du:L(t," OPR/")&&L(t,"Mini")?Dh:L(t," OPR/")?Zo:Qo.test(t)?_n:L(t,"IE"+Oe)||L(t,"WPDesktop")?tu:L(t,"OculusBrowser")?lu:L(t,Xc)?Qc:L(t,Xo)||L(t,"Edg/")?nu:L(t,ns+"/")?ns:L(t,"YaBrowser/")?cu:L(t,is+"/")?is:L(t,Zr+"/")||L(t,"Ddg/")?Zr:L(t,"FBIOS")?"Facebook "+Oe:L(t,"UCWEB")||L(t,"UCBrowser")?"UC Browser":L(t,"CriOS")?eu:L(t,"CrMo")||L(t,Yt)?Yt:L(t,wt)&&L(t,Yn)?su:L(t,"FxiOS")?iu:L(t.toLowerCase(),Yr.toLowerCase())?Yr:L(t,Zn+"/")?Zn:((r,o)=>o&&L(o,Jc)||(function(a){return L(a,Yn)&&!L(a,Yt)&&!L(a,wt)})(r))(t,e)?L(t,Oe)?ru:Yn:L(t,"PaleMoon/")?uu:L(t,ss+"/")?ss:L(t,fn)?fn:L(t,"MSIE")||L(t,"Trident/")?Yo:L(t,"Gecko")?fn:"")},qh={[tu]:[new RegExp("rv:"+le)],[nu]:[new RegExp(Xo+"?\\/"+le)],[Yt]:[new RegExp("("+Yt+"|CrMo)\\/"+le)],[eu]:[new RegExp("CriOS\\/"+le)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+le)],[Yn]:[ur],[ru]:[ur],[Zo]:[new RegExp("(Opera|OPR)\\/"+le)],[fn]:[new RegExp(fn+"\\/"+le)],[iu]:[new RegExp("FxiOS\\/"+le)],[Yr]:[new RegExp("Konqueror[:/]?"+le,"i")],[_n]:[new RegExp(_n+" "+le),ur],[su]:[new RegExp("android\\s"+le,"i")],[Qc]:[new RegExp(Xc+"\\/"+le)],[lu]:[new RegExp("OculusBrowser\\/"+le)],[ns]:[new RegExp(ns+"\\/"+le)],[cu]:[new RegExp("YaBrowser\\/"+le)],[is]:[new RegExp(is+"\\/"+le)],[Zn]:[new RegExp(Zn+"\\/"+le)],[Zr]:[new RegExp("(DuckDuckGo|Ddg)\\/"+le)],[uu]:[new RegExp("PaleMoon\\/"+le)],[ss]:[new RegExp(ss+"\\/"+le)],[du]:[new RegExp("GSA\\/"+le)],[Yo]:[new RegExp("(rv:|MSIE )"+le)],Mozilla:[new RegExp("rv:"+le)]},Vh=function(t,e,n,i){var s=hu(t,e,n,i),r=qh[s];if(x(r))return null;for(var o=0;r.length>o;o++){var a=t.match(r[o]);if(a)return parseFloat(a[a.length-2])}return null},sl=[[new RegExp(gn+"; "+gn+" (.*?)[);]","i"),t=>[gn,t&&t[1]||""]],[new RegExp(ri,"i"),[ri,""]],[new RegExp(oi,"i"),[oi,""]],[Qo,[_n,""]],[new RegExp(Wn,"i"),(t,e)=>{if(/Phone/.test(e)||/WPDesktop/.test(e))return[Kr,""];if(new RegExp(Oe).test(e)&&!/IEMobile\b/.test(e))return[Wn+" "+Oe,""];var n=/Windows NT ([0-9.]+)/i.exec(e);if(n&&n[1]){var i=zh[n[1]]||"";return/arm/i.test(e)&&(i="RT"),[Wn,i]}return[Wn,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,t=>t&&t[3]?[ts,[t[3],t[4],t[5]||"0"].join(".")]:[ts,""]],[/(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i,t=>{var e="";return t&&t.length>=3&&(e=x(t[2])?t[3]:t[2]),["watchOS",e]}],[new RegExp("("+wt+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+wt+")","i"),t=>t&&t[2]?[wt,[t[2],t[3],t[4]||"0"].join(".")]:[wt,""]],[/Mac OS X (\d+)[_.](\d+)[_.]?(\d+)?/i,t=>{var 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/,[Bh,""]],[/Linux|debian/i,["Linux",""]]],rl=function(t){return Wh.test(t)?ri:Hh.test(t)?oi:Uh.test(t)?gn:new RegExp(Jr,"i").test(t)?Jr:new RegExp("("+Kr+"|WPDesktop)","i").test(t)?Kr:/iPad/.test(t)?Kc:/iPod/.test(t)?"iPod Touch":/iPhone/.test(t)?"iPhone":/(watch)(?: ?os[,/]|\d,\d\/)[\d.]+/i.test(t)?Yc:Qo.test(t)?_n:/(kobo)\s(ereader|touch)/i.test(t)?"Kobo":new RegExp(il,"i").test(t)?il:/(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(Oe).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)?wt:Gc:new RegExp("(pda|"+Oe+")","i").test(t)?jh:new RegExp(vn,"i").test(t)&&!new RegExp(vn+" pc","i").test(t)?au:""},Gh=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function ol(t,e){return typeof(n=t)=="string"&&Gh.test(n)?t:e();var n}function Pt(t){return t&&t.split("#")[0]}function ea(t,e){var n=setTimeout(t,e);return n?.unref&&n?.unref(),n}function al(t,e,n){return pu.apply(this,arguments)}function pu(){return(pu=X((function*(t,e,n){var i;try{return yield Promise.race([t,new Promise(((s,r)=>{i=ea((()=>{try{n?.(),s()}catch(o){r(o)}}),e)}))])}finally{clearTimeout(i)}}))).apply(this,arguments)}var Kh=t=>t instanceof Error,fu={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}},Jh=fu.info;function gu(t){if(Ye(t))return{boolValue:t};if(typeof t=="number")return Number.isFinite(t)?Number.isInteger(t)?{intValue:t}:{doubleValue:t}:{stringValue:String(t)};if(typeof t=="string")return{stringValue:t};if(O(t))return{arrayValue:{values:t.map((e=>gu(e)))}};try{return{stringValue:JSON.stringify(t)}}catch{return{stringValue:String(t)}}}function rs(t){var e=[];for(var n in t){var i=t[n];$e(i)||x(i)||e.push({key:n,value:gu(i)})}return e}function Yh(t,e){var n=fu[t.level||"info"]||Jh,i=n.text,s=n.number,r=String(Date.now())+"000000",o={};e.distinctId&&(o.posthogDistinctId=e.distinctId),e.sessionId&&(o.sessionId=e.sessionId),e.windowId&&(o["window.id"]=e.windowId),B(e.sessionStartTimestamp)||(o.sessionStartTimestamp=String(e.sessionStartTimestamp)),B(e.lastActivityTimestamp)||(o.lastActivityTimestamp=String(e.lastActivityTimestamp)),e.currentUrl&&(o["url.full"]=e.currentUrl),e.screenName&&(o["screen.name"]=e.screenName),e.appState&&(o["app.state"]=e.appState),e.activeFeatureFlags&&e.activeFeatureFlags.length>0&&(o.feature_flags=e.activeFeatureFlags);var a=b({},o,t.attributes||{}),l={timeUnixNano:r,observedTimeUnixNano:r,severityNumber:s,severityText:i,body:{stringValue:t.body},attributes:rs(a)};return t.trace_id&&(l.traceId=t.trace_id),t.span_id&&(l.spanId=t.span_id),x(t.trace_flags)||(l.flags=t.trace_flags),l}function mu(t,e,n){return b({},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})}function vu(t,e,n,i){return{resourceLogs:[{resource:{attributes:rs(e)},scopeLogs:[{scope:{name:n,version:i},logRecords:t}]}]}}let Zh=class{constructor(t,e,n,i,s,r,o){var a;r===void 0&&(r=()=>Promise.resolve()),this._instance=t,this.Ne=e,this.rt=n,this.ut=i,this.ht=s,this.dt=r,this.vt=o,this.ct=null,this.ft=0,this.yt=0,this.bt=0,this._t=0,this.wt=!1,this.kt=e.maxBufferSize,this.xt=Math.max((a=e.maxQueueSize)!==null&&a!==void 0?a:e.maxBufferSize,e.maxBufferSize),this.St=e.flushIntervalMs,this.Ct=e.maxBatchRecordsPerPost,this.Mt=e.rateCapWindowMs,this.Tt=e.maxLogsPerInterval}reset(){this.Et(),this.ct=null,this.bt=0,this._t=0,this.wt=!1,this.ft=0,this.yt=0,this.Ct=this.Ne.maxBatchRecordsPerPost}onReconnect(){this.yt=0,this.It()}captureLog(t){if(!this._instance.isDisabled&&!this._instance.optedOut&&t!=null&&t.body){var e=this.Pt(t);if(e!==null)if(e.body){if(this.Rt()){var n={record:Yh(e,this.ut())};this.ht((()=>this.At(n)))}}else this.rt.info("Log was rejected in beforeSend function")}}Pt(t){var e=this.Ne.beforeSend;if(!e)return t;var n=O(e)?e:[e],i=t;for(var s of n)try{var r=s(i);if(!r)return this.rt.info("Log was rejected in beforeSend function"),null;i=r}catch(o){return this.rt.error("Error in beforeSend function for log:",o),null}return i}Rt(){if(this.Tt===void 0)return!0;var t=Date.now(),e=t-this.bt;return this.Mt>e&&e>=0||(this.bt=t,this._t=0,this.wt=!1),this.Tt>this._t?(this._t++,!0):(this.wt||(this.rt.warn("captureLog dropping logs: exceeded "+this.Tt+" logs per "+this.Mt+"ms"),this.wt=!0),!1)}flush(){var t=this;return X((function*(){if(!t._instance.isDisabled)return t.ct||(t.ct=t.Ft().finally((()=>{t.ct=null}))),t.ct}))()}Ft(){var t=this;return X((function*(){var e;t.Et();var n=(e=t._instance.getPersistedProperty(pt.LogsQueue))!==null&&e!==void 0?e:[];if(n.length!==0)for(var i=n.length,s=0;n.length>0&&i>s;){var r,o;t.ft=0;var a=Math.min(n.length,t.Ct),l=n.slice(0,a),u=vu(l.map((d=>d.record)),t.Lt(),(r=t.vt)!==null&&r!==void 0?r:t._instance.getLibraryId(),t._instance.getLibraryVersion()),c=yield t._instance.Ot(u);if(c.kind==="too-large"&&l.length>1)t.Ct=Math.max(1,Math.floor(l.length/2)),t.rt.warn("Received 413 when sending logs batch of size "+l.length+", reducing batch size to "+t.Ct);else if(c.kind==="retry-later"||(c.kind==="too-large"?t.rt.warn("Dropping a single log record after 413 with batch size 1 — the record is larger than the server cap and cannot be split further."):c.kind==="ok"&&t.Ne.maxBatchRecordsPerPost>t.Ct&&(t.Ct=Math.min(t.Ne.maxBatchRecordsPerPost,t.Ct+1)),yield t.Dt(l.length),n=(o=t._instance.getPersistedProperty(pt.LogsQueue))!==null&&o!==void 0?o:[],s+=l.length,c.kind==="fatal"))throw c.error}}))()}Dt(t){var e=this;return X((function*(){var n,i=Math.max(0,t-e.ft),s=(n=e._instance.getPersistedProperty(pt.LogsQueue))!==null&&n!==void 0?n:[];e._instance.setPersistedProperty(pt.LogsQueue,s.slice(i)),yield e.dt()}))()}Lt(){return mu(this.Ne,this._instance.getLibraryId(),this._instance.getLibraryVersion())}At(t){var e;if(!this._instance.optedOut){var n=(e=this._instance.getPersistedProperty(pt.LogsQueue))!==null&&e!==void 0?e:[];this.xt>n.length||(n.shift(),this.ft++,this.rt.info("Logs queue is full, dropping oldest record.")),n.push(t),this._instance.setPersistedProperty(pt.LogsQueue,n),this.kt>n.length?this.$t():this.It()}}$t(t){t===void 0&&(t=this.St),this.Nt||(this.Nt=ea((()=>{this.Nt=void 0,this.It()}),t))}qt(){var t=Math.min(Math.max(0,this.yt-1),6);return this.St*Math.pow(2,t)}jt(){var t=this._instance.getPersistedProperty(pt.LogsQueue);return!!t&&t.length>0}shutdown(t){var e=this;return X((function*(){e.Et();var n=e.flush().catch((()=>{}));t!==void 0?yield al(n,t):yield n}))()}flushWithTimeout(t){var e=this;return X((function*(){var n=e.flush();yield al(n,t,(()=>{n.catch((()=>{}))}))}))()}It(){this.flush().then((()=>{this.yt=0}),(t=>{this.yt++,this.rt.error("PostHog logs flush failed:",t)})).finally((()=>{!this._instance.isDisabled&&this.jt()&&this.$t(this.qt())}))}Et(){this.Nt&&(clearTimeout(this.Nt),this.Nt=void 0)}};var dr=[0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4];function ll(t){return String(t)+"000000"}function cl(t,e,n,i){var s="";return i&&(s=Object.keys(i).sort().map((r=>JSON.stringify(r)+":"+JSON.stringify(i[r]))).join(",")),t+"\0"+e+"\0"+(n??"")+"\0"+s}let Xh=class{constructor(t,e,n){this._instance=t,this.Ne=e,this.rt=n,this.Bt=new Map,this.ct=null,this.Ht=!1,this.Ut=new Map,this.zt=new Set,this.Wt=0}count(t,e,n){e===void 0&&(e=1),this.Vt({name:t,type:"count",value:e,unit:n?.unit,attributes:n?.attributes})}gauge(t,e,n){this.Vt({name:t,type:"gauge",value:e,unit:n?.unit,attributes:n?.attributes})}histogram(t,e,n){this.Vt({name:t,type:"histogram",value:e,unit:n?.unit,attributes:n?.attributes})}flush(){var t=this,e=this.ct,n=(function(){var s=X((function*(){e&&(yield e.catch((()=>{}))),yield t.Zt()}));return function(){return s.apply(this,arguments)}})(),i=n().finally((()=>{this.ct===i&&(this.ct=null)}));return this.ct=i,i}drainWindow(){if(this.Bt.size===0)return null;var t=this.Bt;return this.Bt=new Map,this.Ht=!1,this.Ut=new Map,this.zt=new Set,this.Gt(t)}reset(){this.Wt++,this.Et(),this.Bt=new Map,this.ct=null,this.Ht=!1,this.Ut=new Map,this.zt=new Set}Vt(t){if(!this._instance.isDisabled&&!this._instance.optedOut){var e=this.Pt(t);if(e!==null)if(e.name&&typeof e.name=="string")if(typeof e.value=="number"&&Number.isFinite(e.value))if(e.type==="count"&&0>e.value)this.rt.warn("Dropping count '"+e.name+"': counters are monotonic, value must be >= 0");else{var n,i;try{n=e.attributes?b({},e.attributes):void 0,i=cl(e.type,e.name,e.unit,n)}catch(o){return void this.rt.warn("Dropping metric '"+e.name+"': attributes could not be serialized",o)}var s=this.Bt.get(i);if(!s){if(!this.Qt())return;s={name:e.name,type:e.type,unit:e.unit,attributes:n,windowStartMs:Date.now()},this.Bt.set(i,s)}var r=this.Ut.get(e.name);r===void 0?this.Ut.set(e.name,e.type):r===e.type||this.zt.has(e.name)||(this.zt.add(e.name),this.rt.warn("Metric name '"+e.name+"' is already used as a "+r+"; recording it as a "+e.type+" too will blend both series in charts. Use a distinct name.")),this.Kt(s,e.value),this.$t()}else this.rt.warn("Dropping metric '"+e.name+"': value must be a finite number");else this.rt.warn("Dropping metric with empty name")}}Qt(){return this.Ne.maxSeriesPerFlush>this.Bt.size||(this.Ht||(this.Ht=!0,this.rt.warn("Metric series cap reached ("+this.Ne.maxSeriesPerFlush+" per flush window); dropping new series until the next flush. Reduce attribute cardinality.")),!1)}Kt(t,e){var n;switch(t.type){case"count":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(dr.length+1).fill(0)});var i=t.hist;i.count+=1,i.sum+=e,i.min=Math.min(i.min,e),i.max=Math.max(i.max,e),i.bucketCounts[(function(s,r){for(var o=0;r.length>o;o++)if(r[o]>=s)return o;return r.length})(e,dr)]+=1}}Pt(t){var e=this.Ne.beforeSend;if(!e)return t;var n=O(e)?e:[e],i=t;for(var s of n)try{var r=s(i);if(!r)return this.rt.info("Metric was rejected in beforeSend function"),null;i=r}catch(o){return this.rt.error("Error in beforeSend function for metric:",o),null}return i}$t(){this.Nt||(this.Nt=ea((()=>{this.Nt=void 0,this.flush().catch((t=>{this.rt.error("Metrics flush failed:",t)}))}),this.Ne.flushIntervalMs))}Et(){this.Nt&&(clearTimeout(this.Nt),this.Nt=void 0)}Zt(){var t=this;return X((function*(){if(t.Bt.size!==0){var e=t.Bt;t.Bt=new Map,t.Ht=!1,t.Ut=new Map,t.zt=new Set;var n=t.Wt,i=yield t._instance.Jt(t.Gt(e));if(n===t.Wt)switch(i.kind){case"ok":return;case"retry-later":return t.Yt(e),void t.$t();case"too-large":return void t.rt.warn("Metrics batch exceeded the server size limit and was dropped");case"fatal":return void t.rt.error("Failed to send metrics batch:",i.error)}}}))()}Gt(t){return e=this.Xt(t),n=(function(r,o,a){return b({},r.resourceAttributes,{"service.name":r.serviceName||"unknown_service"},r.environment&&{"deployment.environment":r.environment},r.serviceVersion&&{"service.version":r.serviceVersion},{"telemetry.sdk.name":o,"telemetry.sdk.version":a})})(this.Ne,this._instance.getLibraryId(),this._instance.getLibraryVersion()),i=this._instance.getLibraryId(),s=this._instance.getLibraryVersion(),{resourceMetrics:[{resource:{attributes:rs(n)},scopeMetrics:[{scope:{name:i,version:s},metrics:e}]}]};var e,n,i,s}Xt(t){var e=ll(Date.now()),n=new Map;for(var i of t.values()){var s,r=cl(i.type,i.name,i.unit,void 0),o=n.get(r);o||(o=b({name:i.name},i.unit&&{unit:i.unit}),i.type==="count"?o.sum={aggregationTemporality:1,isMonotonic:!0,dataPoints:[]}:i.type==="gauge"?o.gauge={dataPoints:[]}:o.histogram={aggregationTemporality:1,dataPoints:[]},n.set(r,o));var a=rs((s=i.attributes)!==null&&s!==void 0?s:{}),l=ll(i.windowStartMs);if(i.type==="count"){var u,c={attributes:a,startTimeUnixNano:l,timeUnixNano:e,asDouble:(u=i.total)!==null&&u!==void 0?u:0};o.sum.dataPoints.push(c)}else if(i.type==="gauge"){var d,h={attributes:a,timeUnixNano:e,asDouble:(d=i.last)!==null&&d!==void 0?d:0};o.gauge.dataPoints.push(h)}else i.hist&&o.histogram.dataPoints.push({attributes:a,startTimeUnixNano:l,timeUnixNano:e,count:i.hist.count,sum:i.hist.sum,min:i.hist.min,max:i.hist.max,bucketCounts:i.hist.bucketCounts,explicitBounds:dr})}return Array.from(n.values())}Yt(t){var e,n;for(var i of t){var s=i[0],r=i[1],o=this.Bt.get(s);if(o)switch(o.windowStartMs=Math.min(o.windowStartMs,r.windowStartMs),o.type){case"count":o.total=((e=o.total)!==null&&e!==void 0?e:0)+((n=r.total)!==null&&n!==void 0?n:0);break;case"gauge":break;case"histogram":if(r.hist)if(o.hist){o.hist.count+=r.hist.count,o.hist.sum+=r.hist.sum,o.hist.min=Math.min(o.hist.min,r.hist.min),o.hist.max=Math.max(o.hist.max,r.hist.max);for(var a=0;o.hist.bucketCounts.length>a;a++)o.hist.bucketCounts[a]+=r.hist.bucketCounts[a]}else o.hist=r.hist}else this.Qt()&&this.Bt.set(s,r)}}};var Ii,ul,hr;function Qh(t){var e=globalThis._posthogChunkIds;if(e){var n=Object.keys(e);return hr&&n.length===ul||(ul=n.length,hr=n.reduce(((i,s)=>{Ii||(Ii={});var r=Ii[s];if(r)i[r[0]]=r[1];else for(var o=t(s),a=o.length-1;a>=0;a--){var l=o[a],u=l?.filename,c=e[s];if(u&&c){i[u]=c,Ii[s]=[u,c];break}}return i}),{})),hr}}class ep{constructor(e,n,i){i===void 0&&(i=[]),this.coercers=e,this.stackParser=n,this.modifiers=i}buildFromUnknown(e,n){n===void 0&&(n={});var i=n&&n.mechanism||{handled:!0,type:"generic"},s=this.buildCoercingContext(i,n,0).apply(e),r=this.buildParsingContext(n),o=this.parseStacktrace(s,r);return{$exception_list:this.convertToExceptionList(o,i),$exception_level:"error"}}modifyFrames(e){var n=this;return X((function*(){for(var i of e)i.stacktrace&&i.stacktrace.frames&&O(i.stacktrace.frames)&&(i.stacktrace.frames=yield n.applyModifiers(i.stacktrace.frames));return e}))()}coerceFallback(e){var n;return{type:"Error",value:"Unknown error",stack:(n=e.syntheticException)==null?void 0:n.stack,synthetic:!0}}parseStacktrace(e,n){var i,s;return e.cause!=null&&(i=this.parseStacktrace(e.cause,n)),e.stack!=""&&e.stack!=null&&(s=this.applyChunkIds(this.stackParser(e.stack,e.synthetic?n.skipFirstLines:0),n.chunkIdMap)),b({},e,{cause:i,stack:s})}applyChunkIds(e,n){return e.map((i=>(i.filename&&n&&(i.chunk_id=n[i.filename]),i)))}applyCoercers(e,n){for(var i of this.coercers)if(i.match(e))return i.coerce(e,n);return this.coerceFallback(n)}applyModifiers(e){var n=this;return X((function*(){var i=e;for(var s of n.modifiers)i=yield s(i);return i}))()}convertToExceptionList(e,n){var i,s,r,o={type:e.type,value:e.value,mechanism:{type:(i=n.type)!==null&&i!==void 0?i:"generic",handled:(s=n.handled)===null||s===void 0||s,synthetic:(r=e.synthetic)!==null&&r!==void 0&&r}};e.stack&&(o.stacktrace={type:"raw",frames:e.stack});var a=[o];return e.cause!=null&&a.push(...this.convertToExceptionList(e.cause,b({},n,{handled:!0}))),a}buildParsingContext(e){var n;return{chunkIdMap:Qh(this.stackParser),skipFirstLines:(n=e.skipFirstLines)!==null&&n!==void 0?n:1}}buildCoercingContext(e,n,i){i===void 0&&(i=0);var s=(r,o)=>{if(4>=o){var a=this.buildCoercingContext(e,n,o);return this.applyCoercers(r,a)}};return b({},n,{syntheticException:i==0?n.syntheticException:void 0,mechanism:e,apply:r=>s(r,i),next:r=>s(r,i+1)})}}var yn="?";function Xr(t,e,n,i,s){var r={platform:t,filename:e,function:n===""?yn:n,in_app:!0};return x(i)||(r.lineno=i),x(s)||(r.colno=s),r}var _u=(t,e)=>{var n=t.indexOf("safari-extension")!==-1,i=t.indexOf("safari-web-extension")!==-1;return n||i?[t.indexOf("@")!==-1?t.split("@")[0]:yn,n?"safari-extension:"+e:"safari-web-extension:"+e]:[t,e]},tp=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,np=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,ip=/\((\S*)(?::(\d+))(?::(\d+))\)/,sp=(t,e)=>{var n=tp.exec(t);if(n)return Xr(e,n[1],yn,+n[2],+n[3]);var i=np.exec(t);if(i){if(i[2]&&i[2].indexOf("eval")===0){var s=ip.exec(i[2]);s&&(i[2]=s[1],i[3]=s[2],i[4]=s[3])}var r=_u(i[1]||yn,i[2]);return Xr(e,r[1],r[0],i[3]?+i[3]:void 0,i[4]?+i[4]:void 0)}},rp=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,op=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,ap=(t,e)=>{var n=rp.exec(t);if(n){if(n[3]&&n[3].indexOf(" > eval")>-1){var i=op.exec(n[3]);i&&(n[1]=n[1]||"eval",n[3]=i[1],n[4]=i[2],n[5]="")}var s=n[3],r=n[1]||yn,o=_u(r,s);return Xr(e,s=o[1],r=o[0],n[4]?+n[4]:void 0,n[5]?+n[5]:void 0)}},dl=/\(error: (.*)\)/;class lp{match(e){return this.isDOMException(e)||this.isDOMError(e)}coerce(e,n){var i=q(e.stack);return{type:this.getType(e),value:this.getValue(e),stack:i?e.stack:void 0,cause:e.cause?n.next(e.cause):void 0,synthetic:!1}}getType(e){return this.isDOMError(e)?"DOMError":"DOMException"}getValue(e){var n=e.name||(this.isDOMError(e)?"DOMError":"DOMException");return e.message?n+": "+e.message:n}isDOMException(e){return es(e,"DOMException")}isDOMError(e){return es(e,"DOMError")}}class cp{match(e){return(function(n){switch({}.toString.call(n)){case"[object Error]":case"[object Exception]":case"[object DOMException]":case"[object DOMError]":case"[object WebAssembly.Exception]":return!0;default:return Vc(n,Error)}})(e)}coerce(e,n){return{type:this.getType(e),value:this.getMessage(e,n),stack:this.getStack(e),cause:e.cause?n.next(e.cause):void 0,synthetic:!1}}getType(e){return e.name||e.constructor.name}getMessage(e,n){var i=e.message;return String(i.error&&typeof i.error.message=="string"?i.error.message:i)}getStack(e){return e.stacktrace||e.stack||void 0}}class up{constructor(){}match(e){return!!es(e,"ErrorEvent")&&(e.error!=null||this.fe(e))}coerce(e,n){var i;if(e.error!=null)return n.apply(e.error);var s=n.apply(e.message);return b({},s,{stack:(i=this.pe(e))!==null&&i!==void 0?i:s.stack,synthetic:!0})}fe(e){return q(e.message)&&e.message.length>0}pe(e){var n=e;if(q(n.filename)&&n.filename.length>0){var i,s,r=(i=n.lineno)!==null&&i!==void 0?i:0,o=(s=n.colno)!==null&&s!==void 0?s:0;return`Error - at `+n.filename+":"+r+":"+o}}}var dp=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;class hp{match(e){return typeof e=="string"}coerce(e,n){var i,s=this.getInfos(e),r=s[0],o=s[1];return{type:r??"Error",value:o??e,stack:(i=n.syntheticException)==null?void 0:i.stack,synthetic:!0}}getInfos(e){var n="Error",i=e,s=e.match(dp);return s&&(n=s[1],i=s[2]),[n,i]}}var pp=["fatal","error","warning","log","info","debug"];function yu(t,e){e===void 0&&(e=40);var n=Object.keys(t);if(n.sort(),!n.length)return"[object has no keys]";for(var i=n.length;i>0;i--){var s=n.slice(0,i).join(", ");if(e>=s.length)return i===n.length?s:s.length>e?s.slice(0,e)+"...":s}return""}class fp{match(e){return typeof e=="object"&&e!==null}coerce(e,n){var i,s,r=this.getErrorPropertyFromObject(e);return r?n.apply(r):{type:this.getType(e),value:this.getValue(e),stack:(i=this.getStack(e))!==null&&i!==void 0?i:(s=n.syntheticException)==null?void 0:s.stack,level:this.isSeverityLevel(e.level)?e.level:"error",synthetic:!0}}getType(e){return Jo(e)?e.constructor.name:"Error"}getValue(e){if("name"in e&&typeof e.name=="string"){var n="'"+e.name+"' captured as exception";return"message"in e&&typeof e.message=="string"&&(n+=" with message: '"+e.message+"'"),n}if("message"in e&&typeof e.message=="string")return e.message;var i=this.getObjectClassName(e);return(i&&i!=="Object"?"'"+i+"'":"Object")+" captured as exception with keys: "+yu(e)}isSeverityLevel(e){return q(e)&&!Gr(e)&&pp.indexOf(e)>=0}getStack(e){try{return q(e.stacktrace)&&e.stacktrace.length>0?e.stacktrace:q(e.stack)&&e.stack.length>0?e.stack:void 0}catch{return}}getErrorPropertyFromObject(e){for(var n in e)if({}.hasOwnProperty.call(e,n)){var i=e[n];if(Kh(i))return i}}getObjectClassName(e){try{var n=Object.getPrototypeOf(e);return n?n.constructor.name:void 0}catch{return}}}class gp{match(e){return Jo(e)}coerce(e,n){var i,s=e.constructor.name;return{type:s,value:s+" captured as exception with keys: "+yu(e),stack:(i=n.syntheticException)==null?void 0:i.stack,synthetic:!0}}}class mp{match(e){return qc(e)}coerce(e,n){var i;return{type:"Error",value:"Primitive value captured as exception: "+String(e),stack:(i=n.syntheticException)==null?void 0:i.stack,synthetic:!0}}}class vp{match(e){return es(e,"PromiseRejectionEvent")||this.isCustomEventWrappingRejection(e)}isCustomEventWrappingRejection(e){if(!Jo(e))return!1;try{var n=e.detail;return n!=null&&typeof n=="object"&&"reason"in n}catch{return!1}}coerce(e,n){var i,s=this.getUnhandledRejectionReason(e);return qc(s)?{type:"UnhandledRejection",value:"Non-Error promise rejection captured with value: "+String(s),stack:(i=n.syntheticException)==null?void 0:i.stack,synthetic:!0}:n.apply(s)}getUnhandledRejectionReason(e){try{if("reason"in e)return e.reason;if("detail"in e&&e.detail!=null&&typeof e.detail=="object"&&"reason"in e.detail)return e.detail.reason}catch{}return e}}var os="$message",as="$timestamp",_p=new Set([os,as]),pr={enabled:!0,max_bytes:32768};function ls(t){var e;return t?{enabled:(e=t.enabled)!==null&&e!==void 0?e:pr.enabled,max_bytes:wp(t.max_bytes,pr.max_bytes)}:b({},pr)}class yp{constructor(e){this.Ke=[],this.Je=0,this.Ne=ls(e)}setConfig(e){this.Ne=ls(e),this.Xe()}add(e){var n=(function(s){var r;try{r=Hc(s)}catch{return}try{var o=JSON.parse(r);if(!ne(o))return;var a=o,l=a[os],u=a[as];return!q(l)||l.trim().length===0||!q(u)&&!he(u)?void 0:{step:a,json:r}}catch{return}})(e);if(n){var i=(function(s){if(typeof TextEncoder<"u")return new TextEncoder().encode(s).length;for(var r=encodeURIComponent(s),o=0,a=0;r.length>a;a++)r[a]==="%"?(o+=1,a+=2):o+=1;return o})(n.json);i>this.Ne.max_bytes||(this.Ke.push({step:n.step,bytes:i}),this.Je+=i,this.Xe())}}getAttachable(){return this.Ke.map((e=>e.step))}clear(){this.Ke=[],this.Je=0}size(){return this.Ke.length}Xe(){for(;this.Je>this.Ne.max_bytes&&this.Ke.length>0;){var e=this.Ke.shift();e&&(this.Je-=e.bytes)}}}function wp(t,e){if(!he(t)||t===1/0||t===-1/0)return e;var n=Math.floor(t);return 0>n?e:n}var wu=function(t,e){var n=(e===void 0?{}:e).debugEnabled,i={k(s){if(_&&(Y.DEBUG||_.POSTHOG_DEBUG||n)&&!x(_.console)&&_.console){for(var r=("__rrweb_original__"in _.console[s])?_.console[s].__rrweb_original__:_.console[s],o=arguments.length,a=new Array(o>1?o-1:0),l=1;o>l;l++)a[l-1]=arguments[l];r(t,...a)}},debug(){for(var s=arguments.length,r=new Array(s),o=0;s>o;o++)r[o]=arguments[o];i.k("debug",...r)},info(){for(var s=arguments.length,r=new Array(s),o=0;s>o;o++)r[o]=arguments[o];i.k("log",...r)},warn(){for(var s=arguments.length,r=new Array(s),o=0;s>o;o++)r[o]=arguments[o];i.k("warn",...r)},error(){for(var s=arguments.length,r=new Array(s),o=0;s>o;o++)r[o]=arguments[o];i.k("error",...r)},critical(){for(var s=arguments.length,r=new Array(s),o=0;s>o;o++)r[o]=arguments[o];console.error(t,...r)},uninitializedWarning(s){i.error("You must initialize PostHog before calling "+s)},createLogger:(s,r)=>wu(t+" "+s,r)};return i},k=wu("[PostHog.js]"),ie=k.createLogger,bp=ie("[ExternalScriptsLoader]"),fr=(t,e,n)=>{if(t.config.disable_external_dependency_loading)return bp.warn(e+" was requested but loading of external scripts is disabled."),n("Loading of external scripts is disabled");var i=C?.querySelectorAll("script");if(i){for(var s,r=function(){if(i[o].src===e){var l=i[o];return l.__posthog_loading_callback_fired?{v:n()}:(l.addEventListener("load",(u=>{l.__posthog_loading_callback_fired=!0,n(void 0,u)})),l.onerror=u=>n(u),{v:void 0})}},o=0;i.length>o;o++)if(s=r())return s.v}var a=()=>{if(!C)return n("document not found");var l=C.createElement("script");if(l.type="text/javascript",l.crossOrigin="anonymous",l.src=e,l.onload=d=>{l.__posthog_loading_callback_fired=!0,n(void 0,d)},l.onerror=d=>n(d),t.config.prepare_external_dependency_script&&(l=t.config.prepare_external_dependency_script(l)),!l)return n("prepare_external_dependency_script returned null");if(t.config.external_scripts_inject_target==="head")C.head.appendChild(l);else{var u,c=C.querySelectorAll("body > script");c.length>0?(u=c[0].parentNode)==null||u.insertBefore(l,c[0]):C.body.appendChild(l)}};C!=null&&C.body?a():C?.addEventListener("DOMContentLoaded",a)};R.__PosthogExtensions__=R.__PosthogExtensions__||{},R.__PosthogExtensions__.loadExternalDependency=(t,e,n)=>{if(e!=="remote-config"){var i;if(t.config.strict_script_versioning)i=t.requestRouter.endpointFor("assets","/static/"+t.version+"/"+e+".js");else{var s="/static/"+e+".js?v="+t.version;if(e==="toolbar"){var r=3e5;s=s+"&t="+Math.floor(Date.now()/r)*r}i=t.requestRouter.endpointFor("assets",s)}fr(t,i,n)}else{var o=t.requestRouter.endpointFor("assets","/array/"+t.config.token+"/config.js");fr(t,o,n)}},R.__PosthogExtensions__.loadSiteApp=(t,e,n)=>{var i=t.requestRouter.endpointFor("api",e);fr(t,i,n)};Y.DEBUG=!1,Y.LIB_VERSION="1.415.7",Y.LIB_NAME="web";var bu="$people_distinct_id",ai="$device_id",gr="$device_model",zn="__alias",qn="__timers",Qr="$autocapture_disabled_server_side",eo="$heatmaps_enabled_server_side",to="$exception_capture_enabled_server_side",no="$error_tracking_suppression_rules",io="$error_tracking_capture_extension_exceptions",so="$web_vitals_enabled_server_side",ta="$dead_clicks_enabled_server_side",na="$product_tours_enabled_server_side",ro="$web_vitals_allowed_metrics",Jt="$session_recording_remote_config",Eu="$replay_sample_rate",Su="$replay_override_sampling",xu="$replay_override_linked_flag",ku="$replay_override_url_trigger",Iu="$replay_override_event_trigger",hn="$sesid",ia="$session_is_sampled",Wt="$enabled_feature_flags",Vn="$active_feature_flags",ji="$early_access_features",oo="$feature_flag_details",Gn="$feature_flag_payloads",Ui="$feature_flag_request_id",cs="$minimal_flag_called_events",it="$override_feature_flags",zt="$override_feature_flag_payloads",ht="$stored_person_properties",qt="$stored_group_properties",ao="$surveys",us="$surveys_loaded_at",lo="$surveys_activated",Hi="$surveys_activated_session",Wi="$surveys_activated_timestamps",Kn="ph_product_tours",Gt="$flag_call_reported",Jn="$flag_call_reported_session_id",zi="$feature_flag_errors",Xn="$feature_flag_evaluated_at",He="$user_state",co="$client_session_props",uo="$capture_rate_limit",ho="$initial_campaign_params",po="$initial_referrer_info",ds="$initial_person_info",hs="$epp",Ci="$posthog_cookieless",Cu="$cookieless_mode",Au="$sdk_debug_extensions_init_method",Fu="$sdk_debug_extensions_init_time_ms",Pu="$sdk_debug_recording_script_not_loaded",sa="PostHog loadExternalDependency extension not found.",Vt="on_reject",gt="always",sn="anonymous",Ot="identified",fo="identified_only",ps="visibilitychange",fs="beforeunload",cn="$pageview",mr="$pageleave",vr="$identify",hl="$groupidentify";function Ai(t,e){O(t)&&t.forEach(e)}function Z(t,e){if(!B(t))if(O(t))t.forEach(e);else if(Th(t))t.forEach(((i,s)=>e(i,s)));else for(var n in t)zc.call(t,n)&&e(t[n],n)}var te=function(t){for(var e=arguments.length,n=new Array(e>1?e-1:0),i=1;e>i;i++)n[i-1]=arguments[i];for(var s of n)for(var r in s)s[r]!==void 0&&(t[r]=s[r]);return t};function qi(t){for(var e=Object.keys(t),n=e.length,i=new Array(n);n--;)i[n]=[e[n],t[e[n]]];return i}var pl=function(t){try{return t()}catch{return}},Ep=function(t){return function(){try{for(var e=arguments.length,n=new Array(e),i=0;e>i;i++)n[i]=arguments[i];return t.apply(this,n)}catch(s){k.critical("Implementation error. Please turn on debug mode and open a ticket on https://app.posthog.com/home#panel=support%3Asupport%3A."),k.critical(s)}}},ra=function(t){var e={};return Z(t,(function(n,i){(q(n)&&n.length>0||he(n))&&(e[i]=n)})),e},Sp=["herokuapp.com","vercel.app","netlify.app"];function xp(t){var e=t?.hostname;if(!q(e))return!1;var n=e.split(".").slice(-2).join(".");for(var i of Sp)if(n===i)return!1;return!0}function re(t,e,n,i){var s=i??{},r=s.capture,o=s.passive;t?.addEventListener(e,n,{capture:r!==void 0&&r,passive:o===void 0||o})}function go(t){return t.name==="ph_toolbar_internal"}var $u=t=>{if(C){try{for(var e=t+"=",n=C.cookie.split(";").filter((r=>r.length)),i=0;n.length>i;i++){for(var s=n[i];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}};Math.trunc||(Math.trunc=function(t){return 0>t?Math.ceil(t):Math.floor(t)}),Number.isInteger||(Number.isInteger=function(t){return he(t)&&isFinite(t)&&Math.floor(t)===t});class gs{constructor(e){if(this.bytes=e,e.length!==16)throw new TypeError("not 128-bit length")}static fromFieldsV7(e,n,i,s){if(!Number.isInteger(e)||!Number.isInteger(n)||!Number.isInteger(i)||!Number.isInteger(s)||0>e||0>n||0>i||0>s||e>0xffffffffffff||n>4095||i>1073741823||s>4294967295)throw new RangeError("invalid field value");var r=new Uint8Array(16);return r[0]=e/Math.pow(2,40),r[1]=e/Math.pow(2,32),r[2]=e/Math.pow(2,24),r[3]=e/Math.pow(2,16),r[4]=e/256,r[5]=e,r[6]=112|n>>>8,r[7]=n,r[8]=128|i>>>24,r[9]=i>>>16,r[10]=i>>>8,r[11]=i,r[12]=s>>>24,r[13]=s>>>16,r[14]=s>>>8,r[15]=s,new gs(r)}toString(){for(var e="",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 gs(this.bytes.slice(0))}equals(e){return this.compareTo(e)===0}compareTo(e){for(var n=0;16>n;n++){var i=this.bytes[n]-e.bytes[n];if(i!==0)return Math.sign(i)}return 0}}class kp{generate(){var e=this.generateOrAbort();if(!x(e))return e;this.S=0;var n=this.generateOrAbort();if(x(n))throw new Error("Could not generate UUID after timestamp reset");return n}generateOrAbort(){var e=Date.now();if(e>this.S)this.S=e,this.C();else{if(this.S>=e+1e4)return;this.I++,this.I>4398046511103&&(this.S++,this.C())}return gs.fromFieldsV7(this.S,Math.trunc(this.I/Math.pow(2,30)),this.I&Math.pow(2,30)-1,this.A.nextUint32())}C(){this.I=1024*this.A.nextUint32()+(1023&this.A.nextUint32())}constructor(){this.S=0,this.I=0,this.A=new Ip}}var fl,Tu=t=>{if(typeof UUIDV7_DENY_WEAK_RNG<"u"&&UUIDV7_DENY_WEAK_RNG)throw new Error("no cryptographically strong RNG available");for(var e=0;t.length>e;e++)t[e]=65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random());return t};_&&!x(_.crypto)&&crypto.getRandomValues&&(Tu=t=>crypto.getRandomValues(t));class Ip{nextUint32(){return this.R.length>this.O||(Tu(this.R),this.O=0),this.R[this.O++]}constructor(){this.R=new Uint32Array(8),this.O=1/0}}var ft=()=>Cp().toString(),Cp=()=>(fl||(fl=new kp)).generate(),Nn="",Ap=/[a-z0-9][a-z0-9-]+\.[a-z]{2,}$/i,mt={N:()=>!!C,j(t){k.error("cookieStore error: "+t)},P:$u,H(t){var e;try{e=JSON.parse(mt.P(t))||{}}catch{}return e},F(t,e,n,i,s){if(!C)return!1;try{var r="",o="",a=(function(c,d){if(d){var h=(function(f,g){if(g===void 0&&(g=C),Nn)return Nn;if(!g||["localhost","127.0.0.1"].includes(f))return"";for(var m=f.split("."),v=Math.min(m.length,8),E="dmn_chk_"+ft();!Nn&&v--;){var w=m.slice(v).join("."),I=E+"=1;domain=."+w+";path=/";g.cookie=I+";max-age=3",g.cookie.includes(E)&&(g.cookie=I+";max-age=0",Nn=w)}return Nn})(c);if(!h){var p=(f=>{var g=f.match(Ap);return g?g[0]:""})(c);p!==h&&k.info("Warning: cookie subdomain discovery mismatch",p,h),h=p}return h?"; domain=."+h:""}return""})(C.location.hostname,i);if(n){var l=new Date;l.setTime(l.getTime()+864e5*n),r="; expires="+l.toUTCString()}s&&(o="; secure");var u=t+"="+encodeURIComponent(JSON.stringify(e))+r+"; SameSite=Lax; path=/"+a+o;return u.length>3686.4&&k.warn("cookieStore warning: large cookie, len="+u.length),C.cookie=u,!0}catch{return!1}},q(t,e){if(C!=null&&C.cookie)try{mt.F(t,"",-1,e)}catch{return}}},_r=null,ee={N(){if(!$e(_r))return _r;var t=!0;if(x(_))t=!1;else try{var e="__mplssupport__";ee.F(e,"xyz"),ee.P(e)!=='"xyz"'&&(t=!1),ee.q(e)}catch{t=!1}return t||k.error("localStorage unsupported; falling back to cookie store"),_r=t,t},j(t){k.error("localStorage error: "+t)},P(t){try{return _?.localStorage.getItem(t)}catch(e){ee.j(e)}return null},H(t){try{return JSON.parse(ee.P(t))||{}}catch{}return null},F(t,e){try{return _?.localStorage.setItem(t,JSON.stringify(e)),!0}catch(n){ee.j(n)}return!1},q(t){try{_?.localStorage.removeItem(t)}catch(e){ee.j(e)}}},Fp=[ai,"distinct_id",hn,ia,hs,ds,He],Fi={},Pp={N:()=>!0,j(t){k.error("memoryStorage error: "+t)},P:t=>Fi[t]||null,H:t=>Fi[t]||null,F:(t,e)=>(Fi[t]=e,!0),q(t){delete Fi[t]}},Bt=null,ce={N(){if(!$e(Bt))return Bt;if(Bt=!0,x(_))Bt=!1;else try{var t="__support__";ce.F(t,"xyz"),ce.P(t)!=='"xyz"'&&(Bt=!1),ce.q(t)}catch{Bt=!1}return Bt},j(t){k.error("sessionStorage error: ",t)},P(t){try{return _?.sessionStorage.getItem(t)}catch(e){ce.j(e)}return null},H(t){try{return JSON.parse(ce.P(t))||null}catch{}return null},F(t,e){try{return _?.sessionStorage.setItem(t,JSON.stringify(e)),!0}catch(n){ce.j(n)}return!1},q(t){try{_?.sessionStorage.removeItem(t)}catch(e){ce.j(e)}}};class $p{constructor(e){this._instance=e}get Ne(){return this._instance.config}get consent(){return this.ti()?0:this.ei}isOptedOut(){return this.Ne.cookieless_mode===gt||this.isRejected()||this.consent===-1&&this.Ne.cookieless_mode===Vt}isOptedIn(){return!this.isOptedOut()}isExplicitlyOptedOut(){return this.consent===0}isRejected(){return this.consent===0||this.consent===-1&&this.Ne.opt_out_capturing_by_default}optInOut(e){this.ii.F(this.ri,e?1:0,this.Ne.cookie_expiration,this.Ne.cross_subdomain_cookie,this.Ne.secure_cookie)}reset(){this.ii.q(this.ri,this.Ne.cross_subdomain_cookie)}get ri(){var e=this._instance.config,n=e.token,i=e.opt_out_capturing_cookie_prefix;return e.consent_persistence_name||(i?i+n:"__ph_opt_in_out_"+n)}get ei(){var e=this.ii.P(this.ri);return cr(e)?1:L(Lh,e)?0:-1}get ii(){var e=this.Ne.opt_out_capturing_persistence_type,n=e==="localStorage"?ee:mt;if(!this.ni||this.ni!==n){this.ni=n;var i=e==="localStorage"?mt:ee;i.P(this.ri)&&(this.ni.P(this.ri)||this.optInOut(cr(i.P(this.ri))),i.q(this.ri,this.Ne.cross_subdomain_cookie))}return this.ni}ti(){return!!this.Ne.respect_dnt&&[ke?.doNotTrack,ke?.msDoNotTrack,R.doNotTrack].some((e=>cr(e)))}}function Ru(t,e){var n,i=t==null||(n=t.config)==null?void 0:n.get_current_url;if(!Se(i))return e;try{var s=i(e);return q(s)&&s?s:e}catch(r){return k.error("Error in get_current_url, falling back to window.location.href",r),e}}var Nu="__POSTHOG_TOOLBAR__",Tp=1,Rp=3,Np=11;function gl(t){return t instanceof Element&&(t.id===Nu||!(t.closest==null||!t.closest(".toolbar-global-fade-container")))}function $t(t){return!!t&&t.nodeType===Tp}function Me(t,e){return!!t&&!!t.tagName&&t.tagName.toLowerCase()===e.toLowerCase()}function Mu(t){return!!t&&t.nodeType===Rp}function Lu(t){return!!t&&t.nodeType===Np&&$t(t.host)}var Ou=1e3;function oa(t){return t?Bs(t).split(/\s+/):[]}function ml(t,e){var n=(function(i){var s,r=_==null||(s=_.location)==null?void 0:s.href;return x(r)?void 0:Ru(i,r)})(e);return!!(n&&t&&t.some((i=>n.match(i))))}function ms(t){var 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 oa(e)}function Bu(t){return B(t)?null:Bs(t).split(/(\s+)/).filter((e=>Qn(e))).join("").replace(/[\r\n]/g," ").replace(/[ ]+/g," ").substring(0,255)}function li(t){var e="";return vo(t)&&!Hu(t)&&t.childNodes&&t.childNodes.length&&Z(t.childNodes,(function(n){var i;Mu(n)&&n.textContent&&(e+=(i=Bu(n.textContent))!==null&&i!==void 0?i:"")})),Bs(e)}function yr(t){var e;return x(t.target)?t.srcElement||null:(e=t.target)!=null&&e.shadowRoot?t.composedPath()[0]||null:t.target||null}var aa=["a","button","form","input","select","textarea","label"];function mo(t,e){if(x(e))return!0;var n,i=function(r){if(e.some((o=>(function(a,l){var u=a.matches||a.matchesSelector||a.msMatchesSelector||a.mozMatchesSelector||a.webkitMatchesSelector||a.oMatchesSelector;try{return!!u&&u.call(a,l)}catch{return!1}})(r,o))))return{v:!0}};for(var s of t)if(n=i(s))return n.v;return!1}function Du(t){var e=t.parentNode;return!(!e||!$t(e))&&e}var Mp=[".ph-no-autocapture","[data-ph-no-autocapture]"],ju=["next","previous","prev",">","<"],Lp=[...ju,"+","-","−","–"],vl=(t,e)=>/[a-z0-9]/i.test(e)?t.includes(e):t===e,_l=[".ph-no-rageclick",".ph-no-capture"],Op=["","text","search","email","password","url","tel","number"];function yl(t,e){if(!_||la(t))return!1;var n,i,s,r,o;if(Ye(e)?(n=!!e&&_l,i=void 0,s=!1):(n=(r=e?.css_selector_ignorelist)!==null&&r!==void 0?r:_l,i=e?.content_ignorelist,s=(o=e?.ignore_text_selection)!==null&&o!==void 0&&o),n===!1||s&&(function(l){return!(!l||!$t(l))&&(!!Me(l,"textarea")||(Me(l,"input")?L(Op,(l.getAttribute("type")||"").toLowerCase()):(function(u){if(u.isContentEditable)return!0;var c=u.getAttribute==null?void 0:u.getAttribute("contenteditable");return c==="true"||c===""})(l)))})(t))return!1;var a=Uu(t,!1).targetElementList;return!(function(l,u){if(l===!1||x(l))return!1;var c;if(l===!0)c=ju;else{if(!O(l))return!1;if(l.length>10)return k.error("[PostHog] content_ignorelist array cannot exceed 10 items. Use css_selector_ignorelist for more complex matching."),!1;c=l.map((d=>d.toLowerCase()))}return u.some((d=>{var h=d.safeText,p=d.ariaLabel;return c.some((f=>vl(h,f)||vl(p,f)))}))})(i,a.map((l=>{var u;return{safeText:li(l).toLowerCase(),ariaLabel:((u=l.getAttribute("aria-label"))==null?void 0:u.toLowerCase().trim())||""}})))&&!mo(a,n)}var la=t=>!t||Me(t,"html")||!$t(t),Uu=(t,e)=>{if(!_||la(t))return{parentIsUsefulElement:!1,targetElementList:[]};for(var n=!1,i=[t],s=t;s.parentNode&&!Me(s,"body");)if(Lu(s.parentNode))i.push(s.parentNode.host),s=s.parentNode.host;else{var r=Du(s);if(!r)break;if(e||aa.indexOf(r.tagName.toLowerCase())>-1)n=!0;else try{var o=_.getComputedStyle(r);o&&o.getPropertyValue("cursor")==="pointer"&&(n=!0)}catch{}i.push(r),s=r}return{parentIsUsefulElement:n,targetElementList:i}};function vo(t){for(var e=new Set,n=0,i=t;i.parentNode&&!Me(i,"body");i=i.parentNode){if(n++>=Ou||e.has(i))return!1;e.add(i);var s=ms(i);if(L(s,"ph-sensitive")||L(s,"ph-no-capture"))return!1}if(L(ms(t),"ph-include"))return!0;var r=t.type||"";if(q(r))switch(r.toLowerCase()){case"hidden":case"password":return!1}var o=t.name||t.id||"";return!q(o)||!/^cc|cardnum|ccnum|creditcard|csc|cvc|cvv|exp|pass|pwd|routing|seccode|securitycode|securitynum|socialsec|socsec|ssn/i.test(o.replace(/[^a-zA-Z0-9]/g,""))}function Hu(t){return!!(Me(t,"input")&&!["button","checkbox","submit","reset"].includes(t.type)||Me(t,"select")||Me(t,"textarea")||t.getAttribute("contenteditable")==="true")}var wl=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}))$"),bl=/(^|[^0-9A-Za-z_])([0-9][0-9 -]*[0-9])(?=$|[^0-9A-Za-z_])/g,Bp=[16,15,14,13],Dp=new RegExp("^(\\d{3}-?\\d{2}-?\\d{4})$"),El=new RegExp("(^|[^0-9])((?!000|666)[0-9]{3}-?(?!00)[0-9]{2}-?(?!0000)[0-9]{4})(?=$|([^0-9]))","g"),Sl=/[0-9A-Za-z_]/;function jp(t){for(var e=0,n=!1,i=t.length-1;i>=0;i--){var s=t.charCodeAt(i)-48;n&&(s*=2)>9&&(s-=9),e+=s,n=!n}return e%10==0}function Qn(t,e){if(e===void 0&&(e=!0),B(t))return!1;if(q(t)){t=Bs(t);var n=e?wl.test((t||"").replace(/[- ]/g,"")):(function(s){var r;for(bl.lastIndex=0;r=bl.exec(s);){var o=r[2];if(o)for(var a=o.replace(/[- ]/g,""),l=0;a.length>l;l++)for(var u of Bp){var c=l+u;if(a.length>=c){var d=a.slice(l,c);if(wl.test(d)&&jp(d))return!0}}}return!1})(t);if(n)return!1;var i=e?Dp.test(t):(function(s){var r;for(El.lastIndex=0;r=El.exec(s);){var o=r[1],a=r[3];if(!(o&&a&&Sl.test(o)&&Sl.test(a)))return!0}return!1})(t);if(i)return!1}return!0}function xl(t){var e=li(t);return Qn(e=(e+" "+Wu(t)).trim())?e:""}function Wu(t){var e="";return t&&t.childNodes&&t.childNodes.length&&Z(t.childNodes,(function(n){var i;if(n&&((i=n.tagName)==null?void 0:i.toLowerCase())==="span")try{var s=li(n);e=(e+" "+s).trim(),n.childNodes&&n.childNodes.length&&(e=(e+" "+Wu(n)).trim())}catch(r){k.error("[AutoCapture]",r)}})),e}function kl(t){return t.replace(/"|\\"/g,'\\"')}function Up(t){var e=t.attr__class;if(e)return O(e)?e:oa(e)}var Pi=ie("[Dead Clicks]"),Hp=()=>!0,Wp=t=>{var e,n=!((e=t.instance.persistence)==null||!e.get_property(ta)),i=t.instance.config.capture_dead_clicks;return Ye(i)?i:!!ne(i)||n};class Il{get lazyLoadedDeadClicksAutocapture(){return this.si}constructor(e,n,i){this.instance=e,this.isEnabled=n,this.onCapture=i,this.startIfEnabledOrStop()}onRemoteConfig(e){if(e.ok){var n=e.config;"captureDeadClicks"in n&&(this.instance.persistence&&this.instance.persistence.register({[ta]:n.captureDeadClicks}),this.startIfEnabledOrStop())}}startIfEnabledOrStop(){this.isEnabled(this)?this.ai((()=>{this.oi()})):this.stop()}ai(e){var n,i;(n=R.__PosthogExtensions__)!=null&&n.initDeadClicksAutocapture?e():(i=R.__PosthogExtensions__)==null||i.loadExternalDependency==null||i.loadExternalDependency(this.instance,"dead-clicks-autocapture",(s=>{s?Pi.error("failed to load script",s):e()}))}oi(){var e;if(C){if(!this.si&&(e=R.__PosthogExtensions__)!=null&&e.initDeadClicksAutocapture){var n=ne(this.instance.config.capture_dead_clicks)?b({},this.instance.config.capture_dead_clicks):{};n.__onCapture=this.onCapture,this.onCapture&&(n.capture_dead_swipes=!1),this.si=R.__PosthogExtensions__.initDeadClicksAutocapture(this.instance,n),this.si.start(C),Pi.info("starting...")}}else Pi.error("`document` not found. Cannot start.")}stop(){this.si&&(this.si.stop(),this.si=void 0,Pi.info("stopping..."))}}var wr=ie("[SegmentIntegration]"),zu="posthog-js";function qu(t,e){var n=e===void 0?{}:e,i=n.organization,s=n.projectId,r=n.prefix,o=n.severityAllowList,a=o===void 0?["error"]:o,l=n.sendExceptionsToPostHog,u=l===void 0||l;return c=>{var d,h,p,f,g;if(a!=="*"&&!a.includes(c.level)||!t.__loaded)return c;c.tags||(c.tags={});var m=t.requestRouter.endpointFor("ui","/project/"+t.config.token+"/person/"+t.get_distinct_id());c.tags["PostHog Person URL"]=m,t.sessionRecordingStarted()&&(c.tags["PostHog Recording URL"]=t.get_session_replay_url({withTimestamp:!0}));var v,E=((d=c.exception)==null?void 0:d.values)||[],w=E.map((A=>b({},A,{stacktrace:A.stacktrace?b({},A.stacktrace,{type:"raw",frames:(A.stacktrace.frames||[]).map((F=>b({},F,{platform:"web:javascript"})))}):void 0}))),I={$exception_message:((h=E[0])==null?void 0:h.value)||c.message,$exception_type:(p=E[0])==null?void 0:p.type,$exception_level:c.level,$exception_list:w,$sentry_event_id:c.event_id,$sentry_exception:c.exception,$sentry_exception_message:((f=E[0])==null?void 0:f.value)||c.message,$sentry_exception_type:(g=E[0])==null?void 0:g.type,$sentry_tags:c.tags};return i&&s&&(I.$sentry_url=(r||"https://sentry.io/organizations/")+i+"/issues/?project="+s+"&query="+c.event_id),u&&((v=t.exceptions)==null||v.sendExceptionEvent(I)),c}}class zp{constructor(e,n,i,s,r,o){this.name=zu,this.setupOnce=function(a){a(qu(e,{organization:n,projectId:i,prefix:s,severityAllowList:r,sendExceptionsToPostHog:o==null||o}))}}}class Cl{constructor(e){this.li=(n,i,s)=>{s&&(s.noSessionId||s.activityTimeout||s.sessionPastMaximumLength||s.crossTabAdoption)&&(k.info("[PageViewManager] Session rotated, clearing pageview state",{sessionId:n,changeReason:s}),this.ui=void 0,this._instance.scrollManager.resetContext())},this._instance=e,this.hi()}hi(){var e;this.di=(e=this._instance.sessionManager)==null?void 0:e.onSessionId(this.li)}destroy(){var e;(e=this.di)==null||e.call(this),this.di=void 0}doPageView(e,n){var i,s=this.vi(e,n);return this.ui={pathname:(i=_?.location.pathname)!==null&&i!==void 0?i:"",pageViewId:n,timestamp:e},this._instance.scrollManager.resetContext(),s}doPageLeave(e){var n;return this.vi(e,(n=this.ui)==null?void 0:n.pageViewId)}doEvent(){var e;return{$pageview_id:(e=this.ui)==null?void 0:e.pageViewId}}vi(e,n){var i=this.ui;if(!i)return{$pageview_id:n};var s={$pageview_id:n,$prev_pageview_id:i.pageViewId},r=this._instance.scrollManager.getContext();if(r&&!this._instance.config.disable_scroll_properties){var o=r.maxScrollHeight,a=r.lastScrollY,l=r.maxScrollY,u=r.maxContentHeight,c=r.lastContentY,d=r.maxContentY;if(!(x(o)||x(a)||x(l)||x(u)||x(c)||x(d))){o=Math.ceil(o),a=Math.ceil(a),l=Math.ceil(l),u=Math.ceil(u),c=Math.ceil(c),d=Math.ceil(d);var h=o>1?ot(a/o,0,1,k):1,p=o>1?ot(l/o,0,1,k):1,f=u>1?ot(c/u,0,1,k):1,g=u>1?ot(d/u,0,1,k):1;s=te(s,{$prev_pageview_last_scroll:a,$prev_pageview_last_scroll_percentage:h,$prev_pageview_max_scroll:l,$prev_pageview_max_scroll_percentage:p,$prev_pageview_last_content:c,$prev_pageview_last_content_percentage:f,$prev_pageview_max_content:d,$prev_pageview_max_content_percentage:g})}}return i.pathname&&(s.$prev_pageview_pathname=i.pathname),i.timestamp&&(s.$prev_pageview_duration=(e.getTime()-i.timestamp.getTime())/1e3),s}}var br=["flags","surveys"],qp={[bu]:{exposure:"hidden"},[zn]:{exposure:"hidden"},__cmpns:{exposure:"hidden"},[qn]:{exposure:"hidden"},[Qr]:{exposure:"event"},[eo]:{exposure:"hidden"},[to]:{exposure:"event"},[no]:{exposure:"hidden"},[io]:{exposure:"event"},[so]:{exposure:"event"},[ta]:{exposure:"event"},[na]:{exposure:"hidden"},[ro]:{exposure:"event"},[Jt]:{exposure:"hidden"},$session_recording_enabled_server_side:{exposure:"hidden"},[hn]:{exposure:"hidden"},[ia]:{exposure:"event"},[Eu]:{exposure:"event",shouldSkipFromEventProperties:t=>$e(t)},$session_past_minimum_duration:{exposure:"event"},$session_recording_url_trigger_activated_session:{exposure:"event"},$session_recording_event_trigger_activated_session:{exposure:"event"},$debug_first_full_snapshot_timestamp:{exposure:"event"},$sess_rec_flush_size:{exposure:"hidden"},[Wt]:{exposure:"hidden",storageGroup:"flags"},[Vn]:{exposure:"hidden",storageGroup:"flags"},[ji]:{exposure:"hidden"},[oo]:{exposure:"hidden",storageGroup:"flags"},[Gn]:{exposure:"hidden",storageGroup:"flags"},[Ui]:{exposure:"hidden",storageGroup:"flags",volatile:!0},[cs]:{exposure:"hidden",storageGroup:"flags"},[it]:{exposure:"hidden"},[zt]:{exposure:"hidden"},[ht]:{exposure:"hidden"},[qt]:{exposure:"hidden"},[ao]:{exposure:"hidden",storageGroup:"surveys"},[us]:{exposure:"hidden",storageGroup:"surveys",volatile:!0},[lo]:{exposure:"event"},[Hi]:{exposure:"hidden"},[Wi]:{exposure:"hidden"},[Kn]:{exposure:"hidden"},$product_tours_activated:{exposure:"hidden"},$product_tours_activated_session:{exposure:"hidden"},$conversations_widget_session_id:{exposure:"event"},$conversations_ticket_id:{exposure:"event"},$conversations_widget_state:{exposure:"event"},$conversations_user_traits:{exposure:"event"},[Gt]:{exposure:"hidden"},[Jn]:{exposure:"hidden"},[zi]:{exposure:"hidden"},[Xn]:{exposure:"hidden",storageGroup:"flags",volatile:!0},[He]:{exposure:"hidden"},[co]:{exposure:"hidden"},[uo]:{exposure:"hidden"},[ho]:{exposure:"hidden"},[po]:{exposure:"hidden"},[ds]:{exposure:"hidden"},[hs]:{exposure:"hidden"},[Su]:{exposure:"event"},[xu]:{exposure:"event"},[ku]:{exposure:"event"},[Iu]:{exposure:"event"},[Au]:{exposure:"event"},[Fu]:{exposure:"event"},[Pu]:{exposure:"event"},$sdk_debug_replay_event_trigger_status:{exposure:"event"},$sdk_debug_replay_linked_flag_trigger_status:{exposure:"event"},$sdk_debug_replay_matched_recording_trigger_groups:{exposure:"event"},$sdk_debug_replay_remote_trigger_matching_config:{exposure:"event"},$sdk_debug_replay_trigger_groups_count:{exposure:"event"},$sdk_debug_replay_url_trigger_status:{exposure:"event"},$session_recording_start_reason:{exposure:"event"}},Vp=[["$posthog_sr_group_event_trigger_",{exposure:"hidden"}],["$posthog_sr_group_url_trigger_",{exposure:"hidden"}],["$posthog_sr_group_sampling_",{exposure:"hidden"}]],Dt=t=>{var e=qp[t];if(e)return e;for(var n of Vp){var i=n[1];if(t.indexOf(n[0])===0)return i}},pn=(t,e)=>{try{return JSON.stringify(t,((n,i)=>typeof i=="bigint"?i.toString():i),e)}catch{return Hc(t)}},vs=t=>{var e=C?.createElement("a");return x(e)?null:(e.href=t,e)},wn=function(t,e){for(var n,i=((t.split("#")[0]||"").split(/\?(.*)/)[1]||"").replace(/^\?+/g,"").split("&"),s=0;i.length>s;s++){var r=i[s].split("=");if(r[0]===e){n=r;break}}if(!O(n)||2>n.length)return"";var o=n[1];try{o=decodeURIComponent(o)}catch{k.error("Skipping decoding for malformed query param: "+o)}return o.replace(/\+/g," ")},ci=function(t,e,n){if(!t||!e||!e.length)return t;for(var i=t.split("#"),s=i[1],r=(i[0]||"").split("?"),o=r[1],a=r[0],l=(o||"").split("&"),u=[],c=0;l.length>c;c++){var d=l[c].split("=");O(d)&&(e.includes(d[0])?u.push(d[0]+"="+n):u.push(l[c]))}var h=a;return o!=null&&(h+="?"+u.join("&")),s!=null&&(h+="#"+s),h},_s=function(t,e){var n=t.match(new RegExp(e+"=([^&]*)"));return n?n[1]:null},Vu=(t,e)=>t>=e&&Dc(),Gu=(t,e,n,i)=>{if(t===0){if(Dc()){var s=e+1;return s===n&&i(),s}return e}return 0},$i="https?://(.*)",bn=["gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","irclid","_kx"],Gp=["utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid",...bn],ui="",Kp=["li_fat_id"];function Ku(t,e,n){if(!C)return{};var i,s=e?[...bn,...n||[]]:[],r=Ju(ci(C.URL,s,ui),t),o=(i={},Z(Kp,(function(a){var l=$u(a);i[a]=l||null})),i);return te(o,r)}function Ju(t,e){var n=Gp.concat(e||[]),i={};return Z(n,(function(s){var r=wn(t,s);i[s]=r||null})),i}function Yu(t){var e=(function(r){return r?r.search($i+"google.([^/?]*)")===0?"google":r.search($i+"bing.com")===0?"bing":r.search($i+"yahoo.com")===0?"yahoo":r.search($i+"duckduckgo.com")===0?"duckduckgo":null:null})(t),n=e!="yahoo"?"q":"p",i={};if(!$e(e)){i.$search_engine=e;var s=C?wn(C.referrer,n):"";s.length&&(i.ph_keyword=s)}return i}function Al(){return navigator.language||navigator.userLanguage}var ys="$direct";function Zu(){return C?.referrer||ys}function Xu(t,e,n){n===void 0&&(n=!1);var i=t?[...bn,...e||[]]:[],s=n?Pt(se?.href):se?.href,r=s?.substring(0,1e3);return{r:Zu().substring(0,1e3),u:r?ci(r,i,ui):void 0}}function Qu(t,e){var n;e===void 0&&(e=!1);var i=t.r,s=t.u,r=e?Pt(s):s,o={$referrer:i,$referring_domain:i==null?void 0:i==ys?ys:(n=vs(i))==null?void 0:n.host};if(r){o.$current_url=r;var a=vs(r);o.$host=a?.host,o.$pathname=a?.pathname;var l=Ju(r);te(o,l)}if(i){var u=Yu(i);te(o,u)}return o}function ed(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return}}function Jp(){try{return new Date().getTimezoneOffset()}catch{return}}var Yp={flags:Xn,surveys:us},Zp=["cookie","localstorage","localstorage+cookie","sessionstorage","memory"],rn="main";class Er{constructor(e,n,i){if(i===void 0&&(i=!0),this.ci={},this.fi=!1,this.pi=!1,this.Ne=e,this.gi=i,this.props={},this.mi=void 0,this.yi=(r=>{var o="";return r.token&&(o=r.token.replace(/\+/g,"PL").replace(/\//g,"SL").replace(/=/g,"EQ")),r.persistence_name?"ph_"+r.persistence_name:"ph_"+o+"_posthog"})(e),this.ii=this.bi(e),this.pi=this.wi(e),this.load(),e.debug&&k.info("Persistence loaded",e.persistence,b({},this.props)),this.update_config(e,e,n),this.save(),_){var s=()=>this.flush();re(_,"beforeunload",s,{capture:!1}),re(_,"pagehide",s,{capture:!1})}}ki(){var e,n=(e=this.Ne)==null?void 0:e.persistence_save_debounce_ms;return he(n)&&n>0?n:0}isDisabled(){return!!this.xi}bi(e){Zp.indexOf(e.persistence.toLowerCase())===-1&&(k.critical("Unknown persistence type "+e.persistence+"; falling back to localStorage+cookie"),e.persistence="localStorage+cookie");var n,i=(function(o,a){o===void 0&&(o=[]),a===void 0&&(a=!1);var l=[...Fp,...o];return b({},ee,{H(u){try{var c={};try{c=mt.H(u)||{}}catch{}var d,h=JSON.parse(ee.P(u)||"{}");if(a){var p={};for(var f in c){var g=c[f];$e(g)||g===""||(p[f]=g)}d=te(h,p)}else d=te(c,h);return ee.F(u,d),d}catch{}return null},F(u,c,d,h,p,f){var g=ee.F(u,c,void 0,void 0,f);try{var m={};l.forEach((v=>{c[v]&&(m[v]=c[v])})),Object.keys(m).length&&mt.F(u,m,d,h,p,f)}catch(v){ee.j(v)}return g},q(u,c){try{_?.localStorage.removeItem(u),mt.q(u,c)}catch(d){ee.j(d)}}})})(e.cookie_persisted_properties||[],e.__preview_cookie_wins_on_conflict||!1),s=!1,r=e.persistence.toLowerCase();return r==="localstorage"&&ee.N()?(n=ee,s=!0):r==="localstorage+cookie"&&i.N()?(n=i,s=!0):r==="sessionstorage"&&ce.N()?n=ce:r==="memory"?n=Pp:r==="cookie"?n=mt:i.N()?(n=i,s=!0):n=mt,this.fi=s,n}Si(e){return this.yi+"__"+e}wi(e){return this.fi&&!!e.split_storage}properties(){var e={};return Z(this.props,((n,i)=>{var s=Dt(i);if(!s||s.exposure==="event"){if(s!=null&&s.shouldSkipFromEventProperties!=null&&s.shouldSkipFromEventProperties(n))return;e[i]=n}})),e}load(){if(!this.xi){var e=this.ii.H(this.yi);e&&(this.props=te({},e)),this.pi&&this.Ci()}}Ci(){for(var e of br){var n=ee.H(this.Si(e));if(n&&!yt(n)){var i=this.Mi(e);i.persisted=!0,this.Ti(e)||(i.fingerprint=this.Ei(n,e)),this.Ii(e,n)||te(this.props,n)}}}Ti(e){return Object.keys(this.props).some((n=>{var i;return((i=Dt(n))==null?void 0:i.storageGroup)===e}))}Ii(e,n){var i=Yp[e];if(!i)return!1;var s=n[i],r=this.props[i];return he(s)&&he(r)&&r>s}refreshKey(e){var n;if(!this.xi){var i=this.pi?(n=Dt(e))==null?void 0:n.storageGroup:void 0,s=i?ee.H(this.Si(i)):this.ii.H(this.yi);if(s&&e in s)this.Pi(e,s[e]);else{if(i){var r=this.ii.H(this.yi);if(r&&e in r)return void this.Pi(e,r[e])}this.Ri(e)}}}save(){if(!this.xi){var e=this.ki();e>0?x(this.Ai)&&(this.Ai=setTimeout((()=>{this.Ai=void 0,this.Fi()}),e)):this.Fi()}}flush(){x(this.Ai)||(clearTimeout(this.Ai),this.Ai=void 0,this.Fi())}Fi(){this.xi||(this.pi?this.Li():this.Oi(this.ii,this.yi,this.props,rn))}Li(){var e=this.Di(),n=e.main,i=e.groups;for(var s of(this.Oi(this.ii,this.yi,n,rn),br)){var r,o=i[s];(!yt(o)||(r=this.ci[s])!=null&&r.persisted)&&this.Oi(ee,this.Si(s),o,s)}}Di(){var e={},n={flags:{},surveys:{}};return Z(this.props,((i,s)=>{var r,o=(r=Dt(s))==null?void 0:r.storageGroup;o?n[o][s]=i:e[s]=i})),{main:e,groups:n}}Ei(e,n){if(n===rn)return JSON.stringify(e)+"|"+this.$i+"|"+this.Ni+"|"+this.qi;var i={};return Z(e,((s,r)=>{var o;i[r]=(o=Dt(r))!=null&&o.volatile?"__volatile__":s})),JSON.stringify(i)}Oi(e,n,i,s){var r=this.Mi(s);if(s===rn||r.dirty||x(r.fingerprint)){var o;try{if((o=this.Ei(i,s))===r.fingerprint)return void(r.dirty=!1)}catch{o=void 0}e.F(n,i,this.$i,this.Ni,this.qi,this.Ne.debug)?(r.dirty=!1,s!==rn&&(r.persisted=!0),x(o)||(r.fingerprint=o)):this.Ne.debug&&k.warn('failed to persist storage entry "'+n+'"; will retry on next save')}}remove(e){var n=(e===void 0?{}:e).keepGroupEntries,i=n!==void 0&&n;if(x(this.Ai)||(clearTimeout(this.Ai),this.Ai=void 0),this.ii.q(this.yi,!1),this.ii.q(this.yi,!0),!i&&this.gi)for(var s of br)ee.q(this.Si(s));i?delete this.ci[rn]:this.ci={}}clear(){this.remove(),this.props={}}register_once(e,n,i){if(ne(e)){x(n)&&(n="None"),this.$i=x(i)?this.ji:i;var s=!1;if(Z(e,((r,o)=>{this.props.hasOwnProperty(o)&&this.props[o]!==n||(this.Pi(o,r),s=!0)})),s)return this.save(),!0}return!1}register(e,n){if(ne(e)){this.$i=x(n)?this.ji:n;var i=!1;if(Z(e,((s,r)=>{e.hasOwnProperty(r)&&(this.props[r]!==s||ne(s)||O(s))&&(this.Pi(r,s),i=!0)})),i)return this.save(),!0}return!1}unregister(e){var n=typeof e=="string"?[e]:e,i=!1;for(var s of n)s in this.props&&(this.Ri(s),i=!0);i&&this.save()}update_campaign_params(){var e=C?.URL;if(e!==this.mi){var n=Ku(this.Ne.custom_campaign_params,this.Ne.mask_personal_data_properties,this.Ne.custom_personal_data_properties);yt(ra(n))||this.register(n),this.mi=e}}update_search_keyword(){var e;this.register((e=C?.referrer)?Yu(e):{})}update_referrer_info(){var e;this.register_once({$referrer:Zu(),$referring_domain:C!=null&&C.referrer&&((e=vs(C.referrer))==null?void 0:e.host)||ys},void 0)}set_initial_person_info(){this.props[ho]||this.props[po]||this.register_once({[ds]:Xu(this.Ne.mask_personal_data_properties,this.Ne.custom_personal_data_properties,this.Ne.disable_capture_url_hashes)},void 0)}get_initial_props(){var e={};Z([po,ho],(s=>{var r=this.props[s];r&&Z(r,(function(o,a){e["$initial_"+Vr(a)]=o}))}));var n=this.props[ds];if(n){var i=(function(s,r){r===void 0&&(r=!1);var o=Qu(s,r),a={};return Z(o,(function(l,u){a["$initial_"+Vr(u)]=l})),a})(n,this.Ne.disable_capture_url_hashes);te(e,i)}return e}safe_merge(e){return Z(this.props,(function(n,i){i in e||(e[i]=n)})),e}update_config(e,n,i){this.ji=this.$i=e.cookie_expiration,this.set_disabled(e.disable_persistence||!!i),this.set_cross_subdomain(e.cross_subdomain_cookie),this.set_secure(e.secure_cookie);var s=e.persistence!==n.persistence||!((l,u)=>{if(l.length!==u.length)return!1;var c=[...l].sort(),d=[...u].sort();return c.every(((h,p)=>h===d[p]))})(e.cookie_persisted_properties||[],n.cookie_persisted_properties||[]),r=s?this.bi(e):this.ii,o=this.wi(e);if(s||o!==this.pi){var a=this.props;this.clear(),this.ii=r,this.pi=o,this.props=a,this.save()}}set_disabled(e){this.xi=e,this.xi?this.remove():this.save()}set_cross_subdomain(e){e!==this.Ni&&(this.Ni=e,this.remove({keepGroupEntries:!0}),this.save())}set_secure(e){e!==this.qi&&(this.qi=e,this.remove({keepGroupEntries:!0}),this.save())}set_event_timer(e,n){var i=this.props[qn]||{};i[e]=n,this.Pi(qn,i),this.save()}remove_event_timer(e){var n=this.props[qn]||{},i=n[e];return x(i)||(delete n[e],this.Pi(qn,n),this.save()),i}get_property(e){return this.props[e]}set_property(e,n){this.Pi(e,n),this.save()}Pi(e,n){var i;this.props[e]=n,(i=Dt(e))!=null&&i.volatile||this.Bi(e)}Ri(e){delete this.props[e],this.Bi(e)}Bi(e){var n,i=(n=Dt(e))==null?void 0:n.storageGroup;i&&(this.Mi(i).dirty=!0)}Mi(e){return this.ci[e]||(this.ci[e]={})}}function Ti(t){var e=!0;return{dispose(){if(e){e=!1;var n=t();n&&Se(n.then)&&n.then(void 0,(()=>{}))}}}}var xe={GZipJS:"gzip-js",Base64:"base64"},Mn={Activation:"events",Cancellation:"cancelEvents"},Sr={Popover:"popover",API:"api",Widget:"widget"},vt={SHOWN:"survey shown",DISMISSED:"survey dismissed",SENT:"survey sent"},xr={SURVEY_ID:"$survey_id",SURVEY_ITERATION:"$survey_iteration",SURVEY_LAST_SEEN_DATE:"$survey_last_seen_date"},_o={Popover:"popover",Inline:"inline"},Xp={SHOWN:"product tour shown"},Fl={TOUR_LAST_SEEN_DATE:"$product_tour_last_seen_date",TOUR_TYPE:"$product_tour_type"},Pl=ie("[RateLimiter]");class Qp{constructor(e){this.serverLimits={},this.lastEventRateLimited=!1,this.checkForLimiting=n=>{var i=n.text;if(i&&i.length)try{(JSON.parse(i).quota_limited||[]).forEach((s=>{Pl.info((s||"events")+" is quota limited."),this.serverLimits[s]=new Date().getTime()+6e4}))}catch(s){return void Pl.warn('could not rate limit - continuing. Error: "'+s?.message+'"',{text:i})}},this.instance=e,this.lastEventRateLimited=this.clientRateLimitContext(!0).isRateLimited}get captureEventsPerSecond(){var e;return((e=this.instance.config.rate_limiting)==null?void 0:e.events_per_second)||10}get captureEventsBurstLimit(){var e;return Math.max(((e=this.instance.config.rate_limiting)==null?void 0:e.events_burst_limit)||10*this.captureEventsPerSecond,this.captureEventsPerSecond)}clientRateLimitContext(e){var n,i,s;e===void 0&&(e=!1);var r=this.captureEventsBurstLimit,o=this.captureEventsPerSecond,a=new Date().getTime(),l=(n=(i=this.instance.persistence)==null?void 0:i.get_property(uo))!==null&&n!==void 0?n:{tokens:r,last:a};l.tokens+=(a-l.last)/1e3*o,l.last=a,l.tokens>r&&(l.tokens=r);var u=1>l.tokens;if(u||e||(l.tokens=Math.max(0,l.tokens-1)),u&&!e){var c=(he(l.dropped)?l.dropped:0)+1;l.dropped=c,!this.lastEventRateLimited&&this.Hi(c)&&(l.dropped=0)}return this.lastEventRateLimited=u,(s=this.instance.persistence)==null||s.set_property(uo,l),{isRateLimited:u,remainingTokens:l.tokens}}Ui(e){var n=this.instance.config.property_denylist;return!O(n)||!n.includes(e)}zi(){var e;if(this.Ui("$current_url")&&this.Ui("$pathname")&&se!=null&&se.pathname)return""+((e=se.origin)!==null&&e!==void 0?e:"")+se.pathname}Hi(e){var n,i,s=this.captureEventsBurstLimit,r=this.captureEventsPerSecond,o=this.zi(),a=this.Ui("$session_id")?(n=(i=this.instance).get_session_id)==null?void 0:n.call(i):void 0,l=[e+" event(s) dropped since the last warning",o?"triggered on "+o:void 0,a?"session "+a: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 "+r+" events per second and "+s+" events burst limit."},{skip_client_rate_limiting:!0})}isServerRateLimited(e){var n=this.serverLimits[e||"events"]||!1;return n!==!1&&new Date().getTime()e(this.remoteConfig))):e()}Vi(e){this._instance._send_request({method:"GET",url:this._instance.requestRouter.endpointFor("assets","/array/"+this._instance.config.token+"/config"),callback:e})}load(){try{if(this.remoteConfig)return Ct.info("Using preloaded remote config",this.remoteConfig),this.Zi(this.remoteConfig),void this.Gi();if(this._instance.Qi())return void Ct.warn("Remote config is disabled. Falling back to local config.");this.Wi((e=>{if(!e)return Ct.info("No config found after loading remote JS config. Falling back to JSON."),void this.Vi((n=>{this.Zi(n.json,n),this.Gi()}));this.Zi(e),this.Gi()}))}catch(e){Ct.error("Error loading remote config",e),this.Zi()}}stop(){this.Ki&&(clearInterval(this.Ki),this.Ki=void 0)}refresh(){!this._instance.Qi()&&C&&C.visibilityState!=="hidden"&&this._instance.reloadFeatureFlags()}Gi(){var e;if(!this.Ki){var n=(e=this._instance.config.remote_config_refresh_interval_ms)!==null&&e!==void 0?e:3e5;n!==0&&(this.Ki=setInterval((()=>{this.refresh()}),n))}}Zi(e,n){!e&&n&&(n.statusCode===0?n.error||Ct.warn("Failed to fetch remote config from PostHog."):Ct.error("Failed to fetch remote config from PostHog."));try{this._instance.Zi(e?{ok:!0,config:e}:{ok:!1})}catch(s){Ct.error("Error applying remote config",s)}if(e?.hasFeatureFlags!==!1&&!this._instance.config.advanced_disable_feature_flags_on_first_load)try{var i;(i=this._instance.featureFlags)==null||i.ensureFlagsLoaded()}catch(s){Ct.error("Error loading feature flags",s)}}}var qe=Uint8Array,Pe=Uint16Array,En=Uint32Array,ca=new qe([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]),ua=new qe([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]),$l=new qe([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),nd=function(t,e){for(var n=new Pe(31),i=0;31>i;++i)n[i]=e+=1<i;++i)for(var r=n[i];n[i+1]>r;++r)s[r]=r-n[i]<<5|i;return[n,s]},id=nd(ca,2),yo=id[1];id[0][28]=258,yo[258]=28;for(var Tl=nd(ua,0)[1],sd=new Pe(32768),oe=0;32768>oe;++oe){var on=(43690&oe)>>>1|(21845&oe)<<1;sd[oe]=((65280&(on=(61680&(on=(52428&on)>>>2|(13107&on)<<2))>>>4|(3855&on)<<4))>>>8|(255&on)<<8)>>>1}var ei=function(t,e,n){for(var i=t.length,s=0,r=new Pe(e);i>s;++s)++r[t[s]-1];var o,a=new Pe(e);for(s=0;e>s;++s)a[s]=a[s-1]+r[s-1]<<1;for(o=new Pe(i),s=0;i>s;++s)o[s]=sd[a[t[s]-1]++]>>>15-t[s];return o},Xt=new qe(288);for(oe=0;144>oe;++oe)Xt[oe]=8;for(oe=144;256>oe;++oe)Xt[oe]=9;for(oe=256;280>oe;++oe)Xt[oe]=7;for(oe=280;288>oe;++oe)Xt[oe]=8;var ws=new qe(32);for(oe=0;32>oe;++oe)ws[oe]=5;var ef=ei(Xt,9),tf=ei(ws,5),rd=function(t){return(t/8>>0)+(7&t&&1)},od=function(t,e,n){(n==null||n>t.length)&&(n=t.length);var i=new(t instanceof Pe?Pe:t instanceof En?En:qe)(n-e);return i.set(t.subarray(e,n)),i},ct=function(t,e,n){var i=e/8>>0;t[i]|=n<<=7&e,t[i+1]|=n>>>8},Ln=function(t,e,n){var i=e/8>>0;t[i]|=n<<=7&e,t[i+1]|=n>>>8,t[i+2]|=n>>>16},kr=function(t,e){for(var n=[],i=0;t.length>i;++i)t[i]&&n.push({s:i,f:t[i]});var s=n.length,r=n.slice();if(!s)return[new qe(0),0];if(s==1){var o=new qe(n[0].s+1);return o[n[0].s]=1,[o,1]}n.sort((function(A,F){return A.f-F.f})),n.push({s:-1,f:25001});var a=n[0],l=n[1],u=0,c=1,d=2;for(n[0]={s:-1,f:a.f+l.f,l:a,r:l};c!=s-1;)a=n[n[d].f>n[u].f?u++:d++],l=n[u!=c&&n[d].f>n[u].f?u++:d++],n[c++]={s:-1,f:a.f+l.f,l:a,r:l};var h=r[0].s;for(i=1;s>i;++i)r[i].s>h&&(h=r[i].s);var p=new Pe(h+1),f=wo(n[c-1],p,0);if(f>e){i=0;var g=0,m=f-e,v=1<i;++i){var E=r[i].s;if(e>=p[E])break;g+=v-(1<>>=m;g>0;){var w=r[i].s;e>p[w]?g-=1<=0&&g;--i){var I=r[i].s;p[I]==e&&(--p[I],++g)}f=e}return[new qe(p),f]},wo=function(t,e,n){return t.s==-1?Math.max(wo(t.l,e,n+1),wo(t.r,e,n+1)):e[t.s]=n},Rl=function(t){for(var e=t.length;e&&!t[--e];);for(var n=new Pe(++e),i=0,s=t[0],r=1,o=function(l){n[i++]=l},a=1;e>=a;++a)if(t[a]==s&&a!=e)++r;else{if(!s&&r>2){for(;r>138;r-=138)o(32754);r>2&&(o(r>10?r-11<<5|28690:r-3<<5|12305),r=0)}else if(r>3){for(o(s),--r;r>6;r-=6)o(8304);r>2&&(o(r-3<<5|8208),r=0)}for(;r--;)o(s);r=1,s=t[a]}return[n.subarray(0,i),e]},On=function(t,e){for(var n=0,i=0;e.length>i;++i)n+=t[i]*e[i];return n},bo=function(t,e,n){var i=n.length,s=rd(e+2);t[s]=255&i,t[s+1]=i>>>8,t[s+2]=255^t[s],t[s+3]=255^t[s+1];for(var r=0;i>r;++r)t[s+r+4]=n[r];return 8*(s+4+i)},Nl=function(t,e,n,i,s,r,o,a,l,u,c){ct(e,c++,n),++s[256];for(var d=kr(s,15),h=d[0],p=d[1],f=kr(r,15),g=f[0],m=f[1],v=Rl(h),E=v[0],w=v[1],I=Rl(g),A=I[0],F=I[1],D=new Pe(19),S=0;E.length>S;++S)D[31&E[S]]++;for(S=0;A.length>S;++S)D[31&A[S]]++;for(var $=kr(D,7),T=$[0],M=$[1],N=19;N>4&&!T[$l[N-1]];--N);var P,z,H,U,Q=u+5<<3,fe=On(s,Xt)+On(r,ws)+o,Ie=On(s,h)+On(r,g)+o+14+3*N+On(D,T)+(2*D[16]+3*D[17]+7*D[18]);if(fe>=Q&&Ie>=Q)return bo(e,c,t.subarray(l,l+u));if(ct(e,c,1+(fe>Ie)),c+=2,fe>Ie){P=ei(h,p),z=h,H=ei(g,m),U=g;var _e=ei(T,M);for(ct(e,c,w-257),ct(e,c+5,F-1),ct(e,c+10,N-4),c+=14,S=0;N>S;++S)ct(e,c+3*S,T[$l[S]]);c+=3*N;for(var Ce=[E,A],Te=0;2>Te;++Te){var ae=Ce[Te];for(S=0;ae.length>S;++S)ct(e,c,_e[me=31&ae[S]]),c+=T[me],me>15&&(ct(e,c,ae[S]>>>5&127),c+=ae[S]>>>12)}}else P=ef,z=Xt,H=tf,U=ws;for(S=0;a>S;++S)if(i[S]>255){var me;Ln(e,c,P[257+(me=i[S]>>>18&31)]),c+=z[me+257],me>7&&(ct(e,c,i[S]>>>23&31),c+=ca[me]);var ge=31&i[S];Ln(e,c,H[ge]),c+=U[ge],ge>3&&(Ln(e,c,i[S]>>>5&8191),c+=ua[ge])}else Ln(e,c,P[i[S]]),c+=z[i[S]];return Ln(e,c,P[256]),c+z[256]},nf=new En([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),sf=(function(){for(var t=new En(256),e=0;256>e;++e){for(var n=e,i=9;--i;)n=(1&n&&3988292384)^n>>>1;t[e]=n}return t})(),Ir=function(t,e,n){for(;n;++e)t[e]=n,n>>>=8};function rf(t,e){e===void 0&&(e={});var n=(function(){var d=4294967295;return{p(h){for(var p=d,f=0;h.length>f;++f)p=sf[255&p^h[f]]^p>>>8;d=p},d(){return 4294967295^d}}})(),i=t.length;n.p(t);var s,r,o,a,l,u=(a=10+((s=e).filename&&s.filename.length+1||0),l=8,(function(d,h,p,f,g,m){var v=d.length,E=new qe(f+v+5*(1+Math.floor(v/7e3))+g),w=E.subarray(f,E.length-g),I=0;if(!h||8>v)for(var A=0;v>=A;A+=65535){var F=A+65535;v>F?I=bo(w,I,d.subarray(A,F)):(w[A]=!0,I=bo(w,I,d.subarray(A,v)))}else{for(var D=nf[h-1],S=D>>>13,$=8191&D,T=(1<A;++A){var me=H(A),ge=32767&A,Qe=N[me];if(M[ge]=Qe,N[me]=ge,A>=Te){var Lt=v-A;if((Ie>7e3||Ce>24576)&&Lt>423){I=Nl(d,w,0,U,Q,fe,_e,Ce,ae,A-ae,I),Ce=Ie=_e=0,ae=A;for(var de=0;286>de;++de)Q[de]=0;for(de=0;30>de;++de)fe[de]=0}var Ge=2,It=0,Pn=$,De=ge-Qe&32767;if(Lt>2&&me==H(A-De))for(var Ae=Math.min(S,Lt)-1,Ei=Math.min(32767,A),Si=Math.min(258,Lt);Ei>=De&&--Pn&&ge!=Qe;){if(d[A+Ge]==d[A+Ge-De]){for(var je=0;Si>je&&d[A+je]==d[A+je-De];++je);if(je>Ge){if(Ge=je,It=De,je>Ae)break;var xi=Math.min(De,je-2),tn=0;for(de=0;xi>de;++de){var nn=A-De+de+32768&32767,$n=nn-M[nn]+32768&32767;$n>tn&&(tn=$n,Qe=nn)}}}De+=(ge=Qe)-(Qe=M[ge])+32768&32767}if(It){U[Ce++]=268435456|yo[Ge]<<18|Tl[It];var Va=31&yo[Ge],Ga=31&Tl[It];_e+=ca[Va]+ua[Ga],++Q[257+Va],++fe[Ga],Te=A+Ge,++Ie}else U[Ce++]=d[A],++Q[d[A]]}}I=Nl(d,w,!0,U,Q,fe,_e,Ce,ae,A-ae,I)}return od(E,0,f+rd(I)+g)})(r=t,(o=e).level==null?6:o.level,o.mem==null?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(r.length)))):12+o.mem,a,l)),c=u.length;return(function(d,h){var p=h.filename;if(d[0]=31,d[1]=139,d[2]=8,d[8]=2>h.level?4:h.level==9?2:0,d[9]=3,h.mtime!=0&&Ir(d,4,Math.floor(new Date(h.mtime||Date.now())/1e3)),p){d[3]=8;for(var f=0;p.length>=f;++f)d[f+10]=p.charCodeAt(f)}})(u,e),Ir(u,c-8,n.d()),Ir(u,c-4,i),u}var of=!!Wr||!!Ko,ad="text/plain",Vi=!1,ld=(t,e)=>{var n=t.split("#"),i=n[1],s=n[0].split("?"),r=s[0],o=s[1];if(!o)return t;var a=o.split("&").filter((l=>l.split("=")[0]!==e)).join("&");return r+(a?"?"+a:"")+(i?"#"+i:"")},js=function(t,e,n){var i;n===void 0&&(n=!0);var s=t.split("?"),r=s[0],o=s[1],a=b({},e),l=(i=o?.split("&").map((c=>{var d,h=c.split("="),p=h[0],f=n&&(d=a[p])!==null&&d!==void 0?d:h[1];return delete a[p],p+"="+f})))!==null&&i!==void 0?i:[],u=(function(c,d){var h,p;d===void 0&&(d="&");var f=[];return Z(c,(function(g,m){x(g)||x(m)||m==="undefined"||(h=encodeURIComponent((v=>v instanceof File)(g)?g.name:g.toString()),p=encodeURIComponent(m),f[f.length]=p+"="+h)})),f.join(d)})(a);return u&&l.push(u),l.length>0?r+"?"+l.join("&"):r},Cr=t=>{if(t.Ji)return t.Ji;var e=t.data,n=t.compression;if(e){if(n===xe.GZipJS){var i=rf((function(a,l){var u=a.length;if(typeof TextEncoder<"u")return new TextEncoder().encode(a);for(var c=new qe(a.length+(a.length>>>1)),d=0,h=function(m){c[d++]=m},p=0;u>p;++p){if(d+5>c.length){var f=new qe(d+8+(u-p<<1));f.set(c),c=f}var g=a.charCodeAt(p);128>g?h(g):2048>g?(h(192|g>>>6),h(128|63&g)):g>55295&&57344>g?(h(240|(g=65536+(1047552&g)|1023&a.charCodeAt(++p))>>>18),h(128|g>>>12&63),h(128|g>>>6&63),h(128|63&g)):(h(224|g>>>12),h(128|g>>>6&63),h(128|63&g))}return od(c,0,d)})(pn(e)),{mtime:0});return{contentType:ad,body:i.buffer.slice(i.byteOffset,i.byteOffset+i.byteLength),estimatedSize:i.byteLength}}if(n===xe.Base64){var s=(function(a){return a&&btoa(encodeURIComponent(a).replace(/%([0-9A-F]{2})/g,((l,u)=>String.fromCharCode(parseInt(u,16)))))})(pn(e)),r=(a=>"data="+encodeURIComponent(typeof a=="string"?a:pn(a)))(s);return{contentType:"application/x-www-form-urlencoded",body:r,estimatedSize:new Blob([r]).size}}var o=pn(e);return{contentType:"application/json",body:o,estimatedSize:new Blob([o]).size}}},cd=t=>{var e,n,i=()=>t.transport==="sendBeacon"?{url:js(t.url,{compression:xe.Base64}),encodedBody:Cr(b({},t,{compression:xe.Base64,Ji:void 0}))}:{url:ld(t.url,"compression"),encodedBody:Cr(b({},t,{compression:void 0,Ji:void 0}))};try{e=Cr(t)}catch(s){if(el(t.compression,wn(t.url,"compression")))return k.error("Failed to gzip request body, sending uncompressed payload",s),i();throw s}return e&&el(t.compression,wn(t.url,"compression"))&&!((n=e.body)instanceof ArrayBuffer?zr(new Uint8Array(n)):ArrayBuffer.isView(n)&&zr(new Uint8Array(n.buffer,n.byteOffset,n.byteLength)))?(Vi=!0,i()):{url:t.url,encodedBody:e}},ud=t=>{try{return cd(t)}catch(e){return k.error(e),void(t.callback==null||t.callback({statusCode:0,error:e}))}},af=(function(){var t=X((function*(e){var n=pn(e.data),i=yield(function(r,o,a){return qr.apply(this,arguments)})(n,Y.DEBUG,{rethrow:!0});if(!i)return e;var s=yield i.arrayBuffer();return b({},e,{Ji:{contentType:ad,body:s,estimatedSize:s.byteLength}})}));return function(e){return t.apply(this,arguments)}})(),lf=/Failed to fetch|NetworkError|Load failed/i,dd=t=>t?.name==="TypeError"&&lf.test(t?.message||""),hd=t=>{var e=ud(t);if(e){var n=e.url,i=e.encodedBody,s=i??{},r=s.contentType,o=s.body,a=s.estimatedSize,l=new Headers;Z(t.headers,(function(f,g){l.append(g,f)})),r&&l.append("Content-Type",r);var u=null,c=!1;if(Ka){var d=new Ka;u={signal:d.signal,timeout:setTimeout((()=>{var f,g;c=!0,d.abort((f=t.timeout,(g=new Error("PostHog request timed out"+(f?" after "+f+"ms":""))).name="AbortError",g))}),t.timeout)}}var h=f=>{c&&f?.name==="AbortError"||dd(f)?k.warn(f):k.error(f),t.callback==null||t.callback({statusCode:0,error:f})};try{var p;Ko(n,b({method:t?.method||"GET",headers:l,keepalive:t.method==="POST"&&!t.Yi&&52428.8>(a||0),body:o,signal:(p=u)==null?void 0:p.signal},t.fetchOptions)).then((f=>f.text().then((g=>{var m={statusCode:f.status,text:g};if(f.status===200)try{m.json=JSON.parse(g)}catch(v){k.error(v)}t.callback==null||t.callback(m)})))).catch(h).finally((()=>u?clearTimeout(u.timeout):null))}catch(f){u&&clearTimeout(u.timeout),h(f)}}},Eo=t=>{try{var e,n=cd(t),i=n.url,s=n.encodedBody,r=s??{},o=r.body,a=r.estimatedSize;if(!o)return;var l=o instanceof Blob?o:new Blob([o],{type:r.contentType});if(ke.sendBeacon(i,l))return;var u=O(t.data)?t.data:(e=t.data)==null?void 0:e.batch;if(O(u)&&u.length>1&&(a??0)>16384){var c=Math.ceil(u.length/2),d=h=>O(t.data)?h:b({},t.data,{batch:h});return Eo(b({},t,{data:d(u.slice(0,c))})),void Eo(b({},t,{data:d(u.slice(c))}))}k.warn("Beacon of ~"+(a??0)+" bytes was rejected by the browser, falling back to fetch"),hd(b({},t,{Yi:!0}))}catch(h){k.warn("Beacon send failed",h)}},Ml=(t,e,n,i)=>{var s=i==="query"?e==="POST"?"sent_at":"_":void 0;return js(n===xe.GZipJS?ld(t,"compression"):t,b({},s?{[s]:Date.now().toString()}:{},n===xe.GZipJS?{}:{compression:n}))},Gi=[];Ko&&Gi.push({transport:"fetch",method:hd}),Wr&&Gi.push({transport:"XHR",method(t){var e=ud(t);if(e){var n=new Wr,i=e.encodedBody;n.open(t.method||"GET",e.url,!0);var s=i??{},r=s.contentType,o=s.body;Z(t.headers,(function(a,l){n.setRequestHeader(l,a)})),r&&n.setRequestHeader("Content-Type",r),t.timeout&&(n.timeout=t.timeout),n.onreadystatechange=()=>{if(n.readyState===4){var a={statusCode:n.status,text:n.responseText};if(n.status===200)try{a.json=JSON.parse(n.responseText)}catch{}t.callback==null||t.callback(a)}},n.send(o)}}}),ke!=null&&ke.sendBeacon&&Gi.push({transport:"sendBeacon",method:Eo});var So=3e3;class cf{constructor(e,n){this.Xi=!0,this.tr=[],this.er=ot(n?.flush_interval_ms||So,250,5e3,k.createLogger("flush interval"),So),this.ir=e}enqueue(e){this.tr.push(e),this.rr||this.nr()}unload(){this.sr();var e=this.tr.length>0?this.ar():{},n=Object.values(e);[...n.filter((i=>i.url.indexOf("/e")===0)),...n.filter((i=>i.url.indexOf("/e")!==0))].map((i=>{this.lr(b({},i,{transport:"sendBeacon"}))}))}enable(){this.Xi=!1,this.nr()}nr(){var e=this;this.Xi||(this.rr=setTimeout((()=>{if(this.sr(),this.tr.length>0){var n=this.ar(),i=function(){var r=n[s],o=new Date().getTime();r.data&&O(r.data)&&Z(r.data,(a=>{a.offset=Math.abs(a.timestamp-o),delete a.timestamp})),e.lr(r)};for(var s in n)i()}}),this.er))}lr(e){try{this.ir(e)}catch(n){k.error(n)}}sr(){clearTimeout(this.rr),this.rr=void 0}ar(){var e={};return Z(this.tr,(n=>{var i,s=n,r=(s?s.batchKey:null)||s.url;x(e[r])&&(e[r]=b({},s,{data:[]})),(i=e[r].data)==null||i.push(s.data)})),this.tr=[],e}}var uf=["retriesPerformedSoFar"];class df{constructor(e){this.ur=!1,this.hr=3e3,this.tr=[],this._instance=e,this.tr=[],this.dr=!0,!x(_)&&"onLine"in _.navigator&&(this.dr=_.navigator.onLine,this.vr=()=>{this.dr=!0,this.cr()},this.pr=()=>{this.dr=!1},re(_,"online",this.vr),re(_,"offline",this.pr))}get length(){return this.tr.length}retriableRequest(e){var n=e.retriesPerformedSoFar,i=jc(e,uf);dt(n)&&(i.url=js(i.url,{retry_count:n})),this._instance._send_request(b({},i,{callback:s=>{if(s.statusCode!==200&&(400>s.statusCode||s.statusCode>=500)){if((s.statusCode===0?3:10)>(n??0))return void this.At(b({retriesPerformedSoFar:n},i));s.statusCode===0&&k.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.")}i.callback==null||i.callback(s)}}))}At(e){var n=e.retriesPerformedSoFar||0;e.retriesPerformedSoFar=n+1;var i=(function(o){var a=3e3*Math.pow(2,o),l=a/2,u=Math.min(18e5,a),c=Math.random()-.5;return Math.ceil(u+c*(u-l))})(n),s=Date.now()+i;this.tr.push({retryAt:s,requestOptions:e});var r="Enqueued failed request for retry in "+i;navigator.onLine||(r+=" (Browser is offline)"),k.warn(r),this.ur||(this.ur=!0,this.gr())}gr(){if(this.mr&&clearTimeout(this.mr),this.tr.length===0)return this.ur=!1,void(this.mr=void 0);this.mr=setTimeout((()=>{this.dr&&this.tr.length>0&&this.cr(),this.gr()}),this.hr)}cr(){var e=Date.now(),n=[],i=this.tr.filter((r=>e>r.retryAt||(n.push(r),!1)));if(this.tr=n,i.length>0)for(var s of i)this.retriableRequest(s.requestOptions)}unload(){for(var e of(this.mr&&(clearTimeout(this.mr),this.mr=void 0),this.ur=!1,x(_)||(this.vr&&(_.removeEventListener("online",this.vr),this.vr=void 0),this.pr&&(_.removeEventListener("offline",this.pr),this.pr=void 0)),this.tr)){var n=e.requestOptions;try{this._instance._send_request(b({},n,{transport:"sendBeacon"}))}catch(i){k.error(i)}}this.tr=[]}}class hf{constructor(e){this.yr=()=>{var n,i,s,r;this.br||(this.br={});var o=this.scrollElement(),a=this.scrollY(),l=o?Math.max(0,o.scrollHeight-o.clientHeight):0,u=a+(o?.clientHeight||0),c=o?.scrollHeight||0;this.br.lastScrollY=Math.ceil(a),this.br.maxScrollY=Math.max(a,(n=this.br.maxScrollY)!==null&&n!==void 0?n:0),this.br.maxScrollHeight=Math.max(l,(i=this.br.maxScrollHeight)!==null&&i!==void 0?i:0),this.br.lastContentY=u,this.br.maxContentY=Math.max(u,(s=this.br.maxContentY)!==null&&s!==void 0?s:0),this.br.maxContentHeight=Math.max(c,(r=this.br.maxContentHeight)!==null&&r!==void 0?r:0)},this._instance=e}get _r(){return this._instance.config.scroll_root_selector}getContext(){return this.br}resetContext(){var e=this.br;return setTimeout(this.yr,0),e}startMeasuringScrollPosition(){re(_,"scroll",this.yr,{capture:!0}),re(_,"scrollend",this.yr,{capture:!0}),re(_,"resize",this.yr)}scrollElement(){if(!this._r)return _?.document.documentElement;var e=O(this._r)?this._r:[this._r];for(var n of e){var i=_?.document.querySelector(n);if(i)return i}}wr(e){var n=e==="y"?"scrollTop":"scrollLeft";if(this._r){var i=this.scrollElement();return i&&i[n]||0}return _?e==="y"?_.scrollY||_.pageYOffset||_.document.documentElement.scrollTop||0:_.scrollX||_.pageXOffset||_.document.documentElement.scrollLeft||0:0}scrollY(){return this.wr("y")}scrollX(){return this.wr("x")}}var pf=t=>Xu(t?.config.mask_personal_data_properties,t?.config.custom_personal_data_properties,t?.config.disable_capture_url_hashes);class Ll{constructor(e,n,i,s){this.kr=r=>{var o=this.Sr();if(!o||o.sessionId!==r){var a={sessionId:r,props:this.Cr(this._instance)};this.Mr.register({[co]:a})}},this._instance=e,this.Tr=n,this.Mr=i,this.Cr=s||pf,this.Tr.onSessionId(this.kr)}Sr(){return this.Mr.props[co]}getSetOnceProps(){var e,n=(e=this.Sr())==null?void 0:e.props;return n?"r"in n?Qu(n,this._instance.config.disable_capture_url_hashes):{$referring_domain:n.referringDomain,$pathname:n.initialPathName,utm_source:n.utm_source,utm_campaign:n.utm_campaign,utm_medium:n.utm_medium,utm_content:n.utm_content,utm_term:n.utm_term}:{}}getSessionProps(){var e={};return Z(ra(this.getSetOnceProps()),((n,i)=>{i==="$current_url"&&(i="url"),e["$session_entry_"+Vr(i)]=n})),e}}class da{on(e,n){return this.Er[e]||(this.Er[e]=[]),this.Er[e].push(n),()=>{this.Er[e]=this.Er[e].filter((i=>i!==n))}}emit(e,n){for(var i of this.Er[e]||[])i(n);for(var s of this.Er["*"]||[])s(e,n)}constructor(){this.Er={}}}var Bn=ie("[SessionId]");class Ol{on(e,n){return this.Ir.on(e,n)}constructor(e,n,i){var s;if(this.Pr=null,this.Rr=[],this.Ar=void 0,this.Fr=!1,this.Ir=new da,this.Lr=(u,c)=>!(!dt(u)||!dt(c))&&Math.abs(u-c)>this.sessionTimeoutMs,!e.persistence)throw new Error("SessionIdManager requires a PostHogPersistence instance");if(e.config.cookieless_mode===gt)throw new Error('SessionIdManager cannot be used with cookieless_mode="always"');this.Ne=e.config,this.Mr=e.persistence,this.Or=void 0,this.Dr=void 0,this._sessionStartTimestamp=null,this._sessionActivityTimestamp=null,this.$r=n||ft,this.Nr=i||ft;var r=this.Ne.persistence_name||this.Ne.token;if(this._sessionTimeoutMs=1e3*ot(this.Ne.session_idle_timeout_seconds||1800,60,36e3,Bn.createLogger("session_idle_timeout_seconds"),1800),e.register({$configured_session_timeout_ms:this._sessionTimeoutMs}),this.qr(),this.jr="ph_"+r+"_window_id",this.Br="ph_"+r+"_primary_window_exists",this.Hr()){var o=ce.H(this.jr),a=ce.H(this.Br);o&&!a?this.Or=o:ce.q(this.jr),ce.F(this.Br,!0)}if((s=this.Ne.bootstrap)!=null&&s.sessionID)try{var l=(u=>{var c=this.Ne.bootstrap.sessionID.replace(/-/g,"");if(c.length!==32)throw new Error("Not a valid UUID");if(c[12]!=="7")throw new Error("Not a UUIDv7");return parseInt(c.substring(0,12),16)})();this.Ur(this.Ne.bootstrap.sessionID,new Date().getTime(),l)}catch(u){Bn.error("Invalid sessionID in bootstrap",u)}this.zr()}get sessionTimeoutMs(){return this._sessionTimeoutMs}onSessionId(e){return x(this.Rr)&&(this.Rr=[]),this.Rr.push(e),this.Dr&&e(this.Dr,this.Or),()=>{this.Rr=this.Rr.filter((n=>n!==e))}}Hr(){return this.Ne.persistence!=="memory"&&!this.Mr.xi&&ce.N()}Wr(e){e!==this.Or&&(this.Or=e,this.Hr()&&ce.F(this.jr,e))}Vr(){return this.Or?this.Or:this.Hr()?ce.H(this.jr):null}Zr(e){var n=this.Pr;return!$e(n)&&!$e(e)&&5e3>Math.abs(e-n)}Ur(e,n,i){var s=n!==this._sessionActivityTimestamp,r=!(e!==this.Dr||i!==this._sessionStartTimestamp);this._sessionStartTimestamp=i,this._sessionActivityTimestamp=n,this.Dr=e,r&&!s||r&&this.Zr(n)||(this.Pr=n,this.Mr.register({[hn]:[n,e,i]}))}Gr(){var e,n=(e=this.Ne)==null?void 0:e.persistence_save_debounce_ms;return dt(n)&&n>0}Qr(){this.Gr()?this.Mr.refreshKey(hn):(this.Mr.flush(),this.Mr.load())}Kr(){var e;if(!$e(this._sessionActivityTimestamp)&&this._sessionActivityTimestamp!==this.Pr){this.Qr();var n=this.Jr();n[1]===this.Dr&&n[2]===this._sessionStartTimestamp&&(this.Pr=this._sessionActivityTimestamp,this.Mr.register({[hn]:[this._sessionActivityTimestamp,(e=this.Dr)!==null&&e!==void 0?e:null,this._sessionStartTimestamp]}),this.Mr.flush())}}Yr(){var e=this.Jr()[0],n=dt(e)?e:0,i=dt(this._sessionActivityTimestamp)?this._sessionActivityTimestamp:0;return Math.max(n,i)}Xr(e){return this.Qr(),this.Lr(e,this.Yr())}Jr(){var e=this.Mr.props[hn];return O(e)&&e.length===2&&e.push(e[0]),e||[0,null,0]}resetSessionId(){this.Pr=null,clearTimeout(this.tn),this.tn=void 0,this.Ur(null,null,null)}destroy(){this.Fr=!0,this.Kr(),clearTimeout(this.tn),this.tn=void 0,this.Ar&&_&&(_.removeEventListener(fs,this.Ar,{capture:!1}),this.Ar=void 0),this.Rr=[]}zr(){this.Ar=()=>{this.Kr(),this.Hr()&&ce.q(this.Br)},re(_,fs,this.Ar,{capture:!1})}checkAndGetSessionAndWindowId(e,n){if(e===void 0&&(e=!1),n===void 0&&(n=null),this.Ne.cookieless_mode===gt)throw new Error('checkAndGetSessionAndWindowId should not be called with cookieless_mode="always"');var i=n||new Date().getTime(),s=this.Jr(),r=s[1],o=s[2],a=this.Yr(),l=this.Vr(),u=dt(o)&&Math.abs(i-o)>864e5,c=!1,d=!1,h=!r,p=r,f=!h&&!e&&this.Lr(i,a);if(f){(f=this.Xr(i))||Bn.info("cross-tab refresh kept the session alive",{sessionId:r});var g=this.Jr();r=g[1],o=g[2]}h||f||u?(r=this.$r(),l=this.Nr(),Bn.info("new session ID generated",{sessionId:r,windowId:l,changeReason:{noSessionId:h,activityTimeout:f,sessionPastMaximumLength:u}}),o=i,c=!0):(l||(l=this.Nr(),c=!0),(d=r!==p)&&(Bn.info("adopted cross-tab session id",{sessionId:r,windowId:l}),c=!0));var m=dt(a)&&e&&!u?a:i,v=dt(o)?o:new Date().getTime();this.Wr(l),this.Ur(r,m,v),e||this.qr();var E={noSessionId:h,activityTimeout:f,sessionPastMaximumLength:u,crossTabAdoption:d};return c&&this.Rr.forEach((w=>w(r,l,E))),{sessionId:r,windowId:l,sessionStartTimestamp:v,changeReason:c?E:void 0,lastActivityTimestamp:a}}qr(){this.Fr||(clearTimeout(this.tn),this.tn=setTimeout((()=>{if(!this.Fr)if(this.Xr(new Date().getTime())){var e=this.Dr;this.resetSessionId(),this.Ir.emit("forcedIdleReset",{idleSessionId:e})}else this.qr()}),1.1*this.sessionTimeoutMs))}}var pd=function(t,e){if(!t)return!1;var n=t.userAgent;if(n&&nl(n,e))return!0;try{var i=t?.userAgentData;if(i!=null&&i.brands&&i.brands.some((s=>nl(s?.brand,e))))return!0}catch{}return!!t.webdriver};function fd(){return(fd=X((function*(){var t=ke?.userAgentData;if(t!=null&&t.getHighEntropyValues)try{var e=yield t.getHighEntropyValues(["model"]),n=e?.model;return q(n)&&n.length>0?n:void 0}catch(i){return void k.info("Unable to resolve $device_model from userAgentData.getHighEntropyValues",i)}}))).apply(this,arguments)}var bs=function(t,e){if(!(function(n){try{new RegExp(n)}catch{return!1}return!0})(e))return!1;try{return new RegExp(e).test(t)}catch{return!1}};function Ar(t,e,n){return pn({distinct_id:t,userPropertiesToSet:e,userPropertiesToSetOnce:n})}var gd={exact:(t,e)=>e.some((n=>t.some((i=>n===i)))),is_not:(t,e)=>e.every((n=>t.every((i=>n!==i)))),regex:(t,e)=>e.some((n=>t.some((i=>bs(n,i))))),not_regex:(t,e)=>e.every((n=>t.every((i=>!bs(n,i))))),icontains:(t,e)=>e.map(Ri).some((n=>t.map(Ri).some((i=>n.includes(i))))),not_icontains:(t,e)=>e.map(Ri).every((n=>t.map(Ri).every((i=>!n.includes(i))))),gt:(t,e)=>e.some((n=>{var i=parseFloat(n);return!isNaN(i)&&t.some((s=>i>parseFloat(s)))})),lt:(t,e)=>e.some((n=>{var i=parseFloat(n);return!isNaN(i)&&t.some((s=>it.toLowerCase();function md(t,e){return!t||Object.entries(t).every((n=>{var i=n[1],s=e?.[n[0]];if(x(s)||$e(s))return!1;var r=[String(s)],o=gd[i.operator];return!!o&&o(i.values,r)}))}var xo="custom",Bl="i.posthog.com",ff=/^\/static\//;class gf{constructor(e){this.en={},this.instance=e}get apiHost(){var e=this.instance.config.api_host.trim().replace(/\/$/,"");return e==="https://app.posthog.com"?"https://us.i.posthog.com":e}get flagsApiHost(){var e=this.instance.config.flags_api_host;return e?e.trim().replace(/\/$/,""):this.apiHost}get uiHost(){var e,n=(e=this.instance.config.ui_host)==null?void 0:e.replace(/\/$/,"");return n||(n=this.apiHost.replace("."+Bl,".posthog.com")),n==="https://app.posthog.com"?"https://us.posthog.com":n}get region(){return this.en[this.apiHost]||(this.en[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":xo),this.en[this.apiHost]}rn(e){if(ff.test(e)){var n=this.instance.config.asset_host;if(typeof n=="string")return n.trim().replace(/\/$/,"")||void 0}}endpointFor(e,n){if(n===void 0&&(n=""),n&&(n=n[0]==="/"?n:"/"+n),e==="ui")return this.uiHost+n;if(e==="flags")return this.flagsApiHost+n;if(e==="assets"){var i=this.rn(n);if(i)return""+i+n}if(this.region===xo)return this.apiHost+n;var s=Bl+n;switch(e){case"assets":return"https://"+this.region+"-assets."+s;case"api":return"https://"+this.region+"."+s}}}function vd(t){var e;return!((e=t.conditions)==null||(e=e.events)==null||(e=e.values)==null||!e.length)}var G=ie("[Surveys]"),_d="seenSurvey_",yd=t=>{try{var e=(n=>((i,s)=>""+_d+(function(r){return r.current_iteration&&r.current_iteration>0?r.id+"_"+r.current_iteration:r.id})(s))(0,n))(t);if(localStorage.getItem(e))return;localStorage.setItem(e,"true")}catch(n){G.error("Failed to persist survey seen state",n)}},mf=[Sr.Popover,Sr.Widget,Sr.API],vf={ignoreConditions:!1,ignoreDelay:!1,displayType:_o.Popover},_f=ie("[PostHog ExternalIntegrations]"),yf={intercom:"intercom-integration",crispChat:"crisp-chat-integration"};class wf{constructor(e){this._instance=e}ai(e,n){var i;(i=R.__PosthogExtensions__)==null||i.loadExternalDependency==null||i.loadExternalDependency(this._instance,e,(s=>{if(s)return _f.error("failed to load script",s);n()}))}startIfEnabledOrStop(){var e=this,n=function(){var r,o,a,l=i[0],u=i[1];!u||(r=R.__PosthogExtensions__)!=null&&(r=r.integrations)!=null&&r[l]||e.ai(yf[l],(()=>{var c;(c=R.__PosthogExtensions__)==null||(c=c.integrations)==null||(c=c[l])==null||c.start(e._instance)})),!u&&(o=R.__PosthogExtensions__)!=null&&(o=o.integrations)!=null&&o[l]&&((a=R.__PosthogExtensions__)==null||(a=a.integrations)==null||(a=a[l])==null||a.stop())};for(var i of Object.entries((s=this._instance.config.integrations)!==null&&s!==void 0?s:{})){var s;n()}}}class bf{constructor(e,n){this.rt=e,this.nn=n,this.sn=new Map,this.an=!1}add(e){var n=this;return X((function*(){if(n.an)throw new Error("Cannot add an extension to a disposed ExtensionRuntime");if(n.sn.has(e.name))throw new Error('Browser extension "'+e.name+'" is already registered');n.sn.set(e.name,e);try{var i=e.setup(n.nn);i&&(yield i)}catch(r){var s=n.sn.get(e.name)===e;s&&n.sn.delete(e.name),n.rt.error('Failed to set up browser extension "'+e.name+'"',r),s&&n.ln(e)}}))()}dispose(){if(!this.an){this.an=!0;var e=Array.from(this.sn.values()).reverse();for(var n of(this.sn.clear(),e))this.ln(n)}}ln(e){try{var n=e.dispose==null?void 0:e.dispose();n&&Se(n.then)&&n.then(void 0,(i=>{this.rt.error('Failed to dispose browser extension "'+e.name+'"',i)}))}catch(i){this.rt.error('Failed to dispose browser extension "'+e.name+'"',i)}}}class Ef{constructor(e){this._instance=e}initialize(){}get(e){var n=this._instance.persistence;if(typeof e=="string")return n?.get_property(e);var i={};for(var s of e){var r=n?.get_property(s);x(r)||(i[s]=r)}return i}set(e,n){var i;(i=this._instance.persistence)==null||i.register(typeof e=="string"?{[e]:n}:e)}remove(e){var n;(n=this._instance.persistence)==null||n.unregister(e)}}var Dl="extensionsRemoteConfig";class Sf{constructor(e){this.an=!1,this.instance=e,this.rt=k,this.un=e.hn,this.kv=new Ef(e),this.onEvent=n=>Ti(this.instance.on("eventCaptured",(i=>{try{n({event:i.event,properties:i.properties})}catch(s){this.rt.error("Browser extension event listener failed",s)}}))),this.onRemoteConfig=n=>{if(this.an)return Ti((()=>{}));var i=r=>{try{n(r)}catch(o){this.rt.error("Browser extension remote config listener failed",o)}},s=this.instance.dn.on(Dl,i);return this.un&&i(this.un),Ti(s)},this.vn=new bf(k.createLogger("[BrowserExtensions]"),this)}get logger(){return this.rt}get distinctId(){return this.instance.get_distinct_id()}get anonymousId(){var e;return(e=this.instance.get_property(ai))!==null&&e!==void 0?e:this.distinctId}get deviceId(){var e=this.instance.get_property(ai);return typeof e=="string"?e:void 0}get library(){return{name:Y.LIB_NAME,version:Y.LIB_VERSION}}get initialPersonProperties(){var e,n;return(e=(n=this.instance.persistence)==null?void 0:n.get_initial_props())!==null&&e!==void 0?e:{}}get groups(){return this.instance.getGroups()}get session(){try{var e,n,i,s,r=(e=this.instance.sessionManager)==null?void 0:e.checkAndGetSessionAndWindowId(!0);return{sessionId:(n=r?.sessionId)!==null&&n!==void 0?n:"",windowId:(i=r?.windowId)!==null&&i!==void 0?i:"",sessionStartTimestamp:(s=r?.sessionStartTimestamp)!==null&&s!==void 0?s:0}}catch{return{sessionId:"",windowId:"",sessionStartTimestamp:0}}}get projectToken(){return this.instance.config.token}add(e){return this.vn.add(e)}capture(e,n,i){var s=this;return X((function*(){i?s.instance.capture(e,n,{timestamp:i.timestamp,uuid:i.uuid,$set:i.set,$set_once:i.setOnce}):s.instance.capture(e,n)}))()}registerDynamicEventProperties(e){return Ti(this.instance.cn(e))}handleRemoteConfig(e){this.an||(this.un=e,this.instance.dn.emit(Dl,e))}sendRequest(e,n){var i=this;return X((function*(){var s;n===void 0&&(n={});var r=i.instance.requestRouter.endpointFor((s=n.target)!==null&&s!==void 0?s:"api",e),o={method:n.method,url:n.query?js(r,n.query):r,data:n.body,headers:n.headers,timeout:n.timeoutMs,fireCallbackOnDrop:!0,transport:n.transport,compression:n.compression,timestampMode:n.sentAt};return n.transport==="sendBeacon"?(i.instance._send_request(o),{statusCode:202}):new Promise((a=>{o.callback=a,i.instance._send_request(o)}))}))()}dispose(){this.an||(this.an=!0,this.vn.dispose())}}var ti={},Fr=0,Es=()=>{},jl='Consent opt in/out is not valid with cookieless_mode="always" and will be ignored',Dn="Surveys module not available",Ul="sanitize_properties is deprecated. Use before_send instead",wd="Invalid value for property_denylist config: ",xf=["token","distinct_id",Cu],un="posthog",bd=!of&&Fe?.indexOf("MSIE")===-1&&Fe?.indexOf("Mozilla")===-1,Pr=t=>{var e;return b({api_host:"https://us.i.posthog.com",flags_api_host:null,ui_host:null,asset_host:null,token:"",autocapture:!0,cross_subdomain_cookie:xp(C?.location),persistence:"localStorage+cookie",persistence_name:"",cookie_persisted_properties:[],loaded:Es,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_external_dependency_versioned_paths:!1,__preview_cookie_wins_on_conflict:!1,debug:se&&q(se?.search)&&se.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,disable_external_dependency_loading:!1,strict_script_versioning:!1,enable_recording_console_log:void 0,secure_cookie:(_==null||(e=_.location)==null?void 0:e.protocol)==="https:",ip:!1,opt_out_capturing_by_default:!1,opt_out_persistence_by_default:!1,opt_out_useragent_filter:!1,opt_out_capturing_persistence_type:"localStorage",consent_persistence_name:null,opt_out_capturing_cookie_prefix:null,opt_in_site_apps:!1,property_denylist:[],respect_dnt:!1,sanitize_properties:null,request_headers:{},request_batching:!0,properties_string_max_length:65535,mask_all_element_attributes:!1,mask_all_text:!1,mask_personal_data_properties:!1,custom_personal_data_properties:[],advanced_disable_flags:!1,advanced_disable_decide:!1,advanced_disable_feature_flags:!1,advanced_disable_feature_flags_on_first_load:!1,advanced_only_evaluate_survey_feature_flags:!1,advanced_feature_flags_dedup_per_session:!1,advanced_enable_surveys:!1,advanced_disable_toolbar_metrics:!1,feature_flag_request_timeout_ms:3e3,surveys_request_timeout_ms:1e4,on_request_error(n){k.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:fo,before_send:void 0,get_current_url:void 0,request_queue_config:{flush_interval_ms:So},error_tracking:{},_onCapture:Es},(n=>({rageclick:n&&n>="2026-05-30"?{content_ignorelist:Lp,ignore_text_selection:!0}:!n||"2025-11-30">n||{content_ignorelist:!0},capture_pageview:!n||"2025-05-24">n||"history_change",session_recording:n&&n>="2026-06-25"?{strictMinimumDuration:!0,canvasCapture:{resolutionScale:.6},streamNetworkBody:!0}:n&&n>="2026-05-30"?{strictMinimumDuration:!0,canvasCapture:{resolutionScale:.6}}:n&&n>="2025-11-30"?{strictMinimumDuration:!0}:{},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)}))(t))},kf=[["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"]],Hl=t=>{var e={};for(var n of kf){var i=n[0],s=n[1];x(t[i])||(e[s]=t[i])}var r=te({},e,t),o=t.__preview_external_dependency_versioned_paths;return x(o)||(x(t.strict_script_versioning)&&(r.strict_script_versioning=!!o),q(o)&&x(t.asset_host)&&(r.asset_host=o)),O(t.property_blacklist)&&(x(t.property_denylist)?r.property_denylist=t.property_blacklist:O(t.property_denylist)?r.property_denylist=[...t.property_blacklist,...t.property_denylist]:k.error(wd+t.property_denylist)),r};class If{constructor(){this.__forceAllowLocalhost=!1}get fn(){return this.__forceAllowLocalhost}set fn(e){k.error("WebPerformanceObserver is deprecated and has no impact on network capture. Use `_forceAllowLocalhostNetworkCapture` on `posthog.sessionRecording`"),this.__forceAllowLocalhost=e}}class Re{pn(e,n){if(e){var i=this.sn.indexOf(e);i!==-1&&this.sn.splice(i,1)}return this.sn.push(n),n.initialize==null||n.initialize(),n}gn(){return this.config.cookieless_mode===gt||this.config.cookieless_mode===Vt&&this.consent.isRejected()}get decideEndpointWasHit(){var e,n;return(e=(n=this.featureFlags)==null?void 0:n.hasLoadedFlags)!==null&&e!==void 0&&e}get flagsEndpointWasHit(){var e,n;return(e=(n=this.featureFlags)==null?void 0:n.hasLoadedFlags)!==null&&e!==void 0&&e}constructor(){var e;this.webPerformance=new If,this.mn=!1,this.version=Y.LIB_VERSION,this.yn=new Set,this.bn="",this.dn=new da,this.sn=[],this._n=[],this._calculate_event_properties=this.calculateEventProperties.bind(this),this.config=Pr(),this.SentryIntegration=zp,this.sentryIntegration=i=>(function(s,r){var o=qu(s,r);return{name:zu,processEvent:a=>o(a)}})(this,i),this.__request_queue=[],this.__loaded=!1,this.analyticsDefaultEndpoint="/e/",this.wn=!1,this.kn=null,this.xn=null,this.Sn=null,this.scrollManager=new hf(this),this.pageViewManager=new Cl(this),this.rateLimiter=new Qp(this),this.requestRouter=new gf(this),this.consent=new $p(this),this.externalIntegrations=new wf(this);var n=(e=Re.__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:(i,s,r)=>{var o=q(i)?{[i]:s}:i;this.setPersonProperties(o),r?.({})},set_once:(i,s,r)=>{var o=q(i)?{[i]:s}:i;this.setPersonProperties(void 0,o),r?.({})}},this.on("eventCaptured",(i=>k.info('send "'+i?.event+'"',i)))}init(e,n,i){if(i&&i!==un){var s,r=(s=ti[i])!==null&&s!==void 0?s:new Re;return r._init(e,n,i),ti[i]=r,ti[un][i]=r,r}return this._init(e,n,i)}_init(e,n,i){var s,r;n===void 0&&(n={});var o,a=q(e)?e.trim():"";if(!a)return k.critical("PostHog was initialized without a token. This likely indicates a misconfiguration. Please check the first argument passed to posthog.init()"),this;if(this.__loaded)return a!==((o=this.config)==null?void 0:o.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('"+a+"', { ... }, 'project2')"):console.warn("[PostHog.js]","You have already initialized PostHog! Re-initializing is a no-op"),this;this.__loaded=!0,this.config=Pr(n.defaults),n.debug=this.Cn(n.debug),this.Mn=n,this.Tn=[],n.person_profiles?this.xn=n.person_profiles:n.process_person&&(this.xn=n.process_person);var l=Pr(n.defaults),u=Hl(n),c=te({},l,u,{name:i,token:a});ne(l.rageclick)&&ne(u.rageclick)&&(c.rageclick=te({},l.rageclick,u.rageclick)),ne(l.session_recording)&&ne(u.session_recording)&&(c.session_recording=te({},l.session_recording,u.session_recording)),this.set_config(c),this.config.on_xhr_error&&k.error("on_xhr_error is deprecated. Use on_request_error instead"),this.compression=n.disable_compression?void 0:xe.GZipJS;var d=this.En();if(this.persistence=new Er(this.config,d),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new Er(b({},this.config,{persistence:"sessionStorage"}),d,!1),this.bn="ph_"+(this.config.persistence_name||this.config.token)+"_session_registered_properties",this.config.persistence!=="memory"&&!d&&ce.N()){var h=ce.H(this.bn);O(h)&&h.forEach((F=>{q(F)&&this.yn.add(F)}))}else ce.q(this.bn);var p=b({},this.persistence.props),f=b({},this.sessionPersistence.props);this.register({$initialization_time:new Date().toISOString()}),this.In=new cf((F=>this.Pn(F)),this.config.request_queue_config),this.Rn=new df(this),this.__request_queue=[];var g=this.gn();if(g||(this.sessionManager=new Ol(this),this.sessionPropsManager=new Ll(this,this.sessionManager,this.persistence),this.sessionManager.onSessionId(((F,D,S)=>{(S!=null&&S.activityTimeout||S!=null&&S.sessionPastMaximumLength||S!=null&&S.crossTabAdoption)&&this.An()}))),this.Fn(),this.config.__preview_deferred_init_extensions?(k.info("Deferring extension initialization to improve startup performance"),setTimeout((()=>{this.Ln(g)}),0)):(k.info("Initializing extensions synchronously"),this.Ln(g)),Y.DEBUG=Y.DEBUG||this.config.debug,Y.DEBUG&&k.info("Starting in debug mode",{this:this,config:n,thisC:b({},this.config),p,s:f}),!this.config.identity_distinct_id||(s=n.bootstrap)!=null&&s.distinctID||(n.bootstrap=b({},n.bootstrap,{distinctID:this.config.identity_distinct_id,isIdentifiedID:!0})),((r=n.bootstrap)==null?void 0:r.distinctID)!==void 0){var m=n.bootstrap.distinctID,v=this.get_distinct_id(),E=this.persistence.get_property(He);if(n.bootstrap.isIdentifiedID&&v!=null&&v!==m&&E===sn)this.identify(m);else if(n.bootstrap.isIdentifiedID&&v!=null&&v!==m&&E===Ot)k.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{var w=this.config.get_device_id(ft()),I=n.bootstrap.isIdentifiedID?w:m;this.persistence.set_property(He,n.bootstrap.isIdentifiedID?Ot:sn),this.register({distinct_id:m,$device_id:I})}}if(g)this.register_once({distinct_id:Ci,$device_id:null},"");else if(!this.get_distinct_id()){var A=this.config.get_device_id(ft());this.register_once({distinct_id:A,$device_id:A},""),this.persistence.set_property(He,sn)}return re(_,"onpagehide"in self?"pagehide":"unload",this._handle_unload.bind(this),{passive:!1}),n.segment?(function(F,D){var S=F.config.segment;if(!S)return D();(function($,T){var M=$.config.segment;if(!M)return T();var N=z=>{var H=()=>z.anonymousId()||ft();$.config.get_device_id=H,z.id()&&($.register({distinct_id:z.id(),$device_id:H()}),$.persistence.set_property(He,Ot)),T()},P=M.user();"then"in P&&Se(P.then)?P.then(N):N(P)})(F,(()=>{S.register(($=>{typeof Promise<"u"&&Promise.resolve||wr.warn("This browser does not have Promise support, and can not use the segment integration");var T=(M,N)=>{if(!N)return M;M.event.userId||M.event.anonymousId===$.get_distinct_id()||(wr.info("No userId set, resetting PostHog"),$.reset()),M.event.userId&&M.event.userId!==$.get_distinct_id()&&(wr.info("UserId set, identifying with PostHog"),$.identify(M.event.userId));var P=$.calculateEventProperties(N,M.event.properties);return M.event.properties=Object.assign({},P,M.event.properties),M};return{name:"PostHog JS",type:"enrichment",version:"1.0.0",isLoaded:()=>!0,load:()=>Promise.resolve(),track:M=>T(M,M.event.event),page:M=>T(M,cn),identify:M=>T(M,vr),screen:M=>T(M,"$screen")}})(F)).then((()=>{D()}))}))})(this,(()=>this.On())):this.On(),Se(this.config._onCapture)&&this.config._onCapture!==Es&&(k.warn("onCapture is deprecated. Please use `before_send` instead"),this.on("eventCaptured",(F=>this.config._onCapture(F.event,F)))),this.config.ip&&k.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 fd.apply(this,arguments)})().then((F=>{F&&this.register({[gr]:F})})).catch(Es),this}Fn(){var e,n,i,s,r,o,a=(e=(n=this.config.__extensionClasses)==null?void 0:n.featureFlags)!==null&&e!==void 0?e:(i=Re.__defaultExtensionClasses)==null?void 0:i.featureFlags;a&&(this.featureFlags&&this.featureFlags instanceof a||((s=this.Dn)==null||s.call(this),this.Dn=void 0,this.featureFlags=new a(this)),Se(this.featureFlags.onReloading)&&Se(this.featureFlags.setup)?this.Dn||(this.Dn=this.featureFlags.onReloading((()=>{this.dn.emit("featureFlagsReloading",!0)})),this.$n().add(this.featureFlags)):(r=(o=this.featureFlags).initialize)==null||r.call(o))}Ln(e){var n,i,s,r,o,a,l,u=performance.now(),c=b({},Re.__defaultExtensionClasses,this.config.__extensionClasses),d=[];c.exceptions&&this.sn.push(this.exceptions=(n=this.exceptions)!==null&&n!==void 0?n:new c.exceptions(this)),c.historyAutocapture&&this.sn.push(this.historyAutocapture=new c.historyAutocapture(this)),c.tracingHeaders&&this.sn.push(this.tracingHeaders=new c.tracingHeaders(this)),c.siteApps&&this.sn.push(this.siteApps=new c.siteApps(this)),c.sessionRecording&&!e&&this.sn.push(this.sessionRecording=new c.sessionRecording(this)),this.config.disable_scroll_properties||d.push((()=>{this.scrollManager.startMeasuringScrollPosition()})),c.autocapture&&this.sn.push(this.autocapture=new c.autocapture(this)),c.surveys&&this.sn.push(this.surveys=(i=this.surveys)!==null&&i!==void 0?i:new c.surveys(this)),c.logs&&this.sn.push(this.logs=(s=this.logs)!==null&&s!==void 0?s:new c.logs(this)),c.metrics&&this.sn.push(this.metrics=(r=this.metrics)!==null&&r!==void 0?r:new c.metrics(this)),c.conversations&&this.sn.push(this.conversations=(o=this.conversations)!==null&&o!==void 0?o:new c.conversations(this)),c.productTours&&this.sn.push(this.productTours=new c.productTours(this)),c.heatmaps&&this.sn.push(this.heatmaps=new c.heatmaps(this)),c.webVitalsAutocapture&&this.sn.push(this.webVitalsAutocapture=new c.webVitalsAutocapture(this)),c.exceptionObserver&&this.sn.push(this.exceptionObserver=new c.exceptionObserver(this)),c.deadClicksAutocapture&&this.sn.push(this.deadClicksAutocapture=new c.deadClicksAutocapture(this,Wp)),c.toolbar&&this.sn.push(this.toolbar=(a=this.toolbar)!==null&&a!==void 0?a:new c.toolbar(this)),c.experiments&&this.sn.push(this.experiments=(l=this.experiments)!==null&&l!==void 0?l:new c.experiments(this)),this.sn.forEach((h=>{h.initialize&&d.push((()=>{h.initialize==null||h.initialize()}))})),d.push((()=>{if(this.Nn){var h=this.Nn;this.Nn=void 0,this.sn.forEach((p=>p.onRemoteConfig==null?void 0:p.onRemoteConfig(h)))}})),this.qn(d,u)}qn(e,n){for(;e.length>0;){if(this.config.__preview_deferred_init_extensions&&performance.now()-n>=30&&e.length>0)return void setTimeout((()=>{this.qn(e,n)}),0);var i=e.shift();if(i)try{i()}catch(r){k.error("Error initializing extension:",r)}}var s=Math.round(performance.now()-n);this.register_for_session({[Au]:this.config.__preview_deferred_init_extensions?"deferred":"synchronous",[Fu]:s}),this.config.__preview_deferred_init_extensions&&k.info("PostHog extensions initialized ("+s+"ms)")}Zi(e){var n;if(!C||!C.body)return k.info("document not ready yet, trying again in 500 milliseconds..."),void setTimeout((()=>{this.Zi(e)}),500);if(this.config.__preview_deferred_init_extensions&&(this.Nn=e),this.hn=e,this.compression=void 0,e.ok){var i,s=e.config;s.supportedCompression&&!this.config.disable_compression&&(this.compression=L(s.supportedCompression,xe.GZipJS)?xe.GZipJS:L(s.supportedCompression,xe.Base64)?xe.Base64:void 0),(i=s.analytics)!=null&&i.endpoint&&(this.analyticsDefaultEndpoint=s.analytics.endpoint)}this.set_config({person_profiles:this.xn?this.xn:fo}),(n=this.jn)==null||n.handleRemoteConfig(e),this.sn.forEach((r=>r.onRemoteConfig==null?void 0:r.onRemoteConfig(e)))}On(){try{this.config.loaded(this)}catch(i){k.critical("`loaded` function failed",i)}if(this.Bn(),this.config.internal_or_test_user_hostname&&se!=null&&se.hostname){var e=se.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.gn())&&this.Hn()}),1),this.Un=new td(this),this.Un.load()}Bn(){var e;this.is_capturing()&&this.config.request_batching&&((e=this.In)==null||e.enable())}_dom_loaded(){this.is_capturing()&&Ai(this.__request_queue,(e=>this.Pn(e))),this.__request_queue=[],this.Bn()}_handle_unload(){var e,n,i,s,r;(e=this.surveys)==null||e.handlePageUnload==null||e.handlePageUnload(),(n=this.metrics)==null||n.flush("sendBeacon"),this.config.request_batching?(this.zn()&&this.capture(mr),(i=this.logs)==null||i.flushLogs("sendBeacon"),(s=this.In)==null||s.unload(),(r=this.Rn)==null||r.unload()):this.zn()&&this.capture(mr,null,{transport:"sendBeacon"})}_send_request(e){this.__loaded?bd?this.__request_queue.push(e):this.rateLimiter.isServerRateLimited(e.batchKey)?e.fireCallbackOnDrop&&(e.callback==null||e.callback({statusCode:429})):(e.transport=e.transport||this.config.api_transport,e.headers=b({},this.config.request_headers,e.headers),e.compression=e.compression==="best-available"?this.compression:e.compression,(x(this.config.disable_beacon)?this.config.__preview_disable_beacon:this.config.disable_beacon)&&(e.disableTransport=["sendBeacon"]),e.fetchOptions=e.fetchOptions||this.config.fetch_options,(n=>{var i,s,r,o=b({},n);o.timeout=o.timeout||6e4;var a,l,u,c,d,h=(i=o.transport)!==null&&i!==void 0?i:"fetch";h==="sendBeacon"&&x(o.compression)&&o.data&&(o.compression=xe.Base64),o.method==="POST"&&o.data&&(o.timestampMode==="capture-body"?o.data={api_key:(l=(d=(c=O(a=o.data)?a:[a])[0])==null||(u=d.properties)==null?void 0:u.token)!==null&&l!==void 0?l:d?.token,batch:c,sent_at:new Date().toISOString()}:o.timestampMode==="body"&&(o.data=(function(m,v){return v===void 0&&(v=new Date().toISOString()),O(m)?m.map((E=>b({},E,{sent_at:v}))):b({},m,{sent_at:v})})(o.data))),o.url=Ml(o.url,o.method,o.compression,o.timestampMode);var p=Gi.filter((m=>!o.disableTransport||!m.transport||!o.disableTransport.includes(m.transport))),f=(s=(r=(function(m,v){for(var E=0;m.length>E;E++)if(m[E].transport===h)return m[E]})(p))==null?void 0:r.method)!==null&&s!==void 0?s:p[0].method;if(!f)throw new Error("No available transport method");var g=m=>{try{f(m)}catch(v){dd(v)?k.warn(v):k.error(v),o.callback==null||o.callback({statusCode:0,error:v})}};h!=="sendBeacon"&&o.data&&o.compression===xe.GZipJS&&Ih&&typeof Promise<"u"&&!Vi?af(o).then((m=>{g(m)})).catch((m=>{if(tl(m))return Vi=!0,void g(b({},o,{compression:void 0,url:Ml(n.url,n.method,void 0,n.timestampMode)}));(v=>{if(!v||typeof v!="object")return!1;var E="name"in v?String(v.name):"";return tl(v)||E===Uc})(m)&&(Vi=!0),g(o)})):f(o)})(b({},e,{callback:n=>{var i,s;this.rateLimiter.checkForLimiting(n),400>n.statusCode||(i=(s=this.config).on_request_error)==null||i.call(s,n),e.callback==null||e.callback(n)}}))):e.fireCallbackOnDrop&&(e.callback==null||e.callback({statusCode:0}))}Pn(e){this.Rn?this.Rn.retriableRequest(e):this._send_request(e)}_execute_array(e){Fr++;try{var n,i=[],s=[],r=[];Ai(e,(a=>{if(a)if(O(n=a[0]))r.push(a);else if(Se(a))try{a.call(this)}catch(l){k.error("Error executing queued PostHog call",a,l)}else O(a)&&n==="alias"?i.push(a):O(a)&&n.indexOf("capture")!==-1&&Se(this[n])?r.push(a):s.push(a)}));var o=function(a,l){Ai(a,(function(u){try{if(O(u[0])){var c=l;Z(u,(function(d){c=c[d[0]].apply(c,d.slice(1))}))}else l[u[0]].apply(l,u.slice(1))}catch(d){k.error("Error executing queued PostHog call",u,d)}}))};o(i,this),o(s,this),o(r,this)}finally{Fr--}}push(e){if(Fr>0&&O(e)&&q(e[0])){var n=Re.prototype[e[0]];Se(n)&&n.apply(this,e.slice(1))}else this._execute_array([e])}capture(e,n,i){var s,r,o,a,l;if(this.__loaded&&this.persistence&&this.sessionPersistence&&this.In){if(this.is_capturing())if(!x(e)&&q(e)){var u=!this.config.opt_out_useragent_filter&&this._is_bot();if(!u||this.config.__preview_capture_bot_pageviews){var c=i!=null&&i.skip_client_rate_limiting?void 0:this.rateLimiter.clientRateLimitContext();if(c==null||!c.isRateLimited){n!=null&&n.$current_url&&!q(n?.$current_url)&&(k.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"||i!=null&&i.Wn||k.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&&this.sessionPersistence.update_campaign_params(),this.config.save_referrer&&this.sessionPersistence.update_referrer_info(),(this.config.save_campaign_params||this.config.save_referrer)&&this.persistence.set_initial_person_info();var d=new Date,h=i?.timestamp||d,p=ol(i?.uuid,ft),f={uuid:p,event:e,properties:this.calculateEventProperties(e,n||{},h,p)};e===cn&&this.config.__preview_capture_bot_pageviews&&u&&(f.event="$bot_pageview",f.properties.$browser_type="bot"),c&&(f.properties.$lib_rate_limit_remaining_tokens=c.remainingTokens);var g=e==="$feature_flag_called"&&f.properties.$feature_flag_has_experiment===!1&&this.get_property(cs)===!0;i?.$set&&!g&&(f.$set=i?.$set);var m=i?.$unset;m&&(f.$unset=m);var v,E,w,I=g?void 0:this.Vn(i?.$set_once,e!==hl,e===vr);if(I&&(f.$set_once=I),i!=null&&i._noTruncate||(r=this.config.properties_string_max_length,o=f,a=N=>q(N)?N.slice(0,r):N,l=new Set,f=(function N(P,z){if(P!==Object(P))return a?a(P):P;if(!l.has(P)){var H;if(l.add(P),O(P))H=[],Ai(P,(Q=>{H.push(N(Q))}));else{var U={};Z(P,((Q,fe)=>{l.has(Q)||(U[fe]=N(Q))})),H=U}return H}})(o)),f.timestamp=h,x(i?.timestamp)||(f.properties.$event_time_override_provided=!0,f.properties.$event_time_override_system_time=d),g&&(f.properties=(function(N,P){P===void 0&&(P=[]);var z={},H=U=>{N[U]!==void 0&&(z[U]=N[U])};return Ch.forEach(H),P.forEach(H),z})(f.properties,xf)),e===vt.DISMISSED||e===vt.SENT){var A=n?.[xr.SURVEY_ID],F=n?.[xr.SURVEY_ITERATION];yd({id:A,current_iteration:F}),f.$set=b({},f.$set,{[(v={id:A,current_iteration:F},E=e===vt.SENT?"responded":"dismissed",w="$survey_"+E+"/"+v.id,v.current_iteration&&v.current_iteration>0&&(w="$survey_"+E+"/"+v.id+"/"+v.current_iteration),w)]:!0})}else e===vt.SHOWN&&(f.$set=b({},f.$set,{[xr.SURVEY_LAST_SEEN_DATE]:new Date().toISOString()}));if(e===Xp.SHOWN){var D=n?.[Fl.TOUR_TYPE];D&&(f.$set=b({},f.$set,{[Fl.TOUR_LAST_SEEN_DATE+"/"+D]:new Date().toISOString()}))}var S=b({},f.properties.$set,f.$set);if(yt(S)||this.setPersonPropertiesForFlags(S),!B(this.config.before_send)){var $=this.Pt(f);if(!$)return;(f=$).uuid=ol(f.uuid,ft)}this.dn.emit("eventCaptured",f);var T=(s=i?._url)!==null&&s!==void 0?s:this.requestRouter.endpointFor("api",this.analyticsDefaultEndpoint),M={method:"POST",url:T,data:f,compression:"best-available",timestampMode:i?._batchKey==="recordings"||/\/s\/(?:\?|$)/.test(T)?"body":"capture-body",batchKey:i?._batchKey,transport:i?.transport};return!this.config.request_batching||i&&(i==null||!i._batchKey)||i!=null&&i.send_instantly?this.Pn(M):this.In.enqueue(M),f}k.critical("This capture call is ignored due to client rate limiting.")}}else k.error("No event name provided to posthog.capture")}else k.uninitializedWarning("posthog.capture")}_addCaptureHook(e){return this.on("eventCaptured",(n=>e(n.event,n)))}$n(){var e;return(e=this.jn)!==null&&e!==void 0?e:this.jn=new Sf(this)}cn(e){this._n.push(e);var n=!0;return()=>{if(n){n=!1;var i=this._n.indexOf(e);i!==-1&&this._n.splice(i,1)}}}calculateEventProperties(e,n,i,s,r){if(i=i||new Date,!this.persistence||!this.sessionPersistence)return n;var o=r?void 0:this.persistence.remove_event_timer(e),a=b({},n);if(a.token=this.config.token,a.$config_defaults=this.config.defaults,this.gn()&&(a[Cu]=!0),e==="$snapshot"){var l=b({},this.persistence.properties(),this.sessionPersistence.properties());return a.distinct_id=l.distinct_id,(!q(a.distinct_id)&&!he(a.distinct_id)||Gr(a.distinct_id))&&k.error("Invalid distinct_id for replay event. This indicates a bug in your implementation"),a}var u,c=(function(A,F,D,S){var $,T,M,N;if(S===void 0&&(S=!1),!Fe)return{};var P,z=A?[...bn,...F||[]]:[],H=(function(Si){for(var je=0;sl.length>je;je++){var xi=sl[je],tn=xi[1],nn=xi[0].exec(Si),$n=nn&&(Se(tn)?tn(nn,Si):tn);if($n)return $n}return["",""]})(Fe),U=H[0],Q=H[1],fe=(P=typeof navigator<"u"?navigator:void 0)!=null&&P.brave?{brave:!0}:{},Ie={};x(D)||(Ie.detectGoogleSearchApp=D);var _e={},Ce=($=navigator)==null||($=$.userAgentData)==null?void 0:$.platform,Te=(T=navigator)==null?void 0:T.maxTouchPoints,ae=_==null||(M=_.screen)==null?void 0:M.width,me=_==null||(N=_.screen)==null?void 0:N.height,ge=_?.devicePixelRatio;x(Ce)||(_e.userAgentDataPlatform=Ce),x(Te)||(_e.maxTouchPoints=Te),x(ae)||(_e.screenWidth=ae),x(me)||(_e.screenHeight=me),x(ge)||(_e.devicePixelRatio=ge);var Qe,Lt,de,Ge,It,Pn,De,Ae,Ei=te(ra({$os:U,$os_version:Q,$browser:hu(Fe,navigator.vendor,fe,Ie),$device:rl(Fe),$device_type:(Lt=Fe,de=_e,Ae=rl(Lt),Ae===Kc||Ae===Gc||Ae==="Kobo"||Ae==="Kindle Fire"||Ae===au?vn:Ae===ri||Ae===gn||Ae===oi||Ae===Jr?"Console":Ae===Yc?"Wearable":Ae?Oe:de?.userAgentDataPlatform==="Android"&&((Ge=de?.maxTouchPoints)!==null&&Ge!==void 0?Ge:0)>0?600>Math.min((It=de?.screenWidth)!==null&&It!==void 0?It:0,(Pn=de?.screenHeight)!==null&&Pn!==void 0?Pn:0)/((De=de?.devicePixelRatio)!==null&&De!==void 0?De:1)?Oe:vn:"Desktop"),$timezone:ed(),$timezone_offset:Jp()}),{$current_url:ci(S?Pt(se?.href):se?.href,z,ui),$host:se?.host,$pathname:se?.pathname,$raw_user_agent:Fe.length>1e3?Fe.substring(0,997)+"...":Fe,$browser_version:Vh(Fe,navigator.vendor,fe,Ie),$browser_language:Al(),$browser_language_prefix:(Qe=Al(),typeof Qe=="string"?Qe.split("-")[0]:void 0),$screen_height:_?.screen.height,$screen_width:_?.screen.width,$viewport_height:_?.innerHeight,$viewport_width:_?.innerWidth,$lib:Y.LIB_NAME,$lib_version:Y.LIB_VERSION,$insert_id:Math.random().toString(36).substring(2,10)+Math.random().toString(36).substring(2,10),$time:Date.now()/1e3});return Y.SDK_DIST_CHANNEL&&(Ei.$sdk_dist_channel=Y.SDK_DIST_CHANNEL),Ei})(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){var d=this.sessionManager.checkAndGetSessionAndWindowId(r,i.getTime()),h=d.windowId;a.$session_id=d.sessionId,a.$window_id=h}this.sessionPropsManager&&te(a,this.sessionPropsManager.getSessionProps());try{var p;this.sessionRecording&&te(a,this.sessionRecording.sdkDebugProperties),a.$sdk_debug_retry_queue_size=(p=this.Rn)==null?void 0:p.length}catch(A){a.$sdk_debug_error_capturing_properties=String(A)}if(this.requestRouter.region===xo&&(a.$lib_custom_api_host=this.config.api_host),u=e!==cn||r?e!==mr||r?this.pageViewManager.doEvent():this.pageViewManager.doPageLeave(i):this.pageViewManager.doPageView(i,s),a=te(a,u),e===cn&&C&&(a.title=C.title),!x(o)){var f=i.getTime()-o;a.$duration=parseFloat((f/1e3).toFixed(3))}Fe&&this.config.opt_out_useragent_filter&&(a.$browser_type=this._is_bot()?"bot":"browser");var g=this.persistence.properties(),m=this.sessionPersistence.properties();Z(["$referrer","$referring_domain"],(A=>{A in g&&delete m[A]}));var v={};if(this._n.length>0)for(var E of this._n.slice())try{te(v,E())}catch(A){k.error("Failed to produce browser extension event properties",A)}(a=te({},c,g,m,b({},v,a))).$is_identified=this._isIdentified(),O(this.config.property_denylist)?Z(this.config.property_denylist,(function(A){delete a[A]})):k.error(wd+this.config.property_denylist+" or property_blacklist config: "+this.config.property_blacklist);var w=this.config.sanitize_properties;w&&(k.error(Ul),a=w(a,e));var I=this.Zn();return a.$process_person_profile=I,I&&!r&&this.Gn("_calculate_event_properties"),a}Vn(e,n,i){var s;if(n===void 0&&(n=!0),i===void 0&&(i=!1),!this.persistence||!this.Zn()||this.mn&&!i)return e;var r=this.persistence.get_initial_props(),o=(s=this.sessionPropsManager)==null?void 0:s.getSetOnceProps(),a=te({},r,o||{},e||{}),l=this.config.sanitize_properties;return l&&(k.error(Ul),a=l(a,"$set_once")),n&&(this.mn=!0),yt(a)?void 0:a}register(e,n){var i;(i=this.persistence)==null||i.register(e,n)}register_once(e,n,i){var s;(s=this.persistence)==null||s.register_once(e,n,i)}register_for_session(e){var n;(n=this.sessionPersistence)==null||n.register(e),Object.keys(e).forEach((i=>this.yn.add(i))),this.Qn()}unregister(e){var n;(n=this.persistence)==null||n.unregister(e)}unregister_for_session(e){var n;(n=this.sessionPersistence)==null||n.unregister(e),this.yn.delete(e),this.Qn()}Kn(e,n){this.register({[e]:n})}An(){this.yn.forEach((e=>{var n;(n=this.sessionPersistence)==null||n.unregister(e)})),this.yn.clear(),this.Qn()}Qn(){var e;if(this.bn)if(this.config.persistence==="memory"||(e=this.sessionPersistence)!=null&&e.xi||!ce.N())ce.q(this.bn);else{var n=[];this.yn.forEach((i=>n.push(i))),n.length>0?ce.F(this.bn,n):ce.q(this.bn)}}getFeatureFlag(e,n){var i;return(i=this.featureFlags)==null?void 0:i.getFeatureFlag(e,n)}getFeatureFlagPayload(e){var n;return(n=this.featureFlags)==null?void 0:n.getFeatureFlagPayload(e)}getFeatureFlagResult(e,n){var i;return(i=this.featureFlags)==null?void 0:i.getFeatureFlagResult(e,n)}getAllFeatureFlags(){var e,n;return(e=(n=this.featureFlags)==null?void 0:n.getAllFeatureFlags())!==null&&e!==void 0?e:[]}isFeatureEnabled(e,n){var i,s;return(i=(s=this.featureFlags)==null?void 0:s.isFeatureEnabled(e,n))!==null&&i!==void 0?i:n?.defaultValue}reloadFeatureFlags(){var e;(e=this.featureFlags)==null||e.reloadFeatureFlags()}updateFlags(e,n,i){var s;(s=this.featureFlags)==null||s.updateFlags(e,n,i)}updateEarlyAccessFeatureEnrollment(e,n,i){var s;(s=this.featureFlags)==null||s.updateEarlyAccessFeatureEnrollment(e,n,i)}getEarlyAccessFeatures(e,n,i){var s;return n===void 0&&(n=!1),(s=this.featureFlags)==null?void 0:s.getEarlyAccessFeatures(e,n,i)}on(e,n){return this.dn.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:Dn}),()=>{})}onSessionId(e){var n,i;return(n=(i=this.sessionManager)==null?void 0:i.onSessionId(e))!==null&&n!==void 0?n:()=>{}}getSurveys(e,n){n===void 0&&(n=!1),this.surveys?this.surveys.getSurveys(e,n):e([],{isLoaded:!1,error:Dn})}getActiveMatchingSurveys(e,n){n===void 0&&(n=!1),this.surveys?this.surveys.getActiveMatchingSurveys(e,n):e([],{isLoaded:!1,error:Dn})}renderSurvey(e,n){var i;(i=this.surveys)==null||i.renderSurvey(e,n)}displaySurvey(e,n){var i;n===void 0&&(n=vf),(i=this.surveys)==null||i.displaySurvey(e,n)}cancelPendingSurvey(e){var n;(n=this.surveys)==null||n.cancelPendingSurvey(e)}canRenderSurvey(e){var n,i;return(n=(i=this.surveys)==null?void 0:i.canRenderSurvey(e))!==null&&n!==void 0?n:{visible:!1,disabledReason:Dn}}canRenderSurveyAsync(e,n){var i,s;return n===void 0&&(n=!1),(i=(s=this.surveys)==null?void 0:s.canRenderSurveyAsync(e,n))!==null&&i!==void 0?i:Promise.resolve({visible:!1,disabledReason:Dn})}Jn(e){return!e||Gr(e)?(k.critical("Unique user id has not been set in posthog.identify"),!1):e===Ci?(k.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())||(k.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,i){if(!this.__loaded||!this.persistence)return k.uninitializedWarning("posthog.identify");if(he(e)&&(e=e.toString(),k.warn("The first argument to posthog.identify was a number, but it should be a string. It has been converted to a string.")),this.Jn(e)&&this.Gn("posthog.identify")){var s=this.get_distinct_id();this.register({$user_id:e}),this.get_property(ai)||this.register_once({$had_persisted_distinct_id:!0,$device_id:s},""),e!==s&&e!==this.get_property(zn)&&(this.unregister(zn),this.register({distinct_id:e}));var r,o=(this.persistence.get_property(He)||sn)===sn,a=e!==s,l=!a&&o;if(a&&o)this.persistence.set_property(He,Ot),this.setPersonPropertiesForFlags({$set:n||{},$set_once:i||{}},!1),this.capture(vr,{distinct_id:e,$anon_distinct_id:s},{$set:n||{},$set_once:i||{}}),this.Sn=Ar(e,n,i),(r=this.featureFlags)==null||r.setAnonymousDistinctId(s);else if(l){this.persistence.set_property(He,Ot);var u=n||{},c=i||{};this.setPersonPropertiesForFlags({$set:u,$set_once:c},!1),this.capture("$set",{$set:u,$set_once:c}),this.Sn=Ar(e,n,i)}else(n||i)&&this.setPersonProperties(n,i);a?(this.reloadFeatureFlags(),this.featureFlags?this.featureFlags.resetFlagCallReported():this.unregister(Gt)):l&&(n||i)&&this.reloadFeatureFlags()}}setPersonProperties(e,n){if((e||n)&&this.Gn("posthog.setPersonProperties")){var i=Ar(this.get_distinct_id(),e,n);this.Sn!==i?(this.setPersonPropertiesForFlags({$set:e||{},$set_once:n||{}},!0),this.capture("$set",{$set:e||{},$set_once:n||{}}),this.Sn=i):k.info("A duplicate setPersonProperties call was made with the same properties. It has been ignored.")}}unsetPersonProperties(e){var n,i=(O(e)?e:[e]).filter((s=>q(s)&&s.length>0));i.length!==0&&this.Gn("posthog.unsetPersonProperties")&&((n=this.featureFlags)==null||n.unsetPersonPropertiesForFlags(i,!0),this.capture("$set",{$unset:i}),this.Sn=null)}group(e,n,i){if(e&&n){var s=this.getGroups(),r=s[e]!==n;if(r&&this.resetGroupPropertiesForFlags(e),this.register({$groups:b({},s,{[e]:n})}),r||i){var o={$group_type:e,$group_key:n};i&&(o.$group_set=i),this.capture(hl,o)}i&&this.setGroupPropertiesForFlags({[e]:i}),r&&!i&&this.reloadFeatureFlags()}else k.error("posthog.group requires a group type and group key")}resetGroups(){this.register({$groups:{}}),this.resetGroupPropertiesForFlags(),this.reloadFeatureFlags()}setPersonPropertiesForFlags(e,n){var i;n===void 0&&(n=!0),(i=this.featureFlags)==null||i.setPersonPropertiesForFlags(e,n)}resetPersonPropertiesForFlags(e){var n;e===void 0&&(e=!0),(n=this.featureFlags)==null||n.resetPersonPropertiesForFlags(e)}setGroupPropertiesForFlags(e,n){var i;n===void 0&&(n=!0),this.Gn("posthog.setGroupPropertiesForFlags")&&((i=this.featureFlags)==null||i.setGroupPropertiesForFlags(e,n))}resetGroupPropertiesForFlags(e){var n;(n=this.featureFlags)==null||n.resetGroupPropertiesForFlags(e)}reset(e){this.Yn(e)}Yn(e,n){var i,s,r,o,a,l,u,c,d,h;if(n===void 0&&(n=!1),k.info("reset"),!this.__loaded)return k.uninitializedWarning("posthog.reset");var p,f=this.get_property(ai),g=this.get_property(gr),m=this.get_property(Jt),v=this.is_capturing();if(this.consent.reset(),n||!v||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."),(i=this.persistence)==null||i.clear(),(s=this.sessionPersistence)==null||s.clear(),this.yn.clear(),this.Qn(),x(m)||(p=this.persistence)==null||p.register({[Jt]:m}),(r=this.surveys)==null||r.reset(),(o=this.Un)==null||o.stop(),(a=this.featureFlags)==null||a.reset(),(l=this.conversations)==null||l.reset(),(u=this.logs)==null||u.reset(),(c=this.metrics)==null||c.reset(),(d=this.persistence)==null||d.set_property(He,sn),(h=this.sessionManager)==null||h.resetSessionId(),this.Sn=null,this.config.cookieless_mode===gt)this.register_once({distinct_id:Ci,$device_id:null},"");else{var E=this.config.get_device_id(ft());this.register_once({distinct_id:E,$device_id:e?E:f},""),e||x(g)||this.register({[gr]:g})}this.register({$last_posthog_reset:new Date().toISOString()},1),delete this.config.identity_distinct_id,delete this.config.identity_hash,this.reloadFeatureFlags()}shutdown(e){var n=this;return X((function*(){var i,s,r,o,a,l,u;if(n.__loaded){(i=n.Un)==null||i.stop(),(s=n.jn)==null||s.dispose(),(r=n.sessionRecording)==null||r.dispose(),(o=n.logs)==null||o.flushLogs("sendBeacon"),(a=n.metrics)==null||a.flush("sendBeacon"),(l=n.In)==null||l.unload(),(u=n.Rn)==null||u.unload();try{var c;(c=n.featureFlags)==null||c.destroy()}catch(d){k.error("Error while destroying feature flags",d)}}else k.uninitializedWarning("posthog.shutdown")}))()}setIdentity(e,n){var i;this.config.identity_distinct_id=e,this.config.identity_hash=n,this.alias(e),(i=this.conversations)==null||i.Xn()}clearIdentity(){var e;delete this.config.identity_distinct_id,delete this.config.identity_hash,(e=this.conversations)==null||e.ts()}get_distinct_id(){return this.get_property("distinct_id")}getGroups(){return this.get_property("$groups")||{}}get_session_id(){var e,n;return(e=(n=this.sessionManager)==null?void 0:n.checkAndGetSessionAndWindowId(!0).sessionId)!==null&&e!==void 0?e:""}get_session_replay_url(e){if(!this.sessionManager)return"";var n=this.sessionManager.checkAndGetSessionAndWindowId(!0),i=n.sessionStartTimestamp,s=this.requestRouter.endpointFor("ui","/project/"+this.config.token+"/replay/"+n.sessionId);if(e!=null&&e.withTimestamp&&i){var r,o=(r=e.timestampLookBack)!==null&&r!==void 0?r:10;if(!i)return s;s+="?t="+Math.max(Math.floor((new Date().getTime()-i)/1e3)-o,0)}return s}alias(e,n){return e===this.get_property(bu)?(k.critical("Attempting to create alias for existing People user - aborting."),-2):this.Gn("posthog.alias")?(x(n)&&(n=this.get_distinct_id()),e!==n?(this.Kn(zn,e),this.capture("$create_alias",{alias:e,distinct_id:n})):(k.warn("alias matches current distinct_id - skipping api call."),this.identify(e),-1)):void 0}set_config(e){var n=b({},this.config);if(ne(e)){var i,s,r,o,a,l,u,c,d,h,p,f;te(this.config,Hl(e));var g=this.En();(i=this.persistence)==null||i.update_config(this.config,n,g),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new Er(b({},this.config,{persistence:"sessionStorage"}),g,!1);var m=this.Cn(this.config.debug);Ye(m)&&(this.config.debug=m),Ye(this.config.debug)&&(this.config.debug?(Y.DEBUG=!0,ee.N()&&ee.F("ph_debug",!0),k.info("set_config",{config:e,oldConfig:n,newConfig:b({},this.config)})):(Y.DEBUG=!1,ee.N()&&ee.q("ph_debug"))),(s=this.featureFlags)==null||s.updateConfig==null||s.updateConfig(this.config,this.Qi()),(r=this.exceptionObserver)==null||r.onConfigChange(),(o=this.exceptions)==null||o.onConfigChange(),(a=this.sessionRecording)==null||a.startIfEnabledOrStop(),(l=this.tracingHeaders)==null||l.startIfEnabledOrStop(),(u=this.autocapture)==null||u.startIfEnabled(),(c=this.heatmaps)==null||c.startIfEnabled(),(d=this.exceptionObserver)==null||d.startIfEnabledOrStop(),(h=this.deadClicksAutocapture)==null||h.startIfEnabledOrStop(),(p=this.surveys)==null||p.loadIfEnabled(),this.es(),(f=this.externalIntegrations)==null||f.startIfEnabledOrStop()}}_overrideSDKInfo(e,n){Y.LIB_NAME=e,Y.LIB_VERSION=n}startSessionRecording(e){var n,i,s,r,o,a=e===!0,l={sampling:a||!(e==null||!e.sampling),linked_flag:a||!(e==null||!e.linked_flag),url_trigger:a||!(e==null||!e.url_trigger),event_trigger:a||!(e==null||!e.event_trigger)};Object.values(l).some(Boolean)&&((n=this.sessionManager)==null||n.checkAndGetSessionAndWindowId(),l.sampling&&((i=this.sessionRecording)==null||i.overrideSampling()),l.linked_flag&&((s=this.sessionRecording)==null||s.overrideLinkedFlag()),l.url_trigger&&((r=this.sessionRecording)==null||r.overrideTrigger("url")),l.event_trigger&&((o=this.sessionRecording)==null||o.overrideTrigger("event"))),this.set_config({disable_session_recording:!1})}stopSessionRecording(){this.set_config({disable_session_recording:!0})}sessionRecordingStarted(){var e;return!((e=this.sessionRecording)==null||!e.started)}captureException(e,n){if(this.exceptions){var i=new Error("PostHog syntheticException"),s=this.exceptions.buildProperties(e,{handled:!0,syntheticException:i});return this.exceptions.sendExceptionEvent(b({},s,n))}}addExceptionStep(e,n){var i;(i=this.exceptions)==null||i.addExceptionStep(e,n)}captureLog(e){var n;(n=this.logs)==null||n.captureLog(e)}get logger(){var e,n;return(e=(n=this.logs)==null?void 0:n.logger)!==null&&e!==void 0?e:Re.rs}startExceptionAutocapture(e){this.set_config({capture_exceptions:e==null||e})}stopExceptionAutocapture(){this.set_config({capture_exceptions:!1})}loadToolbar(e){var n,i;return(n=(i=this.toolbar)==null?void 0:i.loadToolbar(e))!==null&&n!==void 0&&n}get_property(e){var n;return(n=this.persistence)==null?void 0:n.props[e]}getSessionProperty(e){var n;return(n=this.sessionPersistence)==null?void 0:n.props[e]}toString(){var e,n=(e=this.config.name)!==null&&e!==void 0?e:un;return n!==un&&(n=un+"."+n),n}_isIdentified(){var e,n;return((e=this.persistence)==null?void 0:e.get_property(He))===Ot||((n=this.sessionPersistence)==null?void 0:n.get_property(He))===Ot}Zn(){var e,n;return!(this.config.person_profiles==="never"||this.config.person_profiles===fo&&!this._isIdentified()&&yt(this.getGroups())&&((e=this.persistence)==null||(e=e.props)==null||!e[zn])&&((n=this.persistence)==null||(n=n.props)==null||!n[hs]))}zn(){return this.config.capture_pageleave===!0||this.config.capture_pageleave==="if_capture_pageview"&&(this.config.capture_pageview===!0||this.config.capture_pageview==="history_change")}createPersonProfile(){this.Zn()||this.Gn("posthog.createPersonProfile")&&this.setPersonProperties({},{})}setInternalOrTestUser(){this.Gn("posthog.setInternalOrTestUser")&&this.setPersonProperties({$internal_or_test_user:!0})}Gn(e){return this.config.person_profiles==="never"?(k.error(e+' was called, but process_person is set to "never". This call will be ignored.'),!1):(this.Kn(hs,!0),!0)}En(){if(this.config.cookieless_mode==="always")return!0;var e=this.consent.isOptedOut();return this.config.disable_persistence||e&&!(!this.config.opt_out_persistence_by_default&&this.config.cookieless_mode!==Vt)}es(){var e,n,i,s,r=this.En();return((e=this.persistence)==null?void 0:e.xi)!==r&&((i=this.persistence)==null||i.set_disabled(r)),((n=this.sessionPersistence)==null?void 0:n.xi)!==r&&((s=this.sessionPersistence)==null||s.set_disabled(r)),r&&(this.yn.clear(),this.Qn()),r}opt_in_capturing(e){var n;if(this.config.cookieless_mode!==gt){if(this.gn()){var i,s,r,o,a;this.Yn(!0,!0),(i=this.sessionManager)==null||i.destroy(),(s=this.pageViewManager)==null||s.destroy(),this.sessionManager=new Ol(this),this.pageViewManager=new Cl(this),this.persistence&&(this.sessionPropsManager=new Ll(this,this.sessionManager,this.persistence));var l,u=(r=(o=this.config.__extensionClasses)==null?void 0:o.sessionRecording)!==null&&r!==void 0?r:(a=Re.__defaultExtensionClasses)==null?void 0:a.sessionRecording;u&&(this.sessionRecording=this.pn(this.sessionRecording,new u(this)),this.hn&&((l=this.sessionRecording)==null||l.onRemoteConfig==null||l.onRemoteConfig(this.hn)))}var c,d;this.consent.optInOut(!0),this.es(),this.Bn(),(n=this.sessionRecording)==null||n.startIfEnabledOrStop(),this.config.cookieless_mode==Vt&&((c=this.surveys)==null||c.loadIfEnabled()),(x(e?.captureEventName)||e!=null&&e.captureEventName)&&this.capture((d=e?.captureEventName)!==null&&d!==void 0?d:"$opt_in",e?.captureProperties,{send_instantly:!0}),this.config.capture_pageview&&this.Hn()}else k.warn(jl)}opt_out_capturing(){var e,n,i;this.config.cookieless_mode!==gt?(this.config.cookieless_mode===Vt&&this.consent.isOptedIn()&&this.Yn(!0,!0),this.consent.optInOut(!1),this.es(),this.config.cookieless_mode===Vt&&(this.register({distinct_id:Ci,$device_id:null}),(e=this.sessionRecording)==null||e.stopRecording(),this.sessionRecording=void 0,(n=this.sessionManager)==null||n.destroy(),(i=this.pageViewManager)==null||i.destroy(),this.sessionManager=void 0,this.sessionPropsManager=void 0,this.config.capture_pageview&&this.Hn(),this.Bn())):k.warn(jl)}has_opted_in_capturing(){return this.consent.isOptedIn()}has_opted_out_capturing(){return this.consent.isOptedOut()}get_explicit_consent_status(){var e=this.consent.consent;return e===1?"granted":e===0?"denied":"pending"}is_capturing(){return this.config.cookieless_mode===gt||(this.config.cookieless_mode===Vt?this.consent.isRejected()||this.consent.isOptedIn():!this.has_opted_out_capturing())}clear_opt_in_out_capturing(){this.consent.reset(),this.es()}_is_bot(){return ke?pd(ke,this.config.custom_blocked_useragents):void 0}Hn(){C&&(C.visibilityState==="visible"?this.wn||(this.wn=!0,this.capture(cn,{title:C.title},{send_instantly:!0}),this.kn&&(C.removeEventListener(ps,this.kn),this.kn=null)):this.kn||(this.kn=this.Hn.bind(this),re(C,ps,this.kn)))}debug(e){e===!1?(_?.console.log("You've disabled debug mode."),this.set_config({debug:!1})):(_?.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}))}Qi(){var e=this.Mn||{};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?(k.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,i,s,r,o){var a=i in n&&!B(n[i]),l=s in n&&!B(n[s]);return a?n[i]:!!l&&(o&&o.warn("Config field '"+s+"' is deprecated. Please use '"+i+"' instead. The old field will be removed in a future major version."),n[s])})(e,"advanced_disable_flags","advanced_disable_decide",0,k)}Pt(e){var n;if(B(this.config.before_send))return e;var i=Object.keys((n=e.properties)!==null&&n!==void 0?n:{}).filter(Nh),s=O(this.config.before_send)?this.config.before_send:[this.config.before_send],r=e;for(var o of s){if(r=o(r),B(r)){var a="Event '"+e.event+"' was rejected in beforeSend function";return Rh(e.event)?k.warn(a+". This can cause unexpected behavior."):k.info(a),null}r.properties&&!yt(r.properties)||k.warn("Event '"+e.event+"' has no properties after beforeSend function, this is likely an error.")}for(var l of i)if(r.properties&&B(r.properties[l]))return k.warn("Event '"+e.event+"' had its '"+l+"' property removed in a beforeSend function. This property is required for ingestion, so the event will be dropped."),null;return r}getPageViewId(){var e;return(e=this.pageViewManager.ui)==null?void 0:e.pageViewId}captureTraceFeedback(e,n){this.capture("$ai_feedback",{$ai_trace_id:String(e),$ai_feedback_text:n})}captureTraceMetric(e,n,i){this.capture("$ai_metric",{$ai_trace_id:String(e),$ai_metric_name:n,$ai_metric_value:String(i)})}Cn(e){var n=Ye(e)&&!e,i=ee.N()&&ee.P("ph_debug")==="true";return!n&&(!!i||e)}}Re.__defaultExtensionClasses={},Re.rs=(()=>{var t=()=>{};return{trace:t,debug:t,info:t,warn:t,error:t,fatal:t}})(),(function(t,e){for(var n=0;e.length>n;n++)t.prototype[e[n]]=Ep(t.prototype[e[n]])})(Re,["identify"]);class Wl{constructor(e){this.disabled=e===!1;var n=ne(e)?e:{};this.thresholdPx=n.threshold_px||30,this.timeoutMs=n.timeout_ms||1e3,this.clickCount=n.click_count||3,this.clicks=[]}isRageClick(e,n,i){if(this.disabled)return!1;var s=this.clicks[this.clicks.length-1];if(s&&Math.abs(e-s.x)+Math.abs(n-s.y)i-s.timestamp){if(this.clicks.push({x:e,y:n,timestamp:i}),this.clicks.length===this.clickCount)return!0}else this.clicks=[{x:e,y:n,timestamp:i}];return!1}}var $r="$copy_autocapture",Tr=ie("[AutoCapture]");function Rr(t,e){return e.length>t?e.slice(0,t)+"...":e}function Cf(t){if(t.previousElementSibling)return t.previousElementSibling;var e=t;do e=e.previousSibling;while(e&&!$t(e));return e}function Af(t,e){var n,i,s=e.e,r=e.maskAllElementAttributes,o=e.maskAllText,a=e.elementAttributeIgnoreList,l=e.elementsChainAsString,u=e.disableCaptureUrlHashes;if(!$t(t))return{props:{}};for(var c=[t],d=new Set([t]),h=t;h.parentNode&&!Me(h,"body")&&Ou>c.length;)if(Lu(h.parentNode)){var p=h.parentNode.host;if(d.has(p))break;d.add(p),c.push(p),h=p}else{if(!$t(h.parentNode)||d.has(h.parentNode))break;d.add(h.parentNode),c.push(h.parentNode),h=h.parentNode}var f,g,m=[],v={},E=!1,w=!1;if(Z(c,(S=>{var $=vo(S);if(Me(S,"a")){var T=S.getAttribute("href");E=!!($&&T&&Qn(T))&&(u?Pt(T):T)}L(ms(S),"ph-no-capture")&&(w=!0),m.push((function(N,P,z,H,U){U===void 0&&(U=!1);var Q=N.tagName.toLowerCase(),fe={tag_name:Q};aa.indexOf(Q)>-1&&!z&&(fe.$el_text=Q.toLowerCase()==="a"||Q.toLowerCase()==="button"?Rr(1024,xl(N)):Rr(1024,li(N)));var Ie=ms(N);Ie.length>0&&(fe.classes=Ie.filter((function(ae){return ae!==""}))),Z(N.attributes,(function(ae){var me;if((!Hu(N)||["name","id","class","aria-label"].indexOf(ae.name)!==-1)&&(H==null||!H.includes(ae.name))&&!P&&Qn(ae.value)&&(!q(me=ae.name)||me.substring(0,10)!=="_ngcontent"&&me.substring(0,7)!=="_nghost")){var ge=ae.value;ae.name==="class"&&(ge=oa(ge).join(" ")),fe["attr__"+ae.name]=Rr(1024,ae.name==="href"&&U?Pt(ge):ge)}}));for(var _e=1,Ce=1,Te=N;Te=Cf(Te);)_e++,Te.tagName===N.tagName&&Ce++;return fe.nth_child=_e,fe.nth_of_type=Ce,fe})(S,r,o,a,u));var M=(function(N){if(!vo(N))return{};var P={};return Z(N.attributes,(function(z){if(z.name&&z.name.indexOf("data-ph-capture-attribute")===0){var H=z.name.replace("data-ph-capture-attribute-",""),U=z.value;H&&U&&Qn(U)&&(P[H]=U)}})),P})(S);te(v,M)})),w)return{props:{},explicitNoCapture:w};if(o||(m[0].$el_text=Me(t,"a")||Me(t,"button")?xl(t):li(t)),E){var I,A;m[0].attr__href=E;var F=(I=vs(E))==null?void 0:I.host,D=_==null||(A=_.location)==null?void 0:A.host;F&&D&&F!==D&&(f=E)}return{props:te({$event_type:s.type,$ce_version:1},l?{}:{$elements:m},{$elements_chain:(g=m,(function(S){return S.map(($=>{var T,M,N="";if($.tag_name&&(N+=$.tag_name),$.attr_class)for(var P of($.attr_class.sort(),$.attr_class))N+="."+P.replace(/"/g,"");var z=b({},$.text?{text:$.text}:{},{"nth-child":(T=$.nth_child)!==null&&T!==void 0?T:0,"nth-of-type":(M=$.nth_of_type)!==null&&M!==void 0?M:0},$.href?{href:$.href}:{},$.attr_id?{attr_id:$.attr_id}:{},$.attributes),H={};return qi(z).sort(((U,Q)=>U[0].localeCompare(Q[0]))).forEach((U=>{var Q=U[1];return H[kl(U[0].toString())]=kl(Q.toString())})),(N+=":")+qi(H).map((U=>U[0]+'="'+U[1]+'"')).join("")})).join(";")})((function(S){return S.map(($=>{var T,M,N={text:(T=$.$el_text)==null?void 0:T.slice(0,400),tag_name:$.tag_name,href:(M=$.attr__href)==null?void 0:M.slice(0,2048),attr_class:Up($),attr_id:$.attr__id,nth_child:$.nth_child,nth_of_type:$.nth_of_type,attributes:{}};return qi($).filter((P=>P[0].indexOf("attr__")===0)).forEach((P=>N.attributes[P[0]]=P[1])),N}))})(g)))},(n=m[0])!=null&&n.$el_text?{$el_text:(i=m[0])==null?void 0:i.$el_text}:{},f&&s.type==="click"?{$external_click_url:f}:{},v)}}var jn=ie("[ExceptionAutocapture]"),zl=()=>{},Ff=ie("[TracingHeaders]"),jt=ie("[Web Vitals]"),ql=9e5,Vl="disabled",Gl="lazy_loading",Un="awaiting_config",Ni="missing_config";ie("[SessionRecording]"),ie("[SessionRecording]");var ko="[SessionRecording]",ut=ie(ko),Pf=ie("[Heatmaps]");function Nr(t){return ne(t)&&"clientX"in t&&"clientY"in t&&he(t.clientX)&&he(t.clientY)}var Mi=ie("[Product Tours]"),Mr=t=>{var e;return!t.config.disable_product_tours&&!((e=t.persistence)==null||!e.get_property(na))},$f=["$set_once","$set"],et=ie("[SiteApps]"),Kl="Error while initializing PostHog app with config id ";function an(t,e,n){if(B(t))return!1;switch(n){case"exact":return t===e;case"contains":var i=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/_/g,".").replace(/%/g,".*");return new RegExp(i,"i").test(t);case"regex":try{return new RegExp(e).test(t)}catch{return!1}default:return!1}}class Tf{constructor(e){this.ns=new da,this.ss=(n,i)=>this.os(n,i)&&this.ls(n,i)&&this.us(n,i)&&this.hs(n,i),this.os=(n,i)=>i==null||!i.event||n?.event===i?.event,this._instance=e,this.ds=new Set,this.vs=new Set}init(){var e,n;x((e=this._instance)==null?void 0:e._addCaptureHook)||(n=this._instance)==null||n._addCaptureHook(((i,s)=>{this.on(i,s)}))}register(e){var n,i;if(!x((n=this._instance)==null?void 0:n._addCaptureHook)&&(e.forEach((o=>{var a,l;(a=this.vs)==null||a.add(o),(l=o.steps)==null||l.forEach((u=>{var c;(c=this.ds)==null||c.add(u?.event||"")}))})),(i=this._instance)!=null&&i.autocapture)){var s,r=new Set;e.forEach((o=>{var a;(a=o.steps)==null||a.forEach((l=>{l!=null&&l.selector&&r.add(l?.selector)}))})),(s=this._instance)==null||s.autocapture.setElementSelectors(r)}}on(e,n){var i;n!=null&&e.length!=0&&(this.ds.has(e)||this.ds.has(n.event))&&this.vs&&((i=this.vs)==null?void 0:i.size)>0&&this.vs.forEach((s=>{this.cs(n,s)&&this.ns.emit("actionCaptured",s.name)}))}fs(e){this.onAction("actionCaptured",(n=>e(n)))}cs(e,n){if(n?.steps==null)return!1;for(var i of n.steps)if(this.ss(e,i))return!0;return!1}onAction(e,n){return this.ns.on(e,n)}ls(e,n){if(n!=null&&n.url){var i,s=e==null||(i=e.properties)==null?void 0:i.$current_url;if(!s||typeof s!="string"||!an(s,n.url,n.url_matching||"contains"))return!1}return!0}us(e,n){return!!this.ps(e,n)&&!!this.gs(e,n)&&!!this.ys(e,n)}ps(e,n){var i;if(n==null||!n.href)return!0;var s=this.bs(e);if(s.length>0)return s.some((a=>an(a.href,n.href,n.href_matching||"exact")));var r,o=(e==null||(i=e.properties)==null?void 0:i.$elements_chain)||"";return!!o&&an((r=o.match(/(?::|")href="(.*?)"/))?r[1]:"",n.href,n.href_matching||"exact")}gs(e,n){var i;if(n==null||!n.text)return!0;var s=this.bs(e);if(s.length>0)return s.some((u=>an(u.text,n.text,n.text_matching||"exact")||an(u.$el_text,n.text,n.text_matching||"exact")));var r,o,a,l=(e==null||(i=e.properties)==null?void 0:i.$elements_chain)||"";return!!l&&(r=(function(u){for(var c,d=[],h=/(?::|")text="(.*?)"/g;!B(c=h.exec(u));)d.includes(c[1])||d.push(c[1]);return d})(l),o=n.text,a=n.text_matching||"exact",r.some((u=>an(u,o,a))))}ys(e,n){var i,s;if(n==null||!n.selector)return!0;var r=e==null||(i=e.properties)==null?void 0:i.$element_selectors;if(r!=null&&r.includes(n.selector))return!0;var o=(e==null||(s=e.properties)==null?void 0:s.$elements_chain)||"";if(n.selector_regex&&o)try{return new RegExp(n.selector_regex).test(o)}catch{return!1}return!1}bs(e){var n;return(e==null||(n=e.properties)==null?void 0:n.$elements)==null?[]:e?.properties.$elements}hs(e,n){return n==null||!n.properties||n.properties.length===0||md(n.properties.reduce(((i,s)=>{var r=O(s.value)?s.value.map(String):s.value!=null?[String(s.value)]:[];return i[s.key]={values:r,operator:s.operator||"exact"},i}),{}),e?.properties)}}class Rf{constructor(e){var n;this._s=[],this._instance=e,this.ws=new Map,this.ks=new Map,this.xs=new Map,(n=this._instance)==null||n.onSessionId==null||n.onSessionId((i=>this.Ss(i)))}Cs(e){return!1}Ms(){return null}Ts(e){}Es(){}Is(e,n){return!!e&&md(e.propertyFilters,n?.properties)}Ps(e,n){var i=new Map;return e.forEach((s=>{var r;(r=s.conditions)==null||(r=r[n])==null||(r=r.values)==null||r.forEach((o=>{if(o!=null&&o.name){var a=i.get(o.name)||[];a.push(s.id),i.set(o.name,a)}}))})),i}Rs(e,n,i){var s=(i===Mn.Activation?this.ws:this.ks).get(e),r=[];return this.As((o=>{r=o.filter((a=>s?.includes(a.id)))})),r.filter((o=>{var a,l=(a=o.conditions)==null||(a=a[i])==null||(a=a.values)==null?void 0:a.find((u=>u.name===e));return this.Is(l,n)}))}register(e){var n;x((n=this._instance)==null?void 0:n._addCaptureHook)||(this.Fs(e),this.Ls(e))}Ls(e){var n=e.filter((i=>{var s,r;return((s=i.conditions)==null?void 0:s.actions)&&((r=i.conditions)==null||(r=r.actions)==null||(r=r.values)==null?void 0:r.length)>0}));n.length!==0&&(this.Os==null&&(this.Os=new Tf(this._instance),this.Os.init(),this.Os.fs((i=>{this.onAction(i)}))),n.forEach((i=>{var s,r,o,a,l;i.conditions&&(s=i.conditions)!=null&&s.actions&&(r=i.conditions)!=null&&(r=r.actions)!=null&&r.values&&((o=i.conditions)==null||(o=o.actions)==null||(o=o.values)==null?void 0:o.length)>0&&((a=this.Os)==null||a.register(i.conditions.actions.values),(l=i.conditions)==null||(l=l.actions)==null||(l=l.values)==null||l.forEach((u=>{if(u&&u.name){var c=this.xs.get(u.name);c&&c.push(i.id),this.xs.set(u.name,c||[i.id])}})))})))}Fs(e){var n,i=e.filter((r=>{var o,a;return((o=r.conditions)==null?void 0:o.events)&&((a=r.conditions)==null||(a=a.events)==null||(a=a.values)==null?void 0:a.length)>0})),s=e.filter((r=>{var o,a;return((o=r.conditions)==null?void 0:o.cancelEvents)&&((a=r.conditions)==null||(a=a.cancelEvents)==null||(a=a.values)==null?void 0:a.length)>0}));i.length===0&&s.length===0||((n=this._instance)==null||n._addCaptureHook(((r,o)=>{this.onEvent(r,o)})),this.ws=this.Ps(e,Mn.Activation),this.ks=this.Ps(e,Mn.Cancellation))}onEvent(e,n){var i,s,r=this.Ds(),o=(n==null||(i=n.properties)==null?void 0:i.$survey_id)||(n==null||(s=n.properties)==null?void 0:s.$product_tour_id);if(o&&this.getActivatedIds().includes(o)){var a=this.$s(e,o);if(a==="consume")return r.info("event consumed activated item, removing it",{event:e,itemId:o}),void this.Ns([o]);if(a==="persist")return r.info("shown item promoted to persisted activation",{event:e,itemId:o}),this.qs(o),void this.js([o])}if(this.ks.has(e)){var l=this.Rs(e,n,Mn.Cancellation);l.length>0&&(r.info("cancel event matched, cancelling items",{event:e,itemsToCancel:l.map((c=>c.id))}),this.Ns(l.map((c=>c.id))),l.forEach((c=>this.Bs(c.id))))}if(this.ws.has(e)){r.info("event name matched",{event:e,eventPayload:n,items:this.ws.get(e)});var u=this.Rs(e,n,Mn.Activation);this.Hs(u.map((c=>c.id)))}}onAction(e){this.xs.has(e)&&this.Hs(this.xs.get(e)||[])}Hs(e){var n;if(e.length!==0){var i=!((n=this._instance)==null||n.get_session_id==null||!n.get_session_id()),s=[];for(var r of e)i&&this.Cs(r)?this.qs(r)&&this.Us(r):s.push(r);s.length>0&&(this._s=[...new Set([...this._s,...s])]),this.Ds().info("updating activated items",{activatedItems:this.getActivatedIds()})}}qs(e){this._s=this._s.filter((i=>i!==e));var n=this.zs();return!n.includes(e)&&(this.Ws([...n,e]),this.Vs(),!0)}Ns(e){var n=new Set(e);this._s=this._s.filter((r=>!n.has(r)));var i=this.Zs(),s=i.filter((r=>!n.has(r)));s.length!==i.length&&(this.Ws(s),s.length===0&&this.Gs()),this.js(e)}Qs(){var e,n=this.Ms();if(!n)return{};var i=(e=this._instance)==null||(e=e.persistence)==null?void 0:e.props[n];return i&&typeof i=="object"?i:{}}Us(e){if(this.Ms()){var n=this.Qs();this.Ts(b({},n,{[e]:Date.now()}))}}js(e){if(this.Ms()){var n=this.Qs(),i={},s=!1;for(var r of Object.entries(n)){var o=r[0],a=r[1];e.includes(o)?s=!0:i[o]=a}s&&(yt(i)?this.Es():this.Ts(i))}}Ks(){this.Ms()&&this.Es()}getActivationTimestamp(e){if(this.zs().includes(e)){var n=this.Qs()[e];return he(n)?n:void 0}}Zs(){var e,n=this.Js();return((e=this._instance)==null||(e=e.persistence)==null?void 0:e.props[n])||[]}zs(){var e,n,i=this.Zs();if(i.length===0)return[];var s=(e=this._instance)==null||(e=e.persistence)==null?void 0:e.props[this.Ys()],r=(n=this._instance)==null||n.get_session_id==null?void 0:n.get_session_id();return r&&s===r?i:[]}Vs(){var e,n=(e=this._instance)==null||e.get_session_id==null?void 0:e.get_session_id();n&&this.Xs(n)}Gs(){this.ta()}Ss(e){var n,i=(n=this._instance)==null||(n=n.persistence)==null?void 0:n.props[this.Ys()];if(i&&i!==e){var s=this.Zs(),r=this.Qs();s.length>0&&(this.Ws([]),s.filter((o=>he(r[o]))).forEach((o=>this.Bs(o)))),this.Gs(),this.Ks()}}getActivatedIds(){return[...new Set([...this.zs(),...this._s])].filter((e=>!this.ea(e)))}reset(){this._s=[],this.Zs().length>0&&this.Ws([]),this.Gs(),this.Ks()}getEventToItemsMap(){return this.ws}ia(){return this.Os}}class Nf extends Rf{constructor(e){super(e)}Js(){return lo}Ys(){return Hi}Ms(){return Wi}Ts(e){var n;(n=this._instance)==null||(n=n.persistence)==null||n.register({[Wi]:e})}Es(){var e;(e=this._instance)==null||(e=e.persistence)==null||e.unregister(Wi)}Cs(e){var n,i;this.As((r=>{i=r.find((o=>o.id===e))}));var s=(n=i)==null||(n=n.appearance)==null?void 0:n.surveyPopupDelaySeconds;return he(s)&&s>0}ra(){return vt.SHOWN}As(e){var n;(n=this._instance)==null||n.getSurveys(e)}Bs(e){var n;(n=this._instance)==null||n.cancelPendingSurvey(e)}Ds(){return G}Ws(e){var n;(n=this._instance)==null||(n=n.persistence)==null||n.register({[lo]:e})}Xs(e){var n;(n=this._instance)==null||(n=n.persistence)==null||n.register({[Hi]:e})}ta(){var e;(e=this._instance)==null||(e=e.persistence)==null||e.unregister(Hi)}ea(){return!1}$s(e,n){var i;this.As((r=>{i=r.find((o=>o.id===n))}));var s=!i||(function(r){var o;return vd(r)&&!((o=r.conditions)==null||(o=o.events)==null||!o.repeatedActivation)||r.schedule==="always"})(i);return s?e===vt.SHOWN?"consume":"ignore":e===vt.SHOWN?"persist":e===vt.DISMISSED||e===vt.SENT?"consume":"ignore"}getSurveys(){return this.getActivatedIds()}getEventToSurveys(){return this.getEventToItemsMap()}}var Li="SDK is not enabled or survey functionality is not yet loaded",Jl="Disabled. Not loading surveys.",Mf=_!=null&&_.location?_s(_.location.hash,"__posthog")||_s(location.hash,"state"):null,Yl="_postHogToolbarParams",Zl=ie("[Toolbar]"),Xl=ie("[FeatureFlags]");class Lf{constructor(e,n){n===void 0&&(n=!1),this.na=!1,this.update(e,n)}update(e,n){this.sa=((i,s)=>{var r,o,a,l;return{bootstrap:{featureFlags:(r=i.bootstrap)==null?void 0:r.featureFlags,featureFlagPayloads:(o=i.bootstrap)==null?void 0:o.featureFlagPayloads},remoteRequestsDisabled:s,featureFlagsDisabled:!!i.advanced_disable_feature_flags,onlyEvaluateSurveyFeatureFlags:!!i.advanced_only_evaluate_survey_feature_flags,deduplicateCallsPerSession:!!i.advanced_feature_flags_dedup_per_session,cacheTtlMs:i.feature_flag_cache_ttl_ms,requestTimeoutMs:i.feature_flag_request_timeout_ms,compression:i.disable_compression?"none":"base64",evaluationContexts:(a=(l=i.evaluation_contexts)!==null&&l!==void 0?l:i.evaluation_environments)!==null&&a!==void 0?a:[],flagKeys:O(i.flag_keys)?i.flag_keys:void 0}})(e,n),!e.evaluation_environments||e.evaluation_contexts||this.na||(Xl.warn("evaluation_environments is deprecated. Use evaluation_contexts instead. evaluation_environments will be removed in a future version."),this.na=!0),x(e.flag_keys)||O(e.flag_keys)||Xl.error("Invalid flag_keys found:",e.flag_keys,"Expected array of non-empty strings")}get(){return this.sa}}var Ql=ie("[FeatureFlags]"),Ut=ie("[FeatureFlags]",{debugEnabled:!0}),Lr=`" failed. Feature flags didn't load in time.`,ec="connection_error",tc=t=>{for(var e={},n=0;t.length>n;n++)e[t[n]]=!0;return e},nc=t=>{var e={};for(var n of qi(t||{})){var i=n[1];i&&(e[n[0]]=i)}return e},tt=ie("[Error tracking]"),ic="Refusing to render web experiment since the viewer is a likely bot",Of={icontains:(t,e)=>e.toLowerCase().indexOf(t.toLowerCase())>-1,not_icontains:(t,e)=>e.toLowerCase().indexOf(t.toLowerCase())===-1,regex:(t,e)=>bs(e,t),not_regex:(t,e)=>!bs(e,t),exact:(t,e)=>e===t,is_not:(t,e)=>e!==t};class ye{get Ne(){return this._instance.config}constructor(e){var n=this;this.getWebExperimentsAndEvaluateDisplayLogic=function(i){i===void 0&&(i=!1),n.getWebExperiments((s=>{ye.aa("retrieved web experiments from the server"),n.oa=new Map,s.forEach((r=>{if(r.feature_flag_key){var o;n.oa&&(ye.aa("setting flag key ",r.feature_flag_key," to web experiment ",r),(o=n.oa)==null||o.set(r.feature_flag_key,r));var a=n._instance.getFeatureFlag(r.feature_flag_key);q(a)&&r.variants[a]&&n.la(r.name,a,r.variants[a].transforms)}else if(r.variants)for(var l in r.variants){var u=r.variants[l];ye.ua(u,n._instance)&&n.la(r.name,l,u.transforms)}}))}),i)},this._instance=e,this._instance.onFeatureFlags((i=>{this.onFeatureFlags(i)}))}initialize(){}onFeatureFlags(e){if(this._is_bot())ye.aa(ic);else if(!this.Ne.disable_web_experiments){if(B(this.oa))return this.oa=new Map,this.loadIfEnabled(),void this.previewWebExperiment();ye.aa("applying feature flags",e),e.forEach((n=>{var i;if(this.oa&&(i=this.oa)!=null&&i.has(n)){var s,r=this._instance.getFeatureFlag(n),o=(s=this.oa)==null?void 0:s.get(n);r&&o!=null&&o.variants[r]&&this.la(o.name,r,o.variants[r].transforms)}}))}}previewWebExperiment(){var e=ye.getWindowLocation();if(e!=null&&e.search){var n=wn(e?.search,"__experiment_id"),i=wn(e?.search,"__experiment_variant");n&&i&&(ye.aa("previewing web experiments "+n+" && "+i),this.getWebExperiments((s=>{this.ha(parseInt(n),i,s)}),!1,!0))}}loadIfEnabled(){this.Ne.disable_web_experiments||this.getWebExperimentsAndEvaluateDisplayLogic()}getWebExperiments(e,n,i){if(this.Ne.disable_web_experiments&&!i)return e([]);var 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.Ne.token),method:"GET",timestampMode:"query",callback:r=>e(r.statusCode===200&&r.json&&r.json.experiments||[])})}ha(e,n,i){var s=i.filter((r=>r.id===e));s&&s.length>0&&(ye.aa("Previewing web experiment ["+s[0].name+"] with variant ["+n+"]"),this.la(s[0].name,n,s[0].variants[n].transforms))}static ua(e,n){return!B(e.conditions)&&ye.da(e,n)&&ye.va(e)}static da(e,n){var i;if(B(e.conditions)||B((i=e.conditions)==null?void 0:i.url))return!0;var s=ye.getWindowLocation();if(s){var r,o,a,l=Ru(n,s.href);return(r=e.conditions)==null||!r.url||Of[(o=(a=e.conditions)==null?void 0:a.urlMatchType)!==null&&o!==void 0?o:"icontains"](e.conditions.url,l)}return!1}static getWindowLocation(){return _?.location}static va(e){var n;if(B(e.conditions)||B((n=e.conditions)==null?void 0:n.utm))return!0;var i=Ku();if(i.utm_source){var s,r,o,a,l,u,c,d,h=(s=e.conditions)==null||(s=s.utm)==null||!s.utm_campaign||((r=e.conditions)==null||(r=r.utm)==null?void 0:r.utm_campaign)==i.utm_campaign,p=(o=e.conditions)==null||(o=o.utm)==null||!o.utm_source||((a=e.conditions)==null||(a=a.utm)==null?void 0:a.utm_source)==i.utm_source,f=(l=e.conditions)==null||(l=l.utm)==null||!l.utm_medium||((u=e.conditions)==null||(u=u.utm)==null?void 0:u.utm_medium)==i.utm_medium,g=(c=e.conditions)==null||(c=c.utm)==null||!c.utm_term||((d=e.conditions)==null||(d=d.utm)==null?void 0:d.utm_term)==i.utm_term;return h&&f&&g&&p}return!1}static aa(e){for(var n=arguments.length,i=new Array(n>1?n-1:0),s=1;n>s;s++)i[s-1]=arguments[s];k.info("[WebExperiments] "+e,i)}la(e,n,i){this._is_bot()?ye.aa(ic):n!=="control"?i.forEach((s=>{if(s.selector){var r;ye.aa("applying transform of variant "+n+" for experiment "+e+" ",s);var o=(r=document)==null?void 0:r.querySelectorAll(s.selector);o?.forEach((a=>{var l=a;s.html&&(l.innerHTML=s.html),s.css&&l.setAttribute("style",s.css)}))}})):ye.aa("Control variants leave the page unmodified.")}_is_bot(){return ke&&this._instance?pd(ke,this.Ne.custom_blocked_useragents):void 0}}var Ue=ie("[Conversations]"),Ht="Conversations not available yet.",sc="console",Ed="__posthogHandledLogsRequestError",Or=(t,e)=>{var n=t instanceof Error?t:new Error(e);return n[Ed]=!0,n},rc=t=>!!t&&typeof t=="object"&&t[Ed]===!0,Us={featureFlags:class{constructor(t){this.name="featureFlags",this.ca=!1,this.featureFlagEventHandlers=[],this.rt=Ql,this.fa={},this.pa={},this.ga=[],this.ma=!1,this.ya=!1,this.ba=0,this._a=!1,this.wa=!1,this.ka=!1,this.xa=!1,this.Sa=0,this.Ca=()=>{var e=this.Ma();this.Sa=0,e&&this.reloadFeatureFlags()},"get"in t?this.Ta=t:(this.Ea=new Lf(t.config,t.Qi()),this.Ta=this.Ea)}updateConfig(t,e){var n;(n=this.Ea)==null||n.update(t,e)}setup(t){return this.Ia=t,this.rt=t.logger.createLogger("[FeatureFlags]"),n=()=>{this.Ia===t&&(this.Ia=void 0,this.nn=t,this.Pa(t))},(e=t.kv.initialize())!=null&&e.then?e.then(n):n();var e,n}Pa(t){if(this.nn===t)return _&&re(_,"online",this.Ca),this.Ra=t.registerDynamicEventProperties((()=>this.Aa()?this.fa:this.pa)),this.Fa(),this.initialize()}destroy(){_?.removeEventListener("online",this.Ca)}dispose(){var t;this.ba++,this.wa=!1,this.Ia=void 0,this.nn&&(this.La(),(t=this.Ra)==null||t.dispose(),this.Ra=void 0,this.ga=[],_?.removeEventListener("online",this.Ca),this.nn=void 0)}get Ne(){return this.Ta.get()}Oa(t){var e;return(e=this.nn)==null?void 0:e.kv.get(t)}F(t){this.Da((()=>{var e;return(e=this.nn)==null?void 0:e.kv.set(t)}))}q(t){this.Da((()=>{var e;return(e=this.nn)==null?void 0:e.kv.remove(t)}))}Da(t){try{t()}catch(e){this.rt.error("Failed to update feature flag persistence",e)}}Fa(){var t={};for(var e of[Vn,Gn,Ui,it]){var n=this.Oa(e);x(n)||(t[e]=n)}this.fa=t;var i=b({},t),s=this.Oa(Wt);if(s)for(var r of Object.entries(s))i["$feature/"+r[0]]=r[1];this.pa=i}Aa(){var t=this.Ne.cacheTtlMs;if(!t||0>=t)return!1;var e=this.Oa(Xn);return typeof e!="number"||Date.now()-e>t}$a(){return!!this.Aa()&&(this.xa||this.ya||(this.xa=!0,this.rt.warn("Feature flag cache is stale, triggering refresh..."),this.reloadFeatureFlags()),!0)}Na(){var t=this.Ne.evaluationContexts;return t!=null&&t.length?t.filter((e=>{var n=e&&typeof e=="string"&&e.trim().length>0;return n||this.rt.error("Invalid evaluation context found:",e,"Expected non-empty string"),n})):[]}qa(){var t=this.Ne.flagKeys;if(!x(t))return t.filter((e=>{var n=e&&typeof e=="string"&&e.trim().length>0;return n||this.rt.error("Invalid flag key found:",e,"Expected non-empty string"),n}))}initialize(){var t,e,n=this.Ne,i=(t=(e=n.bootstrap)==null?void 0:e.featureFlags)!==null&&t!==void 0?t:{};if(Object.keys(i).length){var s,r,o=(s=(r=n.bootstrap)==null?void 0:r.featureFlagPayloads)!==null&&s!==void 0?s:{},a=Object.keys(i).filter((u=>!!i[u])).reduce(((u,c)=>(u[c]=i[c]||!1,u)),{}),l=Object.keys(o).filter((u=>a[u])).reduce(((u,c)=>(o[c]&&(u[c]=o[c]),u)),{});return this.ja({featureFlags:a,featureFlagPayloads:l})}}updateFlags(t,e,n){var i,s,r=n!=null&&n.merge&&(i=this.Oa(Wt))!==null&&i!==void 0?i:{},o=n!=null&&n.merge&&(s=this.Oa(Gn))!==null&&s!==void 0?s:{},a=b({},r,t),l=b({},o,e),u={};for(var c of Object.entries(a)){var d=c[0],h=c[1];u[d]={key:d,enabled:Za(h),variant:Xa(h),reason:void 0,metadata:x(l?.[d])?void 0:{id:0,version:void 0,description:void 0,payload:l[d]}}}this.ja({flags:u})}get hasLoadedFlags(){return this.ma}getFlags(){return Object.keys(this.getFlagVariants())}getFlagsWithDetails(){var t=this.Oa(oo),e=this.Oa(it),n=this.Oa(zt);if(!n&&!e)return t||{};var i=te({},t||{}),s=[...new Set([...Object.keys(n||{}),...Object.keys(e||{})])];for(var r of s){var o,a,l=i[r],u=e?.[r],c=x(u)?(o=l?.enabled)!==null&&o!==void 0&&o:!!u,d=x(u)?l?.variant:typeof u=="string"?u:void 0,h=n?.[r],p=b({},l,{enabled:c,variant:c?d??l?.variant:void 0});c!==l?.enabled&&(p.original_enabled=l?.enabled),d!==l?.variant&&(p.original_variant=l?.variant),h&&(p.metadata=b({},l?.metadata,{payload:h,original_payload:l==null||(a=l.metadata)==null?void 0:a.payload})),i[r]=p}return this.ca||(this.rt.warn(" Overriding feature flag details!",{flagDetails:t,overriddenPayloads:n,finalDetails:i}),this.ca=!0),i}getAllFeatureFlags(){var t=this.getFlagVariants(),e=this.getFlagPayloads();return Object.keys(t).map((n=>{var i=t[n];return{key:n,enabled:Za(i),variant:Xa(i),payload:Ya(e[n])}}))}getFlagVariants(){var t=this.Oa(Wt),e=this.Oa(it);if(!e)return t||{};for(var n=te({},t||{}),i=Object.keys(e),s=0;i.length>s;s++)n[i[s]]=e[i[s]];return this.ca||(this.rt.warn(" Overriding feature flags!",{enabledFlags:t,overriddenFlags:e,finalFlags:n}),this.ca=!0),n}getFlagPayloads(){var t=this.Oa(Gn),e=this.Oa(zt);if(!e)return t||{};for(var n=te({},t||{}),i=Object.keys(e),s=0;i.length>s;s++)n[i[s]]=e[i[s]];return this.ca||(this.rt.warn(" Overriding feature flag payloads!",{flagPayloads:t,overriddenPayloads:e,finalPayloads:n}),this.ca=!0),n}reloadFeatureFlags(){this._a||this.Ne.featureFlagsDisabled||this.Ma()||this.Ba||(this.ga.slice().forEach((t=>{try{t()}catch(e){this.rt.error("Error while running feature flags reloading callback",e)}})),this.Ba=setTimeout((()=>{this.Ha()}),5))}La(){clearTimeout(this.Ba),this.Ba=void 0}onReloading(t){return this.ga.push(t),()=>{this.ga=this.ga.filter((e=>e!==t))}}ensureFlagsLoaded(){this.ma||this.ya||this.Ba||this.reloadFeatureFlags()}setAnonymousDistinctId(t){this.$anon_distinct_id=t}setReloadingPaused(t){this._a=t}resetFlagCallReported(){this.q(Gt)}Ha(t){this.La();var e=this.nn;if(e&&!this.Ne.remoteRequestsDisabled&&!this.Ma())if(this.ya)this.wa=!0;else{var n={token:e.projectToken,distinct_id:e.distinctId,groups:e.groups,$anon_distinct_id:this.$anon_distinct_id,person_properties:b({},e.initialPersonProperties,this.Oa(ht)||{},{$lib:e.library.name,$lib_version:e.library.version}),group_properties:this.Oa(qt),timezone:ed()};x(e.deviceId)||(n.$device_id=e.deviceId),(t!=null&&t.disableFlags||this.Ne.featureFlagsDisabled)&&(n.disable_flags=!0);var i=this.Na();i.length&&(n.evaluation_contexts=i);var s=this.qa();x(s)||(n.flag_keys=s);var r=this.Ne.onlyEvaluateSurveyFeatureFlags,o="/flags/?v=2"+(r?"&only_evaluate_survey_feature_flags=true":""),a=this.ba;this.ya=!0;var l=()=>{this.wa&&(this.wa=!1,this.Ha())},u=c=>{this.ya=!1,a===this.ba&&(this.F({[zi]:[ec]}),this.rt.error("Feature flag request failed",c)),l()};try{e.sendRequest(o,{target:"flags",method:"POST",body:n,compression:this.Ne.compression==="base64"?xe.Base64:void 0,sentAt:"body",timeoutMs:this.Ne.requestTimeoutMs}).then((c=>{var d,h,p=(d=c.json)!==null&&d!==void 0?d:{},f=c.statusCode!==200;if(this.ya=!1,a===this.ba){if(this.Ua(c.statusCode),f||this.wa||(this.$anon_distinct_id=void 0),!n.disable_flags||this.wa){this.ka=!f;var g=[];c.error?g.push(c.error instanceof Error&&c.error.name==="AbortError"?"timeout":c.error instanceof Error?ec:"unknown_error"):c.statusCode!==200&&g.push("api_error_"+c.statusCode),p.errorsWhileComputingFlags&&g.push("errors_while_computing_flags");var m=!((h=p.quotaLimited)==null||!h.includes("feature_flags"));m&&g.push("quota_limited"),this.F({[zi]:g}),m?this.rt.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."):n.disable_flags||this.ja(p,f,{partialResponse:r}),l()}}else l()})).catch(u)}catch(c){u(c)}}}Ma(){return Vu(this.Sa,3)}Ua(t){this.Sa=Gu(t,this.Sa,3,(()=>this.rt.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===void 0&&(e={}),!e.fresh||this.ka)if(this.ma||this.getFlags()&&this.getFlags().length>0){if(!this.$a()){var i=this.getFeatureFlagResult(t,e);return(n=i?.variant)!==null&&n!==void 0?n:i?.enabled}}else this.rt.warn('getFeatureFlag for key "'+t+Lr)}getFeatureFlagDetails(t){return this.getFlagsWithDetails()[t]}getFeatureFlagPayload(t){var e=this.getFeatureFlagResult(t,{send_event:!1});return e?.payload}getFeatureFlagResult(t,e){if(e===void 0&&(e={}),!e.fresh||this.ka)if(this.ma||this.getFlags()&&this.getFlags().length>0){if(!this.$a()){var n,i=this.getFlagVariants(),s=t in i,r=i[t],o=this.getFlagPayloads()[t],a=String(r),l=this.Oa(Ui)||void 0,u=this.Oa(Xn)||void 0,c=this.Oa(Gt)||{};if(this.Ne.deduplicateCallsPerSession){var d,h=(d=this.nn)==null?void 0:d.session.sessionId,p=this.Oa(Jn);h&&h!==p&&(c={},n=h)}if(e.send_event||!("send_event"in e))if(t in c&&c[t].includes(a))n&&this.F({[Gt]:c,[Jn]:n});else{var f,g,m,v,E,w,I,A,F,D;O(c[t])?c[t].push(a):c[t]=[a],this.F(b({[Gt]:c},n?{[Jn]:n}:{}));var S=this.getFeatureFlagDetails(t),$=[...(f=this.Oa(zi))!==null&&f!==void 0?f:[]];x(r)&&$.push("flag_missing");var T={$feature_flag:t,$feature_flag_response:r,$feature_flag_payload:o||null,$feature_flag_request_id:l,$feature_flag_evaluated_at:u,$feature_flag_bootstrapped_response:((g=this.Ne.bootstrap)==null||(g=g.featureFlags)==null?void 0:g[t])||null,$feature_flag_bootstrapped_payload:((m=this.Ne.bootstrap)==null||(m=m.featureFlagPayloads)==null?void 0:m[t])||null,$used_bootstrap_value:!this.ka};x(S==null||(v=S.metadata)==null?void 0:v.has_experiment)||(T.$feature_flag_has_experiment=S.metadata.has_experiment),x(S==null||(E=S.metadata)==null?void 0:E.version)||(T.$feature_flag_version=S.metadata.version);var M,N=(w=S==null||(I=S.reason)==null?void 0:I.description)!==null&&w!==void 0?w:S==null||(A=S.reason)==null?void 0:A.code;N&&(T.$feature_flag_reason=N),S!=null&&(F=S.metadata)!=null&&F.id&&(T.$feature_flag_id=S.metadata.id),x(S?.original_variant)&&x(S?.original_enabled)||(T.$feature_flag_original_response=x(S.original_variant)?S.original_enabled:S.original_variant),S!=null&&(D=S.metadata)!=null&&D.original_payload&&(T.$feature_flag_original_payload=S==null||(M=S.metadata)==null?void 0:M.original_payload),$.length&&(T.$feature_flag_error=$.join(",")),this.za(T)}else n&&this.F({[Gt]:c,[Jn]:n});if(s)return{key:t,enabled:!!r,variant:typeof r=="string"?r:void 0,payload:Ya(o)}}}else this.rt.warn('getFeatureFlagResult for key "'+t+Lr)}za(t){try{var e;(e=this.nn)==null||e.capture("$feature_flag_called",t).catch((n=>{this.rt.error("Failed to capture feature flag call",n)}))}catch(n){this.rt.error("Failed to capture feature flag call",n)}}getRemoteConfigPayload(t,e){this.Wa(t,e)}Wa(t,e){var n=this;return X((function*(){var i=n.nn;if(i){var s={distinct_id:i.distinctId,token:i.projectToken,person_properties:{$lib:i.library.name,$lib_version:i.library.version}},r=n.Na();r.length&&(s.evaluation_contexts=r);var o,a=n.qa();x(a)||(s.flag_keys=a);try{var l,u=(l=(yield i.sendRequest("/flags/?v=2",{target:"flags",method:"POST",body:s,compression:n.Ne.compression==="base64"?xe.Base64:void 0,sentAt:"body",timeoutMs:n.Ne.requestTimeoutMs})).json)==null?void 0:l.featureFlagPayloads;o=u?.[t]||void 0}catch(c){return void n.rt.error("Remote config feature flag request failed",c)}try{e(o)}catch(c){n.rt.error("Remote config feature flag callback failed",c)}}}))()}isFeatureEnabled(t,e){if(e===void 0&&(e={}),e.fresh&&!this.ka)return e.defaultValue;if(!(this.ma||this.getFlags()&&this.getFlags().length>0))return this.rt.warn('isFeatureEnabled for key "'+t+Lr),e.defaultValue;var n=this.getFeatureFlag(t,e);return x(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.ja(t,e,n)}ja(t,e,n){if(this.nn){this.ma=!0;var i=(function(s,r,o,a,l,u){r===void 0&&(r={}),o===void 0&&(o={}),a===void 0&&(a={}),u===void 0&&(u=Ql);var c=((F,D)=>{var S=F.flags;return S?b({},F,{featureFlags:Object.fromEntries(Object.keys(S).map(($=>{var T;return[$,(T=S[$].variant)!==null&&T!==void 0?T:S[$].enabled]}))),featureFlagPayloads:Object.fromEntries(Object.keys(S).filter(($=>S[$].enabled)).filter(($=>{var T;return(T=S[$].metadata)==null?void 0:T.payload})).map(($=>{var T;return[$,(T=S[$].metadata)==null?void 0:T.payload]})))}):(F.featureFlags&&D.warn("Using an older version of the feature flags endpoint. Please upgrade your PostHog server to the latest version"),F)})(s,u),d=c.flags,h=c.featureFlags,p=c.featureFlagPayloads;if(h){var f=s.requestId,g=s.evaluatedAt;if(O(h)){u.warn("v1 of the feature flags endpoint is deprecated. Please use the latest version.");var m={};if(h)for(var v=0;h.length>v;v++)m[h[v]]=!0;return{[Vn]:h,[Wt]:m,[cs]:!1}}var E=h,w=p,I=d;if(l!=null&&l.partialResponse)E=b({},r,E),w=b({},o,w),I=b({},a,I);else if(s.errorsWhileComputingFlags)if(d){var A=new Set(Object.keys(d).filter((F=>{var D;return!((D=d[F])!=null&&D.failed)})));E=b({},r,Object.fromEntries(Object.entries(E).filter((F=>A.has(F[0]))))),w=b({},o,Object.fromEntries(Object.entries(w||{}).filter((F=>A.has(F[0]))))),I=b({},a,Object.fromEntries(Object.entries(I||{}).filter((F=>A.has(F[0])))))}else E=b({},r,E),w=b({},o,w),I=b({},a,I);return b({[Vn]:Object.keys(nc(E)),[Wt]:E||{},[Gn]:w||{},[oo]:I||{},[cs]:s.minimalFlagCalledEvents===!0},f?{[Ui]:f}:{},g?{[Xn]:g}:{})}})(t,this.getFlagVariants(),this.getFlagPayloads(),this.getFlagsWithDetails(),n,this.rt);i&&this.F(i),e||(this.xa=!1),this.Va(e)}}override(t,e){e===void 0&&(e=!1),this.rt.warn("override is deprecated. Please use overrideFeatureFlags instead."),this.overrideFeatureFlags({flags:t,suppressWarning:e})}overrideFeatureFlags(t){this.Za(t)}Za(t){if(this.nn){if(t===!1)return this.q([it,zt]),this.Va(),void Ut.info("All overrides cleared");if(O(t))return this.F({[it]:tc(t)}),this.Va(),void Ut.info("Flag overrides set",{flags:t});if(t&&typeof t=="object"&&("flags"in t||"payloads"in t)){var e,n=t;this.ca=!!((e=n.suppressWarning)!==null&&e!==void 0&&e);var i={},s=n.flags,r=n.payloads;return s&&(i[it]=O(s)?tc(s):s),r&&(i[zt]=r),Object.keys(i).length&&this.F(i),s===!1&&r===!1?this.q([it,zt]):s===!1?this.q(it):r===!1&&this.q(zt),this.Va(),s===!1?Ut.info("Flag overrides cleared"):s&&Ut.info("Flag overrides set",{flags:s}),void(r===!1?Ut.info("Payload overrides cleared"):r&&Ut.info("Payload overrides set",{payloads:r}))}if(t&&typeof t=="object")return this.F({[it]:t}),this.Va(),void Ut.info("Flag overrides set",{flags:t});this.rt.warn("Invalid overrideOptions provided to overrideFeatureFlags",{overrideOptions:t})}else this.rt.warn("posthog.featureFlags.overrideFeatureFlags called before feature flags were ready")}onFeatureFlags(t){if(this.addFeatureFlagsHandler(t),this.ma){var e=this.Ga(),n=e.flags,i=e.flagVariants;try{t(n,i)}catch(s){this.rt.error("Error while running feature flags callback",s)}}return()=>this.removeFeatureFlagsHandler(t)}updateEarlyAccessFeatureEnrollment(t,e,n){var i=(this.Oa(ji)||[]).find((l=>l.flagKey===t)),s={["$feature_enrollment/"+t]:e},r={$feature_flag:t,$feature_enrollment:e,$set:s};i&&(r.$early_access_feature_name=i.name),n&&(r.$feature_enrollment_stage=n);var o=b({},this.getFlagVariants(),{[t]:e});this.F({[Vn]:Object.keys(nc(o)),[Wt]:o,[ht]:b({},this.Oa(ht)||{},s)}),this.Va();try{var a;(a=this.nn)==null||a.capture("$feature_enrollment_update",r).catch((l=>{this.rt.error("Failed to capture early access feature enrollment",l)}))}catch(l){this.rt.error("Failed to capture early access feature enrollment",l)}}getEarlyAccessFeatures(t,e,n){e===void 0&&(e=!1);var i=this.Oa(ji);!i||e?this.Qa(t,n):t(i)}Qa(t,e){var n=this;return X((function*(){var i=n.nn;if(i){var s,r=e?"&"+e.map((a=>"stage="+a)).join("&"):"";try{var o=yield i.sendRequest("/api/early_access_features/?token="+i.projectToken+r,{target:"api",method:"GET",sentAt:"query"});if(!o.json)return;n.F({[ji]:s=o.json.earlyAccessFeatures})}catch(a){return void n.rt.error("Early access feature request failed",a)}try{t(s)}catch(a){n.rt.error("Early access feature callback failed",a)}}}))()}Ga(){var t=this.getFlags(),e=this.getFlagVariants();return{flags:t.filter((n=>e[n])),flagVariants:Object.keys(e).filter((n=>e[n])).reduce(((n,i)=>(n[i]=e[i],n)),{})}}Va(t){this.Fa();var e=this.Ga(),n=e.flags,i=e.flagVariants;this.featureFlagEventHandlers.forEach((s=>{try{s(n,i,{errorsLoading:t})}catch(r){this.rt.error("Error while running feature flags callback",r)}}))}setPersonPropertiesForFlags(t,e){e===void 0&&(e=!0),this.Ka(t,e)}Ka(t,e){e===void 0&&(e=!0);var n=this.Oa(ht)||{},i=t?.$set||(t!=null&&t.$set_once?{}:t),s=t?.$set_once,r={};if(s)for(var o in s)({}).hasOwnProperty.call(s,o)&&(o in n||(r[o]=s[o]));this.F({[ht]:b({},n,r,i)}),e&&this.reloadFeatureFlags()}unsetPersonPropertiesForFlags(t,e){e===void 0&&(e=!0);var n=b({},this.Oa(ht)||{});t.forEach((i=>{delete n[i]})),this.F({[ht]:n}),e&&this.reloadFeatureFlags()}resetPersonPropertiesForFlags(t){t===void 0&&(t=!0),this.q(ht),t&&this.reloadFeatureFlags()}setGroupPropertiesForFlags(t,e){e===void 0&&(e=!0);var n=this.Oa(qt)||{},i=b({},n);for(var s of Object.keys(t))i[s]=b({},n[s],t[s]);this.F({[qt]:i}),e&&this.reloadFeatureFlags()}resetGroupPropertiesForFlags(t){if(t){var e=this.Oa(qt)||{};this.F({[qt]:b({},e,{[t]:{}})})}else this.q(qt)}reset(){this.ba++,this.wa=!1,this.Fa(),this.ma=!1,this._a=!1,this.ka=!1,this.$anon_distinct_id=void 0,this.La(),this.ca=!1,this.Sa=0}}},Bf={sessionRecording:class{get Ne(){return this._instance.config}get Mr(){return this._instance.persistence}get started(){var t;return!((t=this.Ja)==null||!t.isStarted)}get status(){var t,e;return this.Ya===Un||this.Ya===Ni?this.Ya:(t=(e=this.Ja)==null?void 0:e.status)!==null&&t!==void 0?t:this.Ya}constructor(t){if(this._forceAllowLocalhostNetworkCapture=!1,this.Ya=Vl,this.Xa=void 0,this.eo=!1,this.io=(()=>{var e;if(C==null||!C.visibilityState||C.visibilityState==="visible")return!0;var n=_==null||(e=_.performance)==null||e.getEntriesByType==null?void 0:e.getEntriesByType("visibility-state");return!(n!=null&&n.length)||n.some((i=>i.name==="visible"))})(),this.Ie=()=>{var e;C?.visibilityState==="visible"&&(this.io=!0,(e=this.Ja)==null||e.setDocumentWasEverVisible==null||e.setDocumentWasEverVisible(!0))},this._instance=t,!this._instance.sessionManager)throw ut.error("started without valid sessionManager"),new Error(ko+" started without valid sessionManager. This is a bug.");if(this.Ne.cookieless_mode===gt)throw new Error(ko+' cannot be used with cookieless_mode="always"');C!=null&&C.addEventListener&&re(C,"visibilitychange",this.Ie)}initialize(){this.startIfEnabledOrStop()}dispose(){this.eo=!0,C==null||C.removeEventListener==null||C.removeEventListener("visibilitychange",this.Ie),this.stopRecording()}get ro(){var t,e=!((t=this._instance.get_property(Jt))==null||!t.enabled),n=!this.Ne.disable_session_recording,i=this.Ne.disable_session_recording||this._instance.consent.isOptedOut();return _&&e&&n&&!i}startIfEnabledOrStop(t){var e;if(!(this.eo||this.ro&&(e=this.Ja)!=null&&e.isStarted)){var n=!x(Object.assign)&&!x(Array.from);this.ro&&n?(this.no(t),ut.info("starting")):(this.Ya=Vl,this.stopRecording())}}no(t){var e,n,i;this.ro&&(this.Ya!==Un&&this.Ya!==Ni&&(this.Ya=Gl),R!=null&&(e=R.__PosthogExtensions__)!=null&&(e=e.rrweb)!=null&&e.record&&(n=R.__PosthogExtensions__)!=null&&n.initSessionRecording?this.so(t):(i=R.__PosthogExtensions__)==null||i.loadExternalDependency==null||i.loadExternalDependency(this._instance,this.ao,(s=>{if(s)return ut.error("could not load recorder",s);this.so(t)})))}stopRecording(){var t,e;(t=this.Xa)==null||t.call(this),this.Xa=void 0,(e=this.Ja)==null||e.stop()}oo(){var t,e;(t=this.Xa)==null||t.call(this),this.Xa=void 0,(e=this.Ja)==null||e.discard()}lo(){var t,e;(t=this.Mr)==null||t.unregister(ia),(e=this.Mr)==null||e.unregister(Eu)}uo(t,e){if(B(t))return null;var n,i=he(t)?t:parseFloat(t);return typeof(n=i)!="number"||!Number.isFinite(n)||0>n||n>1?(ut.warn(e+" must be between 0 and 1. Ignoring invalid value:",t),null):i}ho(t){if(this.Mr){var e,n,i=this.Mr,s=()=>{var r,o=t.sessionRecording===!1?void 0:t.sessionRecording,a=this.uo((r=this.Ne.session_recording)==null?void 0:r.sampleRate,"session_recording.sampleRate"),l=this.uo(o?.sampleRate,"remote config sampleRate"),u=a??l;B(u)&&this.lo();var c=o?.minimumDurationMilliseconds;i.register({[Jt]:b({cache_timestamp:Date.now(),enabled:!!o},o,{networkPayloadCapture:b({capturePerformance:t.capturePerformance},o?.networkPayloadCapture),canvasRecording:{enabled:o?.recordCanvas,fps:o?.canvasFps,quality:o?.canvasQuality},sampleRate:u,minimumDurationMilliseconds:x(c)?null:c,endpoint:o?.endpoint,triggerMatchType:o?.triggerMatchType,masking:o?.masking,urlTriggers:o?.urlTriggers,version:o?.version,triggerGroups:o?.triggerGroups})})};s(),(e=this.Xa)==null||e.call(this),this.Xa=(n=this._instance.sessionManager)==null?void 0:n.onSessionId(s)}}onRemoteConfig(t){var e=t.ok?t.config:void 0;return e&&"sessionRecording"in e?e.sessionRecording===!1?(this.ho(e),void this.oo()):(this.ho(e),void this.startIfEnabledOrStop()):(this.Ya===Un&&(this.Ya=Ni,ut.warn("config refresh failed, recording will not start until page reload")),void this.startIfEnabledOrStop())}log(t,e){var n;e===void 0&&(e="log"),(n=this.Ja)!=null&&n.log?this.Ja.log(t,e):ut.warn("log called before recorder was ready")}get ao(){var t,e,n=(t=this._instance)==null||(t=t.persistence)==null?void 0:t.get_property(Jt);return(n==null||(e=n.scriptConfig)==null?void 0:e.script)||"lazy-recorder"}do(){var t,e=this._instance.get_property(Jt);if(!e)return!1;try{t=typeof e=="object"?e:JSON.parse(e)}catch(n){return ut.warn("persisted remote config for session recording is invalid and will be ignored",n),!1}return!B(t.cache_timestamp)&&36e5>=Date.now()-t.cache_timestamp}so(t){var e,n,i;if(!this.eo){if((e=R.__PosthogExtensions__)==null||!e.initSessionRecording)return ut.warn("Called on script loaded before session recording is available. This can be caused by adblockers."),void this._instance.register_for_session({[Pu]:!0});var s;if(this.Ja||(this.Ja=(s=R.__PosthogExtensions__)==null?void 0:s.initSessionRecording(this._instance,this.io),this.Ja._forceAllowLocalhostNetworkCapture=this._forceAllowLocalhostNetworkCapture),!this.do())return this.Ya===Ni||this.Ya===Un?void 0:(this.Ya=Un,ut.info("persisted remote config is stale, requesting fresh config before starting"),void new td(this._instance).load());this.Ya=Gl,(n=(i=this.Ja).setDocumentWasEverVisible)==null||n.call(i,this.io),this.Ja.start(t)}}onRRwebEmit(t){var e;(e=this.Ja)==null||e.onRRwebEmit==null||e.onRRwebEmit(t)}overrideLinkedFlag(){var t,e;this.Ja||(e=this.Mr)==null||e.register({[xu]:!0}),(t=this.Ja)==null||t.overrideLinkedFlag()}overrideSampling(){var t,e;this.Ja||(e=this.Mr)==null||e.register({[Su]:!0}),(t=this.Ja)==null||t.overrideSampling()}overrideTrigger(t){var e,n;this.Ja||(n=this.Mr)==null||n.register({[t==="url"?ku:Iu]:!0}),(e=this.Ja)==null||e.overrideTrigger(t)}get sdkDebugProperties(){var t;return((t=this.Ja)==null?void 0:t.sdkDebugProperties)||{$recording_status:this.status}}tryAddCustomEvent(t,e){var n;return!((n=this.Ja)==null||!n.tryAddCustomEvent(t,e))}}},Df={autocapture:class{constructor(t){this.vo=!1,this.co=null,this.fo=!1,this.po=!1,this.instance=t,this.rageclicks=new Wl(t.config.rageclick),this.mo=null}initialize(){this.startIfEnabled()}get Ne(){var t,e,n=ne(this.instance.config.autocapture)?this.instance.config.autocapture:{};return n.url_allowlist=(t=n.url_allowlist)==null?void 0:t.map((i=>new RegExp(i))),n.url_ignorelist=(e=n.url_ignorelist)==null?void 0:e.map((i=>new RegExp(i))),n}yo(){if(this.isBrowserSupported()){if(_&&C){var t=n=>{n=n||_?.event;try{this.bo(n)}catch(i){Tr.error("Failed to capture event",i)}};if(re(C,"submit",t,{capture:!0}),re(C,"change",t,{capture:!0}),re(C,"click",t,{capture:!0}),this.Ne.capture_copied_text){var e=n=>{n=n||_?.event;try{this.bo(n,$r)}catch(i){Tr.error("Failed to capture copy/cut event",i)}};re(C,"copy",e,{capture:!0}),re(C,"cut",e,{capture:!0})}}}else Tr.info("Disabling Automatic Event Collection because this browser is not supported")}startIfEnabled(){this.isEnabled&&!this.vo&&(this.yo(),this.vo=!0)}onRemoteConfig(t){if(this.fo=!0,t.ok){var e=t.config;e.elementsChainAsString&&(this.po=e.elementsChainAsString);var n=e.autocapture_opt_out;Ye(n)&&(this.instance.persistence&&this.instance.persistence.register({[Qr]:n}),this.co=n),this.startIfEnabled()}else this.startIfEnabled()}setElementSelectors(t){this.mo=t}getElementSelectors(t){var e,n=[];return(e=this.mo)==null||e.forEach((i=>{var s=C?.querySelectorAll(i);s?.forEach((r=>{t===r&&n.push(i)}))})),n}get isEnabled(){var t,e,n=(t=this.instance.persistence)==null?void 0:t.props[Qr],i=this.co,s=this.instance.Qi()&&!this.fo;if($e(i)&&!Ye(n)&&!s)return!1;var r=(e=this.co)!==null&&e!==void 0?e:!!n;return!!this.instance.config.autocapture&&!r}bo(t,e){if(e===void 0&&(e="$autocapture"),this.isEnabled){var n,i=yr(t);Mu(i)&&(i=i.parentNode||null),e==="$autocapture"&&t.type==="click"&&t instanceof MouseEvent&&this.instance.config.rageclick&&(n=this.rageclicks)!=null&&n.isRageClick(t.clientX,t.clientY,t.timeStamp||new Date().getTime())&&yl(i,this.instance.config.rageclick)&&this.bo(t,"$rageclick");var s=e===$r;if(i&&(function(d,h,p,f,g,m){var v;if(!_||la(d)||p!=null&&p.url_allowlist&&!ml(p.url_allowlist,m)||p!=null&&p.url_ignorelist&&ml(p.url_ignorelist,m))return!1;if(p!=null&&p.dom_event_allowlist){var E=p.dom_event_allowlist;if(E&&!E.some((S=>h.type===S)))return!1}var w=Uu(d,f),I=w.parentIsUsefulElement,A=w.targetElementList;if(!(function(S,$){var T=$?.element_allowlist;if(x(T))return!0;var M,N=function(z){if(T.some((H=>z.tagName.toLowerCase()===H)))return{v:!0}};for(var P of S)if(M=N(P))return M.v;return!1})(A,p)||!mo(A,p?.css_selector_allowlist)||mo(A,(v=p?.css_selector_ignorelist)!==null&&v!==void 0?v:Mp))return!1;try{var F=_.getComputedStyle(d);if(F&&F.getPropertyValue("cursor")==="pointer"&&h.type==="click")return!0}catch{}var D=d.tagName.toLowerCase();switch(D){case"html":return!1;case"form":return(g||["submit"]).indexOf(h.type)>=0;case"input":case"select":case"textarea":return(g||["change","click"]).indexOf(h.type)>=0;default:return I?(g||["click"]).indexOf(h.type)>=0:(g||["click"]).indexOf(h.type)>=0&&(aa.indexOf(D)>-1||d.getAttribute("contenteditable")==="true")}})(i,t,this.Ne,s,s?["copy","cut"]:void 0,this.instance)){var r=Af(i,{e:t,maskAllElementAttributes:this.instance.config.mask_all_element_attributes,maskAllText:this.instance.config.mask_all_text,elementAttributeIgnoreList:this.Ne.element_attribute_ignorelist,elementsChainAsString:this.po,disableCaptureUrlHashes:this.instance.config.disable_capture_url_hashes}),o=r.props;if(r.explicitNoCapture)return!1;var a=this.getElementSelectors(i);if(a&&a.length>0&&(o.$element_selectors=a),e===$r){var l,u=Bu(_==null||(l=_.getSelection())==null?void 0:l.toString()),c=t.type||"clipboard";if(!u)return!1;o.$selected_content=u,o.$copy_type=c}return this.instance.capture(e,o),!0}}}isBrowserSupported(){return Se(C?.querySelectorAll)}},historyAutocapture:class{constructor(t){var e;this._instance=t,this._o=(_==null||(e=_.location)==null?void 0:e.pathname)||""}initialize(){this.startIfEnabled()}get isEnabled(){return this._instance.config.capture_pageview==="history_change"}startIfEnabled(){this.isEnabled&&(k.info("History API monitoring enabled, starting..."),this.monitorHistoryChanges())}stop(){this.wo&&this.wo(),this.wo=void 0,k.info("History API monitoring stopped")}monitorHistoryChanges(){_&&_.history&&(this.ko("pushState"),this.ko("replaceState"),this.xo())}ko(t){var e;if(_&&((e=_.history[t])==null||!e.__posthog_wrapped__)){var n=this;(function(i,s,r){try{if(!(s in i))return zl;var o={next:i[s]},a=r((function(){for(var l=arguments.length,u=new Array(l),c=0;l>c;c++)u[c]=arguments[c];return o.next.apply(this,u)}));return Se(a)&&(a.prototype=a.prototype||{},Object.defineProperties(a,{__posthog_wrapped__:{enumerable:!1,value:!0},__posthog_layer__:{enumerable:!1,value:o}})),i[s]=a,()=>{if(i[s]!==a)for(var l=i[s];Se(l)&&l.__posthog_layer__;){var u=l.__posthog_layer__;if(u.next===a)return void(u.next=o.next);l=u.next}else i[s]=o.next}}catch{return zl}})(_.history,t,(i=>function(s,r,o){i.call(this,s,r,o),n.So(t)}))}}So(t){try{var e,n=_==null||(e=_.location)==null?void 0:e.pathname;if(!n)return;n!==this._o&&this.isEnabled&&this._instance.capture(cn,{navigation_type:t}),this._o=n}catch(i){k.error("Error capturing "+t+" pageview",i)}}xo(){if(!this.wo){var t=()=>{this.So("popstate")};re(_,"popstate",t),this.wo=()=>{_&&_.removeEventListener("popstate",t)}}}},heatmaps:class{get Ne(){return this.instance.config}constructor(t){var e;this.Co=!1,this.vo=!1,this.Mo=null,this.instance=t,this.Co=!((e=this.instance.persistence)==null||!e.props[eo]),this.rageclicks=new Wl(t.config.rageclick)}initialize(){this.startIfEnabled()}get flushIntervalMilliseconds(){var t=5e3;return ne(this.Ne.capture_heatmaps)&&this.Ne.capture_heatmaps.flush_interval_milliseconds&&(t=this.Ne.capture_heatmaps.flush_interval_milliseconds),t}get isEnabled(){return B(this.Ne.capture_heatmaps)?B(this.Ne.enable_heatmaps)?this.Co:this.Ne.enable_heatmaps:this.Ne.capture_heatmaps!==!1}startIfEnabled(){if(this.isEnabled){if(this.vo)return;Pf.info("starting..."),this.To(),this.Ie()}else{var t;clearInterval((t=this.Mo)!==null&&t!==void 0?t:void 0),this.Eo(),this.getAndClearBuffer()}}onRemoteConfig(t){if(t.ok){var e=t.config;if("heatmaps"in e){var n=!!e.heatmaps;this.instance.persistence&&this.instance.persistence.register({[eo]:n}),this.Co=n,this.startIfEnabled()}}}getAndClearBuffer(){var t=this.R;return this.R=void 0,t}Io(t){Nr(t.originalEvent)&&this.ke(t.originalEvent,"deadclick")}Ie(){this.Mo&&clearInterval(this.Mo),this.Mo=C?.visibilityState==="visible"?setInterval(this.cr.bind(this),this.flushIntervalMilliseconds):null}To(){_&&C&&(this.Po=this.cr.bind(this),re(_,fs,this.Po),this.Ro=t=>this.ke(t||_?.event),re(C,"click",this.Ro,{capture:!0}),this.Ao=t=>this.Fo(t||_?.event),re(C,"mousemove",this.Ao,{capture:!0}),this.Lo=new Il(this.instance,Hp,this.Io.bind(this)),this.Lo.startIfEnabledOrStop(),this.Oo=this.Ie.bind(this),re(C,ps,this.Oo),this.vo=!0)}Eo(){var t;_&&C&&(this.Po&&_.removeEventListener(fs,this.Po),this.Ro&&C.removeEventListener("click",this.Ro,{capture:!0}),this.Ao&&C.removeEventListener("mousemove",this.Ao,{capture:!0}),this.Oo&&C.removeEventListener(ps,this.Oo),clearTimeout(this.Do),(t=this.Lo)==null||t.stop(),this.vo=!1)}$o(t,e){var n=this.instance.scrollManager.scrollY(),i=this.instance.scrollManager.scrollX(),s=this.instance.scrollManager.scrollElement(),r=(function(o,a,l){for(var u=o;u&&$t(u)&&!Me(u,"body");){if(u===l)return!1;var c=void 0;try{var d,h,p;c=(d=(h=(p=u.ownerDocument)==null?void 0:p.defaultView)!==null&&h!==void 0?h:_)==null?void 0:d.getComputedStyle(u).position}catch{return!1}if(L(a,c))return!0;u=Du(u)}return!1})(yr(t),["fixed","sticky"],s);return{x:t.clientX+(r?0:i),y:t.clientY+(r?0:n),target_fixed:r,type:e}}ke(t,e){var n;if(e===void 0&&(e="click"),!gl(t.target)&&Nr(t)){var i=this.$o(t,e);(n=this.rageclicks)!=null&&n.isRageClick(t.clientX,t.clientY,new Date().getTime())&&yl(yr(t),this.instance.config.rageclick)&&this.Vt(b({},i,{type:"rageclick"})),this.Vt(i)}}Fo(t){!gl(t.target)&&Nr(t)&&(clearTimeout(this.Do),this.Do=setTimeout((()=>{this.Vt(this.$o(t,"mousemove"))}),500))}Vt(t){if(_){var e=this.Ne.disable_capture_url_hashes?Pt(_.location.href):_.location.href,n=this.Ne.custom_personal_data_properties,i=this.Ne.mask_personal_data_properties?[...bn,...n||[]]:[],s=ci(e,i,ui);this.R=this.R||{},this.R[s]||(this.R[s]=[]),this.R[s].push(t)}}cr(){this.R&&!yt(this.R)&&this.instance.capture("$$heatmap",{$heatmap_data:this.getAndClearBuffer()})}},deadClicksAutocapture:Il,webVitalsAutocapture:class{constructor(t){var e;this.Co=!1,this.vo=!1,this.R={navigationKey:void 0,url:void 0,metrics:[],firstMetricTimestamp:void 0},this.No=()=>{clearTimeout(this.qo),this.qo=void 0,this.R.metrics.length!==0&&(this._instance.capture("$web_vitals",b({$current_url:this.R.url},this.R.metrics.reduce(((n,i)=>b({},n,{["$web_vitals_"+i.name+"_event"]:b({},i),["$web_vitals_"+i.name+"_value"]:i.value})),{}))),this.R={navigationKey:void 0,url:void 0,metrics:[],firstMetricTimestamp:void 0})},this.jo=n=>{var i;if(this.R=this.R||{navigationKey:void 0,url:void 0,metrics:[],firstMetricTimestamp:void 0},B(n?.name)||B(n?.value))jt.error("Invalid metric received",n);else{var s=typeof n.navigationURL=="string"?n.navigationURL:void 0,r=this.Bo(s);if(!x(r)){var o=he(n.navigationId)||typeof n.navigationId=="string"?"navigation:"+n.navigationId:"url:"+r;if(!this.Ho||this.Ho>n.value){this.R.navigationKey!==o&&(this.No(),this.qo=setTimeout(this.No,this.flushToCaptureTimeoutMs)),x(this.R.navigationKey)&&(this.R.navigationKey=o,this.R.url=r),this.R.firstMetricTimestamp=x(this.R.firstMetricTimestamp)?Date.now():this.R.firstMetricTimestamp,n.attribution&&n.attribution.interactionTargetElement&&(n.attribution.interactionTargetElement=void 0);var a=(i=this._instance.sessionManager)==null?void 0:i.checkAndGetSessionAndWindowId(!0),l=b({},n,s?{navigationURL:r}:{},{$current_url:r,timestamp:Date.now()});x(a)||(l.$session_id=a.sessionId,l.$window_id=a.windowId),this.R.metrics.push(l),this.R.metrics.length===this.allowedMetrics.length&&this.No()}else jt.error("Ignoring metric with value >= "+this.Ho,n)}}},this.Uo=()=>{if(!this.vo){var n,i,s,r,o=R.__PosthogExtensions__,a=o?.postHogWebVitalsCallbacksByFlavor,l=a?.[this.zo]||(this.zo==="web-vitals"&&x(a)?o?.postHogWebVitalsCallbacks:void 0);if(x(l)||(n=l.onLCP,i=l.onCLS,s=l.onFCP,r=l.onINP),n&&i&&s&&r){var u={reportSoftNavs:this.useSoftNavs};this.allowedMetrics.indexOf("LCP")>-1&&n(this.jo.bind(this),u),this.allowedMetrics.indexOf("CLS")>-1&&i(this.jo.bind(this),u),this.allowedMetrics.indexOf("FCP")>-1&&s(this.jo.bind(this),u),this.allowedMetrics.indexOf("INP")>-1&&r(this.jo.bind(this),u),this.vo=!0}else jt.error("web vitals callbacks not loaded - not starting")}},this._instance=t,this.Co=!((e=this._instance.persistence)==null||!e.props[so]),this.startIfEnabled()}get Wo(){return this._instance.config.capture_performance}get allowedMetrics(){var t,e,n=ne(this.Wo)?(t=this.Wo)==null?void 0:t.web_vitals_allowed_metrics:void 0;return B(n)?((e=this._instance.persistence)==null?void 0:e.props[ro])||["CLS","FCP","INP","LCP"]:n}get flushToCaptureTimeoutMs(){return(ne(this.Wo)?this.Wo.web_vitals_delayed_flush_ms:void 0)||5e3}get useAttribution(){var t=ne(this.Wo)?this.Wo.web_vitals_attribution:void 0;return t!=null&&t}get useSoftNavs(){var t=ne(this.Wo)?this.Wo.__preview_web_vitals_soft_navs:void 0;return t!=null&&t}get Ho(){var t=ne(this.Wo)&&he(this.Wo.__web_vitals_max_value)?this.Wo.__web_vitals_max_value:ql;return t>0&&6e4>=t?ql:t}get isEnabled(){var t=se?.protocol;if(t!=="http:"&&t!=="https:")return jt.info("Web Vitals are disabled on non-http/https protocols"),!1;var e=ne(this.Wo)?this.Wo.web_vitals:Ye(this.Wo)?this.Wo:void 0;return Ye(e)?e:this.Co}startIfEnabled(){this.isEnabled&&!this.vo&&(jt.info("enabled, starting..."),this.ai(this.Uo))}onRemoteConfig(t){if(t.ok){var e=t.config;if("capturePerformance"in e){var n=ne(e.capturePerformance)&&!!e.capturePerformance.web_vitals,i=ne(e.capturePerformance)?e.capturePerformance.web_vitals_allowed_metrics:void 0;this._instance.persistence&&(this._instance.persistence.register({[so]:n}),this._instance.persistence.register({[ro]:i})),this.Co=n,this.startIfEnabled()}}}get zo(){return this.useSoftNavs?this.useAttribution?"web-vitals-with-attribution-soft-navs":"web-vitals-soft-navs":this.useAttribution?"web-vitals-with-attribution":"web-vitals"}ai(t){var e=R.__PosthogExtensions__,n=this.zo,i=e?.postHogWebVitalsCallbacksByFlavor;i!=null&&i[n]||n==="web-vitals"&&x(i)&&e!=null&&e.postHogWebVitalsCallbacks?t():e==null||e.loadExternalDependency==null||e.loadExternalDependency(this._instance,n,(s=>{s?jt.error("failed to load script",s):t()}))}Bo(t){var e=t||_?.location.href;if(e){var n=this._instance.config.disable_capture_url_hashes?Pt(e):e,i=this._instance.config.custom_personal_data_properties,s=this._instance.config.mask_personal_data_properties?[...bn,...i||[]]:[];return ci(n,s,ui)}jt.error("Could not determine current URL")}}},jf={exceptionObserver:class{constructor(t){var e;this.Uo=()=>{var n;if(_&&this.isEnabled&&(n=R.__PosthogExtensions__)!=null&&n.errorWrappingFunctions){var i=R.__PosthogExtensions__.errorWrappingFunctions.wrapOnError,s=R.__PosthogExtensions__.errorWrappingFunctions.wrapUnhandledRejection,r=R.__PosthogExtensions__.errorWrappingFunctions.wrapConsoleError;try{!this.Vo&&this.Ne.capture_unhandled_errors&&(this.Vo=i(this.captureException.bind(this))),!this.Zo&&this.Ne.capture_unhandled_rejections&&(this.Zo=s(this.captureException.bind(this))),!this.Go&&this.Ne.capture_console_errors&&(this.Go=r(this.captureException.bind(this)))}catch(o){jn.error("failed to start",o),this.Qo()}}},this._instance=t,this.Ko=!((e=this._instance.persistence)==null||!e.props[to]),this.Jo=new Oh(b({},(function(n){var i,s,r,o;return n===void 0&&(n={}),{refillRate:(i=(s=n.exceptionRateLimiterRefillRate)!==null&&s!==void 0?s:n.__exceptionRateLimiterRefillRate)!==null&&i!==void 0?i:1,bucketSize:(r=(o=n.exceptionRateLimiterBucketSize)!==null&&o!==void 0?o:n.__exceptionRateLimiterBucketSize)!==null&&r!==void 0?r:10}})(this._instance.config.error_tracking),{refillInterval:1e4,rt:jn})),this.Ne=this.Yo(),this.startIfEnabledOrStop()}Yo(){var t=this._instance.config.capture_exceptions,e={capture_unhandled_errors:!1,capture_unhandled_rejections:!1,capture_console_errors:!1};return ne(t)?e=b({},e,t):(x(t)?this.Ko:t)&&(e=b({},e,{capture_unhandled_errors:!0,capture_unhandled_rejections:!0})),e}get isEnabled(){return this.Ne.capture_console_errors||this.Ne.capture_unhandled_errors||this.Ne.capture_unhandled_rejections}startIfEnabledOrStop(){this.isEnabled?(jn.info("enabled"),this.Qo(),this.ai(this.Uo)):this.Qo()}ai(t){var e,n;(e=R.__PosthogExtensions__)!=null&&e.errorWrappingFunctions?t():(n=R.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,"exception-autocapture",(i=>{if(i)return jn.error("failed to load script",i);t()}))}Qo(){var t,e,n;(t=this.Vo)==null||t.call(this),this.Vo=void 0,(e=this.Zo)==null||e.call(this),this.Zo=void 0,(n=this.Go)==null||n.call(this),this.Go=void 0}onRemoteConfig(t){if(t.ok){var e=t.config;"autocaptureExceptions"in e&&(this.Ko=!!e.autocaptureExceptions||!1,this._instance.persistence&&this._instance.persistence.register({[to]:this.Ko}),this.Ne=this.Yo(),this.startIfEnabledOrStop())}}onConfigChange(){this.Ne=this.Yo()}captureException(t){var e,n,i,s=(e=t==null||(n=t.$exception_list)==null||(n=n[0])==null?void 0:n.type)!==null&&e!==void 0?e:"Exception";this.Jo.consumeRateLimit(s)?jn.info("Skipping exception capture because of client rate limiting.",{exception:s}):(i=this._instance.exceptions)==null||i.sendExceptionEvent(t)}},exceptions:class{constructor(t){var e,n;this.Xo=[],this.tl=new ep([new lp,new vp,new up,new cp,new gp,new fp,new hp,new mp],(function(i){for(var s=arguments.length,r=new Array(s>1?s-1:0),o=1;s>o;o++)r[o-1]=arguments[o];return function(a,l){l===void 0&&(l=0);for(var u=[],c=a.split(` -`),d=l;c.length>d;d++){var h=c[d];if(1024>=h.length){var p=dl.test(h)?h.replace(dl,"$1"):h;if(!p.match(/\S*Error: /)){for(var f of r){var g=f(p,i);if(g){u.push(g);break}}if(u.length>=50)break}}}return(function(m){if(!m.length)return[];var v=Array.from(m);return v.reverse(),v.slice(0,50).map((E=>{return b({},E,{filename:E.filename||(w=v,w[w.length-1]||{}).filename,function:E.function||yn});var w}))})(u)}})("web:javascript",sp,ap)),this._instance=t,this.Xo=(e=(n=this._instance.persistence)==null?void 0:n.get_property(no))!==null&&e!==void 0?e:[],this.el=ls(this.il()),this.rl=new yp(this.el)}onConfigChange(){this.el=ls(this.il()),this.rl.setConfig(this.el)}onRemoteConfig(t){var e,n,i;if(t.ok){var s=t.config;if("errorTracking"in s){var r=(e=(n=s.errorTracking)==null?void 0:n.suppressionRules)!==null&&e!==void 0?e:[],o=(i=s.errorTracking)==null?void 0:i.captureExtensionExceptions;this.Xo=r,this._instance.persistence&&this._instance.persistence.register({[no]:this.Xo,[io]:o})}}}get nl(){var t,e=!!this._instance.get_property(io),n=this._instance.config.error_tracking.captureExtensionExceptions;return(t=n??e)!==null&&t!==void 0&&t}buildProperties(t,e){return this.tl.buildFromUnknown(t,{syntheticException:e?.syntheticException,mechanism:{handled:e?.handled}})}addExceptionStep(t,e){if(this.el.enabled)try{if(!q(t)||t.trim().length===0)return void tt.warn("Ignoring exception step because message must be a non-empty string");var n=(function(r){if(!r)return{sanitizedProperties:{},droppedKeys:[]};var o=[];return{sanitizedProperties:Object.keys(r).reduce(((a,l)=>_p.has(l)?(o.push(l),a):(a[l]=r[l],a)),{}),droppedKeys:o}})(this.sl(e)),i=n.sanitizedProperties,s=n.droppedKeys;s.length>0&&tt.warn("Ignoring reserved exception step fields",{droppedKeys:s}),this.rl.add(b({[os]:t,[as]:new Date().toISOString()},i))}catch(r){tt.error("Failed to add exception step. Ignoring breadcrumb.",r)}}sendExceptionEvent(t){try{var e=t.$exception_list;if(this.al(e)){if(this.ol(e))return this.ll("Exception dropped: matched a suppression rule"),void tt.info("Skipping exception capture because a suppression rule matched");if(!this.nl&&this.ul(e))return this.ll("Exception dropped: thrown by a browser extension"),void tt.info("Skipping exception capture because it was thrown by an extension");if(!this._instance.config.error_tracking.__capturePostHogExceptions&&this.hl(e))return this.ll("Exception dropped: thrown by the PostHog SDK"),void tt.info("Skipping exception capture because it was thrown by the PostHog SDK")}var n=this.el.enabled&&B(t.$exception_steps)?this.dl(t):t,i=typeof(r=globalThis._posthogReleaseId)=="string"&&r.length>0?r:void 0;i&&(n.$release_id=i);try{var s=this._instance.capture("$exception",n,{_noTruncate:!0,_batchKey:"exceptionEvent",Wn:!0});return s&&this.rl.clear(),s}catch(o){return tt.error("Failed to capture exception event. Dropping this exception.",o),void this.rl.clear()}}catch(o){return void tt.error("Failed to process exception event. Ignoring this exception.",o)}var r}dl(t){try{var e=this.rl.getAttachable();return e.length===0?t:b({},t,{$exception_steps:e})}catch(n){return tt.error("Failed to read buffered exception steps. Capturing exception without steps.",n),t}}ll(t){this.el.enabled&&this.rl.add({[os]:t,[as]:new Date().toISOString()})}sl(t){return ne(t)?b({},t):{}}il(){var t,e;return(t=(e=this._instance.config.error_tracking)==null?void 0:e.exception_steps)!==null&&t!==void 0?t:{}}ol(t){if(t.length===0)return!1;try{var e=t.reduce(((n,i)=>{var s=i.type,r=i.value;return q(s)&&s.length>0&&n.$exception_types.push(s),q(r)&&r.length>0&&n.$exception_values.push(r),n}),{$exception_types:[],$exception_values:[]});return this.Xo.some((n=>{var i=n.values.map((s=>{var r=gd[s.operator],o=e[s.key];if(!r||!o)return!1;var a=O(s.value)?s.value:[s.value];return a.length>0&&r(a,o)}));return n.type==="OR"?i.some(Boolean):i.every(Boolean)}))}catch(n){return tt.warn("Failed to evaluate suppression rules. Capturing the exception.",n),!1}}ul(t){return t.flatMap((e=>{var n,i;return(n=(i=e.stacktrace)==null?void 0:i.frames)!==null&&n!==void 0?n:[]})).some((e=>e.filename&&e.filename.startsWith("chrome-extension://")))}hl(t){if(t.length>0){var e,n,i,s,r=(e=(n=t[0].stacktrace)==null?void 0:n.frames)!==null&&e!==void 0?e:[],o=r[r.length-1];return(i=o==null||(s=o.filename)==null?void 0:s.includes("posthog.com/static"))!==null&&i!==void 0&&i}return!1}al(t){return!B(t)&&O(t)}}},Uf=b({productTours:class{get Mr(){return this._instance.persistence}constructor(t){this.vl=null,this.cl=null,this._instance=t}initialize(){this.loadIfEnabled()}onRemoteConfig(t){if(t.ok){var e=t.config;if("productTours"in e){var n,i;if(this.Mr&&this.Mr.register({[na]:!!e.productTours}),!Mr(this._instance))return!this.vl&&B((n=this.Mr)==null?void 0:n.props[Kn])||Mi.info("product tours disabled; stopping and clearing cached tours"),(i=this.vl)==null||i.stop(),this.vl=null,void this.clearCache();this.loadIfEnabled()}}}loadIfEnabled(){!this.vl&&Mr(this._instance)&&this.ai((()=>this.fl()))}ai(t){var e,n;(e=R.__PosthogExtensions__)!=null&&e.generateProductTours?t():(n=R.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,"product-tours",(i=>{i?Mi.error("Could not load product tours script",i):t()}))}fl(){var t;!this.vl&&(t=R.__PosthogExtensions__)!=null&&t.generateProductTours&&(this.vl=R.__PosthogExtensions__.generateProductTours(this._instance,!0))}getProductTours(t,e){if(e===void 0&&(e=!1),!O(this.cl)||e){var n=this.Mr;if(n){var i=n.props[Kn];if(O(i)&&!e)return this.cl=i,void t(i,{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:s=>{if(Mr(this._instance)){var r=s.statusCode;if(r!==200||!s.json){var o="Product Tours API could not be loaded, status: "+r;return r===0?s.error||Mi.warn(o):Mi.error(o),void t([],{isLoaded:!1,error:o})}var a=O(s.json.product_tours)?s.json.product_tours:[];this.cl=a,n&&n.register({[Kn]:a}),t(a,{isLoaded:!0})}else t([],{isLoaded:!0})}})}else t(this.cl,{isLoaded:!0})}getActiveProductTours(t){B(this.vl)?t([],{isLoaded:!1,error:"Product tours not loaded"}):this.vl.getActiveProductTours(t)}showProductTour(t){var e;(e=this.vl)==null||e.showTourById(t)}previewTour(t){this.vl?this.vl.previewTour(t):this.ai((()=>{var e;this.fl(),(e=this.vl)==null||e.previewTour(t)}))}dismissProductTour(){var t;(t=this.vl)==null||t.dismissTour("user_clicked_skip")}nextStep(){var t;(t=this.vl)==null||t.nextStep()}previousStep(){var t;(t=this.vl)==null||t.previousStep()}clearCache(){var t;this.cl=null,(t=this.Mr)==null||t.unregister(Kn)}resetTour(t){var e;(e=this.vl)==null||e.resetTour(t)}resetAllTours(){var t;(t=this.vl)==null||t.resetAllTours()}cancelPendingTour(t){var e;(e=this.vl)==null||e.cancelPendingTour(t)}}},Us),Hf={siteApps:class{constructor(t){this.pl=0,this._instance=t,this.gl=[],this.apps={}}get isEnabled(){return!!this._instance.config.opt_in_site_apps}ml(t,e){if(e){var n=this.globalsForEvent(e);this.gl.push(n),this.gl.length>1e3&&(this.gl=this.gl.slice(10))}}get siteAppLoaders(){var t;return(t=R._POSTHOG_REMOTE_CONFIG)==null||(t=t[this._instance.config.token])==null?void 0:t.siteApps}initialize(){if(this.isEnabled){var t=this._instance._addCaptureHook(this.ml.bind(this));this.yl=()=>{t(),this.gl=[],this.yl=void 0}}}globalsForEvent(t){var e,n,i,s,r,o,a;if(!t)throw new Error("Event payload is required");var l={},u=this._instance.get_property("$groups")||[],c=this._instance.get_property("$stored_group_properties")||{};for(var d of Object.entries(c)){var h=d[0];l[h]={id:u[h],type:h,properties:d[1]}}var p=t.$set_once,f=t.$set;return{event:b({},jc(t,$f),{properties:b({},t.properties,f?{$set:b({},(e=(n=t.properties)==null?void 0:n.$set)!==null&&e!==void 0?e:{},f)}:{},p?{$set_once:b({},(i=(s=t.properties)==null?void 0:s.$set_once)!==null&&i!==void 0?i:{},p)}:{}),elements_chain:(r=(o=t.properties)==null?void 0:o.$elements_chain)!==null&&r!==void 0?r:"",distinct_id:(a=t.properties)==null?void 0:a.distinct_id}),person:{properties:this._instance.get_property("$stored_person_properties")},groups:l}}bl(t){var e,n=(e=t.tagName)==null?void 0:e.toLowerCase();return n==="style"&&this._instance.config.prepare_external_dependency_stylesheet?this._instance.config.prepare_external_dependency_stylesheet(t)||(et.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)||(et.error("prepare_external_dependency_script returned null"),null):t}_l(){var t,e,n,i,s,r,o,a;if(!this._instance.config.prepare_external_dependency_stylesheet&&!this._instance.config.prepare_external_dependency_script)return()=>{};var l=C?.defaultView,u=l==null||(t=l.Node)==null?void 0:t.prototype;if(!l||!u)return()=>{};if(this.pl++,this.wl)return this.kl();var c=[],d=this,h=new WeakSet,p=(m,v,E)=>{if(m!=null&&m[v]){var w=m[v];m[v]=E(w),c.push((()=>{m[v]=w}))}},f=m=>{if(h.has(m))return m;var v=d.bl(m);return v&&h.add(v),v},g=m=>m.map((v=>typeof v=="string"?v:f(v))).filter((v=>!$e(v)));return p(u,"appendChild",(m=>function(v){var E=f(v);return E?m.call(this,E):v})),p(u,"insertBefore",(m=>function(v,E){var w=f(v);return w?m.call(this,w,E):v})),p(u,"replaceChild",(m=>function(v,E){var w=f(v);return w?m.call(this,w,E):E})),[(e=l.Element)==null?void 0:e.prototype,(n=l.Document)==null?void 0:n.prototype,(i=l.DocumentFragment)==null?void 0:i.prototype].forEach((m=>{p(m,"append",(v=>function(){for(var E=arguments.length,w=new Array(E),I=0;E>I;I++)w[I]=arguments[I];return v.apply(this,g(w))})),p(m,"prepend",(v=>function(){for(var E=arguments.length,w=new Array(E),I=0;E>I;I++)w[I]=arguments[I];return v.apply(this,g(w))}))})),[(s=l.Element)==null?void 0:s.prototype,(r=l.CharacterData)==null?void 0:r.prototype,(o=l.DocumentType)==null?void 0:o.prototype].forEach((m=>{p(m,"before",(v=>function(){for(var E=arguments.length,w=new Array(E),I=0;E>I;I++)w[I]=arguments[I];return v.apply(this,g(w))})),p(m,"after",(v=>function(){for(var E=arguments.length,w=new Array(E),I=0;E>I;I++)w[I]=arguments[I];return v.apply(this,g(w))})),p(m,"replaceWith",(v=>function(){for(var E=arguments.length,w=new Array(E),I=0;E>I;I++)w[I]=arguments[I];var A=g(w);return w.length&&!A.length?void 0:v.apply(this,A)}))})),p((a=l.Element)==null?void 0:a.prototype,"insertAdjacentElement",(m=>function(v,E){var w=f(E);return w?m.call(this,v,w):null})),this.wl=()=>{c.forEach((m=>m())),this.wl=void 0},this.kl()}kl(){var t=!1;return()=>{var e;t||(t=!0,this.pl--,this.pl===0&&((e=this.wl)==null||e.call(this)))}}xl(t,e){e===void 0&&(e=!0);var n=this._l();try{var i=t(n);return e&&n(),i}catch(s){throw n(),s}}setupSiteApp(t){var e=this.apps[t.id],n=()=>{var o;!e.errored&&this.gl.length&&(et.info("Processing "+this.gl.length+" events for site app with id "+t.id),this.gl.forEach((a=>this.xl((()=>e.processEvent==null?void 0:e.processEvent(a))))),e.processedBuffer=!0),Object.values(this.apps).every((a=>a.processedBuffer||a.errored))&&((o=this.yl)==null||o.call(this))},i=!1,s=o=>{e.errored=!o,e.loaded=!0,et.info("Site app with id "+t.id+" "+(o?"loaded":"errored")),i&&n()};try{var r=this.xl((o=>t.init({posthog:this._instance,callback(a){o(),s(a)}})),!1).processEvent;r&&(e.processEvent=r),i=!0}catch(o){et.error(Kl+t.id,o),s(!1)}if(i&&e.loaded)try{n()}catch(o){et.error("Error while processing buffered events PostHog app with config id "+t.id,o),e.errored=!0}}Sl(){var t=this.siteAppLoaders||[];for(var e of t)this.apps[e.id]={id:e.id,loaded:!1,errored:!1,processedBuffer:!1};for(var n of t)this.setupSiteApp(n)}Cl(t){var e=this;if(Object.keys(this.apps).length!==0){var n=this.globalsForEvent(t),i=function(r){try{e.xl((()=>r.processEvent==null?void 0:r.processEvent(n)))}catch(o){et.error("Error while processing event "+t.event+" for site app "+r.id,o)}};for(var s of Object.values(this.apps))i(s)}}onRemoteConfig(t){var e,n,i,s=this;if((e=this.siteAppLoaders)!=null&&e.length)return this.isEnabled?(this.Sl(),void this._instance.on("eventCaptured",(l=>this.Cl(l)))):void et.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.');if((n=this.yl)==null||n.call(this),t.ok){var r=t.config;if((i=r.siteApps)!=null&&i.length)if(this.isEnabled){var o=function(){var l,u=a.id,c=a.url;R["__$$ph_site_app_"+u]=s._instance,(l=R.__PosthogExtensions__)==null||l.loadSiteApp==null||l.loadSiteApp(s._instance,c,(d=>{if(d)return et.error(Kl+u,d)}))};for(var a of r.siteApps)o()}else et.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.')}}}},Wf={tracingHeaders:class{constructor(t){this.Ml=void 0,this.Tl=void 0,this.El=void 0,this.Uo=()=>{var e,n,i=this.Il();i?(x(this.Ml)&&(this.Ml=(e=R.__PosthogExtensions__)==null||(e=e.tracingHeadersPatchFns)==null?void 0:e._patchXHR(i,(()=>this._instance.get_distinct_id()),this._instance.sessionManager)),x(this.Tl)&&(this.Tl=(n=R.__PosthogExtensions__)==null||(n=n.tracingHeadersPatchFns)==null?void 0:n._patchFetch(i,(()=>this._instance.get_distinct_id()),this._instance.sessionManager))):this.Qo()},this._instance=t}initialize(){this.startIfEnabledOrStop()}ai(t){var e,n;(e=R.__PosthogExtensions__)!=null&&e.tracingHeadersPatchFns?t():(n=R.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,"tracing-headers",(i=>{if(i)return Ff.error("failed to load script",i);t()}))}Pl(){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}Il(){var t=this.Pl();return O(t)?(O(this.El)?this.El.splice(0,this.El.length,...t):this.El=[...t],t.length>0?this.El:void 0):(O(this.El)&&this.El.splice(0),this.El=t||void 0,this.El)}Qo(){var t,e;(t=this.Ml)==null||t.call(this),(e=this.Tl)==null||e.call(this),this.Ml=void 0,this.Tl=void 0}startIfEnabledOrStop(){this.Il()?this.ai(this.Uo):this.Qo()}}},zf=b({surveys:class{get Ne(){return this._instance.config}constructor(t){this.Rl=void 0,this._surveyManager=null,this.Al=!1,this.Fl=[],this.Ll=null,this.Ol=null,this._instance=t,this._surveyEventReceiver=null}initialize(){this.loadIfEnabled()}onRemoteConfig(t){if(!this.Ne.disable_surveys){if(!t.ok)return G.warn("Remote config unavailable. Not loading surveys.");var e=t.config.surveys;if(B(e))return G.warn("Flags not loaded yet. Not loading surveys.");var n=O(e);this.Rl=n?e.length>0:e,G.info("flags response received, isSurveysEnabled: "+this.Rl),this.loadIfEnabled()}}reset(){try{var t;(t=this._surveyEventReceiver)==null||t.reset(),localStorage.removeItem("lastSeenSurveyDate");for(var e=[],n=0;nlocalStorage.removeItem(s)))}catch{}}loadIfEnabled(){if(!this._surveyManager)if(this.Al)G.info("Already initializing surveys, skipping...");else if(this.Ne.disable_surveys)G.info(Jl);else if(this.Ne.cookieless_mode&&this._instance.consent.isOptedOut())G.info("Not loading surveys in cookieless mode without consent.");else{var t=R?.__PosthogExtensions__;if(t){if(!x(this.Rl)||this.Ne.advanced_enable_surveys){var e=this.Rl||this.Ne.advanced_enable_surveys;this.Al=!0;try{var n=t.generateSurveys;if(n)return void this.Dl(n,e);var i=t.loadExternalDependency;if(!i)return void this.$l(sa);i(this._instance,"surveys",(s=>{s||!t.generateSurveys?this.$l("Could not load surveys script",s):this.Dl(t.generateSurveys,e)}))}catch(s){throw this.$l("Error initializing surveys",s),s}finally{this.Al=!1}}}else G.error("PostHog Extensions not found.")}}Dl(t,e){this._surveyManager=t(this._instance,e),this._surveyEventReceiver=new Nf(this._instance),G.info("Surveys loaded successfully"),this.Nl({isLoaded:!0})}$l(t,e){G.error(t,e),this.Nl({isLoaded:!1,error:t})}onSurveysLoaded(t){return this.Fl.push(t),this._surveyManager&&this.Nl({isLoaded:!0}),()=>{this.Fl=this.Fl.filter((e=>e!==t))}}getSurveys(t,e){if(e===void 0&&(e=!1),this.Ne.disable_surveys)return G.info(Jl),t([]);var n,i=this._instance.get_property(ao);if(i&&!e)return t(i,{isLoaded:!0}),void(this.ql()&&this.getSurveys((()=>{}),!0));typeof Promise<"u"&&this.Ll?this.Ll.then((s=>t(s.surveys,s.context))):(typeof Promise<"u"&&(this.Ll=new Promise((s=>{n=s}))),this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/surveys/?token="+this.Ne.token),method:"GET",timestampMode:"query",timeout:this.Ne.surveys_request_timeout_ms,callback:s=>{var r;this.Ll=null;var o=s.statusCode;if(o!==200||!s.json){var a="Surveys API could not be loaded, status: "+o;o!==0?G.error(a):s.error||G.warn(a),this.Ol=Date.now();var l={isLoaded:!1,error:a};return t([],l),void(n==null||n({surveys:[],context:l}))}this.Ol=null;var u,c=s.json.surveys||[],d=c.filter((p=>(function(f){return!(!f.start_date||f.end_date)})(p)&&(vd(p)||(function(f){var g;return!((g=f.conditions)==null||(g=g.actions)==null||(g=g.values)==null||!g.length)})(p))));d.length>0&&((u=this._surveyEventReceiver)==null||u.register(d)),(r=this._instance.persistence)==null||r.register({[ao]:c,[us]:Date.now()});var h={isLoaded:!0};t(c,h),n?.({surveys:c,context:h})}}))}ql(){return this.jl()&&!this.Ll&&!this.Bl()}jl(){var t=this._instance.get_property(us);return he(t)&&Date.now()-t>3e5}Bl(){return he(this.Ol)&&3e5>Date.now()-this.Ol}markSurveyAsSeen(t,e){var n,i={id:t,current_iteration:(n=e?.iteration)!==null&&n!==void 0?n:null};yd(i);try{localStorage.setItem("lastSeenSurveyDate",new Date().toISOString())}catch{}}Nl(t){for(var e of this.Fl)try{if(!t.isLoaded)return e([],t);this.getSurveys(e)}catch(n){G.error("Error in survey callback",n)}}getActiveMatchingSurveys(t,e){if(e===void 0&&(e=!1),!B(this._surveyManager))return this._surveyManager.getActiveMatchingSurveys(t,e);G.warn("init was not called")}Hl(t){var e=null;return this.getSurveys((n=>{var i;e=(i=n.find((s=>s.id===t)))!==null&&i!==void 0?i:null})),e}Ul(t){if(B(this._surveyManager))return{eligible:!1,reason:Li};var e=typeof t=="string"?this.Hl(t):t;return e?this._surveyManager.checkSurveyEligibility(e):{eligible:!1,reason:"Survey not found"}}zl(t){if(B(this._surveyManager))return{eligible:!1,reason:Li};var e=typeof t=="string"?this.Hl(t):t;return e?this._surveyManager.checkSurveyRenderability(e):{eligible:!1,reason:"Survey not found"}}canRenderSurvey(t){if(B(this._surveyManager))return G.warn("init was not called"),{visible:!1,disabledReason:Li};var e=this.zl(t);return{visible:e.eligible,disabledReason:e.reason}}canRenderSurveyAsync(t,e){return B(this._surveyManager)?(G.warn("init was not called"),Promise.resolve({visible:!1,disabledReason:Li})):new Promise((n=>{this.getSurveys((i=>{var s,r=(s=i.find((a=>a.id===t)))!==null&&s!==void 0?s:null;if(r){var o=this.zl(r);n({visible:o.eligible,disabledReason:o.reason})}else n({visible:!1,disabledReason:"Survey not found"})}),e)}))}renderSurvey(t,e,n){var i;if(B(this._surveyManager))G.warn("init was not called");else{var s=typeof t=="string"?this.Hl(t):t;if(s!=null&&s.id)if(mf.includes(s.type)){var r=C?.querySelector(e);if(r)return(i=s.appearance)!=null&&i.surveyPopupDelaySeconds?(G.info("Rendering survey "+s.id+" with delay of "+s.appearance.surveyPopupDelaySeconds+" seconds"),void setTimeout((()=>{var o,a;G.info("Rendering survey "+s.id+" with delay of "+((o=s.appearance)==null?void 0:o.surveyPopupDelaySeconds)+" seconds"),(a=this._surveyManager)==null||a.renderSurvey(s,r,n),G.info("Survey "+s.id+" rendered")}),1e3*s.appearance.surveyPopupDelaySeconds)):void this._surveyManager.renderSurvey(s,r,n);G.warn("Survey element not found")}else G.warn("Surveys of type "+s.type+" cannot be rendered in the app");else G.warn("Survey not found")}}displaySurvey(t,e){var n;if(B(this._surveyManager))G.warn("init was not called");else{var i=this.Hl(t);if(i){var s=i;if((n=i.appearance)!=null&&n.surveyPopupDelaySeconds&&e.ignoreDelay&&(s=b({},i,{appearance:b({},i.appearance,{surveyPopupDelaySeconds:0})})),e.displayType!==_o.Popover&&e.initialResponses&&G.warn("initialResponses is only supported for popover surveys. prefill will not be applied."),e.ignoreConditions===!1){var r=this.Ul(i);if(!r.eligible)return void G.warn("Survey is not eligible to be displayed: ",r.reason)}e.displayType!==_o.Inline?this._surveyManager.handlePopoverSurvey(s,e):this.renderSurvey(s,e.selector,e.properties)}else G.warn("Survey not found")}}cancelPendingSurvey(t){B(this._surveyManager)?G.warn("init was not called"):this._surveyManager.cancelSurvey(t)}handlePageUnload(){var t;(t=this._surveyManager)==null||t.handlePageUnload==null||t.handlePageUnload()}}},Us),qf={toolbar:class{constructor(t){this.instance=t}Wl(t){R.ph_toolbar_state=t}Vl(){var t;return(t=R.ph_toolbar_state)!==null&&t!==void 0?t:0}initialize(){return this.maybeLoadToolbar()}maybeLoadToolbar(t,e,n){if(t===void 0&&(t=void 0),e===void 0&&(e=void 0),n===void 0&&(n=void 0),go(this.instance.config)||!_||!C)return!1;t=t??_.location,n=n??_.history;try{if(!e){try{_.localStorage.setItem("test","test"),_.localStorage.removeItem("test")}catch{return!1}e=_?.localStorage}var i,s=Mf||_s(t.hash,"__posthog")||_s(t.hash,"state"),r=s?pl((()=>JSON.parse(atob(decodeURIComponent(s)))))||pl((()=>JSON.parse(decodeURIComponent(s)))):null;return r&&r.action==="ph_authorize"?((i=r).source="url",i&&Object.keys(i).length>0&&(r.desiredHash?t.hash=r.desiredHash:n?n.replaceState(n.state,"",t.pathname+t.search):t.hash="")):((i=JSON.parse(e.getItem(Yl)||"{}")).source="localstorage",delete i.userIntent),!(!i.token||this.instance.config.token!==i.token||(this.loadToolbar(i),0))}catch{return!1}}Zl(t){var e=R.ph_load_toolbar||R.ph_load_editor;!B(e)&&Se(e)?e(t,this.instance):Zl.warn("No toolbar load function found")}loadToolbar(t){var e=!(C==null||!C.getElementById(Nu));if(!_||e)return!1;var n=this.instance.requestRouter.region==="custom"&&this.instance.config.advanced_disable_toolbar_metrics,i=b({token:this.instance.config.token},t,{apiURL:this.instance.requestRouter.endpointFor("ui")},n?{instrument:!1}:{});if(_.localStorage.setItem(Yl,JSON.stringify(b({},i,{source:void 0}))),this.Vl()===2)this.Zl(i);else if(this.Vl()===0){var s;this.Wl(1),(s=R.__PosthogExtensions__)==null||s.loadExternalDependency==null||s.loadExternalDependency(this.instance,"toolbar",(r=>{if(r)return Zl.error("[Toolbar] Failed to load",r),void this.Wl(0);this.Wl(2),this.Zl(i)})),re(_,"turbolinks:load",(()=>{this.Wl(0),this.loadToolbar(i)}))}return!0}Gl(t){return this.loadToolbar(t)}maybeLoadEditor(t,e,n){return t===void 0&&(t=void 0),e===void 0&&(e=void 0),n===void 0&&(n=void 0),this.maybeLoadToolbar(t,e,n)}}},Vf=b({experiments:ye},Us),Gf={conversations:class{constructor(t){this.Ql=void 0,this._conversationsManager=null,this.Kl=!1,this.Jl=null,this.Yl=!1,this._instance=t}initialize(){this.loadIfEnabled()}onRemoteConfig(t){if(!this._instance.config.disable_conversations&&(this.Xl=t.ok,t.ok)){var e=t.config.conversations;B(e)||(Ye(e)?this.Ql=e:(this.Ql=e.enabled,this.Jl=e),this.loadIfEnabled())}}reset(){var t;(t=this._conversationsManager)==null||t.reset(),this._conversationsManager=null,this.Ql=void 0,this.Jl=null,this.Xl=void 0,this.Yl=!1}loadIfEnabled(){if(!(this._conversationsManager||this.Kl||this._instance.config.disable_conversations||go(this._instance.config)||this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut())){var t=R?.__PosthogExtensions__;if(t&&!x(this.Ql)&&this.Ql)if(this.Jl&&this.Jl.token){this.Kl=!0;try{var e=t.initConversations;if(e)return this.tu(e),void(this.Kl=!1);var n=t.loadExternalDependency;if(!n)return void this.eu(sa);n(this._instance,"conversations",(i=>{i||!t.initConversations?this.eu("Could not load conversations script",i):this.tu(t.initConversations),this.Kl=!1}))}catch(i){this.eu("Error initializing conversations",i),this.Kl=!1}}else Ue.error("Conversations enabled but missing token in remote config.")}}tu(t){if(this.Jl)try{this._conversationsManager=t(this.Jl,this._instance),this.Yl=!1,Ue.info("Conversations loaded successfully")}catch(e){this.eu("Error completing conversations initialization",e)}else Ue.error("Cannot complete initialization: remote config is null")}eu(t,e){Ue.error(t,e),this._conversationsManager=null,this.Kl=!1,this.Yl=!0}show(){this._conversationsManager?this._conversationsManager.show():Ue.warn("Conversations not loaded yet.")}hide(){this._conversationsManager&&this._conversationsManager.hide()}isAvailable(){return this.Ql===!0&&!$e(this._conversationsManager)}getUnavailableReason(){return this.isAvailable()?null:this._instance.config.disable_conversations?"disabled_by_config":go(this._instance.config)?"disabled_for_toolbar":this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut()?"consent_opted_out":this.Xl===!1?"remote_config_failed":x(this.Ql)?this.Xl?"disabled_in_project":"remote_config_pending":this.Ql?B(this.Jl)||!this.Jl.token?"missing_token":R!=null&&R.__PosthogExtensions__?this.Kl?"initializing":this.Yl?"load_failed":"not_loaded":"extensions_unavailable":"disabled_in_project"}isVisible(){var t,e;return(t=(e=this._conversationsManager)==null?void 0:e.isVisible())!==null&&t!==void 0&&t}sendMessage(t,e,n){var i=this;return X((function*(){return i._conversationsManager?i._conversationsManager.sendMessage(t,e,n):(Ue.warn(Ht),null)}))()}getMessages(t,e){var n=this;return X((function*(){return n._conversationsManager?n._conversationsManager.getMessages(t,e):(Ue.warn(Ht),null)}))()}markAsRead(t){var e=this;return X((function*(){return e._conversationsManager?e._conversationsManager.markAsRead(t):(Ue.warn(Ht),null)}))()}getTickets(t){var e=this;return X((function*(){return e._conversationsManager?e._conversationsManager.getTickets(t):(Ue.warn(Ht),null)}))()}requestRestoreLink(t){var e=this;return X((function*(){return e._conversationsManager?e._conversationsManager.requestRestoreLink(t):(Ue.warn(Ht),null)}))()}restoreFromToken(t){var e=this;return X((function*(){return e._conversationsManager?e._conversationsManager.restoreFromToken(t):(Ue.warn(Ht),null)}))()}restoreFromUrlToken(){var t=this;return X((function*(){return t._conversationsManager?t._conversationsManager.restoreFromUrlToken():(Ue.warn(Ht),null)}))()}getCurrentTicketId(){var t,e;return(t=(e=this._conversationsManager)==null?void 0:e.getCurrentTicketId())!==null&&t!==void 0?t:null}getWidgetSessionId(){var t,e;return(t=(e=this._conversationsManager)==null?void 0:e.getWidgetSessionId())!==null&&t!==void 0?t:null}Xn(){var t;(t=this._conversationsManager)==null||t.setIdentity()}ts(){var t;(t=this._conversationsManager)==null||t.clearIdentity()}}},Kf={logs:class{constructor(t){var e,n=this;this.iu=!1,this.ru=!1,this.rt=ie("[logs]"),this.nu=b({},this.rt,{error(){for(var i=arguments.length,s=new Array(i),r=0;i>r;r++)s[r]=arguments[r];s.some(rc)||n.rt.error(...s)}}),this.tr=[],this.su=[],this.Sa=0,this.au=()=>{var i,s;this.Sa=0,(i=this.ou)==null||i.onReconnect(),(s=this.lu)==null||s.onReconnect()},this._instance=t,this._instance&&(e=this._instance.config.logs)!=null&&e.captureConsoleLogs&&(this.iu=!0),_&&re(_,"online",this.au)}uu(t,e,n,i){var s,r=(function(o,a){var l,u,c,d,h,p,f,g=(l=o?.flushIntervalMs)!==null&&l!==void 0?l:3e3,m=(u=o?.maxBufferSize)!==null&&u!==void 0?u:100,v=a!=null&&a.consoleCapture?void 0:(c=o?.maxLogsPerInterval)!==null&&c!==void 0?c:1e3,E=x(v)?Math.max(m,2048):Math.max(m,v),w=o?.resourceAttributes;return{serviceName:(d=(h=w?.["service.name"])!==null&&h!==void 0?h:o?.serviceName)!==null&&d!==void 0?d:a?.serviceNameDefault,serviceVersion:(p=w?.["service.version"])!==null&&p!==void 0?p:o?.serviceVersion,environment:(f=w?.["deployment.environment"])!==null&&f!==void 0?f:o?.environment,resourceAttributes:w,beforeSend:o?.beforeSend,flushIntervalMs:g,maxBufferSize:m,maxQueueSize:E,maxBatchRecordsPerPost:100,rateCapWindowMs:g,maxLogsPerInterval:v,backgroundFlushBudgetMs:0,terminationFlushBudgetMs:0}})((s=this._instance)==null||(s=s.config)==null?void 0:s.logs,n);return[new Zh(this.hu(t,e),r,this.nu,(()=>this.du()),(o=>o()),void 0,i),r]}vu(){var t,e=(t=this._instance)==null||(t=t.config)==null?void 0:t.logs;if(!this.ou||this.cu!==e){var n;(n=this.ou)==null||n.reset(),this.cu=e;var i=this.uu((()=>this.tr),(s=>{this.tr=s}));this.ou=i[0],this.fu=i[1]}return this.ou}pu(){var t,e=(t=this._instance)==null||(t=t.config)==null?void 0:t.logs;if(!this.lu||this.gu!==e){var n;(n=this.lu)==null||n.reset(),this.gu=e;var i=this.uu((()=>this.su),(s=>{this.su=s}),{serviceNameDefault:"posthog-browser-logs",consoleCapture:!0},sc);this.lu=i[0],this.mu=i[1]}return this.lu}initialize(){this.loadIfEnabled()}onRemoteConfig(t){var e;if(t.ok){var n=(e=t.config.logs)==null?void 0:e.captureConsoleLogs;!B(n)&&n&&(this.iu=!0,this.loadIfEnabled())}}reset(){var t,e;this.tr=[],(t=this.ou)==null||t.reset(),this.su=[],(e=this.lu)==null||e.reset(),this.Sa=0}captureLog(t){this.vu().captureLog(t)}he(t){this.pu().captureLog(t)}get logger(){return this.yu||(this.yu={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.yu}flushLogs(t){t?this.bu(t):(this.ou&&this.ou.flush().catch((e=>this._u(e))),this.lu&&this.lu.flush().catch((e=>this._u(e))))}_u(t){rc(t)||this.rt.error("PostHog logs flush failed:",t)}loadIfEnabled(){if(this.iu&&!this.ru){var t=R?.__PosthogExtensions__;if(t){var e=t.loadExternalDependency;e?e(this._instance,"logs",(n=>{var i;n||(i=t.logs)==null||!i.initializeLogs?this.rt.error("Could not load logs script",n):(t.logs.initializeLogs(this._instance),this.ru=!0)})):this.rt.error(sa)}else this.rt.error("PostHog Extensions not found.")}}hu(t,e){var n=this._instance;return{get isDisabled(){return!1},get optedOut(){return!n.is_capturing()},getPersistedProperty:i=>i===pt.LogsQueue?t():void 0,setPersistedProperty(i,s){var r;i===pt.LogsQueue&&e((r=s)!==null&&r!==void 0?r:[])},Ot:i=>this.Ot(i),getLibraryId:()=>Y.LIB_NAME,getLibraryVersion:()=>Y.LIB_VERSION}}Ot(t){return new Promise((e=>{if(Vu(this.Sa,3))e({kind:"fatal",error:Or(void 0,"logs endpoint is unreachable, dropping batch")});else{var n=!1,i=r=>{n||(n=!0,clearTimeout(s),e(r))},s=setTimeout((()=>{this.rt.warn("Logs request timed out before receiving a response"),i({kind:"retry-later",error:Or(void 0,"logs request timed out")})}),9e4);this._instance._send_request({method:"POST",url:this.wu(),data:t,compression:"best-available",batchKey:"logs",fireCallbackOnDrop:!0,callback:r=>{var o=r.statusCode;if(this.ku(o),o>=200&&300>o)i({kind:"ok"});else if(o===413)i({kind:"too-large"});else if(o!==0&&o!==429&&500>o)i({kind:"fatal",error:new Error("logs request failed with status "+o)});else{var a;o===0?(r.error||this.rt.warn("Logs request failed before receiving an HTTP response"),i({kind:"retry-later",error:Or(r.error,"logs request failed before receiving an HTTP response")})):i({kind:"retry-later",error:(a=r.error)!==null&&a!==void 0?a:new Error("logs request failed with status "+o)})}}})}}))}ku(t){(t!==0||this._instance.__loaded)&&(this.Sa=Gu(t,this.Sa,3,(()=>this.rt.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."))))}bu(t){this.tr.length>0&&this.xu(t,this.tr,this.fu,Y.LIB_NAME,(e=>{this.tr=e})),this.su.length>0&&this.xu(t,this.su,this.mu,sc,(e=>{this.su=e}))}xu(t,e,n,i,s){if(e.length!==0){var r=e.map((a=>a.record));s([]);var o=vu(r,mu(n,Y.LIB_NAME,Y.LIB_VERSION),i,Y.LIB_VERSION);this._instance._send_request({method:"POST",url:this.wu(),data:o,compression:"best-available",batchKey:"logs",transport:t})}}wu(){return this._instance.requestRouter.endpointFor("api","/i/v1/logs")+"?token="+encodeURIComponent(this._instance.config.token)}du(){var t,e={};if(e.distinctId=this._instance.get_distinct_id(),this._instance.sessionManager){var n=this._instance.sessionManager.checkAndGetSessionAndWindowId(!0),i=n.windowId,s=n.sessionStartTimestamp,r=n.lastActivityTimestamp;e.sessionId=n.sessionId,e.windowId=i,B(s)||(e.sessionStartTimestamp=s),B(r)||(e.lastActivityTimestamp=r)}if(R!=null&&(t=R.location)!=null&&t.href&&(e.currentUrl=this._instance.config.disable_capture_url_hashes?Pt(R.location.href):R.location.href),this._instance.featureFlags){var o=this._instance.featureFlags.getFlags();o&&o.length>0&&(e.activeFeatureFlags=o)}return e}}},Jf={metrics:class{constructor(t){this.rt=ie("[metrics]"),this._instance=t}initialize(){}vu(){var t,e,n=(t=this._instance)==null||(t=t.config)==null?void 0:t.metrics;return this.ou&&this.cu===n||((e=this.ou)==null||e.reset(),this.cu=n,this.ou=new Xh(this.hu(),(function(i){var s,r,o,a,l,u=i?.resourceAttributes;return{serviceName:(s=u?.["service.name"])!==null&&s!==void 0?s:i?.serviceName,serviceVersion:(r=u?.["service.version"])!==null&&r!==void 0?r:i?.serviceVersion,environment:(o=u?.["deployment.environment"])!==null&&o!==void 0?o:i?.environment,resourceAttributes:u,beforeSend:i?.beforeSend,flushIntervalMs:(a=i?.flushIntervalMs)!==null&&a!==void 0?a:1e4,maxSeriesPerFlush:(l=i?.maxSeriesPerFlush)!==null&&l!==void 0?l:1e3}})(n),this.rt)),this.ou}count(t,e,n){e===void 0&&(e=1),this.vu().count(t,e,n)}gauge(t,e,n){this.vu().gauge(t,e,n)}histogram(t,e,n){this.vu().histogram(t,e,n)}flush(t){if(!this.ou)return Promise.resolve();if(t){var e=this.ou.drainWindow();return e&&this.Jt(e,t),Promise.resolve()}return this.ou.flush().catch((n=>this.rt.error("PostHog metrics flush failed:",n)))}reset(){var t;(t=this.ou)==null||t.reset()}hu(){var t=this._instance,e=this;return{get isDisabled(){return!1},get optedOut(){return!t.is_capturing()},Jt:n=>e.Jt(n),getLibraryId:()=>Y.LIB_NAME,getLibraryVersion:()=>Y.LIB_VERSION}}Jt(t,e){return new Promise((n=>{var i=!1,s=o=>{i||(i=!0,clearTimeout(r),n(o))},r=setTimeout((()=>s({kind:"retry-later",error:new Error("metrics request timed out")})),9e4);this._instance._send_request(b({method:"POST",url:this.Su(),data:t,compression:"best-available",batchKey:"metrics"},e&&{transport:e},{fireCallbackOnDrop:!0,callback(o){var a=o.statusCode;if(a>=200&&300>a)s({kind:"ok"});else if(a===413)s({kind:"too-large"});else if(a!==0&&a!==429&&500>a)s({kind:"fatal",error:new Error("metrics request failed with status "+a)});else{var l;s({kind:"retry-later",error:(l=o.error)!==null&&l!==void 0?l:new Error("metrics request failed with status "+a)})}}}))}))}Su(){return this._instance.requestRouter.endpointFor("api","/i/v1/metrics")+"?token="+encodeURIComponent(this._instance.config.token)}}},Yf=b({},Us,Bf,Df,jf,Uf,Hf,zf,Wf,qf,Vf,Gf,Kf,Jf);Re.__defaultExtensionClasses=b({},Yf);(function(){Y.SDK_DIST_CHANNEL="npm";var t=ti[un]=new Re;return(function(){function e(){e.done||(e.done=!0,bd=!1,Z(ti,(function(n){n._dom_loaded()})))}C!=null&&C.addEventListener?C.readyState==="complete"?e():re(C,"DOMContentLoaded",e,{capture:!1}):_&&k.error("Browser doesn't support `document.addEventListener` so PostHog couldn't be initialized")})(),t})();const Zf=["a[href]","button:not([disabled])","input:not([disabled]):not([type='hidden'])","select:not([disabled])","textarea:not([disabled])","[tabindex]:not([tabindex='-1'])"].join(",");let Je=null,Io=null,Sd="";const Co=new Map;function xd(t){return[...t.querySelectorAll(Zf)].filter(e=>!e.hidden&&e.getAttribute("aria-hidden")!=="true"&&e.getClientRects().length>0)}function Xf(t){for(const e of document.body.children)e===t||e.tagName==="SCRIPT"||(Co.set(e,{inert:e.inert,ariaHidden:e.getAttribute("aria-hidden")}),e.inert=!0,e.setAttribute("aria-hidden","true"))}function Qf(){for(const[t,e]of Co)t.inert=e.inert,e.ariaHidden===null?t.removeAttribute("aria-hidden"):t.setAttribute("aria-hidden",e.ariaHidden);Co.clear()}function kd(t){return t?.dataset.modalDismissible!=="false"&&t?.getAttribute("aria-busy")!=="true"}function Ve(t,e={}){const n=typeof t=="string"?document.getElementById(t):t;if(!n)return!1;Je&&Je!==n&&Xe(Je,{restoreFocus:!1,force:!0}),Io=e.trigger||document.activeElement,Je=n,Sd=document.body.style.overflow,Xf(n),document.body.style.overflow="hidden",n.classList.add("open"),n.setAttribute("aria-hidden","false");const i=n.querySelector(".modal-content");i&&(i.style.transform="scale(1) translateY(0)");const s=()=>{if(Je!==n)return;((e.initialFocus?n.querySelector(e.initialFocus):n.querySelector("[data-modal-initial-focus]"))||xd(n)[0]||n.querySelector(".modal-content")||n).focus({preventScroll:!0})};return requestAnimationFrame(s),setTimeout(s,260),!0}function Xe(t,e={}){const n=typeof t=="string"?document.getElementById(t):t;if(!n||!e.force&&!kd(n))return!1;n.classList.remove("open"),n.setAttribute("aria-hidden","true"),Qf(),document.body.style.overflow=Sd,Je=null;const i=Io;return Io=null,e.restoreFocus!==!1&&i?.isConnected&&i.focus({preventScroll:!0}),!0}function oc(t,e,n="Operation in progress"){const i=typeof t=="string"?document.getElementById(t):t;i&&(i.dataset.modalDismissible=e?"false":"true",i.setAttribute("aria-busy",String(!!e)),e?i.setAttribute("aria-label",n):i.removeAttribute("aria-label"))}function eg(t){if(!kd(t))return;const e=t.dataset.modalCloseHandler;e&&typeof window[e]=="function"?window[e]():Xe(t)}document.addEventListener("keydown",t=>{if(!Je)return;if(t.key==="Escape"){t.preventDefault(),t.stopImmediatePropagation(),eg(Je);return}if(t.key!=="Tab"){t.stopPropagation();return}const e=xd(Je);if(!e.length){t.preventDefault(),(Je.querySelector(".modal-content")||Je).focus();return}const n=e[0],i=e[e.length-1];t.shiftKey&&document.activeElement===n?(t.preventDefault(),i.focus()):!t.shiftKey&&document.activeElement===i&&(t.preventDefault(),n.focus())},!0);function tg(){document.querySelectorAll(".modal-overlay").forEach(t=>{t.setAttribute("role","dialog"),t.setAttribute("aria-modal","true"),t.setAttribute("aria-hidden",t.classList.contains("open")?"false":"true");const e=t.querySelector(".modal-content");e&&!e.hasAttribute("tabindex")&&(e.tabIndex=-1);const n=t.querySelector("h1, h2, h3");n&&(n.id||(n.id=`${t.id}-title`),t.setAttribute("aria-labelledby",n.id)),t.querySelectorAll(".modal-close").forEach(i=>{i.getAttribute("aria-label")||i.setAttribute("aria-label","Close dialog")})})}const Id="CodeFile",Cd="GeneratedCode",ng={CustomAction:"A",CustomWidget:"W",CustomFunction:"F",CustomClass:"C",CodeFile:"C"};function At(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function Ao(t){return String(t||"").trim().replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function ig(t={},e=0){const n=Ao(t.artifactType||t.type||Id),i=Ao(t.artifactName||t.name||t.fileName||`${Cd}-${e+1}`);return`${n||"artifact"}-${i||e+1}`}function Ad(t={},e=0){const n=At(t),i=n.artifactType||n.type||Id,s=n.artifactName||n.name||Cd;let r=n.fileName||s;return r.endsWith(".dart")||(r+=".dart"),{id:Ao(n.id)||ig({...n,artifactType:i,artifactName:s,fileName:r},e),artifactType:i,artifactName:s,fileName:r,deployPath:n.deployPath||"",description:n.description||"",code:n.code||n.content||"",dependencies:Fd(n.dependencies),imports:Array.isArray(n.imports)?n.imports:[],publicApi:Array.isArray(n.publicApi)?n.publicApi:[],relationships:Pd(n.relationships),deployStatus:n.deployStatus||"pending",review:n.review||null,metadata:At(n.metadata),codeType:n.codeType||ng[i]||"O"}}function Fd(t){return t?Array.isArray(t)?t.map(e=>{if(typeof e=="string")return{name:e,version:null,inferred:!1};const n=At(e),i=n.name||n.package;return i?{name:i,version:n.version||null,versionRequired:!!(n.versionRequired||n.required),inferred:!!n.inferred,...n.reason?{reason:n.reason}:{}}:null}).filter(Boolean):Object.entries(At(t)).map(([e,n])=>({name:e,version:n||null,inferred:!1})):[]}function Pd(t){return t?(Array.isArray(t)?t:[t]).map(e=>{const n=At(e);return!n.from&&!n.to?null:{from:n.from||null,to:n.to||null,type:n.type||"uses",description:n.description||""}}).filter(Boolean):[]}function Fo(t){if(typeof t!="string")return null;const e=t.trim();if(!e)return null;try{return JSON.parse(e)}catch{const n=e.match(/```(?:json)?\s*([\s\S]*?)```/i);if(!n)return null;try{return JSON.parse(n[1].trim())}catch{return null}}}function di(t,e={}){const n=[],i=typeof t=="string"?Fo(t):t,r=At(i||{});!i&&typeof t=="string"&&n.push("Structured bundle parse failed; using legacy single-artifact fallback.");const o=Array.isArray(r.artifacts)?r.artifacts:[{artifactType:r.artifactType||e.artifactType,artifactName:r.artifactName||e.artifactName,fileName:r.fileName||e.fileName,description:r.description,code:r.code||e.code||(typeof t=="string"?t:""),dependencies:r.dependencies||e.dependencies,relationships:r.relationships||e.relationships}];o.forEach((d,h)=>{!d?.artifactType&&!d?.type&&n.push(`Artifact ${h+1} has no artifactType; it will deploy as a standalone code file under lib/custom_code/ root.`)});const a=o.map((d,h)=>Ad(d,h)),l=new Map(o.map((d,h)=>[At(d).id,a[h]?.id]).filter(([d,h])=>d&&h)),u=d=>l.get(d)||d,c=Pd(r.relationships||e.relationships).map(d=>({...d,from:d.from?u(d.from):d.from,to:d.to?u(d.to):d.to}));return{schemaVersion:r.schemaVersion||e.schemaVersion||null,id:r.id||e.id||"bundle-current",title:r.title||r.name||e.title||"Generated artifact bundle",description:r.description||e.description||"",artifacts:a,dependencies:Fd(r.dependencies||e.dependencies),relationships:c,deployOrder:Array.isArray(r.deployOrder)?r.deployOrder.map(u):a.map(d=>d.id),warnings:[...n,...Array.isArray(r.warnings)?r.warnings:[]],metadata:At(r.metadata)}}function Ss(t){return di(t).artifacts[0]||Ad()}function Et(t){if(typeof t!="string")return t??"";const e=t.trim();if(!e)return"";try{return JSON.parse(e)}catch{return t}}function Sn(t){return JSON.stringify(t,null,2)}function sg(t){return Sn({task:"architect",userRequest:String(t??"")})}function rg(t){const e=Et(t);return e&&typeof e=="object"&&typeof e.task=="string"?Sn(e):Sn({task:"generate_bundle",bundleSpec:e})}function og(t){return Sn({task:"review_bundle",generatedBundle:Et(t),outputRequirements:{bundleReview:["status","score","summary","manualActions","findings"],scoreRange:[0,100],eachArtifact:["id","review.status","review.findings"],manualActions:{definition:"Setup the developer must perform by hand in the FlutterFlow editor that FlutterFlow will NOT do for them.",exclude:["creating the Custom Action, Widget or Code File itself - deploying the code creates it","declaring parameters or return values FlutterFlow derives from the function signature","anything that resolves as a side effect of using the action or widget in the editor","generic advice such as testing, reviewing or rebuilding the app"],preferEmpty:"Return an empty array when nothing qualifies - an empty list is the expected result for most bundles."}}})}function ha(t,e=null){const n={stage:t};return e!=null&&(n.bundle=Et(e)),n}function ag({bundleSpec:t,artifactBundle:e,bundleReview:n,artifactId:i,userFeedback:s}){return Sn({task:"regenerate_artifact",artifactId:i,bundleSpec:Et(t),artifactBundle:Et(e),bundleReview:Et(n),userFeedback:String(s)})}function $d({bundleSpec:t,artifactBundle:e,bundleReview:n,userFeedback:i}){return Sn({task:"regenerate_bundle",bundleSpec:Et(t),artifactBundle:Et(e),bundleReview:Et(n),userFeedback:String(i??"")})}const ac={csam:"child-safety content",dangerous:"dangerous content",harassment:"harassment",hate_speech:"hate speech",maliciousUrls:"a potentially malicious URL",malicious_uris:"a potentially malicious URL",pi_and_jailbreak:"prompt-injection or jailbreak instructions",promptInjection:"prompt-injection or jailbreak instructions",rai:"restricted content",sdp:"sensitive personal data",sexually_explicit:"sexually explicit content",virus_scan:"potentially malicious file content"},lg=["sanitizationResult","modelArmor","modelArmorResult","data","result","error"];function Le(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function cg(t){return Le(t)?typeof t.filterMatchState=="string"||typeof t.invocationResult=="string"||Array.isArray(t.matchedFilters)||Le(t.filterSummary)||Le(t.filterResults):!1}function Td(t,e=0){if(!Le(t)||e>3)return null;if(cg(t))return t;for(const n of lg){const i=t[n];if(Le(i)){const s=Td(i,e+1);if(s)return s}}return null}function xs(t){return Array.isArray(t)?t.some(xs):Le(t)?t.matched===!0||t.matchState==="MATCH_FOUND"?!0:Object.values(t).some(xs):!1}function Po(t){return Array.isArray(t)?t.some(Po):Le(t)?typeof t.executionState=="string"&&t.executionState!=="EXECUTION_SUCCESS"?!0:Object.values(t).some(Po):!1}function Rd(t){return{csamFilterFilterResult:"csam",maliciousUriFilterResult:"malicious_uris",piAndJailbreakFilterResult:"pi_and_jailbreak",raiFilterResult:"rai",sdpFilterResult:"sdp",virusScanFilterResult:"virus_scan"}[t]||t}function ug(t,e){if(Le(t))for(const[n,i]of Object.entries(t)){if(!Le(i))continue;const s=Le(i.categories)?i.categories:{},r=Object.entries(s).filter(([,o])=>Le(o)&&o.matched===!0).map(([o])=>o);r.length>0?r.forEach(o=>e.add(o)):i.matched===!0&&e.add(Rd(n))}}function dg(t,e){if(!t)return;const n=Array.isArray(t)?t.flatMap(i=>Le(i)?Object.entries(i):[]):Object.entries(t);for(const[i,s]of n){if(!xs(s))continue;const r=Rd(i),o=s?.raiFilterResult?.raiFilterTypeResults||(r==="rai"?s?.raiFilterTypeResults:null),a=Le(o)?Object.entries(o).filter(([,l])=>xs(l)).map(([l])=>l):[];a.length>0?a.forEach(l=>e.add(l)):e.add(r)}}function hg(t){return ac[t]?ac[t]:String(t).replace(/([a-z])([A-Z])/g,"$1 $2").replace(/_/g," ").toLowerCase()}function lc(t){return t.length<=1?t[0]||"content that did not pass":t.length===2?`${t[0]} and ${t[1]}`:`${t.slice(0,-1).join(", ")}, and ${t.at(-1)}`}function pg(t){const e=Td(t);if(!e)return null;const n=new Set(Array.isArray(e.matchedFilters)?e.matchedFilters:[]);ug(e.filterSummary,n),dg(e.filterResults,n);const i=e.blocked===!0||e.filterMatchState==="MATCH_FOUND"||n.size>0,s=e.invocationResult||null,r=Po(e.filterSummary||e.filterResults);return!i&&!r&&!["PARTIAL","FAILURE"].includes(s)?null:{kind:i?"blocked":"unavailable",invocationResult:s,matchedFilters:[...n]}}function fg(t,e){const n=pg(t);if(!n)return null;const i=[...new Set(n.matchedFilters.map(hg))],s=n.kind==="blocked",r=new Error(s?`Safety screening blocked this pipeline step for ${lc(i)}.`:"Safety screening could not be completed. Please try again.");return r.name="ModelArmorError",r.code=s?"MODEL_ARMOR_BLOCKED":"MODEL_ARMOR_UNAVAILABLE",r.isModelArmor=!0,r.pipelineStep=e,r.userTitle=s?"Request blocked for safety":"Safety check unavailable",r.userMessage=s?`The safety check detected ${lc(i)}. Edit your request to remove or rephrase the flagged content, then run the pipeline again.`:"The safety service did not finish all of its checks. Please wait a moment and run the pipeline again.",r.retryExplanation=s?"Trying another model would not change this safety decision.":"A fallback model was not attempted because safety screening must complete first.",r.matchedFilters=n.matchedFilters,r}function gg(t){return String(t||"").replace(/\/\*[\s\S]*?\*\//g,"").replace(/\/\/[^\n]*/g,"")}function cc(t){const e=/^(import|export|part|library|class|enum|extension|typedef|mixin|abstract|const|final|var|late)\b/,n=[];for(const i of gg(t).split(` -`)){if(!/^[A-Za-z_$]/.test(i)||e.test(i))continue;const s=i.match(/^[\w$<>,?\s[\]]+?\s([a-zA-Z_$][\w$]*)\s*\(/);s&&n.push(s[1])}return n}function pa(t,e){const n=t.replace(/\.dart$/,"");if(e==="W")return n.replace(/(^|_)(\w)/g,(i,s,r)=>r.toUpperCase());if(e==="A"){const i=n.replace(/(^|_)(\w)/g,(s,r,o)=>o.toUpperCase());return i.charAt(0).toLowerCase()+i.slice(1)}return e==="F"?"CustomFunctions":e==="C"?t.endsWith(".dart")?t:`${t}.dart`:n}async function uc(t){const e=new TextEncoder().encode(String(t||"")),n=await globalThis.crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(n),i=>i.toString(16).padStart(2,"0")).join("")}async function mg(t,e=new Map){const n={},i=new Set;for(const[o,a]of t.entries()){if(a.type==="D"||a.type==="O")continue;const l=pa(o,a.type),u={old_identifier_name:l,new_identifier_name:l,type:a.type,is_deleted:!1,current_checksum:await uc(a.content)},c=e.get(a.path);if(c!==void 0&&(u.original_checksum=await uc(c)),n[o]=u,a.type==="F"){const d=cc(a.content);(d.length>0?d:[a.functionName].filter(Boolean)).forEach(p=>i.add(p))}}const s=new Set(cc(e.get("lib/flutter_flow/custom_functions.dart")||"")),r={functions_to_rename:[],functions_to_delete:[],functions_to_add:Array.from(i).filter(o=>!s.has(o))};return{fileMapContents:JSON.stringify(n),functionsMapContents:JSON.stringify(r)}}const vg=new Set(["CustomWidget","CustomAction","CustomFunction","CustomClass","CodeFile"]),dc={CustomWidget:"custom_code/widgets/",CustomAction:"custom_code/actions/",CustomFunction:"flutter_flow/custom_functions.dart",CustomClass:"custom_code/",CodeFile:"custom_code/"},_g=new Set(["void","dynamic","String","int","double","num","bool","Color","DateTime","DateTimeRange","LatLng","FFPlace","FFUploadedFile","DocumentReference","List"]),yg=["Struct","Record"],wg=[{id:"required-public-param",severity:"error",message:"CustomWidget constructor uses `required` on a parameter FlutterFlow can leave unset. FlutterFlow omits unset Define Parameters fields from the constructor call, so the widget will not compile when placed. Make the parameter optional and nullable (`this.value` with `final double? value`), or give it a constructor default (`this.value = 0.0`).",detect:t=>Br(t).some(e=>/\brequired\s+this\.\w+/.test(e)),pos:"class W extends StatefulWidget { const W({required this.value}); final double value; }",neg:`class _P { const _P({required this.t}); final double t; } -class W extends StatefulWidget { const W({this.value}); final double? value; }`},{id:"non-nullable-public-field",severity:"error",message:"CustomWidget declares a non-nullable field with no constructor default. FlutterFlow omits unset Define Parameters fields, so the emitted call cannot supply it. Make the field nullable (`final double? value`) or give the parameter a default (`this.value = 0.0`).",detect:t=>Br(t).some(e=>{const n=/^\s*final\s+(?:double|int|String|bool|Color|num)\s+(\w+)\s*;/gm;let i;for(;(i=n.exec(e))!==null;){const s=i[1];if(!(new RegExp(`this\\.${s}\\s*=(?!=)`).test(e)||new RegExp(`[:,]\\s*${s}\\s*=(?!=)`).test(e)))return!0}return!1}),pos:`class W extends StatefulWidget { - const W({required this.value}); - final double value; -}`,neg:`class _P { - const _P({required this.t}); - final double t; -} -class W extends StatefulWidget { - const W({this.value = 1.0}); - final double value; -}`},{id:"asset-without-anchor",severity:"warning",message:'CustomWidget calls Image.asset with a path arriving as a String parameter. An asset reaches the build only when a FlutterFlow widget NODE references it - a filename passed as a parameter does not count, so the image renders as a broken-image icon on device. "Download Unused Project Assets" does not fix it (FlutterFlow issues 522, 2271, 3799). Keep something in the UI referencing the file, or load it over the network instead.',detect:t=>/Image\.asset\s*\(/.test(t)&&/final\s+String\??\s+\w*[Pp]ath\b/.test(t),pos:`class W extends StatefulWidget { final String? imagePath; } -var x = Image.asset(widget.imagePath);`,neg:`class W extends StatefulWidget { final String? imagePath; } -var x = Image.network(widget.imagePath);`},{id:"unsupported-param-type",severity:"error",message:"CustomWidget exposes a Flutter data type FlutterFlow cannot express as a Define Parameter: TextStyle, BoxShadow, FontWeight, FontStyle, TextDirection, TextAlign, EdgeInsets, Offset, Alignment/AlignmentGeometry, Border, BorderRadius, BoxDecoration, BoxConstraints, BorderSide, Gradient, or ThemeData. FlutterFlow's supported data types (docs.flutterflow.io/resources/data-representation/data-types) are only int, double, bool, string, Color, Image, DateTime, Json, LatLng, and the FF objects, so this parameter cannot be configured in the editor and the widget will not place or compile. Expose primitives instead (color, fontSize as double?, fontWeight via a custom enum, doubles for spacing).",detect:t=>Br(t).some(e=>/final\s+(TextStyle|BoxShadow|FontWeight|FontStyle|TextDirection|TextAlign|EdgeInsets|Offset|Alignment(?:Geometry)?|Border(?:Radius|Side)?|BoxDecoration|BoxConstraints|Gradient|LinearGradient|RadialGradient|ThemeData)\??\s+\w+\s*;/.test(e)),pos:`class W extends StatefulWidget { - const W({this.textStyle}); - final TextStyle? textStyle; - @override _S createState() => _S(); -} -class _S extends State { @override Widget build(BuildContext c) => const SizedBox(); }`,neg:`class W extends StatefulWidget { - const W({this.width}); - final double? width; - @override _S createState() => _S(); -} -class _S extends State { @override Widget build(BuildContext c) => Padding(padding: const EdgeInsets.all(8), child: const SizedBox()); }`}];function nt(t,e,n){return{artifactId:t.id,artifactName:t.artifactName,artifactType:t.artifactType,severity:e,message:n}}function hi(t){let e="",n=0;for(;n"&&(n--,n===0))return{inner:t.slice(e+1,i),end:i+1};return null}function Eg(t,e){const n=new RegExp(`class\\s+${e}\\b[^{]*\\{`).exec(t);if(!n)return null;let i=0;for(let s=n.index+n[0].length-1;sSg(t).usable);function kg(t=""){const e=hi(t);return xg.filter(n=>n.detect(e)).map(({id:n,severity:i,message:s})=>({id:n,severity:i,message:s}))}function Ig(t){const e=[],n=t.matchAll(/\bFuture\b/g);for(const i of n){let s=i.index+6,r=null;const o=s;for(;so;if(t[s]==="<"){const u=bg(t,s);if(!u||(r=u.inner.replace(/\s+/g," ").trim(),s=u.end,!/\s/.test(t[s]||"")))continue;for(;shc(o.functionName)===i);if(s)return s;const r=o=>!o.functionName.startsWith("_");return n.find(r)||n[0]}function Hs(t=""){return Array.from(hi(t).matchAll(/\b(?:class|enum)\s+([A-Za-z_]\w*)/g),e=>e[1])}function Cg(t="",e=""){return fa(t,e)?.returnType||null}function pc(t){return String(t||"").replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2").toLowerCase()}function Ag(t,e){const n=Hs(e);if(n.length===0)return null;const s=String(t||"").split("/").pop().replace(/\.dart$/,"");if(n.some(l=>pc(l)===s)||n.length>1)return null;const[o]=n,a=`${pc(o)}.dart`;return`File name "${t}" does not match declared class "${o}". FlutterFlow accepts this, but naming the file "${a}" keeps the Code File recognisable in the editor.`}function ga(t){return String(t||"").replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,"")}function Fg(t,e,n=""){const i=fa(e,n)?.functionName;if(!i)return null;const s=String(t||"").split("/").pop(),r=pa(s,"A");if(r===i)return null;const o=`${ga(i)}.dart`;return`File name "${s}" does not match Action "${i}". FlutterFlow derives the action from the file name, so it looks for "${r}" and reports Action "${r}" declaration not found. Rename the file to "${o}" - FlutterFlow puts an underscore before every capital - or rename the function to "${r}".`}function Pg(t="",e=""){return fa(t,e)!==null}function $g(t,e=new Set){return(t?.match(/[A-Za-z_]\w*/g)||[]).filter(i=>_g.has(i)?!1:!yg.some(r=>i.endsWith(r))||e.has(i))}function Tg(t,{functionName:e="",declaredTypes:n=new Set}={}){const i=Cg(t,e),s=$g(i,n);if(s.length===0)return null;const[r]=s;let o;return n.has(r)?o=`uses Code File type "${r}", which FlutterFlow cannot process as an Action Return Value`:i===r?o="is not a FlutterFlow Action Return Value":o=`uses type "${r}", which is not a FlutterFlow Action Return Value`,`CustomAction return type "${i}" ${o}. Return JSON (Future) or an existing FlutterFlow Data Type (*Struct) instead.`}function Rg(t,e={}){const n=[],i=t.fileName||"",s=t.code||"";if(vg.has(t.artifactType)||n.push(nt(t,"error",`Unsupported artifact type "${t.artifactType}".`)),i.endsWith(".dart")||n.push(nt(t,"error","FlutterFlow custom code artifacts must use .dart files.")),!s.trim())return n.push(nt(t,"warning","Generated artifact has no Dart code yet.")),n;if(t.artifactType==="CustomWidget"){/class\s+\w+\s+extends\s+(StatelessWidget|StatefulWidget)/.test(s)||n.push(nt(t,"warning","CustomWidget code should declare a widget class extending StatelessWidget or StatefulWidget."));for(const r of kg(s))n.push(nt(t,r.severity,r.message))}if(t.artifactType==="CustomAction"&&!Pg(s,t.artifactName)&&n.push(nt(t,"warning","CustomAction code should expose an async Future function callable from FlutterFlow.")),t.artifactType==="CustomAction"){const r=e.declaredTypes||new Set(Hs(s)),o=Tg(s,{functionName:t.artifactName,declaredTypes:r});o&&n.push(nt(t,"error",o));const a=Fg(i,s,t.artifactName);a&&n.push(nt(t,"error",a))}if(t.artifactType==="CustomFunction"&&/class\s+\w+\s+extends\s+(StatelessWidget|StatefulWidget)/.test(s)&&n.push(nt(t,"warning","CustomFunction should be a callable function, not a widget class.")),t.artifactType==="CustomClass"||t.artifactType==="CodeFile"){const r=Ag(i,s);r&&n.push(nt(t,"info",r))}return n}function Ng(t){const e=Array.isArray(t?.artifacts)?t.artifacts:[],n=new Set(e.flatMap(r=>Hs(r.code||""))),i=e.flatMap(r=>Rg(r,{declaredTypes:n})),s=e.map(r=>({artifactId:r.id,fileName:r.fileName,pathHint:dc[r.artifactType]||dc.CodeFile}));return{valid:i.every(r=>r.severity!=="error"),findings:i,deployHints:s}}const fc="// DO NOT REMOVE OR MODIFY THE CODE ABOVE!";function gc(t){return(/^\s*import\s+['"]([^'"]+)['"]/.exec(t)||[])[1]||null}function Mg(t=""){const e=t.indexOf(fc);return e===-1?t:t.slice(e+fc.length).replace(/^\s*\n/,"")}const Lg=/^\s*import\s+['"][^'"]+['"]\s*;\s*(?:\/\/.*)?$/;function Og(t="",e=""){const n=Mg(t),i=new Set((e.match(/^\s*import .*$/gm)||[]).map(gc).filter(Boolean)),s=n.split(` -`).filter(r=>{const o=gc(r);return o===null||!i.has(o)?!0:!Lg.test(r)}).join(` -`).replace(/^\s*\/\/ Automatic FlutterFlow imports\s*$/m,"").replace(/^\s*\n+/,"");return e+s}const Bg=new Set(["flutter","flutter_test","flutter_driver","flutter_localizations"]);function Nd(t){let e="",n=0;for(;n{const i=n.name||n.package;if(!i||i==="flutter")return e;const s=n.versionRequired||n.required;return e[i]=s&&n.version||"",e},{})}function Wg(t){const e=new Map,n=new Map,i=[];for(const s of t)e.has(s.fileName)?i.push(`Duplicate deploy file name "${s.fileName}" for artifacts "${e.get(s.fileName)}" and "${s.artifactId}".`):e.set(s.fileName,s.artifactId),n.has(s.path)?i.push(`Duplicate deploy path "${s.path}" for artifacts "${n.get(s.path)}" and "${s.artifactId}".`):n.set(s.path,s.artifactId);return i}function zg(t,e={}){const n=Array.isArray(t?.artifacts)?t.artifacts:[],s=(e.selectedArtifactIds||t?.deployOrder||n.map(p=>p.id)).map(p=>n.find(f=>f.id===p)).filter(Boolean),r=[...t?.warnings||[]];let o=[];s.forEach(p=>{const f=Hg(p),g=p.fixedCode||p.code||"",m=p.codeType||jg[p.artifactType]||Ne.OTHER;g.trim()||r.push(`${p.artifactName||p.id} has no generated code.`),o.push({artifactId:p.id,artifactName:p.artifactName,artifactType:p.artifactType,fileName:f,content:g,type:m,path:p.deployPath||Ug(f,m),deployPath:p.deployPath||"",deployMode:"customCodeSync"})});const a="lib/flutter_flow/custom_functions.dart",l=o.map((p,f)=>({entry:p,index:f})).filter(({entry:p})=>p.type===Ne.FUNCTION&&p.path===a);if(l.length>1){const p=l[0],f={...p.entry,artifactId:l.map(({entry:m})=>m.artifactId).join("+"),artifactName:p.entry.artifactName,content:l.map(({entry:m})=>`// ${m.artifactId} -${m.content}`).join(` - -`)},g=new Set(l.slice(1).map(({index:m})=>m));o=o.filter((m,v)=>!g.has(v)),o[p.index]=f}const u={...mc(t?.dependencies),...s.reduce((p,f)=>({...p,...mc(f.dependencies)}),{})},c={};s.forEach(p=>{ma(p.code||"").forEach(f=>{f in u||(c[f]="")})});const d={...c,...u},h=Wg(o);return{bundleId:t?.id||"bundle-current",title:t?.title||"Generated artifact bundle",fileEntries:o,dependencies:d,relationships:t?.relationships||[],warnings:r,errors:h}}function qg(t){return String(t||"").match(/\bclass\s+([A-Z][A-Za-z0-9_]*)\b/)?.[1]}function Vg(t){return String(t||"").split("/").pop().replace(/\.dart$/,"").split(/[^A-Za-z0-9]+/).filter(Boolean).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join("")}function Gg(t,e){const i=[Vg(t),qg(e.content),e.artifactName].find(s=>/^[A-Z][A-Za-z0-9_]*$/.test(String(s||"")));if(!i)throw new Error(`Cannot derive a FlutterFlow custom class name for ${t}.`);return i}function Kg(t,e=new Map){const n=[];for(const[i,s]of t.entries())s.type!=="C"||e.has(s.path)||n.push({artifactId:s.artifactId||i,className:Gg(i,s),content:s.content,fileName:i,path:s.path});return n}function Jg(t,e){const n=new Set(e.map(i=>i.path));return new Map(Array.from(t.entries()).filter(([,i])=>!n.has(i.path)))}const vc={pass:0,warning:1,fail:2},Yg=["manualActions"];function Be(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function _t(...t){for(const e of t){if(typeof e=="string"&&e.trim())return e.trim();if(Array.isArray(e)&&e.length>0){const n=e.filter(i=>typeof i=="string").join(` -`);if(n)return n}}return""}function st(t){return t==null?[]:Array.isArray(t)?t:[t]}function Zg(t){const e=Be(t).value??t;if(e==null||typeof e=="string"&&e.trim()==="")return null;const n=Number(e);if(Number.isFinite(n))return n;const i=String(t||"").match(/\bscore\b[^\d]{0,12}(\d{1,3})(?:\s*\/\s*100)?/i);return i?Number(i[1]):null}function We(t){return String(t||"").trim().replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function va(t){const e=String(t||"").toLowerCase();return/(fail|error|critical|block|reject|invalid)/.test(e)?"fail":/(warn|attention|manual|partial|incomplete|concern)/.test(e)?"warning":/(pass|success|ready|approve|valid|clean|info|notice)/.test(e)?"pass":null}function $o(...t){return t.filter(Boolean).reduce((e,n)=>vc[n]>vc[e]?n:e,"pass")}function Md(t,e="warning",n="review"){if(typeof t=="string")return{severity:e,message:t,suggestion:"",source:n};const i=Be(t),s=_t(i.message,i.title,i.issue,i.description,i.summary);return s?{severity:va(i.severity||i.status||i.level)||e,message:s,suggestion:_t(i.suggestion,i.fix,i.recommendation,i.action),source:i.source||n}:null}function To(t,e="review"){const n=Be(t);return[["findings","warning"],["issues","warning"],["criticalIssues","fail"],["errors","fail"],["warnings","warning"],["recommendations","warning"],["requiredFixes","fail"],["suggestions","warning"]].flatMap(([s,r])=>st(n[s]).map(o=>Md(o,r,e)).filter(Boolean))}function Xg(t,e,n=null){if(typeof t=="string")return{id:`${n||"bundle"}-manual-${e+1}`,title:t,detail:"",location:"",timing:"unspecified",artifactId:n,source:"Code Review"};const i=Be(t),s=_t(i.title,i.action,i.step,i.message,i.name,i.description);return s?{id:i.id||`${n||"bundle"}-manual-${e+1}`,title:s,detail:_t(i.detail,i.instructions,i.description),location:_t(i.location,i.flutterFlowPath,i.path),timing:_t(i.timing,i.phase)||"unspecified",artifactId:n,source:_t(i.source)||"Code Review"}:null}function Ro(t,e=null){const n=Be(t);return Yg.flatMap(i=>st(n[i])).map((i,s)=>Xg(i,s,e)).filter(Boolean)}function Qg(t){let e=typeof t=="string"?Fo(t):t;if(!e&&typeof t=="string")return{rawText:t,root:{}};const n=Be(e);typeof n.content=="string"&&(e=Fo(n.content)||e);const i=Be(e),s=Be(i.reviewResult||i.codeReview||i.result);return{rawText:"",root:Object.keys(s).length?s:i}}function em(t,e){const n=[e.id,e.fileName,e.artifactName].map(We);return t.find(i=>{const s=Be(i);return[s.id,s.fileName,s.artifactName,s.name].map(We).some(r=>r&&n.includes(r))})||null}function tm(t,e){return st(t?.metadata?.compatibility?.deployHints).find(s=>We(s?.artifactId)===We(e.id)||We(s?.fileName)===We(e.fileName))?.pathHint||""}function nm(t,e){return st(t?.relationships).filter(n=>We(n?.from)===We(e.id)||We(n?.to)===We(e.id))}function im(t,e){return st(t?.metadata?.compatibility?.findings).filter(n=>!n?.artifactId||We(n.artifactId)===We(e.id)).map(n=>Md(n,"warning","Compatibility check")).filter(Boolean)}function sm(t,e,n,i){const s=em(e,n),r=Be(s?.review||s||n.review),o=Object.keys(r).length>0,a=[...To(r),...im(t,n)],l=Ro(r,n.id),u=va(r.status||r.verdict||r.outcome||r.result),c=a.length?$o(...a.map(h=>h.severity)):null,d=$o(u,c,o?null:"warning");return{...n,index:i,status:d,statusReason:o?_t(r.summary,r.overview,r.assessment,r.conclusion)||(a.length?`${a.length} review finding${a.length===1?"":"s"}`:"No file-level findings"):"No file-level verdict was returned",reviewComplete:o,findings:a,manualSteps:l,fixedSource:typeof r.fixedSource=="string"&&r.fixedSource.trim()?r.fixedSource.trim():null,pathHint:tm(t,n),relationships:nm(t,n)}}function rm({status:t,score:e,artifactPresentations:n,manualSteps:i}){const s=n.length;if(s===0&&i.length===0)return e==null?"Code review returned no overall summary and no score.":`Reviewed bundle with score ${e}/100.`;const r=n.reduce((a,l)=>(a[l.status]+=1,a),{pass:0,warning:0,fail:0}),o=[];return t&&o.push(`Overall verdict: ${t}.`),s&&o.push(`${s} artifact${s===1?"":"s"}: ${r.pass} pass, ${r.warning} warn, ${r.fail} fail.`),i.length&&o.push(`Do before deploy: ${i.map(a=>a.title).join("; ")}.`),e==null&&o.push("No numeric score (0-100) was returned."),o.join(" ")}function om({bundle:t,reviewResult:e}){const n=Be(t),i=st(n.artifacts),{root:s,rawText:r}=Qg(e),o=[s.bundleReview,s.overallReview,s.overall,s.bundleSummary,s.summaryReview,s.review].map(Be).find(w=>Object.keys(w).length)||{},a=st(s.artifacts||s.files||s.reviews),l=i.map((w,I)=>sm(n,a,w,I)),u=To(s),d=[...To(o),...u],h=[...Ro(o),...Ro(s),...l.flatMap(w=>w.manualSteps)].filter((w,I,A)=>A.findIndex(F=>F.title===w.title&&F.artifactId===w.artifactId)===I),p=va(o.status||o.verdict||o.overallStatus||s.status||s.verdict||s.overallStatus||s.outcome),f=$o(p,...d.map(w=>w.severity),...l.map(w=>w.status)),g=o.score??s.score??s.overallScore??r,m=Zg(g),v=_t(o.headline,o.summary,o.executiveSummary,o.overview,o.assessment,o.conclusion,s.overallSummary,s.headline,s.summary,s.executiveSummary,s.overview,s.assessment,s.conclusion,r)||rm({status:f,score:m,artifactPresentations:l,manualSteps:h}),E=l.reduce((w,I)=>(w[I.status]+=1,w),{pass:0,warning:0,fail:0});return{title:n.title||"Generated artifact bundle",description:n.description||"",status:f,score:m,summary:v,findings:d,manualSteps:h,artifacts:l,counts:E,reviewCoverage:{reviewed:l.filter(w=>w.reviewComplete).length,total:l.length},deployOrder:st(n.deployOrder),relationships:st(n.relationships),warnings:st(n.warnings),compatibility:Be(n.metadata?.compatibility)}}const am=/^\uFEFF/;function Hn(t){let e=0,n=t.length;for(;ee&&!t[n-1].trim();)n--;return t.slice(e,n).join(` -`)}function lm(t){const e=String(t??"").replace(am,"");if(!e.trim())return"";const n=e.split(` -`),i=c=>{const d=c.trim();return/^`{3,}[A-Za-z0-9+#_.-]*$/.test(d)?c.length-c.trimStart().length:-1};let s=0,r=-1;const o=[];{let c=0;for(let d=0;d=0&&(s++,r<0&&(r=d),o.push(c+h)),c+=n[d].length+1}}if(s===0)return Hn(n);{const c=No(e);if(!c.error&&o.every(h=>yc(h,c.commentAndStringRanges)))return Hn(n)}if(s===1){const c=Hn(n.slice(0,r)),d=Hn(n.slice(r+1));return d.length>=c.length?d:c}const a=[];let l=null;for(let c=0;cc.length>0);return u.length===0?"":u.join(` - -`)}function cm(t){return String(t??"").replace(/\/\*[\s\S]*?\*\//g," ").replace(/\/\/[^\n]*/g,"").replace(/'''[\s\S]*?'''/g,'""').replace(/"""[\s\S]*?"""/g,'""').replace(/'(?:\\.|[^'\\\n])*'/g,'""').replace(/"(?:\\.|[^"\\\n])*"/g,'""')}function Ld(t){const e=cm(t);return Array.from(e.matchAll(/class\s+([A-Z]\w*)\s+extends\s+[A-Za-z_]\w*Widget\b/g),n=>n[1])}function Od(t){return`${ga(t)}.dart`}function um(t){return pa(t,"W")}const _c={"(":")","[":"]","{":"}"},dm={")":"(","]":"[","}":"{"},hm=/[A-Za-z0-9_]/;function No(t){const e=[{kind:"code",opener:null,openedLine:0}],n=[];let i=1,s=0;const r=(c,d)=>{(c===` -`||c==="\r"&&d!==` -`)&&i++};let o=null;const a=()=>{for(const c of e)(c.kind==="string"||c.kind==="block-comment"||c.kind==="line-comment")&&n.push({start:c.startIndex,end:t.length})};for(;s0?t[s-1]:"",f=s>1?t[s-2]:"",g=(p==="r"||p==="R")&&!hm.test(f);e.push({kind:"string",quote:c,triple:h,raw:g,startIndex:s,openedLine:i}),s+=h?3:1;continue}if(_c[c]){e.push({kind:"code",opener:c,openedLine:i}),s++;continue}if(dm[c]){if(d.interpolation&&c==="}"){e.pop(),s++;continue}if(d.opener&&_c[d.opener]===c){e.pop(),s++;continue}return d.opener?(a(),{error:o??`line ${i}: "${c}" closes nothing - "${d.opener}" opened on line ${d.openedLine} is still open`,commentAndStringRanges:n}):(a(),{error:o??`line ${i}: unexpected "${c}" with no matching opener`,commentAndStringRanges:n})}r(c,t[s+1]),s++}a();let l=e.length-1;for(;l>0&&e[l].kind==="line-comment";)l--;let u=o;if(!u){const c=e[l];if(!(c.kind==="code"&&!c.opener&&!c.interpolation))if(c.kind==="string")u=`unclosed ${c.triple?"triple-quoted ":""}string starting on line ${c.openedLine} was never closed`;else if(c.kind==="block-comment")u=`unterminated /* comment starting on line ${c.openedLine}`;else if(c.interpolation){const d=e.findLast(p=>p.opener);u=`unclosed "\${" expression${d?` opened on line ${d.openedLine}`:""} was never closed`}else u=`"${c.opener}" opened on line ${c.openedLine} is never closed`}return{error:u,commentAndStringRanges:n}}function pm(t){return No(String(t??"")).error}function yc(t,e){return e.some(({start:n,end:i})=>t>=n&&ttypeof n=="string"?n:n?.errorMessage).filter(Boolean);return e.length>0?e.join("; "):JSON.stringify(t)}return t&&typeof t=="object"?t.errorMessage||JSON.stringify(t):String(t??"")}const fm=["gmail.com","googlemail.com","outlook.com","hotmail.com","live.com","msn.com"],gm="MAGIC_LINK_SENT",mm="PLUS_ALIAS_REJECTED",vm="Please enter your primary email address. Plus aliases (such as {email}) are not allowed for {domain} accounts.",Ws={allowlistedDomains:fm,successCode:gm,validationCode:mm,messageTemplate:vm},_m=new Set(Ws.allowlistedDomains),ym=Ws.successCode,Ki=Ws.validationCode;function zs(t){return typeof t=="string"?t.trim():""}function wm(t){const e=zs(t),n=e.lastIndexOf("@");if(n<=0||n===e.length-1)return!1;const i=e.slice(0,n),s=e.slice(n+1).toLowerCase();return _m.has(s)?i.includes("+"):!1}function bm(t,e){return Ws.messageTemplate.replaceAll("{email}",t).replaceAll("{domain}",e)}function Dd(t){if(!wm(t))return null;const e=zs(t),n=e.lastIndexOf("@"),i=e.slice(n+1).toLowerCase();return bm(e,i)}function Em(t,e){return t?.code===Ki?t.message||Dd(e)||"Please enter your primary email address.":t?.code===ym||!t?.code?`Check your email — we sent a link to ${zs(e)}`:t.message||"Something went wrong. Please try again."}const Sm=/^dependencies\s*:\s*(?:#.*)?$/,xm=/^(?:"([^"]+)"|'([^']+)'|([A-Za-z_][A-Za-z0-9_-]*))\s*:/;function qs(t){const e=t.match(xm);return e?e[1]??e[2]??e[3]:null}function _i(t){const e=t.trim();return e===""||e.startsWith("#")}function Fn(t){const e=t.match(/^(\s*)/);return e?e[1].length:0}function _a(t,e){const n=t.findIndex(r=>e.test(r));if(n===-1)return null;let i=n,s=null;for(let r=n+1;r=0.0.0"}`}function Am(t,e={}){const n=String(t||""),i=Object.entries(e).filter(([u])=>u&&u!=="flutter");if(i.length===0)return{yaml:n,added:[],alreadyPresent:[]};const s=n.split(` -`),r=new Set(Ud(n)),o=[],a=[];for(const[u,c]of i)r.has(u)?a.push(u):(o.push([u,c]),r.add(u));if(o.length===0)return{yaml:n,added:[],alreadyPresent:a};const l=ya(s);if(l){const u=o.map(([c,d])=>wc(l.childIndent,c,d));s.splice(l.endIndex,0,...u)}else s.length>0&&s[s.length-1].trim()!==""&&s.push(""),s.push("dependencies:"),o.forEach(([u,c])=>{s.push(wc(" ",u,c))});return{yaml:s.join(` -`),added:o.map(([u])=>u),alreadyPresent:a}}function Fm(t,e={}){const n=String(t||""),i=Object.entries(e).filter(([l])=>l&&l!=="flutter");if(i.length===0)return{yaml:n,overridden:[],skipped:[]};const s=n.split(` -`),r=Gs(n),o=[],a=[];for(const[l,u]of i){const c=r.get(l);if(!c||!c.isScalar||!String(u||"").trim()){a.push(l);continue}const d=" ".repeat(Fn(s[c.lineIndex]));s[c.lineIndex]=`${d}${l}: ${Wd(String(u).trim())}${c.comment}`,o.push({name:l,from:c.constraint,to:u})}return{yaml:s.join(` -`),overridden:o,skipped:a}}function zd(t){const e=String(t||""),n=[];return e.trim()?(/^name:\s*\S+/m.test(e)||n.push("pubspec.yaml missing name field"),ya(e.split(` -`))||n.push("pubspec.yaml missing dependencies section"),Ud(e).includes("flutter")||n.push("pubspec.yaml missing Flutter SDK dependency"),{valid:n.length===0,errors:n}):(n.push("pubspec.yaml is empty"),{valid:!1,errors:n})}const Pm=">=3.0.0 <4.0.0";function Mo(t){const e=String(t||"").trim(),n=e[0];return n!=="'"&&n!=='"'||e[e.length-1]!==n?e:e.slice(1,-1).replaceAll(`${n}${n}`,n)}function $m(t=""){const e=Dg(t).filter(n=>!n.startsWith("dart:")&&!n.startsWith("package:"));return{selfContained:e.length===0,unresolvableImports:e}}function bc(t,e,n){const i=[];for(const[s,r]of t){if(r.isScalar){e[s]=Mo(r.constraint);continue}if(r.sourceKey==="sdk"){n.add(s);continue}if(r.sourceKey===null&&r.version){e[s]=Mo(r.version);continue}i.push(s)}return i}function Tm(t){const e=new Set,n={},i={},s=bc(Gs(t),n,e);s.push(...bc(Im(t,"dependency_overrides"),i,e));const r=new Set([...Object.keys(n),...e]),{sdk:o}=Hd(t);return{sdkConstraint:Mo(o)||Pm,dependencies:n,overrides:i,sdkPackages:[...e].sort(),availablePackages:r,unrepresentable:s}}function Rm(t,e,n){return e.length>0?`${t} imports ${e.join(", ")}, which FlutterFlow only generates once the app is built, so it could not be compiled before the deploy.`:`${t} imports ${n.join(", ")}, which your project's pubspec.yaml does not declare with a version constraint, so it could not be compiled before the deploy.`}function Nm(t,e){const{sdkConstraint:n,dependencies:i,overrides:s,sdkPackages:r,availablePackages:o,unrepresentable:a}=Tm(e),l={sdkConstraint:n,dependencies:i,overrides:s,sdkPackages:r},u=[],c=[];for(const d of t){const{className:h,content:p}=d,f=ma(p);if(a.length>0&&f.length>0){const v=f.filter(E=>a.includes(E));c.push({className:h,reason:v.length>0?`${h} was not compiled before deploying: it imports ${v.join(", ")}, which your project declares from a source that cannot be reproduced outside it, so package resolution could not be matched exactly.`:`${h} was not compiled before deploying: your project declares ${a.join(", ")} from a source that cannot be reproduced outside it, so the package graph ${h} would compile against could not be matched exactly.`});continue}const{unresolvableImports:g}=$m(p),m=f.filter(v=>!o.has(v));if(g.length>0||m.length>0){c.push({className:h,reason:Rm(h,g,m)});continue}u.push({fileName:`${ga(h)}.dart`,content:p})}return{manifest:l,sources:u,skipped:c}}function Ec(t,e){const n=`${t}${e}`.split(` -`),i=n.pop()??"",s=[];for(const r of n){const o=qd(r);o&&s.push(o)}return{events:s,buffer:i}}function Mm(t){const e=qd(t);return e?[e]:[]}function qd(t){const e=t.trim();if(!e)return null;try{const n=JSON.parse(e);return n&&typeof n=="object"&&!Array.isArray(n)?n:null}catch{return null}}async function Lm(t,e={}){const{onPhase:n,onLog:i}=e;let s=null,r="";const o=a=>{if(a.event==="phase"){a.message&&n&&n(a.message);return}if(a.event==="log"){a.message&&i&&i(a.message);return}s=a};if(t.body?.getReader){const a=t.body.getReader(),l=new TextDecoder;for(;;){const{done:u,value:c}=await a.read();if(u)break;const d=Ec(r,l.decode(c,{stream:!0}));r=d.buffer,d.events.forEach(o)}}else{const a=Ec("",await t.text());r=a.buffer,a.events.forEach(o)}return Mm(r).forEach(o),s?{...s,success:s.success===!0||s.success===void 0&&t.ok}:{success:!1,error:t.ok?"The FlutterFlow deploy runner closed the connection before it finished.":`FlutterFlow custom class provisioning failed (HTTP ${t.status}).`}}const Om=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;function St(t){const e=String(t||"").trim().match(Om);return e?{major:Number(e[1]),minor:Number(e[2]),patch:Number(e[3]),prerelease:e[4]?e[4].split("."):[]}:null}function Bm(t,e){if(t.length===0&&e.length===0)return 0;if(t.length===0)return 1;if(e.length===0)return-1;for(let n=0;n0)}function jm(t){const e=St(t);return e?e.major>0?`${e.major+1}.0.0`:`0.${e.minor+1}.0`:null}function wa(t){let e=String(t??"").trim();if((e.startsWith("'")||e.startsWith('"'))&&(e=e.slice(1,-1).trim()),e===""||e==="any"||e==="*")return{min:null,minInclusive:!1,max:null,maxInclusive:!1};if(e.startsWith("^")){const o=e.slice(1).trim();return St(o)?{min:o,minInclusive:!0,max:jm(o),maxInclusive:!1}:null}if(St(e))return{min:e,minInclusive:!0,max:e,maxInclusive:!0};const n={min:null,minInclusive:!1,max:null,maxInclusive:!1},i=/(>=|<=|>|<)\s*([0-9][0-9A-Za-z.+-]*)/g;let s=!1,r;for(;(r=i.exec(e))!==null;){const[,o,a]=r;if(!St(a))return null;s=!0,o===">="||o===">"?(n.min=a,n.minInclusive=o===">="):(n.max=a,n.maxInclusive=o==="<=")}return s?n:null}function Sc(t,e){const n=wa(t);if(!n||!St(e))return!1;if(n.min!==null){const i=ks(e,n.min);if(i<0||i===0&&!n.minInclusive)return!1}if(n.max!==null){const i=ks(e,n.max);if(i>0||i===0&&!n.maxInclusive)return!1}return!0}function Um(t,e){const n=wa(t);if(!n||!St(e))return!1;if(n.max===null)return!0;const i=ks(n.max,e);return i>0?!0:i===0&&n.maxInclusive}function ln(t){const e=wa(t);return e?e.min:null}const Hm="https://pub.dev/api/packages/",Wm=8e3;function zm(t,e={}){const{dartSdkFloor:n=null,flutterSdkFloor:i=null}=e,s=Array.isArray(t?.versions)?t.versions:[];let r=null;for(const o of s){const a=o?.version;if(!a||o.retracted||Dm(a))continue;const l=o.pubspec?.environment||{};n&&l.sdk&&!Sc(l.sdk,n)||i&&l.flutter&&!Sc(l.flutter,i)||(!r||ks(a,r)>0)&&(r=a)}return r?{version:r,constraint:`^${r}`}:null}async function qm(t,e={}){const{dartSdkFloor:n=null,flutterSdkFloor:i=null,fetchImpl:s=fetch}=e;let r;try{const a=await s(`${Hm}${encodeURIComponent(t)}`,{signal:AbortSignal.timeout(Wm)});if(!a.ok)return{name:t,constraint:null,version:null,error:a.status===404?`"${t}" was not found on pub.dev`:`pub.dev returned ${a.status} for "${t}"`};r=await a.json()}catch(a){return{name:t,constraint:null,version:null,error:`could not reach pub.dev for "${t}" (${a.message})`}}const o=zm(r,{dartSdkFloor:n,flutterSdkFloor:i});return o?{name:t,...o,error:null}:{name:t,constraint:null,version:null,error:n?`no published "${t}" release supports Dart ${n}`:`no published "${t}" release could be read`}}async function Vm(t,e={}){const n=await Promise.all(t.map(i=>qm(i,e)));return new Map(n.map(({name:i,...s})=>[i,s]))}async function Gm(t,e={},n={}){const{resolveVersions:i=Vm}=n,s=Object.entries(e).filter(([c])=>c&&c!=="flutter"),r=Hd(t),o={dartSdkFloor:ln(r.sdk),flutterSdkFloor:ln(r.flutter)},a={additions:{},overrides:{},kept:[],warnings:[],sdk:o};if(s.length===0)return a;const l=Gs(t),u=[];for(const[c,d]of s){const h=l.get(c);if(!h){u.push(c);continue}const p=ln(d);if(!p){a.kept.push({name:c,constraint:h.constraint});continue}if(!h.isScalar){a.warnings.push(`"${c}" is declared in your project from a git, path, or SDK source, but the generated code needs at least ${p}. Left as-is — update it yourself if the build fails.`),a.kept.push({name:c,constraint:h.constraint});continue}if(Um(h.constraint,p)){a.kept.push({name:c,constraint:h.constraint});continue}a.overrides[c]=`^${p}`,a.warnings.push(`"${c}" was pinned to ${h.constraint} in your project, which cannot resolve the ${p} the generated code needs. Raising it to ^${p} — this changes a dependency the rest of your app also uses.`)}if(u.length>0){const c=await i(u,o);for(const d of u){const h=c.get(d);if(h?.constraint){a.additions[d]=h.constraint;continue}const p=e[d]||"";if(ln(p)){a.additions[d]=`^${ln(p)}`,a.warnings.push(`Could not confirm "${d}" version on pub.dev (${h?.error||"lookup failed"}). Using ^${ln(p)} from the AI's recommendation — verify this is current.`);continue}a.additions[d]=">=0.0.0",a.warnings.push(`Could not determine a version for "${d}" (${h?.error||"lookup failed"}) and the AI supplied none. Added with a wide-open >=0.0.0 constraint — pin a concrete version in FlutterFlow before deploying.`)}}return a}const Km={"&":"&","<":"<",">":">",'"':""","'":"'"};function xt(t){return String(t??"").replace(/[&<>"']/g,e=>Km[e])}function j(t){return t?xt(t).replace(/\n/g,"
    "):""}function Ft(t){return xt(t).replace(/\r?\n/g," ")}function Jm(t,e={}){const n=t?.pipelineStep;if(n!=null&&e[n]!=null)return e[n];const i=t?.message||"";return i.includes("Code Generator")?2:i.includes("Code Review")?3:1}function Ym(t){const e={"Integration Audit Report":"📋","Critical Issues":"❌",Warnings:"⚠️",Recommendations:"✅","Overall Score":"📊"};for(const[n,i]of Object.entries(e))if(t.toLowerCase().includes(n.toLowerCase()))return i;return"📄"}function Zm(t){const e={critical:"❌",warning:"⚠️",recommendation:"✅",score:"📊",issue:"🔍",fix:"🔧"};for(const[n,i]of Object.entries(e))if(t.toLowerCase().includes(n.toLowerCase()))return i;return"📝"}function Xm(t){return t.includes("class ")&&t.includes("extends ")||t.includes("StatelessWidget")||t.includes("StatefulWidget")||t.includes("import 'package:flutter/")?"dart":t.includes("def ")||t.includes("import ")||t.includes("print(")?"python":t.includes("function ")||t.includes("const ")||t.includes("console.")?"javascript":"dart"}function xn(t){if(!t)return"";if(typeof t!="string")return String(t);const e=/```(?:\w+)?\n?([\s\S]*?)```/,n=t.match(e);return n?n[1].trim():t.trim()}function xc(t){return t=xt(t),t=t.replace(/\*\*(.*?)\*\*/g,'$1'),t=t.replace(/\*(.*?)\*/g,'$1'),t=t.replace(/`(.*?)`/g,'$1'),t=t.replace(/\b(FAIL|ERROR|CRITICAL)\b/g,'$1'),t=t.replace(/\b(WARN|WARNING)\b/g,'$1'),t=t.replace(/\b(PASS|SUCCESS|OK)\b/g,'$1'),t}function Vd(t,e="dart",n=globalThis.hljs){if(!t)return"";const i=xn(t);try{return n.highlight(i,{language:e}).value}catch(s){console.warn("Syntax highlighting failed:",s);try{return n.highlight(i,{language:"json"}).value}catch{return xt(i)}}}function Ks(t,e={}){const{highlighter:n=globalThis.hljs}=e;let i='
    ';const s=String(t??"").split(` -`);let r=!1,o="";for(const a of s){if(a.startsWith("```")){if(r){const l=Xm(o),u=Vd(o.trim(),l,n);i+=`
    -
    ${u}
    -
    `,o="",r=!1}else r=!0;continue}if(r){o+=a+` -`;continue}if(a.startsWith("# ")){const l=a.substring(2).trim();i+=`
    -

    - ${Ym(l)} - ${xt(l)} -

    -
    `;continue}if(a.startsWith("## ")){const l=a.substring(3).trim();i+=`
    -

    - ${Zm(l)} - ${xt(l)} -

    -
    `;continue}if(/^[-*+]\s+/.test(a)||/^\d+\.\s+/.test(a)){const l=a.replace(/^([-*+]|\d+\.)\s+/,"").trim();i+=`
    - • - ${xc(l)} -
    `;continue}a.trim()!==""&&(i+=`

    ${xc(a)}

    `)}return i+="
    ",` -
    -
    -
    - Live Audit Report -
    - ${i} -
    - `}const Qm=[[/gradient stroke\s*$/i," and an animated percentage label"],[/gauge\s*$/i," with a gradient stroke and animated fill"],[/rating\s*(bar|widget)?\s*$/i," with half-star support and haptic feedback"],[/list\s*$/i," with swipe-to-delete and an undo snackbar"],[/pad\s*$/i," that exports a transparent PNG"],[/carousel\s*$/i," with parallax cards and page indicators"],[/(button|cta)\s*$/i," with a loading spinner and success state"],[/(chart|graph)\s*$/i," that animates from a Firestore stream"],[/action\s*(that|to)?\s*$/i," uploads an image to Firebase Storage and returns the URL"],[/timer\s*$/i," with pause, resume and a completion callback"],[/map\s*$/i," with clustered markers and a custom info window"],[/^a\s+\w*$/i," widget that"],[/(picker|selector)\s*$/i," with search and multi-select"]],ev=220,tv=6;function kc(t,e){return!!(t&&t.trim())&&!e}function nv(t,e=""){if(typeof t!="string"||!t||t===e||t.trim().lengthi.test(t));return n?n[1]:null}function iv(){let t="",e="";return{get active(){return t},resolve(n){return t=nv(n,e)??"",t},dismiss(){t=""},accept(n){if(!t)return null;const i=n+t;return e=i,t="",i}}}function sv({onSubmit:t}){const e=document.getElementById("composer"),n=document.getElementById("pipeline-input"),i=document.getElementById("hero-send");if(!e||!n||!i||typeof t!="function")return;const s=e.querySelector(".ghost .typed"),r=e.querySelector(".ghost .suggest"),o=document.getElementById("tab-hint"),a=document.getElementById("suggest-status"),l=Array.from(document.querySelectorAll("#example-chips .chip")),u=window.matchMedia("(prefers-reduced-motion: reduce)"),c=iv();let d=!1,h=!1,p=null,f=null;function g(){i.disabled=!kc(n.value,h)}function m(){s&&(s.textContent=n.value)}function v(){r&&(r.textContent=""),m(),e.classList.remove("has-suggest"),o&&(o.hidden=!0,o.tabIndex=-1),a&&(a.textContent="")}function E(P){r&&(r.textContent=P),m(),e.classList.add("has-suggest"),o&&(o.hidden=!1,o.tabIndex=0,o.setAttribute("aria-label","Accept suggestion: "+P.trim())),a&&(a.textContent="Suggestion: "+P+". Press Tab to accept.")}function w(){c.dismiss(),v()}function I(){if(d||h)return;const P=c.resolve(n.value);P&&E(P)}function A(){clearTimeout(p),!d&&(p=setTimeout(I,ev))}function F(){const P=c.accept(n.value);return P===null?!1:(n.value=P,v(),g(),!0)}function D(P){h=P,e.classList.toggle("is-busy",P),i.classList.toggle("is-busy",P),i.setAttribute("aria-label",P?"Generating":"Generate"),g()}async function S(){if(kc(n.value,h)){w(),D(!0);try{await t()}finally{D(!1)}}}function $(){f&&(clearInterval(f),f=null),e.classList.remove("is-demo-typing")}function T(){l.forEach(P=>{P.classList.remove("is-active"),P.setAttribute("aria-pressed","false")})}function M(){try{n.focus({preventScroll:!0}),n.setSelectionRange(n.value.length,n.value.length)}catch{}}function N(P){const z=P.dataset.prompt||"";if($(),w(),l.forEach(U=>{const Q=U===P;U.classList.toggle("is-active",Q),U.setAttribute("aria-pressed",String(Q))}),u.matches||!z){n.value=z,m(),g(),M();return}n.value="",m(),g(),e.classList.add("is-demo-typing");let H=0;f=setInterval(()=>{H+=1,n.value=z.slice(0,H),m(),g(),H>=z.length&&($(),M())},22)}l.forEach(P=>{P.setAttribute("aria-pressed","false"),P.addEventListener("click",()=>N(P))}),n.addEventListener("keydown",P=>{$(),P.key==="Tab"&&!P.shiftKey&&c.active?(P.preventDefault(),F()):P.key==="Escape"?w():P.key==="Enter"&&!P.shiftKey&&!P.isComposing&&!d&&(P.preventDefault(),S())}),n.addEventListener("input",()=>{$(),T(),w(),g(),A()}),n.addEventListener("compositionstart",()=>{d=!0}),n.addEventListener("compositionend",()=>{d=!1,w(),g(),A()}),n.addEventListener("scroll",()=>{s&&s.parentNode&&(s.parentNode.scrollTop=n.scrollTop)}),o&&o.addEventListener("click",()=>{F(),n.focus({preventScroll:!0})}),i.addEventListener("click",S),n.addEventListener("pointerdown",()=>{$(),T()}),m(),g()}const rv="https://ccc-ffai-runner-y5cyj3473a-uw.a.run.app/deployCustomClasses";const Ze="https://4tgke4.buildship.run",Gd={professional:"price_1T2ldCKszA2slvDXatdeCpbI",power:"price_1T2le9KszA2slvDXR4mPvw7M"},Is="ccc_auth_session",Ic=new WeakSet;let V={email:null,sessionToken:null,isVerified:!1};function kn(t={}){return{tier:"free",status:"none",periodEnd:null,isLoading:!1,isResolved:!1,error:null,...t}}let pe=kn({isResolved:!0});const ov=`${Ze}/service/runpipeline`,av="bs_user_id",lv="bs_identity_token",cv=`${Ze}/authUserCheck`;let Ke={userId:null,token:null,status:null,resolved:!1};const Cs={free:2,professional:50,power:2e3},As="ccc_subscription",Cc=3,uv=new Set(["active","trialing","paid"]),pi="google/gemini-3.7-flash",Ji=["anthropic/claude-opus-5","openai/gpt-5.6-sol","z-ai/glm-5.2","moonshotai/kimi-k3","openrouter/auto-beta","openrouter/free","openrouter/deepseek/deepseek-v4-pro"],dv={"google/gemini-3.7-flash":"Gemini 3.7 Flash","anthropic/claude-opus-5":"Claude Opus 5","openai/gpt-5.6-sol":"GPT-5.6 Sol","z-ai/glm-5.2":"GLM 5.2","moonshotai/kimi-k3":"Kimi K3","openrouter/auto-beta":"OpenRouter: Auto Router","openrouter/free":"OpenRouter: Free Models","openrouter/deepseek/deepseek-v4-pro":"DeepSeek v4 Pro"};function Kt(t){return dv[t]||t}const hv=new Set(["google/gemini-3.7-flash","anthropic/claude-opus-5","openai/gpt-5.6-sol","z-ai/glm-5.2","moonshotai/kimi-k3","openrouter/auto-beta"]);function Kd(t){return hv.has(t)}const Lo=4,Dr=8*1024*1024,pv="https://4tgke4.buildship.run/service/runpipeline-image";let Tt=[];function fv(t){return new Promise(e=>{const n=new FileReader;n.onload=()=>e(n.result),n.onerror=()=>e(null),n.readAsDataURL(t)})}async function gv(t){const e=new FormData;return e.append("file",t),(await fetch(pv,{method:"POST",body:e})).json()}function mv(t){if(Array.isArray(t)){const e=t[0];if(e&&typeof e=="object")for(const n of Object.keys(e)){if(n==="item"||n==="index")continue;const i=e[n];if(i&&typeof i=="object"){if(typeof i.file=="string")return i.file;if(typeof i.url=="string")return i.url}if(typeof i=="string")return i}return""}return typeof t=="string"?t:t&&typeof t=="object"&&(t.url||t.fileUrl||t.file_url||t.downloadUrl||t.imageUrl||t.image_url||t.file)||""}async function vv(t){const e=Array.from(t.target.files||[]);if(!e.length)return;const n=e.filter(l=>l.size>Dr);n.length&&ue(`Skipped ${n.length} image(s) over the ${(Dr/1024/1024).toFixed(0)} MB limit.`,"warning");const i=e.filter(l=>l.size<=Dr);if(!i.length){t.target.value="";return}const s=Lo-Tt.length,o=i.slice(0,s).map(async l=>{const u=await fv(l);if(!u)return null;let c="";try{c=mv(await gv(l))}catch{c=""}return{dataUrl:u,name:l.name,url:c}}),a=(await Promise.all(o)).filter(Boolean);t.target.value="",!(a.length&&!Kd(document.getElementById("code-generator-model")?.value))&&(Tt.push(...a),i.length>s&&ue(`You can attach up to ${Lo} images.`,"info"),ba())}function _v(t){Tt.splice(t,1),ba()}function ba(){const t=document.getElementById("prompt-image-thumbnails"),e=document.getElementById("prompt-image-btn-label");t&&(t.innerHTML="",Tt.forEach((n,i)=>{const s=document.createElement("div");s.className="prompt-img-thumb",s.innerHTML=`Prompt image`,t.appendChild(s)}),e&&(e.textContent=Tt.length>=Lo?"Image limit reached":"Add images"))}function Jd(){const t=document.getElementById("prompt-image-upload");if(!t)return;const e=document.getElementById("code-generator-model"),n=Kd(e?.value);t.classList.toggle("hidden",!n),!n&&Tt.length&&(Tt=[],ba())}const Zt="ccc_usage",Yd="google/gemini-3.7-flash",Zd="google/gemini-3.7-flash",jr="google/gemini-3.7-flash",Oi={professional:11,power:49},Oo={en_US:"USD",en_GB:"GBP",en_AU:"AUD",en_NZ:"NZD",en_CA:"CAD",en_IN:"INR",en_SG:"SGD",en_HK:"HKD",en_PH:"PHP",en_ZA:"ZAR",en:"USD",de:"EUR",fr:"EUR",es:"EUR",it:"EUR",nl:"EUR",pt_PT:"EUR",pt_BR:"BRL",pt:"BRL",ja:"JPY",ko:"KRW",zh_CN:"CNY",zh_TW:"TWD",zh:"CNY",th:"THB",vi:"VND",id:"IDR",ms_MY:"MYR",ms:"MYR",sv:"SEK",nb:"NOK",da:"DKK",pl:"PLN",cs:"CZK",hu:"HUF",ro:"RON",tr:"TRY",ar:"AED",he:"ILS",ru:"RUB",uk:"UAH"},Yi={AUD:1,USD:.65,EUR:.6,GBP:.52,CAD:.88,NZD:1.08,JPY:97,KRW:870,INR:54,SGD:.87,HKD:5.08,BRL:3.18,CNY:4.7,TWD:20.5,THB:22.5,VND:16200,IDR:10200,MYR:2.88,SEK:6.8,NOK:6.95,DKK:4.48,PLN:2.6,CZK:15.2,HUF:238,RON:2.98,TRY:20.9,AED:2.39,ILS:2.38,PHP:36.4,ZAR:11.8,RUB:58,UAH:26.8,CHF:.57,MXN:11.1,ARS:580,CLP:610,COP:2700,PEN:2.44};let Zi={...Yi};async function yv(){const t=new AbortController,e=setTimeout(()=>t.abort(),5e3);try{const n=await fetch("https://open.er-api.com/v6/latest/AUD",{signal:t.signal});if(!n.ok)return;const i=await n.json();if(i.result!=="success"||!i.rates)return;const s=i.rates,r={AUD:1},o=new Set([...Object.keys(Yi),...Object.values(Bo),...Object.values(Oo)]);for(const a of o)a!=="AUD"&&(typeof s[a]=="number"&&s[a]>0?r[a]=s[a]:Yi[a]&&(r[a]=Yi[a]));Zi=r}catch{}finally{clearTimeout(e)}}const Bo={"America/Sao_Paulo":"BRL","America/Fortaleza":"BRL","America/Recife":"BRL","America/Bahia":"BRL","America/Belem":"BRL","America/Manaus":"BRL","America/Cuiaba":"BRL","America/Campo_Grande":"BRL","America/Araguaina":"BRL","America/Noronha":"BRL","America/Rio_Branco":"BRL","America/Porto_Velho":"BRL","America/Boa_Vista":"BRL","America/Maceio":"BRL","America/Santarem":"BRL","America/Eirunepe":"BRL","Europe/London":"GBP","Europe/Paris":"EUR","Europe/Berlin":"EUR","Europe/Madrid":"EUR","Europe/Rome":"EUR","Europe/Amsterdam":"EUR","Europe/Brussels":"EUR","Europe/Vienna":"EUR","Europe/Lisbon":"EUR","Europe/Dublin":"EUR","Europe/Helsinki":"EUR","Europe/Athens":"EUR","Europe/Bucharest":"RON","Europe/Budapest":"HUF","Europe/Warsaw":"PLN","Europe/Prague":"CZK","Europe/Copenhagen":"DKK","Europe/Stockholm":"SEK","Europe/Oslo":"NOK","Europe/Zurich":"CHF","Europe/Istanbul":"TRY","Europe/Moscow":"RUB","Europe/Kiev":"UAH","Europe/Kyiv":"UAH","Asia/Tokyo":"JPY","Asia/Seoul":"KRW","Asia/Shanghai":"CNY","Asia/Taipei":"TWD","Asia/Hong_Kong":"HKD","Asia/Singapore":"SGD","Asia/Kolkata":"INR","Asia/Calcutta":"INR","Asia/Bangkok":"THB","Asia/Ho_Chi_Minh":"VND","Asia/Jakarta":"IDR","Asia/Kuala_Lumpur":"MYR","Asia/Dubai":"AED","Asia/Jerusalem":"ILS","Asia/Tel_Aviv":"ILS","Asia/Manila":"PHP","Pacific/Auckland":"NZD","Australia/Sydney":"AUD","Australia/Melbourne":"AUD","Australia/Brisbane":"AUD","Australia/Perth":"AUD","Australia/Adelaide":"AUD","Australia/Hobart":"AUD","Australia/Darwin":"AUD","Australia/Lord_Howe":"AUD","America/Toronto":"CAD","America/Vancouver":"CAD","America/Edmonton":"CAD","America/Winnipeg":"CAD","America/Halifax":"CAD","America/St_Johns":"CAD","America/Regina":"CAD","America/New_York":"USD","America/Chicago":"USD","America/Denver":"USD","America/Los_Angeles":"USD","America/Phoenix":"USD","America/Anchorage":"USD","Pacific/Honolulu":"USD","America/Mexico_City":"MXN","America/Cancun":"MXN","America/Tijuana":"MXN","America/Argentina/Buenos_Aires":"ARS","America/Santiago":"CLP","America/Bogota":"COP","America/Lima":"PEN","Africa/Johannesburg":"ZAR"};function Xd(){try{const r=Intl.DateTimeFormat().resolvedOptions().timeZone;if(r&&Bo[r])return Bo[r]}catch{}const e=(navigator.language||"en-US").replace("-","_"),n=Oo[e];if(n)return n;const i=e.split("_")[0],s=Oo[i];return s||"USD"}function Bi(t,e){const n=Zi[e]??Zi.USD,i=t*n,s=Math.round(i*100)/100;try{return new Intl.NumberFormat("en-US",{style:"currency",currency:e,minimumFractionDigits:0,maximumFractionDigits:s>=100||s%1===0?0:2}).format(s)}catch{return new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",minimumFractionDigits:0,maximumFractionDigits:2}).format(t*Zi.USD)}}const rt="ccc_api_key_",bt="ccc_session_api_key_",lt="ccc_encryption_key",fi="ccc_encryption_key_scope",wv="ccc_keystore",Fs="keys",gi="ccc_encryption_key_version";let Do=null,Ps=null,mi=!1,$s=!1,Ac=!1;class Ts extends Error{constructor(){super("Secure browser key storage is unavailable."),this.name="CredentialStorageUnavailableError"}}function Fc(){if(Ac)return;Ac=!0;const t="Secure browser key storage is unavailable. Existing credentials were left untouched; new credentials will be available only in this tab session.";console.warn(t),document.body&&ue(t,"warning")}function Qd(){return localStorage.getItem(gi)||""}function jo(){return crypto.randomUUID?.()||th(crypto.getRandomValues(new Uint8Array(16)))}function bv(){const t=Qd();if(t)return t;const e=jo();return localStorage.setItem(gi,e),e}function In(){Do=null,Ps=null,mi=!1,$s=!1}window.addEventListener("storage",t=>{t.key===gi&&In()});function Ev(){return new Promise((t,e)=>{const n=indexedDB.open(wv,1);n.onupgradeneeded=()=>{const i=n.result;i.objectStoreNames.contains(Fs)||i.createObjectStore(Fs)},n.onsuccess=()=>t(n.result),n.onerror=()=>e(n.error)})}async function Ea(t,e){const n=await Ev();return new Promise((i,s)=>{const r=n.transaction(Fs,t);let o;try{o=e(r.objectStore(Fs))}catch(l){n.close(),s(l);return}let a;o.onsuccess=()=>{a=o.result},o.onerror=()=>s(o.error),r.oncomplete=()=>{n.close(),i(a)},r.onerror=()=>{n.close(),s(r.error||new Error("Encryption key transaction failed."))},r.onabort=()=>{n.close(),s(r.error||new Error("Encryption key transaction aborted."))}})}function Sv(t){return t instanceof CryptoKey&&t.algorithm?.name==="AES-GCM"&&t.extractable===!1&&t.usages.includes("encrypt")&&t.usages.includes("decrypt")}async function xv(){const t=await Ea("readonly",e=>e.get(lt));return Sv(t)?t:null}async function eh(t){await Ea("readwrite",e=>e.put(t,lt))}async function kv(){In();try{await Ea("readwrite",t=>t.delete(lt))}catch(t){console.warn("Could not delete the stored encryption key:",t)}}async function Iv(){const t=sessionStorage.getItem(lt);if(!t)return null;const e=await crypto.subtle.importKey("jwk",JSON.parse(t),{name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);return await eh(e),sessionStorage.removeItem(lt),sessionStorage.removeItem(fi),localStorage.removeItem(rt+"salt"),e}async function Pc(t){const e=sessionStorage.getItem(lt);if(e)return $s=sessionStorage.getItem(fi)!=="session",crypto.subtle.importKey("jwk",JSON.parse(e),{name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);if(!t)throw new Ts;const n=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!0,["encrypt","decrypt"]),i=await crypto.subtle.exportKey("jwk",n);return sessionStorage.setItem(lt,JSON.stringify(i)),sessionStorage.setItem(fi,"session"),$s=!1,crypto.subtle.importKey("jwk",i,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}async function Cv(t){if(sessionStorage.getItem(fi)==="session"&&sessionStorage.getItem(lt))return Fc(),mi=!0,Pc(t);try{const e=await xv();if(e)return e;const n=await Iv();if(n)return n;const i=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);return await eh(i),i}catch(e){return console.warn("IndexedDB encryption-key storage failed:",e),Fc(),mi=!0,Pc(t)}}async function Sa(t={}){const{allowSessionFallbackCreation:e=!0}=t,n=bv();Ps!==n&&In();const i=Do||Cv(e);Do=i,Ps=n;try{return await i}catch(s){throw In(),s}}async function Av(t){const e=await Sa(),n=Ps,i=new TextEncoder,s=crypto.getRandomValues(new Uint8Array(12)),r=await crypto.subtle.encrypt({name:"AES-GCM",iv:s},e,i.encode(t)),o=new Uint8Array(s.length+r.byteLength);return o.set(s),o.set(new Uint8Array(r),s.length),{ciphertext:th(o),keyVersion:n,sessionFallback:mi}}async function Fv(t,e={}){const{isSessionCredential:n=!1}=e;try{const i=await Sa({allowSessionFallbackCreation:!1});if(mi&&!n&&!$s)throw new Ts;const s=Pv(t),r=s.slice(0,12),o=s.slice(12),a=await crypto.subtle.decrypt({name:"AES-GCM",iv:r},i,o);return new TextDecoder().decode(a)}catch(i){if(i instanceof Ts)throw i;return console.error("Decryption failed:",i),null}}function th(t){const e=new Uint8Array(t);let n="";for(let i=0;i0}let vi="",Rs="",ni=null,Tc=0;async function xa(){sessionStorage.getItem(lt)&&await Sa(),vi=await Ee("flutterflow"),Rs=await Ee("flutterflow_project_id"),Mv(),en()}function ka(){const t=document.getElementById("api-keys-modal");Ve(t),Ca(),vi&&rh(vi)}function nh(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("api-keys-modal");e&&Xe(e);const n=document.getElementById("walkthrough-modal");n&&(Ia(),Ve(n))}let kt=1;function ih(){const t=document.querySelector(".wt-steps");return t?Array.from(t.querySelectorAll(".wt-step-card")):[]}function Js(){const t=ih();t.length&&t.forEach((e,n)=>{const i=n+1;if(i===kt){e.classList.remove("opacity-60","bg-gray-50","border-gray-200"),e.classList.add("bg-blue-50","border-blue-200");const s=e.querySelector("div:first-child");s&&(s.classList.remove("bg-gray-400"),s.classList.add("bg-blue-500"),s.innerHTML=i)}else if(i0&&kt<=t&&(kt++,Js())}function Tv(){const t=document.getElementById("walkthrough-modal");t&&(kt=1,Js(),Ve(t))}function Rv(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("walkthrough-modal");e&&Xe(e);const n=document.getElementById("walkthrough-dont-show");n&&n.checked&&localStorage.setItem("hasSeenWalkthrough","true")}function sh(){if(V.isVerified&&Nt()&&pe.tier!=="free")return;if(!localStorage.getItem("hasSeenWalkthrough")){const e=document.getElementById("walkthrough-modal");e&&(kt=1,Js(),Ve(e))}}async function Ca(){const t=document.getElementById("flutterflow-api-key-input");vi?(t.value="",t.placeholder="Key saved (enter new to replace)"):t.placeholder="Enter your FlutterFlow API key",Nv()}function Nv(){Rc("flutterflow","flutterflow-key-status"),Rc("flutterflow_project_id","flutterflow-project-status")}function Rc(t,e){const n=document.getElementById(e);if(!n)return;const i=n.querySelector(".key-status-dot"),s=n.querySelector("span");dn(t)?(i.className="key-status-dot configured",s.className="text-green-600",s.textContent="User key configured"):(i.className="key-status-dot missing",s.className="text-gray-500",s.textContent="Not configured")}function en(){const t=y.step2Result&&y.step2Result.length>0,e=document.getElementById("btn-deploy-to-ff"),n=document.getElementById("btn-run-pipeline");n&&n.classList.remove("hidden"),e&&e.classList.toggle("hidden",!t)}function Mv(){const t=document.getElementById("api-keys-status");if(!t)return;const e=t.querySelectorAll(".key-status-dot"),n=["flutterflow"];e.forEach((i,s)=>{const r=n[s];r==="flutterflow"?dn("flutterflow")&&dn("flutterflow_project_id")?(i.className="key-status-dot configured",i.title="FlutterFlow (Fully configured)"):dn("flutterflow")||dn("flutterflow_project_id")?(i.className="key-status-dot env",i.title="FlutterFlow (Partially configured)"):(i.className="key-status-dot missing",i.title="FlutterFlow (Not configured)"):dn(r)?(i.className="key-status-dot configured",i.title=r.charAt(0).toUpperCase()+r.slice(1)+" (User key)"):(i.className="key-status-dot missing",i.title=r.charAt(0).toUpperCase()+r.slice(1)+" (Not configured)")}),en()}async function Lv(){const t=document.getElementById("flutterflow-api-key-input"),e=document.getElementById("flutterflow-projects-select");t.value.trim()&&await $c("flutterflow",t.value);const n=e?.value.trim()||"";if(n){if(!Ys(n)){ue("The selected FlutterFlow project has an unexpected ID format.","error"),e.focus();return}await $c("flutterflow_project_id",n)}await xa(),Ca();const i=document.querySelector("#api-keys-modal .bg-blue-500"),s=i.textContent;i.textContent="Saved!",i.classList.remove("bg-blue-500","hover:bg-blue-600"),i.classList.add("bg-green-500"),setTimeout(()=>{i.textContent=s,i.classList.remove("bg-green-500"),i.classList.add("bg-blue-500","hover:bg-blue-600"),nh()},1e3)}async function Ov(){if(!confirm("Are you sure you want to clear all stored API keys?"))return;localStorage.setItem(gi,jo()),In(),localStorage.removeItem(rt+"flutterflow"),localStorage.removeItem(rt+"flutterflow_project_id"),sessionStorage.removeItem(bt+"flutterflow"),sessionStorage.removeItem(bt+"flutterflow_project_id"),sessionStorage.removeItem(lt),sessionStorage.removeItem(fi),localStorage.removeItem(rt+"salt"),await kv(),localStorage.setItem(gi,jo()),localStorage.removeItem(rt+"flutterflow"),localStorage.removeItem(rt+"flutterflow_project_id"),sessionStorage.removeItem(bt+"flutterflow"),sessionStorage.removeItem(bt+"flutterflow_project_id"),await xa();const t=document.getElementById("flutterflow-projects-select");t&&(t.innerHTML=''),Ca()}function Ys(t){return!t||t.trim().length<5||t.includes(" ")?!1:/^[a-zA-Z0-9-]+$/.test(t)}function Bv(t,e){const n=document.getElementById(t);n&&(n.value?e?n.style.borderColor="#22c55e":n.style.borderColor="#ef4444":n.style.borderColor="")}function Dv(){const t=document.getElementById("flutterflow-api-key-input");t&&(t.addEventListener("input",e=>{const n=e.target.value.trim().length>0;Bv("flutterflow-api-key-input",n)}),t.addEventListener("blur",jv(async e=>{const n=e.target.value.trim();n&&await rh(n)},500)))}function jv(t,e){let n;return function(...s){const r=()=>{clearTimeout(n),t(...s)};clearTimeout(n),n=setTimeout(r,e)}}async function rh(t){const e=document.getElementById("flutterflow-projects-select"),n=document.getElementById("flutterflow-projects-error");if(!e){console.error("Projects dropdown element not found");return}e.innerHTML='',n&&n.classList.add("hidden");try{const s=await new wi(t,"").listProjects();if(!s||s.length===0){e.innerHTML='';return}e.innerHTML='',s.forEach(r=>{const o=document.createElement("option");o.value=r.id||r.projectId||"",o.textContent=r.name||r.projectName||`Project ${r.id}`,e.appendChild(o)}),Rs&&(e.value=Rs)}catch(i){console.error("Failed to fetch projects:",i),e.innerHTML='',n&&(n.textContent=`Failed to load projects: ${i.message}`,n.classList.remove("hidden"))}}function Uv(t){const e=document.getElementById(t),i=e.nextElementSibling.querySelector("svg");e.type==="password"?(e.type="text",i.innerHTML=` - - `):(e.type="password",i.innerHTML=` - - - `)}let y={step1Result:null,step2Result:null,step3Result:null,bundleSpec:null,artifactBundle:null,bundleReview:null,selectedArtifactId:null,resultsViewMode:"summary",currentStep:0,isRunning:!1};function Hv(){y.step1Result=null,y.step2Result=null,y.step3Result=null,y.bundleSpec=null,y.artifactBundle=null,y.bundleReview=null,y.selectedArtifactId=null,y.resultsViewMode="summary"}function Wv(){y.bundleSpec=di(y.step1Result,{artifactType:"CustomWidget",artifactName:"GeneratedWidget"})}function Zs(){const t=Ss(y.bundleSpec);y.artifactBundle=di(y.step2Result,{id:y.bundleSpec?.id,title:y.bundleSpec?.title,description:y.bundleSpec?.description,artifactType:t.artifactType,artifactName:t.artifactName,fileName:t.fileName,dependencies:t.dependencies,relationships:y.bundleSpec?.relationships,code:y.step2Result||""});const e=Ng(y.artifactBundle);y.artifactBundle={...y.artifactBundle,warnings:[...y.artifactBundle.warnings,...e.findings.map(n=>n.message)],metadata:{...y.artifactBundle.metadata,compatibility:e}},y.selectedArtifactId=Ss(y.artifactBundle).id}function Xs(){const t=di(y.step3Result,{id:y.artifactBundle?.id,title:y.artifactBundle?.title}),e=new Map(t.artifacts.map(i=>[i.id,i.review])),n=new Map(t.artifacts.filter(i=>{const s=i.review;return s&&typeof s.fixedSource=="string"&&s.fixedSource.trim()}).map(i=>[i.id,i.review.fixedSource.trim()]));y.bundleReview=di({id:y.artifactBundle?.id,title:y.artifactBundle?.title,artifacts:y.artifactBundle?.artifacts?.map(i=>{const s=n.get(i.id)||null;return{...i,review:e.get(i.id)||i.review||y.step3Result||null,...s?{fixedCode:s}:{}}})||[],relationships:y.artifactBundle?.relationships,warnings:y.artifactBundle?.warnings})}function oh(){const t=Aa();return{artifactType:t.artifactType||"CustomWidget",artifactName:t.artifactName||"GeneratedWidget",fileName:t.fileName||""}}function Aa(){const t=y.artifactBundle||y.bundleSpec||null;return(Array.isArray(t?.artifacts)?t.artifacts:[]).find(n=>n.id===y.selectedArtifactId)||Ss(t)}function Fa(){return Aa().code||y.step2Result||""}async function zv(){try{await xa()}catch(t){return console.error("checkConnection: initializeApiKeys failed:",t),!1}return!0}const Xi={production:"https://api.flutterflow.io/v2/",staging:"https://api.flutterflow.io/v2-staging/"};function qv(t,e){const n=e?.trim()?` (${e.trim().slice(0,200)})`:"";return t===401?`Your FlutterFlow API key was rejected (401 Unauthorized)${n}. Re-enter a current key under API Keys settings, then try again.`:`Listing FlutterFlow projects was denied (403)${n}. The key may be scoped to sync a single project without list permission - verify the key's access in FlutterFlow, re-enter it under API Keys settings, then retry.`}class wi{constructor(e,n,i="main",s=Xi.production){this.apiKey=e,this.baseUrl=s,this._projectId=n,this._branchName=i,this._endpoint=s}get projectId(){return this._projectId}get branchName(){return this._branchName==="main"?"":this._branchName}async exportProjectZip(){console.log(`Exporting code from FlutterFlow project: ${this.projectId}, branch: ${this.branchName||"main"}`);const e=[{project:{path:`projects/${this.projectId}`},...this.branchName?{branch_name:this.branchName}:{},export_as_module:!1,include_assets_map:!1,format:!1,export_as_debug:!1},{project_id:this.projectId,branch_name:this.branchName,include_assets:!1,export_as_module:!1}];let n=null;for(const i of e)try{const s=await fetch(`${this.baseUrl}exportCode`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify(i)});if(!s.ok){const a=await s.text();n=new Error(`Export failed: ${s.status} - ${a}`);continue}const r=await s.json(),o=r?.value?.project_zip||r?.project_zip;if(!o){n=new Error("Export response did not include project source.");continue}return o}catch(s){n=s}throw n||new Error("Export failed for an unknown reason.")}async fetchProjectSource(){const e=await this.exportProjectZip(),n=await JSZip.loadAsync(e,{base64:!0}),i=Object.keys(n.files).filter(a=>!n.files[a].dir&&(a==="pubspec.yaml"||a.endsWith("/pubspec.yaml"))).sort((a,l)=>a.split("/").length-l.split("/").length)[0];if(!i)throw new Error("Export did not contain a pubspec.yaml.");const s=i.slice(0,i.length-12),r=new Map,o=Object.keys(n.files).filter(a=>{if(n.files[a].dir||!a.startsWith(s))return!1;const l=a.slice(s.length);return l==="lib/flutter_flow/custom_functions.dart"||l.startsWith("lib/custom_code/")&&l.endsWith(".dart")});return await Promise.all(o.map(async a=>{r.set(a.slice(s.length),await n.files[a].async("string"))})),{pubspecYaml:await n.files[i].async("string"),files:r}}async pushCodeWithRetry(e,n=3){const i=[Xi.production,Xi.staging],s=Math.max(0,i.indexOf(this._endpoint));for(let r=0;rsetTimeout(d,1e3*(r+1)));continue}return l}catch(l){console.warn(`Push to ${a} failed: ${l.message}, trying next...`),await new Promise(u=>setTimeout(u,1e3*(r+1)))}}throw new Error("All API endpoints failed after retries")}async pushCode(e){return this.pushCodeWithRetry(e)}parseProjectsResponse(e){if(e?.success&&typeof e.value=="string")try{const i=JSON.parse(e.value);if(i&&Array.isArray(i.entries))return i.entries.map(s=>({id:s.id,name:s.project?.name||s.id}))}catch(i){console.error("Failed to parse stringified project value:",i)}const n=e?.projects||e?.items||e?.entries||(Array.isArray(e)?e:[]);return Array.isArray(n)?n:[]}async listProjects(){console.log("Listing projects for API key");const e=[`${this.baseUrl}listProjects`,"https://api.flutterflow.io/v2/l/listProjects"];let n=0,i="";for(const s of e){const r=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify({project_type:"ALL",deserialize_response:!0})});if(r.ok)return s!==e[0]&&console.log(`listProjects answered on legacy path ${s}`),this.parseProjectsResponse(await r.json());if(n=r.status,i=await r.text(),console.warn(`listProjects via ${s} returned ${n}: ${i}`),r.status===401||r.status===403)throw new Error(qv(r.status,i));if(r.status!==404)throw new Error(`List projects failed: ${r.status} - ${i}`)}throw new Error(`List projects failed: ${n} - ${i}`)}}async function Pa(t){const e=t.clone();let n;try{n=await t.json()}catch{const r=await e.text();if(!t.ok)return{success:!1,responseCode:t.status,errorMessage:r||`HTTP ${t.status}`,errorMap:new Map};throw new Error(`Invalid JSON response: ${r}`)}if(!t.ok){let s=n.message||`HTTP ${t.status}`,r=new Map;if(n.errors)r=new Map(Object.entries(n.errors));else if(!n.message&&typeof n=="object"){const o=Object.keys(n).filter(a=>a.endsWith(".dart")&&Array.isArray(n[a]));o.length>0&&(r=new Map(Object.entries(n)),s=o.flatMap(l=>n[l].map(u=>`${l}: ${u.errorMessage}`)).join(` -`)||`HTTP ${t.status}`)}return{success:!1,responseCode:t.status,errorMessage:s,errorMap:r}}let i={};if(n.value)try{i=typeof n.value=="string"?JSON.parse(n.value):n.value}catch(s){console.warn("Ignoring malformed push response value:",s)}return{success:!0,responseCode:t.status,errorMap:new Map(Object.entries(i))}}function $a(t,e){return{401:"Authentication failed. Please check your FlutterFlow API key.",403:"Access denied. You may not have permission to modify this project.",404:"Project not found. Please check your Project ID.",409:"Conflict detected. The project may have been modified elsewhere.",422:"Validation failed: Invalid request format",429:"Rate limit exceeded. Please try again in a few minutes.",500:"FlutterFlow server error. Please try again later.",503:"FlutterFlow service temporarily unavailable."}[t]||`FlutterFlow API error: ${`HTTP ${t}`}`}const W={ACTION:"A",WIDGET:"W",FUNCTION:"F",CODE_FILE:"C",DEPENDENCIES:"D",OTHER:"O"},ah=/class\s+\w+\s+extends\s+(?:StatelessWidget|StatefulWidget)\b/,lh=/extends\s+State<\w+>/;function Vv(t,e=""){if(t==="pubspec.yaml")return W.DEPENDENCIES;if(!t.endsWith(".dart")||t.endsWith("index.dart"))return W.OTHER;if(t==="custom_functions.dart")return W.FUNCTION;if(e){const n=ah.test(e),i=lh.test(e);if(n||i)return W.WIDGET;if(/^\s*Future(?:<[^>]+>)?\s+\w+\s*\(/m.test(e))return W.ACTION;if(e.match(/^\s*(String|int|double|bool|List|Map|dynamic|void)\s+\w+\s*\(/m))return W.FUNCTION}return W.CODE_FILE}function ch(t,e){switch(e){case W.ACTION:return`lib/custom_code/actions/${t}`;case W.WIDGET:return`lib/custom_code/widgets/${t}`;case W.FUNCTION:return"lib/flutter_flow/custom_functions.dart";case W.CODE_FILE:return`lib/custom_code/${t}`;case W.DEPENDENCIES:return"pubspec.yaml";case W.OTHER:return`lib/custom_code/${t}`;default:return t}}async function Ta(t,e=new Map){return mg(t,e)}const Uo=new Map;function uh(t){return`${t.baseUrl}|${t.projectId}|${t.branchName}`}function Qs(t){Uo.delete(uh(t))}async function Ra(t,e,n,i,s=""){const r=Kg(e,n);if(r.length===0)return{remoteFiles:n,syncFileMap:e,unverified:[]};const o=Nm(r,s),a={...o.manifest,sources:o.sources},l=o.skipped.map(d=>d.reason);l.forEach(d=>console.warn(`[custom class deploy] ${d}`)),console.log(`Provisioning ${r.length} new FlutterFlow custom code file(s) before sync.`),be.set("provision");const u=await fetch(rv,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:t.apiKey,projectId:t.projectId,baseUrl:t.baseUrl,commitMessage:i,customClasses:r,verification:a,stream:!0})}),c=await Lm(u,{onPhase:d=>be.setSubstatus(d),onLog:d=>console.log(`[custom class deploy] ${d}`)});if(!c.success){const d=c.details?` ${c.details}`:"";throw new Error(`${c.error||"FlutterFlow custom class provisioning failed."}${d}`)}return Qs(t),c.verificationSkipped&&(console.warn(`[custom class deploy] ${c.verificationSkipped}`),l.push(c.verificationSkipped)),{remoteFiles:n,syncFileMap:Jg(e,r),unverified:l}}async function Na(t,e={}){const n=uh(t);let i=Uo.get(n);if(i===void 0){try{i=await t.fetchProjectSource()}catch(l){throw new Error(`Could not read your project's pubspec.yaml (${l.message}). Deploy was stopped so your existing package dependencies aren't overwritten. Check your FlutterFlow API key and project, then try again.`)}const a=zd(i.pubspecYaml);if(!a.valid)throw new Error(`Your project's pubspec.yaml could not be read reliably (${a.errors.join("; ")}). Deploy was stopped so your existing package dependencies aren't overwritten.`);Uo.set(n,i)}const s=await Gm(i.pubspecYaml,e),r=Fm(i.pubspecYaml,s.overrides),o=Am(r.yaml,s.additions);return s.warnings.forEach(a=>console.warn(`[pubspec] ${a}`)),o.added.length>0&&console.log("Adding dependencies:",o.added.map(a=>`${a}: ${s.additions[a]||"any"}`).join(", "),s.sdk.dartSdkFloor?`(resolved for Dart ${s.sdk.dartSdkFloor})`:""),s.kept.forEach(({name:a,constraint:l})=>console.log(`Keeping your existing ${a}: ${l||"(non-version source)"}`)),{...o,overridden:r.overridden,warnings:s.warnings,remoteFiles:i.files}}function Gv(t){const e=[],n=[];t.content.length>5e4&&n.push("Code file is large (>50KB). This may take longer to commit."),t.content.length>1e5&&e.push("Code file is too large (>100KB). Consider splitting into smaller components.");const i=t.content.split(` -`).length;i>500&&n.push(`Code has ${i} lines. Consider breaking it into smaller widgets.`),t.content.includes("setState")&&t.codeType===W.ACTION&&n.push("Using setState in a Custom Action may not work as expected. Consider using a Custom Widget."),t.content.includes("dynamic")&&!t.content.includes("?")&&n.push('Code uses "dynamic" types. Consider adding explicit types for better null safety.'),t.content.match(/Color\(0xFF[0-9A-Fa-f]{6}\)/)&&n.push("Code contains hardcoded colors. Consider using FlutterFlowTheme.of(context) for theme consistency.");const s=t.content.match(/print\s*\(/g);s&&s.length>3&&n.push(`Code contains ${s.length} print statements. Consider removing debug prints before committing.`);const r=pm(t.content);if(r&&e.push(`FlutterFlow cannot format this code - ${r}. Fix or regenerate before committing.`),t.codeType===W.WIDGET){const o=Ld(t.content),a=um(t.fileName);if(o.length===0)e.push("No public widget class found (must extend StatelessWidget or StatefulWidget).");else if(!o.includes(a)){const l=`${Od(o[0])}`;e.push(`Widget class name "${o[0]}" does not match the file name "${t.fileName}". FlutterFlow derives the widget from the file name, so it will report "No widget ${a} found". Rename the file to "${l}" or the class to match before committing.`)}}return{canProceed:e.length===0,issues:e,warnings:n}}function dh(t,e={}){const{artifactType:n="CustomWidget",artifactName:i="GeneratedCode",fileName:s}=e,r=lm(t);let o=s||i;if(n==="CustomFunction")o="custom_functions.dart";else if(n==="CustomWidget"){const u=Ld(r)[0],c=u?Od(u):null;c&&o!==c?(console.warn(`Commit file name "${o}" does not match declared widget class "${u}"; renaming to "${c}" so FlutterFlow can find the widget.`),o=c):o.endsWith(".dart")||(o+=".dart")}else o.endsWith(".dart")||(o+=".dart");let a=W.CODE_FILE;switch(n){case"CustomAction":a=W.ACTION;break;case"CustomWidget":a=W.WIDGET;break;case"CustomFunction":a=W.FUNCTION;break;case"CustomClass":case"CodeFile":a=W.CODE_FILE;break}let l="";return a===W.WIDGET?l=`// Automatic FlutterFlow imports -import '/flutter_flow/flutter_flow_theme.dart'; -import '/flutter_flow/flutter_flow_util.dart'; -import 'package:flutter/material.dart'; -// Begin custom widget code -// DO NOT REMOVE OR MODIFY THE CODE ABOVE! - -`:a===W.ACTION?l=`// Automatic FlutterFlow imports -import '/flutter_flow/flutter_flow_theme.dart'; -import '/flutter_flow/flutter_flow_util.dart'; -import 'package:flutter/material.dart'; -// Begin custom action code -// DO NOT REMOVE OR MODIFY THE CODE ABOVE! - -`:a===W.FUNCTION&&(l=`// Automatic FlutterFlow imports -import 'dart:convert'; -import 'dart:math' as math; - -import 'package:flutter/material.dart'; -import 'package:google_fonts/google_fonts.dart'; -import 'package:intl/intl.dart'; -import 'package:timeago/timeago.dart' as timeago; -import '/flutter_flow/lat_lng.dart'; -import '/flutter_flow/place.dart'; -import '/flutter_flow/uploaded_file.dart'; - -`),{content:Og(r,l),fileName:o,codeType:a,artifactType:n,artifactName:i}}function Kv(t){const e={};for(const n of ma(t))e[n]="";return e}function Jv(t,e={}){return{timestamp:new Date().toISOString(),artifactType:t.artifactType,artifactName:t.artifactName,codeType:t.codeType,fileName:t.fileName,generatedFrom:e.step1Result?"pipeline":"direct",model:e.selectedModel||"unknown",codeSize:t.content.length}}function Yv(t,e,n,i=new Set,s=""){const r=[],o=ah.test(e),a=lh.test(e);return n===W.WIDGET&&!o&&!a&&r.push("No widget class definition found (must extend StatelessWidget or StatefulWidget)"),{valid:r.length===0,errors:r}}function er(t){const e=[],n=[];if(!t||t.size===0)return e.push("No files to commit"),{valid:!1,errors:e,warnings:n};const i=new Set(Array.from(t.values()).flatMap(s=>Hs(s.content||"")));for(const[s,r]of t.entries()){if((!r.content||r.content.trim().length===0)&&e.push(`File ${s} is empty`),r.content&&r.content.length>1e5&&n.push(`File ${s} is very large (>100KB)`),s.endsWith(".dart")){const o=Yv(s,r.content,r.type,i,r.artifactName);o.valid||e.push(...o.errors.map(a=>`${s}: ${a}`))}if(s==="pubspec.yaml"){const o=zd(r.content);o.valid||e.push(...o.errors)}}return{valid:e.length===0,errors:e,warnings:n}}const K={IDLE:"IDLE",PREPARING:"PREPARING",VALIDATING:"VALIDATING",PUSHING:"PUSHING",SUCCESS:"SUCCESS",ERROR:"ERROR"},J={currentState:K.IDLE,startTime:null,endTime:null,error:null,result:null,filesProcessed:0,totalFiles:0,reset(){this.currentState=K.IDLE,this.startTime=null,this.endTime=null,this.error=null,this.result=null,this.filesProcessed=0,this.totalFiles=0},setState(t){if(!Object.values(K).includes(t)){console.error(`Invalid commit state: ${t}`);return}this.currentState=t,t===K.PREPARING&&(this.startTime=Date.now()),(t===K.SUCCESS||t===K.ERROR)&&(this.endTime=Date.now()),typeof window<"u"&&window.dispatchEvent&&window.dispatchEvent(new CustomEvent("commitStateChange",{detail:{state:t,commitState:this}})),console.log(`Commit state changed to: ${t}`)},setError(t){this.error=t,this.setState(K.ERROR)},setSuccess(t){this.result=t,this.setState(K.SUCCESS)},setProgress(t,e){this.filesProcessed=t,this.totalFiles=e},getElapsedTime(){return this.startTime?(this.endTime||Date.now())-this.startTime:null},isInProgress(){return this.currentState===K.PREPARING||this.currentState===K.VALIDATING||this.currentState===K.PUSHING}};async function Zv(t,e,n={}){let{codeType:i="W"}=n;const{pubspecDeps:s={},artifactName:r=e}=n;i==="CustomWidget"&&(i=W.WIDGET),i==="CustomAction"&&(i=W.ACTION),i==="CustomFunction"&&(i=W.FUNCTION),i==="CustomClass"&&(i=W.CODE_FILE),i==="CodeFile"&&(i=W.CODE_FILE),J.reset(),J.setState(K.PREPARING);try{const o=await Ee("flutterflow"),a=await Ee("flutterflow_project_id");if(!o||!a)throw new Error("FlutterFlow credentials not configured. Please set your API key and Project ID in the API Keys settings.");if(!Ys(a))throw new Error("Invalid FlutterFlow Project ID format.");const l=yi(),u=new wi(o,a,"main",l);J.setState(K.VALIDATING);const c=new Map,d=i||Vv(e,t),h=ch(e,d);c.set(e,{artifactName:r,content:t,type:d,path:h}),J.setProgress(0,c.size);const p=er(c);if(!p.valid)throw new Error(`Validation failed: -${p.errors.join(` -`)}`);const f=await Na(u,s),g=f.yaml,m=await Ra(u,c,f.remoteFiles,`Provision ${r} custom class`,g),v=await Ta(m.syncFileMap,m.remoteFiles),E=new Map(m.syncFileMap);E.set("pubspec.yaml",{content:g,type:"D",path:"pubspec.yaml"}),be.set("package");const w=await Ma(E),I={project_id:a,zipped_custom_code:w,uid:`web_${Date.now()}`,branch_name:u.branchName,serialized_yaml:g,file_map:v.fileMapContents,functions_map:v.functionsMapContents};J.setState(K.PUSHING),J.setProgress(1,c.size),Qs(u),be.set("push");const A=await u.pushCode(I),F=await Pa(A);if(F.success)J.setSuccess({fileCount:c.size,projectId:a,warnings:F.errorMap&&F.errorMap.size>0?Array.from(F.errorMap.entries()):[]});else{const D=F.errorMessage||$a(F.responseCode);throw new Error(D)}return{success:!0,message:`Successfully committed ${e} to FlutterFlow project ${a}`,addedDependencies:f.added,unverified:m.unverified,warnings:F.errorMap?Array.from(F.errorMap.entries()):[]}}catch(o){return console.error("Commit failed:",o),J.setError(o),{success:!1,error:o.message,state:J.currentState}}}async function Ma(t){const e=new JSZip;for(const[n,i]of t.entries())e.file(n,i.content);return e.generateAsync({type:"base64",compression:"DEFLATE",compressionOptions:{level:6}})}async function Xv(t,e={}){const{artifactType:n,artifactName:i,fileName:s,pipelineResult:r}=e;console.log(`Starting commit for ${i} (${n})`);try{J.setState(K.PREPARING);const o=dh(t,{artifactType:n,artifactName:i,fileName:s}),a=Kv(o.content);console.log("Detected dependencies:",a),J.setState(K.VALIDATING);const l=await Ee("flutterflow"),u=ni||await Ee("flutterflow_project_id");if(!l)throw new Error("FlutterFlow API Key not configured. Please add it in API Keys settings.");if(!u)throw new Error("FlutterFlow Project ID not configured. Please add it in API Keys settings.");if(!Ys(u))throw new Error("Invalid FlutterFlow Project ID format.");const c=new Map;c.set(o.fileName,{artifactName:i,content:o.content,type:o.codeType,path:ch(o.fileName,o.codeType),functionName:o.codeType===W.FUNCTION?i:void 0}),J.setProgress(0,c.size);const d=er(c);if(!d.valid)throw new Error(`File validation failed: -${d.errors.join(` -`)}`);d.warnings.length>0&&console.warn("Validation warnings:",d.warnings),J.setState(K.PUSHING);const h=yi(),p=new wi(l,u,"main",h),f=await Na(p,a),g=f.yaml,m=await Ra(p,c,f.remoteFiles,`Provision ${i} custom class`,g),v=await Ta(m.syncFileMap,m.remoteFiles),E=new Map(m.syncFileMap);E.set("pubspec.yaml",{content:g,type:W.DEPENDENCIES,path:"pubspec.yaml"}),be.set("package");const w=await Ma(E),I={project_id:u,zipped_custom_code:w,uid:`web_${Date.now()}`,branch_name:p.branchName,serialized_yaml:g,file_map:v.fileMapContents,functions_map:v.functionsMapContents};J.setProgress(1,c.size),Qs(p),be.set("push");const A=await p.pushCode(I),F=await Pa(A);if(F.success){const D={...Jv(o,r),projectId:u};return J.setSuccess({...D,fileCount:c.size,warnings:F.errorMap?Array.from(F.errorMap.entries()):[]}),{success:!0,message:`Successfully committed ${o.fileName} to FlutterFlow`,metadata:D,addedDependencies:f.added,unverified:m.unverified,warnings:F.errorMap?Array.from(F.errorMap.entries()):[],elapsedTime:J.getElapsedTime()}}else{const D=F.errorMessage||$a(F.responseCode),S=new Error(D);throw S.errorMap=F.errorMap,S}}catch(o){console.error("Commit execution failed:",o),J.setError(o);let a=new Map;if(o.errorMap)a=o.errorMap;else if(o.message&&o.message.includes("{"))try{const l=o.message.match(/\{[\s\S]*\}/);if(l){const u=JSON.parse(l[0]);a=new Map(Object.entries(u))}}catch(l){console.warn("Failed to parse error map from commit response:",l)}return{success:!1,error:o.message,errorMap:a,state:J.currentState,elapsedTime:J.getElapsedTime()}}}async function Qv(t,e={}){const{pipelineResult:n}=e;try{if(J.setState(K.PREPARING),t.errors?.length>0)throw new Error(`Bundle validation failed: -${t.errors.join(` -`)}`);const i=new Map(t.fileEntries.map(I=>[I.fileName,{artifactId:I.artifactId,artifactName:I.artifactName,content:I.content,type:I.type,path:I.path,functionName:I.type===W.FUNCTION?I.artifactName:void 0}]));J.setProgress(0,i.size);const s=er(i);if(!s.valid)throw new Error(`File validation failed: -${s.errors.join(` -`)}`);J.setState(K.VALIDATING);const r=await Ee("flutterflow"),o=ni||await Ee("flutterflow_project_id");if(!r)throw new Error("FlutterFlow API Key not configured. Please add it in API Keys settings.");if(!o)throw new Error("FlutterFlow Project ID not configured. Please add it in API Keys settings.");if(!Ys(o))throw new Error("Invalid FlutterFlow Project ID format.");J.setState(K.PUSHING);const a=yi(),l=new wi(r,o,"main",a),u=await Na(l,t.dependencies),c=u.yaml,d=await Ra(l,i,u.remoteFiles,`Provision ${t.title} custom classes`,c),h=await Ta(d.syncFileMap,d.remoteFiles),p=new Map(d.syncFileMap);p.set("pubspec.yaml",{content:c,type:W.DEPENDENCIES,path:"pubspec.yaml"}),be.set("package");const f=await Ma(p),g={project_id:o,zipped_custom_code:f,uid:`web_${Date.now()}`,branch_name:l.branchName,serialized_yaml:c,file_map:h.fileMapContents,functions_map:h.functionsMapContents};J.setProgress(1,i.size),Qs(l),be.set("push");const m=await l.pushCode(g),v=await Pa(m);if(v.success){const I={...n,artifactType:"Bundle",artifactName:t.title,fileName:`${t.fileEntries.length} artifacts`,codeSize:t.fileEntries.reduce((A,F)=>A+F.content.length,0),projectId:o};return J.setSuccess({...I,fileCount:i.size,warnings:v.errorMap?Array.from(v.errorMap.entries()):[]}),{success:!0,message:`Successfully committed ${t.fileEntries.length} artifacts to FlutterFlow`,metadata:I,addedDependencies:u.added,unverified:d.unverified,warnings:v.errorMap?Array.from(v.errorMap.entries()):[],elapsedTime:J.getElapsedTime()}}const E=v.errorMessage||$a(v.responseCode),w=new Error(E);throw w.errorMap=v.errorMap,w}catch(i){return console.error("Bundle commit execution failed:",i),J.setError(i),{success:!1,error:i.message,errorMap:i.errorMap||new Map,state:J.currentState,elapsedTime:J.getElapsedTime()}}}async function e_(t,e=[]){const n=ha("architect");try{return await Ms("architect",Yd,sg(t),n,e)}catch(i){throw i.isModelArmor?i:new Error(`Prompt Architect failed: ${i.message}`)}}async function tr(t,e,n=[]){const i=rg(t),s=ha("generator",y.bundleSpec);try{return await Ms("generator",e,i,s,n)}catch(r){if(r.isModelArmor)throw r;if(e!==jr){console.warn(`Code Generator failed with ${e}, retrying with fallback model:`,r.message);try{return await Ms("generator",jr,i,s,n)}catch(o){throw o.isModelArmor?o:new Error(`Code Generator failed: primary (${e}): ${r.message} | fallback (${jr}): ${o.message}`)}}throw new Error(`Code Generator failed: ${r.message}`)}}async function nr(t,e=null){const n={...ha("review",y.artifactBundle||y.bundleSpec),architect_output:e};try{return await Ms("review",Zd,og(t),n)}catch(i){throw i.isModelArmor?i:new Error(`Code Review failed: ${i.message}`)}}function La(t,e){return t.isModelArmor?`${t.userTitle}: ${t.userMessage}`:`${e}: ${t.message}`}function Ho(t,e){const n=document.getElementById(`step${t}-item`),i=document.getElementById(`step${t}-status`);!n||!i||(n.classList.remove("active","completed","error"),i.classList.remove("running","completed","error"),e==="active"?(n.classList.add("active"),i.classList.add("running"),i.innerHTML=` - - `):e==="completed"?(n.classList.add("completed"),i.classList.add("completed"),i.innerHTML=` - - `):e==="error"?(n.classList.add("error"),i.classList.add("error"),i.innerHTML=` - - `):i.innerHTML=` - - `)}function ve(t,e){const n=document.getElementById(`step${t}-loading`),i=document.getElementById(`step${t}-result`);e?(n.classList.remove("hidden"),i.classList.add("hidden"),Ho(t,"active")):(n.classList.add("hidden"),i.classList.remove("hidden"),Ho(t,"completed"))}function t_(t){const e=document.getElementById(`${t}-content`),n=document.getElementById(`${t}-chevron`);e.classList.contains("open")?(e.classList.remove("open"),n&&(n.style.transform="rotate(0deg)")):(e.classList.add("open"),n&&(n.style.transform="rotate(180deg)"))}function n_(t){ze(parseInt(t.replace("step","")))}function ze(t){for(let o=1;o<=3;o++){const a=document.getElementById(`step${o}-item`);a&&a.classList.remove("active")}const e=document.getElementById(`step${t}-item`);e&&e.classList.add("active"),Qt();const n=document.getElementById("ready-state");n&&n.classList.add("hidden");for(let o=1;o<=3;o++){const a=document.getElementById(`step${o}-content`);a&&a.classList.add("hidden")}const i=document.getElementById(`step${t}-content`);i&&i.classList.remove("hidden");const s=document.getElementById("stage-title"),r={1:"Prompt Architect",2:"Code Generator",3:"Code Review"};s&&(s.textContent=r[t]||"Active Workflow Stage")}function i_(t){const e=document.getElementById(t);if(!e)return;const n=e.dataset.raw||e.textContent;navigator.clipboard.writeText(n).then(()=>{const s=e.closest(".code-container")?.querySelector(".copy-btn");s&&(s.classList.add("copied"),s.innerHTML=' Copied!',setTimeout(()=>{s.classList.remove("copied"),s.innerHTML=' Copy'},2e3))}).catch(i=>{console.warn("Failed to copy to clipboard:",i)})}function Wo(t){const e=zo(t);console.log(`Step 1 (Prompt Architect): ${Kt(Yd)}`),console.log(e!==t?`Step 2 (Code Generator): ${Kt(t)} → ${Kt(e)} (Free Tier fallback)`:`Step 2 (Code Generator): ${Kt(t)}`),console.log(`Step 3 (Code Review): ${Kt(Zd)}`)}async function s_(){if(console.log("runRefinement called"),y.isRunning)return;const t=document.getElementById("code-generator-model").value;y.isRunning=!0,Oa("standardRegenerate",y.step2Result,y.step1Result);const e=document.querySelectorAll(".btn-refine-action");e.forEach(n=>{n.disabled=!0,n.innerHTML=` - - - Refining...`});try{const n=Aa(),i=ag({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,artifactId:n.id,userFeedback:"Fix the issues listed in the audit report."});or(),at(2),ze(2),ve(2,!0),y.step2Result=await tr(i,t),Zs();const s=document.getElementById("step2-output"),r=xn(y.step2Result);s.textContent=r,s.dataset.raw=r,ve(2,!1),ze(3),at(3),ve(3,!0),y.step3Result=await nr(y.step2Result,y.step1Result),Xs();const o=document.getElementById("step3-output");o.textContent=y.step3Result,ve(3,!1),Mt();const a=Ks(y.step3Result);ar(r,a)}catch(n){console.error("Refinement failed:",n),Mt(),ue(La(n,"Refinement failed"),"error")}finally{y.isRunning=!1,e.forEach(n=>{n.disabled=!1,n.textContent="Refine & Regenerate"}),en()}}async function Oa(t,e,n){const i=`${Ze}/connectFeedback`,s={type:t,code:e,input:n};try{const r=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)});if(!r.ok){const a=await r.text();return console.error(`callEndpoint failed: ${r.status} ${r.statusText}`,a),{success:!1,status:r.status,error:a}}const o=await r.json();return console.log("Telemetry success:",o),o}catch(r){return console.error("callEndpoint failed:",r),{success:!1,error:r.message}}}function r_(){const t=document.getElementById("ff-error-paste-input");t&&(t.value="")}async function o_(){const t=document.getElementById("ff-error-paste-input"),e=t?.value?.trim();if(!e){t?.focus(),t?.classList.add("ring-2","ring-red-400","border-red-300"),setTimeout(()=>t?.classList.remove("ring-2","ring-red-400","border-red-300"),2e3);return}if(!y.step2Result){ue("No generated code found. Please run the full pipeline first.","warning");return}if(y.isRunning)return;const n=document.getElementById("code-generator-model").value;y.isRunning=!0,Oa("flutterflowError",y.step2Result,e);const i=document.getElementById("btn-fix-from-errors");i&&(i.disabled=!0,i.innerHTML=` - - Fixing…`);try{const s=$d({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,userFeedback:e});Sh(),or(),at(2),ze(2),ve(2,!0),y.step2Result=await tr(s,n),Zs();const r=document.getElementById("step2-output"),o=xn(y.step2Result);r.textContent=o,r.dataset.raw=o,ve(2,!1),ze(3),at(3),ve(3,!0),y.step3Result=await nr(y.step2Result,y.step1Result),Xs();const a=document.getElementById("step3-output");a.textContent=y.step3Result,ve(3,!1),Mt();const l=Ks(y.step3Result);ar(o,l),t&&(t.value="")}catch(s){console.error("Fix from errors failed:",s),Mt(),ue(La(s,"Failed to fix errors"),"error")}finally{y.isRunning=!1,i&&(i.disabled=!1,i.textContent="Fix Errors & Regenerate"),en()}}async function Ns(){if(console.log("runThinkingPipeline called"),y.isRunning)return;localStorage.setItem("hasSeenWalkthrough","true");const t=document.getElementById("pipeline-input").value,e=document.getElementById("code-generator-model").value;if(!t.trim()){ue("Please describe your FlutterFlow widget first.","warning");return}if(!await I_())return;await w_();const n=zo(e);t.length;const i=document.getElementById("btn-run-pipeline");y.isRunning=!0,Hv(),i&&(i.disabled=!0,i.innerHTML=` - - - Running...`),Wo(n);try{Qt();const s=document.getElementById("ready-state");s&&s.classList.add("hidden");const r=document.getElementById("paywall-exhausted");r&&r.classList.add("hidden"),or(),ze(1),at(1),ve(1,!0);const o=Tt.filter(p=>p.url).map(p=>({url:p.url}));y.step1Result=await e_(t,o),Wv();const a=document.getElementById("step1-output"),l=xn(y.step1Result);a.textContent=l,a.dataset.raw=l,ve(1,!1),ze(2),at(2),ve(2,!0),y.step2Result=await tr(y.step1Result,n,o),Zs();const u=document.getElementById("step2-output"),c=xn(y.step2Result);u.textContent=c,u.dataset.raw=c,ve(2,!1),ze(3),at(3),ve(3,!0),y.step3Result=await nr(y.step2Result,y.step1Result),Xs();const d=document.getElementById("step3-output");d.textContent=y.step3Result,ve(3,!1),Mt();const h=Ks(y.step3Result);ar(c,h)}catch(s){if(console.error("Pipeline failed:",s),Mt(),s.isUsageLimit){const{count:c}=bi();Ua(c,sr(),{openModal:!0});return}s.message,zo(document.getElementById("code-generator-model").value);const o=Jm(s,{architect:1,generator:2,review:3});ze(o);const a=document.getElementById(`step${o}-result`),l=document.getElementById(`step${o}-loading`),u=document.getElementById(`step${o}-output`);if(l&&l.classList.add("hidden"),a&&a.classList.remove("hidden"),u)if(s.isModelArmor)u.innerHTML=``;else{let c=s.message;s.message.includes("image input")?c=`This model doesn't support image input. Please use ${Kt(pi)} for image-based requests or remove image references from your prompt.`:(s.message.includes("Load failed")||s.message.includes("CORS"))&&(c="API connection failed. This might be due to CORS restrictions or network issues. Please check your API key and try again."),u.innerHTML=`
    -

    Connection Error

    -

    ${j(c)}

    -
    -

    Check if API key is valid

    -

    Try using a different model

    -

    Ensure network allows API calls

    -
    -
    `}Ho(o,"error")}finally{y.isRunning=!1,i&&(i.disabled=!1,i.innerHTML=` - - - Run Pipeline`),en()}}function a_(){const t=document.getElementById("code-generator-model").value,e=[pi,"anthropic/claude-opus-5","openai/gpt-5.6-sol"].filter(i=>i!==t),n=prompt(`Retry with different model? - -Current: ${t} - -Options: -1. ${e[0]} -2. ${e[1]} - -Enter 1 or 2:`);n==="1"?(document.getElementById("code-generator-model").value=e[0],Ns()):n==="2"&&(document.getElementById("code-generator-model").value=e[1],Ns())}async function l_(){const t=Fa();if(!t){ue("No code to commit. Please run the pipeline first.","warning");return}const e=await Ee("flutterflow"),n=await Ee("flutterflow_project_id");if(!e||!n){ue("FlutterFlow credentials not configured. Add your API Key and Project ID in settings.","warning"),ka();return}if(y.artifactBundle?.artifacts?.length>1){await c_();return}const{artifactType:i,artifactName:s,fileName:r}=oh(),o=dh(t,{artifactType:i,artifactName:s,fileName:r}),a=Gv(o);if(!a.canProceed){ue(`Pre-commit checks failed: ${a.issues.join("; ")}`,"error");return}Wa(o,a,null,null)}async function c_(){const t=await Ee("flutterflow"),e=await Ee("flutterflow_project_id");if(!t||!e){ue("FlutterFlow credentials not configured. Add your API Key and Project ID in settings.","warning"),ka();return}const n=zg(y.artifactBundle);if(n.errors.length>0){ue(`Bundle validation failed: ${n.errors.join("; ")}`,"error");return}const i=new Map(n.fileEntries.map(a=>[a.fileName,{content:a.content,type:a.type,path:a.path}])),s=er(i),r={canProceed:s.valid&&n.errors.length===0,issues:[...n.errors,...s.errors],warnings:[...n.warnings,...s.warnings]};if(!r.canProceed){ue(`Bundle validation failed: ${r.issues.join("; ")}`,"error");return}const o={content:n.fileEntries.map(a=>`// ${a.fileName} -${a.content}`).join(` - -`),fileName:`${n.fileEntries.length} files`,codeType:"bundle",artifactType:"Bundle",artifactName:n.title};Wa(o,r,n.dependencies,n)}function u_(t){let e=t.errorMap||new Map;!(e instanceof Map)&&typeof e=="object"&&(e=new Map(Object.entries(e)));let n=`
    -

    FlutterFlow Commit Failed

    -

    ${j(t.error)}

    `;if(e&&e.size>0){n+=`
    -

    Errors:

    -
      `;for(const[s,r]of e.entries()){const o=Bd(r);n+=`
    • - ${j(s)}: ${j(o)} -
    • `}n+="
    "}n+="
    ",n+=`
    - -
    `;const i=document.getElementById("step3-output");i&&(i.innerHTML=n,document.getElementById("btn-regenerate-from-error")?.addEventListener("click",()=>{d_(t.error,e)}))}async function d_(t,e){if(y.isRunning)return;const n=document.getElementById("code-generator-model").value;y.isRunning=!0;const i=document.getElementById("btn-regenerate-from-error");i&&(i.disabled=!0,i.innerHTML=` - - Fixing...`);try{let s=`The previous code had the following errors when committing to FlutterFlow: - -`;if(e&&e.size>0)for(const[c,d]of e.entries()){const h=Bd(d);s+=`File: ${c} -Error: ${h} - -`}else s+=`${t} -`;const r=$d({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,userFeedback:s});or(),at(2),ze(2),ve(2,!0),y.step2Result=await tr(r,n),Zs();const o=document.getElementById("step2-output"),a=xn(y.step2Result);o.textContent=a,o.dataset.raw=a,ve(2,!1),ze(3),at(3),ve(3,!0),y.step3Result=await nr(y.step2Result,y.step1Result),Xs();const l=document.getElementById("step3-output");l.textContent=y.step3Result,ve(3,!1),Mt();const u=Ks(y.step3Result);ar(a,u)}catch(s){console.error("Regeneration failed:",s),Mt(),ue(La(s,"Regeneration failed"),"error")}finally{y.isRunning=!1,i&&(i.disabled=!1,i.textContent="Fix Errors & Regenerate"),en()}}async function h_(){const t=document.getElementById("ff-status-dot"),e=document.getElementById("ff-status-text");if(!t||!e)return;const n=await Ee("flutterflow"),i=await Ee("flutterflow_project_id");n&&i?(t.className="w-2 h-2 rounded-full bg-green-500",e.textContent="FlutterFlow credentials configured",e.className="text-green-600"):n||i?(t.className="w-2 h-2 rounded-full bg-yellow-500",e.textContent="FlutterFlow credentials incomplete",e.className="text-yellow-600"):(t.className="w-2 h-2 rounded-full bg-red-500",e.textContent="FlutterFlow credentials not configured",e.className="text-red-600")}async function p_(t){try{const e=await fetch(`${Ze}/auth/send-magic-link`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:t})});if(!e.ok)throw new Error(`Failed to send magic link: HTTP ${e.status}`);return e.json()}catch(e){throw console.error("sendMagicLink failed:",{email:t,message:e.message,stack:e.stack}),e}}async function f_(t){try{const n=await(await fetch(`${Ze}/auth/verify-magic-link`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:t})})).json();if(n.error||!n.email||!n.sessionToken)throw new Error(n.error||"Invalid or expired link");return n}catch(e){throw console.error("verifyMagicLink failed:",{message:e.message,stack:e.stack}),e}}async function g_(t){try{const e=await fetch(`${Ze}/auth/refresh-session`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:t})});if(!e.ok)return console.error("refreshSession: non-OK response",{url:`${Ze}/auth/refresh-session`,status:e.status}),null;const n=await e.json();return n.error||!n.email||!n.sessionToken?(console.warn("refreshSession: validation failed",{error:n.error,hasEmail:!!n.email,hasToken:!!n.sessionToken}),null):n}catch(e){return console.error("refreshSession: fetch failed",{url:`${Ze}/auth/refresh-session`,message:e.message,stack:e.stack}),null}}function Nc(t,e){const n=hh(),i=(V.email||n.email)!==t;V.email=t,V.sessionToken=e,V.isVerified=!0,pe=kn({isLoading:!0}),localStorage.setItem(Is,JSON.stringify({email:t,sessionToken:e})),i&&Ha()}function Ba(){V.email=null,V.sessionToken=null,V.isVerified=!1,pe=kn({isResolved:!0}),localStorage.removeItem(Is),localStorage.removeItem(As)}function hh(){try{const t=localStorage.getItem(Is);if(!t)return{email:null,sessionToken:null};const e=JSON.parse(t);return!e.email||!e.sessionToken?{email:null,sessionToken:null}:e}catch(t){return console.warn("getStoredSession: failed to parse auth session:",t),localStorage.removeItem(Is),{email:null,sessionToken:null}}}async function m_(){const e=new URLSearchParams(window.location.search).get("token");if(e){window.history.replaceState({},"",window.location.pathname+window.location.hash);try{const{email:n,sessionToken:i}=await f_(e);Nc(n,i)}catch(n){ue(n.message||"Sign-in link invalid or expired.","error")}}else{const{email:n,sessionToken:i}=hh();if(n&&i){const s=await g_(i);s?Nc(s.email,s.sessionToken):Ba()}}ja()}function Da(){const t=document.getElementById("signin-modal");t&&Ve(t)}function v_(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("signin-modal");e&&Xe(e)}async function __(){const t=document.getElementById("signin-email-input"),e=document.getElementById("signin-submit-btn"),n=document.getElementById("signin-message"),i=zs(t?.value);if(!i||!/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/.test(i)||i.length>254){n&&(n.textContent="Please enter a valid email address.");return}e&&(e.disabled=!0,e.textContent="Sending…");const r=Dd(i);n&&r&&(n.textContent=r);try{const o=await p_(i);t&&o?.code!==Ki&&(t.value=""),n&&(n.textContent=Em(o,i)),e&&(e.textContent=o?.code===Ki?"Send Link":"Sent!"),e&&o?.code===Ki&&(e.disabled=!1)}catch(o){console.error("handleMagicLinkRequest: sendMagicLink failed",{email:i,err:o}),n&&(n.textContent="Something went wrong. Please try again."),e&&(e.disabled=!1,e.textContent="Send Link")}}function y_(){Ba(),Ha(),ja(),rr()}function ja(){const t=V.isVerified&&!!V.email,e=document.getElementById("auth-signedout"),n=document.getElementById("auth-signedin"),i=document.getElementById("auth-guest-usage");e&&e.classList.toggle("hidden",t),n&&n.classList.toggle("hidden",!t),i&&i.classList.toggle("hidden",t);const s=document.getElementById("auth-user-email");s&&(s.textContent=V.email||""),Qi(),rr()}async function ph(){try{if(typeof FingerprintJS>"u"){console.warn("resolveIdentity: FingerprintJS not loaded, skipping");return}const e=await(await FingerprintJS.load()).get(),n=e.visitorId,i=await fetch(cv,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({fingerprint:e.visitorId,cookie_id:n})});if(!i.ok)throw new Error(`Identity check HTTP ${i.status}`);const s=await i.json();if(Ke.userId=s.user_id,Ke.token=s.identity_token||null,Ke.status=s.status,Ke.resolved=!0,sessionStorage.setItem(av,s.user_id),Ke.token&&sessionStorage.setItem(lv,Ke.token),s.usage_count!==void 0){const r=Rt(),a=(s.usage_month||r)===r?s.usage_count:0;localStorage.setItem(Zt,JSON.stringify({count:a,month:r})),ii()}console.log(`Identity resolved: ${s.status} (${s.user_id.slice(0,8)}...) usage: ${s.usage_count??"n/a"}`)}catch(t){console.error("resolveIdentity failed:",t)}}let Ur=null;function w_(t=5e3){return Ke.resolved?Promise.resolve():(Ur||(Ur=ph().catch(e=>{console.warn("ensureIdentityReady: identity resolution failed",e)})),Promise.race([Ur,new Promise(e=>setTimeout(e,t))]))}function fh(){const t=Rt();try{const e=localStorage.getItem(Zt);return e?JSON.parse(e):{count:0,month:t}}catch(e){return console.warn("getUsageData: failed to parse usage storage",{key:Zt,month:t,err:e}),localStorage.removeItem(Zt),{count:0,month:t}}}function Rt(){const t=new Date;return`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,"0")}`}function bi(){const t=fh();return t.month!==Rt()?{count:0,month:Rt()}:t}function b_(){const e={count:bi().count+1,month:Rt()};return localStorage.setItem(Zt,JSON.stringify(e)),e}function ir(){return!!pe.isLoading}function Nt(){return!!pe.isResolved}function E_(t){if(!t)return null;const e=String(t).toLowerCase().replace(/[^a-z0-9]+/g,"_");return e==="pro"||e==="professional_plan"?"professional":e==="power_developer"||e==="power_plan"?"power":Object.prototype.hasOwnProperty.call(Cs,e)?e:null}function S_(t){return t&&Object.entries(Gd).find(([,e])=>e===t)?.[0]||null}function Di(...t){return t.find(e=>e!=null&&e!=="")}function x_(...t){return t.find(e=>e&&typeof e=="object")||{}}function k_(t){const e=t.data&&typeof t.data=="object"?t.data:t,n=x_(e.subscription,e.stripeSubscription,e.currentSubscription,e.customer?.subscriptions?.data?.[0],e.subscriptions?.data?.[0],e.subscriptions?.[0]),i=e.metadata||n.metadata||e.customer?.metadata||{},s=Di(e.priceId,e.price_id,e.stripePriceId,e.stripe_price_id,n.priceId,n.price_id,n.plan?.id,n.price?.id,n.items?.data?.[0]?.price?.id,n.items?.[0]?.price?.id,n.lines?.data?.[0]?.price?.id),r=Di(e.status,e.subscriptionStatus,e.subscription_status,n.status,"none"),o=E_(Di(e.tier,e.plan,e.planId,e.plan_id,e.subscriptionTier,e.subscription_tier,e.product,e.productName,n.tier,n.plan,i.tier,i.plan)),a=uv.has(String(r).toLowerCase()),l=e.active===!0||e.isSubscribed===!0||e.subscribed===!0||e.hasSubscription===!0,u=o||S_(s)||(a||l?"professional":"free");return kn({tier:u,status:r,periodEnd:Di(e.periodEnd,e.currentPeriodEnd,e.current_period_end,n.current_period_end,n.periodEnd,null),isResolved:!0})}function sr(){return Cs[pe.tier]??Cs.free}async function I_(){if(V.isVerified&&(!Nt()||ir())&&(await gh({force:!0}),rr()),V.isVerified&&!Nt())return ue("Could not verify your subscription. Please refresh or try Manage billing.","error"),!1;const{count:t}=bi(),e=sr();if(t>=e)return Ua(t,e,{openModal:!0}),!1;const n=Math.floor(e*.8);if(t>=n){const i=e-t;ue(`${i} run${i===1?"":"s"} remaining this month.`,"warning")}return!0}function Hr(){const t=document.getElementById("paywall-exhausted");t&&t.classList.add("hidden")}function Ua(t,e,n={}){An(!0);const i=document.getElementById("walkthrough-modal");i&&Xe(i,{restoreFocus:!1});const s=document.getElementById("ready-state");s&&s.classList.add("hidden");const r=document.getElementById("preview-frame-container");r&&(r.style.display="none");const o=document.getElementById("main-stage-container");o&&o.classList.add("visible");const a=document.getElementById("results-view");a&&a.classList.remove("visible"),document.body.classList.remove("results-fullscreen","results-with-sidebar");const l=document.getElementById("pipeline-progress");l&&l.classList.remove("visible");const u=document.getElementById("paywall-exhausted");if(!u){ue(`You've used all ${e} runs for this month. Upgrade to continue.`,"error"),Ls();return}const c=document.getElementById("paywall-exhausted-text");if(c){const h=pe.tier;h==="free"?c.textContent=`You've used all ${e} free generations this month. Upgrade to Pro for 50 generations/month and access to all AI models.`:c.textContent=`You've used all ${e} generations this month on your ${h} plan. Your limit resets next month.`}const d=document.getElementById("paywall-signin-btn");d&&d.classList.toggle("hidden",V.isVerified),u.classList.remove("hidden"),n.openModal&&Ls()}function zo(t){return pe.tier==="free"&&Ji.includes(t)?pi:t}function C_(){const t=document.getElementById("code-options-content"),e=document.getElementById("code-generator-model");if(!t||!e)return;const n=pe.tier,s=!(V.isVerified&&!Nt())&&n==="free";Array.from(e.options).forEach(o=>{const a=Kt(o.value),l=Ji.includes(o.value);o.textContent=l&&s?`${a} (PRO)`:a,o.disabled=!1}),s&&Ji.includes(e.value)&&(e.value=pi),e.disabled=!1,Ic.has(e)||(e.addEventListener("change",()=>{Nt()&&pe.tier==="free"&&Ji.includes(e.value)&&(e.value=pi,Ls()),Wo(e.value),Jd()}),Ic.add(e));let r=document.getElementById("model-selector-free-notice");s?(r||(r=document.createElement("p"),r.id="model-selector-free-notice",r.className="text-xs text-gray-400 mt-1",t.appendChild(r)),r.innerHTML='Free plan — Gemini only. '):r&&r.remove(),Wo(e.value)}function ii(){const t=document.getElementById("usage-counter");if(!t)return;if(V.isVerified&&ir()){t.textContent="Checking plan…",t.className="text-xs text-gray-500",Qi(),Hr();return}if(V.isVerified&&!Nt()){t.textContent="Plan check failed",t.className="text-xs text-red-600 font-medium",Qi(),Hr();return}const{count:e}=bi(),n=sr();t.textContent=`${e} / ${n} runs this month`;const i=n>0?e/n:0;t.className=i>=1?"text-xs text-red-600 font-medium":i>=.8?"text-xs text-yellow-600 font-medium":"text-xs text-gray-500",Qi(),e>=n&&!y.isRunning?Ua(e,n):Hr()}function Qi(){const t=document.getElementById("guest-usage-text");if(!t)return;const e=fh(),n=e.month===Rt()?e.count??0:0,i=Cs.free;t.textContent=`${n} / ${i} generations used`}async function gh(t={}){const e=t.force===!0;if(!V.isVerified||!V.sessionToken){pe=kn({isResolved:!0});return}pe={...pe,isLoading:!0,error:null};const n=localStorage.getItem(As);if(!e&&n)try{const{data:i,email:s,ts:r,version:o}=JSON.parse(n);if(o===Cc&&s===V.email&&Date.now()-r<300*1e3){pe={...i,isLoading:!1,isResolved:i.isResolved!==!1};return}}catch(i){console.warn("Failed to parse subscription cache:",i,"| raw value:",n)}try{const s=await(await fetch(`${Ze}/stripe/get-subscription`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:V.sessionToken,user_id:Ke.userId})})).json();if(s.error){if(["unauthorized","invalid session","expired session"].some(o=>String(s.error).toLowerCase().includes(o))){Ba(),ja();return}pe=kn({isResolved:!1,error:s.error});return}pe=k_(s),localStorage.setItem(As,JSON.stringify({version:Cc,data:pe,email:V.email,ts:Date.now()}))}catch(i){console.error("fetchSubscription failed:",i),pe={...pe,isLoading:!1,isResolved:!1,error:i.message}}}function Ha(){localStorage.removeItem(As)}async function A_(t){if(!V.isVerified||!V.sessionToken){mh(),Da();return}if(!Gd[t]){ue("Invalid plan selected.","error");return}const e=document.getElementById(`checkout-btn-${t}`);e&&(e.disabled=!0,e.textContent="Redirecting…");try{const i=await(await fetch(`${Ze}/stripe/create-checkout-session-intl`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tierId:t,sessionToken:V.sessionToken,currency:Xd()})})).json();if(i.error||!i.url)throw new Error(i.error||"Failed to create checkout session");const{url:s}=i;window.location.href=s}catch(n){console.error("startCheckout failed:",n),e&&(e.disabled=!1,e.textContent="Subscribe"),ue("Could not start checkout. Please try again.","error")}}async function F_(){if(!V.isVerified||!V.sessionToken){Da();return}const t=document.getElementById("manage-billing-btn");t&&(t.disabled=!0,t.textContent="Loading…");try{const n=await(await fetch(`${Ze}/stripe/create-portal-session`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:V.sessionToken})})).json();if(n.error||!n.url)throw new Error(n.error||"Failed to open billing portal");const{url:i}=n;window.location.href=i}catch(e){console.error("openCustomerPortal failed:",e),t&&(t.disabled=!1,t.textContent="Manage billing"),ue("Could not open billing portal. Please try again.","error")}}async function Ms(t,e,n,i={},s=[]){const o=new AbortController,a=setTimeout(()=>o.abort(),12e4);try{const l=await fetch(ov,{method:"POST",headers:{"Content-Type":"application/json",...Ke.token?{Authorization:`Bearer ${Ke.token}`}:{}},signal:o.signal,body:JSON.stringify({user_id:Ke.userId,step:t,model:e,prompt:n,images:s,context:i})}),u=await l.text();let c={};try{c=u?JSON.parse(u):{}}catch{c={}}if(l.status===429){c.serverCount!==void 0&&(localStorage.setItem(Zt,JSON.stringify({count:c.serverCount,month:Rt()})),ii());const p=new Error(c.message||"Monthly usage limit reached. Upgrade to continue.");throw p.isUsageLimit=!0,p}const d=fg(c,t);if(d)throw d;if(console.log(`[BuildShip] ${t} response keys:`,Object.keys(c),"content type:",typeof c.content),!l.ok)throw new Error(`${c.message||c.error||"BuildShip pipeline error"} (HTTP ${l.status})`);if(t==="generator")if(c.usage_status==="success"&&Number.isFinite(c.usage_count)){const p=Rt();(c.usage_month||p)===p&&(localStorage.setItem(Zt,JSON.stringify({count:c.usage_count,month:p})),ii())}else b_(),ii();let h=c.output||c.content;if(!h){const p=u?` (body: ${u.slice(0,120)})`:"";throw new Error(`BuildShip returned no output for step "${t}"${p}`)}return Array.isArray(h)&&(h=h.map(p=>typeof p=="string"?p:p.text||"").join("")),typeof h!="string"&&(h=JSON.stringify(h)),h}catch(l){throw l.name==="AbortError"?new Error(`BuildShip ${t} timed out after ${12e4/1e3}s`):l instanceof TypeError?new Error(`BuildShip unreachable: ${l.message}`):l}finally{clearTimeout(a)}}function P_(){const e=new URLSearchParams(window.location.search).get("checkout");e==="success"?(window.history.replaceState({},"",window.location.pathname+window.location.hash),Ha(),ue("Subscription active! Welcome aboard.","success")):e==="cancel"&&(window.history.replaceState({},"",window.location.pathname+window.location.hash),ue("Checkout cancelled.","info"))}function rr(){const t=V.isVerified&&!!V.email,e=pe.tier,n=t&&ir(),i=!t||Nt(),s=document.getElementById("subscription-tier-badge");if(s){const a={free:"Free",professional:"Professional",power:"Power Developer"},l={free:"bg-gray-100 text-gray-600",professional:"bg-indigo-100 text-indigo-700",power:"bg-purple-100 text-purple-700",unresolved:"bg-red-50 text-red-600"};s.textContent=n?"Checking…":i?a[e]||"Free":"Plan unavailable",s.className=`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${i?l[e]||l.free:l.unresolved}`}const r=document.getElementById("upgrade-prompt");r&&r.classList.toggle("hidden",!t||n||!i||e!=="free");const o=document.getElementById("manage-billing-btn");o&&o.classList.toggle("hidden",!t||n||i&&e==="free"),$_(i?e:null),C_(),Jd(),ii(),xh()}function $_(t){const e=["bg-gray-100","text-gray-500","cursor-default"];Object.entries({professional:{btnId:"checkout-btn-professional",defaultText:"Subscribe"},power:{btnId:"checkout-btn-power",defaultText:"Subscribe"}}).forEach(([s,{btnId:r,defaultText:o}])=>{const a=document.getElementById(r);a&&(s===t?(a.disabled=!0,a.textContent="Current plan",a.classList.add(...e)):(a.disabled=!1,a.textContent=o,a.classList.remove(...e)))});const i=document.getElementById("free-tier-current");i&&i.classList.toggle("hidden",t!=="free")}function qo(){const t=Xd(),e=document.getElementById("pro-price"),n=document.getElementById("power-price"),i=document.getElementById("plans-pro-price"),s=document.getElementById("plans-power-price"),r=document.getElementById("pro-price-note"),o=document.getElementById("power-price-note"),a=document.getElementById("plans-pro-price-note"),l=document.getElementById("plans-power-price-note");e&&(e.textContent=Bi(Oi.professional,t)),n&&(n.textContent=Bi(Oi.power,t)),i&&(i.textContent=Bi(Oi.professional,t)),s&&(s.textContent=Bi(Oi.power,t));const u="billed monthly";r&&(r.textContent=u),o&&(o.textContent=u),a&&(a.textContent=u),l&&(l.textContent=u)}function Ls(){qo();const t=document.getElementById("pricing-modal");t&&Ve(t),yv().then(()=>qo())}function mh(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("pricing-modal");e&&Xe(e)}function ue(t,e="info"){const n={success:"bg-green-600 text-white",error:"bg-red-600 text-white",warning:"bg-amber-500 text-white",info:"bg-gray-800 text-white"},i=document.createElement("div");i.className=`fixed bottom-6 left-1/2 -translate-x-1/2 px-5 py-3 rounded-lg text-sm font-medium shadow-lg z-50 transition-opacity duration-300 ${n[e]||n.info}`,i.textContent=t,document.body.appendChild(i),setTimeout(()=>{i.style.opacity="0",setTimeout(()=>i.remove(),300)},3500)}document.addEventListener("DOMContentLoaded",async()=>{tg(),hljs.configure({tabReplace:" ",classPrefix:"hljs-"}),T_(),await m_(),P_(),await gh(),rr(),qo(),await zv(),Dv();const t=document.getElementById("flutterflow-endpoint-select");if(t){const n=yi();t.value=n}sh(),ph();const e=document.getElementById("pipeline-input");e&&(e.addEventListener("input",()=>{kt===2&&e.value.trim().length>0&&(Ia(),Js())}),e.addEventListener("blur",()=>{const n=document.getElementById("walkthrough-modal");kt===2&&n&&Ve(n)}),e.addEventListener("keydown",n=>{if(n.key==="Tab"){const i=document.getElementById("walkthrough-modal");kt===2&&i&&setTimeout(()=>{Ve(i)},100)}})),window.addEventListener("commitStateChange",n=>{const{state:i}=n.detail;i===K.PREPARING||i===K.VALIDATING||i===K.PUSHING?(be.phaseId||_h(),Lc(i)):(i===K.SUCCESS||i===K.ERROR)&&(Lc(i),setTimeout(Os,1e3))}),sv({onSubmit:Ns}),qa()});function T_(){const t=document.getElementById("preview-frame-container");t&&(t.style.display="")}function R_(){const t=document.getElementById("welcome-video-player");t&&(t.addEventListener("click",Qt),document.addEventListener("keydown",Qt))}function Qt(){const t=document.getElementById("preview-frame-container"),e=document.getElementById("main-stage-container"),n=document.getElementById("ready-state");t&&(t.style.display="none"),e&&e.classList.add("visible"),n&&n.classList.remove("hidden");const i=document.getElementById("welcome-video-player");i&&i.removeEventListener("click",Qt),document.removeEventListener("keydown",Qt),sh()}let si=null;async function N_(){const t=document.getElementById("confirm-project-select");if(!t)return;const e=++Tc,n=()=>e===Tc,i=await Ee("flutterflow"),s=await Ee("flutterflow_project_id");if(n()){if(!i){t.innerHTML='',t.disabled=!0;return}t.disabled=!1,t.innerHTML='';try{const o=await new wi(i,"").listProjects();if(!n())return;if(!o||o.length===0){t.innerHTML='';return}t.innerHTML='',o.forEach(a=>{const l=document.createElement("option");l.value=a.id||a.projectId||"",l.textContent=a.name||a.projectName||`Project ${a.id}`,t.appendChild(l)}),s&&(t.value=s)}catch(r){if(!n())return;console.error("Failed to load projects for deploy:",r),t.innerHTML=''}}}function M_(){return document.getElementById("confirm-project-select")?.value?.trim()||null}function Wa(t,e,n,i=null){si={codeInfo:t,checks:e,deps:n,bundlePlan:i},document.getElementById("confirm-file-name").textContent=t.fileName,document.getElementById("confirm-artifact-type").textContent=t.artifactType,document.getElementById("confirm-file-size").textContent=`${(t.content.length/1024).toFixed(1)} KB`,document.getElementById("confirm-line-count").textContent=i?`${i.fileEntries.length} files`:t.content.split(` -`).length,N_();const s=document.getElementById("confirm-deps-list"),r=document.getElementById("confirm-deps-section");n&&Object.keys(n).length>0?(s.innerHTML=Object.entries(n).map(([u,c])=>{const d=c?`at least ${xt(c)}`:"version resolved from your project";return`
  • • ${xt(u)}: ${d}
  • `}).join(""),r.classList.remove("hidden")):r.classList.add("hidden");const o=document.getElementById("confirm-warnings-list"),a=document.getElementById("confirm-warnings-section");e.warnings&&e.warnings.length>0?(o.innerHTML=e.warnings.map(u=>`
  • • ${xt(u)}
  • `).join(""),a.classList.remove("hidden")):a.classList.add("hidden"),document.getElementById("confirm-code-preview").textContent=t.content,document.getElementById("code-preview-content").classList.add("hidden"),document.getElementById("code-preview-chevron").style.transform="rotate(0deg)";const l=document.getElementById("commit-confirm-modal");l&&Ve(l)}function vh(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("commit-confirm-modal");e&&Xe(e),si=null}function L_(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("commit-success-modal");e&&Xe(e);const n=["success-message","success-project-id","success-file-name","success-artifact-type","success-time","success-size"];for(const r of n){const o=document.getElementById(r);o&&(o.textContent="")}const i=document.getElementById("success-warnings-section");i&&i.classList.add("hidden");const s=document.getElementById("success-warnings-list");s&&(s.innerHTML="")}function Vo(t){const e=(g,m)=>{const v=document.getElementById(g);v&&(v.textContent=m||"")},n=t.metadata?.fileName||"",i=t.metadata?.projectId||"",s=t.metadata?.artifactType||"",r=t.elapsedTime?`${(t.elapsedTime/1e3).toFixed(1)}s`:"",o=t.metadata?.codeSize?`${(t.metadata.codeSize/1024).toFixed(1)} KB`:"";e("success-message",t.message||"Code committed successfully!"),e("success-project-id",i),e("success-file-name",n),e("success-artifact-type",s),e("success-time",r),e("success-size",o);const a=t.addedDependencies||[],l=document.getElementById("success-deps-row");l&&l.classList.toggle("hidden",a.length===0),e("success-deps",a.join(", "));const u=document.getElementById("success-open-ff-link");u&&i&&(u.href=`https://app.flutterflow.io/project/${i}`);const c=document.getElementById("success-warnings-section"),d=document.getElementById("success-warnings-list"),h=t.unverified||[],p=t.warnings||[];(p.length>0||h.length>0)&&c&&d&&(d.innerHTML=[...h.map(g=>`
  • Not verified before deploying: ${j(String(g))}
  • `),...p.map(([g,m])=>`
  • ${j(g)}: ${j(String(m))}
  • `)].join(""),c.classList.remove("hidden"));const f=document.getElementById("commit-success-modal");f&&Ve(f)}function Go(t){Os(),u_(t)}function O_(){const t=document.getElementById("code-preview-content"),e=document.getElementById("code-preview-chevron");t.classList.contains("hidden")?(t.classList.remove("hidden"),e.style.transform="rotate(90deg)"):(t.classList.add("hidden"),e.style.transform="rotate(0deg)")}const Mc={prepare:{message:"Preparing your code...",start:4,end:14},validate:{message:"Checking FlutterFlow credentials...",start:14,end:22},project:{message:"Reading your FlutterFlow project...",start:22,end:40},provision:{message:"Creating custom classes in FlutterFlow...",start:40,end:82},package:{message:"Packaging files for upload...",start:82,end:88},push:{message:"Pushing to FlutterFlow...",start:88,end:97},done:{message:"Complete!",start:100,end:100}},B_=[{after:0,text:"Starting a FlutterFlow build runner..."},{after:12,text:"Preparing the FlutterFlow AI workspace..."},{after:35,text:"Uploading your custom classes..."},{after:60,text:"FlutterFlow is applying the changes..."},{after:100,text:"Still working — this can take a couple of minutes..."}],be={sequence:[],phaseId:null,phaseStartedAt:null,timer:null,substatus:null,liveSubstatus:!1,start({withProvisioning:t=!1}={}){this.sequence=["prepare","validate","project"],t&&this.sequence.push("provision"),this.sequence.push("package","push","done");const e=document.getElementById("commit-progress-overlay");e&&(oc(e,!0,"Deploying to FlutterFlow"),Ve(e)),this.set("prepare")},set(t,e=null){if(!(!Mc[t]||t===this.phaseId)){if(!this.sequence.includes(t)){const n=this.sequence.indexOf("package");this.sequence.splice(n===-1?this.sequence.length:n,0,t)}this.phaseId=t,this.phaseStartedAt=Date.now(),this.substatus=e,this.liveSubstatus=!1,this.render(),this.timer&&clearInterval(this.timer),t!=="done"&&(this.timer=setInterval(()=>this.render(),500))}},setSubstatus(t){t&&(this.liveSubstatus=!0,this.substatus=t,this.render())},render(){const t=Mc[this.phaseId];if(!t)return;const e=(Date.now()-this.phaseStartedAt)/1e3,n=t.start+(t.end-t.start)*(1-Math.exp(-e/25));if(this.phaseId==="provision"&&!this.liveSubstatus){const o=B_.filter(a=>e>=a.after).pop();o&&(this.substatus=o.text)}const i=this.sequence.indexOf(this.phaseId),r=[`Step ${i===-1?1:i+1} of ${this.sequence.length}`];e>=5&&r.push(D_(e)),yh(this.phaseId==="done"?100:n,t.message,r.join(" · "),this.substatus)},stop(){this.timer&&clearInterval(this.timer),this.timer=null,this.phaseId=null;const t=document.getElementById("commit-progress-overlay");t&&(oc(t,!1),Xe(t,{force:!0,restoreFocus:!1}))}};function D_(t){const e=Math.floor(t);return e<60?`${e}s elapsed`:`${Math.floor(e/60)}m ${String(e%60).padStart(2,"0")}s elapsed`}function _h(t){be.start(t)}function Os(){be.stop()}function yh(t,e,n,i=null){const s=document.getElementById("commit-progress-bar"),r=document.getElementById("progress-message"),o=document.getElementById("progress-detail"),a=document.getElementById("progress-substatus");s&&(s.style.width=`${Math.round(t*10)/10}%`),r&&(r.textContent=e),o&&(o.textContent=n),a&&(a.textContent=i||"",a.classList.toggle("hidden",!i))}function Lc(t){const e={[K.PREPARING]:"prepare",[K.VALIDATING]:"validate",[K.PUSHING]:"project",[K.SUCCESS]:"done"};if(t===K.ERROR){be.timer&&clearInterval(be.timer),be.timer=null,yh(100,"Failed","Error occurred");return}const n=e[t];n&&be.set(n)}function j_(t){return t.bundlePlan?t.bundlePlan.fileEntries.some(e=>e.type===W.CODE_FILE):t.codeInfo?.codeType===W.CODE_FILE}async function U_(){if(!si){console.error("No pending commit data");return}const t=si;if(si=null,ni=M_(),vh(),_h({withProvisioning:j_(t)}),t.bundlePlan){const o=await Qv(t.bundlePlan,{pipelineResult:{step1Result:y.step1Result,selectedModel:document.getElementById("code-generator-model")?.value}});ni=null,Os(),o.success?Vo(o):Go(o);return}const{codeInfo:e}=t,{artifactType:n,artifactName:i,fileName:s}=oh(),r=await Xv(e.content,{artifactType:n,artifactName:i,fileName:s,pipelineResult:{step1Result:y.step1Result,selectedModel:document.getElementById("code-generator-model")?.value}});ni=null,Os(),r.success?Vo(r):Go(r)}window.runThinkingPipeline=Ns;window.toggleStep=n_;window.toggleSection=t_;window.selectWorkflowStep=ze;window.copyCode=i_;window.retryWithDifferentModel=a_;window.openApiKeysModal=ka;window.closeApiKeysModal=nh;window.closeWalkthroughModal=Rv;window.openWalkthroughModal=Tv;window.advanceWalkthrough=Ia;window.commitToFlutterFlow=Zv;function H_(){const t=document.getElementById("pipeline-input");t&&t.focus()}function W_(){const t=document.getElementById("advanced-settings");t&&(t.open=!0);const e=document.getElementById("code-generator-model");e&&(e.scrollIntoView({behavior:"smooth",block:"center"}),e.focus(),e.click())}window.focusPromptInput=H_;window.openModelSelector=W_;window.handlePromptImageSelect=vv;window.removePromptImage=_v;window.saveApiKeys=Lv;window.clearAllApiKeys=Ov;window.toggleKeyVisibility=Uv;window.handleWelcomeVideoEnd=R_;window.dismissWelcomeVideo=Qt;window.initiateCommitToFlutterFlow=l_;window.updateFlutterFlowCredentialStatus=h_;window.openCommitConfirmModal=Wa;window.closeCommitConfirmModal=vh;window.closeCommitSuccessModal=L_;window.showCommitSuccessModal=Vo;window.showCommitFailureModal=Go;window.toggleCodePreview=O_;window.confirmCommitToFlutterFlow=U_;window.runRefinement=s_;window.regenerateFromPastedErrors=o_;window.clearErrorInput=r_;window.setFlutterFlowEndpoint=$v;window.getFlutterFlowEndpoint=yi;window.commitProgress=be;window.openSignInModal=Da;window.closeSignInModal=v_;window.handleMagicLinkRequest=__;window.handleSignOut=y_;window.startCheckout=A_;window.openCustomerPortal=F_;window.openPricingModal=Ls;window.closePricingModal=mh;let mn=null,wh=null;const Oc=120;function or(){An(!0);const t=document.getElementById("pipeline-progress"),e=document.getElementById("results-view"),n=document.getElementById("ready-state");n&&n.classList.add("hidden"),e&&e.classList.remove("visible"),document.body.classList.remove("results-fullscreen","results-with-sidebar"),t&&t.classList.add("visible"),wh=Date.now();for(let i=1;i<=3;i++){const s=document.getElementById(`pdot-${i}`);s&&(s.className="progress-dot")}at(1),z_()}function at(t){const e={1:"Analyzing your prompt...",2:"Generating Dart code...",3:"Running code audit..."},n={1:"Step 1 of 3 — Prompt Architect",2:"Step 2 of 3 — Code Generator",3:"Step 3 of 3 — Code Review"},i=document.getElementById("progress-title-text"),s=document.getElementById("progress-substep-text");i&&(i.textContent=e[t]||e[1]),s&&(s.textContent=n[t]||n[1]);for(let r=1;r<=3;r++){const o=document.getElementById(`pdot-${r}`);o&&(r{const t=(Date.now()-wh)/1e3,e=document.getElementById("progress-elapsed"),n=document.getElementById("pipeline-progress-fill");e&&(e.textContent=`${Math.floor(t)}s`);const i=t/Oc*100,s=Math.min(95,i*(1-Math.exp(-t/(Oc*.6)))*1.2);n&&(n.style.width=`${s}%`)},250)}function Mt(){mn&&(clearInterval(mn),mn=null);const t=document.getElementById("pipeline-progress-fill");t&&(t.style.width="100%");for(let e=1;e<=3;e++){const n=document.getElementById(`pdot-${e}`);n&&(n.className="progress-dot completed")}setTimeout(()=>{const e=document.getElementById("pipeline-progress");e&&e.classList.remove("visible"),t&&(t.style.width="0%")},400)}function Cn(t,e=""){const n={pass:'',warning:'',fail:'',info:''};return``}function bh(t){return{pass:"Passed review",warning:"Needs attention",fail:"Blocking issues"}[t]||"Needs attention"}function q_(){return om({bundle:y.artifactBundle,reviewResult:y.step3Result})}function V_(t){return` -
    - ${Cn(t.severity)} -
    -
    ${j(t.message)}
    - ${t.suggestion?`
    ${j(t.suggestion)}
    `:""} - ${j(t.source)} -
    -
    - `}function G_(t){return` -
  • -
    - ${j(t.title)} - ${t.detail&&t.detail!==t.title?`

    ${j(t.detail)}

    `:""} -
    -
  • - `}function K_(t){const e=document.getElementById("results-summary-detail"),n=document.getElementById("results-title");if(!e)return;n&&(n.textContent=t.title);const i=t.score,s=i==null?"neutral":i>=80?"pass":i>=60?"warning":"fail",r=i==null?"":i>=80?"Strong":i>=60?"Needs work":"High risk",o=t.findings.length?` -
      - ${t.findings.map(l=>` -
    • - ${Cn(l.severity)} - - ${j(l.message)} - ${l.suggestion?`${j(l.suggestion)}`:""} - -
    • - `).join("")} -
    - `:"",a=t.manualSteps.length?` -
    -

    ${Cn("info")} Complete in FlutterFlow

    -

    For your information — these don't block the deploy. Finish them by hand in the FlutterFlow editor once the code is pushed.

    -
      - ${t.manualSteps.map(l=>` -
    • - ${j(l.title)} - ${l.detail&&l.detail!==l.title?`${j(l.detail)}`:""} -
    • - `).join("")} -
    -
    - `:"";e.innerHTML=` -
    -
    -

    ${j(t.summary)}

    - ${o} - ${a} -
    -
    - -
    - Is the generated code correct? -
    - - -
    -
    -
    -
    - `}function J_(t){const e=t.artifacts.find(l=>l.id===y.selectedArtifactId)||t.artifacts[0];if(!e)return"";const n={pass:{icon:"pass",message:"No file-specific issues were found."},warning:{icon:"warning",message:"This file needs attention, but Code Review did not return a specific finding."},fail:{icon:"fail",message:"This file is blocked, but Code Review did not return a specific finding."}}[e.status],i=e.findings.length?e.findings.map(V_).join(""):`
    ${Cn(n.icon)} ${j(n.message)}
    `,s=e.dependencies?.length?e.dependencies.map(l=>` -
  • ${j(l.name)}${l.version?` ${j(l.version)}`:""}${l.reason?`

    ${j(l.reason)}

    `:""}
  • - `).join(""):'
  • No external packages
  • ',r=e.imports?.length?e.imports.map(l=>`${j(l)}`).join(""):'No imports returned',o=e.publicApi?.length?e.publicApi.map(l=>`${j(l)}`).join(""):'No public API signature returned',a=e.relationships.length?e.relationships.map(l=>` -
  • ${j(l.from||"Bundle")} ${j(l.type)} ${j(l.to||"Bundle")}${l.description?`

    ${j(l.description)}

    `:""}
  • - `).join(""):'
  • No relationships for this file
  • ';return` -
    -
    - ${Cn(e.status)} ${j(bh(e.status))} -

    ${j(e.artifactName)}

    - ${e.description?`

    ${j(e.description)}

    `:""} -
    -
    - ${j(e.artifactType)} - ${j(e.fileName)} -
    -
    -
    -

    Code Review findings

    - ${i} -
    - ${e.manualSteps.length?` -
    -

    Manual FlutterFlow steps for this file

    -
      ${e.manualSteps.map(G_).join("")}
    -
    - `:""} -
    - File details -
    -
    -

    Dependencies

    -
      ${s}
    -
    -
    -

    Deployment

    -
    -
    Status
    ${j(e.deployStatus||"pending")}
    -
    Order
    ${e.index+1} of ${t.artifacts.length}
    -
    Path hint
    ${j(e.pathHint||"Not returned")}
    -
    -
    -
    -
    -

    Public API

    -
    ${o}
    -
    -
    -

    Imports

    -
    ${r}
    -
    -
    -

    Relationships

    -
      ${a}
    -
    -
    - `}function Y_(t){const e=document.getElementById("bundle-strip"),n=document.getElementById("results-summary-tab"),i=document.getElementById("artifact-tabs"),s=document.getElementById("results-file-count");if(n&&n.classList.toggle("active",y.resultsViewMode==="summary"),!t.artifacts.length){s&&(s.textContent="0 files"),e&&e.classList.remove("visible"),i&&(i.innerHTML="");return}if(s){const r=t.artifacts.length;s.textContent=`${r} ${r===1?"file":"files"}`}i&&(i.innerHTML=t.artifacts.map(r=>` - - `).join(""),i.onclick=r=>{const o=r.target.closest(".artifact-tab");o?.dataset?.artifactId&&Eh(o.dataset.artifactId)}),e&&e.classList.add("visible")}function za(){document.body.classList.add("results-fullscreen"),document.body.classList.add("results-with-sidebar");const t=document.getElementById("results-view"),e=document.getElementById("results-code-output"),n=document.getElementById("results-audit-output"),i=document.getElementById("results-summary-detail"),s=document.getElementById("artifact-results-split"),r=q_(),o=Fa();if(K_(r),Y_(r),e&&(e.textContent=""),e){const a=Vd(o);e.innerHTML=a}n&&(n.innerHTML=J_(r)),i&&i.classList.toggle("hidden",y.resultsViewMode!=="summary"),s&&s.classList.toggle("hidden",y.resultsViewMode!=="file"),t&&t.classList.add("visible")}function ar(t,e){An(!0),y.selectedArtifactId||(y.selectedArtifactId=Ss(y.artifactBundle).id),y.resultsViewMode="summary",document.body.classList.add("results-fullscreen");const n=document.getElementById("step3-output");n&&(n.textContent=""),za(),en();const i=document.getElementById("btn-feedback-up"),s=document.getElementById("btn-feedback-down");i&&(i.className="feedback-btn"),s&&(s.className="feedback-btn")}function Eh(t){y.selectedArtifactId=t,y.resultsViewMode="file",za()}function Z_(){y.resultsViewMode="summary",za()}function X_(){const t=document.getElementById("btn-copy-results"),e=Fa();navigator.clipboard.writeText(e).then(()=>{if(t){t.classList.add("copied");const n=t.querySelector("span");if(n){const i=n.textContent;n.textContent="Copied!",setTimeout(()=>{t.classList.remove("copied"),n.textContent=i},2e3)}}})}function Q_(t){const e=document.getElementById("btn-feedback-up"),n=document.getElementById("btn-feedback-down");t==="up"?(e.classList.toggle("active-up"),n.classList.remove("active-down")):(n.classList.toggle("active-down"),e.classList.remove("active-up")),Oa(t==="up"?"thumbsUp":"thumbsDown",y.step2Result,y.step1Result)}function ey(){const t=document.getElementById("error-input-panel");if(t){t.classList.remove("hidden"),t.style.display="flex";const e=document.getElementById("ff-error-paste-input");e&&setTimeout(()=>e.focus(),100)}}function Sh(){const t=document.getElementById("error-input-panel");t&&(t.classList.add("hidden"),t.style.display="none")}function An(t){const e=document.getElementById("generation-stage");e&&(t?(e.hidden=!1,e.inert=!1,requestAnimationFrame(()=>e.classList.add("is-active"))):(e.classList.remove("is-active"),e.inert=!0,setTimeout(()=>{e.classList.contains("is-active")||(e.hidden=!0)},260)))}function xh(){const t=V.isVerified&&!!V.email,e=pe.tier||"free",n=t&&ir(),i=!t||Nt(),r=n?"Checking…":i?{free:"Free",professional:"Pro",power:"Power"}[e]||"Free":"—",o=document.getElementById("topbar-plan");o&&(o.textContent=r);const a=document.getElementById("topbar-avatar");a&&(a.textContent=(V.email||"?")[0].toUpperCase());const l=bi(),u=`${l.count} / ${sr()} runs this month`,c=document.getElementById("topbar-credits-count");c&&(c.textContent=String(l.count));const d=document.getElementById("credits-balance");d&&(d.textContent=u);const h=document.getElementById("plans-free-current");h&&h.classList.toggle("hidden",e!=="free"||!i);const p=document.getElementById("plans-checkout-btn-professional");if(p){const g=e==="professional"&&i;p.disabled=g,p.textContent=g?"Current plan":"Subscribe"}const f=document.getElementById("plans-checkout-btn-power");if(f){const g=e==="power"&&i;f.disabled=g,f.textContent=g?"Current plan":"Subscribe"}}function ty(){xh();const t=document.getElementById("credits-modal");t&&Ve(t)}function ny(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("credits-modal");e&&Xe(e)}function kh(t,e=!0,n=!0){if(t=["home","account","plans"].includes(t)?t:"home",document.querySelectorAll(".view[data-view]").forEach(s=>{s.dataset.view===t?(s.hidden=!1,s.removeAttribute("inert"),requestAnimationFrame(()=>{s.classList.add("is-active"),n&&s.focus({preventScroll:!0})})):(s.classList.remove("is-active"),s.setAttribute("inert","true"),setTimeout(()=>{s.classList.contains("is-active")||(s.hidden=!0)},260))}),t!=="home")An(!1);else{const s=document.getElementById("main-stage-container");s&&s.classList.contains("visible")&&An(!0)}if(document.querySelectorAll(".nav-link[data-view]").forEach(s=>{const r=s.dataset.view===t;s.setAttribute("aria-current",r?"page":null),r||s.removeAttribute("aria-current")}),e){const s=t==="home"?"":`#${t}`;window.location.hash!==s&&window.history.pushState({view:t},"",s||"#")}}let Bc=!1;function qa(){const t=window.location.hash.replace(/^#/,"");kh(t||"home",!1,Bc),Bc=!0}window.addEventListener("popstate",t=>{qa()});window.addEventListener("hashchange",()=>{qa()});window.copyResultsCode=X_;window.selectArtifact=Eh;window.selectResultsSummary=Z_;window.submitResultsFeedback=Q_;window.showErrorInputPanel=ey;window.hideErrorInputPanel=Sh;window.setGenerationStageVisible=An;window.switchView=kh;window.openCreditsModal=ty;window.closeCreditsModal=ny; diff --git a/dist/index.html b/dist/index.html index 6edf0d0..6633c19 100644 --- a/dist/index.html +++ b/dist/index.html @@ -2697,6 +2697,20 @@ cursor: pointer; } .icon-btn svg { width: 18px; height: 18px; } + .prompt-image-upload { + display: flex; + align-items: center; + gap: 4px; + } + .prompt-image-upload.hidden { display: none; } + .prompt-image-thumbnails { + display: flex; + align-items: center; + gap: 4px; + } + .prompt-image-thumbnails:empty { display: none; } + .composer .prompt-img-thumb { width: 40px; height: 40px; border-radius: 8px; } + .composer .prompt-img-remove { width: 16px; height: 16px; top: 2px; right: 2px; font-size: 11px; } .icon-btn:hover { background: oklch(95% 0.01 260); color: var(--fg); } .send { position: absolute; @@ -2862,7 +2876,7 @@ .send.is-busy .send-spin { animation: none; opacity: 0.6; } } - + @@ -2907,18 +2921,22 @@

    FlutterFlow custom code.
    - +
    + +
    + +
    -
    - +
    + +
    + +
    - `,t.appendChild(s)}),e&&(e.textContent=Tt.length>=Lo?"Image limit reached":"Add images"))}function Jd(){const t=document.getElementById("prompt-image-upload");if(!t)return;const e=document.getElementById("code-generator-model"),n=Kd(e?.value);t.classList.toggle("hidden",!n),!n&&Tt.length&&(Tt=[],ba())}const Zt="ccc_usage",Yd="google/gemini-3.7-flash",Zd="google/gemini-3.7-flash",jr="google/gemini-3.7-flash",Oi={professional:11,power:49},Oo={en_US:"USD",en_GB:"GBP",en_AU:"AUD",en_NZ:"NZD",en_CA:"CAD",en_IN:"INR",en_SG:"SGD",en_HK:"HKD",en_PH:"PHP",en_ZA:"ZAR",en:"USD",de:"EUR",fr:"EUR",es:"EUR",it:"EUR",nl:"EUR",pt_PT:"EUR",pt_BR:"BRL",pt:"BRL",ja:"JPY",ko:"KRW",zh_CN:"CNY",zh_TW:"TWD",zh:"CNY",th:"THB",vi:"VND",id:"IDR",ms_MY:"MYR",ms:"MYR",sv:"SEK",nb:"NOK",da:"DKK",pl:"PLN",cs:"CZK",hu:"HUF",ro:"RON",tr:"TRY",ar:"AED",he:"ILS",ru:"RUB",uk:"UAH"},Yi={AUD:1,USD:.65,EUR:.6,GBP:.52,CAD:.88,NZD:1.08,JPY:97,KRW:870,INR:54,SGD:.87,HKD:5.08,BRL:3.18,CNY:4.7,TWD:20.5,THB:22.5,VND:16200,IDR:10200,MYR:2.88,SEK:6.8,NOK:6.95,DKK:4.48,PLN:2.6,CZK:15.2,HUF:238,RON:2.98,TRY:20.9,AED:2.39,ILS:2.38,PHP:36.4,ZAR:11.8,RUB:58,UAH:26.8,CHF:.57,MXN:11.1,ARS:580,CLP:610,COP:2700,PEN:2.44};let Zi={...Yi};async function yv(){const t=new AbortController,e=setTimeout(()=>t.abort(),5e3);try{const n=await fetch("https://open.er-api.com/v6/latest/AUD",{signal:t.signal});if(!n.ok)return;const i=await n.json();if(i.result!=="success"||!i.rates)return;const s=i.rates,r={AUD:1},o=new Set([...Object.keys(Yi),...Object.values(Bo),...Object.values(Oo)]);for(const a of o)a!=="AUD"&&(typeof s[a]=="number"&&s[a]>0?r[a]=s[a]:Yi[a]&&(r[a]=Yi[a]));Zi=r}catch{}finally{clearTimeout(e)}}const Bo={"America/Sao_Paulo":"BRL","America/Fortaleza":"BRL","America/Recife":"BRL","America/Bahia":"BRL","America/Belem":"BRL","America/Manaus":"BRL","America/Cuiaba":"BRL","America/Campo_Grande":"BRL","America/Araguaina":"BRL","America/Noronha":"BRL","America/Rio_Branco":"BRL","America/Porto_Velho":"BRL","America/Boa_Vista":"BRL","America/Maceio":"BRL","America/Santarem":"BRL","America/Eirunepe":"BRL","Europe/London":"GBP","Europe/Paris":"EUR","Europe/Berlin":"EUR","Europe/Madrid":"EUR","Europe/Rome":"EUR","Europe/Amsterdam":"EUR","Europe/Brussels":"EUR","Europe/Vienna":"EUR","Europe/Lisbon":"EUR","Europe/Dublin":"EUR","Europe/Helsinki":"EUR","Europe/Athens":"EUR","Europe/Bucharest":"RON","Europe/Budapest":"HUF","Europe/Warsaw":"PLN","Europe/Prague":"CZK","Europe/Copenhagen":"DKK","Europe/Stockholm":"SEK","Europe/Oslo":"NOK","Europe/Zurich":"CHF","Europe/Istanbul":"TRY","Europe/Moscow":"RUB","Europe/Kiev":"UAH","Europe/Kyiv":"UAH","Asia/Tokyo":"JPY","Asia/Seoul":"KRW","Asia/Shanghai":"CNY","Asia/Taipei":"TWD","Asia/Hong_Kong":"HKD","Asia/Singapore":"SGD","Asia/Kolkata":"INR","Asia/Calcutta":"INR","Asia/Bangkok":"THB","Asia/Ho_Chi_Minh":"VND","Asia/Jakarta":"IDR","Asia/Kuala_Lumpur":"MYR","Asia/Dubai":"AED","Asia/Jerusalem":"ILS","Asia/Tel_Aviv":"ILS","Asia/Manila":"PHP","Pacific/Auckland":"NZD","Australia/Sydney":"AUD","Australia/Melbourne":"AUD","Australia/Brisbane":"AUD","Australia/Perth":"AUD","Australia/Adelaide":"AUD","Australia/Hobart":"AUD","Australia/Darwin":"AUD","Australia/Lord_Howe":"AUD","America/Toronto":"CAD","America/Vancouver":"CAD","America/Edmonton":"CAD","America/Winnipeg":"CAD","America/Halifax":"CAD","America/St_Johns":"CAD","America/Regina":"CAD","America/New_York":"USD","America/Chicago":"USD","America/Denver":"USD","America/Los_Angeles":"USD","America/Phoenix":"USD","America/Anchorage":"USD","Pacific/Honolulu":"USD","America/Mexico_City":"MXN","America/Cancun":"MXN","America/Tijuana":"MXN","America/Argentina/Buenos_Aires":"ARS","America/Santiago":"CLP","America/Bogota":"COP","America/Lima":"PEN","Africa/Johannesburg":"ZAR"};function Xd(){try{const r=Intl.DateTimeFormat().resolvedOptions().timeZone;if(r&&Bo[r])return Bo[r]}catch{}const e=(navigator.language||"en-US").replace("-","_"),n=Oo[e];if(n)return n;const i=e.split("_")[0],s=Oo[i];return s||"USD"}function Bi(t,e){const n=Zi[e]??Zi.USD,i=t*n,s=Math.round(i*100)/100;try{return new Intl.NumberFormat("en-US",{style:"currency",currency:e,minimumFractionDigits:0,maximumFractionDigits:s>=100||s%1===0?0:2}).format(s)}catch{return new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",minimumFractionDigits:0,maximumFractionDigits:2}).format(t*Zi.USD)}}const rt="ccc_api_key_",bt="ccc_session_api_key_",lt="ccc_encryption_key",fi="ccc_encryption_key_scope",wv="ccc_keystore",Fs="keys",gi="ccc_encryption_key_version";let Do=null,Ps=null,mi=!1,$s=!1,Ac=!1;class Ts extends Error{constructor(){super("Secure browser key storage is unavailable."),this.name="CredentialStorageUnavailableError"}}function Fc(){if(Ac)return;Ac=!0;const t="Secure browser key storage is unavailable. Existing credentials were left untouched; new credentials will be available only in this tab session.";console.warn(t),document.body&&ue(t,"warning")}function Qd(){return localStorage.getItem(gi)||""}function jo(){return crypto.randomUUID?.()||th(crypto.getRandomValues(new Uint8Array(16)))}function bv(){const t=Qd();if(t)return t;const e=jo();return localStorage.setItem(gi,e),e}function In(){Do=null,Ps=null,mi=!1,$s=!1}window.addEventListener("storage",t=>{t.key===gi&&In()});function Ev(){return new Promise((t,e)=>{const n=indexedDB.open(wv,1);n.onupgradeneeded=()=>{const i=n.result;i.objectStoreNames.contains(Fs)||i.createObjectStore(Fs)},n.onsuccess=()=>t(n.result),n.onerror=()=>e(n.error)})}async function Ea(t,e){const n=await Ev();return new Promise((i,s)=>{const r=n.transaction(Fs,t);let o;try{o=e(r.objectStore(Fs))}catch(l){n.close(),s(l);return}let a;o.onsuccess=()=>{a=o.result},o.onerror=()=>s(o.error),r.oncomplete=()=>{n.close(),i(a)},r.onerror=()=>{n.close(),s(r.error||new Error("Encryption key transaction failed."))},r.onabort=()=>{n.close(),s(r.error||new Error("Encryption key transaction aborted."))}})}function Sv(t){return t instanceof CryptoKey&&t.algorithm?.name==="AES-GCM"&&t.extractable===!1&&t.usages.includes("encrypt")&&t.usages.includes("decrypt")}async function xv(){const t=await Ea("readonly",e=>e.get(lt));return Sv(t)?t:null}async function eh(t){await Ea("readwrite",e=>e.put(t,lt))}async function kv(){In();try{await Ea("readwrite",t=>t.delete(lt))}catch(t){console.warn("Could not delete the stored encryption key:",t)}}async function Iv(){const t=sessionStorage.getItem(lt);if(!t)return null;const e=await crypto.subtle.importKey("jwk",JSON.parse(t),{name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);return await eh(e),sessionStorage.removeItem(lt),sessionStorage.removeItem(fi),localStorage.removeItem(rt+"salt"),e}async function Pc(t){const e=sessionStorage.getItem(lt);if(e)return $s=sessionStorage.getItem(fi)!=="session",crypto.subtle.importKey("jwk",JSON.parse(e),{name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);if(!t)throw new Ts;const n=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!0,["encrypt","decrypt"]),i=await crypto.subtle.exportKey("jwk",n);return sessionStorage.setItem(lt,JSON.stringify(i)),sessionStorage.setItem(fi,"session"),$s=!1,crypto.subtle.importKey("jwk",i,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}async function Cv(t){if(sessionStorage.getItem(fi)==="session"&&sessionStorage.getItem(lt))return Fc(),mi=!0,Pc(t);try{const e=await xv();if(e)return e;const n=await Iv();if(n)return n;const i=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);return await eh(i),i}catch(e){return console.warn("IndexedDB encryption-key storage failed:",e),Fc(),mi=!0,Pc(t)}}async function Sa(t={}){const{allowSessionFallbackCreation:e=!0}=t,n=bv();Ps!==n&&In();const i=Do||Cv(e);Do=i,Ps=n;try{return await i}catch(s){throw In(),s}}async function Av(t){const e=await Sa(),n=Ps,i=new TextEncoder,s=crypto.getRandomValues(new Uint8Array(12)),r=await crypto.subtle.encrypt({name:"AES-GCM",iv:s},e,i.encode(t)),o=new Uint8Array(s.length+r.byteLength);return o.set(s),o.set(new Uint8Array(r),s.length),{ciphertext:th(o),keyVersion:n,sessionFallback:mi}}async function Fv(t,e={}){const{isSessionCredential:n=!1}=e;try{const i=await Sa({allowSessionFallbackCreation:!1});if(mi&&!n&&!$s)throw new Ts;const s=Pv(t),r=s.slice(0,12),o=s.slice(12),a=await crypto.subtle.decrypt({name:"AES-GCM",iv:r},i,o);return new TextDecoder().decode(a)}catch(i){if(i instanceof Ts)throw i;return console.error("Decryption failed:",i),null}}function th(t){const e=new Uint8Array(t);let n="";for(let i=0;i0}let vi="",Rs="",ni=null,Tc=0;async function xa(){sessionStorage.getItem(lt)&&await Sa(),vi=await Ee("flutterflow"),Rs=await Ee("flutterflow_project_id"),Mv(),en()}function ka(){const t=document.getElementById("api-keys-modal");Ve(t),Ca(),vi&&rh(vi)}function nh(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("api-keys-modal");e&&Xe(e);const n=document.getElementById("walkthrough-modal");n&&(Ia(),Ve(n))}let kt=1;function ih(){const t=document.querySelector(".wt-steps");return t?Array.from(t.querySelectorAll(".wt-step-card")):[]}function Js(){const t=ih();t.length&&t.forEach((e,n)=>{const i=n+1;if(i===kt){e.classList.remove("opacity-60","bg-gray-50","border-gray-200"),e.classList.add("bg-blue-50","border-blue-200");const s=e.querySelector("div:first-child");s&&(s.classList.remove("bg-gray-400"),s.classList.add("bg-blue-500"),s.innerHTML=i)}else if(i0&&kt<=t&&(kt++,Js())}function Tv(){const t=document.getElementById("walkthrough-modal");t&&(kt=1,Js(),Ve(t))}function Rv(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("walkthrough-modal");e&&Xe(e);const n=document.getElementById("walkthrough-dont-show");n&&n.checked&&localStorage.setItem("hasSeenWalkthrough","true")}function sh(){if(V.isVerified&&Nt()&&pe.tier!=="free")return;if(!localStorage.getItem("hasSeenWalkthrough")){const e=document.getElementById("walkthrough-modal");e&&(kt=1,Js(),Ve(e))}}async function Ca(){const t=document.getElementById("flutterflow-api-key-input");vi?(t.value="",t.placeholder="Key saved (enter new to replace)"):t.placeholder="Enter your FlutterFlow API key",Nv()}function Nv(){Rc("flutterflow","flutterflow-key-status"),Rc("flutterflow_project_id","flutterflow-project-status")}function Rc(t,e){const n=document.getElementById(e);if(!n)return;const i=n.querySelector(".key-status-dot"),s=n.querySelector("span");dn(t)?(i.className="key-status-dot configured",s.className="text-green-600",s.textContent="User key configured"):(i.className="key-status-dot missing",s.className="text-gray-500",s.textContent="Not configured")}function en(){const t=y.step2Result&&y.step2Result.length>0,e=document.getElementById("btn-deploy-to-ff"),n=document.getElementById("btn-run-pipeline");n&&n.classList.remove("hidden"),e&&e.classList.toggle("hidden",!t)}function Mv(){const t=document.getElementById("api-keys-status");if(!t)return;const e=t.querySelectorAll(".key-status-dot"),n=["flutterflow"];e.forEach((i,s)=>{const r=n[s];r==="flutterflow"?dn("flutterflow")&&dn("flutterflow_project_id")?(i.className="key-status-dot configured",i.title="FlutterFlow (Fully configured)"):dn("flutterflow")||dn("flutterflow_project_id")?(i.className="key-status-dot env",i.title="FlutterFlow (Partially configured)"):(i.className="key-status-dot missing",i.title="FlutterFlow (Not configured)"):dn(r)?(i.className="key-status-dot configured",i.title=r.charAt(0).toUpperCase()+r.slice(1)+" (User key)"):(i.className="key-status-dot missing",i.title=r.charAt(0).toUpperCase()+r.slice(1)+" (Not configured)")}),en()}async function Lv(){const t=document.getElementById("flutterflow-api-key-input"),e=document.getElementById("flutterflow-projects-select");t.value.trim()&&await $c("flutterflow",t.value);const n=e?.value.trim()||"";if(n){if(!Ys(n)){ue("The selected FlutterFlow project has an unexpected ID format.","error"),e.focus();return}await $c("flutterflow_project_id",n)}await xa(),Ca();const i=document.querySelector("#api-keys-modal .bg-blue-500"),s=i.textContent;i.textContent="Saved!",i.classList.remove("bg-blue-500","hover:bg-blue-600"),i.classList.add("bg-green-500"),setTimeout(()=>{i.textContent=s,i.classList.remove("bg-green-500"),i.classList.add("bg-blue-500","hover:bg-blue-600"),nh()},1e3)}async function Ov(){if(!confirm("Are you sure you want to clear all stored API keys?"))return;localStorage.setItem(gi,jo()),In(),localStorage.removeItem(rt+"flutterflow"),localStorage.removeItem(rt+"flutterflow_project_id"),sessionStorage.removeItem(bt+"flutterflow"),sessionStorage.removeItem(bt+"flutterflow_project_id"),sessionStorage.removeItem(lt),sessionStorage.removeItem(fi),localStorage.removeItem(rt+"salt"),await kv(),localStorage.setItem(gi,jo()),localStorage.removeItem(rt+"flutterflow"),localStorage.removeItem(rt+"flutterflow_project_id"),sessionStorage.removeItem(bt+"flutterflow"),sessionStorage.removeItem(bt+"flutterflow_project_id"),await xa();const t=document.getElementById("flutterflow-projects-select");t&&(t.innerHTML=''),Ca()}function Ys(t){return!t||t.trim().length<5||t.includes(" ")?!1:/^[a-zA-Z0-9-]+$/.test(t)}function Bv(t,e){const n=document.getElementById(t);n&&(n.value?e?n.style.borderColor="#22c55e":n.style.borderColor="#ef4444":n.style.borderColor="")}function Dv(){const t=document.getElementById("flutterflow-api-key-input");t&&(t.addEventListener("input",e=>{const n=e.target.value.trim().length>0;Bv("flutterflow-api-key-input",n)}),t.addEventListener("blur",jv(async e=>{const n=e.target.value.trim();n&&await rh(n)},500)))}function jv(t,e){let n;return function(...s){const r=()=>{clearTimeout(n),t(...s)};clearTimeout(n),n=setTimeout(r,e)}}async function rh(t){const e=document.getElementById("flutterflow-projects-select"),n=document.getElementById("flutterflow-projects-error");if(!e){console.error("Projects dropdown element not found");return}e.innerHTML='',n&&n.classList.add("hidden");try{const s=await new wi(t,"").listProjects();if(!s||s.length===0){e.innerHTML='';return}e.innerHTML='',s.forEach(r=>{const o=document.createElement("option");o.value=r.id||r.projectId||"",o.textContent=r.name||r.projectName||`Project ${r.id}`,e.appendChild(o)}),Rs&&(e.value=Rs)}catch(i){console.error("Failed to fetch projects:",i),e.innerHTML='',n&&(n.textContent=`Failed to load projects: ${i.message}`,n.classList.remove("hidden"))}}function Uv(t){const e=document.getElementById(t),i=e.nextElementSibling.querySelector("svg");e.type==="password"?(e.type="text",i.innerHTML=` + + `):(e.type="password",i.innerHTML=` + + + `)}let y={step1Result:null,step2Result:null,step3Result:null,bundleSpec:null,artifactBundle:null,bundleReview:null,selectedArtifactId:null,resultsViewMode:"summary",currentStep:0,isRunning:!1};function Hv(){y.step1Result=null,y.step2Result=null,y.step3Result=null,y.bundleSpec=null,y.artifactBundle=null,y.bundleReview=null,y.selectedArtifactId=null,y.resultsViewMode="summary"}function Wv(){y.bundleSpec=di(y.step1Result,{artifactType:"CustomWidget",artifactName:"GeneratedWidget"})}function Zs(){const t=Ss(y.bundleSpec);y.artifactBundle=di(y.step2Result,{id:y.bundleSpec?.id,title:y.bundleSpec?.title,description:y.bundleSpec?.description,artifactType:t.artifactType,artifactName:t.artifactName,fileName:t.fileName,dependencies:t.dependencies,relationships:y.bundleSpec?.relationships,code:y.step2Result||""});const e=Ng(y.artifactBundle);y.artifactBundle={...y.artifactBundle,warnings:[...y.artifactBundle.warnings,...e.findings.map(n=>n.message)],metadata:{...y.artifactBundle.metadata,compatibility:e}},y.selectedArtifactId=Ss(y.artifactBundle).id}function Xs(){const t=di(y.step3Result,{id:y.artifactBundle?.id,title:y.artifactBundle?.title}),e=new Map(t.artifacts.map(i=>[i.id,i.review])),n=new Map(t.artifacts.filter(i=>{const s=i.review;return s&&typeof s.fixedSource=="string"&&s.fixedSource.trim()}).map(i=>[i.id,i.review.fixedSource.trim()]));y.bundleReview=di({id:y.artifactBundle?.id,title:y.artifactBundle?.title,artifacts:y.artifactBundle?.artifacts?.map(i=>{const s=n.get(i.id)||null;return{...i,review:e.get(i.id)||i.review||y.step3Result||null,...s?{fixedCode:s}:{}}})||[],relationships:y.artifactBundle?.relationships,warnings:y.artifactBundle?.warnings})}function oh(){const t=Aa();return{artifactType:t.artifactType||"CustomWidget",artifactName:t.artifactName||"GeneratedWidget",fileName:t.fileName||""}}function Aa(){const t=y.artifactBundle||y.bundleSpec||null;return(Array.isArray(t?.artifacts)?t.artifacts:[]).find(n=>n.id===y.selectedArtifactId)||Ss(t)}function Fa(){return Aa().code||y.step2Result||""}async function zv(){try{await xa()}catch(t){return console.error("checkConnection: initializeApiKeys failed:",t),!1}return!0}const Xi={production:"https://api.flutterflow.io/v2/",staging:"https://api.flutterflow.io/v2-staging/"};function qv(t,e){const n=e?.trim()?` (${e.trim().slice(0,200)})`:"";return t===401?`Your FlutterFlow API key was rejected (401 Unauthorized)${n}. Re-enter a current key under API Keys settings, then try again.`:`Listing FlutterFlow projects was denied (403)${n}. The key may be scoped to sync a single project without list permission - verify the key's access in FlutterFlow, re-enter it under API Keys settings, then retry.`}class wi{constructor(e,n,i="main",s=Xi.production){this.apiKey=e,this.baseUrl=s,this._projectId=n,this._branchName=i,this._endpoint=s}get projectId(){return this._projectId}get branchName(){return this._branchName==="main"?"":this._branchName}async exportProjectZip(){console.log(`Exporting code from FlutterFlow project: ${this.projectId}, branch: ${this.branchName||"main"}`);const e=[{project:{path:`projects/${this.projectId}`},...this.branchName?{branch_name:this.branchName}:{},export_as_module:!1,include_assets_map:!1,format:!1,export_as_debug:!1},{project_id:this.projectId,branch_name:this.branchName,include_assets:!1,export_as_module:!1}];let n=null;for(const i of e)try{const s=await fetch(`${this.baseUrl}exportCode`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify(i)});if(!s.ok){const a=await s.text();n=new Error(`Export failed: ${s.status} - ${a}`);continue}const r=await s.json(),o=r?.value?.project_zip||r?.project_zip;if(!o){n=new Error("Export response did not include project source.");continue}return o}catch(s){n=s}throw n||new Error("Export failed for an unknown reason.")}async fetchProjectSource(){const e=await this.exportProjectZip(),n=await JSZip.loadAsync(e,{base64:!0}),i=Object.keys(n.files).filter(a=>!n.files[a].dir&&(a==="pubspec.yaml"||a.endsWith("/pubspec.yaml"))).sort((a,l)=>a.split("/").length-l.split("/").length)[0];if(!i)throw new Error("Export did not contain a pubspec.yaml.");const s=i.slice(0,i.length-12),r=new Map,o=Object.keys(n.files).filter(a=>{if(n.files[a].dir||!a.startsWith(s))return!1;const l=a.slice(s.length);return l==="lib/flutter_flow/custom_functions.dart"||l.startsWith("lib/custom_code/")&&l.endsWith(".dart")});return await Promise.all(o.map(async a=>{r.set(a.slice(s.length),await n.files[a].async("string"))})),{pubspecYaml:await n.files[i].async("string"),files:r}}async pushCodeWithRetry(e,n=3){const i=[Xi.production,Xi.staging],s=Math.max(0,i.indexOf(this._endpoint));for(let r=0;rsetTimeout(d,1e3*(r+1)));continue}return l}catch(l){console.warn(`Push to ${a} failed: ${l.message}, trying next...`),await new Promise(u=>setTimeout(u,1e3*(r+1)))}}throw new Error("All API endpoints failed after retries")}async pushCode(e){return this.pushCodeWithRetry(e)}parseProjectsResponse(e){if(e?.success&&typeof e.value=="string")try{const i=JSON.parse(e.value);if(i&&Array.isArray(i.entries))return i.entries.map(s=>({id:s.id,name:s.project?.name||s.id}))}catch(i){console.error("Failed to parse stringified project value:",i)}const n=e?.projects||e?.items||e?.entries||(Array.isArray(e)?e:[]);return Array.isArray(n)?n:[]}async listProjects(){console.log("Listing projects for API key");const e=[`${this.baseUrl}listProjects`,"https://api.flutterflow.io/v2/l/listProjects"];let n=0,i="";for(const s of e){const r=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify({project_type:"ALL",deserialize_response:!0})});if(r.ok)return s!==e[0]&&console.log(`listProjects answered on legacy path ${s}`),this.parseProjectsResponse(await r.json());if(n=r.status,i=await r.text(),console.warn(`listProjects via ${s} returned ${n}: ${i}`),r.status===401||r.status===403)throw new Error(qv(r.status,i));if(r.status!==404)throw new Error(`List projects failed: ${r.status} - ${i}`)}throw new Error(`List projects failed: ${n} - ${i}`)}}async function Pa(t){const e=t.clone();let n;try{n=await t.json()}catch{const r=await e.text();if(!t.ok)return{success:!1,responseCode:t.status,errorMessage:r||`HTTP ${t.status}`,errorMap:new Map};throw new Error(`Invalid JSON response: ${r}`)}if(!t.ok){let s=n.message||`HTTP ${t.status}`,r=new Map;if(n.errors)r=new Map(Object.entries(n.errors));else if(!n.message&&typeof n=="object"){const o=Object.keys(n).filter(a=>a.endsWith(".dart")&&Array.isArray(n[a]));o.length>0&&(r=new Map(Object.entries(n)),s=o.flatMap(l=>n[l].map(u=>`${l}: ${u.errorMessage}`)).join(` +`)||`HTTP ${t.status}`)}return{success:!1,responseCode:t.status,errorMessage:s,errorMap:r}}let i={};if(n.value)try{i=typeof n.value=="string"?JSON.parse(n.value):n.value}catch(s){console.warn("Ignoring malformed push response value:",s)}return{success:!0,responseCode:t.status,errorMap:new Map(Object.entries(i))}}function $a(t,e){return{401:"Authentication failed. Please check your FlutterFlow API key.",403:"Access denied. You may not have permission to modify this project.",404:"Project not found. Please check your Project ID.",409:"Conflict detected. The project may have been modified elsewhere.",422:"Validation failed: Invalid request format",429:"Rate limit exceeded. Please try again in a few minutes.",500:"FlutterFlow server error. Please try again later.",503:"FlutterFlow service temporarily unavailable."}[t]||`FlutterFlow API error: ${`HTTP ${t}`}`}const W={ACTION:"A",WIDGET:"W",FUNCTION:"F",CODE_FILE:"C",DEPENDENCIES:"D",OTHER:"O"},ah=/class\s+\w+\s+extends\s+(?:StatelessWidget|StatefulWidget)\b/,lh=/extends\s+State<\w+>/;function Vv(t,e=""){if(t==="pubspec.yaml")return W.DEPENDENCIES;if(!t.endsWith(".dart")||t.endsWith("index.dart"))return W.OTHER;if(t==="custom_functions.dart")return W.FUNCTION;if(e){const n=ah.test(e),i=lh.test(e);if(n||i)return W.WIDGET;if(/^\s*Future(?:<[^>]+>)?\s+\w+\s*\(/m.test(e))return W.ACTION;if(e.match(/^\s*(String|int|double|bool|List|Map|dynamic|void)\s+\w+\s*\(/m))return W.FUNCTION}return W.CODE_FILE}function ch(t,e){switch(e){case W.ACTION:return`lib/custom_code/actions/${t}`;case W.WIDGET:return`lib/custom_code/widgets/${t}`;case W.FUNCTION:return"lib/flutter_flow/custom_functions.dart";case W.CODE_FILE:return`lib/custom_code/${t}`;case W.DEPENDENCIES:return"pubspec.yaml";case W.OTHER:return`lib/custom_code/${t}`;default:return t}}async function Ta(t,e=new Map){return mg(t,e)}const Uo=new Map;function uh(t){return`${t.baseUrl}|${t.projectId}|${t.branchName}`}function Qs(t){Uo.delete(uh(t))}async function Ra(t,e,n,i,s=""){const r=Kg(e,n);if(r.length===0)return{remoteFiles:n,syncFileMap:e,unverified:[]};const o=Nm(r,s),a={...o.manifest,sources:o.sources},l=o.skipped.map(d=>d.reason);l.forEach(d=>console.warn(`[custom class deploy] ${d}`)),console.log(`Provisioning ${r.length} new FlutterFlow custom code file(s) before sync.`),be.set("provision");const u=await fetch(rv,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:t.apiKey,projectId:t.projectId,baseUrl:t.baseUrl,commitMessage:i,customClasses:r,verification:a,stream:!0})}),c=await Lm(u,{onPhase:d=>be.setSubstatus(d),onLog:d=>console.log(`[custom class deploy] ${d}`)});if(!c.success){const d=c.details?` ${c.details}`:"";throw new Error(`${c.error||"FlutterFlow custom class provisioning failed."}${d}`)}return Qs(t),c.verificationSkipped&&(console.warn(`[custom class deploy] ${c.verificationSkipped}`),l.push(c.verificationSkipped)),{remoteFiles:n,syncFileMap:Jg(e,r),unverified:l}}async function Na(t,e={}){const n=uh(t);let i=Uo.get(n);if(i===void 0){try{i=await t.fetchProjectSource()}catch(l){throw new Error(`Could not read your project's pubspec.yaml (${l.message}). Deploy was stopped so your existing package dependencies aren't overwritten. Check your FlutterFlow API key and project, then try again.`)}const a=zd(i.pubspecYaml);if(!a.valid)throw new Error(`Your project's pubspec.yaml could not be read reliably (${a.errors.join("; ")}). Deploy was stopped so your existing package dependencies aren't overwritten.`);Uo.set(n,i)}const s=await Gm(i.pubspecYaml,e),r=Fm(i.pubspecYaml,s.overrides),o=Am(r.yaml,s.additions);return s.warnings.forEach(a=>console.warn(`[pubspec] ${a}`)),o.added.length>0&&console.log("Adding dependencies:",o.added.map(a=>`${a}: ${s.additions[a]||"any"}`).join(", "),s.sdk.dartSdkFloor?`(resolved for Dart ${s.sdk.dartSdkFloor})`:""),s.kept.forEach(({name:a,constraint:l})=>console.log(`Keeping your existing ${a}: ${l||"(non-version source)"}`)),{...o,overridden:r.overridden,warnings:s.warnings,remoteFiles:i.files}}function Gv(t){const e=[],n=[];t.content.length>5e4&&n.push("Code file is large (>50KB). This may take longer to commit."),t.content.length>1e5&&e.push("Code file is too large (>100KB). Consider splitting into smaller components.");const i=t.content.split(` +`).length;i>500&&n.push(`Code has ${i} lines. Consider breaking it into smaller widgets.`),t.content.includes("setState")&&t.codeType===W.ACTION&&n.push("Using setState in a Custom Action may not work as expected. Consider using a Custom Widget."),t.content.includes("dynamic")&&!t.content.includes("?")&&n.push('Code uses "dynamic" types. Consider adding explicit types for better null safety.'),t.content.match(/Color\(0xFF[0-9A-Fa-f]{6}\)/)&&n.push("Code contains hardcoded colors. Consider using FlutterFlowTheme.of(context) for theme consistency.");const s=t.content.match(/print\s*\(/g);s&&s.length>3&&n.push(`Code contains ${s.length} print statements. Consider removing debug prints before committing.`);const r=pm(t.content);if(r&&e.push(`FlutterFlow cannot format this code - ${r}. Fix or regenerate before committing.`),t.codeType===W.WIDGET){const o=Ld(t.content),a=um(t.fileName);if(o.length===0)e.push("No public widget class found (must extend StatelessWidget or StatefulWidget).");else if(!o.includes(a)){const l=`${Od(o[0])}`;e.push(`Widget class name "${o[0]}" does not match the file name "${t.fileName}". FlutterFlow derives the widget from the file name, so it will report "No widget ${a} found". Rename the file to "${l}" or the class to match before committing.`)}}return{canProceed:e.length===0,issues:e,warnings:n}}function dh(t,e={}){const{artifactType:n="CustomWidget",artifactName:i="GeneratedCode",fileName:s}=e,r=lm(t);let o=s||i;if(n==="CustomFunction")o="custom_functions.dart";else if(n==="CustomWidget"){const u=Ld(r)[0],c=u?Od(u):null;c&&o!==c?(console.warn(`Commit file name "${o}" does not match declared widget class "${u}"; renaming to "${c}" so FlutterFlow can find the widget.`),o=c):o.endsWith(".dart")||(o+=".dart")}else o.endsWith(".dart")||(o+=".dart");let a=W.CODE_FILE;switch(n){case"CustomAction":a=W.ACTION;break;case"CustomWidget":a=W.WIDGET;break;case"CustomFunction":a=W.FUNCTION;break;case"CustomClass":case"CodeFile":a=W.CODE_FILE;break}let l="";return a===W.WIDGET?l=`// Automatic FlutterFlow imports +import '/flutter_flow/flutter_flow_theme.dart'; +import '/flutter_flow/flutter_flow_util.dart'; +import 'package:flutter/material.dart'; +// Begin custom widget code +// DO NOT REMOVE OR MODIFY THE CODE ABOVE! + +`:a===W.ACTION?l=`// Automatic FlutterFlow imports +import '/flutter_flow/flutter_flow_theme.dart'; +import '/flutter_flow/flutter_flow_util.dart'; +import 'package:flutter/material.dart'; +// Begin custom action code +// DO NOT REMOVE OR MODIFY THE CODE ABOVE! + +`:a===W.FUNCTION&&(l=`// Automatic FlutterFlow imports +import 'dart:convert'; +import 'dart:math' as math; + +import 'package:flutter/material.dart'; +import 'package:google_fonts/google_fonts.dart'; +import 'package:intl/intl.dart'; +import 'package:timeago/timeago.dart' as timeago; +import '/flutter_flow/lat_lng.dart'; +import '/flutter_flow/place.dart'; +import '/flutter_flow/uploaded_file.dart'; + +`),{content:Og(r,l),fileName:o,codeType:a,artifactType:n,artifactName:i}}function Kv(t){const e={};for(const n of ma(t))e[n]="";return e}function Jv(t,e={}){return{timestamp:new Date().toISOString(),artifactType:t.artifactType,artifactName:t.artifactName,codeType:t.codeType,fileName:t.fileName,generatedFrom:e.step1Result?"pipeline":"direct",model:e.selectedModel||"unknown",codeSize:t.content.length}}function Yv(t,e,n,i=new Set,s=""){const r=[],o=ah.test(e),a=lh.test(e);return n===W.WIDGET&&!o&&!a&&r.push("No widget class definition found (must extend StatelessWidget or StatefulWidget)"),{valid:r.length===0,errors:r}}function er(t){const e=[],n=[];if(!t||t.size===0)return e.push("No files to commit"),{valid:!1,errors:e,warnings:n};const i=new Set(Array.from(t.values()).flatMap(s=>Hs(s.content||"")));for(const[s,r]of t.entries()){if((!r.content||r.content.trim().length===0)&&e.push(`File ${s} is empty`),r.content&&r.content.length>1e5&&n.push(`File ${s} is very large (>100KB)`),s.endsWith(".dart")){const o=Yv(s,r.content,r.type,i,r.artifactName);o.valid||e.push(...o.errors.map(a=>`${s}: ${a}`))}if(s==="pubspec.yaml"){const o=zd(r.content);o.valid||e.push(...o.errors)}}return{valid:e.length===0,errors:e,warnings:n}}const K={IDLE:"IDLE",PREPARING:"PREPARING",VALIDATING:"VALIDATING",PUSHING:"PUSHING",SUCCESS:"SUCCESS",ERROR:"ERROR"},J={currentState:K.IDLE,startTime:null,endTime:null,error:null,result:null,filesProcessed:0,totalFiles:0,reset(){this.currentState=K.IDLE,this.startTime=null,this.endTime=null,this.error=null,this.result=null,this.filesProcessed=0,this.totalFiles=0},setState(t){if(!Object.values(K).includes(t)){console.error(`Invalid commit state: ${t}`);return}this.currentState=t,t===K.PREPARING&&(this.startTime=Date.now()),(t===K.SUCCESS||t===K.ERROR)&&(this.endTime=Date.now()),typeof window<"u"&&window.dispatchEvent&&window.dispatchEvent(new CustomEvent("commitStateChange",{detail:{state:t,commitState:this}})),console.log(`Commit state changed to: ${t}`)},setError(t){this.error=t,this.setState(K.ERROR)},setSuccess(t){this.result=t,this.setState(K.SUCCESS)},setProgress(t,e){this.filesProcessed=t,this.totalFiles=e},getElapsedTime(){return this.startTime?(this.endTime||Date.now())-this.startTime:null},isInProgress(){return this.currentState===K.PREPARING||this.currentState===K.VALIDATING||this.currentState===K.PUSHING}};async function Zv(t,e,n={}){let{codeType:i="W"}=n;const{pubspecDeps:s={},artifactName:r=e}=n;i==="CustomWidget"&&(i=W.WIDGET),i==="CustomAction"&&(i=W.ACTION),i==="CustomFunction"&&(i=W.FUNCTION),i==="CustomClass"&&(i=W.CODE_FILE),i==="CodeFile"&&(i=W.CODE_FILE),J.reset(),J.setState(K.PREPARING);try{const o=await Ee("flutterflow"),a=await Ee("flutterflow_project_id");if(!o||!a)throw new Error("FlutterFlow credentials not configured. Please set your API key and Project ID in the API Keys settings.");if(!Ys(a))throw new Error("Invalid FlutterFlow Project ID format.");const l=yi(),u=new wi(o,a,"main",l);J.setState(K.VALIDATING);const c=new Map,d=i||Vv(e,t),h=ch(e,d);c.set(e,{artifactName:r,content:t,type:d,path:h}),J.setProgress(0,c.size);const p=er(c);if(!p.valid)throw new Error(`Validation failed: +${p.errors.join(` +`)}`);const f=await Na(u,s),g=f.yaml,m=await Ra(u,c,f.remoteFiles,`Provision ${r} custom class`,g),v=await Ta(m.syncFileMap,m.remoteFiles),E=new Map(m.syncFileMap);E.set("pubspec.yaml",{content:g,type:"D",path:"pubspec.yaml"}),be.set("package");const w=await Ma(E),I={project_id:a,zipped_custom_code:w,uid:`web_${Date.now()}`,branch_name:u.branchName,serialized_yaml:g,file_map:v.fileMapContents,functions_map:v.functionsMapContents};J.setState(K.PUSHING),J.setProgress(1,c.size),Qs(u),be.set("push");const A=await u.pushCode(I),F=await Pa(A);if(F.success)J.setSuccess({fileCount:c.size,projectId:a,warnings:F.errorMap&&F.errorMap.size>0?Array.from(F.errorMap.entries()):[]});else{const D=F.errorMessage||$a(F.responseCode);throw new Error(D)}return{success:!0,message:`Successfully committed ${e} to FlutterFlow project ${a}`,addedDependencies:f.added,unverified:m.unverified,warnings:F.errorMap?Array.from(F.errorMap.entries()):[]}}catch(o){return console.error("Commit failed:",o),J.setError(o),{success:!1,error:o.message,state:J.currentState}}}async function Ma(t){const e=new JSZip;for(const[n,i]of t.entries())e.file(n,i.content);return e.generateAsync({type:"base64",compression:"DEFLATE",compressionOptions:{level:6}})}async function Xv(t,e={}){const{artifactType:n,artifactName:i,fileName:s,pipelineResult:r}=e;console.log(`Starting commit for ${i} (${n})`);try{J.setState(K.PREPARING);const o=dh(t,{artifactType:n,artifactName:i,fileName:s}),a=Kv(o.content);console.log("Detected dependencies:",a),J.setState(K.VALIDATING);const l=await Ee("flutterflow"),u=ni||await Ee("flutterflow_project_id");if(!l)throw new Error("FlutterFlow API Key not configured. Please add it in API Keys settings.");if(!u)throw new Error("FlutterFlow Project ID not configured. Please add it in API Keys settings.");if(!Ys(u))throw new Error("Invalid FlutterFlow Project ID format.");const c=new Map;c.set(o.fileName,{artifactName:i,content:o.content,type:o.codeType,path:ch(o.fileName,o.codeType),functionName:o.codeType===W.FUNCTION?i:void 0}),J.setProgress(0,c.size);const d=er(c);if(!d.valid)throw new Error(`File validation failed: +${d.errors.join(` +`)}`);d.warnings.length>0&&console.warn("Validation warnings:",d.warnings),J.setState(K.PUSHING);const h=yi(),p=new wi(l,u,"main",h),f=await Na(p,a),g=f.yaml,m=await Ra(p,c,f.remoteFiles,`Provision ${i} custom class`,g),v=await Ta(m.syncFileMap,m.remoteFiles),E=new Map(m.syncFileMap);E.set("pubspec.yaml",{content:g,type:W.DEPENDENCIES,path:"pubspec.yaml"}),be.set("package");const w=await Ma(E),I={project_id:u,zipped_custom_code:w,uid:`web_${Date.now()}`,branch_name:p.branchName,serialized_yaml:g,file_map:v.fileMapContents,functions_map:v.functionsMapContents};J.setProgress(1,c.size),Qs(p),be.set("push");const A=await p.pushCode(I),F=await Pa(A);if(F.success){const D={...Jv(o,r),projectId:u};return J.setSuccess({...D,fileCount:c.size,warnings:F.errorMap?Array.from(F.errorMap.entries()):[]}),{success:!0,message:`Successfully committed ${o.fileName} to FlutterFlow`,metadata:D,addedDependencies:f.added,unverified:m.unverified,warnings:F.errorMap?Array.from(F.errorMap.entries()):[],elapsedTime:J.getElapsedTime()}}else{const D=F.errorMessage||$a(F.responseCode),S=new Error(D);throw S.errorMap=F.errorMap,S}}catch(o){console.error("Commit execution failed:",o),J.setError(o);let a=new Map;if(o.errorMap)a=o.errorMap;else if(o.message&&o.message.includes("{"))try{const l=o.message.match(/\{[\s\S]*\}/);if(l){const u=JSON.parse(l[0]);a=new Map(Object.entries(u))}}catch(l){console.warn("Failed to parse error map from commit response:",l)}return{success:!1,error:o.message,errorMap:a,state:J.currentState,elapsedTime:J.getElapsedTime()}}}async function Qv(t,e={}){const{pipelineResult:n}=e;try{if(J.setState(K.PREPARING),t.errors?.length>0)throw new Error(`Bundle validation failed: +${t.errors.join(` +`)}`);const i=new Map(t.fileEntries.map(I=>[I.fileName,{artifactId:I.artifactId,artifactName:I.artifactName,content:I.content,type:I.type,path:I.path,functionName:I.type===W.FUNCTION?I.artifactName:void 0}]));J.setProgress(0,i.size);const s=er(i);if(!s.valid)throw new Error(`File validation failed: +${s.errors.join(` +`)}`);J.setState(K.VALIDATING);const r=await Ee("flutterflow"),o=ni||await Ee("flutterflow_project_id");if(!r)throw new Error("FlutterFlow API Key not configured. Please add it in API Keys settings.");if(!o)throw new Error("FlutterFlow Project ID not configured. Please add it in API Keys settings.");if(!Ys(o))throw new Error("Invalid FlutterFlow Project ID format.");J.setState(K.PUSHING);const a=yi(),l=new wi(r,o,"main",a),u=await Na(l,t.dependencies),c=u.yaml,d=await Ra(l,i,u.remoteFiles,`Provision ${t.title} custom classes`,c),h=await Ta(d.syncFileMap,d.remoteFiles),p=new Map(d.syncFileMap);p.set("pubspec.yaml",{content:c,type:W.DEPENDENCIES,path:"pubspec.yaml"}),be.set("package");const f=await Ma(p),g={project_id:o,zipped_custom_code:f,uid:`web_${Date.now()}`,branch_name:l.branchName,serialized_yaml:c,file_map:h.fileMapContents,functions_map:h.functionsMapContents};J.setProgress(1,i.size),Qs(l),be.set("push");const m=await l.pushCode(g),v=await Pa(m);if(v.success){const I={...n,artifactType:"Bundle",artifactName:t.title,fileName:`${t.fileEntries.length} artifacts`,codeSize:t.fileEntries.reduce((A,F)=>A+F.content.length,0),projectId:o};return J.setSuccess({...I,fileCount:i.size,warnings:v.errorMap?Array.from(v.errorMap.entries()):[]}),{success:!0,message:`Successfully committed ${t.fileEntries.length} artifacts to FlutterFlow`,metadata:I,addedDependencies:u.added,unverified:d.unverified,warnings:v.errorMap?Array.from(v.errorMap.entries()):[],elapsedTime:J.getElapsedTime()}}const E=v.errorMessage||$a(v.responseCode),w=new Error(E);throw w.errorMap=v.errorMap,w}catch(i){return console.error("Bundle commit execution failed:",i),J.setError(i),{success:!1,error:i.message,errorMap:i.errorMap||new Map,state:J.currentState,elapsedTime:J.getElapsedTime()}}}async function e_(t,e=[]){const n=ha("architect");try{return await Ms("architect",Yd,sg(t),n,e)}catch(i){throw i.isModelArmor?i:new Error(`Prompt Architect failed: ${i.message}`)}}async function tr(t,e,n=[]){const i=rg(t),s=ha("generator",y.bundleSpec);try{return await Ms("generator",e,i,s,n)}catch(r){if(r.isModelArmor)throw r;if(e!==jr){console.warn(`Code Generator failed with ${e}, retrying with fallback model:`,r.message);try{return await Ms("generator",jr,i,s,n)}catch(o){throw o.isModelArmor?o:new Error(`Code Generator failed: primary (${e}): ${r.message} | fallback (${jr}): ${o.message}`)}}throw new Error(`Code Generator failed: ${r.message}`)}}async function nr(t,e=null){const n={...ha("review",y.artifactBundle||y.bundleSpec),architect_output:e};try{return await Ms("review",Zd,og(t),n)}catch(i){throw i.isModelArmor?i:new Error(`Code Review failed: ${i.message}`)}}function La(t,e){return t.isModelArmor?`${t.userTitle}: ${t.userMessage}`:`${e}: ${t.message}`}function Ho(t,e){const n=document.getElementById(`step${t}-item`),i=document.getElementById(`step${t}-status`);!n||!i||(n.classList.remove("active","completed","error"),i.classList.remove("running","completed","error"),e==="active"?(n.classList.add("active"),i.classList.add("running"),i.innerHTML=` + + `):e==="completed"?(n.classList.add("completed"),i.classList.add("completed"),i.innerHTML=` + + `):e==="error"?(n.classList.add("error"),i.classList.add("error"),i.innerHTML=` + + `):i.innerHTML=` + + `)}function ve(t,e){const n=document.getElementById(`step${t}-loading`),i=document.getElementById(`step${t}-result`);e?(n.classList.remove("hidden"),i.classList.add("hidden"),Ho(t,"active")):(n.classList.add("hidden"),i.classList.remove("hidden"),Ho(t,"completed"))}function t_(t){const e=document.getElementById(`${t}-content`),n=document.getElementById(`${t}-chevron`);e.classList.contains("open")?(e.classList.remove("open"),n&&(n.style.transform="rotate(0deg)")):(e.classList.add("open"),n&&(n.style.transform="rotate(180deg)"))}function n_(t){ze(parseInt(t.replace("step","")))}function ze(t){for(let o=1;o<=3;o++){const a=document.getElementById(`step${o}-item`);a&&a.classList.remove("active")}const e=document.getElementById(`step${t}-item`);e&&e.classList.add("active"),Qt();const n=document.getElementById("ready-state");n&&n.classList.add("hidden");for(let o=1;o<=3;o++){const a=document.getElementById(`step${o}-content`);a&&a.classList.add("hidden")}const i=document.getElementById(`step${t}-content`);i&&i.classList.remove("hidden");const s=document.getElementById("stage-title"),r={1:"Prompt Architect",2:"Code Generator",3:"Code Review"};s&&(s.textContent=r[t]||"Active Workflow Stage")}function i_(t){const e=document.getElementById(t);if(!e)return;const n=e.dataset.raw||e.textContent;navigator.clipboard.writeText(n).then(()=>{const s=e.closest(".code-container")?.querySelector(".copy-btn");s&&(s.classList.add("copied"),s.innerHTML=' Copied!',setTimeout(()=>{s.classList.remove("copied"),s.innerHTML=' Copy'},2e3))}).catch(i=>{console.warn("Failed to copy to clipboard:",i)})}function Wo(t){const e=zo(t);console.log(`Step 1 (Prompt Architect): ${Kt(Yd)}`),console.log(e!==t?`Step 2 (Code Generator): ${Kt(t)} → ${Kt(e)} (Free Tier fallback)`:`Step 2 (Code Generator): ${Kt(t)}`),console.log(`Step 3 (Code Review): ${Kt(Zd)}`)}async function s_(){if(console.log("runRefinement called"),y.isRunning)return;const t=document.getElementById("code-generator-model").value;y.isRunning=!0,Oa("standardRegenerate",y.step2Result,y.step1Result);const e=document.querySelectorAll(".btn-refine-action");e.forEach(n=>{n.disabled=!0,n.innerHTML=` + + + Refining...`});try{const n=Aa(),i=ag({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,artifactId:n.id,userFeedback:"Fix the issues listed in the audit report."});or(),at(2),ze(2),ve(2,!0),y.step2Result=await tr(i,t),Zs();const s=document.getElementById("step2-output"),r=xn(y.step2Result);s.textContent=r,s.dataset.raw=r,ve(2,!1),ze(3),at(3),ve(3,!0),y.step3Result=await nr(y.step2Result,y.step1Result),Xs();const o=document.getElementById("step3-output");o.textContent=y.step3Result,ve(3,!1),Mt();const a=Ks(y.step3Result);ar(r,a)}catch(n){console.error("Refinement failed:",n),Mt(),ue(La(n,"Refinement failed"),"error")}finally{y.isRunning=!1,e.forEach(n=>{n.disabled=!1,n.textContent="Refine & Regenerate"}),en()}}async function Oa(t,e,n){const i=`${Ze}/connectFeedback`,s={type:t,code:e,input:n};try{const r=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)});if(!r.ok){const a=await r.text();return console.error(`callEndpoint failed: ${r.status} ${r.statusText}`,a),{success:!1,status:r.status,error:a}}const o=await r.json();return console.log("Telemetry success:",o),o}catch(r){return console.error("callEndpoint failed:",r),{success:!1,error:r.message}}}function r_(){const t=document.getElementById("ff-error-paste-input");t&&(t.value="")}async function o_(){const t=document.getElementById("ff-error-paste-input"),e=t?.value?.trim();if(!e){t?.focus(),t?.classList.add("ring-2","ring-red-400","border-red-300"),setTimeout(()=>t?.classList.remove("ring-2","ring-red-400","border-red-300"),2e3);return}if(!y.step2Result){ue("No generated code found. Please run the full pipeline first.","warning");return}if(y.isRunning)return;const n=document.getElementById("code-generator-model").value;y.isRunning=!0,Oa("flutterflowError",y.step2Result,e);const i=document.getElementById("btn-fix-from-errors");i&&(i.disabled=!0,i.innerHTML=` + + Fixing…`);try{const s=$d({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,userFeedback:e});Sh(),or(),at(2),ze(2),ve(2,!0),y.step2Result=await tr(s,n),Zs();const r=document.getElementById("step2-output"),o=xn(y.step2Result);r.textContent=o,r.dataset.raw=o,ve(2,!1),ze(3),at(3),ve(3,!0),y.step3Result=await nr(y.step2Result,y.step1Result),Xs();const a=document.getElementById("step3-output");a.textContent=y.step3Result,ve(3,!1),Mt();const l=Ks(y.step3Result);ar(o,l),t&&(t.value="")}catch(s){console.error("Fix from errors failed:",s),Mt(),ue(La(s,"Failed to fix errors"),"error")}finally{y.isRunning=!1,i&&(i.disabled=!1,i.textContent="Fix Errors & Regenerate"),en()}}async function Ns(){if(console.log("runThinkingPipeline called"),y.isRunning)return;localStorage.setItem("hasSeenWalkthrough","true");const t=document.getElementById("pipeline-input").value,e=document.getElementById("code-generator-model").value;if(!t.trim()){ue("Please describe your FlutterFlow widget first.","warning");return}if(!await I_())return;await w_();const n=zo(e);t.length;const i=document.getElementById("btn-run-pipeline");y.isRunning=!0,Hv(),i&&(i.disabled=!0,i.innerHTML=` + + + Running...`),Wo(n);try{Qt();const s=document.getElementById("ready-state");s&&s.classList.add("hidden");const r=document.getElementById("paywall-exhausted");r&&r.classList.add("hidden"),or(),ze(1),at(1),ve(1,!0);const o=Tt.filter(p=>p.url).map(p=>({url:p.url}));y.step1Result=await e_(t,o),Wv();const a=document.getElementById("step1-output"),l=xn(y.step1Result);a.textContent=l,a.dataset.raw=l,ve(1,!1),ze(2),at(2),ve(2,!0),y.step2Result=await tr(y.step1Result,n,o),Zs();const u=document.getElementById("step2-output"),c=xn(y.step2Result);u.textContent=c,u.dataset.raw=c,ve(2,!1),ze(3),at(3),ve(3,!0),y.step3Result=await nr(y.step2Result,y.step1Result),Xs();const d=document.getElementById("step3-output");d.textContent=y.step3Result,ve(3,!1),Mt();const h=Ks(y.step3Result);ar(c,h)}catch(s){if(console.error("Pipeline failed:",s),Mt(),s.isUsageLimit){const{count:c}=bi();Ua(c,sr(),{openModal:!0});return}s.message,zo(document.getElementById("code-generator-model").value);const o=Jm(s,{architect:1,generator:2,review:3});ze(o);const a=document.getElementById(`step${o}-result`),l=document.getElementById(`step${o}-loading`),u=document.getElementById(`step${o}-output`);if(l&&l.classList.add("hidden"),a&&a.classList.remove("hidden"),u)if(s.isModelArmor)u.innerHTML=``;else{let c=s.message;s.message.includes("image input")?c=`This model doesn't support image input. Please use ${Kt(pi)} for image-based requests or remove image references from your prompt.`:(s.message.includes("Load failed")||s.message.includes("CORS"))&&(c="API connection failed. This might be due to CORS restrictions or network issues. Please check your API key and try again."),u.innerHTML=`
    +

    Connection Error

    +

    ${j(c)}

    +
    +

    Check if API key is valid

    +

    Try using a different model

    +

    Ensure network allows API calls

    +
    +
    `}Ho(o,"error")}finally{y.isRunning=!1,i&&(i.disabled=!1,i.innerHTML=` + + + Run Pipeline`),en()}}function a_(){const t=document.getElementById("code-generator-model").value,e=[pi,"anthropic/claude-opus-5","openai/gpt-5.6-sol"].filter(i=>i!==t),n=prompt(`Retry with different model? + +Current: ${t} + +Options: +1. ${e[0]} +2. ${e[1]} + +Enter 1 or 2:`);n==="1"?(document.getElementById("code-generator-model").value=e[0],Ns()):n==="2"&&(document.getElementById("code-generator-model").value=e[1],Ns())}async function l_(){const t=Fa();if(!t){ue("No code to commit. Please run the pipeline first.","warning");return}const e=await Ee("flutterflow"),n=await Ee("flutterflow_project_id");if(!e||!n){ue("FlutterFlow credentials not configured. Add your API Key and Project ID in settings.","warning"),ka();return}if(y.artifactBundle?.artifacts?.length>1){await c_();return}const{artifactType:i,artifactName:s,fileName:r}=oh(),o=dh(t,{artifactType:i,artifactName:s,fileName:r}),a=Gv(o);if(!a.canProceed){ue(`Pre-commit checks failed: ${a.issues.join("; ")}`,"error");return}Wa(o,a,null,null)}async function c_(){const t=await Ee("flutterflow"),e=await Ee("flutterflow_project_id");if(!t||!e){ue("FlutterFlow credentials not configured. Add your API Key and Project ID in settings.","warning"),ka();return}const n=zg(y.artifactBundle);if(n.errors.length>0){ue(`Bundle validation failed: ${n.errors.join("; ")}`,"error");return}const i=new Map(n.fileEntries.map(a=>[a.fileName,{content:a.content,type:a.type,path:a.path}])),s=er(i),r={canProceed:s.valid&&n.errors.length===0,issues:[...n.errors,...s.errors],warnings:[...n.warnings,...s.warnings]};if(!r.canProceed){ue(`Bundle validation failed: ${r.issues.join("; ")}`,"error");return}const o={content:n.fileEntries.map(a=>`// ${a.fileName} +${a.content}`).join(` + +`),fileName:`${n.fileEntries.length} files`,codeType:"bundle",artifactType:"Bundle",artifactName:n.title};Wa(o,r,n.dependencies,n)}function u_(t){let e=t.errorMap||new Map;!(e instanceof Map)&&typeof e=="object"&&(e=new Map(Object.entries(e)));let n=`
    +

    FlutterFlow Commit Failed

    +

    ${j(t.error)}

    `;if(e&&e.size>0){n+=`
    +

    Errors:

    +
      `;for(const[s,r]of e.entries()){const o=Bd(r);n+=`
    • + ${j(s)}: ${j(o)} +
    • `}n+="
    "}n+="
    ",n+=`
    + +
    `;const i=document.getElementById("step3-output");i&&(i.innerHTML=n,document.getElementById("btn-regenerate-from-error")?.addEventListener("click",()=>{d_(t.error,e)}))}async function d_(t,e){if(y.isRunning)return;const n=document.getElementById("code-generator-model").value;y.isRunning=!0;const i=document.getElementById("btn-regenerate-from-error");i&&(i.disabled=!0,i.innerHTML=` + + Fixing...`);try{let s=`The previous code had the following errors when committing to FlutterFlow: + +`;if(e&&e.size>0)for(const[c,d]of e.entries()){const h=Bd(d);s+=`File: ${c} +Error: ${h} + +`}else s+=`${t} +`;const r=$d({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,userFeedback:s});or(),at(2),ze(2),ve(2,!0),y.step2Result=await tr(r,n),Zs();const o=document.getElementById("step2-output"),a=xn(y.step2Result);o.textContent=a,o.dataset.raw=a,ve(2,!1),ze(3),at(3),ve(3,!0),y.step3Result=await nr(y.step2Result,y.step1Result),Xs();const l=document.getElementById("step3-output");l.textContent=y.step3Result,ve(3,!1),Mt();const u=Ks(y.step3Result);ar(a,u)}catch(s){console.error("Regeneration failed:",s),Mt(),ue(La(s,"Regeneration failed"),"error")}finally{y.isRunning=!1,i&&(i.disabled=!1,i.textContent="Fix Errors & Regenerate"),en()}}async function h_(){const t=document.getElementById("ff-status-dot"),e=document.getElementById("ff-status-text");if(!t||!e)return;const n=await Ee("flutterflow"),i=await Ee("flutterflow_project_id");n&&i?(t.className="w-2 h-2 rounded-full bg-green-500",e.textContent="FlutterFlow credentials configured",e.className="text-green-600"):n||i?(t.className="w-2 h-2 rounded-full bg-yellow-500",e.textContent="FlutterFlow credentials incomplete",e.className="text-yellow-600"):(t.className="w-2 h-2 rounded-full bg-red-500",e.textContent="FlutterFlow credentials not configured",e.className="text-red-600")}async function p_(t){try{const e=await fetch(`${Ze}/auth/send-magic-link`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:t})});if(!e.ok)throw new Error(`Failed to send magic link: HTTP ${e.status}`);return e.json()}catch(e){throw console.error("sendMagicLink failed:",{email:t,message:e.message,stack:e.stack}),e}}async function f_(t){try{const n=await(await fetch(`${Ze}/auth/verify-magic-link`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:t})})).json();if(n.error||!n.email||!n.sessionToken)throw new Error(n.error||"Invalid or expired link");return n}catch(e){throw console.error("verifyMagicLink failed:",{message:e.message,stack:e.stack}),e}}async function g_(t){try{const e=await fetch(`${Ze}/auth/refresh-session`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:t})});if(!e.ok)return console.error("refreshSession: non-OK response",{url:`${Ze}/auth/refresh-session`,status:e.status}),null;const n=await e.json();return n.error||!n.email||!n.sessionToken?(console.warn("refreshSession: validation failed",{error:n.error,hasEmail:!!n.email,hasToken:!!n.sessionToken}),null):n}catch(e){return console.error("refreshSession: fetch failed",{url:`${Ze}/auth/refresh-session`,message:e.message,stack:e.stack}),null}}function Nc(t,e){const n=hh(),i=(V.email||n.email)!==t;V.email=t,V.sessionToken=e,V.isVerified=!0,pe=kn({isLoading:!0}),localStorage.setItem(Is,JSON.stringify({email:t,sessionToken:e})),i&&Ha()}function Ba(){V.email=null,V.sessionToken=null,V.isVerified=!1,pe=kn({isResolved:!0}),localStorage.removeItem(Is),localStorage.removeItem(As)}function hh(){try{const t=localStorage.getItem(Is);if(!t)return{email:null,sessionToken:null};const e=JSON.parse(t);return!e.email||!e.sessionToken?{email:null,sessionToken:null}:e}catch(t){return console.warn("getStoredSession: failed to parse auth session:",t),localStorage.removeItem(Is),{email:null,sessionToken:null}}}async function m_(){const e=new URLSearchParams(window.location.search).get("token");if(e){window.history.replaceState({},"",window.location.pathname+window.location.hash);try{const{email:n,sessionToken:i}=await f_(e);Nc(n,i)}catch(n){ue(n.message||"Sign-in link invalid or expired.","error")}}else{const{email:n,sessionToken:i}=hh();if(n&&i){const s=await g_(i);s?Nc(s.email,s.sessionToken):Ba()}}ja()}function Da(){const t=document.getElementById("signin-modal");t&&Ve(t)}function v_(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("signin-modal");e&&Xe(e)}async function __(){const t=document.getElementById("signin-email-input"),e=document.getElementById("signin-submit-btn"),n=document.getElementById("signin-message"),i=zs(t?.value);if(!i||!/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/.test(i)||i.length>254){n&&(n.textContent="Please enter a valid email address.");return}e&&(e.disabled=!0,e.textContent="Sending…");const r=Dd(i);n&&r&&(n.textContent=r);try{const o=await p_(i);t&&o?.code!==Ki&&(t.value=""),n&&(n.textContent=Em(o,i)),e&&(e.textContent=o?.code===Ki?"Send Link":"Sent!"),e&&o?.code===Ki&&(e.disabled=!1)}catch(o){console.error("handleMagicLinkRequest: sendMagicLink failed",{email:i,err:o}),n&&(n.textContent="Something went wrong. Please try again."),e&&(e.disabled=!1,e.textContent="Send Link")}}function y_(){Ba(),Ha(),ja(),rr()}function ja(){const t=V.isVerified&&!!V.email,e=document.getElementById("auth-signedout"),n=document.getElementById("auth-signedin"),i=document.getElementById("auth-guest-usage");e&&e.classList.toggle("hidden",t),n&&n.classList.toggle("hidden",!t),i&&i.classList.toggle("hidden",t);const s=document.getElementById("auth-user-email");s&&(s.textContent=V.email||""),Qi(),rr()}async function ph(){try{if(typeof FingerprintJS>"u"){console.warn("resolveIdentity: FingerprintJS not loaded, skipping");return}const e=await(await FingerprintJS.load()).get(),n=e.visitorId,i=await fetch(cv,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({fingerprint:e.visitorId,cookie_id:n})});if(!i.ok)throw new Error(`Identity check HTTP ${i.status}`);const s=await i.json();if(Ke.userId=s.user_id,Ke.token=s.identity_token||null,Ke.status=s.status,Ke.resolved=!0,sessionStorage.setItem(av,s.user_id),Ke.token&&sessionStorage.setItem(lv,Ke.token),s.usage_count!==void 0){const r=Rt(),a=(s.usage_month||r)===r?s.usage_count:0;localStorage.setItem(Zt,JSON.stringify({count:a,month:r})),ii()}console.log(`Identity resolved: ${s.status} (${s.user_id.slice(0,8)}...) usage: ${s.usage_count??"n/a"}`)}catch(t){console.error("resolveIdentity failed:",t)}}let Ur=null;function w_(t=5e3){return Ke.resolved?Promise.resolve():(Ur||(Ur=ph().catch(e=>{console.warn("ensureIdentityReady: identity resolution failed",e)})),Promise.race([Ur,new Promise(e=>setTimeout(e,t))]))}function fh(){const t=Rt();try{const e=localStorage.getItem(Zt);return e?JSON.parse(e):{count:0,month:t}}catch(e){return console.warn("getUsageData: failed to parse usage storage",{key:Zt,month:t,err:e}),localStorage.removeItem(Zt),{count:0,month:t}}}function Rt(){const t=new Date;return`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,"0")}`}function bi(){const t=fh();return t.month!==Rt()?{count:0,month:Rt()}:t}function b_(){const e={count:bi().count+1,month:Rt()};return localStorage.setItem(Zt,JSON.stringify(e)),e}function ir(){return!!pe.isLoading}function Nt(){return!!pe.isResolved}function E_(t){if(!t)return null;const e=String(t).toLowerCase().replace(/[^a-z0-9]+/g,"_");return e==="pro"||e==="professional_plan"?"professional":e==="power_developer"||e==="power_plan"?"power":Object.prototype.hasOwnProperty.call(Cs,e)?e:null}function S_(t){return t&&Object.entries(Gd).find(([,e])=>e===t)?.[0]||null}function Di(...t){return t.find(e=>e!=null&&e!=="")}function x_(...t){return t.find(e=>e&&typeof e=="object")||{}}function k_(t){const e=t.data&&typeof t.data=="object"?t.data:t,n=x_(e.subscription,e.stripeSubscription,e.currentSubscription,e.customer?.subscriptions?.data?.[0],e.subscriptions?.data?.[0],e.subscriptions?.[0]),i=e.metadata||n.metadata||e.customer?.metadata||{},s=Di(e.priceId,e.price_id,e.stripePriceId,e.stripe_price_id,n.priceId,n.price_id,n.plan?.id,n.price?.id,n.items?.data?.[0]?.price?.id,n.items?.[0]?.price?.id,n.lines?.data?.[0]?.price?.id),r=Di(e.status,e.subscriptionStatus,e.subscription_status,n.status,"none"),o=E_(Di(e.tier,e.plan,e.planId,e.plan_id,e.subscriptionTier,e.subscription_tier,e.product,e.productName,n.tier,n.plan,i.tier,i.plan)),a=uv.has(String(r).toLowerCase()),l=e.active===!0||e.isSubscribed===!0||e.subscribed===!0||e.hasSubscription===!0,u=o||S_(s)||(a||l?"professional":"free");return kn({tier:u,status:r,periodEnd:Di(e.periodEnd,e.currentPeriodEnd,e.current_period_end,n.current_period_end,n.periodEnd,null),isResolved:!0})}function sr(){return Cs[pe.tier]??Cs.free}async function I_(){if(V.isVerified&&(!Nt()||ir())&&(await gh({force:!0}),rr()),V.isVerified&&!Nt())return ue("Could not verify your subscription. Please refresh or try Manage billing.","error"),!1;const{count:t}=bi(),e=sr();if(t>=e)return Ua(t,e,{openModal:!0}),!1;const n=Math.floor(e*.8);if(t>=n){const i=e-t;ue(`${i} run${i===1?"":"s"} remaining this month.`,"warning")}return!0}function Hr(){const t=document.getElementById("paywall-exhausted");t&&t.classList.add("hidden")}function Ua(t,e,n={}){An(!0);const i=document.getElementById("walkthrough-modal");i&&Xe(i,{restoreFocus:!1});const s=document.getElementById("ready-state");s&&s.classList.add("hidden");const r=document.getElementById("preview-frame-container");r&&(r.style.display="none");const o=document.getElementById("main-stage-container");o&&o.classList.add("visible");const a=document.getElementById("results-view");a&&a.classList.remove("visible"),document.body.classList.remove("results-fullscreen","results-with-sidebar");const l=document.getElementById("pipeline-progress");l&&l.classList.remove("visible");const u=document.getElementById("paywall-exhausted");if(!u){ue(`You've used all ${e} runs for this month. Upgrade to continue.`,"error"),Ls();return}const c=document.getElementById("paywall-exhausted-text");if(c){const h=pe.tier;h==="free"?c.textContent=`You've used all ${e} free generations this month. Upgrade to Pro for 50 generations/month and access to all AI models.`:c.textContent=`You've used all ${e} generations this month on your ${h} plan. Your limit resets next month.`}const d=document.getElementById("paywall-signin-btn");d&&d.classList.toggle("hidden",V.isVerified),u.classList.remove("hidden"),n.openModal&&Ls()}function zo(t){return pe.tier==="free"&&Ji.includes(t)?pi:t}function C_(){const t=document.getElementById("code-options-content"),e=document.getElementById("code-generator-model");if(!t||!e)return;const n=pe.tier,s=!(V.isVerified&&!Nt())&&n==="free";Array.from(e.options).forEach(o=>{const a=Kt(o.value),l=Ji.includes(o.value);o.textContent=l&&s?`${a} (PRO)`:a,o.disabled=!1}),s&&Ji.includes(e.value)&&(e.value=pi),e.disabled=!1,Ic.has(e)||(e.addEventListener("change",()=>{Nt()&&pe.tier==="free"&&Ji.includes(e.value)&&(e.value=pi,Ls()),Wo(e.value),Jd()}),Ic.add(e));let r=document.getElementById("model-selector-free-notice");s?(r||(r=document.createElement("p"),r.id="model-selector-free-notice",r.className="text-xs text-gray-400 mt-1",t.appendChild(r)),r.innerHTML='Free plan — Gemini only. '):r&&r.remove(),Wo(e.value)}function ii(){const t=document.getElementById("usage-counter");if(!t)return;if(V.isVerified&&ir()){t.textContent="Checking plan…",t.className="text-xs text-gray-500",Qi(),Hr();return}if(V.isVerified&&!Nt()){t.textContent="Plan check failed",t.className="text-xs text-red-600 font-medium",Qi(),Hr();return}const{count:e}=bi(),n=sr();t.textContent=`${e} / ${n} runs this month`;const i=n>0?e/n:0;t.className=i>=1?"text-xs text-red-600 font-medium":i>=.8?"text-xs text-yellow-600 font-medium":"text-xs text-gray-500",Qi(),e>=n&&!y.isRunning?Ua(e,n):Hr()}function Qi(){const t=document.getElementById("guest-usage-text");if(!t)return;const e=fh(),n=e.month===Rt()?e.count??0:0,i=Cs.free;t.textContent=`${n} / ${i} generations used`}async function gh(t={}){const e=t.force===!0;if(!V.isVerified||!V.sessionToken){pe=kn({isResolved:!0});return}pe={...pe,isLoading:!0,error:null};const n=localStorage.getItem(As);if(!e&&n)try{const{data:i,email:s,ts:r,version:o}=JSON.parse(n);if(o===Cc&&s===V.email&&Date.now()-r<300*1e3){pe={...i,isLoading:!1,isResolved:i.isResolved!==!1};return}}catch(i){console.warn("Failed to parse subscription cache:",i,"| raw value:",n)}try{const s=await(await fetch(`${Ze}/stripe/get-subscription`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:V.sessionToken,user_id:Ke.userId})})).json();if(s.error){if(["unauthorized","invalid session","expired session"].some(o=>String(s.error).toLowerCase().includes(o))){Ba(),ja();return}pe=kn({isResolved:!1,error:s.error});return}pe=k_(s),localStorage.setItem(As,JSON.stringify({version:Cc,data:pe,email:V.email,ts:Date.now()}))}catch(i){console.error("fetchSubscription failed:",i),pe={...pe,isLoading:!1,isResolved:!1,error:i.message}}}function Ha(){localStorage.removeItem(As)}async function A_(t){if(!V.isVerified||!V.sessionToken){mh(),Da();return}if(!Gd[t]){ue("Invalid plan selected.","error");return}const e=document.getElementById(`checkout-btn-${t}`);e&&(e.disabled=!0,e.textContent="Redirecting…");try{const i=await(await fetch(`${Ze}/stripe/create-checkout-session-intl`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tierId:t,sessionToken:V.sessionToken,currency:Xd()})})).json();if(i.error||!i.url)throw new Error(i.error||"Failed to create checkout session");const{url:s}=i;window.location.href=s}catch(n){console.error("startCheckout failed:",n),e&&(e.disabled=!1,e.textContent="Subscribe"),ue("Could not start checkout. Please try again.","error")}}async function F_(){if(!V.isVerified||!V.sessionToken){Da();return}const t=document.getElementById("manage-billing-btn");t&&(t.disabled=!0,t.textContent="Loading…");try{const n=await(await fetch(`${Ze}/stripe/create-portal-session`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:V.sessionToken})})).json();if(n.error||!n.url)throw new Error(n.error||"Failed to open billing portal");const{url:i}=n;window.location.href=i}catch(e){console.error("openCustomerPortal failed:",e),t&&(t.disabled=!1,t.textContent="Manage billing"),ue("Could not open billing portal. Please try again.","error")}}async function Ms(t,e,n,i={},s=[]){const o=new AbortController,a=setTimeout(()=>o.abort(),12e4);try{const l=await fetch(ov,{method:"POST",headers:{"Content-Type":"application/json",...Ke.token?{Authorization:`Bearer ${Ke.token}`}:{}},signal:o.signal,body:JSON.stringify({user_id:Ke.userId,step:t,model:e,prompt:n,images:s,context:i})}),u=await l.text();let c={};try{c=u?JSON.parse(u):{}}catch{c={}}if(l.status===429){c.serverCount!==void 0&&(localStorage.setItem(Zt,JSON.stringify({count:c.serverCount,month:Rt()})),ii());const p=new Error(c.message||"Monthly usage limit reached. Upgrade to continue.");throw p.isUsageLimit=!0,p}const d=fg(c,t);if(d)throw d;if(console.log(`[BuildShip] ${t} response keys:`,Object.keys(c),"content type:",typeof c.content),!l.ok)throw new Error(`${c.message||c.error||"BuildShip pipeline error"} (HTTP ${l.status})`);if(t==="generator")if(c.usage_status==="success"&&Number.isFinite(c.usage_count)){const p=Rt();(c.usage_month||p)===p&&(localStorage.setItem(Zt,JSON.stringify({count:c.usage_count,month:p})),ii())}else b_(),ii();let h=c.output||c.content;if(!h){const p=u?` (body: ${u.slice(0,120)})`:"";throw new Error(`BuildShip returned no output for step "${t}"${p}`)}return Array.isArray(h)&&(h=h.map(p=>typeof p=="string"?p:p.text||"").join("")),typeof h!="string"&&(h=JSON.stringify(h)),h}catch(l){throw l.name==="AbortError"?new Error(`BuildShip ${t} timed out after ${12e4/1e3}s`):l instanceof TypeError?new Error(`BuildShip unreachable: ${l.message}`):l}finally{clearTimeout(a)}}function P_(){const e=new URLSearchParams(window.location.search).get("checkout");e==="success"?(window.history.replaceState({},"",window.location.pathname+window.location.hash),Ha(),ue("Subscription active! Welcome aboard.","success")):e==="cancel"&&(window.history.replaceState({},"",window.location.pathname+window.location.hash),ue("Checkout cancelled.","info"))}function rr(){const t=V.isVerified&&!!V.email,e=pe.tier,n=t&&ir(),i=!t||Nt(),s=document.getElementById("subscription-tier-badge");if(s){const a={free:"Free",professional:"Professional",power:"Power Developer"},l={free:"bg-gray-100 text-gray-600",professional:"bg-indigo-100 text-indigo-700",power:"bg-purple-100 text-purple-700",unresolved:"bg-red-50 text-red-600"};s.textContent=n?"Checking…":i?a[e]||"Free":"Plan unavailable",s.className=`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${i?l[e]||l.free:l.unresolved}`}const r=document.getElementById("upgrade-prompt");r&&r.classList.toggle("hidden",!t||n||!i||e!=="free");const o=document.getElementById("manage-billing-btn");o&&o.classList.toggle("hidden",!t||n||i&&e==="free"),$_(i?e:null),C_(),Jd(),ii(),xh()}function $_(t){const e=["bg-gray-100","text-gray-500","cursor-default"];Object.entries({professional:{btnId:"checkout-btn-professional",defaultText:"Subscribe"},power:{btnId:"checkout-btn-power",defaultText:"Subscribe"}}).forEach(([s,{btnId:r,defaultText:o}])=>{const a=document.getElementById(r);a&&(s===t?(a.disabled=!0,a.textContent="Current plan",a.classList.add(...e)):(a.disabled=!1,a.textContent=o,a.classList.remove(...e)))});const i=document.getElementById("free-tier-current");i&&i.classList.toggle("hidden",t!=="free")}function qo(){const t=Xd(),e=document.getElementById("pro-price"),n=document.getElementById("power-price"),i=document.getElementById("plans-pro-price"),s=document.getElementById("plans-power-price"),r=document.getElementById("pro-price-note"),o=document.getElementById("power-price-note"),a=document.getElementById("plans-pro-price-note"),l=document.getElementById("plans-power-price-note");e&&(e.textContent=Bi(Oi.professional,t)),n&&(n.textContent=Bi(Oi.power,t)),i&&(i.textContent=Bi(Oi.professional,t)),s&&(s.textContent=Bi(Oi.power,t));const u="billed monthly";r&&(r.textContent=u),o&&(o.textContent=u),a&&(a.textContent=u),l&&(l.textContent=u)}function Ls(){qo();const t=document.getElementById("pricing-modal");t&&Ve(t),yv().then(()=>qo())}function mh(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("pricing-modal");e&&Xe(e)}function ue(t,e="info"){const n={success:"bg-green-600 text-white",error:"bg-red-600 text-white",warning:"bg-amber-500 text-white",info:"bg-gray-800 text-white"},i=document.createElement("div");i.className=`fixed bottom-6 left-1/2 -translate-x-1/2 px-5 py-3 rounded-lg text-sm font-medium shadow-lg z-50 transition-opacity duration-300 ${n[e]||n.info}`,i.textContent=t,document.body.appendChild(i),setTimeout(()=>{i.style.opacity="0",setTimeout(()=>i.remove(),300)},3500)}document.addEventListener("DOMContentLoaded",async()=>{tg(),hljs.configure({tabReplace:" ",classPrefix:"hljs-"}),T_(),await m_(),P_(),await gh(),rr(),qo(),await zv(),Dv();const t=document.getElementById("flutterflow-endpoint-select");if(t){const n=yi();t.value=n}sh(),ph();const e=document.getElementById("pipeline-input");e&&(e.addEventListener("input",()=>{kt===2&&e.value.trim().length>0&&(Ia(),Js())}),e.addEventListener("blur",()=>{const n=document.getElementById("walkthrough-modal");kt===2&&n&&Ve(n)}),e.addEventListener("keydown",n=>{if(n.key==="Tab"){const i=document.getElementById("walkthrough-modal");kt===2&&i&&setTimeout(()=>{Ve(i)},100)}})),window.addEventListener("commitStateChange",n=>{const{state:i}=n.detail;i===K.PREPARING||i===K.VALIDATING||i===K.PUSHING?(be.phaseId||_h(),Lc(i)):(i===K.SUCCESS||i===K.ERROR)&&(Lc(i),setTimeout(Os,1e3))}),sv({onSubmit:Ns}),qa()});function T_(){const t=document.getElementById("preview-frame-container");t&&(t.style.display="")}function R_(){const t=document.getElementById("welcome-video-player");t&&(t.addEventListener("click",Qt),document.addEventListener("keydown",Qt))}function Qt(){const t=document.getElementById("preview-frame-container"),e=document.getElementById("main-stage-container"),n=document.getElementById("ready-state");t&&(t.style.display="none"),e&&e.classList.add("visible"),n&&n.classList.remove("hidden");const i=document.getElementById("welcome-video-player");i&&i.removeEventListener("click",Qt),document.removeEventListener("keydown",Qt),sh()}let si=null;async function N_(){const t=document.getElementById("confirm-project-select");if(!t)return;const e=++Tc,n=()=>e===Tc,i=await Ee("flutterflow"),s=await Ee("flutterflow_project_id");if(n()){if(!i){t.innerHTML='',t.disabled=!0;return}t.disabled=!1,t.innerHTML='';try{const o=await new wi(i,"").listProjects();if(!n())return;if(!o||o.length===0){t.innerHTML='';return}t.innerHTML='',o.forEach(a=>{const l=document.createElement("option");l.value=a.id||a.projectId||"",l.textContent=a.name||a.projectName||`Project ${a.id}`,t.appendChild(l)}),s&&(t.value=s)}catch(r){if(!n())return;console.error("Failed to load projects for deploy:",r),t.innerHTML=''}}}function M_(){return document.getElementById("confirm-project-select")?.value?.trim()||null}function Wa(t,e,n,i=null){si={codeInfo:t,checks:e,deps:n,bundlePlan:i},document.getElementById("confirm-file-name").textContent=t.fileName,document.getElementById("confirm-artifact-type").textContent=t.artifactType,document.getElementById("confirm-file-size").textContent=`${(t.content.length/1024).toFixed(1)} KB`,document.getElementById("confirm-line-count").textContent=i?`${i.fileEntries.length} files`:t.content.split(` +`).length,N_();const s=document.getElementById("confirm-deps-list"),r=document.getElementById("confirm-deps-section");n&&Object.keys(n).length>0?(s.innerHTML=Object.entries(n).map(([u,c])=>{const d=c?`at least ${xt(c)}`:"version resolved from your project";return`
  • • ${xt(u)}: ${d}
  • `}).join(""),r.classList.remove("hidden")):r.classList.add("hidden");const o=document.getElementById("confirm-warnings-list"),a=document.getElementById("confirm-warnings-section");e.warnings&&e.warnings.length>0?(o.innerHTML=e.warnings.map(u=>`
  • • ${xt(u)}
  • `).join(""),a.classList.remove("hidden")):a.classList.add("hidden"),document.getElementById("confirm-code-preview").textContent=t.content,document.getElementById("code-preview-content").classList.add("hidden"),document.getElementById("code-preview-chevron").style.transform="rotate(0deg)";const l=document.getElementById("commit-confirm-modal");l&&Ve(l)}function vh(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("commit-confirm-modal");e&&Xe(e),si=null}function L_(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("commit-success-modal");e&&Xe(e);const n=["success-message","success-project-id","success-file-name","success-artifact-type","success-time","success-size"];for(const r of n){const o=document.getElementById(r);o&&(o.textContent="")}const i=document.getElementById("success-warnings-section");i&&i.classList.add("hidden");const s=document.getElementById("success-warnings-list");s&&(s.innerHTML="")}function Vo(t){const e=(g,m)=>{const v=document.getElementById(g);v&&(v.textContent=m||"")},n=t.metadata?.fileName||"",i=t.metadata?.projectId||"",s=t.metadata?.artifactType||"",r=t.elapsedTime?`${(t.elapsedTime/1e3).toFixed(1)}s`:"",o=t.metadata?.codeSize?`${(t.metadata.codeSize/1024).toFixed(1)} KB`:"";e("success-message",t.message||"Code committed successfully!"),e("success-project-id",i),e("success-file-name",n),e("success-artifact-type",s),e("success-time",r),e("success-size",o);const a=t.addedDependencies||[],l=document.getElementById("success-deps-row");l&&l.classList.toggle("hidden",a.length===0),e("success-deps",a.join(", "));const u=document.getElementById("success-open-ff-link");u&&i&&(u.href=`https://app.flutterflow.io/project/${i}`);const c=document.getElementById("success-warnings-section"),d=document.getElementById("success-warnings-list"),h=t.unverified||[],p=t.warnings||[];(p.length>0||h.length>0)&&c&&d&&(d.innerHTML=[...h.map(g=>`
  • Not verified before deploying: ${j(String(g))}
  • `),...p.map(([g,m])=>`
  • ${j(g)}: ${j(String(m))}
  • `)].join(""),c.classList.remove("hidden"));const f=document.getElementById("commit-success-modal");f&&Ve(f)}function Go(t){Os(),u_(t)}function O_(){const t=document.getElementById("code-preview-content"),e=document.getElementById("code-preview-chevron");t.classList.contains("hidden")?(t.classList.remove("hidden"),e.style.transform="rotate(90deg)"):(t.classList.add("hidden"),e.style.transform="rotate(0deg)")}const Mc={prepare:{message:"Preparing your code...",start:4,end:14},validate:{message:"Checking FlutterFlow credentials...",start:14,end:22},project:{message:"Reading your FlutterFlow project...",start:22,end:40},provision:{message:"Creating custom classes in FlutterFlow...",start:40,end:82},package:{message:"Packaging files for upload...",start:82,end:88},push:{message:"Pushing to FlutterFlow...",start:88,end:97},done:{message:"Complete!",start:100,end:100}},B_=[{after:0,text:"Starting a FlutterFlow build runner..."},{after:12,text:"Preparing the FlutterFlow AI workspace..."},{after:35,text:"Uploading your custom classes..."},{after:60,text:"FlutterFlow is applying the changes..."},{after:100,text:"Still working — this can take a couple of minutes..."}],be={sequence:[],phaseId:null,phaseStartedAt:null,timer:null,substatus:null,liveSubstatus:!1,start({withProvisioning:t=!1}={}){this.sequence=["prepare","validate","project"],t&&this.sequence.push("provision"),this.sequence.push("package","push","done");const e=document.getElementById("commit-progress-overlay");e&&(oc(e,!0,"Deploying to FlutterFlow"),Ve(e)),this.set("prepare")},set(t,e=null){if(!(!Mc[t]||t===this.phaseId)){if(!this.sequence.includes(t)){const n=this.sequence.indexOf("package");this.sequence.splice(n===-1?this.sequence.length:n,0,t)}this.phaseId=t,this.phaseStartedAt=Date.now(),this.substatus=e,this.liveSubstatus=!1,this.render(),this.timer&&clearInterval(this.timer),t!=="done"&&(this.timer=setInterval(()=>this.render(),500))}},setSubstatus(t){t&&(this.liveSubstatus=!0,this.substatus=t,this.render())},render(){const t=Mc[this.phaseId];if(!t)return;const e=(Date.now()-this.phaseStartedAt)/1e3,n=t.start+(t.end-t.start)*(1-Math.exp(-e/25));if(this.phaseId==="provision"&&!this.liveSubstatus){const o=B_.filter(a=>e>=a.after).pop();o&&(this.substatus=o.text)}const i=this.sequence.indexOf(this.phaseId),r=[`Step ${i===-1?1:i+1} of ${this.sequence.length}`];e>=5&&r.push(D_(e)),yh(this.phaseId==="done"?100:n,t.message,r.join(" · "),this.substatus)},stop(){this.timer&&clearInterval(this.timer),this.timer=null,this.phaseId=null;const t=document.getElementById("commit-progress-overlay");t&&(oc(t,!1),Xe(t,{force:!0,restoreFocus:!1}))}};function D_(t){const e=Math.floor(t);return e<60?`${e}s elapsed`:`${Math.floor(e/60)}m ${String(e%60).padStart(2,"0")}s elapsed`}function _h(t){be.start(t)}function Os(){be.stop()}function yh(t,e,n,i=null){const s=document.getElementById("commit-progress-bar"),r=document.getElementById("progress-message"),o=document.getElementById("progress-detail"),a=document.getElementById("progress-substatus");s&&(s.style.width=`${Math.round(t*10)/10}%`),r&&(r.textContent=e),o&&(o.textContent=n),a&&(a.textContent=i||"",a.classList.toggle("hidden",!i))}function Lc(t){const e={[K.PREPARING]:"prepare",[K.VALIDATING]:"validate",[K.PUSHING]:"project",[K.SUCCESS]:"done"};if(t===K.ERROR){be.timer&&clearInterval(be.timer),be.timer=null,yh(100,"Failed","Error occurred");return}const n=e[t];n&&be.set(n)}function j_(t){return t.bundlePlan?t.bundlePlan.fileEntries.some(e=>e.type===W.CODE_FILE):t.codeInfo?.codeType===W.CODE_FILE}async function U_(){if(!si){console.error("No pending commit data");return}const t=si;if(si=null,ni=M_(),vh(),_h({withProvisioning:j_(t)}),t.bundlePlan){const o=await Qv(t.bundlePlan,{pipelineResult:{step1Result:y.step1Result,selectedModel:document.getElementById("code-generator-model")?.value}});ni=null,Os(),o.success?Vo(o):Go(o);return}const{codeInfo:e}=t,{artifactType:n,artifactName:i,fileName:s}=oh(),r=await Xv(e.content,{artifactType:n,artifactName:i,fileName:s,pipelineResult:{step1Result:y.step1Result,selectedModel:document.getElementById("code-generator-model")?.value}});ni=null,Os(),r.success?Vo(r):Go(r)}window.runThinkingPipeline=Ns;window.toggleStep=n_;window.toggleSection=t_;window.selectWorkflowStep=ze;window.copyCode=i_;window.retryWithDifferentModel=a_;window.openApiKeysModal=ka;window.closeApiKeysModal=nh;window.closeWalkthroughModal=Rv;window.openWalkthroughModal=Tv;window.advanceWalkthrough=Ia;window.commitToFlutterFlow=Zv;function H_(){const t=document.getElementById("pipeline-input");t&&t.focus()}function W_(){const t=document.getElementById("advanced-settings");t&&(t.open=!0);const e=document.getElementById("code-generator-model");e&&(e.scrollIntoView({behavior:"smooth",block:"center"}),e.focus(),e.click())}window.focusPromptInput=H_;window.openModelSelector=W_;window.handlePromptImageSelect=vv;window.removePromptImage=_v;window.saveApiKeys=Lv;window.clearAllApiKeys=Ov;window.toggleKeyVisibility=Uv;window.handleWelcomeVideoEnd=R_;window.dismissWelcomeVideo=Qt;window.initiateCommitToFlutterFlow=l_;window.updateFlutterFlowCredentialStatus=h_;window.openCommitConfirmModal=Wa;window.closeCommitConfirmModal=vh;window.closeCommitSuccessModal=L_;window.showCommitSuccessModal=Vo;window.showCommitFailureModal=Go;window.toggleCodePreview=O_;window.confirmCommitToFlutterFlow=U_;window.runRefinement=s_;window.regenerateFromPastedErrors=o_;window.clearErrorInput=r_;window.setFlutterFlowEndpoint=$v;window.getFlutterFlowEndpoint=yi;window.commitProgress=be;window.openSignInModal=Da;window.closeSignInModal=v_;window.handleMagicLinkRequest=__;window.handleSignOut=y_;window.startCheckout=A_;window.openCustomerPortal=F_;window.openPricingModal=Ls;window.closePricingModal=mh;let mn=null,wh=null;const Oc=120;function or(){An(!0);const t=document.getElementById("pipeline-progress"),e=document.getElementById("results-view"),n=document.getElementById("ready-state");n&&n.classList.add("hidden"),e&&e.classList.remove("visible"),document.body.classList.remove("results-fullscreen","results-with-sidebar"),t&&t.classList.add("visible"),wh=Date.now();for(let i=1;i<=3;i++){const s=document.getElementById(`pdot-${i}`);s&&(s.className="progress-dot")}at(1),z_()}function at(t){const e={1:"Analyzing your prompt...",2:"Generating Dart code...",3:"Running code audit..."},n={1:"Step 1 of 3 — Prompt Architect",2:"Step 2 of 3 — Code Generator",3:"Step 3 of 3 — Code Review"},i=document.getElementById("progress-title-text"),s=document.getElementById("progress-substep-text");i&&(i.textContent=e[t]||e[1]),s&&(s.textContent=n[t]||n[1]);for(let r=1;r<=3;r++){const o=document.getElementById(`pdot-${r}`);o&&(r{const t=(Date.now()-wh)/1e3,e=document.getElementById("progress-elapsed"),n=document.getElementById("pipeline-progress-fill");e&&(e.textContent=`${Math.floor(t)}s`);const i=t/Oc*100,s=Math.min(95,i*(1-Math.exp(-t/(Oc*.6)))*1.2);n&&(n.style.width=`${s}%`)},250)}function Mt(){mn&&(clearInterval(mn),mn=null);const t=document.getElementById("pipeline-progress-fill");t&&(t.style.width="100%");for(let e=1;e<=3;e++){const n=document.getElementById(`pdot-${e}`);n&&(n.className="progress-dot completed")}setTimeout(()=>{const e=document.getElementById("pipeline-progress");e&&e.classList.remove("visible"),t&&(t.style.width="0%")},400)}function Cn(t,e=""){const n={pass:'',warning:'',fail:'',info:''};return``}function bh(t){return{pass:"Passed review",warning:"Needs attention",fail:"Blocking issues"}[t]||"Needs attention"}function q_(){return om({bundle:y.artifactBundle,reviewResult:y.step3Result})}function V_(t){return` +
    + ${Cn(t.severity)} +
    +
    ${j(t.message)}
    + ${t.suggestion?`
    ${j(t.suggestion)}
    `:""} + ${j(t.source)} +
    +
    + `}function G_(t){return` +
  • +
    + ${j(t.title)} + ${t.detail&&t.detail!==t.title?`

    ${j(t.detail)}

    `:""} +
    +
  • + `}function K_(t){const e=document.getElementById("results-summary-detail"),n=document.getElementById("results-title");if(!e)return;n&&(n.textContent=t.title);const i=t.score,s=i==null?"neutral":i>=80?"pass":i>=60?"warning":"fail",r=i==null?"":i>=80?"Strong":i>=60?"Needs work":"High risk",o=t.findings.length?` +
      + ${t.findings.map(l=>` +
    • + ${Cn(l.severity)} + + ${j(l.message)} + ${l.suggestion?`${j(l.suggestion)}`:""} + +
    • + `).join("")} +
    + `:"",a=t.manualSteps.length?` +
    +

    ${Cn("info")} Complete in FlutterFlow

    +

    For your information — these don't block the deploy. Finish them by hand in the FlutterFlow editor once the code is pushed.

    +
      + ${t.manualSteps.map(l=>` +
    • + ${j(l.title)} + ${l.detail&&l.detail!==l.title?`${j(l.detail)}`:""} +
    • + `).join("")} +
    +
    + `:"";e.innerHTML=` +
    +
    +

    ${j(t.summary)}

    + ${o} + ${a} +
    +
    + +
    + Is the generated code correct? +
    + + +
    +
    +
    +
    + `}function J_(t){const e=t.artifacts.find(l=>l.id===y.selectedArtifactId)||t.artifacts[0];if(!e)return"";const n={pass:{icon:"pass",message:"No file-specific issues were found."},warning:{icon:"warning",message:"This file needs attention, but Code Review did not return a specific finding."},fail:{icon:"fail",message:"This file is blocked, but Code Review did not return a specific finding."}}[e.status],i=e.findings.length?e.findings.map(V_).join(""):`
    ${Cn(n.icon)} ${j(n.message)}
    `,s=e.dependencies?.length?e.dependencies.map(l=>` +
  • ${j(l.name)}${l.version?` ${j(l.version)}`:""}${l.reason?`

    ${j(l.reason)}

    `:""}
  • + `).join(""):'
  • No external packages
  • ',r=e.imports?.length?e.imports.map(l=>`${j(l)}`).join(""):'No imports returned',o=e.publicApi?.length?e.publicApi.map(l=>`${j(l)}`).join(""):'No public API signature returned',a=e.relationships.length?e.relationships.map(l=>` +
  • ${j(l.from||"Bundle")} ${j(l.type)} ${j(l.to||"Bundle")}${l.description?`

    ${j(l.description)}

    `:""}
  • + `).join(""):'
  • No relationships for this file
  • ';return` +
    +
    + ${Cn(e.status)} ${j(bh(e.status))} +

    ${j(e.artifactName)}

    + ${e.description?`

    ${j(e.description)}

    `:""} +
    +
    + ${j(e.artifactType)} + ${j(e.fileName)} +
    +
    +
    +

    Code Review findings

    + ${i} +
    + ${e.manualSteps.length?` +
    +

    Manual FlutterFlow steps for this file

    +
      ${e.manualSteps.map(G_).join("")}
    +
    + `:""} +
    + File details +
    +
    +

    Dependencies

    +
      ${s}
    +
    +
    +

    Deployment

    +
    +
    Status
    ${j(e.deployStatus||"pending")}
    +
    Order
    ${e.index+1} of ${t.artifacts.length}
    +
    Path hint
    ${j(e.pathHint||"Not returned")}
    +
    +
    +
    +
    +

    Public API

    +
    ${o}
    +
    +
    +

    Imports

    +
    ${r}
    +
    +
    +

    Relationships

    +
      ${a}
    +
    +
    + `}function Y_(t){const e=document.getElementById("bundle-strip"),n=document.getElementById("results-summary-tab"),i=document.getElementById("artifact-tabs"),s=document.getElementById("results-file-count");if(n&&n.classList.toggle("active",y.resultsViewMode==="summary"),!t.artifacts.length){s&&(s.textContent="0 files"),e&&e.classList.remove("visible"),i&&(i.innerHTML="");return}if(s){const r=t.artifacts.length;s.textContent=`${r} ${r===1?"file":"files"}`}i&&(i.innerHTML=t.artifacts.map(r=>` + + `).join(""),i.onclick=r=>{const o=r.target.closest(".artifact-tab");o?.dataset?.artifactId&&Eh(o.dataset.artifactId)}),e&&e.classList.add("visible")}function za(){document.body.classList.add("results-fullscreen"),document.body.classList.add("results-with-sidebar");const t=document.getElementById("results-view"),e=document.getElementById("results-code-output"),n=document.getElementById("results-audit-output"),i=document.getElementById("results-summary-detail"),s=document.getElementById("artifact-results-split"),r=q_(),o=Fa();if(K_(r),Y_(r),e&&(e.textContent=""),e){const a=Vd(o);e.innerHTML=a}n&&(n.innerHTML=J_(r)),i&&i.classList.toggle("hidden",y.resultsViewMode!=="summary"),s&&s.classList.toggle("hidden",y.resultsViewMode!=="file"),t&&t.classList.add("visible")}function ar(t,e){An(!0),y.selectedArtifactId||(y.selectedArtifactId=Ss(y.artifactBundle).id),y.resultsViewMode="summary",document.body.classList.add("results-fullscreen");const n=document.getElementById("step3-output");n&&(n.textContent=""),za(),en();const i=document.getElementById("btn-feedback-up"),s=document.getElementById("btn-feedback-down");i&&(i.className="feedback-btn"),s&&(s.className="feedback-btn")}function Eh(t){y.selectedArtifactId=t,y.resultsViewMode="file",za()}function Z_(){y.resultsViewMode="summary",za()}function X_(){const t=document.getElementById("btn-copy-results"),e=Fa();navigator.clipboard.writeText(e).then(()=>{if(t){t.classList.add("copied");const n=t.querySelector("span");if(n){const i=n.textContent;n.textContent="Copied!",setTimeout(()=>{t.classList.remove("copied"),n.textContent=i},2e3)}}})}function Q_(t){const e=document.getElementById("btn-feedback-up"),n=document.getElementById("btn-feedback-down");t==="up"?(e.classList.toggle("active-up"),n.classList.remove("active-down")):(n.classList.toggle("active-down"),e.classList.remove("active-up")),Oa(t==="up"?"thumbsUp":"thumbsDown",y.step2Result,y.step1Result)}function ey(){const t=document.getElementById("error-input-panel");if(t){t.classList.remove("hidden"),t.style.display="flex";const e=document.getElementById("ff-error-paste-input");e&&setTimeout(()=>e.focus(),100)}}function Sh(){const t=document.getElementById("error-input-panel");t&&(t.classList.add("hidden"),t.style.display="none")}function An(t){const e=document.getElementById("generation-stage");e&&(t?(e.hidden=!1,e.inert=!1,requestAnimationFrame(()=>e.classList.add("is-active"))):(e.classList.remove("is-active"),e.inert=!0,setTimeout(()=>{e.classList.contains("is-active")||(e.hidden=!0)},260)))}function xh(){const t=V.isVerified&&!!V.email,e=pe.tier||"free",n=t&&ir(),i=!t||Nt(),r=n?"Checking…":i?{free:"Free",professional:"Pro",power:"Power"}[e]||"Free":"—",o=document.getElementById("topbar-plan");o&&(o.textContent=r);const a=document.getElementById("topbar-avatar");a&&(a.textContent=(V.email||"?")[0].toUpperCase());const l=bi(),u=`${l.count} / ${sr()} runs this month`,c=document.getElementById("topbar-credits-count");c&&(c.textContent=String(l.count));const d=document.getElementById("credits-balance");d&&(d.textContent=u);const h=document.getElementById("plans-free-current");h&&h.classList.toggle("hidden",e!=="free"||!i);const p=document.getElementById("plans-checkout-btn-professional");if(p){const g=e==="professional"&&i;p.disabled=g,p.textContent=g?"Current plan":"Subscribe"}const f=document.getElementById("plans-checkout-btn-power");if(f){const g=e==="power"&&i;f.disabled=g,f.textContent=g?"Current plan":"Subscribe"}}function ty(){xh();const t=document.getElementById("credits-modal");t&&Ve(t)}function ny(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("credits-modal");e&&Xe(e)}function kh(t,e=!0,n=!0){if(t=["home","account","plans"].includes(t)?t:"home",document.querySelectorAll(".view[data-view]").forEach(s=>{s.dataset.view===t?(s.hidden=!1,s.removeAttribute("inert"),requestAnimationFrame(()=>{s.classList.add("is-active"),n&&s.focus({preventScroll:!0})})):(s.classList.remove("is-active"),s.setAttribute("inert","true"),setTimeout(()=>{s.classList.contains("is-active")||(s.hidden=!0)},260))}),t!=="home")An(!1);else{const s=document.getElementById("main-stage-container");s&&s.classList.contains("visible")&&An(!0)}if(document.querySelectorAll(".nav-link[data-view]").forEach(s=>{const r=s.dataset.view===t;s.setAttribute("aria-current",r?"page":null),r||s.removeAttribute("aria-current")}),e){const s=t==="home"?"":`#${t}`;window.location.hash!==s&&window.history.pushState({view:t},"",s||"#")}}let Bc=!1;function qa(){const t=window.location.hash.replace(/^#/,"");kh(t||"home",!1,Bc),Bc=!0}window.addEventListener("popstate",t=>{qa()});window.addEventListener("hashchange",()=>{qa()});window.copyResultsCode=X_;window.selectArtifact=Eh;window.selectResultsSummary=Z_;window.submitResultsFeedback=Q_;window.showErrorInputPanel=ey;window.hideErrorInputPanel=Sh;window.setGenerationStageVisible=An;window.switchView=kh;window.openCreditsModal=ty;window.closeCreditsModal=ny; From 8f99fa3d4965a203060b72a4c455dcf770eba402 Mon Sep 17 00:00:00 2001 From: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> Date: Wed, 23 Sep 2026 10:14:26 +0000 Subject: [PATCH 05/11] =?UTF-8?q?fix:=20Devin=20Review=20findings=20?= =?UTF-8?q?=E2=80=94=20bind=20composer=20before=20awaited=20startup,=20gat?= =?UTF-8?q?e=20submit=20during=20chip=20typing,=20restore=20disclosed-appr?= =?UTF-8?q?oximation=20verification?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - initComposer now runs before the first awaited startup call (initializeAuth), so the send button's listener exists while auth/subscription requests are in flight; early clicks are no longer dropped.\n- Chip demo-typing now counts as busy: send stays disabled, Enter is rejected while a chip types its prompt, and doSubmit re-checks the state, so a half-typed chip prompt can never submit.\n- Restore the disclosed-approximation verification policy (planCustomCodeVerification returns approximate notices plumbed to the deploy result and success modal) instead of skipping every package-importing class — matching the approach defended in this PR's review thread.\n\nCo-Authored-By: Stuart Gardoll Co-Authored-By: Stuart Gardoll --- app.js | 30 +- dist/assets/index-CJRo2614.js | 318 ++++ dist/assets/index-CNM4BL4C.js | 317 ---- dist/assets/index-DMRXA2V6.js | 320 ---- ...{index-CleimGxe.css => index-DcLSblVK.css} | 2 +- dist/index.html | 1557 ++++++++++++----- src/composerAdapter.js | 24 +- 7 files changed, 1457 insertions(+), 1111 deletions(-) create mode 100644 dist/assets/index-CJRo2614.js delete mode 100644 dist/assets/index-CNM4BL4C.js delete mode 100644 dist/assets/index-DMRXA2V6.js rename dist/assets/{index-CleimGxe.css => index-DcLSblVK.css} (85%) diff --git a/app.js b/app.js index 7025ef2..9744035 100644 --- a/app.js +++ b/app.js @@ -2405,7 +2405,7 @@ async function provisionMissingCodeFiles( ) { const missingCodeFiles = findMissingCodeFiles(fileMap, remoteFiles); if (missingCodeFiles.length === 0) { - return { remoteFiles, syncFileMap: fileMap, unverified: [] }; + return { remoteFiles, syncFileMap: fileMap, unverified: [], approximate: [] }; } // The runner compiles these against the project's own package versions @@ -2429,6 +2429,14 @@ async function provisionMissingCodeFiles( const unverified = verificationPlan.skipped.map((entry) => entry.reason); unverified.forEach((reason) => console.warn(`[custom class deploy] ${reason}`)); + // Classes that do not import an unrepresentable package directly are still + // checked, but against a scratch graph that omits it. That approximation is + // disclosed here - before the push - and returned alongside `unverified`, + // so it reaches the deploy result and is never mistaken for a full-graph + // check. + const approximate = verificationPlan.approximate; + approximate.forEach((notice) => console.warn(`[custom class deploy] ${notice}`)); + console.log( `Provisioning ${missingCodeFiles.length} new FlutterFlow custom code file(s) before sync.`, ); @@ -2502,6 +2510,7 @@ async function provisionMissingCodeFiles( remoteFiles, syncFileMap: excludeProvisionedCodeFiles(fileMap, missingCodeFiles), unverified, + approximate, // Custom classes were actually upserted on the FlutterFlow side by the // runner. Any failure of the *remaining* sync is therefore a partial // outcome — classes wrote, the rest did not — never a clean total failure. @@ -3198,6 +3207,7 @@ async function commitToFlutterFlow(dartCode, fileName, options = {}) { message: `Successfully committed ${fileName} to FlutterFlow project ${projectId}`, addedDependencies: pubspecMerge.added, unverified: provisioning.unverified, + approximate: provisioning.approximate, warnings: result.errorMap ? Array.from(result.errorMap.entries()) : [], }; } catch (error) { @@ -3386,6 +3396,7 @@ async function executeCommit(code, options = {}) { targetIdentity, addedDependencies: pubspecMerge.added, unverified: provisioning.unverified, + approximate: provisioning.approximate, warnings: result.errorMap ? Array.from(result.errorMap.entries()) : [], elapsedTime: commitState.getElapsedTime(), }; @@ -3593,6 +3604,7 @@ async function executeBundleCommit(bundlePlan, options = {}) { targetIdentity, addedDependencies: pubspecMerge.added, unverified: provisioning.unverified, + approximate: provisioning.approximate, warnings: result.errorMap ? Array.from(result.errorMap.entries()) : [], elapsedTime: commitState.getElapsedTime(), }; @@ -6070,6 +6082,11 @@ document.addEventListener("DOMContentLoaded", async () => { // cleanup-safe on view transition; completion never depends on it. window.__pipelineLogo = createPipelineLogoLoop(); + // Bind the composer before the first awaited startup call so the send + // button's listener exists while auth/subscription requests are still in + // flight; the pipeline's own gates handle a submission that lands early. + initComposer({ onSubmit: runThinkingPipeline }); + await initializeAuth(); handleCheckoutRedirect(); await fetchSubscription(); @@ -6145,7 +6162,6 @@ document.addEventListener("DOMContentLoaded", async () => { } }); - initComposer({ onSubmit: runThinkingPipeline }); restoreViewFromHash(); }); @@ -6400,11 +6416,14 @@ function showCommitSuccessModal(result) { const warningsSection = document.getElementById("success-warnings-section"); const warningsList = document.getElementById("success-warnings-list"); // A class that could not be compiled before the push is reported here rather - // than left implicit, so "deployed" never reads as "checked". + // than left implicit, so "deployed" never reads as "checked". A class that + // was compiled against a reduced package graph is reported beside it: the + // check ran, but approximately, and that has to stay visible too. const unverified = result.unverified || []; + const approximate = result.approximate || []; const fileWarnings = result.warnings || []; if ( - (fileWarnings.length > 0 || unverified.length > 0) && + (fileWarnings.length > 0 || unverified.length > 0 || approximate.length > 0) && warningsSection && warningsList ) { @@ -6412,6 +6431,9 @@ function showCommitSuccessModal(result) { ...unverified.map((reason) => `
  • Not verified before deploying: ${escapeHtml(String(reason))}
  • ` ), + ...approximate.map((notice) => + `
  • Verified approximately: ${escapeHtml(String(notice))}
  • ` + ), ...fileWarnings.map(([file, errs]) => `
  • ${escapeHtml(file)}: ${escapeHtml(String(errs))}
  • ` ), diff --git a/dist/assets/index-CJRo2614.js b/dist/assets/index-CJRo2614.js new file mode 100644 index 0000000..d56bfd8 --- /dev/null +++ b/dist/assets/index-CJRo2614.js @@ -0,0 +1,318 @@ +(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const r of document.querySelectorAll('link[rel="modulepreload"]'))i(r);new MutationObserver(r=>{for(const s of r)if(s.type==="childList")for(const o of s.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&i(o)}).observe(document,{childList:!0,subtree:!0});function n(r){const s={};return r.integrity&&(s.integrity=r.integrity),r.referrerPolicy&&(s.referrerPolicy=r.referrerPolicy),r.crossOrigin==="use-credentials"?s.credentials="include":r.crossOrigin==="anonymous"?s.credentials="omit":s.credentials="same-origin",s}function i(r){if(r.ep)return;r.ep=!0;const s=n(r);fetch(r.href,s)}})();var w=typeof window<"u"?window:void 0,Le=typeof globalThis<"u"?globalThis:w,je=Le?.navigator,F=Le?.document,ge=Le?.location,Ya=Le?.fetch,Wo=Le!=null&&Le.XMLHttpRequest&&"withCredentials"in new Le.XMLHttpRequest?Le.XMLHttpRequest:void 0,oc=Le?.AbortController,bp=Le?.CompressionStream,We=je?.userAgent;function nd(){return!(!w||w.navigator.onLine===!1)}var pi=typeof globalThis<"u"?globalThis:w;pi&&typeof self>"u"&&(pi.self=pi),pi&&typeof File>"u"&&(pi.File=function(){});var O=w??{},ne={DEBUG:!1,LIB_VERSION:"0.5.0",LIB_NAME:"browser-common"};function ac(t,e,n,i,r,s,o){try{var a=t[s](o),l=a.value}catch(u){return void n(u)}a.done?e(l):Promise.resolve(l).then(i,r)}function re(t){return function(){var e=this,n=arguments;return new Promise((function(i,r){var s=t.apply(e,n);function o(l){ac(s,i,r,o,a,"next",l)}function a(l){ac(s,i,r,o,a,"throw",l)}o(void 0)}))}}function k(){return k=Object.assign?Object.assign.bind():function(t){for(var e=1;arguments.length>e;e++){var n=arguments[e];for(var i in n)({}).hasOwnProperty.call(n,i)&&(t[i]=n[i])}return t},k.apply(null,arguments)}function id(t,e){if(t==null)return{};var n={};for(var i in t)if({}.hasOwnProperty.call(t,i)){if(e.indexOf(i)!==-1)continue;n[i]=t[i]}return n}var lc=t=>{if(typeof t!="string")return t;try{return JSON.parse(t)}catch{return t}};function cc(t){return typeof t=="string"||t}function uc(t){return typeof t=="string"?t:void 0}var gi,Ep=["$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","irclid","_kx","$session_id","$window_id","$lib","$lib_version","$device_id","$is_server"],jt=(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.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.SurveysSeen="surveys_seen",t.Surveys="surveys",t.RemoteConfig="remote_config",t.FlagsEndpointWasHit="flags_endpoint_was_hit",t.DeviceId="device_id",t})({}),dc=(function(t){return t.GZipJS="gzip-js",t.Base64="base64",t})({}),Sp=["$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"],xp=["token"],rd="NativeGzipValidationError",qo=t=>t.length>=2&&t[0]===31&&t[1]===139,fc=(t,e)=>t===dc.GZipJS||e===dc.GZipJS||e==="gzip",hc=t=>!(!t||typeof t!="object")&&("name"in t?String(t.name):"")==="NotReadableError",cr=t=>{var e=new Error("Native gzip produced invalid output: "+t);throw e.name=rd,e},Ip=(function(){var t=re((function*(e,n){18>e.size&&cr("too-short");var i=new Uint8Array(yield e.slice(0,10).arrayBuffer());qo(i)&&i[2]===8||cr("invalid-header");var r=new DataView(yield e.slice(e.size-8).arrayBuffer());r.getUint32(0,!0)!==(o=>{for(var a=(()=>{if(gi)return gi;gi=[];for(var c=0;256>c;c++){for(var d=c,f=0;8>f;f++)d=1&d?3988292384^d>>>1:d>>>1;gi[c]=d>>>0}return gi})(),l=4294967295,u=0;o.length>u;u++)l=a[255&(l^o[u])]^l>>>8;return(4294967295^l)>>>0})(n)&&cr("invalid-crc");var s=n.length>>>0;r.getUint32(4,!0)!==s&&cr("invalid-size")}));return function(e,n){return t.apply(this,arguments)}})();function zo(){return zo=re((function*(t,e,n){e===void 0&&(e=!0);try{var i=new TextEncoder().encode(t),r=new globalThis.CompressionStream("gzip"),s=r.writable.getWriter(),o=s.write(i).then((()=>s.close())).catch((function(){var u=re((function*(c){try{yield s.abort(c)}catch{}throw c}));return function(c){return u.apply(this,arguments)}})()),a=new Response(r.readable).blob(),l=(yield Promise.all([a,o]))[0];return yield Ip(l,i),l}catch(u){if(n!=null&&n.rethrow)throw u;return e&&console.error("Failed to gzip compress data",u),null}})),zo.apply(this,arguments)}var kp=["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","pinterest","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"],pc=function(t,e){if(e===void 0&&(e=[]),!t)return!1;var n=t.toLowerCase();return kp.concat(e).some((i=>{var r=i.toLowerCase();return n.indexOf(r)!==-1}))};function j(t,e){return t.indexOf(e)!==-1}var bs=function(t){return t.trim()},Vo=function(t){return t.replace(/^\$/,"")};function sd(t){var e,n=[];return(e=JSON.stringify(t,(function(i,r){if(typeof r=="bigint")return r.toString();if(typeof r!="function"&&typeof r!="symbol"){if(r instanceof Error)return{name:r.name,message:r.message,stack:r.stack};if(r&&typeof r=="object"){for(;n.length>0&&n[n.length-1]!==this;)n.pop();if(n.includes(r))return"[Circular]";n.push(r)}return r}})))!==null&&e!==void 0?e:"null"}var od=Object.prototype,ad=od.hasOwnProperty,Es=od.toString,U=Array.isArray||function(t){return Es.call(t)==="[object Array]"},Be=t=>typeof t=="function",de=t=>t===Object(t)&&!U(t),Vt=t=>{if(de(t)){for(var e in t)if(ad.call(t,e))return!1;return!0}return!1},C=t=>t===void 0,Z=t=>Es.call(t)=="[object String]",Go=t=>Z(t)&&t.trim().length===0,ze=t=>t===null,H=t=>C(t)||ze(t),xe=t=>Es.call(t)=="[object Number]"&&t==t,Bt=t=>xe(t)&&t>0,pt=t=>Es.call(t)==="[object Boolean]",Cp=t=>t instanceof FormData,Ap=t=>j(Sp,t),Pp=t=>j(xp,t);function ld(t){return t===null||typeof t!="object"}function Or(t,e){return{}.toString.call(t)==="[object "+e+"]"}function Ja(t){return typeof Event<"u"&&cd(t,Event)}function cd(t,e){try{return t instanceof e}catch{return!1}}var Fp=[!0,"true",1,"1","yes"],co=t=>j(Fp,t),Rp=[!1,"false",0,"0","no"];function kt(t,e,n,i,r){return e>n&&(i.warn("min cannot be greater than max."),e=n),xe(t)?t>n?(i.warn(" cannot be greater than max: "+n+". Using max value instead."),n):e>t?(i.warn(" cannot be less than min: "+e+". Using min value instead."),e):t:(i.warn(" must be a number. using max or fallback. max: "+n+", fallback: "+r),kt(r||n,e,n,i))}class Tp{constructor(e){this.tt={},this.et=e.et,this.it=kt(e.bucketSize,0,100,e.rt),this.nt=kt(e.refillRate,0,this.it,e.rt),this.st=kt(e.refillInterval,0,864e5,e.rt)}ot(e,n){var i=Math.floor((n-e.lastAccess)/this.st);i>0&&(e.tokens=Math.min(e.tokens+i*this.nt,this.it),e.lastAccess=e.lastAccess+i*this.st)}consumeRateLimit(e){var n,i=Date.now(),r=String(e),s=this.tt[r];return s?this.ot(s,i):this.tt[r]=s={tokens:this.it,lastAccess:i},s.tokens===0||(s.tokens--,s.tokens===0&&((n=this.et)==null||n.call(this,e)),s.tokens===0)}stop(){this.tt={}}}var nt="Mobile",Br="iOS",Gt="Android",Zn="Tablet",ud=Gt+" "+Zn,dd="iPad",fd="Apple",hd=fd+" Watch",Li="Safari",Xn="BlackBerry",pd="Samsung",gd=pd+"Browser",md=pd+" Internet",kn="Chrome",$p=kn+" OS",vd=kn+" "+Br,Za="Internet Explorer",_d=Za+" "+nt,Xa="Opera",Mp=Xa+" Mini",Qa="Edge",yd="Microsoft "+Qa,Kn="Firefox",wd=Kn+" "+Br,qi="Nintendo",zi="PlayStation",Yn="Xbox",bd=Gt+" "+nt,Ed=nt+" "+Li,ki="Windows",Ko=ki+" Phone",gc="Nokia",Yo="Ouya",Sd="Generic",Lp=Sd+" "+nt.toLowerCase(),xd=Sd+" "+Zn.toLowerCase(),Jo="Konqueror",Id="Oculus Browser",Dr="Vivaldi",kd="Yandex",jr="Whale",Zo="DuckDuckGo",Cd="Pale Moon",Ur="Waterfox",Ni="Brave",Ad="Google Search App",_e="(\\d+(\\.\\d+)?)",uo=new RegExp("Version/"+_e),Np=new RegExp(Yn,"i"),Op=new RegExp(zi+" \\w+","i"),Bp=new RegExp(qi+" \\w+","i"),el=new RegExp(Xn+"|PlayBook|BB10","i"),Dp={"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"},Pd=function(t,e,n,i){e=e||"";var r=(function(s){return s!=null&&s.brave?Ni:null})(n);return r||(i!=null&&i.detectGoogleSearchApp&&j(t,"GSA/")?Ad:j(t," OPR/")&&j(t,"Mini")?Mp:j(t," OPR/")?Xa:el.test(t)?Xn:j(t,"IE"+nt)||j(t,"WPDesktop")?_d:j(t,"OculusBrowser")?Id:j(t,gd)?md:j(t,Qa)||j(t,"Edg/")?yd:j(t,Dr+"/")?Dr:j(t,"YaBrowser/")?kd:j(t,jr+"/")?jr:j(t,Zo+"/")||j(t,"Ddg/")?Zo:j(t,"FBIOS")?"Facebook "+nt:j(t,"UCWEB")||j(t,"UCBrowser")?"UC Browser":j(t,"CriOS")?vd:j(t,"CrMo")||j(t,kn)?kn:j(t,Gt)&&j(t,Li)?bd:j(t,"FxiOS")?wd:j(t.toLowerCase(),Jo.toLowerCase())?Jo:j(t,Ni+"/")?Ni:((s,o)=>o&&j(o,fd)||(function(a){return j(a,Li)&&!j(a,kn)&&!j(a,Gt)})(s))(t,e)?j(t,nt)?Ed:Li:j(t,"PaleMoon/")?Cd:j(t,Ur+"/")?Ur:j(t,Kn)?Kn:j(t,"MSIE")||j(t,"Trident/")?Za:j(t,"Gecko")?Kn:"")},jp={[_d]:[new RegExp("rv:"+_e)],[yd]:[new RegExp(Qa+"?\\/"+_e)],[kn]:[new RegExp("("+kn+"|CrMo)\\/"+_e)],[vd]:[new RegExp("CriOS\\/"+_e)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+_e)],[Li]:[uo],[Ed]:[uo],[Xa]:[new RegExp("(Opera|OPR)\\/"+_e)],[Kn]:[new RegExp(Kn+"\\/"+_e)],[wd]:[new RegExp("FxiOS\\/"+_e)],[Jo]:[new RegExp("Konqueror[:/]?"+_e,"i")],[Xn]:[new RegExp(Xn+" "+_e),uo],[bd]:[new RegExp("android\\s"+_e,"i")],[md]:[new RegExp(gd+"\\/"+_e)],[Id]:[new RegExp("OculusBrowser\\/"+_e)],[Dr]:[new RegExp(Dr+"\\/"+_e)],[kd]:[new RegExp("YaBrowser\\/"+_e)],[jr]:[new RegExp(jr+"\\/"+_e)],[Ni]:[new RegExp(Ni+"\\/"+_e)],[Zo]:[new RegExp("(DuckDuckGo|Ddg)\\/"+_e)],[Cd]:[new RegExp("PaleMoon\\/"+_e)],[Ur]:[new RegExp(Ur+"\\/"+_e)],[Ad]:[new RegExp("GSA\\/"+_e)],[Za]:[new RegExp("(rv:|MSIE )"+_e)],Mozilla:[new RegExp("rv:"+_e)]},Up=function(t,e,n,i){var r=Pd(t,e,n,i),s=jp[r];if(C(s))return null;for(var o=0;s.length>o;o++){var a=t.match(s[o]);if(a)return parseFloat(a[a.length-2])}return null},mc=[[new RegExp(Yn+"; "+Yn+" (.*?)[);]","i"),t=>[Yn,t&&t[1]||""]],[new RegExp(qi,"i"),[qi,""]],[new RegExp(zi,"i"),[zi,""]],[el,[Xn,""]],[new RegExp(ki,"i"),(t,e)=>{if(/Phone/.test(e)||/WPDesktop/.test(e))return[Ko,""];if(new RegExp(nt).test(e)&&!/IEMobile\b/.test(e))return[ki+" "+nt,""];var n=/Windows NT ([0-9.]+)/i.exec(e);if(n&&n[1]){var i=Dp[n[1]]||"";return/arm/i.test(e)&&(i="RT"),[ki,i]}return[ki,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,t=>t&&t[3]?[Br,[t[3],t[4],t[5]||"0"].join(".")]:[Br,""]],[/(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i,t=>{var e="";return t&&t.length>=3&&(e=C(t[2])?t[3]:t[2]),["watchOS",e]}],[new RegExp("("+Gt+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+Gt+")","i"),t=>t&&t[2]?[Gt,[t[2],t[3],t[4]||"0"].join(".")]:[Gt,""]],[/Mac OS X (\d+)[_.](\d+)[_.]?(\d+)?/i,t=>{var 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/,[$p,""]],[/Linux|debian/i,["Linux",""]]],vc=function(t){return Bp.test(t)?qi:Op.test(t)?zi:Np.test(t)?Yn:new RegExp(Yo,"i").test(t)?Yo:new RegExp("("+Ko+"|WPDesktop)","i").test(t)?Ko:/iPad/.test(t)?dd:/iPod/.test(t)?"iPod Touch":/iPhone/.test(t)?"iPhone":/(watch)(?: ?os[,/]|\d,\d\/)[\d.]+/i.test(t)?hd:el.test(t)?Xn:/(kobo)\s(ereader|touch)/i.test(t)?"Kobo":new RegExp(gc,"i").test(t)?gc:/(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(nt).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)?Gt:ud:new RegExp("(pda|"+nt+")","i").test(t)?Lp:new RegExp(Zn,"i").test(t)&&!new RegExp(Zn+" pc","i").test(t)?xd:""},Hp=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function _c(t,e){return typeof(n=t)=="string"&&Hp.test(n)?t:e();var n}function un(t){return t&&t.split("#")[0]}function tl(t,e){var n=setTimeout(t,e);return n?.unref&&n?.unref(),n}function yc(t,e,n){return Fd.apply(this,arguments)}function Fd(){return(Fd=re((function*(t,e,n){var i;try{return yield Promise.race([t,new Promise(((r,s)=>{i=tl((()=>{try{n?.(),r()}catch(o){s(o)}}),e)}))])}finally{clearTimeout(i)}}))).apply(this,arguments)}var Wp=t=>t instanceof Error,Rd={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}},qp=Rd.info;function Td(t){if(pt(t))return{boolValue:t};if(typeof t=="number")return Number.isFinite(t)?Number.isInteger(t)?{intValue:t}:{doubleValue:t}:{stringValue:String(t)};if(typeof t=="string")return{stringValue:t};if(U(t))return{arrayValue:{values:t.map((e=>Td(e)))}};try{return{stringValue:JSON.stringify(t)}}catch{return{stringValue:String(t)}}}function Hr(t){var e=[];for(var n in t){var i=t[n];ze(i)||C(i)||e.push({key:n,value:Td(i)})}return e}function zp(t,e){var n=Rd[t.level||"info"]||qp,i=n.text,r=n.number,s=String(Date.now())+"000000",o={};e.distinctId&&(o.posthogDistinctId=e.distinctId),e.sessionId&&(o.sessionId=e.sessionId),e.windowId&&(o["window.id"]=e.windowId),H(e.sessionStartTimestamp)||(o.sessionStartTimestamp=String(e.sessionStartTimestamp)),H(e.lastActivityTimestamp)||(o.lastActivityTimestamp=String(e.lastActivityTimestamp)),e.currentUrl&&(o["url.full"]=e.currentUrl),e.screenName&&(o["screen.name"]=e.screenName),e.appState&&(o["app.state"]=e.appState),e.activeFeatureFlags&&e.activeFeatureFlags.length>0&&(o.feature_flags=e.activeFeatureFlags);var a=k({},o,t.attributes||{}),l={timeUnixNano:s,observedTimeUnixNano:s,severityNumber:r,severityText:i,body:{stringValue:t.body},attributes:Hr(a)};return t.trace_id&&(l.traceId=t.trace_id),t.span_id&&(l.spanId=t.span_id),C(t.trace_flags)||(l.flags=t.trace_flags),l}function $d(t,e,n){return k({},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})}function Md(t,e,n,i){return{resourceLogs:[{resource:{attributes:Hr(e)},scopeLogs:[{scope:{name:n,version:i},logRecords:t}]}]}}let Vp=class{constructor(t,e,n,i,r,s,o){var a;s===void 0&&(s=()=>Promise.resolve()),this._instance=t,this.Ne=e,this.rt=n,this.ut=i,this.ht=r,this.dt=s,this.vt=o,this.ct=null,this.ft=0,this.yt=0,this.bt=0,this._t=0,this.wt=!1,this.kt=e.maxBufferSize,this.xt=Math.max((a=e.maxQueueSize)!==null&&a!==void 0?a:e.maxBufferSize,e.maxBufferSize),this.St=e.flushIntervalMs,this.Ct=e.maxBatchRecordsPerPost,this.Mt=e.rateCapWindowMs,this.Tt=e.maxLogsPerInterval}reset(){this.Et(),this.ct=null,this.bt=0,this._t=0,this.wt=!1,this.ft=0,this.yt=0,this.Ct=this.Ne.maxBatchRecordsPerPost}onReconnect(){this.yt=0,this.It()}captureLog(t){if(!this._instance.isDisabled&&!this._instance.optedOut&&t!=null&&t.body){var e=this.Pt(t);if(e!==null)if(e.body){if(this.Rt()){var n={record:zp(e,this.ut())};this.ht((()=>this.At(n)))}}else this.rt.info("Log was rejected in beforeSend function")}}Pt(t){var e=this.Ne.beforeSend;if(!e)return t;var n=U(e)?e:[e],i=t;for(var r of n)try{var s=r(i);if(!s)return this.rt.info("Log was rejected in beforeSend function"),null;i=s}catch(o){return this.rt.error("Error in beforeSend function for log:",o),null}return i}Rt(){if(this.Tt===void 0)return!0;var t=Date.now(),e=t-this.bt;return this.Mt>e&&e>=0||(this.bt=t,this._t=0,this.wt=!1),this.Tt>this._t?(this._t++,!0):(this.wt||(this.rt.warn("captureLog dropping logs: exceeded "+this.Tt+" logs per "+this.Mt+"ms"),this.wt=!0),!1)}flush(){var t=this;return re((function*(){if(!t._instance.isDisabled)return t.ct||(t.ct=t.Ft().finally((()=>{t.ct=null}))),t.ct}))()}Ft(){var t=this;return re((function*(){var e;t.Et();var n=(e=t._instance.getPersistedProperty(jt.LogsQueue))!==null&&e!==void 0?e:[];if(n.length!==0)for(var i=n.length,r=0;n.length>0&&i>r;){var s,o;t.ft=0;var a=Math.min(n.length,t.Ct),l=n.slice(0,a),u=Md(l.map((d=>d.record)),t.Lt(),(s=t.vt)!==null&&s!==void 0?s:t._instance.getLibraryId(),t._instance.getLibraryVersion()),c=yield t._instance.Ot(u);if(c.kind==="too-large"&&l.length>1)t.Ct=Math.max(1,Math.floor(l.length/2)),t.rt.warn("Received 413 when sending logs batch of size "+l.length+", reducing batch size to "+t.Ct);else if(c.kind==="retry-later"||(c.kind==="too-large"?t.rt.warn("Dropping a single log record after 413 with batch size 1 — the record is larger than the server cap and cannot be split further."):c.kind==="ok"&&t.Ne.maxBatchRecordsPerPost>t.Ct&&(t.Ct=Math.min(t.Ne.maxBatchRecordsPerPost,t.Ct+1)),yield t.Dt(l.length),n=(o=t._instance.getPersistedProperty(jt.LogsQueue))!==null&&o!==void 0?o:[],r+=l.length,c.kind==="fatal"))throw c.error}}))()}Dt(t){var e=this;return re((function*(){var n,i=Math.max(0,t-e.ft),r=(n=e._instance.getPersistedProperty(jt.LogsQueue))!==null&&n!==void 0?n:[];e._instance.setPersistedProperty(jt.LogsQueue,r.slice(i)),yield e.dt()}))()}Lt(){return $d(this.Ne,this._instance.getLibraryId(),this._instance.getLibraryVersion())}At(t){var e;if(!this._instance.optedOut){var n=(e=this._instance.getPersistedProperty(jt.LogsQueue))!==null&&e!==void 0?e:[];this.xt>n.length||(n.shift(),this.ft++,this.rt.info("Logs queue is full, dropping oldest record.")),n.push(t),this._instance.setPersistedProperty(jt.LogsQueue,n),this.kt>n.length?this.$t():this.It()}}$t(t){t===void 0&&(t=this.St),this.Nt||(this.Nt=tl((()=>{this.Nt=void 0,this.It()}),t))}qt(){var t=Math.min(Math.max(0,this.yt-1),6);return this.St*Math.pow(2,t)}jt(){var t=this._instance.getPersistedProperty(jt.LogsQueue);return!!t&&t.length>0}shutdown(t){var e=this;return re((function*(){e.Et();var n=e.flush().catch((()=>{}));t!==void 0?yield yc(n,t):yield n}))()}flushWithTimeout(t){var e=this;return re((function*(){var n=e.flush();yield yc(n,t,(()=>{n.catch((()=>{}))}))}))()}It(){this.flush().then((()=>{this.yt=0}),(t=>{this.yt++,this.rt.error("PostHog logs flush failed:",t)})).finally((()=>{!this._instance.isDisabled&&this.jt()&&this.$t(this.qt())}))}Et(){this.Nt&&(clearTimeout(this.Nt),this.Nt=void 0)}};var fo=[0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4];function wc(t){return String(t)+"000000"}function bc(t,e,n,i){var r="";return i&&(r=Object.keys(i).sort().map((s=>JSON.stringify(s)+":"+JSON.stringify(i[s]))).join(",")),t+"\0"+e+"\0"+(n??"")+"\0"+r}let Gp=class{constructor(t,e,n){this._instance=t,this.Ne=e,this.rt=n,this.Bt=new Map,this.ct=null,this.Ht=!1,this.Ut=new Map,this.zt=new Set,this.Wt=0}count(t,e,n){e===void 0&&(e=1),this.Vt({name:t,type:"count",value:e,unit:n?.unit,attributes:n?.attributes})}gauge(t,e,n){this.Vt({name:t,type:"gauge",value:e,unit:n?.unit,attributes:n?.attributes})}histogram(t,e,n){this.Vt({name:t,type:"histogram",value:e,unit:n?.unit,attributes:n?.attributes})}flush(){var t=this,e=this.ct,n=(function(){var r=re((function*(){e&&(yield e.catch((()=>{}))),yield t.Zt()}));return function(){return r.apply(this,arguments)}})(),i=n().finally((()=>{this.ct===i&&(this.ct=null)}));return this.ct=i,i}drainWindow(){if(this.Bt.size===0)return null;var t=this.Bt;return this.Bt=new Map,this.Ht=!1,this.Ut=new Map,this.zt=new Set,this.Gt(t)}reset(){this.Wt++,this.Et(),this.Bt=new Map,this.ct=null,this.Ht=!1,this.Ut=new Map,this.zt=new Set}Vt(t){if(!this._instance.isDisabled&&!this._instance.optedOut){var e=this.Pt(t);if(e!==null)if(e.name&&typeof e.name=="string")if(typeof e.value=="number"&&Number.isFinite(e.value))if(e.type==="count"&&0>e.value)this.rt.warn("Dropping count '"+e.name+"': counters are monotonic, value must be >= 0");else{var n,i;try{n=e.attributes?k({},e.attributes):void 0,i=bc(e.type,e.name,e.unit,n)}catch(o){return void this.rt.warn("Dropping metric '"+e.name+"': attributes could not be serialized",o)}var r=this.Bt.get(i);if(!r){if(!this.Qt())return;r={name:e.name,type:e.type,unit:e.unit,attributes:n,windowStartMs:Date.now()},this.Bt.set(i,r)}var s=this.Ut.get(e.name);s===void 0?this.Ut.set(e.name,e.type):s===e.type||this.zt.has(e.name)||(this.zt.add(e.name),this.rt.warn("Metric name '"+e.name+"' is already used as a "+s+"; recording it as a "+e.type+" too will blend both series in charts. Use a distinct name.")),this.Kt(r,e.value),this.$t()}else this.rt.warn("Dropping metric '"+e.name+"': value must be a finite number");else this.rt.warn("Dropping metric with empty name")}}Qt(){return this.Ne.maxSeriesPerFlush>this.Bt.size||(this.Ht||(this.Ht=!0,this.rt.warn("Metric series cap reached ("+this.Ne.maxSeriesPerFlush+" per flush window); dropping new series until the next flush. Reduce attribute cardinality.")),!1)}Kt(t,e){var n;switch(t.type){case"count":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(fo.length+1).fill(0)});var i=t.hist;i.count+=1,i.sum+=e,i.min=Math.min(i.min,e),i.max=Math.max(i.max,e),i.bucketCounts[(function(r,s){for(var o=0;s.length>o;o++)if(s[o]>=r)return o;return s.length})(e,fo)]+=1}}Pt(t){var e=this.Ne.beforeSend;if(!e)return t;var n=U(e)?e:[e],i=t;for(var r of n)try{var s=r(i);if(!s)return this.rt.info("Metric was rejected in beforeSend function"),null;i=s}catch(o){return this.rt.error("Error in beforeSend function for metric:",o),null}return i}$t(){this.Nt||(this.Nt=tl((()=>{this.Nt=void 0,this.flush().catch((t=>{this.rt.error("Metrics flush failed:",t)}))}),this.Ne.flushIntervalMs))}Et(){this.Nt&&(clearTimeout(this.Nt),this.Nt=void 0)}Zt(){var t=this;return re((function*(){if(t.Bt.size!==0){var e=t.Bt;t.Bt=new Map,t.Ht=!1,t.Ut=new Map,t.zt=new Set;var n=t.Wt,i=yield t._instance.Jt(t.Gt(e));if(n===t.Wt)switch(i.kind){case"ok":return;case"retry-later":return t.Yt(e),void t.$t();case"too-large":return void t.rt.warn("Metrics batch exceeded the server size limit and was dropped");case"fatal":return void t.rt.error("Failed to send metrics batch:",i.error)}}}))()}Gt(t){return e=this.Xt(t),n=(function(s,o,a){return k({},s.resourceAttributes,{"service.name":s.serviceName||"unknown_service"},s.environment&&{"deployment.environment":s.environment},s.serviceVersion&&{"service.version":s.serviceVersion},{"telemetry.sdk.name":o,"telemetry.sdk.version":a})})(this.Ne,this._instance.getLibraryId(),this._instance.getLibraryVersion()),i=this._instance.getLibraryId(),r=this._instance.getLibraryVersion(),{resourceMetrics:[{resource:{attributes:Hr(n)},scopeMetrics:[{scope:{name:i,version:r},metrics:e}]}]};var e,n,i,r}Xt(t){var e=wc(Date.now()),n=new Map;for(var i of t.values()){var r,s=bc(i.type,i.name,i.unit,void 0),o=n.get(s);o||(o=k({name:i.name},i.unit&&{unit:i.unit}),i.type==="count"?o.sum={aggregationTemporality:1,isMonotonic:!0,dataPoints:[]}:i.type==="gauge"?o.gauge={dataPoints:[]}:o.histogram={aggregationTemporality:1,dataPoints:[]},n.set(s,o));var a=Hr((r=i.attributes)!==null&&r!==void 0?r:{}),l=wc(i.windowStartMs);if(i.type==="count"){var u,c={attributes:a,startTimeUnixNano:l,timeUnixNano:e,asDouble:(u=i.total)!==null&&u!==void 0?u:0};o.sum.dataPoints.push(c)}else if(i.type==="gauge"){var d,f={attributes:a,timeUnixNano:e,asDouble:(d=i.last)!==null&&d!==void 0?d:0};o.gauge.dataPoints.push(f)}else i.hist&&o.histogram.dataPoints.push({attributes:a,startTimeUnixNano:l,timeUnixNano:e,count:i.hist.count,sum:i.hist.sum,min:i.hist.min,max:i.hist.max,bucketCounts:i.hist.bucketCounts,explicitBounds:fo})}return Array.from(n.values())}Yt(t){var e,n;for(var i of t){var r=i[0],s=i[1],o=this.Bt.get(r);if(o)switch(o.windowStartMs=Math.min(o.windowStartMs,s.windowStartMs),o.type){case"count":o.total=((e=o.total)!==null&&e!==void 0?e:0)+((n=s.total)!==null&&n!==void 0?n:0);break;case"gauge":break;case"histogram":if(s.hist)if(o.hist){o.hist.count+=s.hist.count,o.hist.sum+=s.hist.sum,o.hist.min=Math.min(o.hist.min,s.hist.min),o.hist.max=Math.max(o.hist.max,s.hist.max);for(var a=0;o.hist.bucketCounts.length>a;a++)o.hist.bucketCounts[a]+=s.hist.bucketCounts[a]}else o.hist=s.hist}else this.Qt()&&this.Bt.set(r,s)}}};var ur,Ec,ho;function Kp(t){var e=globalThis._posthogChunkIds;if(e){var n=Object.keys(e);return ho&&n.length===Ec||(Ec=n.length,ho=n.reduce(((i,r)=>{ur||(ur={});var s=ur[r];if(s)i[s[0]]=s[1];else for(var o=t(r),a=o.length-1;a>=0;a--){var l=o[a],u=l?.filename,c=e[r];if(u&&c){i[u]=c,ur[r]=[u,c];break}}return i}),{})),ho}}class Yp{constructor(e,n,i){i===void 0&&(i=[]),this.coercers=e,this.stackParser=n,this.modifiers=i}buildFromUnknown(e,n){n===void 0&&(n={});var i=n&&n.mechanism||{handled:!0,type:"generic"},r=this.buildCoercingContext(i,n,0).apply(e),s=this.buildParsingContext(n),o=this.parseStacktrace(r,s);return{$exception_list:this.convertToExceptionList(o,i),$exception_level:"error"}}modifyFrames(e){var n=this;return re((function*(){for(var i of e)i.stacktrace&&i.stacktrace.frames&&U(i.stacktrace.frames)&&(i.stacktrace.frames=yield n.applyModifiers(i.stacktrace.frames));return e}))()}coerceFallback(e){var n;return{type:"Error",value:"Unknown error",stack:(n=e.syntheticException)==null?void 0:n.stack,synthetic:!0}}parseStacktrace(e,n){var i,r;return e.cause!=null&&(i=this.parseStacktrace(e.cause,n)),e.stack!=""&&e.stack!=null&&(r=this.applyChunkIds(this.stackParser(e.stack,e.synthetic?n.skipFirstLines:0),n.chunkIdMap)),k({},e,{cause:i,stack:r})}applyChunkIds(e,n){return e.map((i=>(i.filename&&n&&(i.chunk_id=n[i.filename]),i)))}applyCoercers(e,n){for(var i of this.coercers)if(i.match(e))return i.coerce(e,n);return this.coerceFallback(n)}applyModifiers(e){var n=this;return re((function*(){var i=e;for(var r of n.modifiers)i=yield r(i);return i}))()}convertToExceptionList(e,n){var i,r,s,o={type:e.type,value:e.value,mechanism:{type:(i=n.type)!==null&&i!==void 0?i:"generic",handled:(r=n.handled)===null||r===void 0||r,synthetic:(s=e.synthetic)!==null&&s!==void 0&&s}};e.stack&&(o.stacktrace={type:"raw",frames:e.stack});var a=[o];return e.cause!=null&&a.push(...this.convertToExceptionList(e.cause,k({},n,{handled:!0}))),a}buildParsingContext(e){var n;return{chunkIdMap:Kp(this.stackParser),skipFirstLines:(n=e.skipFirstLines)!==null&&n!==void 0?n:1}}buildCoercingContext(e,n,i){i===void 0&&(i=0);var r=(s,o)=>{if(4>=o){var a=this.buildCoercingContext(e,n,o);return this.applyCoercers(s,a)}};return k({},n,{syntheticException:i==0?n.syntheticException:void 0,mechanism:e,apply:s=>r(s,i),next:s=>r(s,i+1)})}}var Qn="?";function Xo(t,e,n,i,r){var s={platform:t,filename:e,function:n===""?Qn:n,in_app:!0};return C(i)||(s.lineno=i),C(r)||(s.colno=r),s}var Ld=(t,e)=>{var n=t.indexOf("safari-extension")!==-1,i=t.indexOf("safari-web-extension")!==-1;return n||i?[t.indexOf("@")!==-1?t.split("@")[0]:Qn,n?"safari-extension:"+e:"safari-web-extension:"+e]:[t,e]},Jp=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,Zp=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,Xp=/\((\S*)(?::(\d+))(?::(\d+))\)/,Qp=(t,e)=>{var n=Jp.exec(t);if(n)return Xo(e,n[1],Qn,+n[2],+n[3]);var i=Zp.exec(t);if(i){if(i[2]&&i[2].indexOf("eval")===0){var r=Xp.exec(i[2]);r&&(i[2]=r[1],i[3]=r[2],i[4]=r[3])}var s=Ld(i[1]||Qn,i[2]);return Xo(e,s[1],s[0],i[3]?+i[3]:void 0,i[4]?+i[4]:void 0)}},eg=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,tg=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,ng=(t,e)=>{var n=eg.exec(t);if(n){if(n[3]&&n[3].indexOf(" > eval")>-1){var i=tg.exec(n[3]);i&&(n[1]=n[1]||"eval",n[3]=i[1],n[4]=i[2],n[5]="")}var r=n[3],s=n[1]||Qn,o=Ld(s,r);return Xo(e,r=o[1],s=o[0],n[4]?+n[4]:void 0,n[5]?+n[5]:void 0)}},Sc=/\(error: (.*)\)/;class ig{match(e){return this.isDOMException(e)||this.isDOMError(e)}coerce(e,n){var i=Z(e.stack);return{type:this.getType(e),value:this.getValue(e),stack:i?e.stack:void 0,cause:e.cause?n.next(e.cause):void 0,synthetic:!1}}getType(e){return this.isDOMError(e)?"DOMError":"DOMException"}getValue(e){var n=e.name||(this.isDOMError(e)?"DOMError":"DOMException");return e.message?n+": "+e.message:n}isDOMException(e){return Or(e,"DOMException")}isDOMError(e){return Or(e,"DOMError")}}class rg{match(e){return(function(n){switch({}.toString.call(n)){case"[object Error]":case"[object Exception]":case"[object DOMException]":case"[object DOMError]":case"[object WebAssembly.Exception]":return!0;default:return cd(n,Error)}})(e)}coerce(e,n){return{type:this.getType(e),value:this.getMessage(e,n),stack:this.getStack(e),cause:e.cause?n.next(e.cause):void 0,synthetic:!1}}getType(e){return e.name||e.constructor.name}getMessage(e,n){var i=e.message;return String(i.error&&typeof i.error.message=="string"?i.error.message:i)}getStack(e){return e.stacktrace||e.stack||void 0}}class sg{constructor(){}match(e){return!!Or(e,"ErrorEvent")&&(e.error!=null||this.fe(e))}coerce(e,n){var i;if(e.error!=null)return n.apply(e.error);var r=n.apply(e.message);return k({},r,{stack:(i=this.pe(e))!==null&&i!==void 0?i:r.stack,synthetic:!0})}fe(e){return Z(e.message)&&e.message.length>0}pe(e){var n=e;if(Z(n.filename)&&n.filename.length>0){var i,r,s=(i=n.lineno)!==null&&i!==void 0?i:0,o=(r=n.colno)!==null&&r!==void 0?r:0;return`Error + at `+n.filename+":"+s+":"+o}}}var og=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;class ag{match(e){return typeof e=="string"}coerce(e,n){var i,r=this.getInfos(e),s=r[0],o=r[1];return{type:s??"Error",value:o??e,stack:(i=n.syntheticException)==null?void 0:i.stack,synthetic:!0}}getInfos(e){var n="Error",i=e,r=e.match(og);return r&&(n=r[1],i=r[2]),[n,i]}}var lg=["fatal","error","warning","log","info","debug"];function Nd(t,e){e===void 0&&(e=40);var n=Object.keys(t);if(n.sort(),!n.length)return"[object has no keys]";for(var i=n.length;i>0;i--){var r=n.slice(0,i).join(", ");if(e>=r.length)return i===n.length?r:r.length>e?r.slice(0,e)+"...":r}return""}class cg{match(e){return typeof e=="object"&&e!==null}coerce(e,n){var i,r,s=this.getErrorPropertyFromObject(e);return s?n.apply(s):{type:this.getType(e),value:this.getValue(e),stack:(i=this.getStack(e))!==null&&i!==void 0?i:(r=n.syntheticException)==null?void 0:r.stack,level:this.isSeverityLevel(e.level)?e.level:"error",synthetic:!0}}getType(e){return Ja(e)?e.constructor.name:"Error"}getValue(e){if("name"in e&&typeof e.name=="string"){var n="'"+e.name+"' captured as exception";return"message"in e&&typeof e.message=="string"&&(n+=" with message: '"+e.message+"'"),n}if("message"in e&&typeof e.message=="string")return e.message;var i=this.getObjectClassName(e);return(i&&i!=="Object"?"'"+i+"'":"Object")+" captured as exception with keys: "+Nd(e)}isSeverityLevel(e){return Z(e)&&!Go(e)&&lg.indexOf(e)>=0}getStack(e){try{return Z(e.stacktrace)&&e.stacktrace.length>0?e.stacktrace:Z(e.stack)&&e.stack.length>0?e.stack:void 0}catch{return}}getErrorPropertyFromObject(e){for(var n in e)if({}.hasOwnProperty.call(e,n)){var i=e[n];if(Wp(i))return i}}getObjectClassName(e){try{var n=Object.getPrototypeOf(e);return n?n.constructor.name:void 0}catch{return}}}class ug{match(e){return Ja(e)}coerce(e,n){var i,r=e.constructor.name;return{type:r,value:r+" captured as exception with keys: "+Nd(e),stack:(i=n.syntheticException)==null?void 0:i.stack,synthetic:!0}}}class dg{match(e){return ld(e)}coerce(e,n){var i;return{type:"Error",value:"Primitive value captured as exception: "+String(e),stack:(i=n.syntheticException)==null?void 0:i.stack,synthetic:!0}}}class fg{match(e){return Or(e,"PromiseRejectionEvent")||this.isCustomEventWrappingRejection(e)}isCustomEventWrappingRejection(e){if(!Ja(e))return!1;try{var n=e.detail;return n!=null&&typeof n=="object"&&"reason"in n}catch{return!1}}coerce(e,n){var i,r=this.getUnhandledRejectionReason(e);return ld(r)?{type:"UnhandledRejection",value:"Non-Error promise rejection captured with value: "+String(r),stack:(i=n.syntheticException)==null?void 0:i.stack,synthetic:!0}:n.apply(r)}getUnhandledRejectionReason(e){try{if("reason"in e)return e.reason;if("detail"in e&&e.detail!=null&&typeof e.detail=="object"&&"reason"in e.detail)return e.detail.reason}catch{}return e}}var Wr="$message",qr="$timestamp",hg=new Set([Wr,qr]),po={enabled:!0,max_bytes:32768};function zr(t){var e;return t?{enabled:(e=t.enabled)!==null&&e!==void 0?e:po.enabled,max_bytes:gg(t.max_bytes,po.max_bytes)}:k({},po)}class pg{constructor(e){this.Ke=[],this.Je=0,this.Ne=zr(e)}setConfig(e){this.Ne=zr(e),this.Xe()}add(e){var n=(function(r){var s;try{s=sd(r)}catch{return}try{var o=JSON.parse(s);if(!de(o))return;var a=o,l=a[Wr],u=a[qr];return!Z(l)||l.trim().length===0||!Z(u)&&!xe(u)?void 0:{step:a,json:s}}catch{return}})(e);if(n){var i=(function(r){if(typeof TextEncoder<"u")return new TextEncoder().encode(r).length;for(var s=encodeURIComponent(r),o=0,a=0;s.length>a;a++)s[a]==="%"?(o+=1,a+=2):o+=1;return o})(n.json);i>this.Ne.max_bytes||(this.Ke.push({step:n.step,bytes:i}),this.Je+=i,this.Xe())}}getAttachable(){return this.Ke.map((e=>e.step))}clear(){this.Ke=[],this.Je=0}size(){return this.Ke.length}Xe(){for(;this.Je>this.Ne.max_bytes&&this.Ke.length>0;){var e=this.Ke.shift();e&&(this.Je-=e.bytes)}}}function gg(t,e){if(!xe(t)||t===1/0||t===-1/0)return e;var n=Math.floor(t);return 0>n?e:n}var Od=function(t,e){var n=(e===void 0?{}:e).debugEnabled,i={k(r){if(w&&(ne.DEBUG||w.POSTHOG_DEBUG||n)&&!C(w.console)&&w.console){for(var s=("__rrweb_original__"in w.console[r])?w.console[r].__rrweb_original__:w.console[r],o=arguments.length,a=new Array(o>1?o-1:0),l=1;o>l;l++)a[l-1]=arguments[l];s(t,...a)}},debug(){for(var r=arguments.length,s=new Array(r),o=0;r>o;o++)s[o]=arguments[o];i.k("debug",...s)},info(){for(var r=arguments.length,s=new Array(r),o=0;r>o;o++)s[o]=arguments[o];i.k("log",...s)},warn(){for(var r=arguments.length,s=new Array(r),o=0;r>o;o++)s[o]=arguments[o];i.k("warn",...s)},error(){for(var r=arguments.length,s=new Array(r),o=0;r>o;o++)s[o]=arguments[o];i.k("error",...s)},critical(){for(var r=arguments.length,s=new Array(r),o=0;r>o;o++)s[o]=arguments[o];console.error(t,...s)},uninitializedWarning(r){i.error("You must initialize PostHog before calling "+r)},createLogger:(r,s)=>Od(t+" "+r,s)};return i},A=Od("[PostHog.js]"),he=A.createLogger,mg=he("[ExternalScriptsLoader]"),go=(t,e,n)=>{if(t.config.disable_external_dependency_loading)return mg.warn(e+" was requested but loading of external scripts is disabled."),n("Loading of external scripts is disabled");var i=F?.querySelectorAll("script");if(i){for(var r,s=function(){if(i[o].src===e){var l=i[o];return l.__posthog_loading_callback_fired?{v:n()}:(l.addEventListener("load",(u=>{l.__posthog_loading_callback_fired=!0,n(void 0,u)})),l.onerror=u=>n(u),{v:void 0})}},o=0;i.length>o;o++)if(r=s())return r.v}var a=()=>{if(!F)return n("document not found");var l=F.createElement("script");if(l.type="text/javascript",l.crossOrigin="anonymous",l.src=e,l.onload=d=>{l.__posthog_loading_callback_fired=!0,n(void 0,d)},l.onerror=d=>n(d),t.config.prepare_external_dependency_script&&(l=t.config.prepare_external_dependency_script(l)),!l)return n("prepare_external_dependency_script returned null");if(t.config.external_scripts_inject_target==="head")F.head.appendChild(l);else{var u,c=F.querySelectorAll("body > script");c.length>0?(u=c[0].parentNode)==null||u.insertBefore(l,c[0]):F.body.appendChild(l)}};F!=null&&F.body?a():F?.addEventListener("DOMContentLoaded",a)};O.__PosthogExtensions__=O.__PosthogExtensions__||{},O.__PosthogExtensions__.loadExternalDependency=(t,e,n)=>{if(e!=="remote-config"){var i;if(t.config.strict_script_versioning)i=t.requestRouter.endpointFor("assets","/static/"+t.version+"/"+e+".js");else{var r="/static/"+e+".js?v="+t.version;if(e==="toolbar"){var s=3e5;r=r+"&t="+Math.floor(Date.now()/s)*s}i=t.requestRouter.endpointFor("assets",r)}go(t,i,n)}else{var o=t.requestRouter.endpointFor("assets","/array/"+t.config.token+"/config.js");go(t,o,n)}},O.__PosthogExtensions__.loadSiteApp=(t,e,n)=>{var i=t.requestRouter.endpointFor("api",e);go(t,i,n)};ne.DEBUG=!1,ne.LIB_VERSION="1.415.7",ne.LIB_NAME="web";var Bd="$people_distinct_id",Vi="$device_id",mo="$device_model",Ci="__alias",Ai="__timers",Qo="$autocapture_disabled_server_side",ea="$heatmaps_enabled_server_side",ta="$exception_capture_enabled_server_side",na="$error_tracking_suppression_rules",ia="$error_tracking_capture_extension_exceptions",ra="$web_vitals_enabled_server_side",nl="$dead_clicks_enabled_server_side",il="$product_tours_enabled_server_side",sa="$web_vitals_allowed_metrics",In="$session_recording_remote_config",Dd="$replay_sample_rate",jd="$replay_override_sampling",Ud="$replay_override_linked_flag",Hd="$replay_override_url_trigger",Wd="$replay_override_event_trigger",zn="$sesid",rl="$session_is_sampled",wn="$enabled_feature_flags",Pi="$active_feature_flags",Sr="$early_access_features",oa="$feature_flag_details",Fi="$feature_flag_payloads",xr="$feature_flag_request_id",Vr="$minimal_flag_called_events",St="$override_feature_flags",bn="$override_feature_flag_payloads",Dt="$stored_person_properties",En="$stored_group_properties",aa="$surveys",Gr="$surveys_loaded_at",la="$surveys_activated",Ir="$surveys_activated_session",kr="$surveys_activated_timestamps",Ri="ph_product_tours",xn="$flag_call_reported",Ti="$flag_call_reported_session_id",Cr="$feature_flag_errors",Oi="$feature_flag_evaluated_at",st="$user_state",ca="$client_session_props",ua="$capture_rate_limit",da="$initial_campaign_params",fa="$initial_referrer_info",Kr="$initial_person_info",Yr="$epp",dr="$posthog_cookieless",qd="$cookieless_mode",zd="$sdk_debug_extensions_init_method",Vd="$sdk_debug_extensions_init_time_ms",Gd="$sdk_debug_recording_script_not_loaded",sl="PostHog loadExternalDependency extension not found.",Sn="on_reject",Ht="always",Bn="anonymous",pn="identified",ha="identified_only",Jr="visibilitychange",Zr="beforeunload",Wn="$pageview",vo="$pageleave",_o="$identify",xc="$groupidentify";function fr(t,e){U(t)&&t.forEach(e)}function ie(t,e){if(!H(t))if(U(t))t.forEach(e);else if(Cp(t))t.forEach(((i,r)=>e(i,r)));else for(var n in t)ad.call(t,n)&&e(t[n],n)}var ue=function(t){for(var e=arguments.length,n=new Array(e>1?e-1:0),i=1;e>i;i++)n[i-1]=arguments[i];for(var r of n)for(var s in r)r[s]!==void 0&&(t[s]=r[s]);return t};function Ar(t){for(var e=Object.keys(t),n=e.length,i=new Array(n);n--;)i[n]=[e[n],t[e[n]]];return i}var Ic=function(t){try{return t()}catch{return}},vg=function(t){return function(){try{for(var e=arguments.length,n=new Array(e),i=0;e>i;i++)n[i]=arguments[i];return t.apply(this,n)}catch(r){A.critical("Implementation error. Please turn on debug mode and open a ticket on https://app.posthog.com/home#panel=support%3Asupport%3A."),A.critical(r)}}},ol=function(t){var e={};return ie(t,(function(n,i){(Z(n)&&n.length>0||xe(n))&&(e[i]=n)})),e},_g=["herokuapp.com","vercel.app","netlify.app"];function yg(t){var e=t?.hostname;if(!Z(e))return!1;var n=e.split(".").slice(-2).join(".");for(var i of _g)if(n===i)return!1;return!0}function me(t,e,n,i){var r=i??{},s=r.capture,o=r.passive;t?.addEventListener(e,n,{capture:s!==void 0&&s,passive:o===void 0||o})}function pa(t){return t.name==="ph_toolbar_internal"}var Kd=t=>{if(F){try{for(var e=t+"=",n=F.cookie.split(";").filter((s=>s.length)),i=0;n.length>i;i++){for(var r=n[i];r.charAt(0)==" ";)r=r.substring(1,r.length);if(r.indexOf(e)===0)return decodeURIComponent(r.substring(e.length,r.length))}}catch{}return null}};Math.trunc||(Math.trunc=function(t){return 0>t?Math.ceil(t):Math.floor(t)}),Number.isInteger||(Number.isInteger=function(t){return xe(t)&&isFinite(t)&&Math.floor(t)===t});class Xr{constructor(e){if(this.bytes=e,e.length!==16)throw new TypeError("not 128-bit length")}static fromFieldsV7(e,n,i,r){if(!Number.isInteger(e)||!Number.isInteger(n)||!Number.isInteger(i)||!Number.isInteger(r)||0>e||0>n||0>i||0>r||e>0xffffffffffff||n>4095||i>1073741823||r>4294967295)throw new RangeError("invalid field value");var s=new Uint8Array(16);return s[0]=e/Math.pow(2,40),s[1]=e/Math.pow(2,32),s[2]=e/Math.pow(2,24),s[3]=e/Math.pow(2,16),s[4]=e/256,s[5]=e,s[6]=112|n>>>8,s[7]=n,s[8]=128|i>>>24,s[9]=i>>>16,s[10]=i>>>8,s[11]=i,s[12]=r>>>24,s[13]=r>>>16,s[14]=r>>>8,s[15]=r,new Xr(s)}toString(){for(var e="",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 Xr(this.bytes.slice(0))}equals(e){return this.compareTo(e)===0}compareTo(e){for(var n=0;16>n;n++){var i=this.bytes[n]-e.bytes[n];if(i!==0)return Math.sign(i)}return 0}}class wg{generate(){var e=this.generateOrAbort();if(!C(e))return e;this.S=0;var n=this.generateOrAbort();if(C(n))throw new Error("Could not generate UUID after timestamp reset");return n}generateOrAbort(){var e=Date.now();if(e>this.S)this.S=e,this.C();else{if(this.S>=e+1e4)return;this.I++,this.I>4398046511103&&(this.S++,this.C())}return Xr.fromFieldsV7(this.S,Math.trunc(this.I/Math.pow(2,30)),this.I&Math.pow(2,30)-1,this.A.nextUint32())}C(){this.I=1024*this.A.nextUint32()+(1023&this.A.nextUint32())}constructor(){this.S=0,this.I=0,this.A=new bg}}var kc,Yd=t=>{if(typeof UUIDV7_DENY_WEAK_RNG<"u"&&UUIDV7_DENY_WEAK_RNG)throw new Error("no cryptographically strong RNG available");for(var e=0;t.length>e;e++)t[e]=65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random());return t};w&&!C(w.crypto)&&crypto.getRandomValues&&(Yd=t=>crypto.getRandomValues(t));class bg{nextUint32(){return this.R.length>this.O||(Yd(this.R),this.O=0),this.R[this.O++]}constructor(){this.R=new Uint32Array(8),this.O=1/0}}var Ut=()=>Eg().toString(),Eg=()=>(kc||(kc=new wg)).generate(),mi="",Sg=/[a-z0-9][a-z0-9-]+\.[a-z]{2,}$/i,Wt={N:()=>!!F,j(t){A.error("cookieStore error: "+t)},P:Kd,H(t){var e;try{e=JSON.parse(Wt.P(t))||{}}catch{}return e},F(t,e,n,i,r){if(!F)return!1;try{var s="",o="",a=(function(c,d){if(d){var f=(function(p,g){if(g===void 0&&(g=F),mi)return mi;if(!g||["localhost","127.0.0.1"].includes(p))return"";for(var m=p.split("."),v=Math.min(m.length,8),E="dmn_chk_"+Ut();!mi&&v--;){var S=m.slice(v).join("."),_=E+"=1;domain=."+S+";path=/";g.cookie=_+";max-age=3",g.cookie.includes(E)&&(g.cookie=_+";max-age=0",mi=S)}return mi})(c);if(!f){var h=(p=>{var g=p.match(Sg);return g?g[0]:""})(c);h!==f&&A.info("Warning: cookie subdomain discovery mismatch",h,f),f=h}return f?"; domain=."+f:""}return""})(F.location.hostname,i);if(n){var l=new Date;l.setTime(l.getTime()+864e5*n),s="; expires="+l.toUTCString()}r&&(o="; secure");var u=t+"="+encodeURIComponent(JSON.stringify(e))+s+"; SameSite=Lax; path=/"+a+o;return u.length>3686.4&&A.warn("cookieStore warning: large cookie, len="+u.length),F.cookie=u,!0}catch{return!1}},q(t,e){if(F!=null&&F.cookie)try{Wt.F(t,"",-1,e)}catch{return}}},yo=null,oe={N(){if(!ze(yo))return yo;var t=!0;if(C(w))t=!1;else try{var e="__mplssupport__";oe.F(e,"xyz"),oe.P(e)!=='"xyz"'&&(t=!1),oe.q(e)}catch{t=!1}return t||A.error("localStorage unsupported; falling back to cookie store"),yo=t,t},j(t){A.error("localStorage error: "+t)},P(t){try{return w?.localStorage.getItem(t)}catch(e){oe.j(e)}return null},H(t){try{return JSON.parse(oe.P(t))||{}}catch{}return null},F(t,e){try{return w?.localStorage.setItem(t,JSON.stringify(e)),!0}catch(n){oe.j(n)}return!1},q(t){try{w?.localStorage.removeItem(t)}catch(e){oe.j(e)}}},xg=[Vi,"distinct_id",zn,rl,Yr,Kr,st],hr={},Ig={N:()=>!0,j(t){A.error("memoryStorage error: "+t)},P:t=>hr[t]||null,H:t=>hr[t]||null,F:(t,e)=>(hr[t]=e,!0),q(t){delete hr[t]}},gn=null,ye={N(){if(!ze(gn))return gn;if(gn=!0,C(w))gn=!1;else try{var t="__support__";ye.F(t,"xyz"),ye.P(t)!=='"xyz"'&&(gn=!1),ye.q(t)}catch{gn=!1}return gn},j(t){A.error("sessionStorage error: ",t)},P(t){try{return w?.sessionStorage.getItem(t)}catch(e){ye.j(e)}return null},H(t){try{return JSON.parse(ye.P(t))||null}catch{}return null},F(t,e){try{return w?.sessionStorage.setItem(t,JSON.stringify(e)),!0}catch(n){ye.j(n)}return!1},q(t){try{w?.sessionStorage.removeItem(t)}catch(e){ye.j(e)}}};class kg{constructor(e){this._instance=e}get Ne(){return this._instance.config}get consent(){return this.ti()?0:this.ei}isOptedOut(){return this.Ne.cookieless_mode===Ht||this.isRejected()||this.consent===-1&&this.Ne.cookieless_mode===Sn}isOptedIn(){return!this.isOptedOut()}isExplicitlyOptedOut(){return this.consent===0}isRejected(){return this.consent===0||this.consent===-1&&this.Ne.opt_out_capturing_by_default}optInOut(e){this.ii.F(this.ri,e?1:0,this.Ne.cookie_expiration,this.Ne.cross_subdomain_cookie,this.Ne.secure_cookie)}reset(){this.ii.q(this.ri,this.Ne.cross_subdomain_cookie)}get ri(){var e=this._instance.config,n=e.token,i=e.opt_out_capturing_cookie_prefix;return e.consent_persistence_name||(i?i+n:"__ph_opt_in_out_"+n)}get ei(){var e=this.ii.P(this.ri);return co(e)?1:j(Rp,e)?0:-1}get ii(){var e=this.Ne.opt_out_capturing_persistence_type,n=e==="localStorage"?oe:Wt;if(!this.ni||this.ni!==n){this.ni=n;var i=e==="localStorage"?Wt:oe;i.P(this.ri)&&(this.ni.P(this.ri)||this.optInOut(co(i.P(this.ri))),i.q(this.ri,this.Ne.cross_subdomain_cookie))}return this.ni}ti(){return!!this.Ne.respect_dnt&&[je?.doNotTrack,je?.msDoNotTrack,O.doNotTrack].some((e=>co(e)))}}function Jd(t,e){var n,i=t==null||(n=t.config)==null?void 0:n.get_current_url;if(!Be(i))return e;try{var r=i(e);return Z(r)&&r?r:e}catch(s){return A.error("Error in get_current_url, falling back to window.location.href",s),e}}var Zd="__POSTHOG_TOOLBAR__",Cg=1,Ag=3,Pg=11;function Cc(t){return t instanceof Element&&(t.id===Zd||!(t.closest==null||!t.closest(".toolbar-global-fade-container")))}function dn(t){return!!t&&t.nodeType===Cg}function Xe(t,e){return!!t&&!!t.tagName&&t.tagName.toLowerCase()===e.toLowerCase()}function Xd(t){return!!t&&t.nodeType===Ag}function Qd(t){return!!t&&t.nodeType===Pg&&dn(t.host)}var ef=1e3;function al(t){return t?bs(t).split(/\s+/):[]}function Ac(t,e){var n=(function(i){var r,s=w==null||(r=w.location)==null?void 0:r.href;return C(s)?void 0:Jd(i,s)})(e);return!!(n&&t&&t.some((i=>n.match(i))))}function Qr(t){var 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 al(e)}function tf(t){return H(t)?null:bs(t).split(/(\s+)/).filter((e=>Bi(e))).join("").replace(/[\r\n]/g," ").replace(/[ ]+/g," ").substring(0,255)}function Gi(t){var e="";return ma(t)&&!of(t)&&t.childNodes&&t.childNodes.length&&ie(t.childNodes,(function(n){var i;Xd(n)&&n.textContent&&(e+=(i=tf(n.textContent))!==null&&i!==void 0?i:"")})),bs(e)}function wo(t){var e;return C(t.target)?t.srcElement||null:(e=t.target)!=null&&e.shadowRoot?t.composedPath()[0]||null:t.target||null}var ll=["a","button","form","input","select","textarea","label"];function ga(t,e){if(C(e))return!0;var n,i=function(s){if(e.some((o=>(function(a,l){var u=a.matches||a.matchesSelector||a.msMatchesSelector||a.mozMatchesSelector||a.webkitMatchesSelector||a.oMatchesSelector;try{return!!u&&u.call(a,l)}catch{return!1}})(s,o))))return{v:!0}};for(var r of t)if(n=i(r))return n.v;return!1}function nf(t){var e=t.parentNode;return!(!e||!dn(e))&&e}var Fg=[".ph-no-autocapture","[data-ph-no-autocapture]"],rf=["next","previous","prev",">","<"],Rg=[...rf,"+","-","−","–"],Pc=(t,e)=>/[a-z0-9]/i.test(e)?t.includes(e):t===e,Fc=[".ph-no-rageclick",".ph-no-capture"],Tg=["","text","search","email","password","url","tel","number"];function Rc(t,e){if(!w||cl(t))return!1;var n,i,r,s,o;if(pt(e)?(n=!!e&&Fc,i=void 0,r=!1):(n=(s=e?.css_selector_ignorelist)!==null&&s!==void 0?s:Fc,i=e?.content_ignorelist,r=(o=e?.ignore_text_selection)!==null&&o!==void 0&&o),n===!1||r&&(function(l){return!(!l||!dn(l))&&(!!Xe(l,"textarea")||(Xe(l,"input")?j(Tg,(l.getAttribute("type")||"").toLowerCase()):(function(u){if(u.isContentEditable)return!0;var c=u.getAttribute==null?void 0:u.getAttribute("contenteditable");return c==="true"||c===""})(l)))})(t))return!1;var a=sf(t,!1).targetElementList;return!(function(l,u){if(l===!1||C(l))return!1;var c;if(l===!0)c=rf;else{if(!U(l))return!1;if(l.length>10)return A.error("[PostHog] content_ignorelist array cannot exceed 10 items. Use css_selector_ignorelist for more complex matching."),!1;c=l.map((d=>d.toLowerCase()))}return u.some((d=>{var f=d.safeText,h=d.ariaLabel;return c.some((p=>Pc(f,p)||Pc(h,p)))}))})(i,a.map((l=>{var u;return{safeText:Gi(l).toLowerCase(),ariaLabel:((u=l.getAttribute("aria-label"))==null?void 0:u.toLowerCase().trim())||""}})))&&!ga(a,n)}var cl=t=>!t||Xe(t,"html")||!dn(t),sf=(t,e)=>{if(!w||cl(t))return{parentIsUsefulElement:!1,targetElementList:[]};for(var n=!1,i=[t],r=t;r.parentNode&&!Xe(r,"body");)if(Qd(r.parentNode))i.push(r.parentNode.host),r=r.parentNode.host;else{var s=nf(r);if(!s)break;if(e||ll.indexOf(s.tagName.toLowerCase())>-1)n=!0;else try{var o=w.getComputedStyle(s);o&&o.getPropertyValue("cursor")==="pointer"&&(n=!0)}catch{}i.push(s),r=s}return{parentIsUsefulElement:n,targetElementList:i}};function ma(t){for(var e=new Set,n=0,i=t;i.parentNode&&!Xe(i,"body");i=i.parentNode){if(n++>=ef||e.has(i))return!1;e.add(i);var r=Qr(i);if(j(r,"ph-sensitive")||j(r,"ph-no-capture"))return!1}if(j(Qr(t),"ph-include"))return!0;var s=t.type||"";if(Z(s))switch(s.toLowerCase()){case"hidden":case"password":return!1}var o=t.name||t.id||"";return!Z(o)||!/^cc|cardnum|ccnum|creditcard|csc|cvc|cvv|exp|pass|pwd|routing|seccode|securitycode|securitynum|socialsec|socsec|ssn/i.test(o.replace(/[^a-zA-Z0-9]/g,""))}function of(t){return!!(Xe(t,"input")&&!["button","checkbox","submit","reset"].includes(t.type)||Xe(t,"select")||Xe(t,"textarea")||t.getAttribute("contenteditable")==="true")}var Tc=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}))$"),$c=/(^|[^0-9A-Za-z_])([0-9][0-9 -]*[0-9])(?=$|[^0-9A-Za-z_])/g,$g=[16,15,14,13],Mg=new RegExp("^(\\d{3}-?\\d{2}-?\\d{4})$"),Mc=new RegExp("(^|[^0-9])((?!000|666)[0-9]{3}-?(?!00)[0-9]{2}-?(?!0000)[0-9]{4})(?=$|([^0-9]))","g"),Lc=/[0-9A-Za-z_]/;function Lg(t){for(var e=0,n=!1,i=t.length-1;i>=0;i--){var r=t.charCodeAt(i)-48;n&&(r*=2)>9&&(r-=9),e+=r,n=!n}return e%10==0}function Bi(t,e){if(e===void 0&&(e=!0),H(t))return!1;if(Z(t)){t=bs(t);var n=e?Tc.test((t||"").replace(/[- ]/g,"")):(function(r){var s;for($c.lastIndex=0;s=$c.exec(r);){var o=s[2];if(o)for(var a=o.replace(/[- ]/g,""),l=0;a.length>l;l++)for(var u of $g){var c=l+u;if(a.length>=c){var d=a.slice(l,c);if(Tc.test(d)&&Lg(d))return!0}}}return!1})(t);if(n)return!1;var i=e?Mg.test(t):(function(r){var s;for(Mc.lastIndex=0;s=Mc.exec(r);){var o=s[1],a=s[3];if(!(o&&a&&Lc.test(o)&&Lc.test(a)))return!0}return!1})(t);if(i)return!1}return!0}function Nc(t){var e=Gi(t);return Bi(e=(e+" "+af(t)).trim())?e:""}function af(t){var e="";return t&&t.childNodes&&t.childNodes.length&&ie(t.childNodes,(function(n){var i;if(n&&((i=n.tagName)==null?void 0:i.toLowerCase())==="span")try{var r=Gi(n);e=(e+" "+r).trim(),n.childNodes&&n.childNodes.length&&(e=(e+" "+af(n)).trim())}catch(s){A.error("[AutoCapture]",s)}})),e}function Oc(t){return t.replace(/"|\\"/g,'\\"')}function Ng(t){var e=t.attr__class;if(e)return U(e)?e:al(e)}var pr=he("[Dead Clicks]"),Og=()=>!0,Bg=t=>{var e,n=!((e=t.instance.persistence)==null||!e.get_property(nl)),i=t.instance.config.capture_dead_clicks;return pt(i)?i:!!de(i)||n};class Bc{get lazyLoadedDeadClicksAutocapture(){return this.si}constructor(e,n,i){this.instance=e,this.isEnabled=n,this.onCapture=i,this.startIfEnabledOrStop()}onRemoteConfig(e){if(e.ok){var n=e.config;"captureDeadClicks"in n&&(this.instance.persistence&&this.instance.persistence.register({[nl]:n.captureDeadClicks}),this.startIfEnabledOrStop())}}startIfEnabledOrStop(){this.isEnabled(this)?this.ai((()=>{this.oi()})):this.stop()}ai(e){var n,i;(n=O.__PosthogExtensions__)!=null&&n.initDeadClicksAutocapture?e():(i=O.__PosthogExtensions__)==null||i.loadExternalDependency==null||i.loadExternalDependency(this.instance,"dead-clicks-autocapture",(r=>{r?pr.error("failed to load script",r):e()}))}oi(){var e;if(F){if(!this.si&&(e=O.__PosthogExtensions__)!=null&&e.initDeadClicksAutocapture){var n=de(this.instance.config.capture_dead_clicks)?k({},this.instance.config.capture_dead_clicks):{};n.__onCapture=this.onCapture,this.onCapture&&(n.capture_dead_swipes=!1),this.si=O.__PosthogExtensions__.initDeadClicksAutocapture(this.instance,n),this.si.start(F),pr.info("starting...")}}else pr.error("`document` not found. Cannot start.")}stop(){this.si&&(this.si.stop(),this.si=void 0,pr.info("stopping..."))}}var bo=he("[SegmentIntegration]"),lf="posthog-js";function cf(t,e){var n=e===void 0?{}:e,i=n.organization,r=n.projectId,s=n.prefix,o=n.severityAllowList,a=o===void 0?["error"]:o,l=n.sendExceptionsToPostHog,u=l===void 0||l;return c=>{var d,f,h,p,g;if(a!=="*"&&!a.includes(c.level)||!t.__loaded)return c;c.tags||(c.tags={});var m=t.requestRouter.endpointFor("ui","/project/"+t.config.token+"/person/"+t.get_distinct_id());c.tags["PostHog Person URL"]=m,t.sessionRecordingStarted()&&(c.tags["PostHog Recording URL"]=t.get_session_replay_url({withTimestamp:!0}));var v,E=((d=c.exception)==null?void 0:d.values)||[],S=E.map((x=>k({},x,{stacktrace:x.stacktrace?k({},x.stacktrace,{type:"raw",frames:(x.stacktrace.frames||[]).map((I=>k({},I,{platform:"web:javascript"})))}):void 0}))),_={$exception_message:((f=E[0])==null?void 0:f.value)||c.message,$exception_type:(h=E[0])==null?void 0:h.type,$exception_level:c.level,$exception_list:S,$sentry_event_id:c.event_id,$sentry_exception:c.exception,$sentry_exception_message:((p=E[0])==null?void 0:p.value)||c.message,$sentry_exception_type:(g=E[0])==null?void 0:g.type,$sentry_tags:c.tags};return i&&r&&(_.$sentry_url=(s||"https://sentry.io/organizations/")+i+"/issues/?project="+r+"&query="+c.event_id),u&&((v=t.exceptions)==null||v.sendExceptionEvent(_)),c}}class Dg{constructor(e,n,i,r,s,o){this.name=lf,this.setupOnce=function(a){a(cf(e,{organization:n,projectId:i,prefix:r,severityAllowList:s,sendExceptionsToPostHog:o==null||o}))}}}class Dc{constructor(e){this.li=(n,i,r)=>{r&&(r.noSessionId||r.activityTimeout||r.sessionPastMaximumLength||r.crossTabAdoption)&&(A.info("[PageViewManager] Session rotated, clearing pageview state",{sessionId:n,changeReason:r}),this.ui=void 0,this._instance.scrollManager.resetContext())},this._instance=e,this.hi()}hi(){var e;this.di=(e=this._instance.sessionManager)==null?void 0:e.onSessionId(this.li)}destroy(){var e;(e=this.di)==null||e.call(this),this.di=void 0}doPageView(e,n){var i,r=this.vi(e,n);return this.ui={pathname:(i=w?.location.pathname)!==null&&i!==void 0?i:"",pageViewId:n,timestamp:e},this._instance.scrollManager.resetContext(),r}doPageLeave(e){var n;return this.vi(e,(n=this.ui)==null?void 0:n.pageViewId)}doEvent(){var e;return{$pageview_id:(e=this.ui)==null?void 0:e.pageViewId}}vi(e,n){var i=this.ui;if(!i)return{$pageview_id:n};var r={$pageview_id:n,$prev_pageview_id:i.pageViewId},s=this._instance.scrollManager.getContext();if(s&&!this._instance.config.disable_scroll_properties){var o=s.maxScrollHeight,a=s.lastScrollY,l=s.maxScrollY,u=s.maxContentHeight,c=s.lastContentY,d=s.maxContentY;if(!(C(o)||C(a)||C(l)||C(u)||C(c)||C(d))){o=Math.ceil(o),a=Math.ceil(a),l=Math.ceil(l),u=Math.ceil(u),c=Math.ceil(c),d=Math.ceil(d);var f=o>1?kt(a/o,0,1,A):1,h=o>1?kt(l/o,0,1,A):1,p=u>1?kt(c/u,0,1,A):1,g=u>1?kt(d/u,0,1,A):1;r=ue(r,{$prev_pageview_last_scroll:a,$prev_pageview_last_scroll_percentage:f,$prev_pageview_max_scroll:l,$prev_pageview_max_scroll_percentage:h,$prev_pageview_last_content:c,$prev_pageview_last_content_percentage:p,$prev_pageview_max_content:d,$prev_pageview_max_content_percentage:g})}}return i.pathname&&(r.$prev_pageview_pathname=i.pathname),i.timestamp&&(r.$prev_pageview_duration=(e.getTime()-i.timestamp.getTime())/1e3),r}}var Eo=["flags","surveys"],jg={[Bd]:{exposure:"hidden"},[Ci]:{exposure:"hidden"},__cmpns:{exposure:"hidden"},[Ai]:{exposure:"hidden"},[Qo]:{exposure:"event"},[ea]:{exposure:"hidden"},[ta]:{exposure:"event"},[na]:{exposure:"hidden"},[ia]:{exposure:"event"},[ra]:{exposure:"event"},[nl]:{exposure:"event"},[il]:{exposure:"hidden"},[sa]:{exposure:"event"},[In]:{exposure:"hidden"},$session_recording_enabled_server_side:{exposure:"hidden"},[zn]:{exposure:"hidden"},[rl]:{exposure:"event"},[Dd]:{exposure:"event",shouldSkipFromEventProperties:t=>ze(t)},$session_past_minimum_duration:{exposure:"event"},$session_recording_url_trigger_activated_session:{exposure:"event"},$session_recording_event_trigger_activated_session:{exposure:"event"},$debug_first_full_snapshot_timestamp:{exposure:"event"},$sess_rec_flush_size:{exposure:"hidden"},[wn]:{exposure:"hidden",storageGroup:"flags"},[Pi]:{exposure:"hidden",storageGroup:"flags"},[Sr]:{exposure:"hidden"},[oa]:{exposure:"hidden",storageGroup:"flags"},[Fi]:{exposure:"hidden",storageGroup:"flags"},[xr]:{exposure:"hidden",storageGroup:"flags",volatile:!0},[Vr]:{exposure:"hidden",storageGroup:"flags"},[St]:{exposure:"hidden"},[bn]:{exposure:"hidden"},[Dt]:{exposure:"hidden"},[En]:{exposure:"hidden"},[aa]:{exposure:"hidden",storageGroup:"surveys"},[Gr]:{exposure:"hidden",storageGroup:"surveys",volatile:!0},[la]:{exposure:"event"},[Ir]:{exposure:"hidden"},[kr]:{exposure:"hidden"},[Ri]:{exposure:"hidden"},$product_tours_activated:{exposure:"hidden"},$product_tours_activated_session:{exposure:"hidden"},$conversations_widget_session_id:{exposure:"event"},$conversations_ticket_id:{exposure:"event"},$conversations_widget_state:{exposure:"event"},$conversations_user_traits:{exposure:"event"},[xn]:{exposure:"hidden"},[Ti]:{exposure:"hidden"},[Cr]:{exposure:"hidden"},[Oi]:{exposure:"hidden",storageGroup:"flags",volatile:!0},[st]:{exposure:"hidden"},[ca]:{exposure:"hidden"},[ua]:{exposure:"hidden"},[da]:{exposure:"hidden"},[fa]:{exposure:"hidden"},[Kr]:{exposure:"hidden"},[Yr]:{exposure:"hidden"},[jd]:{exposure:"event"},[Ud]:{exposure:"event"},[Hd]:{exposure:"event"},[Wd]:{exposure:"event"},[zd]:{exposure:"event"},[Vd]:{exposure:"event"},[Gd]:{exposure:"event"},$sdk_debug_replay_event_trigger_status:{exposure:"event"},$sdk_debug_replay_linked_flag_trigger_status:{exposure:"event"},$sdk_debug_replay_matched_recording_trigger_groups:{exposure:"event"},$sdk_debug_replay_remote_trigger_matching_config:{exposure:"event"},$sdk_debug_replay_trigger_groups_count:{exposure:"event"},$sdk_debug_replay_url_trigger_status:{exposure:"event"},$session_recording_start_reason:{exposure:"event"}},Ug=[["$posthog_sr_group_event_trigger_",{exposure:"hidden"}],["$posthog_sr_group_url_trigger_",{exposure:"hidden"}],["$posthog_sr_group_sampling_",{exposure:"hidden"}]],mn=t=>{var e=jg[t];if(e)return e;for(var n of Ug){var i=n[1];if(t.indexOf(n[0])===0)return i}},Vn=(t,e)=>{try{return JSON.stringify(t,((n,i)=>typeof i=="bigint"?i.toString():i),e)}catch{return sd(t)}},es=t=>{var e=F?.createElement("a");return C(e)?null:(e.href=t,e)},ei=function(t,e){for(var n,i=((t.split("#")[0]||"").split(/\?(.*)/)[1]||"").replace(/^\?+/g,"").split("&"),r=0;i.length>r;r++){var s=i[r].split("=");if(s[0]===e){n=s;break}}if(!U(n)||2>n.length)return"";var o=n[1];try{o=decodeURIComponent(o)}catch{A.error("Skipping decoding for malformed query param: "+o)}return o.replace(/\+/g," ")},Ki=function(t,e,n){if(!t||!e||!e.length)return t;for(var i=t.split("#"),r=i[1],s=(i[0]||"").split("?"),o=s[1],a=s[0],l=(o||"").split("&"),u=[],c=0;l.length>c;c++){var d=l[c].split("=");U(d)&&(e.includes(d[0])?u.push(d[0]+"="+n):u.push(l[c]))}var f=a;return o!=null&&(f+="?"+u.join("&")),r!=null&&(f+="#"+r),f},ts=function(t,e){var n=t.match(new RegExp(e+"=([^&]*)"));return n?n[1]:null},uf=(t,e)=>t>=e&&nd(),df=(t,e,n,i)=>{if(t===0){if(nd()){var r=e+1;return r===n&&i(),r}return e}return 0},gr="https?://(.*)",ti=["gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","irclid","_kx"],Hg=["utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid",...ti],Yi="",Wg=["li_fat_id"];function ff(t,e,n){if(!F)return{};var i,r=e?[...ti,...n||[]]:[],s=hf(Ki(F.URL,r,Yi),t),o=(i={},ie(Wg,(function(a){var l=Kd(a);i[a]=l||null})),i);return ue(o,s)}function hf(t,e){var n=Hg.concat(e||[]),i={};return ie(n,(function(r){var s=ei(t,r);i[r]=s||null})),i}function pf(t){var e=(function(s){return s?s.search(gr+"google.([^/?]*)")===0?"google":s.search(gr+"bing.com")===0?"bing":s.search(gr+"yahoo.com")===0?"yahoo":s.search(gr+"duckduckgo.com")===0?"duckduckgo":null:null})(t),n=e!="yahoo"?"q":"p",i={};if(!ze(e)){i.$search_engine=e;var r=F?ei(F.referrer,n):"";r.length&&(i.ph_keyword=r)}return i}function jc(){return navigator.language||navigator.userLanguage}var ns="$direct";function gf(){return F?.referrer||ns}function mf(t,e,n){n===void 0&&(n=!1);var i=t?[...ti,...e||[]]:[],r=n?un(ge?.href):ge?.href,s=r?.substring(0,1e3);return{r:gf().substring(0,1e3),u:s?Ki(s,i,Yi):void 0}}function vf(t,e){var n;e===void 0&&(e=!1);var i=t.r,r=t.u,s=e?un(r):r,o={$referrer:i,$referring_domain:i==null?void 0:i==ns?ns:(n=es(i))==null?void 0:n.host};if(s){o.$current_url=s;var a=es(s);o.$host=a?.host,o.$pathname=a?.pathname;var l=hf(s);ue(o,l)}if(i){var u=pf(i);ue(o,u)}return o}function _f(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return}}function qg(){try{return new Date().getTimezoneOffset()}catch{return}}var zg={flags:Oi,surveys:Gr},Vg=["cookie","localstorage","localstorage+cookie","sessionstorage","memory"],Dn="main";class So{constructor(e,n,i){if(i===void 0&&(i=!0),this.ci={},this.fi=!1,this.pi=!1,this.Ne=e,this.gi=i,this.props={},this.mi=void 0,this.yi=(s=>{var o="";return s.token&&(o=s.token.replace(/\+/g,"PL").replace(/\//g,"SL").replace(/=/g,"EQ")),s.persistence_name?"ph_"+s.persistence_name:"ph_"+o+"_posthog"})(e),this.ii=this.bi(e),this.pi=this.wi(e),this.load(),e.debug&&A.info("Persistence loaded",e.persistence,k({},this.props)),this.update_config(e,e,n),this.save(),w){var r=()=>this.flush();me(w,"beforeunload",r,{capture:!1}),me(w,"pagehide",r,{capture:!1})}}ki(){var e,n=(e=this.Ne)==null?void 0:e.persistence_save_debounce_ms;return xe(n)&&n>0?n:0}isDisabled(){return!!this.xi}bi(e){Vg.indexOf(e.persistence.toLowerCase())===-1&&(A.critical("Unknown persistence type "+e.persistence+"; falling back to localStorage+cookie"),e.persistence="localStorage+cookie");var n,i=(function(o,a){o===void 0&&(o=[]),a===void 0&&(a=!1);var l=[...xg,...o];return k({},oe,{H(u){try{var c={};try{c=Wt.H(u)||{}}catch{}var d,f=JSON.parse(oe.P(u)||"{}");if(a){var h={};for(var p in c){var g=c[p];ze(g)||g===""||(h[p]=g)}d=ue(f,h)}else d=ue(c,f);return oe.F(u,d),d}catch{}return null},F(u,c,d,f,h,p){var g=oe.F(u,c,void 0,void 0,p);try{var m={};l.forEach((v=>{c[v]&&(m[v]=c[v])})),Object.keys(m).length&&Wt.F(u,m,d,f,h,p)}catch(v){oe.j(v)}return g},q(u,c){try{w?.localStorage.removeItem(u),Wt.q(u,c)}catch(d){oe.j(d)}}})})(e.cookie_persisted_properties||[],e.__preview_cookie_wins_on_conflict||!1),r=!1,s=e.persistence.toLowerCase();return s==="localstorage"&&oe.N()?(n=oe,r=!0):s==="localstorage+cookie"&&i.N()?(n=i,r=!0):s==="sessionstorage"&&ye.N()?n=ye:s==="memory"?n=Ig:s==="cookie"?n=Wt:i.N()?(n=i,r=!0):n=Wt,this.fi=r,n}Si(e){return this.yi+"__"+e}wi(e){return this.fi&&!!e.split_storage}properties(){var e={};return ie(this.props,((n,i)=>{var r=mn(i);if(!r||r.exposure==="event"){if(r!=null&&r.shouldSkipFromEventProperties!=null&&r.shouldSkipFromEventProperties(n))return;e[i]=n}})),e}load(){if(!this.xi){var e=this.ii.H(this.yi);e&&(this.props=ue({},e)),this.pi&&this.Ci()}}Ci(){for(var e of Eo){var n=oe.H(this.Si(e));if(n&&!Vt(n)){var i=this.Mi(e);i.persisted=!0,this.Ti(e)||(i.fingerprint=this.Ei(n,e)),this.Ii(e,n)||ue(this.props,n)}}}Ti(e){return Object.keys(this.props).some((n=>{var i;return((i=mn(n))==null?void 0:i.storageGroup)===e}))}Ii(e,n){var i=zg[e];if(!i)return!1;var r=n[i],s=this.props[i];return xe(r)&&xe(s)&&s>r}refreshKey(e){var n;if(!this.xi){var i=this.pi?(n=mn(e))==null?void 0:n.storageGroup:void 0,r=i?oe.H(this.Si(i)):this.ii.H(this.yi);if(r&&e in r)this.Pi(e,r[e]);else{if(i){var s=this.ii.H(this.yi);if(s&&e in s)return void this.Pi(e,s[e])}this.Ri(e)}}}save(){if(!this.xi){var e=this.ki();e>0?C(this.Ai)&&(this.Ai=setTimeout((()=>{this.Ai=void 0,this.Fi()}),e)):this.Fi()}}flush(){C(this.Ai)||(clearTimeout(this.Ai),this.Ai=void 0,this.Fi())}Fi(){this.xi||(this.pi?this.Li():this.Oi(this.ii,this.yi,this.props,Dn))}Li(){var e=this.Di(),n=e.main,i=e.groups;for(var r of(this.Oi(this.ii,this.yi,n,Dn),Eo)){var s,o=i[r];(!Vt(o)||(s=this.ci[r])!=null&&s.persisted)&&this.Oi(oe,this.Si(r),o,r)}}Di(){var e={},n={flags:{},surveys:{}};return ie(this.props,((i,r)=>{var s,o=(s=mn(r))==null?void 0:s.storageGroup;o?n[o][r]=i:e[r]=i})),{main:e,groups:n}}Ei(e,n){if(n===Dn)return JSON.stringify(e)+"|"+this.$i+"|"+this.Ni+"|"+this.qi;var i={};return ie(e,((r,s)=>{var o;i[s]=(o=mn(s))!=null&&o.volatile?"__volatile__":r})),JSON.stringify(i)}Oi(e,n,i,r){var s=this.Mi(r);if(r===Dn||s.dirty||C(s.fingerprint)){var o;try{if((o=this.Ei(i,r))===s.fingerprint)return void(s.dirty=!1)}catch{o=void 0}e.F(n,i,this.$i,this.Ni,this.qi,this.Ne.debug)?(s.dirty=!1,r!==Dn&&(s.persisted=!0),C(o)||(s.fingerprint=o)):this.Ne.debug&&A.warn('failed to persist storage entry "'+n+'"; will retry on next save')}}remove(e){var n=(e===void 0?{}:e).keepGroupEntries,i=n!==void 0&&n;if(C(this.Ai)||(clearTimeout(this.Ai),this.Ai=void 0),this.ii.q(this.yi,!1),this.ii.q(this.yi,!0),!i&&this.gi)for(var r of Eo)oe.q(this.Si(r));i?delete this.ci[Dn]:this.ci={}}clear(){this.remove(),this.props={}}register_once(e,n,i){if(de(e)){C(n)&&(n="None"),this.$i=C(i)?this.ji:i;var r=!1;if(ie(e,((s,o)=>{this.props.hasOwnProperty(o)&&this.props[o]!==n||(this.Pi(o,s),r=!0)})),r)return this.save(),!0}return!1}register(e,n){if(de(e)){this.$i=C(n)?this.ji:n;var i=!1;if(ie(e,((r,s)=>{e.hasOwnProperty(s)&&(this.props[s]!==r||de(r)||U(r))&&(this.Pi(s,r),i=!0)})),i)return this.save(),!0}return!1}unregister(e){var n=typeof e=="string"?[e]:e,i=!1;for(var r of n)r in this.props&&(this.Ri(r),i=!0);i&&this.save()}update_campaign_params(){var e=F?.URL;if(e!==this.mi){var n=ff(this.Ne.custom_campaign_params,this.Ne.mask_personal_data_properties,this.Ne.custom_personal_data_properties);Vt(ol(n))||this.register(n),this.mi=e}}update_search_keyword(){var e;this.register((e=F?.referrer)?pf(e):{})}update_referrer_info(){var e;this.register_once({$referrer:gf(),$referring_domain:F!=null&&F.referrer&&((e=es(F.referrer))==null?void 0:e.host)||ns},void 0)}set_initial_person_info(){this.props[da]||this.props[fa]||this.register_once({[Kr]:mf(this.Ne.mask_personal_data_properties,this.Ne.custom_personal_data_properties,this.Ne.disable_capture_url_hashes)},void 0)}get_initial_props(){var e={};ie([fa,da],(r=>{var s=this.props[r];s&&ie(s,(function(o,a){e["$initial_"+Vo(a)]=o}))}));var n=this.props[Kr];if(n){var i=(function(r,s){s===void 0&&(s=!1);var o=vf(r,s),a={};return ie(o,(function(l,u){a["$initial_"+Vo(u)]=l})),a})(n,this.Ne.disable_capture_url_hashes);ue(e,i)}return e}safe_merge(e){return ie(this.props,(function(n,i){i in e||(e[i]=n)})),e}update_config(e,n,i){this.ji=this.$i=e.cookie_expiration,this.set_disabled(e.disable_persistence||!!i),this.set_cross_subdomain(e.cross_subdomain_cookie),this.set_secure(e.secure_cookie);var r=e.persistence!==n.persistence||!((l,u)=>{if(l.length!==u.length)return!1;var c=[...l].sort(),d=[...u].sort();return c.every(((f,h)=>f===d[h]))})(e.cookie_persisted_properties||[],n.cookie_persisted_properties||[]),s=r?this.bi(e):this.ii,o=this.wi(e);if(r||o!==this.pi){var a=this.props;this.clear(),this.ii=s,this.pi=o,this.props=a,this.save()}}set_disabled(e){this.xi=e,this.xi?this.remove():this.save()}set_cross_subdomain(e){e!==this.Ni&&(this.Ni=e,this.remove({keepGroupEntries:!0}),this.save())}set_secure(e){e!==this.qi&&(this.qi=e,this.remove({keepGroupEntries:!0}),this.save())}set_event_timer(e,n){var i=this.props[Ai]||{};i[e]=n,this.Pi(Ai,i),this.save()}remove_event_timer(e){var n=this.props[Ai]||{},i=n[e];return C(i)||(delete n[e],this.Pi(Ai,n),this.save()),i}get_property(e){return this.props[e]}set_property(e,n){this.Pi(e,n),this.save()}Pi(e,n){var i;this.props[e]=n,(i=mn(e))!=null&&i.volatile||this.Bi(e)}Ri(e){delete this.props[e],this.Bi(e)}Bi(e){var n,i=(n=mn(e))==null?void 0:n.storageGroup;i&&(this.Mi(i).dirty=!0)}Mi(e){return this.ci[e]||(this.ci[e]={})}}function mr(t){var e=!0;return{dispose(){if(e){e=!1;var n=t();n&&Be(n.then)&&n.then(void 0,(()=>{}))}}}}var De={GZipJS:"gzip-js",Base64:"base64"},vi={Activation:"events",Cancellation:"cancelEvents"},xo={Popover:"popover",API:"api",Widget:"widget"},qt={SHOWN:"survey shown",DISMISSED:"survey dismissed",SENT:"survey sent"},Io={SURVEY_ID:"$survey_id",SURVEY_ITERATION:"$survey_iteration",SURVEY_LAST_SEEN_DATE:"$survey_last_seen_date"},va={Popover:"popover",Inline:"inline"},Gg={SHOWN:"product tour shown"},Uc={TOUR_LAST_SEEN_DATE:"$product_tour_last_seen_date",TOUR_TYPE:"$product_tour_type"},Hc=he("[RateLimiter]");class Kg{constructor(e){this.serverLimits={},this.lastEventRateLimited=!1,this.checkForLimiting=n=>{var i=n.text;if(i&&i.length)try{(JSON.parse(i).quota_limited||[]).forEach((r=>{Hc.info((r||"events")+" is quota limited."),this.serverLimits[r]=new Date().getTime()+6e4}))}catch(r){return void Hc.warn('could not rate limit - continuing. Error: "'+r?.message+'"',{text:i})}},this.instance=e,this.lastEventRateLimited=this.clientRateLimitContext(!0).isRateLimited}get captureEventsPerSecond(){var e;return((e=this.instance.config.rate_limiting)==null?void 0:e.events_per_second)||10}get captureEventsBurstLimit(){var e;return Math.max(((e=this.instance.config.rate_limiting)==null?void 0:e.events_burst_limit)||10*this.captureEventsPerSecond,this.captureEventsPerSecond)}clientRateLimitContext(e){var n,i,r;e===void 0&&(e=!1);var s=this.captureEventsBurstLimit,o=this.captureEventsPerSecond,a=new Date().getTime(),l=(n=(i=this.instance.persistence)==null?void 0:i.get_property(ua))!==null&&n!==void 0?n:{tokens:s,last:a};l.tokens+=(a-l.last)/1e3*o,l.last=a,l.tokens>s&&(l.tokens=s);var u=1>l.tokens;if(u||e||(l.tokens=Math.max(0,l.tokens-1)),u&&!e){var c=(xe(l.dropped)?l.dropped:0)+1;l.dropped=c,!this.lastEventRateLimited&&this.Hi(c)&&(l.dropped=0)}return this.lastEventRateLimited=u,(r=this.instance.persistence)==null||r.set_property(ua,l),{isRateLimited:u,remainingTokens:l.tokens}}Ui(e){var n=this.instance.config.property_denylist;return!U(n)||!n.includes(e)}zi(){var e;if(this.Ui("$current_url")&&this.Ui("$pathname")&&ge!=null&&ge.pathname)return""+((e=ge.origin)!==null&&e!==void 0?e:"")+ge.pathname}Hi(e){var n,i,r=this.captureEventsBurstLimit,s=this.captureEventsPerSecond,o=this.zi(),a=this.Ui("$session_id")?(n=(i=this.instance).get_session_id)==null?void 0:n.call(i):void 0,l=[e+" event(s) dropped since the last warning",o?"triggered on "+o:void 0,a?"session "+a: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(e){var n=this.serverLimits[e||"events"]||!1;return n!==!1&&new Date().getTime()e(this.remoteConfig))):e()}Vi(e){this._instance._send_request({method:"GET",url:this._instance.requestRouter.endpointFor("assets","/array/"+this._instance.config.token+"/config"),callback:e})}load(){try{if(this.remoteConfig)return sn.info("Using preloaded remote config",this.remoteConfig),this.Zi(this.remoteConfig),void this.Gi();if(this._instance.Qi())return void sn.warn("Remote config is disabled. Falling back to local config.");this.Wi((e=>{if(!e)return sn.info("No config found after loading remote JS config. Falling back to JSON."),void this.Vi((n=>{this.Zi(n.json,n),this.Gi()}));this.Zi(e),this.Gi()}))}catch(e){sn.error("Error loading remote config",e),this.Zi()}}stop(){this.Ki&&(clearInterval(this.Ki),this.Ki=void 0)}refresh(){!this._instance.Qi()&&F&&F.visibilityState!=="hidden"&&this._instance.reloadFeatureFlags()}Gi(){var e;if(!this.Ki){var n=(e=this._instance.config.remote_config_refresh_interval_ms)!==null&&e!==void 0?e:3e5;n!==0&&(this.Ki=setInterval((()=>{this.refresh()}),n))}}Zi(e,n){!e&&n&&(n.statusCode===0?n.error||sn.warn("Failed to fetch remote config from PostHog."):sn.error("Failed to fetch remote config from PostHog."));try{this._instance.Zi(e?{ok:!0,config:e}:{ok:!1})}catch(r){sn.error("Error applying remote config",r)}if(e?.hasFeatureFlags!==!1&&!this._instance.config.advanced_disable_feature_flags_on_first_load)try{var i;(i=this._instance.featureFlags)==null||i.ensureFlagsLoaded()}catch(r){sn.error("Error loading feature flags",r)}}}var at=Uint8Array,qe=Uint16Array,ni=Uint32Array,ul=new at([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]),dl=new at([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]),Wc=new at([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),wf=function(t,e){for(var n=new qe(31),i=0;31>i;++i)n[i]=e+=1<i;++i)for(var s=n[i];n[i+1]>s;++s)r[s]=s-n[i]<<5|i;return[n,r]},bf=wf(ul,2),_a=bf[1];bf[0][28]=258,_a[258]=28;for(var qc=wf(dl,0)[1],Ef=new qe(32768),ve=0;32768>ve;++ve){var jn=(43690&ve)>>>1|(21845&ve)<<1;Ef[ve]=((65280&(jn=(61680&(jn=(52428&jn)>>>2|(13107&jn)<<2))>>>4|(3855&jn)<<4))>>>8|(255&jn)<<8)>>>1}var Di=function(t,e,n){for(var i=t.length,r=0,s=new qe(e);i>r;++r)++s[t[r]-1];var o,a=new qe(e);for(r=0;e>r;++r)a[r]=a[r-1]+s[r-1]<<1;for(o=new qe(i),r=0;i>r;++r)o[r]=Ef[a[t[r]-1]++]>>>15-t[r];return o},Fn=new at(288);for(ve=0;144>ve;++ve)Fn[ve]=8;for(ve=144;256>ve;++ve)Fn[ve]=9;for(ve=256;280>ve;++ve)Fn[ve]=7;for(ve=280;288>ve;++ve)Fn[ve]=8;var is=new at(32);for(ve=0;32>ve;++ve)is[ve]=5;var Yg=Di(Fn,9),Jg=Di(is,5),Sf=function(t){return(t/8>>0)+(7&t&&1)},xf=function(t,e,n){(n==null||n>t.length)&&(n=t.length);var i=new(t instanceof qe?qe:t instanceof ni?ni:at)(n-e);return i.set(t.subarray(e,n)),i},Nt=function(t,e,n){var i=e/8>>0;t[i]|=n<<=7&e,t[i+1]|=n>>>8},_i=function(t,e,n){var i=e/8>>0;t[i]|=n<<=7&e,t[i+1]|=n>>>8,t[i+2]|=n>>>16},ko=function(t,e){for(var n=[],i=0;t.length>i;++i)t[i]&&n.push({s:i,f:t[i]});var r=n.length,s=n.slice();if(!r)return[new at(0),0];if(r==1){var o=new at(n[0].s+1);return o[n[0].s]=1,[o,1]}n.sort((function(x,I){return x.f-I.f})),n.push({s:-1,f:25001});var a=n[0],l=n[1],u=0,c=1,d=2;for(n[0]={s:-1,f:a.f+l.f,l:a,r:l};c!=r-1;)a=n[n[d].f>n[u].f?u++:d++],l=n[u!=c&&n[d].f>n[u].f?u++:d++],n[c++]={s:-1,f:a.f+l.f,l:a,r:l};var f=s[0].s;for(i=1;r>i;++i)s[i].s>f&&(f=s[i].s);var h=new qe(f+1),p=ya(n[c-1],h,0);if(p>e){i=0;var g=0,m=p-e,v=1<i;++i){var E=s[i].s;if(e>=h[E])break;g+=v-(1<>>=m;g>0;){var S=s[i].s;e>h[S]?g-=1<=0&&g;--i){var _=s[i].s;h[_]==e&&(--h[_],++g)}p=e}return[new at(h),p]},ya=function(t,e,n){return t.s==-1?Math.max(ya(t.l,e,n+1),ya(t.r,e,n+1)):e[t.s]=n},zc=function(t){for(var e=t.length;e&&!t[--e];);for(var n=new qe(++e),i=0,r=t[0],s=1,o=function(l){n[i++]=l},a=1;e>=a;++a)if(t[a]==r&&a!=e)++s;else{if(!r&&s>2){for(;s>138;s-=138)o(32754);s>2&&(o(s>10?s-11<<5|28690:s-3<<5|12305),s=0)}else if(s>3){for(o(r),--s;s>6;s-=6)o(8304);s>2&&(o(s-3<<5|8208),s=0)}for(;s--;)o(r);s=1,r=t[a]}return[n.subarray(0,i),e]},yi=function(t,e){for(var n=0,i=0;e.length>i;++i)n+=t[i]*e[i];return n},wa=function(t,e,n){var i=n.length,r=Sf(e+2);t[r]=255&i,t[r+1]=i>>>8,t[r+2]=255^t[r],t[r+3]=255^t[r+1];for(var s=0;i>s;++s)t[r+s+4]=n[s];return 8*(r+4+i)},Vc=function(t,e,n,i,r,s,o,a,l,u,c){Nt(e,c++,n),++r[256];for(var d=ko(r,15),f=d[0],h=d[1],p=ko(s,15),g=p[0],m=p[1],v=zc(f),E=v[0],S=v[1],_=zc(g),x=_[0],I=_[1],M=new qe(19),b=0;E.length>b;++b)M[31&E[b]]++;for(b=0;x.length>b;++b)M[31&x[b]]++;for(var P=ko(M,7),R=P[0],N=P[1],L=19;L>4&&!R[Wc[L-1]];--L);var B,T,V,$,G=u+5<<3,ee=yi(r,Fn)+yi(s,is)+o,Fe=yi(r,f)+yi(s,g)+o+14+3*L+yi(M,R)+(2*M[16]+3*M[17]+7*M[18]);if(ee>=G&&Fe>=G)return wa(e,c,t.subarray(l,l+u));if(Nt(e,c,1+(ee>Fe)),c+=2,ee>Fe){B=Di(f,h),T=f,V=Di(g,m),$=g;var we=Di(R,N);for(Nt(e,c,S-257),Nt(e,c+5,I-1),Nt(e,c+10,L-4),c+=14,b=0;L>b;++b)Nt(e,c+3*b,R[Wc[b]]);c+=3*L;for(var ke=[E,x],$e=0;2>$e;++$e){var se=ke[$e];for(b=0;se.length>b;++b)Nt(e,c,we[Se=31&se[b]]),c+=R[Se],Se>15&&(Nt(e,c,se[b]>>>5&127),c+=se[b]>>>12)}}else B=Yg,T=Fn,V=Jg,$=is;for(b=0;a>b;++b)if(i[b]>255){var Se;_i(e,c,B[257+(Se=i[b]>>>18&31)]),c+=T[Se+257],Se>7&&(Nt(e,c,i[b]>>>23&31),c+=ul[Se]);var be=31&i[b];_i(e,c,V[be]),c+=$[be],be>3&&(_i(e,c,i[b]>>>5&8191),c+=dl[be])}else _i(e,c,B[i[b]]),c+=T[i[b]];return _i(e,c,B[256]),c+T[256]},Zg=new ni([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),Xg=(function(){for(var t=new ni(256),e=0;256>e;++e){for(var n=e,i=9;--i;)n=(1&n&&3988292384)^n>>>1;t[e]=n}return t})(),Co=function(t,e,n){for(;n;++e)t[e]=n,n>>>=8};function Qg(t,e){e===void 0&&(e={});var n=(function(){var d=4294967295;return{p(f){for(var h=d,p=0;f.length>p;++p)h=Xg[255&h^f[p]]^h>>>8;d=h},d(){return 4294967295^d}}})(),i=t.length;n.p(t);var r,s,o,a,l,u=(a=10+((r=e).filename&&r.filename.length+1||0),l=8,(function(d,f,h,p,g,m){var v=d.length,E=new at(p+v+5*(1+Math.floor(v/7e3))+g),S=E.subarray(p,E.length-g),_=0;if(!f||8>v)for(var x=0;v>=x;x+=65535){var I=x+65535;v>I?_=wa(S,_,d.subarray(x,I)):(S[x]=!0,_=wa(S,_,d.subarray(x,v)))}else{for(var M=Zg[f-1],b=M>>>13,P=8191&M,R=(1<x;++x){var Se=V(x),be=32767&x,Oe=L[Se];if(N[be]=Oe,L[Se]=be,x>=$e){var _t=v-x;if((Fe>7e3||ke>24576)&&_t>423){_=Vc(d,S,0,$,G,ee,we,ke,se,x-se,_),ke=Fe=we=0,se=x;for(var pe=0;286>pe;++pe)G[pe]=0;for(pe=0;30>pe;++pe)ee[pe]=0}var Ke=2,yt=0,hn=P,Re=be-Oe&32767;if(_t>2&&Se==V(x-Re))for(var Ae=Math.min(b,_t)-1,Tt=Math.min(32767,x),Ln=Math.min(258,_t);Tt>=Re&&--hn&&be!=Oe;){if(d[x+Ke]==d[x+Ke-Re]){for(var Ue=0;Ln>Ue&&d[x+Ue]==d[x+Ue-Re];++Ue);if(Ue>Ke){if(Ke=Ue,yt=Re,Ue>Ae)break;var Nn=Math.min(Re,Ue-2),$t=0;for(pe=0;Nn>pe;++pe){var Mt=x-Re+pe+32768&32767,lt=Mt-N[Mt]+32768&32767;lt>$t&&($t=lt,Oe=Mt)}}}Re+=(be=Oe)-(Oe=N[be])+32768&32767}if(yt){$[ke++]=268435456|_a[Ke]<<18|qc[yt];var nn=31&_a[Ke],fi=31&qc[yt];we+=ul[nn]+dl[fi],++G[257+nn],++ee[fi],$e=x+Ke,++Fe}else $[ke++]=d[x],++G[d[x]]}}_=Vc(d,S,!0,$,G,ee,we,ke,se,x-se,_)}return xf(E,0,p+Sf(_)+g)})(s=t,(o=e).level==null?6:o.level,o.mem==null?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(s.length)))):12+o.mem,a,l)),c=u.length;return(function(d,f){var h=f.filename;if(d[0]=31,d[1]=139,d[2]=8,d[8]=2>f.level?4:f.level==9?2:0,d[9]=3,f.mtime!=0&&Co(d,4,Math.floor(new Date(f.mtime||Date.now())/1e3)),h){d[3]=8;for(var p=0;h.length>=p;++p)d[p+10]=h.charCodeAt(p)}})(u,e),Co(u,c-8,n.d()),Co(u,c-4,i),u}var em=!!Wo||!!Ya,If="text/plain",Pr=!1,kf=(t,e)=>{var n=t.split("#"),i=n[1],r=n[0].split("?"),s=r[0],o=r[1];if(!o)return t;var a=o.split("&").filter((l=>l.split("=")[0]!==e)).join("&");return s+(a?"?"+a:"")+(i?"#"+i:"")},Ss=function(t,e,n){var i;n===void 0&&(n=!0);var r=t.split("?"),s=r[0],o=r[1],a=k({},e),l=(i=o?.split("&").map((c=>{var d,f=c.split("="),h=f[0],p=n&&(d=a[h])!==null&&d!==void 0?d:f[1];return delete a[h],h+"="+p})))!==null&&i!==void 0?i:[],u=(function(c,d){var f,h;d===void 0&&(d="&");var p=[];return ie(c,(function(g,m){C(g)||C(m)||m==="undefined"||(f=encodeURIComponent((v=>v instanceof File)(g)?g.name:g.toString()),h=encodeURIComponent(m),p[p.length]=h+"="+f)})),p.join(d)})(a);return u&&l.push(u),l.length>0?s+"?"+l.join("&"):s},Ao=t=>{if(t.Ji)return t.Ji;var e=t.data,n=t.compression;if(e){if(n===De.GZipJS){var i=Qg((function(a,l){var u=a.length;if(typeof TextEncoder<"u")return new TextEncoder().encode(a);for(var c=new at(a.length+(a.length>>>1)),d=0,f=function(m){c[d++]=m},h=0;u>h;++h){if(d+5>c.length){var p=new at(d+8+(u-h<<1));p.set(c),c=p}var g=a.charCodeAt(h);128>g?f(g):2048>g?(f(192|g>>>6),f(128|63&g)):g>55295&&57344>g?(f(240|(g=65536+(1047552&g)|1023&a.charCodeAt(++h))>>>18),f(128|g>>>12&63),f(128|g>>>6&63),f(128|63&g)):(f(224|g>>>12),f(128|g>>>6&63),f(128|63&g))}return xf(c,0,d)})(Vn(e)),{mtime:0});return{contentType:If,body:i.buffer.slice(i.byteOffset,i.byteOffset+i.byteLength),estimatedSize:i.byteLength}}if(n===De.Base64){var r=(function(a){return a&&btoa(encodeURIComponent(a).replace(/%([0-9A-F]{2})/g,((l,u)=>String.fromCharCode(parseInt(u,16)))))})(Vn(e)),s=(a=>"data="+encodeURIComponent(typeof a=="string"?a:Vn(a)))(r);return{contentType:"application/x-www-form-urlencoded",body:s,estimatedSize:new Blob([s]).size}}var o=Vn(e);return{contentType:"application/json",body:o,estimatedSize:new Blob([o]).size}}},Cf=t=>{var e,n,i=()=>t.transport==="sendBeacon"?{url:Ss(t.url,{compression:De.Base64}),encodedBody:Ao(k({},t,{compression:De.Base64,Ji:void 0}))}:{url:kf(t.url,"compression"),encodedBody:Ao(k({},t,{compression:void 0,Ji:void 0}))};try{e=Ao(t)}catch(r){if(fc(t.compression,ei(t.url,"compression")))return A.error("Failed to gzip request body, sending uncompressed payload",r),i();throw r}return e&&fc(t.compression,ei(t.url,"compression"))&&!((n=e.body)instanceof ArrayBuffer?qo(new Uint8Array(n)):ArrayBuffer.isView(n)&&qo(new Uint8Array(n.buffer,n.byteOffset,n.byteLength)))?(Pr=!0,i()):{url:t.url,encodedBody:e}},Af=t=>{try{return Cf(t)}catch(e){return A.error(e),void(t.callback==null||t.callback({statusCode:0,error:e}))}},tm=(function(){var t=re((function*(e){var n=Vn(e.data),i=yield(function(s,o,a){return zo.apply(this,arguments)})(n,ne.DEBUG,{rethrow:!0});if(!i)return e;var r=yield i.arrayBuffer();return k({},e,{Ji:{contentType:If,body:r,estimatedSize:r.byteLength}})}));return function(e){return t.apply(this,arguments)}})(),nm=/Failed to fetch|NetworkError|Load failed/i,Pf=t=>t?.name==="TypeError"&&nm.test(t?.message||""),Ff=t=>{var e=Af(t);if(e){var n=e.url,i=e.encodedBody,r=i??{},s=r.contentType,o=r.body,a=r.estimatedSize,l=new Headers;ie(t.headers,(function(p,g){l.append(g,p)})),s&&l.append("Content-Type",s);var u=null,c=!1;if(oc){var d=new oc;u={signal:d.signal,timeout:setTimeout((()=>{var p,g;c=!0,d.abort((p=t.timeout,(g=new Error("PostHog request timed out"+(p?" after "+p+"ms":""))).name="AbortError",g))}),t.timeout)}}var f=p=>{c&&p?.name==="AbortError"||Pf(p)?A.warn(p):A.error(p),t.callback==null||t.callback({statusCode:0,error:p})};try{var h;Ya(n,k({method:t?.method||"GET",headers:l,keepalive:t.method==="POST"&&!t.Yi&&52428.8>(a||0),body:o,signal:(h=u)==null?void 0:h.signal},t.fetchOptions)).then((p=>p.text().then((g=>{var m={statusCode:p.status,text:g};if(p.status===200)try{m.json=JSON.parse(g)}catch(v){A.error(v)}t.callback==null||t.callback(m)})))).catch(f).finally((()=>u?clearTimeout(u.timeout):null))}catch(p){u&&clearTimeout(u.timeout),f(p)}}},ba=t=>{try{var e,n=Cf(t),i=n.url,r=n.encodedBody,s=r??{},o=s.body,a=s.estimatedSize;if(!o)return;var l=o instanceof Blob?o:new Blob([o],{type:s.contentType});if(je.sendBeacon(i,l))return;var u=U(t.data)?t.data:(e=t.data)==null?void 0:e.batch;if(U(u)&&u.length>1&&(a??0)>16384){var c=Math.ceil(u.length/2),d=f=>U(t.data)?f:k({},t.data,{batch:f});return ba(k({},t,{data:d(u.slice(0,c))})),void ba(k({},t,{data:d(u.slice(c))}))}A.warn("Beacon of ~"+(a??0)+" bytes was rejected by the browser, falling back to fetch"),Ff(k({},t,{Yi:!0}))}catch(f){A.warn("Beacon send failed",f)}},Gc=(t,e,n,i)=>{var r=i==="query"?e==="POST"?"sent_at":"_":void 0;return Ss(n===De.GZipJS?kf(t,"compression"):t,k({},r?{[r]:Date.now().toString()}:{},n===De.GZipJS?{}:{compression:n}))},Fr=[];Ya&&Fr.push({transport:"fetch",method:Ff}),Wo&&Fr.push({transport:"XHR",method(t){var e=Af(t);if(e){var n=new Wo,i=e.encodedBody;n.open(t.method||"GET",e.url,!0);var r=i??{},s=r.contentType,o=r.body;ie(t.headers,(function(a,l){n.setRequestHeader(l,a)})),s&&n.setRequestHeader("Content-Type",s),t.timeout&&(n.timeout=t.timeout),n.onreadystatechange=()=>{if(n.readyState===4){var a={statusCode:n.status,text:n.responseText};if(n.status===200)try{a.json=JSON.parse(n.responseText)}catch{}t.callback==null||t.callback(a)}},n.send(o)}}}),je!=null&&je.sendBeacon&&Fr.push({transport:"sendBeacon",method:ba});var Ea=3e3;class im{constructor(e,n){this.Xi=!0,this.tr=[],this.er=kt(n?.flush_interval_ms||Ea,250,5e3,A.createLogger("flush interval"),Ea),this.ir=e}enqueue(e){this.tr.push(e),this.rr||this.nr()}unload(){this.sr();var e=this.tr.length>0?this.ar():{},n=Object.values(e);[...n.filter((i=>i.url.indexOf("/e")===0)),...n.filter((i=>i.url.indexOf("/e")!==0))].map((i=>{this.lr(k({},i,{transport:"sendBeacon"}))}))}enable(){this.Xi=!1,this.nr()}nr(){var e=this;this.Xi||(this.rr=setTimeout((()=>{if(this.sr(),this.tr.length>0){var n=this.ar(),i=function(){var s=n[r],o=new Date().getTime();s.data&&U(s.data)&&ie(s.data,(a=>{a.offset=Math.abs(a.timestamp-o),delete a.timestamp})),e.lr(s)};for(var r in n)i()}}),this.er))}lr(e){try{this.ir(e)}catch(n){A.error(n)}}sr(){clearTimeout(this.rr),this.rr=void 0}ar(){var e={};return ie(this.tr,(n=>{var i,r=n,s=(r?r.batchKey:null)||r.url;C(e[s])&&(e[s]=k({},r,{data:[]})),(i=e[s].data)==null||i.push(r.data)})),this.tr=[],e}}var rm=["retriesPerformedSoFar"];class sm{constructor(e){this.ur=!1,this.hr=3e3,this.tr=[],this._instance=e,this.tr=[],this.dr=!0,!C(w)&&"onLine"in w.navigator&&(this.dr=w.navigator.onLine,this.vr=()=>{this.dr=!0,this.cr()},this.pr=()=>{this.dr=!1},me(w,"online",this.vr),me(w,"offline",this.pr))}get length(){return this.tr.length}retriableRequest(e){var n=e.retriesPerformedSoFar,i=id(e,rm);Bt(n)&&(i.url=Ss(i.url,{retry_count:n})),this._instance._send_request(k({},i,{callback:r=>{if(r.statusCode!==200&&(400>r.statusCode||r.statusCode>=500)){if((r.statusCode===0?3:10)>(n??0))return void this.At(k({retriesPerformedSoFar:n},i));r.statusCode===0&&A.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.")}i.callback==null||i.callback(r)}}))}At(e){var n=e.retriesPerformedSoFar||0;e.retriesPerformedSoFar=n+1;var i=(function(o){var a=3e3*Math.pow(2,o),l=a/2,u=Math.min(18e5,a),c=Math.random()-.5;return Math.ceil(u+c*(u-l))})(n),r=Date.now()+i;this.tr.push({retryAt:r,requestOptions:e});var s="Enqueued failed request for retry in "+i;navigator.onLine||(s+=" (Browser is offline)"),A.warn(s),this.ur||(this.ur=!0,this.gr())}gr(){if(this.mr&&clearTimeout(this.mr),this.tr.length===0)return this.ur=!1,void(this.mr=void 0);this.mr=setTimeout((()=>{this.dr&&this.tr.length>0&&this.cr(),this.gr()}),this.hr)}cr(){var e=Date.now(),n=[],i=this.tr.filter((s=>e>s.retryAt||(n.push(s),!1)));if(this.tr=n,i.length>0)for(var r of i)this.retriableRequest(r.requestOptions)}unload(){for(var e of(this.mr&&(clearTimeout(this.mr),this.mr=void 0),this.ur=!1,C(w)||(this.vr&&(w.removeEventListener("online",this.vr),this.vr=void 0),this.pr&&(w.removeEventListener("offline",this.pr),this.pr=void 0)),this.tr)){var n=e.requestOptions;try{this._instance._send_request(k({},n,{transport:"sendBeacon"}))}catch(i){A.error(i)}}this.tr=[]}}class om{constructor(e){this.yr=()=>{var n,i,r,s;this.br||(this.br={});var o=this.scrollElement(),a=this.scrollY(),l=o?Math.max(0,o.scrollHeight-o.clientHeight):0,u=a+(o?.clientHeight||0),c=o?.scrollHeight||0;this.br.lastScrollY=Math.ceil(a),this.br.maxScrollY=Math.max(a,(n=this.br.maxScrollY)!==null&&n!==void 0?n:0),this.br.maxScrollHeight=Math.max(l,(i=this.br.maxScrollHeight)!==null&&i!==void 0?i:0),this.br.lastContentY=u,this.br.maxContentY=Math.max(u,(r=this.br.maxContentY)!==null&&r!==void 0?r:0),this.br.maxContentHeight=Math.max(c,(s=this.br.maxContentHeight)!==null&&s!==void 0?s:0)},this._instance=e}get _r(){return this._instance.config.scroll_root_selector}getContext(){return this.br}resetContext(){var e=this.br;return setTimeout(this.yr,0),e}startMeasuringScrollPosition(){me(w,"scroll",this.yr,{capture:!0}),me(w,"scrollend",this.yr,{capture:!0}),me(w,"resize",this.yr)}scrollElement(){if(!this._r)return w?.document.documentElement;var e=U(this._r)?this._r:[this._r];for(var n of e){var i=w?.document.querySelector(n);if(i)return i}}wr(e){var n=e==="y"?"scrollTop":"scrollLeft";if(this._r){var i=this.scrollElement();return i&&i[n]||0}return w?e==="y"?w.scrollY||w.pageYOffset||w.document.documentElement.scrollTop||0:w.scrollX||w.pageXOffset||w.document.documentElement.scrollLeft||0:0}scrollY(){return this.wr("y")}scrollX(){return this.wr("x")}}var am=t=>mf(t?.config.mask_personal_data_properties,t?.config.custom_personal_data_properties,t?.config.disable_capture_url_hashes);class Kc{constructor(e,n,i,r){this.kr=s=>{var o=this.Sr();if(!o||o.sessionId!==s){var a={sessionId:s,props:this.Cr(this._instance)};this.Mr.register({[ca]:a})}},this._instance=e,this.Tr=n,this.Mr=i,this.Cr=r||am,this.Tr.onSessionId(this.kr)}Sr(){return this.Mr.props[ca]}getSetOnceProps(){var e,n=(e=this.Sr())==null?void 0:e.props;return n?"r"in n?vf(n,this._instance.config.disable_capture_url_hashes):{$referring_domain:n.referringDomain,$pathname:n.initialPathName,utm_source:n.utm_source,utm_campaign:n.utm_campaign,utm_medium:n.utm_medium,utm_content:n.utm_content,utm_term:n.utm_term}:{}}getSessionProps(){var e={};return ie(ol(this.getSetOnceProps()),((n,i)=>{i==="$current_url"&&(i="url"),e["$session_entry_"+Vo(i)]=n})),e}}class fl{on(e,n){return this.Er[e]||(this.Er[e]=[]),this.Er[e].push(n),()=>{this.Er[e]=this.Er[e].filter((i=>i!==n))}}emit(e,n){for(var i of this.Er[e]||[])i(n);for(var r of this.Er["*"]||[])r(e,n)}constructor(){this.Er={}}}var wi=he("[SessionId]");class Yc{on(e,n){return this.Ir.on(e,n)}constructor(e,n,i){var r;if(this.Pr=null,this.Rr=[],this.Ar=void 0,this.Fr=!1,this.Ir=new fl,this.Lr=(u,c)=>!(!Bt(u)||!Bt(c))&&Math.abs(u-c)>this.sessionTimeoutMs,!e.persistence)throw new Error("SessionIdManager requires a PostHogPersistence instance");if(e.config.cookieless_mode===Ht)throw new Error('SessionIdManager cannot be used with cookieless_mode="always"');this.Ne=e.config,this.Mr=e.persistence,this.Or=void 0,this.Dr=void 0,this._sessionStartTimestamp=null,this._sessionActivityTimestamp=null,this.$r=n||Ut,this.Nr=i||Ut;var s=this.Ne.persistence_name||this.Ne.token;if(this._sessionTimeoutMs=1e3*kt(this.Ne.session_idle_timeout_seconds||1800,60,36e3,wi.createLogger("session_idle_timeout_seconds"),1800),e.register({$configured_session_timeout_ms:this._sessionTimeoutMs}),this.qr(),this.jr="ph_"+s+"_window_id",this.Br="ph_"+s+"_primary_window_exists",this.Hr()){var o=ye.H(this.jr),a=ye.H(this.Br);o&&!a?this.Or=o:ye.q(this.jr),ye.F(this.Br,!0)}if((r=this.Ne.bootstrap)!=null&&r.sessionID)try{var l=(u=>{var c=this.Ne.bootstrap.sessionID.replace(/-/g,"");if(c.length!==32)throw new Error("Not a valid UUID");if(c[12]!=="7")throw new Error("Not a UUIDv7");return parseInt(c.substring(0,12),16)})();this.Ur(this.Ne.bootstrap.sessionID,new Date().getTime(),l)}catch(u){wi.error("Invalid sessionID in bootstrap",u)}this.zr()}get sessionTimeoutMs(){return this._sessionTimeoutMs}onSessionId(e){return C(this.Rr)&&(this.Rr=[]),this.Rr.push(e),this.Dr&&e(this.Dr,this.Or),()=>{this.Rr=this.Rr.filter((n=>n!==e))}}Hr(){return this.Ne.persistence!=="memory"&&!this.Mr.xi&&ye.N()}Wr(e){e!==this.Or&&(this.Or=e,this.Hr()&&ye.F(this.jr,e))}Vr(){return this.Or?this.Or:this.Hr()?ye.H(this.jr):null}Zr(e){var n=this.Pr;return!ze(n)&&!ze(e)&&5e3>Math.abs(e-n)}Ur(e,n,i){var r=n!==this._sessionActivityTimestamp,s=!(e!==this.Dr||i!==this._sessionStartTimestamp);this._sessionStartTimestamp=i,this._sessionActivityTimestamp=n,this.Dr=e,s&&!r||s&&this.Zr(n)||(this.Pr=n,this.Mr.register({[zn]:[n,e,i]}))}Gr(){var e,n=(e=this.Ne)==null?void 0:e.persistence_save_debounce_ms;return Bt(n)&&n>0}Qr(){this.Gr()?this.Mr.refreshKey(zn):(this.Mr.flush(),this.Mr.load())}Kr(){var e;if(!ze(this._sessionActivityTimestamp)&&this._sessionActivityTimestamp!==this.Pr){this.Qr();var n=this.Jr();n[1]===this.Dr&&n[2]===this._sessionStartTimestamp&&(this.Pr=this._sessionActivityTimestamp,this.Mr.register({[zn]:[this._sessionActivityTimestamp,(e=this.Dr)!==null&&e!==void 0?e:null,this._sessionStartTimestamp]}),this.Mr.flush())}}Yr(){var e=this.Jr()[0],n=Bt(e)?e:0,i=Bt(this._sessionActivityTimestamp)?this._sessionActivityTimestamp:0;return Math.max(n,i)}Xr(e){return this.Qr(),this.Lr(e,this.Yr())}Jr(){var e=this.Mr.props[zn];return U(e)&&e.length===2&&e.push(e[0]),e||[0,null,0]}resetSessionId(){this.Pr=null,clearTimeout(this.tn),this.tn=void 0,this.Ur(null,null,null)}destroy(){this.Fr=!0,this.Kr(),clearTimeout(this.tn),this.tn=void 0,this.Ar&&w&&(w.removeEventListener(Zr,this.Ar,{capture:!1}),this.Ar=void 0),this.Rr=[]}zr(){this.Ar=()=>{this.Kr(),this.Hr()&&ye.q(this.Br)},me(w,Zr,this.Ar,{capture:!1})}checkAndGetSessionAndWindowId(e,n){if(e===void 0&&(e=!1),n===void 0&&(n=null),this.Ne.cookieless_mode===Ht)throw new Error('checkAndGetSessionAndWindowId should not be called with cookieless_mode="always"');var i=n||new Date().getTime(),r=this.Jr(),s=r[1],o=r[2],a=this.Yr(),l=this.Vr(),u=Bt(o)&&Math.abs(i-o)>864e5,c=!1,d=!1,f=!s,h=s,p=!f&&!e&&this.Lr(i,a);if(p){(p=this.Xr(i))||wi.info("cross-tab refresh kept the session alive",{sessionId:s});var g=this.Jr();s=g[1],o=g[2]}f||p||u?(s=this.$r(),l=this.Nr(),wi.info("new session ID generated",{sessionId:s,windowId:l,changeReason:{noSessionId:f,activityTimeout:p,sessionPastMaximumLength:u}}),o=i,c=!0):(l||(l=this.Nr(),c=!0),(d=s!==h)&&(wi.info("adopted cross-tab session id",{sessionId:s,windowId:l}),c=!0));var m=Bt(a)&&e&&!u?a:i,v=Bt(o)?o:new Date().getTime();this.Wr(l),this.Ur(s,m,v),e||this.qr();var E={noSessionId:f,activityTimeout:p,sessionPastMaximumLength:u,crossTabAdoption:d};return c&&this.Rr.forEach((S=>S(s,l,E))),{sessionId:s,windowId:l,sessionStartTimestamp:v,changeReason:c?E:void 0,lastActivityTimestamp:a}}qr(){this.Fr||(clearTimeout(this.tn),this.tn=setTimeout((()=>{if(!this.Fr)if(this.Xr(new Date().getTime())){var e=this.Dr;this.resetSessionId(),this.Ir.emit("forcedIdleReset",{idleSessionId:e})}else this.qr()}),1.1*this.sessionTimeoutMs))}}var Rf=function(t,e){if(!t)return!1;var n=t.userAgent;if(n&&pc(n,e))return!0;try{var i=t?.userAgentData;if(i!=null&&i.brands&&i.brands.some((r=>pc(r?.brand,e))))return!0}catch{}return!!t.webdriver};function Tf(){return(Tf=re((function*(){var t=je?.userAgentData;if(t!=null&&t.getHighEntropyValues)try{var e=yield t.getHighEntropyValues(["model"]),n=e?.model;return Z(n)&&n.length>0?n:void 0}catch(i){return void A.info("Unable to resolve $device_model from userAgentData.getHighEntropyValues",i)}}))).apply(this,arguments)}var rs=function(t,e){if(!(function(n){try{new RegExp(n)}catch{return!1}return!0})(e))return!1;try{return new RegExp(e).test(t)}catch{return!1}};function Po(t,e,n){return Vn({distinct_id:t,userPropertiesToSet:e,userPropertiesToSetOnce:n})}var $f={exact:(t,e)=>e.some((n=>t.some((i=>n===i)))),is_not:(t,e)=>e.every((n=>t.every((i=>n!==i)))),regex:(t,e)=>e.some((n=>t.some((i=>rs(n,i))))),not_regex:(t,e)=>e.every((n=>t.every((i=>!rs(n,i))))),icontains:(t,e)=>e.map(vr).some((n=>t.map(vr).some((i=>n.includes(i))))),not_icontains:(t,e)=>e.map(vr).every((n=>t.map(vr).every((i=>!n.includes(i))))),gt:(t,e)=>e.some((n=>{var i=parseFloat(n);return!isNaN(i)&&t.some((r=>i>parseFloat(r)))})),lt:(t,e)=>e.some((n=>{var i=parseFloat(n);return!isNaN(i)&&t.some((r=>it.toLowerCase();function Mf(t,e){return!t||Object.entries(t).every((n=>{var i=n[1],r=e?.[n[0]];if(C(r)||ze(r))return!1;var s=[String(r)],o=$f[i.operator];return!!o&&o(i.values,s)}))}var Sa="custom",Jc="i.posthog.com",lm=/^\/static\//;class cm{constructor(e){this.en={},this.instance=e}get apiHost(){var e=this.instance.config.api_host.trim().replace(/\/$/,"");return e==="https://app.posthog.com"?"https://us.i.posthog.com":e}get flagsApiHost(){var e=this.instance.config.flags_api_host;return e?e.trim().replace(/\/$/,""):this.apiHost}get uiHost(){var e,n=(e=this.instance.config.ui_host)==null?void 0:e.replace(/\/$/,"");return n||(n=this.apiHost.replace("."+Jc,".posthog.com")),n==="https://app.posthog.com"?"https://us.posthog.com":n}get region(){return this.en[this.apiHost]||(this.en[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":Sa),this.en[this.apiHost]}rn(e){if(lm.test(e)){var n=this.instance.config.asset_host;if(typeof n=="string")return n.trim().replace(/\/$/,"")||void 0}}endpointFor(e,n){if(n===void 0&&(n=""),n&&(n=n[0]==="/"?n:"/"+n),e==="ui")return this.uiHost+n;if(e==="flags")return this.flagsApiHost+n;if(e==="assets"){var i=this.rn(n);if(i)return""+i+n}if(this.region===Sa)return this.apiHost+n;var r=Jc+n;switch(e){case"assets":return"https://"+this.region+"-assets."+r;case"api":return"https://"+this.region+"."+r}}}function Lf(t){var e;return!((e=t.conditions)==null||(e=e.events)==null||(e=e.values)==null||!e.length)}var X=he("[Surveys]"),Nf="seenSurvey_",Of=t=>{try{var e=(n=>((i,r)=>""+Nf+(function(s){return s.current_iteration&&s.current_iteration>0?s.id+"_"+s.current_iteration:s.id})(r))(0,n))(t);if(localStorage.getItem(e))return;localStorage.setItem(e,"true")}catch(n){X.error("Failed to persist survey seen state",n)}},um=[xo.Popover,xo.Widget,xo.API],dm={ignoreConditions:!1,ignoreDelay:!1,displayType:va.Popover},fm=he("[PostHog ExternalIntegrations]"),hm={intercom:"intercom-integration",crispChat:"crisp-chat-integration"};class pm{constructor(e){this._instance=e}ai(e,n){var i;(i=O.__PosthogExtensions__)==null||i.loadExternalDependency==null||i.loadExternalDependency(this._instance,e,(r=>{if(r)return fm.error("failed to load script",r);n()}))}startIfEnabledOrStop(){var e=this,n=function(){var s,o,a,l=i[0],u=i[1];!u||(s=O.__PosthogExtensions__)!=null&&(s=s.integrations)!=null&&s[l]||e.ai(hm[l],(()=>{var c;(c=O.__PosthogExtensions__)==null||(c=c.integrations)==null||(c=c[l])==null||c.start(e._instance)})),!u&&(o=O.__PosthogExtensions__)!=null&&(o=o.integrations)!=null&&o[l]&&((a=O.__PosthogExtensions__)==null||(a=a.integrations)==null||(a=a[l])==null||a.stop())};for(var i of Object.entries((r=this._instance.config.integrations)!==null&&r!==void 0?r:{})){var r;n()}}}class gm{constructor(e,n){this.rt=e,this.nn=n,this.sn=new Map,this.an=!1}add(e){var n=this;return re((function*(){if(n.an)throw new Error("Cannot add an extension to a disposed ExtensionRuntime");if(n.sn.has(e.name))throw new Error('Browser extension "'+e.name+'" is already registered');n.sn.set(e.name,e);try{var i=e.setup(n.nn);i&&(yield i)}catch(s){var r=n.sn.get(e.name)===e;r&&n.sn.delete(e.name),n.rt.error('Failed to set up browser extension "'+e.name+'"',s),r&&n.ln(e)}}))()}dispose(){if(!this.an){this.an=!0;var e=Array.from(this.sn.values()).reverse();for(var n of(this.sn.clear(),e))this.ln(n)}}ln(e){try{var n=e.dispose==null?void 0:e.dispose();n&&Be(n.then)&&n.then(void 0,(i=>{this.rt.error('Failed to dispose browser extension "'+e.name+'"',i)}))}catch(i){this.rt.error('Failed to dispose browser extension "'+e.name+'"',i)}}}class mm{constructor(e){this._instance=e}initialize(){}get(e){var n=this._instance.persistence;if(typeof e=="string")return n?.get_property(e);var i={};for(var r of e){var s=n?.get_property(r);C(s)||(i[r]=s)}return i}set(e,n){var i;(i=this._instance.persistence)==null||i.register(typeof e=="string"?{[e]:n}:e)}remove(e){var n;(n=this._instance.persistence)==null||n.unregister(e)}}var Zc="extensionsRemoteConfig";class vm{constructor(e){this.an=!1,this.instance=e,this.rt=A,this.un=e.hn,this.kv=new mm(e),this.onEvent=n=>mr(this.instance.on("eventCaptured",(i=>{try{n({event:i.event,properties:i.properties})}catch(r){this.rt.error("Browser extension event listener failed",r)}}))),this.onRemoteConfig=n=>{if(this.an)return mr((()=>{}));var i=s=>{try{n(s)}catch(o){this.rt.error("Browser extension remote config listener failed",o)}},r=this.instance.dn.on(Zc,i);return this.un&&i(this.un),mr(r)},this.vn=new gm(A.createLogger("[BrowserExtensions]"),this)}get logger(){return this.rt}get distinctId(){return this.instance.get_distinct_id()}get anonymousId(){var e;return(e=this.instance.get_property(Vi))!==null&&e!==void 0?e:this.distinctId}get deviceId(){var e=this.instance.get_property(Vi);return typeof e=="string"?e:void 0}get library(){return{name:ne.LIB_NAME,version:ne.LIB_VERSION}}get initialPersonProperties(){var e,n;return(e=(n=this.instance.persistence)==null?void 0:n.get_initial_props())!==null&&e!==void 0?e:{}}get groups(){return this.instance.getGroups()}get session(){try{var e,n,i,r,s=(e=this.instance.sessionManager)==null?void 0:e.checkAndGetSessionAndWindowId(!0);return{sessionId:(n=s?.sessionId)!==null&&n!==void 0?n:"",windowId:(i=s?.windowId)!==null&&i!==void 0?i:"",sessionStartTimestamp:(r=s?.sessionStartTimestamp)!==null&&r!==void 0?r:0}}catch{return{sessionId:"",windowId:"",sessionStartTimestamp:0}}}get projectToken(){return this.instance.config.token}add(e){return this.vn.add(e)}capture(e,n,i){var r=this;return re((function*(){i?r.instance.capture(e,n,{timestamp:i.timestamp,uuid:i.uuid,$set:i.set,$set_once:i.setOnce}):r.instance.capture(e,n)}))()}registerDynamicEventProperties(e){return mr(this.instance.cn(e))}handleRemoteConfig(e){this.an||(this.un=e,this.instance.dn.emit(Zc,e))}sendRequest(e,n){var i=this;return re((function*(){var r;n===void 0&&(n={});var s=i.instance.requestRouter.endpointFor((r=n.target)!==null&&r!==void 0?r:"api",e),o={method:n.method,url:n.query?Ss(s,n.query):s,data:n.body,headers:n.headers,timeout:n.timeoutMs,fireCallbackOnDrop:!0,transport:n.transport,compression:n.compression,timestampMode:n.sentAt};return n.transport==="sendBeacon"?(i.instance._send_request(o),{statusCode:202}):new Promise((a=>{o.callback=a,i.instance._send_request(o)}))}))()}dispose(){this.an||(this.an=!0,this.vn.dispose())}}var ji={},Fo=0,ss=()=>{},Xc='Consent opt in/out is not valid with cookieless_mode="always" and will be ignored',bi="Surveys module not available",Qc="sanitize_properties is deprecated. Use before_send instead",Bf="Invalid value for property_denylist config: ",_m=["token","distinct_id",qd],qn="posthog",Df=!em&&We?.indexOf("MSIE")===-1&&We?.indexOf("Mozilla")===-1,Ro=t=>{var e;return k({api_host:"https://us.i.posthog.com",flags_api_host:null,ui_host:null,asset_host:null,token:"",autocapture:!0,cross_subdomain_cookie:yg(F?.location),persistence:"localStorage+cookie",persistence_name:"",cookie_persisted_properties:[],loaded:ss,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_external_dependency_versioned_paths:!1,__preview_cookie_wins_on_conflict:!1,debug:ge&&Z(ge?.search)&&ge.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,disable_external_dependency_loading:!1,strict_script_versioning:!1,enable_recording_console_log:void 0,secure_cookie:(w==null||(e=w.location)==null?void 0:e.protocol)==="https:",ip:!1,opt_out_capturing_by_default:!1,opt_out_persistence_by_default:!1,opt_out_useragent_filter:!1,opt_out_capturing_persistence_type:"localStorage",consent_persistence_name:null,opt_out_capturing_cookie_prefix:null,opt_in_site_apps:!1,property_denylist:[],respect_dnt:!1,sanitize_properties:null,request_headers:{},request_batching:!0,properties_string_max_length:65535,mask_all_element_attributes:!1,mask_all_text:!1,mask_personal_data_properties:!1,custom_personal_data_properties:[],advanced_disable_flags:!1,advanced_disable_decide:!1,advanced_disable_feature_flags:!1,advanced_disable_feature_flags_on_first_load:!1,advanced_only_evaluate_survey_feature_flags:!1,advanced_feature_flags_dedup_per_session:!1,advanced_enable_surveys:!1,advanced_disable_toolbar_metrics:!1,feature_flag_request_timeout_ms:3e3,surveys_request_timeout_ms:1e4,on_request_error(n){A.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:ha,before_send:void 0,get_current_url:void 0,request_queue_config:{flush_interval_ms:Ea},error_tracking:{},_onCapture:ss},(n=>({rageclick:n&&n>="2026-05-30"?{content_ignorelist:Rg,ignore_text_selection:!0}:!n||"2025-11-30">n||{content_ignorelist:!0},capture_pageview:!n||"2025-05-24">n||"history_change",session_recording:n&&n>="2026-06-25"?{strictMinimumDuration:!0,canvasCapture:{resolutionScale:.6},streamNetworkBody:!0}:n&&n>="2026-05-30"?{strictMinimumDuration:!0,canvasCapture:{resolutionScale:.6}}:n&&n>="2025-11-30"?{strictMinimumDuration:!0}:{},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)}))(t))},ym=[["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"]],eu=t=>{var e={};for(var n of ym){var i=n[0],r=n[1];C(t[i])||(e[r]=t[i])}var s=ue({},e,t),o=t.__preview_external_dependency_versioned_paths;return C(o)||(C(t.strict_script_versioning)&&(s.strict_script_versioning=!!o),Z(o)&&C(t.asset_host)&&(s.asset_host=o)),U(t.property_blacklist)&&(C(t.property_denylist)?s.property_denylist=t.property_blacklist:U(t.property_denylist)?s.property_denylist=[...t.property_blacklist,...t.property_denylist]:A.error(Bf+t.property_denylist)),s};class wm{constructor(){this.__forceAllowLocalhost=!1}get fn(){return this.__forceAllowLocalhost}set fn(e){A.error("WebPerformanceObserver is deprecated and has no impact on network capture. Use `_forceAllowLocalhostNetworkCapture` on `posthog.sessionRecording`"),this.__forceAllowLocalhost=e}}class Ye{pn(e,n){if(e){var i=this.sn.indexOf(e);i!==-1&&this.sn.splice(i,1)}return this.sn.push(n),n.initialize==null||n.initialize(),n}gn(){return this.config.cookieless_mode===Ht||this.config.cookieless_mode===Sn&&this.consent.isRejected()}get decideEndpointWasHit(){var e,n;return(e=(n=this.featureFlags)==null?void 0:n.hasLoadedFlags)!==null&&e!==void 0&&e}get flagsEndpointWasHit(){var e,n;return(e=(n=this.featureFlags)==null?void 0:n.hasLoadedFlags)!==null&&e!==void 0&&e}constructor(){var e;this.webPerformance=new wm,this.mn=!1,this.version=ne.LIB_VERSION,this.yn=new Set,this.bn="",this.dn=new fl,this.sn=[],this._n=[],this._calculate_event_properties=this.calculateEventProperties.bind(this),this.config=Ro(),this.SentryIntegration=Dg,this.sentryIntegration=i=>(function(r,s){var o=cf(r,s);return{name:lf,processEvent:a=>o(a)}})(this,i),this.__request_queue=[],this.__loaded=!1,this.analyticsDefaultEndpoint="/e/",this.wn=!1,this.kn=null,this.xn=null,this.Sn=null,this.scrollManager=new om(this),this.pageViewManager=new Dc(this),this.rateLimiter=new Kg(this),this.requestRouter=new cm(this),this.consent=new kg(this),this.externalIntegrations=new pm(this);var n=(e=Ye.__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:(i,r,s)=>{var o=Z(i)?{[i]:r}:i;this.setPersonProperties(o),s?.({})},set_once:(i,r,s)=>{var o=Z(i)?{[i]:r}:i;this.setPersonProperties(void 0,o),s?.({})}},this.on("eventCaptured",(i=>A.info('send "'+i?.event+'"',i)))}init(e,n,i){if(i&&i!==qn){var r,s=(r=ji[i])!==null&&r!==void 0?r:new Ye;return s._init(e,n,i),ji[i]=s,ji[qn][i]=s,s}return this._init(e,n,i)}_init(e,n,i){var r,s;n===void 0&&(n={});var o,a=Z(e)?e.trim():"";if(!a)return A.critical("PostHog was initialized without a token. This likely indicates a misconfiguration. Please check the first argument passed to posthog.init()"),this;if(this.__loaded)return a!==((o=this.config)==null?void 0:o.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('"+a+"', { ... }, 'project2')"):console.warn("[PostHog.js]","You have already initialized PostHog! Re-initializing is a no-op"),this;this.__loaded=!0,this.config=Ro(n.defaults),n.debug=this.Cn(n.debug),this.Mn=n,this.Tn=[],n.person_profiles?this.xn=n.person_profiles:n.process_person&&(this.xn=n.process_person);var l=Ro(n.defaults),u=eu(n),c=ue({},l,u,{name:i,token:a});de(l.rageclick)&&de(u.rageclick)&&(c.rageclick=ue({},l.rageclick,u.rageclick)),de(l.session_recording)&&de(u.session_recording)&&(c.session_recording=ue({},l.session_recording,u.session_recording)),this.set_config(c),this.config.on_xhr_error&&A.error("on_xhr_error is deprecated. Use on_request_error instead"),this.compression=n.disable_compression?void 0:De.GZipJS;var d=this.En();if(this.persistence=new So(this.config,d),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new So(k({},this.config,{persistence:"sessionStorage"}),d,!1),this.bn="ph_"+(this.config.persistence_name||this.config.token)+"_session_registered_properties",this.config.persistence!=="memory"&&!d&&ye.N()){var f=ye.H(this.bn);U(f)&&f.forEach((I=>{Z(I)&&this.yn.add(I)}))}else ye.q(this.bn);var h=k({},this.persistence.props),p=k({},this.sessionPersistence.props);this.register({$initialization_time:new Date().toISOString()}),this.In=new im((I=>this.Pn(I)),this.config.request_queue_config),this.Rn=new sm(this),this.__request_queue=[];var g=this.gn();if(g||(this.sessionManager=new Yc(this),this.sessionPropsManager=new Kc(this,this.sessionManager,this.persistence),this.sessionManager.onSessionId(((I,M,b)=>{(b!=null&&b.activityTimeout||b!=null&&b.sessionPastMaximumLength||b!=null&&b.crossTabAdoption)&&this.An()}))),this.Fn(),this.config.__preview_deferred_init_extensions?(A.info("Deferring extension initialization to improve startup performance"),setTimeout((()=>{this.Ln(g)}),0)):(A.info("Initializing extensions synchronously"),this.Ln(g)),ne.DEBUG=ne.DEBUG||this.config.debug,ne.DEBUG&&A.info("Starting in debug mode",{this:this,config:n,thisC:k({},this.config),p:h,s:p}),!this.config.identity_distinct_id||(r=n.bootstrap)!=null&&r.distinctID||(n.bootstrap=k({},n.bootstrap,{distinctID:this.config.identity_distinct_id,isIdentifiedID:!0})),((s=n.bootstrap)==null?void 0:s.distinctID)!==void 0){var m=n.bootstrap.distinctID,v=this.get_distinct_id(),E=this.persistence.get_property(st);if(n.bootstrap.isIdentifiedID&&v!=null&&v!==m&&E===Bn)this.identify(m);else if(n.bootstrap.isIdentifiedID&&v!=null&&v!==m&&E===pn)A.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{var S=this.config.get_device_id(Ut()),_=n.bootstrap.isIdentifiedID?S:m;this.persistence.set_property(st,n.bootstrap.isIdentifiedID?pn:Bn),this.register({distinct_id:m,$device_id:_})}}if(g)this.register_once({distinct_id:dr,$device_id:null},"");else if(!this.get_distinct_id()){var x=this.config.get_device_id(Ut());this.register_once({distinct_id:x,$device_id:x},""),this.persistence.set_property(st,Bn)}return me(w,"onpagehide"in self?"pagehide":"unload",this._handle_unload.bind(this),{passive:!1}),n.segment?(function(I,M){var b=I.config.segment;if(!b)return M();(function(P,R){var N=P.config.segment;if(!N)return R();var L=T=>{var V=()=>T.anonymousId()||Ut();P.config.get_device_id=V,T.id()&&(P.register({distinct_id:T.id(),$device_id:V()}),P.persistence.set_property(st,pn)),R()},B=N.user();"then"in B&&Be(B.then)?B.then(L):L(B)})(I,(()=>{b.register((P=>{typeof Promise<"u"&&Promise.resolve||bo.warn("This browser does not have Promise support, and can not use the segment integration");var R=(N,L)=>{if(!L)return N;N.event.userId||N.event.anonymousId===P.get_distinct_id()||(bo.info("No userId set, resetting PostHog"),P.reset()),N.event.userId&&N.event.userId!==P.get_distinct_id()&&(bo.info("UserId set, identifying with PostHog"),P.identify(N.event.userId));var B=P.calculateEventProperties(L,N.event.properties);return N.event.properties=Object.assign({},B,N.event.properties),N};return{name:"PostHog JS",type:"enrichment",version:"1.0.0",isLoaded:()=>!0,load:()=>Promise.resolve(),track:N=>R(N,N.event.event),page:N=>R(N,Wn),identify:N=>R(N,_o),screen:N=>R(N,"$screen")}})(I)).then((()=>{M()}))}))})(this,(()=>this.On())):this.On(),Be(this.config._onCapture)&&this.config._onCapture!==ss&&(A.warn("onCapture is deprecated. Please use `before_send` instead"),this.on("eventCaptured",(I=>this.config._onCapture(I.event,I)))),this.config.ip&&A.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 Tf.apply(this,arguments)})().then((I=>{I&&this.register({[mo]:I})})).catch(ss),this}Fn(){var e,n,i,r,s,o,a=(e=(n=this.config.__extensionClasses)==null?void 0:n.featureFlags)!==null&&e!==void 0?e:(i=Ye.__defaultExtensionClasses)==null?void 0:i.featureFlags;a&&(this.featureFlags&&this.featureFlags instanceof a||((r=this.Dn)==null||r.call(this),this.Dn=void 0,this.featureFlags=new a(this)),Be(this.featureFlags.onReloading)&&Be(this.featureFlags.setup)?this.Dn||(this.Dn=this.featureFlags.onReloading((()=>{this.dn.emit("featureFlagsReloading",!0)})),this.$n().add(this.featureFlags)):(s=(o=this.featureFlags).initialize)==null||s.call(o))}Ln(e){var n,i,r,s,o,a,l,u=performance.now(),c=k({},Ye.__defaultExtensionClasses,this.config.__extensionClasses),d=[];c.exceptions&&this.sn.push(this.exceptions=(n=this.exceptions)!==null&&n!==void 0?n:new c.exceptions(this)),c.historyAutocapture&&this.sn.push(this.historyAutocapture=new c.historyAutocapture(this)),c.tracingHeaders&&this.sn.push(this.tracingHeaders=new c.tracingHeaders(this)),c.siteApps&&this.sn.push(this.siteApps=new c.siteApps(this)),c.sessionRecording&&!e&&this.sn.push(this.sessionRecording=new c.sessionRecording(this)),this.config.disable_scroll_properties||d.push((()=>{this.scrollManager.startMeasuringScrollPosition()})),c.autocapture&&this.sn.push(this.autocapture=new c.autocapture(this)),c.surveys&&this.sn.push(this.surveys=(i=this.surveys)!==null&&i!==void 0?i:new c.surveys(this)),c.logs&&this.sn.push(this.logs=(r=this.logs)!==null&&r!==void 0?r:new c.logs(this)),c.metrics&&this.sn.push(this.metrics=(s=this.metrics)!==null&&s!==void 0?s:new c.metrics(this)),c.conversations&&this.sn.push(this.conversations=(o=this.conversations)!==null&&o!==void 0?o:new c.conversations(this)),c.productTours&&this.sn.push(this.productTours=new c.productTours(this)),c.heatmaps&&this.sn.push(this.heatmaps=new c.heatmaps(this)),c.webVitalsAutocapture&&this.sn.push(this.webVitalsAutocapture=new c.webVitalsAutocapture(this)),c.exceptionObserver&&this.sn.push(this.exceptionObserver=new c.exceptionObserver(this)),c.deadClicksAutocapture&&this.sn.push(this.deadClicksAutocapture=new c.deadClicksAutocapture(this,Bg)),c.toolbar&&this.sn.push(this.toolbar=(a=this.toolbar)!==null&&a!==void 0?a:new c.toolbar(this)),c.experiments&&this.sn.push(this.experiments=(l=this.experiments)!==null&&l!==void 0?l:new c.experiments(this)),this.sn.forEach((f=>{f.initialize&&d.push((()=>{f.initialize==null||f.initialize()}))})),d.push((()=>{if(this.Nn){var f=this.Nn;this.Nn=void 0,this.sn.forEach((h=>h.onRemoteConfig==null?void 0:h.onRemoteConfig(f)))}})),this.qn(d,u)}qn(e,n){for(;e.length>0;){if(this.config.__preview_deferred_init_extensions&&performance.now()-n>=30&&e.length>0)return void setTimeout((()=>{this.qn(e,n)}),0);var i=e.shift();if(i)try{i()}catch(s){A.error("Error initializing extension:",s)}}var r=Math.round(performance.now()-n);this.register_for_session({[zd]:this.config.__preview_deferred_init_extensions?"deferred":"synchronous",[Vd]:r}),this.config.__preview_deferred_init_extensions&&A.info("PostHog extensions initialized ("+r+"ms)")}Zi(e){var n;if(!F||!F.body)return A.info("document not ready yet, trying again in 500 milliseconds..."),void setTimeout((()=>{this.Zi(e)}),500);if(this.config.__preview_deferred_init_extensions&&(this.Nn=e),this.hn=e,this.compression=void 0,e.ok){var i,r=e.config;r.supportedCompression&&!this.config.disable_compression&&(this.compression=j(r.supportedCompression,De.GZipJS)?De.GZipJS:j(r.supportedCompression,De.Base64)?De.Base64:void 0),(i=r.analytics)!=null&&i.endpoint&&(this.analyticsDefaultEndpoint=r.analytics.endpoint)}this.set_config({person_profiles:this.xn?this.xn:ha}),(n=this.jn)==null||n.handleRemoteConfig(e),this.sn.forEach((s=>s.onRemoteConfig==null?void 0:s.onRemoteConfig(e)))}On(){try{this.config.loaded(this)}catch(i){A.critical("`loaded` function failed",i)}if(this.Bn(),this.config.internal_or_test_user_hostname&&ge!=null&&ge.hostname){var e=ge.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.gn())&&this.Hn()}),1),this.Un=new yf(this),this.Un.load()}Bn(){var e;this.is_capturing()&&this.config.request_batching&&((e=this.In)==null||e.enable())}_dom_loaded(){this.is_capturing()&&fr(this.__request_queue,(e=>this.Pn(e))),this.__request_queue=[],this.Bn()}_handle_unload(){var e,n,i,r,s;(e=this.surveys)==null||e.handlePageUnload==null||e.handlePageUnload(),(n=this.metrics)==null||n.flush("sendBeacon"),this.config.request_batching?(this.zn()&&this.capture(vo),(i=this.logs)==null||i.flushLogs("sendBeacon"),(r=this.In)==null||r.unload(),(s=this.Rn)==null||s.unload()):this.zn()&&this.capture(vo,null,{transport:"sendBeacon"})}_send_request(e){this.__loaded?Df?this.__request_queue.push(e):this.rateLimiter.isServerRateLimited(e.batchKey)?e.fireCallbackOnDrop&&(e.callback==null||e.callback({statusCode:429})):(e.transport=e.transport||this.config.api_transport,e.headers=k({},this.config.request_headers,e.headers),e.compression=e.compression==="best-available"?this.compression:e.compression,(C(this.config.disable_beacon)?this.config.__preview_disable_beacon:this.config.disable_beacon)&&(e.disableTransport=["sendBeacon"]),e.fetchOptions=e.fetchOptions||this.config.fetch_options,(n=>{var i,r,s,o=k({},n);o.timeout=o.timeout||6e4;var a,l,u,c,d,f=(i=o.transport)!==null&&i!==void 0?i:"fetch";f==="sendBeacon"&&C(o.compression)&&o.data&&(o.compression=De.Base64),o.method==="POST"&&o.data&&(o.timestampMode==="capture-body"?o.data={api_key:(l=(d=(c=U(a=o.data)?a:[a])[0])==null||(u=d.properties)==null?void 0:u.token)!==null&&l!==void 0?l:d?.token,batch:c,sent_at:new Date().toISOString()}:o.timestampMode==="body"&&(o.data=(function(m,v){return v===void 0&&(v=new Date().toISOString()),U(m)?m.map((E=>k({},E,{sent_at:v}))):k({},m,{sent_at:v})})(o.data))),o.url=Gc(o.url,o.method,o.compression,o.timestampMode);var h=Fr.filter((m=>!o.disableTransport||!m.transport||!o.disableTransport.includes(m.transport))),p=(r=(s=(function(m,v){for(var E=0;m.length>E;E++)if(m[E].transport===f)return m[E]})(h))==null?void 0:s.method)!==null&&r!==void 0?r:h[0].method;if(!p)throw new Error("No available transport method");var g=m=>{try{p(m)}catch(v){Pf(v)?A.warn(v):A.error(v),o.callback==null||o.callback({statusCode:0,error:v})}};f!=="sendBeacon"&&o.data&&o.compression===De.GZipJS&&bp&&typeof Promise<"u"&&!Pr?tm(o).then((m=>{g(m)})).catch((m=>{if(hc(m))return Pr=!0,void g(k({},o,{compression:void 0,url:Gc(n.url,n.method,void 0,n.timestampMode)}));(v=>{if(!v||typeof v!="object")return!1;var E="name"in v?String(v.name):"";return hc(v)||E===rd})(m)&&(Pr=!0),g(o)})):p(o)})(k({},e,{callback:n=>{var i,r;this.rateLimiter.checkForLimiting(n),400>n.statusCode||(i=(r=this.config).on_request_error)==null||i.call(r,n),e.callback==null||e.callback(n)}}))):e.fireCallbackOnDrop&&(e.callback==null||e.callback({statusCode:0}))}Pn(e){this.Rn?this.Rn.retriableRequest(e):this._send_request(e)}_execute_array(e){Fo++;try{var n,i=[],r=[],s=[];fr(e,(a=>{if(a)if(U(n=a[0]))s.push(a);else if(Be(a))try{a.call(this)}catch(l){A.error("Error executing queued PostHog call",a,l)}else U(a)&&n==="alias"?i.push(a):U(a)&&n.indexOf("capture")!==-1&&Be(this[n])?s.push(a):r.push(a)}));var o=function(a,l){fr(a,(function(u){try{if(U(u[0])){var c=l;ie(u,(function(d){c=c[d[0]].apply(c,d.slice(1))}))}else l[u[0]].apply(l,u.slice(1))}catch(d){A.error("Error executing queued PostHog call",u,d)}}))};o(i,this),o(r,this),o(s,this)}finally{Fo--}}push(e){if(Fo>0&&U(e)&&Z(e[0])){var n=Ye.prototype[e[0]];Be(n)&&n.apply(this,e.slice(1))}else this._execute_array([e])}capture(e,n,i){var r,s,o,a,l;if(this.__loaded&&this.persistence&&this.sessionPersistence&&this.In){if(this.is_capturing())if(!C(e)&&Z(e)){var u=!this.config.opt_out_useragent_filter&&this._is_bot();if(!u||this.config.__preview_capture_bot_pageviews){var c=i!=null&&i.skip_client_rate_limiting?void 0:this.rateLimiter.clientRateLimitContext();if(c==null||!c.isRateLimited){n!=null&&n.$current_url&&!Z(n?.$current_url)&&(A.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"||i!=null&&i.Wn||A.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&&this.sessionPersistence.update_campaign_params(),this.config.save_referrer&&this.sessionPersistence.update_referrer_info(),(this.config.save_campaign_params||this.config.save_referrer)&&this.persistence.set_initial_person_info();var d=new Date,f=i?.timestamp||d,h=_c(i?.uuid,Ut),p={uuid:h,event:e,properties:this.calculateEventProperties(e,n||{},f,h)};e===Wn&&this.config.__preview_capture_bot_pageviews&&u&&(p.event="$bot_pageview",p.properties.$browser_type="bot"),c&&(p.properties.$lib_rate_limit_remaining_tokens=c.remainingTokens);var g=e==="$feature_flag_called"&&p.properties.$feature_flag_has_experiment===!1&&this.get_property(Vr)===!0;i?.$set&&!g&&(p.$set=i?.$set);var m=i?.$unset;m&&(p.$unset=m);var v,E,S,_=g?void 0:this.Vn(i?.$set_once,e!==xc,e===_o);if(_&&(p.$set_once=_),i!=null&&i._noTruncate||(s=this.config.properties_string_max_length,o=p,a=L=>Z(L)?L.slice(0,s):L,l=new Set,p=(function L(B,T){if(B!==Object(B))return a?a(B):B;if(!l.has(B)){var V;if(l.add(B),U(B))V=[],fr(B,(G=>{V.push(L(G))}));else{var $={};ie(B,((G,ee)=>{l.has(G)||($[ee]=L(G))})),V=$}return V}})(o)),p.timestamp=f,C(i?.timestamp)||(p.properties.$event_time_override_provided=!0,p.properties.$event_time_override_system_time=d),g&&(p.properties=(function(L,B){B===void 0&&(B=[]);var T={},V=$=>{L[$]!==void 0&&(T[$]=L[$])};return Ep.forEach(V),B.forEach(V),T})(p.properties,_m)),e===qt.DISMISSED||e===qt.SENT){var x=n?.[Io.SURVEY_ID],I=n?.[Io.SURVEY_ITERATION];Of({id:x,current_iteration:I}),p.$set=k({},p.$set,{[(v={id:x,current_iteration:I},E=e===qt.SENT?"responded":"dismissed",S="$survey_"+E+"/"+v.id,v.current_iteration&&v.current_iteration>0&&(S="$survey_"+E+"/"+v.id+"/"+v.current_iteration),S)]:!0})}else e===qt.SHOWN&&(p.$set=k({},p.$set,{[Io.SURVEY_LAST_SEEN_DATE]:new Date().toISOString()}));if(e===Gg.SHOWN){var M=n?.[Uc.TOUR_TYPE];M&&(p.$set=k({},p.$set,{[Uc.TOUR_LAST_SEEN_DATE+"/"+M]:new Date().toISOString()}))}var b=k({},p.properties.$set,p.$set);if(Vt(b)||this.setPersonPropertiesForFlags(b),!H(this.config.before_send)){var P=this.Pt(p);if(!P)return;(p=P).uuid=_c(p.uuid,Ut)}this.dn.emit("eventCaptured",p);var R=(r=i?._url)!==null&&r!==void 0?r:this.requestRouter.endpointFor("api",this.analyticsDefaultEndpoint),N={method:"POST",url:R,data:p,compression:"best-available",timestampMode:i?._batchKey==="recordings"||/\/s\/(?:\?|$)/.test(R)?"body":"capture-body",batchKey:i?._batchKey,transport:i?.transport};return!this.config.request_batching||i&&(i==null||!i._batchKey)||i!=null&&i.send_instantly?this.Pn(N):this.In.enqueue(N),p}A.critical("This capture call is ignored due to client rate limiting.")}}else A.error("No event name provided to posthog.capture")}else A.uninitializedWarning("posthog.capture")}_addCaptureHook(e){return this.on("eventCaptured",(n=>e(n.event,n)))}$n(){var e;return(e=this.jn)!==null&&e!==void 0?e:this.jn=new vm(this)}cn(e){this._n.push(e);var n=!0;return()=>{if(n){n=!1;var i=this._n.indexOf(e);i!==-1&&this._n.splice(i,1)}}}calculateEventProperties(e,n,i,r,s){if(i=i||new Date,!this.persistence||!this.sessionPersistence)return n;var o=s?void 0:this.persistence.remove_event_timer(e),a=k({},n);if(a.token=this.config.token,a.$config_defaults=this.config.defaults,this.gn()&&(a[qd]=!0),e==="$snapshot"){var l=k({},this.persistence.properties(),this.sessionPersistence.properties());return a.distinct_id=l.distinct_id,(!Z(a.distinct_id)&&!xe(a.distinct_id)||Go(a.distinct_id))&&A.error("Invalid distinct_id for replay event. This indicates a bug in your implementation"),a}var u,c=(function(x,I,M,b){var P,R,N,L;if(b===void 0&&(b=!1),!We)return{};var B,T=x?[...ti,...I||[]]:[],V=(function(Ln){for(var Ue=0;mc.length>Ue;Ue++){var Nn=mc[Ue],$t=Nn[1],Mt=Nn[0].exec(Ln),lt=Mt&&(Be($t)?$t(Mt,Ln):$t);if(lt)return lt}return["",""]})(We),$=V[0],G=V[1],ee=(B=typeof navigator<"u"?navigator:void 0)!=null&&B.brave?{brave:!0}:{},Fe={};C(M)||(Fe.detectGoogleSearchApp=M);var we={},ke=(P=navigator)==null||(P=P.userAgentData)==null?void 0:P.platform,$e=(R=navigator)==null?void 0:R.maxTouchPoints,se=w==null||(N=w.screen)==null?void 0:N.width,Se=w==null||(L=w.screen)==null?void 0:L.height,be=w?.devicePixelRatio;C(ke)||(we.userAgentDataPlatform=ke),C($e)||(we.maxTouchPoints=$e),C(se)||(we.screenWidth=se),C(Se)||(we.screenHeight=Se),C(be)||(we.devicePixelRatio=be);var Oe,_t,pe,Ke,yt,hn,Re,Ae,Tt=ue(ol({$os:$,$os_version:G,$browser:Pd(We,navigator.vendor,ee,Fe),$device:vc(We),$device_type:(_t=We,pe=we,Ae=vc(_t),Ae===dd||Ae===ud||Ae==="Kobo"||Ae==="Kindle Fire"||Ae===xd?Zn:Ae===qi||Ae===Yn||Ae===zi||Ae===Yo?"Console":Ae===hd?"Wearable":Ae?nt:pe?.userAgentDataPlatform==="Android"&&((Ke=pe?.maxTouchPoints)!==null&&Ke!==void 0?Ke:0)>0?600>Math.min((yt=pe?.screenWidth)!==null&&yt!==void 0?yt:0,(hn=pe?.screenHeight)!==null&&hn!==void 0?hn:0)/((Re=pe?.devicePixelRatio)!==null&&Re!==void 0?Re:1)?nt:Zn:"Desktop"),$timezone:_f(),$timezone_offset:qg()}),{$current_url:Ki(b?un(ge?.href):ge?.href,T,Yi),$host:ge?.host,$pathname:ge?.pathname,$raw_user_agent:We.length>1e3?We.substring(0,997)+"...":We,$browser_version:Up(We,navigator.vendor,ee,Fe),$browser_language:jc(),$browser_language_prefix:(Oe=jc(),typeof Oe=="string"?Oe.split("-")[0]:void 0),$screen_height:w?.screen.height,$screen_width:w?.screen.width,$viewport_height:w?.innerHeight,$viewport_width:w?.innerWidth,$lib:ne.LIB_NAME,$lib_version:ne.LIB_VERSION,$insert_id:Math.random().toString(36).substring(2,10)+Math.random().toString(36).substring(2,10),$time:Date.now()/1e3});return ne.SDK_DIST_CHANNEL&&(Tt.$sdk_dist_channel=ne.SDK_DIST_CHANNEL),Tt})(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){var d=this.sessionManager.checkAndGetSessionAndWindowId(s,i.getTime()),f=d.windowId;a.$session_id=d.sessionId,a.$window_id=f}this.sessionPropsManager&&ue(a,this.sessionPropsManager.getSessionProps());try{var h;this.sessionRecording&&ue(a,this.sessionRecording.sdkDebugProperties),a.$sdk_debug_retry_queue_size=(h=this.Rn)==null?void 0:h.length}catch(x){a.$sdk_debug_error_capturing_properties=String(x)}if(this.requestRouter.region===Sa&&(a.$lib_custom_api_host=this.config.api_host),u=e!==Wn||s?e!==vo||s?this.pageViewManager.doEvent():this.pageViewManager.doPageLeave(i):this.pageViewManager.doPageView(i,r),a=ue(a,u),e===Wn&&F&&(a.title=F.title),!C(o)){var p=i.getTime()-o;a.$duration=parseFloat((p/1e3).toFixed(3))}We&&this.config.opt_out_useragent_filter&&(a.$browser_type=this._is_bot()?"bot":"browser");var g=this.persistence.properties(),m=this.sessionPersistence.properties();ie(["$referrer","$referring_domain"],(x=>{x in g&&delete m[x]}));var v={};if(this._n.length>0)for(var E of this._n.slice())try{ue(v,E())}catch(x){A.error("Failed to produce browser extension event properties",x)}(a=ue({},c,g,m,k({},v,a))).$is_identified=this._isIdentified(),U(this.config.property_denylist)?ie(this.config.property_denylist,(function(x){delete a[x]})):A.error(Bf+this.config.property_denylist+" or property_blacklist config: "+this.config.property_blacklist);var S=this.config.sanitize_properties;S&&(A.error(Qc),a=S(a,e));var _=this.Zn();return a.$process_person_profile=_,_&&!s&&this.Gn("_calculate_event_properties"),a}Vn(e,n,i){var r;if(n===void 0&&(n=!0),i===void 0&&(i=!1),!this.persistence||!this.Zn()||this.mn&&!i)return e;var s=this.persistence.get_initial_props(),o=(r=this.sessionPropsManager)==null?void 0:r.getSetOnceProps(),a=ue({},s,o||{},e||{}),l=this.config.sanitize_properties;return l&&(A.error(Qc),a=l(a,"$set_once")),n&&(this.mn=!0),Vt(a)?void 0:a}register(e,n){var i;(i=this.persistence)==null||i.register(e,n)}register_once(e,n,i){var r;(r=this.persistence)==null||r.register_once(e,n,i)}register_for_session(e){var n;(n=this.sessionPersistence)==null||n.register(e),Object.keys(e).forEach((i=>this.yn.add(i))),this.Qn()}unregister(e){var n;(n=this.persistence)==null||n.unregister(e)}unregister_for_session(e){var n;(n=this.sessionPersistence)==null||n.unregister(e),this.yn.delete(e),this.Qn()}Kn(e,n){this.register({[e]:n})}An(){this.yn.forEach((e=>{var n;(n=this.sessionPersistence)==null||n.unregister(e)})),this.yn.clear(),this.Qn()}Qn(){var e;if(this.bn)if(this.config.persistence==="memory"||(e=this.sessionPersistence)!=null&&e.xi||!ye.N())ye.q(this.bn);else{var n=[];this.yn.forEach((i=>n.push(i))),n.length>0?ye.F(this.bn,n):ye.q(this.bn)}}getFeatureFlag(e,n){var i;return(i=this.featureFlags)==null?void 0:i.getFeatureFlag(e,n)}getFeatureFlagPayload(e){var n;return(n=this.featureFlags)==null?void 0:n.getFeatureFlagPayload(e)}getFeatureFlagResult(e,n){var i;return(i=this.featureFlags)==null?void 0:i.getFeatureFlagResult(e,n)}getAllFeatureFlags(){var e,n;return(e=(n=this.featureFlags)==null?void 0:n.getAllFeatureFlags())!==null&&e!==void 0?e:[]}isFeatureEnabled(e,n){var i,r;return(i=(r=this.featureFlags)==null?void 0:r.isFeatureEnabled(e,n))!==null&&i!==void 0?i:n?.defaultValue}reloadFeatureFlags(){var e;(e=this.featureFlags)==null||e.reloadFeatureFlags()}updateFlags(e,n,i){var r;(r=this.featureFlags)==null||r.updateFlags(e,n,i)}updateEarlyAccessFeatureEnrollment(e,n,i){var r;(r=this.featureFlags)==null||r.updateEarlyAccessFeatureEnrollment(e,n,i)}getEarlyAccessFeatures(e,n,i){var r;return n===void 0&&(n=!1),(r=this.featureFlags)==null?void 0:r.getEarlyAccessFeatures(e,n,i)}on(e,n){return this.dn.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:bi}),()=>{})}onSessionId(e){var n,i;return(n=(i=this.sessionManager)==null?void 0:i.onSessionId(e))!==null&&n!==void 0?n:()=>{}}getSurveys(e,n){n===void 0&&(n=!1),this.surveys?this.surveys.getSurveys(e,n):e([],{isLoaded:!1,error:bi})}getActiveMatchingSurveys(e,n){n===void 0&&(n=!1),this.surveys?this.surveys.getActiveMatchingSurveys(e,n):e([],{isLoaded:!1,error:bi})}renderSurvey(e,n){var i;(i=this.surveys)==null||i.renderSurvey(e,n)}displaySurvey(e,n){var i;n===void 0&&(n=dm),(i=this.surveys)==null||i.displaySurvey(e,n)}cancelPendingSurvey(e){var n;(n=this.surveys)==null||n.cancelPendingSurvey(e)}canRenderSurvey(e){var n,i;return(n=(i=this.surveys)==null?void 0:i.canRenderSurvey(e))!==null&&n!==void 0?n:{visible:!1,disabledReason:bi}}canRenderSurveyAsync(e,n){var i,r;return n===void 0&&(n=!1),(i=(r=this.surveys)==null?void 0:r.canRenderSurveyAsync(e,n))!==null&&i!==void 0?i:Promise.resolve({visible:!1,disabledReason:bi})}Jn(e){return!e||Go(e)?(A.critical("Unique user id has not been set in posthog.identify"),!1):e===dr?(A.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())||(A.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,i){if(!this.__loaded||!this.persistence)return A.uninitializedWarning("posthog.identify");if(xe(e)&&(e=e.toString(),A.warn("The first argument to posthog.identify was a number, but it should be a string. It has been converted to a string.")),this.Jn(e)&&this.Gn("posthog.identify")){var r=this.get_distinct_id();this.register({$user_id:e}),this.get_property(Vi)||this.register_once({$had_persisted_distinct_id:!0,$device_id:r},""),e!==r&&e!==this.get_property(Ci)&&(this.unregister(Ci),this.register({distinct_id:e}));var s,o=(this.persistence.get_property(st)||Bn)===Bn,a=e!==r,l=!a&&o;if(a&&o)this.persistence.set_property(st,pn),this.setPersonPropertiesForFlags({$set:n||{},$set_once:i||{}},!1),this.capture(_o,{distinct_id:e,$anon_distinct_id:r},{$set:n||{},$set_once:i||{}}),this.Sn=Po(e,n,i),(s=this.featureFlags)==null||s.setAnonymousDistinctId(r);else if(l){this.persistence.set_property(st,pn);var u=n||{},c=i||{};this.setPersonPropertiesForFlags({$set:u,$set_once:c},!1),this.capture("$set",{$set:u,$set_once:c}),this.Sn=Po(e,n,i)}else(n||i)&&this.setPersonProperties(n,i);a?(this.reloadFeatureFlags(),this.featureFlags?this.featureFlags.resetFlagCallReported():this.unregister(xn)):l&&(n||i)&&this.reloadFeatureFlags()}}setPersonProperties(e,n){if((e||n)&&this.Gn("posthog.setPersonProperties")){var i=Po(this.get_distinct_id(),e,n);this.Sn!==i?(this.setPersonPropertiesForFlags({$set:e||{},$set_once:n||{}},!0),this.capture("$set",{$set:e||{},$set_once:n||{}}),this.Sn=i):A.info("A duplicate setPersonProperties call was made with the same properties. It has been ignored.")}}unsetPersonProperties(e){var n,i=(U(e)?e:[e]).filter((r=>Z(r)&&r.length>0));i.length!==0&&this.Gn("posthog.unsetPersonProperties")&&((n=this.featureFlags)==null||n.unsetPersonPropertiesForFlags(i,!0),this.capture("$set",{$unset:i}),this.Sn=null)}group(e,n,i){if(e&&n){var r=this.getGroups(),s=r[e]!==n;if(s&&this.resetGroupPropertiesForFlags(e),this.register({$groups:k({},r,{[e]:n})}),s||i){var o={$group_type:e,$group_key:n};i&&(o.$group_set=i),this.capture(xc,o)}i&&this.setGroupPropertiesForFlags({[e]:i}),s&&!i&&this.reloadFeatureFlags()}else A.error("posthog.group requires a group type and group key")}resetGroups(){this.register({$groups:{}}),this.resetGroupPropertiesForFlags(),this.reloadFeatureFlags()}setPersonPropertiesForFlags(e,n){var i;n===void 0&&(n=!0),(i=this.featureFlags)==null||i.setPersonPropertiesForFlags(e,n)}resetPersonPropertiesForFlags(e){var n;e===void 0&&(e=!0),(n=this.featureFlags)==null||n.resetPersonPropertiesForFlags(e)}setGroupPropertiesForFlags(e,n){var i;n===void 0&&(n=!0),this.Gn("posthog.setGroupPropertiesForFlags")&&((i=this.featureFlags)==null||i.setGroupPropertiesForFlags(e,n))}resetGroupPropertiesForFlags(e){var n;(n=this.featureFlags)==null||n.resetGroupPropertiesForFlags(e)}reset(e){this.Yn(e)}Yn(e,n){var i,r,s,o,a,l,u,c,d,f;if(n===void 0&&(n=!1),A.info("reset"),!this.__loaded)return A.uninitializedWarning("posthog.reset");var h,p=this.get_property(Vi),g=this.get_property(mo),m=this.get_property(In),v=this.is_capturing();if(this.consent.reset(),n||!v||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."),(i=this.persistence)==null||i.clear(),(r=this.sessionPersistence)==null||r.clear(),this.yn.clear(),this.Qn(),C(m)||(h=this.persistence)==null||h.register({[In]:m}),(s=this.surveys)==null||s.reset(),(o=this.Un)==null||o.stop(),(a=this.featureFlags)==null||a.reset(),(l=this.conversations)==null||l.reset(),(u=this.logs)==null||u.reset(),(c=this.metrics)==null||c.reset(),(d=this.persistence)==null||d.set_property(st,Bn),(f=this.sessionManager)==null||f.resetSessionId(),this.Sn=null,this.config.cookieless_mode===Ht)this.register_once({distinct_id:dr,$device_id:null},"");else{var E=this.config.get_device_id(Ut());this.register_once({distinct_id:E,$device_id:e?E:p},""),e||C(g)||this.register({[mo]:g})}this.register({$last_posthog_reset:new Date().toISOString()},1),delete this.config.identity_distinct_id,delete this.config.identity_hash,this.reloadFeatureFlags()}shutdown(e){var n=this;return re((function*(){var i,r,s,o,a,l,u;if(n.__loaded){(i=n.Un)==null||i.stop(),(r=n.jn)==null||r.dispose(),(s=n.sessionRecording)==null||s.dispose(),(o=n.logs)==null||o.flushLogs("sendBeacon"),(a=n.metrics)==null||a.flush("sendBeacon"),(l=n.In)==null||l.unload(),(u=n.Rn)==null||u.unload();try{var c;(c=n.featureFlags)==null||c.destroy()}catch(d){A.error("Error while destroying feature flags",d)}}else A.uninitializedWarning("posthog.shutdown")}))()}setIdentity(e,n){var i;this.config.identity_distinct_id=e,this.config.identity_hash=n,this.alias(e),(i=this.conversations)==null||i.Xn()}clearIdentity(){var e;delete this.config.identity_distinct_id,delete this.config.identity_hash,(e=this.conversations)==null||e.ts()}get_distinct_id(){return this.get_property("distinct_id")}getGroups(){return this.get_property("$groups")||{}}get_session_id(){var e,n;return(e=(n=this.sessionManager)==null?void 0:n.checkAndGetSessionAndWindowId(!0).sessionId)!==null&&e!==void 0?e:""}get_session_replay_url(e){if(!this.sessionManager)return"";var n=this.sessionManager.checkAndGetSessionAndWindowId(!0),i=n.sessionStartTimestamp,r=this.requestRouter.endpointFor("ui","/project/"+this.config.token+"/replay/"+n.sessionId);if(e!=null&&e.withTimestamp&&i){var s,o=(s=e.timestampLookBack)!==null&&s!==void 0?s:10;if(!i)return r;r+="?t="+Math.max(Math.floor((new Date().getTime()-i)/1e3)-o,0)}return r}alias(e,n){return e===this.get_property(Bd)?(A.critical("Attempting to create alias for existing People user - aborting."),-2):this.Gn("posthog.alias")?(C(n)&&(n=this.get_distinct_id()),e!==n?(this.Kn(Ci,e),this.capture("$create_alias",{alias:e,distinct_id:n})):(A.warn("alias matches current distinct_id - skipping api call."),this.identify(e),-1)):void 0}set_config(e){var n=k({},this.config);if(de(e)){var i,r,s,o,a,l,u,c,d,f,h,p;ue(this.config,eu(e));var g=this.En();(i=this.persistence)==null||i.update_config(this.config,n,g),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new So(k({},this.config,{persistence:"sessionStorage"}),g,!1);var m=this.Cn(this.config.debug);pt(m)&&(this.config.debug=m),pt(this.config.debug)&&(this.config.debug?(ne.DEBUG=!0,oe.N()&&oe.F("ph_debug",!0),A.info("set_config",{config:e,oldConfig:n,newConfig:k({},this.config)})):(ne.DEBUG=!1,oe.N()&&oe.q("ph_debug"))),(r=this.featureFlags)==null||r.updateConfig==null||r.updateConfig(this.config,this.Qi()),(s=this.exceptionObserver)==null||s.onConfigChange(),(o=this.exceptions)==null||o.onConfigChange(),(a=this.sessionRecording)==null||a.startIfEnabledOrStop(),(l=this.tracingHeaders)==null||l.startIfEnabledOrStop(),(u=this.autocapture)==null||u.startIfEnabled(),(c=this.heatmaps)==null||c.startIfEnabled(),(d=this.exceptionObserver)==null||d.startIfEnabledOrStop(),(f=this.deadClicksAutocapture)==null||f.startIfEnabledOrStop(),(h=this.surveys)==null||h.loadIfEnabled(),this.es(),(p=this.externalIntegrations)==null||p.startIfEnabledOrStop()}}_overrideSDKInfo(e,n){ne.LIB_NAME=e,ne.LIB_VERSION=n}startSessionRecording(e){var n,i,r,s,o,a=e===!0,l={sampling:a||!(e==null||!e.sampling),linked_flag:a||!(e==null||!e.linked_flag),url_trigger:a||!(e==null||!e.url_trigger),event_trigger:a||!(e==null||!e.event_trigger)};Object.values(l).some(Boolean)&&((n=this.sessionManager)==null||n.checkAndGetSessionAndWindowId(),l.sampling&&((i=this.sessionRecording)==null||i.overrideSampling()),l.linked_flag&&((r=this.sessionRecording)==null||r.overrideLinkedFlag()),l.url_trigger&&((s=this.sessionRecording)==null||s.overrideTrigger("url")),l.event_trigger&&((o=this.sessionRecording)==null||o.overrideTrigger("event"))),this.set_config({disable_session_recording:!1})}stopSessionRecording(){this.set_config({disable_session_recording:!0})}sessionRecordingStarted(){var e;return!((e=this.sessionRecording)==null||!e.started)}captureException(e,n){if(this.exceptions){var i=new Error("PostHog syntheticException"),r=this.exceptions.buildProperties(e,{handled:!0,syntheticException:i});return this.exceptions.sendExceptionEvent(k({},r,n))}}addExceptionStep(e,n){var i;(i=this.exceptions)==null||i.addExceptionStep(e,n)}captureLog(e){var n;(n=this.logs)==null||n.captureLog(e)}get logger(){var e,n;return(e=(n=this.logs)==null?void 0:n.logger)!==null&&e!==void 0?e:Ye.rs}startExceptionAutocapture(e){this.set_config({capture_exceptions:e==null||e})}stopExceptionAutocapture(){this.set_config({capture_exceptions:!1})}loadToolbar(e){var n,i;return(n=(i=this.toolbar)==null?void 0:i.loadToolbar(e))!==null&&n!==void 0&&n}get_property(e){var n;return(n=this.persistence)==null?void 0:n.props[e]}getSessionProperty(e){var n;return(n=this.sessionPersistence)==null?void 0:n.props[e]}toString(){var e,n=(e=this.config.name)!==null&&e!==void 0?e:qn;return n!==qn&&(n=qn+"."+n),n}_isIdentified(){var e,n;return((e=this.persistence)==null?void 0:e.get_property(st))===pn||((n=this.sessionPersistence)==null?void 0:n.get_property(st))===pn}Zn(){var e,n;return!(this.config.person_profiles==="never"||this.config.person_profiles===ha&&!this._isIdentified()&&Vt(this.getGroups())&&((e=this.persistence)==null||(e=e.props)==null||!e[Ci])&&((n=this.persistence)==null||(n=n.props)==null||!n[Yr]))}zn(){return this.config.capture_pageleave===!0||this.config.capture_pageleave==="if_capture_pageview"&&(this.config.capture_pageview===!0||this.config.capture_pageview==="history_change")}createPersonProfile(){this.Zn()||this.Gn("posthog.createPersonProfile")&&this.setPersonProperties({},{})}setInternalOrTestUser(){this.Gn("posthog.setInternalOrTestUser")&&this.setPersonProperties({$internal_or_test_user:!0})}Gn(e){return this.config.person_profiles==="never"?(A.error(e+' was called, but process_person is set to "never". This call will be ignored.'),!1):(this.Kn(Yr,!0),!0)}En(){if(this.config.cookieless_mode==="always")return!0;var e=this.consent.isOptedOut();return this.config.disable_persistence||e&&!(!this.config.opt_out_persistence_by_default&&this.config.cookieless_mode!==Sn)}es(){var e,n,i,r,s=this.En();return((e=this.persistence)==null?void 0:e.xi)!==s&&((i=this.persistence)==null||i.set_disabled(s)),((n=this.sessionPersistence)==null?void 0:n.xi)!==s&&((r=this.sessionPersistence)==null||r.set_disabled(s)),s&&(this.yn.clear(),this.Qn()),s}opt_in_capturing(e){var n;if(this.config.cookieless_mode!==Ht){if(this.gn()){var i,r,s,o,a;this.Yn(!0,!0),(i=this.sessionManager)==null||i.destroy(),(r=this.pageViewManager)==null||r.destroy(),this.sessionManager=new Yc(this),this.pageViewManager=new Dc(this),this.persistence&&(this.sessionPropsManager=new Kc(this,this.sessionManager,this.persistence));var l,u=(s=(o=this.config.__extensionClasses)==null?void 0:o.sessionRecording)!==null&&s!==void 0?s:(a=Ye.__defaultExtensionClasses)==null?void 0:a.sessionRecording;u&&(this.sessionRecording=this.pn(this.sessionRecording,new u(this)),this.hn&&((l=this.sessionRecording)==null||l.onRemoteConfig==null||l.onRemoteConfig(this.hn)))}var c,d;this.consent.optInOut(!0),this.es(),this.Bn(),(n=this.sessionRecording)==null||n.startIfEnabledOrStop(),this.config.cookieless_mode==Sn&&((c=this.surveys)==null||c.loadIfEnabled()),(C(e?.captureEventName)||e!=null&&e.captureEventName)&&this.capture((d=e?.captureEventName)!==null&&d!==void 0?d:"$opt_in",e?.captureProperties,{send_instantly:!0}),this.config.capture_pageview&&this.Hn()}else A.warn(Xc)}opt_out_capturing(){var e,n,i;this.config.cookieless_mode!==Ht?(this.config.cookieless_mode===Sn&&this.consent.isOptedIn()&&this.Yn(!0,!0),this.consent.optInOut(!1),this.es(),this.config.cookieless_mode===Sn&&(this.register({distinct_id:dr,$device_id:null}),(e=this.sessionRecording)==null||e.stopRecording(),this.sessionRecording=void 0,(n=this.sessionManager)==null||n.destroy(),(i=this.pageViewManager)==null||i.destroy(),this.sessionManager=void 0,this.sessionPropsManager=void 0,this.config.capture_pageview&&this.Hn(),this.Bn())):A.warn(Xc)}has_opted_in_capturing(){return this.consent.isOptedIn()}has_opted_out_capturing(){return this.consent.isOptedOut()}get_explicit_consent_status(){var e=this.consent.consent;return e===1?"granted":e===0?"denied":"pending"}is_capturing(){return this.config.cookieless_mode===Ht||(this.config.cookieless_mode===Sn?this.consent.isRejected()||this.consent.isOptedIn():!this.has_opted_out_capturing())}clear_opt_in_out_capturing(){this.consent.reset(),this.es()}_is_bot(){return je?Rf(je,this.config.custom_blocked_useragents):void 0}Hn(){F&&(F.visibilityState==="visible"?this.wn||(this.wn=!0,this.capture(Wn,{title:F.title},{send_instantly:!0}),this.kn&&(F.removeEventListener(Jr,this.kn),this.kn=null)):this.kn||(this.kn=this.Hn.bind(this),me(F,Jr,this.kn)))}debug(e){e===!1?(w?.console.log("You've disabled debug mode."),this.set_config({debug:!1})):(w?.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}))}Qi(){var e=this.Mn||{};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?(A.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,i,r,s,o){var a=i in n&&!H(n[i]),l=r in n&&!H(n[r]);return a?n[i]:!!l&&(o&&o.warn("Config field '"+r+"' is deprecated. Please use '"+i+"' instead. The old field will be removed in a future major version."),n[r])})(e,"advanced_disable_flags","advanced_disable_decide",0,A)}Pt(e){var n;if(H(this.config.before_send))return e;var i=Object.keys((n=e.properties)!==null&&n!==void 0?n:{}).filter(Pp),r=U(this.config.before_send)?this.config.before_send:[this.config.before_send],s=e;for(var o of r){if(s=o(s),H(s)){var a="Event '"+e.event+"' was rejected in beforeSend function";return Ap(e.event)?A.warn(a+". This can cause unexpected behavior."):A.info(a),null}s.properties&&!Vt(s.properties)||A.warn("Event '"+e.event+"' has no properties after beforeSend function, this is likely an error.")}for(var l of i)if(s.properties&&H(s.properties[l]))return A.warn("Event '"+e.event+"' had its '"+l+"' property removed in a beforeSend function. This property is required for ingestion, so the event will be dropped."),null;return s}getPageViewId(){var e;return(e=this.pageViewManager.ui)==null?void 0:e.pageViewId}captureTraceFeedback(e,n){this.capture("$ai_feedback",{$ai_trace_id:String(e),$ai_feedback_text:n})}captureTraceMetric(e,n,i){this.capture("$ai_metric",{$ai_trace_id:String(e),$ai_metric_name:n,$ai_metric_value:String(i)})}Cn(e){var n=pt(e)&&!e,i=oe.N()&&oe.P("ph_debug")==="true";return!n&&(!!i||e)}}Ye.__defaultExtensionClasses={},Ye.rs=(()=>{var t=()=>{};return{trace:t,debug:t,info:t,warn:t,error:t,fatal:t}})(),(function(t,e){for(var n=0;e.length>n;n++)t.prototype[e[n]]=vg(t.prototype[e[n]])})(Ye,["identify"]);class tu{constructor(e){this.disabled=e===!1;var n=de(e)?e:{};this.thresholdPx=n.threshold_px||30,this.timeoutMs=n.timeout_ms||1e3,this.clickCount=n.click_count||3,this.clicks=[]}isRageClick(e,n,i){if(this.disabled)return!1;var r=this.clicks[this.clicks.length-1];if(r&&Math.abs(e-r.x)+Math.abs(n-r.y)i-r.timestamp){if(this.clicks.push({x:e,y:n,timestamp:i}),this.clicks.length===this.clickCount)return!0}else this.clicks=[{x:e,y:n,timestamp:i}];return!1}}var To="$copy_autocapture",$o=he("[AutoCapture]");function Mo(t,e){return e.length>t?e.slice(0,t)+"...":e}function bm(t){if(t.previousElementSibling)return t.previousElementSibling;var e=t;do e=e.previousSibling;while(e&&!dn(e));return e}function Em(t,e){var n,i,r=e.e,s=e.maskAllElementAttributes,o=e.maskAllText,a=e.elementAttributeIgnoreList,l=e.elementsChainAsString,u=e.disableCaptureUrlHashes;if(!dn(t))return{props:{}};for(var c=[t],d=new Set([t]),f=t;f.parentNode&&!Xe(f,"body")&&ef>c.length;)if(Qd(f.parentNode)){var h=f.parentNode.host;if(d.has(h))break;d.add(h),c.push(h),f=h}else{if(!dn(f.parentNode)||d.has(f.parentNode))break;d.add(f.parentNode),c.push(f.parentNode),f=f.parentNode}var p,g,m=[],v={},E=!1,S=!1;if(ie(c,(b=>{var P=ma(b);if(Xe(b,"a")){var R=b.getAttribute("href");E=!!(P&&R&&Bi(R))&&(u?un(R):R)}j(Qr(b),"ph-no-capture")&&(S=!0),m.push((function(L,B,T,V,$){$===void 0&&($=!1);var G=L.tagName.toLowerCase(),ee={tag_name:G};ll.indexOf(G)>-1&&!T&&(ee.$el_text=G.toLowerCase()==="a"||G.toLowerCase()==="button"?Mo(1024,Nc(L)):Mo(1024,Gi(L)));var Fe=Qr(L);Fe.length>0&&(ee.classes=Fe.filter((function(se){return se!==""}))),ie(L.attributes,(function(se){var Se;if((!of(L)||["name","id","class","aria-label"].indexOf(se.name)!==-1)&&(V==null||!V.includes(se.name))&&!B&&Bi(se.value)&&(!Z(Se=se.name)||Se.substring(0,10)!=="_ngcontent"&&Se.substring(0,7)!=="_nghost")){var be=se.value;se.name==="class"&&(be=al(be).join(" ")),ee["attr__"+se.name]=Mo(1024,se.name==="href"&&$?un(be):be)}}));for(var we=1,ke=1,$e=L;$e=bm($e);)we++,$e.tagName===L.tagName&&ke++;return ee.nth_child=we,ee.nth_of_type=ke,ee})(b,s,o,a,u));var N=(function(L){if(!ma(L))return{};var B={};return ie(L.attributes,(function(T){if(T.name&&T.name.indexOf("data-ph-capture-attribute")===0){var V=T.name.replace("data-ph-capture-attribute-",""),$=T.value;V&&$&&Bi($)&&(B[V]=$)}})),B})(b);ue(v,N)})),S)return{props:{},explicitNoCapture:S};if(o||(m[0].$el_text=Xe(t,"a")||Xe(t,"button")?Nc(t):Gi(t)),E){var _,x;m[0].attr__href=E;var I=(_=es(E))==null?void 0:_.host,M=w==null||(x=w.location)==null?void 0:x.host;I&&M&&I!==M&&(p=E)}return{props:ue({$event_type:r.type,$ce_version:1},l?{}:{$elements:m},{$elements_chain:(g=m,(function(b){return b.map((P=>{var R,N,L="";if(P.tag_name&&(L+=P.tag_name),P.attr_class)for(var B of(P.attr_class.sort(),P.attr_class))L+="."+B.replace(/"/g,"");var T=k({},P.text?{text:P.text}:{},{"nth-child":(R=P.nth_child)!==null&&R!==void 0?R:0,"nth-of-type":(N=P.nth_of_type)!==null&&N!==void 0?N:0},P.href?{href:P.href}:{},P.attr_id?{attr_id:P.attr_id}:{},P.attributes),V={};return Ar(T).sort((($,G)=>$[0].localeCompare(G[0]))).forEach(($=>{var G=$[1];return V[Oc($[0].toString())]=Oc(G.toString())})),(L+=":")+Ar(V).map(($=>$[0]+'="'+$[1]+'"')).join("")})).join(";")})((function(b){return b.map((P=>{var R,N,L={text:(R=P.$el_text)==null?void 0:R.slice(0,400),tag_name:P.tag_name,href:(N=P.attr__href)==null?void 0:N.slice(0,2048),attr_class:Ng(P),attr_id:P.attr__id,nth_child:P.nth_child,nth_of_type:P.nth_of_type,attributes:{}};return Ar(P).filter((B=>B[0].indexOf("attr__")===0)).forEach((B=>L.attributes[B[0]]=B[1])),L}))})(g)))},(n=m[0])!=null&&n.$el_text?{$el_text:(i=m[0])==null?void 0:i.$el_text}:{},p&&r.type==="click"?{$external_click_url:p}:{},v)}}var Ei=he("[ExceptionAutocapture]"),nu=()=>{},Sm=he("[TracingHeaders]"),vn=he("[Web Vitals]"),iu=9e5,ru="disabled",su="lazy_loading",Si="awaiting_config",_r="missing_config";he("[SessionRecording]"),he("[SessionRecording]");var xa="[SessionRecording]",Ot=he(xa),xm=he("[Heatmaps]");function Lo(t){return de(t)&&"clientX"in t&&"clientY"in t&&xe(t.clientX)&&xe(t.clientY)}var yr=he("[Product Tours]"),No=t=>{var e;return!t.config.disable_product_tours&&!((e=t.persistence)==null||!e.get_property(il))},Im=["$set_once","$set"],wt=he("[SiteApps]"),ou="Error while initializing PostHog app with config id ";function Un(t,e,n){if(H(t))return!1;switch(n){case"exact":return t===e;case"contains":var i=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/_/g,".").replace(/%/g,".*");return new RegExp(i,"i").test(t);case"regex":try{return new RegExp(e).test(t)}catch{return!1}default:return!1}}class km{constructor(e){this.ns=new fl,this.ss=(n,i)=>this.os(n,i)&&this.ls(n,i)&&this.us(n,i)&&this.hs(n,i),this.os=(n,i)=>i==null||!i.event||n?.event===i?.event,this._instance=e,this.ds=new Set,this.vs=new Set}init(){var e,n;C((e=this._instance)==null?void 0:e._addCaptureHook)||(n=this._instance)==null||n._addCaptureHook(((i,r)=>{this.on(i,r)}))}register(e){var n,i;if(!C((n=this._instance)==null?void 0:n._addCaptureHook)&&(e.forEach((o=>{var a,l;(a=this.vs)==null||a.add(o),(l=o.steps)==null||l.forEach((u=>{var c;(c=this.ds)==null||c.add(u?.event||"")}))})),(i=this._instance)!=null&&i.autocapture)){var r,s=new Set;e.forEach((o=>{var a;(a=o.steps)==null||a.forEach((l=>{l!=null&&l.selector&&s.add(l?.selector)}))})),(r=this._instance)==null||r.autocapture.setElementSelectors(s)}}on(e,n){var i;n!=null&&e.length!=0&&(this.ds.has(e)||this.ds.has(n.event))&&this.vs&&((i=this.vs)==null?void 0:i.size)>0&&this.vs.forEach((r=>{this.cs(n,r)&&this.ns.emit("actionCaptured",r.name)}))}fs(e){this.onAction("actionCaptured",(n=>e(n)))}cs(e,n){if(n?.steps==null)return!1;for(var i of n.steps)if(this.ss(e,i))return!0;return!1}onAction(e,n){return this.ns.on(e,n)}ls(e,n){if(n!=null&&n.url){var i,r=e==null||(i=e.properties)==null?void 0:i.$current_url;if(!r||typeof r!="string"||!Un(r,n.url,n.url_matching||"contains"))return!1}return!0}us(e,n){return!!this.ps(e,n)&&!!this.gs(e,n)&&!!this.ys(e,n)}ps(e,n){var i;if(n==null||!n.href)return!0;var r=this.bs(e);if(r.length>0)return r.some((a=>Un(a.href,n.href,n.href_matching||"exact")));var s,o=(e==null||(i=e.properties)==null?void 0:i.$elements_chain)||"";return!!o&&Un((s=o.match(/(?::|")href="(.*?)"/))?s[1]:"",n.href,n.href_matching||"exact")}gs(e,n){var i;if(n==null||!n.text)return!0;var r=this.bs(e);if(r.length>0)return r.some((u=>Un(u.text,n.text,n.text_matching||"exact")||Un(u.$el_text,n.text,n.text_matching||"exact")));var s,o,a,l=(e==null||(i=e.properties)==null?void 0:i.$elements_chain)||"";return!!l&&(s=(function(u){for(var c,d=[],f=/(?::|")text="(.*?)"/g;!H(c=f.exec(u));)d.includes(c[1])||d.push(c[1]);return d})(l),o=n.text,a=n.text_matching||"exact",s.some((u=>Un(u,o,a))))}ys(e,n){var i,r;if(n==null||!n.selector)return!0;var s=e==null||(i=e.properties)==null?void 0:i.$element_selectors;if(s!=null&&s.includes(n.selector))return!0;var o=(e==null||(r=e.properties)==null?void 0:r.$elements_chain)||"";if(n.selector_regex&&o)try{return new RegExp(n.selector_regex).test(o)}catch{return!1}return!1}bs(e){var n;return(e==null||(n=e.properties)==null?void 0:n.$elements)==null?[]:e?.properties.$elements}hs(e,n){return n==null||!n.properties||n.properties.length===0||Mf(n.properties.reduce(((i,r)=>{var s=U(r.value)?r.value.map(String):r.value!=null?[String(r.value)]:[];return i[r.key]={values:s,operator:r.operator||"exact"},i}),{}),e?.properties)}}class Cm{constructor(e){var n;this._s=[],this._instance=e,this.ws=new Map,this.ks=new Map,this.xs=new Map,(n=this._instance)==null||n.onSessionId==null||n.onSessionId((i=>this.Ss(i)))}Cs(e){return!1}Ms(){return null}Ts(e){}Es(){}Is(e,n){return!!e&&Mf(e.propertyFilters,n?.properties)}Ps(e,n){var i=new Map;return e.forEach((r=>{var s;(s=r.conditions)==null||(s=s[n])==null||(s=s.values)==null||s.forEach((o=>{if(o!=null&&o.name){var a=i.get(o.name)||[];a.push(r.id),i.set(o.name,a)}}))})),i}Rs(e,n,i){var r=(i===vi.Activation?this.ws:this.ks).get(e),s=[];return this.As((o=>{s=o.filter((a=>r?.includes(a.id)))})),s.filter((o=>{var a,l=(a=o.conditions)==null||(a=a[i])==null||(a=a.values)==null?void 0:a.find((u=>u.name===e));return this.Is(l,n)}))}register(e){var n;C((n=this._instance)==null?void 0:n._addCaptureHook)||(this.Fs(e),this.Ls(e))}Ls(e){var n=e.filter((i=>{var r,s;return((r=i.conditions)==null?void 0:r.actions)&&((s=i.conditions)==null||(s=s.actions)==null||(s=s.values)==null?void 0:s.length)>0}));n.length!==0&&(this.Os==null&&(this.Os=new km(this._instance),this.Os.init(),this.Os.fs((i=>{this.onAction(i)}))),n.forEach((i=>{var r,s,o,a,l;i.conditions&&(r=i.conditions)!=null&&r.actions&&(s=i.conditions)!=null&&(s=s.actions)!=null&&s.values&&((o=i.conditions)==null||(o=o.actions)==null||(o=o.values)==null?void 0:o.length)>0&&((a=this.Os)==null||a.register(i.conditions.actions.values),(l=i.conditions)==null||(l=l.actions)==null||(l=l.values)==null||l.forEach((u=>{if(u&&u.name){var c=this.xs.get(u.name);c&&c.push(i.id),this.xs.set(u.name,c||[i.id])}})))})))}Fs(e){var n,i=e.filter((s=>{var o,a;return((o=s.conditions)==null?void 0:o.events)&&((a=s.conditions)==null||(a=a.events)==null||(a=a.values)==null?void 0:a.length)>0})),r=e.filter((s=>{var o,a;return((o=s.conditions)==null?void 0:o.cancelEvents)&&((a=s.conditions)==null||(a=a.cancelEvents)==null||(a=a.values)==null?void 0:a.length)>0}));i.length===0&&r.length===0||((n=this._instance)==null||n._addCaptureHook(((s,o)=>{this.onEvent(s,o)})),this.ws=this.Ps(e,vi.Activation),this.ks=this.Ps(e,vi.Cancellation))}onEvent(e,n){var i,r,s=this.Ds(),o=(n==null||(i=n.properties)==null?void 0:i.$survey_id)||(n==null||(r=n.properties)==null?void 0:r.$product_tour_id);if(o&&this.getActivatedIds().includes(o)){var a=this.$s(e,o);if(a==="consume")return s.info("event consumed activated item, removing it",{event:e,itemId:o}),void this.Ns([o]);if(a==="persist")return s.info("shown item promoted to persisted activation",{event:e,itemId:o}),this.qs(o),void this.js([o])}if(this.ks.has(e)){var l=this.Rs(e,n,vi.Cancellation);l.length>0&&(s.info("cancel event matched, cancelling items",{event:e,itemsToCancel:l.map((c=>c.id))}),this.Ns(l.map((c=>c.id))),l.forEach((c=>this.Bs(c.id))))}if(this.ws.has(e)){s.info("event name matched",{event:e,eventPayload:n,items:this.ws.get(e)});var u=this.Rs(e,n,vi.Activation);this.Hs(u.map((c=>c.id)))}}onAction(e){this.xs.has(e)&&this.Hs(this.xs.get(e)||[])}Hs(e){var n;if(e.length!==0){var i=!((n=this._instance)==null||n.get_session_id==null||!n.get_session_id()),r=[];for(var s of e)i&&this.Cs(s)?this.qs(s)&&this.Us(s):r.push(s);r.length>0&&(this._s=[...new Set([...this._s,...r])]),this.Ds().info("updating activated items",{activatedItems:this.getActivatedIds()})}}qs(e){this._s=this._s.filter((i=>i!==e));var n=this.zs();return!n.includes(e)&&(this.Ws([...n,e]),this.Vs(),!0)}Ns(e){var n=new Set(e);this._s=this._s.filter((s=>!n.has(s)));var i=this.Zs(),r=i.filter((s=>!n.has(s)));r.length!==i.length&&(this.Ws(r),r.length===0&&this.Gs()),this.js(e)}Qs(){var e,n=this.Ms();if(!n)return{};var i=(e=this._instance)==null||(e=e.persistence)==null?void 0:e.props[n];return i&&typeof i=="object"?i:{}}Us(e){if(this.Ms()){var n=this.Qs();this.Ts(k({},n,{[e]:Date.now()}))}}js(e){if(this.Ms()){var n=this.Qs(),i={},r=!1;for(var s of Object.entries(n)){var o=s[0],a=s[1];e.includes(o)?r=!0:i[o]=a}r&&(Vt(i)?this.Es():this.Ts(i))}}Ks(){this.Ms()&&this.Es()}getActivationTimestamp(e){if(this.zs().includes(e)){var n=this.Qs()[e];return xe(n)?n:void 0}}Zs(){var e,n=this.Js();return((e=this._instance)==null||(e=e.persistence)==null?void 0:e.props[n])||[]}zs(){var e,n,i=this.Zs();if(i.length===0)return[];var r=(e=this._instance)==null||(e=e.persistence)==null?void 0:e.props[this.Ys()],s=(n=this._instance)==null||n.get_session_id==null?void 0:n.get_session_id();return s&&r===s?i:[]}Vs(){var e,n=(e=this._instance)==null||e.get_session_id==null?void 0:e.get_session_id();n&&this.Xs(n)}Gs(){this.ta()}Ss(e){var n,i=(n=this._instance)==null||(n=n.persistence)==null?void 0:n.props[this.Ys()];if(i&&i!==e){var r=this.Zs(),s=this.Qs();r.length>0&&(this.Ws([]),r.filter((o=>xe(s[o]))).forEach((o=>this.Bs(o)))),this.Gs(),this.Ks()}}getActivatedIds(){return[...new Set([...this.zs(),...this._s])].filter((e=>!this.ea(e)))}reset(){this._s=[],this.Zs().length>0&&this.Ws([]),this.Gs(),this.Ks()}getEventToItemsMap(){return this.ws}ia(){return this.Os}}class Am extends Cm{constructor(e){super(e)}Js(){return la}Ys(){return Ir}Ms(){return kr}Ts(e){var n;(n=this._instance)==null||(n=n.persistence)==null||n.register({[kr]:e})}Es(){var e;(e=this._instance)==null||(e=e.persistence)==null||e.unregister(kr)}Cs(e){var n,i;this.As((s=>{i=s.find((o=>o.id===e))}));var r=(n=i)==null||(n=n.appearance)==null?void 0:n.surveyPopupDelaySeconds;return xe(r)&&r>0}ra(){return qt.SHOWN}As(e){var n;(n=this._instance)==null||n.getSurveys(e)}Bs(e){var n;(n=this._instance)==null||n.cancelPendingSurvey(e)}Ds(){return X}Ws(e){var n;(n=this._instance)==null||(n=n.persistence)==null||n.register({[la]:e})}Xs(e){var n;(n=this._instance)==null||(n=n.persistence)==null||n.register({[Ir]:e})}ta(){var e;(e=this._instance)==null||(e=e.persistence)==null||e.unregister(Ir)}ea(){return!1}$s(e,n){var i;this.As((s=>{i=s.find((o=>o.id===n))}));var r=!i||(function(s){var o;return Lf(s)&&!((o=s.conditions)==null||(o=o.events)==null||!o.repeatedActivation)||s.schedule==="always"})(i);return r?e===qt.SHOWN?"consume":"ignore":e===qt.SHOWN?"persist":e===qt.DISMISSED||e===qt.SENT?"consume":"ignore"}getSurveys(){return this.getActivatedIds()}getEventToSurveys(){return this.getEventToItemsMap()}}var wr="SDK is not enabled or survey functionality is not yet loaded",au="Disabled. Not loading surveys.",Pm=w!=null&&w.location?ts(w.location.hash,"__posthog")||ts(location.hash,"state"):null,lu="_postHogToolbarParams",cu=he("[Toolbar]"),uu=he("[FeatureFlags]");class Fm{constructor(e,n){n===void 0&&(n=!1),this.na=!1,this.update(e,n)}update(e,n){this.sa=((i,r)=>{var s,o,a,l;return{bootstrap:{featureFlags:(s=i.bootstrap)==null?void 0:s.featureFlags,featureFlagPayloads:(o=i.bootstrap)==null?void 0:o.featureFlagPayloads},remoteRequestsDisabled:r,featureFlagsDisabled:!!i.advanced_disable_feature_flags,onlyEvaluateSurveyFeatureFlags:!!i.advanced_only_evaluate_survey_feature_flags,deduplicateCallsPerSession:!!i.advanced_feature_flags_dedup_per_session,cacheTtlMs:i.feature_flag_cache_ttl_ms,requestTimeoutMs:i.feature_flag_request_timeout_ms,compression:i.disable_compression?"none":"base64",evaluationContexts:(a=(l=i.evaluation_contexts)!==null&&l!==void 0?l:i.evaluation_environments)!==null&&a!==void 0?a:[],flagKeys:U(i.flag_keys)?i.flag_keys:void 0}})(e,n),!e.evaluation_environments||e.evaluation_contexts||this.na||(uu.warn("evaluation_environments is deprecated. Use evaluation_contexts instead. evaluation_environments will be removed in a future version."),this.na=!0),C(e.flag_keys)||U(e.flag_keys)||uu.error("Invalid flag_keys found:",e.flag_keys,"Expected array of non-empty strings")}get(){return this.sa}}var du=he("[FeatureFlags]"),_n=he("[FeatureFlags]",{debugEnabled:!0}),Oo=`" failed. Feature flags didn't load in time.`,fu="connection_error",hu=t=>{for(var e={},n=0;t.length>n;n++)e[t[n]]=!0;return e},pu=t=>{var e={};for(var n of Ar(t||{})){var i=n[1];i&&(e[n[0]]=i)}return e},bt=he("[Error tracking]"),gu="Refusing to render web experiment since the viewer is a likely bot",Rm={icontains:(t,e)=>e.toLowerCase().indexOf(t.toLowerCase())>-1,not_icontains:(t,e)=>e.toLowerCase().indexOf(t.toLowerCase())===-1,regex:(t,e)=>rs(e,t),not_regex:(t,e)=>!rs(e,t),exact:(t,e)=>e===t,is_not:(t,e)=>e!==t};class Me{get Ne(){return this._instance.config}constructor(e){var n=this;this.getWebExperimentsAndEvaluateDisplayLogic=function(i){i===void 0&&(i=!1),n.getWebExperiments((r=>{Me.aa("retrieved web experiments from the server"),n.oa=new Map,r.forEach((s=>{if(s.feature_flag_key){var o;n.oa&&(Me.aa("setting flag key ",s.feature_flag_key," to web experiment ",s),(o=n.oa)==null||o.set(s.feature_flag_key,s));var a=n._instance.getFeatureFlag(s.feature_flag_key);Z(a)&&s.variants[a]&&n.la(s.name,a,s.variants[a].transforms)}else if(s.variants)for(var l in s.variants){var u=s.variants[l];Me.ua(u,n._instance)&&n.la(s.name,l,u.transforms)}}))}),i)},this._instance=e,this._instance.onFeatureFlags((i=>{this.onFeatureFlags(i)}))}initialize(){}onFeatureFlags(e){if(this._is_bot())Me.aa(gu);else if(!this.Ne.disable_web_experiments){if(H(this.oa))return this.oa=new Map,this.loadIfEnabled(),void this.previewWebExperiment();Me.aa("applying feature flags",e),e.forEach((n=>{var i;if(this.oa&&(i=this.oa)!=null&&i.has(n)){var r,s=this._instance.getFeatureFlag(n),o=(r=this.oa)==null?void 0:r.get(n);s&&o!=null&&o.variants[s]&&this.la(o.name,s,o.variants[s].transforms)}}))}}previewWebExperiment(){var e=Me.getWindowLocation();if(e!=null&&e.search){var n=ei(e?.search,"__experiment_id"),i=ei(e?.search,"__experiment_variant");n&&i&&(Me.aa("previewing web experiments "+n+" && "+i),this.getWebExperiments((r=>{this.ha(parseInt(n),i,r)}),!1,!0))}}loadIfEnabled(){this.Ne.disable_web_experiments||this.getWebExperimentsAndEvaluateDisplayLogic()}getWebExperiments(e,n,i){if(this.Ne.disable_web_experiments&&!i)return e([]);var r=this._instance.get_property("$web_experiments");if(r&&!n)return e(r);this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/web_experiments/?token="+this.Ne.token),method:"GET",timestampMode:"query",callback:s=>e(s.statusCode===200&&s.json&&s.json.experiments||[])})}ha(e,n,i){var r=i.filter((s=>s.id===e));r&&r.length>0&&(Me.aa("Previewing web experiment ["+r[0].name+"] with variant ["+n+"]"),this.la(r[0].name,n,r[0].variants[n].transforms))}static ua(e,n){return!H(e.conditions)&&Me.da(e,n)&&Me.va(e)}static da(e,n){var i;if(H(e.conditions)||H((i=e.conditions)==null?void 0:i.url))return!0;var r=Me.getWindowLocation();if(r){var s,o,a,l=Jd(n,r.href);return(s=e.conditions)==null||!s.url||Rm[(o=(a=e.conditions)==null?void 0:a.urlMatchType)!==null&&o!==void 0?o:"icontains"](e.conditions.url,l)}return!1}static getWindowLocation(){return w?.location}static va(e){var n;if(H(e.conditions)||H((n=e.conditions)==null?void 0:n.utm))return!0;var i=ff();if(i.utm_source){var r,s,o,a,l,u,c,d,f=(r=e.conditions)==null||(r=r.utm)==null||!r.utm_campaign||((s=e.conditions)==null||(s=s.utm)==null?void 0:s.utm_campaign)==i.utm_campaign,h=(o=e.conditions)==null||(o=o.utm)==null||!o.utm_source||((a=e.conditions)==null||(a=a.utm)==null?void 0:a.utm_source)==i.utm_source,p=(l=e.conditions)==null||(l=l.utm)==null||!l.utm_medium||((u=e.conditions)==null||(u=u.utm)==null?void 0:u.utm_medium)==i.utm_medium,g=(c=e.conditions)==null||(c=c.utm)==null||!c.utm_term||((d=e.conditions)==null||(d=d.utm)==null?void 0:d.utm_term)==i.utm_term;return f&&p&&g&&h}return!1}static aa(e){for(var n=arguments.length,i=new Array(n>1?n-1:0),r=1;n>r;r++)i[r-1]=arguments[r];A.info("[WebExperiments] "+e,i)}la(e,n,i){this._is_bot()?Me.aa(gu):n!=="control"?i.forEach((r=>{if(r.selector){var s;Me.aa("applying transform of variant "+n+" for experiment "+e+" ",r);var o=(s=document)==null?void 0:s.querySelectorAll(r.selector);o?.forEach((a=>{var l=a;r.html&&(l.innerHTML=r.html),r.css&&l.setAttribute("style",r.css)}))}})):Me.aa("Control variants leave the page unmodified.")}_is_bot(){return je&&this._instance?Rf(je,this.Ne.custom_blocked_useragents):void 0}}var rt=he("[Conversations]"),yn="Conversations not available yet.",mu="console",jf="__posthogHandledLogsRequestError",Bo=(t,e)=>{var n=t instanceof Error?t:new Error(e);return n[jf]=!0,n},vu=t=>!!t&&typeof t=="object"&&t[jf]===!0,xs={featureFlags:class{constructor(t){this.name="featureFlags",this.ca=!1,this.featureFlagEventHandlers=[],this.rt=du,this.fa={},this.pa={},this.ga=[],this.ma=!1,this.ya=!1,this.ba=0,this._a=!1,this.wa=!1,this.ka=!1,this.xa=!1,this.Sa=0,this.Ca=()=>{var e=this.Ma();this.Sa=0,e&&this.reloadFeatureFlags()},"get"in t?this.Ta=t:(this.Ea=new Fm(t.config,t.Qi()),this.Ta=this.Ea)}updateConfig(t,e){var n;(n=this.Ea)==null||n.update(t,e)}setup(t){return this.Ia=t,this.rt=t.logger.createLogger("[FeatureFlags]"),n=()=>{this.Ia===t&&(this.Ia=void 0,this.nn=t,this.Pa(t))},(e=t.kv.initialize())!=null&&e.then?e.then(n):n();var e,n}Pa(t){if(this.nn===t)return w&&me(w,"online",this.Ca),this.Ra=t.registerDynamicEventProperties((()=>this.Aa()?this.fa:this.pa)),this.Fa(),this.initialize()}destroy(){w?.removeEventListener("online",this.Ca)}dispose(){var t;this.ba++,this.wa=!1,this.Ia=void 0,this.nn&&(this.La(),(t=this.Ra)==null||t.dispose(),this.Ra=void 0,this.ga=[],w?.removeEventListener("online",this.Ca),this.nn=void 0)}get Ne(){return this.Ta.get()}Oa(t){var e;return(e=this.nn)==null?void 0:e.kv.get(t)}F(t){this.Da((()=>{var e;return(e=this.nn)==null?void 0:e.kv.set(t)}))}q(t){this.Da((()=>{var e;return(e=this.nn)==null?void 0:e.kv.remove(t)}))}Da(t){try{t()}catch(e){this.rt.error("Failed to update feature flag persistence",e)}}Fa(){var t={};for(var e of[Pi,Fi,xr,St]){var n=this.Oa(e);C(n)||(t[e]=n)}this.fa=t;var i=k({},t),r=this.Oa(wn);if(r)for(var s of Object.entries(r))i["$feature/"+s[0]]=s[1];this.pa=i}Aa(){var t=this.Ne.cacheTtlMs;if(!t||0>=t)return!1;var e=this.Oa(Oi);return typeof e!="number"||Date.now()-e>t}$a(){return!!this.Aa()&&(this.xa||this.ya||(this.xa=!0,this.rt.warn("Feature flag cache is stale, triggering refresh..."),this.reloadFeatureFlags()),!0)}Na(){var t=this.Ne.evaluationContexts;return t!=null&&t.length?t.filter((e=>{var n=e&&typeof e=="string"&&e.trim().length>0;return n||this.rt.error("Invalid evaluation context found:",e,"Expected non-empty string"),n})):[]}qa(){var t=this.Ne.flagKeys;if(!C(t))return t.filter((e=>{var n=e&&typeof e=="string"&&e.trim().length>0;return n||this.rt.error("Invalid flag key found:",e,"Expected non-empty string"),n}))}initialize(){var t,e,n=this.Ne,i=(t=(e=n.bootstrap)==null?void 0:e.featureFlags)!==null&&t!==void 0?t:{};if(Object.keys(i).length){var r,s,o=(r=(s=n.bootstrap)==null?void 0:s.featureFlagPayloads)!==null&&r!==void 0?r:{},a=Object.keys(i).filter((u=>!!i[u])).reduce(((u,c)=>(u[c]=i[c]||!1,u)),{}),l=Object.keys(o).filter((u=>a[u])).reduce(((u,c)=>(o[c]&&(u[c]=o[c]),u)),{});return this.ja({featureFlags:a,featureFlagPayloads:l})}}updateFlags(t,e,n){var i,r,s=n!=null&&n.merge&&(i=this.Oa(wn))!==null&&i!==void 0?i:{},o=n!=null&&n.merge&&(r=this.Oa(Fi))!==null&&r!==void 0?r:{},a=k({},s,t),l=k({},o,e),u={};for(var c of Object.entries(a)){var d=c[0],f=c[1];u[d]={key:d,enabled:cc(f),variant:uc(f),reason:void 0,metadata:C(l?.[d])?void 0:{id:0,version:void 0,description:void 0,payload:l[d]}}}this.ja({flags:u})}get hasLoadedFlags(){return this.ma}getFlags(){return Object.keys(this.getFlagVariants())}getFlagsWithDetails(){var t=this.Oa(oa),e=this.Oa(St),n=this.Oa(bn);if(!n&&!e)return t||{};var i=ue({},t||{}),r=[...new Set([...Object.keys(n||{}),...Object.keys(e||{})])];for(var s of r){var o,a,l=i[s],u=e?.[s],c=C(u)?(o=l?.enabled)!==null&&o!==void 0&&o:!!u,d=C(u)?l?.variant:typeof u=="string"?u:void 0,f=n?.[s],h=k({},l,{enabled:c,variant:c?d??l?.variant:void 0});c!==l?.enabled&&(h.original_enabled=l?.enabled),d!==l?.variant&&(h.original_variant=l?.variant),f&&(h.metadata=k({},l?.metadata,{payload:f,original_payload:l==null||(a=l.metadata)==null?void 0:a.payload})),i[s]=h}return this.ca||(this.rt.warn(" Overriding feature flag details!",{flagDetails:t,overriddenPayloads:n,finalDetails:i}),this.ca=!0),i}getAllFeatureFlags(){var t=this.getFlagVariants(),e=this.getFlagPayloads();return Object.keys(t).map((n=>{var i=t[n];return{key:n,enabled:cc(i),variant:uc(i),payload:lc(e[n])}}))}getFlagVariants(){var t=this.Oa(wn),e=this.Oa(St);if(!e)return t||{};for(var n=ue({},t||{}),i=Object.keys(e),r=0;i.length>r;r++)n[i[r]]=e[i[r]];return this.ca||(this.rt.warn(" Overriding feature flags!",{enabledFlags:t,overriddenFlags:e,finalFlags:n}),this.ca=!0),n}getFlagPayloads(){var t=this.Oa(Fi),e=this.Oa(bn);if(!e)return t||{};for(var n=ue({},t||{}),i=Object.keys(e),r=0;i.length>r;r++)n[i[r]]=e[i[r]];return this.ca||(this.rt.warn(" Overriding feature flag payloads!",{flagPayloads:t,overriddenPayloads:e,finalPayloads:n}),this.ca=!0),n}reloadFeatureFlags(){this._a||this.Ne.featureFlagsDisabled||this.Ma()||this.Ba||(this.ga.slice().forEach((t=>{try{t()}catch(e){this.rt.error("Error while running feature flags reloading callback",e)}})),this.Ba=setTimeout((()=>{this.Ha()}),5))}La(){clearTimeout(this.Ba),this.Ba=void 0}onReloading(t){return this.ga.push(t),()=>{this.ga=this.ga.filter((e=>e!==t))}}ensureFlagsLoaded(){this.ma||this.ya||this.Ba||this.reloadFeatureFlags()}setAnonymousDistinctId(t){this.$anon_distinct_id=t}setReloadingPaused(t){this._a=t}resetFlagCallReported(){this.q(xn)}Ha(t){this.La();var e=this.nn;if(e&&!this.Ne.remoteRequestsDisabled&&!this.Ma())if(this.ya)this.wa=!0;else{var n={token:e.projectToken,distinct_id:e.distinctId,groups:e.groups,$anon_distinct_id:this.$anon_distinct_id,person_properties:k({},e.initialPersonProperties,this.Oa(Dt)||{},{$lib:e.library.name,$lib_version:e.library.version}),group_properties:this.Oa(En),timezone:_f()};C(e.deviceId)||(n.$device_id=e.deviceId),(t!=null&&t.disableFlags||this.Ne.featureFlagsDisabled)&&(n.disable_flags=!0);var i=this.Na();i.length&&(n.evaluation_contexts=i);var r=this.qa();C(r)||(n.flag_keys=r);var s=this.Ne.onlyEvaluateSurveyFeatureFlags,o="/flags/?v=2"+(s?"&only_evaluate_survey_feature_flags=true":""),a=this.ba;this.ya=!0;var l=()=>{this.wa&&(this.wa=!1,this.Ha())},u=c=>{this.ya=!1,a===this.ba&&(this.F({[Cr]:[fu]}),this.rt.error("Feature flag request failed",c)),l()};try{e.sendRequest(o,{target:"flags",method:"POST",body:n,compression:this.Ne.compression==="base64"?De.Base64:void 0,sentAt:"body",timeoutMs:this.Ne.requestTimeoutMs}).then((c=>{var d,f,h=(d=c.json)!==null&&d!==void 0?d:{},p=c.statusCode!==200;if(this.ya=!1,a===this.ba){if(this.Ua(c.statusCode),p||this.wa||(this.$anon_distinct_id=void 0),!n.disable_flags||this.wa){this.ka=!p;var g=[];c.error?g.push(c.error instanceof Error&&c.error.name==="AbortError"?"timeout":c.error instanceof Error?fu:"unknown_error"):c.statusCode!==200&&g.push("api_error_"+c.statusCode),h.errorsWhileComputingFlags&&g.push("errors_while_computing_flags");var m=!((f=h.quotaLimited)==null||!f.includes("feature_flags"));m&&g.push("quota_limited"),this.F({[Cr]:g}),m?this.rt.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."):n.disable_flags||this.ja(h,p,{partialResponse:s}),l()}}else l()})).catch(u)}catch(c){u(c)}}}Ma(){return uf(this.Sa,3)}Ua(t){this.Sa=df(t,this.Sa,3,(()=>this.rt.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===void 0&&(e={}),!e.fresh||this.ka)if(this.ma||this.getFlags()&&this.getFlags().length>0){if(!this.$a()){var i=this.getFeatureFlagResult(t,e);return(n=i?.variant)!==null&&n!==void 0?n:i?.enabled}}else this.rt.warn('getFeatureFlag for key "'+t+Oo)}getFeatureFlagDetails(t){return this.getFlagsWithDetails()[t]}getFeatureFlagPayload(t){var e=this.getFeatureFlagResult(t,{send_event:!1});return e?.payload}getFeatureFlagResult(t,e){if(e===void 0&&(e={}),!e.fresh||this.ka)if(this.ma||this.getFlags()&&this.getFlags().length>0){if(!this.$a()){var n,i=this.getFlagVariants(),r=t in i,s=i[t],o=this.getFlagPayloads()[t],a=String(s),l=this.Oa(xr)||void 0,u=this.Oa(Oi)||void 0,c=this.Oa(xn)||{};if(this.Ne.deduplicateCallsPerSession){var d,f=(d=this.nn)==null?void 0:d.session.sessionId,h=this.Oa(Ti);f&&f!==h&&(c={},n=f)}if(e.send_event||!("send_event"in e))if(t in c&&c[t].includes(a))n&&this.F({[xn]:c,[Ti]:n});else{var p,g,m,v,E,S,_,x,I,M;U(c[t])?c[t].push(a):c[t]=[a],this.F(k({[xn]:c},n?{[Ti]:n}:{}));var b=this.getFeatureFlagDetails(t),P=[...(p=this.Oa(Cr))!==null&&p!==void 0?p:[]];C(s)&&P.push("flag_missing");var R={$feature_flag:t,$feature_flag_response:s,$feature_flag_payload:o||null,$feature_flag_request_id:l,$feature_flag_evaluated_at:u,$feature_flag_bootstrapped_response:((g=this.Ne.bootstrap)==null||(g=g.featureFlags)==null?void 0:g[t])||null,$feature_flag_bootstrapped_payload:((m=this.Ne.bootstrap)==null||(m=m.featureFlagPayloads)==null?void 0:m[t])||null,$used_bootstrap_value:!this.ka};C(b==null||(v=b.metadata)==null?void 0:v.has_experiment)||(R.$feature_flag_has_experiment=b.metadata.has_experiment),C(b==null||(E=b.metadata)==null?void 0:E.version)||(R.$feature_flag_version=b.metadata.version);var N,L=(S=b==null||(_=b.reason)==null?void 0:_.description)!==null&&S!==void 0?S:b==null||(x=b.reason)==null?void 0:x.code;L&&(R.$feature_flag_reason=L),b!=null&&(I=b.metadata)!=null&&I.id&&(R.$feature_flag_id=b.metadata.id),C(b?.original_variant)&&C(b?.original_enabled)||(R.$feature_flag_original_response=C(b.original_variant)?b.original_enabled:b.original_variant),b!=null&&(M=b.metadata)!=null&&M.original_payload&&(R.$feature_flag_original_payload=b==null||(N=b.metadata)==null?void 0:N.original_payload),P.length&&(R.$feature_flag_error=P.join(",")),this.za(R)}else n&&this.F({[xn]:c,[Ti]:n});if(r)return{key:t,enabled:!!s,variant:typeof s=="string"?s:void 0,payload:lc(o)}}}else this.rt.warn('getFeatureFlagResult for key "'+t+Oo)}za(t){try{var e;(e=this.nn)==null||e.capture("$feature_flag_called",t).catch((n=>{this.rt.error("Failed to capture feature flag call",n)}))}catch(n){this.rt.error("Failed to capture feature flag call",n)}}getRemoteConfigPayload(t,e){this.Wa(t,e)}Wa(t,e){var n=this;return re((function*(){var i=n.nn;if(i){var r={distinct_id:i.distinctId,token:i.projectToken,person_properties:{$lib:i.library.name,$lib_version:i.library.version}},s=n.Na();s.length&&(r.evaluation_contexts=s);var o,a=n.qa();C(a)||(r.flag_keys=a);try{var l,u=(l=(yield i.sendRequest("/flags/?v=2",{target:"flags",method:"POST",body:r,compression:n.Ne.compression==="base64"?De.Base64:void 0,sentAt:"body",timeoutMs:n.Ne.requestTimeoutMs})).json)==null?void 0:l.featureFlagPayloads;o=u?.[t]||void 0}catch(c){return void n.rt.error("Remote config feature flag request failed",c)}try{e(o)}catch(c){n.rt.error("Remote config feature flag callback failed",c)}}}))()}isFeatureEnabled(t,e){if(e===void 0&&(e={}),e.fresh&&!this.ka)return e.defaultValue;if(!(this.ma||this.getFlags()&&this.getFlags().length>0))return this.rt.warn('isFeatureEnabled for key "'+t+Oo),e.defaultValue;var n=this.getFeatureFlag(t,e);return C(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.ja(t,e,n)}ja(t,e,n){if(this.nn){this.ma=!0;var i=(function(r,s,o,a,l,u){s===void 0&&(s={}),o===void 0&&(o={}),a===void 0&&(a={}),u===void 0&&(u=du);var c=((I,M)=>{var b=I.flags;return b?k({},I,{featureFlags:Object.fromEntries(Object.keys(b).map((P=>{var R;return[P,(R=b[P].variant)!==null&&R!==void 0?R:b[P].enabled]}))),featureFlagPayloads:Object.fromEntries(Object.keys(b).filter((P=>b[P].enabled)).filter((P=>{var R;return(R=b[P].metadata)==null?void 0:R.payload})).map((P=>{var R;return[P,(R=b[P].metadata)==null?void 0:R.payload]})))}):(I.featureFlags&&M.warn("Using an older version of the feature flags endpoint. Please upgrade your PostHog server to the latest version"),I)})(r,u),d=c.flags,f=c.featureFlags,h=c.featureFlagPayloads;if(f){var p=r.requestId,g=r.evaluatedAt;if(U(f)){u.warn("v1 of the feature flags endpoint is deprecated. Please use the latest version.");var m={};if(f)for(var v=0;f.length>v;v++)m[f[v]]=!0;return{[Pi]:f,[wn]:m,[Vr]:!1}}var E=f,S=h,_=d;if(l!=null&&l.partialResponse)E=k({},s,E),S=k({},o,S),_=k({},a,_);else if(r.errorsWhileComputingFlags)if(d){var x=new Set(Object.keys(d).filter((I=>{var M;return!((M=d[I])!=null&&M.failed)})));E=k({},s,Object.fromEntries(Object.entries(E).filter((I=>x.has(I[0]))))),S=k({},o,Object.fromEntries(Object.entries(S||{}).filter((I=>x.has(I[0]))))),_=k({},a,Object.fromEntries(Object.entries(_||{}).filter((I=>x.has(I[0])))))}else E=k({},s,E),S=k({},o,S),_=k({},a,_);return k({[Pi]:Object.keys(pu(E)),[wn]:E||{},[Fi]:S||{},[oa]:_||{},[Vr]:r.minimalFlagCalledEvents===!0},p?{[xr]:p}:{},g?{[Oi]:g}:{})}})(t,this.getFlagVariants(),this.getFlagPayloads(),this.getFlagsWithDetails(),n,this.rt);i&&this.F(i),e||(this.xa=!1),this.Va(e)}}override(t,e){e===void 0&&(e=!1),this.rt.warn("override is deprecated. Please use overrideFeatureFlags instead."),this.overrideFeatureFlags({flags:t,suppressWarning:e})}overrideFeatureFlags(t){this.Za(t)}Za(t){if(this.nn){if(t===!1)return this.q([St,bn]),this.Va(),void _n.info("All overrides cleared");if(U(t))return this.F({[St]:hu(t)}),this.Va(),void _n.info("Flag overrides set",{flags:t});if(t&&typeof t=="object"&&("flags"in t||"payloads"in t)){var e,n=t;this.ca=!!((e=n.suppressWarning)!==null&&e!==void 0&&e);var i={},r=n.flags,s=n.payloads;return r&&(i[St]=U(r)?hu(r):r),s&&(i[bn]=s),Object.keys(i).length&&this.F(i),r===!1&&s===!1?this.q([St,bn]):r===!1?this.q(St):s===!1&&this.q(bn),this.Va(),r===!1?_n.info("Flag overrides cleared"):r&&_n.info("Flag overrides set",{flags:r}),void(s===!1?_n.info("Payload overrides cleared"):s&&_n.info("Payload overrides set",{payloads:s}))}if(t&&typeof t=="object")return this.F({[St]:t}),this.Va(),void _n.info("Flag overrides set",{flags:t});this.rt.warn("Invalid overrideOptions provided to overrideFeatureFlags",{overrideOptions:t})}else this.rt.warn("posthog.featureFlags.overrideFeatureFlags called before feature flags were ready")}onFeatureFlags(t){if(this.addFeatureFlagsHandler(t),this.ma){var e=this.Ga(),n=e.flags,i=e.flagVariants;try{t(n,i)}catch(r){this.rt.error("Error while running feature flags callback",r)}}return()=>this.removeFeatureFlagsHandler(t)}updateEarlyAccessFeatureEnrollment(t,e,n){var i=(this.Oa(Sr)||[]).find((l=>l.flagKey===t)),r={["$feature_enrollment/"+t]:e},s={$feature_flag:t,$feature_enrollment:e,$set:r};i&&(s.$early_access_feature_name=i.name),n&&(s.$feature_enrollment_stage=n);var o=k({},this.getFlagVariants(),{[t]:e});this.F({[Pi]:Object.keys(pu(o)),[wn]:o,[Dt]:k({},this.Oa(Dt)||{},r)}),this.Va();try{var a;(a=this.nn)==null||a.capture("$feature_enrollment_update",s).catch((l=>{this.rt.error("Failed to capture early access feature enrollment",l)}))}catch(l){this.rt.error("Failed to capture early access feature enrollment",l)}}getEarlyAccessFeatures(t,e,n){e===void 0&&(e=!1);var i=this.Oa(Sr);!i||e?this.Qa(t,n):t(i)}Qa(t,e){var n=this;return re((function*(){var i=n.nn;if(i){var r,s=e?"&"+e.map((a=>"stage="+a)).join("&"):"";try{var o=yield i.sendRequest("/api/early_access_features/?token="+i.projectToken+s,{target:"api",method:"GET",sentAt:"query"});if(!o.json)return;n.F({[Sr]:r=o.json.earlyAccessFeatures})}catch(a){return void n.rt.error("Early access feature request failed",a)}try{t(r)}catch(a){n.rt.error("Early access feature callback failed",a)}}}))()}Ga(){var t=this.getFlags(),e=this.getFlagVariants();return{flags:t.filter((n=>e[n])),flagVariants:Object.keys(e).filter((n=>e[n])).reduce(((n,i)=>(n[i]=e[i],n)),{})}}Va(t){this.Fa();var e=this.Ga(),n=e.flags,i=e.flagVariants;this.featureFlagEventHandlers.forEach((r=>{try{r(n,i,{errorsLoading:t})}catch(s){this.rt.error("Error while running feature flags callback",s)}}))}setPersonPropertiesForFlags(t,e){e===void 0&&(e=!0),this.Ka(t,e)}Ka(t,e){e===void 0&&(e=!0);var n=this.Oa(Dt)||{},i=t?.$set||(t!=null&&t.$set_once?{}:t),r=t?.$set_once,s={};if(r)for(var o in r)({}).hasOwnProperty.call(r,o)&&(o in n||(s[o]=r[o]));this.F({[Dt]:k({},n,s,i)}),e&&this.reloadFeatureFlags()}unsetPersonPropertiesForFlags(t,e){e===void 0&&(e=!0);var n=k({},this.Oa(Dt)||{});t.forEach((i=>{delete n[i]})),this.F({[Dt]:n}),e&&this.reloadFeatureFlags()}resetPersonPropertiesForFlags(t){t===void 0&&(t=!0),this.q(Dt),t&&this.reloadFeatureFlags()}setGroupPropertiesForFlags(t,e){e===void 0&&(e=!0);var n=this.Oa(En)||{},i=k({},n);for(var r of Object.keys(t))i[r]=k({},n[r],t[r]);this.F({[En]:i}),e&&this.reloadFeatureFlags()}resetGroupPropertiesForFlags(t){if(t){var e=this.Oa(En)||{};this.F({[En]:k({},e,{[t]:{}})})}else this.q(En)}reset(){this.ba++,this.wa=!1,this.Fa(),this.ma=!1,this._a=!1,this.ka=!1,this.$anon_distinct_id=void 0,this.La(),this.ca=!1,this.Sa=0}}},Tm={sessionRecording:class{get Ne(){return this._instance.config}get Mr(){return this._instance.persistence}get started(){var t;return!((t=this.Ja)==null||!t.isStarted)}get status(){var t,e;return this.Ya===Si||this.Ya===_r?this.Ya:(t=(e=this.Ja)==null?void 0:e.status)!==null&&t!==void 0?t:this.Ya}constructor(t){if(this._forceAllowLocalhostNetworkCapture=!1,this.Ya=ru,this.Xa=void 0,this.eo=!1,this.io=(()=>{var e;if(F==null||!F.visibilityState||F.visibilityState==="visible")return!0;var n=w==null||(e=w.performance)==null||e.getEntriesByType==null?void 0:e.getEntriesByType("visibility-state");return!(n!=null&&n.length)||n.some((i=>i.name==="visible"))})(),this.Ie=()=>{var e;F?.visibilityState==="visible"&&(this.io=!0,(e=this.Ja)==null||e.setDocumentWasEverVisible==null||e.setDocumentWasEverVisible(!0))},this._instance=t,!this._instance.sessionManager)throw Ot.error("started without valid sessionManager"),new Error(xa+" started without valid sessionManager. This is a bug.");if(this.Ne.cookieless_mode===Ht)throw new Error(xa+' cannot be used with cookieless_mode="always"');F!=null&&F.addEventListener&&me(F,"visibilitychange",this.Ie)}initialize(){this.startIfEnabledOrStop()}dispose(){this.eo=!0,F==null||F.removeEventListener==null||F.removeEventListener("visibilitychange",this.Ie),this.stopRecording()}get ro(){var t,e=!((t=this._instance.get_property(In))==null||!t.enabled),n=!this.Ne.disable_session_recording,i=this.Ne.disable_session_recording||this._instance.consent.isOptedOut();return w&&e&&n&&!i}startIfEnabledOrStop(t){var e;if(!(this.eo||this.ro&&(e=this.Ja)!=null&&e.isStarted)){var n=!C(Object.assign)&&!C(Array.from);this.ro&&n?(this.no(t),Ot.info("starting")):(this.Ya=ru,this.stopRecording())}}no(t){var e,n,i;this.ro&&(this.Ya!==Si&&this.Ya!==_r&&(this.Ya=su),O!=null&&(e=O.__PosthogExtensions__)!=null&&(e=e.rrweb)!=null&&e.record&&(n=O.__PosthogExtensions__)!=null&&n.initSessionRecording?this.so(t):(i=O.__PosthogExtensions__)==null||i.loadExternalDependency==null||i.loadExternalDependency(this._instance,this.ao,(r=>{if(r)return Ot.error("could not load recorder",r);this.so(t)})))}stopRecording(){var t,e;(t=this.Xa)==null||t.call(this),this.Xa=void 0,(e=this.Ja)==null||e.stop()}oo(){var t,e;(t=this.Xa)==null||t.call(this),this.Xa=void 0,(e=this.Ja)==null||e.discard()}lo(){var t,e;(t=this.Mr)==null||t.unregister(rl),(e=this.Mr)==null||e.unregister(Dd)}uo(t,e){if(H(t))return null;var n,i=xe(t)?t:parseFloat(t);return typeof(n=i)!="number"||!Number.isFinite(n)||0>n||n>1?(Ot.warn(e+" must be between 0 and 1. Ignoring invalid value:",t),null):i}ho(t){if(this.Mr){var e,n,i=this.Mr,r=()=>{var s,o=t.sessionRecording===!1?void 0:t.sessionRecording,a=this.uo((s=this.Ne.session_recording)==null?void 0:s.sampleRate,"session_recording.sampleRate"),l=this.uo(o?.sampleRate,"remote config sampleRate"),u=a??l;H(u)&&this.lo();var c=o?.minimumDurationMilliseconds;i.register({[In]:k({cache_timestamp:Date.now(),enabled:!!o},o,{networkPayloadCapture:k({capturePerformance:t.capturePerformance},o?.networkPayloadCapture),canvasRecording:{enabled:o?.recordCanvas,fps:o?.canvasFps,quality:o?.canvasQuality},sampleRate:u,minimumDurationMilliseconds:C(c)?null:c,endpoint:o?.endpoint,triggerMatchType:o?.triggerMatchType,masking:o?.masking,urlTriggers:o?.urlTriggers,version:o?.version,triggerGroups:o?.triggerGroups})})};r(),(e=this.Xa)==null||e.call(this),this.Xa=(n=this._instance.sessionManager)==null?void 0:n.onSessionId(r)}}onRemoteConfig(t){var e=t.ok?t.config:void 0;return e&&"sessionRecording"in e?e.sessionRecording===!1?(this.ho(e),void this.oo()):(this.ho(e),void this.startIfEnabledOrStop()):(this.Ya===Si&&(this.Ya=_r,Ot.warn("config refresh failed, recording will not start until page reload")),void this.startIfEnabledOrStop())}log(t,e){var n;e===void 0&&(e="log"),(n=this.Ja)!=null&&n.log?this.Ja.log(t,e):Ot.warn("log called before recorder was ready")}get ao(){var t,e,n=(t=this._instance)==null||(t=t.persistence)==null?void 0:t.get_property(In);return(n==null||(e=n.scriptConfig)==null?void 0:e.script)||"lazy-recorder"}do(){var t,e=this._instance.get_property(In);if(!e)return!1;try{t=typeof e=="object"?e:JSON.parse(e)}catch(n){return Ot.warn("persisted remote config for session recording is invalid and will be ignored",n),!1}return!H(t.cache_timestamp)&&36e5>=Date.now()-t.cache_timestamp}so(t){var e,n,i;if(!this.eo){if((e=O.__PosthogExtensions__)==null||!e.initSessionRecording)return Ot.warn("Called on script loaded before session recording is available. This can be caused by adblockers."),void this._instance.register_for_session({[Gd]:!0});var r;if(this.Ja||(this.Ja=(r=O.__PosthogExtensions__)==null?void 0:r.initSessionRecording(this._instance,this.io),this.Ja._forceAllowLocalhostNetworkCapture=this._forceAllowLocalhostNetworkCapture),!this.do())return this.Ya===_r||this.Ya===Si?void 0:(this.Ya=Si,Ot.info("persisted remote config is stale, requesting fresh config before starting"),void new yf(this._instance).load());this.Ya=su,(n=(i=this.Ja).setDocumentWasEverVisible)==null||n.call(i,this.io),this.Ja.start(t)}}onRRwebEmit(t){var e;(e=this.Ja)==null||e.onRRwebEmit==null||e.onRRwebEmit(t)}overrideLinkedFlag(){var t,e;this.Ja||(e=this.Mr)==null||e.register({[Ud]:!0}),(t=this.Ja)==null||t.overrideLinkedFlag()}overrideSampling(){var t,e;this.Ja||(e=this.Mr)==null||e.register({[jd]:!0}),(t=this.Ja)==null||t.overrideSampling()}overrideTrigger(t){var e,n;this.Ja||(n=this.Mr)==null||n.register({[t==="url"?Hd:Wd]:!0}),(e=this.Ja)==null||e.overrideTrigger(t)}get sdkDebugProperties(){var t;return((t=this.Ja)==null?void 0:t.sdkDebugProperties)||{$recording_status:this.status}}tryAddCustomEvent(t,e){var n;return!((n=this.Ja)==null||!n.tryAddCustomEvent(t,e))}}},$m={autocapture:class{constructor(t){this.vo=!1,this.co=null,this.fo=!1,this.po=!1,this.instance=t,this.rageclicks=new tu(t.config.rageclick),this.mo=null}initialize(){this.startIfEnabled()}get Ne(){var t,e,n=de(this.instance.config.autocapture)?this.instance.config.autocapture:{};return n.url_allowlist=(t=n.url_allowlist)==null?void 0:t.map((i=>new RegExp(i))),n.url_ignorelist=(e=n.url_ignorelist)==null?void 0:e.map((i=>new RegExp(i))),n}yo(){if(this.isBrowserSupported()){if(w&&F){var t=n=>{n=n||w?.event;try{this.bo(n)}catch(i){$o.error("Failed to capture event",i)}};if(me(F,"submit",t,{capture:!0}),me(F,"change",t,{capture:!0}),me(F,"click",t,{capture:!0}),this.Ne.capture_copied_text){var e=n=>{n=n||w?.event;try{this.bo(n,To)}catch(i){$o.error("Failed to capture copy/cut event",i)}};me(F,"copy",e,{capture:!0}),me(F,"cut",e,{capture:!0})}}}else $o.info("Disabling Automatic Event Collection because this browser is not supported")}startIfEnabled(){this.isEnabled&&!this.vo&&(this.yo(),this.vo=!0)}onRemoteConfig(t){if(this.fo=!0,t.ok){var e=t.config;e.elementsChainAsString&&(this.po=e.elementsChainAsString);var n=e.autocapture_opt_out;pt(n)&&(this.instance.persistence&&this.instance.persistence.register({[Qo]:n}),this.co=n),this.startIfEnabled()}else this.startIfEnabled()}setElementSelectors(t){this.mo=t}getElementSelectors(t){var e,n=[];return(e=this.mo)==null||e.forEach((i=>{var r=F?.querySelectorAll(i);r?.forEach((s=>{t===s&&n.push(i)}))})),n}get isEnabled(){var t,e,n=(t=this.instance.persistence)==null?void 0:t.props[Qo],i=this.co,r=this.instance.Qi()&&!this.fo;if(ze(i)&&!pt(n)&&!r)return!1;var s=(e=this.co)!==null&&e!==void 0?e:!!n;return!!this.instance.config.autocapture&&!s}bo(t,e){if(e===void 0&&(e="$autocapture"),this.isEnabled){var n,i=wo(t);Xd(i)&&(i=i.parentNode||null),e==="$autocapture"&&t.type==="click"&&t instanceof MouseEvent&&this.instance.config.rageclick&&(n=this.rageclicks)!=null&&n.isRageClick(t.clientX,t.clientY,t.timeStamp||new Date().getTime())&&Rc(i,this.instance.config.rageclick)&&this.bo(t,"$rageclick");var r=e===To;if(i&&(function(d,f,h,p,g,m){var v;if(!w||cl(d)||h!=null&&h.url_allowlist&&!Ac(h.url_allowlist,m)||h!=null&&h.url_ignorelist&&Ac(h.url_ignorelist,m))return!1;if(h!=null&&h.dom_event_allowlist){var E=h.dom_event_allowlist;if(E&&!E.some((b=>f.type===b)))return!1}var S=sf(d,p),_=S.parentIsUsefulElement,x=S.targetElementList;if(!(function(b,P){var R=P?.element_allowlist;if(C(R))return!0;var N,L=function(T){if(R.some((V=>T.tagName.toLowerCase()===V)))return{v:!0}};for(var B of b)if(N=L(B))return N.v;return!1})(x,h)||!ga(x,h?.css_selector_allowlist)||ga(x,(v=h?.css_selector_ignorelist)!==null&&v!==void 0?v:Fg))return!1;try{var I=w.getComputedStyle(d);if(I&&I.getPropertyValue("cursor")==="pointer"&&f.type==="click")return!0}catch{}var M=d.tagName.toLowerCase();switch(M){case"html":return!1;case"form":return(g||["submit"]).indexOf(f.type)>=0;case"input":case"select":case"textarea":return(g||["change","click"]).indexOf(f.type)>=0;default:return _?(g||["click"]).indexOf(f.type)>=0:(g||["click"]).indexOf(f.type)>=0&&(ll.indexOf(M)>-1||d.getAttribute("contenteditable")==="true")}})(i,t,this.Ne,r,r?["copy","cut"]:void 0,this.instance)){var s=Em(i,{e:t,maskAllElementAttributes:this.instance.config.mask_all_element_attributes,maskAllText:this.instance.config.mask_all_text,elementAttributeIgnoreList:this.Ne.element_attribute_ignorelist,elementsChainAsString:this.po,disableCaptureUrlHashes:this.instance.config.disable_capture_url_hashes}),o=s.props;if(s.explicitNoCapture)return!1;var a=this.getElementSelectors(i);if(a&&a.length>0&&(o.$element_selectors=a),e===To){var l,u=tf(w==null||(l=w.getSelection())==null?void 0:l.toString()),c=t.type||"clipboard";if(!u)return!1;o.$selected_content=u,o.$copy_type=c}return this.instance.capture(e,o),!0}}}isBrowserSupported(){return Be(F?.querySelectorAll)}},historyAutocapture:class{constructor(t){var e;this._instance=t,this._o=(w==null||(e=w.location)==null?void 0:e.pathname)||""}initialize(){this.startIfEnabled()}get isEnabled(){return this._instance.config.capture_pageview==="history_change"}startIfEnabled(){this.isEnabled&&(A.info("History API monitoring enabled, starting..."),this.monitorHistoryChanges())}stop(){this.wo&&this.wo(),this.wo=void 0,A.info("History API monitoring stopped")}monitorHistoryChanges(){w&&w.history&&(this.ko("pushState"),this.ko("replaceState"),this.xo())}ko(t){var e;if(w&&((e=w.history[t])==null||!e.__posthog_wrapped__)){var n=this;(function(i,r,s){try{if(!(r in i))return nu;var o={next:i[r]},a=s((function(){for(var l=arguments.length,u=new Array(l),c=0;l>c;c++)u[c]=arguments[c];return o.next.apply(this,u)}));return Be(a)&&(a.prototype=a.prototype||{},Object.defineProperties(a,{__posthog_wrapped__:{enumerable:!1,value:!0},__posthog_layer__:{enumerable:!1,value:o}})),i[r]=a,()=>{if(i[r]!==a)for(var l=i[r];Be(l)&&l.__posthog_layer__;){var u=l.__posthog_layer__;if(u.next===a)return void(u.next=o.next);l=u.next}else i[r]=o.next}}catch{return nu}})(w.history,t,(i=>function(r,s,o){i.call(this,r,s,o),n.So(t)}))}}So(t){try{var e,n=w==null||(e=w.location)==null?void 0:e.pathname;if(!n)return;n!==this._o&&this.isEnabled&&this._instance.capture(Wn,{navigation_type:t}),this._o=n}catch(i){A.error("Error capturing "+t+" pageview",i)}}xo(){if(!this.wo){var t=()=>{this.So("popstate")};me(w,"popstate",t),this.wo=()=>{w&&w.removeEventListener("popstate",t)}}}},heatmaps:class{get Ne(){return this.instance.config}constructor(t){var e;this.Co=!1,this.vo=!1,this.Mo=null,this.instance=t,this.Co=!((e=this.instance.persistence)==null||!e.props[ea]),this.rageclicks=new tu(t.config.rageclick)}initialize(){this.startIfEnabled()}get flushIntervalMilliseconds(){var t=5e3;return de(this.Ne.capture_heatmaps)&&this.Ne.capture_heatmaps.flush_interval_milliseconds&&(t=this.Ne.capture_heatmaps.flush_interval_milliseconds),t}get isEnabled(){return H(this.Ne.capture_heatmaps)?H(this.Ne.enable_heatmaps)?this.Co:this.Ne.enable_heatmaps:this.Ne.capture_heatmaps!==!1}startIfEnabled(){if(this.isEnabled){if(this.vo)return;xm.info("starting..."),this.To(),this.Ie()}else{var t;clearInterval((t=this.Mo)!==null&&t!==void 0?t:void 0),this.Eo(),this.getAndClearBuffer()}}onRemoteConfig(t){if(t.ok){var e=t.config;if("heatmaps"in e){var n=!!e.heatmaps;this.instance.persistence&&this.instance.persistence.register({[ea]:n}),this.Co=n,this.startIfEnabled()}}}getAndClearBuffer(){var t=this.R;return this.R=void 0,t}Io(t){Lo(t.originalEvent)&&this.ke(t.originalEvent,"deadclick")}Ie(){this.Mo&&clearInterval(this.Mo),this.Mo=F?.visibilityState==="visible"?setInterval(this.cr.bind(this),this.flushIntervalMilliseconds):null}To(){w&&F&&(this.Po=this.cr.bind(this),me(w,Zr,this.Po),this.Ro=t=>this.ke(t||w?.event),me(F,"click",this.Ro,{capture:!0}),this.Ao=t=>this.Fo(t||w?.event),me(F,"mousemove",this.Ao,{capture:!0}),this.Lo=new Bc(this.instance,Og,this.Io.bind(this)),this.Lo.startIfEnabledOrStop(),this.Oo=this.Ie.bind(this),me(F,Jr,this.Oo),this.vo=!0)}Eo(){var t;w&&F&&(this.Po&&w.removeEventListener(Zr,this.Po),this.Ro&&F.removeEventListener("click",this.Ro,{capture:!0}),this.Ao&&F.removeEventListener("mousemove",this.Ao,{capture:!0}),this.Oo&&F.removeEventListener(Jr,this.Oo),clearTimeout(this.Do),(t=this.Lo)==null||t.stop(),this.vo=!1)}$o(t,e){var n=this.instance.scrollManager.scrollY(),i=this.instance.scrollManager.scrollX(),r=this.instance.scrollManager.scrollElement(),s=(function(o,a,l){for(var u=o;u&&dn(u)&&!Xe(u,"body");){if(u===l)return!1;var c=void 0;try{var d,f,h;c=(d=(f=(h=u.ownerDocument)==null?void 0:h.defaultView)!==null&&f!==void 0?f:w)==null?void 0:d.getComputedStyle(u).position}catch{return!1}if(j(a,c))return!0;u=nf(u)}return!1})(wo(t),["fixed","sticky"],r);return{x:t.clientX+(s?0:i),y:t.clientY+(s?0:n),target_fixed:s,type:e}}ke(t,e){var n;if(e===void 0&&(e="click"),!Cc(t.target)&&Lo(t)){var i=this.$o(t,e);(n=this.rageclicks)!=null&&n.isRageClick(t.clientX,t.clientY,new Date().getTime())&&Rc(wo(t),this.instance.config.rageclick)&&this.Vt(k({},i,{type:"rageclick"})),this.Vt(i)}}Fo(t){!Cc(t.target)&&Lo(t)&&(clearTimeout(this.Do),this.Do=setTimeout((()=>{this.Vt(this.$o(t,"mousemove"))}),500))}Vt(t){if(w){var e=this.Ne.disable_capture_url_hashes?un(w.location.href):w.location.href,n=this.Ne.custom_personal_data_properties,i=this.Ne.mask_personal_data_properties?[...ti,...n||[]]:[],r=Ki(e,i,Yi);this.R=this.R||{},this.R[r]||(this.R[r]=[]),this.R[r].push(t)}}cr(){this.R&&!Vt(this.R)&&this.instance.capture("$$heatmap",{$heatmap_data:this.getAndClearBuffer()})}},deadClicksAutocapture:Bc,webVitalsAutocapture:class{constructor(t){var e;this.Co=!1,this.vo=!1,this.R={navigationKey:void 0,url:void 0,metrics:[],firstMetricTimestamp:void 0},this.No=()=>{clearTimeout(this.qo),this.qo=void 0,this.R.metrics.length!==0&&(this._instance.capture("$web_vitals",k({$current_url:this.R.url},this.R.metrics.reduce(((n,i)=>k({},n,{["$web_vitals_"+i.name+"_event"]:k({},i),["$web_vitals_"+i.name+"_value"]:i.value})),{}))),this.R={navigationKey:void 0,url:void 0,metrics:[],firstMetricTimestamp:void 0})},this.jo=n=>{var i;if(this.R=this.R||{navigationKey:void 0,url:void 0,metrics:[],firstMetricTimestamp:void 0},H(n?.name)||H(n?.value))vn.error("Invalid metric received",n);else{var r=typeof n.navigationURL=="string"?n.navigationURL:void 0,s=this.Bo(r);if(!C(s)){var o=xe(n.navigationId)||typeof n.navigationId=="string"?"navigation:"+n.navigationId:"url:"+s;if(!this.Ho||this.Ho>n.value){this.R.navigationKey!==o&&(this.No(),this.qo=setTimeout(this.No,this.flushToCaptureTimeoutMs)),C(this.R.navigationKey)&&(this.R.navigationKey=o,this.R.url=s),this.R.firstMetricTimestamp=C(this.R.firstMetricTimestamp)?Date.now():this.R.firstMetricTimestamp,n.attribution&&n.attribution.interactionTargetElement&&(n.attribution.interactionTargetElement=void 0);var a=(i=this._instance.sessionManager)==null?void 0:i.checkAndGetSessionAndWindowId(!0),l=k({},n,r?{navigationURL:s}:{},{$current_url:s,timestamp:Date.now()});C(a)||(l.$session_id=a.sessionId,l.$window_id=a.windowId),this.R.metrics.push(l),this.R.metrics.length===this.allowedMetrics.length&&this.No()}else vn.error("Ignoring metric with value >= "+this.Ho,n)}}},this.Uo=()=>{if(!this.vo){var n,i,r,s,o=O.__PosthogExtensions__,a=o?.postHogWebVitalsCallbacksByFlavor,l=a?.[this.zo]||(this.zo==="web-vitals"&&C(a)?o?.postHogWebVitalsCallbacks:void 0);if(C(l)||(n=l.onLCP,i=l.onCLS,r=l.onFCP,s=l.onINP),n&&i&&r&&s){var u={reportSoftNavs:this.useSoftNavs};this.allowedMetrics.indexOf("LCP")>-1&&n(this.jo.bind(this),u),this.allowedMetrics.indexOf("CLS")>-1&&i(this.jo.bind(this),u),this.allowedMetrics.indexOf("FCP")>-1&&r(this.jo.bind(this),u),this.allowedMetrics.indexOf("INP")>-1&&s(this.jo.bind(this),u),this.vo=!0}else vn.error("web vitals callbacks not loaded - not starting")}},this._instance=t,this.Co=!((e=this._instance.persistence)==null||!e.props[ra]),this.startIfEnabled()}get Wo(){return this._instance.config.capture_performance}get allowedMetrics(){var t,e,n=de(this.Wo)?(t=this.Wo)==null?void 0:t.web_vitals_allowed_metrics:void 0;return H(n)?((e=this._instance.persistence)==null?void 0:e.props[sa])||["CLS","FCP","INP","LCP"]:n}get flushToCaptureTimeoutMs(){return(de(this.Wo)?this.Wo.web_vitals_delayed_flush_ms:void 0)||5e3}get useAttribution(){var t=de(this.Wo)?this.Wo.web_vitals_attribution:void 0;return t!=null&&t}get useSoftNavs(){var t=de(this.Wo)?this.Wo.__preview_web_vitals_soft_navs:void 0;return t!=null&&t}get Ho(){var t=de(this.Wo)&&xe(this.Wo.__web_vitals_max_value)?this.Wo.__web_vitals_max_value:iu;return t>0&&6e4>=t?iu:t}get isEnabled(){var t=ge?.protocol;if(t!=="http:"&&t!=="https:")return vn.info("Web Vitals are disabled on non-http/https protocols"),!1;var e=de(this.Wo)?this.Wo.web_vitals:pt(this.Wo)?this.Wo:void 0;return pt(e)?e:this.Co}startIfEnabled(){this.isEnabled&&!this.vo&&(vn.info("enabled, starting..."),this.ai(this.Uo))}onRemoteConfig(t){if(t.ok){var e=t.config;if("capturePerformance"in e){var n=de(e.capturePerformance)&&!!e.capturePerformance.web_vitals,i=de(e.capturePerformance)?e.capturePerformance.web_vitals_allowed_metrics:void 0;this._instance.persistence&&(this._instance.persistence.register({[ra]:n}),this._instance.persistence.register({[sa]:i})),this.Co=n,this.startIfEnabled()}}}get zo(){return this.useSoftNavs?this.useAttribution?"web-vitals-with-attribution-soft-navs":"web-vitals-soft-navs":this.useAttribution?"web-vitals-with-attribution":"web-vitals"}ai(t){var e=O.__PosthogExtensions__,n=this.zo,i=e?.postHogWebVitalsCallbacksByFlavor;i!=null&&i[n]||n==="web-vitals"&&C(i)&&e!=null&&e.postHogWebVitalsCallbacks?t():e==null||e.loadExternalDependency==null||e.loadExternalDependency(this._instance,n,(r=>{r?vn.error("failed to load script",r):t()}))}Bo(t){var e=t||w?.location.href;if(e){var n=this._instance.config.disable_capture_url_hashes?un(e):e,i=this._instance.config.custom_personal_data_properties,r=this._instance.config.mask_personal_data_properties?[...ti,...i||[]]:[];return Ki(n,r,Yi)}vn.error("Could not determine current URL")}}},Mm={exceptionObserver:class{constructor(t){var e;this.Uo=()=>{var n;if(w&&this.isEnabled&&(n=O.__PosthogExtensions__)!=null&&n.errorWrappingFunctions){var i=O.__PosthogExtensions__.errorWrappingFunctions.wrapOnError,r=O.__PosthogExtensions__.errorWrappingFunctions.wrapUnhandledRejection,s=O.__PosthogExtensions__.errorWrappingFunctions.wrapConsoleError;try{!this.Vo&&this.Ne.capture_unhandled_errors&&(this.Vo=i(this.captureException.bind(this))),!this.Zo&&this.Ne.capture_unhandled_rejections&&(this.Zo=r(this.captureException.bind(this))),!this.Go&&this.Ne.capture_console_errors&&(this.Go=s(this.captureException.bind(this)))}catch(o){Ei.error("failed to start",o),this.Qo()}}},this._instance=t,this.Ko=!((e=this._instance.persistence)==null||!e.props[ta]),this.Jo=new Tp(k({},(function(n){var i,r,s,o;return n===void 0&&(n={}),{refillRate:(i=(r=n.exceptionRateLimiterRefillRate)!==null&&r!==void 0?r:n.__exceptionRateLimiterRefillRate)!==null&&i!==void 0?i:1,bucketSize:(s=(o=n.exceptionRateLimiterBucketSize)!==null&&o!==void 0?o:n.__exceptionRateLimiterBucketSize)!==null&&s!==void 0?s:10}})(this._instance.config.error_tracking),{refillInterval:1e4,rt:Ei})),this.Ne=this.Yo(),this.startIfEnabledOrStop()}Yo(){var t=this._instance.config.capture_exceptions,e={capture_unhandled_errors:!1,capture_unhandled_rejections:!1,capture_console_errors:!1};return de(t)?e=k({},e,t):(C(t)?this.Ko:t)&&(e=k({},e,{capture_unhandled_errors:!0,capture_unhandled_rejections:!0})),e}get isEnabled(){return this.Ne.capture_console_errors||this.Ne.capture_unhandled_errors||this.Ne.capture_unhandled_rejections}startIfEnabledOrStop(){this.isEnabled?(Ei.info("enabled"),this.Qo(),this.ai(this.Uo)):this.Qo()}ai(t){var e,n;(e=O.__PosthogExtensions__)!=null&&e.errorWrappingFunctions?t():(n=O.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,"exception-autocapture",(i=>{if(i)return Ei.error("failed to load script",i);t()}))}Qo(){var t,e,n;(t=this.Vo)==null||t.call(this),this.Vo=void 0,(e=this.Zo)==null||e.call(this),this.Zo=void 0,(n=this.Go)==null||n.call(this),this.Go=void 0}onRemoteConfig(t){if(t.ok){var e=t.config;"autocaptureExceptions"in e&&(this.Ko=!!e.autocaptureExceptions||!1,this._instance.persistence&&this._instance.persistence.register({[ta]:this.Ko}),this.Ne=this.Yo(),this.startIfEnabledOrStop())}}onConfigChange(){this.Ne=this.Yo()}captureException(t){var e,n,i,r=(e=t==null||(n=t.$exception_list)==null||(n=n[0])==null?void 0:n.type)!==null&&e!==void 0?e:"Exception";this.Jo.consumeRateLimit(r)?Ei.info("Skipping exception capture because of client rate limiting.",{exception:r}):(i=this._instance.exceptions)==null||i.sendExceptionEvent(t)}},exceptions:class{constructor(t){var e,n;this.Xo=[],this.tl=new Yp([new ig,new fg,new sg,new rg,new ug,new cg,new ag,new dg],(function(i){for(var r=arguments.length,s=new Array(r>1?r-1:0),o=1;r>o;o++)s[o-1]=arguments[o];return function(a,l){l===void 0&&(l=0);for(var u=[],c=a.split(` +`),d=l;c.length>d;d++){var f=c[d];if(1024>=f.length){var h=Sc.test(f)?f.replace(Sc,"$1"):f;if(!h.match(/\S*Error: /)){for(var p of s){var g=p(h,i);if(g){u.push(g);break}}if(u.length>=50)break}}}return(function(m){if(!m.length)return[];var v=Array.from(m);return v.reverse(),v.slice(0,50).map((E=>{return k({},E,{filename:E.filename||(S=v,S[S.length-1]||{}).filename,function:E.function||Qn});var S}))})(u)}})("web:javascript",Qp,ng)),this._instance=t,this.Xo=(e=(n=this._instance.persistence)==null?void 0:n.get_property(na))!==null&&e!==void 0?e:[],this.el=zr(this.il()),this.rl=new pg(this.el)}onConfigChange(){this.el=zr(this.il()),this.rl.setConfig(this.el)}onRemoteConfig(t){var e,n,i;if(t.ok){var r=t.config;if("errorTracking"in r){var s=(e=(n=r.errorTracking)==null?void 0:n.suppressionRules)!==null&&e!==void 0?e:[],o=(i=r.errorTracking)==null?void 0:i.captureExtensionExceptions;this.Xo=s,this._instance.persistence&&this._instance.persistence.register({[na]:this.Xo,[ia]:o})}}}get nl(){var t,e=!!this._instance.get_property(ia),n=this._instance.config.error_tracking.captureExtensionExceptions;return(t=n??e)!==null&&t!==void 0&&t}buildProperties(t,e){return this.tl.buildFromUnknown(t,{syntheticException:e?.syntheticException,mechanism:{handled:e?.handled}})}addExceptionStep(t,e){if(this.el.enabled)try{if(!Z(t)||t.trim().length===0)return void bt.warn("Ignoring exception step because message must be a non-empty string");var n=(function(s){if(!s)return{sanitizedProperties:{},droppedKeys:[]};var o=[];return{sanitizedProperties:Object.keys(s).reduce(((a,l)=>hg.has(l)?(o.push(l),a):(a[l]=s[l],a)),{}),droppedKeys:o}})(this.sl(e)),i=n.sanitizedProperties,r=n.droppedKeys;r.length>0&&bt.warn("Ignoring reserved exception step fields",{droppedKeys:r}),this.rl.add(k({[Wr]:t,[qr]:new Date().toISOString()},i))}catch(s){bt.error("Failed to add exception step. Ignoring breadcrumb.",s)}}sendExceptionEvent(t){try{var e=t.$exception_list;if(this.al(e)){if(this.ol(e))return this.ll("Exception dropped: matched a suppression rule"),void bt.info("Skipping exception capture because a suppression rule matched");if(!this.nl&&this.ul(e))return this.ll("Exception dropped: thrown by a browser extension"),void bt.info("Skipping exception capture because it was thrown by an extension");if(!this._instance.config.error_tracking.__capturePostHogExceptions&&this.hl(e))return this.ll("Exception dropped: thrown by the PostHog SDK"),void bt.info("Skipping exception capture because it was thrown by the PostHog SDK")}var n=this.el.enabled&&H(t.$exception_steps)?this.dl(t):t,i=typeof(s=globalThis._posthogReleaseId)=="string"&&s.length>0?s:void 0;i&&(n.$release_id=i);try{var r=this._instance.capture("$exception",n,{_noTruncate:!0,_batchKey:"exceptionEvent",Wn:!0});return r&&this.rl.clear(),r}catch(o){return bt.error("Failed to capture exception event. Dropping this exception.",o),void this.rl.clear()}}catch(o){return void bt.error("Failed to process exception event. Ignoring this exception.",o)}var s}dl(t){try{var e=this.rl.getAttachable();return e.length===0?t:k({},t,{$exception_steps:e})}catch(n){return bt.error("Failed to read buffered exception steps. Capturing exception without steps.",n),t}}ll(t){this.el.enabled&&this.rl.add({[Wr]:t,[qr]:new Date().toISOString()})}sl(t){return de(t)?k({},t):{}}il(){var t,e;return(t=(e=this._instance.config.error_tracking)==null?void 0:e.exception_steps)!==null&&t!==void 0?t:{}}ol(t){if(t.length===0)return!1;try{var e=t.reduce(((n,i)=>{var r=i.type,s=i.value;return Z(r)&&r.length>0&&n.$exception_types.push(r),Z(s)&&s.length>0&&n.$exception_values.push(s),n}),{$exception_types:[],$exception_values:[]});return this.Xo.some((n=>{var i=n.values.map((r=>{var s=$f[r.operator],o=e[r.key];if(!s||!o)return!1;var a=U(r.value)?r.value:[r.value];return a.length>0&&s(a,o)}));return n.type==="OR"?i.some(Boolean):i.every(Boolean)}))}catch(n){return bt.warn("Failed to evaluate suppression rules. Capturing the exception.",n),!1}}ul(t){return t.flatMap((e=>{var n,i;return(n=(i=e.stacktrace)==null?void 0:i.frames)!==null&&n!==void 0?n:[]})).some((e=>e.filename&&e.filename.startsWith("chrome-extension://")))}hl(t){if(t.length>0){var e,n,i,r,s=(e=(n=t[0].stacktrace)==null?void 0:n.frames)!==null&&e!==void 0?e:[],o=s[s.length-1];return(i=o==null||(r=o.filename)==null?void 0:r.includes("posthog.com/static"))!==null&&i!==void 0&&i}return!1}al(t){return!H(t)&&U(t)}}},Lm=k({productTours:class{get Mr(){return this._instance.persistence}constructor(t){this.vl=null,this.cl=null,this._instance=t}initialize(){this.loadIfEnabled()}onRemoteConfig(t){if(t.ok){var e=t.config;if("productTours"in e){var n,i;if(this.Mr&&this.Mr.register({[il]:!!e.productTours}),!No(this._instance))return!this.vl&&H((n=this.Mr)==null?void 0:n.props[Ri])||yr.info("product tours disabled; stopping and clearing cached tours"),(i=this.vl)==null||i.stop(),this.vl=null,void this.clearCache();this.loadIfEnabled()}}}loadIfEnabled(){!this.vl&&No(this._instance)&&this.ai((()=>this.fl()))}ai(t){var e,n;(e=O.__PosthogExtensions__)!=null&&e.generateProductTours?t():(n=O.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,"product-tours",(i=>{i?yr.error("Could not load product tours script",i):t()}))}fl(){var t;!this.vl&&(t=O.__PosthogExtensions__)!=null&&t.generateProductTours&&(this.vl=O.__PosthogExtensions__.generateProductTours(this._instance,!0))}getProductTours(t,e){if(e===void 0&&(e=!1),!U(this.cl)||e){var n=this.Mr;if(n){var i=n.props[Ri];if(U(i)&&!e)return this.cl=i,void t(i,{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(No(this._instance)){var s=r.statusCode;if(s!==200||!r.json){var o="Product Tours API could not be loaded, status: "+s;return s===0?r.error||yr.warn(o):yr.error(o),void t([],{isLoaded:!1,error:o})}var a=U(r.json.product_tours)?r.json.product_tours:[];this.cl=a,n&&n.register({[Ri]:a}),t(a,{isLoaded:!0})}else t([],{isLoaded:!0})}})}else t(this.cl,{isLoaded:!0})}getActiveProductTours(t){H(this.vl)?t([],{isLoaded:!1,error:"Product tours not loaded"}):this.vl.getActiveProductTours(t)}showProductTour(t){var e;(e=this.vl)==null||e.showTourById(t)}previewTour(t){this.vl?this.vl.previewTour(t):this.ai((()=>{var e;this.fl(),(e=this.vl)==null||e.previewTour(t)}))}dismissProductTour(){var t;(t=this.vl)==null||t.dismissTour("user_clicked_skip")}nextStep(){var t;(t=this.vl)==null||t.nextStep()}previousStep(){var t;(t=this.vl)==null||t.previousStep()}clearCache(){var t;this.cl=null,(t=this.Mr)==null||t.unregister(Ri)}resetTour(t){var e;(e=this.vl)==null||e.resetTour(t)}resetAllTours(){var t;(t=this.vl)==null||t.resetAllTours()}cancelPendingTour(t){var e;(e=this.vl)==null||e.cancelPendingTour(t)}}},xs),Nm={siteApps:class{constructor(t){this.pl=0,this._instance=t,this.gl=[],this.apps={}}get isEnabled(){return!!this._instance.config.opt_in_site_apps}ml(t,e){if(e){var n=this.globalsForEvent(e);this.gl.push(n),this.gl.length>1e3&&(this.gl=this.gl.slice(10))}}get siteAppLoaders(){var t;return(t=O._POSTHOG_REMOTE_CONFIG)==null||(t=t[this._instance.config.token])==null?void 0:t.siteApps}initialize(){if(this.isEnabled){var t=this._instance._addCaptureHook(this.ml.bind(this));this.yl=()=>{t(),this.gl=[],this.yl=void 0}}}globalsForEvent(t){var e,n,i,r,s,o,a;if(!t)throw new Error("Event payload is required");var l={},u=this._instance.get_property("$groups")||[],c=this._instance.get_property("$stored_group_properties")||{};for(var d of Object.entries(c)){var f=d[0];l[f]={id:u[f],type:f,properties:d[1]}}var h=t.$set_once,p=t.$set;return{event:k({},id(t,Im),{properties:k({},t.properties,p?{$set:k({},(e=(n=t.properties)==null?void 0:n.$set)!==null&&e!==void 0?e:{},p)}:{},h?{$set_once:k({},(i=(r=t.properties)==null?void 0:r.$set_once)!==null&&i!==void 0?i:{},h)}:{}),elements_chain:(s=(o=t.properties)==null?void 0:o.$elements_chain)!==null&&s!==void 0?s:"",distinct_id:(a=t.properties)==null?void 0:a.distinct_id}),person:{properties:this._instance.get_property("$stored_person_properties")},groups:l}}bl(t){var e,n=(e=t.tagName)==null?void 0:e.toLowerCase();return n==="style"&&this._instance.config.prepare_external_dependency_stylesheet?this._instance.config.prepare_external_dependency_stylesheet(t)||(wt.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)||(wt.error("prepare_external_dependency_script returned null"),null):t}_l(){var t,e,n,i,r,s,o,a;if(!this._instance.config.prepare_external_dependency_stylesheet&&!this._instance.config.prepare_external_dependency_script)return()=>{};var l=F?.defaultView,u=l==null||(t=l.Node)==null?void 0:t.prototype;if(!l||!u)return()=>{};if(this.pl++,this.wl)return this.kl();var c=[],d=this,f=new WeakSet,h=(m,v,E)=>{if(m!=null&&m[v]){var S=m[v];m[v]=E(S),c.push((()=>{m[v]=S}))}},p=m=>{if(f.has(m))return m;var v=d.bl(m);return v&&f.add(v),v},g=m=>m.map((v=>typeof v=="string"?v:p(v))).filter((v=>!ze(v)));return h(u,"appendChild",(m=>function(v){var E=p(v);return E?m.call(this,E):v})),h(u,"insertBefore",(m=>function(v,E){var S=p(v);return S?m.call(this,S,E):v})),h(u,"replaceChild",(m=>function(v,E){var S=p(v);return S?m.call(this,S,E):E})),[(e=l.Element)==null?void 0:e.prototype,(n=l.Document)==null?void 0:n.prototype,(i=l.DocumentFragment)==null?void 0:i.prototype].forEach((m=>{h(m,"append",(v=>function(){for(var E=arguments.length,S=new Array(E),_=0;E>_;_++)S[_]=arguments[_];return v.apply(this,g(S))})),h(m,"prepend",(v=>function(){for(var E=arguments.length,S=new Array(E),_=0;E>_;_++)S[_]=arguments[_];return v.apply(this,g(S))}))})),[(r=l.Element)==null?void 0:r.prototype,(s=l.CharacterData)==null?void 0:s.prototype,(o=l.DocumentType)==null?void 0:o.prototype].forEach((m=>{h(m,"before",(v=>function(){for(var E=arguments.length,S=new Array(E),_=0;E>_;_++)S[_]=arguments[_];return v.apply(this,g(S))})),h(m,"after",(v=>function(){for(var E=arguments.length,S=new Array(E),_=0;E>_;_++)S[_]=arguments[_];return v.apply(this,g(S))})),h(m,"replaceWith",(v=>function(){for(var E=arguments.length,S=new Array(E),_=0;E>_;_++)S[_]=arguments[_];var x=g(S);return S.length&&!x.length?void 0:v.apply(this,x)}))})),h((a=l.Element)==null?void 0:a.prototype,"insertAdjacentElement",(m=>function(v,E){var S=p(E);return S?m.call(this,v,S):null})),this.wl=()=>{c.forEach((m=>m())),this.wl=void 0},this.kl()}kl(){var t=!1;return()=>{var e;t||(t=!0,this.pl--,this.pl===0&&((e=this.wl)==null||e.call(this)))}}xl(t,e){e===void 0&&(e=!0);var n=this._l();try{var i=t(n);return e&&n(),i}catch(r){throw n(),r}}setupSiteApp(t){var e=this.apps[t.id],n=()=>{var o;!e.errored&&this.gl.length&&(wt.info("Processing "+this.gl.length+" events for site app with id "+t.id),this.gl.forEach((a=>this.xl((()=>e.processEvent==null?void 0:e.processEvent(a))))),e.processedBuffer=!0),Object.values(this.apps).every((a=>a.processedBuffer||a.errored))&&((o=this.yl)==null||o.call(this))},i=!1,r=o=>{e.errored=!o,e.loaded=!0,wt.info("Site app with id "+t.id+" "+(o?"loaded":"errored")),i&&n()};try{var s=this.xl((o=>t.init({posthog:this._instance,callback(a){o(),r(a)}})),!1).processEvent;s&&(e.processEvent=s),i=!0}catch(o){wt.error(ou+t.id,o),r(!1)}if(i&&e.loaded)try{n()}catch(o){wt.error("Error while processing buffered events PostHog app with config id "+t.id,o),e.errored=!0}}Sl(){var t=this.siteAppLoaders||[];for(var e of t)this.apps[e.id]={id:e.id,loaded:!1,errored:!1,processedBuffer:!1};for(var n of t)this.setupSiteApp(n)}Cl(t){var e=this;if(Object.keys(this.apps).length!==0){var n=this.globalsForEvent(t),i=function(s){try{e.xl((()=>s.processEvent==null?void 0:s.processEvent(n)))}catch(o){wt.error("Error while processing event "+t.event+" for site app "+s.id,o)}};for(var r of Object.values(this.apps))i(r)}}onRemoteConfig(t){var e,n,i,r=this;if((e=this.siteAppLoaders)!=null&&e.length)return this.isEnabled?(this.Sl(),void this._instance.on("eventCaptured",(l=>this.Cl(l)))):void wt.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.');if((n=this.yl)==null||n.call(this),t.ok){var s=t.config;if((i=s.siteApps)!=null&&i.length)if(this.isEnabled){var o=function(){var l,u=a.id,c=a.url;O["__$$ph_site_app_"+u]=r._instance,(l=O.__PosthogExtensions__)==null||l.loadSiteApp==null||l.loadSiteApp(r._instance,c,(d=>{if(d)return wt.error(ou+u,d)}))};for(var a of s.siteApps)o()}else wt.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.')}}}},Om={tracingHeaders:class{constructor(t){this.Ml=void 0,this.Tl=void 0,this.El=void 0,this.Uo=()=>{var e,n,i=this.Il();i?(C(this.Ml)&&(this.Ml=(e=O.__PosthogExtensions__)==null||(e=e.tracingHeadersPatchFns)==null?void 0:e._patchXHR(i,(()=>this._instance.get_distinct_id()),this._instance.sessionManager)),C(this.Tl)&&(this.Tl=(n=O.__PosthogExtensions__)==null||(n=n.tracingHeadersPatchFns)==null?void 0:n._patchFetch(i,(()=>this._instance.get_distinct_id()),this._instance.sessionManager))):this.Qo()},this._instance=t}initialize(){this.startIfEnabledOrStop()}ai(t){var e,n;(e=O.__PosthogExtensions__)!=null&&e.tracingHeadersPatchFns?t():(n=O.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,"tracing-headers",(i=>{if(i)return Sm.error("failed to load script",i);t()}))}Pl(){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}Il(){var t=this.Pl();return U(t)?(U(this.El)?this.El.splice(0,this.El.length,...t):this.El=[...t],t.length>0?this.El:void 0):(U(this.El)&&this.El.splice(0),this.El=t||void 0,this.El)}Qo(){var t,e;(t=this.Ml)==null||t.call(this),(e=this.Tl)==null||e.call(this),this.Ml=void 0,this.Tl=void 0}startIfEnabledOrStop(){this.Il()?this.ai(this.Uo):this.Qo()}}},Bm=k({surveys:class{get Ne(){return this._instance.config}constructor(t){this.Rl=void 0,this._surveyManager=null,this.Al=!1,this.Fl=[],this.Ll=null,this.Ol=null,this._instance=t,this._surveyEventReceiver=null}initialize(){this.loadIfEnabled()}onRemoteConfig(t){if(!this.Ne.disable_surveys){if(!t.ok)return X.warn("Remote config unavailable. Not loading surveys.");var e=t.config.surveys;if(H(e))return X.warn("Flags not loaded yet. Not loading surveys.");var n=U(e);this.Rl=n?e.length>0:e,X.info("flags response received, isSurveysEnabled: "+this.Rl),this.loadIfEnabled()}}reset(){try{var t;(t=this._surveyEventReceiver)==null||t.reset(),localStorage.removeItem("lastSeenSurveyDate");for(var e=[],n=0;nlocalStorage.removeItem(r)))}catch{}}loadIfEnabled(){if(!this._surveyManager)if(this.Al)X.info("Already initializing surveys, skipping...");else if(this.Ne.disable_surveys)X.info(au);else if(this.Ne.cookieless_mode&&this._instance.consent.isOptedOut())X.info("Not loading surveys in cookieless mode without consent.");else{var t=O?.__PosthogExtensions__;if(t){if(!C(this.Rl)||this.Ne.advanced_enable_surveys){var e=this.Rl||this.Ne.advanced_enable_surveys;this.Al=!0;try{var n=t.generateSurveys;if(n)return void this.Dl(n,e);var i=t.loadExternalDependency;if(!i)return void this.$l(sl);i(this._instance,"surveys",(r=>{r||!t.generateSurveys?this.$l("Could not load surveys script",r):this.Dl(t.generateSurveys,e)}))}catch(r){throw this.$l("Error initializing surveys",r),r}finally{this.Al=!1}}}else X.error("PostHog Extensions not found.")}}Dl(t,e){this._surveyManager=t(this._instance,e),this._surveyEventReceiver=new Am(this._instance),X.info("Surveys loaded successfully"),this.Nl({isLoaded:!0})}$l(t,e){X.error(t,e),this.Nl({isLoaded:!1,error:t})}onSurveysLoaded(t){return this.Fl.push(t),this._surveyManager&&this.Nl({isLoaded:!0}),()=>{this.Fl=this.Fl.filter((e=>e!==t))}}getSurveys(t,e){if(e===void 0&&(e=!1),this.Ne.disable_surveys)return X.info(au),t([]);var n,i=this._instance.get_property(aa);if(i&&!e)return t(i,{isLoaded:!0}),void(this.ql()&&this.getSurveys((()=>{}),!0));typeof Promise<"u"&&this.Ll?this.Ll.then((r=>t(r.surveys,r.context))):(typeof Promise<"u"&&(this.Ll=new Promise((r=>{n=r}))),this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/surveys/?token="+this.Ne.token),method:"GET",timestampMode:"query",timeout:this.Ne.surveys_request_timeout_ms,callback:r=>{var s;this.Ll=null;var o=r.statusCode;if(o!==200||!r.json){var a="Surveys API could not be loaded, status: "+o;o!==0?X.error(a):r.error||X.warn(a),this.Ol=Date.now();var l={isLoaded:!1,error:a};return t([],l),void(n==null||n({surveys:[],context:l}))}this.Ol=null;var u,c=r.json.surveys||[],d=c.filter((h=>(function(p){return!(!p.start_date||p.end_date)})(h)&&(Lf(h)||(function(p){var g;return!((g=p.conditions)==null||(g=g.actions)==null||(g=g.values)==null||!g.length)})(h))));d.length>0&&((u=this._surveyEventReceiver)==null||u.register(d)),(s=this._instance.persistence)==null||s.register({[aa]:c,[Gr]:Date.now()});var f={isLoaded:!0};t(c,f),n?.({surveys:c,context:f})}}))}ql(){return this.jl()&&!this.Ll&&!this.Bl()}jl(){var t=this._instance.get_property(Gr);return xe(t)&&Date.now()-t>3e5}Bl(){return xe(this.Ol)&&3e5>Date.now()-this.Ol}markSurveyAsSeen(t,e){var n,i={id:t,current_iteration:(n=e?.iteration)!==null&&n!==void 0?n:null};Of(i);try{localStorage.setItem("lastSeenSurveyDate",new Date().toISOString())}catch{}}Nl(t){for(var e of this.Fl)try{if(!t.isLoaded)return e([],t);this.getSurveys(e)}catch(n){X.error("Error in survey callback",n)}}getActiveMatchingSurveys(t,e){if(e===void 0&&(e=!1),!H(this._surveyManager))return this._surveyManager.getActiveMatchingSurveys(t,e);X.warn("init was not called")}Hl(t){var e=null;return this.getSurveys((n=>{var i;e=(i=n.find((r=>r.id===t)))!==null&&i!==void 0?i:null})),e}Ul(t){if(H(this._surveyManager))return{eligible:!1,reason:wr};var e=typeof t=="string"?this.Hl(t):t;return e?this._surveyManager.checkSurveyEligibility(e):{eligible:!1,reason:"Survey not found"}}zl(t){if(H(this._surveyManager))return{eligible:!1,reason:wr};var e=typeof t=="string"?this.Hl(t):t;return e?this._surveyManager.checkSurveyRenderability(e):{eligible:!1,reason:"Survey not found"}}canRenderSurvey(t){if(H(this._surveyManager))return X.warn("init was not called"),{visible:!1,disabledReason:wr};var e=this.zl(t);return{visible:e.eligible,disabledReason:e.reason}}canRenderSurveyAsync(t,e){return H(this._surveyManager)?(X.warn("init was not called"),Promise.resolve({visible:!1,disabledReason:wr})):new Promise((n=>{this.getSurveys((i=>{var r,s=(r=i.find((a=>a.id===t)))!==null&&r!==void 0?r:null;if(s){var o=this.zl(s);n({visible:o.eligible,disabledReason:o.reason})}else n({visible:!1,disabledReason:"Survey not found"})}),e)}))}renderSurvey(t,e,n){var i;if(H(this._surveyManager))X.warn("init was not called");else{var r=typeof t=="string"?this.Hl(t):t;if(r!=null&&r.id)if(um.includes(r.type)){var s=F?.querySelector(e);if(s)return(i=r.appearance)!=null&&i.surveyPopupDelaySeconds?(X.info("Rendering survey "+r.id+" with delay of "+r.appearance.surveyPopupDelaySeconds+" seconds"),void setTimeout((()=>{var o,a;X.info("Rendering survey "+r.id+" with delay of "+((o=r.appearance)==null?void 0:o.surveyPopupDelaySeconds)+" seconds"),(a=this._surveyManager)==null||a.renderSurvey(r,s,n),X.info("Survey "+r.id+" rendered")}),1e3*r.appearance.surveyPopupDelaySeconds)):void this._surveyManager.renderSurvey(r,s,n);X.warn("Survey element not found")}else X.warn("Surveys of type "+r.type+" cannot be rendered in the app");else X.warn("Survey not found")}}displaySurvey(t,e){var n;if(H(this._surveyManager))X.warn("init was not called");else{var i=this.Hl(t);if(i){var r=i;if((n=i.appearance)!=null&&n.surveyPopupDelaySeconds&&e.ignoreDelay&&(r=k({},i,{appearance:k({},i.appearance,{surveyPopupDelaySeconds:0})})),e.displayType!==va.Popover&&e.initialResponses&&X.warn("initialResponses is only supported for popover surveys. prefill will not be applied."),e.ignoreConditions===!1){var s=this.Ul(i);if(!s.eligible)return void X.warn("Survey is not eligible to be displayed: ",s.reason)}e.displayType!==va.Inline?this._surveyManager.handlePopoverSurvey(r,e):this.renderSurvey(r,e.selector,e.properties)}else X.warn("Survey not found")}}cancelPendingSurvey(t){H(this._surveyManager)?X.warn("init was not called"):this._surveyManager.cancelSurvey(t)}handlePageUnload(){var t;(t=this._surveyManager)==null||t.handlePageUnload==null||t.handlePageUnload()}}},xs),Dm={toolbar:class{constructor(t){this.instance=t}Wl(t){O.ph_toolbar_state=t}Vl(){var t;return(t=O.ph_toolbar_state)!==null&&t!==void 0?t:0}initialize(){return this.maybeLoadToolbar()}maybeLoadToolbar(t,e,n){if(t===void 0&&(t=void 0),e===void 0&&(e=void 0),n===void 0&&(n=void 0),pa(this.instance.config)||!w||!F)return!1;t=t??w.location,n=n??w.history;try{if(!e){try{w.localStorage.setItem("test","test"),w.localStorage.removeItem("test")}catch{return!1}e=w?.localStorage}var i,r=Pm||ts(t.hash,"__posthog")||ts(t.hash,"state"),s=r?Ic((()=>JSON.parse(atob(decodeURIComponent(r)))))||Ic((()=>JSON.parse(decodeURIComponent(r)))):null;return s&&s.action==="ph_authorize"?((i=s).source="url",i&&Object.keys(i).length>0&&(s.desiredHash?t.hash=s.desiredHash:n?n.replaceState(n.state,"",t.pathname+t.search):t.hash="")):((i=JSON.parse(e.getItem(lu)||"{}")).source="localstorage",delete i.userIntent),!(!i.token||this.instance.config.token!==i.token||(this.loadToolbar(i),0))}catch{return!1}}Zl(t){var e=O.ph_load_toolbar||O.ph_load_editor;!H(e)&&Be(e)?e(t,this.instance):cu.warn("No toolbar load function found")}loadToolbar(t){var e=!(F==null||!F.getElementById(Zd));if(!w||e)return!1;var n=this.instance.requestRouter.region==="custom"&&this.instance.config.advanced_disable_toolbar_metrics,i=k({token:this.instance.config.token},t,{apiURL:this.instance.requestRouter.endpointFor("ui")},n?{instrument:!1}:{});if(w.localStorage.setItem(lu,JSON.stringify(k({},i,{source:void 0}))),this.Vl()===2)this.Zl(i);else if(this.Vl()===0){var r;this.Wl(1),(r=O.__PosthogExtensions__)==null||r.loadExternalDependency==null||r.loadExternalDependency(this.instance,"toolbar",(s=>{if(s)return cu.error("[Toolbar] Failed to load",s),void this.Wl(0);this.Wl(2),this.Zl(i)})),me(w,"turbolinks:load",(()=>{this.Wl(0),this.loadToolbar(i)}))}return!0}Gl(t){return this.loadToolbar(t)}maybeLoadEditor(t,e,n){return t===void 0&&(t=void 0),e===void 0&&(e=void 0),n===void 0&&(n=void 0),this.maybeLoadToolbar(t,e,n)}}},jm=k({experiments:Me},xs),Um={conversations:class{constructor(t){this.Ql=void 0,this._conversationsManager=null,this.Kl=!1,this.Jl=null,this.Yl=!1,this._instance=t}initialize(){this.loadIfEnabled()}onRemoteConfig(t){if(!this._instance.config.disable_conversations&&(this.Xl=t.ok,t.ok)){var e=t.config.conversations;H(e)||(pt(e)?this.Ql=e:(this.Ql=e.enabled,this.Jl=e),this.loadIfEnabled())}}reset(){var t;(t=this._conversationsManager)==null||t.reset(),this._conversationsManager=null,this.Ql=void 0,this.Jl=null,this.Xl=void 0,this.Yl=!1}loadIfEnabled(){if(!(this._conversationsManager||this.Kl||this._instance.config.disable_conversations||pa(this._instance.config)||this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut())){var t=O?.__PosthogExtensions__;if(t&&!C(this.Ql)&&this.Ql)if(this.Jl&&this.Jl.token){this.Kl=!0;try{var e=t.initConversations;if(e)return this.tu(e),void(this.Kl=!1);var n=t.loadExternalDependency;if(!n)return void this.eu(sl);n(this._instance,"conversations",(i=>{i||!t.initConversations?this.eu("Could not load conversations script",i):this.tu(t.initConversations),this.Kl=!1}))}catch(i){this.eu("Error initializing conversations",i),this.Kl=!1}}else rt.error("Conversations enabled but missing token in remote config.")}}tu(t){if(this.Jl)try{this._conversationsManager=t(this.Jl,this._instance),this.Yl=!1,rt.info("Conversations loaded successfully")}catch(e){this.eu("Error completing conversations initialization",e)}else rt.error("Cannot complete initialization: remote config is null")}eu(t,e){rt.error(t,e),this._conversationsManager=null,this.Kl=!1,this.Yl=!0}show(){this._conversationsManager?this._conversationsManager.show():rt.warn("Conversations not loaded yet.")}hide(){this._conversationsManager&&this._conversationsManager.hide()}isAvailable(){return this.Ql===!0&&!ze(this._conversationsManager)}getUnavailableReason(){return this.isAvailable()?null:this._instance.config.disable_conversations?"disabled_by_config":pa(this._instance.config)?"disabled_for_toolbar":this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut()?"consent_opted_out":this.Xl===!1?"remote_config_failed":C(this.Ql)?this.Xl?"disabled_in_project":"remote_config_pending":this.Ql?H(this.Jl)||!this.Jl.token?"missing_token":O!=null&&O.__PosthogExtensions__?this.Kl?"initializing":this.Yl?"load_failed":"not_loaded":"extensions_unavailable":"disabled_in_project"}isVisible(){var t,e;return(t=(e=this._conversationsManager)==null?void 0:e.isVisible())!==null&&t!==void 0&&t}sendMessage(t,e,n){var i=this;return re((function*(){return i._conversationsManager?i._conversationsManager.sendMessage(t,e,n):(rt.warn(yn),null)}))()}getMessages(t,e){var n=this;return re((function*(){return n._conversationsManager?n._conversationsManager.getMessages(t,e):(rt.warn(yn),null)}))()}markAsRead(t){var e=this;return re((function*(){return e._conversationsManager?e._conversationsManager.markAsRead(t):(rt.warn(yn),null)}))()}getTickets(t){var e=this;return re((function*(){return e._conversationsManager?e._conversationsManager.getTickets(t):(rt.warn(yn),null)}))()}requestRestoreLink(t){var e=this;return re((function*(){return e._conversationsManager?e._conversationsManager.requestRestoreLink(t):(rt.warn(yn),null)}))()}restoreFromToken(t){var e=this;return re((function*(){return e._conversationsManager?e._conversationsManager.restoreFromToken(t):(rt.warn(yn),null)}))()}restoreFromUrlToken(){var t=this;return re((function*(){return t._conversationsManager?t._conversationsManager.restoreFromUrlToken():(rt.warn(yn),null)}))()}getCurrentTicketId(){var t,e;return(t=(e=this._conversationsManager)==null?void 0:e.getCurrentTicketId())!==null&&t!==void 0?t:null}getWidgetSessionId(){var t,e;return(t=(e=this._conversationsManager)==null?void 0:e.getWidgetSessionId())!==null&&t!==void 0?t:null}Xn(){var t;(t=this._conversationsManager)==null||t.setIdentity()}ts(){var t;(t=this._conversationsManager)==null||t.clearIdentity()}}},Hm={logs:class{constructor(t){var e,n=this;this.iu=!1,this.ru=!1,this.rt=he("[logs]"),this.nu=k({},this.rt,{error(){for(var i=arguments.length,r=new Array(i),s=0;i>s;s++)r[s]=arguments[s];r.some(vu)||n.rt.error(...r)}}),this.tr=[],this.su=[],this.Sa=0,this.au=()=>{var i,r;this.Sa=0,(i=this.ou)==null||i.onReconnect(),(r=this.lu)==null||r.onReconnect()},this._instance=t,this._instance&&(e=this._instance.config.logs)!=null&&e.captureConsoleLogs&&(this.iu=!0),w&&me(w,"online",this.au)}uu(t,e,n,i){var r,s=(function(o,a){var l,u,c,d,f,h,p,g=(l=o?.flushIntervalMs)!==null&&l!==void 0?l:3e3,m=(u=o?.maxBufferSize)!==null&&u!==void 0?u:100,v=a!=null&&a.consoleCapture?void 0:(c=o?.maxLogsPerInterval)!==null&&c!==void 0?c:1e3,E=C(v)?Math.max(m,2048):Math.max(m,v),S=o?.resourceAttributes;return{serviceName:(d=(f=S?.["service.name"])!==null&&f!==void 0?f:o?.serviceName)!==null&&d!==void 0?d:a?.serviceNameDefault,serviceVersion:(h=S?.["service.version"])!==null&&h!==void 0?h:o?.serviceVersion,environment:(p=S?.["deployment.environment"])!==null&&p!==void 0?p:o?.environment,resourceAttributes:S,beforeSend:o?.beforeSend,flushIntervalMs:g,maxBufferSize:m,maxQueueSize:E,maxBatchRecordsPerPost:100,rateCapWindowMs:g,maxLogsPerInterval:v,backgroundFlushBudgetMs:0,terminationFlushBudgetMs:0}})((r=this._instance)==null||(r=r.config)==null?void 0:r.logs,n);return[new Vp(this.hu(t,e),s,this.nu,(()=>this.du()),(o=>o()),void 0,i),s]}vu(){var t,e=(t=this._instance)==null||(t=t.config)==null?void 0:t.logs;if(!this.ou||this.cu!==e){var n;(n=this.ou)==null||n.reset(),this.cu=e;var i=this.uu((()=>this.tr),(r=>{this.tr=r}));this.ou=i[0],this.fu=i[1]}return this.ou}pu(){var t,e=(t=this._instance)==null||(t=t.config)==null?void 0:t.logs;if(!this.lu||this.gu!==e){var n;(n=this.lu)==null||n.reset(),this.gu=e;var i=this.uu((()=>this.su),(r=>{this.su=r}),{serviceNameDefault:"posthog-browser-logs",consoleCapture:!0},mu);this.lu=i[0],this.mu=i[1]}return this.lu}initialize(){this.loadIfEnabled()}onRemoteConfig(t){var e;if(t.ok){var n=(e=t.config.logs)==null?void 0:e.captureConsoleLogs;!H(n)&&n&&(this.iu=!0,this.loadIfEnabled())}}reset(){var t,e;this.tr=[],(t=this.ou)==null||t.reset(),this.su=[],(e=this.lu)==null||e.reset(),this.Sa=0}captureLog(t){this.vu().captureLog(t)}he(t){this.pu().captureLog(t)}get logger(){return this.yu||(this.yu={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.yu}flushLogs(t){t?this.bu(t):(this.ou&&this.ou.flush().catch((e=>this._u(e))),this.lu&&this.lu.flush().catch((e=>this._u(e))))}_u(t){vu(t)||this.rt.error("PostHog logs flush failed:",t)}loadIfEnabled(){if(this.iu&&!this.ru){var t=O?.__PosthogExtensions__;if(t){var e=t.loadExternalDependency;e?e(this._instance,"logs",(n=>{var i;n||(i=t.logs)==null||!i.initializeLogs?this.rt.error("Could not load logs script",n):(t.logs.initializeLogs(this._instance),this.ru=!0)})):this.rt.error(sl)}else this.rt.error("PostHog Extensions not found.")}}hu(t,e){var n=this._instance;return{get isDisabled(){return!1},get optedOut(){return!n.is_capturing()},getPersistedProperty:i=>i===jt.LogsQueue?t():void 0,setPersistedProperty(i,r){var s;i===jt.LogsQueue&&e((s=r)!==null&&s!==void 0?s:[])},Ot:i=>this.Ot(i),getLibraryId:()=>ne.LIB_NAME,getLibraryVersion:()=>ne.LIB_VERSION}}Ot(t){return new Promise((e=>{if(uf(this.Sa,3))e({kind:"fatal",error:Bo(void 0,"logs endpoint is unreachable, dropping batch")});else{var n=!1,i=s=>{n||(n=!0,clearTimeout(r),e(s))},r=setTimeout((()=>{this.rt.warn("Logs request timed out before receiving a response"),i({kind:"retry-later",error:Bo(void 0,"logs request timed out")})}),9e4);this._instance._send_request({method:"POST",url:this.wu(),data:t,compression:"best-available",batchKey:"logs",fireCallbackOnDrop:!0,callback:s=>{var o=s.statusCode;if(this.ku(o),o>=200&&300>o)i({kind:"ok"});else if(o===413)i({kind:"too-large"});else if(o!==0&&o!==429&&500>o)i({kind:"fatal",error:new Error("logs request failed with status "+o)});else{var a;o===0?(s.error||this.rt.warn("Logs request failed before receiving an HTTP response"),i({kind:"retry-later",error:Bo(s.error,"logs request failed before receiving an HTTP response")})):i({kind:"retry-later",error:(a=s.error)!==null&&a!==void 0?a:new Error("logs request failed with status "+o)})}}})}}))}ku(t){(t!==0||this._instance.__loaded)&&(this.Sa=df(t,this.Sa,3,(()=>this.rt.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."))))}bu(t){this.tr.length>0&&this.xu(t,this.tr,this.fu,ne.LIB_NAME,(e=>{this.tr=e})),this.su.length>0&&this.xu(t,this.su,this.mu,mu,(e=>{this.su=e}))}xu(t,e,n,i,r){if(e.length!==0){var s=e.map((a=>a.record));r([]);var o=Md(s,$d(n,ne.LIB_NAME,ne.LIB_VERSION),i,ne.LIB_VERSION);this._instance._send_request({method:"POST",url:this.wu(),data:o,compression:"best-available",batchKey:"logs",transport:t})}}wu(){return this._instance.requestRouter.endpointFor("api","/i/v1/logs")+"?token="+encodeURIComponent(this._instance.config.token)}du(){var t,e={};if(e.distinctId=this._instance.get_distinct_id(),this._instance.sessionManager){var n=this._instance.sessionManager.checkAndGetSessionAndWindowId(!0),i=n.windowId,r=n.sessionStartTimestamp,s=n.lastActivityTimestamp;e.sessionId=n.sessionId,e.windowId=i,H(r)||(e.sessionStartTimestamp=r),H(s)||(e.lastActivityTimestamp=s)}if(O!=null&&(t=O.location)!=null&&t.href&&(e.currentUrl=this._instance.config.disable_capture_url_hashes?un(O.location.href):O.location.href),this._instance.featureFlags){var o=this._instance.featureFlags.getFlags();o&&o.length>0&&(e.activeFeatureFlags=o)}return e}}},Wm={metrics:class{constructor(t){this.rt=he("[metrics]"),this._instance=t}initialize(){}vu(){var t,e,n=(t=this._instance)==null||(t=t.config)==null?void 0:t.metrics;return this.ou&&this.cu===n||((e=this.ou)==null||e.reset(),this.cu=n,this.ou=new Gp(this.hu(),(function(i){var r,s,o,a,l,u=i?.resourceAttributes;return{serviceName:(r=u?.["service.name"])!==null&&r!==void 0?r:i?.serviceName,serviceVersion:(s=u?.["service.version"])!==null&&s!==void 0?s:i?.serviceVersion,environment:(o=u?.["deployment.environment"])!==null&&o!==void 0?o:i?.environment,resourceAttributes:u,beforeSend:i?.beforeSend,flushIntervalMs:(a=i?.flushIntervalMs)!==null&&a!==void 0?a:1e4,maxSeriesPerFlush:(l=i?.maxSeriesPerFlush)!==null&&l!==void 0?l:1e3}})(n),this.rt)),this.ou}count(t,e,n){e===void 0&&(e=1),this.vu().count(t,e,n)}gauge(t,e,n){this.vu().gauge(t,e,n)}histogram(t,e,n){this.vu().histogram(t,e,n)}flush(t){if(!this.ou)return Promise.resolve();if(t){var e=this.ou.drainWindow();return e&&this.Jt(e,t),Promise.resolve()}return this.ou.flush().catch((n=>this.rt.error("PostHog metrics flush failed:",n)))}reset(){var t;(t=this.ou)==null||t.reset()}hu(){var t=this._instance,e=this;return{get isDisabled(){return!1},get optedOut(){return!t.is_capturing()},Jt:n=>e.Jt(n),getLibraryId:()=>ne.LIB_NAME,getLibraryVersion:()=>ne.LIB_VERSION}}Jt(t,e){return new Promise((n=>{var i=!1,r=o=>{i||(i=!0,clearTimeout(s),n(o))},s=setTimeout((()=>r({kind:"retry-later",error:new Error("metrics request timed out")})),9e4);this._instance._send_request(k({method:"POST",url:this.Su(),data:t,compression:"best-available",batchKey:"metrics"},e&&{transport:e},{fireCallbackOnDrop:!0,callback(o){var a=o.statusCode;if(a>=200&&300>a)r({kind:"ok"});else if(a===413)r({kind:"too-large"});else if(a!==0&&a!==429&&500>a)r({kind:"fatal",error:new Error("metrics request failed with status "+a)});else{var l;r({kind:"retry-later",error:(l=o.error)!==null&&l!==void 0?l:new Error("metrics request failed with status "+a)})}}}))}))}Su(){return this._instance.requestRouter.endpointFor("api","/i/v1/metrics")+"?token="+encodeURIComponent(this._instance.config.token)}}},qm=k({},xs,Tm,$m,Mm,Lm,Nm,Bm,Om,Dm,jm,Um,Hm,Wm);Ye.__defaultExtensionClasses=k({},qm);(function(){ne.SDK_DIST_CHANNEL="npm";var t=ji[qn]=new Ye;return(function(){function e(){e.done||(e.done=!0,Df=!1,ie(ji,(function(n){n._dom_loaded()})))}F!=null&&F.addEventListener?F.readyState==="complete"?e():me(F,"DOMContentLoaded",e,{capture:!1}):w&&A.error("Browser doesn't support `document.addEventListener` so PostHog couldn't be initialized")})(),t})();const zm=["a[href]","button:not([disabled])","input:not([disabled]):not([type='hidden'])","select:not([disabled])","textarea:not([disabled])","[tabindex]:not([tabindex='-1'])"].join(",");let ft=null,Ia=null,Uf="";const ka=new Map;function Hf(t){return[...t.querySelectorAll(zm)].filter(e=>!e.hidden&&e.getAttribute("aria-hidden")!=="true"&&e.getClientRects().length>0)}function Vm(t){for(const e of document.body.children)e===t||e.tagName==="SCRIPT"||(ka.set(e,{inert:e.inert,ariaHidden:e.getAttribute("aria-hidden")}),e.inert=!0,e.setAttribute("aria-hidden","true"))}function Gm(){for(const[t,e]of ka)t.inert=e.inert,e.ariaHidden===null?t.removeAttribute("aria-hidden"):t.setAttribute("aria-hidden",e.ariaHidden);ka.clear()}function Wf(t){return t?.dataset.modalDismissible!=="false"&&t?.getAttribute("aria-busy")!=="true"}function Ve(t,e={}){const n=typeof t=="string"?document.getElementById(t):t;if(!n)return!1;ft&&ft!==n&&Ge(ft,{restoreFocus:!1,force:!0}),Ia=e.trigger||document.activeElement,ft=n,Uf=document.body.style.overflow,Vm(n),document.body.style.overflow="hidden",n.classList.add("open"),n.setAttribute("aria-hidden","false");const i=n.querySelector(".modal-content");i&&(i.style.transform="scale(1) translateY(0)");const r=()=>{if(ft!==n)return;((e.initialFocus?n.querySelector(e.initialFocus):n.querySelector("[data-modal-initial-focus]"))||Hf(n)[0]||n.querySelector(".modal-content")||n).focus({preventScroll:!0})};return requestAnimationFrame(r),setTimeout(r,260),!0}function Ge(t,e={}){const n=typeof t=="string"?document.getElementById(t):t;if(!n||!e.force&&!Wf(n))return!1;n.classList.remove("open"),n.setAttribute("aria-hidden","true"),Gm(),document.body.style.overflow=Uf,ft=null;const i=Ia;return Ia=null,e.restoreFocus!==!1&&i?.isConnected&&i.focus({preventScroll:!0}),!0}function _u(t,e,n="Operation in progress"){const i=typeof t=="string"?document.getElementById(t):t;i&&(i.dataset.modalDismissible=e?"false":"true",i.setAttribute("aria-busy",String(!!e)),e?i.setAttribute("aria-label",n):i.removeAttribute("aria-label"))}function Km(t){if(!Wf(t))return;const e=t.dataset.modalCloseHandler;e&&typeof window[e]=="function"?window[e]():Ge(t)}document.addEventListener("keydown",t=>{if(!ft)return;if(t.key==="Escape"){t.preventDefault(),t.stopImmediatePropagation(),Km(ft);return}if(t.key!=="Tab"){t.stopPropagation();return}const e=Hf(ft);if(!e.length){t.preventDefault(),(ft.querySelector(".modal-content")||ft).focus();return}const n=e[0],i=e[e.length-1];t.shiftKey&&document.activeElement===n?(t.preventDefault(),i.focus()):!t.shiftKey&&document.activeElement===i&&(t.preventDefault(),n.focus())},!0);function Ym(){document.querySelectorAll(".modal-overlay").forEach(t=>{t.setAttribute("role","dialog"),t.setAttribute("aria-modal","true"),t.setAttribute("aria-hidden",t.classList.contains("open")?"false":"true");const e=t.querySelector(".modal-content");e&&!e.hasAttribute("tabindex")&&(e.tabIndex=-1);const n=t.querySelector("h1, h2, h3");n&&(n.id||(n.id=`${t.id}-title`),t.setAttribute("aria-labelledby",n.id)),t.querySelectorAll(".modal-close").forEach(i=>{i.getAttribute("aria-label")||i.setAttribute("aria-label","Close dialog")})})}const hl=Object.freeze({free:"Free",professional:"Pro",power:"Power"}),Jm=Object.freeze({free:2,professional:50,power:2e3}),Zm="(contact us)",Xm=Object.freeze({free:Object.freeze(["2 generations/month","Gemini model only","Code Review"]),professional:Object.freeze(["50 generations/month","All models","Code Regeneration","Code Review"]),power:Object.freeze(["2000 generations/month","All models","Code Regeneration","Bring your own key (BYOK)","Code Review","All models + early access",`API & MCP access ${Zm}`])}),qf="CodeFile",zf="GeneratedCode",Qm={CustomAction:"A",CustomWidget:"W",CustomFunction:"F",CustomClass:"C",CodeFile:"C"};function an(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function Ca(t){return String(t||"").trim().replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function ev(t={},e=0){const n=Ca(t.artifactType||t.type||qf),i=Ca(t.artifactName||t.name||t.fileName||`${zf}-${e+1}`);return`${n||"artifact"}-${i||e+1}`}function Vf(t={},e=0){const n=an(t),i=n.artifactType||n.type||qf,r=n.artifactName||n.name||zf;let s=n.fileName||r;return s.endsWith(".dart")||(s+=".dart"),{id:Ca(n.id)||ev({...n,artifactType:i,artifactName:r,fileName:s},e),artifactType:i,artifactName:r,fileName:s,deployPath:n.deployPath||"",description:n.description||"",code:n.code||n.content||"",dependencies:Gf(n.dependencies),imports:Array.isArray(n.imports)?n.imports:[],publicApi:Array.isArray(n.publicApi)?n.publicApi:[],relationships:Kf(n.relationships),deployStatus:n.deployStatus||"pending",review:n.review||null,metadata:an(n.metadata),codeType:n.codeType||Qm[i]||"O"}}function Gf(t){return t?Array.isArray(t)?t.map(e=>{if(typeof e=="string")return{name:e,version:null,inferred:!1};const n=an(e),i=n.name||n.package;return i?{name:i,version:n.version||null,versionRequired:!!(n.versionRequired||n.required),inferred:!!n.inferred,...n.reason?{reason:n.reason}:{}}:null}).filter(Boolean):Object.entries(an(t)).map(([e,n])=>({name:e,version:n||null,inferred:!1})):[]}function Kf(t){return t?(Array.isArray(t)?t:[t]).map(e=>{const n=an(e);return!n.from&&!n.to?null:{from:n.from||null,to:n.to||null,type:n.type||"uses",description:n.description||""}}).filter(Boolean):[]}function Aa(t){if(typeof t!="string")return null;const e=t.trim();if(!e)return null;try{return JSON.parse(e)}catch{const n=e.match(/```(?:json)?\s*([\s\S]*?)```/i);if(!n)return null;try{return JSON.parse(n[1].trim())}catch{return null}}}function Ji(t,e={}){const n=[],i=typeof t=="string"?Aa(t):t,s=an(i||{});!i&&typeof t=="string"&&n.push("Structured bundle parse failed; using legacy single-artifact fallback.");const o=Array.isArray(s.artifacts)?s.artifacts:[{artifactType:s.artifactType||e.artifactType,artifactName:s.artifactName||e.artifactName,fileName:s.fileName||e.fileName,description:s.description,code:s.code||e.code||(typeof t=="string"?t:""),dependencies:s.dependencies||e.dependencies,relationships:s.relationships||e.relationships}];o.forEach((d,f)=>{!d?.artifactType&&!d?.type&&n.push(`Artifact ${f+1} has no artifactType; it will deploy as a standalone code file under lib/custom_code/ root.`)});const a=o.map((d,f)=>Vf(d,f)),l=new Map(o.map((d,f)=>[an(d).id,a[f]?.id]).filter(([d,f])=>d&&f)),u=d=>l.get(d)||d,c=Kf(s.relationships||e.relationships).map(d=>({...d,from:d.from?u(d.from):d.from,to:d.to?u(d.to):d.to}));return{schemaVersion:s.schemaVersion||e.schemaVersion||null,id:s.id||e.id||"bundle-current",title:s.title||s.name||e.title||"Generated artifact bundle",description:s.description||e.description||"",artifacts:a,dependencies:Gf(s.dependencies||e.dependencies),relationships:c,deployOrder:Array.isArray(s.deployOrder)?s.deployOrder.map(u):a.map(d=>d.id),warnings:[...n,...Array.isArray(s.warnings)?s.warnings:[]],metadata:an(s.metadata)}}function ii(t){return Ji(t).artifacts[0]||Vf()}function Yt(t){if(typeof t!="string")return t??"";const e=t.trim();if(!e)return"";try{return JSON.parse(e)}catch{return t}}function ri(t){return JSON.stringify(t,null,2)}function tv(t){return ri({task:"architect",userRequest:String(t??"")})}function nv(t){const e=Yt(t);return e&&typeof e=="object"&&typeof e.task=="string"?ri(e):ri({task:"generate_bundle",bundleSpec:e})}function iv(t){return ri({task:"review_bundle",generatedBundle:Yt(t),outputRequirements:{bundleReview:["status","score","summary","manualActions","findings"],scoreRange:[0,100],eachArtifact:["id","review.status","review.findings"],manualActions:{definition:"Setup the developer must perform by hand in the FlutterFlow editor that FlutterFlow will NOT do for them.",exclude:["creating the Custom Action, Widget or Code File itself - deploying the code creates it","declaring parameters or return values FlutterFlow derives from the function signature","anything that resolves as a side effect of using the action or widget in the editor","generic advice such as testing, reviewing or rebuilding the app"],preferEmpty:"Return an empty array when nothing qualifies - an empty list is the expected result for most bundles."}}})}function pl(t,e=null){const n={stage:t};return e!=null&&(n.bundle=Yt(e)),n}function rv({bundleSpec:t,artifactBundle:e,bundleReview:n,artifactId:i,userFeedback:r}){return ri({task:"regenerate_artifact",artifactId:i,bundleSpec:Yt(t),artifactBundle:Yt(e),bundleReview:Yt(n),userFeedback:String(r)})}function Yf({bundleSpec:t,artifactBundle:e,bundleReview:n,userFeedback:i}){return ri({task:"regenerate_bundle",bundleSpec:Yt(t),artifactBundle:Yt(e),bundleReview:Yt(n),userFeedback:String(i??"")})}const yu={csam:"child-safety content",dangerous:"dangerous content",harassment:"harassment",hate_speech:"hate speech",maliciousUrls:"a potentially malicious URL",malicious_uris:"a potentially malicious URL",pi_and_jailbreak:"prompt-injection or jailbreak instructions",promptInjection:"prompt-injection or jailbreak instructions",rai:"restricted content",sdp:"sensitive personal data",sexually_explicit:"sexually explicit content",virus_scan:"potentially malicious file content"},sv=["sanitizationResult","modelArmor","modelArmorResult","data","result","error"];function Qe(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function ov(t){return Qe(t)?typeof t.filterMatchState=="string"||typeof t.invocationResult=="string"||Array.isArray(t.matchedFilters)||Qe(t.filterSummary)||Qe(t.filterResults):!1}function Jf(t,e=0){if(!Qe(t)||e>3)return null;if(ov(t))return t;for(const n of sv){const i=t[n];if(Qe(i)){const r=Jf(i,e+1);if(r)return r}}return null}function os(t){return Array.isArray(t)?t.some(os):Qe(t)?t.matched===!0||t.matchState==="MATCH_FOUND"?!0:Object.values(t).some(os):!1}function Pa(t){return Array.isArray(t)?t.some(Pa):Qe(t)?typeof t.executionState=="string"&&t.executionState!=="EXECUTION_SUCCESS"?!0:Object.values(t).some(Pa):!1}function Zf(t){return{csamFilterFilterResult:"csam",maliciousUriFilterResult:"malicious_uris",piAndJailbreakFilterResult:"pi_and_jailbreak",raiFilterResult:"rai",sdpFilterResult:"sdp",virusScanFilterResult:"virus_scan"}[t]||t}function av(t,e){if(Qe(t))for(const[n,i]of Object.entries(t)){if(!Qe(i))continue;const r=Qe(i.categories)?i.categories:{},s=Object.entries(r).filter(([,o])=>Qe(o)&&o.matched===!0).map(([o])=>o);s.length>0?s.forEach(o=>e.add(o)):i.matched===!0&&e.add(Zf(n))}}function lv(t,e){if(!t)return;const n=Array.isArray(t)?t.flatMap(i=>Qe(i)?Object.entries(i):[]):Object.entries(t);for(const[i,r]of n){if(!os(r))continue;const s=Zf(i),o=r?.raiFilterResult?.raiFilterTypeResults||(s==="rai"?r?.raiFilterTypeResults:null),a=Qe(o)?Object.entries(o).filter(([,l])=>os(l)).map(([l])=>l):[];a.length>0?a.forEach(l=>e.add(l)):e.add(s)}}function cv(t){return yu[t]?yu[t]:String(t).replace(/([a-z])([A-Z])/g,"$1 $2").replace(/_/g," ").toLowerCase()}function wu(t){return t.length<=1?t[0]||"content that did not pass":t.length===2?`${t[0]} and ${t[1]}`:`${t.slice(0,-1).join(", ")}, and ${t.at(-1)}`}function uv(t){const e=Jf(t);if(!e)return null;const n=new Set(Array.isArray(e.matchedFilters)?e.matchedFilters:[]);av(e.filterSummary,n),lv(e.filterResults,n);const i=e.blocked===!0||e.filterMatchState==="MATCH_FOUND"||n.size>0,r=e.invocationResult||null,s=Pa(e.filterSummary||e.filterResults);return!i&&!s&&!["PARTIAL","FAILURE"].includes(r)?null:{kind:i?"blocked":"unavailable",invocationResult:r,matchedFilters:[...n]}}function dv(t,e){const n=uv(t);if(!n)return null;const i=[...new Set(n.matchedFilters.map(cv))],r=n.kind==="blocked",s=new Error(r?`Safety screening blocked this pipeline step for ${wu(i)}.`:"Safety screening could not be completed. Please try again.");return s.name="ModelArmorError",s.code=r?"MODEL_ARMOR_BLOCKED":"MODEL_ARMOR_UNAVAILABLE",s.isModelArmor=!0,s.pipelineStep=e,s.userTitle=r?"Request blocked for safety":"Safety check unavailable",s.userMessage=r?`The safety check detected ${wu(i)}. Edit your request to remove or rephrase the flagged content, then run the pipeline again.`:"The safety service did not finish all of its checks. Please wait a moment and run the pipeline again.",s.retryExplanation=r?"Trying another model would not change this safety decision.":"A fallback model was not attempted because safety screening must complete first.",s.matchedFilters=n.matchedFilters,s}function fv(t){return String(t||"").replace(/\/\*[\s\S]*?\*\//g,"").replace(/\/\/[^\n]*/g,"")}function bu(t){const e=/^(import|export|part|library|class|enum|extension|typedef|mixin|abstract|const|final|var|late)\b/,n=[];for(const i of fv(t).split(` +`)){if(!/^[A-Za-z_$]/.test(i)||e.test(i))continue;const r=i.match(/^[\w$<>,?\s[\]]+?\s([a-zA-Z_$][\w$]*)\s*\(/);r&&n.push(r[1])}return n}function gl(t,e){const n=t.replace(/\.dart$/,"");if(e==="W")return n.replace(/(^|_)(\w)/g,(i,r,s)=>s.toUpperCase());if(e==="A"){const i=n.replace(/(^|_)(\w)/g,(r,s,o)=>o.toUpperCase());return i.charAt(0).toLowerCase()+i.slice(1)}return e==="F"?"CustomFunctions":e==="C"?t.endsWith(".dart")?t:`${t}.dart`:n}async function Eu(t){const e=new TextEncoder().encode(String(t||"")),n=await globalThis.crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(n),i=>i.toString(16).padStart(2,"0")).join("")}async function hv(t,e=new Map){const n={},i=new Set;for(const[o,a]of t.entries()){if(a.type==="D"||a.type==="O")continue;const l=gl(o,a.type),u={old_identifier_name:l,new_identifier_name:l,type:a.type,is_deleted:!1,current_checksum:await Eu(a.content)},c=e.get(a.path);if(c!==void 0&&(u.original_checksum=await Eu(c)),n[o]=u,a.type==="F"){const d=bu(a.content);(d.length>0?d:[a.functionName].filter(Boolean)).forEach(h=>i.add(h))}}const r=new Set(bu(e.get("lib/flutter_flow/custom_functions.dart")||"")),s={functions_to_rename:[],functions_to_delete:[],functions_to_add:Array.from(i).filter(o=>!r.has(o))};return{fileMapContents:JSON.stringify(n),functionsMapContents:JSON.stringify(s)}}const pv=new Set(["CustomWidget","CustomAction","CustomFunction","CustomClass","CodeFile"]),Su={CustomWidget:"custom_code/widgets/",CustomAction:"custom_code/actions/",CustomFunction:"flutter_flow/custom_functions.dart",CustomClass:"custom_code/",CodeFile:"custom_code/"},gv=new Set(["void","dynamic","String","int","double","num","bool","Color","DateTime","DateTimeRange","LatLng","FFPlace","FFUploadedFile","DocumentReference","List"]),mv=["Struct","Record"],vv=[{id:"required-public-param",severity:"error",message:"CustomWidget constructor uses `required` on a parameter FlutterFlow can leave unset. FlutterFlow omits unset Define Parameters fields from the constructor call, so the widget will not compile when placed. Make the parameter optional and nullable (`this.value` with `final double? value`), or give it a constructor default (`this.value = 0.0`).",detect:t=>Do(t).some(e=>/\brequired\s+this\.\w+/.test(e)),pos:"class W extends StatefulWidget { const W({required this.value}); final double value; }",neg:`class _P { const _P({required this.t}); final double t; } +class W extends StatefulWidget { const W({this.value}); final double? value; }`},{id:"non-nullable-public-field",severity:"error",message:"CustomWidget declares a non-nullable field with no constructor default. FlutterFlow omits unset Define Parameters fields, so the emitted call cannot supply it. Make the field nullable (`final double? value`) or give the parameter a default (`this.value = 0.0`).",detect:t=>Do(t).some(e=>{const n=/^\s*final\s+(?:double|int|String|bool|Color|num)\s+(\w+)\s*;/gm;let i;for(;(i=n.exec(e))!==null;){const r=i[1];if(!(new RegExp(`this\\.${r}\\s*=(?!=)`).test(e)||new RegExp(`[:,]\\s*${r}\\s*=(?!=)`).test(e)))return!0}return!1}),pos:`class W extends StatefulWidget { + const W({required this.value}); + final double value; +}`,neg:`class _P { + const _P({required this.t}); + final double t; +} +class W extends StatefulWidget { + const W({this.value = 1.0}); + final double value; +}`},{id:"asset-without-anchor",severity:"warning",message:'CustomWidget calls Image.asset with a path arriving as a String parameter. An asset reaches the build only when a FlutterFlow widget NODE references it - a filename passed as a parameter does not count, so the image renders as a broken-image icon on device. "Download Unused Project Assets" does not fix it (FlutterFlow issues 522, 2271, 3799). Keep something in the UI referencing the file, or load it over the network instead.',detect:t=>/Image\.asset\s*\(/.test(t)&&/final\s+String\??\s+\w*[Pp]ath\b/.test(t),pos:`class W extends StatefulWidget { final String? imagePath; } +var x = Image.asset(widget.imagePath);`,neg:`class W extends StatefulWidget { final String? imagePath; } +var x = Image.network(widget.imagePath);`},{id:"unsupported-param-type",severity:"error",message:"CustomWidget exposes a Flutter data type FlutterFlow cannot express as a Define Parameter: TextStyle, BoxShadow, FontWeight, FontStyle, TextDirection, TextAlign, EdgeInsets, Offset, Alignment/AlignmentGeometry, Border, BorderRadius, BoxDecoration, BoxConstraints, BorderSide, Gradient, or ThemeData. FlutterFlow's supported data types (docs.flutterflow.io/resources/data-representation/data-types) are only int, double, bool, string, Color, Image, DateTime, Json, LatLng, and the FF objects, so this parameter cannot be configured in the editor and the widget will not place or compile. Expose primitives instead (color, fontSize as double?, fontWeight via a custom enum, doubles for spacing).",detect:t=>Do(t).some(e=>/final\s+(TextStyle|BoxShadow|FontWeight|FontStyle|TextDirection|TextAlign|EdgeInsets|Offset|Alignment(?:Geometry)?|Border(?:Radius|Side)?|BoxDecoration|BoxConstraints|Gradient|LinearGradient|RadialGradient|ThemeData)\??\s+\w+\s*;/.test(e)),pos:`class W extends StatefulWidget { + const W({this.textStyle}); + final TextStyle? textStyle; + @override _S createState() => _S(); +} +class _S extends State { @override Widget build(BuildContext c) => const SizedBox(); }`,neg:`class W extends StatefulWidget { + const W({this.width}); + final double? width; + @override _S createState() => _S(); +} +class _S extends State { @override Widget build(BuildContext c) => Padding(padding: const EdgeInsets.all(8), child: const SizedBox()); }`}];function Et(t,e,n){return{artifactId:t.id,artifactName:t.artifactName,artifactType:t.artifactType,severity:e,message:n}}function Zi(t){let e="",n=0;for(;n"&&(n--,n===0))return{inner:t.slice(e+1,i),end:i+1};return null}function yv(t,e){const n=new RegExp(`class\\s+${e}\\b[^{]*\\{`).exec(t);if(!n)return null;let i=0;for(let r=n.index+n[0].length-1;rwv(t).usable);function Ev(t=""){const e=Zi(t);return bv.filter(n=>n.detect(e)).map(({id:n,severity:i,message:r})=>({id:n,severity:i,message:r}))}function Sv(t){const e=[],n=t.matchAll(/\bFuture\b/g);for(const i of n){let r=i.index+6,s=null;const o=r;for(;ro;if(t[r]==="<"){const u=_v(t,r);if(!u||(s=u.inner.replace(/\s+/g," ").trim(),r=u.end,!/\s/.test(t[r]||"")))continue;for(;rxu(o.functionName)===i);if(r)return r;const s=o=>!o.functionName.startsWith("_");return n.find(s)||n[0]}function Is(t=""){return Array.from(Zi(t).matchAll(/\b(?:class|enum)\s+([A-Za-z_]\w*)/g),e=>e[1])}function xv(t="",e=""){return ml(t,e)?.returnType||null}function Iu(t){return String(t||"").replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2").toLowerCase()}function Iv(t,e){const n=Is(e);if(n.length===0)return null;const r=String(t||"").split("/").pop().replace(/\.dart$/,"");if(n.some(l=>Iu(l)===r)||n.length>1)return null;const[o]=n,a=`${Iu(o)}.dart`;return`File name "${t}" does not match declared class "${o}". FlutterFlow accepts this, but naming the file "${a}" keeps the Code File recognisable in the editor.`}function vl(t){return String(t||"").replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,"")}function kv(t,e,n=""){const i=ml(e,n)?.functionName;if(!i)return null;const r=String(t||"").split("/").pop(),s=gl(r,"A");if(s===i)return null;const o=`${vl(i)}.dart`;return`File name "${r}" does not match Action "${i}". FlutterFlow derives the action from the file name, so it looks for "${s}" and reports Action "${s}" declaration not found. Rename the file to "${o}" - FlutterFlow puts an underscore before every capital - or rename the function to "${s}".`}function Cv(t="",e=""){return ml(t,e)!==null}function Av(t,e=new Set){return(t?.match(/[A-Za-z_]\w*/g)||[]).filter(i=>gv.has(i)?!1:!mv.some(s=>i.endsWith(s))||e.has(i))}function Pv(t,{functionName:e="",declaredTypes:n=new Set}={}){const i=xv(t,e),r=Av(i,n);if(r.length===0)return null;const[s]=r;let o;return n.has(s)?o=`uses Code File type "${s}", which FlutterFlow cannot process as an Action Return Value`:i===s?o="is not a FlutterFlow Action Return Value":o=`uses type "${s}", which is not a FlutterFlow Action Return Value`,`CustomAction return type "${i}" ${o}. Return JSON (Future) or an existing FlutterFlow Data Type (*Struct) instead.`}function Fv(t,e={}){const n=[],i=t.fileName||"",r=t.code||"";if(pv.has(t.artifactType)||n.push(Et(t,"error",`Unsupported artifact type "${t.artifactType}".`)),i.endsWith(".dart")||n.push(Et(t,"error","FlutterFlow custom code artifacts must use .dart files.")),!r.trim())return n.push(Et(t,"warning","Generated artifact has no Dart code yet.")),n;if(t.artifactType==="CustomWidget"){/class\s+\w+\s+extends\s+(StatelessWidget|StatefulWidget)/.test(r)||n.push(Et(t,"warning","CustomWidget code should declare a widget class extending StatelessWidget or StatefulWidget."));for(const s of Ev(r))n.push(Et(t,s.severity,s.message))}if(t.artifactType==="CustomAction"&&!Cv(r,t.artifactName)&&n.push(Et(t,"warning","CustomAction code should expose an async Future function callable from FlutterFlow.")),t.artifactType==="CustomAction"){const s=e.declaredTypes||new Set(Is(r)),o=Pv(r,{functionName:t.artifactName,declaredTypes:s});o&&n.push(Et(t,"error",o));const a=kv(i,r,t.artifactName);a&&n.push(Et(t,"error",a))}if(t.artifactType==="CustomFunction"&&/class\s+\w+\s+extends\s+(StatelessWidget|StatefulWidget)/.test(r)&&n.push(Et(t,"warning","CustomFunction should be a callable function, not a widget class.")),t.artifactType==="CustomClass"||t.artifactType==="CodeFile"){const s=Iv(i,r);s&&n.push(Et(t,"info",s))}return n}function Rv(t){const e=Array.isArray(t?.artifacts)?t.artifacts:[],n=new Set(e.flatMap(s=>Is(s.code||""))),i=e.flatMap(s=>Fv(s,{declaredTypes:n})),r=e.map(s=>({artifactId:s.id,fileName:s.fileName,pathHint:Su[s.artifactType]||Su.CodeFile}));return{valid:i.every(s=>s.severity!=="error"),findings:i,deployHints:r}}const ku="// DO NOT REMOVE OR MODIFY THE CODE ABOVE!";function Cu(t){return(/^\s*import\s+['"]([^'"]+)['"]/.exec(t)||[])[1]||null}function Tv(t=""){const e=t.indexOf(ku);return e===-1?t:t.slice(e+ku.length).replace(/^\s*\n/,"")}const $v=/^\s*import\s+['"][^'"]+['"]\s*;\s*(?:\/\/.*)?$/;function Mv(t="",e=""){const n=Tv(t),i=new Set((e.match(/^\s*import .*$/gm)||[]).map(Cu).filter(Boolean)),r=n.split(` +`).filter(s=>{const o=Cu(s);return o===null||!i.has(o)?!0:!$v.test(s)}).join(` +`).replace(/^\s*\/\/ Automatic FlutterFlow imports\s*$/m,"").replace(/^\s*\n+/,"");return e+r}const Lv=new Set(["flutter","flutter_test","flutter_driver","flutter_localizations"]);function Xf(t){let e="",n=0;for(;n{const i=n.name||n.package;if(!i||i==="flutter")return e;const r=n.versionRequired||n.required;return e[i]=r&&n.version||"",e},{})}function jv(t){const e=new Map,n=new Map,i=[];for(const r of t)e.has(r.fileName)?i.push(`Duplicate deploy file name "${r.fileName}" for artifacts "${e.get(r.fileName)}" and "${r.artifactId}".`):e.set(r.fileName,r.artifactId),n.has(r.path)?i.push(`Duplicate deploy path "${r.path}" for artifacts "${n.get(r.path)}" and "${r.artifactId}".`):n.set(r.path,r.artifactId);return i}function Uv(t,e={}){const n=Array.isArray(t?.artifacts)?t.artifacts:[],r=(e.selectedArtifactIds||t?.deployOrder||n.map(h=>h.id)).map(h=>n.find(p=>p.id===h)).filter(Boolean),s=[...t?.warnings||[]];let o=[];r.forEach(h=>{const p=Dv(h),g=h.fixedCode||h.code||"",m=h.codeType||Ov[h.artifactType]||Je.OTHER;g.trim()||s.push(`${h.artifactName||h.id} has no generated code.`),o.push({artifactId:h.id,artifactName:h.artifactName,artifactType:h.artifactType,fileName:p,content:g,type:m,path:h.deployPath||Bv(p,m),deployPath:h.deployPath||"",deployMode:"customCodeSync"})});const a="lib/flutter_flow/custom_functions.dart",l=o.map((h,p)=>({entry:h,index:p})).filter(({entry:h})=>h.type===Je.FUNCTION&&h.path===a);if(l.length>1){const h=l[0],p={...h.entry,artifactId:l.map(({entry:m})=>m.artifactId).join("+"),artifactName:h.entry.artifactName,content:l.map(({entry:m})=>`// ${m.artifactId} +${m.content}`).join(` + +`)},g=new Set(l.slice(1).map(({index:m})=>m));o=o.filter((m,v)=>!g.has(v)),o[h.index]=p}const u={...Au(t?.dependencies),...r.reduce((h,p)=>({...h,...Au(p.dependencies)}),{})},c={};r.forEach(h=>{_l(h.code||"").forEach(p=>{p in u||(c[p]="")})});const d={...c,...u},f=jv(o);return{bundleId:t?.id||"bundle-current",title:t?.title||"Generated artifact bundle",fileEntries:o,dependencies:d,relationships:t?.relationships||[],warnings:s,errors:f}}function Hv(t){return String(t||"").match(/\bclass\s+([A-Z][A-Za-z0-9_]*)\b/)?.[1]}function Wv(t){return String(t||"").split("/").pop().replace(/\.dart$/,"").split(/[^A-Za-z0-9]+/).filter(Boolean).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join("")}function qv(t,e){const i=[Wv(t),Hv(e.content),e.artifactName].find(r=>/^[A-Z][A-Za-z0-9_]*$/.test(String(r||"")));if(!i)throw new Error(`Cannot derive a FlutterFlow custom class name for ${t}.`);return i}function zv(t,e=new Map){const n=[];for(const[i,r]of t.entries())r.type!=="C"||e.has(r.path)||n.push({artifactId:r.artifactId||i,className:qv(i,r),content:r.content,fileName:i,path:r.path});return n}function Vv(t,e){const n=new Set(e.map(i=>i.path));return new Map(Array.from(t.entries()).filter(([,i])=>!n.has(i.path)))}const Pu={pass:0,warning:1,fail:2},Gv=["manualActions"];function it(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function zt(...t){for(const e of t){if(typeof e=="string"&&e.trim())return e.trim();if(Array.isArray(e)&&e.length>0){const n=e.filter(i=>typeof i=="string").join(` +`);if(n)return n}}return""}function xt(t){return t==null?[]:Array.isArray(t)?t:[t]}function Kv(t){const e=it(t).value??t;if(e==null||typeof e=="string"&&e.trim()==="")return null;const n=Number(e);if(Number.isFinite(n))return Fu(n);const i=String(t||"").match(/\bscore\b[^\d]{0,12}(\d{1,3})(?:\s*\/\s*100)?/i);return i?Fu(Number(i[1])):null}function Fu(t){return t>=0&&t<=100?t:null}function ot(t){return String(t||"").trim().replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function yl(t){const e=String(t||"").toLowerCase();return/(fail|error|critical|block|reject|invalid)/.test(e)?"fail":/(warn|attention|manual|partial|incomplete|concern)/.test(e)?"warning":/(pass|success|ready|approve|valid|clean|info|notice)/.test(e)?"pass":null}function Fa(...t){return t.filter(Boolean).reduce((e,n)=>Pu[n]>Pu[e]?n:e,"pass")}function Qf(t,e="warning",n="review"){if(typeof t=="string")return{severity:e,message:t,suggestion:"",source:n};const i=it(t),r=zt(i.message,i.title,i.issue,i.description,i.summary);return r?{severity:yl(i.severity||i.status||i.level)||e,message:r,suggestion:zt(i.suggestion,i.fix,i.recommendation,i.action),source:i.source||n}:null}function Ra(t,e="review"){const n=it(t);return[["findings","warning"],["issues","warning"],["criticalIssues","fail"],["errors","fail"],["warnings","warning"],["recommendations","warning"],["requiredFixes","fail"],["suggestions","warning"]].flatMap(([r,s])=>xt(n[r]).map(o=>Qf(o,s,e)).filter(Boolean))}function Yv(t,e,n=null){if(typeof t=="string")return{id:`${n||"bundle"}-manual-${e+1}`,title:t,detail:"",location:"",timing:"unspecified",artifactId:n,source:"Code Review"};const i=it(t),r=zt(i.title,i.action,i.step,i.message,i.name,i.description);return r?{id:i.id||`${n||"bundle"}-manual-${e+1}`,title:r,detail:zt(i.detail,i.instructions,i.description),location:zt(i.location,i.flutterFlowPath,i.path),timing:zt(i.timing,i.phase)||"unspecified",artifactId:n,source:zt(i.source)||"Code Review"}:null}function Ta(t,e=null){const n=it(t);return Gv.flatMap(i=>xt(n[i])).map((i,r)=>Yv(i,r,e)).filter(Boolean)}function Jv(t){let e=typeof t=="string"?Aa(t):t;if(!e&&typeof t=="string")return{rawText:t,root:{}};const n=it(e);typeof n.content=="string"&&(e=Aa(n.content)||e);const i=it(e),r=it(i.reviewResult||i.codeReview||i.result);return{rawText:"",root:Object.keys(r).length?r:i}}function Zv(t,e){const n=[e.id,e.fileName,e.artifactName].map(ot);return t.find(i=>{const r=it(i);return[r.id,r.fileName,r.artifactName,r.name].map(ot).some(s=>s&&n.includes(s))})||null}function Xv(t,e){return xt(t?.metadata?.compatibility?.deployHints).find(r=>ot(r?.artifactId)===ot(e.id)||ot(r?.fileName)===ot(e.fileName))?.pathHint||""}function Qv(t,e){return xt(t?.relationships).filter(n=>ot(n?.from)===ot(e.id)||ot(n?.to)===ot(e.id))}function e_(t,e){return xt(t?.metadata?.compatibility?.findings).filter(n=>!n?.artifactId||ot(n.artifactId)===ot(e.id)).map(n=>Qf(n,"warning","Compatibility check")).filter(Boolean)}function t_(t,e,n,i){const r=Zv(e,n),s=it(r?.review||r||n.review),o=Object.keys(s).length>0,a=[...Ra(s),...e_(t,n)],l=Ta(s,n.id),u=yl(s.status||s.verdict||s.outcome||s.result),c=a.length?Fa(...a.map(f=>f.severity)):null,d=Fa(u,c,o?null:"warning");return{...n,index:i,status:d,statusReason:o?zt(s.summary,s.overview,s.assessment,s.conclusion)||(a.length?`${a.length} review finding${a.length===1?"":"s"}`:"No file-level findings"):"No file-level verdict was returned",reviewComplete:o,findings:a,manualSteps:l,fixedSource:typeof s.fixedSource=="string"&&s.fixedSource.trim()?s.fixedSource.trim():null,pathHint:Xv(t,n),relationships:Qv(t,n)}}function n_({status:t,score:e,artifactPresentations:n,manualSteps:i}){const r=n.length;if(r===0&&i.length===0)return e==null?"Code review returned no overall summary and no score.":`Reviewed bundle with score ${e}/100.`;const s=n.reduce((a,l)=>(a[l.status]+=1,a),{pass:0,warning:0,fail:0}),o=[];return t&&o.push(`Overall verdict: ${t}.`),r&&o.push(`${r} artifact${r===1?"":"s"}: ${s.pass} pass, ${s.warning} warn, ${s.fail} fail.`),i.length&&o.push(`Do before deploy: ${i.map(a=>a.title).join("; ")}.`),e==null&&o.push("No numeric score (0-100) was returned."),o.join(" ")}function i_({bundle:t,reviewResult:e}){const n=it(t),i=xt(n.artifacts),{root:r,rawText:s}=Jv(e),o=[r.bundleReview,r.overallReview,r.overall,r.bundleSummary,r.summaryReview,r.review].map(it).find(S=>Object.keys(S).length)||{},a=xt(r.artifacts||r.files||r.reviews),l=i.map((S,_)=>t_(n,a,S,_)),u=Ra(r),d=[...Ra(o),...u],f=[...Ta(o),...Ta(r),...l.flatMap(S=>S.manualSteps)].filter((S,_,x)=>x.findIndex(I=>I.title===S.title&&I.artifactId===S.artifactId)===_),h=yl(o.status||o.verdict||o.overallStatus||r.status||r.verdict||r.overallStatus||r.outcome),p=Fa(h,...d.map(S=>S.severity),...l.map(S=>S.status)),g=o.score??r.score??r.overallScore??s,m=Kv(g),v=zt(o.headline,o.summary,o.executiveSummary,o.overview,o.assessment,o.conclusion,r.overallSummary,r.headline,r.summary,r.executiveSummary,r.overview,r.assessment,r.conclusion,s)||n_({status:p,score:m,artifactPresentations:l,manualSteps:f}),E=l.reduce((S,_)=>(S[_.status]+=1,S),{pass:0,warning:0,fail:0});return{title:n.title||"Generated artifact bundle",description:n.description||"",status:p,score:m,summary:v,findings:d,manualSteps:f,artifacts:l,counts:E,reviewCoverage:{reviewed:l.filter(S=>S.reviewComplete).length,total:l.length},deployOrder:xt(n.deployOrder),relationships:xt(n.relationships),warnings:xt(n.warnings),compatibility:it(n.metadata?.compatibility)}}const r_=/^\uFEFF/;function xi(t){let e=0,n=t.length;for(;ee&&!t[n-1].trim();)n--;return t.slice(e,n).join(` +`)}function s_(t){const e=String(t??"").replace(r_,"");if(!e.trim())return"";const n=e.split(` +`),i=c=>{const d=c.trim();return/^`{3,}[A-Za-z0-9+#_.-]*$/.test(d)?c.length-c.trimStart().length:-1};let r=0,s=-1;const o=[];{let c=0;for(let d=0;d=0&&(r++,s<0&&(s=d),o.push(c+f)),c+=n[d].length+1}}if(r===0)return xi(n);{const c=$a(e);if(!c.error&&o.every(f=>Tu(f,c.commentAndStringRanges)))return xi(n)}if(r===1){const c=xi(n.slice(0,s)),d=xi(n.slice(s+1));return d.length>=c.length?d:c}const a=[];let l=null;for(let c=0;cc.length>0);return u.length===0?"":u.join(` + +`)}function o_(t){return String(t??"").replace(/\/\*[\s\S]*?\*\//g," ").replace(/\/\/[^\n]*/g,"").replace(/'''[\s\S]*?'''/g,'""').replace(/"""[\s\S]*?"""/g,'""').replace(/'(?:\\.|[^'\\\n])*'/g,'""').replace(/"(?:\\.|[^"\\\n])*"/g,'""')}function eh(t){const e=o_(t);return Array.from(e.matchAll(/class\s+([A-Z]\w*)\s+extends\s+[A-Za-z_]\w*Widget\b/g),n=>n[1])}function th(t){return`${vl(t)}.dart`}function a_(t){return gl(t,"W")}const Ru={"(":")","[":"]","{":"}"},l_={")":"(","]":"[","}":"{"},c_=/[A-Za-z0-9_]/;function $a(t){const e=[{kind:"code",opener:null,openedLine:0}],n=[];let i=1,r=0;const s=(c,d)=>{(c===` +`||c==="\r"&&d!==` +`)&&i++};let o=null;const a=()=>{for(const c of e)(c.kind==="string"||c.kind==="block-comment"||c.kind==="line-comment")&&n.push({start:c.startIndex,end:t.length})};for(;r0?t[r-1]:"",p=r>1?t[r-2]:"",g=(h==="r"||h==="R")&&!c_.test(p);e.push({kind:"string",quote:c,triple:f,raw:g,startIndex:r,openedLine:i}),r+=f?3:1;continue}if(Ru[c]){e.push({kind:"code",opener:c,openedLine:i}),r++;continue}if(l_[c]){if(d.interpolation&&c==="}"){e.pop(),r++;continue}if(d.opener&&Ru[d.opener]===c){e.pop(),r++;continue}return d.opener?(a(),{error:o??`line ${i}: "${c}" closes nothing - "${d.opener}" opened on line ${d.openedLine} is still open`,commentAndStringRanges:n}):(a(),{error:o??`line ${i}: unexpected "${c}" with no matching opener`,commentAndStringRanges:n})}s(c,t[r+1]),r++}a();let l=e.length-1;for(;l>0&&e[l].kind==="line-comment";)l--;let u=o;if(!u){const c=e[l];if(!(c.kind==="code"&&!c.opener&&!c.interpolation))if(c.kind==="string")u=`unclosed ${c.triple?"triple-quoted ":""}string starting on line ${c.openedLine} was never closed`;else if(c.kind==="block-comment")u=`unterminated /* comment starting on line ${c.openedLine}`;else if(c.interpolation){const d=e.findLast(h=>h.opener);u=`unclosed "\${" expression${d?` opened on line ${d.openedLine}`:""} was never closed`}else u=`"${c.opener}" opened on line ${c.openedLine} is never closed`}return{error:u,commentAndStringRanges:n}}function u_(t){return $a(String(t??"")).error}function Tu(t,e){return e.some(({start:n,end:i})=>t>=n&&ttypeof n=="string"?n:n?.errorMessage).filter(Boolean);return e.length>0?e.join("; "):JSON.stringify(t)}return t&&typeof t=="object"?t.errorMessage||JSON.stringify(t):String(t??"")}const d_=["gmail.com","googlemail.com","outlook.com","hotmail.com","live.com","msn.com"],f_="MAGIC_LINK_SENT",h_="PLUS_ALIAS_REJECTED",p_="Please enter your primary email address. Plus aliases (such as {email}) are not allowed for {domain} accounts.",ks={allowlistedDomains:d_,successCode:f_,validationCode:h_,messageTemplate:p_},g_=new Set(ks.allowlistedDomains),m_=ks.successCode,nh=ks.validationCode;function Cs(t){return typeof t=="string"?t.trim():""}function v_(t){const e=Cs(t),n=e.lastIndexOf("@");if(n<=0||n===e.length-1)return!1;const i=e.slice(0,n),r=e.slice(n+1).toLowerCase();return g_.has(r)?i.includes("+"):!1}function __(t,e){return ks.messageTemplate.replaceAll("{email}",t).replaceAll("{domain}",e)}function ih(t){if(!v_(t))return null;const e=Cs(t),n=e.lastIndexOf("@"),i=e.slice(n+1).toLowerCase();return __(e,i)}function rh(t,e){return t?.code===nh?t.message||ih(e)||"Please enter your primary email address.":t?.code===m_||!t?.code?`Check your email — we sent a link to ${Cs(e)}`:t.message||"Something went wrong. Please try again."}const y_="ccc_auth_session",w_="ccc_subscription",b_=Object.freeze(["hasSeenWalkthrough"]);function E_(t){const e=[];for(const n of b_)t.getItem(n)!==null&&(t.removeItem(n),e.push(n));return e}function S_(){return[y_,w_]}function x_({storage:t,onIdentityChanged:e,onPlanChanged:n}){for(const i of S_())t.removeItem(i);typeof e=="function"&&e(),typeof n=="function"&&n()}function I_({sendLink:t,getEmail:e,onState:n}){let i=!1;return async function(){if(i)return{status:"busy"};i=!0;let s;try{n({status:"pending",error:null});const o=await t(e());return s={status:"sent",data:o},n({status:"sent",data:o}),s}catch(o){return s={status:"error",error:o},n({status:"error",error:o}),s}finally{i=!1}}}const k_=/^dependencies\s*:\s*(?:#.*)?$/,C_=/^(?:"([^"]+)"|'([^']+)'|([A-Za-z_][A-Za-z0-9_-]*))\s*:/;function As(t){const e=t.match(C_);return e?e[1]??e[2]??e[3]:null}function nr(t){const e=t.trim();return e===""||e.startsWith("#")}function ci(t){const e=t.match(/^(\s*)/);return e?e[1].length:0}function bl(t,e){const n=t.findIndex(s=>e.test(s));if(n===-1)return null;let i=n,r=null;for(let s=n+1;s=0.0.0"}`}function R_(t,e={}){const n=String(t||""),i=Object.entries(e).filter(([u])=>u&&u!=="flutter");if(i.length===0)return{yaml:n,added:[],alreadyPresent:[]};const r=n.split(` +`),s=new Set(oh(n)),o=[],a=[];for(const[u,c]of i)s.has(u)?a.push(u):(o.push([u,c]),s.add(u));if(o.length===0)return{yaml:n,added:[],alreadyPresent:a};const l=El(r);if(l){const u=o.map(([c,d])=>$u(l.childIndent,c,d));r.splice(l.endIndex,0,...u)}else r.length>0&&r[r.length-1].trim()!==""&&r.push(""),r.push("dependencies:"),o.forEach(([u,c])=>{r.push($u(" ",u,c))});return{yaml:r.join(` +`),added:o.map(([u])=>u),alreadyPresent:a}}function T_(t,e={}){const n=String(t||""),i=Object.entries(e).filter(([l])=>l&&l!=="flutter");if(i.length===0)return{yaml:n,overridden:[],skipped:[]};const r=n.split(` +`),s=Fs(n),o=[],a=[];for(const[l,u]of i){const c=s.get(l);if(!c||!c.isScalar||!String(u||"").trim()){a.push(l);continue}const d=" ".repeat(ci(r[c.lineIndex]));r[c.lineIndex]=`${d}${l}: ${lh(String(u).trim())}${c.comment}`,o.push({name:l,from:c.constraint,to:u})}return{yaml:r.join(` +`),overridden:o,skipped:a}}function ch(t){const e=String(t||""),n=[];return e.trim()?(/^name:\s*\S+/m.test(e)||n.push("pubspec.yaml missing name field"),El(e.split(` +`))||n.push("pubspec.yaml missing dependencies section"),oh(e).includes("flutter")||n.push("pubspec.yaml missing Flutter SDK dependency"),{valid:n.length===0,errors:n}):(n.push("pubspec.yaml is empty"),{valid:!1,errors:n})}const $_=">=3.0.0 <4.0.0";function Ma(t){const e=String(t||"").trim(),n=e[0];return n!=="'"&&n!=='"'||e[e.length-1]!==n?e:e.slice(1,-1).replaceAll(`${n}${n}`,n)}function M_(t=""){const e=Nv(t).filter(n=>!n.startsWith("dart:")&&!n.startsWith("package:"));return{selfContained:e.length===0,unresolvableImports:e}}function Mu(t,e,n){const i=[];for(const[r,s]of t){if(s.isScalar){e[r]=Ma(s.constraint);continue}if(s.sourceKey==="sdk"){n.add(r);continue}if(s.sourceKey===null&&s.version){e[r]=Ma(s.version);continue}i.push(r)}return i}function L_(t){const e=new Set,n={},i={},r=Mu(Fs(t),n,e);r.push(...Mu(P_(t,"dependency_overrides"),i,e));const s=new Set([...Object.keys(n),...e]),{sdk:o}=ah(t);return{sdkConstraint:Ma(o)||$_,dependencies:n,overrides:i,sdkPackages:[...e].sort(),availablePackages:s,unrepresentable:r}}function N_(t,e,n){return e.length>0?`${t} imports ${e.join(", ")}, which FlutterFlow only generates once the app is built, so it could not be compiled before the deploy.`:`${t} imports ${n.join(", ")}, which your project's pubspec.yaml does not declare with a version constraint, so it could not be compiled before the deploy.`}function O_(t,e){const{sdkConstraint:n,dependencies:i,overrides:r,sdkPackages:s,availablePackages:o,unrepresentable:a}=L_(e),l={sdkConstraint:n,dependencies:i,overrides:r,sdkPackages:s},u=[],c=[],d=a.map(f=>`Your project declares ${f} from a source that cannot be reproduced outside it, so the pre-deploy compile check runs against a scratch package graph that omits ${f}. Classes that do not import ${f} directly are still checked, but against that reduced graph, so their transitive package resolution may differ from your project's and the check is approximate for them.`);for(const f of t){const{className:h,content:p}=f,g=_l(p),m=g.filter(S=>a.includes(S));if(m.length>0){c.push({className:h,reason:`${h} was not compiled before deploying: it imports ${m.join(", ")}, which your project declares from a source that cannot be reproduced outside it, so package resolution could not be matched exactly.`});continue}const{unresolvableImports:v}=M_(p),E=g.filter(S=>!o.has(S));if(v.length>0||E.length>0){c.push({className:h,reason:N_(h,v,E)});continue}u.push({fileName:`${vl(h)}.dart`,content:p})}return{manifest:l,sources:u,skipped:c,approximate:d}}function Lu(t,e){const n=`${t}${e}`.split(` +`),i=n.pop()??"",r=[];for(const s of n){const o=uh(s);o&&r.push(o)}return{events:r,buffer:i}}function B_(t){const e=uh(t);return e?[e]:[]}function uh(t){const e=t.trim();if(!e)return null;try{const n=JSON.parse(e);return n&&typeof n=="object"&&!Array.isArray(n)?n:null}catch{return null}}const Ze=Object.freeze({COMMITTED:"committed",PARTIAL:"partial",FAILED:"failed",UNCONFIRMED:"unconfirmed"}),D_=12e4;function dh(t){return t?.unconfirmed===!0||t?.outcome===Ze.UNCONFIRMED?Ze.UNCONFIRMED:t?.partial===!0||t?.outcome===Ze.PARTIAL?Ze.PARTIAL:t?.success===!0?Ze.COMMITTED:Ze.FAILED}async function j_(t,e={}){const{onPhase:n,onLog:i}=e;let r=null,s="";const o=a=>{if(a.event==="phase"){a.message&&n&&n(a.message);return}if(a.event==="log"){a.message&&i&&i(a.message);return}r=a};if(t.body?.getReader){const a=t.body.getReader(),l=new TextDecoder;for(;;){const{done:u,value:c}=await a.read();if(u)break;const d=Lu(s,l.decode(c,{stream:!0}));s=d.buffer,d.events.forEach(o)}}else{const a=Lu("",await t.text());s=a.buffer,a.events.forEach(o)}return B_(s).forEach(o),r?{...r,success:r.success===!0||r.success===void 0&&t.ok,finalResultReceived:!0}:{success:!1,finalResultReceived:!1,httpRejected:!t.ok,httpStatus:t.status,error:t.ok?"The FlutterFlow deploy runner closed the connection before it finished.":`FlutterFlow custom class provisioning failed (HTTP ${t.status}).`}}function U_(t){return t?.finalResultReceived?dh(t):t?.httpRejected?Ze.FAILED:Ze.UNCONFIRMED}function H_(){let t=document.getElementById("fx-grid");if(!t)return null;const e=window.matchMedia("(prefers-reduced-motion: reduce)"),n=window.matchMedia("(pointer: none)");let i=t.getContext("webgl2",{alpha:!0,antialias:!1,depth:!1,stencil:!1,premultipliedAlpha:!0,powerPreference:"low-power"}),r=i?null:t.getContext("2d");if(!i&&!r)return null;const s='',o=`#version 300 es +in vec2 p; void main(){ gl_Position = vec4(p, 0.0, 1.0); }`;function a(){return["#version 300 es","precision highp float;","out vec4 o;","uniform vec2 res;","uniform vec2 design;","uniform vec2 mouse;","uniform float energy;","uniform float parallax;","uniform float t;","uniform vec3 ink;","uniform sampler2D mark;","uniform vec2 rot;","const float WARP_A = 0.0032;","void main(){"," vec2 px = gl_FragCoord.xy * (design / res);"," vec2 p = vec2(px.x, design.y - px.y);"," vec2 off = vec2(0.0, -parallax) + vec2(sin(t * 0.11), cos(t * 0.09)) * 7.0;"," vec2 g = p + off;"," vec2 gm = mouse + off;"," float base = min(design.x, design.y);"," float spacing = clamp(base / 10.0, 64.0, 118.0);"," vec2 rel = g - gm;"," float rho = length(rel) + 1e-5;"," vec2 dir = rel / rho;"," vec2 pw = gm + dir * (rho + WARP_A * rho * rho);"," vec2 cell = floor(pw / spacing);"," vec2 cw = (cell + 0.5) * spacing - gm;"," float Rc = length(cw) + 1e-5;"," float rhoC = (-1.0 + sqrt(1.0 + 4.0 * WARP_A * Rc)) / (2.0 * WARP_A);"," vec2 c = gm + (cw / Rc) * rhoC;"," float cellSize = spacing / (1.0 + 2.0 * WARP_A * rhoC);"," float sigma = spacing * 2.9;"," float f = exp(-(rhoC * rhoC) / (2.0 * sigma * sigma));"," float scale = mix(0.32, 1.42, f);"," float weight = smoothstep(0.06, 0.80, f);"," float hs = cellSize * 0.26 * scale;"," vec2 uv = (g - c) / hs;"," vec2 ruv = mat2(rot.x, rot.y, -rot.y, rot.x) * uv;"," float cov = 0.0;"," if (abs(ruv.x) <= 1.0 && abs(ruv.y) <= 1.0) cov = texture(mark, ruv * 0.5 + 0.5).a;"," float s = cov * weight * energy * 0.26;"," o = vec4(ink * s, s);","}"].join(` +`)}let l=null,u,c,d,f,h,p,g,m,v;function E(K,W){if(!i)return null;const D=i.createShader(K);return i.shaderSource(D,W),i.compileShader(D),i.getShaderParameter(D,i.COMPILE_STATUS)?D:(window.console&&console.warn("fx-grid shader: "+i.getShaderInfoLog(D)),null)}if(i){const K=E(i.VERTEX_SHADER,o),W=E(i.FRAGMENT_SHADER,a());if(K&&W&&(l=i.createProgram(),i.attachShader(l,K),i.attachShader(l,W),i.linkProgram(l),i.getProgramParameter(l,i.LINK_STATUS)||(window.console&&console.warn("fx-grid link: "+i.getProgramInfoLog(l)),l=null)),l){i.useProgram(l),i.bindBuffer(i.ARRAY_BUFFER,i.createBuffer()),i.bufferData(i.ARRAY_BUFFER,new Float32Array([-1,-1,3,-1,-1,3]),i.STATIC_DRAW);const D=i.getAttribLocation(l,"p");i.enableVertexAttribArray(D),i.vertexAttribPointer(D,2,i.FLOAT,!1,0,0),u=i.getUniformLocation(l,"res"),c=i.getUniformLocation(l,"design"),d=i.getUniformLocation(l,"mouse"),f=i.getUniformLocation(l,"energy"),h=i.getUniformLocation(l,"parallax"),p=i.getUniformLocation(l,"t"),g=i.getUniformLocation(l,"ink"),m=i.getUniformLocation(l,"mark"),v=i.getUniformLocation(l,"rot"),i.enable(i.BLEND),i.blendFunc(i.ONE,i.ONE_MINUS_SRC_ALPHA),i.clearColor(0,0,0,0)}else{i=null;const D=t.cloneNode(!1);if(t.parentNode.replaceChild(D,t),t=D,r=t.getContext("2d"),!r)return null}}function S(K){if(!K)return null;const W=/^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(K);if(W){let D=W[1];return D.length===3&&(D=D[0]+D[0]+D[1]+D[1]+D[2]+D[2]),[parseInt(D.slice(0,2),16)/255,parseInt(D.slice(2,4),16)/255,parseInt(D.slice(4,6),16)/255]}try{const D=document.createElement("canvas");D.width=1,D.height=1;const le=D.getContext("2d");le.fillStyle="rgb(9, 8, 7)";const Ee=String(le.fillStyle);le.fillStyle=K;const Pe=String(le.fillStyle);if(Pe===Ee)return null;const ct=/^#([0-9a-f]{6})$/i.exec(Pe);if(ct){const ut=ct[1];return[parseInt(ut.slice(0,2),16)/255,parseInt(ut.slice(2,4),16)/255,parseInt(ut.slice(4,6),16)/255]}const Lt=/rgba?\(\s*([\d.]+)[,\s]+([\d.]+)[,\s]+([\d.]+)/i.exec(Pe);if(Lt)return[Number(Lt[1])/255,Number(Lt[2])/255,Number(Lt[3])/255]}catch{}return null}function _(){let K="";try{const W=getComputedStyle(document.documentElement);K=(W.getPropertyValue("--fx-ink")||"").trim()||(W.getPropertyValue("--fg")||"").trim()}catch{}return S(K)||[.56,.68,.88]}const x=_();let I=1920,M=1080,b=960,P=540,R=960,N=540,L=.66,B=0,T=-1e9,V=!1,$=0,G=0,ee=null,Fe=!1,we=!1,ke=!1;const $e=64,se=15.2;let Se=0,be=0;const Oe=.0032,_t=0,pe=.56,Ke=.26,yt=.32,hn=.16,Re=.349;let Ae=_t;function Tt(){const K=t.getBoundingClientRect(),W=t.clientWidth,D=t.clientHeight;if(!K.width||!W||!D)return;const le=Math.min(window.devicePixelRatio||1,2),Ee=Math.max(.2,Math.min(2,K.width/W*le)),Pe=Math.max(2,Math.round(W*Ee)),ct=Math.max(2,Math.round(D*Ee));(Pe!==t.width||ct!==t.height)&&(t.width=Pe,t.height=ct,i&&i.viewport(0,0,Pe,ct)),I=W,M=D,V||(b=R=I/2,P=N=M/2,V=!0)}function Ln(K){!l||!Fe||!i||(i.uniform2f(u,t.width,t.height),i.uniform2f(c,I,M),i.uniform2f(d,b,P),i.uniform1f(f,L),i.uniform1f(h,B),i.uniform2f(v,Math.cos(Ae),Math.sin(Ae)),i.uniform1f(p,K),i.uniform3f(g,x[0],x[1],x[2]),i.clear(i.COLOR_BUFFER_BIT),i.drawArrays(i.TRIANGLES,0,3))}function Ue(K,W,D){const le=Math.max(0,Math.min(1,(D-K)/(W-K)));return le*le*(3-2*le)}function Nn(K){if(!ee||!r)return;const W=r;W.setTransform(1,0,0,1,0,0),W.clearRect(0,0,t.width,t.height);const D=t.width/I;W.setTransform(D,0,0,D,0,0),W.globalAlpha=1;const le=Math.min(I,M),Ee=Math.max(64,Math.min(118,le/10)),Pe=Ee*2.9,ct=2*Pe*Pe,Lt=Math.sin(K*.11)*7,ut=Math.cos(K*.09)*7-B,or=b+Lt,ar=P+ut,to=Pe*Math.sqrt(2*Math.log(1/.06)),hi=to+Oe*to*to+Ee,mp=Math.floor((or-hi)/Ee)-1,vp=Math.ceil((or+hi)/Ee)+1,_p=Math.floor((ar-hi)/Ee)-1,yp=Math.ceil((ar+hi)/Ee)+1;for(let no=_p;no<=yp;no++){const wp=(no+.5)*Ee;for(let io=mp;io<=vp;io++){const ro=(io+.5)*Ee-or,so=wp-ar,oo=Math.sqrt(ro*ro+so*so)+1e-5;if(oo>hi)continue;const lr=(-1+Math.sqrt(1+4*Oe*oo))/(2*Oe),ic=Math.exp(-(lr*lr)/ct),rc=Ue(.06,.8,ic)*L*.26;if(rc<.004)continue;const rn=Ee/(1+2*Oe*lr)*.26*(.32+1.1*ic),sc=lr/oo,ao=or+ro*sc,lo=ar+so*sc;ao<-rn*1.6||ao>I+rn*1.6||lo<-rn*1.6||lo>M+rn*1.6||(W.globalAlpha=rc,W.save(),W.translate(ao,lo),W.rotate(Ae),W.drawImage(ee,-rn,-rn,rn*2,rn*2),W.restore())}}W.globalAlpha=1}function $t(K){if(!we)return;const W=G?Math.min(.05,(K-G)/1e3):.016;G=K;const le=K-T>2400?.6:1;L+=(le-L)*Math.min(1,W*3.2);const Ee=Math.min(.05,W);Se+=((R-b)*$e-Se*se)*Ee,be+=((N-P)*$e-be*se)*Ee,b+=Se*Ee,P+=be*Ee,B=(window.scrollY||window.pageYOffset||0)*.55;const Pe=K/1e3,ct=b/(I||1)-.5,Lt=P/(M||1)-.5;let ut=ct*(ct>=0?pe:Ke)+Lt*(Lt>=0?yt:hn);ut>Re?ut=Re:ut<-Re&&(ut=-Re),Ae=_t+ut-B*6e-4,Tt(),i?Ln(Pe):Nn(Pe),$=requestAnimationFrame($t)}function Mt(K){if(!we)return;const W=t.getBoundingClientRect();!W.width||!I||!M||(R=(K.clientX-W.left)/W.width*I,N=(K.clientY-W.top)/W.height*M,T=performance.now())}function lt(){we||eo||e.matches||n.matches||!ke||document.hidden||(we=!0,G=0,$=requestAnimationFrame($t))}function nn(){we=!1,$&&(cancelAnimationFrame($),$=0),G=0}function fi(){e.matches?(nn(),t.classList.remove("is-ready")):ke&<()}function On(){n.matches?nn():ke&<()}function ec(){document.hidden?nn():ke&<()}const tc=new IntersectionObserver(K=>{ke=K[0]?.isIntersecting||!1,ke?lt():nn()},{threshold:0});tc.observe(t),window.addEventListener("pointermove",Mt,{passive:!0,capture:!0}),window.addEventListener("resize",Tt),e.addEventListener("change",fi),n.addEventListener("change",On),document.addEventListener("visibilitychange",ec);function gp(){const K=(s.match(/\sd="([^"]+)"/)||[])[1],W=document.createElement("canvas");W.width=256,W.height=256;const D=W.getContext("2d");if(K&&window.Path2D){const le=Math.min(8.533333333333333,8.421052631578947);D.setTransform(le,0,0,le,le+(256-30*le)/2,-6.4*le),D.fillStyle="rgb(255,255,255)",D.fill(new Path2D(K),"evenodd"),D.setTransform(1,0,0,1,0,0)}try{const le=D.getImageData(0,0,256,256),Ee=le.data;for(let Pe=3;Pewe}}const W_=120;function q_(t,e,n){return tn?n:t}function ce(t,e,n){return q_((t-e)/(n-e),0,1)}function z_(t){return t<.5?2*t*t:1-Math.pow(-2*t+2,2)/2}function jo(t){return 1-Math.pow(1-t,3)}function He(t,e){return e=e===void 0?1.7:e,1+(e+1)*Math.pow(t-1,3)+e*Math.pow(t-1,2)}function Nu(t){return 1-Math.pow(2,-9*t)*Math.cos(t*15)}function te(t,e){if(t<=e[0].t)return e[0].v;for(let n=1;n8.2&&_<9.4&&(s*=1-.07*Math.sin(ce(_,8.2,9.4)*Math.PI))}else if(t<53){const _=t-42;g=te(_,[{t:0,v:1},{t:2,v:0},{t:4.2,v:0},{t:4.6,v:1},{t:6.8,v:1},{t:7.4,v:0},{t:9.4,v:0},{t:10.6,v:1}]),p=te(_,[{t:0,v:1},{t:2,v:.3},{t:4.6,v:1,e:He}]),d=te(_,[{t:0,v:0},{t:2,v:.3},{t:4.6,v:.16,e:He},{t:10.6,v:0}]),h=te(_,[{t:0,v:0},{t:2,v:-40},{t:4.6,v:0,e:He}]),o=te(_,[{t:0,v:0},{t:4.6,v:-.12},{t:10.6,v:0}])}else if(t<60){const _=t-53;c=te(_,[{t:0,v:1},{t:.35,v:0},{t:.45,v:0},{t:.7,v:1}]);const x=ce(_,.45,2.2);a=x>0?-2.6*(1-Nu(x)):0,g=te(_,[{t:0,v:1},{t:.57,v:0},{t:.67,v:0},{t:.92,v:1}]);const I=ce(_,.67,2.42);f=I>0?-2.6*(1-Nu(I)):0,s=1-.05*(Math.sin(ce(_,1.9,2.5)*Math.PI)+Math.sin(ce(_,2.5,3.1)*Math.PI))}else if(t<74){let x=function(P){return[te(P,[{t:0,v:0},{t:.25,v:1},{t:.5,v:1},{t:.72,v:.14},{t:.82,v:.14},{t:1,v:0}]),te(P,[{t:0,v:0},{t:.08,v:-.62},{t:.25,v:-.62},{t:.33,v:.62},{t:.7,v:.62},{t:.82,v:-.62},{t:1,v:-.62}])]};var S=x;const _=t-60,I=1-ce(_,12,14),M=x(ce(_,0,12)),b=x(ce(_-.5,0,12));n=M[0]*I,i=(M[1]+.05*Math.sin(_*7))*I,o=(b[0]-M[0])*.6*I,a=(b[1]-M[1])*.6*I,h=(b[0]-M[0])*30*I,E=ce(_,0,.4)*I}else if(t<85.4){const _=t-74,x=te(_,[{t:0,v:0},{t:4,v:1},{t:8,v:.24},{t:9.6,v:1,e:He},{t:11.4,v:0}]);o=x*.5,d=-x*.5,l=te(_,[{t:0,v:0},{t:4,v:6},{t:8,v:20},{t:9.6,v:38,e:He},{t:11.4,v:0}]),h=-l*.7,a=te(_,[{t:0,v:0},{t:8,v:0},{t:9.6,v:.4},{t:11.4,v:0}])}else if(t<96.4){const _=t-85.4,x=ce(_,0,5.6),I=ce(_,5.6,7.6),M=.72*Math.min(1,_/.6)*(1-I);d=Math.cos(x*Math.PI*2)*M,f=Math.sin(x*Math.PI*2)*M*.55,h=x*360*(1-I);const b=te(_,[{t:0,v:0},{t:7.6,v:0},{t:8.2,v:1,e:jo},{t:8.6,v:.55},{t:9.4,v:0}]);o=-.16*b,d+=.16*b,l=-6*b,h+=6*b,s=1+.05*b,m=1+.9*b}else if(t<108.6){const _=t-96.4,x=ce(_,9.6,12.2);n=te(_,[{t:0,v:0},{t:2.1,v:1},{t:4.8,v:.08},{t:7.5,v:1},{t:9.6,v:0}])*(1-x),i=-.35*Math.abs(Math.sin(ce(_,0,9.6)*Math.PI*3))*(1-x);const I=Math.sin(_*6.2)*(1-x);u=1+.12*I,p=1-.12*I,l=I*8,h=-I*8,o=.06*I,d=-.06*I,E=ce(_,0,.4)*(1-x)}else{const _=t-108.6,x=Math.sin(ce(_,0,8)*Math.PI),I=1-ce(_,8,11.4);s=1+.04*x*I,i=-.1*x*I,r=2*x*I,m=1+.5*Math.sin(ce(_,0,6)*Math.PI),v=1+.1*Math.sin(ce(_,0,6)*Math.PI)}return e.x=n,e.y=i,e.rot=r,e.scale=s,e.ax=o,e.ay=a,e.ar=l,e.asc=u,e.afade=c,e.bx=d,e.by=f,e.br=h,e.bsc=p,e.bfade=g,e.hfade=m,e.hsc=v,e.shd=E,e}function V_(t={}){const e=t.arena||document.querySelector(".pipeline-glyph.logo-loop");if(!e)return null;const n=e.querySelector(".loop-mark"),i=e.querySelector(".loop-piece-a"),r=e.querySelector(".loop-piece-b"),s=e.querySelector(".loop-halo"),o=e.querySelector(".loop-shadow");if(!n||!i||!r||!s||!o)return null;const a=t.reducedMotion||window.matchMedia("(prefers-reduced-motion: reduce)"),l=W_;let u=34,c=0,d=0;function f(){u=n.offsetWidth||34,c=Math.max(0,e.offsetWidth-u-4),d=Math.max(0,(e.offsetHeight-u)/2-2),e.style.setProperty("--mark-c",u/2+"px")}function h($){const G=Math.min(1,Math.max(0,$.x))*c,ee=$.y*d;n.style.transform="translate3d("+G.toFixed(2)+"px,"+ee.toFixed(2)+"px,0) rotate("+$.rot.toFixed(2)+"deg) scale("+$.scale.toFixed(3)+")",i.style.transform="translate3d("+($.ax*u).toFixed(2)+"px,"+($.ay*u).toFixed(2)+"px,0) rotate("+$.ar.toFixed(2)+"deg) scale("+$.asc.toFixed(3)+")",i.style.opacity=$.afade.toFixed(3),r.style.transform="translate3d("+($.bx*u).toFixed(2)+"px,"+($.by*u).toFixed(2)+"px,0) rotate("+$.br.toFixed(2)+"deg) scale("+$.bsc.toFixed(3)+")",r.style.opacity=$.bfade.toFixed(3),s.style.transform="scale("+$.hsc.toFixed(3)+")",s.style.opacity=(.09*$.hfade).toFixed(3),o.style.transform="translateX("+G.toFixed(2)+"px) scaleX("+(.75+.4*Math.abs($.x)).toFixed(3)+")",o.style.opacity=($.shd*.5).toFixed(3)}let p=0,g=0,m=0,v=!1,E=!1,S=!1,_=0;function x(){return S||a.matches||document.hidden||!e.offsetParent?!1:E}function I($){if(!v)return;if(m=requestAnimationFrame(I),!x()){b();return}const G=g?($-g)/1e3:0;g=$,p=(p+Math.min(G,.1))%l,_+=1,h(Ii(p))}function M(){v||S||x()&&(v=!0,g=0,m=requestAnimationFrame(I))}function b(){v=!1,m&&(cancelAnimationFrame(m),m=0),g=0}function P(){x()?M():b()}function R(){a.matches?(b(),h(Ii(0))):P()}function N(){f(),v&&h(Ii(p))}function L(){g=0,P()}const B=new IntersectionObserver($=>{E=$[0]?$[0].isIntersecting:!1,P()},{threshold:0});B.observe(e),window.addEventListener("resize",N),a.addEventListener("change",R),document.addEventListener("visibilitychange",L);function T(){S||(S=!0,b(),B.disconnect(),window.removeEventListener("resize",N),a.removeEventListener("change",R),document.removeEventListener("visibilitychange",L))}window.addEventListener("pagehide",T);function V($){p=($%l+l)%l,h(Ii(p))}return f(),h(Ii(0)),P(),{isRunning:()=>v,currentTime:()=>p,frameCount:()=>_,seek:V,dispose:T}}const G_=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;function Jt(t){const e=String(t||"").trim().match(G_);return e?{major:Number(e[1]),minor:Number(e[2]),patch:Number(e[3]),prerelease:e[4]?e[4].split("."):[]}:null}function K_(t,e){if(t.length===0&&e.length===0)return 0;if(t.length===0)return 1;if(e.length===0)return-1;for(let n=0;n0)}function J_(t){const e=Jt(t);return e?e.major>0?`${e.major+1}.0.0`:`0.${e.minor+1}.0`:null}function Sl(t){let e=String(t??"").trim();if((e.startsWith("'")||e.startsWith('"'))&&(e=e.slice(1,-1).trim()),e===""||e==="any"||e==="*")return{min:null,minInclusive:!1,max:null,maxInclusive:!1};if(e.startsWith("^")){const o=e.slice(1).trim();return Jt(o)?{min:o,minInclusive:!0,max:J_(o),maxInclusive:!1}:null}if(Jt(e))return{min:e,minInclusive:!0,max:e,maxInclusive:!0};const n={min:null,minInclusive:!1,max:null,maxInclusive:!1},i=/(>=|<=|>|<)\s*([0-9][0-9A-Za-z.+-]*)/g;let r=!1,s;for(;(s=i.exec(e))!==null;){const[,o,a]=s;if(!Jt(a))return null;r=!0,o===">="||o===">"?(n.min=a,n.minInclusive=o===">="):(n.max=a,n.maxInclusive=o==="<=")}return r?n:null}function Ou(t,e){const n=Sl(t);if(!n||!Jt(e))return!1;if(n.min!==null){const i=as(e,n.min);if(i<0||i===0&&!n.minInclusive)return!1}if(n.max!==null){const i=as(e,n.max);if(i>0||i===0&&!n.maxInclusive)return!1}return!0}function Z_(t,e){const n=Sl(t);if(!n||!Jt(e))return!1;if(n.max===null)return!0;const i=as(n.max,e);return i>0?!0:i===0&&n.maxInclusive}function Hn(t){const e=Sl(t);return e?e.min:null}const X_="https://pub.dev/api/packages/",Q_=8e3;function ey(t,e={}){const{dartSdkFloor:n=null,flutterSdkFloor:i=null}=e,r=Array.isArray(t?.versions)?t.versions:[];let s=null;for(const o of r){const a=o?.version;if(!a||o.retracted||Y_(a))continue;const l=o.pubspec?.environment||{};n&&l.sdk&&!Ou(l.sdk,n)||i&&l.flutter&&!Ou(l.flutter,i)||(!s||as(a,s)>0)&&(s=a)}return s?{version:s,constraint:`^${s}`}:null}async function ty(t,e={}){const{dartSdkFloor:n=null,flutterSdkFloor:i=null,fetchImpl:r=fetch}=e;let s;try{const a=await r(`${X_}${encodeURIComponent(t)}`,{signal:AbortSignal.timeout(Q_)});if(!a.ok)return{name:t,constraint:null,version:null,error:a.status===404?`"${t}" was not found on pub.dev`:`pub.dev returned ${a.status} for "${t}"`};s=await a.json()}catch(a){return{name:t,constraint:null,version:null,error:`could not reach pub.dev for "${t}" (${a.message})`}}const o=ey(s,{dartSdkFloor:n,flutterSdkFloor:i});return o?{name:t,...o,error:null}:{name:t,constraint:null,version:null,error:n?`no published "${t}" release supports Dart ${n}`:`no published "${t}" release could be read`}}async function ny(t,e={}){const n=await Promise.all(t.map(i=>ty(i,e)));return new Map(n.map(({name:i,...r})=>[i,r]))}async function iy(t,e={},n={}){const{resolveVersions:i=ny}=n,r=Object.entries(e).filter(([c])=>c&&c!=="flutter"),s=ah(t),o={dartSdkFloor:Hn(s.sdk),flutterSdkFloor:Hn(s.flutter)},a={additions:{},overrides:{},kept:[],warnings:[],sdk:o};if(r.length===0)return a;const l=Fs(t),u=[];for(const[c,d]of r){const f=l.get(c);if(!f){u.push(c);continue}const h=Hn(d);if(!h){a.kept.push({name:c,constraint:f.constraint});continue}if(!f.isScalar){a.warnings.push(`"${c}" is declared in your project from a git, path, or SDK source, but the generated code needs at least ${h}. Left as-is — update it yourself if the build fails.`),a.kept.push({name:c,constraint:f.constraint});continue}if(Z_(f.constraint,h)){a.kept.push({name:c,constraint:f.constraint});continue}a.overrides[c]=`^${h}`,a.warnings.push(`"${c}" was pinned to ${f.constraint} in your project, which cannot resolve the ${h} the generated code needs. Raising it to ^${h} — this changes a dependency the rest of your app also uses.`)}if(u.length>0){const c=await i(u,o);for(const d of u){const f=c.get(d);if(f?.constraint){a.additions[d]=f.constraint;continue}const h=e[d]||"";if(Hn(h)){a.additions[d]=`^${Hn(h)}`,a.warnings.push(`Could not confirm "${d}" version on pub.dev (${f?.error||"lookup failed"}). Using ^${Hn(h)} from the AI's recommendation — verify this is current.`);continue}a.additions[d]=">=0.0.0",a.warnings.push(`Could not determine a version for "${d}" (${f?.error||"lookup failed"}) and the AI supplied none. Added with a wide-open >=0.0.0 constraint — pin a concrete version in FlutterFlow before deploying.`)}}return a}const ry={"&":"&","<":"<",">":">",'"':""","'":"'"};function Zt(t){return String(t??"").replace(/[&<>"']/g,e=>ry[e])}function q(t){return t?Zt(t).replace(/\n/g,"
    "):""}function Kt(t){return Zt(t).replace(/\r?\n/g," ")}function Rs(t,e={}){const n=t?.pipelineStep;if(n!=null&&e[n]!=null)return e[n];const i=t?.message||"";return i.includes("Code Generator")?2:i.includes("Code Review")?3:1}function hh(t){if(!t)return{kind:"generic",title:"Generation failed",message:"An unknown error occurred. Please try again.",detail:"",canRetry:!0,canEdit:!0,canUpgrade:!1};if(t.isModelArmor){const n=t.code==="MODEL_ARMOR_BLOCKED";return{kind:"safety",title:t.userTitle||"Request blocked for safety",message:t.userMessage||t.message,detail:t.retryExplanation||"",canRetry:!n,canEdit:!0,canUpgrade:!1}}if(t.isUsageLimit)return{kind:"quota",title:"Monthly limit reached",message:t.message||"You've used all your generations for this period.",detail:"",canRetry:!1,canEdit:!1,canUpgrade:!0};const e=t.message||"";return/timed out after/i.test(e)?{kind:"timeout",title:"Request timed out",message:"The generation service took too long to respond.",detail:e,canRetry:!0,canEdit:!0,canUpgrade:!1}:/unreachable|failed to fetch|load failed|cors/i.test(e)?{kind:"network",title:"Connection problem",message:"We couldn't reach the generation service. Check your connection and try again.",detail:e,canRetry:!0,canEdit:!0,canUpgrade:!1}:{kind:"generic",title:"Generation failed",message:e||"An unexpected error occurred.",detail:"",canRetry:!0,canEdit:!0,canUpgrade:!1}}function sy(t){const e={"Integration Audit Report":"📋","Critical Issues":"❌",Warnings:"⚠️",Recommendations:"✅","Overall Score":"📊"};for(const[n,i]of Object.entries(e))if(t.toLowerCase().includes(n.toLowerCase()))return i;return"📄"}function oy(t){const e={critical:"❌",warning:"⚠️",recommendation:"✅",score:"📊",issue:"🔍",fix:"🔧"};for(const[n,i]of Object.entries(e))if(t.toLowerCase().includes(n.toLowerCase()))return i;return"📝"}function ay(t){return t.includes("class ")&&t.includes("extends ")||t.includes("StatelessWidget")||t.includes("StatefulWidget")||t.includes("import 'package:flutter/")?"dart":t.includes("def ")||t.includes("import ")||t.includes("print(")?"python":t.includes("function ")||t.includes("const ")||t.includes("console.")?"javascript":"dart"}function si(t){if(!t)return"";if(typeof t!="string")return String(t);const e=/```(?:\w+)?\n?([\s\S]*?)```/,n=t.match(e);return n?n[1].trim():t.trim()}function Bu(t){return t=Zt(t),t=t.replace(/\*\*(.*?)\*\*/g,'$1'),t=t.replace(/\*(.*?)\*/g,'$1'),t=t.replace(/`(.*?)`/g,'$1'),t=t.replace(/\b(FAIL|ERROR|CRITICAL)\b/g,'$1'),t=t.replace(/\b(WARN|WARNING)\b/g,'$1'),t=t.replace(/\b(PASS|SUCCESS|OK)\b/g,'$1'),t}function ph(t,e="dart",n=globalThis.hljs){if(!t)return"";const i=si(t);try{return n.highlight(i,{language:e}).value}catch(r){console.warn("Syntax highlighting failed:",r);try{return n.highlight(i,{language:"json"}).value}catch{return Zt(i)}}}function Ts(t,e={}){const{highlighter:n=globalThis.hljs}=e;let i='
    ';const r=String(t??"").split(` +`);let s=!1,o="";for(const a of r){if(a.startsWith("```")){if(s){const l=ay(o),u=ph(o.trim(),l,n);i+=`
    +
    ${u}
    +
    `,o="",s=!1}else s=!0;continue}if(s){o+=a+` +`;continue}if(a.startsWith("# ")){const l=a.substring(2).trim();i+=`
    +

    + ${sy(l)} + ${Zt(l)} +

    +
    `;continue}if(a.startsWith("## ")){const l=a.substring(3).trim();i+=`
    +

    + ${oy(l)} + ${Zt(l)} +

    +
    `;continue}if(/^[-*+]\s+/.test(a)||/^\d+\.\s+/.test(a)){const l=a.replace(/^([-*+]|\d+\.)\s+/,"").trim();i+=`
    + • + ${Bu(l)} +
    `;continue}a.trim()!==""&&(i+=`

    ${Bu(a)}

    `)}return i+="
    ",` +
    +
    +
    + Live Audit Report +
    + ${i} +
    + `}const ly=[[/gradient stroke\s*$/i," and an animated percentage label"],[/gauge\s*$/i," with a gradient stroke and animated fill"],[/rating\s*(bar|widget)?\s*$/i," with half-star support and haptic feedback"],[/list\s*$/i," with swipe-to-delete and an undo snackbar"],[/pad\s*$/i," that exports a transparent PNG"],[/carousel\s*$/i," with parallax cards and page indicators"],[/(button|cta)\s*$/i," with a loading spinner and success state"],[/(chart|graph)\s*$/i," that animates from a Firestore stream"],[/action\s*(that|to)?\s*$/i," uploads an image to Firebase Storage and returns the URL"],[/timer\s*$/i," with pause, resume and a completion callback"],[/map\s*$/i," with clustered markers and a custom info window"],[/^a\s+\w*$/i," widget that"],[/(picker|selector)\s*$/i," with search and multi-select"]],cy=220,uy=6;function Du(t,e){return!!(t&&t.trim())&&!e}function dy(t,e=""){if(typeof t!="string"||!t||t===e||t.trim().lengthi.test(t));return n?n[1]:null}function fy(){let t="",e="";return{get active(){return t},resolve(n){return t=dy(n,e)??"",t},dismiss(){t=""},accept(n){if(!t)return null;const i=n+t;return e=i,t="",i}}}function hy({onSubmit:t}){const e=document.getElementById("composer"),n=document.getElementById("pipeline-input"),i=document.getElementById("hero-send");if(!e||!n||!i||typeof t!="function")return;const r=e.querySelector(".ghost .typed"),s=e.querySelector(".ghost .suggest"),o=document.getElementById("tab-hint"),a=document.getElementById("suggest-status"),l=Array.from(document.querySelectorAll("#example-chips .chip")),u=window.matchMedia("(prefers-reduced-motion: reduce)"),c=fy();let d=!1,f=!1,h=!1,p=null,g=null;function m(){i.disabled=!Du(n.value,f||h)}function v(){r&&(r.textContent=n.value)}function E(){s&&(s.textContent=""),v(),e.classList.remove("has-suggest"),o&&(o.hidden=!0,o.tabIndex=-1),a&&(a.textContent="")}function S(T){s&&(s.textContent=T),v(),e.classList.add("has-suggest"),o&&(o.hidden=!1,o.tabIndex=0,o.setAttribute("aria-label","Accept suggestion: "+T.trim())),a&&(a.textContent="Suggestion: "+T+". Press Tab to accept.")}function _(){c.dismiss(),E()}function x(){if(d||f)return;const T=c.resolve(n.value);T&&S(T)}function I(){clearTimeout(p),!d&&(p=setTimeout(x,cy))}function M(){const T=c.accept(n.value);return T===null?!1:(n.value=T,E(),m(),!0)}function b(T){f=T,e.classList.toggle("is-busy",T),i.classList.toggle("is-busy",T),i.setAttribute("aria-label",T?"Generating":"Generate"),m()}async function P(){if(Du(n.value,f||h)){_(),b(!0);try{await t()}finally{b(!1)}}}function R(){h=!1,g&&(clearInterval(g),g=null),e.classList.remove("is-demo-typing"),m()}function N(){l.forEach(T=>{T.classList.remove("is-active"),T.setAttribute("aria-pressed","false")})}function L(){try{n.focus({preventScroll:!0}),n.setSelectionRange(n.value.length,n.value.length)}catch{}}function B(T){const V=T.dataset.prompt||"";if(R(),_(),l.forEach(G=>{const ee=G===T;G.classList.toggle("is-active",ee),G.setAttribute("aria-pressed",String(ee))}),u.matches||!V){n.value=V,v(),m(),L();return}n.value="",v(),h=!0,m(),e.classList.add("is-demo-typing");let $=0;g=setInterval(()=>{$+=1,n.value=V.slice(0,$),v(),$>=V.length?(R(),L()):m()},22)}l.forEach(T=>{T.setAttribute("aria-pressed","false"),T.addEventListener("click",()=>B(T))}),n.addEventListener("keydown",T=>{if(h&&T.key==="Enter"&&!T.shiftKey&&!T.isComposing&&!d){T.preventDefault();return}R(),T.key==="Tab"&&!T.shiftKey&&c.active?(T.preventDefault(),M()):T.key==="Escape"?(clearTimeout(p),p=null,_()):T.key==="Enter"&&!T.shiftKey&&!T.isComposing&&!d&&(T.preventDefault(),P())}),n.addEventListener("input",()=>{R(),N(),_(),m(),I()}),n.addEventListener("compositionstart",()=>{d=!0}),n.addEventListener("compositionend",()=>{d=!1,_(),m(),I()}),n.addEventListener("scroll",()=>{r&&r.parentNode&&(r.parentNode.scrollTop=n.scrollTop)}),o&&o.addEventListener("click",()=>{M(),n.focus({preventScroll:!0})}),i.addEventListener("click",P),n.addEventListener("pointerdown",()=>{R(),N()}),v(),m()}const py="https://ccc-ffai-runner-y5cyj3473a-uw.a.run.app/deployCustomClasses";const mt="https://4tgke4.buildship.run",gh={professional:"price_1T2ldCKszA2slvDXatdeCpbI",power:"price_1T2le9KszA2slvDXR4mPvw7M"},ls="ccc_auth_session",La="ccc_signin_return",gy=1800*1e3,ju=new WeakSet;let z={email:null,sessionToken:null,isVerified:!1};function Rn(t={}){return{tier:"free",status:"none",periodEnd:null,isLoading:!1,isResolved:!1,error:null,...t}}let ae=Rn({isResolved:!0});const my=`${mt}/service/runpipeline`,vy="bs_user_id",_y="bs_identity_token",yy=`${mt}/authUserCheck`;let dt={userId:null,token:null,status:null,resolved:!1};const cs=Jm,us="ccc_subscription",Uu=3,wy=new Set(["active","trialing","paid"]),ds="google/gemini-3.7-flash",Rr=["anthropic/claude-opus-5","openai/gpt-5.6-sol","z-ai/glm-5.2","moonshotai/kimi-k3","openrouter/auto-beta","openrouter/free","openrouter/deepseek/deepseek-v4-pro"],by={"google/gemini-3.7-flash":"Gemini 3.7 Flash","anthropic/claude-opus-5":"Claude Opus 5","openai/gpt-5.6-sol":"GPT-5.6 Sol","z-ai/glm-5.2":"GLM 5.2","moonshotai/kimi-k3":"Kimi K3","openrouter/auto-beta":"OpenRouter: Auto Router","openrouter/free":"OpenRouter: Free Models","openrouter/deepseek/deepseek-v4-pro":"DeepSeek v4 Pro"};function on(t){return by[t]||t}const Ey=new Set(["google/gemini-3.7-flash","anthropic/claude-opus-5","openai/gpt-5.6-sol","z-ai/glm-5.2","moonshotai/kimi-k3","openrouter/auto-beta"]);function mh(t){return Ey.has(t)}const Na=4,Uo=8*1024*1024,Sy="https://4tgke4.buildship.run/service/runpipeline-image";let Pt=[];function xy(t){return new Promise(e=>{const n=new FileReader;n.onload=()=>e(n.result),n.onerror=()=>e(null),n.readAsDataURL(t)})}async function Iy(t){const e=new FormData;return e.append("file",t),(await fetch(Sy,{method:"POST",body:e})).json()}function ky(t){if(Array.isArray(t)){const e=t[0];if(e&&typeof e=="object")for(const n of Object.keys(e)){if(n==="item"||n==="index")continue;const i=e[n];if(i&&typeof i=="object"){if(typeof i.file=="string")return i.file;if(typeof i.url=="string")return i.url}if(typeof i=="string")return i}return""}return typeof t=="string"?t:t&&typeof t=="object"&&(t.url||t.fileUrl||t.file_url||t.downloadUrl||t.imageUrl||t.image_url||t.file)||""}async function Cy(t){const e=Array.from(t.target.files||[]);if(!e.length)return;const n=e.filter(l=>l.size>Uo);n.length&&Ie(`Skipped ${n.length} image(s) over the ${(Uo/1024/1024).toFixed(0)} MB limit.`,"warning");const i=e.filter(l=>l.size<=Uo);if(!i.length){t.target.value="";return}const r=Na-Pt.length,o=i.slice(0,r).map(async l=>{const u=await xy(l);if(!u)return null;let c="";try{c=ky(await Iy(l))}catch{c=""}return{dataUrl:u,name:l.name,url:c}}),a=(await Promise.all(o)).filter(Boolean);t.target.value="",!(a.length&&!mh(document.getElementById("code-generator-model")?.value))&&(Pt.push(...a),i.length>r&&Ie(`You can attach up to ${Na} images.`,"info"),$s())}function Ay(t){Pt.splice(t,1),$s()}function $s(){const t=document.getElementById("prompt-image-thumbnails"),e=document.getElementById("prompt-image-btn-label");t&&(t.innerHTML="",Pt.forEach((n,i)=>{const r=document.createElement("div");r.className="prompt-img-thumb",r.innerHTML=`Prompt image`,t.appendChild(r)}),e&&(e.textContent=Pt.length>=Na?"Image limit reached":"Add images"))}function vh(){const t=document.getElementById("prompt-image-upload");if(!t)return;const e=document.getElementById("code-generator-model"),n=mh(e?.value);t.classList.toggle("hidden",!n),!n&&Pt.length&&(Pt=[],$s())}const Cn="ccc_usage",_h="google/gemini-3.7-flash",yh="google/gemini-3.7-flash",br="google/gemini-3.7-flash",$i={professional:11,power:49},Oa={en_US:"USD",en_GB:"GBP",en_AU:"AUD",en_NZ:"NZD",en_CA:"CAD",en_IN:"INR",en_SG:"SGD",en_HK:"HKD",en_PH:"PHP",en_ZA:"ZAR",en:"USD",de:"EUR",fr:"EUR",es:"EUR",it:"EUR",nl:"EUR",pt_PT:"EUR",pt_BR:"BRL",pt:"BRL",ja:"JPY",ko:"KRW",zh_CN:"CNY",zh_TW:"TWD",zh:"CNY",th:"THB",vi:"VND",id:"IDR",ms_MY:"MYR",ms:"MYR",sv:"SEK",nb:"NOK",da:"DKK",pl:"PLN",cs:"CZK",hu:"HUF",ro:"RON",tr:"TRY",ar:"AED",he:"ILS",ru:"RUB",uk:"UAH"},Tr={AUD:1,USD:.65,EUR:.6,GBP:.52,CAD:.88,NZD:1.08,JPY:97,KRW:870,INR:54,SGD:.87,HKD:5.08,BRL:3.18,CNY:4.7,TWD:20.5,THB:22.5,VND:16200,IDR:10200,MYR:2.88,SEK:6.8,NOK:6.95,DKK:4.48,PLN:2.6,CZK:15.2,HUF:238,RON:2.98,TRY:20.9,AED:2.39,ILS:2.38,PHP:36.4,ZAR:11.8,RUB:58,UAH:26.8,CHF:.57,MXN:11.1,ARS:580,CLP:610,COP:2700,PEN:2.44};let $r={...Tr};async function Py(){const t=new AbortController,e=setTimeout(()=>t.abort(),5e3);try{const n=await fetch("https://open.er-api.com/v6/latest/AUD",{signal:t.signal});if(!n.ok)return;const i=await n.json();if(i.result!=="success"||!i.rates)return;const r=i.rates,s={AUD:1},o=new Set([...Object.keys(Tr),...Object.values(Ba),...Object.values(Oa)]);for(const a of o)a!=="AUD"&&(typeof r[a]=="number"&&r[a]>0?s[a]=r[a]:Tr[a]&&(s[a]=Tr[a]));$r=s}catch{}finally{clearTimeout(e)}}const Ba={"America/Sao_Paulo":"BRL","America/Fortaleza":"BRL","America/Recife":"BRL","America/Bahia":"BRL","America/Belem":"BRL","America/Manaus":"BRL","America/Cuiaba":"BRL","America/Campo_Grande":"BRL","America/Araguaina":"BRL","America/Noronha":"BRL","America/Rio_Branco":"BRL","America/Porto_Velho":"BRL","America/Boa_Vista":"BRL","America/Maceio":"BRL","America/Santarem":"BRL","America/Eirunepe":"BRL","Europe/London":"GBP","Europe/Paris":"EUR","Europe/Berlin":"EUR","Europe/Madrid":"EUR","Europe/Rome":"EUR","Europe/Amsterdam":"EUR","Europe/Brussels":"EUR","Europe/Vienna":"EUR","Europe/Lisbon":"EUR","Europe/Dublin":"EUR","Europe/Helsinki":"EUR","Europe/Athens":"EUR","Europe/Bucharest":"RON","Europe/Budapest":"HUF","Europe/Warsaw":"PLN","Europe/Prague":"CZK","Europe/Copenhagen":"DKK","Europe/Stockholm":"SEK","Europe/Oslo":"NOK","Europe/Zurich":"CHF","Europe/Istanbul":"TRY","Europe/Moscow":"RUB","Europe/Kiev":"UAH","Europe/Kyiv":"UAH","Asia/Tokyo":"JPY","Asia/Seoul":"KRW","Asia/Shanghai":"CNY","Asia/Taipei":"TWD","Asia/Hong_Kong":"HKD","Asia/Singapore":"SGD","Asia/Kolkata":"INR","Asia/Calcutta":"INR","Asia/Bangkok":"THB","Asia/Ho_Chi_Minh":"VND","Asia/Jakarta":"IDR","Asia/Kuala_Lumpur":"MYR","Asia/Dubai":"AED","Asia/Jerusalem":"ILS","Asia/Tel_Aviv":"ILS","Asia/Manila":"PHP","Pacific/Auckland":"NZD","Australia/Sydney":"AUD","Australia/Melbourne":"AUD","Australia/Brisbane":"AUD","Australia/Perth":"AUD","Australia/Adelaide":"AUD","Australia/Hobart":"AUD","Australia/Darwin":"AUD","Australia/Lord_Howe":"AUD","America/Toronto":"CAD","America/Vancouver":"CAD","America/Edmonton":"CAD","America/Winnipeg":"CAD","America/Halifax":"CAD","America/St_Johns":"CAD","America/Regina":"CAD","America/New_York":"USD","America/Chicago":"USD","America/Denver":"USD","America/Los_Angeles":"USD","America/Phoenix":"USD","America/Anchorage":"USD","Pacific/Honolulu":"USD","America/Mexico_City":"MXN","America/Cancun":"MXN","America/Tijuana":"MXN","America/Argentina/Buenos_Aires":"ARS","America/Santiago":"CLP","America/Bogota":"COP","America/Lima":"PEN","Africa/Johannesburg":"ZAR"};function xl(){try{const s=Intl.DateTimeFormat().resolvedOptions().timeZone;if(s&&Ba[s])return Ba[s]}catch{}const e=(navigator.language||"en-US").replace("-","_"),n=Oa[e];if(n)return n;const i=e.split("_")[0],r=Oa[i];return r||"USD"}function Mi(t,e){const n=$r[e]??$r.USD,i=t*n,r=Math.round(i*100)/100;try{return new Intl.NumberFormat("en-US",{style:"currency",currency:e,minimumFractionDigits:0,maximumFractionDigits:r>=100||r%1===0?0:2}).format(r)}catch{return new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",minimumFractionDigits:0,maximumFractionDigits:2}).format(t*$r.USD)}}const ht="ccc_api_key_",Ct="ccc_session_api_key_",Ft="ccc_encryption_key",Xi="ccc_encryption_key_scope",Fy="ccc_keystore",fs="keys",Qi="ccc_encryption_key_version";let Da=null,hs=null,er=!1,ps=!1,Hu=!1;class gs extends Error{constructor(){super("Secure browser key storage is unavailable."),this.name="CredentialStorageUnavailableError"}}function Wu(){if(Hu)return;Hu=!0;const t="Secure browser key storage is unavailable. Existing credentials were left untouched; new credentials will be available only in this tab session.";console.warn(t),document.body&&Ie(t,"warning")}function wh(){return localStorage.getItem(Qi)||""}function ja(){return crypto.randomUUID?.()||Eh(crypto.getRandomValues(new Uint8Array(16)))}function Ry(){const t=wh();if(t)return t;const e=ja();return localStorage.setItem(Qi,e),e}function oi(){Da=null,hs=null,er=!1,ps=!1}window.addEventListener("storage",t=>{t.key===Qi&&oi()});function Ty(){return new Promise((t,e)=>{const n=indexedDB.open(Fy,1);n.onupgradeneeded=()=>{const i=n.result;i.objectStoreNames.contains(fs)||i.createObjectStore(fs)},n.onsuccess=()=>t(n.result),n.onerror=()=>e(n.error)})}async function Il(t,e){const n=await Ty();return new Promise((i,r)=>{const s=n.transaction(fs,t);let o;try{o=e(s.objectStore(fs))}catch(l){n.close(),r(l);return}let a;o.onsuccess=()=>{a=o.result},o.onerror=()=>r(o.error),s.oncomplete=()=>{n.close(),i(a)},s.onerror=()=>{n.close(),r(s.error||new Error("Encryption key transaction failed."))},s.onabort=()=>{n.close(),r(s.error||new Error("Encryption key transaction aborted."))}})}function $y(t){return t instanceof CryptoKey&&t.algorithm?.name==="AES-GCM"&&t.extractable===!1&&t.usages.includes("encrypt")&&t.usages.includes("decrypt")}async function My(){const t=await Il("readonly",e=>e.get(Ft));return $y(t)?t:null}async function bh(t){await Il("readwrite",e=>e.put(t,Ft))}async function Ly(){oi();try{await Il("readwrite",t=>t.delete(Ft))}catch(t){console.warn("Could not delete the stored encryption key:",t)}}async function Ny(){const t=sessionStorage.getItem(Ft);if(!t)return null;const e=await crypto.subtle.importKey("jwk",JSON.parse(t),{name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);return await bh(e),sessionStorage.removeItem(Ft),sessionStorage.removeItem(Xi),localStorage.removeItem(ht+"salt"),e}async function qu(t){const e=sessionStorage.getItem(Ft);if(e)return ps=sessionStorage.getItem(Xi)!=="session",crypto.subtle.importKey("jwk",JSON.parse(e),{name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);if(!t)throw new gs;const n=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!0,["encrypt","decrypt"]),i=await crypto.subtle.exportKey("jwk",n);return sessionStorage.setItem(Ft,JSON.stringify(i)),sessionStorage.setItem(Xi,"session"),ps=!1,crypto.subtle.importKey("jwk",i,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}async function Oy(t){if(sessionStorage.getItem(Xi)==="session"&&sessionStorage.getItem(Ft))return Wu(),er=!0,qu(t);try{const e=await My();if(e)return e;const n=await Ny();if(n)return n;const i=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);return await bh(i),i}catch(e){return console.warn("IndexedDB encryption-key storage failed:",e),Wu(),er=!0,qu(t)}}async function kl(t={}){const{allowSessionFallbackCreation:e=!0}=t,n=Ry();hs!==n&&oi();const i=Da||Oy(e);Da=i,hs=n;try{return await i}catch(r){throw oi(),r}}async function By(t){const e=await kl(),n=hs,i=new TextEncoder,r=crypto.getRandomValues(new Uint8Array(12)),s=await crypto.subtle.encrypt({name:"AES-GCM",iv:r},e,i.encode(t)),o=new Uint8Array(r.length+s.byteLength);return o.set(r),o.set(new Uint8Array(s),r.length),{ciphertext:Eh(o),keyVersion:n,sessionFallback:er}}async function Dy(t,e={}){const{isSessionCredential:n=!1}=e;try{const i=await kl({allowSessionFallbackCreation:!1});if(er&&!n&&!ps)throw new gs;const r=jy(t),s=r.slice(0,12),o=r.slice(12),a=await crypto.subtle.decrypt({name:"AES-GCM",iv:s},i,o);return new TextDecoder().decode(a)}catch(i){if(i instanceof gs)throw i;return console.error("Decryption failed:",i),null}}function Eh(t){const e=new Uint8Array(t);let n="";for(let i=0;i0}let Tn="",ai="",Ui=null,Vu=0,et="not-configured";async function Cl(){sessionStorage.getItem(Ft)&&await kl(),Tn=await Te("flutterflow"),ai=await Te("flutterflow_project_id"),Vy(),tn(),Tn?Rl():(et="not-configured",gt())}let ms=!1;function Sh(){const t=document.getElementById("api-keys-modal");Ve(t),Fl(),Tn&&Tl(Tn)}function Al(){ms=!1,Sh()}function Hy(){ms=!0;const t=document.getElementById("walkthrough-modal");t&&Ge(t),Sh()}function xh(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("api-keys-modal");e&&Ge(e);const n=ms;if(ms=!1,n){const i=document.getElementById("walkthrough-modal");i&&(et==="connected"&&Pl(),Ve(i))}}let Xt=1;function Ih(){const t=document.querySelector(".wt-steps");return t?Array.from(t.querySelectorAll(".wt-step-card")):[]}function Ms(){const t=Ih();t.length&&t.forEach((e,n)=>{const i=n+1;e.classList.remove("wt-current","wt-done","wt-pending");const r=e.querySelector(".wt-step-num");i===Xt?(e.classList.add("wt-current"),r&&(r.textContent=i)):i0&&Xt<=t&&(Xt++,Ms())}function Wy(){const t=document.getElementById("walkthrough-modal");t&&(Xt=1,Ms(),Ve(t))}function qy(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("walkthrough-modal");e&&Ge(e);const n=document.getElementById("walkthrough-dont-show");n&&n.checked&&localStorage.setItem("hasSeenWalkthrough","true")}function kh(){if(z.isVerified&&Rt()&&ae.tier!=="free")return;if(!localStorage.getItem("hasSeenWalkthrough")){const e=document.getElementById("walkthrough-modal");e&&(Xt=1,Ms(),Ve(e))}}async function Fl(){const t=document.getElementById("flutterflow-api-key-input");Tn?(t.value="",t.placeholder="Key saved (enter new to replace)"):t.placeholder="Enter your FlutterFlow API key",zy()}function zy(){Gu("flutterflow","flutterflow-key-status"),Gu("flutterflow_project_id","flutterflow-project-status")}function Gu(t,e){const n=document.getElementById(e);if(!n)return;const i=n.querySelector(".key-status-dot"),r=n.querySelector("span");It(t)?(i.className="key-status-dot configured",r.className="text-green-600",r.textContent="User key configured"):(i.className="key-status-dot missing",r.className="text-gray-500",r.textContent="Not configured")}function tn(){const t=y.step2Result&&y.step2Result.length>0,e=document.getElementById("btn-deploy-to-ff");e&&e.classList.toggle("hidden",!t)}function Vy(){const t=document.getElementById("api-keys-status");if(!t)return;const e=t.querySelectorAll(".key-status-dot"),n=["flutterflow"];e.forEach((i,r)=>{const s=n[r];s==="flutterflow"?It("flutterflow")&&It("flutterflow_project_id")?(i.className="key-status-dot configured",i.title="FlutterFlow (Fully configured)"):It("flutterflow")||It("flutterflow_project_id")?(i.className="key-status-dot env",i.title="FlutterFlow (Partially configured)"):(i.className="key-status-dot missing",i.title="FlutterFlow (Not configured)"):It(s)?(i.className="key-status-dot configured",i.title=s.charAt(0).toUpperCase()+s.slice(1)+" (User key)"):(i.className="key-status-dot missing",i.title=s.charAt(0).toUpperCase()+s.slice(1)+" (Not configured)")}),tn()}async function Gy(){const t=document.getElementById("flutterflow-api-key-input"),e=document.getElementById("flutterflow-projects-select"),n=t.value.trim();n&&await zu("flutterflow",n);const i=e?.value.trim()||"";if(i){if(!Ls(i)){Ie("The selected FlutterFlow project has an unexpected ID format.","error"),e.focus();return}await zu("flutterflow_project_id",i)}await Cl(),n&&await Rl(),Fl();const r=document.querySelector("#api-keys-modal .bg-blue-500"),s=r.textContent;r.textContent="Saved!",r.classList.remove("bg-blue-500","hover:bg-blue-600"),r.classList.add("bg-green-500"),setTimeout(()=>{r.textContent=s,r.classList.remove("bg-green-500"),r.classList.add("bg-blue-500","hover:bg-blue-600"),xh()},1e3)}async function Ky(){if(!confirm("Are you sure you want to clear all stored API keys?"))return;localStorage.setItem(Qi,ja()),oi(),localStorage.removeItem(ht+"flutterflow"),localStorage.removeItem(ht+"flutterflow_project_id"),sessionStorage.removeItem(Ct+"flutterflow"),sessionStorage.removeItem(Ct+"flutterflow_project_id"),sessionStorage.removeItem(Ft),sessionStorage.removeItem(Xi),localStorage.removeItem(ht+"salt"),await Ly(),localStorage.setItem(Qi,ja()),localStorage.removeItem(ht+"flutterflow"),localStorage.removeItem(ht+"flutterflow_project_id"),sessionStorage.removeItem(Ct+"flutterflow"),sessionStorage.removeItem(Ct+"flutterflow_project_id"),await Cl();const t=document.getElementById("flutterflow-projects-select");t&&(t.innerHTML=''),Fl()}function Ls(t){return!t||t.trim().length<5||t.includes(" ")?!1:/^[a-zA-Z0-9-]+$/.test(t)}function gt(){const t=document.getElementById("acct-ff-dot"),e=document.getElementById("acct-ff-status"),n=document.getElementById("acct-ff-endpoint"),i=document.getElementById("acct-ff-project");if(n){const o=vt();n.textContent=o.includes("staging")?"Staging":"Production"}if(i&&(i.textContent=ai||"—"),!e)return;let r,s;if(!It("flutterflow"))r="Not connected — add your FlutterFlow API key",s="";else switch(et){case"connected":r="Connected to FlutterFlow",s="ok";break;case"no-projects":r="Key accepted — no projects found",s="warn";break;case"unauthorized":r="API key rejected (401/403) — re-enter your key",s="bad";break;case"network-error":r="Could not reach FlutterFlow — check your network",s="bad";break;default:r="Checking connection…",s="warn";break}e.textContent=r,t&&(t.className=`acct-dot${s?" "+s:""}`)}async function Rl(){const t=await Te("flutterflow");if(!t||!It("flutterflow"))return et="not-configured",gt(),null;et="validating",gt();try{const n=await new ui(t,"","main",vt()).listProjects();return et=n&&n.length>0?"connected":"no-projects",gt(),n}catch(e){const n=String(e&&e.message||"");return et=/(401|403)|denied|unauthorized|scoped|list permission/i.test(n)?"unauthorized":"network-error",gt(),null}}function Yy(){ai="",localStorage.removeItem(ht+"flutterflow_project_id"),sessionStorage.removeItem(Ct+"flutterflow_project_id")}function Jy(){Yy();const t=document.getElementById("flutterflow-projects-select");t&&(t.innerHTML='',t.value=""),It("flutterflow")?(et="validating",Tl(Tn)):et="not-configured",gt()}function Zy(t,e){const n=document.getElementById(t);n&&(n.value?e?n.style.borderColor="#22c55e":n.style.borderColor="#ef4444":n.style.borderColor="")}function Xy(){const t=document.getElementById("flutterflow-api-key-input");t&&(t.addEventListener("input",e=>{const n=e.target.value.trim().length>0;Zy("flutterflow-api-key-input",n)}),t.addEventListener("blur",Qy(async e=>{const n=e.target.value.trim();n&&await Tl(n)},500)))}function Qy(t,e){let n;return function(...r){const s=()=>{clearTimeout(n),t(...r)};clearTimeout(n),n=setTimeout(s,e)}}async function Tl(t){const e=document.getElementById("flutterflow-projects-select"),n=document.getElementById("flutterflow-projects-error");if(!e){console.error("Projects dropdown element not found");return}e.innerHTML='',n&&n.classList.add("hidden"),(It("flutterflow")||t)&&(et="validating"),gt();try{const r=await new ui(t,"","main",vt()).listProjects();if(!r||r.length===0){et="no-projects",gt(),e.innerHTML='';return}et="connected",gt(),e.innerHTML='',r.forEach(s=>{const o=document.createElement("option");o.value=s.id||s.projectId||"",o.textContent=s.name||s.projectName||`Project ${s.id}`,e.appendChild(o)}),ai&&(e.value=ai)}catch(i){console.error("Failed to fetch projects:",i);const r=String(i&&i.message||"");et=/(401|403)|denied|unauthorized|scoped|list permission/i.test(r)?"unauthorized":"network-error",gt(),e.innerHTML='',n&&(n.textContent=`Failed to load projects: ${i.message}`,n.classList.remove("hidden"))}}function e0(t){const e=document.getElementById(t),i=e.nextElementSibling.querySelector("svg");e.type==="password"?(e.type="text",i.innerHTML=` + + `):(e.type="password",i.innerHTML=` + + + `)}let y={step1Result:null,step2Result:null,step3Result:null,bundleSpec:null,artifactBundle:null,bundleReview:null,selectedArtifactId:null,resultsViewMode:"summary",currentStep:0,isRunning:!1,runId:0,submittedPrompt:"",submittedImages:[]};function t0(){y.step1Result=null,y.step2Result=null,y.step3Result=null,y.bundleSpec=null,y.artifactBundle=null,y.bundleReview=null,y.selectedArtifactId=null,y.resultsViewMode="summary"}function n0(){y.bundleSpec=Ji(y.step1Result,{artifactType:"CustomWidget",artifactName:"GeneratedWidget"})}function Ns(){const t=ii(y.bundleSpec);y.artifactBundle=Ji(y.step2Result,{id:y.bundleSpec?.id,title:y.bundleSpec?.title,description:y.bundleSpec?.description,artifactType:t.artifactType,artifactName:t.artifactName,fileName:t.fileName,dependencies:t.dependencies,relationships:y.bundleSpec?.relationships,code:y.step2Result||""});const e=Rv(y.artifactBundle);y.artifactBundle={...y.artifactBundle,warnings:[...y.artifactBundle.warnings,...e.findings.map(n=>n.message)],metadata:{...y.artifactBundle.metadata,compatibility:e}},y.selectedArtifactId=ii(y.artifactBundle).id}function Os(){const t=Ji(y.step3Result,{id:y.artifactBundle?.id,title:y.artifactBundle?.title}),e=new Map(t.artifacts.map(i=>[i.id,i.review])),n=new Map(t.artifacts.filter(i=>{const r=i.review;return r&&typeof r.fixedSource=="string"&&r.fixedSource.trim()}).map(i=>[i.id,i.review.fixedSource.trim()]));y.bundleReview=Ji({id:y.artifactBundle?.id,title:y.artifactBundle?.title,artifacts:y.artifactBundle?.artifacts?.map(i=>{const r=n.get(i.id)||null;return{...i,review:e.get(i.id)||i.review||y.step3Result||null,...r?{fixedCode:r}:{}}})||[],relationships:y.artifactBundle?.relationships,warnings:y.artifactBundle?.warnings})}function Ch(){const t=$l();return{artifactType:t.artifactType||"CustomWidget",artifactName:t.artifactName||"GeneratedWidget",fileName:t.fileName||""}}function $l(){const t=y.artifactBundle||y.bundleSpec||null;return(Array.isArray(t?.artifacts)?t.artifacts:[]).find(n=>n.id===y.selectedArtifactId)||ii(t)}function Ml(){return $l().code||y.step2Result||""}async function i0(){try{await Cl()}catch(t){return console.error("checkConnection: initializeApiKeys failed:",t),!1}return!0}const Mr={production:"https://api.flutterflow.io/v2/",staging:"https://api.flutterflow.io/v2-staging/"};function r0(t,e){const n=e?.trim()?` (${e.trim().slice(0,200)})`:"";return t===401?`Your FlutterFlow API key was rejected (401 Unauthorized)${n}. Re-enter a current key under API Keys settings, then try again.`:`Listing FlutterFlow projects was denied (403)${n}. The key may be scoped to sync a single project without list permission - verify the key's access in FlutterFlow, re-enter it under API Keys settings, then retry.`}class ui{constructor(e,n,i="main",r=Mr.production){this.apiKey=e,this.baseUrl=r,this._projectId=n,this._branchName=i,this._endpoint=r}get projectId(){return this._projectId}get branchName(){return this._branchName==="main"?"":this._branchName}async exportProjectZip(){console.log(`Exporting code from FlutterFlow project: ${this.projectId}, branch: ${this.branchName||"main"}`);const e=[{project:{path:`projects/${this.projectId}`},...this.branchName?{branch_name:this.branchName}:{},export_as_module:!1,include_assets_map:!1,format:!1,export_as_debug:!1},{project_id:this.projectId,branch_name:this.branchName,include_assets:!1,export_as_module:!1}];let n=null;for(const i of e)try{const r=await fetch(`${this.baseUrl}exportCode`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify(i)});if(!r.ok){const a=await r.text();n=new Error(`Export failed: ${r.status} - ${a}`);continue}const s=await r.json(),o=s?.value?.project_zip||s?.project_zip;if(!o){n=new Error("Export response did not include project source.");continue}return o}catch(r){n=r}throw n||new Error("Export failed for an unknown reason.")}async fetchProjectSource(){const e=await this.exportProjectZip(),n=await JSZip.loadAsync(e,{base64:!0}),i=Object.keys(n.files).filter(a=>!n.files[a].dir&&(a==="pubspec.yaml"||a.endsWith("/pubspec.yaml"))).sort((a,l)=>a.split("/").length-l.split("/").length)[0];if(!i)throw new Error("Export did not contain a pubspec.yaml.");const r=i.slice(0,i.length-12),s=new Map,o=Object.keys(n.files).filter(a=>{if(n.files[a].dir||!a.startsWith(r))return!1;const l=a.slice(r.length);return l==="lib/flutter_flow/custom_functions.dart"||l.startsWith("lib/custom_code/")&&l.endsWith(".dart")});return await Promise.all(o.map(async a=>{s.set(a.slice(r.length),await n.files[a].async("string"))})),{pubspecYaml:await n.files[i].async("string"),files:s}}async pushCodeWithRetry(e,n=3){const i=[Mr.production,Mr.staging],r=Math.max(0,i.indexOf(this._endpoint));for(let s=0;ssetTimeout(d,1e3*(s+1)));continue}return l}catch(l){console.warn(`Push to ${a} failed: ${l.message}, trying next...`),await new Promise(u=>setTimeout(u,1e3*(s+1)))}}throw new Error("All API endpoints failed after retries")}async pushCode(e){return this.pushCodeWithRetry(e)}parseProjectsResponse(e){if(e?.success&&typeof e.value=="string")try{const i=JSON.parse(e.value);if(i&&Array.isArray(i.entries))return i.entries.map(r=>({id:r.id,name:r.project?.name||r.id}))}catch(i){console.error("Failed to parse stringified project value:",i)}const n=e?.projects||e?.items||e?.entries||(Array.isArray(e)?e:[]);return Array.isArray(n)?n:[]}async listProjects(){console.log("Listing projects for API key");const e=[`${this.baseUrl}listProjects`,"https://api.flutterflow.io/v2/l/listProjects"];let n=0,i="";for(const r of e){const s=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify({project_type:"ALL",deserialize_response:!0})});if(s.ok)return r!==e[0]&&console.log(`listProjects answered on legacy path ${r}`),this.parseProjectsResponse(await s.json());if(n=s.status,i=await s.text(),console.warn(`listProjects via ${r} returned ${n}: ${i}`),s.status===401||s.status===403)throw new Error(r0(s.status,i));if(s.status!==404)throw new Error(`List projects failed: ${s.status} - ${i}`)}throw new Error(`List projects failed: ${n} - ${i}`)}}async function Ll(t){const e=t.clone();let n;try{n=await t.json()}catch{const s=await e.text();if(!t.ok)return{success:!1,responseCode:t.status,errorMessage:s||`HTTP ${t.status}`,errorMap:new Map};throw new Error(`Invalid JSON response: ${s}`)}if(!t.ok){let r=n.message||`HTTP ${t.status}`,s=new Map;if(n.errors)s=new Map(Object.entries(n.errors));else if(!n.message&&typeof n=="object"){const o=Object.keys(n).filter(a=>a.endsWith(".dart")&&Array.isArray(n[a]));o.length>0&&(s=new Map(Object.entries(n)),r=o.flatMap(l=>n[l].map(u=>`${l}: ${u.errorMessage}`)).join(` +`)||`HTTP ${t.status}`)}return{success:!1,responseCode:t.status,errorMessage:r,errorMap:s}}let i={};if(n.value)try{i=typeof n.value=="string"?JSON.parse(n.value):n.value}catch(r){console.warn("Ignoring malformed push response value:",r)}return{success:!0,responseCode:t.status,errorMap:new Map(Object.entries(i))}}function Nl(t,e){return{401:"Authentication failed. Please check your FlutterFlow API key.",403:"Access denied. You may not have permission to modify this project.",404:"Project not found. Please check your Project ID.",409:"Conflict detected. The project may have been modified elsewhere.",422:"Validation failed: Invalid request format",429:"Rate limit exceeded. Please try again in a few minutes.",500:"FlutterFlow server error. Please try again later.",503:"FlutterFlow service temporarily unavailable."}[t]||`FlutterFlow API error: ${`HTTP ${t}`}`}const J={ACTION:"A",WIDGET:"W",FUNCTION:"F",CODE_FILE:"C",DEPENDENCIES:"D",OTHER:"O"},Ah=/class\s+\w+\s+extends\s+(?:StatelessWidget|StatefulWidget)\b/,Ph=/extends\s+State<\w+>/;function s0(t,e=""){if(t==="pubspec.yaml")return J.DEPENDENCIES;if(!t.endsWith(".dart")||t.endsWith("index.dart"))return J.OTHER;if(t==="custom_functions.dart")return J.FUNCTION;if(e){const n=Ah.test(e),i=Ph.test(e);if(n||i)return J.WIDGET;if(/^\s*Future(?:<[^>]+>)?\s+\w+\s*\(/m.test(e))return J.ACTION;if(e.match(/^\s*(String|int|double|bool|List|Map|dynamic|void)\s+\w+\s*\(/m))return J.FUNCTION}return J.CODE_FILE}function Fh(t,e){switch(e){case J.ACTION:return`lib/custom_code/actions/${t}`;case J.WIDGET:return`lib/custom_code/widgets/${t}`;case J.FUNCTION:return"lib/flutter_flow/custom_functions.dart";case J.CODE_FILE:return`lib/custom_code/${t}`;case J.DEPENDENCIES:return"pubspec.yaml";case J.OTHER:return`lib/custom_code/${t}`;default:return t}}async function Ol(t,e=new Map){return hv(t,e)}const Ua=new Map;function Rh(t){return`${t.baseUrl}|${t.projectId}|${t.branchName}`}function Bs(t){Ua.delete(Rh(t))}class vs extends Error{constructor(e){super(e),this.name="UnconfirmedDeployError",this.outcome=Ze.UNCONFIRMED}}function o0(t,e,n){return new Promise((i,r)=>{let s=!1;const o=(l,u,c)=>{s||(s=!0,c==="resolve"?i(u):r(u))},a=setTimeout(()=>{s||(s=!0,n(i,r))},e);t.then(l=>{clearTimeout(a),o(i,l,"resolve")},l=>{clearTimeout(a),o(r,l,"reject")})})}async function Bl(t,e,n,i,r=""){const s=zv(e,n);if(s.length===0)return{remoteFiles:n,syncFileMap:e,unverified:[],approximate:[]};const o=O_(s,r),a={...o.manifest,sources:o.sources},l=o.skipped.map(f=>f.reason);l.forEach(f=>console.warn(`[custom class deploy] ${f}`));const u=o.approximate;u.forEach(f=>console.warn(`[custom class deploy] ${f}`)),console.log(`Provisioning ${s.length} new FlutterFlow custom code file(s) before sync.`),Ne.set("provision");const c=await fetch(py,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:t.apiKey,projectId:t.projectId,baseUrl:t.baseUrl,commitMessage:i,customClasses:s,verification:a,stream:!0})}),d=await o0(j_(c,{onPhase:f=>Ne.setSubstatus(f),onLog:f=>console.log(`[custom class deploy] ${f}`)}),D_,(f,h)=>h(new vs("The deploy is still working on the FlutterFlow server, but this browser tab has stopped waiting. Your custom classes may or may not have been written — the outcome is not yet known. Open your FlutterFlow project to reconcile before retrying the deploy.")));if(!d.finalResultReceived)throw U_(d)===Ze.FAILED?new Error(d.error||`FlutterFlow custom class provisioning failed (HTTP ${d.httpStatus}).`):new vs("The connection to the FlutterFlow deploy runner dropped before it reported a result. The deploy may still be finishing on the server; open your FlutterFlow project to reconcile before retrying.");if(!d.success){const f=d.details?` ${d.details}`:"";throw new Error(`${d.error||"FlutterFlow custom class provisioning failed."}${f}`)}return Bs(t),d.verificationSkipped&&(console.warn(`[custom class deploy] ${d.verificationSkipped}`),l.push(d.verificationSkipped)),{remoteFiles:n,syncFileMap:Vv(e,s),unverified:l,approximate:u,provisionSucceeded:!0}}async function Dl(t,e={}){const n=Rh(t);let i=Ua.get(n);if(i===void 0){try{i=await t.fetchProjectSource()}catch(l){throw new Error(`Could not read your project's pubspec.yaml (${l.message}). Deploy was stopped so your existing package dependencies aren't overwritten. Check your FlutterFlow API key and project, then try again.`)}const a=ch(i.pubspecYaml);if(!a.valid)throw new Error(`Your project's pubspec.yaml could not be read reliably (${a.errors.join("; ")}). Deploy was stopped so your existing package dependencies aren't overwritten.`);Ua.set(n,i)}const r=await iy(i.pubspecYaml,e),s=T_(i.pubspecYaml,r.overrides),o=R_(s.yaml,r.additions);return r.warnings.forEach(a=>console.warn(`[pubspec] ${a}`)),o.added.length>0&&console.log("Adding dependencies:",o.added.map(a=>`${a}: ${r.additions[a]||"any"}`).join(", "),r.sdk.dartSdkFloor?`(resolved for Dart ${r.sdk.dartSdkFloor})`:""),r.kept.forEach(({name:a,constraint:l})=>console.log(`Keeping your existing ${a}: ${l||"(non-version source)"}`)),{...o,overridden:s.overridden,warnings:r.warnings,remoteFiles:i.files}}function a0(t){const e=[],n=[];t.content.length>5e4&&n.push("Code file is large (>50KB). This may take longer to commit."),t.content.length>1e5&&e.push("Code file is too large (>100KB). Consider splitting into smaller components.");const i=t.content.split(` +`).length;i>500&&n.push(`Code has ${i} lines. Consider breaking it into smaller widgets.`),t.content.includes("setState")&&t.codeType===J.ACTION&&n.push("Using setState in a Custom Action may not work as expected. Consider using a Custom Widget."),t.content.includes("dynamic")&&!t.content.includes("?")&&n.push('Code uses "dynamic" types. Consider adding explicit types for better null safety.'),t.content.match(/Color\(0xFF[0-9A-Fa-f]{6}\)/)&&n.push("Code contains hardcoded colors. Consider using FlutterFlowTheme.of(context) for theme consistency.");const r=t.content.match(/print\s*\(/g);r&&r.length>3&&n.push(`Code contains ${r.length} print statements. Consider removing debug prints before committing.`);const s=u_(t.content);if(s&&e.push(`FlutterFlow cannot format this code - ${s}. Fix or regenerate before committing.`),t.codeType===J.WIDGET){const o=eh(t.content),a=a_(t.fileName);if(o.length===0)e.push("No public widget class found (must extend StatelessWidget or StatefulWidget).");else if(!o.includes(a)){const l=`${th(o[0])}`;e.push(`Widget class name "${o[0]}" does not match the file name "${t.fileName}". FlutterFlow derives the widget from the file name, so it will report "No widget ${a} found". Rename the file to "${l}" or the class to match before committing.`)}}return{canProceed:e.length===0,issues:e,warnings:n}}function Th(t,e={}){const{artifactType:n="CustomWidget",artifactName:i="GeneratedCode",fileName:r}=e,s=s_(t);let o=r||i;if(n==="CustomFunction")o="custom_functions.dart";else if(n==="CustomWidget"){const u=eh(s)[0],c=u?th(u):null;c&&o!==c?(console.warn(`Commit file name "${o}" does not match declared widget class "${u}"; renaming to "${c}" so FlutterFlow can find the widget.`),o=c):o.endsWith(".dart")||(o+=".dart")}else o.endsWith(".dart")||(o+=".dart");let a=J.CODE_FILE;switch(n){case"CustomAction":a=J.ACTION;break;case"CustomWidget":a=J.WIDGET;break;case"CustomFunction":a=J.FUNCTION;break;case"CustomClass":case"CodeFile":a=J.CODE_FILE;break}let l="";return a===J.WIDGET?l=`// Automatic FlutterFlow imports +import '/flutter_flow/flutter_flow_theme.dart'; +import '/flutter_flow/flutter_flow_util.dart'; +import 'package:flutter/material.dart'; +// Begin custom widget code +// DO NOT REMOVE OR MODIFY THE CODE ABOVE! + +`:a===J.ACTION?l=`// Automatic FlutterFlow imports +import '/flutter_flow/flutter_flow_theme.dart'; +import '/flutter_flow/flutter_flow_util.dart'; +import 'package:flutter/material.dart'; +// Begin custom action code +// DO NOT REMOVE OR MODIFY THE CODE ABOVE! + +`:a===J.FUNCTION&&(l=`// Automatic FlutterFlow imports +import 'dart:convert'; +import 'dart:math' as math; + +import 'package:flutter/material.dart'; +import 'package:google_fonts/google_fonts.dart'; +import 'package:intl/intl.dart'; +import 'package:timeago/timeago.dart' as timeago; +import '/flutter_flow/lat_lng.dart'; +import '/flutter_flow/place.dart'; +import '/flutter_flow/uploaded_file.dart'; + +`),{content:Mv(s,l),fileName:o,codeType:a,artifactType:n,artifactName:i}}function l0(t){const e={};for(const n of _l(t))e[n]="";return e}function c0(t,e={}){return{timestamp:new Date().toISOString(),artifactType:t.artifactType,artifactName:t.artifactName,codeType:t.codeType,fileName:t.fileName,generatedFrom:e.step1Result?"pipeline":"direct",model:e.selectedModel||"unknown",codeSize:t.content.length}}function u0(t,e,n,i=new Set,r=""){const s=[],o=Ah.test(e),a=Ph.test(e);return n===J.WIDGET&&!o&&!a&&s.push("No widget class definition found (must extend StatelessWidget or StatefulWidget)"),{valid:s.length===0,errors:s}}function Ds(t){const e=[],n=[];if(!t||t.size===0)return e.push("No files to commit"),{valid:!1,errors:e,warnings:n};const i=new Set(Array.from(t.values()).flatMap(r=>Is(r.content||"")));for(const[r,s]of t.entries()){if((!s.content||s.content.trim().length===0)&&e.push(`File ${r} is empty`),s.content&&s.content.length>1e5&&n.push(`File ${r} is very large (>100KB)`),r.endsWith(".dart")){const o=u0(r,s.content,s.type,i,s.artifactName);o.valid||e.push(...o.errors.map(a=>`${r}: ${a}`))}if(r==="pubspec.yaml"){const o=ch(s.content);o.valid||e.push(...o.errors)}}return{valid:e.length===0,errors:e,warnings:n}}const Q={IDLE:"IDLE",PREPARING:"PREPARING",VALIDATING:"VALIDATING",PUSHING:"PUSHING",SUCCESS:"SUCCESS",ERROR:"ERROR"},Y={currentState:Q.IDLE,startTime:null,endTime:null,error:null,result:null,filesProcessed:0,totalFiles:0,reset(){this.currentState=Q.IDLE,this.startTime=null,this.endTime=null,this.error=null,this.result=null,this.filesProcessed=0,this.totalFiles=0},setState(t){if(!Object.values(Q).includes(t)){console.error(`Invalid commit state: ${t}`);return}this.currentState=t,t===Q.PREPARING&&(this.startTime=Date.now()),(t===Q.SUCCESS||t===Q.ERROR)&&(this.endTime=Date.now()),typeof window<"u"&&window.dispatchEvent&&window.dispatchEvent(new CustomEvent("commitStateChange",{detail:{state:t,commitState:this}})),console.log(`Commit state changed to: ${t}`)},setError(t){this.error=t,this.setState(Q.ERROR)},setSuccess(t){this.result=t,this.setState(Q.SUCCESS)},setProgress(t,e){this.filesProcessed=t,this.totalFiles=e},getElapsedTime(){return this.startTime?(this.endTime||Date.now())-this.startTime:null},isInProgress(){return this.currentState===Q.PREPARING||this.currentState===Q.VALIDATING||this.currentState===Q.PUSHING}};async function d0(t,e,n={}){let{codeType:i="W"}=n;const{pubspecDeps:r={},artifactName:s=e}=n;i==="CustomWidget"&&(i=J.WIDGET),i==="CustomAction"&&(i=J.ACTION),i==="CustomFunction"&&(i=J.FUNCTION),i==="CustomClass"&&(i=J.CODE_FILE),i==="CodeFile"&&(i=J.CODE_FILE),Y.reset(),Y.setState(Q.PREPARING);try{const o=await Te("flutterflow"),a=await Te("flutterflow_project_id");if(!o||!a)throw new Error("FlutterFlow credentials not configured. Please set your API key and Project ID in the API Keys settings.");if(!Ls(a))throw new Error("Invalid FlutterFlow Project ID format.");const l=vt(),u=new ui(o,a,"main",l);Y.setState(Q.VALIDATING);const c=new Map,d=i||s0(e,t),f=Fh(e,d);c.set(e,{artifactName:s,content:t,type:d,path:f}),Y.setProgress(0,c.size);const h=Ds(c);if(!h.valid)throw new Error(`Validation failed: +${h.errors.join(` +`)}`);const p=await Dl(u,r),g=p.yaml,m=await Bl(u,c,p.remoteFiles,`Provision ${s} custom class`,g),v=await Ol(m.syncFileMap,m.remoteFiles),E=new Map(m.syncFileMap);E.set("pubspec.yaml",{content:g,type:"D",path:"pubspec.yaml"}),Ne.set("package");const S=await jl(E),_={project_id:a,zipped_custom_code:S,uid:`web_${Date.now()}`,branch_name:u.branchName,serialized_yaml:g,file_map:v.fileMapContents,functions_map:v.functionsMapContents};Y.setState(Q.PUSHING),Y.setProgress(1,c.size),Bs(u),Ne.set("push");const x=await u.pushCode(_),I=await Ll(x);if(I.success)Y.setSuccess({fileCount:c.size,projectId:a,warnings:I.errorMap&&I.errorMap.size>0?Array.from(I.errorMap.entries()):[]});else{const M=I.errorMessage||Nl(I.responseCode);throw new Error(M)}return{success:!0,message:`Successfully committed ${e} to FlutterFlow project ${a}`,addedDependencies:p.added,unverified:m.unverified,approximate:m.approximate,warnings:I.errorMap?Array.from(I.errorMap.entries()):[]}}catch(o){return console.error("Commit failed:",o),Y.setError(o),{success:!1,error:o.message,state:Y.currentState}}}async function jl(t){const e=new JSZip;for(const[n,i]of t.entries())e.file(n,i.content);return e.generateAsync({type:"base64",compression:"DEFLATE",compressionOptions:{level:6}})}async function f0(t,e={}){const{artifactType:n,artifactName:i,fileName:r,pipelineResult:s}=e;console.log(`Starting commit for ${i} (${n})`);let o=!1;const a={projectId:null,endpoint:vt(),artifactType:n,artifactName:i,fileName:r};try{Y.setState(Q.PREPARING);const l=Th(t,{artifactType:n,artifactName:i,fileName:r}),u=l0(l.content);console.log("Detected dependencies:",u),Y.setState(Q.VALIDATING);const c=await Te("flutterflow"),d=Ui||await Te("flutterflow_project_id");if(!c)throw new Error("FlutterFlow API Key not configured. Please add it in API Keys settings.");if(!d)throw new Error("FlutterFlow Project ID not configured. Please add it in API Keys settings.");if(!Ls(d))throw new Error("Invalid FlutterFlow Project ID format.");const f=new Map;f.set(l.fileName,{artifactName:i,content:l.content,type:l.codeType,path:Fh(l.fileName,l.codeType),functionName:l.codeType===J.FUNCTION?i:void 0}),Y.setProgress(0,f.size);const h=Ds(f);if(!h.valid)throw new Error(`File validation failed: +${h.errors.join(` +`)}`);h.warnings.length>0&&console.warn("Validation warnings:",h.warnings),Y.setState(Q.PUSHING);const p=vt(),g=new ui(c,d,"main",p),m=await Dl(g,u),v=m.yaml,E=await Bl(g,f,m.remoteFiles,`Provision ${i} custom class`,v);a.projectId=d,o=E.provisionSucceeded===!0;const S=await Ol(E.syncFileMap,E.remoteFiles),_=new Map(E.syncFileMap);_.set("pubspec.yaml",{content:v,type:J.DEPENDENCIES,path:"pubspec.yaml"}),Ne.set("package");const x=await jl(_),I={project_id:d,zipped_custom_code:x,uid:`web_${Date.now()}`,branch_name:g.branchName,serialized_yaml:v,file_map:S.fileMapContents,functions_map:S.functionsMapContents};Y.setProgress(1,f.size),Bs(g),Ne.set("push");const M=await g.pushCode(I),b=await Ll(M);if(b.success){const P={...c0(l,s),projectId:d};return Y.setSuccess({...P,fileCount:f.size,warnings:b.errorMap?Array.from(b.errorMap.entries()):[]}),{success:!0,message:`Successfully committed ${l.fileName} to FlutterFlow`,metadata:P,targetIdentity:a,addedDependencies:m.added,unverified:E.unverified,approximate:E.approximate,warnings:b.errorMap?Array.from(b.errorMap.entries()):[],elapsedTime:Y.getElapsedTime()}}else{const P=b.errorMessage||Nl(b.responseCode),R=new Error(P);throw R.errorMap=b.errorMap,R}}catch(l){console.error("Commit execution failed:",l),Y.setError(l);let u=new Map;if(l.errorMap)u=l.errorMap;else if(l.message&&l.message.includes("{"))try{const c=l.message.match(/\{[\s\S]*\}/);if(c){const d=JSON.parse(c[0]);u=new Map(Object.entries(d))}}catch(c){console.warn("Failed to parse error map from commit response:",c)}return l instanceof vs?{success:!1,unconfirmed:!0,error:l.message,errorMap:u,targetIdentity:a,state:Y.currentState,elapsedTime:Y.getElapsedTime()}:o?{success:!1,partial:!0,error:l.message,errorMap:u,targetIdentity:a,state:Y.currentState,elapsedTime:Y.getElapsedTime()}:{success:!1,error:l.message,errorMap:u,targetIdentity:a,state:Y.currentState,elapsedTime:Y.getElapsedTime()}}}async function h0(t,e={}){const{pipelineResult:n}=e;let i=!1;const r={projectId:null,endpoint:vt(),artifactType:"Bundle",artifactName:t?.title,fileName:t?.fileEntries?`${t.fileEntries.length} artifacts`:"bundle"};try{if(Y.setState(Q.PREPARING),t.errors?.length>0)throw new Error(`Bundle validation failed: +${t.errors.join(` +`)}`);const s=new Map(t.fileEntries.map(I=>[I.fileName,{artifactId:I.artifactId,artifactName:I.artifactName,content:I.content,type:I.type,path:I.path,functionName:I.type===J.FUNCTION?I.artifactName:void 0}]));Y.setProgress(0,s.size);const o=Ds(s);if(!o.valid)throw new Error(`File validation failed: +${o.errors.join(` +`)}`);Y.setState(Q.VALIDATING);const a=await Te("flutterflow"),l=Ui||await Te("flutterflow_project_id");if(!a)throw new Error("FlutterFlow API Key not configured. Please add it in API Keys settings.");if(!l)throw new Error("FlutterFlow Project ID not configured. Please add it in API Keys settings.");if(!Ls(l))throw new Error("Invalid FlutterFlow Project ID format.");Y.setState(Q.PUSHING);const u=vt(),c=new ui(a,l,"main",u),d=await Dl(c,t.dependencies),f=d.yaml,h=await Bl(c,s,d.remoteFiles,`Provision ${t.title} custom classes`,f);r.projectId=l,i=h.provisionSucceeded===!0;const p=await Ol(h.syncFileMap,h.remoteFiles),g=new Map(h.syncFileMap);g.set("pubspec.yaml",{content:f,type:J.DEPENDENCIES,path:"pubspec.yaml"}),Ne.set("package");const m=await jl(g),v={project_id:l,zipped_custom_code:m,uid:`web_${Date.now()}`,branch_name:c.branchName,serialized_yaml:f,file_map:p.fileMapContents,functions_map:p.functionsMapContents};Y.setProgress(1,s.size),Bs(c),Ne.set("push");const E=await c.pushCode(v),S=await Ll(E);if(S.success){const I={...n,artifactType:"Bundle",artifactName:t.title,fileName:`${t.fileEntries.length} artifacts`,codeSize:t.fileEntries.reduce((M,b)=>M+b.content.length,0),projectId:l};return Y.setSuccess({...I,fileCount:s.size,warnings:S.errorMap?Array.from(S.errorMap.entries()):[]}),{success:!0,message:`Successfully committed ${t.fileEntries.length} artifacts to FlutterFlow`,metadata:I,targetIdentity:r,addedDependencies:d.added,unverified:h.unverified,approximate:h.approximate,warnings:S.errorMap?Array.from(S.errorMap.entries()):[],elapsedTime:Y.getElapsedTime()}}const _=S.errorMessage||Nl(S.responseCode),x=new Error(_);throw x.errorMap=S.errorMap,x}catch(s){console.error("Bundle commit execution failed:",s),Y.setError(s);const o=s.errorMap||new Map;return s instanceof vs?{success:!1,unconfirmed:!0,error:s.message,errorMap:o,targetIdentity:r,state:Y.currentState,elapsedTime:Y.getElapsedTime()}:i?{success:!1,partial:!0,error:s.message,errorMap:o,targetIdentity:r,state:Y.currentState,elapsedTime:Y.getElapsedTime()}:{success:!1,error:s.message,errorMap:o,targetIdentity:r,state:Y.currentState,elapsedTime:Y.getElapsedTime()}}}async function p0(t,e=[]){const n=pl("architect");try{return await ws("architect",_h,tv(t),n,e)}catch(i){throw i.isModelArmor||i.isUsageLimit||i.isPipelineCancel?i:new Error(`Prompt Architect failed: ${i.message}`)}}async function js(t,e,n=[],i){const r=nv(t),s=pl("generator",y.bundleSpec);try{return await ws("generator",e,r,s,n)}catch(o){if(o.isModelArmor||o.isUsageLimit||o.isPipelineCancel)throw o;if(e!==br){console.warn(`Code Generator failed with ${e}, retrying with fallback model:`,o.message),yw(e,br,i);try{return await ws("generator",br,r,s,n)}catch(a){throw a.isModelArmor||a.isUsageLimit||a.isPipelineCancel?a:new Error(`Code Generator failed: primary (${e}): ${o.message} | fallback (${br}): ${a.message}`)}}throw new Error(`Code Generator failed: ${o.message}`)}}async function Us(t,e=null){const n={...pl("review",y.artifactBundle||y.bundleSpec),architect_output:e};try{return await ws("review",yh,iv(t),n)}catch(i){throw i.isModelArmor||i.isUsageLimit||i.isPipelineCancel?i:new Error(`Code Review failed: ${i.message}`)}}function _s(t,e){const n=document.getElementById(`step${t}-item`),i=document.getElementById(`step${t}-status`);!n||!i||(n.classList.remove("active","completed","error"),i.classList.remove("running","completed","error"),e==="active"?(n.classList.add("active"),i.classList.add("running"),i.innerHTML=` + + `):e==="completed"?(n.classList.add("completed"),i.classList.add("completed"),i.innerHTML=` + + `):e==="error"?(n.classList.add("error"),i.classList.add("error"),i.innerHTML=` + + `):i.innerHTML=` + + `)}function Ce(t,e){const n=document.getElementById(`step${t}-loading`),i=document.getElementById(`step${t}-result`);e?(n.classList.remove("hidden"),i.classList.add("hidden"),_s(t,"active")):(n.classList.add("hidden"),i.classList.remove("hidden"),_s(t,"completed"))}function g0(t){const e=document.getElementById(`${t}-content`),n=document.getElementById(`${t}-chevron`);e.classList.contains("open")?(e.classList.remove("open"),n&&(n.style.transform="rotate(0deg)")):(e.classList.add("open"),n&&(n.style.transform="rotate(180deg)"))}function m0(t){tt(parseInt(t.replace("step","")))}function tt(t){for(let o=1;o<=3;o++){const a=document.getElementById(`step${o}-item`);a&&a.classList.remove("active")}const e=document.getElementById(`step${t}-item`);e&&e.classList.add("active"),$n();const n=document.getElementById("ready-state");n&&n.classList.add("hidden");for(let o=1;o<=3;o++){const a=document.getElementById(`step${o}-content`);a&&a.classList.add("hidden")}const i=document.getElementById(`step${t}-content`);i&&i.classList.remove("hidden");const r=document.getElementById("stage-title"),s={1:"Prompt Architect",2:"Code Generator",3:"Code Review"};r&&(r.textContent=s[t]||"Active Workflow Stage")}function v0(t){const e=document.getElementById(t);if(!e)return;const n=e.dataset.raw||e.textContent;navigator.clipboard.writeText(n).then(()=>{const r=e.closest(".code-container")?.querySelector(".copy-btn");r&&(r.classList.add("copied"),r.innerHTML=' Copied!',setTimeout(()=>{r.classList.remove("copied"),r.innerHTML=' Copy'},2e3))}).catch(i=>{console.warn("Failed to copy to clipboard:",i)})}function Ha(t){const e=Wa(t);console.log(`Step 1 (Prompt Architect): ${on(_h)}`),console.log(e!==t?`Step 2 (Code Generator): ${on(t)} → ${on(e)} (Free Tier fallback)`:`Step 2 (Code Generator): ${on(t)}`),console.log(`Step 3 (Code Review): ${on(yh)}`)}function $h(){return{step1Result:y.step1Result,step2Result:y.step2Result,step3Result:y.step3Result,artifactBundle:y.artifactBundle,bundleReview:y.bundleReview,selectedArtifactId:y.selectedArtifactId}}function _0(t){if(!t)return;Object.assign(y,t),new Set((y.artifactBundle?.artifacts||[]).map(n=>n.id)).has(y.selectedArtifactId)||(y.selectedArtifactId=ii(y.artifactBundle)?.id||null)}const Mh="results-replacement-error";function y0(t,{stage:e=2,runId:n,retry:i}){if(!fe(n))return;const r=document.getElementById(Mh);if(!r)return;const s=hh(t),o=document.getElementById("results-replacement-error-title"),a=document.getElementById("results-replacement-error-message"),l=document.getElementById("results-replacement-error-retry"),u=document.getElementById("results-replacement-error-upgrade");o&&(o.textContent=`${zs[e]||"Regeneration"}: ${s.title}`),a&&(a.textContent=s.message),r.hidden=!1;let c=null;u&&(u.hidden=!s.canUpgrade,s.canUpgrade&&(u.textContent="View plans",u.onclick=()=>li(),c=u)),l&&(l.hidden=s.canUpgrade,s.canUpgrade||(l.onclick=()=>{Ul(),typeof i=="function"&&i()},l.textContent="Retry",c=l)),(c||r).focus({preventScroll:!0})}function Ul(){const t=document.getElementById(Mh);t&&(t.hidden=!0)}function Lh(t,{previous:e,stage:n,runId:i,retry:r}){fe(i)&&(t.isUsageLimit&&ln(),_0(e),rr(),en(!0),sr(),Qs(),y0(t,{stage:n,runId:i,retry:r}),tn())}async function Nh(){if(console.log("runRefinement called"),y.isRunning)return;const t=document.getElementById("code-generator-model").value;y.isRunning=!0;const e=Vs();Hl("standardRegenerate",y.step2Result,y.step1Result);const n=document.querySelectorAll(".btn-refine-action"),i=$h();n.forEach(r=>{r.disabled=!0,r.innerHTML=` + + + Refining...`});try{Ul();const r=$l(),s=r.id,o=rv({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,artifactId:r.id,userFeedback:"Fix the issues listed in the audit report."});Js({runId:e}),At(2,e),tt(2),Ce(2,!0);const a=await js(o,t,[],e);if(!fe(e))return;y.step2Result=a,Ns(),Qt(2,e);const l=document.getElementById("step2-output"),u=si(y.step2Result);l.textContent=u,l.dataset.raw=u,Ce(2,!1),tt(3),At(3,e),Ce(3,!0);const c=await Us(y.step2Result,y.step1Result);if(!fe(e))return;y.step3Result=c,Os(),Qt(3,e),y.artifactBundle?.artifacts?.some(h=>h.id===s)?y.selectedArtifactId=s:y.selectedArtifactId=ii(y.artifactBundle)?.id||null;const d=document.getElementById("step3-output");d.textContent=y.step3Result,Ce(3,!1),rr();const f=Ts(y.step3Result);sr(u,f)}catch(r){if(console.error("Refinement failed:",r),!fe(e))return;const s=Rs(r,{architect:2,generator:2,review:3});Lh(r,{previous:i,stage:s,runId:e,retry:Nh})}finally{n.forEach(r=>{r.disabled=!1,r.textContent="Refine & Regenerate"}),fe(e)&&(y.isRunning=!1,tn())}}async function Hl(t,e,n){const i=`${mt}/connectFeedback`,r={type:t,code:e,input:n};try{const s=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!s.ok){const a=await s.text();return console.error(`callEndpoint failed: ${s.status} ${s.statusText}`,a),{success:!1,status:s.status,error:a}}const o=await s.json();return console.log("Telemetry success:",o),o}catch(s){return console.error("callEndpoint failed:",s),{success:!1,error:s.message}}}function w0(){const t=document.getElementById("ff-error-paste-input");t&&(t.value="")}async function Oh(){const t=document.getElementById("ff-error-paste-input"),e=t?.value?.trim();if(!e){t?.focus(),t?.classList.add("ring-2","ring-red-400","border-red-300"),setTimeout(()=>t?.classList.remove("ring-2","ring-red-400","border-red-300"),2e3);return}if(!y.step2Result){Ie("No generated code found. Please run the full pipeline first.","warning");return}if(y.isRunning)return;const n=document.getElementById("code-generator-model").value;y.isRunning=!0;const i=Vs();Hl("flutterflowError",y.step2Result,e);const r=document.getElementById("btn-fix-from-errors");r&&(r.disabled=!0,r.innerHTML=` + + Fixing…`);const s=$h();try{Ul();const o=Yf({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,userFeedback:e});fp(),Js({runId:i}),At(2,i),tt(2),Ce(2,!0);const a=await js(o,n,[],i);if(!fe(i))return;y.step2Result=a,Ns(),Qt(2,i);const l=document.getElementById("step2-output"),u=si(y.step2Result);l.textContent=u,l.dataset.raw=u,Ce(2,!1),tt(3),At(3,i),Ce(3,!0);const c=await Us(y.step2Result,y.step1Result);if(!fe(i))return;y.step3Result=c,Os(),Qt(3,i);const d=document.getElementById("step3-output");d.textContent=y.step3Result,Ce(3,!1),rr();const f=Ts(y.step3Result);sr(u,f),t&&(t.value="")}catch(o){if(console.error("Fix from errors failed:",o),!fe(i))return;const a=Rs(o,{architect:2,generator:2,review:3});Lh(o,{previous:s,stage:a,runId:i,retry:Oh})}finally{r&&(r.disabled=!1,r.textContent="Fix Errors & Regenerate"),fe(i)&&(y.isRunning=!1,tn())}}async function tr(){if(console.log("runThinkingPipeline called"),y.isRunning)return;localStorage.setItem("hasSeenWalkthrough","true");const t=document.getElementById("pipeline-input").value,e=document.getElementById("code-generator-model").value;if(!t.trim()){Ie("Please describe your FlutterFlow widget first.","warning");return}y.isRunning=!0;const n=Vs();try{if(!await q0()||!fe(n)||(await B0(),!fe(n)))return;const i=Wa(e);t.length,t0(),y.submittedPrompt=t,y.submittedImages=Pt.slice(),Va(!0),Ha(i),$n();const r=document.getElementById("ready-state");r&&r.classList.add("hidden");const s=document.getElementById("paywall-exhausted");s&&s.classList.add("hidden"),Js({prompt:t,runId:n}),Sw(),tt(1),At(1,n),Ce(1,!0);const o=Pt.filter(m=>m.url).map(m=>({url:m.url})),a=await p0(t,o);if(!fe(n))return;y.step1Result=a,n0(),Qt(1,n);const l=document.getElementById("step1-output"),u=si(y.step1Result);l.textContent=u,l.dataset.raw=u,Ce(1,!1),tt(2),At(2,n),Ce(2,!0);const c=await js(y.step1Result,i,o,n);if(!fe(n))return;y.step2Result=c,Ns(),Qt(2,n);const d=document.getElementById("step2-output"),f=si(y.step2Result);d.textContent=f,d.dataset.raw=f,Ce(2,!1),tt(3),At(3,n),Ce(3,!0);const h=await Us(y.step2Result,y.step1Result);if(!fe(n))return;y.step3Result=h,Os(),Qt(3,n);const p=document.getElementById("step3-output");p.textContent=y.step3Result,Ce(3,!1),rr();const g=Ts(y.step3Result);xw(),sr(f,g)}catch(i){if(i.isPipelineCancel||console.error("Pipeline failed:",i),!fe(n))return;const r=Rs(i,{architect:1,generator:2,review:3});i.isUsageLimit?ln():(i.message,Wa(document.getElementById("code-generator-model").value),void 0),tt(r),Ce(r,!1),lp(i,{stage:r,runId:n}),_s(r,"error")}finally{fe(n)&&(y.isRunning=!1,Va(!1),tn())}}function b0(){const t=document.getElementById("code-generator-model").value,e=[ds,"anthropic/claude-opus-5","openai/gpt-5.6-sol"].filter(i=>i!==t),n=prompt(`Retry with different model? + +Current: ${t} + +Options: +1. ${e[0]} +2. ${e[1]} + +Enter 1 or 2:`);n==="1"?(document.getElementById("code-generator-model").value=e[0],tr()):n==="2"&&(document.getElementById("code-generator-model").value=e[1],tr())}async function E0(){const t=Ml();if(!t){Ie("No code to commit. Please run the pipeline first.","warning");return}const e=await Te("flutterflow"),n=await Te("flutterflow_project_id");if(!e||!n){Ie("FlutterFlow credentials not configured. Add your API Key and Project ID in settings.","warning"),Al();return}if(y.artifactBundle?.artifacts?.length>1){await S0();return}const{artifactType:i,artifactName:r,fileName:s}=Ch(),o=Th(t,{artifactType:i,artifactName:r,fileName:s}),a=a0(o);if(!a.canProceed){Ie(`Pre-commit checks failed: ${a.issues.join("; ")}`,"error");return}zl(o,a,null,null)}async function S0(){const t=await Te("flutterflow"),e=await Te("flutterflow_project_id");if(!t||!e){Ie("FlutterFlow credentials not configured. Add your API Key and Project ID in settings.","warning"),Al();return}const n=Uv(y.artifactBundle);if(n.errors.length>0){Ie(`Bundle validation failed: ${n.errors.join("; ")}`,"error");return}const i=new Map(n.fileEntries.map(a=>[a.fileName,{content:a.content,type:a.type,path:a.path}])),r=Ds(i),s={canProceed:r.valid&&n.errors.length===0,issues:[...n.errors,...r.errors],warnings:[...n.warnings,...r.warnings]};if(!s.canProceed){Ie(`Bundle validation failed: ${s.issues.join("; ")}`,"error");return}const o={content:n.fileEntries.map(a=>`// ${a.fileName} +${a.content}`).join(` + +`),fileName:`${n.fileEntries.length} files`,codeType:"bundle",artifactType:"Bundle",artifactName:n.title};zl(o,s,n.dependencies,n)}function x0(t){let e=t.errorMap||new Map;!(e instanceof Map)&&typeof e=="object"&&(e=new Map(Object.entries(e)));let n=`
    +

    FlutterFlow Commit Failed

    +

    ${q(t.error)}

    `;if(e&&e.size>0){n+=`
    +

    Errors:

    +
      `;for(const[r,s]of e.entries()){const o=wl(s);n+=`
    • + ${q(r)}: ${q(o)} +
    • `}n+="
    "}n+="
    ",n+=`
    + +
    `;const i=document.getElementById("step3-output");i&&(i.innerHTML=n,document.getElementById("btn-regenerate-from-error")?.addEventListener("click",()=>{Bh(t.error,e)}))}async function Bh(t,e){if(y.isRunning)return;const n=document.getElementById("code-generator-model").value;y.isRunning=!0;const i=Vs(),r=document.getElementById("btn-regenerate-from-error");r&&(r.disabled=!0,r.innerHTML=` + + Fixing...`);try{let s=`The previous code had the following errors when committing to FlutterFlow: + +`;if(e&&e.size>0)for(const[h,p]of e.entries()){const g=wl(p);s+=`File: ${h} +Error: ${g} + +`}else s+=`${t} +`;const o=Yf({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,userFeedback:s});Js({runId:i}),At(2,i),tt(2),Ce(2,!0);const a=await js(o,n,[],i);if(!fe(i))return;y.step2Result=a,Ns(),Qt(2,i);const l=document.getElementById("step2-output"),u=si(y.step2Result);l.textContent=u,l.dataset.raw=u,Ce(2,!1),tt(3),At(3,i),Ce(3,!0);const c=await Us(y.step2Result,y.step1Result);if(!fe(i))return;y.step3Result=c,Os(),Qt(3,i);const d=document.getElementById("step3-output");d.textContent=y.step3Result,Ce(3,!1),rr();const f=Ts(y.step3Result);sr(u,f)}catch(s){if(console.error("Regeneration failed:",s),!fe(i))return;const o=Rs(s,{architect:2,generator:2,review:3});s.isUsageLimit&&ln(),tt(o),Ce(o,!1),lp(s,{stage:o,runId:i,retry:()=>Bh(t,e)}),_s(o,"error")}finally{r&&(r.disabled=!1,r.textContent="Fix Errors & Regenerate"),fe(i)&&(y.isRunning=!1,tn())}}async function I0(){const t=document.getElementById("ff-status-dot"),e=document.getElementById("ff-status-text");if(!t||!e)return;const n=await Te("flutterflow"),i=await Te("flutterflow_project_id");n&&i?(t.className="w-2 h-2 rounded-full bg-green-500",e.textContent="FlutterFlow credentials configured",e.className="text-green-600"):n||i?(t.className="w-2 h-2 rounded-full bg-yellow-500",e.textContent="FlutterFlow credentials incomplete",e.className="text-yellow-600"):(t.className="w-2 h-2 rounded-full bg-red-500",e.textContent="FlutterFlow credentials not configured",e.className="text-red-600")}async function Dh(t){try{const e=await fetch(`${mt}/auth/send-magic-link`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:t})});if(!e.ok)throw new Error(`Failed to send magic link: HTTP ${e.status}`);return e.json()}catch(e){throw console.error("sendMagicLink failed:",{email:t,message:e.message,stack:e.stack}),e}}async function k0(t){try{const n=await(await fetch(`${mt}/auth/verify-magic-link`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:t})})).json();if(n.error||!n.email||!n.sessionToken)throw new Error(n.error||"Invalid or expired link");return n}catch(e){throw console.error("verifyMagicLink failed:",{message:e.message,stack:e.stack}),e}}async function C0(t){try{const e=await fetch(`${mt}/auth/refresh-session`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:t})});if(!e.ok)return console.error("refreshSession: non-OK response",{url:`${mt}/auth/refresh-session`,status:e.status}),null;const n=await e.json();return n.error||!n.email||!n.sessionToken?(console.warn("refreshSession: validation failed",{error:n.error,hasEmail:!!n.email,hasToken:!!n.sessionToken}),null):n}catch(e){return console.error("refreshSession: fetch failed",{url:`${mt}/auth/refresh-session`,message:e.message,stack:e.stack}),null}}function Ku(t,e){const n=Uh(),i=(z.email||n.email)!==t;z.email=t,z.sessionToken=e,z.isVerified=!0,ae=Rn({isLoading:!0}),localStorage.setItem(ls,JSON.stringify({email:t,sessionToken:e})),i&&Gh()}function jh(){z.email=null,z.sessionToken=null,z.isVerified=!1,ae=Rn({isResolved:!0}),localStorage.removeItem(ls),localStorage.removeItem(us)}function Uh(){try{const t=localStorage.getItem(ls);if(!t)return{email:null,sessionToken:null};const e=JSON.parse(t);return!e.email||!e.sessionToken?{email:null,sessionToken:null}:e}catch(t){return console.warn("getStoredSession: failed to parse auth session:",t),localStorage.removeItem(ls),{email:null,sessionToken:null}}}async function A0(){const e=new URLSearchParams(window.location.search).get("token");if(e){window.history.replaceState({},"",window.location.pathname+window.location.hash);try{const{email:n,sessionToken:i}=await k0(e);Ku(n,i),Hh();const r=Yu();r&&!window.location.hash&&(window.location.hash=r)}catch(n){Yu();const i=n.message||"Sign-in link invalid or expired.";Ie(i,"error"),Hs(),Gn(i,"error")}}else{const{email:n,sessionToken:i}=Uh();if(n&&i){const r=await C0(i);r?Ku(r.email,r.sessionToken):jh()}}Wl()}function P0(){try{localStorage.setItem(La,JSON.stringify({hash:window.location.hash||"#home",ts:Date.now()}))}catch(t){console.warn("rememberSignInReturnSurface: failed to persist return surface:",t)}}function Yu(){try{const t=localStorage.getItem(La);if(localStorage.removeItem(La),!t)return null;const{hash:e,ts:n}=JSON.parse(t);return!e||typeof n!="number"||Date.now()-n>gy?null:e}catch(t){return console.warn("consumeSignInReturnSurface: failed to read return surface:",t),null}}function Hs(){const t=document.getElementById("signin-modal");if(!t)return;P0(),document.getElementById("signin-email-input")?.removeAttribute("aria-invalid"),Gn(""),Ve(t)}function Hh(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("signin-modal");e&&Ge(e)}function Gn(t,e){const n=document.getElementById("signin-message");n&&(n.textContent=t||"",n.classList.remove("signin-message-success","signin-message-error"),e&&n.classList.add(`signin-message-${e}`))}async function F0(){const t=document.getElementById("signin-email-input"),e=document.getElementById("signin-submit-btn"),n=Cs(t?.value);if(!n||!/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/.test(n)||n.length>254){t?.setAttribute("aria-invalid","true"),Gn("Please enter a valid email address.","error");return}t?.removeAttribute("aria-invalid"),e&&(e.disabled=!0,e.textContent="Sending…");const r=ih(n);r&&Gn(r,"error");try{const s=await Dh(n),o=s?.code===nh;t&&!o&&(t.value=""),t?.setAttribute("aria-invalid",String(o)),Gn(rh(s,n),o?"error":"success"),e&&(e.disabled=!1,e.textContent=o?"Send Sign-in Link":"Sent!",o||setTimeout(()=>{e.textContent==="Sent!"&&(e.textContent="Send Sign-in Link")},2500))}catch(s){console.error("handleMagicLinkRequest: sendMagicLink failed",{email:n,err:s}),Gn("Something went wrong. Please try again.","error"),e&&(e.disabled=!1,e.textContent="Send Sign-in Link")}}function R0(){z.email=null,z.sessionToken=null,z.isVerified=!1,ae=Rn({isResolved:!0}),x_({storage:window.localStorage,onIdentityChanged:Wl,onPlanChanged:qs})}const T0=I_({sendLink:Dh,getEmail:()=>z.email||"",onState:$0});function $0(t){const e=document.getElementById("send-new-link-btn"),n=document.getElementById("send-new-link-msg");if(!e||!n)return;if(t.status==="pending"){e.disabled=!0,e.textContent="Sending…",n.className="acct-access-msg",n.textContent="Sending a fresh sign-in link…";return}if(t.status==="sent"){e.disabled=!1,e.textContent="Send new link",n.className="acct-access-msg",n.textContent=rh(t.data,z.email||"")||"Link sent — check your email.";return}e.disabled=!1,e.textContent="Send new link",n.className="acct-access-msg error";const i=t.error?.message?`Couldn't send a link right now. ${t.error.message}`:"Couldn't send a link right now. Please try again.";n.textContent=i}async function M0(){await T0()}function L0(){const t=E_(window.localStorage),e=t.length?`Cleared disposable UI caches: ${t.join(", ")}.`:"Nothing disposable to clear.";Ie(`${e} Your run count, identity and stored keys are kept.`,"info")}function N0(){const t=document.getElementById("delete-unavailable-modal");t&&Ve(t,{trigger:document.activeElement})}function O0(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("delete-unavailable-modal");e&&Ge(e)}function Wl(){const t=z.isVerified&&!!z.email,e=document.getElementById("auth-signedout"),n=document.getElementById("auth-signedin"),i=document.getElementById("auth-guest-usage");e&&e.classList.toggle("hidden",t),n&&n.classList.toggle("hidden",!t),i&&i.classList.toggle("hidden",t);const r=document.getElementById("auth-user-email");r&&(r.textContent=z.email||"");const s=document.getElementById("access-signed-email");s&&(s.textContent=z.email||""),G0(),qs()}async function Wh(){try{if(typeof FingerprintJS>"u"){console.warn("resolveIdentity: FingerprintJS not loaded, skipping");return}const e=await(await FingerprintJS.load()).get(),n=e.visitorId,i=await fetch(yy,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({fingerprint:e.visitorId,cookie_id:n})});if(!i.ok)throw new Error(`Identity check HTTP ${i.status}`);const r=await i.json();if(dt.userId=r.user_id,dt.token=r.identity_token||null,dt.status=r.status,dt.resolved=!0,sessionStorage.setItem(vy,r.user_id),dt.token&&sessionStorage.setItem(_y,dt.token),r.usage_count!==void 0){const s=fn(),a=(r.usage_month||s)===s?r.usage_count:0;localStorage.setItem(Cn,JSON.stringify({count:a,month:s})),ln()}console.log(`Identity resolved: ${r.status} (${r.user_id.slice(0,8)}...) usage: ${r.usage_count??"n/a"}`)}catch(t){console.error("resolveIdentity failed:",t)}}let Ho=null;function B0(t=5e3){return dt.resolved?Promise.resolve():(Ho||(Ho=Wh().catch(e=>{console.warn("ensureIdentityReady: identity resolution failed",e)})),Promise.race([Ho,new Promise(e=>setTimeout(e,t))]))}function qh(){const t=fn();try{const e=localStorage.getItem(Cn);return e?JSON.parse(e):{count:0,month:t}}catch(e){return console.warn("getUsageData: failed to parse usage storage",{key:Cn,month:t,err:e}),localStorage.removeItem(Cn),{count:0,month:t}}}function fn(){const t=new Date;return`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,"0")}`}function ir(){const t=qh();return t.month!==fn()?{count:0,month:fn()}:t}function D0(){const e={count:ir().count+1,month:fn()};return localStorage.setItem(Cn,JSON.stringify(e)),e}function di(){return!!ae.isLoading}function Rt(){return!!ae.isResolved}function j0(t){if(!t)return null;const e=String(t).toLowerCase().replace(/[^a-z0-9]+/g,"_");return e==="pro"||e==="professional_plan"?"professional":e==="power_developer"||e==="power_plan"?"power":Object.prototype.hasOwnProperty.call(cs,e)?e:null}function U0(t){return t&&Object.entries(gh).find(([,e])=>e===t)?.[0]||null}function Er(...t){return t.find(e=>e!=null&&e!=="")}function H0(...t){return t.find(e=>e&&typeof e=="object")||{}}function W0(t){const e=t.data&&typeof t.data=="object"?t.data:t,n=H0(e.subscription,e.stripeSubscription,e.currentSubscription,e.customer?.subscriptions?.data?.[0],e.subscriptions?.data?.[0],e.subscriptions?.[0]),i=e.metadata||n.metadata||e.customer?.metadata||{},r=Er(e.priceId,e.price_id,e.stripePriceId,e.stripe_price_id,n.priceId,n.price_id,n.plan?.id,n.price?.id,n.items?.data?.[0]?.price?.id,n.items?.[0]?.price?.id,n.lines?.data?.[0]?.price?.id),s=Er(e.status,e.subscriptionStatus,e.subscription_status,n.status,"none"),o=j0(Er(e.tier,e.plan,e.planId,e.plan_id,e.subscriptionTier,e.subscription_tier,e.product,e.productName,n.tier,n.plan,i.tier,i.plan)),a=wy.has(String(s).toLowerCase()),l=e.active===!0||e.isSubscribed===!0||e.subscribed===!0||e.hasSubscription===!0,u=o||U0(r)||(a||l?"professional":"free");return Rn({tier:u,status:s,periodEnd:Er(e.periodEnd,e.currentPeriodEnd,e.current_period_end,n.current_period_end,n.periodEnd,null),isResolved:!0})}function Ws(){return cs[ae.tier]??cs.free}async function q0(){if(z.isVerified&&(!Rt()||di())&&(await Vh({force:!0}),qs()),z.isVerified&&!Rt())return Ie("Could not verify your subscription. Please refresh or try Manage billing.","error"),!1;const{count:t}=ir(),e=Ws();if(t>=e)return zh(t,e,{openModal:!0}),!1;const n=Math.floor(e*.8);if(t>=n){const i=e-t;Ie(`${i} run${i===1?"":"s"} remaining this month.`,"warning")}return!0}function Ju(){const t=document.getElementById("paywall-exhausted");t&&t.classList.add("hidden")}function zh(t,e,n={}){en(!0);const i=document.getElementById("walkthrough-modal");i&&Ge(i,{restoreFocus:!1});const r=document.getElementById("ready-state");r&&r.classList.add("hidden");const s=document.getElementById("preview-frame-container");s&&(s.style.display="none");const o=document.getElementById("main-stage-container");o&&o.classList.add("visible");const a=document.getElementById("results-view");a&&a.classList.remove("visible"),document.body.classList.remove("results-fullscreen","results-with-sidebar");const l=document.getElementById("pipeline-progress");l&&l.classList.remove("visible");const u=document.getElementById("paywall-exhausted");if(!u){Ie(`You've used all ${e} runs for this month. Upgrade to continue.`,"error"),li();return}const c=document.getElementById("paywall-exhausted-text");if(c){const f=ae.tier;f==="free"?c.textContent=`You've used all ${e} free generations this month. Upgrade to Pro for 50 generations/month and access to all AI models.`:c.textContent=`You've used all ${e} generations this month on your ${f} plan. Your limit resets next month.`}const d=document.getElementById("paywall-signin-btn");d&&d.classList.toggle("hidden",z.isVerified),u.classList.remove("hidden"),n.openModal&&li()}function Wa(t){return ae.tier==="free"&&Rr.includes(t)?ds:t}function z0(){const t=document.getElementById("code-options-content"),e=document.getElementById("code-generator-model");if(!t||!e)return;const n=ae.tier,r=!(z.isVerified&&!Rt())&&n==="free";Array.from(e.options).forEach(o=>{const a=on(o.value),l=Rr.includes(o.value);o.textContent=l&&r?`${a} (PRO)`:a,o.disabled=!1}),r&&Rr.includes(e.value)&&(e.value=ds),e.disabled=!1,ju.has(e)||(e.addEventListener("change",()=>{Rt()&&ae.tier==="free"&&Rr.includes(e.value)&&(e.value=ds,li()),Ha(e.value),vh()}),ju.add(e));let s=document.getElementById("model-selector-free-notice");r?(s||(s=document.createElement("p"),s.id="model-selector-free-notice",s.className="text-xs text-gray-400 mt-1",t.appendChild(s)),s.innerHTML='Free plan — Gemini only. '):s&&s.remove(),Ha(e.value)}function ql(){const t=z.isVerified&&!!z.email,e=t&&di(),n=!t||Rt(),i=ir(),r=n?i.count:0,s=n?Ws():0,o=Math.max(0,s-r),a=`${r} / ${s} runs this month`,l=hl,u=n?ae.tier||"free":null,c=document.getElementById("topbar-credits-count");c&&(e?c.textContent="…":n?c.textContent=String(o):c.textContent="—");const d=document.getElementById("credits-balance");d&&(e?d.textContent="Checking plan…":n?d.textContent=a:d.textContent="Plan check failed");const f=document.getElementById("usage-dialog-tier");f&&(e?f.textContent="Checking…":n?f.textContent=l[u]||"Free":f.textContent="Unavailable");const h=document.getElementById("usage-dialog-status");h&&(e?h.textContent="Verifying your subscription…":n?h.textContent="Runs reset at the start of each month.":h.textContent="Could not verify your subscription. Try again or sign out.");const p=document.getElementById("usage-counter");if(p)if(e&&t)p.textContent="Checking plan…",p.className="text-xs text-gray-500";else if(!n&&t)p.textContent="Plan check failed",p.className="text-xs text-red-600 font-medium";else{p.textContent=a;const g=s>0?r/s:0;p.className=g>=1?"text-xs text-red-600 font-medium":g>=.8?"text-xs text-yellow-600 font-medium":"text-xs text-gray-500"}if(!t){const g=document.getElementById("guest-usage-text");if(g){const m=qh(),v=m.month===fn()?m.count??0:0;g.textContent=`${v} / ${cs.free} generations used`}}V0()}function V0(){if(!(z.isVerified&&!!z.email))return;const e=di(),n=Rt(),i=ir(),r=n?i.count:0,s=n?Ws():0,o=Math.max(0,s-r),a=n?ae.tier||"free":null,l={free:"Free",professional:"Pro",power:"Power"}[a]||"Free",u=z.email||"",c=u.split("@")[0]||u,d=document.getElementById("acct-avatar");d&&(d.textContent=(u[0]||"?").toUpperCase());const f=document.getElementById("acct-name");f&&(f.textContent=c||"—");const h=document.getElementById("acct-plan-tier"),p=document.getElementById("acct-plan-price"),g=document.getElementById("acct-plan-note"),m=document.getElementById("acct-renewal");if(h&&(h.textContent=e?"Checking…":n?l:"Plan unavailable"),p)if(e)p.textContent="—";else if(!n)p.textContent="—";else if(a==="free")p.textContent="$0 / month";else{const b=Mi($i[a]??0,xl());p.textContent=`${b} / month`}if(g&&(e?g.textContent="Verifying your subscription…":n?a==="free"?g.textContent="No subscription. Upgrade for more generations.":g.textContent="billed monthly through Stripe":g.textContent="Could not verify your subscription. Check billing or sign out."),m){const b=Date.parse(ae.periodEnd||""),P=n&&a!=="free"&&!!ae.periodEnd&&!Number.isNaN(b);if(e)m.textContent="";else if(!n)m.textContent="";else if(a==="free")m.textContent="";else if(P){const R=new Date(b).toLocaleDateString(void 0,{year:"numeric",month:"long",day:"numeric"});m.textContent=`Renews ${R} · reset at the start of each month.`}else m.textContent="Renewal date is not available for this period."}const v=document.getElementById("acct-left-count"),E=document.getElementById("acct-left-limit"),S=document.getElementById("acct-reset-note");v&&(v.textContent=e?"…":n?String(o):"—"),E&&(E.textContent=e?"…":n?String(s):"—"),S&&(e?S.textContent="Checking plan…":n?S.textContent="Runs reset at the start of each month.":S.textContent="Plan check failed. Refresh or manage billing.");const _=document.getElementById("acct-used-count"),x=document.getElementById("acct-meter-fill"),I=document.getElementById("acct-meter-meta"),M=document.getElementById("acct-meter-track");if(_&&(_.textContent=e?"…":n?String(r):"—"),x){const b=n&&s>0?Math.min(100,Math.round(r/s*100)):0;x.style.width=`${b}%`}if(I)if(e)I.textContent="Checking…";else if(!n)I.textContent="Plan check failed";else if(s===0)I.textContent=`${r} of ${s}`;else{const b=Math.round(r/s*100);I.textContent=`${r} of ${s} · ${b}%`}M&&(e?M.setAttribute("aria-label","Checking usage…"):n?M.setAttribute("aria-label",`${r} of ${s} generations used`):M.setAttribute("aria-label","Usage unavailable")),gt()}function ln(){if(ql(),z.isVerified&&(di()||!Rt())){Ju();return}const{count:t}=ir(),e=Ws();t>=e&&!y.isRunning?zh(t,e):Ju()}function G0(){ql()}async function Vh(t={}){const e=t.force===!0;if(!z.isVerified||!z.sessionToken){ae=Rn({isResolved:!0});return}ae={...ae,isLoading:!0,error:null};const n=localStorage.getItem(us);if(!e&&n)try{const{data:i,email:r,ts:s,version:o}=JSON.parse(n);if(o===Uu&&r===z.email&&Date.now()-s<300*1e3){ae={...i,isLoading:!1,isResolved:i.isResolved!==!1};return}}catch(i){console.warn("Failed to parse subscription cache:",i,"| raw value:",n)}try{const r=await(await fetch(`${mt}/stripe/get-subscription`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:z.sessionToken,user_id:dt.userId})})).json();if(r.error){if(["unauthorized","invalid session","expired session"].some(o=>String(r.error).toLowerCase().includes(o))){jh(),Wl();return}ae=Rn({isResolved:!1,error:r.error});return}ae=W0(r),localStorage.setItem(us,JSON.stringify({version:Uu,data:ae,email:z.email,ts:Date.now()}))}catch(i){console.error("fetchSubscription failed:",i),ae={...ae,isLoading:!1,isResolved:!1,error:i.message}}}function Gh(){localStorage.removeItem(us)}async function K0(t){if(!z.isVerified||!z.sessionToken){Kh(),Hs();return}if(!gh[t]){Ie("Invalid plan selected.","error");return}const e=document.getElementById(`checkout-btn-${t}`);e&&(e.disabled=!0,e.textContent="Redirecting…");try{const i=await(await fetch(`${mt}/stripe/create-checkout-session-intl`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tierId:t,sessionToken:z.sessionToken,currency:xl()})})).json();if(i.error||!i.url)throw new Error(i.error||"Failed to create checkout session");const{url:r}=i;window.location.href=r}catch(n){console.error("startCheckout failed:",n),e&&(e.disabled=!1,e.textContent="Subscribe"),Ie("Could not start checkout. Please try again.","error")}}async function Y0(t){if(!z.isVerified||!z.sessionToken){Hs();return}const e=t||document.getElementById("manage-billing-btn"),n=e?e.textContent:"";e&&(e.disabled=!0,e.textContent="Loading…");try{const r=await(await fetch(`${mt}/stripe/create-portal-session`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:z.sessionToken})})).json();if(r.error||!r.url)throw new Error(r.error||"Failed to open billing portal");const{url:s}=r;window.location.href=s}catch(i){console.error("openCustomerPortal failed:",i),e&&(e.disabled=!1,e.textContent=n),Ie("Could not open billing portal. Please try again.","error")}}const ys=new Set;function J0(){ys.forEach(t=>t.abort()),ys.clear()}async function ws(t,e,n,i={},r=[]){const o=new AbortController;ys.add(o);let a=!1;const l=setTimeout(()=>{a=!0,o.abort()},12e4);try{const u=await fetch(my,{method:"POST",headers:{"Content-Type":"application/json",...dt.token?{Authorization:`Bearer ${dt.token}`}:{}},signal:o.signal,body:JSON.stringify({user_id:dt.userId,step:t,model:e,prompt:n,images:r,context:i})}),c=await u.text();let d={};try{d=c?JSON.parse(c):{}}catch{d={}}if(u.status===429){d.serverCount!==void 0&&(localStorage.setItem(Cn,JSON.stringify({count:d.serverCount,month:fn()})),ln());const p=new Error(d.message||"Monthly usage limit reached. Upgrade to continue.");throw p.isUsageLimit=!0,p.pipelineStep=t,p}const f=dv(d,t);if(f)throw f;if(console.log(`[BuildShip] ${t} response keys:`,Object.keys(d),"content type:",typeof d.content),!u.ok)throw new Error(`${d.message||d.error||"BuildShip pipeline error"} (HTTP ${u.status})`);if(t==="generator")if(d.usage_status==="success"&&Number.isFinite(d.usage_count)){const p=fn();(d.usage_month||p)===p&&(localStorage.setItem(Cn,JSON.stringify({count:d.usage_count,month:p})),ln())}else D0(),ln();let h=d.output||d.content;if(!h){const p=c?` (body: ${c.slice(0,120)})`:"";throw new Error(`BuildShip returned no output for step "${t}"${p}`)}return Array.isArray(h)&&(h=h.map(p=>typeof p=="string"?p:p.text||"").join("")),typeof h!="string"&&(h=JSON.stringify(h)),h}catch(u){if(u.name==="AbortError"){if(a)throw new Error(`BuildShip ${t} timed out after ${12e4/1e3}s`);const c=new Error(`BuildShip ${t} request cancelled`);throw c.isPipelineCancel=!0,c}throw u instanceof TypeError?new Error(`BuildShip unreachable: ${u.message}`):u}finally{clearTimeout(l),ys.delete(o)}}let qa=!1;function Z0(){const e=new URLSearchParams(window.location.search).get("checkout");return e==="success"?(window.history.replaceState({},"",window.location.pathname+window.location.hash),Gh(),qa=!0):e==="cancel"&&(window.history.replaceState({},"",window.location.pathname+window.location.hash),Ie("Checkout cancelled.","info")),e}function X0(){if(!qa)return;qa=!1;const t=ae.tier!=="free";Ie(t?"Subscription active! Your plan is live.":"Checkout complete — confirming your subscription. Check Manage billing if it does not update.",t?"success":"info")}function qs(){const t=z.isVerified&&!!z.email,e=ae.tier,n=t&&di(),i=!t||Rt(),r=document.getElementById("subscription-tier-badge");if(r){const a=hl,l={free:"bg-gray-100 text-gray-600",professional:"bg-indigo-100 text-indigo-700",power:"bg-purple-100 text-purple-700",unresolved:"bg-red-50 text-red-600"};r.textContent=n?"Checking…":i?a[e]||"Free":"Plan unavailable",r.className=`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${i?l[e]||l.free:l.unresolved}`}const s=document.getElementById("upgrade-prompt");s&&s.classList.toggle("hidden",!t||n||!i||e!=="free");const o=document.getElementById("manage-billing-btn");o&&o.classList.toggle("hidden",!t||n||i&&e==="free"),Q0(i?e:null),z0(),vh(),ln(),hp()}function Q0(t){const e=["bg-gray-100","text-gray-500","cursor-default"];Object.entries({professional:{btnId:"checkout-btn-professional",defaultText:"Subscribe"},power:{btnId:"checkout-btn-power",defaultText:"Subscribe"}}).forEach(([r,{btnId:s,defaultText:o}])=>{const a=document.getElementById(s);a&&(r===t?(a.disabled=!0,a.textContent="Current plan",a.classList.add(...e)):(a.disabled=!1,a.textContent=o,a.classList.remove(...e)))});const i=document.getElementById("free-tier-current");i&&i.classList.toggle("hidden",t!=="free")}function ew(){document.querySelectorAll(".pm-card[data-tier]").forEach(t=>{const e=t.dataset.tier,n=Xm[e];if(!n)return;const i=t.querySelector("ul.pm-features");if(i){i.innerHTML="";for(const r of n){const s=document.createElement("li");s.textContent=r,i.appendChild(s)}}})}function za(){const t=xl(),e=document.getElementById("pro-price"),n=document.getElementById("power-price"),i=document.getElementById("plans-pro-price"),r=document.getElementById("plans-power-price"),s=document.getElementById("pro-price-note"),o=document.getElementById("power-price-note"),a=document.getElementById("plans-pro-price-note"),l=document.getElementById("plans-power-price-note");e&&(e.textContent=Mi($i.professional,t)),n&&(n.textContent=Mi($i.power,t)),i&&(i.textContent=Mi($i.professional,t)),r&&(r.textContent=Mi($i.power,t));const u="billed monthly";s&&(s.textContent=u),o&&(o.textContent=u),a&&(a.textContent=u),l&&(l.textContent=u)}function li(){za();const t=document.getElementById("pricing-modal");t&&Ve(t),Py().then(()=>za())}function Kh(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("pricing-modal");e&&Ge(e)}function Ie(t,e="info"){const n={success:"bg-green-600 text-white",error:"bg-red-600 text-white",warning:"bg-amber-500 text-white",info:"bg-gray-800 text-white"},i=document.createElement("div");i.className=`fixed bottom-6 left-1/2 -translate-x-1/2 px-5 py-3 rounded-lg text-sm font-medium shadow-lg z-50 transition-opacity duration-300 ${n[e]||n.info}`,i.textContent=t,document.body.appendChild(i),setTimeout(()=>{i.style.opacity="0",setTimeout(()=>i.remove(),300)},3500)}document.addEventListener("DOMContentLoaded",async()=>{Ym(),hljs.configure({tabReplace:" ",classPrefix:"hljs-"}),tw(),window.__heroField=H_(),window.__pipelineLogo=V_(),hy({onSubmit:tr}),await A0(),Z0(),await Vh(),X0(),qs(),za(),ew(),await i0(),Xy();const t=document.getElementById("flutterflow-endpoint-select");if(t){const n=vt();t.value=n}kh(),Wh();const e=document.getElementById("pipeline-input");e&&(e.addEventListener("input",()=>{Xt===2&&e.value.trim().length>0&&(Pl(),Ms())}),e.addEventListener("blur",()=>{const n=document.getElementById("walkthrough-modal");Xt===2&&n&&Ve(n)}),e.addEventListener("keydown",n=>{if(n.key==="Tab"){const i=document.getElementById("walkthrough-modal");Xt===2&&i&&setTimeout(()=>{Ve(i)},100)}})),window.addEventListener("commitStateChange",n=>{const{state:i}=n.detail;i===Q.PREPARING||i===Q.VALIDATING||i===Q.PUSHING?(Ne.phaseId||tp(),Xu(i)):(i===Q.SUCCESS||i===Q.ERROR)&&(Xu(i),setTimeout(Vl,1e3))}),Ql()});function tw(){const t=document.getElementById("preview-frame-container");t&&(t.style.display="")}function nw(){const t=document.getElementById("welcome-video-player");t&&(t.addEventListener("click",$n),document.addEventListener("keydown",$n))}function $n(){const t=document.getElementById("preview-frame-container"),e=document.getElementById("main-stage-container"),n=document.getElementById("ready-state");t&&(t.style.display="none"),e&&e.classList.add("visible"),n&&n.classList.remove("hidden");const i=document.getElementById("welcome-video-player");i&&i.removeEventListener("click",$n),document.removeEventListener("keydown",$n),kh()}let Hi=null;async function iw(){const t=document.getElementById("confirm-project-select");if(!t)return;const e=++Vu,n=()=>e===Vu,i=await Te("flutterflow"),r=await Te("flutterflow_project_id");if(n()){if(!i){t.innerHTML='',t.disabled=!0;return}t.disabled=!1,t.innerHTML='';try{const o=await new ui(i,"","main",vt()).listProjects();if(!n())return;if(!o||o.length===0){t.innerHTML='';return}t.innerHTML='',o.forEach(a=>{const l=document.createElement("option");l.value=a.id||a.projectId||"",l.textContent=a.name||a.projectName||`Project ${a.id}`,t.appendChild(l)}),r&&(t.value=r)}catch(s){if(!n())return;console.error("Failed to load projects for deploy:",s),t.innerHTML=''}}}function rw(){return document.getElementById("confirm-project-select")?.value?.trim()||null}function zl(t,e,n,i=null){Hi={codeInfo:t,checks:e,deps:n,bundlePlan:i},document.getElementById("confirm-file-name").textContent=t.fileName,document.getElementById("confirm-artifact-type").textContent=t.artifactType,document.getElementById("confirm-file-size").textContent=`${(t.content.length/1024).toFixed(1)} KB`,document.getElementById("confirm-line-count").textContent=i?`${i.fileEntries.length} files`:t.content.split(` +`).length,iw();const r=document.getElementById("confirm-deps-list"),s=document.getElementById("confirm-deps-section");n&&Object.keys(n).length>0?(r.innerHTML=Object.entries(n).map(([u,c])=>{const d=c?`at least ${Zt(c)}`:"version resolved from your project";return`
  • • ${Zt(u)}: ${d}
  • `}).join(""),s.classList.remove("hidden")):s.classList.add("hidden");const o=document.getElementById("confirm-warnings-list"),a=document.getElementById("confirm-warnings-section");e.warnings&&e.warnings.length>0?(o.innerHTML=e.warnings.map(u=>`
  • • ${Zt(u)}
  • `).join(""),a.classList.remove("hidden")):a.classList.add("hidden"),document.getElementById("confirm-code-preview").textContent=t.content,document.getElementById("code-preview-content").classList.add("hidden"),document.getElementById("code-preview-chevron").style.transform="rotate(0deg)";const l=document.getElementById("commit-confirm-modal");l&&Ve(l)}function Yh(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("commit-confirm-modal");e&&Ge(e),Hi=null}function sw(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("commit-success-modal");e&&Ge(e);const n=["success-message","success-project-id","success-file-name","success-artifact-type","success-time","success-size"];for(const s of n){const o=document.getElementById(s);o&&(o.textContent="")}const i=document.getElementById("success-warnings-section");i&&i.classList.add("hidden");const r=document.getElementById("success-warnings-list");r&&(r.innerHTML="")}function Jh(t){const e=(m,v)=>{const E=document.getElementById(m);E&&(E.textContent=v||"")},n=t.metadata?.fileName||"",i=t.metadata?.projectId||"",r=t.metadata?.artifactType||"",s=t.elapsedTime?`${(t.elapsedTime/1e3).toFixed(1)}s`:"",o=t.metadata?.codeSize?`${(t.metadata.codeSize/1024).toFixed(1)} KB`:"";e("success-message",t.message||"Code committed successfully!"),e("success-project-id",i),e("success-file-name",n),e("success-artifact-type",r),e("success-time",s),e("success-size",o);const a=t.addedDependencies||[],l=document.getElementById("success-deps-row");l&&l.classList.toggle("hidden",a.length===0),e("success-deps",a.join(", "));const u=document.getElementById("success-open-ff-link");u&&i&&(u.href=`https://app.flutterflow.io/project/${i}`);const c=document.getElementById("success-warnings-section"),d=document.getElementById("success-warnings-list"),f=t.unverified||[],h=t.approximate||[],p=t.warnings||[];(p.length>0||f.length>0||h.length>0)&&c&&d&&(d.innerHTML=[...f.map(m=>`
  • Not verified before deploying: ${q(String(m))}
  • `),...h.map(m=>`
  • Verified approximately: ${q(String(m))}
  • `),...p.map(([m,v])=>`
  • ${q(m)}: ${q(String(v))}
  • `)].join(""),c.classList.remove("hidden"));const g=document.getElementById("commit-success-modal");g&&Ve(g)}function Zh(t){Vl(),x0(t)}function Xh(t,{heading:e,title:n,guidance:i}){const r=t.targetIdentity||{},s=document.getElementById("commit-terminal-modal");if(!s)return!1;const o=(h,p)=>{const g=document.getElementById(h);g&&(g.textContent=p||"")};o("terminal-heading",e),o("terminal-title",n),o("terminal-message",t.error||t.message||"");const a=document.getElementById("terminal-identity-list");if(a){const h=[["Project",r.projectId||t.metadata?.projectId],["Endpoint",r.endpoint],["File",r.fileName||t.metadata?.fileName],["Artifact",r.artifactType||t.metadata?.artifactType]];a.innerHTML=h.map(([p,g])=>`
    ${q(p)}:${q(String(g??"—"))}
    `).join("")}const l=document.getElementById("terminal-file-outcomes");let u=t.errorMap;u&&!(u instanceof Map)&&(u=new Map(Object.entries(u))),l&&u&&u.size>0?(l.innerHTML=[...u.entries()].map(([h,p])=>`
  • ${q(h)}: ${q(wl(p))}
  • `).join(""),l.classList.remove("hidden")):l&&l.classList.add("hidden");const c=document.getElementById("terminal-guidance");c&&(c.innerHTML=i);const d=document.getElementById("terminal-open-ff-link"),f=r.projectId||t.metadata?.projectId;return d&&(d.href=f?`https://app.flutterflow.io/project/${f}`:"https://app.flutterflow.io/"),Ve(s),!0}function Qh(t){Xh(t,{heading:"Deploy partially applied",title:"Some custom classes reached FlutterFlow, but the deploy did not fully complete.",guidance:"The custom classes the runner confirmed are already in your project and are not lost. Review the per-file errors above, fix them in FlutterFlow or regenerate, then deploy again. Open the project to see exactly what landed."})}function ep(t){Xh(t,{heading:"Deploy outcome not yet known",title:"This browser stopped waiting before the FlutterFlow server reported a result.",guidance:"The deploy may still be finishing on the server — it was not cancelled. Open your FlutterFlow project and confirm whether the class landed before retrying, so you do not push a duplicate or build on top of an unknown state."})}function ow(t){t&&t.target!==t.currentTarget||Ge(document.getElementById("commit-terminal-modal"))}function aw(){const t=document.getElementById("code-preview-content"),e=document.getElementById("code-preview-chevron");t.classList.contains("hidden")?(t.classList.remove("hidden"),e.style.transform="rotate(90deg)"):(t.classList.add("hidden"),e.style.transform="rotate(0deg)")}const Zu={prepare:{message:"Preparing your code...",start:4,end:14},validate:{message:"Checking FlutterFlow credentials...",start:14,end:22},project:{message:"Reading your FlutterFlow project...",start:22,end:40},provision:{message:"Creating custom classes in FlutterFlow...",start:40,end:82},package:{message:"Packaging files for upload...",start:82,end:88},push:{message:"Pushing to FlutterFlow...",start:88,end:97},done:{message:"Complete!",start:100,end:100}},lw=[{after:0,text:"Starting a FlutterFlow build runner..."},{after:12,text:"Preparing the FlutterFlow AI workspace..."},{after:35,text:"Uploading your custom classes..."},{after:60,text:"FlutterFlow is applying the changes..."},{after:100,text:"Still working — this can take a couple of minutes..."}],Ne={sequence:[],phaseId:null,phaseStartedAt:null,timer:null,substatus:null,liveSubstatus:!1,start({withProvisioning:t=!1}={}){this.sequence=["prepare","validate","project"],t&&this.sequence.push("provision"),this.sequence.push("package","push","done");const e=document.getElementById("commit-progress-overlay");e&&(_u(e,!0,"Deploying to FlutterFlow"),Ve(e)),this.set("prepare")},set(t,e=null){if(!(!Zu[t]||t===this.phaseId)){if(!this.sequence.includes(t)){const n=this.sequence.indexOf("package");this.sequence.splice(n===-1?this.sequence.length:n,0,t)}this.phaseId=t,this.phaseStartedAt=Date.now(),this.substatus=e,this.liveSubstatus=!1,this.render(),this.timer&&clearInterval(this.timer),t!=="done"&&(this.timer=setInterval(()=>this.render(),500))}},setSubstatus(t){t&&(this.liveSubstatus=!0,this.substatus=t,this.render())},render(){const t=Zu[this.phaseId];if(!t)return;const e=(Date.now()-this.phaseStartedAt)/1e3,n=t.start+(t.end-t.start)*(1-Math.exp(-e/25));if(this.phaseId==="provision"&&!this.liveSubstatus){const o=lw.filter(a=>e>=a.after).pop();o&&(this.substatus=o.text)}const i=this.sequence.indexOf(this.phaseId),s=[`Step ${i===-1?1:i+1} of ${this.sequence.length}`];e>=5&&s.push(cw(e)),np(this.phaseId==="done"?100:n,t.message,s.join(" · "),this.substatus)},stop(){this.timer&&clearInterval(this.timer),this.timer=null,this.phaseId=null;const t=document.getElementById("commit-progress-overlay");t&&(_u(t,!1),Ge(t,{force:!0,restoreFocus:!1}))}};function cw(t){const e=Math.floor(t);return e<60?`${e}s elapsed`:`${Math.floor(e/60)}m ${String(e%60).padStart(2,"0")}s elapsed`}function tp(t){Ne.start(t)}function Vl(){Ne.stop()}function np(t,e,n,i=null){const r=document.getElementById("commit-progress-bar"),s=document.getElementById("progress-message"),o=document.getElementById("progress-detail"),a=document.getElementById("progress-substatus");r&&(r.style.width=`${Math.round(t*10)/10}%`),s&&(s.textContent=e),o&&(o.textContent=n),a&&(a.textContent=i||"",a.classList.toggle("hidden",!i))}function Xu(t){const e={[Q.PREPARING]:"prepare",[Q.VALIDATING]:"validate",[Q.PUSHING]:"project",[Q.SUCCESS]:"done"};if(t===Q.ERROR){Ne.timer&&clearInterval(Ne.timer),Ne.timer=null,np(100,"Failed","Error occurred");return}const n=e[t];n&&Ne.set(n)}function uw(t){return t.bundlePlan?t.bundlePlan.fileEntries.some(e=>e.type===J.CODE_FILE):t.codeInfo?.codeType===J.CODE_FILE}let ip=!1;function rp(t){ip=t;const e=document.querySelector("#commit-confirm-modal button[data-deploy-confirm]");e&&(e.disabled=t),[...document.querySelectorAll("[data-deploy-start]"),...document.querySelectorAll("#btn-deploy-to-ff")].forEach(i=>{i.disabled=t})}function Qu(t){Vl(),rp(!1);const e=dh(t);e===Ze.COMMITTED?Jh(t):e===Ze.PARTIAL?Qh(t):e===Ze.UNCONFIRMED?ep(t):Zh(t)}async function dw(){if(!Hi){console.error("No pending commit data");return}if(ip){console.warn("Deploy already in flight; ignoring duplicate confirm.");return}const t=Hi;if(Hi=null,Ui=rw(),Yh(),rp(!0),tp({withProvisioning:uw(t)}),t.bundlePlan){const o=await h0(t.bundlePlan,{pipelineResult:{step1Result:y.step1Result,selectedModel:document.getElementById("code-generator-model")?.value}});Ui=null,Qu(o);return}const{codeInfo:e}=t,{artifactType:n,artifactName:i,fileName:r}=Ch(),s=await f0(e.content,{artifactType:n,artifactName:i,fileName:r,pipelineResult:{step1Result:y.step1Result,selectedModel:document.getElementById("code-generator-model")?.value}});Ui=null,Qu(s)}window.runThinkingPipeline=tr;window.toggleStep=m0;window.toggleSection=g0;window.selectWorkflowStep=tt;window.copyCode=v0;window.retryWithDifferentModel=b0;window.openApiKeysModal=Al;window.closeApiKeysModal=xh;window.walkthroughConnectAccount=Hy;window.closeWalkthroughModal=qy;window.openWalkthroughModal=Wy;window.advanceWalkthrough=Pl;window.commitToFlutterFlow=d0;function fw(){const t=document.getElementById("pipeline-input");t&&t.focus()}function hw(){const t=document.getElementById("advanced-settings");t&&(t.open=!0);const e=document.getElementById("code-generator-model");e&&(e.scrollIntoView({behavior:"smooth",block:"center"}),e.focus(),e.click())}window.focusPromptInput=fw;window.openModelSelector=hw;window.handlePromptImageSelect=Cy;window.removePromptImage=Ay;window.saveApiKeys=Gy;window.validateFlutterFlowConnection=Rl;window.clearAllApiKeys=Ky;window.toggleKeyVisibility=e0;window.handleWelcomeVideoEnd=nw;window.dismissWelcomeVideo=$n;window.initiateCommitToFlutterFlow=E0;window.updateFlutterFlowCredentialStatus=I0;window.openCommitConfirmModal=zl;window.closeCommitConfirmModal=Yh;window.closeCommitSuccessModal=sw;window.closeCommitTerminalModal=ow;window.showCommitPartialModal=Qh;window.showCommitUnconfirmedModal=ep;window.showCommitSuccessModal=Jh;window.showCommitFailureModal=Zh;window.toggleCodePreview=aw;window.confirmCommitToFlutterFlow=dw;window.runRefinement=Nh;window.regenerateFromPastedErrors=Oh;window.clearErrorInput=w0;window.setFlutterFlowEndpoint=Uy;window.getFlutterFlowEndpoint=vt;window.commitProgress=Ne;window.openSignInModal=Hs;window.closeSignInModal=Hh;window.handleMagicLinkRequest=F0;window.handleSignOut=R0;window.handleSendNewLink=M0;window.handleClearCache=L0;window.handleDeleteAccount=N0;window.closeDeleteUnavailableModal=O0;window.startCheckout=K0;window.openCustomerPortal=Y0;window.openPricingModal=li;window.closePricingModal=Kh;let Lr=null,sp=null,Mn={1:"pending",2:"pending",3:"pending"},Gl=1,Kl=null;const zs={1:"Prompt Architect",2:"Code Generator",3:"Code Review"},pw={1:"Understanding your prompt",2:"Generating Dart code",3:"Running the code audit"},gw={1:"Prompt understood",2:"Dart code generated",3:"Code audit complete"};function Vs(){return y.runId+=1,y.runId}function fe(t){return t===void 0||t===y.runId}function mw(){y.runId+=1}function Yl(t){return document.getElementById(`pdot-${t}`)}function Va(t){const e=document.getElementById("btn-run-pipeline")||document.getElementById("hero-send");e&&(e.disabled=t,e.classList.toggle("is-busy",t),t?e.setAttribute("aria-busy","true"):e.removeAttribute("aria-busy"))}function Gs(t){const e=document.getElementById("pipeline-progress");e&&(e.dataset.runState=t)}function An(t,e){Mn[t]=e;const n=Yl(t);if(!n)return;n.dataset.state=e,n.disabled=e==="pending"||e==="skipped";const i=zs[t],r={pending:"not started",active:"in progress",done:"complete",failed:"failed",skipped:"not run"};n.setAttribute("aria-label",`Step ${t} of 3, ${i}: ${r[e]||e}`),e==="active"?n.setAttribute("aria-current","step"):n.removeAttribute("aria-current")}function vw(){return[1,2,3].filter(t=>Mn[t]==="done").length}function Ks(){const t=document.getElementById("pipeline-progress-fill");t&&(t.style.width=`${vw()/3*100}%`);const e=document.getElementById("progress-stage-count");e&&(e.textContent=`Step ${Gl} of 3`)}function Ys(t,{done:e=!1}={}){const n=document.getElementById("progress-title-text"),i=document.getElementById("progress-substep-text"),r=Mn[t],s=e||r==="done";if(n&&(n.textContent=s?gw[t]:pw[t]),i){const o=s?" — complete":r==="failed"?" — stopped":"";i.textContent=`Step ${t} of 3 — ${zs[t]}${o}`}}function _w(t){Mn[t]==="pending"||Mn[t]==="skipped"||(Kl=t,[1,2,3].forEach(e=>{const n=Yl(e);n&&n.setAttribute("aria-pressed",String(e===t))}),Ys(t))}function Jl(){Kl=null,[1,2,3].forEach(t=>{const e=Yl(t);e&&e.removeAttribute("aria-pressed")})}function op(t){const e=document.getElementById("pipeline-note");e&&(e.textContent=t||"",e.hidden=!t)}function yw(t,e,n){fe(n)&&op(`${on(t)} did not answer. Continuing on ${on(e)}.`)}function Zl(){const t=document.getElementById("pipeline-failure");if(!t)return;t.hidden=!0;const e=document.getElementById("pipeline-failure-actions");e&&e.replaceChildren()}const ww=1120;function bw(){const t=getComputedStyle(document.documentElement).getPropertyValue("--t-morph").trim(),e=Number.parseFloat(t);return Number.isFinite(e)&&e>0?e:ww}let Jn=null,Nr=null;function Ew(){return window.matchMedia?.("(prefers-reduced-motion: reduce)").matches===!0}function cn(){if(Nr){try{Nr.cancel()}catch{}Nr=null}Jn&&(Jn.remove(),Jn=null),window.removeEventListener("resize",cn)}function ap(t,e){if(cn(),Ew()||!t||!e||!document.body||typeof Element.prototype.animate!="function")return;const n=t.getBoundingClientRect(),i=e.getBoundingClientRect();if(!n.width||!n.height||!i.width||!i.height)return;const r=document.createElement("div");r.className="composer-morph",r.setAttribute("aria-hidden","true"),r.style.cssText=`left:${i.left}px;top:${i.top}px;width:${i.width}px;height:${i.height}px;opacity:0;`,document.body.appendChild(r);const s=n.left+n.width/2-(i.left+i.width/2),o=n.top+n.height/2-(i.top+i.height/2),a=n.width/i.width,l=n.height/i.height,u=`translate(${s}px,${o}px) scale(${a},${l})`,c=r.animate([{transform:u,opacity:0,offset:0,easing:"cubic-bezier(.2,0,0,1)"},{transform:u,opacity:1,offset:.14,easing:"cubic-bezier(.4,0,.2,1)"},{transform:`translate(${s}px,${o}px) scale(${a*.93},${l*.93})`,opacity:1,offset:.28,easing:"cubic-bezier(.32,1.38,.5,1)"},{transform:"translate(0px,0px) scale(1,1)",opacity:1,offset:1}],{duration:bw(),fill:"both"});Jn=r,Nr=c,window.addEventListener("resize",cn),c.onfinish=()=>{if(Jn!==r)return;const d=r.animate([{opacity:1},{opacity:0}],{duration:260,fill:"forwards"});d.onfinish=()=>{Jn===r&&cn()}}}function Sw(){const e=document.getElementById("composer")?.getBoundingClientRect();e&&requestAnimationFrame(()=>{requestAnimationFrame(()=>{ap({getBoundingClientRect:()=>e},document.getElementById("main-stage-container"))})})}function xw(){ap(document.getElementById("pipeline-progress"),document.getElementById("main-stage-container"))}window.addEventListener("hashchange",cn);window.addEventListener("popstate",cn);function Js(t={}){const{prompt:e=null,runId:n}=t;if(!fe(n))return;Xs(),en(!0);const i=document.getElementById("pipeline-progress"),r=document.getElementById("results-view"),s=document.getElementById("ready-state");if(s&&s.classList.add("hidden"),r&&r.classList.remove("visible"),document.body.classList.remove("results-fullscreen","results-with-sidebar"),i&&i.classList.add("visible"),Gs("running"),e!==null){const a=document.getElementById("pipeline-submitted-prompt");a&&(a.textContent=e)}sp=Date.now();const o=document.getElementById("progress-elapsed");o&&(o.textContent="0s"),Mn={1:"pending",2:"pending",3:"pending"},Jl(),Zl(),op(""),[1,2,3].forEach(a=>An(a,"pending")),At(1,n),Iw()}function At(t,e){fe(e)&&(Gl=t,Jl(),[1,2,3].forEach(n=>{n===t?An(n,"active"):nt&&An(n,"pending")}),Ys(t),Ks())}function Qt(t,e){fe(e)&&(An(t,"done"),Kl===null&&Ys(t,{done:!0}),Ks())}function lp(t,{stage:e=1,runId:n,retry:i=cp}={}){if(!fe(n))return;Zs(),Xs(),cn(),Gs("failed"),en(!0);const r=document.getElementById("pipeline-progress");r&&r.classList.add("visible");const s=document.getElementById("results-view");s&&s.classList.remove("visible"),document.body.classList.remove("results-fullscreen","results-with-sidebar"),An(e,"failed"),[1,2,3].forEach(p=>{p>e&&An(p,"pending")}),Gl=e,Jl(),Ys(e),Ks();const o=hh(t),a=document.getElementById("pipeline-failure"),l=document.getElementById("pipeline-failure-title"),u=document.getElementById("pipeline-failure-message"),c=document.getElementById("pipeline-failure-hint"),d=document.getElementById("pipeline-failure-actions");if(!a||!l||!u||!d)return;if(a.dataset.kind=o.kind,l.textContent=`${zs[e]}: ${o.title}`,u.textContent=o.message,c){const p=o.detail&&o.detail!==o.message?o.detail:"";c.textContent=p,c.hidden=!p}d.replaceChildren();const f=[o.canUpgrade&&{id:"upgrade",label:"View plans",variant:"primary",onClick:()=>li()},o.canRetry&&{id:"retry",label:"Retry",variant:o.canUpgrade?"secondary":"primary",onClick:i},o.canEdit&&{id:"edit",label:"Edit prompt",variant:"secondary",onClick:Ga}].filter(Boolean);!o.canEdit&&!o.canRetry&&f.push({id:"edit",label:"Back to prompt",variant:"secondary",onClick:Ga}),f.forEach(p=>{const g=document.createElement("button");g.type="button",g.textContent=p.label,g.dataset.action=p.id,g.dataset.variant=p.variant,g.addEventListener("click",p.onClick),d.appendChild(g)}),a.hidden=!1;const h=d.querySelector("button");h&&h.focus({preventScroll:!0})}function Ga(){mw(),J0(),y.isRunning=!1,Va(!1),tn(),Gs("settled"),cn(),Zs(),Xs(),Zl();const t=document.getElementById("pipeline-progress");t&&t.classList.remove("visible"),en(!1);const e=document.getElementById("pipeline-input");e&&(y.submittedPrompt&&(e.value=y.submittedPrompt),e.focus({preventScroll:!0}),e.setSelectionRange(e.value.length,e.value.length))}function cp(){const t=document.getElementById("pipeline-input");t&&y.submittedPrompt&&(t.value=y.submittedPrompt),Pt=y.submittedImages.slice(),$s(),Zl(),tr()}function Iw(){Zs(),Lr=setInterval(()=>{const t=(Date.now()-sp)/1e3,e=document.getElementById("progress-elapsed");e&&(e.textContent=`${Math.floor(t)}s`)},250)}function Zs(){Lr&&(clearInterval(Lr),Lr=null)}let Wi=null;function Xs(){Wi&&(clearTimeout(Wi),Wi=null)}function rr(){Zs(),Xs(),Gs("settled"),Ks();const t=document.getElementById("pipeline-progress-fill");Wi=setTimeout(()=>{Wi=null;const e=document.getElementById("pipeline-progress");e&&e.classList.remove("visible"),t&&(t.style.width="0%")},400)}function Pn(t,e=""){const n={pass:'',warning:'',fail:'',info:''};return``}function up(t){return{pass:"Passed review",warning:"Needs attention",fail:"Blocking issues"}[t]||"Needs attention"}function kw(){return i_({bundle:y.artifactBundle,reviewResult:y.step3Result})}function Cw(t){return` +
    + ${Pn(t.severity)} +
    +
    ${q(t.message)}
    + ${t.suggestion?`
    ${q(t.suggestion)}
    `:""} + ${q(t.source)} +
    +
    + `}function Aw(t){return` +
  • +
    + ${q(t.title)} + ${t.detail&&t.detail!==t.title?`

    ${q(t.detail)}

    `:""} +
    +
  • + `}function Pw(t){const e=document.getElementById("results-summary-detail"),n=document.getElementById("results-title");if(!e)return;n&&(n.textContent=t.title);const i=t.score,r=i==null?"neutral":i>=80?"pass":i>=60?"warning":"fail",s=i==null?"":i>=80?"Strong":i>=60?"Needs work":"High risk",o=t.findings.length?` +
      + ${t.findings.map(u=>` +
    • + ${Pn(u.severity)} + + ${q(u.message)} + ${u.suggestion?`${q(u.suggestion)}`:""} + +
    • + `).join("")} +
    + `:"",a=t.warnings.length?` +
    +

    ${Pn("warning")} Bundle

    +
      + ${t.warnings.map(u=>`
    • ${q(u)}
    • `).join("")} +
    +
    + `:"",l=t.manualSteps.length?` +
    +

    ${Pn("info")} Complete in FlutterFlow

    +

    For your information — these don't block the deploy. Finish them by hand in the FlutterFlow editor once the code is pushed.

    +
      + ${t.manualSteps.map(u=>` +
    • + ${q(u.title)} + ${u.detail&&u.detail!==u.title?`${q(u.detail)}`:""} +
    • + `).join("")} +
    +
    + `:"";e.innerHTML=` +
    +
    +

    ${q(t.summary)}

    + ${o} + ${a} + ${l} +
    +
    + +
    + Is the generated code correct? +
    + + +
    + +
    +
    +
    + `}function Fw(t){const e=t.artifacts.find(l=>l.id===y.selectedArtifactId)||t.artifacts[0];if(!e)return"";const n={pass:{icon:"pass",message:"No file-specific issues were found."},warning:{icon:"warning",message:"This file needs attention, but Code Review did not return a specific finding."},fail:{icon:"fail",message:"This file is blocked, but Code Review did not return a specific finding."}}[e.status],i=e.findings.length?e.findings.map(Cw).join(""):`
    ${Pn(n.icon)} ${q(n.message)}
    `,r=e.dependencies?.length?e.dependencies.map(l=>` +
  • ${q(l.name)}${l.version?` ${q(l.version)}`:""}${l.reason?`

    ${q(l.reason)}

    `:""}
  • + `).join(""):'
  • No external packages
  • ',s=e.imports?.length?e.imports.map(l=>`${q(l)}`).join(""):'No imports returned',o=e.publicApi?.length?e.publicApi.map(l=>`${q(l)}`).join(""):'No public API signature returned',a=e.relationships.length?e.relationships.map(l=>` +
  • ${q(l.from||"Bundle")} ${q(l.type)} ${q(l.to||"Bundle")}${l.description?`

    ${q(l.description)}

    `:""}
  • + `).join(""):'
  • No relationships for this file
  • ';return` +
    +
    + ${Pn(e.status)} ${q(up(e.status))} +

    ${q(e.artifactName)}

    + ${e.description?`

    ${q(e.description)}

    `:""} +
    +
    + ${q(e.artifactType)} + ${q(e.fileName)} +
    +
    +
    +

    Code Review findings

    + ${i} +
    + ${e.manualSteps.length?` +
    +

    Manual FlutterFlow steps for this file

    +
      ${e.manualSteps.map(Aw).join("")}
    +
    + `:""} +
    + File details +
    +
    +

    Dependencies

    +
      ${r}
    +
    +
    +

    Deployment

    +
    +
    Status
    ${q(e.deployStatus||"pending")}
    +
    Order
    ${e.index+1} of ${t.artifacts.length}
    +
    Path hint
    ${q(e.pathHint||"Not returned")}
    +
    +
    +
    +
    +

    Public API

    +
    ${o}
    +
    +
    +

    Imports

    +
    ${s}
    +
    +
    +

    Relationships

    +
      ${a}
    +
    +
    + `}function Rw(t){const e=document.getElementById("bundle-strip"),n=document.getElementById("results-summary-tab"),i=document.getElementById("artifact-tabs"),r=document.getElementById("results-file-count");if(n){const s=y.resultsViewMode==="summary";n.classList.toggle("active",s),n.setAttribute("role","tab"),n.setAttribute("aria-selected",String(s)),n.setAttribute("aria-controls","results-summary-detail"),n.tabIndex=s?0:-1}if(i&&(i.setAttribute("role","tablist"),i.setAttribute("aria-label","Artifacts in this bundle")),!t.artifacts.length){r&&(r.textContent="0 files"),e&&e.classList.remove("visible"),i&&(i.innerHTML=""),ed();return}if(r){const s=t.artifacts.length;r.textContent=`${s} ${s===1?"file":"files"}`}i&&(i.innerHTML=t.artifacts.map(s=>{const o=y.resultsViewMode==="file"&&s.id===y.selectedArtifactId;return` + + `}).join(""),i.onclick=s=>{const o=s.target.closest(".artifact-tab");o?.dataset?.artifactId&&Xl(o.dataset.artifactId)},ed()),e&&e.classList.add("visible")}function ed(){const t=document.getElementById("bundle-strip");!t||t.dataset.tabKeyboard==="bound"||(t.dataset.tabKeyboard="bound",t.addEventListener("keydown",e=>{if(e.defaultPrevented)return;const n=[document.getElementById("results-summary-tab"),...Array.from(document.querySelectorAll("#artifact-tabs .artifact-tab"))].filter(Boolean);if(!n.length||!n.includes(document.activeElement))return;let i=-1;const r=n.indexOf(document.activeElement);if(e.key==="ArrowRight")i=(r+1)%n.length;else if(e.key==="ArrowLeft")i=(r-1+n.length)%n.length;else if(e.key==="Home")i=0;else if(e.key==="End")i=n.length-1;else return;e.preventDefault();const s=n[i];if(!s)return;if(s.id==="results-summary-tab")dp();else{const a=s.dataset.artifactId;a&&Xl(a)}const o=s.id==="results-summary-tab"?document.getElementById("results-summary-tab"):document.querySelector(`#artifact-tabs .artifact-tab[data-artifact-id="${s.dataset.artifactId}"]`);o&&o.focus()}))}function Qs(){document.body.classList.add("results-fullscreen"),document.body.classList.add("results-with-sidebar");const t=document.getElementById("results-view"),e=document.getElementById("results-code-output"),n=document.getElementById("results-audit-output"),i=document.getElementById("results-summary-detail"),r=document.getElementById("artifact-results-split"),s=kw(),o=Ml();if(i&&(i.setAttribute("role","tabpanel"),i.setAttribute("aria-labelledby","results-summary-tab")),r){r.setAttribute("role","tabpanel");const a=s?.artifacts?.find(l=>l.id===y.selectedArtifactId);r.setAttribute("aria-labelledby",a?`artifact-tab-${a.id}`:"results-summary-tab")}if(Pw(s),Rw(s),e&&(e.textContent=""),e){const a=ph(o);e.innerHTML=a}n&&(n.innerHTML=Fw(s)),i&&i.classList.toggle("hidden",y.resultsViewMode!=="summary"),r&&r.classList.toggle("hidden",y.resultsViewMode!=="file"),t&&t.classList.add("visible")}function sr(t,e){en(!0),y.selectedArtifactId||(y.selectedArtifactId=ii(y.artifactBundle).id),y.resultsViewMode="summary",document.body.classList.add("results-fullscreen");const n=document.getElementById("step3-output");n&&(n.textContent=""),Qs(),tn(),Tw()}function Tw(){const t=document.getElementById("btn-feedback-up"),e=document.getElementById("btn-feedback-down"),n=document.getElementById("results-feedback-status");t&&(t.className="feedback-btn",t.setAttribute("aria-pressed","false"),t.disabled=!1,t.removeAttribute("aria-disabled")),e&&(e.className="feedback-btn",e.setAttribute("aria-pressed","false"),e.disabled=!1,e.removeAttribute("aria-disabled")),n&&(n.textContent=""),Ka=!1}function Xl(t){y.selectedArtifactId=t,y.resultsViewMode="file",Qs()}function dp(){y.resultsViewMode="summary",Qs()}function $w(){const t=document.getElementById("btn-copy-results"),e=document.getElementById("results-copy-status"),n=Ml(),i=(r,s)=>{e&&(e.textContent=r,e.classList.toggle("ok",!!s),e.classList.toggle("fail",!s))};if(!navigator.clipboard?.writeText){i("Copying isn't supported in this browser.",!1);return}navigator.clipboard.writeText(n).then(()=>{if(i("Copied to clipboard",!0),t){t.classList.add("copied");const r=t.querySelector("span");if(r){const s=r.textContent;r.textContent="Copied!",setTimeout(()=>{t.classList.remove("copied"),r.textContent=s},2e3)}}}).catch(()=>{i("Clipboard permission was denied. Select the code to copy it manually.",!1)})}let Ka=!1;async function Mw(t){const e=document.getElementById("btn-feedback-up"),n=document.getElementById("btn-feedback-down"),i=document.getElementById("results-feedback-status");if(!e||!n||Ka)return;const r=l=>{i&&(i.textContent="",i.offsetWidth,i.textContent=l)},s=l=>{Ka=l,[e,n].forEach(u=>{u.disabled=l,u.setAttribute("aria-disabled",String(l))})},o=t==="up"?"thumbsUp":"thumbsDown";s(!0),r("Submitting review feedback…");const a={type:o,code:y.step2Result,input:y.step1Result};try{const l=await Hl(a.type,a.code,a.input);if(!l||l.success!==!0){s(!1),r("Review feedback could not be sent. Tap again to retry.");return}e.classList.toggle("active-up",t==="up"),n.classList.toggle("active-down",t==="down"),e.setAttribute("aria-pressed",String(t==="up")),n.setAttribute("aria-pressed",String(t==="down")),s(!1),r("Review feedback saved.")}catch{s(!1),r("Review feedback could not be sent. Tap again to retry.")}}function Lw(){const t=document.getElementById("error-input-panel");if(t){t.classList.remove("hidden"),t.style.display="flex";const e=document.getElementById("ff-error-paste-input");e&&setTimeout(()=>e.focus(),100)}}function fp(){const t=document.getElementById("error-input-panel");t&&(t.classList.add("hidden"),t.style.display="none")}function en(t){const e=document.getElementById("generation-stage");e&&(t?(e.hidden=!1,e.inert=!1,requestAnimationFrame(()=>e.classList.add("is-active"))):(e.classList.remove("is-active"),e.inert=!0,setTimeout(()=>{e.classList.contains("is-active")||(e.hidden=!0)},260)))}function hp(){const t=z.isVerified&&!!z.email,e=ae.tier||"free",n=t&&di(),i=!t||Rt(),s=n?"Checking…":i?hl[e]||"Free":"—",o=document.getElementById("topbar-plan");o&&(o.textContent=s);const a=document.getElementById("topbar-avatar");a&&(a.textContent=(z.email||"?")[0].toUpperCase()),ql();const l=document.getElementById("plans-free-current");l&&l.classList.toggle("hidden",e!=="free"||!i);const u=document.getElementById("plans-checkout-btn-professional");if(u){const d=e==="professional"&&i;u.disabled=d,u.textContent=d?"Current plan":"Subscribe"}const c=document.getElementById("plans-checkout-btn-power");if(c){const d=e==="power"&&i;c.disabled=d,c.textContent=d?"Current plan":"Subscribe"}}function Nw(){hp();const t=document.getElementById("credits-modal");t&&Ve(t)}function Ow(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("credits-modal");e&&Ge(e)}function pp(t,e=!0,n=!0){if(t=["home","account","plans"].includes(t)?t:"home",document.querySelectorAll(".view[data-view]").forEach(r=>{r.dataset.view===t?(r.hidden=!1,r.removeAttribute("inert"),requestAnimationFrame(()=>{r.classList.add("is-active"),n&&r.focus({preventScroll:!0})})):(r.classList.remove("is-active"),r.setAttribute("inert","true"),setTimeout(()=>{r.classList.contains("is-active")||(r.hidden=!0)},260))}),t!=="home")en(!1);else{const r=document.getElementById("main-stage-container");r&&r.classList.contains("visible")&&en(!0)}if(document.querySelectorAll(".nav-link[data-view]").forEach(r=>{const s=r.dataset.view===t;r.setAttribute("aria-current",s?"page":null),s||r.removeAttribute("aria-current")}),e){const r=t==="home"?"":`#${t}`;window.location.hash!==r&&window.history.pushState({view:t},"",r||"#")}}let td=!1;function Ql(){const t=window.location.hash.replace(/^#/,"");pp(t||"home",!1,td),td=!0}window.addEventListener("popstate",t=>{Ql()});window.addEventListener("hashchange",()=>{Ql()});window.copyResultsCode=$w;window.selectArtifact=Xl;window.selectResultsSummary=dp;window.submitResultsFeedback=Mw;window.showErrorInputPanel=Lw;window.hideErrorInputPanel=fp;window.setGenerationStageVisible=en;window.switchView=pp;window.selectPipelineStage=_w;window.editPipelinePrompt=Ga;window.retryPipelineRun=cp;window.openCreditsModal=Nw;window.closeCreditsModal=Ow; diff --git a/dist/assets/index-CNM4BL4C.js b/dist/assets/index-CNM4BL4C.js deleted file mode 100644 index ae86c29..0000000 --- a/dist/assets/index-CNM4BL4C.js +++ /dev/null @@ -1,317 +0,0 @@ -(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const r of document.querySelectorAll('link[rel="modulepreload"]'))i(r);new MutationObserver(r=>{for(const s of r)if(s.type==="childList")for(const o of s.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&i(o)}).observe(document,{childList:!0,subtree:!0});function n(r){const s={};return r.integrity&&(s.integrity=r.integrity),r.referrerPolicy&&(s.referrerPolicy=r.referrerPolicy),r.crossOrigin==="use-credentials"?s.credentials="include":r.crossOrigin==="anonymous"?s.credentials="omit":s.credentials="same-origin",s}function i(r){if(r.ep)return;r.ep=!0;const s=n(r);fetch(r.href,s)}})();var _=typeof window<"u"?window:void 0,Te=typeof globalThis<"u"?globalThis:_,Be=Te?.navigator,C=Te?.document,ue=Te?.location,Na=Te?.fetch,Ro=Te!=null&&Te.XMLHttpRequest&&"withCredentials"in new Te.XMLHttpRequest?Te.XMLHttpRequest:void 0,Vl=Te?.AbortController,Df=Te?.CompressionStream,Ue=Be?.userAgent;function Bu(){return!(!_||_.navigator.onLine===!1)}var ti=typeof globalThis<"u"?globalThis:_;ti&&typeof self>"u"&&(ti.self=ti),ti&&typeof File>"u"&&(ti.File=function(){});var T=_??{},ee={DEBUG:!1,LIB_VERSION:"0.5.0",LIB_NAME:"browser-common"};function Gl(t,e,n,i,r,s,o){try{var a=t[s](o),l=a.value}catch(u){return void n(u)}a.done?e(l):Promise.resolve(l).then(i,r)}function ne(t){return function(){var e=this,n=arguments;return new Promise((function(i,r){var s=t.apply(e,n);function o(l){Gl(s,i,r,o,a,"next",l)}function a(l){Gl(s,i,r,o,a,"throw",l)}o(void 0)}))}}function E(){return E=Object.assign?Object.assign.bind():function(t){for(var e=1;arguments.length>e;e++){var n=arguments[e];for(var i in n)({}).hasOwnProperty.call(n,i)&&(t[i]=n[i])}return t},E.apply(null,arguments)}function Du(t,e){if(t==null)return{};var n={};for(var i in t)if({}.hasOwnProperty.call(t,i)){if(e.indexOf(i)!==-1)continue;n[i]=t[i]}return n}var Kl=t=>{if(typeof t!="string")return t;try{return JSON.parse(t)}catch{return t}};function Yl(t){return typeof t=="string"||t}function Jl(t){return typeof t=="string"?t:void 0}var ni,jf=["$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","irclid","_kx","$session_id","$window_id","$lib","$lib_version","$device_id","$is_server"],Ft=(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.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.SurveysSeen="surveys_seen",t.Surveys="surveys",t.RemoteConfig="remote_config",t.FlagsEndpointWasHit="flags_endpoint_was_hit",t.DeviceId="device_id",t})({}),Zl=(function(t){return t.GZipJS="gzip-js",t.Base64="base64",t})({}),Uf=["$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"],Hf=["token"],ju="NativeGzipValidationError",To=t=>t.length>=2&&t[0]===31&&t[1]===139,Xl=(t,e)=>t===Zl.GZipJS||e===Zl.GZipJS||e==="gzip",Ql=t=>!(!t||typeof t!="object")&&("name"in t?String(t.name):"")==="NotReadableError",Ki=t=>{var e=new Error("Native gzip produced invalid output: "+t);throw e.name=ju,e},Wf=(function(){var t=ne((function*(e,n){18>e.size&&Ki("too-short");var i=new Uint8Array(yield e.slice(0,10).arrayBuffer());To(i)&&i[2]===8||Ki("invalid-header");var r=new DataView(yield e.slice(e.size-8).arrayBuffer());r.getUint32(0,!0)!==(o=>{for(var a=(()=>{if(ni)return ni;ni=[];for(var c=0;256>c;c++){for(var d=c,h=0;8>h;h++)d=1&d?3988292384^d>>>1:d>>>1;ni[c]=d>>>0}return ni})(),l=4294967295,u=0;o.length>u;u++)l=a[255&(l^o[u])]^l>>>8;return(4294967295^l)>>>0})(n)&&Ki("invalid-crc");var s=n.length>>>0;r.getUint32(4,!0)!==s&&Ki("invalid-size")}));return function(e,n){return t.apply(this,arguments)}})();function $o(){return $o=ne((function*(t,e,n){e===void 0&&(e=!0);try{var i=new TextEncoder().encode(t),r=new globalThis.CompressionStream("gzip"),s=r.writable.getWriter(),o=s.write(i).then((()=>s.close())).catch((function(){var u=ne((function*(c){try{yield s.abort(c)}catch{}throw c}));return function(c){return u.apply(this,arguments)}})()),a=new Response(r.readable).blob(),l=(yield Promise.all([a,o]))[0];return yield Wf(l,i),l}catch(u){if(n!=null&&n.rethrow)throw u;return e&&console.error("Failed to gzip compress data",u),null}})),$o.apply(this,arguments)}var qf=["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","pinterest","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"],ec=function(t,e){if(e===void 0&&(e=[]),!t)return!1;var n=t.toLowerCase();return qf.concat(e).some((i=>{var r=i.toLowerCase();return n.indexOf(r)!==-1}))};function B(t,e){return t.indexOf(e)!==-1}var us=function(t){return t.trim()},Mo=function(t){return t.replace(/^\$/,"")};function Uu(t){var e,n=[];return(e=JSON.stringify(t,(function(i,r){if(typeof r=="bigint")return r.toString();if(typeof r!="function"&&typeof r!="symbol"){if(r instanceof Error)return{name:r.name,message:r.message,stack:r.stack};if(r&&typeof r=="object"){for(;n.length>0&&n[n.length-1]!==this;)n.pop();if(n.includes(r))return"[Circular]";n.push(r)}return r}})))!==null&&e!==void 0?e:"null"}var Hu=Object.prototype,Wu=Hu.hasOwnProperty,ds=Hu.toString,D=Array.isArray||function(t){return ds.call(t)==="[object Array]"},Ne=t=>typeof t=="function",ae=t=>t===Object(t)&&!D(t),Nt=t=>{if(ae(t)){for(var e in t)if(Wu.call(t,e))return!1;return!0}return!1},x=t=>t===void 0,K=t=>ds.call(t)=="[object String]",Lo=t=>K(t)&&t.trim().length===0,We=t=>t===null,j=t=>x(t)||We(t),Se=t=>ds.call(t)=="[object Number]"&&t==t,At=t=>Se(t)&&t>0,at=t=>ds.call(t)==="[object Boolean]",zf=t=>t instanceof FormData,Vf=t=>B(Uf,t),Gf=t=>B(Hf,t);function qu(t){return t===null||typeof t!="object"}function kr(t,e){return{}.toString.call(t)==="[object "+e+"]"}function Oa(t){return typeof Event<"u"&&zu(t,Event)}function zu(t,e){try{return t instanceof e}catch{return!1}}var Kf=[!0,"true",1,"1","yes"],Xs=t=>B(Kf,t),Yf=[!1,"false",0,"0","no"];function _t(t,e,n,i,r){return e>n&&(i.warn("min cannot be greater than max."),e=n),Se(t)?t>n?(i.warn(" cannot be greater than max: "+n+". Using max value instead."),n):e>t?(i.warn(" cannot be less than min: "+e+". Using min value instead."),e):t:(i.warn(" must be a number. using max or fallback. max: "+n+", fallback: "+r),_t(r||n,e,n,i))}class Jf{constructor(e){this.tt={},this.et=e.et,this.it=_t(e.bucketSize,0,100,e.rt),this.nt=_t(e.refillRate,0,this.it,e.rt),this.st=_t(e.refillInterval,0,864e5,e.rt)}ot(e,n){var i=Math.floor((n-e.lastAccess)/this.st);i>0&&(e.tokens=Math.min(e.tokens+i*this.nt,this.it),e.lastAccess=e.lastAccess+i*this.st)}consumeRateLimit(e){var n,i=Date.now(),r=String(e),s=this.tt[r];return s?this.ot(s,i):this.tt[r]=s={tokens:this.it,lastAccess:i},s.tokens===0||(s.tokens--,s.tokens===0&&((n=this.et)==null||n.call(this,e)),s.tokens===0)}stop(){this.tt={}}}var Ye="Mobile",Ir="iOS",Ot="Android",Un="Tablet",Vu=Ot+" "+Un,Gu="iPad",Ku="Apple",Yu=Ku+" Watch",yi="Safari",Hn="BlackBerry",Ju="Samsung",Zu=Ju+"Browser",Xu=Ju+" Internet",_n="Chrome",Zf=_n+" OS",Qu=_n+" "+Ir,Ba="Internet Explorer",ed=Ba+" "+Ye,Da="Opera",Xf=Da+" Mini",ja="Edge",td="Microsoft "+ja,Bn="Firefox",nd=Bn+" "+Ir,Ai="Nintendo",Pi="PlayStation",Dn="Xbox",id=Ot+" "+Ye,rd=Ye+" "+yi,hi="Windows",No=hi+" Phone",tc="Nokia",Oo="Ouya",sd="Generic",Qf=sd+" "+Ye.toLowerCase(),od=sd+" "+Un.toLowerCase(),Bo="Konqueror",ad="Oculus Browser",Cr="Vivaldi",ld="Yandex",Ar="Whale",Do="DuckDuckGo",cd="Pale Moon",Pr="Waterfox",wi="Brave",ud="Google Search App",pe="(\\d+(\\.\\d+)?)",Qs=new RegExp("Version/"+pe),ep=new RegExp(Dn,"i"),tp=new RegExp(Pi+" \\w+","i"),np=new RegExp(Ai+" \\w+","i"),Ua=new RegExp(Hn+"|PlayBook|BB10","i"),ip={"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"},dd=function(t,e,n,i){e=e||"";var r=(function(s){return s!=null&&s.brave?wi:null})(n);return r||(i!=null&&i.detectGoogleSearchApp&&B(t,"GSA/")?ud:B(t," OPR/")&&B(t,"Mini")?Xf:B(t," OPR/")?Da:Ua.test(t)?Hn:B(t,"IE"+Ye)||B(t,"WPDesktop")?ed:B(t,"OculusBrowser")?ad:B(t,Zu)?Xu:B(t,ja)||B(t,"Edg/")?td:B(t,Cr+"/")?Cr:B(t,"YaBrowser/")?ld:B(t,Ar+"/")?Ar:B(t,Do+"/")||B(t,"Ddg/")?Do:B(t,"FBIOS")?"Facebook "+Ye:B(t,"UCWEB")||B(t,"UCBrowser")?"UC Browser":B(t,"CriOS")?Qu:B(t,"CrMo")||B(t,_n)?_n:B(t,Ot)&&B(t,yi)?id:B(t,"FxiOS")?nd:B(t.toLowerCase(),Bo.toLowerCase())?Bo:B(t,wi+"/")?wi:((s,o)=>o&&B(o,Ku)||(function(a){return B(a,yi)&&!B(a,_n)&&!B(a,Ot)})(s))(t,e)?B(t,Ye)?rd:yi:B(t,"PaleMoon/")?cd:B(t,Pr+"/")?Pr:B(t,Bn)?Bn:B(t,"MSIE")||B(t,"Trident/")?Ba:B(t,"Gecko")?Bn:"")},rp={[ed]:[new RegExp("rv:"+pe)],[td]:[new RegExp(ja+"?\\/"+pe)],[_n]:[new RegExp("("+_n+"|CrMo)\\/"+pe)],[Qu]:[new RegExp("CriOS\\/"+pe)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+pe)],[yi]:[Qs],[rd]:[Qs],[Da]:[new RegExp("(Opera|OPR)\\/"+pe)],[Bn]:[new RegExp(Bn+"\\/"+pe)],[nd]:[new RegExp("FxiOS\\/"+pe)],[Bo]:[new RegExp("Konqueror[:/]?"+pe,"i")],[Hn]:[new RegExp(Hn+" "+pe),Qs],[id]:[new RegExp("android\\s"+pe,"i")],[Xu]:[new RegExp(Zu+"\\/"+pe)],[ad]:[new RegExp("OculusBrowser\\/"+pe)],[Cr]:[new RegExp(Cr+"\\/"+pe)],[ld]:[new RegExp("YaBrowser\\/"+pe)],[Ar]:[new RegExp(Ar+"\\/"+pe)],[wi]:[new RegExp(wi+"\\/"+pe)],[Do]:[new RegExp("(DuckDuckGo|Ddg)\\/"+pe)],[cd]:[new RegExp("PaleMoon\\/"+pe)],[Pr]:[new RegExp(Pr+"\\/"+pe)],[ud]:[new RegExp("GSA\\/"+pe)],[Ba]:[new RegExp("(rv:|MSIE )"+pe)],Mozilla:[new RegExp("rv:"+pe)]},sp=function(t,e,n,i){var r=dd(t,e,n,i),s=rp[r];if(x(s))return null;for(var o=0;s.length>o;o++){var a=t.match(s[o]);if(a)return parseFloat(a[a.length-2])}return null},nc=[[new RegExp(Dn+"; "+Dn+" (.*?)[);]","i"),t=>[Dn,t&&t[1]||""]],[new RegExp(Ai,"i"),[Ai,""]],[new RegExp(Pi,"i"),[Pi,""]],[Ua,[Hn,""]],[new RegExp(hi,"i"),(t,e)=>{if(/Phone/.test(e)||/WPDesktop/.test(e))return[No,""];if(new RegExp(Ye).test(e)&&!/IEMobile\b/.test(e))return[hi+" "+Ye,""];var n=/Windows NT ([0-9.]+)/i.exec(e);if(n&&n[1]){var i=ip[n[1]]||"";return/arm/i.test(e)&&(i="RT"),[hi,i]}return[hi,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,t=>t&&t[3]?[Ir,[t[3],t[4],t[5]||"0"].join(".")]:[Ir,""]],[/(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i,t=>{var e="";return t&&t.length>=3&&(e=x(t[2])?t[3]:t[2]),["watchOS",e]}],[new RegExp("("+Ot+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+Ot+")","i"),t=>t&&t[2]?[Ot,[t[2],t[3],t[4]||"0"].join(".")]:[Ot,""]],[/Mac OS X (\d+)[_.](\d+)[_.]?(\d+)?/i,t=>{var 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/,[Zf,""]],[/Linux|debian/i,["Linux",""]]],ic=function(t){return np.test(t)?Ai:tp.test(t)?Pi:ep.test(t)?Dn:new RegExp(Oo,"i").test(t)?Oo:new RegExp("("+No+"|WPDesktop)","i").test(t)?No:/iPad/.test(t)?Gu:/iPod/.test(t)?"iPod Touch":/iPhone/.test(t)?"iPhone":/(watch)(?: ?os[,/]|\d,\d\/)[\d.]+/i.test(t)?Yu:Ua.test(t)?Hn:/(kobo)\s(ereader|touch)/i.test(t)?"Kobo":new RegExp(tc,"i").test(t)?tc:/(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(Ye).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)?Ot:Vu:new RegExp("(pda|"+Ye+")","i").test(t)?Qf:new RegExp(Un,"i").test(t)&&!new RegExp(Un+" pc","i").test(t)?od:""},op=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function rc(t,e){return typeof(n=t)=="string"&&op.test(n)?t:e();var n}function Qt(t){return t&&t.split("#")[0]}function Ha(t,e){var n=setTimeout(t,e);return n?.unref&&n?.unref(),n}function sc(t,e,n){return hd.apply(this,arguments)}function hd(){return(hd=ne((function*(t,e,n){var i;try{return yield Promise.race([t,new Promise(((r,s)=>{i=Ha((()=>{try{n?.(),r()}catch(o){s(o)}}),e)}))])}finally{clearTimeout(i)}}))).apply(this,arguments)}var ap=t=>t instanceof Error,fd={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}},lp=fd.info;function pd(t){if(at(t))return{boolValue:t};if(typeof t=="number")return Number.isFinite(t)?Number.isInteger(t)?{intValue:t}:{doubleValue:t}:{stringValue:String(t)};if(typeof t=="string")return{stringValue:t};if(D(t))return{arrayValue:{values:t.map((e=>pd(e)))}};try{return{stringValue:JSON.stringify(t)}}catch{return{stringValue:String(t)}}}function Fr(t){var e=[];for(var n in t){var i=t[n];We(i)||x(i)||e.push({key:n,value:pd(i)})}return e}function cp(t,e){var n=fd[t.level||"info"]||lp,i=n.text,r=n.number,s=String(Date.now())+"000000",o={};e.distinctId&&(o.posthogDistinctId=e.distinctId),e.sessionId&&(o.sessionId=e.sessionId),e.windowId&&(o["window.id"]=e.windowId),j(e.sessionStartTimestamp)||(o.sessionStartTimestamp=String(e.sessionStartTimestamp)),j(e.lastActivityTimestamp)||(o.lastActivityTimestamp=String(e.lastActivityTimestamp)),e.currentUrl&&(o["url.full"]=e.currentUrl),e.screenName&&(o["screen.name"]=e.screenName),e.appState&&(o["app.state"]=e.appState),e.activeFeatureFlags&&e.activeFeatureFlags.length>0&&(o.feature_flags=e.activeFeatureFlags);var a=E({},o,t.attributes||{}),l={timeUnixNano:s,observedTimeUnixNano:s,severityNumber:r,severityText:i,body:{stringValue:t.body},attributes:Fr(a)};return t.trace_id&&(l.traceId=t.trace_id),t.span_id&&(l.spanId=t.span_id),x(t.trace_flags)||(l.flags=t.trace_flags),l}function gd(t,e,n){return E({},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})}function md(t,e,n,i){return{resourceLogs:[{resource:{attributes:Fr(e)},scopeLogs:[{scope:{name:n,version:i},logRecords:t}]}]}}let up=class{constructor(t,e,n,i,r,s,o){var a;s===void 0&&(s=()=>Promise.resolve()),this._instance=t,this.Ne=e,this.rt=n,this.ut=i,this.ht=r,this.dt=s,this.vt=o,this.ct=null,this.ft=0,this.yt=0,this.bt=0,this._t=0,this.wt=!1,this.kt=e.maxBufferSize,this.xt=Math.max((a=e.maxQueueSize)!==null&&a!==void 0?a:e.maxBufferSize,e.maxBufferSize),this.St=e.flushIntervalMs,this.Ct=e.maxBatchRecordsPerPost,this.Mt=e.rateCapWindowMs,this.Tt=e.maxLogsPerInterval}reset(){this.Et(),this.ct=null,this.bt=0,this._t=0,this.wt=!1,this.ft=0,this.yt=0,this.Ct=this.Ne.maxBatchRecordsPerPost}onReconnect(){this.yt=0,this.It()}captureLog(t){if(!this._instance.isDisabled&&!this._instance.optedOut&&t!=null&&t.body){var e=this.Pt(t);if(e!==null)if(e.body){if(this.Rt()){var n={record:cp(e,this.ut())};this.ht((()=>this.At(n)))}}else this.rt.info("Log was rejected in beforeSend function")}}Pt(t){var e=this.Ne.beforeSend;if(!e)return t;var n=D(e)?e:[e],i=t;for(var r of n)try{var s=r(i);if(!s)return this.rt.info("Log was rejected in beforeSend function"),null;i=s}catch(o){return this.rt.error("Error in beforeSend function for log:",o),null}return i}Rt(){if(this.Tt===void 0)return!0;var t=Date.now(),e=t-this.bt;return this.Mt>e&&e>=0||(this.bt=t,this._t=0,this.wt=!1),this.Tt>this._t?(this._t++,!0):(this.wt||(this.rt.warn("captureLog dropping logs: exceeded "+this.Tt+" logs per "+this.Mt+"ms"),this.wt=!0),!1)}flush(){var t=this;return ne((function*(){if(!t._instance.isDisabled)return t.ct||(t.ct=t.Ft().finally((()=>{t.ct=null}))),t.ct}))()}Ft(){var t=this;return ne((function*(){var e;t.Et();var n=(e=t._instance.getPersistedProperty(Ft.LogsQueue))!==null&&e!==void 0?e:[];if(n.length!==0)for(var i=n.length,r=0;n.length>0&&i>r;){var s,o;t.ft=0;var a=Math.min(n.length,t.Ct),l=n.slice(0,a),u=md(l.map((d=>d.record)),t.Lt(),(s=t.vt)!==null&&s!==void 0?s:t._instance.getLibraryId(),t._instance.getLibraryVersion()),c=yield t._instance.Ot(u);if(c.kind==="too-large"&&l.length>1)t.Ct=Math.max(1,Math.floor(l.length/2)),t.rt.warn("Received 413 when sending logs batch of size "+l.length+", reducing batch size to "+t.Ct);else if(c.kind==="retry-later"||(c.kind==="too-large"?t.rt.warn("Dropping a single log record after 413 with batch size 1 — the record is larger than the server cap and cannot be split further."):c.kind==="ok"&&t.Ne.maxBatchRecordsPerPost>t.Ct&&(t.Ct=Math.min(t.Ne.maxBatchRecordsPerPost,t.Ct+1)),yield t.Dt(l.length),n=(o=t._instance.getPersistedProperty(Ft.LogsQueue))!==null&&o!==void 0?o:[],r+=l.length,c.kind==="fatal"))throw c.error}}))()}Dt(t){var e=this;return ne((function*(){var n,i=Math.max(0,t-e.ft),r=(n=e._instance.getPersistedProperty(Ft.LogsQueue))!==null&&n!==void 0?n:[];e._instance.setPersistedProperty(Ft.LogsQueue,r.slice(i)),yield e.dt()}))()}Lt(){return gd(this.Ne,this._instance.getLibraryId(),this._instance.getLibraryVersion())}At(t){var e;if(!this._instance.optedOut){var n=(e=this._instance.getPersistedProperty(Ft.LogsQueue))!==null&&e!==void 0?e:[];this.xt>n.length||(n.shift(),this.ft++,this.rt.info("Logs queue is full, dropping oldest record.")),n.push(t),this._instance.setPersistedProperty(Ft.LogsQueue,n),this.kt>n.length?this.$t():this.It()}}$t(t){t===void 0&&(t=this.St),this.Nt||(this.Nt=Ha((()=>{this.Nt=void 0,this.It()}),t))}qt(){var t=Math.min(Math.max(0,this.yt-1),6);return this.St*Math.pow(2,t)}jt(){var t=this._instance.getPersistedProperty(Ft.LogsQueue);return!!t&&t.length>0}shutdown(t){var e=this;return ne((function*(){e.Et();var n=e.flush().catch((()=>{}));t!==void 0?yield sc(n,t):yield n}))()}flushWithTimeout(t){var e=this;return ne((function*(){var n=e.flush();yield sc(n,t,(()=>{n.catch((()=>{}))}))}))()}It(){this.flush().then((()=>{this.yt=0}),(t=>{this.yt++,this.rt.error("PostHog logs flush failed:",t)})).finally((()=>{!this._instance.isDisabled&&this.jt()&&this.$t(this.qt())}))}Et(){this.Nt&&(clearTimeout(this.Nt),this.Nt=void 0)}};var eo=[0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4];function oc(t){return String(t)+"000000"}function ac(t,e,n,i){var r="";return i&&(r=Object.keys(i).sort().map((s=>JSON.stringify(s)+":"+JSON.stringify(i[s]))).join(",")),t+"\0"+e+"\0"+(n??"")+"\0"+r}let dp=class{constructor(t,e,n){this._instance=t,this.Ne=e,this.rt=n,this.Bt=new Map,this.ct=null,this.Ht=!1,this.Ut=new Map,this.zt=new Set,this.Wt=0}count(t,e,n){e===void 0&&(e=1),this.Vt({name:t,type:"count",value:e,unit:n?.unit,attributes:n?.attributes})}gauge(t,e,n){this.Vt({name:t,type:"gauge",value:e,unit:n?.unit,attributes:n?.attributes})}histogram(t,e,n){this.Vt({name:t,type:"histogram",value:e,unit:n?.unit,attributes:n?.attributes})}flush(){var t=this,e=this.ct,n=(function(){var r=ne((function*(){e&&(yield e.catch((()=>{}))),yield t.Zt()}));return function(){return r.apply(this,arguments)}})(),i=n().finally((()=>{this.ct===i&&(this.ct=null)}));return this.ct=i,i}drainWindow(){if(this.Bt.size===0)return null;var t=this.Bt;return this.Bt=new Map,this.Ht=!1,this.Ut=new Map,this.zt=new Set,this.Gt(t)}reset(){this.Wt++,this.Et(),this.Bt=new Map,this.ct=null,this.Ht=!1,this.Ut=new Map,this.zt=new Set}Vt(t){if(!this._instance.isDisabled&&!this._instance.optedOut){var e=this.Pt(t);if(e!==null)if(e.name&&typeof e.name=="string")if(typeof e.value=="number"&&Number.isFinite(e.value))if(e.type==="count"&&0>e.value)this.rt.warn("Dropping count '"+e.name+"': counters are monotonic, value must be >= 0");else{var n,i;try{n=e.attributes?E({},e.attributes):void 0,i=ac(e.type,e.name,e.unit,n)}catch(o){return void this.rt.warn("Dropping metric '"+e.name+"': attributes could not be serialized",o)}var r=this.Bt.get(i);if(!r){if(!this.Qt())return;r={name:e.name,type:e.type,unit:e.unit,attributes:n,windowStartMs:Date.now()},this.Bt.set(i,r)}var s=this.Ut.get(e.name);s===void 0?this.Ut.set(e.name,e.type):s===e.type||this.zt.has(e.name)||(this.zt.add(e.name),this.rt.warn("Metric name '"+e.name+"' is already used as a "+s+"; recording it as a "+e.type+" too will blend both series in charts. Use a distinct name.")),this.Kt(r,e.value),this.$t()}else this.rt.warn("Dropping metric '"+e.name+"': value must be a finite number");else this.rt.warn("Dropping metric with empty name")}}Qt(){return this.Ne.maxSeriesPerFlush>this.Bt.size||(this.Ht||(this.Ht=!0,this.rt.warn("Metric series cap reached ("+this.Ne.maxSeriesPerFlush+" per flush window); dropping new series until the next flush. Reduce attribute cardinality.")),!1)}Kt(t,e){var n;switch(t.type){case"count":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(eo.length+1).fill(0)});var i=t.hist;i.count+=1,i.sum+=e,i.min=Math.min(i.min,e),i.max=Math.max(i.max,e),i.bucketCounts[(function(r,s){for(var o=0;s.length>o;o++)if(s[o]>=r)return o;return s.length})(e,eo)]+=1}}Pt(t){var e=this.Ne.beforeSend;if(!e)return t;var n=D(e)?e:[e],i=t;for(var r of n)try{var s=r(i);if(!s)return this.rt.info("Metric was rejected in beforeSend function"),null;i=s}catch(o){return this.rt.error("Error in beforeSend function for metric:",o),null}return i}$t(){this.Nt||(this.Nt=Ha((()=>{this.Nt=void 0,this.flush().catch((t=>{this.rt.error("Metrics flush failed:",t)}))}),this.Ne.flushIntervalMs))}Et(){this.Nt&&(clearTimeout(this.Nt),this.Nt=void 0)}Zt(){var t=this;return ne((function*(){if(t.Bt.size!==0){var e=t.Bt;t.Bt=new Map,t.Ht=!1,t.Ut=new Map,t.zt=new Set;var n=t.Wt,i=yield t._instance.Jt(t.Gt(e));if(n===t.Wt)switch(i.kind){case"ok":return;case"retry-later":return t.Yt(e),void t.$t();case"too-large":return void t.rt.warn("Metrics batch exceeded the server size limit and was dropped");case"fatal":return void t.rt.error("Failed to send metrics batch:",i.error)}}}))()}Gt(t){return e=this.Xt(t),n=(function(s,o,a){return E({},s.resourceAttributes,{"service.name":s.serviceName||"unknown_service"},s.environment&&{"deployment.environment":s.environment},s.serviceVersion&&{"service.version":s.serviceVersion},{"telemetry.sdk.name":o,"telemetry.sdk.version":a})})(this.Ne,this._instance.getLibraryId(),this._instance.getLibraryVersion()),i=this._instance.getLibraryId(),r=this._instance.getLibraryVersion(),{resourceMetrics:[{resource:{attributes:Fr(n)},scopeMetrics:[{scope:{name:i,version:r},metrics:e}]}]};var e,n,i,r}Xt(t){var e=oc(Date.now()),n=new Map;for(var i of t.values()){var r,s=ac(i.type,i.name,i.unit,void 0),o=n.get(s);o||(o=E({name:i.name},i.unit&&{unit:i.unit}),i.type==="count"?o.sum={aggregationTemporality:1,isMonotonic:!0,dataPoints:[]}:i.type==="gauge"?o.gauge={dataPoints:[]}:o.histogram={aggregationTemporality:1,dataPoints:[]},n.set(s,o));var a=Fr((r=i.attributes)!==null&&r!==void 0?r:{}),l=oc(i.windowStartMs);if(i.type==="count"){var u,c={attributes:a,startTimeUnixNano:l,timeUnixNano:e,asDouble:(u=i.total)!==null&&u!==void 0?u:0};o.sum.dataPoints.push(c)}else if(i.type==="gauge"){var d,h={attributes:a,timeUnixNano:e,asDouble:(d=i.last)!==null&&d!==void 0?d:0};o.gauge.dataPoints.push(h)}else i.hist&&o.histogram.dataPoints.push({attributes:a,startTimeUnixNano:l,timeUnixNano:e,count:i.hist.count,sum:i.hist.sum,min:i.hist.min,max:i.hist.max,bucketCounts:i.hist.bucketCounts,explicitBounds:eo})}return Array.from(n.values())}Yt(t){var e,n;for(var i of t){var r=i[0],s=i[1],o=this.Bt.get(r);if(o)switch(o.windowStartMs=Math.min(o.windowStartMs,s.windowStartMs),o.type){case"count":o.total=((e=o.total)!==null&&e!==void 0?e:0)+((n=s.total)!==null&&n!==void 0?n:0);break;case"gauge":break;case"histogram":if(s.hist)if(o.hist){o.hist.count+=s.hist.count,o.hist.sum+=s.hist.sum,o.hist.min=Math.min(o.hist.min,s.hist.min),o.hist.max=Math.max(o.hist.max,s.hist.max);for(var a=0;o.hist.bucketCounts.length>a;a++)o.hist.bucketCounts[a]+=s.hist.bucketCounts[a]}else o.hist=s.hist}else this.Qt()&&this.Bt.set(r,s)}}};var Yi,lc,to;function hp(t){var e=globalThis._posthogChunkIds;if(e){var n=Object.keys(e);return to&&n.length===lc||(lc=n.length,to=n.reduce(((i,r)=>{Yi||(Yi={});var s=Yi[r];if(s)i[s[0]]=s[1];else for(var o=t(r),a=o.length-1;a>=0;a--){var l=o[a],u=l?.filename,c=e[r];if(u&&c){i[u]=c,Yi[r]=[u,c];break}}return i}),{})),to}}class fp{constructor(e,n,i){i===void 0&&(i=[]),this.coercers=e,this.stackParser=n,this.modifiers=i}buildFromUnknown(e,n){n===void 0&&(n={});var i=n&&n.mechanism||{handled:!0,type:"generic"},r=this.buildCoercingContext(i,n,0).apply(e),s=this.buildParsingContext(n),o=this.parseStacktrace(r,s);return{$exception_list:this.convertToExceptionList(o,i),$exception_level:"error"}}modifyFrames(e){var n=this;return ne((function*(){for(var i of e)i.stacktrace&&i.stacktrace.frames&&D(i.stacktrace.frames)&&(i.stacktrace.frames=yield n.applyModifiers(i.stacktrace.frames));return e}))()}coerceFallback(e){var n;return{type:"Error",value:"Unknown error",stack:(n=e.syntheticException)==null?void 0:n.stack,synthetic:!0}}parseStacktrace(e,n){var i,r;return e.cause!=null&&(i=this.parseStacktrace(e.cause,n)),e.stack!=""&&e.stack!=null&&(r=this.applyChunkIds(this.stackParser(e.stack,e.synthetic?n.skipFirstLines:0),n.chunkIdMap)),E({},e,{cause:i,stack:r})}applyChunkIds(e,n){return e.map((i=>(i.filename&&n&&(i.chunk_id=n[i.filename]),i)))}applyCoercers(e,n){for(var i of this.coercers)if(i.match(e))return i.coerce(e,n);return this.coerceFallback(n)}applyModifiers(e){var n=this;return ne((function*(){var i=e;for(var r of n.modifiers)i=yield r(i);return i}))()}convertToExceptionList(e,n){var i,r,s,o={type:e.type,value:e.value,mechanism:{type:(i=n.type)!==null&&i!==void 0?i:"generic",handled:(r=n.handled)===null||r===void 0||r,synthetic:(s=e.synthetic)!==null&&s!==void 0&&s}};e.stack&&(o.stacktrace={type:"raw",frames:e.stack});var a=[o];return e.cause!=null&&a.push(...this.convertToExceptionList(e.cause,E({},n,{handled:!0}))),a}buildParsingContext(e){var n;return{chunkIdMap:hp(this.stackParser),skipFirstLines:(n=e.skipFirstLines)!==null&&n!==void 0?n:1}}buildCoercingContext(e,n,i){i===void 0&&(i=0);var r=(s,o)=>{if(4>=o){var a=this.buildCoercingContext(e,n,o);return this.applyCoercers(s,a)}};return E({},n,{syntheticException:i==0?n.syntheticException:void 0,mechanism:e,apply:s=>r(s,i),next:s=>r(s,i+1)})}}var Wn="?";function jo(t,e,n,i,r){var s={platform:t,filename:e,function:n===""?Wn:n,in_app:!0};return x(i)||(s.lineno=i),x(r)||(s.colno=r),s}var vd=(t,e)=>{var n=t.indexOf("safari-extension")!==-1,i=t.indexOf("safari-web-extension")!==-1;return n||i?[t.indexOf("@")!==-1?t.split("@")[0]:Wn,n?"safari-extension:"+e:"safari-web-extension:"+e]:[t,e]},pp=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,gp=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,mp=/\((\S*)(?::(\d+))(?::(\d+))\)/,vp=(t,e)=>{var n=pp.exec(t);if(n)return jo(e,n[1],Wn,+n[2],+n[3]);var i=gp.exec(t);if(i){if(i[2]&&i[2].indexOf("eval")===0){var r=mp.exec(i[2]);r&&(i[2]=r[1],i[3]=r[2],i[4]=r[3])}var s=vd(i[1]||Wn,i[2]);return jo(e,s[1],s[0],i[3]?+i[3]:void 0,i[4]?+i[4]:void 0)}},_p=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,yp=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,wp=(t,e)=>{var n=_p.exec(t);if(n){if(n[3]&&n[3].indexOf(" > eval")>-1){var i=yp.exec(n[3]);i&&(n[1]=n[1]||"eval",n[3]=i[1],n[4]=i[2],n[5]="")}var r=n[3],s=n[1]||Wn,o=vd(s,r);return jo(e,r=o[1],s=o[0],n[4]?+n[4]:void 0,n[5]?+n[5]:void 0)}},cc=/\(error: (.*)\)/;class bp{match(e){return this.isDOMException(e)||this.isDOMError(e)}coerce(e,n){var i=K(e.stack);return{type:this.getType(e),value:this.getValue(e),stack:i?e.stack:void 0,cause:e.cause?n.next(e.cause):void 0,synthetic:!1}}getType(e){return this.isDOMError(e)?"DOMError":"DOMException"}getValue(e){var n=e.name||(this.isDOMError(e)?"DOMError":"DOMException");return e.message?n+": "+e.message:n}isDOMException(e){return kr(e,"DOMException")}isDOMError(e){return kr(e,"DOMError")}}class Ep{match(e){return(function(n){switch({}.toString.call(n)){case"[object Error]":case"[object Exception]":case"[object DOMException]":case"[object DOMError]":case"[object WebAssembly.Exception]":return!0;default:return zu(n,Error)}})(e)}coerce(e,n){return{type:this.getType(e),value:this.getMessage(e,n),stack:this.getStack(e),cause:e.cause?n.next(e.cause):void 0,synthetic:!1}}getType(e){return e.name||e.constructor.name}getMessage(e,n){var i=e.message;return String(i.error&&typeof i.error.message=="string"?i.error.message:i)}getStack(e){return e.stacktrace||e.stack||void 0}}class Sp{constructor(){}match(e){return!!kr(e,"ErrorEvent")&&(e.error!=null||this.fe(e))}coerce(e,n){var i;if(e.error!=null)return n.apply(e.error);var r=n.apply(e.message);return E({},r,{stack:(i=this.pe(e))!==null&&i!==void 0?i:r.stack,synthetic:!0})}fe(e){return K(e.message)&&e.message.length>0}pe(e){var n=e;if(K(n.filename)&&n.filename.length>0){var i,r,s=(i=n.lineno)!==null&&i!==void 0?i:0,o=(r=n.colno)!==null&&r!==void 0?r:0;return`Error - at `+n.filename+":"+s+":"+o}}}var xp=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;class kp{match(e){return typeof e=="string"}coerce(e,n){var i,r=this.getInfos(e),s=r[0],o=r[1];return{type:s??"Error",value:o??e,stack:(i=n.syntheticException)==null?void 0:i.stack,synthetic:!0}}getInfos(e){var n="Error",i=e,r=e.match(xp);return r&&(n=r[1],i=r[2]),[n,i]}}var Ip=["fatal","error","warning","log","info","debug"];function _d(t,e){e===void 0&&(e=40);var n=Object.keys(t);if(n.sort(),!n.length)return"[object has no keys]";for(var i=n.length;i>0;i--){var r=n.slice(0,i).join(", ");if(e>=r.length)return i===n.length?r:r.length>e?r.slice(0,e)+"...":r}return""}class Cp{match(e){return typeof e=="object"&&e!==null}coerce(e,n){var i,r,s=this.getErrorPropertyFromObject(e);return s?n.apply(s):{type:this.getType(e),value:this.getValue(e),stack:(i=this.getStack(e))!==null&&i!==void 0?i:(r=n.syntheticException)==null?void 0:r.stack,level:this.isSeverityLevel(e.level)?e.level:"error",synthetic:!0}}getType(e){return Oa(e)?e.constructor.name:"Error"}getValue(e){if("name"in e&&typeof e.name=="string"){var n="'"+e.name+"' captured as exception";return"message"in e&&typeof e.message=="string"&&(n+=" with message: '"+e.message+"'"),n}if("message"in e&&typeof e.message=="string")return e.message;var i=this.getObjectClassName(e);return(i&&i!=="Object"?"'"+i+"'":"Object")+" captured as exception with keys: "+_d(e)}isSeverityLevel(e){return K(e)&&!Lo(e)&&Ip.indexOf(e)>=0}getStack(e){try{return K(e.stacktrace)&&e.stacktrace.length>0?e.stacktrace:K(e.stack)&&e.stack.length>0?e.stack:void 0}catch{return}}getErrorPropertyFromObject(e){for(var n in e)if({}.hasOwnProperty.call(e,n)){var i=e[n];if(ap(i))return i}}getObjectClassName(e){try{var n=Object.getPrototypeOf(e);return n?n.constructor.name:void 0}catch{return}}}class Ap{match(e){return Oa(e)}coerce(e,n){var i,r=e.constructor.name;return{type:r,value:r+" captured as exception with keys: "+_d(e),stack:(i=n.syntheticException)==null?void 0:i.stack,synthetic:!0}}}class Pp{match(e){return qu(e)}coerce(e,n){var i;return{type:"Error",value:"Primitive value captured as exception: "+String(e),stack:(i=n.syntheticException)==null?void 0:i.stack,synthetic:!0}}}class Fp{match(e){return kr(e,"PromiseRejectionEvent")||this.isCustomEventWrappingRejection(e)}isCustomEventWrappingRejection(e){if(!Oa(e))return!1;try{var n=e.detail;return n!=null&&typeof n=="object"&&"reason"in n}catch{return!1}}coerce(e,n){var i,r=this.getUnhandledRejectionReason(e);return qu(r)?{type:"UnhandledRejection",value:"Non-Error promise rejection captured with value: "+String(r),stack:(i=n.syntheticException)==null?void 0:i.stack,synthetic:!0}:n.apply(r)}getUnhandledRejectionReason(e){try{if("reason"in e)return e.reason;if("detail"in e&&e.detail!=null&&typeof e.detail=="object"&&"reason"in e.detail)return e.detail.reason}catch{}return e}}var Rr="$message",Tr="$timestamp",Rp=new Set([Rr,Tr]),no={enabled:!0,max_bytes:32768};function $r(t){var e;return t?{enabled:(e=t.enabled)!==null&&e!==void 0?e:no.enabled,max_bytes:$p(t.max_bytes,no.max_bytes)}:E({},no)}class Tp{constructor(e){this.Ke=[],this.Je=0,this.Ne=$r(e)}setConfig(e){this.Ne=$r(e),this.Xe()}add(e){var n=(function(r){var s;try{s=Uu(r)}catch{return}try{var o=JSON.parse(s);if(!ae(o))return;var a=o,l=a[Rr],u=a[Tr];return!K(l)||l.trim().length===0||!K(u)&&!Se(u)?void 0:{step:a,json:s}}catch{return}})(e);if(n){var i=(function(r){if(typeof TextEncoder<"u")return new TextEncoder().encode(r).length;for(var s=encodeURIComponent(r),o=0,a=0;s.length>a;a++)s[a]==="%"?(o+=1,a+=2):o+=1;return o})(n.json);i>this.Ne.max_bytes||(this.Ke.push({step:n.step,bytes:i}),this.Je+=i,this.Xe())}}getAttachable(){return this.Ke.map((e=>e.step))}clear(){this.Ke=[],this.Je=0}size(){return this.Ke.length}Xe(){for(;this.Je>this.Ne.max_bytes&&this.Ke.length>0;){var e=this.Ke.shift();e&&(this.Je-=e.bytes)}}}function $p(t,e){if(!Se(t)||t===1/0||t===-1/0)return e;var n=Math.floor(t);return 0>n?e:n}var yd=function(t,e){var n=(e===void 0?{}:e).debugEnabled,i={k(r){if(_&&(ee.DEBUG||_.POSTHOG_DEBUG||n)&&!x(_.console)&&_.console){for(var s=("__rrweb_original__"in _.console[r])?_.console[r].__rrweb_original__:_.console[r],o=arguments.length,a=new Array(o>1?o-1:0),l=1;o>l;l++)a[l-1]=arguments[l];s(t,...a)}},debug(){for(var r=arguments.length,s=new Array(r),o=0;r>o;o++)s[o]=arguments[o];i.k("debug",...s)},info(){for(var r=arguments.length,s=new Array(r),o=0;r>o;o++)s[o]=arguments[o];i.k("log",...s)},warn(){for(var r=arguments.length,s=new Array(r),o=0;r>o;o++)s[o]=arguments[o];i.k("warn",...s)},error(){for(var r=arguments.length,s=new Array(r),o=0;r>o;o++)s[o]=arguments[o];i.k("error",...s)},critical(){for(var r=arguments.length,s=new Array(r),o=0;r>o;o++)s[o]=arguments[o];console.error(t,...s)},uninitializedWarning(r){i.error("You must initialize PostHog before calling "+r)},createLogger:(r,s)=>yd(t+" "+r,s)};return i},k=yd("[PostHog.js]"),le=k.createLogger,Mp=le("[ExternalScriptsLoader]"),io=(t,e,n)=>{if(t.config.disable_external_dependency_loading)return Mp.warn(e+" was requested but loading of external scripts is disabled."),n("Loading of external scripts is disabled");var i=C?.querySelectorAll("script");if(i){for(var r,s=function(){if(i[o].src===e){var l=i[o];return l.__posthog_loading_callback_fired?{v:n()}:(l.addEventListener("load",(u=>{l.__posthog_loading_callback_fired=!0,n(void 0,u)})),l.onerror=u=>n(u),{v:void 0})}},o=0;i.length>o;o++)if(r=s())return r.v}var a=()=>{if(!C)return n("document not found");var l=C.createElement("script");if(l.type="text/javascript",l.crossOrigin="anonymous",l.src=e,l.onload=d=>{l.__posthog_loading_callback_fired=!0,n(void 0,d)},l.onerror=d=>n(d),t.config.prepare_external_dependency_script&&(l=t.config.prepare_external_dependency_script(l)),!l)return n("prepare_external_dependency_script returned null");if(t.config.external_scripts_inject_target==="head")C.head.appendChild(l);else{var u,c=C.querySelectorAll("body > script");c.length>0?(u=c[0].parentNode)==null||u.insertBefore(l,c[0]):C.body.appendChild(l)}};C!=null&&C.body?a():C?.addEventListener("DOMContentLoaded",a)};T.__PosthogExtensions__=T.__PosthogExtensions__||{},T.__PosthogExtensions__.loadExternalDependency=(t,e,n)=>{if(e!=="remote-config"){var i;if(t.config.strict_script_versioning)i=t.requestRouter.endpointFor("assets","/static/"+t.version+"/"+e+".js");else{var r="/static/"+e+".js?v="+t.version;if(e==="toolbar"){var s=3e5;r=r+"&t="+Math.floor(Date.now()/s)*s}i=t.requestRouter.endpointFor("assets",r)}io(t,i,n)}else{var o=t.requestRouter.endpointFor("assets","/array/"+t.config.token+"/config.js");io(t,o,n)}},T.__PosthogExtensions__.loadSiteApp=(t,e,n)=>{var i=t.requestRouter.endpointFor("api",e);io(t,i,n)};ee.DEBUG=!1,ee.LIB_VERSION="1.415.7",ee.LIB_NAME="web";var wd="$people_distinct_id",Fi="$device_id",ro="$device_model",fi="__alias",pi="__timers",Uo="$autocapture_disabled_server_side",Ho="$heatmaps_enabled_server_side",Wo="$exception_capture_enabled_server_side",qo="$error_tracking_suppression_rules",zo="$error_tracking_capture_extension_exceptions",Vo="$web_vitals_enabled_server_side",Wa="$dead_clicks_enabled_server_side",qa="$product_tours_enabled_server_side",Go="$web_vitals_allowed_metrics",vn="$session_recording_remote_config",bd="$replay_sample_rate",Ed="$replay_override_sampling",Sd="$replay_override_linked_flag",xd="$replay_override_url_trigger",kd="$replay_override_event_trigger",Nn="$sesid",za="$session_is_sampled",hn="$enabled_feature_flags",gi="$active_feature_flags",ur="$early_access_features",Ko="$feature_flag_details",mi="$feature_flag_payloads",dr="$feature_flag_request_id",Mr="$minimal_flag_called_events",gt="$override_feature_flags",fn="$override_feature_flag_payloads",Pt="$stored_person_properties",pn="$stored_group_properties",Yo="$surveys",Lr="$surveys_loaded_at",Jo="$surveys_activated",hr="$surveys_activated_session",fr="$surveys_activated_timestamps",vi="ph_product_tours",mn="$flag_call_reported",_i="$flag_call_reported_session_id",pr="$feature_flag_errors",bi="$feature_flag_evaluated_at",Xe="$user_state",Zo="$client_session_props",Xo="$capture_rate_limit",Qo="$initial_campaign_params",ea="$initial_referrer_info",Nr="$initial_person_info",Or="$epp",Ji="$posthog_cookieless",Id="$cookieless_mode",Cd="$sdk_debug_extensions_init_method",Ad="$sdk_debug_extensions_init_time_ms",Pd="$sdk_debug_recording_script_not_loaded",Va="PostHog loadExternalDependency extension not found.",gn="on_reject",Tt="always",An="anonymous",on="identified",ta="identified_only",Br="visibilitychange",Dr="beforeunload",$n="$pageview",so="$pageleave",oo="$identify",uc="$groupidentify";function Zi(t,e){D(t)&&t.forEach(e)}function te(t,e){if(!j(t))if(D(t))t.forEach(e);else if(zf(t))t.forEach(((i,r)=>e(i,r)));else for(var n in t)Wu.call(t,n)&&e(t[n],n)}var oe=function(t){for(var e=arguments.length,n=new Array(e>1?e-1:0),i=1;e>i;i++)n[i-1]=arguments[i];for(var r of n)for(var s in r)r[s]!==void 0&&(t[s]=r[s]);return t};function gr(t){for(var e=Object.keys(t),n=e.length,i=new Array(n);n--;)i[n]=[e[n],t[e[n]]];return i}var dc=function(t){try{return t()}catch{return}},Lp=function(t){return function(){try{for(var e=arguments.length,n=new Array(e),i=0;e>i;i++)n[i]=arguments[i];return t.apply(this,n)}catch(r){k.critical("Implementation error. Please turn on debug mode and open a ticket on https://app.posthog.com/home#panel=support%3Asupport%3A."),k.critical(r)}}},Ga=function(t){var e={};return te(t,(function(n,i){(K(n)&&n.length>0||Se(n))&&(e[i]=n)})),e},Np=["herokuapp.com","vercel.app","netlify.app"];function Op(t){var e=t?.hostname;if(!K(e))return!1;var n=e.split(".").slice(-2).join(".");for(var i of Np)if(n===i)return!1;return!0}function de(t,e,n,i){var r=i??{},s=r.capture,o=r.passive;t?.addEventListener(e,n,{capture:s!==void 0&&s,passive:o===void 0||o})}function na(t){return t.name==="ph_toolbar_internal"}var Fd=t=>{if(C){try{for(var e=t+"=",n=C.cookie.split(";").filter((s=>s.length)),i=0;n.length>i;i++){for(var r=n[i];r.charAt(0)==" ";)r=r.substring(1,r.length);if(r.indexOf(e)===0)return decodeURIComponent(r.substring(e.length,r.length))}}catch{}return null}};Math.trunc||(Math.trunc=function(t){return 0>t?Math.ceil(t):Math.floor(t)}),Number.isInteger||(Number.isInteger=function(t){return Se(t)&&isFinite(t)&&Math.floor(t)===t});class jr{constructor(e){if(this.bytes=e,e.length!==16)throw new TypeError("not 128-bit length")}static fromFieldsV7(e,n,i,r){if(!Number.isInteger(e)||!Number.isInteger(n)||!Number.isInteger(i)||!Number.isInteger(r)||0>e||0>n||0>i||0>r||e>0xffffffffffff||n>4095||i>1073741823||r>4294967295)throw new RangeError("invalid field value");var s=new Uint8Array(16);return s[0]=e/Math.pow(2,40),s[1]=e/Math.pow(2,32),s[2]=e/Math.pow(2,24),s[3]=e/Math.pow(2,16),s[4]=e/256,s[5]=e,s[6]=112|n>>>8,s[7]=n,s[8]=128|i>>>24,s[9]=i>>>16,s[10]=i>>>8,s[11]=i,s[12]=r>>>24,s[13]=r>>>16,s[14]=r>>>8,s[15]=r,new jr(s)}toString(){for(var e="",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 jr(this.bytes.slice(0))}equals(e){return this.compareTo(e)===0}compareTo(e){for(var n=0;16>n;n++){var i=this.bytes[n]-e.bytes[n];if(i!==0)return Math.sign(i)}return 0}}class Bp{generate(){var e=this.generateOrAbort();if(!x(e))return e;this.S=0;var n=this.generateOrAbort();if(x(n))throw new Error("Could not generate UUID after timestamp reset");return n}generateOrAbort(){var e=Date.now();if(e>this.S)this.S=e,this.C();else{if(this.S>=e+1e4)return;this.I++,this.I>4398046511103&&(this.S++,this.C())}return jr.fromFieldsV7(this.S,Math.trunc(this.I/Math.pow(2,30)),this.I&Math.pow(2,30)-1,this.A.nextUint32())}C(){this.I=1024*this.A.nextUint32()+(1023&this.A.nextUint32())}constructor(){this.S=0,this.I=0,this.A=new Dp}}var hc,Rd=t=>{if(typeof UUIDV7_DENY_WEAK_RNG<"u"&&UUIDV7_DENY_WEAK_RNG)throw new Error("no cryptographically strong RNG available");for(var e=0;t.length>e;e++)t[e]=65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random());return t};_&&!x(_.crypto)&&crypto.getRandomValues&&(Rd=t=>crypto.getRandomValues(t));class Dp{nextUint32(){return this.R.length>this.O||(Rd(this.R),this.O=0),this.R[this.O++]}constructor(){this.R=new Uint32Array(8),this.O=1/0}}var Rt=()=>jp().toString(),jp=()=>(hc||(hc=new Bp)).generate(),ii="",Up=/[a-z0-9][a-z0-9-]+\.[a-z]{2,}$/i,$t={N:()=>!!C,j(t){k.error("cookieStore error: "+t)},P:Fd,H(t){var e;try{e=JSON.parse($t.P(t))||{}}catch{}return e},F(t,e,n,i,r){if(!C)return!1;try{var s="",o="",a=(function(c,d){if(d){var h=(function(p,g){if(g===void 0&&(g=C),ii)return ii;if(!g||["localhost","127.0.0.1"].includes(p))return"";for(var m=p.split("."),v=Math.min(m.length,8),w="dmn_chk_"+Rt();!ii&&v--;){var b=m.slice(v).join("."),I=w+"=1;domain=."+b+";path=/";g.cookie=I+";max-age=3",g.cookie.includes(w)&&(g.cookie=I+";max-age=0",ii=b)}return ii})(c);if(!h){var f=(p=>{var g=p.match(Up);return g?g[0]:""})(c);f!==h&&k.info("Warning: cookie subdomain discovery mismatch",f,h),h=f}return h?"; domain=."+h:""}return""})(C.location.hostname,i);if(n){var l=new Date;l.setTime(l.getTime()+864e5*n),s="; expires="+l.toUTCString()}r&&(o="; secure");var u=t+"="+encodeURIComponent(JSON.stringify(e))+s+"; SameSite=Lax; path=/"+a+o;return u.length>3686.4&&k.warn("cookieStore warning: large cookie, len="+u.length),C.cookie=u,!0}catch{return!1}},q(t,e){if(C!=null&&C.cookie)try{$t.F(t,"",-1,e)}catch{return}}},ao=null,re={N(){if(!We(ao))return ao;var t=!0;if(x(_))t=!1;else try{var e="__mplssupport__";re.F(e,"xyz"),re.P(e)!=='"xyz"'&&(t=!1),re.q(e)}catch{t=!1}return t||k.error("localStorage unsupported; falling back to cookie store"),ao=t,t},j(t){k.error("localStorage error: "+t)},P(t){try{return _?.localStorage.getItem(t)}catch(e){re.j(e)}return null},H(t){try{return JSON.parse(re.P(t))||{}}catch{}return null},F(t,e){try{return _?.localStorage.setItem(t,JSON.stringify(e)),!0}catch(n){re.j(n)}return!1},q(t){try{_?.localStorage.removeItem(t)}catch(e){re.j(e)}}},Hp=[Fi,"distinct_id",Nn,za,Or,Nr,Xe],Xi={},Wp={N:()=>!0,j(t){k.error("memoryStorage error: "+t)},P:t=>Xi[t]||null,H:t=>Xi[t]||null,F:(t,e)=>(Xi[t]=e,!0),q(t){delete Xi[t]}},an=null,ge={N(){if(!We(an))return an;if(an=!0,x(_))an=!1;else try{var t="__support__";ge.F(t,"xyz"),ge.P(t)!=='"xyz"'&&(an=!1),ge.q(t)}catch{an=!1}return an},j(t){k.error("sessionStorage error: ",t)},P(t){try{return _?.sessionStorage.getItem(t)}catch(e){ge.j(e)}return null},H(t){try{return JSON.parse(ge.P(t))||null}catch{}return null},F(t,e){try{return _?.sessionStorage.setItem(t,JSON.stringify(e)),!0}catch(n){ge.j(n)}return!1},q(t){try{_?.sessionStorage.removeItem(t)}catch(e){ge.j(e)}}};class qp{constructor(e){this._instance=e}get Ne(){return this._instance.config}get consent(){return this.ti()?0:this.ei}isOptedOut(){return this.Ne.cookieless_mode===Tt||this.isRejected()||this.consent===-1&&this.Ne.cookieless_mode===gn}isOptedIn(){return!this.isOptedOut()}isExplicitlyOptedOut(){return this.consent===0}isRejected(){return this.consent===0||this.consent===-1&&this.Ne.opt_out_capturing_by_default}optInOut(e){this.ii.F(this.ri,e?1:0,this.Ne.cookie_expiration,this.Ne.cross_subdomain_cookie,this.Ne.secure_cookie)}reset(){this.ii.q(this.ri,this.Ne.cross_subdomain_cookie)}get ri(){var e=this._instance.config,n=e.token,i=e.opt_out_capturing_cookie_prefix;return e.consent_persistence_name||(i?i+n:"__ph_opt_in_out_"+n)}get ei(){var e=this.ii.P(this.ri);return Xs(e)?1:B(Yf,e)?0:-1}get ii(){var e=this.Ne.opt_out_capturing_persistence_type,n=e==="localStorage"?re:$t;if(!this.ni||this.ni!==n){this.ni=n;var i=e==="localStorage"?$t:re;i.P(this.ri)&&(this.ni.P(this.ri)||this.optInOut(Xs(i.P(this.ri))),i.q(this.ri,this.Ne.cross_subdomain_cookie))}return this.ni}ti(){return!!this.Ne.respect_dnt&&[Be?.doNotTrack,Be?.msDoNotTrack,T.doNotTrack].some((e=>Xs(e)))}}function Td(t,e){var n,i=t==null||(n=t.config)==null?void 0:n.get_current_url;if(!Ne(i))return e;try{var r=i(e);return K(r)&&r?r:e}catch(s){return k.error("Error in get_current_url, falling back to window.location.href",s),e}}var $d="__POSTHOG_TOOLBAR__",zp=1,Vp=3,Gp=11;function fc(t){return t instanceof Element&&(t.id===$d||!(t.closest==null||!t.closest(".toolbar-global-fade-container")))}function en(t){return!!t&&t.nodeType===zp}function Ge(t,e){return!!t&&!!t.tagName&&t.tagName.toLowerCase()===e.toLowerCase()}function Md(t){return!!t&&t.nodeType===Vp}function Ld(t){return!!t&&t.nodeType===Gp&&en(t.host)}var Nd=1e3;function Ka(t){return t?us(t).split(/\s+/):[]}function pc(t,e){var n=(function(i){var r,s=_==null||(r=_.location)==null?void 0:r.href;return x(s)?void 0:Td(i,s)})(e);return!!(n&&t&&t.some((i=>n.match(i))))}function Ur(t){var 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 Ka(e)}function Od(t){return j(t)?null:us(t).split(/(\s+)/).filter((e=>Ei(e))).join("").replace(/[\r\n]/g," ").replace(/[ ]+/g," ").substring(0,255)}function Ri(t){var e="";return ra(t)&&!Ud(t)&&t.childNodes&&t.childNodes.length&&te(t.childNodes,(function(n){var i;Md(n)&&n.textContent&&(e+=(i=Od(n.textContent))!==null&&i!==void 0?i:"")})),us(e)}function lo(t){var e;return x(t.target)?t.srcElement||null:(e=t.target)!=null&&e.shadowRoot?t.composedPath()[0]||null:t.target||null}var Ya=["a","button","form","input","select","textarea","label"];function ia(t,e){if(x(e))return!0;var n,i=function(s){if(e.some((o=>(function(a,l){var u=a.matches||a.matchesSelector||a.msMatchesSelector||a.mozMatchesSelector||a.webkitMatchesSelector||a.oMatchesSelector;try{return!!u&&u.call(a,l)}catch{return!1}})(s,o))))return{v:!0}};for(var r of t)if(n=i(r))return n.v;return!1}function Bd(t){var e=t.parentNode;return!(!e||!en(e))&&e}var Kp=[".ph-no-autocapture","[data-ph-no-autocapture]"],Dd=["next","previous","prev",">","<"],Yp=[...Dd,"+","-","−","–"],gc=(t,e)=>/[a-z0-9]/i.test(e)?t.includes(e):t===e,mc=[".ph-no-rageclick",".ph-no-capture"],Jp=["","text","search","email","password","url","tel","number"];function vc(t,e){if(!_||Ja(t))return!1;var n,i,r,s,o;if(at(e)?(n=!!e&&mc,i=void 0,r=!1):(n=(s=e?.css_selector_ignorelist)!==null&&s!==void 0?s:mc,i=e?.content_ignorelist,r=(o=e?.ignore_text_selection)!==null&&o!==void 0&&o),n===!1||r&&(function(l){return!(!l||!en(l))&&(!!Ge(l,"textarea")||(Ge(l,"input")?B(Jp,(l.getAttribute("type")||"").toLowerCase()):(function(u){if(u.isContentEditable)return!0;var c=u.getAttribute==null?void 0:u.getAttribute("contenteditable");return c==="true"||c===""})(l)))})(t))return!1;var a=jd(t,!1).targetElementList;return!(function(l,u){if(l===!1||x(l))return!1;var c;if(l===!0)c=Dd;else{if(!D(l))return!1;if(l.length>10)return k.error("[PostHog] content_ignorelist array cannot exceed 10 items. Use css_selector_ignorelist for more complex matching."),!1;c=l.map((d=>d.toLowerCase()))}return u.some((d=>{var h=d.safeText,f=d.ariaLabel;return c.some((p=>gc(h,p)||gc(f,p)))}))})(i,a.map((l=>{var u;return{safeText:Ri(l).toLowerCase(),ariaLabel:((u=l.getAttribute("aria-label"))==null?void 0:u.toLowerCase().trim())||""}})))&&!ia(a,n)}var Ja=t=>!t||Ge(t,"html")||!en(t),jd=(t,e)=>{if(!_||Ja(t))return{parentIsUsefulElement:!1,targetElementList:[]};for(var n=!1,i=[t],r=t;r.parentNode&&!Ge(r,"body");)if(Ld(r.parentNode))i.push(r.parentNode.host),r=r.parentNode.host;else{var s=Bd(r);if(!s)break;if(e||Ya.indexOf(s.tagName.toLowerCase())>-1)n=!0;else try{var o=_.getComputedStyle(s);o&&o.getPropertyValue("cursor")==="pointer"&&(n=!0)}catch{}i.push(s),r=s}return{parentIsUsefulElement:n,targetElementList:i}};function ra(t){for(var e=new Set,n=0,i=t;i.parentNode&&!Ge(i,"body");i=i.parentNode){if(n++>=Nd||e.has(i))return!1;e.add(i);var r=Ur(i);if(B(r,"ph-sensitive")||B(r,"ph-no-capture"))return!1}if(B(Ur(t),"ph-include"))return!0;var s=t.type||"";if(K(s))switch(s.toLowerCase()){case"hidden":case"password":return!1}var o=t.name||t.id||"";return!K(o)||!/^cc|cardnum|ccnum|creditcard|csc|cvc|cvv|exp|pass|pwd|routing|seccode|securitycode|securitynum|socialsec|socsec|ssn/i.test(o.replace(/[^a-zA-Z0-9]/g,""))}function Ud(t){return!!(Ge(t,"input")&&!["button","checkbox","submit","reset"].includes(t.type)||Ge(t,"select")||Ge(t,"textarea")||t.getAttribute("contenteditable")==="true")}var _c=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}))$"),yc=/(^|[^0-9A-Za-z_])([0-9][0-9 -]*[0-9])(?=$|[^0-9A-Za-z_])/g,Zp=[16,15,14,13],Xp=new RegExp("^(\\d{3}-?\\d{2}-?\\d{4})$"),wc=new RegExp("(^|[^0-9])((?!000|666)[0-9]{3}-?(?!00)[0-9]{2}-?(?!0000)[0-9]{4})(?=$|([^0-9]))","g"),bc=/[0-9A-Za-z_]/;function Qp(t){for(var e=0,n=!1,i=t.length-1;i>=0;i--){var r=t.charCodeAt(i)-48;n&&(r*=2)>9&&(r-=9),e+=r,n=!n}return e%10==0}function Ei(t,e){if(e===void 0&&(e=!0),j(t))return!1;if(K(t)){t=us(t);var n=e?_c.test((t||"").replace(/[- ]/g,"")):(function(r){var s;for(yc.lastIndex=0;s=yc.exec(r);){var o=s[2];if(o)for(var a=o.replace(/[- ]/g,""),l=0;a.length>l;l++)for(var u of Zp){var c=l+u;if(a.length>=c){var d=a.slice(l,c);if(_c.test(d)&&Qp(d))return!0}}}return!1})(t);if(n)return!1;var i=e?Xp.test(t):(function(r){var s;for(wc.lastIndex=0;s=wc.exec(r);){var o=s[1],a=s[3];if(!(o&&a&&bc.test(o)&&bc.test(a)))return!0}return!1})(t);if(i)return!1}return!0}function Ec(t){var e=Ri(t);return Ei(e=(e+" "+Hd(t)).trim())?e:""}function Hd(t){var e="";return t&&t.childNodes&&t.childNodes.length&&te(t.childNodes,(function(n){var i;if(n&&((i=n.tagName)==null?void 0:i.toLowerCase())==="span")try{var r=Ri(n);e=(e+" "+r).trim(),n.childNodes&&n.childNodes.length&&(e=(e+" "+Hd(n)).trim())}catch(s){k.error("[AutoCapture]",s)}})),e}function Sc(t){return t.replace(/"|\\"/g,'\\"')}function eg(t){var e=t.attr__class;if(e)return D(e)?e:Ka(e)}var Qi=le("[Dead Clicks]"),tg=()=>!0,ng=t=>{var e,n=!((e=t.instance.persistence)==null||!e.get_property(Wa)),i=t.instance.config.capture_dead_clicks;return at(i)?i:!!ae(i)||n};class xc{get lazyLoadedDeadClicksAutocapture(){return this.si}constructor(e,n,i){this.instance=e,this.isEnabled=n,this.onCapture=i,this.startIfEnabledOrStop()}onRemoteConfig(e){if(e.ok){var n=e.config;"captureDeadClicks"in n&&(this.instance.persistence&&this.instance.persistence.register({[Wa]:n.captureDeadClicks}),this.startIfEnabledOrStop())}}startIfEnabledOrStop(){this.isEnabled(this)?this.ai((()=>{this.oi()})):this.stop()}ai(e){var n,i;(n=T.__PosthogExtensions__)!=null&&n.initDeadClicksAutocapture?e():(i=T.__PosthogExtensions__)==null||i.loadExternalDependency==null||i.loadExternalDependency(this.instance,"dead-clicks-autocapture",(r=>{r?Qi.error("failed to load script",r):e()}))}oi(){var e;if(C){if(!this.si&&(e=T.__PosthogExtensions__)!=null&&e.initDeadClicksAutocapture){var n=ae(this.instance.config.capture_dead_clicks)?E({},this.instance.config.capture_dead_clicks):{};n.__onCapture=this.onCapture,this.onCapture&&(n.capture_dead_swipes=!1),this.si=T.__PosthogExtensions__.initDeadClicksAutocapture(this.instance,n),this.si.start(C),Qi.info("starting...")}}else Qi.error("`document` not found. Cannot start.")}stop(){this.si&&(this.si.stop(),this.si=void 0,Qi.info("stopping..."))}}var co=le("[SegmentIntegration]"),Wd="posthog-js";function qd(t,e){var n=e===void 0?{}:e,i=n.organization,r=n.projectId,s=n.prefix,o=n.severityAllowList,a=o===void 0?["error"]:o,l=n.sendExceptionsToPostHog,u=l===void 0||l;return c=>{var d,h,f,p,g;if(a!=="*"&&!a.includes(c.level)||!t.__loaded)return c;c.tags||(c.tags={});var m=t.requestRouter.endpointFor("ui","/project/"+t.config.token+"/person/"+t.get_distinct_id());c.tags["PostHog Person URL"]=m,t.sessionRecordingStarted()&&(c.tags["PostHog Recording URL"]=t.get_session_replay_url({withTimestamp:!0}));var v,w=((d=c.exception)==null?void 0:d.values)||[],b=w.map((A=>E({},A,{stacktrace:A.stacktrace?E({},A.stacktrace,{type:"raw",frames:(A.stacktrace.frames||[]).map((P=>E({},P,{platform:"web:javascript"})))}):void 0}))),I={$exception_message:((h=w[0])==null?void 0:h.value)||c.message,$exception_type:(f=w[0])==null?void 0:f.type,$exception_level:c.level,$exception_list:b,$sentry_event_id:c.event_id,$sentry_exception:c.exception,$sentry_exception_message:((p=w[0])==null?void 0:p.value)||c.message,$sentry_exception_type:(g=w[0])==null?void 0:g.type,$sentry_tags:c.tags};return i&&r&&(I.$sentry_url=(s||"https://sentry.io/organizations/")+i+"/issues/?project="+r+"&query="+c.event_id),u&&((v=t.exceptions)==null||v.sendExceptionEvent(I)),c}}class ig{constructor(e,n,i,r,s,o){this.name=Wd,this.setupOnce=function(a){a(qd(e,{organization:n,projectId:i,prefix:r,severityAllowList:s,sendExceptionsToPostHog:o==null||o}))}}}class kc{constructor(e){this.li=(n,i,r)=>{r&&(r.noSessionId||r.activityTimeout||r.sessionPastMaximumLength||r.crossTabAdoption)&&(k.info("[PageViewManager] Session rotated, clearing pageview state",{sessionId:n,changeReason:r}),this.ui=void 0,this._instance.scrollManager.resetContext())},this._instance=e,this.hi()}hi(){var e;this.di=(e=this._instance.sessionManager)==null?void 0:e.onSessionId(this.li)}destroy(){var e;(e=this.di)==null||e.call(this),this.di=void 0}doPageView(e,n){var i,r=this.vi(e,n);return this.ui={pathname:(i=_?.location.pathname)!==null&&i!==void 0?i:"",pageViewId:n,timestamp:e},this._instance.scrollManager.resetContext(),r}doPageLeave(e){var n;return this.vi(e,(n=this.ui)==null?void 0:n.pageViewId)}doEvent(){var e;return{$pageview_id:(e=this.ui)==null?void 0:e.pageViewId}}vi(e,n){var i=this.ui;if(!i)return{$pageview_id:n};var r={$pageview_id:n,$prev_pageview_id:i.pageViewId},s=this._instance.scrollManager.getContext();if(s&&!this._instance.config.disable_scroll_properties){var o=s.maxScrollHeight,a=s.lastScrollY,l=s.maxScrollY,u=s.maxContentHeight,c=s.lastContentY,d=s.maxContentY;if(!(x(o)||x(a)||x(l)||x(u)||x(c)||x(d))){o=Math.ceil(o),a=Math.ceil(a),l=Math.ceil(l),u=Math.ceil(u),c=Math.ceil(c),d=Math.ceil(d);var h=o>1?_t(a/o,0,1,k):1,f=o>1?_t(l/o,0,1,k):1,p=u>1?_t(c/u,0,1,k):1,g=u>1?_t(d/u,0,1,k):1;r=oe(r,{$prev_pageview_last_scroll:a,$prev_pageview_last_scroll_percentage:h,$prev_pageview_max_scroll:l,$prev_pageview_max_scroll_percentage:f,$prev_pageview_last_content:c,$prev_pageview_last_content_percentage:p,$prev_pageview_max_content:d,$prev_pageview_max_content_percentage:g})}}return i.pathname&&(r.$prev_pageview_pathname=i.pathname),i.timestamp&&(r.$prev_pageview_duration=(e.getTime()-i.timestamp.getTime())/1e3),r}}var uo=["flags","surveys"],rg={[wd]:{exposure:"hidden"},[fi]:{exposure:"hidden"},__cmpns:{exposure:"hidden"},[pi]:{exposure:"hidden"},[Uo]:{exposure:"event"},[Ho]:{exposure:"hidden"},[Wo]:{exposure:"event"},[qo]:{exposure:"hidden"},[zo]:{exposure:"event"},[Vo]:{exposure:"event"},[Wa]:{exposure:"event"},[qa]:{exposure:"hidden"},[Go]:{exposure:"event"},[vn]:{exposure:"hidden"},$session_recording_enabled_server_side:{exposure:"hidden"},[Nn]:{exposure:"hidden"},[za]:{exposure:"event"},[bd]:{exposure:"event",shouldSkipFromEventProperties:t=>We(t)},$session_past_minimum_duration:{exposure:"event"},$session_recording_url_trigger_activated_session:{exposure:"event"},$session_recording_event_trigger_activated_session:{exposure:"event"},$debug_first_full_snapshot_timestamp:{exposure:"event"},$sess_rec_flush_size:{exposure:"hidden"},[hn]:{exposure:"hidden",storageGroup:"flags"},[gi]:{exposure:"hidden",storageGroup:"flags"},[ur]:{exposure:"hidden"},[Ko]:{exposure:"hidden",storageGroup:"flags"},[mi]:{exposure:"hidden",storageGroup:"flags"},[dr]:{exposure:"hidden",storageGroup:"flags",volatile:!0},[Mr]:{exposure:"hidden",storageGroup:"flags"},[gt]:{exposure:"hidden"},[fn]:{exposure:"hidden"},[Pt]:{exposure:"hidden"},[pn]:{exposure:"hidden"},[Yo]:{exposure:"hidden",storageGroup:"surveys"},[Lr]:{exposure:"hidden",storageGroup:"surveys",volatile:!0},[Jo]:{exposure:"event"},[hr]:{exposure:"hidden"},[fr]:{exposure:"hidden"},[vi]:{exposure:"hidden"},$product_tours_activated:{exposure:"hidden"},$product_tours_activated_session:{exposure:"hidden"},$conversations_widget_session_id:{exposure:"event"},$conversations_ticket_id:{exposure:"event"},$conversations_widget_state:{exposure:"event"},$conversations_user_traits:{exposure:"event"},[mn]:{exposure:"hidden"},[_i]:{exposure:"hidden"},[pr]:{exposure:"hidden"},[bi]:{exposure:"hidden",storageGroup:"flags",volatile:!0},[Xe]:{exposure:"hidden"},[Zo]:{exposure:"hidden"},[Xo]:{exposure:"hidden"},[Qo]:{exposure:"hidden"},[ea]:{exposure:"hidden"},[Nr]:{exposure:"hidden"},[Or]:{exposure:"hidden"},[Ed]:{exposure:"event"},[Sd]:{exposure:"event"},[xd]:{exposure:"event"},[kd]:{exposure:"event"},[Cd]:{exposure:"event"},[Ad]:{exposure:"event"},[Pd]:{exposure:"event"},$sdk_debug_replay_event_trigger_status:{exposure:"event"},$sdk_debug_replay_linked_flag_trigger_status:{exposure:"event"},$sdk_debug_replay_matched_recording_trigger_groups:{exposure:"event"},$sdk_debug_replay_remote_trigger_matching_config:{exposure:"event"},$sdk_debug_replay_trigger_groups_count:{exposure:"event"},$sdk_debug_replay_url_trigger_status:{exposure:"event"},$session_recording_start_reason:{exposure:"event"}},sg=[["$posthog_sr_group_event_trigger_",{exposure:"hidden"}],["$posthog_sr_group_url_trigger_",{exposure:"hidden"}],["$posthog_sr_group_sampling_",{exposure:"hidden"}]],ln=t=>{var e=rg[t];if(e)return e;for(var n of sg){var i=n[1];if(t.indexOf(n[0])===0)return i}},On=(t,e)=>{try{return JSON.stringify(t,((n,i)=>typeof i=="bigint"?i.toString():i),e)}catch{return Uu(t)}},Hr=t=>{var e=C?.createElement("a");return x(e)?null:(e.href=t,e)},qn=function(t,e){for(var n,i=((t.split("#")[0]||"").split(/\?(.*)/)[1]||"").replace(/^\?+/g,"").split("&"),r=0;i.length>r;r++){var s=i[r].split("=");if(s[0]===e){n=s;break}}if(!D(n)||2>n.length)return"";var o=n[1];try{o=decodeURIComponent(o)}catch{k.error("Skipping decoding for malformed query param: "+o)}return o.replace(/\+/g," ")},Ti=function(t,e,n){if(!t||!e||!e.length)return t;for(var i=t.split("#"),r=i[1],s=(i[0]||"").split("?"),o=s[1],a=s[0],l=(o||"").split("&"),u=[],c=0;l.length>c;c++){var d=l[c].split("=");D(d)&&(e.includes(d[0])?u.push(d[0]+"="+n):u.push(l[c]))}var h=a;return o!=null&&(h+="?"+u.join("&")),r!=null&&(h+="#"+r),h},Wr=function(t,e){var n=t.match(new RegExp(e+"=([^&]*)"));return n?n[1]:null},zd=(t,e)=>t>=e&&Bu(),Vd=(t,e,n,i)=>{if(t===0){if(Bu()){var r=e+1;return r===n&&i(),r}return e}return 0},er="https?://(.*)",zn=["gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","irclid","_kx"],og=["utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid",...zn],$i="",ag=["li_fat_id"];function Gd(t,e,n){if(!C)return{};var i,r=e?[...zn,...n||[]]:[],s=Kd(Ti(C.URL,r,$i),t),o=(i={},te(ag,(function(a){var l=Fd(a);i[a]=l||null})),i);return oe(o,s)}function Kd(t,e){var n=og.concat(e||[]),i={};return te(n,(function(r){var s=qn(t,r);i[r]=s||null})),i}function Yd(t){var e=(function(s){return s?s.search(er+"google.([^/?]*)")===0?"google":s.search(er+"bing.com")===0?"bing":s.search(er+"yahoo.com")===0?"yahoo":s.search(er+"duckduckgo.com")===0?"duckduckgo":null:null})(t),n=e!="yahoo"?"q":"p",i={};if(!We(e)){i.$search_engine=e;var r=C?qn(C.referrer,n):"";r.length&&(i.ph_keyword=r)}return i}function Ic(){return navigator.language||navigator.userLanguage}var qr="$direct";function Jd(){return C?.referrer||qr}function Zd(t,e,n){n===void 0&&(n=!1);var i=t?[...zn,...e||[]]:[],r=n?Qt(ue?.href):ue?.href,s=r?.substring(0,1e3);return{r:Jd().substring(0,1e3),u:s?Ti(s,i,$i):void 0}}function Xd(t,e){var n;e===void 0&&(e=!1);var i=t.r,r=t.u,s=e?Qt(r):r,o={$referrer:i,$referring_domain:i==null?void 0:i==qr?qr:(n=Hr(i))==null?void 0:n.host};if(s){o.$current_url=s;var a=Hr(s);o.$host=a?.host,o.$pathname=a?.pathname;var l=Kd(s);oe(o,l)}if(i){var u=Yd(i);oe(o,u)}return o}function Qd(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return}}function lg(){try{return new Date().getTimezoneOffset()}catch{return}}var cg={flags:bi,surveys:Lr},ug=["cookie","localstorage","localstorage+cookie","sessionstorage","memory"],Pn="main";class ho{constructor(e,n,i){if(i===void 0&&(i=!0),this.ci={},this.fi=!1,this.pi=!1,this.Ne=e,this.gi=i,this.props={},this.mi=void 0,this.yi=(s=>{var o="";return s.token&&(o=s.token.replace(/\+/g,"PL").replace(/\//g,"SL").replace(/=/g,"EQ")),s.persistence_name?"ph_"+s.persistence_name:"ph_"+o+"_posthog"})(e),this.ii=this.bi(e),this.pi=this.wi(e),this.load(),e.debug&&k.info("Persistence loaded",e.persistence,E({},this.props)),this.update_config(e,e,n),this.save(),_){var r=()=>this.flush();de(_,"beforeunload",r,{capture:!1}),de(_,"pagehide",r,{capture:!1})}}ki(){var e,n=(e=this.Ne)==null?void 0:e.persistence_save_debounce_ms;return Se(n)&&n>0?n:0}isDisabled(){return!!this.xi}bi(e){ug.indexOf(e.persistence.toLowerCase())===-1&&(k.critical("Unknown persistence type "+e.persistence+"; falling back to localStorage+cookie"),e.persistence="localStorage+cookie");var n,i=(function(o,a){o===void 0&&(o=[]),a===void 0&&(a=!1);var l=[...Hp,...o];return E({},re,{H(u){try{var c={};try{c=$t.H(u)||{}}catch{}var d,h=JSON.parse(re.P(u)||"{}");if(a){var f={};for(var p in c){var g=c[p];We(g)||g===""||(f[p]=g)}d=oe(h,f)}else d=oe(c,h);return re.F(u,d),d}catch{}return null},F(u,c,d,h,f,p){var g=re.F(u,c,void 0,void 0,p);try{var m={};l.forEach((v=>{c[v]&&(m[v]=c[v])})),Object.keys(m).length&&$t.F(u,m,d,h,f,p)}catch(v){re.j(v)}return g},q(u,c){try{_?.localStorage.removeItem(u),$t.q(u,c)}catch(d){re.j(d)}}})})(e.cookie_persisted_properties||[],e.__preview_cookie_wins_on_conflict||!1),r=!1,s=e.persistence.toLowerCase();return s==="localstorage"&&re.N()?(n=re,r=!0):s==="localstorage+cookie"&&i.N()?(n=i,r=!0):s==="sessionstorage"&&ge.N()?n=ge:s==="memory"?n=Wp:s==="cookie"?n=$t:i.N()?(n=i,r=!0):n=$t,this.fi=r,n}Si(e){return this.yi+"__"+e}wi(e){return this.fi&&!!e.split_storage}properties(){var e={};return te(this.props,((n,i)=>{var r=ln(i);if(!r||r.exposure==="event"){if(r!=null&&r.shouldSkipFromEventProperties!=null&&r.shouldSkipFromEventProperties(n))return;e[i]=n}})),e}load(){if(!this.xi){var e=this.ii.H(this.yi);e&&(this.props=oe({},e)),this.pi&&this.Ci()}}Ci(){for(var e of uo){var n=re.H(this.Si(e));if(n&&!Nt(n)){var i=this.Mi(e);i.persisted=!0,this.Ti(e)||(i.fingerprint=this.Ei(n,e)),this.Ii(e,n)||oe(this.props,n)}}}Ti(e){return Object.keys(this.props).some((n=>{var i;return((i=ln(n))==null?void 0:i.storageGroup)===e}))}Ii(e,n){var i=cg[e];if(!i)return!1;var r=n[i],s=this.props[i];return Se(r)&&Se(s)&&s>r}refreshKey(e){var n;if(!this.xi){var i=this.pi?(n=ln(e))==null?void 0:n.storageGroup:void 0,r=i?re.H(this.Si(i)):this.ii.H(this.yi);if(r&&e in r)this.Pi(e,r[e]);else{if(i){var s=this.ii.H(this.yi);if(s&&e in s)return void this.Pi(e,s[e])}this.Ri(e)}}}save(){if(!this.xi){var e=this.ki();e>0?x(this.Ai)&&(this.Ai=setTimeout((()=>{this.Ai=void 0,this.Fi()}),e)):this.Fi()}}flush(){x(this.Ai)||(clearTimeout(this.Ai),this.Ai=void 0,this.Fi())}Fi(){this.xi||(this.pi?this.Li():this.Oi(this.ii,this.yi,this.props,Pn))}Li(){var e=this.Di(),n=e.main,i=e.groups;for(var r of(this.Oi(this.ii,this.yi,n,Pn),uo)){var s,o=i[r];(!Nt(o)||(s=this.ci[r])!=null&&s.persisted)&&this.Oi(re,this.Si(r),o,r)}}Di(){var e={},n={flags:{},surveys:{}};return te(this.props,((i,r)=>{var s,o=(s=ln(r))==null?void 0:s.storageGroup;o?n[o][r]=i:e[r]=i})),{main:e,groups:n}}Ei(e,n){if(n===Pn)return JSON.stringify(e)+"|"+this.$i+"|"+this.Ni+"|"+this.qi;var i={};return te(e,((r,s)=>{var o;i[s]=(o=ln(s))!=null&&o.volatile?"__volatile__":r})),JSON.stringify(i)}Oi(e,n,i,r){var s=this.Mi(r);if(r===Pn||s.dirty||x(s.fingerprint)){var o;try{if((o=this.Ei(i,r))===s.fingerprint)return void(s.dirty=!1)}catch{o=void 0}e.F(n,i,this.$i,this.Ni,this.qi,this.Ne.debug)?(s.dirty=!1,r!==Pn&&(s.persisted=!0),x(o)||(s.fingerprint=o)):this.Ne.debug&&k.warn('failed to persist storage entry "'+n+'"; will retry on next save')}}remove(e){var n=(e===void 0?{}:e).keepGroupEntries,i=n!==void 0&&n;if(x(this.Ai)||(clearTimeout(this.Ai),this.Ai=void 0),this.ii.q(this.yi,!1),this.ii.q(this.yi,!0),!i&&this.gi)for(var r of uo)re.q(this.Si(r));i?delete this.ci[Pn]:this.ci={}}clear(){this.remove(),this.props={}}register_once(e,n,i){if(ae(e)){x(n)&&(n="None"),this.$i=x(i)?this.ji:i;var r=!1;if(te(e,((s,o)=>{this.props.hasOwnProperty(o)&&this.props[o]!==n||(this.Pi(o,s),r=!0)})),r)return this.save(),!0}return!1}register(e,n){if(ae(e)){this.$i=x(n)?this.ji:n;var i=!1;if(te(e,((r,s)=>{e.hasOwnProperty(s)&&(this.props[s]!==r||ae(r)||D(r))&&(this.Pi(s,r),i=!0)})),i)return this.save(),!0}return!1}unregister(e){var n=typeof e=="string"?[e]:e,i=!1;for(var r of n)r in this.props&&(this.Ri(r),i=!0);i&&this.save()}update_campaign_params(){var e=C?.URL;if(e!==this.mi){var n=Gd(this.Ne.custom_campaign_params,this.Ne.mask_personal_data_properties,this.Ne.custom_personal_data_properties);Nt(Ga(n))||this.register(n),this.mi=e}}update_search_keyword(){var e;this.register((e=C?.referrer)?Yd(e):{})}update_referrer_info(){var e;this.register_once({$referrer:Jd(),$referring_domain:C!=null&&C.referrer&&((e=Hr(C.referrer))==null?void 0:e.host)||qr},void 0)}set_initial_person_info(){this.props[Qo]||this.props[ea]||this.register_once({[Nr]:Zd(this.Ne.mask_personal_data_properties,this.Ne.custom_personal_data_properties,this.Ne.disable_capture_url_hashes)},void 0)}get_initial_props(){var e={};te([ea,Qo],(r=>{var s=this.props[r];s&&te(s,(function(o,a){e["$initial_"+Mo(a)]=o}))}));var n=this.props[Nr];if(n){var i=(function(r,s){s===void 0&&(s=!1);var o=Xd(r,s),a={};return te(o,(function(l,u){a["$initial_"+Mo(u)]=l})),a})(n,this.Ne.disable_capture_url_hashes);oe(e,i)}return e}safe_merge(e){return te(this.props,(function(n,i){i in e||(e[i]=n)})),e}update_config(e,n,i){this.ji=this.$i=e.cookie_expiration,this.set_disabled(e.disable_persistence||!!i),this.set_cross_subdomain(e.cross_subdomain_cookie),this.set_secure(e.secure_cookie);var r=e.persistence!==n.persistence||!((l,u)=>{if(l.length!==u.length)return!1;var c=[...l].sort(),d=[...u].sort();return c.every(((h,f)=>h===d[f]))})(e.cookie_persisted_properties||[],n.cookie_persisted_properties||[]),s=r?this.bi(e):this.ii,o=this.wi(e);if(r||o!==this.pi){var a=this.props;this.clear(),this.ii=s,this.pi=o,this.props=a,this.save()}}set_disabled(e){this.xi=e,this.xi?this.remove():this.save()}set_cross_subdomain(e){e!==this.Ni&&(this.Ni=e,this.remove({keepGroupEntries:!0}),this.save())}set_secure(e){e!==this.qi&&(this.qi=e,this.remove({keepGroupEntries:!0}),this.save())}set_event_timer(e,n){var i=this.props[pi]||{};i[e]=n,this.Pi(pi,i),this.save()}remove_event_timer(e){var n=this.props[pi]||{},i=n[e];return x(i)||(delete n[e],this.Pi(pi,n),this.save()),i}get_property(e){return this.props[e]}set_property(e,n){this.Pi(e,n),this.save()}Pi(e,n){var i;this.props[e]=n,(i=ln(e))!=null&&i.volatile||this.Bi(e)}Ri(e){delete this.props[e],this.Bi(e)}Bi(e){var n,i=(n=ln(e))==null?void 0:n.storageGroup;i&&(this.Mi(i).dirty=!0)}Mi(e){return this.ci[e]||(this.ci[e]={})}}function tr(t){var e=!0;return{dispose(){if(e){e=!1;var n=t();n&&Ne(n.then)&&n.then(void 0,(()=>{}))}}}}var Oe={GZipJS:"gzip-js",Base64:"base64"},ri={Activation:"events",Cancellation:"cancelEvents"},fo={Popover:"popover",API:"api",Widget:"widget"},Mt={SHOWN:"survey shown",DISMISSED:"survey dismissed",SENT:"survey sent"},po={SURVEY_ID:"$survey_id",SURVEY_ITERATION:"$survey_iteration",SURVEY_LAST_SEEN_DATE:"$survey_last_seen_date"},sa={Popover:"popover",Inline:"inline"},dg={SHOWN:"product tour shown"},Cc={TOUR_LAST_SEEN_DATE:"$product_tour_last_seen_date",TOUR_TYPE:"$product_tour_type"},Ac=le("[RateLimiter]");class hg{constructor(e){this.serverLimits={},this.lastEventRateLimited=!1,this.checkForLimiting=n=>{var i=n.text;if(i&&i.length)try{(JSON.parse(i).quota_limited||[]).forEach((r=>{Ac.info((r||"events")+" is quota limited."),this.serverLimits[r]=new Date().getTime()+6e4}))}catch(r){return void Ac.warn('could not rate limit - continuing. Error: "'+r?.message+'"',{text:i})}},this.instance=e,this.lastEventRateLimited=this.clientRateLimitContext(!0).isRateLimited}get captureEventsPerSecond(){var e;return((e=this.instance.config.rate_limiting)==null?void 0:e.events_per_second)||10}get captureEventsBurstLimit(){var e;return Math.max(((e=this.instance.config.rate_limiting)==null?void 0:e.events_burst_limit)||10*this.captureEventsPerSecond,this.captureEventsPerSecond)}clientRateLimitContext(e){var n,i,r;e===void 0&&(e=!1);var s=this.captureEventsBurstLimit,o=this.captureEventsPerSecond,a=new Date().getTime(),l=(n=(i=this.instance.persistence)==null?void 0:i.get_property(Xo))!==null&&n!==void 0?n:{tokens:s,last:a};l.tokens+=(a-l.last)/1e3*o,l.last=a,l.tokens>s&&(l.tokens=s);var u=1>l.tokens;if(u||e||(l.tokens=Math.max(0,l.tokens-1)),u&&!e){var c=(Se(l.dropped)?l.dropped:0)+1;l.dropped=c,!this.lastEventRateLimited&&this.Hi(c)&&(l.dropped=0)}return this.lastEventRateLimited=u,(r=this.instance.persistence)==null||r.set_property(Xo,l),{isRateLimited:u,remainingTokens:l.tokens}}Ui(e){var n=this.instance.config.property_denylist;return!D(n)||!n.includes(e)}zi(){var e;if(this.Ui("$current_url")&&this.Ui("$pathname")&&ue!=null&&ue.pathname)return""+((e=ue.origin)!==null&&e!==void 0?e:"")+ue.pathname}Hi(e){var n,i,r=this.captureEventsBurstLimit,s=this.captureEventsPerSecond,o=this.zi(),a=this.Ui("$session_id")?(n=(i=this.instance).get_session_id)==null?void 0:n.call(i):void 0,l=[e+" event(s) dropped since the last warning",o?"triggered on "+o:void 0,a?"session "+a: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(e){var n=this.serverLimits[e||"events"]||!1;return n!==!1&&new Date().getTime()e(this.remoteConfig))):e()}Vi(e){this._instance._send_request({method:"GET",url:this._instance.requestRouter.endpointFor("assets","/array/"+this._instance.config.token+"/config"),callback:e})}load(){try{if(this.remoteConfig)return Yt.info("Using preloaded remote config",this.remoteConfig),this.Zi(this.remoteConfig),void this.Gi();if(this._instance.Qi())return void Yt.warn("Remote config is disabled. Falling back to local config.");this.Wi((e=>{if(!e)return Yt.info("No config found after loading remote JS config. Falling back to JSON."),void this.Vi((n=>{this.Zi(n.json,n),this.Gi()}));this.Zi(e),this.Gi()}))}catch(e){Yt.error("Error loading remote config",e),this.Zi()}}stop(){this.Ki&&(clearInterval(this.Ki),this.Ki=void 0)}refresh(){!this._instance.Qi()&&C&&C.visibilityState!=="hidden"&&this._instance.reloadFeatureFlags()}Gi(){var e;if(!this.Ki){var n=(e=this._instance.config.remote_config_refresh_interval_ms)!==null&&e!==void 0?e:3e5;n!==0&&(this.Ki=setInterval((()=>{this.refresh()}),n))}}Zi(e,n){!e&&n&&(n.statusCode===0?n.error||Yt.warn("Failed to fetch remote config from PostHog."):Yt.error("Failed to fetch remote config from PostHog."));try{this._instance.Zi(e?{ok:!0,config:e}:{ok:!1})}catch(r){Yt.error("Error applying remote config",r)}if(e?.hasFeatureFlags!==!1&&!this._instance.config.advanced_disable_feature_flags_on_first_load)try{var i;(i=this._instance.featureFlags)==null||i.ensureFlagsLoaded()}catch(r){Yt.error("Error loading feature flags",r)}}}var et=Uint8Array,He=Uint16Array,Vn=Uint32Array,Za=new et([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]),Xa=new et([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]),Pc=new et([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),th=function(t,e){for(var n=new He(31),i=0;31>i;++i)n[i]=e+=1<i;++i)for(var s=n[i];n[i+1]>s;++s)r[s]=s-n[i]<<5|i;return[n,r]},nh=th(Za,2),oa=nh[1];nh[0][28]=258,oa[258]=28;for(var Fc=th(Xa,0)[1],ih=new He(32768),he=0;32768>he;++he){var Fn=(43690&he)>>>1|(21845&he)<<1;ih[he]=((65280&(Fn=(61680&(Fn=(52428&Fn)>>>2|(13107&Fn)<<2))>>>4|(3855&Fn)<<4))>>>8|(255&Fn)<<8)>>>1}var Si=function(t,e,n){for(var i=t.length,r=0,s=new He(e);i>r;++r)++s[t[r]-1];var o,a=new He(e);for(r=0;e>r;++r)a[r]=a[r-1]+s[r-1]<<1;for(o=new He(i),r=0;i>r;++r)o[r]=ih[a[t[r]-1]++]>>>15-t[r];return o},En=new et(288);for(he=0;144>he;++he)En[he]=8;for(he=144;256>he;++he)En[he]=9;for(he=256;280>he;++he)En[he]=7;for(he=280;288>he;++he)En[he]=8;var zr=new et(32);for(he=0;32>he;++he)zr[he]=5;var fg=Si(En,9),pg=Si(zr,5),rh=function(t){return(t/8>>0)+(7&t&&1)},sh=function(t,e,n){(n==null||n>t.length)&&(n=t.length);var i=new(t instanceof He?He:t instanceof Vn?Vn:et)(n-e);return i.set(t.subarray(e,n)),i},It=function(t,e,n){var i=e/8>>0;t[i]|=n<<=7&e,t[i+1]|=n>>>8},si=function(t,e,n){var i=e/8>>0;t[i]|=n<<=7&e,t[i+1]|=n>>>8,t[i+2]|=n>>>16},go=function(t,e){for(var n=[],i=0;t.length>i;++i)t[i]&&n.push({s:i,f:t[i]});var r=n.length,s=n.slice();if(!r)return[new et(0),0];if(r==1){var o=new et(n[0].s+1);return o[n[0].s]=1,[o,1]}n.sort((function(A,P){return A.f-P.f})),n.push({s:-1,f:25001});var a=n[0],l=n[1],u=0,c=1,d=2;for(n[0]={s:-1,f:a.f+l.f,l:a,r:l};c!=r-1;)a=n[n[d].f>n[u].f?u++:d++],l=n[u!=c&&n[d].f>n[u].f?u++:d++],n[c++]={s:-1,f:a.f+l.f,l:a,r:l};var h=s[0].s;for(i=1;r>i;++i)s[i].s>h&&(h=s[i].s);var f=new He(h+1),p=aa(n[c-1],f,0);if(p>e){i=0;var g=0,m=p-e,v=1<i;++i){var w=s[i].s;if(e>=f[w])break;g+=v-(1<>>=m;g>0;){var b=s[i].s;e>f[b]?g-=1<=0&&g;--i){var I=s[i].s;f[I]==e&&(--f[I],++g)}p=e}return[new et(f),p]},aa=function(t,e,n){return t.s==-1?Math.max(aa(t.l,e,n+1),aa(t.r,e,n+1)):e[t.s]=n},Rc=function(t){for(var e=t.length;e&&!t[--e];);for(var n=new He(++e),i=0,r=t[0],s=1,o=function(l){n[i++]=l},a=1;e>=a;++a)if(t[a]==r&&a!=e)++s;else{if(!r&&s>2){for(;s>138;s-=138)o(32754);s>2&&(o(s>10?s-11<<5|28690:s-3<<5|12305),s=0)}else if(s>3){for(o(r),--s;s>6;s-=6)o(8304);s>2&&(o(s-3<<5|8208),s=0)}for(;s--;)o(r);s=1,r=t[a]}return[n.subarray(0,i),e]},oi=function(t,e){for(var n=0,i=0;e.length>i;++i)n+=t[i]*e[i];return n},la=function(t,e,n){var i=n.length,r=rh(e+2);t[r]=255&i,t[r+1]=i>>>8,t[r+2]=255^t[r],t[r+3]=255^t[r+1];for(var s=0;i>s;++s)t[r+s+4]=n[s];return 8*(r+4+i)},Tc=function(t,e,n,i,r,s,o,a,l,u,c){It(e,c++,n),++r[256];for(var d=go(r,15),h=d[0],f=d[1],p=go(s,15),g=p[0],m=p[1],v=Rc(h),w=v[0],b=v[1],I=Rc(g),A=I[0],P=I[1],O=new He(19),S=0;w.length>S;++S)O[31&w[S]]++;for(S=0;A.length>S;++S)O[31&A[S]]++;for(var F=go(O,7),R=F[0],M=F[1],$=19;$>4&&!R[Pc[$-1]];--$);var N,Y,V,H,J=u+5<<3,fe=oi(r,En)+oi(s,zr)+o,Ae=oi(r,h)+oi(s,g)+o+14+3*$+oi(O,R)+(2*O[16]+3*O[17]+7*O[18]);if(fe>=J&&Ae>=J)return la(e,c,t.subarray(l,l+u));if(It(e,c,1+(fe>Ae)),c+=2,fe>Ae){N=Si(h,f),Y=h,V=Si(g,m),H=g;var ve=Si(R,M);for(It(e,c,b-257),It(e,c+5,P-1),It(e,c+10,$-4),c+=14,S=0;$>S;++S)It(e,c+3*S,R[Pc[S]]);c+=3*$;for(var xe=[w,A],Fe=0;2>Fe;++Fe){var ie=xe[Fe];for(S=0;ie.length>S;++S)It(e,c,ve[we=31&ie[S]]),c+=R[we],we>15&&(It(e,c,ie[S]>>>5&127),c+=ie[S]>>>12)}}else N=fg,Y=En,V=pg,H=zr;for(S=0;a>S;++S)if(i[S]>255){var we;si(e,c,N[257+(we=i[S]>>>18&31)]),c+=Y[we+257],we>7&&(It(e,c,i[S]>>>23&31),c+=Za[we]);var _e=31&i[S];si(e,c,V[_e]),c+=H[_e],_e>3&&(si(e,c,i[S]>>>5&8191),c+=Xa[_e])}else si(e,c,N[i[S]]),c+=Y[i[S]];return si(e,c,N[256]),c+Y[256]},gg=new Vn([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),mg=(function(){for(var t=new Vn(256),e=0;256>e;++e){for(var n=e,i=9;--i;)n=(1&n&&3988292384)^n>>>1;t[e]=n}return t})(),mo=function(t,e,n){for(;n;++e)t[e]=n,n>>>=8};function vg(t,e){e===void 0&&(e={});var n=(function(){var d=4294967295;return{p(h){for(var f=d,p=0;h.length>p;++p)f=mg[255&f^h[p]]^f>>>8;d=f},d(){return 4294967295^d}}})(),i=t.length;n.p(t);var r,s,o,a,l,u=(a=10+((r=e).filename&&r.filename.length+1||0),l=8,(function(d,h,f,p,g,m){var v=d.length,w=new et(p+v+5*(1+Math.floor(v/7e3))+g),b=w.subarray(p,w.length-g),I=0;if(!h||8>v)for(var A=0;v>=A;A+=65535){var P=A+65535;v>P?I=la(b,I,d.subarray(A,P)):(b[A]=!0,I=la(b,I,d.subarray(A,v)))}else{for(var O=gg[h-1],S=O>>>13,F=8191&O,R=(1<A;++A){var we=V(A),_e=32767&A,Le=$[we];if(M[_e]=Le,$[we]=_e,A>=Fe){var ut=v-A;if((Ae>7e3||xe>24576)&&ut>423){I=Tc(d,b,0,H,J,fe,ve,xe,ie,A-ie,I),xe=Ae=ve=0,ie=A;for(var ce=0;286>ce;++ce)J[ce]=0;for(ce=0;30>ce;++ce)fe[ce]=0}var qe=2,dt=0,sn=F,Pe=_e-Le&32767;if(ut>2&&we==V(A-Pe))for(var Ie=Math.min(S,ut)-1,Et=Math.min(32767,A),kn=Math.min(258,ut);Et>=Pe&&--sn&&_e!=Le;){if(d[A+qe]==d[A+qe-Pe]){for(var je=0;kn>je&&d[A+je]==d[A+je-Pe];++je);if(je>qe){if(qe=je,dt=Pe,je>Ie)break;var In=Math.min(Pe,je-2),St=0;for(ce=0;In>ce;++ce){var xt=A-Pe+ce+32768&32767,nt=xt-M[xt]+32768&32767;nt>St&&(St=nt,Le=xt)}}}Pe+=(_e=Le)-(Le=M[_e])+32768&32767}if(dt){H[xe++]=268435456|oa[qe]<<18|Fc[dt];var Gt=31&oa[qe],Qn=31&Fc[dt];ve+=Za[Gt]+Xa[Qn],++J[257+Gt],++fe[Qn],Fe=A+qe,++Ae}else H[xe++]=d[A],++J[d[A]]}}I=Tc(d,b,!0,H,J,fe,ve,xe,ie,A-ie,I)}return sh(w,0,p+rh(I)+g)})(s=t,(o=e).level==null?6:o.level,o.mem==null?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(s.length)))):12+o.mem,a,l)),c=u.length;return(function(d,h){var f=h.filename;if(d[0]=31,d[1]=139,d[2]=8,d[8]=2>h.level?4:h.level==9?2:0,d[9]=3,h.mtime!=0&&mo(d,4,Math.floor(new Date(h.mtime||Date.now())/1e3)),f){d[3]=8;for(var p=0;f.length>=p;++p)d[p+10]=f.charCodeAt(p)}})(u,e),mo(u,c-8,n.d()),mo(u,c-4,i),u}var _g=!!Ro||!!Na,oh="text/plain",mr=!1,ah=(t,e)=>{var n=t.split("#"),i=n[1],r=n[0].split("?"),s=r[0],o=r[1];if(!o)return t;var a=o.split("&").filter((l=>l.split("=")[0]!==e)).join("&");return s+(a?"?"+a:"")+(i?"#"+i:"")},hs=function(t,e,n){var i;n===void 0&&(n=!0);var r=t.split("?"),s=r[0],o=r[1],a=E({},e),l=(i=o?.split("&").map((c=>{var d,h=c.split("="),f=h[0],p=n&&(d=a[f])!==null&&d!==void 0?d:h[1];return delete a[f],f+"="+p})))!==null&&i!==void 0?i:[],u=(function(c,d){var h,f;d===void 0&&(d="&");var p=[];return te(c,(function(g,m){x(g)||x(m)||m==="undefined"||(h=encodeURIComponent((v=>v instanceof File)(g)?g.name:g.toString()),f=encodeURIComponent(m),p[p.length]=f+"="+h)})),p.join(d)})(a);return u&&l.push(u),l.length>0?s+"?"+l.join("&"):s},vo=t=>{if(t.Ji)return t.Ji;var e=t.data,n=t.compression;if(e){if(n===Oe.GZipJS){var i=vg((function(a,l){var u=a.length;if(typeof TextEncoder<"u")return new TextEncoder().encode(a);for(var c=new et(a.length+(a.length>>>1)),d=0,h=function(m){c[d++]=m},f=0;u>f;++f){if(d+5>c.length){var p=new et(d+8+(u-f<<1));p.set(c),c=p}var g=a.charCodeAt(f);128>g?h(g):2048>g?(h(192|g>>>6),h(128|63&g)):g>55295&&57344>g?(h(240|(g=65536+(1047552&g)|1023&a.charCodeAt(++f))>>>18),h(128|g>>>12&63),h(128|g>>>6&63),h(128|63&g)):(h(224|g>>>12),h(128|g>>>6&63),h(128|63&g))}return sh(c,0,d)})(On(e)),{mtime:0});return{contentType:oh,body:i.buffer.slice(i.byteOffset,i.byteOffset+i.byteLength),estimatedSize:i.byteLength}}if(n===Oe.Base64){var r=(function(a){return a&&btoa(encodeURIComponent(a).replace(/%([0-9A-F]{2})/g,((l,u)=>String.fromCharCode(parseInt(u,16)))))})(On(e)),s=(a=>"data="+encodeURIComponent(typeof a=="string"?a:On(a)))(r);return{contentType:"application/x-www-form-urlencoded",body:s,estimatedSize:new Blob([s]).size}}var o=On(e);return{contentType:"application/json",body:o,estimatedSize:new Blob([o]).size}}},lh=t=>{var e,n,i=()=>t.transport==="sendBeacon"?{url:hs(t.url,{compression:Oe.Base64}),encodedBody:vo(E({},t,{compression:Oe.Base64,Ji:void 0}))}:{url:ah(t.url,"compression"),encodedBody:vo(E({},t,{compression:void 0,Ji:void 0}))};try{e=vo(t)}catch(r){if(Xl(t.compression,qn(t.url,"compression")))return k.error("Failed to gzip request body, sending uncompressed payload",r),i();throw r}return e&&Xl(t.compression,qn(t.url,"compression"))&&!((n=e.body)instanceof ArrayBuffer?To(new Uint8Array(n)):ArrayBuffer.isView(n)&&To(new Uint8Array(n.buffer,n.byteOffset,n.byteLength)))?(mr=!0,i()):{url:t.url,encodedBody:e}},ch=t=>{try{return lh(t)}catch(e){return k.error(e),void(t.callback==null||t.callback({statusCode:0,error:e}))}},yg=(function(){var t=ne((function*(e){var n=On(e.data),i=yield(function(s,o,a){return $o.apply(this,arguments)})(n,ee.DEBUG,{rethrow:!0});if(!i)return e;var r=yield i.arrayBuffer();return E({},e,{Ji:{contentType:oh,body:r,estimatedSize:r.byteLength}})}));return function(e){return t.apply(this,arguments)}})(),wg=/Failed to fetch|NetworkError|Load failed/i,uh=t=>t?.name==="TypeError"&&wg.test(t?.message||""),dh=t=>{var e=ch(t);if(e){var n=e.url,i=e.encodedBody,r=i??{},s=r.contentType,o=r.body,a=r.estimatedSize,l=new Headers;te(t.headers,(function(p,g){l.append(g,p)})),s&&l.append("Content-Type",s);var u=null,c=!1;if(Vl){var d=new Vl;u={signal:d.signal,timeout:setTimeout((()=>{var p,g;c=!0,d.abort((p=t.timeout,(g=new Error("PostHog request timed out"+(p?" after "+p+"ms":""))).name="AbortError",g))}),t.timeout)}}var h=p=>{c&&p?.name==="AbortError"||uh(p)?k.warn(p):k.error(p),t.callback==null||t.callback({statusCode:0,error:p})};try{var f;Na(n,E({method:t?.method||"GET",headers:l,keepalive:t.method==="POST"&&!t.Yi&&52428.8>(a||0),body:o,signal:(f=u)==null?void 0:f.signal},t.fetchOptions)).then((p=>p.text().then((g=>{var m={statusCode:p.status,text:g};if(p.status===200)try{m.json=JSON.parse(g)}catch(v){k.error(v)}t.callback==null||t.callback(m)})))).catch(h).finally((()=>u?clearTimeout(u.timeout):null))}catch(p){u&&clearTimeout(u.timeout),h(p)}}},ca=t=>{try{var e,n=lh(t),i=n.url,r=n.encodedBody,s=r??{},o=s.body,a=s.estimatedSize;if(!o)return;var l=o instanceof Blob?o:new Blob([o],{type:s.contentType});if(Be.sendBeacon(i,l))return;var u=D(t.data)?t.data:(e=t.data)==null?void 0:e.batch;if(D(u)&&u.length>1&&(a??0)>16384){var c=Math.ceil(u.length/2),d=h=>D(t.data)?h:E({},t.data,{batch:h});return ca(E({},t,{data:d(u.slice(0,c))})),void ca(E({},t,{data:d(u.slice(c))}))}k.warn("Beacon of ~"+(a??0)+" bytes was rejected by the browser, falling back to fetch"),dh(E({},t,{Yi:!0}))}catch(h){k.warn("Beacon send failed",h)}},$c=(t,e,n,i)=>{var r=i==="query"?e==="POST"?"sent_at":"_":void 0;return hs(n===Oe.GZipJS?ah(t,"compression"):t,E({},r?{[r]:Date.now().toString()}:{},n===Oe.GZipJS?{}:{compression:n}))},vr=[];Na&&vr.push({transport:"fetch",method:dh}),Ro&&vr.push({transport:"XHR",method(t){var e=ch(t);if(e){var n=new Ro,i=e.encodedBody;n.open(t.method||"GET",e.url,!0);var r=i??{},s=r.contentType,o=r.body;te(t.headers,(function(a,l){n.setRequestHeader(l,a)})),s&&n.setRequestHeader("Content-Type",s),t.timeout&&(n.timeout=t.timeout),n.onreadystatechange=()=>{if(n.readyState===4){var a={statusCode:n.status,text:n.responseText};if(n.status===200)try{a.json=JSON.parse(n.responseText)}catch{}t.callback==null||t.callback(a)}},n.send(o)}}}),Be!=null&&Be.sendBeacon&&vr.push({transport:"sendBeacon",method:ca});var ua=3e3;class bg{constructor(e,n){this.Xi=!0,this.tr=[],this.er=_t(n?.flush_interval_ms||ua,250,5e3,k.createLogger("flush interval"),ua),this.ir=e}enqueue(e){this.tr.push(e),this.rr||this.nr()}unload(){this.sr();var e=this.tr.length>0?this.ar():{},n=Object.values(e);[...n.filter((i=>i.url.indexOf("/e")===0)),...n.filter((i=>i.url.indexOf("/e")!==0))].map((i=>{this.lr(E({},i,{transport:"sendBeacon"}))}))}enable(){this.Xi=!1,this.nr()}nr(){var e=this;this.Xi||(this.rr=setTimeout((()=>{if(this.sr(),this.tr.length>0){var n=this.ar(),i=function(){var s=n[r],o=new Date().getTime();s.data&&D(s.data)&&te(s.data,(a=>{a.offset=Math.abs(a.timestamp-o),delete a.timestamp})),e.lr(s)};for(var r in n)i()}}),this.er))}lr(e){try{this.ir(e)}catch(n){k.error(n)}}sr(){clearTimeout(this.rr),this.rr=void 0}ar(){var e={};return te(this.tr,(n=>{var i,r=n,s=(r?r.batchKey:null)||r.url;x(e[s])&&(e[s]=E({},r,{data:[]})),(i=e[s].data)==null||i.push(r.data)})),this.tr=[],e}}var Eg=["retriesPerformedSoFar"];class Sg{constructor(e){this.ur=!1,this.hr=3e3,this.tr=[],this._instance=e,this.tr=[],this.dr=!0,!x(_)&&"onLine"in _.navigator&&(this.dr=_.navigator.onLine,this.vr=()=>{this.dr=!0,this.cr()},this.pr=()=>{this.dr=!1},de(_,"online",this.vr),de(_,"offline",this.pr))}get length(){return this.tr.length}retriableRequest(e){var n=e.retriesPerformedSoFar,i=Du(e,Eg);At(n)&&(i.url=hs(i.url,{retry_count:n})),this._instance._send_request(E({},i,{callback:r=>{if(r.statusCode!==200&&(400>r.statusCode||r.statusCode>=500)){if((r.statusCode===0?3:10)>(n??0))return void this.At(E({retriesPerformedSoFar:n},i));r.statusCode===0&&k.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.")}i.callback==null||i.callback(r)}}))}At(e){var n=e.retriesPerformedSoFar||0;e.retriesPerformedSoFar=n+1;var i=(function(o){var a=3e3*Math.pow(2,o),l=a/2,u=Math.min(18e5,a),c=Math.random()-.5;return Math.ceil(u+c*(u-l))})(n),r=Date.now()+i;this.tr.push({retryAt:r,requestOptions:e});var s="Enqueued failed request for retry in "+i;navigator.onLine||(s+=" (Browser is offline)"),k.warn(s),this.ur||(this.ur=!0,this.gr())}gr(){if(this.mr&&clearTimeout(this.mr),this.tr.length===0)return this.ur=!1,void(this.mr=void 0);this.mr=setTimeout((()=>{this.dr&&this.tr.length>0&&this.cr(),this.gr()}),this.hr)}cr(){var e=Date.now(),n=[],i=this.tr.filter((s=>e>s.retryAt||(n.push(s),!1)));if(this.tr=n,i.length>0)for(var r of i)this.retriableRequest(r.requestOptions)}unload(){for(var e of(this.mr&&(clearTimeout(this.mr),this.mr=void 0),this.ur=!1,x(_)||(this.vr&&(_.removeEventListener("online",this.vr),this.vr=void 0),this.pr&&(_.removeEventListener("offline",this.pr),this.pr=void 0)),this.tr)){var n=e.requestOptions;try{this._instance._send_request(E({},n,{transport:"sendBeacon"}))}catch(i){k.error(i)}}this.tr=[]}}class xg{constructor(e){this.yr=()=>{var n,i,r,s;this.br||(this.br={});var o=this.scrollElement(),a=this.scrollY(),l=o?Math.max(0,o.scrollHeight-o.clientHeight):0,u=a+(o?.clientHeight||0),c=o?.scrollHeight||0;this.br.lastScrollY=Math.ceil(a),this.br.maxScrollY=Math.max(a,(n=this.br.maxScrollY)!==null&&n!==void 0?n:0),this.br.maxScrollHeight=Math.max(l,(i=this.br.maxScrollHeight)!==null&&i!==void 0?i:0),this.br.lastContentY=u,this.br.maxContentY=Math.max(u,(r=this.br.maxContentY)!==null&&r!==void 0?r:0),this.br.maxContentHeight=Math.max(c,(s=this.br.maxContentHeight)!==null&&s!==void 0?s:0)},this._instance=e}get _r(){return this._instance.config.scroll_root_selector}getContext(){return this.br}resetContext(){var e=this.br;return setTimeout(this.yr,0),e}startMeasuringScrollPosition(){de(_,"scroll",this.yr,{capture:!0}),de(_,"scrollend",this.yr,{capture:!0}),de(_,"resize",this.yr)}scrollElement(){if(!this._r)return _?.document.documentElement;var e=D(this._r)?this._r:[this._r];for(var n of e){var i=_?.document.querySelector(n);if(i)return i}}wr(e){var n=e==="y"?"scrollTop":"scrollLeft";if(this._r){var i=this.scrollElement();return i&&i[n]||0}return _?e==="y"?_.scrollY||_.pageYOffset||_.document.documentElement.scrollTop||0:_.scrollX||_.pageXOffset||_.document.documentElement.scrollLeft||0:0}scrollY(){return this.wr("y")}scrollX(){return this.wr("x")}}var kg=t=>Zd(t?.config.mask_personal_data_properties,t?.config.custom_personal_data_properties,t?.config.disable_capture_url_hashes);class Mc{constructor(e,n,i,r){this.kr=s=>{var o=this.Sr();if(!o||o.sessionId!==s){var a={sessionId:s,props:this.Cr(this._instance)};this.Mr.register({[Zo]:a})}},this._instance=e,this.Tr=n,this.Mr=i,this.Cr=r||kg,this.Tr.onSessionId(this.kr)}Sr(){return this.Mr.props[Zo]}getSetOnceProps(){var e,n=(e=this.Sr())==null?void 0:e.props;return n?"r"in n?Xd(n,this._instance.config.disable_capture_url_hashes):{$referring_domain:n.referringDomain,$pathname:n.initialPathName,utm_source:n.utm_source,utm_campaign:n.utm_campaign,utm_medium:n.utm_medium,utm_content:n.utm_content,utm_term:n.utm_term}:{}}getSessionProps(){var e={};return te(Ga(this.getSetOnceProps()),((n,i)=>{i==="$current_url"&&(i="url"),e["$session_entry_"+Mo(i)]=n})),e}}class Qa{on(e,n){return this.Er[e]||(this.Er[e]=[]),this.Er[e].push(n),()=>{this.Er[e]=this.Er[e].filter((i=>i!==n))}}emit(e,n){for(var i of this.Er[e]||[])i(n);for(var r of this.Er["*"]||[])r(e,n)}constructor(){this.Er={}}}var ai=le("[SessionId]");class Lc{on(e,n){return this.Ir.on(e,n)}constructor(e,n,i){var r;if(this.Pr=null,this.Rr=[],this.Ar=void 0,this.Fr=!1,this.Ir=new Qa,this.Lr=(u,c)=>!(!At(u)||!At(c))&&Math.abs(u-c)>this.sessionTimeoutMs,!e.persistence)throw new Error("SessionIdManager requires a PostHogPersistence instance");if(e.config.cookieless_mode===Tt)throw new Error('SessionIdManager cannot be used with cookieless_mode="always"');this.Ne=e.config,this.Mr=e.persistence,this.Or=void 0,this.Dr=void 0,this._sessionStartTimestamp=null,this._sessionActivityTimestamp=null,this.$r=n||Rt,this.Nr=i||Rt;var s=this.Ne.persistence_name||this.Ne.token;if(this._sessionTimeoutMs=1e3*_t(this.Ne.session_idle_timeout_seconds||1800,60,36e3,ai.createLogger("session_idle_timeout_seconds"),1800),e.register({$configured_session_timeout_ms:this._sessionTimeoutMs}),this.qr(),this.jr="ph_"+s+"_window_id",this.Br="ph_"+s+"_primary_window_exists",this.Hr()){var o=ge.H(this.jr),a=ge.H(this.Br);o&&!a?this.Or=o:ge.q(this.jr),ge.F(this.Br,!0)}if((r=this.Ne.bootstrap)!=null&&r.sessionID)try{var l=(u=>{var c=this.Ne.bootstrap.sessionID.replace(/-/g,"");if(c.length!==32)throw new Error("Not a valid UUID");if(c[12]!=="7")throw new Error("Not a UUIDv7");return parseInt(c.substring(0,12),16)})();this.Ur(this.Ne.bootstrap.sessionID,new Date().getTime(),l)}catch(u){ai.error("Invalid sessionID in bootstrap",u)}this.zr()}get sessionTimeoutMs(){return this._sessionTimeoutMs}onSessionId(e){return x(this.Rr)&&(this.Rr=[]),this.Rr.push(e),this.Dr&&e(this.Dr,this.Or),()=>{this.Rr=this.Rr.filter((n=>n!==e))}}Hr(){return this.Ne.persistence!=="memory"&&!this.Mr.xi&&ge.N()}Wr(e){e!==this.Or&&(this.Or=e,this.Hr()&&ge.F(this.jr,e))}Vr(){return this.Or?this.Or:this.Hr()?ge.H(this.jr):null}Zr(e){var n=this.Pr;return!We(n)&&!We(e)&&5e3>Math.abs(e-n)}Ur(e,n,i){var r=n!==this._sessionActivityTimestamp,s=!(e!==this.Dr||i!==this._sessionStartTimestamp);this._sessionStartTimestamp=i,this._sessionActivityTimestamp=n,this.Dr=e,s&&!r||s&&this.Zr(n)||(this.Pr=n,this.Mr.register({[Nn]:[n,e,i]}))}Gr(){var e,n=(e=this.Ne)==null?void 0:e.persistence_save_debounce_ms;return At(n)&&n>0}Qr(){this.Gr()?this.Mr.refreshKey(Nn):(this.Mr.flush(),this.Mr.load())}Kr(){var e;if(!We(this._sessionActivityTimestamp)&&this._sessionActivityTimestamp!==this.Pr){this.Qr();var n=this.Jr();n[1]===this.Dr&&n[2]===this._sessionStartTimestamp&&(this.Pr=this._sessionActivityTimestamp,this.Mr.register({[Nn]:[this._sessionActivityTimestamp,(e=this.Dr)!==null&&e!==void 0?e:null,this._sessionStartTimestamp]}),this.Mr.flush())}}Yr(){var e=this.Jr()[0],n=At(e)?e:0,i=At(this._sessionActivityTimestamp)?this._sessionActivityTimestamp:0;return Math.max(n,i)}Xr(e){return this.Qr(),this.Lr(e,this.Yr())}Jr(){var e=this.Mr.props[Nn];return D(e)&&e.length===2&&e.push(e[0]),e||[0,null,0]}resetSessionId(){this.Pr=null,clearTimeout(this.tn),this.tn=void 0,this.Ur(null,null,null)}destroy(){this.Fr=!0,this.Kr(),clearTimeout(this.tn),this.tn=void 0,this.Ar&&_&&(_.removeEventListener(Dr,this.Ar,{capture:!1}),this.Ar=void 0),this.Rr=[]}zr(){this.Ar=()=>{this.Kr(),this.Hr()&&ge.q(this.Br)},de(_,Dr,this.Ar,{capture:!1})}checkAndGetSessionAndWindowId(e,n){if(e===void 0&&(e=!1),n===void 0&&(n=null),this.Ne.cookieless_mode===Tt)throw new Error('checkAndGetSessionAndWindowId should not be called with cookieless_mode="always"');var i=n||new Date().getTime(),r=this.Jr(),s=r[1],o=r[2],a=this.Yr(),l=this.Vr(),u=At(o)&&Math.abs(i-o)>864e5,c=!1,d=!1,h=!s,f=s,p=!h&&!e&&this.Lr(i,a);if(p){(p=this.Xr(i))||ai.info("cross-tab refresh kept the session alive",{sessionId:s});var g=this.Jr();s=g[1],o=g[2]}h||p||u?(s=this.$r(),l=this.Nr(),ai.info("new session ID generated",{sessionId:s,windowId:l,changeReason:{noSessionId:h,activityTimeout:p,sessionPastMaximumLength:u}}),o=i,c=!0):(l||(l=this.Nr(),c=!0),(d=s!==f)&&(ai.info("adopted cross-tab session id",{sessionId:s,windowId:l}),c=!0));var m=At(a)&&e&&!u?a:i,v=At(o)?o:new Date().getTime();this.Wr(l),this.Ur(s,m,v),e||this.qr();var w={noSessionId:h,activityTimeout:p,sessionPastMaximumLength:u,crossTabAdoption:d};return c&&this.Rr.forEach((b=>b(s,l,w))),{sessionId:s,windowId:l,sessionStartTimestamp:v,changeReason:c?w:void 0,lastActivityTimestamp:a}}qr(){this.Fr||(clearTimeout(this.tn),this.tn=setTimeout((()=>{if(!this.Fr)if(this.Xr(new Date().getTime())){var e=this.Dr;this.resetSessionId(),this.Ir.emit("forcedIdleReset",{idleSessionId:e})}else this.qr()}),1.1*this.sessionTimeoutMs))}}var hh=function(t,e){if(!t)return!1;var n=t.userAgent;if(n&&ec(n,e))return!0;try{var i=t?.userAgentData;if(i!=null&&i.brands&&i.brands.some((r=>ec(r?.brand,e))))return!0}catch{}return!!t.webdriver};function fh(){return(fh=ne((function*(){var t=Be?.userAgentData;if(t!=null&&t.getHighEntropyValues)try{var e=yield t.getHighEntropyValues(["model"]),n=e?.model;return K(n)&&n.length>0?n:void 0}catch(i){return void k.info("Unable to resolve $device_model from userAgentData.getHighEntropyValues",i)}}))).apply(this,arguments)}var Vr=function(t,e){if(!(function(n){try{new RegExp(n)}catch{return!1}return!0})(e))return!1;try{return new RegExp(e).test(t)}catch{return!1}};function _o(t,e,n){return On({distinct_id:t,userPropertiesToSet:e,userPropertiesToSetOnce:n})}var ph={exact:(t,e)=>e.some((n=>t.some((i=>n===i)))),is_not:(t,e)=>e.every((n=>t.every((i=>n!==i)))),regex:(t,e)=>e.some((n=>t.some((i=>Vr(n,i))))),not_regex:(t,e)=>e.every((n=>t.every((i=>!Vr(n,i))))),icontains:(t,e)=>e.map(nr).some((n=>t.map(nr).some((i=>n.includes(i))))),not_icontains:(t,e)=>e.map(nr).every((n=>t.map(nr).every((i=>!n.includes(i))))),gt:(t,e)=>e.some((n=>{var i=parseFloat(n);return!isNaN(i)&&t.some((r=>i>parseFloat(r)))})),lt:(t,e)=>e.some((n=>{var i=parseFloat(n);return!isNaN(i)&&t.some((r=>it.toLowerCase();function gh(t,e){return!t||Object.entries(t).every((n=>{var i=n[1],r=e?.[n[0]];if(x(r)||We(r))return!1;var s=[String(r)],o=ph[i.operator];return!!o&&o(i.values,s)}))}var da="custom",Nc="i.posthog.com",Ig=/^\/static\//;class Cg{constructor(e){this.en={},this.instance=e}get apiHost(){var e=this.instance.config.api_host.trim().replace(/\/$/,"");return e==="https://app.posthog.com"?"https://us.i.posthog.com":e}get flagsApiHost(){var e=this.instance.config.flags_api_host;return e?e.trim().replace(/\/$/,""):this.apiHost}get uiHost(){var e,n=(e=this.instance.config.ui_host)==null?void 0:e.replace(/\/$/,"");return n||(n=this.apiHost.replace("."+Nc,".posthog.com")),n==="https://app.posthog.com"?"https://us.posthog.com":n}get region(){return this.en[this.apiHost]||(this.en[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":da),this.en[this.apiHost]}rn(e){if(Ig.test(e)){var n=this.instance.config.asset_host;if(typeof n=="string")return n.trim().replace(/\/$/,"")||void 0}}endpointFor(e,n){if(n===void 0&&(n=""),n&&(n=n[0]==="/"?n:"/"+n),e==="ui")return this.uiHost+n;if(e==="flags")return this.flagsApiHost+n;if(e==="assets"){var i=this.rn(n);if(i)return""+i+n}if(this.region===da)return this.apiHost+n;var r=Nc+n;switch(e){case"assets":return"https://"+this.region+"-assets."+r;case"api":return"https://"+this.region+"."+r}}}function mh(t){var e;return!((e=t.conditions)==null||(e=e.events)==null||(e=e.values)==null||!e.length)}var Z=le("[Surveys]"),vh="seenSurvey_",_h=t=>{try{var e=(n=>((i,r)=>""+vh+(function(s){return s.current_iteration&&s.current_iteration>0?s.id+"_"+s.current_iteration:s.id})(r))(0,n))(t);if(localStorage.getItem(e))return;localStorage.setItem(e,"true")}catch(n){Z.error("Failed to persist survey seen state",n)}},Ag=[fo.Popover,fo.Widget,fo.API],Pg={ignoreConditions:!1,ignoreDelay:!1,displayType:sa.Popover},Fg=le("[PostHog ExternalIntegrations]"),Rg={intercom:"intercom-integration",crispChat:"crisp-chat-integration"};class Tg{constructor(e){this._instance=e}ai(e,n){var i;(i=T.__PosthogExtensions__)==null||i.loadExternalDependency==null||i.loadExternalDependency(this._instance,e,(r=>{if(r)return Fg.error("failed to load script",r);n()}))}startIfEnabledOrStop(){var e=this,n=function(){var s,o,a,l=i[0],u=i[1];!u||(s=T.__PosthogExtensions__)!=null&&(s=s.integrations)!=null&&s[l]||e.ai(Rg[l],(()=>{var c;(c=T.__PosthogExtensions__)==null||(c=c.integrations)==null||(c=c[l])==null||c.start(e._instance)})),!u&&(o=T.__PosthogExtensions__)!=null&&(o=o.integrations)!=null&&o[l]&&((a=T.__PosthogExtensions__)==null||(a=a.integrations)==null||(a=a[l])==null||a.stop())};for(var i of Object.entries((r=this._instance.config.integrations)!==null&&r!==void 0?r:{})){var r;n()}}}class $g{constructor(e,n){this.rt=e,this.nn=n,this.sn=new Map,this.an=!1}add(e){var n=this;return ne((function*(){if(n.an)throw new Error("Cannot add an extension to a disposed ExtensionRuntime");if(n.sn.has(e.name))throw new Error('Browser extension "'+e.name+'" is already registered');n.sn.set(e.name,e);try{var i=e.setup(n.nn);i&&(yield i)}catch(s){var r=n.sn.get(e.name)===e;r&&n.sn.delete(e.name),n.rt.error('Failed to set up browser extension "'+e.name+'"',s),r&&n.ln(e)}}))()}dispose(){if(!this.an){this.an=!0;var e=Array.from(this.sn.values()).reverse();for(var n of(this.sn.clear(),e))this.ln(n)}}ln(e){try{var n=e.dispose==null?void 0:e.dispose();n&&Ne(n.then)&&n.then(void 0,(i=>{this.rt.error('Failed to dispose browser extension "'+e.name+'"',i)}))}catch(i){this.rt.error('Failed to dispose browser extension "'+e.name+'"',i)}}}class Mg{constructor(e){this._instance=e}initialize(){}get(e){var n=this._instance.persistence;if(typeof e=="string")return n?.get_property(e);var i={};for(var r of e){var s=n?.get_property(r);x(s)||(i[r]=s)}return i}set(e,n){var i;(i=this._instance.persistence)==null||i.register(typeof e=="string"?{[e]:n}:e)}remove(e){var n;(n=this._instance.persistence)==null||n.unregister(e)}}var Oc="extensionsRemoteConfig";class Lg{constructor(e){this.an=!1,this.instance=e,this.rt=k,this.un=e.hn,this.kv=new Mg(e),this.onEvent=n=>tr(this.instance.on("eventCaptured",(i=>{try{n({event:i.event,properties:i.properties})}catch(r){this.rt.error("Browser extension event listener failed",r)}}))),this.onRemoteConfig=n=>{if(this.an)return tr((()=>{}));var i=s=>{try{n(s)}catch(o){this.rt.error("Browser extension remote config listener failed",o)}},r=this.instance.dn.on(Oc,i);return this.un&&i(this.un),tr(r)},this.vn=new $g(k.createLogger("[BrowserExtensions]"),this)}get logger(){return this.rt}get distinctId(){return this.instance.get_distinct_id()}get anonymousId(){var e;return(e=this.instance.get_property(Fi))!==null&&e!==void 0?e:this.distinctId}get deviceId(){var e=this.instance.get_property(Fi);return typeof e=="string"?e:void 0}get library(){return{name:ee.LIB_NAME,version:ee.LIB_VERSION}}get initialPersonProperties(){var e,n;return(e=(n=this.instance.persistence)==null?void 0:n.get_initial_props())!==null&&e!==void 0?e:{}}get groups(){return this.instance.getGroups()}get session(){try{var e,n,i,r,s=(e=this.instance.sessionManager)==null?void 0:e.checkAndGetSessionAndWindowId(!0);return{sessionId:(n=s?.sessionId)!==null&&n!==void 0?n:"",windowId:(i=s?.windowId)!==null&&i!==void 0?i:"",sessionStartTimestamp:(r=s?.sessionStartTimestamp)!==null&&r!==void 0?r:0}}catch{return{sessionId:"",windowId:"",sessionStartTimestamp:0}}}get projectToken(){return this.instance.config.token}add(e){return this.vn.add(e)}capture(e,n,i){var r=this;return ne((function*(){i?r.instance.capture(e,n,{timestamp:i.timestamp,uuid:i.uuid,$set:i.set,$set_once:i.setOnce}):r.instance.capture(e,n)}))()}registerDynamicEventProperties(e){return tr(this.instance.cn(e))}handleRemoteConfig(e){this.an||(this.un=e,this.instance.dn.emit(Oc,e))}sendRequest(e,n){var i=this;return ne((function*(){var r;n===void 0&&(n={});var s=i.instance.requestRouter.endpointFor((r=n.target)!==null&&r!==void 0?r:"api",e),o={method:n.method,url:n.query?hs(s,n.query):s,data:n.body,headers:n.headers,timeout:n.timeoutMs,fireCallbackOnDrop:!0,transport:n.transport,compression:n.compression,timestampMode:n.sentAt};return n.transport==="sendBeacon"?(i.instance._send_request(o),{statusCode:202}):new Promise((a=>{o.callback=a,i.instance._send_request(o)}))}))()}dispose(){this.an||(this.an=!0,this.vn.dispose())}}var xi={},yo=0,Gr=()=>{},Bc='Consent opt in/out is not valid with cookieless_mode="always" and will be ignored',li="Surveys module not available",Dc="sanitize_properties is deprecated. Use before_send instead",yh="Invalid value for property_denylist config: ",Ng=["token","distinct_id",Id],Mn="posthog",wh=!_g&&Ue?.indexOf("MSIE")===-1&&Ue?.indexOf("Mozilla")===-1,wo=t=>{var e;return E({api_host:"https://us.i.posthog.com",flags_api_host:null,ui_host:null,asset_host:null,token:"",autocapture:!0,cross_subdomain_cookie:Op(C?.location),persistence:"localStorage+cookie",persistence_name:"",cookie_persisted_properties:[],loaded:Gr,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_external_dependency_versioned_paths:!1,__preview_cookie_wins_on_conflict:!1,debug:ue&&K(ue?.search)&&ue.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,disable_external_dependency_loading:!1,strict_script_versioning:!1,enable_recording_console_log:void 0,secure_cookie:(_==null||(e=_.location)==null?void 0:e.protocol)==="https:",ip:!1,opt_out_capturing_by_default:!1,opt_out_persistence_by_default:!1,opt_out_useragent_filter:!1,opt_out_capturing_persistence_type:"localStorage",consent_persistence_name:null,opt_out_capturing_cookie_prefix:null,opt_in_site_apps:!1,property_denylist:[],respect_dnt:!1,sanitize_properties:null,request_headers:{},request_batching:!0,properties_string_max_length:65535,mask_all_element_attributes:!1,mask_all_text:!1,mask_personal_data_properties:!1,custom_personal_data_properties:[],advanced_disable_flags:!1,advanced_disable_decide:!1,advanced_disable_feature_flags:!1,advanced_disable_feature_flags_on_first_load:!1,advanced_only_evaluate_survey_feature_flags:!1,advanced_feature_flags_dedup_per_session:!1,advanced_enable_surveys:!1,advanced_disable_toolbar_metrics:!1,feature_flag_request_timeout_ms:3e3,surveys_request_timeout_ms:1e4,on_request_error(n){k.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:ta,before_send:void 0,get_current_url:void 0,request_queue_config:{flush_interval_ms:ua},error_tracking:{},_onCapture:Gr},(n=>({rageclick:n&&n>="2026-05-30"?{content_ignorelist:Yp,ignore_text_selection:!0}:!n||"2025-11-30">n||{content_ignorelist:!0},capture_pageview:!n||"2025-05-24">n||"history_change",session_recording:n&&n>="2026-06-25"?{strictMinimumDuration:!0,canvasCapture:{resolutionScale:.6},streamNetworkBody:!0}:n&&n>="2026-05-30"?{strictMinimumDuration:!0,canvasCapture:{resolutionScale:.6}}:n&&n>="2025-11-30"?{strictMinimumDuration:!0}:{},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)}))(t))},Og=[["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"]],jc=t=>{var e={};for(var n of Og){var i=n[0],r=n[1];x(t[i])||(e[r]=t[i])}var s=oe({},e,t),o=t.__preview_external_dependency_versioned_paths;return x(o)||(x(t.strict_script_versioning)&&(s.strict_script_versioning=!!o),K(o)&&x(t.asset_host)&&(s.asset_host=o)),D(t.property_blacklist)&&(x(t.property_denylist)?s.property_denylist=t.property_blacklist:D(t.property_denylist)?s.property_denylist=[...t.property_blacklist,...t.property_denylist]:k.error(yh+t.property_denylist)),s};class Bg{constructor(){this.__forceAllowLocalhost=!1}get fn(){return this.__forceAllowLocalhost}set fn(e){k.error("WebPerformanceObserver is deprecated and has no impact on network capture. Use `_forceAllowLocalhostNetworkCapture` on `posthog.sessionRecording`"),this.__forceAllowLocalhost=e}}class ze{pn(e,n){if(e){var i=this.sn.indexOf(e);i!==-1&&this.sn.splice(i,1)}return this.sn.push(n),n.initialize==null||n.initialize(),n}gn(){return this.config.cookieless_mode===Tt||this.config.cookieless_mode===gn&&this.consent.isRejected()}get decideEndpointWasHit(){var e,n;return(e=(n=this.featureFlags)==null?void 0:n.hasLoadedFlags)!==null&&e!==void 0&&e}get flagsEndpointWasHit(){var e,n;return(e=(n=this.featureFlags)==null?void 0:n.hasLoadedFlags)!==null&&e!==void 0&&e}constructor(){var e;this.webPerformance=new Bg,this.mn=!1,this.version=ee.LIB_VERSION,this.yn=new Set,this.bn="",this.dn=new Qa,this.sn=[],this._n=[],this._calculate_event_properties=this.calculateEventProperties.bind(this),this.config=wo(),this.SentryIntegration=ig,this.sentryIntegration=i=>(function(r,s){var o=qd(r,s);return{name:Wd,processEvent:a=>o(a)}})(this,i),this.__request_queue=[],this.__loaded=!1,this.analyticsDefaultEndpoint="/e/",this.wn=!1,this.kn=null,this.xn=null,this.Sn=null,this.scrollManager=new xg(this),this.pageViewManager=new kc(this),this.rateLimiter=new hg(this),this.requestRouter=new Cg(this),this.consent=new qp(this),this.externalIntegrations=new Tg(this);var n=(e=ze.__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:(i,r,s)=>{var o=K(i)?{[i]:r}:i;this.setPersonProperties(o),s?.({})},set_once:(i,r,s)=>{var o=K(i)?{[i]:r}:i;this.setPersonProperties(void 0,o),s?.({})}},this.on("eventCaptured",(i=>k.info('send "'+i?.event+'"',i)))}init(e,n,i){if(i&&i!==Mn){var r,s=(r=xi[i])!==null&&r!==void 0?r:new ze;return s._init(e,n,i),xi[i]=s,xi[Mn][i]=s,s}return this._init(e,n,i)}_init(e,n,i){var r,s;n===void 0&&(n={});var o,a=K(e)?e.trim():"";if(!a)return k.critical("PostHog was initialized without a token. This likely indicates a misconfiguration. Please check the first argument passed to posthog.init()"),this;if(this.__loaded)return a!==((o=this.config)==null?void 0:o.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('"+a+"', { ... }, 'project2')"):console.warn("[PostHog.js]","You have already initialized PostHog! Re-initializing is a no-op"),this;this.__loaded=!0,this.config=wo(n.defaults),n.debug=this.Cn(n.debug),this.Mn=n,this.Tn=[],n.person_profiles?this.xn=n.person_profiles:n.process_person&&(this.xn=n.process_person);var l=wo(n.defaults),u=jc(n),c=oe({},l,u,{name:i,token:a});ae(l.rageclick)&&ae(u.rageclick)&&(c.rageclick=oe({},l.rageclick,u.rageclick)),ae(l.session_recording)&&ae(u.session_recording)&&(c.session_recording=oe({},l.session_recording,u.session_recording)),this.set_config(c),this.config.on_xhr_error&&k.error("on_xhr_error is deprecated. Use on_request_error instead"),this.compression=n.disable_compression?void 0:Oe.GZipJS;var d=this.En();if(this.persistence=new ho(this.config,d),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new ho(E({},this.config,{persistence:"sessionStorage"}),d,!1),this.bn="ph_"+(this.config.persistence_name||this.config.token)+"_session_registered_properties",this.config.persistence!=="memory"&&!d&&ge.N()){var h=ge.H(this.bn);D(h)&&h.forEach((P=>{K(P)&&this.yn.add(P)}))}else ge.q(this.bn);var f=E({},this.persistence.props),p=E({},this.sessionPersistence.props);this.register({$initialization_time:new Date().toISOString()}),this.In=new bg((P=>this.Pn(P)),this.config.request_queue_config),this.Rn=new Sg(this),this.__request_queue=[];var g=this.gn();if(g||(this.sessionManager=new Lc(this),this.sessionPropsManager=new Mc(this,this.sessionManager,this.persistence),this.sessionManager.onSessionId(((P,O,S)=>{(S!=null&&S.activityTimeout||S!=null&&S.sessionPastMaximumLength||S!=null&&S.crossTabAdoption)&&this.An()}))),this.Fn(),this.config.__preview_deferred_init_extensions?(k.info("Deferring extension initialization to improve startup performance"),setTimeout((()=>{this.Ln(g)}),0)):(k.info("Initializing extensions synchronously"),this.Ln(g)),ee.DEBUG=ee.DEBUG||this.config.debug,ee.DEBUG&&k.info("Starting in debug mode",{this:this,config:n,thisC:E({},this.config),p:f,s:p}),!this.config.identity_distinct_id||(r=n.bootstrap)!=null&&r.distinctID||(n.bootstrap=E({},n.bootstrap,{distinctID:this.config.identity_distinct_id,isIdentifiedID:!0})),((s=n.bootstrap)==null?void 0:s.distinctID)!==void 0){var m=n.bootstrap.distinctID,v=this.get_distinct_id(),w=this.persistence.get_property(Xe);if(n.bootstrap.isIdentifiedID&&v!=null&&v!==m&&w===An)this.identify(m);else if(n.bootstrap.isIdentifiedID&&v!=null&&v!==m&&w===on)k.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{var b=this.config.get_device_id(Rt()),I=n.bootstrap.isIdentifiedID?b:m;this.persistence.set_property(Xe,n.bootstrap.isIdentifiedID?on:An),this.register({distinct_id:m,$device_id:I})}}if(g)this.register_once({distinct_id:Ji,$device_id:null},"");else if(!this.get_distinct_id()){var A=this.config.get_device_id(Rt());this.register_once({distinct_id:A,$device_id:A},""),this.persistence.set_property(Xe,An)}return de(_,"onpagehide"in self?"pagehide":"unload",this._handle_unload.bind(this),{passive:!1}),n.segment?(function(P,O){var S=P.config.segment;if(!S)return O();(function(F,R){var M=F.config.segment;if(!M)return R();var $=Y=>{var V=()=>Y.anonymousId()||Rt();F.config.get_device_id=V,Y.id()&&(F.register({distinct_id:Y.id(),$device_id:V()}),F.persistence.set_property(Xe,on)),R()},N=M.user();"then"in N&&Ne(N.then)?N.then($):$(N)})(P,(()=>{S.register((F=>{typeof Promise<"u"&&Promise.resolve||co.warn("This browser does not have Promise support, and can not use the segment integration");var R=(M,$)=>{if(!$)return M;M.event.userId||M.event.anonymousId===F.get_distinct_id()||(co.info("No userId set, resetting PostHog"),F.reset()),M.event.userId&&M.event.userId!==F.get_distinct_id()&&(co.info("UserId set, identifying with PostHog"),F.identify(M.event.userId));var N=F.calculateEventProperties($,M.event.properties);return M.event.properties=Object.assign({},N,M.event.properties),M};return{name:"PostHog JS",type:"enrichment",version:"1.0.0",isLoaded:()=>!0,load:()=>Promise.resolve(),track:M=>R(M,M.event.event),page:M=>R(M,$n),identify:M=>R(M,oo),screen:M=>R(M,"$screen")}})(P)).then((()=>{O()}))}))})(this,(()=>this.On())):this.On(),Ne(this.config._onCapture)&&this.config._onCapture!==Gr&&(k.warn("onCapture is deprecated. Please use `before_send` instead"),this.on("eventCaptured",(P=>this.config._onCapture(P.event,P)))),this.config.ip&&k.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 fh.apply(this,arguments)})().then((P=>{P&&this.register({[ro]:P})})).catch(Gr),this}Fn(){var e,n,i,r,s,o,a=(e=(n=this.config.__extensionClasses)==null?void 0:n.featureFlags)!==null&&e!==void 0?e:(i=ze.__defaultExtensionClasses)==null?void 0:i.featureFlags;a&&(this.featureFlags&&this.featureFlags instanceof a||((r=this.Dn)==null||r.call(this),this.Dn=void 0,this.featureFlags=new a(this)),Ne(this.featureFlags.onReloading)&&Ne(this.featureFlags.setup)?this.Dn||(this.Dn=this.featureFlags.onReloading((()=>{this.dn.emit("featureFlagsReloading",!0)})),this.$n().add(this.featureFlags)):(s=(o=this.featureFlags).initialize)==null||s.call(o))}Ln(e){var n,i,r,s,o,a,l,u=performance.now(),c=E({},ze.__defaultExtensionClasses,this.config.__extensionClasses),d=[];c.exceptions&&this.sn.push(this.exceptions=(n=this.exceptions)!==null&&n!==void 0?n:new c.exceptions(this)),c.historyAutocapture&&this.sn.push(this.historyAutocapture=new c.historyAutocapture(this)),c.tracingHeaders&&this.sn.push(this.tracingHeaders=new c.tracingHeaders(this)),c.siteApps&&this.sn.push(this.siteApps=new c.siteApps(this)),c.sessionRecording&&!e&&this.sn.push(this.sessionRecording=new c.sessionRecording(this)),this.config.disable_scroll_properties||d.push((()=>{this.scrollManager.startMeasuringScrollPosition()})),c.autocapture&&this.sn.push(this.autocapture=new c.autocapture(this)),c.surveys&&this.sn.push(this.surveys=(i=this.surveys)!==null&&i!==void 0?i:new c.surveys(this)),c.logs&&this.sn.push(this.logs=(r=this.logs)!==null&&r!==void 0?r:new c.logs(this)),c.metrics&&this.sn.push(this.metrics=(s=this.metrics)!==null&&s!==void 0?s:new c.metrics(this)),c.conversations&&this.sn.push(this.conversations=(o=this.conversations)!==null&&o!==void 0?o:new c.conversations(this)),c.productTours&&this.sn.push(this.productTours=new c.productTours(this)),c.heatmaps&&this.sn.push(this.heatmaps=new c.heatmaps(this)),c.webVitalsAutocapture&&this.sn.push(this.webVitalsAutocapture=new c.webVitalsAutocapture(this)),c.exceptionObserver&&this.sn.push(this.exceptionObserver=new c.exceptionObserver(this)),c.deadClicksAutocapture&&this.sn.push(this.deadClicksAutocapture=new c.deadClicksAutocapture(this,ng)),c.toolbar&&this.sn.push(this.toolbar=(a=this.toolbar)!==null&&a!==void 0?a:new c.toolbar(this)),c.experiments&&this.sn.push(this.experiments=(l=this.experiments)!==null&&l!==void 0?l:new c.experiments(this)),this.sn.forEach((h=>{h.initialize&&d.push((()=>{h.initialize==null||h.initialize()}))})),d.push((()=>{if(this.Nn){var h=this.Nn;this.Nn=void 0,this.sn.forEach((f=>f.onRemoteConfig==null?void 0:f.onRemoteConfig(h)))}})),this.qn(d,u)}qn(e,n){for(;e.length>0;){if(this.config.__preview_deferred_init_extensions&&performance.now()-n>=30&&e.length>0)return void setTimeout((()=>{this.qn(e,n)}),0);var i=e.shift();if(i)try{i()}catch(s){k.error("Error initializing extension:",s)}}var r=Math.round(performance.now()-n);this.register_for_session({[Cd]:this.config.__preview_deferred_init_extensions?"deferred":"synchronous",[Ad]:r}),this.config.__preview_deferred_init_extensions&&k.info("PostHog extensions initialized ("+r+"ms)")}Zi(e){var n;if(!C||!C.body)return k.info("document not ready yet, trying again in 500 milliseconds..."),void setTimeout((()=>{this.Zi(e)}),500);if(this.config.__preview_deferred_init_extensions&&(this.Nn=e),this.hn=e,this.compression=void 0,e.ok){var i,r=e.config;r.supportedCompression&&!this.config.disable_compression&&(this.compression=B(r.supportedCompression,Oe.GZipJS)?Oe.GZipJS:B(r.supportedCompression,Oe.Base64)?Oe.Base64:void 0),(i=r.analytics)!=null&&i.endpoint&&(this.analyticsDefaultEndpoint=r.analytics.endpoint)}this.set_config({person_profiles:this.xn?this.xn:ta}),(n=this.jn)==null||n.handleRemoteConfig(e),this.sn.forEach((s=>s.onRemoteConfig==null?void 0:s.onRemoteConfig(e)))}On(){try{this.config.loaded(this)}catch(i){k.critical("`loaded` function failed",i)}if(this.Bn(),this.config.internal_or_test_user_hostname&&ue!=null&&ue.hostname){var e=ue.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.gn())&&this.Hn()}),1),this.Un=new eh(this),this.Un.load()}Bn(){var e;this.is_capturing()&&this.config.request_batching&&((e=this.In)==null||e.enable())}_dom_loaded(){this.is_capturing()&&Zi(this.__request_queue,(e=>this.Pn(e))),this.__request_queue=[],this.Bn()}_handle_unload(){var e,n,i,r,s;(e=this.surveys)==null||e.handlePageUnload==null||e.handlePageUnload(),(n=this.metrics)==null||n.flush("sendBeacon"),this.config.request_batching?(this.zn()&&this.capture(so),(i=this.logs)==null||i.flushLogs("sendBeacon"),(r=this.In)==null||r.unload(),(s=this.Rn)==null||s.unload()):this.zn()&&this.capture(so,null,{transport:"sendBeacon"})}_send_request(e){this.__loaded?wh?this.__request_queue.push(e):this.rateLimiter.isServerRateLimited(e.batchKey)?e.fireCallbackOnDrop&&(e.callback==null||e.callback({statusCode:429})):(e.transport=e.transport||this.config.api_transport,e.headers=E({},this.config.request_headers,e.headers),e.compression=e.compression==="best-available"?this.compression:e.compression,(x(this.config.disable_beacon)?this.config.__preview_disable_beacon:this.config.disable_beacon)&&(e.disableTransport=["sendBeacon"]),e.fetchOptions=e.fetchOptions||this.config.fetch_options,(n=>{var i,r,s,o=E({},n);o.timeout=o.timeout||6e4;var a,l,u,c,d,h=(i=o.transport)!==null&&i!==void 0?i:"fetch";h==="sendBeacon"&&x(o.compression)&&o.data&&(o.compression=Oe.Base64),o.method==="POST"&&o.data&&(o.timestampMode==="capture-body"?o.data={api_key:(l=(d=(c=D(a=o.data)?a:[a])[0])==null||(u=d.properties)==null?void 0:u.token)!==null&&l!==void 0?l:d?.token,batch:c,sent_at:new Date().toISOString()}:o.timestampMode==="body"&&(o.data=(function(m,v){return v===void 0&&(v=new Date().toISOString()),D(m)?m.map((w=>E({},w,{sent_at:v}))):E({},m,{sent_at:v})})(o.data))),o.url=$c(o.url,o.method,o.compression,o.timestampMode);var f=vr.filter((m=>!o.disableTransport||!m.transport||!o.disableTransport.includes(m.transport))),p=(r=(s=(function(m,v){for(var w=0;m.length>w;w++)if(m[w].transport===h)return m[w]})(f))==null?void 0:s.method)!==null&&r!==void 0?r:f[0].method;if(!p)throw new Error("No available transport method");var g=m=>{try{p(m)}catch(v){uh(v)?k.warn(v):k.error(v),o.callback==null||o.callback({statusCode:0,error:v})}};h!=="sendBeacon"&&o.data&&o.compression===Oe.GZipJS&&Df&&typeof Promise<"u"&&!mr?yg(o).then((m=>{g(m)})).catch((m=>{if(Ql(m))return mr=!0,void g(E({},o,{compression:void 0,url:$c(n.url,n.method,void 0,n.timestampMode)}));(v=>{if(!v||typeof v!="object")return!1;var w="name"in v?String(v.name):"";return Ql(v)||w===ju})(m)&&(mr=!0),g(o)})):p(o)})(E({},e,{callback:n=>{var i,r;this.rateLimiter.checkForLimiting(n),400>n.statusCode||(i=(r=this.config).on_request_error)==null||i.call(r,n),e.callback==null||e.callback(n)}}))):e.fireCallbackOnDrop&&(e.callback==null||e.callback({statusCode:0}))}Pn(e){this.Rn?this.Rn.retriableRequest(e):this._send_request(e)}_execute_array(e){yo++;try{var n,i=[],r=[],s=[];Zi(e,(a=>{if(a)if(D(n=a[0]))s.push(a);else if(Ne(a))try{a.call(this)}catch(l){k.error("Error executing queued PostHog call",a,l)}else D(a)&&n==="alias"?i.push(a):D(a)&&n.indexOf("capture")!==-1&&Ne(this[n])?s.push(a):r.push(a)}));var o=function(a,l){Zi(a,(function(u){try{if(D(u[0])){var c=l;te(u,(function(d){c=c[d[0]].apply(c,d.slice(1))}))}else l[u[0]].apply(l,u.slice(1))}catch(d){k.error("Error executing queued PostHog call",u,d)}}))};o(i,this),o(r,this),o(s,this)}finally{yo--}}push(e){if(yo>0&&D(e)&&K(e[0])){var n=ze.prototype[e[0]];Ne(n)&&n.apply(this,e.slice(1))}else this._execute_array([e])}capture(e,n,i){var r,s,o,a,l;if(this.__loaded&&this.persistence&&this.sessionPersistence&&this.In){if(this.is_capturing())if(!x(e)&&K(e)){var u=!this.config.opt_out_useragent_filter&&this._is_bot();if(!u||this.config.__preview_capture_bot_pageviews){var c=i!=null&&i.skip_client_rate_limiting?void 0:this.rateLimiter.clientRateLimitContext();if(c==null||!c.isRateLimited){n!=null&&n.$current_url&&!K(n?.$current_url)&&(k.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"||i!=null&&i.Wn||k.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&&this.sessionPersistence.update_campaign_params(),this.config.save_referrer&&this.sessionPersistence.update_referrer_info(),(this.config.save_campaign_params||this.config.save_referrer)&&this.persistence.set_initial_person_info();var d=new Date,h=i?.timestamp||d,f=rc(i?.uuid,Rt),p={uuid:f,event:e,properties:this.calculateEventProperties(e,n||{},h,f)};e===$n&&this.config.__preview_capture_bot_pageviews&&u&&(p.event="$bot_pageview",p.properties.$browser_type="bot"),c&&(p.properties.$lib_rate_limit_remaining_tokens=c.remainingTokens);var g=e==="$feature_flag_called"&&p.properties.$feature_flag_has_experiment===!1&&this.get_property(Mr)===!0;i?.$set&&!g&&(p.$set=i?.$set);var m=i?.$unset;m&&(p.$unset=m);var v,w,b,I=g?void 0:this.Vn(i?.$set_once,e!==uc,e===oo);if(I&&(p.$set_once=I),i!=null&&i._noTruncate||(s=this.config.properties_string_max_length,o=p,a=$=>K($)?$.slice(0,s):$,l=new Set,p=(function $(N,Y){if(N!==Object(N))return a?a(N):N;if(!l.has(N)){var V;if(l.add(N),D(N))V=[],Zi(N,(J=>{V.push($(J))}));else{var H={};te(N,((J,fe)=>{l.has(J)||(H[fe]=$(J))})),V=H}return V}})(o)),p.timestamp=h,x(i?.timestamp)||(p.properties.$event_time_override_provided=!0,p.properties.$event_time_override_system_time=d),g&&(p.properties=(function($,N){N===void 0&&(N=[]);var Y={},V=H=>{$[H]!==void 0&&(Y[H]=$[H])};return jf.forEach(V),N.forEach(V),Y})(p.properties,Ng)),e===Mt.DISMISSED||e===Mt.SENT){var A=n?.[po.SURVEY_ID],P=n?.[po.SURVEY_ITERATION];_h({id:A,current_iteration:P}),p.$set=E({},p.$set,{[(v={id:A,current_iteration:P},w=e===Mt.SENT?"responded":"dismissed",b="$survey_"+w+"/"+v.id,v.current_iteration&&v.current_iteration>0&&(b="$survey_"+w+"/"+v.id+"/"+v.current_iteration),b)]:!0})}else e===Mt.SHOWN&&(p.$set=E({},p.$set,{[po.SURVEY_LAST_SEEN_DATE]:new Date().toISOString()}));if(e===dg.SHOWN){var O=n?.[Cc.TOUR_TYPE];O&&(p.$set=E({},p.$set,{[Cc.TOUR_LAST_SEEN_DATE+"/"+O]:new Date().toISOString()}))}var S=E({},p.properties.$set,p.$set);if(Nt(S)||this.setPersonPropertiesForFlags(S),!j(this.config.before_send)){var F=this.Pt(p);if(!F)return;(p=F).uuid=rc(p.uuid,Rt)}this.dn.emit("eventCaptured",p);var R=(r=i?._url)!==null&&r!==void 0?r:this.requestRouter.endpointFor("api",this.analyticsDefaultEndpoint),M={method:"POST",url:R,data:p,compression:"best-available",timestampMode:i?._batchKey==="recordings"||/\/s\/(?:\?|$)/.test(R)?"body":"capture-body",batchKey:i?._batchKey,transport:i?.transport};return!this.config.request_batching||i&&(i==null||!i._batchKey)||i!=null&&i.send_instantly?this.Pn(M):this.In.enqueue(M),p}k.critical("This capture call is ignored due to client rate limiting.")}}else k.error("No event name provided to posthog.capture")}else k.uninitializedWarning("posthog.capture")}_addCaptureHook(e){return this.on("eventCaptured",(n=>e(n.event,n)))}$n(){var e;return(e=this.jn)!==null&&e!==void 0?e:this.jn=new Lg(this)}cn(e){this._n.push(e);var n=!0;return()=>{if(n){n=!1;var i=this._n.indexOf(e);i!==-1&&this._n.splice(i,1)}}}calculateEventProperties(e,n,i,r,s){if(i=i||new Date,!this.persistence||!this.sessionPersistence)return n;var o=s?void 0:this.persistence.remove_event_timer(e),a=E({},n);if(a.token=this.config.token,a.$config_defaults=this.config.defaults,this.gn()&&(a[Id]=!0),e==="$snapshot"){var l=E({},this.persistence.properties(),this.sessionPersistence.properties());return a.distinct_id=l.distinct_id,(!K(a.distinct_id)&&!Se(a.distinct_id)||Lo(a.distinct_id))&&k.error("Invalid distinct_id for replay event. This indicates a bug in your implementation"),a}var u,c=(function(A,P,O,S){var F,R,M,$;if(S===void 0&&(S=!1),!Ue)return{};var N,Y=A?[...zn,...P||[]]:[],V=(function(kn){for(var je=0;nc.length>je;je++){var In=nc[je],St=In[1],xt=In[0].exec(kn),nt=xt&&(Ne(St)?St(xt,kn):St);if(nt)return nt}return["",""]})(Ue),H=V[0],J=V[1],fe=(N=typeof navigator<"u"?navigator:void 0)!=null&&N.brave?{brave:!0}:{},Ae={};x(O)||(Ae.detectGoogleSearchApp=O);var ve={},xe=(F=navigator)==null||(F=F.userAgentData)==null?void 0:F.platform,Fe=(R=navigator)==null?void 0:R.maxTouchPoints,ie=_==null||(M=_.screen)==null?void 0:M.width,we=_==null||($=_.screen)==null?void 0:$.height,_e=_?.devicePixelRatio;x(xe)||(ve.userAgentDataPlatform=xe),x(Fe)||(ve.maxTouchPoints=Fe),x(ie)||(ve.screenWidth=ie),x(we)||(ve.screenHeight=we),x(_e)||(ve.devicePixelRatio=_e);var Le,ut,ce,qe,dt,sn,Pe,Ie,Et=oe(Ga({$os:H,$os_version:J,$browser:dd(Ue,navigator.vendor,fe,Ae),$device:ic(Ue),$device_type:(ut=Ue,ce=ve,Ie=ic(ut),Ie===Gu||Ie===Vu||Ie==="Kobo"||Ie==="Kindle Fire"||Ie===od?Un:Ie===Ai||Ie===Dn||Ie===Pi||Ie===Oo?"Console":Ie===Yu?"Wearable":Ie?Ye:ce?.userAgentDataPlatform==="Android"&&((qe=ce?.maxTouchPoints)!==null&&qe!==void 0?qe:0)>0?600>Math.min((dt=ce?.screenWidth)!==null&&dt!==void 0?dt:0,(sn=ce?.screenHeight)!==null&&sn!==void 0?sn:0)/((Pe=ce?.devicePixelRatio)!==null&&Pe!==void 0?Pe:1)?Ye:Un:"Desktop"),$timezone:Qd(),$timezone_offset:lg()}),{$current_url:Ti(S?Qt(ue?.href):ue?.href,Y,$i),$host:ue?.host,$pathname:ue?.pathname,$raw_user_agent:Ue.length>1e3?Ue.substring(0,997)+"...":Ue,$browser_version:sp(Ue,navigator.vendor,fe,Ae),$browser_language:Ic(),$browser_language_prefix:(Le=Ic(),typeof Le=="string"?Le.split("-")[0]:void 0),$screen_height:_?.screen.height,$screen_width:_?.screen.width,$viewport_height:_?.innerHeight,$viewport_width:_?.innerWidth,$lib:ee.LIB_NAME,$lib_version:ee.LIB_VERSION,$insert_id:Math.random().toString(36).substring(2,10)+Math.random().toString(36).substring(2,10),$time:Date.now()/1e3});return ee.SDK_DIST_CHANNEL&&(Et.$sdk_dist_channel=ee.SDK_DIST_CHANNEL),Et})(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){var d=this.sessionManager.checkAndGetSessionAndWindowId(s,i.getTime()),h=d.windowId;a.$session_id=d.sessionId,a.$window_id=h}this.sessionPropsManager&&oe(a,this.sessionPropsManager.getSessionProps());try{var f;this.sessionRecording&&oe(a,this.sessionRecording.sdkDebugProperties),a.$sdk_debug_retry_queue_size=(f=this.Rn)==null?void 0:f.length}catch(A){a.$sdk_debug_error_capturing_properties=String(A)}if(this.requestRouter.region===da&&(a.$lib_custom_api_host=this.config.api_host),u=e!==$n||s?e!==so||s?this.pageViewManager.doEvent():this.pageViewManager.doPageLeave(i):this.pageViewManager.doPageView(i,r),a=oe(a,u),e===$n&&C&&(a.title=C.title),!x(o)){var p=i.getTime()-o;a.$duration=parseFloat((p/1e3).toFixed(3))}Ue&&this.config.opt_out_useragent_filter&&(a.$browser_type=this._is_bot()?"bot":"browser");var g=this.persistence.properties(),m=this.sessionPersistence.properties();te(["$referrer","$referring_domain"],(A=>{A in g&&delete m[A]}));var v={};if(this._n.length>0)for(var w of this._n.slice())try{oe(v,w())}catch(A){k.error("Failed to produce browser extension event properties",A)}(a=oe({},c,g,m,E({},v,a))).$is_identified=this._isIdentified(),D(this.config.property_denylist)?te(this.config.property_denylist,(function(A){delete a[A]})):k.error(yh+this.config.property_denylist+" or property_blacklist config: "+this.config.property_blacklist);var b=this.config.sanitize_properties;b&&(k.error(Dc),a=b(a,e));var I=this.Zn();return a.$process_person_profile=I,I&&!s&&this.Gn("_calculate_event_properties"),a}Vn(e,n,i){var r;if(n===void 0&&(n=!0),i===void 0&&(i=!1),!this.persistence||!this.Zn()||this.mn&&!i)return e;var s=this.persistence.get_initial_props(),o=(r=this.sessionPropsManager)==null?void 0:r.getSetOnceProps(),a=oe({},s,o||{},e||{}),l=this.config.sanitize_properties;return l&&(k.error(Dc),a=l(a,"$set_once")),n&&(this.mn=!0),Nt(a)?void 0:a}register(e,n){var i;(i=this.persistence)==null||i.register(e,n)}register_once(e,n,i){var r;(r=this.persistence)==null||r.register_once(e,n,i)}register_for_session(e){var n;(n=this.sessionPersistence)==null||n.register(e),Object.keys(e).forEach((i=>this.yn.add(i))),this.Qn()}unregister(e){var n;(n=this.persistence)==null||n.unregister(e)}unregister_for_session(e){var n;(n=this.sessionPersistence)==null||n.unregister(e),this.yn.delete(e),this.Qn()}Kn(e,n){this.register({[e]:n})}An(){this.yn.forEach((e=>{var n;(n=this.sessionPersistence)==null||n.unregister(e)})),this.yn.clear(),this.Qn()}Qn(){var e;if(this.bn)if(this.config.persistence==="memory"||(e=this.sessionPersistence)!=null&&e.xi||!ge.N())ge.q(this.bn);else{var n=[];this.yn.forEach((i=>n.push(i))),n.length>0?ge.F(this.bn,n):ge.q(this.bn)}}getFeatureFlag(e,n){var i;return(i=this.featureFlags)==null?void 0:i.getFeatureFlag(e,n)}getFeatureFlagPayload(e){var n;return(n=this.featureFlags)==null?void 0:n.getFeatureFlagPayload(e)}getFeatureFlagResult(e,n){var i;return(i=this.featureFlags)==null?void 0:i.getFeatureFlagResult(e,n)}getAllFeatureFlags(){var e,n;return(e=(n=this.featureFlags)==null?void 0:n.getAllFeatureFlags())!==null&&e!==void 0?e:[]}isFeatureEnabled(e,n){var i,r;return(i=(r=this.featureFlags)==null?void 0:r.isFeatureEnabled(e,n))!==null&&i!==void 0?i:n?.defaultValue}reloadFeatureFlags(){var e;(e=this.featureFlags)==null||e.reloadFeatureFlags()}updateFlags(e,n,i){var r;(r=this.featureFlags)==null||r.updateFlags(e,n,i)}updateEarlyAccessFeatureEnrollment(e,n,i){var r;(r=this.featureFlags)==null||r.updateEarlyAccessFeatureEnrollment(e,n,i)}getEarlyAccessFeatures(e,n,i){var r;return n===void 0&&(n=!1),(r=this.featureFlags)==null?void 0:r.getEarlyAccessFeatures(e,n,i)}on(e,n){return this.dn.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:li}),()=>{})}onSessionId(e){var n,i;return(n=(i=this.sessionManager)==null?void 0:i.onSessionId(e))!==null&&n!==void 0?n:()=>{}}getSurveys(e,n){n===void 0&&(n=!1),this.surveys?this.surveys.getSurveys(e,n):e([],{isLoaded:!1,error:li})}getActiveMatchingSurveys(e,n){n===void 0&&(n=!1),this.surveys?this.surveys.getActiveMatchingSurveys(e,n):e([],{isLoaded:!1,error:li})}renderSurvey(e,n){var i;(i=this.surveys)==null||i.renderSurvey(e,n)}displaySurvey(e,n){var i;n===void 0&&(n=Pg),(i=this.surveys)==null||i.displaySurvey(e,n)}cancelPendingSurvey(e){var n;(n=this.surveys)==null||n.cancelPendingSurvey(e)}canRenderSurvey(e){var n,i;return(n=(i=this.surveys)==null?void 0:i.canRenderSurvey(e))!==null&&n!==void 0?n:{visible:!1,disabledReason:li}}canRenderSurveyAsync(e,n){var i,r;return n===void 0&&(n=!1),(i=(r=this.surveys)==null?void 0:r.canRenderSurveyAsync(e,n))!==null&&i!==void 0?i:Promise.resolve({visible:!1,disabledReason:li})}Jn(e){return!e||Lo(e)?(k.critical("Unique user id has not been set in posthog.identify"),!1):e===Ji?(k.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())||(k.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,i){if(!this.__loaded||!this.persistence)return k.uninitializedWarning("posthog.identify");if(Se(e)&&(e=e.toString(),k.warn("The first argument to posthog.identify was a number, but it should be a string. It has been converted to a string.")),this.Jn(e)&&this.Gn("posthog.identify")){var r=this.get_distinct_id();this.register({$user_id:e}),this.get_property(Fi)||this.register_once({$had_persisted_distinct_id:!0,$device_id:r},""),e!==r&&e!==this.get_property(fi)&&(this.unregister(fi),this.register({distinct_id:e}));var s,o=(this.persistence.get_property(Xe)||An)===An,a=e!==r,l=!a&&o;if(a&&o)this.persistence.set_property(Xe,on),this.setPersonPropertiesForFlags({$set:n||{},$set_once:i||{}},!1),this.capture(oo,{distinct_id:e,$anon_distinct_id:r},{$set:n||{},$set_once:i||{}}),this.Sn=_o(e,n,i),(s=this.featureFlags)==null||s.setAnonymousDistinctId(r);else if(l){this.persistence.set_property(Xe,on);var u=n||{},c=i||{};this.setPersonPropertiesForFlags({$set:u,$set_once:c},!1),this.capture("$set",{$set:u,$set_once:c}),this.Sn=_o(e,n,i)}else(n||i)&&this.setPersonProperties(n,i);a?(this.reloadFeatureFlags(),this.featureFlags?this.featureFlags.resetFlagCallReported():this.unregister(mn)):l&&(n||i)&&this.reloadFeatureFlags()}}setPersonProperties(e,n){if((e||n)&&this.Gn("posthog.setPersonProperties")){var i=_o(this.get_distinct_id(),e,n);this.Sn!==i?(this.setPersonPropertiesForFlags({$set:e||{},$set_once:n||{}},!0),this.capture("$set",{$set:e||{},$set_once:n||{}}),this.Sn=i):k.info("A duplicate setPersonProperties call was made with the same properties. It has been ignored.")}}unsetPersonProperties(e){var n,i=(D(e)?e:[e]).filter((r=>K(r)&&r.length>0));i.length!==0&&this.Gn("posthog.unsetPersonProperties")&&((n=this.featureFlags)==null||n.unsetPersonPropertiesForFlags(i,!0),this.capture("$set",{$unset:i}),this.Sn=null)}group(e,n,i){if(e&&n){var r=this.getGroups(),s=r[e]!==n;if(s&&this.resetGroupPropertiesForFlags(e),this.register({$groups:E({},r,{[e]:n})}),s||i){var o={$group_type:e,$group_key:n};i&&(o.$group_set=i),this.capture(uc,o)}i&&this.setGroupPropertiesForFlags({[e]:i}),s&&!i&&this.reloadFeatureFlags()}else k.error("posthog.group requires a group type and group key")}resetGroups(){this.register({$groups:{}}),this.resetGroupPropertiesForFlags(),this.reloadFeatureFlags()}setPersonPropertiesForFlags(e,n){var i;n===void 0&&(n=!0),(i=this.featureFlags)==null||i.setPersonPropertiesForFlags(e,n)}resetPersonPropertiesForFlags(e){var n;e===void 0&&(e=!0),(n=this.featureFlags)==null||n.resetPersonPropertiesForFlags(e)}setGroupPropertiesForFlags(e,n){var i;n===void 0&&(n=!0),this.Gn("posthog.setGroupPropertiesForFlags")&&((i=this.featureFlags)==null||i.setGroupPropertiesForFlags(e,n))}resetGroupPropertiesForFlags(e){var n;(n=this.featureFlags)==null||n.resetGroupPropertiesForFlags(e)}reset(e){this.Yn(e)}Yn(e,n){var i,r,s,o,a,l,u,c,d,h;if(n===void 0&&(n=!1),k.info("reset"),!this.__loaded)return k.uninitializedWarning("posthog.reset");var f,p=this.get_property(Fi),g=this.get_property(ro),m=this.get_property(vn),v=this.is_capturing();if(this.consent.reset(),n||!v||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."),(i=this.persistence)==null||i.clear(),(r=this.sessionPersistence)==null||r.clear(),this.yn.clear(),this.Qn(),x(m)||(f=this.persistence)==null||f.register({[vn]:m}),(s=this.surveys)==null||s.reset(),(o=this.Un)==null||o.stop(),(a=this.featureFlags)==null||a.reset(),(l=this.conversations)==null||l.reset(),(u=this.logs)==null||u.reset(),(c=this.metrics)==null||c.reset(),(d=this.persistence)==null||d.set_property(Xe,An),(h=this.sessionManager)==null||h.resetSessionId(),this.Sn=null,this.config.cookieless_mode===Tt)this.register_once({distinct_id:Ji,$device_id:null},"");else{var w=this.config.get_device_id(Rt());this.register_once({distinct_id:w,$device_id:e?w:p},""),e||x(g)||this.register({[ro]:g})}this.register({$last_posthog_reset:new Date().toISOString()},1),delete this.config.identity_distinct_id,delete this.config.identity_hash,this.reloadFeatureFlags()}shutdown(e){var n=this;return ne((function*(){var i,r,s,o,a,l,u;if(n.__loaded){(i=n.Un)==null||i.stop(),(r=n.jn)==null||r.dispose(),(s=n.sessionRecording)==null||s.dispose(),(o=n.logs)==null||o.flushLogs("sendBeacon"),(a=n.metrics)==null||a.flush("sendBeacon"),(l=n.In)==null||l.unload(),(u=n.Rn)==null||u.unload();try{var c;(c=n.featureFlags)==null||c.destroy()}catch(d){k.error("Error while destroying feature flags",d)}}else k.uninitializedWarning("posthog.shutdown")}))()}setIdentity(e,n){var i;this.config.identity_distinct_id=e,this.config.identity_hash=n,this.alias(e),(i=this.conversations)==null||i.Xn()}clearIdentity(){var e;delete this.config.identity_distinct_id,delete this.config.identity_hash,(e=this.conversations)==null||e.ts()}get_distinct_id(){return this.get_property("distinct_id")}getGroups(){return this.get_property("$groups")||{}}get_session_id(){var e,n;return(e=(n=this.sessionManager)==null?void 0:n.checkAndGetSessionAndWindowId(!0).sessionId)!==null&&e!==void 0?e:""}get_session_replay_url(e){if(!this.sessionManager)return"";var n=this.sessionManager.checkAndGetSessionAndWindowId(!0),i=n.sessionStartTimestamp,r=this.requestRouter.endpointFor("ui","/project/"+this.config.token+"/replay/"+n.sessionId);if(e!=null&&e.withTimestamp&&i){var s,o=(s=e.timestampLookBack)!==null&&s!==void 0?s:10;if(!i)return r;r+="?t="+Math.max(Math.floor((new Date().getTime()-i)/1e3)-o,0)}return r}alias(e,n){return e===this.get_property(wd)?(k.critical("Attempting to create alias for existing People user - aborting."),-2):this.Gn("posthog.alias")?(x(n)&&(n=this.get_distinct_id()),e!==n?(this.Kn(fi,e),this.capture("$create_alias",{alias:e,distinct_id:n})):(k.warn("alias matches current distinct_id - skipping api call."),this.identify(e),-1)):void 0}set_config(e){var n=E({},this.config);if(ae(e)){var i,r,s,o,a,l,u,c,d,h,f,p;oe(this.config,jc(e));var g=this.En();(i=this.persistence)==null||i.update_config(this.config,n,g),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new ho(E({},this.config,{persistence:"sessionStorage"}),g,!1);var m=this.Cn(this.config.debug);at(m)&&(this.config.debug=m),at(this.config.debug)&&(this.config.debug?(ee.DEBUG=!0,re.N()&&re.F("ph_debug",!0),k.info("set_config",{config:e,oldConfig:n,newConfig:E({},this.config)})):(ee.DEBUG=!1,re.N()&&re.q("ph_debug"))),(r=this.featureFlags)==null||r.updateConfig==null||r.updateConfig(this.config,this.Qi()),(s=this.exceptionObserver)==null||s.onConfigChange(),(o=this.exceptions)==null||o.onConfigChange(),(a=this.sessionRecording)==null||a.startIfEnabledOrStop(),(l=this.tracingHeaders)==null||l.startIfEnabledOrStop(),(u=this.autocapture)==null||u.startIfEnabled(),(c=this.heatmaps)==null||c.startIfEnabled(),(d=this.exceptionObserver)==null||d.startIfEnabledOrStop(),(h=this.deadClicksAutocapture)==null||h.startIfEnabledOrStop(),(f=this.surveys)==null||f.loadIfEnabled(),this.es(),(p=this.externalIntegrations)==null||p.startIfEnabledOrStop()}}_overrideSDKInfo(e,n){ee.LIB_NAME=e,ee.LIB_VERSION=n}startSessionRecording(e){var n,i,r,s,o,a=e===!0,l={sampling:a||!(e==null||!e.sampling),linked_flag:a||!(e==null||!e.linked_flag),url_trigger:a||!(e==null||!e.url_trigger),event_trigger:a||!(e==null||!e.event_trigger)};Object.values(l).some(Boolean)&&((n=this.sessionManager)==null||n.checkAndGetSessionAndWindowId(),l.sampling&&((i=this.sessionRecording)==null||i.overrideSampling()),l.linked_flag&&((r=this.sessionRecording)==null||r.overrideLinkedFlag()),l.url_trigger&&((s=this.sessionRecording)==null||s.overrideTrigger("url")),l.event_trigger&&((o=this.sessionRecording)==null||o.overrideTrigger("event"))),this.set_config({disable_session_recording:!1})}stopSessionRecording(){this.set_config({disable_session_recording:!0})}sessionRecordingStarted(){var e;return!((e=this.sessionRecording)==null||!e.started)}captureException(e,n){if(this.exceptions){var i=new Error("PostHog syntheticException"),r=this.exceptions.buildProperties(e,{handled:!0,syntheticException:i});return this.exceptions.sendExceptionEvent(E({},r,n))}}addExceptionStep(e,n){var i;(i=this.exceptions)==null||i.addExceptionStep(e,n)}captureLog(e){var n;(n=this.logs)==null||n.captureLog(e)}get logger(){var e,n;return(e=(n=this.logs)==null?void 0:n.logger)!==null&&e!==void 0?e:ze.rs}startExceptionAutocapture(e){this.set_config({capture_exceptions:e==null||e})}stopExceptionAutocapture(){this.set_config({capture_exceptions:!1})}loadToolbar(e){var n,i;return(n=(i=this.toolbar)==null?void 0:i.loadToolbar(e))!==null&&n!==void 0&&n}get_property(e){var n;return(n=this.persistence)==null?void 0:n.props[e]}getSessionProperty(e){var n;return(n=this.sessionPersistence)==null?void 0:n.props[e]}toString(){var e,n=(e=this.config.name)!==null&&e!==void 0?e:Mn;return n!==Mn&&(n=Mn+"."+n),n}_isIdentified(){var e,n;return((e=this.persistence)==null?void 0:e.get_property(Xe))===on||((n=this.sessionPersistence)==null?void 0:n.get_property(Xe))===on}Zn(){var e,n;return!(this.config.person_profiles==="never"||this.config.person_profiles===ta&&!this._isIdentified()&&Nt(this.getGroups())&&((e=this.persistence)==null||(e=e.props)==null||!e[fi])&&((n=this.persistence)==null||(n=n.props)==null||!n[Or]))}zn(){return this.config.capture_pageleave===!0||this.config.capture_pageleave==="if_capture_pageview"&&(this.config.capture_pageview===!0||this.config.capture_pageview==="history_change")}createPersonProfile(){this.Zn()||this.Gn("posthog.createPersonProfile")&&this.setPersonProperties({},{})}setInternalOrTestUser(){this.Gn("posthog.setInternalOrTestUser")&&this.setPersonProperties({$internal_or_test_user:!0})}Gn(e){return this.config.person_profiles==="never"?(k.error(e+' was called, but process_person is set to "never". This call will be ignored.'),!1):(this.Kn(Or,!0),!0)}En(){if(this.config.cookieless_mode==="always")return!0;var e=this.consent.isOptedOut();return this.config.disable_persistence||e&&!(!this.config.opt_out_persistence_by_default&&this.config.cookieless_mode!==gn)}es(){var e,n,i,r,s=this.En();return((e=this.persistence)==null?void 0:e.xi)!==s&&((i=this.persistence)==null||i.set_disabled(s)),((n=this.sessionPersistence)==null?void 0:n.xi)!==s&&((r=this.sessionPersistence)==null||r.set_disabled(s)),s&&(this.yn.clear(),this.Qn()),s}opt_in_capturing(e){var n;if(this.config.cookieless_mode!==Tt){if(this.gn()){var i,r,s,o,a;this.Yn(!0,!0),(i=this.sessionManager)==null||i.destroy(),(r=this.pageViewManager)==null||r.destroy(),this.sessionManager=new Lc(this),this.pageViewManager=new kc(this),this.persistence&&(this.sessionPropsManager=new Mc(this,this.sessionManager,this.persistence));var l,u=(s=(o=this.config.__extensionClasses)==null?void 0:o.sessionRecording)!==null&&s!==void 0?s:(a=ze.__defaultExtensionClasses)==null?void 0:a.sessionRecording;u&&(this.sessionRecording=this.pn(this.sessionRecording,new u(this)),this.hn&&((l=this.sessionRecording)==null||l.onRemoteConfig==null||l.onRemoteConfig(this.hn)))}var c,d;this.consent.optInOut(!0),this.es(),this.Bn(),(n=this.sessionRecording)==null||n.startIfEnabledOrStop(),this.config.cookieless_mode==gn&&((c=this.surveys)==null||c.loadIfEnabled()),(x(e?.captureEventName)||e!=null&&e.captureEventName)&&this.capture((d=e?.captureEventName)!==null&&d!==void 0?d:"$opt_in",e?.captureProperties,{send_instantly:!0}),this.config.capture_pageview&&this.Hn()}else k.warn(Bc)}opt_out_capturing(){var e,n,i;this.config.cookieless_mode!==Tt?(this.config.cookieless_mode===gn&&this.consent.isOptedIn()&&this.Yn(!0,!0),this.consent.optInOut(!1),this.es(),this.config.cookieless_mode===gn&&(this.register({distinct_id:Ji,$device_id:null}),(e=this.sessionRecording)==null||e.stopRecording(),this.sessionRecording=void 0,(n=this.sessionManager)==null||n.destroy(),(i=this.pageViewManager)==null||i.destroy(),this.sessionManager=void 0,this.sessionPropsManager=void 0,this.config.capture_pageview&&this.Hn(),this.Bn())):k.warn(Bc)}has_opted_in_capturing(){return this.consent.isOptedIn()}has_opted_out_capturing(){return this.consent.isOptedOut()}get_explicit_consent_status(){var e=this.consent.consent;return e===1?"granted":e===0?"denied":"pending"}is_capturing(){return this.config.cookieless_mode===Tt||(this.config.cookieless_mode===gn?this.consent.isRejected()||this.consent.isOptedIn():!this.has_opted_out_capturing())}clear_opt_in_out_capturing(){this.consent.reset(),this.es()}_is_bot(){return Be?hh(Be,this.config.custom_blocked_useragents):void 0}Hn(){C&&(C.visibilityState==="visible"?this.wn||(this.wn=!0,this.capture($n,{title:C.title},{send_instantly:!0}),this.kn&&(C.removeEventListener(Br,this.kn),this.kn=null)):this.kn||(this.kn=this.Hn.bind(this),de(C,Br,this.kn)))}debug(e){e===!1?(_?.console.log("You've disabled debug mode."),this.set_config({debug:!1})):(_?.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}))}Qi(){var e=this.Mn||{};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?(k.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,i,r,s,o){var a=i in n&&!j(n[i]),l=r in n&&!j(n[r]);return a?n[i]:!!l&&(o&&o.warn("Config field '"+r+"' is deprecated. Please use '"+i+"' instead. The old field will be removed in a future major version."),n[r])})(e,"advanced_disable_flags","advanced_disable_decide",0,k)}Pt(e){var n;if(j(this.config.before_send))return e;var i=Object.keys((n=e.properties)!==null&&n!==void 0?n:{}).filter(Gf),r=D(this.config.before_send)?this.config.before_send:[this.config.before_send],s=e;for(var o of r){if(s=o(s),j(s)){var a="Event '"+e.event+"' was rejected in beforeSend function";return Vf(e.event)?k.warn(a+". This can cause unexpected behavior."):k.info(a),null}s.properties&&!Nt(s.properties)||k.warn("Event '"+e.event+"' has no properties after beforeSend function, this is likely an error.")}for(var l of i)if(s.properties&&j(s.properties[l]))return k.warn("Event '"+e.event+"' had its '"+l+"' property removed in a beforeSend function. This property is required for ingestion, so the event will be dropped."),null;return s}getPageViewId(){var e;return(e=this.pageViewManager.ui)==null?void 0:e.pageViewId}captureTraceFeedback(e,n){this.capture("$ai_feedback",{$ai_trace_id:String(e),$ai_feedback_text:n})}captureTraceMetric(e,n,i){this.capture("$ai_metric",{$ai_trace_id:String(e),$ai_metric_name:n,$ai_metric_value:String(i)})}Cn(e){var n=at(e)&&!e,i=re.N()&&re.P("ph_debug")==="true";return!n&&(!!i||e)}}ze.__defaultExtensionClasses={},ze.rs=(()=>{var t=()=>{};return{trace:t,debug:t,info:t,warn:t,error:t,fatal:t}})(),(function(t,e){for(var n=0;e.length>n;n++)t.prototype[e[n]]=Lp(t.prototype[e[n]])})(ze,["identify"]);class Uc{constructor(e){this.disabled=e===!1;var n=ae(e)?e:{};this.thresholdPx=n.threshold_px||30,this.timeoutMs=n.timeout_ms||1e3,this.clickCount=n.click_count||3,this.clicks=[]}isRageClick(e,n,i){if(this.disabled)return!1;var r=this.clicks[this.clicks.length-1];if(r&&Math.abs(e-r.x)+Math.abs(n-r.y)i-r.timestamp){if(this.clicks.push({x:e,y:n,timestamp:i}),this.clicks.length===this.clickCount)return!0}else this.clicks=[{x:e,y:n,timestamp:i}];return!1}}var bo="$copy_autocapture",Eo=le("[AutoCapture]");function So(t,e){return e.length>t?e.slice(0,t)+"...":e}function Dg(t){if(t.previousElementSibling)return t.previousElementSibling;var e=t;do e=e.previousSibling;while(e&&!en(e));return e}function jg(t,e){var n,i,r=e.e,s=e.maskAllElementAttributes,o=e.maskAllText,a=e.elementAttributeIgnoreList,l=e.elementsChainAsString,u=e.disableCaptureUrlHashes;if(!en(t))return{props:{}};for(var c=[t],d=new Set([t]),h=t;h.parentNode&&!Ge(h,"body")&&Nd>c.length;)if(Ld(h.parentNode)){var f=h.parentNode.host;if(d.has(f))break;d.add(f),c.push(f),h=f}else{if(!en(h.parentNode)||d.has(h.parentNode))break;d.add(h.parentNode),c.push(h.parentNode),h=h.parentNode}var p,g,m=[],v={},w=!1,b=!1;if(te(c,(S=>{var F=ra(S);if(Ge(S,"a")){var R=S.getAttribute("href");w=!!(F&&R&&Ei(R))&&(u?Qt(R):R)}B(Ur(S),"ph-no-capture")&&(b=!0),m.push((function($,N,Y,V,H){H===void 0&&(H=!1);var J=$.tagName.toLowerCase(),fe={tag_name:J};Ya.indexOf(J)>-1&&!Y&&(fe.$el_text=J.toLowerCase()==="a"||J.toLowerCase()==="button"?So(1024,Ec($)):So(1024,Ri($)));var Ae=Ur($);Ae.length>0&&(fe.classes=Ae.filter((function(ie){return ie!==""}))),te($.attributes,(function(ie){var we;if((!Ud($)||["name","id","class","aria-label"].indexOf(ie.name)!==-1)&&(V==null||!V.includes(ie.name))&&!N&&Ei(ie.value)&&(!K(we=ie.name)||we.substring(0,10)!=="_ngcontent"&&we.substring(0,7)!=="_nghost")){var _e=ie.value;ie.name==="class"&&(_e=Ka(_e).join(" ")),fe["attr__"+ie.name]=So(1024,ie.name==="href"&&H?Qt(_e):_e)}}));for(var ve=1,xe=1,Fe=$;Fe=Dg(Fe);)ve++,Fe.tagName===$.tagName&&xe++;return fe.nth_child=ve,fe.nth_of_type=xe,fe})(S,s,o,a,u));var M=(function($){if(!ra($))return{};var N={};return te($.attributes,(function(Y){if(Y.name&&Y.name.indexOf("data-ph-capture-attribute")===0){var V=Y.name.replace("data-ph-capture-attribute-",""),H=Y.value;V&&H&&Ei(H)&&(N[V]=H)}})),N})(S);oe(v,M)})),b)return{props:{},explicitNoCapture:b};if(o||(m[0].$el_text=Ge(t,"a")||Ge(t,"button")?Ec(t):Ri(t)),w){var I,A;m[0].attr__href=w;var P=(I=Hr(w))==null?void 0:I.host,O=_==null||(A=_.location)==null?void 0:A.host;P&&O&&P!==O&&(p=w)}return{props:oe({$event_type:r.type,$ce_version:1},l?{}:{$elements:m},{$elements_chain:(g=m,(function(S){return S.map((F=>{var R,M,$="";if(F.tag_name&&($+=F.tag_name),F.attr_class)for(var N of(F.attr_class.sort(),F.attr_class))$+="."+N.replace(/"/g,"");var Y=E({},F.text?{text:F.text}:{},{"nth-child":(R=F.nth_child)!==null&&R!==void 0?R:0,"nth-of-type":(M=F.nth_of_type)!==null&&M!==void 0?M:0},F.href?{href:F.href}:{},F.attr_id?{attr_id:F.attr_id}:{},F.attributes),V={};return gr(Y).sort(((H,J)=>H[0].localeCompare(J[0]))).forEach((H=>{var J=H[1];return V[Sc(H[0].toString())]=Sc(J.toString())})),($+=":")+gr(V).map((H=>H[0]+'="'+H[1]+'"')).join("")})).join(";")})((function(S){return S.map((F=>{var R,M,$={text:(R=F.$el_text)==null?void 0:R.slice(0,400),tag_name:F.tag_name,href:(M=F.attr__href)==null?void 0:M.slice(0,2048),attr_class:eg(F),attr_id:F.attr__id,nth_child:F.nth_child,nth_of_type:F.nth_of_type,attributes:{}};return gr(F).filter((N=>N[0].indexOf("attr__")===0)).forEach((N=>$.attributes[N[0]]=N[1])),$}))})(g)))},(n=m[0])!=null&&n.$el_text?{$el_text:(i=m[0])==null?void 0:i.$el_text}:{},p&&r.type==="click"?{$external_click_url:p}:{},v)}}var ci=le("[ExceptionAutocapture]"),Hc=()=>{},Ug=le("[TracingHeaders]"),cn=le("[Web Vitals]"),Wc=9e5,qc="disabled",zc="lazy_loading",ui="awaiting_config",ir="missing_config";le("[SessionRecording]"),le("[SessionRecording]");var ha="[SessionRecording]",Ct=le(ha),Hg=le("[Heatmaps]");function xo(t){return ae(t)&&"clientX"in t&&"clientY"in t&&Se(t.clientX)&&Se(t.clientY)}var rr=le("[Product Tours]"),ko=t=>{var e;return!t.config.disable_product_tours&&!((e=t.persistence)==null||!e.get_property(qa))},Wg=["$set_once","$set"],ht=le("[SiteApps]"),Vc="Error while initializing PostHog app with config id ";function Rn(t,e,n){if(j(t))return!1;switch(n){case"exact":return t===e;case"contains":var i=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/_/g,".").replace(/%/g,".*");return new RegExp(i,"i").test(t);case"regex":try{return new RegExp(e).test(t)}catch{return!1}default:return!1}}class qg{constructor(e){this.ns=new Qa,this.ss=(n,i)=>this.os(n,i)&&this.ls(n,i)&&this.us(n,i)&&this.hs(n,i),this.os=(n,i)=>i==null||!i.event||n?.event===i?.event,this._instance=e,this.ds=new Set,this.vs=new Set}init(){var e,n;x((e=this._instance)==null?void 0:e._addCaptureHook)||(n=this._instance)==null||n._addCaptureHook(((i,r)=>{this.on(i,r)}))}register(e){var n,i;if(!x((n=this._instance)==null?void 0:n._addCaptureHook)&&(e.forEach((o=>{var a,l;(a=this.vs)==null||a.add(o),(l=o.steps)==null||l.forEach((u=>{var c;(c=this.ds)==null||c.add(u?.event||"")}))})),(i=this._instance)!=null&&i.autocapture)){var r,s=new Set;e.forEach((o=>{var a;(a=o.steps)==null||a.forEach((l=>{l!=null&&l.selector&&s.add(l?.selector)}))})),(r=this._instance)==null||r.autocapture.setElementSelectors(s)}}on(e,n){var i;n!=null&&e.length!=0&&(this.ds.has(e)||this.ds.has(n.event))&&this.vs&&((i=this.vs)==null?void 0:i.size)>0&&this.vs.forEach((r=>{this.cs(n,r)&&this.ns.emit("actionCaptured",r.name)}))}fs(e){this.onAction("actionCaptured",(n=>e(n)))}cs(e,n){if(n?.steps==null)return!1;for(var i of n.steps)if(this.ss(e,i))return!0;return!1}onAction(e,n){return this.ns.on(e,n)}ls(e,n){if(n!=null&&n.url){var i,r=e==null||(i=e.properties)==null?void 0:i.$current_url;if(!r||typeof r!="string"||!Rn(r,n.url,n.url_matching||"contains"))return!1}return!0}us(e,n){return!!this.ps(e,n)&&!!this.gs(e,n)&&!!this.ys(e,n)}ps(e,n){var i;if(n==null||!n.href)return!0;var r=this.bs(e);if(r.length>0)return r.some((a=>Rn(a.href,n.href,n.href_matching||"exact")));var s,o=(e==null||(i=e.properties)==null?void 0:i.$elements_chain)||"";return!!o&&Rn((s=o.match(/(?::|")href="(.*?)"/))?s[1]:"",n.href,n.href_matching||"exact")}gs(e,n){var i;if(n==null||!n.text)return!0;var r=this.bs(e);if(r.length>0)return r.some((u=>Rn(u.text,n.text,n.text_matching||"exact")||Rn(u.$el_text,n.text,n.text_matching||"exact")));var s,o,a,l=(e==null||(i=e.properties)==null?void 0:i.$elements_chain)||"";return!!l&&(s=(function(u){for(var c,d=[],h=/(?::|")text="(.*?)"/g;!j(c=h.exec(u));)d.includes(c[1])||d.push(c[1]);return d})(l),o=n.text,a=n.text_matching||"exact",s.some((u=>Rn(u,o,a))))}ys(e,n){var i,r;if(n==null||!n.selector)return!0;var s=e==null||(i=e.properties)==null?void 0:i.$element_selectors;if(s!=null&&s.includes(n.selector))return!0;var o=(e==null||(r=e.properties)==null?void 0:r.$elements_chain)||"";if(n.selector_regex&&o)try{return new RegExp(n.selector_regex).test(o)}catch{return!1}return!1}bs(e){var n;return(e==null||(n=e.properties)==null?void 0:n.$elements)==null?[]:e?.properties.$elements}hs(e,n){return n==null||!n.properties||n.properties.length===0||gh(n.properties.reduce(((i,r)=>{var s=D(r.value)?r.value.map(String):r.value!=null?[String(r.value)]:[];return i[r.key]={values:s,operator:r.operator||"exact"},i}),{}),e?.properties)}}class zg{constructor(e){var n;this._s=[],this._instance=e,this.ws=new Map,this.ks=new Map,this.xs=new Map,(n=this._instance)==null||n.onSessionId==null||n.onSessionId((i=>this.Ss(i)))}Cs(e){return!1}Ms(){return null}Ts(e){}Es(){}Is(e,n){return!!e&&gh(e.propertyFilters,n?.properties)}Ps(e,n){var i=new Map;return e.forEach((r=>{var s;(s=r.conditions)==null||(s=s[n])==null||(s=s.values)==null||s.forEach((o=>{if(o!=null&&o.name){var a=i.get(o.name)||[];a.push(r.id),i.set(o.name,a)}}))})),i}Rs(e,n,i){var r=(i===ri.Activation?this.ws:this.ks).get(e),s=[];return this.As((o=>{s=o.filter((a=>r?.includes(a.id)))})),s.filter((o=>{var a,l=(a=o.conditions)==null||(a=a[i])==null||(a=a.values)==null?void 0:a.find((u=>u.name===e));return this.Is(l,n)}))}register(e){var n;x((n=this._instance)==null?void 0:n._addCaptureHook)||(this.Fs(e),this.Ls(e))}Ls(e){var n=e.filter((i=>{var r,s;return((r=i.conditions)==null?void 0:r.actions)&&((s=i.conditions)==null||(s=s.actions)==null||(s=s.values)==null?void 0:s.length)>0}));n.length!==0&&(this.Os==null&&(this.Os=new qg(this._instance),this.Os.init(),this.Os.fs((i=>{this.onAction(i)}))),n.forEach((i=>{var r,s,o,a,l;i.conditions&&(r=i.conditions)!=null&&r.actions&&(s=i.conditions)!=null&&(s=s.actions)!=null&&s.values&&((o=i.conditions)==null||(o=o.actions)==null||(o=o.values)==null?void 0:o.length)>0&&((a=this.Os)==null||a.register(i.conditions.actions.values),(l=i.conditions)==null||(l=l.actions)==null||(l=l.values)==null||l.forEach((u=>{if(u&&u.name){var c=this.xs.get(u.name);c&&c.push(i.id),this.xs.set(u.name,c||[i.id])}})))})))}Fs(e){var n,i=e.filter((s=>{var o,a;return((o=s.conditions)==null?void 0:o.events)&&((a=s.conditions)==null||(a=a.events)==null||(a=a.values)==null?void 0:a.length)>0})),r=e.filter((s=>{var o,a;return((o=s.conditions)==null?void 0:o.cancelEvents)&&((a=s.conditions)==null||(a=a.cancelEvents)==null||(a=a.values)==null?void 0:a.length)>0}));i.length===0&&r.length===0||((n=this._instance)==null||n._addCaptureHook(((s,o)=>{this.onEvent(s,o)})),this.ws=this.Ps(e,ri.Activation),this.ks=this.Ps(e,ri.Cancellation))}onEvent(e,n){var i,r,s=this.Ds(),o=(n==null||(i=n.properties)==null?void 0:i.$survey_id)||(n==null||(r=n.properties)==null?void 0:r.$product_tour_id);if(o&&this.getActivatedIds().includes(o)){var a=this.$s(e,o);if(a==="consume")return s.info("event consumed activated item, removing it",{event:e,itemId:o}),void this.Ns([o]);if(a==="persist")return s.info("shown item promoted to persisted activation",{event:e,itemId:o}),this.qs(o),void this.js([o])}if(this.ks.has(e)){var l=this.Rs(e,n,ri.Cancellation);l.length>0&&(s.info("cancel event matched, cancelling items",{event:e,itemsToCancel:l.map((c=>c.id))}),this.Ns(l.map((c=>c.id))),l.forEach((c=>this.Bs(c.id))))}if(this.ws.has(e)){s.info("event name matched",{event:e,eventPayload:n,items:this.ws.get(e)});var u=this.Rs(e,n,ri.Activation);this.Hs(u.map((c=>c.id)))}}onAction(e){this.xs.has(e)&&this.Hs(this.xs.get(e)||[])}Hs(e){var n;if(e.length!==0){var i=!((n=this._instance)==null||n.get_session_id==null||!n.get_session_id()),r=[];for(var s of e)i&&this.Cs(s)?this.qs(s)&&this.Us(s):r.push(s);r.length>0&&(this._s=[...new Set([...this._s,...r])]),this.Ds().info("updating activated items",{activatedItems:this.getActivatedIds()})}}qs(e){this._s=this._s.filter((i=>i!==e));var n=this.zs();return!n.includes(e)&&(this.Ws([...n,e]),this.Vs(),!0)}Ns(e){var n=new Set(e);this._s=this._s.filter((s=>!n.has(s)));var i=this.Zs(),r=i.filter((s=>!n.has(s)));r.length!==i.length&&(this.Ws(r),r.length===0&&this.Gs()),this.js(e)}Qs(){var e,n=this.Ms();if(!n)return{};var i=(e=this._instance)==null||(e=e.persistence)==null?void 0:e.props[n];return i&&typeof i=="object"?i:{}}Us(e){if(this.Ms()){var n=this.Qs();this.Ts(E({},n,{[e]:Date.now()}))}}js(e){if(this.Ms()){var n=this.Qs(),i={},r=!1;for(var s of Object.entries(n)){var o=s[0],a=s[1];e.includes(o)?r=!0:i[o]=a}r&&(Nt(i)?this.Es():this.Ts(i))}}Ks(){this.Ms()&&this.Es()}getActivationTimestamp(e){if(this.zs().includes(e)){var n=this.Qs()[e];return Se(n)?n:void 0}}Zs(){var e,n=this.Js();return((e=this._instance)==null||(e=e.persistence)==null?void 0:e.props[n])||[]}zs(){var e,n,i=this.Zs();if(i.length===0)return[];var r=(e=this._instance)==null||(e=e.persistence)==null?void 0:e.props[this.Ys()],s=(n=this._instance)==null||n.get_session_id==null?void 0:n.get_session_id();return s&&r===s?i:[]}Vs(){var e,n=(e=this._instance)==null||e.get_session_id==null?void 0:e.get_session_id();n&&this.Xs(n)}Gs(){this.ta()}Ss(e){var n,i=(n=this._instance)==null||(n=n.persistence)==null?void 0:n.props[this.Ys()];if(i&&i!==e){var r=this.Zs(),s=this.Qs();r.length>0&&(this.Ws([]),r.filter((o=>Se(s[o]))).forEach((o=>this.Bs(o)))),this.Gs(),this.Ks()}}getActivatedIds(){return[...new Set([...this.zs(),...this._s])].filter((e=>!this.ea(e)))}reset(){this._s=[],this.Zs().length>0&&this.Ws([]),this.Gs(),this.Ks()}getEventToItemsMap(){return this.ws}ia(){return this.Os}}class Vg extends zg{constructor(e){super(e)}Js(){return Jo}Ys(){return hr}Ms(){return fr}Ts(e){var n;(n=this._instance)==null||(n=n.persistence)==null||n.register({[fr]:e})}Es(){var e;(e=this._instance)==null||(e=e.persistence)==null||e.unregister(fr)}Cs(e){var n,i;this.As((s=>{i=s.find((o=>o.id===e))}));var r=(n=i)==null||(n=n.appearance)==null?void 0:n.surveyPopupDelaySeconds;return Se(r)&&r>0}ra(){return Mt.SHOWN}As(e){var n;(n=this._instance)==null||n.getSurveys(e)}Bs(e){var n;(n=this._instance)==null||n.cancelPendingSurvey(e)}Ds(){return Z}Ws(e){var n;(n=this._instance)==null||(n=n.persistence)==null||n.register({[Jo]:e})}Xs(e){var n;(n=this._instance)==null||(n=n.persistence)==null||n.register({[hr]:e})}ta(){var e;(e=this._instance)==null||(e=e.persistence)==null||e.unregister(hr)}ea(){return!1}$s(e,n){var i;this.As((s=>{i=s.find((o=>o.id===n))}));var r=!i||(function(s){var o;return mh(s)&&!((o=s.conditions)==null||(o=o.events)==null||!o.repeatedActivation)||s.schedule==="always"})(i);return r?e===Mt.SHOWN?"consume":"ignore":e===Mt.SHOWN?"persist":e===Mt.DISMISSED||e===Mt.SENT?"consume":"ignore"}getSurveys(){return this.getActivatedIds()}getEventToSurveys(){return this.getEventToItemsMap()}}var sr="SDK is not enabled or survey functionality is not yet loaded",Gc="Disabled. Not loading surveys.",Gg=_!=null&&_.location?Wr(_.location.hash,"__posthog")||Wr(location.hash,"state"):null,Kc="_postHogToolbarParams",Yc=le("[Toolbar]"),Jc=le("[FeatureFlags]");class Kg{constructor(e,n){n===void 0&&(n=!1),this.na=!1,this.update(e,n)}update(e,n){this.sa=((i,r)=>{var s,o,a,l;return{bootstrap:{featureFlags:(s=i.bootstrap)==null?void 0:s.featureFlags,featureFlagPayloads:(o=i.bootstrap)==null?void 0:o.featureFlagPayloads},remoteRequestsDisabled:r,featureFlagsDisabled:!!i.advanced_disable_feature_flags,onlyEvaluateSurveyFeatureFlags:!!i.advanced_only_evaluate_survey_feature_flags,deduplicateCallsPerSession:!!i.advanced_feature_flags_dedup_per_session,cacheTtlMs:i.feature_flag_cache_ttl_ms,requestTimeoutMs:i.feature_flag_request_timeout_ms,compression:i.disable_compression?"none":"base64",evaluationContexts:(a=(l=i.evaluation_contexts)!==null&&l!==void 0?l:i.evaluation_environments)!==null&&a!==void 0?a:[],flagKeys:D(i.flag_keys)?i.flag_keys:void 0}})(e,n),!e.evaluation_environments||e.evaluation_contexts||this.na||(Jc.warn("evaluation_environments is deprecated. Use evaluation_contexts instead. evaluation_environments will be removed in a future version."),this.na=!0),x(e.flag_keys)||D(e.flag_keys)||Jc.error("Invalid flag_keys found:",e.flag_keys,"Expected array of non-empty strings")}get(){return this.sa}}var Zc=le("[FeatureFlags]"),un=le("[FeatureFlags]",{debugEnabled:!0}),Io=`" failed. Feature flags didn't load in time.`,Xc="connection_error",Qc=t=>{for(var e={},n=0;t.length>n;n++)e[t[n]]=!0;return e},eu=t=>{var e={};for(var n of gr(t||{})){var i=n[1];i&&(e[n[0]]=i)}return e},ft=le("[Error tracking]"),tu="Refusing to render web experiment since the viewer is a likely bot",Yg={icontains:(t,e)=>e.toLowerCase().indexOf(t.toLowerCase())>-1,not_icontains:(t,e)=>e.toLowerCase().indexOf(t.toLowerCase())===-1,regex:(t,e)=>Vr(e,t),not_regex:(t,e)=>!Vr(e,t),exact:(t,e)=>e===t,is_not:(t,e)=>e!==t};class Re{get Ne(){return this._instance.config}constructor(e){var n=this;this.getWebExperimentsAndEvaluateDisplayLogic=function(i){i===void 0&&(i=!1),n.getWebExperiments((r=>{Re.aa("retrieved web experiments from the server"),n.oa=new Map,r.forEach((s=>{if(s.feature_flag_key){var o;n.oa&&(Re.aa("setting flag key ",s.feature_flag_key," to web experiment ",s),(o=n.oa)==null||o.set(s.feature_flag_key,s));var a=n._instance.getFeatureFlag(s.feature_flag_key);K(a)&&s.variants[a]&&n.la(s.name,a,s.variants[a].transforms)}else if(s.variants)for(var l in s.variants){var u=s.variants[l];Re.ua(u,n._instance)&&n.la(s.name,l,u.transforms)}}))}),i)},this._instance=e,this._instance.onFeatureFlags((i=>{this.onFeatureFlags(i)}))}initialize(){}onFeatureFlags(e){if(this._is_bot())Re.aa(tu);else if(!this.Ne.disable_web_experiments){if(j(this.oa))return this.oa=new Map,this.loadIfEnabled(),void this.previewWebExperiment();Re.aa("applying feature flags",e),e.forEach((n=>{var i;if(this.oa&&(i=this.oa)!=null&&i.has(n)){var r,s=this._instance.getFeatureFlag(n),o=(r=this.oa)==null?void 0:r.get(n);s&&o!=null&&o.variants[s]&&this.la(o.name,s,o.variants[s].transforms)}}))}}previewWebExperiment(){var e=Re.getWindowLocation();if(e!=null&&e.search){var n=qn(e?.search,"__experiment_id"),i=qn(e?.search,"__experiment_variant");n&&i&&(Re.aa("previewing web experiments "+n+" && "+i),this.getWebExperiments((r=>{this.ha(parseInt(n),i,r)}),!1,!0))}}loadIfEnabled(){this.Ne.disable_web_experiments||this.getWebExperimentsAndEvaluateDisplayLogic()}getWebExperiments(e,n,i){if(this.Ne.disable_web_experiments&&!i)return e([]);var r=this._instance.get_property("$web_experiments");if(r&&!n)return e(r);this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/web_experiments/?token="+this.Ne.token),method:"GET",timestampMode:"query",callback:s=>e(s.statusCode===200&&s.json&&s.json.experiments||[])})}ha(e,n,i){var r=i.filter((s=>s.id===e));r&&r.length>0&&(Re.aa("Previewing web experiment ["+r[0].name+"] with variant ["+n+"]"),this.la(r[0].name,n,r[0].variants[n].transforms))}static ua(e,n){return!j(e.conditions)&&Re.da(e,n)&&Re.va(e)}static da(e,n){var i;if(j(e.conditions)||j((i=e.conditions)==null?void 0:i.url))return!0;var r=Re.getWindowLocation();if(r){var s,o,a,l=Td(n,r.href);return(s=e.conditions)==null||!s.url||Yg[(o=(a=e.conditions)==null?void 0:a.urlMatchType)!==null&&o!==void 0?o:"icontains"](e.conditions.url,l)}return!1}static getWindowLocation(){return _?.location}static va(e){var n;if(j(e.conditions)||j((n=e.conditions)==null?void 0:n.utm))return!0;var i=Gd();if(i.utm_source){var r,s,o,a,l,u,c,d,h=(r=e.conditions)==null||(r=r.utm)==null||!r.utm_campaign||((s=e.conditions)==null||(s=s.utm)==null?void 0:s.utm_campaign)==i.utm_campaign,f=(o=e.conditions)==null||(o=o.utm)==null||!o.utm_source||((a=e.conditions)==null||(a=a.utm)==null?void 0:a.utm_source)==i.utm_source,p=(l=e.conditions)==null||(l=l.utm)==null||!l.utm_medium||((u=e.conditions)==null||(u=u.utm)==null?void 0:u.utm_medium)==i.utm_medium,g=(c=e.conditions)==null||(c=c.utm)==null||!c.utm_term||((d=e.conditions)==null||(d=d.utm)==null?void 0:d.utm_term)==i.utm_term;return h&&p&&g&&f}return!1}static aa(e){for(var n=arguments.length,i=new Array(n>1?n-1:0),r=1;n>r;r++)i[r-1]=arguments[r];k.info("[WebExperiments] "+e,i)}la(e,n,i){this._is_bot()?Re.aa(tu):n!=="control"?i.forEach((r=>{if(r.selector){var s;Re.aa("applying transform of variant "+n+" for experiment "+e+" ",r);var o=(s=document)==null?void 0:s.querySelectorAll(r.selector);o?.forEach((a=>{var l=a;r.html&&(l.innerHTML=r.html),r.css&&l.setAttribute("style",r.css)}))}})):Re.aa("Control variants leave the page unmodified.")}_is_bot(){return Be&&this._instance?hh(Be,this.Ne.custom_blocked_useragents):void 0}}var Ze=le("[Conversations]"),dn="Conversations not available yet.",nu="console",bh="__posthogHandledLogsRequestError",Co=(t,e)=>{var n=t instanceof Error?t:new Error(e);return n[bh]=!0,n},iu=t=>!!t&&typeof t=="object"&&t[bh]===!0,fs={featureFlags:class{constructor(t){this.name="featureFlags",this.ca=!1,this.featureFlagEventHandlers=[],this.rt=Zc,this.fa={},this.pa={},this.ga=[],this.ma=!1,this.ya=!1,this.ba=0,this._a=!1,this.wa=!1,this.ka=!1,this.xa=!1,this.Sa=0,this.Ca=()=>{var e=this.Ma();this.Sa=0,e&&this.reloadFeatureFlags()},"get"in t?this.Ta=t:(this.Ea=new Kg(t.config,t.Qi()),this.Ta=this.Ea)}updateConfig(t,e){var n;(n=this.Ea)==null||n.update(t,e)}setup(t){return this.Ia=t,this.rt=t.logger.createLogger("[FeatureFlags]"),n=()=>{this.Ia===t&&(this.Ia=void 0,this.nn=t,this.Pa(t))},(e=t.kv.initialize())!=null&&e.then?e.then(n):n();var e,n}Pa(t){if(this.nn===t)return _&&de(_,"online",this.Ca),this.Ra=t.registerDynamicEventProperties((()=>this.Aa()?this.fa:this.pa)),this.Fa(),this.initialize()}destroy(){_?.removeEventListener("online",this.Ca)}dispose(){var t;this.ba++,this.wa=!1,this.Ia=void 0,this.nn&&(this.La(),(t=this.Ra)==null||t.dispose(),this.Ra=void 0,this.ga=[],_?.removeEventListener("online",this.Ca),this.nn=void 0)}get Ne(){return this.Ta.get()}Oa(t){var e;return(e=this.nn)==null?void 0:e.kv.get(t)}F(t){this.Da((()=>{var e;return(e=this.nn)==null?void 0:e.kv.set(t)}))}q(t){this.Da((()=>{var e;return(e=this.nn)==null?void 0:e.kv.remove(t)}))}Da(t){try{t()}catch(e){this.rt.error("Failed to update feature flag persistence",e)}}Fa(){var t={};for(var e of[gi,mi,dr,gt]){var n=this.Oa(e);x(n)||(t[e]=n)}this.fa=t;var i=E({},t),r=this.Oa(hn);if(r)for(var s of Object.entries(r))i["$feature/"+s[0]]=s[1];this.pa=i}Aa(){var t=this.Ne.cacheTtlMs;if(!t||0>=t)return!1;var e=this.Oa(bi);return typeof e!="number"||Date.now()-e>t}$a(){return!!this.Aa()&&(this.xa||this.ya||(this.xa=!0,this.rt.warn("Feature flag cache is stale, triggering refresh..."),this.reloadFeatureFlags()),!0)}Na(){var t=this.Ne.evaluationContexts;return t!=null&&t.length?t.filter((e=>{var n=e&&typeof e=="string"&&e.trim().length>0;return n||this.rt.error("Invalid evaluation context found:",e,"Expected non-empty string"),n})):[]}qa(){var t=this.Ne.flagKeys;if(!x(t))return t.filter((e=>{var n=e&&typeof e=="string"&&e.trim().length>0;return n||this.rt.error("Invalid flag key found:",e,"Expected non-empty string"),n}))}initialize(){var t,e,n=this.Ne,i=(t=(e=n.bootstrap)==null?void 0:e.featureFlags)!==null&&t!==void 0?t:{};if(Object.keys(i).length){var r,s,o=(r=(s=n.bootstrap)==null?void 0:s.featureFlagPayloads)!==null&&r!==void 0?r:{},a=Object.keys(i).filter((u=>!!i[u])).reduce(((u,c)=>(u[c]=i[c]||!1,u)),{}),l=Object.keys(o).filter((u=>a[u])).reduce(((u,c)=>(o[c]&&(u[c]=o[c]),u)),{});return this.ja({featureFlags:a,featureFlagPayloads:l})}}updateFlags(t,e,n){var i,r,s=n!=null&&n.merge&&(i=this.Oa(hn))!==null&&i!==void 0?i:{},o=n!=null&&n.merge&&(r=this.Oa(mi))!==null&&r!==void 0?r:{},a=E({},s,t),l=E({},o,e),u={};for(var c of Object.entries(a)){var d=c[0],h=c[1];u[d]={key:d,enabled:Yl(h),variant:Jl(h),reason:void 0,metadata:x(l?.[d])?void 0:{id:0,version:void 0,description:void 0,payload:l[d]}}}this.ja({flags:u})}get hasLoadedFlags(){return this.ma}getFlags(){return Object.keys(this.getFlagVariants())}getFlagsWithDetails(){var t=this.Oa(Ko),e=this.Oa(gt),n=this.Oa(fn);if(!n&&!e)return t||{};var i=oe({},t||{}),r=[...new Set([...Object.keys(n||{}),...Object.keys(e||{})])];for(var s of r){var o,a,l=i[s],u=e?.[s],c=x(u)?(o=l?.enabled)!==null&&o!==void 0&&o:!!u,d=x(u)?l?.variant:typeof u=="string"?u:void 0,h=n?.[s],f=E({},l,{enabled:c,variant:c?d??l?.variant:void 0});c!==l?.enabled&&(f.original_enabled=l?.enabled),d!==l?.variant&&(f.original_variant=l?.variant),h&&(f.metadata=E({},l?.metadata,{payload:h,original_payload:l==null||(a=l.metadata)==null?void 0:a.payload})),i[s]=f}return this.ca||(this.rt.warn(" Overriding feature flag details!",{flagDetails:t,overriddenPayloads:n,finalDetails:i}),this.ca=!0),i}getAllFeatureFlags(){var t=this.getFlagVariants(),e=this.getFlagPayloads();return Object.keys(t).map((n=>{var i=t[n];return{key:n,enabled:Yl(i),variant:Jl(i),payload:Kl(e[n])}}))}getFlagVariants(){var t=this.Oa(hn),e=this.Oa(gt);if(!e)return t||{};for(var n=oe({},t||{}),i=Object.keys(e),r=0;i.length>r;r++)n[i[r]]=e[i[r]];return this.ca||(this.rt.warn(" Overriding feature flags!",{enabledFlags:t,overriddenFlags:e,finalFlags:n}),this.ca=!0),n}getFlagPayloads(){var t=this.Oa(mi),e=this.Oa(fn);if(!e)return t||{};for(var n=oe({},t||{}),i=Object.keys(e),r=0;i.length>r;r++)n[i[r]]=e[i[r]];return this.ca||(this.rt.warn(" Overriding feature flag payloads!",{flagPayloads:t,overriddenPayloads:e,finalPayloads:n}),this.ca=!0),n}reloadFeatureFlags(){this._a||this.Ne.featureFlagsDisabled||this.Ma()||this.Ba||(this.ga.slice().forEach((t=>{try{t()}catch(e){this.rt.error("Error while running feature flags reloading callback",e)}})),this.Ba=setTimeout((()=>{this.Ha()}),5))}La(){clearTimeout(this.Ba),this.Ba=void 0}onReloading(t){return this.ga.push(t),()=>{this.ga=this.ga.filter((e=>e!==t))}}ensureFlagsLoaded(){this.ma||this.ya||this.Ba||this.reloadFeatureFlags()}setAnonymousDistinctId(t){this.$anon_distinct_id=t}setReloadingPaused(t){this._a=t}resetFlagCallReported(){this.q(mn)}Ha(t){this.La();var e=this.nn;if(e&&!this.Ne.remoteRequestsDisabled&&!this.Ma())if(this.ya)this.wa=!0;else{var n={token:e.projectToken,distinct_id:e.distinctId,groups:e.groups,$anon_distinct_id:this.$anon_distinct_id,person_properties:E({},e.initialPersonProperties,this.Oa(Pt)||{},{$lib:e.library.name,$lib_version:e.library.version}),group_properties:this.Oa(pn),timezone:Qd()};x(e.deviceId)||(n.$device_id=e.deviceId),(t!=null&&t.disableFlags||this.Ne.featureFlagsDisabled)&&(n.disable_flags=!0);var i=this.Na();i.length&&(n.evaluation_contexts=i);var r=this.qa();x(r)||(n.flag_keys=r);var s=this.Ne.onlyEvaluateSurveyFeatureFlags,o="/flags/?v=2"+(s?"&only_evaluate_survey_feature_flags=true":""),a=this.ba;this.ya=!0;var l=()=>{this.wa&&(this.wa=!1,this.Ha())},u=c=>{this.ya=!1,a===this.ba&&(this.F({[pr]:[Xc]}),this.rt.error("Feature flag request failed",c)),l()};try{e.sendRequest(o,{target:"flags",method:"POST",body:n,compression:this.Ne.compression==="base64"?Oe.Base64:void 0,sentAt:"body",timeoutMs:this.Ne.requestTimeoutMs}).then((c=>{var d,h,f=(d=c.json)!==null&&d!==void 0?d:{},p=c.statusCode!==200;if(this.ya=!1,a===this.ba){if(this.Ua(c.statusCode),p||this.wa||(this.$anon_distinct_id=void 0),!n.disable_flags||this.wa){this.ka=!p;var g=[];c.error?g.push(c.error instanceof Error&&c.error.name==="AbortError"?"timeout":c.error instanceof Error?Xc:"unknown_error"):c.statusCode!==200&&g.push("api_error_"+c.statusCode),f.errorsWhileComputingFlags&&g.push("errors_while_computing_flags");var m=!((h=f.quotaLimited)==null||!h.includes("feature_flags"));m&&g.push("quota_limited"),this.F({[pr]:g}),m?this.rt.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."):n.disable_flags||this.ja(f,p,{partialResponse:s}),l()}}else l()})).catch(u)}catch(c){u(c)}}}Ma(){return zd(this.Sa,3)}Ua(t){this.Sa=Vd(t,this.Sa,3,(()=>this.rt.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===void 0&&(e={}),!e.fresh||this.ka)if(this.ma||this.getFlags()&&this.getFlags().length>0){if(!this.$a()){var i=this.getFeatureFlagResult(t,e);return(n=i?.variant)!==null&&n!==void 0?n:i?.enabled}}else this.rt.warn('getFeatureFlag for key "'+t+Io)}getFeatureFlagDetails(t){return this.getFlagsWithDetails()[t]}getFeatureFlagPayload(t){var e=this.getFeatureFlagResult(t,{send_event:!1});return e?.payload}getFeatureFlagResult(t,e){if(e===void 0&&(e={}),!e.fresh||this.ka)if(this.ma||this.getFlags()&&this.getFlags().length>0){if(!this.$a()){var n,i=this.getFlagVariants(),r=t in i,s=i[t],o=this.getFlagPayloads()[t],a=String(s),l=this.Oa(dr)||void 0,u=this.Oa(bi)||void 0,c=this.Oa(mn)||{};if(this.Ne.deduplicateCallsPerSession){var d,h=(d=this.nn)==null?void 0:d.session.sessionId,f=this.Oa(_i);h&&h!==f&&(c={},n=h)}if(e.send_event||!("send_event"in e))if(t in c&&c[t].includes(a))n&&this.F({[mn]:c,[_i]:n});else{var p,g,m,v,w,b,I,A,P,O;D(c[t])?c[t].push(a):c[t]=[a],this.F(E({[mn]:c},n?{[_i]:n}:{}));var S=this.getFeatureFlagDetails(t),F=[...(p=this.Oa(pr))!==null&&p!==void 0?p:[]];x(s)&&F.push("flag_missing");var R={$feature_flag:t,$feature_flag_response:s,$feature_flag_payload:o||null,$feature_flag_request_id:l,$feature_flag_evaluated_at:u,$feature_flag_bootstrapped_response:((g=this.Ne.bootstrap)==null||(g=g.featureFlags)==null?void 0:g[t])||null,$feature_flag_bootstrapped_payload:((m=this.Ne.bootstrap)==null||(m=m.featureFlagPayloads)==null?void 0:m[t])||null,$used_bootstrap_value:!this.ka};x(S==null||(v=S.metadata)==null?void 0:v.has_experiment)||(R.$feature_flag_has_experiment=S.metadata.has_experiment),x(S==null||(w=S.metadata)==null?void 0:w.version)||(R.$feature_flag_version=S.metadata.version);var M,$=(b=S==null||(I=S.reason)==null?void 0:I.description)!==null&&b!==void 0?b:S==null||(A=S.reason)==null?void 0:A.code;$&&(R.$feature_flag_reason=$),S!=null&&(P=S.metadata)!=null&&P.id&&(R.$feature_flag_id=S.metadata.id),x(S?.original_variant)&&x(S?.original_enabled)||(R.$feature_flag_original_response=x(S.original_variant)?S.original_enabled:S.original_variant),S!=null&&(O=S.metadata)!=null&&O.original_payload&&(R.$feature_flag_original_payload=S==null||(M=S.metadata)==null?void 0:M.original_payload),F.length&&(R.$feature_flag_error=F.join(",")),this.za(R)}else n&&this.F({[mn]:c,[_i]:n});if(r)return{key:t,enabled:!!s,variant:typeof s=="string"?s:void 0,payload:Kl(o)}}}else this.rt.warn('getFeatureFlagResult for key "'+t+Io)}za(t){try{var e;(e=this.nn)==null||e.capture("$feature_flag_called",t).catch((n=>{this.rt.error("Failed to capture feature flag call",n)}))}catch(n){this.rt.error("Failed to capture feature flag call",n)}}getRemoteConfigPayload(t,e){this.Wa(t,e)}Wa(t,e){var n=this;return ne((function*(){var i=n.nn;if(i){var r={distinct_id:i.distinctId,token:i.projectToken,person_properties:{$lib:i.library.name,$lib_version:i.library.version}},s=n.Na();s.length&&(r.evaluation_contexts=s);var o,a=n.qa();x(a)||(r.flag_keys=a);try{var l,u=(l=(yield i.sendRequest("/flags/?v=2",{target:"flags",method:"POST",body:r,compression:n.Ne.compression==="base64"?Oe.Base64:void 0,sentAt:"body",timeoutMs:n.Ne.requestTimeoutMs})).json)==null?void 0:l.featureFlagPayloads;o=u?.[t]||void 0}catch(c){return void n.rt.error("Remote config feature flag request failed",c)}try{e(o)}catch(c){n.rt.error("Remote config feature flag callback failed",c)}}}))()}isFeatureEnabled(t,e){if(e===void 0&&(e={}),e.fresh&&!this.ka)return e.defaultValue;if(!(this.ma||this.getFlags()&&this.getFlags().length>0))return this.rt.warn('isFeatureEnabled for key "'+t+Io),e.defaultValue;var n=this.getFeatureFlag(t,e);return x(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.ja(t,e,n)}ja(t,e,n){if(this.nn){this.ma=!0;var i=(function(r,s,o,a,l,u){s===void 0&&(s={}),o===void 0&&(o={}),a===void 0&&(a={}),u===void 0&&(u=Zc);var c=((P,O)=>{var S=P.flags;return S?E({},P,{featureFlags:Object.fromEntries(Object.keys(S).map((F=>{var R;return[F,(R=S[F].variant)!==null&&R!==void 0?R:S[F].enabled]}))),featureFlagPayloads:Object.fromEntries(Object.keys(S).filter((F=>S[F].enabled)).filter((F=>{var R;return(R=S[F].metadata)==null?void 0:R.payload})).map((F=>{var R;return[F,(R=S[F].metadata)==null?void 0:R.payload]})))}):(P.featureFlags&&O.warn("Using an older version of the feature flags endpoint. Please upgrade your PostHog server to the latest version"),P)})(r,u),d=c.flags,h=c.featureFlags,f=c.featureFlagPayloads;if(h){var p=r.requestId,g=r.evaluatedAt;if(D(h)){u.warn("v1 of the feature flags endpoint is deprecated. Please use the latest version.");var m={};if(h)for(var v=0;h.length>v;v++)m[h[v]]=!0;return{[gi]:h,[hn]:m,[Mr]:!1}}var w=h,b=f,I=d;if(l!=null&&l.partialResponse)w=E({},s,w),b=E({},o,b),I=E({},a,I);else if(r.errorsWhileComputingFlags)if(d){var A=new Set(Object.keys(d).filter((P=>{var O;return!((O=d[P])!=null&&O.failed)})));w=E({},s,Object.fromEntries(Object.entries(w).filter((P=>A.has(P[0]))))),b=E({},o,Object.fromEntries(Object.entries(b||{}).filter((P=>A.has(P[0]))))),I=E({},a,Object.fromEntries(Object.entries(I||{}).filter((P=>A.has(P[0])))))}else w=E({},s,w),b=E({},o,b),I=E({},a,I);return E({[gi]:Object.keys(eu(w)),[hn]:w||{},[mi]:b||{},[Ko]:I||{},[Mr]:r.minimalFlagCalledEvents===!0},p?{[dr]:p}:{},g?{[bi]:g}:{})}})(t,this.getFlagVariants(),this.getFlagPayloads(),this.getFlagsWithDetails(),n,this.rt);i&&this.F(i),e||(this.xa=!1),this.Va(e)}}override(t,e){e===void 0&&(e=!1),this.rt.warn("override is deprecated. Please use overrideFeatureFlags instead."),this.overrideFeatureFlags({flags:t,suppressWarning:e})}overrideFeatureFlags(t){this.Za(t)}Za(t){if(this.nn){if(t===!1)return this.q([gt,fn]),this.Va(),void un.info("All overrides cleared");if(D(t))return this.F({[gt]:Qc(t)}),this.Va(),void un.info("Flag overrides set",{flags:t});if(t&&typeof t=="object"&&("flags"in t||"payloads"in t)){var e,n=t;this.ca=!!((e=n.suppressWarning)!==null&&e!==void 0&&e);var i={},r=n.flags,s=n.payloads;return r&&(i[gt]=D(r)?Qc(r):r),s&&(i[fn]=s),Object.keys(i).length&&this.F(i),r===!1&&s===!1?this.q([gt,fn]):r===!1?this.q(gt):s===!1&&this.q(fn),this.Va(),r===!1?un.info("Flag overrides cleared"):r&&un.info("Flag overrides set",{flags:r}),void(s===!1?un.info("Payload overrides cleared"):s&&un.info("Payload overrides set",{payloads:s}))}if(t&&typeof t=="object")return this.F({[gt]:t}),this.Va(),void un.info("Flag overrides set",{flags:t});this.rt.warn("Invalid overrideOptions provided to overrideFeatureFlags",{overrideOptions:t})}else this.rt.warn("posthog.featureFlags.overrideFeatureFlags called before feature flags were ready")}onFeatureFlags(t){if(this.addFeatureFlagsHandler(t),this.ma){var e=this.Ga(),n=e.flags,i=e.flagVariants;try{t(n,i)}catch(r){this.rt.error("Error while running feature flags callback",r)}}return()=>this.removeFeatureFlagsHandler(t)}updateEarlyAccessFeatureEnrollment(t,e,n){var i=(this.Oa(ur)||[]).find((l=>l.flagKey===t)),r={["$feature_enrollment/"+t]:e},s={$feature_flag:t,$feature_enrollment:e,$set:r};i&&(s.$early_access_feature_name=i.name),n&&(s.$feature_enrollment_stage=n);var o=E({},this.getFlagVariants(),{[t]:e});this.F({[gi]:Object.keys(eu(o)),[hn]:o,[Pt]:E({},this.Oa(Pt)||{},r)}),this.Va();try{var a;(a=this.nn)==null||a.capture("$feature_enrollment_update",s).catch((l=>{this.rt.error("Failed to capture early access feature enrollment",l)}))}catch(l){this.rt.error("Failed to capture early access feature enrollment",l)}}getEarlyAccessFeatures(t,e,n){e===void 0&&(e=!1);var i=this.Oa(ur);!i||e?this.Qa(t,n):t(i)}Qa(t,e){var n=this;return ne((function*(){var i=n.nn;if(i){var r,s=e?"&"+e.map((a=>"stage="+a)).join("&"):"";try{var o=yield i.sendRequest("/api/early_access_features/?token="+i.projectToken+s,{target:"api",method:"GET",sentAt:"query"});if(!o.json)return;n.F({[ur]:r=o.json.earlyAccessFeatures})}catch(a){return void n.rt.error("Early access feature request failed",a)}try{t(r)}catch(a){n.rt.error("Early access feature callback failed",a)}}}))()}Ga(){var t=this.getFlags(),e=this.getFlagVariants();return{flags:t.filter((n=>e[n])),flagVariants:Object.keys(e).filter((n=>e[n])).reduce(((n,i)=>(n[i]=e[i],n)),{})}}Va(t){this.Fa();var e=this.Ga(),n=e.flags,i=e.flagVariants;this.featureFlagEventHandlers.forEach((r=>{try{r(n,i,{errorsLoading:t})}catch(s){this.rt.error("Error while running feature flags callback",s)}}))}setPersonPropertiesForFlags(t,e){e===void 0&&(e=!0),this.Ka(t,e)}Ka(t,e){e===void 0&&(e=!0);var n=this.Oa(Pt)||{},i=t?.$set||(t!=null&&t.$set_once?{}:t),r=t?.$set_once,s={};if(r)for(var o in r)({}).hasOwnProperty.call(r,o)&&(o in n||(s[o]=r[o]));this.F({[Pt]:E({},n,s,i)}),e&&this.reloadFeatureFlags()}unsetPersonPropertiesForFlags(t,e){e===void 0&&(e=!0);var n=E({},this.Oa(Pt)||{});t.forEach((i=>{delete n[i]})),this.F({[Pt]:n}),e&&this.reloadFeatureFlags()}resetPersonPropertiesForFlags(t){t===void 0&&(t=!0),this.q(Pt),t&&this.reloadFeatureFlags()}setGroupPropertiesForFlags(t,e){e===void 0&&(e=!0);var n=this.Oa(pn)||{},i=E({},n);for(var r of Object.keys(t))i[r]=E({},n[r],t[r]);this.F({[pn]:i}),e&&this.reloadFeatureFlags()}resetGroupPropertiesForFlags(t){if(t){var e=this.Oa(pn)||{};this.F({[pn]:E({},e,{[t]:{}})})}else this.q(pn)}reset(){this.ba++,this.wa=!1,this.Fa(),this.ma=!1,this._a=!1,this.ka=!1,this.$anon_distinct_id=void 0,this.La(),this.ca=!1,this.Sa=0}}},Jg={sessionRecording:class{get Ne(){return this._instance.config}get Mr(){return this._instance.persistence}get started(){var t;return!((t=this.Ja)==null||!t.isStarted)}get status(){var t,e;return this.Ya===ui||this.Ya===ir?this.Ya:(t=(e=this.Ja)==null?void 0:e.status)!==null&&t!==void 0?t:this.Ya}constructor(t){if(this._forceAllowLocalhostNetworkCapture=!1,this.Ya=qc,this.Xa=void 0,this.eo=!1,this.io=(()=>{var e;if(C==null||!C.visibilityState||C.visibilityState==="visible")return!0;var n=_==null||(e=_.performance)==null||e.getEntriesByType==null?void 0:e.getEntriesByType("visibility-state");return!(n!=null&&n.length)||n.some((i=>i.name==="visible"))})(),this.Ie=()=>{var e;C?.visibilityState==="visible"&&(this.io=!0,(e=this.Ja)==null||e.setDocumentWasEverVisible==null||e.setDocumentWasEverVisible(!0))},this._instance=t,!this._instance.sessionManager)throw Ct.error("started without valid sessionManager"),new Error(ha+" started without valid sessionManager. This is a bug.");if(this.Ne.cookieless_mode===Tt)throw new Error(ha+' cannot be used with cookieless_mode="always"');C!=null&&C.addEventListener&&de(C,"visibilitychange",this.Ie)}initialize(){this.startIfEnabledOrStop()}dispose(){this.eo=!0,C==null||C.removeEventListener==null||C.removeEventListener("visibilitychange",this.Ie),this.stopRecording()}get ro(){var t,e=!((t=this._instance.get_property(vn))==null||!t.enabled),n=!this.Ne.disable_session_recording,i=this.Ne.disable_session_recording||this._instance.consent.isOptedOut();return _&&e&&n&&!i}startIfEnabledOrStop(t){var e;if(!(this.eo||this.ro&&(e=this.Ja)!=null&&e.isStarted)){var n=!x(Object.assign)&&!x(Array.from);this.ro&&n?(this.no(t),Ct.info("starting")):(this.Ya=qc,this.stopRecording())}}no(t){var e,n,i;this.ro&&(this.Ya!==ui&&this.Ya!==ir&&(this.Ya=zc),T!=null&&(e=T.__PosthogExtensions__)!=null&&(e=e.rrweb)!=null&&e.record&&(n=T.__PosthogExtensions__)!=null&&n.initSessionRecording?this.so(t):(i=T.__PosthogExtensions__)==null||i.loadExternalDependency==null||i.loadExternalDependency(this._instance,this.ao,(r=>{if(r)return Ct.error("could not load recorder",r);this.so(t)})))}stopRecording(){var t,e;(t=this.Xa)==null||t.call(this),this.Xa=void 0,(e=this.Ja)==null||e.stop()}oo(){var t,e;(t=this.Xa)==null||t.call(this),this.Xa=void 0,(e=this.Ja)==null||e.discard()}lo(){var t,e;(t=this.Mr)==null||t.unregister(za),(e=this.Mr)==null||e.unregister(bd)}uo(t,e){if(j(t))return null;var n,i=Se(t)?t:parseFloat(t);return typeof(n=i)!="number"||!Number.isFinite(n)||0>n||n>1?(Ct.warn(e+" must be between 0 and 1. Ignoring invalid value:",t),null):i}ho(t){if(this.Mr){var e,n,i=this.Mr,r=()=>{var s,o=t.sessionRecording===!1?void 0:t.sessionRecording,a=this.uo((s=this.Ne.session_recording)==null?void 0:s.sampleRate,"session_recording.sampleRate"),l=this.uo(o?.sampleRate,"remote config sampleRate"),u=a??l;j(u)&&this.lo();var c=o?.minimumDurationMilliseconds;i.register({[vn]:E({cache_timestamp:Date.now(),enabled:!!o},o,{networkPayloadCapture:E({capturePerformance:t.capturePerformance},o?.networkPayloadCapture),canvasRecording:{enabled:o?.recordCanvas,fps:o?.canvasFps,quality:o?.canvasQuality},sampleRate:u,minimumDurationMilliseconds:x(c)?null:c,endpoint:o?.endpoint,triggerMatchType:o?.triggerMatchType,masking:o?.masking,urlTriggers:o?.urlTriggers,version:o?.version,triggerGroups:o?.triggerGroups})})};r(),(e=this.Xa)==null||e.call(this),this.Xa=(n=this._instance.sessionManager)==null?void 0:n.onSessionId(r)}}onRemoteConfig(t){var e=t.ok?t.config:void 0;return e&&"sessionRecording"in e?e.sessionRecording===!1?(this.ho(e),void this.oo()):(this.ho(e),void this.startIfEnabledOrStop()):(this.Ya===ui&&(this.Ya=ir,Ct.warn("config refresh failed, recording will not start until page reload")),void this.startIfEnabledOrStop())}log(t,e){var n;e===void 0&&(e="log"),(n=this.Ja)!=null&&n.log?this.Ja.log(t,e):Ct.warn("log called before recorder was ready")}get ao(){var t,e,n=(t=this._instance)==null||(t=t.persistence)==null?void 0:t.get_property(vn);return(n==null||(e=n.scriptConfig)==null?void 0:e.script)||"lazy-recorder"}do(){var t,e=this._instance.get_property(vn);if(!e)return!1;try{t=typeof e=="object"?e:JSON.parse(e)}catch(n){return Ct.warn("persisted remote config for session recording is invalid and will be ignored",n),!1}return!j(t.cache_timestamp)&&36e5>=Date.now()-t.cache_timestamp}so(t){var e,n,i;if(!this.eo){if((e=T.__PosthogExtensions__)==null||!e.initSessionRecording)return Ct.warn("Called on script loaded before session recording is available. This can be caused by adblockers."),void this._instance.register_for_session({[Pd]:!0});var r;if(this.Ja||(this.Ja=(r=T.__PosthogExtensions__)==null?void 0:r.initSessionRecording(this._instance,this.io),this.Ja._forceAllowLocalhostNetworkCapture=this._forceAllowLocalhostNetworkCapture),!this.do())return this.Ya===ir||this.Ya===ui?void 0:(this.Ya=ui,Ct.info("persisted remote config is stale, requesting fresh config before starting"),void new eh(this._instance).load());this.Ya=zc,(n=(i=this.Ja).setDocumentWasEverVisible)==null||n.call(i,this.io),this.Ja.start(t)}}onRRwebEmit(t){var e;(e=this.Ja)==null||e.onRRwebEmit==null||e.onRRwebEmit(t)}overrideLinkedFlag(){var t,e;this.Ja||(e=this.Mr)==null||e.register({[Sd]:!0}),(t=this.Ja)==null||t.overrideLinkedFlag()}overrideSampling(){var t,e;this.Ja||(e=this.Mr)==null||e.register({[Ed]:!0}),(t=this.Ja)==null||t.overrideSampling()}overrideTrigger(t){var e,n;this.Ja||(n=this.Mr)==null||n.register({[t==="url"?xd:kd]:!0}),(e=this.Ja)==null||e.overrideTrigger(t)}get sdkDebugProperties(){var t;return((t=this.Ja)==null?void 0:t.sdkDebugProperties)||{$recording_status:this.status}}tryAddCustomEvent(t,e){var n;return!((n=this.Ja)==null||!n.tryAddCustomEvent(t,e))}}},Zg={autocapture:class{constructor(t){this.vo=!1,this.co=null,this.fo=!1,this.po=!1,this.instance=t,this.rageclicks=new Uc(t.config.rageclick),this.mo=null}initialize(){this.startIfEnabled()}get Ne(){var t,e,n=ae(this.instance.config.autocapture)?this.instance.config.autocapture:{};return n.url_allowlist=(t=n.url_allowlist)==null?void 0:t.map((i=>new RegExp(i))),n.url_ignorelist=(e=n.url_ignorelist)==null?void 0:e.map((i=>new RegExp(i))),n}yo(){if(this.isBrowserSupported()){if(_&&C){var t=n=>{n=n||_?.event;try{this.bo(n)}catch(i){Eo.error("Failed to capture event",i)}};if(de(C,"submit",t,{capture:!0}),de(C,"change",t,{capture:!0}),de(C,"click",t,{capture:!0}),this.Ne.capture_copied_text){var e=n=>{n=n||_?.event;try{this.bo(n,bo)}catch(i){Eo.error("Failed to capture copy/cut event",i)}};de(C,"copy",e,{capture:!0}),de(C,"cut",e,{capture:!0})}}}else Eo.info("Disabling Automatic Event Collection because this browser is not supported")}startIfEnabled(){this.isEnabled&&!this.vo&&(this.yo(),this.vo=!0)}onRemoteConfig(t){if(this.fo=!0,t.ok){var e=t.config;e.elementsChainAsString&&(this.po=e.elementsChainAsString);var n=e.autocapture_opt_out;at(n)&&(this.instance.persistence&&this.instance.persistence.register({[Uo]:n}),this.co=n),this.startIfEnabled()}else this.startIfEnabled()}setElementSelectors(t){this.mo=t}getElementSelectors(t){var e,n=[];return(e=this.mo)==null||e.forEach((i=>{var r=C?.querySelectorAll(i);r?.forEach((s=>{t===s&&n.push(i)}))})),n}get isEnabled(){var t,e,n=(t=this.instance.persistence)==null?void 0:t.props[Uo],i=this.co,r=this.instance.Qi()&&!this.fo;if(We(i)&&!at(n)&&!r)return!1;var s=(e=this.co)!==null&&e!==void 0?e:!!n;return!!this.instance.config.autocapture&&!s}bo(t,e){if(e===void 0&&(e="$autocapture"),this.isEnabled){var n,i=lo(t);Md(i)&&(i=i.parentNode||null),e==="$autocapture"&&t.type==="click"&&t instanceof MouseEvent&&this.instance.config.rageclick&&(n=this.rageclicks)!=null&&n.isRageClick(t.clientX,t.clientY,t.timeStamp||new Date().getTime())&&vc(i,this.instance.config.rageclick)&&this.bo(t,"$rageclick");var r=e===bo;if(i&&(function(d,h,f,p,g,m){var v;if(!_||Ja(d)||f!=null&&f.url_allowlist&&!pc(f.url_allowlist,m)||f!=null&&f.url_ignorelist&&pc(f.url_ignorelist,m))return!1;if(f!=null&&f.dom_event_allowlist){var w=f.dom_event_allowlist;if(w&&!w.some((S=>h.type===S)))return!1}var b=jd(d,p),I=b.parentIsUsefulElement,A=b.targetElementList;if(!(function(S,F){var R=F?.element_allowlist;if(x(R))return!0;var M,$=function(Y){if(R.some((V=>Y.tagName.toLowerCase()===V)))return{v:!0}};for(var N of S)if(M=$(N))return M.v;return!1})(A,f)||!ia(A,f?.css_selector_allowlist)||ia(A,(v=f?.css_selector_ignorelist)!==null&&v!==void 0?v:Kp))return!1;try{var P=_.getComputedStyle(d);if(P&&P.getPropertyValue("cursor")==="pointer"&&h.type==="click")return!0}catch{}var O=d.tagName.toLowerCase();switch(O){case"html":return!1;case"form":return(g||["submit"]).indexOf(h.type)>=0;case"input":case"select":case"textarea":return(g||["change","click"]).indexOf(h.type)>=0;default:return I?(g||["click"]).indexOf(h.type)>=0:(g||["click"]).indexOf(h.type)>=0&&(Ya.indexOf(O)>-1||d.getAttribute("contenteditable")==="true")}})(i,t,this.Ne,r,r?["copy","cut"]:void 0,this.instance)){var s=jg(i,{e:t,maskAllElementAttributes:this.instance.config.mask_all_element_attributes,maskAllText:this.instance.config.mask_all_text,elementAttributeIgnoreList:this.Ne.element_attribute_ignorelist,elementsChainAsString:this.po,disableCaptureUrlHashes:this.instance.config.disable_capture_url_hashes}),o=s.props;if(s.explicitNoCapture)return!1;var a=this.getElementSelectors(i);if(a&&a.length>0&&(o.$element_selectors=a),e===bo){var l,u=Od(_==null||(l=_.getSelection())==null?void 0:l.toString()),c=t.type||"clipboard";if(!u)return!1;o.$selected_content=u,o.$copy_type=c}return this.instance.capture(e,o),!0}}}isBrowserSupported(){return Ne(C?.querySelectorAll)}},historyAutocapture:class{constructor(t){var e;this._instance=t,this._o=(_==null||(e=_.location)==null?void 0:e.pathname)||""}initialize(){this.startIfEnabled()}get isEnabled(){return this._instance.config.capture_pageview==="history_change"}startIfEnabled(){this.isEnabled&&(k.info("History API monitoring enabled, starting..."),this.monitorHistoryChanges())}stop(){this.wo&&this.wo(),this.wo=void 0,k.info("History API monitoring stopped")}monitorHistoryChanges(){_&&_.history&&(this.ko("pushState"),this.ko("replaceState"),this.xo())}ko(t){var e;if(_&&((e=_.history[t])==null||!e.__posthog_wrapped__)){var n=this;(function(i,r,s){try{if(!(r in i))return Hc;var o={next:i[r]},a=s((function(){for(var l=arguments.length,u=new Array(l),c=0;l>c;c++)u[c]=arguments[c];return o.next.apply(this,u)}));return Ne(a)&&(a.prototype=a.prototype||{},Object.defineProperties(a,{__posthog_wrapped__:{enumerable:!1,value:!0},__posthog_layer__:{enumerable:!1,value:o}})),i[r]=a,()=>{if(i[r]!==a)for(var l=i[r];Ne(l)&&l.__posthog_layer__;){var u=l.__posthog_layer__;if(u.next===a)return void(u.next=o.next);l=u.next}else i[r]=o.next}}catch{return Hc}})(_.history,t,(i=>function(r,s,o){i.call(this,r,s,o),n.So(t)}))}}So(t){try{var e,n=_==null||(e=_.location)==null?void 0:e.pathname;if(!n)return;n!==this._o&&this.isEnabled&&this._instance.capture($n,{navigation_type:t}),this._o=n}catch(i){k.error("Error capturing "+t+" pageview",i)}}xo(){if(!this.wo){var t=()=>{this.So("popstate")};de(_,"popstate",t),this.wo=()=>{_&&_.removeEventListener("popstate",t)}}}},heatmaps:class{get Ne(){return this.instance.config}constructor(t){var e;this.Co=!1,this.vo=!1,this.Mo=null,this.instance=t,this.Co=!((e=this.instance.persistence)==null||!e.props[Ho]),this.rageclicks=new Uc(t.config.rageclick)}initialize(){this.startIfEnabled()}get flushIntervalMilliseconds(){var t=5e3;return ae(this.Ne.capture_heatmaps)&&this.Ne.capture_heatmaps.flush_interval_milliseconds&&(t=this.Ne.capture_heatmaps.flush_interval_milliseconds),t}get isEnabled(){return j(this.Ne.capture_heatmaps)?j(this.Ne.enable_heatmaps)?this.Co:this.Ne.enable_heatmaps:this.Ne.capture_heatmaps!==!1}startIfEnabled(){if(this.isEnabled){if(this.vo)return;Hg.info("starting..."),this.To(),this.Ie()}else{var t;clearInterval((t=this.Mo)!==null&&t!==void 0?t:void 0),this.Eo(),this.getAndClearBuffer()}}onRemoteConfig(t){if(t.ok){var e=t.config;if("heatmaps"in e){var n=!!e.heatmaps;this.instance.persistence&&this.instance.persistence.register({[Ho]:n}),this.Co=n,this.startIfEnabled()}}}getAndClearBuffer(){var t=this.R;return this.R=void 0,t}Io(t){xo(t.originalEvent)&&this.ke(t.originalEvent,"deadclick")}Ie(){this.Mo&&clearInterval(this.Mo),this.Mo=C?.visibilityState==="visible"?setInterval(this.cr.bind(this),this.flushIntervalMilliseconds):null}To(){_&&C&&(this.Po=this.cr.bind(this),de(_,Dr,this.Po),this.Ro=t=>this.ke(t||_?.event),de(C,"click",this.Ro,{capture:!0}),this.Ao=t=>this.Fo(t||_?.event),de(C,"mousemove",this.Ao,{capture:!0}),this.Lo=new xc(this.instance,tg,this.Io.bind(this)),this.Lo.startIfEnabledOrStop(),this.Oo=this.Ie.bind(this),de(C,Br,this.Oo),this.vo=!0)}Eo(){var t;_&&C&&(this.Po&&_.removeEventListener(Dr,this.Po),this.Ro&&C.removeEventListener("click",this.Ro,{capture:!0}),this.Ao&&C.removeEventListener("mousemove",this.Ao,{capture:!0}),this.Oo&&C.removeEventListener(Br,this.Oo),clearTimeout(this.Do),(t=this.Lo)==null||t.stop(),this.vo=!1)}$o(t,e){var n=this.instance.scrollManager.scrollY(),i=this.instance.scrollManager.scrollX(),r=this.instance.scrollManager.scrollElement(),s=(function(o,a,l){for(var u=o;u&&en(u)&&!Ge(u,"body");){if(u===l)return!1;var c=void 0;try{var d,h,f;c=(d=(h=(f=u.ownerDocument)==null?void 0:f.defaultView)!==null&&h!==void 0?h:_)==null?void 0:d.getComputedStyle(u).position}catch{return!1}if(B(a,c))return!0;u=Bd(u)}return!1})(lo(t),["fixed","sticky"],r);return{x:t.clientX+(s?0:i),y:t.clientY+(s?0:n),target_fixed:s,type:e}}ke(t,e){var n;if(e===void 0&&(e="click"),!fc(t.target)&&xo(t)){var i=this.$o(t,e);(n=this.rageclicks)!=null&&n.isRageClick(t.clientX,t.clientY,new Date().getTime())&&vc(lo(t),this.instance.config.rageclick)&&this.Vt(E({},i,{type:"rageclick"})),this.Vt(i)}}Fo(t){!fc(t.target)&&xo(t)&&(clearTimeout(this.Do),this.Do=setTimeout((()=>{this.Vt(this.$o(t,"mousemove"))}),500))}Vt(t){if(_){var e=this.Ne.disable_capture_url_hashes?Qt(_.location.href):_.location.href,n=this.Ne.custom_personal_data_properties,i=this.Ne.mask_personal_data_properties?[...zn,...n||[]]:[],r=Ti(e,i,$i);this.R=this.R||{},this.R[r]||(this.R[r]=[]),this.R[r].push(t)}}cr(){this.R&&!Nt(this.R)&&this.instance.capture("$$heatmap",{$heatmap_data:this.getAndClearBuffer()})}},deadClicksAutocapture:xc,webVitalsAutocapture:class{constructor(t){var e;this.Co=!1,this.vo=!1,this.R={navigationKey:void 0,url:void 0,metrics:[],firstMetricTimestamp:void 0},this.No=()=>{clearTimeout(this.qo),this.qo=void 0,this.R.metrics.length!==0&&(this._instance.capture("$web_vitals",E({$current_url:this.R.url},this.R.metrics.reduce(((n,i)=>E({},n,{["$web_vitals_"+i.name+"_event"]:E({},i),["$web_vitals_"+i.name+"_value"]:i.value})),{}))),this.R={navigationKey:void 0,url:void 0,metrics:[],firstMetricTimestamp:void 0})},this.jo=n=>{var i;if(this.R=this.R||{navigationKey:void 0,url:void 0,metrics:[],firstMetricTimestamp:void 0},j(n?.name)||j(n?.value))cn.error("Invalid metric received",n);else{var r=typeof n.navigationURL=="string"?n.navigationURL:void 0,s=this.Bo(r);if(!x(s)){var o=Se(n.navigationId)||typeof n.navigationId=="string"?"navigation:"+n.navigationId:"url:"+s;if(!this.Ho||this.Ho>n.value){this.R.navigationKey!==o&&(this.No(),this.qo=setTimeout(this.No,this.flushToCaptureTimeoutMs)),x(this.R.navigationKey)&&(this.R.navigationKey=o,this.R.url=s),this.R.firstMetricTimestamp=x(this.R.firstMetricTimestamp)?Date.now():this.R.firstMetricTimestamp,n.attribution&&n.attribution.interactionTargetElement&&(n.attribution.interactionTargetElement=void 0);var a=(i=this._instance.sessionManager)==null?void 0:i.checkAndGetSessionAndWindowId(!0),l=E({},n,r?{navigationURL:s}:{},{$current_url:s,timestamp:Date.now()});x(a)||(l.$session_id=a.sessionId,l.$window_id=a.windowId),this.R.metrics.push(l),this.R.metrics.length===this.allowedMetrics.length&&this.No()}else cn.error("Ignoring metric with value >= "+this.Ho,n)}}},this.Uo=()=>{if(!this.vo){var n,i,r,s,o=T.__PosthogExtensions__,a=o?.postHogWebVitalsCallbacksByFlavor,l=a?.[this.zo]||(this.zo==="web-vitals"&&x(a)?o?.postHogWebVitalsCallbacks:void 0);if(x(l)||(n=l.onLCP,i=l.onCLS,r=l.onFCP,s=l.onINP),n&&i&&r&&s){var u={reportSoftNavs:this.useSoftNavs};this.allowedMetrics.indexOf("LCP")>-1&&n(this.jo.bind(this),u),this.allowedMetrics.indexOf("CLS")>-1&&i(this.jo.bind(this),u),this.allowedMetrics.indexOf("FCP")>-1&&r(this.jo.bind(this),u),this.allowedMetrics.indexOf("INP")>-1&&s(this.jo.bind(this),u),this.vo=!0}else cn.error("web vitals callbacks not loaded - not starting")}},this._instance=t,this.Co=!((e=this._instance.persistence)==null||!e.props[Vo]),this.startIfEnabled()}get Wo(){return this._instance.config.capture_performance}get allowedMetrics(){var t,e,n=ae(this.Wo)?(t=this.Wo)==null?void 0:t.web_vitals_allowed_metrics:void 0;return j(n)?((e=this._instance.persistence)==null?void 0:e.props[Go])||["CLS","FCP","INP","LCP"]:n}get flushToCaptureTimeoutMs(){return(ae(this.Wo)?this.Wo.web_vitals_delayed_flush_ms:void 0)||5e3}get useAttribution(){var t=ae(this.Wo)?this.Wo.web_vitals_attribution:void 0;return t!=null&&t}get useSoftNavs(){var t=ae(this.Wo)?this.Wo.__preview_web_vitals_soft_navs:void 0;return t!=null&&t}get Ho(){var t=ae(this.Wo)&&Se(this.Wo.__web_vitals_max_value)?this.Wo.__web_vitals_max_value:Wc;return t>0&&6e4>=t?Wc:t}get isEnabled(){var t=ue?.protocol;if(t!=="http:"&&t!=="https:")return cn.info("Web Vitals are disabled on non-http/https protocols"),!1;var e=ae(this.Wo)?this.Wo.web_vitals:at(this.Wo)?this.Wo:void 0;return at(e)?e:this.Co}startIfEnabled(){this.isEnabled&&!this.vo&&(cn.info("enabled, starting..."),this.ai(this.Uo))}onRemoteConfig(t){if(t.ok){var e=t.config;if("capturePerformance"in e){var n=ae(e.capturePerformance)&&!!e.capturePerformance.web_vitals,i=ae(e.capturePerformance)?e.capturePerformance.web_vitals_allowed_metrics:void 0;this._instance.persistence&&(this._instance.persistence.register({[Vo]:n}),this._instance.persistence.register({[Go]:i})),this.Co=n,this.startIfEnabled()}}}get zo(){return this.useSoftNavs?this.useAttribution?"web-vitals-with-attribution-soft-navs":"web-vitals-soft-navs":this.useAttribution?"web-vitals-with-attribution":"web-vitals"}ai(t){var e=T.__PosthogExtensions__,n=this.zo,i=e?.postHogWebVitalsCallbacksByFlavor;i!=null&&i[n]||n==="web-vitals"&&x(i)&&e!=null&&e.postHogWebVitalsCallbacks?t():e==null||e.loadExternalDependency==null||e.loadExternalDependency(this._instance,n,(r=>{r?cn.error("failed to load script",r):t()}))}Bo(t){var e=t||_?.location.href;if(e){var n=this._instance.config.disable_capture_url_hashes?Qt(e):e,i=this._instance.config.custom_personal_data_properties,r=this._instance.config.mask_personal_data_properties?[...zn,...i||[]]:[];return Ti(n,r,$i)}cn.error("Could not determine current URL")}}},Xg={exceptionObserver:class{constructor(t){var e;this.Uo=()=>{var n;if(_&&this.isEnabled&&(n=T.__PosthogExtensions__)!=null&&n.errorWrappingFunctions){var i=T.__PosthogExtensions__.errorWrappingFunctions.wrapOnError,r=T.__PosthogExtensions__.errorWrappingFunctions.wrapUnhandledRejection,s=T.__PosthogExtensions__.errorWrappingFunctions.wrapConsoleError;try{!this.Vo&&this.Ne.capture_unhandled_errors&&(this.Vo=i(this.captureException.bind(this))),!this.Zo&&this.Ne.capture_unhandled_rejections&&(this.Zo=r(this.captureException.bind(this))),!this.Go&&this.Ne.capture_console_errors&&(this.Go=s(this.captureException.bind(this)))}catch(o){ci.error("failed to start",o),this.Qo()}}},this._instance=t,this.Ko=!((e=this._instance.persistence)==null||!e.props[Wo]),this.Jo=new Jf(E({},(function(n){var i,r,s,o;return n===void 0&&(n={}),{refillRate:(i=(r=n.exceptionRateLimiterRefillRate)!==null&&r!==void 0?r:n.__exceptionRateLimiterRefillRate)!==null&&i!==void 0?i:1,bucketSize:(s=(o=n.exceptionRateLimiterBucketSize)!==null&&o!==void 0?o:n.__exceptionRateLimiterBucketSize)!==null&&s!==void 0?s:10}})(this._instance.config.error_tracking),{refillInterval:1e4,rt:ci})),this.Ne=this.Yo(),this.startIfEnabledOrStop()}Yo(){var t=this._instance.config.capture_exceptions,e={capture_unhandled_errors:!1,capture_unhandled_rejections:!1,capture_console_errors:!1};return ae(t)?e=E({},e,t):(x(t)?this.Ko:t)&&(e=E({},e,{capture_unhandled_errors:!0,capture_unhandled_rejections:!0})),e}get isEnabled(){return this.Ne.capture_console_errors||this.Ne.capture_unhandled_errors||this.Ne.capture_unhandled_rejections}startIfEnabledOrStop(){this.isEnabled?(ci.info("enabled"),this.Qo(),this.ai(this.Uo)):this.Qo()}ai(t){var e,n;(e=T.__PosthogExtensions__)!=null&&e.errorWrappingFunctions?t():(n=T.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,"exception-autocapture",(i=>{if(i)return ci.error("failed to load script",i);t()}))}Qo(){var t,e,n;(t=this.Vo)==null||t.call(this),this.Vo=void 0,(e=this.Zo)==null||e.call(this),this.Zo=void 0,(n=this.Go)==null||n.call(this),this.Go=void 0}onRemoteConfig(t){if(t.ok){var e=t.config;"autocaptureExceptions"in e&&(this.Ko=!!e.autocaptureExceptions||!1,this._instance.persistence&&this._instance.persistence.register({[Wo]:this.Ko}),this.Ne=this.Yo(),this.startIfEnabledOrStop())}}onConfigChange(){this.Ne=this.Yo()}captureException(t){var e,n,i,r=(e=t==null||(n=t.$exception_list)==null||(n=n[0])==null?void 0:n.type)!==null&&e!==void 0?e:"Exception";this.Jo.consumeRateLimit(r)?ci.info("Skipping exception capture because of client rate limiting.",{exception:r}):(i=this._instance.exceptions)==null||i.sendExceptionEvent(t)}},exceptions:class{constructor(t){var e,n;this.Xo=[],this.tl=new fp([new bp,new Fp,new Sp,new Ep,new Ap,new Cp,new kp,new Pp],(function(i){for(var r=arguments.length,s=new Array(r>1?r-1:0),o=1;r>o;o++)s[o-1]=arguments[o];return function(a,l){l===void 0&&(l=0);for(var u=[],c=a.split(` -`),d=l;c.length>d;d++){var h=c[d];if(1024>=h.length){var f=cc.test(h)?h.replace(cc,"$1"):h;if(!f.match(/\S*Error: /)){for(var p of s){var g=p(f,i);if(g){u.push(g);break}}if(u.length>=50)break}}}return(function(m){if(!m.length)return[];var v=Array.from(m);return v.reverse(),v.slice(0,50).map((w=>{return E({},w,{filename:w.filename||(b=v,b[b.length-1]||{}).filename,function:w.function||Wn});var b}))})(u)}})("web:javascript",vp,wp)),this._instance=t,this.Xo=(e=(n=this._instance.persistence)==null?void 0:n.get_property(qo))!==null&&e!==void 0?e:[],this.el=$r(this.il()),this.rl=new Tp(this.el)}onConfigChange(){this.el=$r(this.il()),this.rl.setConfig(this.el)}onRemoteConfig(t){var e,n,i;if(t.ok){var r=t.config;if("errorTracking"in r){var s=(e=(n=r.errorTracking)==null?void 0:n.suppressionRules)!==null&&e!==void 0?e:[],o=(i=r.errorTracking)==null?void 0:i.captureExtensionExceptions;this.Xo=s,this._instance.persistence&&this._instance.persistence.register({[qo]:this.Xo,[zo]:o})}}}get nl(){var t,e=!!this._instance.get_property(zo),n=this._instance.config.error_tracking.captureExtensionExceptions;return(t=n??e)!==null&&t!==void 0&&t}buildProperties(t,e){return this.tl.buildFromUnknown(t,{syntheticException:e?.syntheticException,mechanism:{handled:e?.handled}})}addExceptionStep(t,e){if(this.el.enabled)try{if(!K(t)||t.trim().length===0)return void ft.warn("Ignoring exception step because message must be a non-empty string");var n=(function(s){if(!s)return{sanitizedProperties:{},droppedKeys:[]};var o=[];return{sanitizedProperties:Object.keys(s).reduce(((a,l)=>Rp.has(l)?(o.push(l),a):(a[l]=s[l],a)),{}),droppedKeys:o}})(this.sl(e)),i=n.sanitizedProperties,r=n.droppedKeys;r.length>0&&ft.warn("Ignoring reserved exception step fields",{droppedKeys:r}),this.rl.add(E({[Rr]:t,[Tr]:new Date().toISOString()},i))}catch(s){ft.error("Failed to add exception step. Ignoring breadcrumb.",s)}}sendExceptionEvent(t){try{var e=t.$exception_list;if(this.al(e)){if(this.ol(e))return this.ll("Exception dropped: matched a suppression rule"),void ft.info("Skipping exception capture because a suppression rule matched");if(!this.nl&&this.ul(e))return this.ll("Exception dropped: thrown by a browser extension"),void ft.info("Skipping exception capture because it was thrown by an extension");if(!this._instance.config.error_tracking.__capturePostHogExceptions&&this.hl(e))return this.ll("Exception dropped: thrown by the PostHog SDK"),void ft.info("Skipping exception capture because it was thrown by the PostHog SDK")}var n=this.el.enabled&&j(t.$exception_steps)?this.dl(t):t,i=typeof(s=globalThis._posthogReleaseId)=="string"&&s.length>0?s:void 0;i&&(n.$release_id=i);try{var r=this._instance.capture("$exception",n,{_noTruncate:!0,_batchKey:"exceptionEvent",Wn:!0});return r&&this.rl.clear(),r}catch(o){return ft.error("Failed to capture exception event. Dropping this exception.",o),void this.rl.clear()}}catch(o){return void ft.error("Failed to process exception event. Ignoring this exception.",o)}var s}dl(t){try{var e=this.rl.getAttachable();return e.length===0?t:E({},t,{$exception_steps:e})}catch(n){return ft.error("Failed to read buffered exception steps. Capturing exception without steps.",n),t}}ll(t){this.el.enabled&&this.rl.add({[Rr]:t,[Tr]:new Date().toISOString()})}sl(t){return ae(t)?E({},t):{}}il(){var t,e;return(t=(e=this._instance.config.error_tracking)==null?void 0:e.exception_steps)!==null&&t!==void 0?t:{}}ol(t){if(t.length===0)return!1;try{var e=t.reduce(((n,i)=>{var r=i.type,s=i.value;return K(r)&&r.length>0&&n.$exception_types.push(r),K(s)&&s.length>0&&n.$exception_values.push(s),n}),{$exception_types:[],$exception_values:[]});return this.Xo.some((n=>{var i=n.values.map((r=>{var s=ph[r.operator],o=e[r.key];if(!s||!o)return!1;var a=D(r.value)?r.value:[r.value];return a.length>0&&s(a,o)}));return n.type==="OR"?i.some(Boolean):i.every(Boolean)}))}catch(n){return ft.warn("Failed to evaluate suppression rules. Capturing the exception.",n),!1}}ul(t){return t.flatMap((e=>{var n,i;return(n=(i=e.stacktrace)==null?void 0:i.frames)!==null&&n!==void 0?n:[]})).some((e=>e.filename&&e.filename.startsWith("chrome-extension://")))}hl(t){if(t.length>0){var e,n,i,r,s=(e=(n=t[0].stacktrace)==null?void 0:n.frames)!==null&&e!==void 0?e:[],o=s[s.length-1];return(i=o==null||(r=o.filename)==null?void 0:r.includes("posthog.com/static"))!==null&&i!==void 0&&i}return!1}al(t){return!j(t)&&D(t)}}},Qg=E({productTours:class{get Mr(){return this._instance.persistence}constructor(t){this.vl=null,this.cl=null,this._instance=t}initialize(){this.loadIfEnabled()}onRemoteConfig(t){if(t.ok){var e=t.config;if("productTours"in e){var n,i;if(this.Mr&&this.Mr.register({[qa]:!!e.productTours}),!ko(this._instance))return!this.vl&&j((n=this.Mr)==null?void 0:n.props[vi])||rr.info("product tours disabled; stopping and clearing cached tours"),(i=this.vl)==null||i.stop(),this.vl=null,void this.clearCache();this.loadIfEnabled()}}}loadIfEnabled(){!this.vl&&ko(this._instance)&&this.ai((()=>this.fl()))}ai(t){var e,n;(e=T.__PosthogExtensions__)!=null&&e.generateProductTours?t():(n=T.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,"product-tours",(i=>{i?rr.error("Could not load product tours script",i):t()}))}fl(){var t;!this.vl&&(t=T.__PosthogExtensions__)!=null&&t.generateProductTours&&(this.vl=T.__PosthogExtensions__.generateProductTours(this._instance,!0))}getProductTours(t,e){if(e===void 0&&(e=!1),!D(this.cl)||e){var n=this.Mr;if(n){var i=n.props[vi];if(D(i)&&!e)return this.cl=i,void t(i,{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(ko(this._instance)){var s=r.statusCode;if(s!==200||!r.json){var o="Product Tours API could not be loaded, status: "+s;return s===0?r.error||rr.warn(o):rr.error(o),void t([],{isLoaded:!1,error:o})}var a=D(r.json.product_tours)?r.json.product_tours:[];this.cl=a,n&&n.register({[vi]:a}),t(a,{isLoaded:!0})}else t([],{isLoaded:!0})}})}else t(this.cl,{isLoaded:!0})}getActiveProductTours(t){j(this.vl)?t([],{isLoaded:!1,error:"Product tours not loaded"}):this.vl.getActiveProductTours(t)}showProductTour(t){var e;(e=this.vl)==null||e.showTourById(t)}previewTour(t){this.vl?this.vl.previewTour(t):this.ai((()=>{var e;this.fl(),(e=this.vl)==null||e.previewTour(t)}))}dismissProductTour(){var t;(t=this.vl)==null||t.dismissTour("user_clicked_skip")}nextStep(){var t;(t=this.vl)==null||t.nextStep()}previousStep(){var t;(t=this.vl)==null||t.previousStep()}clearCache(){var t;this.cl=null,(t=this.Mr)==null||t.unregister(vi)}resetTour(t){var e;(e=this.vl)==null||e.resetTour(t)}resetAllTours(){var t;(t=this.vl)==null||t.resetAllTours()}cancelPendingTour(t){var e;(e=this.vl)==null||e.cancelPendingTour(t)}}},fs),em={siteApps:class{constructor(t){this.pl=0,this._instance=t,this.gl=[],this.apps={}}get isEnabled(){return!!this._instance.config.opt_in_site_apps}ml(t,e){if(e){var n=this.globalsForEvent(e);this.gl.push(n),this.gl.length>1e3&&(this.gl=this.gl.slice(10))}}get siteAppLoaders(){var t;return(t=T._POSTHOG_REMOTE_CONFIG)==null||(t=t[this._instance.config.token])==null?void 0:t.siteApps}initialize(){if(this.isEnabled){var t=this._instance._addCaptureHook(this.ml.bind(this));this.yl=()=>{t(),this.gl=[],this.yl=void 0}}}globalsForEvent(t){var e,n,i,r,s,o,a;if(!t)throw new Error("Event payload is required");var l={},u=this._instance.get_property("$groups")||[],c=this._instance.get_property("$stored_group_properties")||{};for(var d of Object.entries(c)){var h=d[0];l[h]={id:u[h],type:h,properties:d[1]}}var f=t.$set_once,p=t.$set;return{event:E({},Du(t,Wg),{properties:E({},t.properties,p?{$set:E({},(e=(n=t.properties)==null?void 0:n.$set)!==null&&e!==void 0?e:{},p)}:{},f?{$set_once:E({},(i=(r=t.properties)==null?void 0:r.$set_once)!==null&&i!==void 0?i:{},f)}:{}),elements_chain:(s=(o=t.properties)==null?void 0:o.$elements_chain)!==null&&s!==void 0?s:"",distinct_id:(a=t.properties)==null?void 0:a.distinct_id}),person:{properties:this._instance.get_property("$stored_person_properties")},groups:l}}bl(t){var e,n=(e=t.tagName)==null?void 0:e.toLowerCase();return n==="style"&&this._instance.config.prepare_external_dependency_stylesheet?this._instance.config.prepare_external_dependency_stylesheet(t)||(ht.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)||(ht.error("prepare_external_dependency_script returned null"),null):t}_l(){var t,e,n,i,r,s,o,a;if(!this._instance.config.prepare_external_dependency_stylesheet&&!this._instance.config.prepare_external_dependency_script)return()=>{};var l=C?.defaultView,u=l==null||(t=l.Node)==null?void 0:t.prototype;if(!l||!u)return()=>{};if(this.pl++,this.wl)return this.kl();var c=[],d=this,h=new WeakSet,f=(m,v,w)=>{if(m!=null&&m[v]){var b=m[v];m[v]=w(b),c.push((()=>{m[v]=b}))}},p=m=>{if(h.has(m))return m;var v=d.bl(m);return v&&h.add(v),v},g=m=>m.map((v=>typeof v=="string"?v:p(v))).filter((v=>!We(v)));return f(u,"appendChild",(m=>function(v){var w=p(v);return w?m.call(this,w):v})),f(u,"insertBefore",(m=>function(v,w){var b=p(v);return b?m.call(this,b,w):v})),f(u,"replaceChild",(m=>function(v,w){var b=p(v);return b?m.call(this,b,w):w})),[(e=l.Element)==null?void 0:e.prototype,(n=l.Document)==null?void 0:n.prototype,(i=l.DocumentFragment)==null?void 0:i.prototype].forEach((m=>{f(m,"append",(v=>function(){for(var w=arguments.length,b=new Array(w),I=0;w>I;I++)b[I]=arguments[I];return v.apply(this,g(b))})),f(m,"prepend",(v=>function(){for(var w=arguments.length,b=new Array(w),I=0;w>I;I++)b[I]=arguments[I];return v.apply(this,g(b))}))})),[(r=l.Element)==null?void 0:r.prototype,(s=l.CharacterData)==null?void 0:s.prototype,(o=l.DocumentType)==null?void 0:o.prototype].forEach((m=>{f(m,"before",(v=>function(){for(var w=arguments.length,b=new Array(w),I=0;w>I;I++)b[I]=arguments[I];return v.apply(this,g(b))})),f(m,"after",(v=>function(){for(var w=arguments.length,b=new Array(w),I=0;w>I;I++)b[I]=arguments[I];return v.apply(this,g(b))})),f(m,"replaceWith",(v=>function(){for(var w=arguments.length,b=new Array(w),I=0;w>I;I++)b[I]=arguments[I];var A=g(b);return b.length&&!A.length?void 0:v.apply(this,A)}))})),f((a=l.Element)==null?void 0:a.prototype,"insertAdjacentElement",(m=>function(v,w){var b=p(w);return b?m.call(this,v,b):null})),this.wl=()=>{c.forEach((m=>m())),this.wl=void 0},this.kl()}kl(){var t=!1;return()=>{var e;t||(t=!0,this.pl--,this.pl===0&&((e=this.wl)==null||e.call(this)))}}xl(t,e){e===void 0&&(e=!0);var n=this._l();try{var i=t(n);return e&&n(),i}catch(r){throw n(),r}}setupSiteApp(t){var e=this.apps[t.id],n=()=>{var o;!e.errored&&this.gl.length&&(ht.info("Processing "+this.gl.length+" events for site app with id "+t.id),this.gl.forEach((a=>this.xl((()=>e.processEvent==null?void 0:e.processEvent(a))))),e.processedBuffer=!0),Object.values(this.apps).every((a=>a.processedBuffer||a.errored))&&((o=this.yl)==null||o.call(this))},i=!1,r=o=>{e.errored=!o,e.loaded=!0,ht.info("Site app with id "+t.id+" "+(o?"loaded":"errored")),i&&n()};try{var s=this.xl((o=>t.init({posthog:this._instance,callback(a){o(),r(a)}})),!1).processEvent;s&&(e.processEvent=s),i=!0}catch(o){ht.error(Vc+t.id,o),r(!1)}if(i&&e.loaded)try{n()}catch(o){ht.error("Error while processing buffered events PostHog app with config id "+t.id,o),e.errored=!0}}Sl(){var t=this.siteAppLoaders||[];for(var e of t)this.apps[e.id]={id:e.id,loaded:!1,errored:!1,processedBuffer:!1};for(var n of t)this.setupSiteApp(n)}Cl(t){var e=this;if(Object.keys(this.apps).length!==0){var n=this.globalsForEvent(t),i=function(s){try{e.xl((()=>s.processEvent==null?void 0:s.processEvent(n)))}catch(o){ht.error("Error while processing event "+t.event+" for site app "+s.id,o)}};for(var r of Object.values(this.apps))i(r)}}onRemoteConfig(t){var e,n,i,r=this;if((e=this.siteAppLoaders)!=null&&e.length)return this.isEnabled?(this.Sl(),void this._instance.on("eventCaptured",(l=>this.Cl(l)))):void ht.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.');if((n=this.yl)==null||n.call(this),t.ok){var s=t.config;if((i=s.siteApps)!=null&&i.length)if(this.isEnabled){var o=function(){var l,u=a.id,c=a.url;T["__$$ph_site_app_"+u]=r._instance,(l=T.__PosthogExtensions__)==null||l.loadSiteApp==null||l.loadSiteApp(r._instance,c,(d=>{if(d)return ht.error(Vc+u,d)}))};for(var a of s.siteApps)o()}else ht.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.')}}}},tm={tracingHeaders:class{constructor(t){this.Ml=void 0,this.Tl=void 0,this.El=void 0,this.Uo=()=>{var e,n,i=this.Il();i?(x(this.Ml)&&(this.Ml=(e=T.__PosthogExtensions__)==null||(e=e.tracingHeadersPatchFns)==null?void 0:e._patchXHR(i,(()=>this._instance.get_distinct_id()),this._instance.sessionManager)),x(this.Tl)&&(this.Tl=(n=T.__PosthogExtensions__)==null||(n=n.tracingHeadersPatchFns)==null?void 0:n._patchFetch(i,(()=>this._instance.get_distinct_id()),this._instance.sessionManager))):this.Qo()},this._instance=t}initialize(){this.startIfEnabledOrStop()}ai(t){var e,n;(e=T.__PosthogExtensions__)!=null&&e.tracingHeadersPatchFns?t():(n=T.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,"tracing-headers",(i=>{if(i)return Ug.error("failed to load script",i);t()}))}Pl(){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}Il(){var t=this.Pl();return D(t)?(D(this.El)?this.El.splice(0,this.El.length,...t):this.El=[...t],t.length>0?this.El:void 0):(D(this.El)&&this.El.splice(0),this.El=t||void 0,this.El)}Qo(){var t,e;(t=this.Ml)==null||t.call(this),(e=this.Tl)==null||e.call(this),this.Ml=void 0,this.Tl=void 0}startIfEnabledOrStop(){this.Il()?this.ai(this.Uo):this.Qo()}}},nm=E({surveys:class{get Ne(){return this._instance.config}constructor(t){this.Rl=void 0,this._surveyManager=null,this.Al=!1,this.Fl=[],this.Ll=null,this.Ol=null,this._instance=t,this._surveyEventReceiver=null}initialize(){this.loadIfEnabled()}onRemoteConfig(t){if(!this.Ne.disable_surveys){if(!t.ok)return Z.warn("Remote config unavailable. Not loading surveys.");var e=t.config.surveys;if(j(e))return Z.warn("Flags not loaded yet. Not loading surveys.");var n=D(e);this.Rl=n?e.length>0:e,Z.info("flags response received, isSurveysEnabled: "+this.Rl),this.loadIfEnabled()}}reset(){try{var t;(t=this._surveyEventReceiver)==null||t.reset(),localStorage.removeItem("lastSeenSurveyDate");for(var e=[],n=0;nlocalStorage.removeItem(r)))}catch{}}loadIfEnabled(){if(!this._surveyManager)if(this.Al)Z.info("Already initializing surveys, skipping...");else if(this.Ne.disable_surveys)Z.info(Gc);else if(this.Ne.cookieless_mode&&this._instance.consent.isOptedOut())Z.info("Not loading surveys in cookieless mode without consent.");else{var t=T?.__PosthogExtensions__;if(t){if(!x(this.Rl)||this.Ne.advanced_enable_surveys){var e=this.Rl||this.Ne.advanced_enable_surveys;this.Al=!0;try{var n=t.generateSurveys;if(n)return void this.Dl(n,e);var i=t.loadExternalDependency;if(!i)return void this.$l(Va);i(this._instance,"surveys",(r=>{r||!t.generateSurveys?this.$l("Could not load surveys script",r):this.Dl(t.generateSurveys,e)}))}catch(r){throw this.$l("Error initializing surveys",r),r}finally{this.Al=!1}}}else Z.error("PostHog Extensions not found.")}}Dl(t,e){this._surveyManager=t(this._instance,e),this._surveyEventReceiver=new Vg(this._instance),Z.info("Surveys loaded successfully"),this.Nl({isLoaded:!0})}$l(t,e){Z.error(t,e),this.Nl({isLoaded:!1,error:t})}onSurveysLoaded(t){return this.Fl.push(t),this._surveyManager&&this.Nl({isLoaded:!0}),()=>{this.Fl=this.Fl.filter((e=>e!==t))}}getSurveys(t,e){if(e===void 0&&(e=!1),this.Ne.disable_surveys)return Z.info(Gc),t([]);var n,i=this._instance.get_property(Yo);if(i&&!e)return t(i,{isLoaded:!0}),void(this.ql()&&this.getSurveys((()=>{}),!0));typeof Promise<"u"&&this.Ll?this.Ll.then((r=>t(r.surveys,r.context))):(typeof Promise<"u"&&(this.Ll=new Promise((r=>{n=r}))),this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/surveys/?token="+this.Ne.token),method:"GET",timestampMode:"query",timeout:this.Ne.surveys_request_timeout_ms,callback:r=>{var s;this.Ll=null;var o=r.statusCode;if(o!==200||!r.json){var a="Surveys API could not be loaded, status: "+o;o!==0?Z.error(a):r.error||Z.warn(a),this.Ol=Date.now();var l={isLoaded:!1,error:a};return t([],l),void(n==null||n({surveys:[],context:l}))}this.Ol=null;var u,c=r.json.surveys||[],d=c.filter((f=>(function(p){return!(!p.start_date||p.end_date)})(f)&&(mh(f)||(function(p){var g;return!((g=p.conditions)==null||(g=g.actions)==null||(g=g.values)==null||!g.length)})(f))));d.length>0&&((u=this._surveyEventReceiver)==null||u.register(d)),(s=this._instance.persistence)==null||s.register({[Yo]:c,[Lr]:Date.now()});var h={isLoaded:!0};t(c,h),n?.({surveys:c,context:h})}}))}ql(){return this.jl()&&!this.Ll&&!this.Bl()}jl(){var t=this._instance.get_property(Lr);return Se(t)&&Date.now()-t>3e5}Bl(){return Se(this.Ol)&&3e5>Date.now()-this.Ol}markSurveyAsSeen(t,e){var n,i={id:t,current_iteration:(n=e?.iteration)!==null&&n!==void 0?n:null};_h(i);try{localStorage.setItem("lastSeenSurveyDate",new Date().toISOString())}catch{}}Nl(t){for(var e of this.Fl)try{if(!t.isLoaded)return e([],t);this.getSurveys(e)}catch(n){Z.error("Error in survey callback",n)}}getActiveMatchingSurveys(t,e){if(e===void 0&&(e=!1),!j(this._surveyManager))return this._surveyManager.getActiveMatchingSurveys(t,e);Z.warn("init was not called")}Hl(t){var e=null;return this.getSurveys((n=>{var i;e=(i=n.find((r=>r.id===t)))!==null&&i!==void 0?i:null})),e}Ul(t){if(j(this._surveyManager))return{eligible:!1,reason:sr};var e=typeof t=="string"?this.Hl(t):t;return e?this._surveyManager.checkSurveyEligibility(e):{eligible:!1,reason:"Survey not found"}}zl(t){if(j(this._surveyManager))return{eligible:!1,reason:sr};var e=typeof t=="string"?this.Hl(t):t;return e?this._surveyManager.checkSurveyRenderability(e):{eligible:!1,reason:"Survey not found"}}canRenderSurvey(t){if(j(this._surveyManager))return Z.warn("init was not called"),{visible:!1,disabledReason:sr};var e=this.zl(t);return{visible:e.eligible,disabledReason:e.reason}}canRenderSurveyAsync(t,e){return j(this._surveyManager)?(Z.warn("init was not called"),Promise.resolve({visible:!1,disabledReason:sr})):new Promise((n=>{this.getSurveys((i=>{var r,s=(r=i.find((a=>a.id===t)))!==null&&r!==void 0?r:null;if(s){var o=this.zl(s);n({visible:o.eligible,disabledReason:o.reason})}else n({visible:!1,disabledReason:"Survey not found"})}),e)}))}renderSurvey(t,e,n){var i;if(j(this._surveyManager))Z.warn("init was not called");else{var r=typeof t=="string"?this.Hl(t):t;if(r!=null&&r.id)if(Ag.includes(r.type)){var s=C?.querySelector(e);if(s)return(i=r.appearance)!=null&&i.surveyPopupDelaySeconds?(Z.info("Rendering survey "+r.id+" with delay of "+r.appearance.surveyPopupDelaySeconds+" seconds"),void setTimeout((()=>{var o,a;Z.info("Rendering survey "+r.id+" with delay of "+((o=r.appearance)==null?void 0:o.surveyPopupDelaySeconds)+" seconds"),(a=this._surveyManager)==null||a.renderSurvey(r,s,n),Z.info("Survey "+r.id+" rendered")}),1e3*r.appearance.surveyPopupDelaySeconds)):void this._surveyManager.renderSurvey(r,s,n);Z.warn("Survey element not found")}else Z.warn("Surveys of type "+r.type+" cannot be rendered in the app");else Z.warn("Survey not found")}}displaySurvey(t,e){var n;if(j(this._surveyManager))Z.warn("init was not called");else{var i=this.Hl(t);if(i){var r=i;if((n=i.appearance)!=null&&n.surveyPopupDelaySeconds&&e.ignoreDelay&&(r=E({},i,{appearance:E({},i.appearance,{surveyPopupDelaySeconds:0})})),e.displayType!==sa.Popover&&e.initialResponses&&Z.warn("initialResponses is only supported for popover surveys. prefill will not be applied."),e.ignoreConditions===!1){var s=this.Ul(i);if(!s.eligible)return void Z.warn("Survey is not eligible to be displayed: ",s.reason)}e.displayType!==sa.Inline?this._surveyManager.handlePopoverSurvey(r,e):this.renderSurvey(r,e.selector,e.properties)}else Z.warn("Survey not found")}}cancelPendingSurvey(t){j(this._surveyManager)?Z.warn("init was not called"):this._surveyManager.cancelSurvey(t)}handlePageUnload(){var t;(t=this._surveyManager)==null||t.handlePageUnload==null||t.handlePageUnload()}}},fs),im={toolbar:class{constructor(t){this.instance=t}Wl(t){T.ph_toolbar_state=t}Vl(){var t;return(t=T.ph_toolbar_state)!==null&&t!==void 0?t:0}initialize(){return this.maybeLoadToolbar()}maybeLoadToolbar(t,e,n){if(t===void 0&&(t=void 0),e===void 0&&(e=void 0),n===void 0&&(n=void 0),na(this.instance.config)||!_||!C)return!1;t=t??_.location,n=n??_.history;try{if(!e){try{_.localStorage.setItem("test","test"),_.localStorage.removeItem("test")}catch{return!1}e=_?.localStorage}var i,r=Gg||Wr(t.hash,"__posthog")||Wr(t.hash,"state"),s=r?dc((()=>JSON.parse(atob(decodeURIComponent(r)))))||dc((()=>JSON.parse(decodeURIComponent(r)))):null;return s&&s.action==="ph_authorize"?((i=s).source="url",i&&Object.keys(i).length>0&&(s.desiredHash?t.hash=s.desiredHash:n?n.replaceState(n.state,"",t.pathname+t.search):t.hash="")):((i=JSON.parse(e.getItem(Kc)||"{}")).source="localstorage",delete i.userIntent),!(!i.token||this.instance.config.token!==i.token||(this.loadToolbar(i),0))}catch{return!1}}Zl(t){var e=T.ph_load_toolbar||T.ph_load_editor;!j(e)&&Ne(e)?e(t,this.instance):Yc.warn("No toolbar load function found")}loadToolbar(t){var e=!(C==null||!C.getElementById($d));if(!_||e)return!1;var n=this.instance.requestRouter.region==="custom"&&this.instance.config.advanced_disable_toolbar_metrics,i=E({token:this.instance.config.token},t,{apiURL:this.instance.requestRouter.endpointFor("ui")},n?{instrument:!1}:{});if(_.localStorage.setItem(Kc,JSON.stringify(E({},i,{source:void 0}))),this.Vl()===2)this.Zl(i);else if(this.Vl()===0){var r;this.Wl(1),(r=T.__PosthogExtensions__)==null||r.loadExternalDependency==null||r.loadExternalDependency(this.instance,"toolbar",(s=>{if(s)return Yc.error("[Toolbar] Failed to load",s),void this.Wl(0);this.Wl(2),this.Zl(i)})),de(_,"turbolinks:load",(()=>{this.Wl(0),this.loadToolbar(i)}))}return!0}Gl(t){return this.loadToolbar(t)}maybeLoadEditor(t,e,n){return t===void 0&&(t=void 0),e===void 0&&(e=void 0),n===void 0&&(n=void 0),this.maybeLoadToolbar(t,e,n)}}},rm=E({experiments:Re},fs),sm={conversations:class{constructor(t){this.Ql=void 0,this._conversationsManager=null,this.Kl=!1,this.Jl=null,this.Yl=!1,this._instance=t}initialize(){this.loadIfEnabled()}onRemoteConfig(t){if(!this._instance.config.disable_conversations&&(this.Xl=t.ok,t.ok)){var e=t.config.conversations;j(e)||(at(e)?this.Ql=e:(this.Ql=e.enabled,this.Jl=e),this.loadIfEnabled())}}reset(){var t;(t=this._conversationsManager)==null||t.reset(),this._conversationsManager=null,this.Ql=void 0,this.Jl=null,this.Xl=void 0,this.Yl=!1}loadIfEnabled(){if(!(this._conversationsManager||this.Kl||this._instance.config.disable_conversations||na(this._instance.config)||this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut())){var t=T?.__PosthogExtensions__;if(t&&!x(this.Ql)&&this.Ql)if(this.Jl&&this.Jl.token){this.Kl=!0;try{var e=t.initConversations;if(e)return this.tu(e),void(this.Kl=!1);var n=t.loadExternalDependency;if(!n)return void this.eu(Va);n(this._instance,"conversations",(i=>{i||!t.initConversations?this.eu("Could not load conversations script",i):this.tu(t.initConversations),this.Kl=!1}))}catch(i){this.eu("Error initializing conversations",i),this.Kl=!1}}else Ze.error("Conversations enabled but missing token in remote config.")}}tu(t){if(this.Jl)try{this._conversationsManager=t(this.Jl,this._instance),this.Yl=!1,Ze.info("Conversations loaded successfully")}catch(e){this.eu("Error completing conversations initialization",e)}else Ze.error("Cannot complete initialization: remote config is null")}eu(t,e){Ze.error(t,e),this._conversationsManager=null,this.Kl=!1,this.Yl=!0}show(){this._conversationsManager?this._conversationsManager.show():Ze.warn("Conversations not loaded yet.")}hide(){this._conversationsManager&&this._conversationsManager.hide()}isAvailable(){return this.Ql===!0&&!We(this._conversationsManager)}getUnavailableReason(){return this.isAvailable()?null:this._instance.config.disable_conversations?"disabled_by_config":na(this._instance.config)?"disabled_for_toolbar":this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut()?"consent_opted_out":this.Xl===!1?"remote_config_failed":x(this.Ql)?this.Xl?"disabled_in_project":"remote_config_pending":this.Ql?j(this.Jl)||!this.Jl.token?"missing_token":T!=null&&T.__PosthogExtensions__?this.Kl?"initializing":this.Yl?"load_failed":"not_loaded":"extensions_unavailable":"disabled_in_project"}isVisible(){var t,e;return(t=(e=this._conversationsManager)==null?void 0:e.isVisible())!==null&&t!==void 0&&t}sendMessage(t,e,n){var i=this;return ne((function*(){return i._conversationsManager?i._conversationsManager.sendMessage(t,e,n):(Ze.warn(dn),null)}))()}getMessages(t,e){var n=this;return ne((function*(){return n._conversationsManager?n._conversationsManager.getMessages(t,e):(Ze.warn(dn),null)}))()}markAsRead(t){var e=this;return ne((function*(){return e._conversationsManager?e._conversationsManager.markAsRead(t):(Ze.warn(dn),null)}))()}getTickets(t){var e=this;return ne((function*(){return e._conversationsManager?e._conversationsManager.getTickets(t):(Ze.warn(dn),null)}))()}requestRestoreLink(t){var e=this;return ne((function*(){return e._conversationsManager?e._conversationsManager.requestRestoreLink(t):(Ze.warn(dn),null)}))()}restoreFromToken(t){var e=this;return ne((function*(){return e._conversationsManager?e._conversationsManager.restoreFromToken(t):(Ze.warn(dn),null)}))()}restoreFromUrlToken(){var t=this;return ne((function*(){return t._conversationsManager?t._conversationsManager.restoreFromUrlToken():(Ze.warn(dn),null)}))()}getCurrentTicketId(){var t,e;return(t=(e=this._conversationsManager)==null?void 0:e.getCurrentTicketId())!==null&&t!==void 0?t:null}getWidgetSessionId(){var t,e;return(t=(e=this._conversationsManager)==null?void 0:e.getWidgetSessionId())!==null&&t!==void 0?t:null}Xn(){var t;(t=this._conversationsManager)==null||t.setIdentity()}ts(){var t;(t=this._conversationsManager)==null||t.clearIdentity()}}},om={logs:class{constructor(t){var e,n=this;this.iu=!1,this.ru=!1,this.rt=le("[logs]"),this.nu=E({},this.rt,{error(){for(var i=arguments.length,r=new Array(i),s=0;i>s;s++)r[s]=arguments[s];r.some(iu)||n.rt.error(...r)}}),this.tr=[],this.su=[],this.Sa=0,this.au=()=>{var i,r;this.Sa=0,(i=this.ou)==null||i.onReconnect(),(r=this.lu)==null||r.onReconnect()},this._instance=t,this._instance&&(e=this._instance.config.logs)!=null&&e.captureConsoleLogs&&(this.iu=!0),_&&de(_,"online",this.au)}uu(t,e,n,i){var r,s=(function(o,a){var l,u,c,d,h,f,p,g=(l=o?.flushIntervalMs)!==null&&l!==void 0?l:3e3,m=(u=o?.maxBufferSize)!==null&&u!==void 0?u:100,v=a!=null&&a.consoleCapture?void 0:(c=o?.maxLogsPerInterval)!==null&&c!==void 0?c:1e3,w=x(v)?Math.max(m,2048):Math.max(m,v),b=o?.resourceAttributes;return{serviceName:(d=(h=b?.["service.name"])!==null&&h!==void 0?h:o?.serviceName)!==null&&d!==void 0?d:a?.serviceNameDefault,serviceVersion:(f=b?.["service.version"])!==null&&f!==void 0?f:o?.serviceVersion,environment:(p=b?.["deployment.environment"])!==null&&p!==void 0?p:o?.environment,resourceAttributes:b,beforeSend:o?.beforeSend,flushIntervalMs:g,maxBufferSize:m,maxQueueSize:w,maxBatchRecordsPerPost:100,rateCapWindowMs:g,maxLogsPerInterval:v,backgroundFlushBudgetMs:0,terminationFlushBudgetMs:0}})((r=this._instance)==null||(r=r.config)==null?void 0:r.logs,n);return[new up(this.hu(t,e),s,this.nu,(()=>this.du()),(o=>o()),void 0,i),s]}vu(){var t,e=(t=this._instance)==null||(t=t.config)==null?void 0:t.logs;if(!this.ou||this.cu!==e){var n;(n=this.ou)==null||n.reset(),this.cu=e;var i=this.uu((()=>this.tr),(r=>{this.tr=r}));this.ou=i[0],this.fu=i[1]}return this.ou}pu(){var t,e=(t=this._instance)==null||(t=t.config)==null?void 0:t.logs;if(!this.lu||this.gu!==e){var n;(n=this.lu)==null||n.reset(),this.gu=e;var i=this.uu((()=>this.su),(r=>{this.su=r}),{serviceNameDefault:"posthog-browser-logs",consoleCapture:!0},nu);this.lu=i[0],this.mu=i[1]}return this.lu}initialize(){this.loadIfEnabled()}onRemoteConfig(t){var e;if(t.ok){var n=(e=t.config.logs)==null?void 0:e.captureConsoleLogs;!j(n)&&n&&(this.iu=!0,this.loadIfEnabled())}}reset(){var t,e;this.tr=[],(t=this.ou)==null||t.reset(),this.su=[],(e=this.lu)==null||e.reset(),this.Sa=0}captureLog(t){this.vu().captureLog(t)}he(t){this.pu().captureLog(t)}get logger(){return this.yu||(this.yu={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.yu}flushLogs(t){t?this.bu(t):(this.ou&&this.ou.flush().catch((e=>this._u(e))),this.lu&&this.lu.flush().catch((e=>this._u(e))))}_u(t){iu(t)||this.rt.error("PostHog logs flush failed:",t)}loadIfEnabled(){if(this.iu&&!this.ru){var t=T?.__PosthogExtensions__;if(t){var e=t.loadExternalDependency;e?e(this._instance,"logs",(n=>{var i;n||(i=t.logs)==null||!i.initializeLogs?this.rt.error("Could not load logs script",n):(t.logs.initializeLogs(this._instance),this.ru=!0)})):this.rt.error(Va)}else this.rt.error("PostHog Extensions not found.")}}hu(t,e){var n=this._instance;return{get isDisabled(){return!1},get optedOut(){return!n.is_capturing()},getPersistedProperty:i=>i===Ft.LogsQueue?t():void 0,setPersistedProperty(i,r){var s;i===Ft.LogsQueue&&e((s=r)!==null&&s!==void 0?s:[])},Ot:i=>this.Ot(i),getLibraryId:()=>ee.LIB_NAME,getLibraryVersion:()=>ee.LIB_VERSION}}Ot(t){return new Promise((e=>{if(zd(this.Sa,3))e({kind:"fatal",error:Co(void 0,"logs endpoint is unreachable, dropping batch")});else{var n=!1,i=s=>{n||(n=!0,clearTimeout(r),e(s))},r=setTimeout((()=>{this.rt.warn("Logs request timed out before receiving a response"),i({kind:"retry-later",error:Co(void 0,"logs request timed out")})}),9e4);this._instance._send_request({method:"POST",url:this.wu(),data:t,compression:"best-available",batchKey:"logs",fireCallbackOnDrop:!0,callback:s=>{var o=s.statusCode;if(this.ku(o),o>=200&&300>o)i({kind:"ok"});else if(o===413)i({kind:"too-large"});else if(o!==0&&o!==429&&500>o)i({kind:"fatal",error:new Error("logs request failed with status "+o)});else{var a;o===0?(s.error||this.rt.warn("Logs request failed before receiving an HTTP response"),i({kind:"retry-later",error:Co(s.error,"logs request failed before receiving an HTTP response")})):i({kind:"retry-later",error:(a=s.error)!==null&&a!==void 0?a:new Error("logs request failed with status "+o)})}}})}}))}ku(t){(t!==0||this._instance.__loaded)&&(this.Sa=Vd(t,this.Sa,3,(()=>this.rt.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."))))}bu(t){this.tr.length>0&&this.xu(t,this.tr,this.fu,ee.LIB_NAME,(e=>{this.tr=e})),this.su.length>0&&this.xu(t,this.su,this.mu,nu,(e=>{this.su=e}))}xu(t,e,n,i,r){if(e.length!==0){var s=e.map((a=>a.record));r([]);var o=md(s,gd(n,ee.LIB_NAME,ee.LIB_VERSION),i,ee.LIB_VERSION);this._instance._send_request({method:"POST",url:this.wu(),data:o,compression:"best-available",batchKey:"logs",transport:t})}}wu(){return this._instance.requestRouter.endpointFor("api","/i/v1/logs")+"?token="+encodeURIComponent(this._instance.config.token)}du(){var t,e={};if(e.distinctId=this._instance.get_distinct_id(),this._instance.sessionManager){var n=this._instance.sessionManager.checkAndGetSessionAndWindowId(!0),i=n.windowId,r=n.sessionStartTimestamp,s=n.lastActivityTimestamp;e.sessionId=n.sessionId,e.windowId=i,j(r)||(e.sessionStartTimestamp=r),j(s)||(e.lastActivityTimestamp=s)}if(T!=null&&(t=T.location)!=null&&t.href&&(e.currentUrl=this._instance.config.disable_capture_url_hashes?Qt(T.location.href):T.location.href),this._instance.featureFlags){var o=this._instance.featureFlags.getFlags();o&&o.length>0&&(e.activeFeatureFlags=o)}return e}}},am={metrics:class{constructor(t){this.rt=le("[metrics]"),this._instance=t}initialize(){}vu(){var t,e,n=(t=this._instance)==null||(t=t.config)==null?void 0:t.metrics;return this.ou&&this.cu===n||((e=this.ou)==null||e.reset(),this.cu=n,this.ou=new dp(this.hu(),(function(i){var r,s,o,a,l,u=i?.resourceAttributes;return{serviceName:(r=u?.["service.name"])!==null&&r!==void 0?r:i?.serviceName,serviceVersion:(s=u?.["service.version"])!==null&&s!==void 0?s:i?.serviceVersion,environment:(o=u?.["deployment.environment"])!==null&&o!==void 0?o:i?.environment,resourceAttributes:u,beforeSend:i?.beforeSend,flushIntervalMs:(a=i?.flushIntervalMs)!==null&&a!==void 0?a:1e4,maxSeriesPerFlush:(l=i?.maxSeriesPerFlush)!==null&&l!==void 0?l:1e3}})(n),this.rt)),this.ou}count(t,e,n){e===void 0&&(e=1),this.vu().count(t,e,n)}gauge(t,e,n){this.vu().gauge(t,e,n)}histogram(t,e,n){this.vu().histogram(t,e,n)}flush(t){if(!this.ou)return Promise.resolve();if(t){var e=this.ou.drainWindow();return e&&this.Jt(e,t),Promise.resolve()}return this.ou.flush().catch((n=>this.rt.error("PostHog metrics flush failed:",n)))}reset(){var t;(t=this.ou)==null||t.reset()}hu(){var t=this._instance,e=this;return{get isDisabled(){return!1},get optedOut(){return!t.is_capturing()},Jt:n=>e.Jt(n),getLibraryId:()=>ee.LIB_NAME,getLibraryVersion:()=>ee.LIB_VERSION}}Jt(t,e){return new Promise((n=>{var i=!1,r=o=>{i||(i=!0,clearTimeout(s),n(o))},s=setTimeout((()=>r({kind:"retry-later",error:new Error("metrics request timed out")})),9e4);this._instance._send_request(E({method:"POST",url:this.Su(),data:t,compression:"best-available",batchKey:"metrics"},e&&{transport:e},{fireCallbackOnDrop:!0,callback(o){var a=o.statusCode;if(a>=200&&300>a)r({kind:"ok"});else if(a===413)r({kind:"too-large"});else if(a!==0&&a!==429&&500>a)r({kind:"fatal",error:new Error("metrics request failed with status "+a)});else{var l;r({kind:"retry-later",error:(l=o.error)!==null&&l!==void 0?l:new Error("metrics request failed with status "+a)})}}}))}))}Su(){return this._instance.requestRouter.endpointFor("api","/i/v1/metrics")+"?token="+encodeURIComponent(this._instance.config.token)}}},lm=E({},fs,Jg,Zg,Xg,Qg,em,nm,tm,im,rm,sm,om,am);ze.__defaultExtensionClasses=E({},lm);(function(){ee.SDK_DIST_CHANNEL="npm";var t=xi[Mn]=new ze;return(function(){function e(){e.done||(e.done=!0,wh=!1,te(xi,(function(n){n._dom_loaded()})))}C!=null&&C.addEventListener?C.readyState==="complete"?e():de(C,"DOMContentLoaded",e,{capture:!1}):_&&k.error("Browser doesn't support `document.addEventListener` so PostHog couldn't be initialized")})(),t})();const cm=["a[href]","button:not([disabled])","input:not([disabled]):not([type='hidden'])","select:not([disabled])","textarea:not([disabled])","[tabindex]:not([tabindex='-1'])"].join(",");let ot=null,fa=null,Eh="";const pa=new Map;function Sh(t){return[...t.querySelectorAll(cm)].filter(e=>!e.hidden&&e.getAttribute("aria-hidden")!=="true"&&e.getClientRects().length>0)}function um(t){for(const e of document.body.children)e===t||e.tagName==="SCRIPT"||(pa.set(e,{inert:e.inert,ariaHidden:e.getAttribute("aria-hidden")}),e.inert=!0,e.setAttribute("aria-hidden","true"))}function dm(){for(const[t,e]of pa)t.inert=e.inert,e.ariaHidden===null?t.removeAttribute("aria-hidden"):t.setAttribute("aria-hidden",e.ariaHidden);pa.clear()}function xh(t){return t?.dataset.modalDismissible!=="false"&&t?.getAttribute("aria-busy")!=="true"}function tt(t,e={}){const n=typeof t=="string"?document.getElementById(t):t;if(!n)return!1;ot&&ot!==n&&ct(ot,{restoreFocus:!1,force:!0}),fa=e.trigger||document.activeElement,ot=n,Eh=document.body.style.overflow,um(n),document.body.style.overflow="hidden",n.classList.add("open"),n.setAttribute("aria-hidden","false");const i=n.querySelector(".modal-content");i&&(i.style.transform="scale(1) translateY(0)");const r=()=>{if(ot!==n)return;((e.initialFocus?n.querySelector(e.initialFocus):n.querySelector("[data-modal-initial-focus]"))||Sh(n)[0]||n.querySelector(".modal-content")||n).focus({preventScroll:!0})};return requestAnimationFrame(r),setTimeout(r,260),!0}function ct(t,e={}){const n=typeof t=="string"?document.getElementById(t):t;if(!n||!e.force&&!xh(n))return!1;n.classList.remove("open"),n.setAttribute("aria-hidden","true"),dm(),document.body.style.overflow=Eh,ot=null;const i=fa;return fa=null,e.restoreFocus!==!1&&i?.isConnected&&i.focus({preventScroll:!0}),!0}function ru(t,e,n="Operation in progress"){const i=typeof t=="string"?document.getElementById(t):t;i&&(i.dataset.modalDismissible=e?"false":"true",i.setAttribute("aria-busy",String(!!e)),e?i.setAttribute("aria-label",n):i.removeAttribute("aria-label"))}function hm(t){if(!xh(t))return;const e=t.dataset.modalCloseHandler;e&&typeof window[e]=="function"?window[e]():ct(t)}document.addEventListener("keydown",t=>{if(!ot)return;if(t.key==="Escape"){t.preventDefault(),t.stopImmediatePropagation(),hm(ot);return}if(t.key!=="Tab"){t.stopPropagation();return}const e=Sh(ot);if(!e.length){t.preventDefault(),(ot.querySelector(".modal-content")||ot).focus();return}const n=e[0],i=e[e.length-1];t.shiftKey&&document.activeElement===n?(t.preventDefault(),i.focus()):!t.shiftKey&&document.activeElement===i&&(t.preventDefault(),n.focus())},!0);function fm(){document.querySelectorAll(".modal-overlay").forEach(t=>{t.setAttribute("role","dialog"),t.setAttribute("aria-modal","true"),t.setAttribute("aria-hidden",t.classList.contains("open")?"false":"true");const e=t.querySelector(".modal-content");e&&!e.hasAttribute("tabindex")&&(e.tabIndex=-1);const n=t.querySelector("h1, h2, h3");n&&(n.id||(n.id=`${t.id}-title`),t.setAttribute("aria-labelledby",n.id)),t.querySelectorAll(".modal-close").forEach(i=>{i.getAttribute("aria-label")||i.setAttribute("aria-label","Close dialog")})})}const kh="CodeFile",Ih="GeneratedCode",pm={CustomAction:"A",CustomWidget:"W",CustomFunction:"F",CustomClass:"C",CodeFile:"C"};function Zt(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function ga(t){return String(t||"").trim().replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function gm(t={},e=0){const n=ga(t.artifactType||t.type||kh),i=ga(t.artifactName||t.name||t.fileName||`${Ih}-${e+1}`);return`${n||"artifact"}-${i||e+1}`}function Ch(t={},e=0){const n=Zt(t),i=n.artifactType||n.type||kh,r=n.artifactName||n.name||Ih;let s=n.fileName||r;return s.endsWith(".dart")||(s+=".dart"),{id:ga(n.id)||gm({...n,artifactType:i,artifactName:r,fileName:s},e),artifactType:i,artifactName:r,fileName:s,deployPath:n.deployPath||"",description:n.description||"",code:n.code||n.content||"",dependencies:Ah(n.dependencies),imports:Array.isArray(n.imports)?n.imports:[],publicApi:Array.isArray(n.publicApi)?n.publicApi:[],relationships:Ph(n.relationships),deployStatus:n.deployStatus||"pending",review:n.review||null,metadata:Zt(n.metadata),codeType:n.codeType||pm[i]||"O"}}function Ah(t){return t?Array.isArray(t)?t.map(e=>{if(typeof e=="string")return{name:e,version:null,inferred:!1};const n=Zt(e),i=n.name||n.package;return i?{name:i,version:n.version||null,versionRequired:!!(n.versionRequired||n.required),inferred:!!n.inferred,...n.reason?{reason:n.reason}:{}}:null}).filter(Boolean):Object.entries(Zt(t)).map(([e,n])=>({name:e,version:n||null,inferred:!1})):[]}function Ph(t){return t?(Array.isArray(t)?t:[t]).map(e=>{const n=Zt(e);return!n.from&&!n.to?null:{from:n.from||null,to:n.to||null,type:n.type||"uses",description:n.description||""}}).filter(Boolean):[]}function ma(t){if(typeof t!="string")return null;const e=t.trim();if(!e)return null;try{return JSON.parse(e)}catch{const n=e.match(/```(?:json)?\s*([\s\S]*?)```/i);if(!n)return null;try{return JSON.parse(n[1].trim())}catch{return null}}}function Mi(t,e={}){const n=[],i=typeof t=="string"?ma(t):t,s=Zt(i||{});!i&&typeof t=="string"&&n.push("Structured bundle parse failed; using legacy single-artifact fallback.");const o=Array.isArray(s.artifacts)?s.artifacts:[{artifactType:s.artifactType||e.artifactType,artifactName:s.artifactName||e.artifactName,fileName:s.fileName||e.fileName,description:s.description,code:s.code||e.code||(typeof t=="string"?t:""),dependencies:s.dependencies||e.dependencies,relationships:s.relationships||e.relationships}];o.forEach((d,h)=>{!d?.artifactType&&!d?.type&&n.push(`Artifact ${h+1} has no artifactType; it will deploy as a standalone code file under lib/custom_code/ root.`)});const a=o.map((d,h)=>Ch(d,h)),l=new Map(o.map((d,h)=>[Zt(d).id,a[h]?.id]).filter(([d,h])=>d&&h)),u=d=>l.get(d)||d,c=Ph(s.relationships||e.relationships).map(d=>({...d,from:d.from?u(d.from):d.from,to:d.to?u(d.to):d.to}));return{schemaVersion:s.schemaVersion||e.schemaVersion||null,id:s.id||e.id||"bundle-current",title:s.title||s.name||e.title||"Generated artifact bundle",description:s.description||e.description||"",artifacts:a,dependencies:Ah(s.dependencies||e.dependencies),relationships:c,deployOrder:Array.isArray(s.deployOrder)?s.deployOrder.map(u):a.map(d=>d.id),warnings:[...n,...Array.isArray(s.warnings)?s.warnings:[]],metadata:Zt(s.metadata)}}function Kr(t){return Mi(t).artifacts[0]||Ch()}function jt(t){if(typeof t!="string")return t??"";const e=t.trim();if(!e)return"";try{return JSON.parse(e)}catch{return t}}function Gn(t){return JSON.stringify(t,null,2)}function mm(t){return Gn({task:"architect",userRequest:String(t??"")})}function vm(t){const e=jt(t);return e&&typeof e=="object"&&typeof e.task=="string"?Gn(e):Gn({task:"generate_bundle",bundleSpec:e})}function _m(t){return Gn({task:"review_bundle",generatedBundle:jt(t),outputRequirements:{bundleReview:["status","score","summary","manualActions","findings"],scoreRange:[0,100],eachArtifact:["id","review.status","review.findings"],manualActions:{definition:"Setup the developer must perform by hand in the FlutterFlow editor that FlutterFlow will NOT do for them.",exclude:["creating the Custom Action, Widget or Code File itself - deploying the code creates it","declaring parameters or return values FlutterFlow derives from the function signature","anything that resolves as a side effect of using the action or widget in the editor","generic advice such as testing, reviewing or rebuilding the app"],preferEmpty:"Return an empty array when nothing qualifies - an empty list is the expected result for most bundles."}}})}function el(t,e=null){const n={stage:t};return e!=null&&(n.bundle=jt(e)),n}function ym({bundleSpec:t,artifactBundle:e,bundleReview:n,artifactId:i,userFeedback:r}){return Gn({task:"regenerate_artifact",artifactId:i,bundleSpec:jt(t),artifactBundle:jt(e),bundleReview:jt(n),userFeedback:String(r)})}function Fh({bundleSpec:t,artifactBundle:e,bundleReview:n,userFeedback:i}){return Gn({task:"regenerate_bundle",bundleSpec:jt(t),artifactBundle:jt(e),bundleReview:jt(n),userFeedback:String(i??"")})}const su={csam:"child-safety content",dangerous:"dangerous content",harassment:"harassment",hate_speech:"hate speech",maliciousUrls:"a potentially malicious URL",malicious_uris:"a potentially malicious URL",pi_and_jailbreak:"prompt-injection or jailbreak instructions",promptInjection:"prompt-injection or jailbreak instructions",rai:"restricted content",sdp:"sensitive personal data",sexually_explicit:"sexually explicit content",virus_scan:"potentially malicious file content"},wm=["sanitizationResult","modelArmor","modelArmorResult","data","result","error"];function Ke(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function bm(t){return Ke(t)?typeof t.filterMatchState=="string"||typeof t.invocationResult=="string"||Array.isArray(t.matchedFilters)||Ke(t.filterSummary)||Ke(t.filterResults):!1}function Rh(t,e=0){if(!Ke(t)||e>3)return null;if(bm(t))return t;for(const n of wm){const i=t[n];if(Ke(i)){const r=Rh(i,e+1);if(r)return r}}return null}function Yr(t){return Array.isArray(t)?t.some(Yr):Ke(t)?t.matched===!0||t.matchState==="MATCH_FOUND"?!0:Object.values(t).some(Yr):!1}function va(t){return Array.isArray(t)?t.some(va):Ke(t)?typeof t.executionState=="string"&&t.executionState!=="EXECUTION_SUCCESS"?!0:Object.values(t).some(va):!1}function Th(t){return{csamFilterFilterResult:"csam",maliciousUriFilterResult:"malicious_uris",piAndJailbreakFilterResult:"pi_and_jailbreak",raiFilterResult:"rai",sdpFilterResult:"sdp",virusScanFilterResult:"virus_scan"}[t]||t}function Em(t,e){if(Ke(t))for(const[n,i]of Object.entries(t)){if(!Ke(i))continue;const r=Ke(i.categories)?i.categories:{},s=Object.entries(r).filter(([,o])=>Ke(o)&&o.matched===!0).map(([o])=>o);s.length>0?s.forEach(o=>e.add(o)):i.matched===!0&&e.add(Th(n))}}function Sm(t,e){if(!t)return;const n=Array.isArray(t)?t.flatMap(i=>Ke(i)?Object.entries(i):[]):Object.entries(t);for(const[i,r]of n){if(!Yr(r))continue;const s=Th(i),o=r?.raiFilterResult?.raiFilterTypeResults||(s==="rai"?r?.raiFilterTypeResults:null),a=Ke(o)?Object.entries(o).filter(([,l])=>Yr(l)).map(([l])=>l):[];a.length>0?a.forEach(l=>e.add(l)):e.add(s)}}function xm(t){return su[t]?su[t]:String(t).replace(/([a-z])([A-Z])/g,"$1 $2").replace(/_/g," ").toLowerCase()}function ou(t){return t.length<=1?t[0]||"content that did not pass":t.length===2?`${t[0]} and ${t[1]}`:`${t.slice(0,-1).join(", ")}, and ${t.at(-1)}`}function km(t){const e=Rh(t);if(!e)return null;const n=new Set(Array.isArray(e.matchedFilters)?e.matchedFilters:[]);Em(e.filterSummary,n),Sm(e.filterResults,n);const i=e.blocked===!0||e.filterMatchState==="MATCH_FOUND"||n.size>0,r=e.invocationResult||null,s=va(e.filterSummary||e.filterResults);return!i&&!s&&!["PARTIAL","FAILURE"].includes(r)?null:{kind:i?"blocked":"unavailable",invocationResult:r,matchedFilters:[...n]}}function Im(t,e){const n=km(t);if(!n)return null;const i=[...new Set(n.matchedFilters.map(xm))],r=n.kind==="blocked",s=new Error(r?`Safety screening blocked this pipeline step for ${ou(i)}.`:"Safety screening could not be completed. Please try again.");return s.name="ModelArmorError",s.code=r?"MODEL_ARMOR_BLOCKED":"MODEL_ARMOR_UNAVAILABLE",s.isModelArmor=!0,s.pipelineStep=e,s.userTitle=r?"Request blocked for safety":"Safety check unavailable",s.userMessage=r?`The safety check detected ${ou(i)}. Edit your request to remove or rephrase the flagged content, then run the pipeline again.`:"The safety service did not finish all of its checks. Please wait a moment and run the pipeline again.",s.retryExplanation=r?"Trying another model would not change this safety decision.":"A fallback model was not attempted because safety screening must complete first.",s.matchedFilters=n.matchedFilters,s}function Cm(t){return String(t||"").replace(/\/\*[\s\S]*?\*\//g,"").replace(/\/\/[^\n]*/g,"")}function au(t){const e=/^(import|export|part|library|class|enum|extension|typedef|mixin|abstract|const|final|var|late)\b/,n=[];for(const i of Cm(t).split(` -`)){if(!/^[A-Za-z_$]/.test(i)||e.test(i))continue;const r=i.match(/^[\w$<>,?\s[\]]+?\s([a-zA-Z_$][\w$]*)\s*\(/);r&&n.push(r[1])}return n}function tl(t,e){const n=t.replace(/\.dart$/,"");if(e==="W")return n.replace(/(^|_)(\w)/g,(i,r,s)=>s.toUpperCase());if(e==="A"){const i=n.replace(/(^|_)(\w)/g,(r,s,o)=>o.toUpperCase());return i.charAt(0).toLowerCase()+i.slice(1)}return e==="F"?"CustomFunctions":e==="C"?t.endsWith(".dart")?t:`${t}.dart`:n}async function lu(t){const e=new TextEncoder().encode(String(t||"")),n=await globalThis.crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(n),i=>i.toString(16).padStart(2,"0")).join("")}async function Am(t,e=new Map){const n={},i=new Set;for(const[o,a]of t.entries()){if(a.type==="D"||a.type==="O")continue;const l=tl(o,a.type),u={old_identifier_name:l,new_identifier_name:l,type:a.type,is_deleted:!1,current_checksum:await lu(a.content)},c=e.get(a.path);if(c!==void 0&&(u.original_checksum=await lu(c)),n[o]=u,a.type==="F"){const d=au(a.content);(d.length>0?d:[a.functionName].filter(Boolean)).forEach(f=>i.add(f))}}const r=new Set(au(e.get("lib/flutter_flow/custom_functions.dart")||"")),s={functions_to_rename:[],functions_to_delete:[],functions_to_add:Array.from(i).filter(o=>!r.has(o))};return{fileMapContents:JSON.stringify(n),functionsMapContents:JSON.stringify(s)}}const Pm=new Set(["CustomWidget","CustomAction","CustomFunction","CustomClass","CodeFile"]),cu={CustomWidget:"custom_code/widgets/",CustomAction:"custom_code/actions/",CustomFunction:"flutter_flow/custom_functions.dart",CustomClass:"custom_code/",CodeFile:"custom_code/"},Fm=new Set(["void","dynamic","String","int","double","num","bool","Color","DateTime","DateTimeRange","LatLng","FFPlace","FFUploadedFile","DocumentReference","List"]),Rm=["Struct","Record"],Tm=[{id:"required-public-param",severity:"error",message:"CustomWidget constructor uses `required` on a parameter FlutterFlow can leave unset. FlutterFlow omits unset Define Parameters fields from the constructor call, so the widget will not compile when placed. Make the parameter optional and nullable (`this.value` with `final double? value`), or give it a constructor default (`this.value = 0.0`).",detect:t=>Ao(t).some(e=>/\brequired\s+this\.\w+/.test(e)),pos:"class W extends StatefulWidget { const W({required this.value}); final double value; }",neg:`class _P { const _P({required this.t}); final double t; } -class W extends StatefulWidget { const W({this.value}); final double? value; }`},{id:"non-nullable-public-field",severity:"error",message:"CustomWidget declares a non-nullable field with no constructor default. FlutterFlow omits unset Define Parameters fields, so the emitted call cannot supply it. Make the field nullable (`final double? value`) or give the parameter a default (`this.value = 0.0`).",detect:t=>Ao(t).some(e=>{const n=/^\s*final\s+(?:double|int|String|bool|Color|num)\s+(\w+)\s*;/gm;let i;for(;(i=n.exec(e))!==null;){const r=i[1];if(!(new RegExp(`this\\.${r}\\s*=(?!=)`).test(e)||new RegExp(`[:,]\\s*${r}\\s*=(?!=)`).test(e)))return!0}return!1}),pos:`class W extends StatefulWidget { - const W({required this.value}); - final double value; -}`,neg:`class _P { - const _P({required this.t}); - final double t; -} -class W extends StatefulWidget { - const W({this.value = 1.0}); - final double value; -}`},{id:"asset-without-anchor",severity:"warning",message:'CustomWidget calls Image.asset with a path arriving as a String parameter. An asset reaches the build only when a FlutterFlow widget NODE references it - a filename passed as a parameter does not count, so the image renders as a broken-image icon on device. "Download Unused Project Assets" does not fix it (FlutterFlow issues 522, 2271, 3799). Keep something in the UI referencing the file, or load it over the network instead.',detect:t=>/Image\.asset\s*\(/.test(t)&&/final\s+String\??\s+\w*[Pp]ath\b/.test(t),pos:`class W extends StatefulWidget { final String? imagePath; } -var x = Image.asset(widget.imagePath);`,neg:`class W extends StatefulWidget { final String? imagePath; } -var x = Image.network(widget.imagePath);`},{id:"unsupported-param-type",severity:"error",message:"CustomWidget exposes a Flutter data type FlutterFlow cannot express as a Define Parameter: TextStyle, BoxShadow, FontWeight, FontStyle, TextDirection, TextAlign, EdgeInsets, Offset, Alignment/AlignmentGeometry, Border, BorderRadius, BoxDecoration, BoxConstraints, BorderSide, Gradient, or ThemeData. FlutterFlow's supported data types (docs.flutterflow.io/resources/data-representation/data-types) are only int, double, bool, string, Color, Image, DateTime, Json, LatLng, and the FF objects, so this parameter cannot be configured in the editor and the widget will not place or compile. Expose primitives instead (color, fontSize as double?, fontWeight via a custom enum, doubles for spacing).",detect:t=>Ao(t).some(e=>/final\s+(TextStyle|BoxShadow|FontWeight|FontStyle|TextDirection|TextAlign|EdgeInsets|Offset|Alignment(?:Geometry)?|Border(?:Radius|Side)?|BoxDecoration|BoxConstraints|Gradient|LinearGradient|RadialGradient|ThemeData)\??\s+\w+\s*;/.test(e)),pos:`class W extends StatefulWidget { - const W({this.textStyle}); - final TextStyle? textStyle; - @override _S createState() => _S(); -} -class _S extends State { @override Widget build(BuildContext c) => const SizedBox(); }`,neg:`class W extends StatefulWidget { - const W({this.width}); - final double? width; - @override _S createState() => _S(); -} -class _S extends State { @override Widget build(BuildContext c) => Padding(padding: const EdgeInsets.all(8), child: const SizedBox()); }`}];function pt(t,e,n){return{artifactId:t.id,artifactName:t.artifactName,artifactType:t.artifactType,severity:e,message:n}}function Li(t){let e="",n=0;for(;n"&&(n--,n===0))return{inner:t.slice(e+1,i),end:i+1};return null}function Mm(t,e){const n=new RegExp(`class\\s+${e}\\b[^{]*\\{`).exec(t);if(!n)return null;let i=0;for(let r=n.index+n[0].length-1;rLm(t).usable);function Om(t=""){const e=Li(t);return Nm.filter(n=>n.detect(e)).map(({id:n,severity:i,message:r})=>({id:n,severity:i,message:r}))}function Bm(t){const e=[],n=t.matchAll(/\bFuture\b/g);for(const i of n){let r=i.index+6,s=null;const o=r;for(;ro;if(t[r]==="<"){const u=$m(t,r);if(!u||(s=u.inner.replace(/\s+/g," ").trim(),r=u.end,!/\s/.test(t[r]||"")))continue;for(;ruu(o.functionName)===i);if(r)return r;const s=o=>!o.functionName.startsWith("_");return n.find(s)||n[0]}function ps(t=""){return Array.from(Li(t).matchAll(/\b(?:class|enum)\s+([A-Za-z_]\w*)/g),e=>e[1])}function Dm(t="",e=""){return nl(t,e)?.returnType||null}function du(t){return String(t||"").replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2").toLowerCase()}function jm(t,e){const n=ps(e);if(n.length===0)return null;const r=String(t||"").split("/").pop().replace(/\.dart$/,"");if(n.some(l=>du(l)===r)||n.length>1)return null;const[o]=n,a=`${du(o)}.dart`;return`File name "${t}" does not match declared class "${o}". FlutterFlow accepts this, but naming the file "${a}" keeps the Code File recognisable in the editor.`}function il(t){return String(t||"").replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,"")}function Um(t,e,n=""){const i=nl(e,n)?.functionName;if(!i)return null;const r=String(t||"").split("/").pop(),s=tl(r,"A");if(s===i)return null;const o=`${il(i)}.dart`;return`File name "${r}" does not match Action "${i}". FlutterFlow derives the action from the file name, so it looks for "${s}" and reports Action "${s}" declaration not found. Rename the file to "${o}" - FlutterFlow puts an underscore before every capital - or rename the function to "${s}".`}function Hm(t="",e=""){return nl(t,e)!==null}function Wm(t,e=new Set){return(t?.match(/[A-Za-z_]\w*/g)||[]).filter(i=>Fm.has(i)?!1:!Rm.some(s=>i.endsWith(s))||e.has(i))}function qm(t,{functionName:e="",declaredTypes:n=new Set}={}){const i=Dm(t,e),r=Wm(i,n);if(r.length===0)return null;const[s]=r;let o;return n.has(s)?o=`uses Code File type "${s}", which FlutterFlow cannot process as an Action Return Value`:i===s?o="is not a FlutterFlow Action Return Value":o=`uses type "${s}", which is not a FlutterFlow Action Return Value`,`CustomAction return type "${i}" ${o}. Return JSON (Future) or an existing FlutterFlow Data Type (*Struct) instead.`}function zm(t,e={}){const n=[],i=t.fileName||"",r=t.code||"";if(Pm.has(t.artifactType)||n.push(pt(t,"error",`Unsupported artifact type "${t.artifactType}".`)),i.endsWith(".dart")||n.push(pt(t,"error","FlutterFlow custom code artifacts must use .dart files.")),!r.trim())return n.push(pt(t,"warning","Generated artifact has no Dart code yet.")),n;if(t.artifactType==="CustomWidget"){/class\s+\w+\s+extends\s+(StatelessWidget|StatefulWidget)/.test(r)||n.push(pt(t,"warning","CustomWidget code should declare a widget class extending StatelessWidget or StatefulWidget."));for(const s of Om(r))n.push(pt(t,s.severity,s.message))}if(t.artifactType==="CustomAction"&&!Hm(r,t.artifactName)&&n.push(pt(t,"warning","CustomAction code should expose an async Future function callable from FlutterFlow.")),t.artifactType==="CustomAction"){const s=e.declaredTypes||new Set(ps(r)),o=qm(r,{functionName:t.artifactName,declaredTypes:s});o&&n.push(pt(t,"error",o));const a=Um(i,r,t.artifactName);a&&n.push(pt(t,"error",a))}if(t.artifactType==="CustomFunction"&&/class\s+\w+\s+extends\s+(StatelessWidget|StatefulWidget)/.test(r)&&n.push(pt(t,"warning","CustomFunction should be a callable function, not a widget class.")),t.artifactType==="CustomClass"||t.artifactType==="CodeFile"){const s=jm(i,r);s&&n.push(pt(t,"info",s))}return n}function Vm(t){const e=Array.isArray(t?.artifacts)?t.artifacts:[],n=new Set(e.flatMap(s=>ps(s.code||""))),i=e.flatMap(s=>zm(s,{declaredTypes:n})),r=e.map(s=>({artifactId:s.id,fileName:s.fileName,pathHint:cu[s.artifactType]||cu.CodeFile}));return{valid:i.every(s=>s.severity!=="error"),findings:i,deployHints:r}}const hu="// DO NOT REMOVE OR MODIFY THE CODE ABOVE!";function fu(t){return(/^\s*import\s+['"]([^'"]+)['"]/.exec(t)||[])[1]||null}function Gm(t=""){const e=t.indexOf(hu);return e===-1?t:t.slice(e+hu.length).replace(/^\s*\n/,"")}const Km=/^\s*import\s+['"][^'"]+['"]\s*;\s*(?:\/\/.*)?$/;function Ym(t="",e=""){const n=Gm(t),i=new Set((e.match(/^\s*import .*$/gm)||[]).map(fu).filter(Boolean)),r=n.split(` -`).filter(s=>{const o=fu(s);return o===null||!i.has(o)?!0:!Km.test(s)}).join(` -`).replace(/^\s*\/\/ Automatic FlutterFlow imports\s*$/m,"").replace(/^\s*\n+/,"");return e+r}const Jm=new Set(["flutter","flutter_test","flutter_driver","flutter_localizations"]);function $h(t){let e="",n=0;for(;n{const i=n.name||n.package;if(!i||i==="flutter")return e;const r=n.versionRequired||n.required;return e[i]=r&&n.version||"",e},{})}function tv(t){const e=new Map,n=new Map,i=[];for(const r of t)e.has(r.fileName)?i.push(`Duplicate deploy file name "${r.fileName}" for artifacts "${e.get(r.fileName)}" and "${r.artifactId}".`):e.set(r.fileName,r.artifactId),n.has(r.path)?i.push(`Duplicate deploy path "${r.path}" for artifacts "${n.get(r.path)}" and "${r.artifactId}".`):n.set(r.path,r.artifactId);return i}function nv(t,e={}){const n=Array.isArray(t?.artifacts)?t.artifacts:[],r=(e.selectedArtifactIds||t?.deployOrder||n.map(f=>f.id)).map(f=>n.find(p=>p.id===f)).filter(Boolean),s=[...t?.warnings||[]];let o=[];r.forEach(f=>{const p=ev(f),g=f.fixedCode||f.code||"",m=f.codeType||Xm[f.artifactType]||Ve.OTHER;g.trim()||s.push(`${f.artifactName||f.id} has no generated code.`),o.push({artifactId:f.id,artifactName:f.artifactName,artifactType:f.artifactType,fileName:p,content:g,type:m,path:f.deployPath||Qm(p,m),deployPath:f.deployPath||"",deployMode:"customCodeSync"})});const a="lib/flutter_flow/custom_functions.dart",l=o.map((f,p)=>({entry:f,index:p})).filter(({entry:f})=>f.type===Ve.FUNCTION&&f.path===a);if(l.length>1){const f=l[0],p={...f.entry,artifactId:l.map(({entry:m})=>m.artifactId).join("+"),artifactName:f.entry.artifactName,content:l.map(({entry:m})=>`// ${m.artifactId} -${m.content}`).join(` - -`)},g=new Set(l.slice(1).map(({index:m})=>m));o=o.filter((m,v)=>!g.has(v)),o[f.index]=p}const u={...pu(t?.dependencies),...r.reduce((f,p)=>({...f,...pu(p.dependencies)}),{})},c={};r.forEach(f=>{rl(f.code||"").forEach(p=>{p in u||(c[p]="")})});const d={...c,...u},h=tv(o);return{bundleId:t?.id||"bundle-current",title:t?.title||"Generated artifact bundle",fileEntries:o,dependencies:d,relationships:t?.relationships||[],warnings:s,errors:h}}function iv(t){return String(t||"").match(/\bclass\s+([A-Z][A-Za-z0-9_]*)\b/)?.[1]}function rv(t){return String(t||"").split("/").pop().replace(/\.dart$/,"").split(/[^A-Za-z0-9]+/).filter(Boolean).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join("")}function sv(t,e){const i=[rv(t),iv(e.content),e.artifactName].find(r=>/^[A-Z][A-Za-z0-9_]*$/.test(String(r||"")));if(!i)throw new Error(`Cannot derive a FlutterFlow custom class name for ${t}.`);return i}function ov(t,e=new Map){const n=[];for(const[i,r]of t.entries())r.type!=="C"||e.has(r.path)||n.push({artifactId:r.artifactId||i,className:sv(i,r),content:r.content,fileName:i,path:r.path});return n}function av(t,e){const n=new Set(e.map(i=>i.path));return new Map(Array.from(t.entries()).filter(([,i])=>!n.has(i.path)))}const gu={pass:0,warning:1,fail:2},lv=["manualActions"];function Je(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function Lt(...t){for(const e of t){if(typeof e=="string"&&e.trim())return e.trim();if(Array.isArray(e)&&e.length>0){const n=e.filter(i=>typeof i=="string").join(` -`);if(n)return n}}return""}function mt(t){return t==null?[]:Array.isArray(t)?t:[t]}function cv(t){const e=Je(t).value??t;if(e==null||typeof e=="string"&&e.trim()==="")return null;const n=Number(e);if(Number.isFinite(n))return mu(n);const i=String(t||"").match(/\bscore\b[^\d]{0,12}(\d{1,3})(?:\s*\/\s*100)?/i);return i?mu(Number(i[1])):null}function mu(t){return t>=0&&t<=100?t:null}function Qe(t){return String(t||"").trim().replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function sl(t){const e=String(t||"").toLowerCase();return/(fail|error|critical|block|reject|invalid)/.test(e)?"fail":/(warn|attention|manual|partial|incomplete|concern)/.test(e)?"warning":/(pass|success|ready|approve|valid|clean|info|notice)/.test(e)?"pass":null}function _a(...t){return t.filter(Boolean).reduce((e,n)=>gu[n]>gu[e]?n:e,"pass")}function Mh(t,e="warning",n="review"){if(typeof t=="string")return{severity:e,message:t,suggestion:"",source:n};const i=Je(t),r=Lt(i.message,i.title,i.issue,i.description,i.summary);return r?{severity:sl(i.severity||i.status||i.level)||e,message:r,suggestion:Lt(i.suggestion,i.fix,i.recommendation,i.action),source:i.source||n}:null}function ya(t,e="review"){const n=Je(t);return[["findings","warning"],["issues","warning"],["criticalIssues","fail"],["errors","fail"],["warnings","warning"],["recommendations","warning"],["requiredFixes","fail"],["suggestions","warning"]].flatMap(([r,s])=>mt(n[r]).map(o=>Mh(o,s,e)).filter(Boolean))}function uv(t,e,n=null){if(typeof t=="string")return{id:`${n||"bundle"}-manual-${e+1}`,title:t,detail:"",location:"",timing:"unspecified",artifactId:n,source:"Code Review"};const i=Je(t),r=Lt(i.title,i.action,i.step,i.message,i.name,i.description);return r?{id:i.id||`${n||"bundle"}-manual-${e+1}`,title:r,detail:Lt(i.detail,i.instructions,i.description),location:Lt(i.location,i.flutterFlowPath,i.path),timing:Lt(i.timing,i.phase)||"unspecified",artifactId:n,source:Lt(i.source)||"Code Review"}:null}function wa(t,e=null){const n=Je(t);return lv.flatMap(i=>mt(n[i])).map((i,r)=>uv(i,r,e)).filter(Boolean)}function dv(t){let e=typeof t=="string"?ma(t):t;if(!e&&typeof t=="string")return{rawText:t,root:{}};const n=Je(e);typeof n.content=="string"&&(e=ma(n.content)||e);const i=Je(e),r=Je(i.reviewResult||i.codeReview||i.result);return{rawText:"",root:Object.keys(r).length?r:i}}function hv(t,e){const n=[e.id,e.fileName,e.artifactName].map(Qe);return t.find(i=>{const r=Je(i);return[r.id,r.fileName,r.artifactName,r.name].map(Qe).some(s=>s&&n.includes(s))})||null}function fv(t,e){return mt(t?.metadata?.compatibility?.deployHints).find(r=>Qe(r?.artifactId)===Qe(e.id)||Qe(r?.fileName)===Qe(e.fileName))?.pathHint||""}function pv(t,e){return mt(t?.relationships).filter(n=>Qe(n?.from)===Qe(e.id)||Qe(n?.to)===Qe(e.id))}function gv(t,e){return mt(t?.metadata?.compatibility?.findings).filter(n=>!n?.artifactId||Qe(n.artifactId)===Qe(e.id)).map(n=>Mh(n,"warning","Compatibility check")).filter(Boolean)}function mv(t,e,n,i){const r=hv(e,n),s=Je(r?.review||r||n.review),o=Object.keys(s).length>0,a=[...ya(s),...gv(t,n)],l=wa(s,n.id),u=sl(s.status||s.verdict||s.outcome||s.result),c=a.length?_a(...a.map(h=>h.severity)):null,d=_a(u,c,o?null:"warning");return{...n,index:i,status:d,statusReason:o?Lt(s.summary,s.overview,s.assessment,s.conclusion)||(a.length?`${a.length} review finding${a.length===1?"":"s"}`:"No file-level findings"):"No file-level verdict was returned",reviewComplete:o,findings:a,manualSteps:l,fixedSource:typeof s.fixedSource=="string"&&s.fixedSource.trim()?s.fixedSource.trim():null,pathHint:fv(t,n),relationships:pv(t,n)}}function vv({status:t,score:e,artifactPresentations:n,manualSteps:i}){const r=n.length;if(r===0&&i.length===0)return e==null?"Code review returned no overall summary and no score.":`Reviewed bundle with score ${e}/100.`;const s=n.reduce((a,l)=>(a[l.status]+=1,a),{pass:0,warning:0,fail:0}),o=[];return t&&o.push(`Overall verdict: ${t}.`),r&&o.push(`${r} artifact${r===1?"":"s"}: ${s.pass} pass, ${s.warning} warn, ${s.fail} fail.`),i.length&&o.push(`Do before deploy: ${i.map(a=>a.title).join("; ")}.`),e==null&&o.push("No numeric score (0-100) was returned."),o.join(" ")}function _v({bundle:t,reviewResult:e}){const n=Je(t),i=mt(n.artifacts),{root:r,rawText:s}=dv(e),o=[r.bundleReview,r.overallReview,r.overall,r.bundleSummary,r.summaryReview,r.review].map(Je).find(b=>Object.keys(b).length)||{},a=mt(r.artifacts||r.files||r.reviews),l=i.map((b,I)=>mv(n,a,b,I)),u=ya(r),d=[...ya(o),...u],h=[...wa(o),...wa(r),...l.flatMap(b=>b.manualSteps)].filter((b,I,A)=>A.findIndex(P=>P.title===b.title&&P.artifactId===b.artifactId)===I),f=sl(o.status||o.verdict||o.overallStatus||r.status||r.verdict||r.overallStatus||r.outcome),p=_a(f,...d.map(b=>b.severity),...l.map(b=>b.status)),g=o.score??r.score??r.overallScore??s,m=cv(g),v=Lt(o.headline,o.summary,o.executiveSummary,o.overview,o.assessment,o.conclusion,r.overallSummary,r.headline,r.summary,r.executiveSummary,r.overview,r.assessment,r.conclusion,s)||vv({status:p,score:m,artifactPresentations:l,manualSteps:h}),w=l.reduce((b,I)=>(b[I.status]+=1,b),{pass:0,warning:0,fail:0});return{title:n.title||"Generated artifact bundle",description:n.description||"",status:p,score:m,summary:v,findings:d,manualSteps:h,artifacts:l,counts:w,reviewCoverage:{reviewed:l.filter(b=>b.reviewComplete).length,total:l.length},deployOrder:mt(n.deployOrder),relationships:mt(n.relationships),warnings:mt(n.warnings),compatibility:Je(n.metadata?.compatibility)}}const yv=/^\uFEFF/;function di(t){let e=0,n=t.length;for(;ee&&!t[n-1].trim();)n--;return t.slice(e,n).join(` -`)}function wv(t){const e=String(t??"").replace(yv,"");if(!e.trim())return"";const n=e.split(` -`),i=c=>{const d=c.trim();return/^`{3,}[A-Za-z0-9+#_.-]*$/.test(d)?c.length-c.trimStart().length:-1};let r=0,s=-1;const o=[];{let c=0;for(let d=0;d=0&&(r++,s<0&&(s=d),o.push(c+h)),c+=n[d].length+1}}if(r===0)return di(n);{const c=ba(e);if(!c.error&&o.every(h=>_u(h,c.commentAndStringRanges)))return di(n)}if(r===1){const c=di(n.slice(0,s)),d=di(n.slice(s+1));return d.length>=c.length?d:c}const a=[];let l=null;for(let c=0;cc.length>0);return u.length===0?"":u.join(` - -`)}function bv(t){return String(t??"").replace(/\/\*[\s\S]*?\*\//g," ").replace(/\/\/[^\n]*/g,"").replace(/'''[\s\S]*?'''/g,'""').replace(/"""[\s\S]*?"""/g,'""').replace(/'(?:\\.|[^'\\\n])*'/g,'""').replace(/"(?:\\.|[^"\\\n])*"/g,'""')}function Lh(t){const e=bv(t);return Array.from(e.matchAll(/class\s+([A-Z]\w*)\s+extends\s+[A-Za-z_]\w*Widget\b/g),n=>n[1])}function Nh(t){return`${il(t)}.dart`}function Ev(t){return tl(t,"W")}const vu={"(":")","[":"]","{":"}"},Sv={")":"(","]":"[","}":"{"},xv=/[A-Za-z0-9_]/;function ba(t){const e=[{kind:"code",opener:null,openedLine:0}],n=[];let i=1,r=0;const s=(c,d)=>{(c===` -`||c==="\r"&&d!==` -`)&&i++};let o=null;const a=()=>{for(const c of e)(c.kind==="string"||c.kind==="block-comment"||c.kind==="line-comment")&&n.push({start:c.startIndex,end:t.length})};for(;r0?t[r-1]:"",p=r>1?t[r-2]:"",g=(f==="r"||f==="R")&&!xv.test(p);e.push({kind:"string",quote:c,triple:h,raw:g,startIndex:r,openedLine:i}),r+=h?3:1;continue}if(vu[c]){e.push({kind:"code",opener:c,openedLine:i}),r++;continue}if(Sv[c]){if(d.interpolation&&c==="}"){e.pop(),r++;continue}if(d.opener&&vu[d.opener]===c){e.pop(),r++;continue}return d.opener?(a(),{error:o??`line ${i}: "${c}" closes nothing - "${d.opener}" opened on line ${d.openedLine} is still open`,commentAndStringRanges:n}):(a(),{error:o??`line ${i}: unexpected "${c}" with no matching opener`,commentAndStringRanges:n})}s(c,t[r+1]),r++}a();let l=e.length-1;for(;l>0&&e[l].kind==="line-comment";)l--;let u=o;if(!u){const c=e[l];if(!(c.kind==="code"&&!c.opener&&!c.interpolation))if(c.kind==="string")u=`unclosed ${c.triple?"triple-quoted ":""}string starting on line ${c.openedLine} was never closed`;else if(c.kind==="block-comment")u=`unterminated /* comment starting on line ${c.openedLine}`;else if(c.interpolation){const d=e.findLast(f=>f.opener);u=`unclosed "\${" expression${d?` opened on line ${d.openedLine}`:""} was never closed`}else u=`"${c.opener}" opened on line ${c.openedLine} is never closed`}return{error:u,commentAndStringRanges:n}}function kv(t){return ba(String(t??"")).error}function _u(t,e){return e.some(({start:n,end:i})=>t>=n&&ttypeof n=="string"?n:n?.errorMessage).filter(Boolean);return e.length>0?e.join("; "):JSON.stringify(t)}return t&&typeof t=="object"?t.errorMessage||JSON.stringify(t):String(t??"")}const Iv=["gmail.com","googlemail.com","outlook.com","hotmail.com","live.com","msn.com"],Cv="MAGIC_LINK_SENT",Av="PLUS_ALIAS_REJECTED",Pv="Please enter your primary email address. Plus aliases (such as {email}) are not allowed for {domain} accounts.",gs={allowlistedDomains:Iv,successCode:Cv,validationCode:Av,messageTemplate:Pv},Fv=new Set(gs.allowlistedDomains),Rv=gs.successCode,_r=gs.validationCode;function ms(t){return typeof t=="string"?t.trim():""}function Tv(t){const e=ms(t),n=e.lastIndexOf("@");if(n<=0||n===e.length-1)return!1;const i=e.slice(0,n),r=e.slice(n+1).toLowerCase();return Fv.has(r)?i.includes("+"):!1}function $v(t,e){return gs.messageTemplate.replaceAll("{email}",t).replaceAll("{domain}",e)}function Bh(t){if(!Tv(t))return null;const e=ms(t),n=e.lastIndexOf("@"),i=e.slice(n+1).toLowerCase();return $v(e,i)}function Mv(t,e){return t?.code===_r?t.message||Bh(e)||"Please enter your primary email address.":t?.code===Rv||!t?.code?`Check your email — we sent a link to ${ms(e)}`:t.message||"Something went wrong. Please try again."}const Lv=/^dependencies\s*:\s*(?:#.*)?$/,Nv=/^(?:"([^"]+)"|'([^']+)'|([A-Za-z_][A-Za-z0-9_-]*))\s*:/;function vs(t){const e=t.match(Nv);return e?e[1]??e[2]??e[3]:null}function Ui(t){const e=t.trim();return e===""||e.startsWith("#")}function Xn(t){const e=t.match(/^(\s*)/);return e?e[1].length:0}function ol(t,e){const n=t.findIndex(s=>e.test(s));if(n===-1)return null;let i=n,r=null;for(let s=n+1;s=0.0.0"}`}function jv(t,e={}){const n=String(t||""),i=Object.entries(e).filter(([u])=>u&&u!=="flutter");if(i.length===0)return{yaml:n,added:[],alreadyPresent:[]};const r=n.split(` -`),s=new Set(jh(n)),o=[],a=[];for(const[u,c]of i)s.has(u)?a.push(u):(o.push([u,c]),s.add(u));if(o.length===0)return{yaml:n,added:[],alreadyPresent:a};const l=al(r);if(l){const u=o.map(([c,d])=>yu(l.childIndent,c,d));r.splice(l.endIndex,0,...u)}else r.length>0&&r[r.length-1].trim()!==""&&r.push(""),r.push("dependencies:"),o.forEach(([u,c])=>{r.push(yu(" ",u,c))});return{yaml:r.join(` -`),added:o.map(([u])=>u),alreadyPresent:a}}function Uv(t,e={}){const n=String(t||""),i=Object.entries(e).filter(([l])=>l&&l!=="flutter");if(i.length===0)return{yaml:n,overridden:[],skipped:[]};const r=n.split(` -`),s=ys(n),o=[],a=[];for(const[l,u]of i){const c=s.get(l);if(!c||!c.isScalar||!String(u||"").trim()){a.push(l);continue}const d=" ".repeat(Xn(r[c.lineIndex]));r[c.lineIndex]=`${d}${l}: ${Hh(String(u).trim())}${c.comment}`,o.push({name:l,from:c.constraint,to:u})}return{yaml:r.join(` -`),overridden:o,skipped:a}}function Wh(t){const e=String(t||""),n=[];return e.trim()?(/^name:\s*\S+/m.test(e)||n.push("pubspec.yaml missing name field"),al(e.split(` -`))||n.push("pubspec.yaml missing dependencies section"),jh(e).includes("flutter")||n.push("pubspec.yaml missing Flutter SDK dependency"),{valid:n.length===0,errors:n}):(n.push("pubspec.yaml is empty"),{valid:!1,errors:n})}const Hv=">=3.0.0 <4.0.0";function Ea(t){const e=String(t||"").trim(),n=e[0];return n!=="'"&&n!=='"'||e[e.length-1]!==n?e:e.slice(1,-1).replaceAll(`${n}${n}`,n)}function Wv(t=""){const e=Zm(t).filter(n=>!n.startsWith("dart:")&&!n.startsWith("package:"));return{selfContained:e.length===0,unresolvableImports:e}}function wu(t,e,n){const i=[];for(const[r,s]of t){if(s.isScalar){e[r]=Ea(s.constraint);continue}if(s.sourceKey==="sdk"){n.add(r);continue}if(s.sourceKey===null&&s.version){e[r]=Ea(s.version);continue}i.push(r)}return i}function qv(t){const e=new Set,n={},i={},r=wu(ys(t),n,e);r.push(...wu(Bv(t,"dependency_overrides"),i,e));const s=new Set([...Object.keys(n),...e]),{sdk:o}=Uh(t);return{sdkConstraint:Ea(o)||Hv,dependencies:n,overrides:i,sdkPackages:[...e].sort(),availablePackages:s,unrepresentable:r}}function zv(t,e,n){return e.length>0?`${t} imports ${e.join(", ")}, which FlutterFlow only generates once the app is built, so it could not be compiled before the deploy.`:`${t} imports ${n.join(", ")}, which your project's pubspec.yaml does not declare with a version constraint, so it could not be compiled before the deploy.`}function Vv(t,e){const{sdkConstraint:n,dependencies:i,overrides:r,sdkPackages:s,availablePackages:o,unrepresentable:a}=qv(e),l={sdkConstraint:n,dependencies:i,overrides:r,sdkPackages:s},u=[],c=[],d=a.map(h=>`Your project declares ${h} from a source that cannot be reproduced outside it, so the pre-deploy compile check runs against a scratch package graph that omits ${h}. Classes that do not import ${h} directly are still checked, but against that reduced graph, so their transitive package resolution may differ from your project's and the check is approximate for them.`);for(const h of t){const{className:f,content:p}=h,g=rl(p),m=g.filter(b=>a.includes(b));if(m.length>0){c.push({className:f,reason:`${f} was not compiled before deploying: it imports ${m.join(", ")}, which your project declares from a source that cannot be reproduced outside it, so package resolution could not be matched exactly.`});continue}const{unresolvableImports:v}=Wv(p),w=g.filter(b=>!o.has(b));if(v.length>0||w.length>0){c.push({className:f,reason:zv(f,v,w)});continue}u.push({fileName:`${il(f)}.dart`,content:p})}return{manifest:l,sources:u,skipped:c,approximate:d}}function bu(t,e){const n=`${t}${e}`.split(` -`),i=n.pop()??"",r=[];for(const s of n){const o=qh(s);o&&r.push(o)}return{events:r,buffer:i}}function Gv(t){const e=qh(t);return e?[e]:[]}function qh(t){const e=t.trim();if(!e)return null;try{const n=JSON.parse(e);return n&&typeof n=="object"&&!Array.isArray(n)?n:null}catch{return null}}async function Kv(t,e={}){const{onPhase:n,onLog:i}=e;let r=null,s="";const o=a=>{if(a.event==="phase"){a.message&&n&&n(a.message);return}if(a.event==="log"){a.message&&i&&i(a.message);return}r=a};if(t.body?.getReader){const a=t.body.getReader(),l=new TextDecoder;for(;;){const{done:u,value:c}=await a.read();if(u)break;const d=bu(s,l.decode(c,{stream:!0}));s=d.buffer,d.events.forEach(o)}}else{const a=bu("",await t.text());s=a.buffer,a.events.forEach(o)}return Gv(s).forEach(o),r?{...r,success:r.success===!0||r.success===void 0&&t.ok}:{success:!1,error:t.ok?"The FlutterFlow deploy runner closed the connection before it finished.":`FlutterFlow custom class provisioning failed (HTTP ${t.status}).`}}function Yv(){let t=document.getElementById("fx-grid");if(!t)return null;const e=window.matchMedia("(prefers-reduced-motion: reduce)"),n=window.matchMedia("(pointer: none)");let i=t.getContext("webgl2",{alpha:!0,antialias:!1,depth:!1,stencil:!1,premultipliedAlpha:!0,powerPreference:"low-power"}),r=i?null:t.getContext("2d");if(!i&&!r)return null;const s='',o=`#version 300 es -in vec2 p; void main(){ gl_Position = vec4(p, 0.0, 1.0); }`;function a(){return["#version 300 es","precision highp float;","out vec4 o;","uniform vec2 res;","uniform vec2 design;","uniform vec2 mouse;","uniform float energy;","uniform float parallax;","uniform float t;","uniform vec3 ink;","uniform sampler2D mark;","uniform vec2 rot;","const float WARP_A = 0.0032;","void main(){"," vec2 px = gl_FragCoord.xy * (design / res);"," vec2 p = vec2(px.x, design.y - px.y);"," vec2 off = vec2(0.0, -parallax) + vec2(sin(t * 0.11), cos(t * 0.09)) * 7.0;"," vec2 g = p + off;"," vec2 gm = mouse + off;"," float base = min(design.x, design.y);"," float spacing = clamp(base / 10.0, 64.0, 118.0);"," vec2 rel = g - gm;"," float rho = length(rel) + 1e-5;"," vec2 dir = rel / rho;"," vec2 pw = gm + dir * (rho + WARP_A * rho * rho);"," vec2 cell = floor(pw / spacing);"," vec2 cw = (cell + 0.5) * spacing - gm;"," float Rc = length(cw) + 1e-5;"," float rhoC = (-1.0 + sqrt(1.0 + 4.0 * WARP_A * Rc)) / (2.0 * WARP_A);"," vec2 c = gm + (cw / Rc) * rhoC;"," float cellSize = spacing / (1.0 + 2.0 * WARP_A * rhoC);"," float sigma = spacing * 2.9;"," float f = exp(-(rhoC * rhoC) / (2.0 * sigma * sigma));"," float scale = mix(0.32, 1.42, f);"," float weight = smoothstep(0.06, 0.80, f);"," float hs = cellSize * 0.26 * scale;"," vec2 uv = (g - c) / hs;"," vec2 ruv = mat2(rot.x, rot.y, -rot.y, rot.x) * uv;"," float cov = 0.0;"," if (abs(ruv.x) <= 1.0 && abs(ruv.y) <= 1.0) cov = texture(mark, ruv * 0.5 + 0.5).a;"," float s = cov * weight * energy * 0.26;"," o = vec4(ink * s, s);","}"].join(` -`)}let l=null,u,c,d,h,f,p,g,m,v;function w(q,U){if(!i)return null;const L=i.createShader(q);return i.shaderSource(L,U),i.compileShader(L),i.getShaderParameter(L,i.COMPILE_STATUS)?L:(window.console&&console.warn("fx-grid shader: "+i.getShaderInfoLog(L)),null)}if(i){const q=w(i.VERTEX_SHADER,o),U=w(i.FRAGMENT_SHADER,a());if(q&&U&&(l=i.createProgram(),i.attachShader(l,q),i.attachShader(l,U),i.linkProgram(l),i.getProgramParameter(l,i.LINK_STATUS)||(window.console&&console.warn("fx-grid link: "+i.getProgramInfoLog(l)),l=null)),l){i.useProgram(l),i.bindBuffer(i.ARRAY_BUFFER,i.createBuffer()),i.bufferData(i.ARRAY_BUFFER,new Float32Array([-1,-1,3,-1,-1,3]),i.STATIC_DRAW);const L=i.getAttribLocation(l,"p");i.enableVertexAttribArray(L),i.vertexAttribPointer(L,2,i.FLOAT,!1,0,0),u=i.getUniformLocation(l,"res"),c=i.getUniformLocation(l,"design"),d=i.getUniformLocation(l,"mouse"),h=i.getUniformLocation(l,"energy"),f=i.getUniformLocation(l,"parallax"),p=i.getUniformLocation(l,"t"),g=i.getUniformLocation(l,"ink"),m=i.getUniformLocation(l,"mark"),v=i.getUniformLocation(l,"rot"),i.enable(i.BLEND),i.blendFunc(i.ONE,i.ONE_MINUS_SRC_ALPHA),i.clearColor(0,0,0,0)}else{i=null;const L=t.cloneNode(!1);if(t.parentNode.replaceChild(L,t),t=L,r=t.getContext("2d"),!r)return null}}function b(q){if(!q)return null;const U=/^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(q);if(U){let L=U[1];return L.length===3&&(L=L[0]+L[0]+L[1]+L[1]+L[2]+L[2]),[parseInt(L.slice(0,2),16)/255,parseInt(L.slice(2,4),16)/255,parseInt(L.slice(4,6),16)/255]}try{const L=document.createElement("canvas");L.width=1,L.height=1;const se=L.getContext("2d");se.fillStyle="rgb(9, 8, 7)";const ye=String(se.fillStyle);se.fillStyle=q;const Ce=String(se.fillStyle);if(Ce===ye)return null;const it=/^#([0-9a-f]{6})$/i.exec(Ce);if(it){const rt=it[1];return[parseInt(rt.slice(0,2),16)/255,parseInt(rt.slice(2,4),16)/255,parseInt(rt.slice(4,6),16)/255]}const kt=/rgba?\(\s*([\d.]+)[,\s]+([\d.]+)[,\s]+([\d.]+)/i.exec(Ce);if(kt)return[Number(kt[1])/255,Number(kt[2])/255,Number(kt[3])/255]}catch{}return null}function I(){let q="";try{const U=getComputedStyle(document.documentElement);q=(U.getPropertyValue("--fx-ink")||"").trim()||(U.getPropertyValue("--fg")||"").trim()}catch{}return b(q)||[.56,.68,.88]}const A=I();let P=1920,O=1080,S=960,F=540,R=960,M=540,$=.66,N=0,Y=-1e9,V=!1,H=0,J=0,fe=null,Ae=!1,ve=!1,xe=!1;const Fe=64,ie=15.2;let we=0,_e=0;const Le=.0032,ut=0,ce=.56,qe=.26,dt=.32,sn=.16,Pe=.349;let Ie=ut;function Et(){const q=t.getBoundingClientRect(),U=t.clientWidth,L=t.clientHeight;if(!q.width||!U||!L)return;const se=Math.min(window.devicePixelRatio||1,2),ye=Math.max(.2,Math.min(2,q.width/U*se)),Ce=Math.max(2,Math.round(U*ye)),it=Math.max(2,Math.round(L*ye));(Ce!==t.width||it!==t.height)&&(t.width=Ce,t.height=it,i&&i.viewport(0,0,Ce,it)),P=U,O=L,V||(S=R=P/2,F=M=O/2,V=!0)}function kn(q){!l||!Ae||!i||(i.uniform2f(u,t.width,t.height),i.uniform2f(c,P,O),i.uniform2f(d,S,F),i.uniform1f(h,$),i.uniform1f(f,N),i.uniform2f(v,Math.cos(Ie),Math.sin(Ie)),i.uniform1f(p,q),i.uniform3f(g,A[0],A[1],A[2]),i.clear(i.COLOR_BUFFER_BIT),i.drawArrays(i.TRIANGLES,0,3))}function je(q,U,L){const se=Math.max(0,Math.min(1,(L-q)/(U-q)));return se*se*(3-2*se)}function In(q){if(!fe||!r)return;const U=r;U.setTransform(1,0,0,1,0,0),U.clearRect(0,0,t.width,t.height);const L=t.width/P;U.setTransform(L,0,0,L,0,0),U.globalAlpha=1;const se=Math.min(P,O),ye=Math.max(64,Math.min(118,se/10)),Ce=ye*2.9,it=2*Ce*Ce,kt=Math.sin(q*.11)*7,rt=Math.cos(q*.09)*7-N,zi=S+kt,Vi=F+rt,qs=Ce*Math.sqrt(2*Math.log(1/.06)),ei=qs+Le*qs*qs+ye,Mf=Math.floor((zi-ei)/ye)-1,Lf=Math.ceil((zi+ei)/ye)+1,Nf=Math.floor((Vi-ei)/ye)-1,Of=Math.ceil((Vi+ei)/ye)+1;for(let zs=Nf;zs<=Of;zs++){const Bf=(zs+.5)*ye;for(let Vs=Mf;Vs<=Lf;Vs++){const Gs=(Vs+.5)*ye-zi,Ks=Bf-Vi,Ys=Math.sqrt(Gs*Gs+Ks*Ks)+1e-5;if(Ys>ei)continue;const Gi=(-1+Math.sqrt(1+4*Le*Ys))/(2*Le),Wl=Math.exp(-(Gi*Gi)/it),ql=je(.06,.8,Wl)*$*.26;if(ql<.004)continue;const Kt=ye/(1+2*Le*Gi)*.26*(.32+1.1*Wl),zl=Gi/Ys,Js=zi+Gs*zl,Zs=Vi+Ks*zl;Js<-Kt*1.6||Js>P+Kt*1.6||Zs<-Kt*1.6||Zs>O+Kt*1.6||(U.globalAlpha=ql,U.save(),U.translate(Js,Zs),U.rotate(Ie),U.drawImage(fe,-Kt,-Kt,Kt*2,Kt*2),U.restore())}}U.globalAlpha=1}function St(q){if(!ve)return;const U=J?Math.min(.05,(q-J)/1e3):.016;J=q;const se=q-Y>2400?.6:1;$+=(se-$)*Math.min(1,U*3.2);const ye=Math.min(.05,U);we+=((R-S)*Fe-we*ie)*ye,_e+=((M-F)*Fe-_e*ie)*ye,S+=we*ye,F+=_e*ye,N=(window.scrollY||window.pageYOffset||0)*.55;const Ce=q/1e3,it=S/(P||1)-.5,kt=F/(O||1)-.5;let rt=it*(it>=0?ce:qe)+kt*(kt>=0?dt:sn);rt>Pe?rt=Pe:rt<-Pe&&(rt=-Pe),Ie=ut+rt-N*6e-4,Et(),i?kn(Ce):In(Ce),H=requestAnimationFrame(St)}function xt(q){if(!ve)return;const U=t.getBoundingClientRect();!U.width||!P||!O||(R=(q.clientX-U.left)/U.width*P,M=(q.clientY-U.top)/U.height*O,Y=performance.now())}function nt(){ve||Ws||e.matches||n.matches||!xe||document.hidden||(ve=!0,J=0,H=requestAnimationFrame(St))}function Gt(){ve=!1,H&&(cancelAnimationFrame(H),H=0),J=0}function Qn(){e.matches?(Gt(),t.classList.remove("is-ready")):xe&&nt()}function Cn(){n.matches?Gt():xe&&nt()}function jl(){document.hidden?Gt():xe&&nt()}const Ul=new IntersectionObserver(q=>{xe=q[0]?.isIntersecting||!1,xe?nt():Gt()},{threshold:0});Ul.observe(t),window.addEventListener("pointermove",xt,{passive:!0,capture:!0}),window.addEventListener("resize",Et),e.addEventListener("change",Qn),n.addEventListener("change",Cn),document.addEventListener("visibilitychange",jl);function $f(){const q=(s.match(/\sd="([^"]+)"/)||[])[1],U=document.createElement("canvas");U.width=256,U.height=256;const L=U.getContext("2d");if(q&&window.Path2D){const se=Math.min(8.533333333333333,8.421052631578947);L.setTransform(se,0,0,se,se+(256-30*se)/2,-6.4*se),L.fillStyle="rgb(255,255,255)",L.fill(new Path2D(q),"evenodd"),L.setTransform(1,0,0,1,0,0)}try{const se=L.getImageData(0,0,256,256),ye=se.data;for(let Ce=3;Ceve}}const Jv=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;function Ut(t){const e=String(t||"").trim().match(Jv);return e?{major:Number(e[1]),minor:Number(e[2]),patch:Number(e[3]),prerelease:e[4]?e[4].split("."):[]}:null}function Zv(t,e){if(t.length===0&&e.length===0)return 0;if(t.length===0)return 1;if(e.length===0)return-1;for(let n=0;n0)}function Qv(t){const e=Ut(t);return e?e.major>0?`${e.major+1}.0.0`:`0.${e.minor+1}.0`:null}function ll(t){let e=String(t??"").trim();if((e.startsWith("'")||e.startsWith('"'))&&(e=e.slice(1,-1).trim()),e===""||e==="any"||e==="*")return{min:null,minInclusive:!1,max:null,maxInclusive:!1};if(e.startsWith("^")){const o=e.slice(1).trim();return Ut(o)?{min:o,minInclusive:!0,max:Qv(o),maxInclusive:!1}:null}if(Ut(e))return{min:e,minInclusive:!0,max:e,maxInclusive:!0};const n={min:null,minInclusive:!1,max:null,maxInclusive:!1},i=/(>=|<=|>|<)\s*([0-9][0-9A-Za-z.+-]*)/g;let r=!1,s;for(;(s=i.exec(e))!==null;){const[,o,a]=s;if(!Ut(a))return null;r=!0,o===">="||o===">"?(n.min=a,n.minInclusive=o===">="):(n.max=a,n.maxInclusive=o==="<=")}return r?n:null}function Eu(t,e){const n=ll(t);if(!n||!Ut(e))return!1;if(n.min!==null){const i=Jr(e,n.min);if(i<0||i===0&&!n.minInclusive)return!1}if(n.max!==null){const i=Jr(e,n.max);if(i>0||i===0&&!n.maxInclusive)return!1}return!0}function e_(t,e){const n=ll(t);if(!n||!Ut(e))return!1;if(n.max===null)return!0;const i=Jr(n.max,e);return i>0?!0:i===0&&n.maxInclusive}function Tn(t){const e=ll(t);return e?e.min:null}const t_="https://pub.dev/api/packages/",n_=8e3;function i_(t,e={}){const{dartSdkFloor:n=null,flutterSdkFloor:i=null}=e,r=Array.isArray(t?.versions)?t.versions:[];let s=null;for(const o of r){const a=o?.version;if(!a||o.retracted||Xv(a))continue;const l=o.pubspec?.environment||{};n&&l.sdk&&!Eu(l.sdk,n)||i&&l.flutter&&!Eu(l.flutter,i)||(!s||Jr(a,s)>0)&&(s=a)}return s?{version:s,constraint:`^${s}`}:null}async function r_(t,e={}){const{dartSdkFloor:n=null,flutterSdkFloor:i=null,fetchImpl:r=fetch}=e;let s;try{const a=await r(`${t_}${encodeURIComponent(t)}`,{signal:AbortSignal.timeout(n_)});if(!a.ok)return{name:t,constraint:null,version:null,error:a.status===404?`"${t}" was not found on pub.dev`:`pub.dev returned ${a.status} for "${t}"`};s=await a.json()}catch(a){return{name:t,constraint:null,version:null,error:`could not reach pub.dev for "${t}" (${a.message})`}}const o=i_(s,{dartSdkFloor:n,flutterSdkFloor:i});return o?{name:t,...o,error:null}:{name:t,constraint:null,version:null,error:n?`no published "${t}" release supports Dart ${n}`:`no published "${t}" release could be read`}}async function s_(t,e={}){const n=await Promise.all(t.map(i=>r_(i,e)));return new Map(n.map(({name:i,...r})=>[i,r]))}async function o_(t,e={},n={}){const{resolveVersions:i=s_}=n,r=Object.entries(e).filter(([c])=>c&&c!=="flutter"),s=Uh(t),o={dartSdkFloor:Tn(s.sdk),flutterSdkFloor:Tn(s.flutter)},a={additions:{},overrides:{},kept:[],warnings:[],sdk:o};if(r.length===0)return a;const l=ys(t),u=[];for(const[c,d]of r){const h=l.get(c);if(!h){u.push(c);continue}const f=Tn(d);if(!f){a.kept.push({name:c,constraint:h.constraint});continue}if(!h.isScalar){a.warnings.push(`"${c}" is declared in your project from a git, path, or SDK source, but the generated code needs at least ${f}. Left as-is — update it yourself if the build fails.`),a.kept.push({name:c,constraint:h.constraint});continue}if(e_(h.constraint,f)){a.kept.push({name:c,constraint:h.constraint});continue}a.overrides[c]=`^${f}`,a.warnings.push(`"${c}" was pinned to ${h.constraint} in your project, which cannot resolve the ${f} the generated code needs. Raising it to ^${f} — this changes a dependency the rest of your app also uses.`)}if(u.length>0){const c=await i(u,o);for(const d of u){const h=c.get(d);if(h?.constraint){a.additions[d]=h.constraint;continue}const f=e[d]||"";if(Tn(f)){a.additions[d]=`^${Tn(f)}`,a.warnings.push(`Could not confirm "${d}" version on pub.dev (${h?.error||"lookup failed"}). Using ^${Tn(f)} from the AI's recommendation — verify this is current.`);continue}a.additions[d]=">=0.0.0",a.warnings.push(`Could not determine a version for "${d}" (${h?.error||"lookup failed"}) and the AI supplied none. Added with a wide-open >=0.0.0 constraint — pin a concrete version in FlutterFlow before deploying.`)}}return a}const a_={"&":"&","<":"<",">":">",'"':""","'":"'"};function Ht(t){return String(t??"").replace(/[&<>"']/g,e=>a_[e])}function W(t){return t?Ht(t).replace(/\n/g,"
    "):""}function Bt(t){return Ht(t).replace(/\r?\n/g," ")}function ws(t,e={}){const n=t?.pipelineStep;if(n!=null&&e[n]!=null)return e[n];const i=t?.message||"";return i.includes("Code Generator")?2:i.includes("Code Review")?3:1}function l_(t){if(!t)return{kind:"generic",title:"Generation failed",message:"An unknown error occurred. Please try again.",detail:"",canRetry:!0,canEdit:!0,canUpgrade:!1};if(t.isModelArmor){const n=t.code==="MODEL_ARMOR_BLOCKED";return{kind:"safety",title:t.userTitle||"Request blocked for safety",message:t.userMessage||t.message,detail:t.retryExplanation||"",canRetry:!n,canEdit:!0,canUpgrade:!1}}if(t.isUsageLimit)return{kind:"quota",title:"Monthly limit reached",message:t.message||"You've used all your generations for this period.",detail:"",canRetry:!1,canEdit:!1,canUpgrade:!0};const e=t.message||"";return/timed out after/i.test(e)?{kind:"timeout",title:"Request timed out",message:"The generation service took too long to respond.",detail:e,canRetry:!0,canEdit:!0,canUpgrade:!1}:/unreachable|failed to fetch|load failed|cors/i.test(e)?{kind:"network",title:"Connection problem",message:"We couldn't reach the generation service. Check your connection and try again.",detail:e,canRetry:!0,canEdit:!0,canUpgrade:!1}:{kind:"generic",title:"Generation failed",message:e||"An unexpected error occurred.",detail:"",canRetry:!0,canEdit:!0,canUpgrade:!1}}function c_(t){const e={"Integration Audit Report":"📋","Critical Issues":"❌",Warnings:"⚠️",Recommendations:"✅","Overall Score":"📊"};for(const[n,i]of Object.entries(e))if(t.toLowerCase().includes(n.toLowerCase()))return i;return"📄"}function u_(t){const e={critical:"❌",warning:"⚠️",recommendation:"✅",score:"📊",issue:"🔍",fix:"🔧"};for(const[n,i]of Object.entries(e))if(t.toLowerCase().includes(n.toLowerCase()))return i;return"📝"}function d_(t){return t.includes("class ")&&t.includes("extends ")||t.includes("StatelessWidget")||t.includes("StatefulWidget")||t.includes("import 'package:flutter/")?"dart":t.includes("def ")||t.includes("import ")||t.includes("print(")?"python":t.includes("function ")||t.includes("const ")||t.includes("console.")?"javascript":"dart"}function Kn(t){if(!t)return"";if(typeof t!="string")return String(t);const e=/```(?:\w+)?\n?([\s\S]*?)```/,n=t.match(e);return n?n[1].trim():t.trim()}function Su(t){return t=Ht(t),t=t.replace(/\*\*(.*?)\*\*/g,'$1'),t=t.replace(/\*(.*?)\*/g,'$1'),t=t.replace(/`(.*?)`/g,'$1'),t=t.replace(/\b(FAIL|ERROR|CRITICAL)\b/g,'$1'),t=t.replace(/\b(WARN|WARNING)\b/g,'$1'),t=t.replace(/\b(PASS|SUCCESS|OK)\b/g,'$1'),t}function zh(t,e="dart",n=globalThis.hljs){if(!t)return"";const i=Kn(t);try{return n.highlight(i,{language:e}).value}catch(r){console.warn("Syntax highlighting failed:",r);try{return n.highlight(i,{language:"json"}).value}catch{return Ht(i)}}}function bs(t,e={}){const{highlighter:n=globalThis.hljs}=e;let i='
    ';const r=String(t??"").split(` -`);let s=!1,o="";for(const a of r){if(a.startsWith("```")){if(s){const l=d_(o),u=zh(o.trim(),l,n);i+=`
    -
    ${u}
    -
    `,o="",s=!1}else s=!0;continue}if(s){o+=a+` -`;continue}if(a.startsWith("# ")){const l=a.substring(2).trim();i+=`
    -

    - ${c_(l)} - ${Ht(l)} -

    -
    `;continue}if(a.startsWith("## ")){const l=a.substring(3).trim();i+=`
    -

    - ${u_(l)} - ${Ht(l)} -

    -
    `;continue}if(/^[-*+]\s+/.test(a)||/^\d+\.\s+/.test(a)){const l=a.replace(/^([-*+]|\d+\.)\s+/,"").trim();i+=`
    - • - ${Su(l)} -
    `;continue}a.trim()!==""&&(i+=`

    ${Su(a)}

    `)}return i+="
    ",` -
    -
    -
    - Live Audit Report -
    - ${i} -
    - `}const h_="https://ccc-ffai-runner-y5cyj3473a-uw.a.run.app/deployCustomClasses";const lt="https://4tgke4.buildship.run",Vh={professional:"price_1T2ldCKszA2slvDXatdeCpbI",power:"price_1T2le9KszA2slvDXR4mPvw7M"},Zr="ccc_auth_session",xu=new WeakSet;let G={email:null,sessionToken:null,isVerified:!1};function Yn(t={}){return{tier:"free",status:"none",periodEnd:null,isLoading:!1,isResolved:!1,error:null,...t}}let be=Yn({isResolved:!0});const f_=`${lt}/service/runpipeline`,p_="bs_user_id",g_="bs_identity_token",m_=`${lt}/authUserCheck`;let st={userId:null,token:null,status:null,resolved:!1};const Xr={free:2,professional:50,power:2e3},Qr="ccc_subscription",ku=3,v_=new Set(["active","trialing","paid"]),es="google/gemini-3.7-flash",yr=["anthropic/claude-opus-5","openai/gpt-5.6-sol","z-ai/glm-5.2","moonshotai/kimi-k3","openrouter/auto-beta","openrouter/free","openrouter/deepseek/deepseek-v4-pro"],__={"google/gemini-3.7-flash":"Gemini 3.7 Flash","anthropic/claude-opus-5":"Claude Opus 5","openai/gpt-5.6-sol":"GPT-5.6 Sol","z-ai/glm-5.2":"GLM 5.2","moonshotai/kimi-k3":"Kimi K3","openrouter/auto-beta":"OpenRouter: Auto Router","openrouter/free":"OpenRouter: Free Models","openrouter/deepseek/deepseek-v4-pro":"DeepSeek v4 Pro"};function Jt(t){return __[t]||t}const y_=new Set(["google/gemini-3.7-flash","anthropic/claude-opus-5","openai/gpt-5.6-sol","z-ai/glm-5.2","moonshotai/kimi-k3","openrouter/auto-beta"]);function Gh(t){return y_.has(t)}const Sa=4,Po=8*1024*1024,w_="https://4tgke4.buildship.run/service/runpipeline-image";let wt=[];function b_(t){return new Promise(e=>{const n=new FileReader;n.onload=()=>e(n.result),n.onerror=()=>e(null),n.readAsDataURL(t)})}async function E_(t){const e=new FormData;return e.append("file",t),(await fetch(w_,{method:"POST",body:e})).json()}function S_(t){if(Array.isArray(t)){const e=t[0];if(e&&typeof e=="object")for(const n of Object.keys(e)){if(n==="item"||n==="index")continue;const i=e[n];if(i&&typeof i=="object"){if(typeof i.file=="string")return i.file;if(typeof i.url=="string")return i.url}if(typeof i=="string")return i}return""}return typeof t=="string"?t:t&&typeof t=="object"&&(t.url||t.fileUrl||t.file_url||t.downloadUrl||t.imageUrl||t.image_url||t.file)||""}async function x_(t){const e=Array.from(t.target.files||[]);if(!e.length)return;const n=e.filter(l=>l.size>Po);n.length&&ke(`Skipped ${n.length} image(s) over the ${(Po/1024/1024).toFixed(0)} MB limit.`,"warning");const i=e.filter(l=>l.size<=Po);if(!i.length){t.target.value="";return}const r=Sa-wt.length,o=i.slice(0,r).map(async l=>{const u=await b_(l);if(!u)return null;let c="";try{c=S_(await E_(l))}catch{c=""}return{dataUrl:u,name:l.name,url:c}}),a=(await Promise.all(o)).filter(Boolean);t.target.value="",!(a.length&&!Gh(document.getElementById("code-generator-model")?.value))&&(wt.push(...a),i.length>r&&ke(`You can attach up to ${Sa} images.`,"info"),Es())}function k_(t){wt.splice(t,1),Es()}function Es(){const t=document.getElementById("prompt-image-thumbnails"),e=document.getElementById("prompt-image-btn-label");t&&(t.innerHTML="",wt.forEach((n,i)=>{const r=document.createElement("div");r.className="prompt-img-thumb",r.innerHTML=`Prompt image`,t.appendChild(r)}),e&&(e.textContent=wt.length>=Sa?"Image limit reached":"Add images"))}function Kh(){const t=document.getElementById("prompt-image-upload");if(!t)return;const e=document.getElementById("code-generator-model"),n=Gh(e?.value);t.classList.toggle("hidden",!n),!n&&wt.length&&(wt=[],Es())}const yn="ccc_usage",Yh="google/gemini-3.7-flash",Jh="google/gemini-3.7-flash",or="google/gemini-3.7-flash",ar={professional:11,power:49},xa={en_US:"USD",en_GB:"GBP",en_AU:"AUD",en_NZ:"NZD",en_CA:"CAD",en_IN:"INR",en_SG:"SGD",en_HK:"HKD",en_PH:"PHP",en_ZA:"ZAR",en:"USD",de:"EUR",fr:"EUR",es:"EUR",it:"EUR",nl:"EUR",pt_PT:"EUR",pt_BR:"BRL",pt:"BRL",ja:"JPY",ko:"KRW",zh_CN:"CNY",zh_TW:"TWD",zh:"CNY",th:"THB",vi:"VND",id:"IDR",ms_MY:"MYR",ms:"MYR",sv:"SEK",nb:"NOK",da:"DKK",pl:"PLN",cs:"CZK",hu:"HUF",ro:"RON",tr:"TRY",ar:"AED",he:"ILS",ru:"RUB",uk:"UAH"},wr={AUD:1,USD:.65,EUR:.6,GBP:.52,CAD:.88,NZD:1.08,JPY:97,KRW:870,INR:54,SGD:.87,HKD:5.08,BRL:3.18,CNY:4.7,TWD:20.5,THB:22.5,VND:16200,IDR:10200,MYR:2.88,SEK:6.8,NOK:6.95,DKK:4.48,PLN:2.6,CZK:15.2,HUF:238,RON:2.98,TRY:20.9,AED:2.39,ILS:2.38,PHP:36.4,ZAR:11.8,RUB:58,UAH:26.8,CHF:.57,MXN:11.1,ARS:580,CLP:610,COP:2700,PEN:2.44};let br={...wr};async function I_(){const t=new AbortController,e=setTimeout(()=>t.abort(),5e3);try{const n=await fetch("https://open.er-api.com/v6/latest/AUD",{signal:t.signal});if(!n.ok)return;const i=await n.json();if(i.result!=="success"||!i.rates)return;const r=i.rates,s={AUD:1},o=new Set([...Object.keys(wr),...Object.values(ka),...Object.values(xa)]);for(const a of o)a!=="AUD"&&(typeof r[a]=="number"&&r[a]>0?s[a]=r[a]:wr[a]&&(s[a]=wr[a]));br=s}catch{}finally{clearTimeout(e)}}const ka={"America/Sao_Paulo":"BRL","America/Fortaleza":"BRL","America/Recife":"BRL","America/Bahia":"BRL","America/Belem":"BRL","America/Manaus":"BRL","America/Cuiaba":"BRL","America/Campo_Grande":"BRL","America/Araguaina":"BRL","America/Noronha":"BRL","America/Rio_Branco":"BRL","America/Porto_Velho":"BRL","America/Boa_Vista":"BRL","America/Maceio":"BRL","America/Santarem":"BRL","America/Eirunepe":"BRL","Europe/London":"GBP","Europe/Paris":"EUR","Europe/Berlin":"EUR","Europe/Madrid":"EUR","Europe/Rome":"EUR","Europe/Amsterdam":"EUR","Europe/Brussels":"EUR","Europe/Vienna":"EUR","Europe/Lisbon":"EUR","Europe/Dublin":"EUR","Europe/Helsinki":"EUR","Europe/Athens":"EUR","Europe/Bucharest":"RON","Europe/Budapest":"HUF","Europe/Warsaw":"PLN","Europe/Prague":"CZK","Europe/Copenhagen":"DKK","Europe/Stockholm":"SEK","Europe/Oslo":"NOK","Europe/Zurich":"CHF","Europe/Istanbul":"TRY","Europe/Moscow":"RUB","Europe/Kiev":"UAH","Europe/Kyiv":"UAH","Asia/Tokyo":"JPY","Asia/Seoul":"KRW","Asia/Shanghai":"CNY","Asia/Taipei":"TWD","Asia/Hong_Kong":"HKD","Asia/Singapore":"SGD","Asia/Kolkata":"INR","Asia/Calcutta":"INR","Asia/Bangkok":"THB","Asia/Ho_Chi_Minh":"VND","Asia/Jakarta":"IDR","Asia/Kuala_Lumpur":"MYR","Asia/Dubai":"AED","Asia/Jerusalem":"ILS","Asia/Tel_Aviv":"ILS","Asia/Manila":"PHP","Pacific/Auckland":"NZD","Australia/Sydney":"AUD","Australia/Melbourne":"AUD","Australia/Brisbane":"AUD","Australia/Perth":"AUD","Australia/Adelaide":"AUD","Australia/Hobart":"AUD","Australia/Darwin":"AUD","Australia/Lord_Howe":"AUD","America/Toronto":"CAD","America/Vancouver":"CAD","America/Edmonton":"CAD","America/Winnipeg":"CAD","America/Halifax":"CAD","America/St_Johns":"CAD","America/Regina":"CAD","America/New_York":"USD","America/Chicago":"USD","America/Denver":"USD","America/Los_Angeles":"USD","America/Phoenix":"USD","America/Anchorage":"USD","Pacific/Honolulu":"USD","America/Mexico_City":"MXN","America/Cancun":"MXN","America/Tijuana":"MXN","America/Argentina/Buenos_Aires":"ARS","America/Santiago":"CLP","America/Bogota":"COP","America/Lima":"PEN","Africa/Johannesburg":"ZAR"};function Zh(){try{const s=Intl.DateTimeFormat().resolvedOptions().timeZone;if(s&&ka[s])return ka[s]}catch{}const e=(navigator.language||"en-US").replace("-","_"),n=xa[e];if(n)return n;const i=e.split("_")[0],r=xa[i];return r||"USD"}function lr(t,e){const n=br[e]??br.USD,i=t*n,r=Math.round(i*100)/100;try{return new Intl.NumberFormat("en-US",{style:"currency",currency:e,minimumFractionDigits:0,maximumFractionDigits:r>=100||r%1===0?0:2}).format(r)}catch{return new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",minimumFractionDigits:0,maximumFractionDigits:2}).format(t*br.USD)}}const vt="ccc_api_key_",Dt="ccc_session_api_key_",bt="ccc_encryption_key",Ni="ccc_encryption_key_scope",C_="ccc_keystore",ts="keys",Oi="ccc_encryption_key_version";let Ia=null,ns=null,Bi=!1,is=!1,Iu=!1;class rs extends Error{constructor(){super("Secure browser key storage is unavailable."),this.name="CredentialStorageUnavailableError"}}function Cu(){if(Iu)return;Iu=!0;const t="Secure browser key storage is unavailable. Existing credentials were left untouched; new credentials will be available only in this tab session.";console.warn(t),document.body&&ke(t,"warning")}function Xh(){return localStorage.getItem(Oi)||""}function Ca(){return crypto.randomUUID?.()||ef(crypto.getRandomValues(new Uint8Array(16)))}function A_(){const t=Xh();if(t)return t;const e=Ca();return localStorage.setItem(Oi,e),e}function Jn(){Ia=null,ns=null,Bi=!1,is=!1}window.addEventListener("storage",t=>{t.key===Oi&&Jn()});function P_(){return new Promise((t,e)=>{const n=indexedDB.open(C_,1);n.onupgradeneeded=()=>{const i=n.result;i.objectStoreNames.contains(ts)||i.createObjectStore(ts)},n.onsuccess=()=>t(n.result),n.onerror=()=>e(n.error)})}async function cl(t,e){const n=await P_();return new Promise((i,r)=>{const s=n.transaction(ts,t);let o;try{o=e(s.objectStore(ts))}catch(l){n.close(),r(l);return}let a;o.onsuccess=()=>{a=o.result},o.onerror=()=>r(o.error),s.oncomplete=()=>{n.close(),i(a)},s.onerror=()=>{n.close(),r(s.error||new Error("Encryption key transaction failed."))},s.onabort=()=>{n.close(),r(s.error||new Error("Encryption key transaction aborted."))}})}function F_(t){return t instanceof CryptoKey&&t.algorithm?.name==="AES-GCM"&&t.extractable===!1&&t.usages.includes("encrypt")&&t.usages.includes("decrypt")}async function R_(){const t=await cl("readonly",e=>e.get(bt));return F_(t)?t:null}async function Qh(t){await cl("readwrite",e=>e.put(t,bt))}async function T_(){Jn();try{await cl("readwrite",t=>t.delete(bt))}catch(t){console.warn("Could not delete the stored encryption key:",t)}}async function $_(){const t=sessionStorage.getItem(bt);if(!t)return null;const e=await crypto.subtle.importKey("jwk",JSON.parse(t),{name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);return await Qh(e),sessionStorage.removeItem(bt),sessionStorage.removeItem(Ni),localStorage.removeItem(vt+"salt"),e}async function Au(t){const e=sessionStorage.getItem(bt);if(e)return is=sessionStorage.getItem(Ni)!=="session",crypto.subtle.importKey("jwk",JSON.parse(e),{name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);if(!t)throw new rs;const n=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!0,["encrypt","decrypt"]),i=await crypto.subtle.exportKey("jwk",n);return sessionStorage.setItem(bt,JSON.stringify(i)),sessionStorage.setItem(Ni,"session"),is=!1,crypto.subtle.importKey("jwk",i,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}async function M_(t){if(sessionStorage.getItem(Ni)==="session"&&sessionStorage.getItem(bt))return Cu(),Bi=!0,Au(t);try{const e=await R_();if(e)return e;const n=await $_();if(n)return n;const i=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);return await Qh(i),i}catch(e){return console.warn("IndexedDB encryption-key storage failed:",e),Cu(),Bi=!0,Au(t)}}async function ul(t={}){const{allowSessionFallbackCreation:e=!0}=t,n=A_();ns!==n&&Jn();const i=Ia||M_(e);Ia=i,ns=n;try{return await i}catch(r){throw Jn(),r}}async function L_(t){const e=await ul(),n=ns,i=new TextEncoder,r=crypto.getRandomValues(new Uint8Array(12)),s=await crypto.subtle.encrypt({name:"AES-GCM",iv:r},e,i.encode(t)),o=new Uint8Array(r.length+s.byteLength);return o.set(r),o.set(new Uint8Array(s),r.length),{ciphertext:ef(o),keyVersion:n,sessionFallback:Bi}}async function N_(t,e={}){const{isSessionCredential:n=!1}=e;try{const i=await ul({allowSessionFallbackCreation:!1});if(Bi&&!n&&!is)throw new rs;const r=O_(t),s=r.slice(0,12),o=r.slice(12),a=await crypto.subtle.decrypt({name:"AES-GCM",iv:s},i,o);return new TextDecoder().decode(a)}catch(i){if(i instanceof rs)throw i;return console.error("Decryption failed:",i),null}}function ef(t){const e=new Uint8Array(t);let n="";for(let i=0;i0}let Di="",ss="",ki=null,Fu=0;async function dl(){sessionStorage.getItem(bt)&&await ul(),Di=await Me("flutterflow"),ss=await Me("flutterflow_project_id"),H_(),rn()}function hl(){const t=document.getElementById("api-keys-modal");tt(t),pl(),Di&&sf(Di)}function tf(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("api-keys-modal");e&&ct(e);const n=document.getElementById("walkthrough-modal");n&&(fl(),tt(n))}let Wt=1;function nf(){const t=document.querySelector(".wt-steps");return t?Array.from(t.querySelectorAll(".wt-step-card")):[]}function Ss(){const t=nf();t.length&&t.forEach((e,n)=>{const i=n+1;if(i===Wt){e.classList.remove("opacity-60","bg-gray-50","border-gray-200"),e.classList.add("bg-blue-50","border-blue-200");const r=e.querySelector("div:first-child");r&&(r.classList.remove("bg-gray-400"),r.classList.add("bg-blue-500"),r.innerHTML=i)}else if(i0&&Wt<=t&&(Wt++,Ss())}function D_(){const t=document.getElementById("walkthrough-modal");t&&(Wt=1,Ss(),tt(t))}function j_(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("walkthrough-modal");e&&ct(e);const n=document.getElementById("walkthrough-dont-show");n&&n.checked&&localStorage.setItem("hasSeenWalkthrough","true")}function rf(){if(G.isVerified&&Vt()&&be.tier!=="free")return;if(!localStorage.getItem("hasSeenWalkthrough")){const e=document.getElementById("walkthrough-modal");e&&(Wt=1,Ss(),tt(e))}}async function pl(){const t=document.getElementById("flutterflow-api-key-input");Di?(t.value="",t.placeholder="Key saved (enter new to replace)"):t.placeholder="Enter your FlutterFlow API key",U_()}function U_(){Ru("flutterflow","flutterflow-key-status"),Ru("flutterflow_project_id","flutterflow-project-status")}function Ru(t,e){const n=document.getElementById(e);if(!n)return;const i=n.querySelector(".key-status-dot"),r=n.querySelector("span");Ln(t)?(i.className="key-status-dot configured",r.className="text-green-600",r.textContent="User key configured"):(i.className="key-status-dot missing",r.className="text-gray-500",r.textContent="Not configured")}function rn(){const t=y.step2Result&&y.step2Result.length>0,e=document.getElementById("btn-deploy-to-ff");e&&e.classList.toggle("hidden",!t)}function H_(){const t=document.getElementById("api-keys-status");if(!t)return;const e=t.querySelectorAll(".key-status-dot"),n=["flutterflow"];e.forEach((i,r)=>{const s=n[r];s==="flutterflow"?Ln("flutterflow")&&Ln("flutterflow_project_id")?(i.className="key-status-dot configured",i.title="FlutterFlow (Fully configured)"):Ln("flutterflow")||Ln("flutterflow_project_id")?(i.className="key-status-dot env",i.title="FlutterFlow (Partially configured)"):(i.className="key-status-dot missing",i.title="FlutterFlow (Not configured)"):Ln(s)?(i.className="key-status-dot configured",i.title=s.charAt(0).toUpperCase()+s.slice(1)+" (User key)"):(i.className="key-status-dot missing",i.title=s.charAt(0).toUpperCase()+s.slice(1)+" (Not configured)")}),rn()}async function W_(){const t=document.getElementById("flutterflow-api-key-input"),e=document.getElementById("flutterflow-projects-select");t.value.trim()&&await Pu("flutterflow",t.value);const n=e?.value.trim()||"";if(n){if(!xs(n)){ke("The selected FlutterFlow project has an unexpected ID format.","error"),e.focus();return}await Pu("flutterflow_project_id",n)}await dl(),pl();const i=document.querySelector("#api-keys-modal .bg-blue-500"),r=i.textContent;i.textContent="Saved!",i.classList.remove("bg-blue-500","hover:bg-blue-600"),i.classList.add("bg-green-500"),setTimeout(()=>{i.textContent=r,i.classList.remove("bg-green-500"),i.classList.add("bg-blue-500","hover:bg-blue-600"),tf()},1e3)}async function q_(){if(!confirm("Are you sure you want to clear all stored API keys?"))return;localStorage.setItem(Oi,Ca()),Jn(),localStorage.removeItem(vt+"flutterflow"),localStorage.removeItem(vt+"flutterflow_project_id"),sessionStorage.removeItem(Dt+"flutterflow"),sessionStorage.removeItem(Dt+"flutterflow_project_id"),sessionStorage.removeItem(bt),sessionStorage.removeItem(Ni),localStorage.removeItem(vt+"salt"),await T_(),localStorage.setItem(Oi,Ca()),localStorage.removeItem(vt+"flutterflow"),localStorage.removeItem(vt+"flutterflow_project_id"),sessionStorage.removeItem(Dt+"flutterflow"),sessionStorage.removeItem(Dt+"flutterflow_project_id"),await dl();const t=document.getElementById("flutterflow-projects-select");t&&(t.innerHTML=''),pl()}function xs(t){return!t||t.trim().length<5||t.includes(" ")?!1:/^[a-zA-Z0-9-]+$/.test(t)}function z_(t,e){const n=document.getElementById(t);n&&(n.value?e?n.style.borderColor="#22c55e":n.style.borderColor="#ef4444":n.style.borderColor="")}function V_(){const t=document.getElementById("flutterflow-api-key-input");t&&(t.addEventListener("input",e=>{const n=e.target.value.trim().length>0;z_("flutterflow-api-key-input",n)}),t.addEventListener("blur",G_(async e=>{const n=e.target.value.trim();n&&await sf(n)},500)))}function G_(t,e){let n;return function(...r){const s=()=>{clearTimeout(n),t(...r)};clearTimeout(n),n=setTimeout(s,e)}}async function sf(t){const e=document.getElementById("flutterflow-projects-select"),n=document.getElementById("flutterflow-projects-error");if(!e){console.error("Projects dropdown element not found");return}e.innerHTML='',n&&n.classList.add("hidden");try{const r=await new Wi(t,"").listProjects();if(!r||r.length===0){e.innerHTML='';return}e.innerHTML='',r.forEach(s=>{const o=document.createElement("option");o.value=s.id||s.projectId||"",o.textContent=s.name||s.projectName||`Project ${s.id}`,e.appendChild(o)}),ss&&(e.value=ss)}catch(i){console.error("Failed to fetch projects:",i),e.innerHTML='',n&&(n.textContent=`Failed to load projects: ${i.message}`,n.classList.remove("hidden"))}}function K_(t){const e=document.getElementById(t),i=e.nextElementSibling.querySelector("svg");e.type==="password"?(e.type="text",i.innerHTML=` - - `):(e.type="password",i.innerHTML=` - - - `)}let y={step1Result:null,step2Result:null,step3Result:null,bundleSpec:null,artifactBundle:null,bundleReview:null,selectedArtifactId:null,resultsViewMode:"summary",currentStep:0,isRunning:!1,runId:0,submittedPrompt:"",submittedImages:[]};function Y_(){y.step1Result=null,y.step2Result=null,y.step3Result=null,y.bundleSpec=null,y.artifactBundle=null,y.bundleReview=null,y.selectedArtifactId=null,y.resultsViewMode="summary"}function J_(){y.bundleSpec=Mi(y.step1Result,{artifactType:"CustomWidget",artifactName:"GeneratedWidget"})}function ks(){const t=Kr(y.bundleSpec);y.artifactBundle=Mi(y.step2Result,{id:y.bundleSpec?.id,title:y.bundleSpec?.title,description:y.bundleSpec?.description,artifactType:t.artifactType,artifactName:t.artifactName,fileName:t.fileName,dependencies:t.dependencies,relationships:y.bundleSpec?.relationships,code:y.step2Result||""});const e=Vm(y.artifactBundle);y.artifactBundle={...y.artifactBundle,warnings:[...y.artifactBundle.warnings,...e.findings.map(n=>n.message)],metadata:{...y.artifactBundle.metadata,compatibility:e}},y.selectedArtifactId=Kr(y.artifactBundle).id}function Is(){const t=Mi(y.step3Result,{id:y.artifactBundle?.id,title:y.artifactBundle?.title}),e=new Map(t.artifacts.map(i=>[i.id,i.review])),n=new Map(t.artifacts.filter(i=>{const r=i.review;return r&&typeof r.fixedSource=="string"&&r.fixedSource.trim()}).map(i=>[i.id,i.review.fixedSource.trim()]));y.bundleReview=Mi({id:y.artifactBundle?.id,title:y.artifactBundle?.title,artifacts:y.artifactBundle?.artifacts?.map(i=>{const r=n.get(i.id)||null;return{...i,review:e.get(i.id)||i.review||y.step3Result||null,...r?{fixedCode:r}:{}}})||[],relationships:y.artifactBundle?.relationships,warnings:y.artifactBundle?.warnings})}function of(){const t=gl();return{artifactType:t.artifactType||"CustomWidget",artifactName:t.artifactName||"GeneratedWidget",fileName:t.fileName||""}}function gl(){const t=y.artifactBundle||y.bundleSpec||null;return(Array.isArray(t?.artifacts)?t.artifacts:[]).find(n=>n.id===y.selectedArtifactId)||Kr(t)}function ml(){return gl().code||y.step2Result||""}async function Z_(){try{await dl()}catch(t){return console.error("checkConnection: initializeApiKeys failed:",t),!1}return!0}const Er={production:"https://api.flutterflow.io/v2/",staging:"https://api.flutterflow.io/v2-staging/"};function X_(t,e){const n=e?.trim()?` (${e.trim().slice(0,200)})`:"";return t===401?`Your FlutterFlow API key was rejected (401 Unauthorized)${n}. Re-enter a current key under API Keys settings, then try again.`:`Listing FlutterFlow projects was denied (403)${n}. The key may be scoped to sync a single project without list permission - verify the key's access in FlutterFlow, re-enter it under API Keys settings, then retry.`}class Wi{constructor(e,n,i="main",r=Er.production){this.apiKey=e,this.baseUrl=r,this._projectId=n,this._branchName=i,this._endpoint=r}get projectId(){return this._projectId}get branchName(){return this._branchName==="main"?"":this._branchName}async exportProjectZip(){console.log(`Exporting code from FlutterFlow project: ${this.projectId}, branch: ${this.branchName||"main"}`);const e=[{project:{path:`projects/${this.projectId}`},...this.branchName?{branch_name:this.branchName}:{},export_as_module:!1,include_assets_map:!1,format:!1,export_as_debug:!1},{project_id:this.projectId,branch_name:this.branchName,include_assets:!1,export_as_module:!1}];let n=null;for(const i of e)try{const r=await fetch(`${this.baseUrl}exportCode`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify(i)});if(!r.ok){const a=await r.text();n=new Error(`Export failed: ${r.status} - ${a}`);continue}const s=await r.json(),o=s?.value?.project_zip||s?.project_zip;if(!o){n=new Error("Export response did not include project source.");continue}return o}catch(r){n=r}throw n||new Error("Export failed for an unknown reason.")}async fetchProjectSource(){const e=await this.exportProjectZip(),n=await JSZip.loadAsync(e,{base64:!0}),i=Object.keys(n.files).filter(a=>!n.files[a].dir&&(a==="pubspec.yaml"||a.endsWith("/pubspec.yaml"))).sort((a,l)=>a.split("/").length-l.split("/").length)[0];if(!i)throw new Error("Export did not contain a pubspec.yaml.");const r=i.slice(0,i.length-12),s=new Map,o=Object.keys(n.files).filter(a=>{if(n.files[a].dir||!a.startsWith(r))return!1;const l=a.slice(r.length);return l==="lib/flutter_flow/custom_functions.dart"||l.startsWith("lib/custom_code/")&&l.endsWith(".dart")});return await Promise.all(o.map(async a=>{s.set(a.slice(r.length),await n.files[a].async("string"))})),{pubspecYaml:await n.files[i].async("string"),files:s}}async pushCodeWithRetry(e,n=3){const i=[Er.production,Er.staging],r=Math.max(0,i.indexOf(this._endpoint));for(let s=0;ssetTimeout(d,1e3*(s+1)));continue}return l}catch(l){console.warn(`Push to ${a} failed: ${l.message}, trying next...`),await new Promise(u=>setTimeout(u,1e3*(s+1)))}}throw new Error("All API endpoints failed after retries")}async pushCode(e){return this.pushCodeWithRetry(e)}parseProjectsResponse(e){if(e?.success&&typeof e.value=="string")try{const i=JSON.parse(e.value);if(i&&Array.isArray(i.entries))return i.entries.map(r=>({id:r.id,name:r.project?.name||r.id}))}catch(i){console.error("Failed to parse stringified project value:",i)}const n=e?.projects||e?.items||e?.entries||(Array.isArray(e)?e:[]);return Array.isArray(n)?n:[]}async listProjects(){console.log("Listing projects for API key");const e=[`${this.baseUrl}listProjects`,"https://api.flutterflow.io/v2/l/listProjects"];let n=0,i="";for(const r of e){const s=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify({project_type:"ALL",deserialize_response:!0})});if(s.ok)return r!==e[0]&&console.log(`listProjects answered on legacy path ${r}`),this.parseProjectsResponse(await s.json());if(n=s.status,i=await s.text(),console.warn(`listProjects via ${r} returned ${n}: ${i}`),s.status===401||s.status===403)throw new Error(X_(s.status,i));if(s.status!==404)throw new Error(`List projects failed: ${s.status} - ${i}`)}throw new Error(`List projects failed: ${n} - ${i}`)}}async function vl(t){const e=t.clone();let n;try{n=await t.json()}catch{const s=await e.text();if(!t.ok)return{success:!1,responseCode:t.status,errorMessage:s||`HTTP ${t.status}`,errorMap:new Map};throw new Error(`Invalid JSON response: ${s}`)}if(!t.ok){let r=n.message||`HTTP ${t.status}`,s=new Map;if(n.errors)s=new Map(Object.entries(n.errors));else if(!n.message&&typeof n=="object"){const o=Object.keys(n).filter(a=>a.endsWith(".dart")&&Array.isArray(n[a]));o.length>0&&(s=new Map(Object.entries(n)),r=o.flatMap(l=>n[l].map(u=>`${l}: ${u.errorMessage}`)).join(` -`)||`HTTP ${t.status}`)}return{success:!1,responseCode:t.status,errorMessage:r,errorMap:s}}let i={};if(n.value)try{i=typeof n.value=="string"?JSON.parse(n.value):n.value}catch(r){console.warn("Ignoring malformed push response value:",r)}return{success:!0,responseCode:t.status,errorMap:new Map(Object.entries(i))}}function _l(t,e){return{401:"Authentication failed. Please check your FlutterFlow API key.",403:"Access denied. You may not have permission to modify this project.",404:"Project not found. Please check your Project ID.",409:"Conflict detected. The project may have been modified elsewhere.",422:"Validation failed: Invalid request format",429:"Rate limit exceeded. Please try again in a few minutes.",500:"FlutterFlow server error. Please try again later.",503:"FlutterFlow service temporarily unavailable."}[t]||`FlutterFlow API error: ${`HTTP ${t}`}`}const z={ACTION:"A",WIDGET:"W",FUNCTION:"F",CODE_FILE:"C",DEPENDENCIES:"D",OTHER:"O"},af=/class\s+\w+\s+extends\s+(?:StatelessWidget|StatefulWidget)\b/,lf=/extends\s+State<\w+>/;function Q_(t,e=""){if(t==="pubspec.yaml")return z.DEPENDENCIES;if(!t.endsWith(".dart")||t.endsWith("index.dart"))return z.OTHER;if(t==="custom_functions.dart")return z.FUNCTION;if(e){const n=af.test(e),i=lf.test(e);if(n||i)return z.WIDGET;if(/^\s*Future(?:<[^>]+>)?\s+\w+\s*\(/m.test(e))return z.ACTION;if(e.match(/^\s*(String|int|double|bool|List|Map|dynamic|void)\s+\w+\s*\(/m))return z.FUNCTION}return z.CODE_FILE}function cf(t,e){switch(e){case z.ACTION:return`lib/custom_code/actions/${t}`;case z.WIDGET:return`lib/custom_code/widgets/${t}`;case z.FUNCTION:return"lib/flutter_flow/custom_functions.dart";case z.CODE_FILE:return`lib/custom_code/${t}`;case z.DEPENDENCIES:return"pubspec.yaml";case z.OTHER:return`lib/custom_code/${t}`;default:return t}}async function yl(t,e=new Map){return Am(t,e)}const Aa=new Map;function uf(t){return`${t.baseUrl}|${t.projectId}|${t.branchName}`}function Cs(t){Aa.delete(uf(t))}async function wl(t,e,n,i,r=""){const s=ov(e,n);if(s.length===0)return{remoteFiles:n,syncFileMap:e,unverified:[],approximate:[]};const o=Vv(s,r),a={...o.manifest,sources:o.sources},l=o.skipped.map(h=>h.reason);l.forEach(h=>console.warn(`[custom class deploy] ${h}`));const u=o.approximate;u.forEach(h=>console.warn(`[custom class deploy] ${h}`)),console.log(`Provisioning ${s.length} new FlutterFlow custom code file(s) before sync.`),$e.set("provision");const c=await fetch(h_,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:t.apiKey,projectId:t.projectId,baseUrl:t.baseUrl,commitMessage:i,customClasses:s,verification:a,stream:!0})}),d=await Kv(c,{onPhase:h=>$e.setSubstatus(h),onLog:h=>console.log(`[custom class deploy] ${h}`)});if(!d.success){const h=d.details?` ${d.details}`:"";throw new Error(`${d.error||"FlutterFlow custom class provisioning failed."}${h}`)}return Cs(t),d.verificationSkipped&&(console.warn(`[custom class deploy] ${d.verificationSkipped}`),l.push(d.verificationSkipped)),{remoteFiles:n,syncFileMap:av(e,s),unverified:l,approximate:u}}async function bl(t,e={}){const n=uf(t);let i=Aa.get(n);if(i===void 0){try{i=await t.fetchProjectSource()}catch(l){throw new Error(`Could not read your project's pubspec.yaml (${l.message}). Deploy was stopped so your existing package dependencies aren't overwritten. Check your FlutterFlow API key and project, then try again.`)}const a=Wh(i.pubspecYaml);if(!a.valid)throw new Error(`Your project's pubspec.yaml could not be read reliably (${a.errors.join("; ")}). Deploy was stopped so your existing package dependencies aren't overwritten.`);Aa.set(n,i)}const r=await o_(i.pubspecYaml,e),s=Uv(i.pubspecYaml,r.overrides),o=jv(s.yaml,r.additions);return r.warnings.forEach(a=>console.warn(`[pubspec] ${a}`)),o.added.length>0&&console.log("Adding dependencies:",o.added.map(a=>`${a}: ${r.additions[a]||"any"}`).join(", "),r.sdk.dartSdkFloor?`(resolved for Dart ${r.sdk.dartSdkFloor})`:""),r.kept.forEach(({name:a,constraint:l})=>console.log(`Keeping your existing ${a}: ${l||"(non-version source)"}`)),{...o,overridden:s.overridden,warnings:r.warnings,remoteFiles:i.files}}function ey(t){const e=[],n=[];t.content.length>5e4&&n.push("Code file is large (>50KB). This may take longer to commit."),t.content.length>1e5&&e.push("Code file is too large (>100KB). Consider splitting into smaller components.");const i=t.content.split(` -`).length;i>500&&n.push(`Code has ${i} lines. Consider breaking it into smaller widgets.`),t.content.includes("setState")&&t.codeType===z.ACTION&&n.push("Using setState in a Custom Action may not work as expected. Consider using a Custom Widget."),t.content.includes("dynamic")&&!t.content.includes("?")&&n.push('Code uses "dynamic" types. Consider adding explicit types for better null safety.'),t.content.match(/Color\(0xFF[0-9A-Fa-f]{6}\)/)&&n.push("Code contains hardcoded colors. Consider using FlutterFlowTheme.of(context) for theme consistency.");const r=t.content.match(/print\s*\(/g);r&&r.length>3&&n.push(`Code contains ${r.length} print statements. Consider removing debug prints before committing.`);const s=kv(t.content);if(s&&e.push(`FlutterFlow cannot format this code - ${s}. Fix or regenerate before committing.`),t.codeType===z.WIDGET){const o=Lh(t.content),a=Ev(t.fileName);if(o.length===0)e.push("No public widget class found (must extend StatelessWidget or StatefulWidget).");else if(!o.includes(a)){const l=`${Nh(o[0])}`;e.push(`Widget class name "${o[0]}" does not match the file name "${t.fileName}". FlutterFlow derives the widget from the file name, so it will report "No widget ${a} found". Rename the file to "${l}" or the class to match before committing.`)}}return{canProceed:e.length===0,issues:e,warnings:n}}function df(t,e={}){const{artifactType:n="CustomWidget",artifactName:i="GeneratedCode",fileName:r}=e,s=wv(t);let o=r||i;if(n==="CustomFunction")o="custom_functions.dart";else if(n==="CustomWidget"){const u=Lh(s)[0],c=u?Nh(u):null;c&&o!==c?(console.warn(`Commit file name "${o}" does not match declared widget class "${u}"; renaming to "${c}" so FlutterFlow can find the widget.`),o=c):o.endsWith(".dart")||(o+=".dart")}else o.endsWith(".dart")||(o+=".dart");let a=z.CODE_FILE;switch(n){case"CustomAction":a=z.ACTION;break;case"CustomWidget":a=z.WIDGET;break;case"CustomFunction":a=z.FUNCTION;break;case"CustomClass":case"CodeFile":a=z.CODE_FILE;break}let l="";return a===z.WIDGET?l=`// Automatic FlutterFlow imports -import '/flutter_flow/flutter_flow_theme.dart'; -import '/flutter_flow/flutter_flow_util.dart'; -import 'package:flutter/material.dart'; -// Begin custom widget code -// DO NOT REMOVE OR MODIFY THE CODE ABOVE! - -`:a===z.ACTION?l=`// Automatic FlutterFlow imports -import '/flutter_flow/flutter_flow_theme.dart'; -import '/flutter_flow/flutter_flow_util.dart'; -import 'package:flutter/material.dart'; -// Begin custom action code -// DO NOT REMOVE OR MODIFY THE CODE ABOVE! - -`:a===z.FUNCTION&&(l=`// Automatic FlutterFlow imports -import 'dart:convert'; -import 'dart:math' as math; - -import 'package:flutter/material.dart'; -import 'package:google_fonts/google_fonts.dart'; -import 'package:intl/intl.dart'; -import 'package:timeago/timeago.dart' as timeago; -import '/flutter_flow/lat_lng.dart'; -import '/flutter_flow/place.dart'; -import '/flutter_flow/uploaded_file.dart'; - -`),{content:Ym(s,l),fileName:o,codeType:a,artifactType:n,artifactName:i}}function ty(t){const e={};for(const n of rl(t))e[n]="";return e}function ny(t,e={}){return{timestamp:new Date().toISOString(),artifactType:t.artifactType,artifactName:t.artifactName,codeType:t.codeType,fileName:t.fileName,generatedFrom:e.step1Result?"pipeline":"direct",model:e.selectedModel||"unknown",codeSize:t.content.length}}function iy(t,e,n,i=new Set,r=""){const s=[],o=af.test(e),a=lf.test(e);return n===z.WIDGET&&!o&&!a&&s.push("No widget class definition found (must extend StatelessWidget or StatefulWidget)"),{valid:s.length===0,errors:s}}function As(t){const e=[],n=[];if(!t||t.size===0)return e.push("No files to commit"),{valid:!1,errors:e,warnings:n};const i=new Set(Array.from(t.values()).flatMap(r=>ps(r.content||"")));for(const[r,s]of t.entries()){if((!s.content||s.content.trim().length===0)&&e.push(`File ${r} is empty`),s.content&&s.content.length>1e5&&n.push(`File ${r} is very large (>100KB)`),r.endsWith(".dart")){const o=iy(r,s.content,s.type,i,s.artifactName);o.valid||e.push(...o.errors.map(a=>`${r}: ${a}`))}if(r==="pubspec.yaml"){const o=Wh(s.content);o.valid||e.push(...o.errors)}}return{valid:e.length===0,errors:e,warnings:n}}const X={IDLE:"IDLE",PREPARING:"PREPARING",VALIDATING:"VALIDATING",PUSHING:"PUSHING",SUCCESS:"SUCCESS",ERROR:"ERROR"},Q={currentState:X.IDLE,startTime:null,endTime:null,error:null,result:null,filesProcessed:0,totalFiles:0,reset(){this.currentState=X.IDLE,this.startTime=null,this.endTime=null,this.error=null,this.result=null,this.filesProcessed=0,this.totalFiles=0},setState(t){if(!Object.values(X).includes(t)){console.error(`Invalid commit state: ${t}`);return}this.currentState=t,t===X.PREPARING&&(this.startTime=Date.now()),(t===X.SUCCESS||t===X.ERROR)&&(this.endTime=Date.now()),typeof window<"u"&&window.dispatchEvent&&window.dispatchEvent(new CustomEvent("commitStateChange",{detail:{state:t,commitState:this}})),console.log(`Commit state changed to: ${t}`)},setError(t){this.error=t,this.setState(X.ERROR)},setSuccess(t){this.result=t,this.setState(X.SUCCESS)},setProgress(t,e){this.filesProcessed=t,this.totalFiles=e},getElapsedTime(){return this.startTime?(this.endTime||Date.now())-this.startTime:null},isInProgress(){return this.currentState===X.PREPARING||this.currentState===X.VALIDATING||this.currentState===X.PUSHING}};async function ry(t,e,n={}){let{codeType:i="W"}=n;const{pubspecDeps:r={},artifactName:s=e}=n;i==="CustomWidget"&&(i=z.WIDGET),i==="CustomAction"&&(i=z.ACTION),i==="CustomFunction"&&(i=z.FUNCTION),i==="CustomClass"&&(i=z.CODE_FILE),i==="CodeFile"&&(i=z.CODE_FILE),Q.reset(),Q.setState(X.PREPARING);try{const o=await Me("flutterflow"),a=await Me("flutterflow_project_id");if(!o||!a)throw new Error("FlutterFlow credentials not configured. Please set your API key and Project ID in the API Keys settings.");if(!xs(a))throw new Error("Invalid FlutterFlow Project ID format.");const l=Hi(),u=new Wi(o,a,"main",l);Q.setState(X.VALIDATING);const c=new Map,d=i||Q_(e,t),h=cf(e,d);c.set(e,{artifactName:s,content:t,type:d,path:h}),Q.setProgress(0,c.size);const f=As(c);if(!f.valid)throw new Error(`Validation failed: -${f.errors.join(` -`)}`);const p=await bl(u,r),g=p.yaml,m=await wl(u,c,p.remoteFiles,`Provision ${s} custom class`,g),v=await yl(m.syncFileMap,m.remoteFiles),w=new Map(m.syncFileMap);w.set("pubspec.yaml",{content:g,type:"D",path:"pubspec.yaml"}),$e.set("package");const b=await El(w),I={project_id:a,zipped_custom_code:b,uid:`web_${Date.now()}`,branch_name:u.branchName,serialized_yaml:g,file_map:v.fileMapContents,functions_map:v.functionsMapContents};Q.setState(X.PUSHING),Q.setProgress(1,c.size),Cs(u),$e.set("push");const A=await u.pushCode(I),P=await vl(A);if(P.success)Q.setSuccess({fileCount:c.size,projectId:a,warnings:P.errorMap&&P.errorMap.size>0?Array.from(P.errorMap.entries()):[]});else{const O=P.errorMessage||_l(P.responseCode);throw new Error(O)}return{success:!0,message:`Successfully committed ${e} to FlutterFlow project ${a}`,addedDependencies:p.added,unverified:m.unverified,approximate:m.approximate,warnings:P.errorMap?Array.from(P.errorMap.entries()):[]}}catch(o){return console.error("Commit failed:",o),Q.setError(o),{success:!1,error:o.message,state:Q.currentState}}}async function El(t){const e=new JSZip;for(const[n,i]of t.entries())e.file(n,i.content);return e.generateAsync({type:"base64",compression:"DEFLATE",compressionOptions:{level:6}})}async function sy(t,e={}){const{artifactType:n,artifactName:i,fileName:r,pipelineResult:s}=e;console.log(`Starting commit for ${i} (${n})`);try{Q.setState(X.PREPARING);const o=df(t,{artifactType:n,artifactName:i,fileName:r}),a=ty(o.content);console.log("Detected dependencies:",a),Q.setState(X.VALIDATING);const l=await Me("flutterflow"),u=ki||await Me("flutterflow_project_id");if(!l)throw new Error("FlutterFlow API Key not configured. Please add it in API Keys settings.");if(!u)throw new Error("FlutterFlow Project ID not configured. Please add it in API Keys settings.");if(!xs(u))throw new Error("Invalid FlutterFlow Project ID format.");const c=new Map;c.set(o.fileName,{artifactName:i,content:o.content,type:o.codeType,path:cf(o.fileName,o.codeType),functionName:o.codeType===z.FUNCTION?i:void 0}),Q.setProgress(0,c.size);const d=As(c);if(!d.valid)throw new Error(`File validation failed: -${d.errors.join(` -`)}`);d.warnings.length>0&&console.warn("Validation warnings:",d.warnings),Q.setState(X.PUSHING);const h=Hi(),f=new Wi(l,u,"main",h),p=await bl(f,a),g=p.yaml,m=await wl(f,c,p.remoteFiles,`Provision ${i} custom class`,g),v=await yl(m.syncFileMap,m.remoteFiles),w=new Map(m.syncFileMap);w.set("pubspec.yaml",{content:g,type:z.DEPENDENCIES,path:"pubspec.yaml"}),$e.set("package");const b=await El(w),I={project_id:u,zipped_custom_code:b,uid:`web_${Date.now()}`,branch_name:f.branchName,serialized_yaml:g,file_map:v.fileMapContents,functions_map:v.functionsMapContents};Q.setProgress(1,c.size),Cs(f),$e.set("push");const A=await f.pushCode(I),P=await vl(A);if(P.success){const O={...ny(o,s),projectId:u};return Q.setSuccess({...O,fileCount:c.size,warnings:P.errorMap?Array.from(P.errorMap.entries()):[]}),{success:!0,message:`Successfully committed ${o.fileName} to FlutterFlow`,metadata:O,addedDependencies:p.added,unverified:m.unverified,approximate:m.approximate,warnings:P.errorMap?Array.from(P.errorMap.entries()):[],elapsedTime:Q.getElapsedTime()}}else{const O=P.errorMessage||_l(P.responseCode),S=new Error(O);throw S.errorMap=P.errorMap,S}}catch(o){console.error("Commit execution failed:",o),Q.setError(o);let a=new Map;if(o.errorMap)a=o.errorMap;else if(o.message&&o.message.includes("{"))try{const l=o.message.match(/\{[\s\S]*\}/);if(l){const u=JSON.parse(l[0]);a=new Map(Object.entries(u))}}catch(l){console.warn("Failed to parse error map from commit response:",l)}return{success:!1,error:o.message,errorMap:a,state:Q.currentState,elapsedTime:Q.getElapsedTime()}}}async function oy(t,e={}){const{pipelineResult:n}=e;try{if(Q.setState(X.PREPARING),t.errors?.length>0)throw new Error(`Bundle validation failed: -${t.errors.join(` -`)}`);const i=new Map(t.fileEntries.map(I=>[I.fileName,{artifactId:I.artifactId,artifactName:I.artifactName,content:I.content,type:I.type,path:I.path,functionName:I.type===z.FUNCTION?I.artifactName:void 0}]));Q.setProgress(0,i.size);const r=As(i);if(!r.valid)throw new Error(`File validation failed: -${r.errors.join(` -`)}`);Q.setState(X.VALIDATING);const s=await Me("flutterflow"),o=ki||await Me("flutterflow_project_id");if(!s)throw new Error("FlutterFlow API Key not configured. Please add it in API Keys settings.");if(!o)throw new Error("FlutterFlow Project ID not configured. Please add it in API Keys settings.");if(!xs(o))throw new Error("Invalid FlutterFlow Project ID format.");Q.setState(X.PUSHING);const a=Hi(),l=new Wi(s,o,"main",a),u=await bl(l,t.dependencies),c=u.yaml,d=await wl(l,i,u.remoteFiles,`Provision ${t.title} custom classes`,c),h=await yl(d.syncFileMap,d.remoteFiles),f=new Map(d.syncFileMap);f.set("pubspec.yaml",{content:c,type:z.DEPENDENCIES,path:"pubspec.yaml"}),$e.set("package");const p=await El(f),g={project_id:o,zipped_custom_code:p,uid:`web_${Date.now()}`,branch_name:l.branchName,serialized_yaml:c,file_map:h.fileMapContents,functions_map:h.functionsMapContents};Q.setProgress(1,i.size),Cs(l),$e.set("push");const m=await l.pushCode(g),v=await vl(m);if(v.success){const I={...n,artifactType:"Bundle",artifactName:t.title,fileName:`${t.fileEntries.length} artifacts`,codeSize:t.fileEntries.reduce((A,P)=>A+P.content.length,0),projectId:o};return Q.setSuccess({...I,fileCount:i.size,warnings:v.errorMap?Array.from(v.errorMap.entries()):[]}),{success:!0,message:`Successfully committed ${t.fileEntries.length} artifacts to FlutterFlow`,metadata:I,addedDependencies:u.added,unverified:d.unverified,approximate:d.approximate,warnings:v.errorMap?Array.from(v.errorMap.entries()):[],elapsedTime:Q.getElapsedTime()}}const w=v.errorMessage||_l(v.responseCode),b=new Error(w);throw b.errorMap=v.errorMap,b}catch(i){return console.error("Bundle commit execution failed:",i),Q.setError(i),{success:!1,error:i.message,errorMap:i.errorMap||new Map,state:Q.currentState,elapsedTime:Q.getElapsedTime()}}}async function ay(t,e=[]){const n=el("architect");try{return await ls("architect",Yh,mm(t),n,e)}catch(i){throw i.isModelArmor||i.isUsageLimit||i.isPipelineCancel?i:new Error(`Prompt Architect failed: ${i.message}`)}}async function Ps(t,e,n=[],i){const r=vm(t),s=el("generator",y.bundleSpec);try{return await ls("generator",e,r,s,n)}catch(o){if(o.isModelArmor||o.isUsageLimit||o.isPipelineCancel)throw o;if(e!==or){console.warn(`Code Generator failed with ${e}, retrying with fallback model:`,o.message),t0(e,or,i);try{return await ls("generator",or,r,s,n)}catch(a){throw a.isModelArmor||a.isUsageLimit||a.isPipelineCancel?a:new Error(`Code Generator failed: primary (${e}): ${o.message} | fallback (${or}): ${a.message}`)}}throw new Error(`Code Generator failed: ${o.message}`)}}async function Fs(t,e=null){const n={...el("review",y.artifactBundle||y.bundleSpec),architect_output:e};try{return await ls("review",Jh,_m(t),n)}catch(i){throw i.isModelArmor||i.isUsageLimit||i.isPipelineCancel?i:new Error(`Code Review failed: ${i.message}`)}}function Zn(t,e){const n=document.getElementById(`step${t}-item`),i=document.getElementById(`step${t}-status`);!n||!i||(n.classList.remove("active","completed","error"),i.classList.remove("running","completed","error"),e==="active"?(n.classList.add("active"),i.classList.add("running"),i.innerHTML=` - - `):e==="completed"?(n.classList.add("completed"),i.classList.add("completed"),i.innerHTML=` - - `):e==="error"?(n.classList.add("error"),i.classList.add("error"),i.innerHTML=` - - `):i.innerHTML=` - - `)}function Ee(t,e){const n=document.getElementById(`step${t}-loading`),i=document.getElementById(`step${t}-result`);e?(n.classList.remove("hidden"),i.classList.add("hidden"),Zn(t,"active")):(n.classList.add("hidden"),i.classList.remove("hidden"),Zn(t,"completed"))}function ly(t){const e=document.getElementById(`${t}-content`),n=document.getElementById(`${t}-chevron`);e.classList.contains("open")?(e.classList.remove("open"),n&&(n.style.transform="rotate(0deg)")):(e.classList.add("open"),n&&(n.style.transform="rotate(180deg)"))}function cy(t){De(parseInt(t.replace("step","")))}function De(t){for(let o=1;o<=3;o++){const a=document.getElementById(`step${o}-item`);a&&a.classList.remove("active")}const e=document.getElementById(`step${t}-item`);e&&e.classList.add("active"),Sn();const n=document.getElementById("ready-state");n&&n.classList.add("hidden");for(let o=1;o<=3;o++){const a=document.getElementById(`step${o}-content`);a&&a.classList.add("hidden")}const i=document.getElementById(`step${t}-content`);i&&i.classList.remove("hidden");const r=document.getElementById("stage-title"),s={1:"Prompt Architect",2:"Code Generator",3:"Code Review"};r&&(r.textContent=s[t]||"Active Workflow Stage")}function uy(t){const e=document.getElementById(t);if(!e)return;const n=e.dataset.raw||e.textContent;navigator.clipboard.writeText(n).then(()=>{const r=e.closest(".code-container")?.querySelector(".copy-btn");r&&(r.classList.add("copied"),r.innerHTML=' Copied!',setTimeout(()=>{r.classList.remove("copied"),r.innerHTML=' Copy'},2e3))}).catch(i=>{console.warn("Failed to copy to clipboard:",i)})}function Pa(t){const e=Fa(t);console.log(`Step 1 (Prompt Architect): ${Jt(Yh)}`),console.log(e!==t?`Step 2 (Code Generator): ${Jt(t)} → ${Jt(e)} (Free Tier fallback)`:`Step 2 (Code Generator): ${Jt(t)}`),console.log(`Step 3 (Code Review): ${Jt(Jh)}`)}async function hf(){if(console.log("runRefinement called"),y.isRunning)return;const t=document.getElementById("code-generator-model").value;y.isRunning=!0;const e=$s();Sl("standardRegenerate",y.step2Result,y.step1Result);const n=document.querySelectorAll(".btn-refine-action");n.forEach(i=>{i.disabled=!0,i.innerHTML=` - - - Refining...`});try{const i=gl(),r=ym({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,artifactId:i.id,userFeedback:"Fix the issues listed in the audit report."});Os({runId:e}),yt(2,e),De(2),Ee(2,!0);const s=await Ps(r,t,[],e);if(!me(e))return;y.step2Result=s,ks(),zt(2,e);const o=document.getElementById("step2-output"),a=Kn(y.step2Result);o.textContent=a,o.dataset.raw=a,Ee(2,!1),De(3),yt(3,e),Ee(3,!0);const l=await Fs(y.step2Result,y.step1Result);if(!me(e))return;y.step3Result=l,Is(),zt(3,e);const u=document.getElementById("step3-output");u.textContent=y.step3Result,Ee(3,!1),Us();const c=bs(y.step3Result);Hs(a,c)}catch(i){if(console.error("Refinement failed:",i),!me(e))return;const r=ws(i,{architect:2,generator:2,review:3});i.isUsageLimit&&qt(),De(r),Ee(r,!1),Bs(i,{stage:r,runId:e,retry:hf}),Zn(r,"error")}finally{n.forEach(i=>{i.disabled=!1,i.textContent="Refine & Regenerate"}),me(e)&&(y.isRunning=!1,rn())}}async function Sl(t,e,n){const i=`${lt}/connectFeedback`,r={type:t,code:e,input:n};try{const s=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!s.ok){const a=await s.text();return console.error(`callEndpoint failed: ${s.status} ${s.statusText}`,a),{success:!1,status:s.status,error:a}}const o=await s.json();return console.log("Telemetry success:",o),o}catch(s){return console.error("callEndpoint failed:",s),{success:!1,error:s.message}}}function dy(){const t=document.getElementById("ff-error-paste-input");t&&(t.value="")}async function ff(){const t=document.getElementById("ff-error-paste-input"),e=t?.value?.trim();if(!e){t?.focus(),t?.classList.add("ring-2","ring-red-400","border-red-300"),setTimeout(()=>t?.classList.remove("ring-2","ring-red-400","border-red-300"),2e3);return}if(!y.step2Result){ke("No generated code found. Please run the full pipeline first.","warning");return}if(y.isRunning)return;const n=document.getElementById("code-generator-model").value;y.isRunning=!0;const i=$s();Sl("flutterflowError",y.step2Result,e);const r=document.getElementById("btn-fix-from-errors");r&&(r.disabled=!0,r.innerHTML=` - - Fixing…`);try{const s=Fh({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,userFeedback:e});Ff(),Os({runId:i}),yt(2,i),De(2),Ee(2,!0);const o=await Ps(s,n,[],i);if(!me(i))return;y.step2Result=o,ks(),zt(2,i);const a=document.getElementById("step2-output"),l=Kn(y.step2Result);a.textContent=l,a.dataset.raw=l,Ee(2,!1),De(3),yt(3,i),Ee(3,!0);const u=await Fs(y.step2Result,y.step1Result);if(!me(i))return;y.step3Result=u,Is(),zt(3,i);const c=document.getElementById("step3-output");c.textContent=y.step3Result,Ee(3,!1),Us();const d=bs(y.step3Result);Hs(l,d),t&&(t.value="")}catch(s){if(console.error("Fix from errors failed:",s),!me(i))return;const o=ws(s,{architect:2,generator:2,review:3});s.isUsageLimit&&qt(),De(o),Ee(o,!1),Bs(s,{stage:o,runId:i,retry:ff}),Zn(o,"error")}finally{r&&(r.disabled=!1,r.textContent="Fix Errors & Regenerate"),me(i)&&(y.isRunning=!1,rn())}}async function os(){if(console.log("runThinkingPipeline called"),y.isRunning)return;localStorage.setItem("hasSeenWalkthrough","true");const t=document.getElementById("pipeline-input").value,e=document.getElementById("code-generator-model").value;if(!t.trim()){ke("Please describe your FlutterFlow widget first.","warning");return}y.isRunning=!0;const n=$s();try{if(!await Fy()||!me(n)||(await xy(),!me(n)))return;const i=Fa(e);t.length,Y_(),y.submittedPrompt=t,y.submittedImages=wt.slice(),Ma(!0),Pa(i),Sn();const r=document.getElementById("ready-state");r&&r.classList.add("hidden");const s=document.getElementById("paywall-exhausted");s&&s.classList.add("hidden"),Os({prompt:t,runId:n}),s0(),De(1),yt(1,n),Ee(1,!0);const o=wt.filter(m=>m.url).map(m=>({url:m.url})),a=await ay(t,o);if(!me(n))return;y.step1Result=a,J_(),zt(1,n);const l=document.getElementById("step1-output"),u=Kn(y.step1Result);l.textContent=u,l.dataset.raw=u,Ee(1,!1),De(2),yt(2,n),Ee(2,!0);const c=await Ps(y.step1Result,i,o,n);if(!me(n))return;y.step2Result=c,ks(),zt(2,n);const d=document.getElementById("step2-output"),h=Kn(y.step2Result);d.textContent=h,d.dataset.raw=h,Ee(2,!1),De(3),yt(3,n),Ee(3,!0);const f=await Fs(y.step2Result,y.step1Result);if(!me(n))return;y.step3Result=f,Is(),zt(3,n);const p=document.getElementById("step3-output");p.textContent=y.step3Result,Ee(3,!1),Us();const g=bs(y.step3Result);o0(),Hs(h,g)}catch(i){if(i.isPipelineCancel||console.error("Pipeline failed:",i),!me(n))return;const r=ws(i,{architect:1,generator:2,review:3});i.isUsageLimit?qt():(i.message,Fa(document.getElementById("code-generator-model").value),void 0),De(r),Ee(r,!1),Bs(i,{stage:r,runId:n}),Zn(r,"error")}finally{me(n)&&(y.isRunning=!1,Ma(!1),rn())}}function hy(){const t=document.getElementById("code-generator-model").value,e=[es,"anthropic/claude-opus-5","openai/gpt-5.6-sol"].filter(i=>i!==t),n=prompt(`Retry with different model? - -Current: ${t} - -Options: -1. ${e[0]} -2. ${e[1]} - -Enter 1 or 2:`);n==="1"?(document.getElementById("code-generator-model").value=e[0],os()):n==="2"&&(document.getElementById("code-generator-model").value=e[1],os())}async function fy(){const t=ml();if(!t){ke("No code to commit. Please run the pipeline first.","warning");return}const e=await Me("flutterflow"),n=await Me("flutterflow_project_id");if(!e||!n){ke("FlutterFlow credentials not configured. Add your API Key and Project ID in settings.","warning"),hl();return}if(y.artifactBundle?.artifacts?.length>1){await py();return}const{artifactType:i,artifactName:r,fileName:s}=of(),o=df(t,{artifactType:i,artifactName:r,fileName:s}),a=ey(o);if(!a.canProceed){ke(`Pre-commit checks failed: ${a.issues.join("; ")}`,"error");return}Fl(o,a,null,null)}async function py(){const t=await Me("flutterflow"),e=await Me("flutterflow_project_id");if(!t||!e){ke("FlutterFlow credentials not configured. Add your API Key and Project ID in settings.","warning"),hl();return}const n=nv(y.artifactBundle);if(n.errors.length>0){ke(`Bundle validation failed: ${n.errors.join("; ")}`,"error");return}const i=new Map(n.fileEntries.map(a=>[a.fileName,{content:a.content,type:a.type,path:a.path}])),r=As(i),s={canProceed:r.valid&&n.errors.length===0,issues:[...n.errors,...r.errors],warnings:[...n.warnings,...r.warnings]};if(!s.canProceed){ke(`Bundle validation failed: ${s.issues.join("; ")}`,"error");return}const o={content:n.fileEntries.map(a=>`// ${a.fileName} -${a.content}`).join(` - -`),fileName:`${n.fileEntries.length} files`,codeType:"bundle",artifactType:"Bundle",artifactName:n.title};Fl(o,s,n.dependencies,n)}function gy(t){let e=t.errorMap||new Map;!(e instanceof Map)&&typeof e=="object"&&(e=new Map(Object.entries(e)));let n=`
    -

    FlutterFlow Commit Failed

    -

    ${W(t.error)}

    `;if(e&&e.size>0){n+=`
    -

    Errors:

    -
      `;for(const[r,s]of e.entries()){const o=Oh(s);n+=`
    • - ${W(r)}: ${W(o)} -
    • `}n+="
    "}n+="
    ",n+=`
    - -
    `;const i=document.getElementById("step3-output");i&&(i.innerHTML=n,document.getElementById("btn-regenerate-from-error")?.addEventListener("click",()=>{pf(t.error,e)}))}async function pf(t,e){if(y.isRunning)return;const n=document.getElementById("code-generator-model").value;y.isRunning=!0;const i=$s(),r=document.getElementById("btn-regenerate-from-error");r&&(r.disabled=!0,r.innerHTML=` - - Fixing...`);try{let s=`The previous code had the following errors when committing to FlutterFlow: - -`;if(e&&e.size>0)for(const[f,p]of e.entries()){const g=Oh(p);s+=`File: ${f} -Error: ${g} - -`}else s+=`${t} -`;const o=Fh({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,userFeedback:s});Os({runId:i}),yt(2,i),De(2),Ee(2,!0);const a=await Ps(o,n,[],i);if(!me(i))return;y.step2Result=a,ks(),zt(2,i);const l=document.getElementById("step2-output"),u=Kn(y.step2Result);l.textContent=u,l.dataset.raw=u,Ee(2,!1),De(3),yt(3,i),Ee(3,!0);const c=await Fs(y.step2Result,y.step1Result);if(!me(i))return;y.step3Result=c,Is(),zt(3,i);const d=document.getElementById("step3-output");d.textContent=y.step3Result,Ee(3,!1),Us();const h=bs(y.step3Result);Hs(u,h)}catch(s){if(console.error("Regeneration failed:",s),!me(i))return;const o=ws(s,{architect:2,generator:2,review:3});s.isUsageLimit&&qt(),De(o),Ee(o,!1),Bs(s,{stage:o,runId:i,retry:()=>pf(t,e)}),Zn(o,"error")}finally{r&&(r.disabled=!1,r.textContent="Fix Errors & Regenerate"),me(i)&&(y.isRunning=!1,rn())}}async function my(){const t=document.getElementById("ff-status-dot"),e=document.getElementById("ff-status-text");if(!t||!e)return;const n=await Me("flutterflow"),i=await Me("flutterflow_project_id");n&&i?(t.className="w-2 h-2 rounded-full bg-green-500",e.textContent="FlutterFlow credentials configured",e.className="text-green-600"):n||i?(t.className="w-2 h-2 rounded-full bg-yellow-500",e.textContent="FlutterFlow credentials incomplete",e.className="text-yellow-600"):(t.className="w-2 h-2 rounded-full bg-red-500",e.textContent="FlutterFlow credentials not configured",e.className="text-red-600")}async function vy(t){try{const e=await fetch(`${lt}/auth/send-magic-link`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:t})});if(!e.ok)throw new Error(`Failed to send magic link: HTTP ${e.status}`);return e.json()}catch(e){throw console.error("sendMagicLink failed:",{email:t,message:e.message,stack:e.stack}),e}}async function _y(t){try{const n=await(await fetch(`${lt}/auth/verify-magic-link`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:t})})).json();if(n.error||!n.email||!n.sessionToken)throw new Error(n.error||"Invalid or expired link");return n}catch(e){throw console.error("verifyMagicLink failed:",{message:e.message,stack:e.stack}),e}}async function yy(t){try{const e=await fetch(`${lt}/auth/refresh-session`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:t})});if(!e.ok)return console.error("refreshSession: non-OK response",{url:`${lt}/auth/refresh-session`,status:e.status}),null;const n=await e.json();return n.error||!n.email||!n.sessionToken?(console.warn("refreshSession: validation failed",{error:n.error,hasEmail:!!n.email,hasToken:!!n.sessionToken}),null):n}catch(e){return console.error("refreshSession: fetch failed",{url:`${lt}/auth/refresh-session`,message:e.message,stack:e.stack}),null}}function Tu(t,e){const n=gf(),i=(G.email||n.email)!==t;G.email=t,G.sessionToken=e,G.isVerified=!0,be=Yn({isLoading:!0}),localStorage.setItem(Zr,JSON.stringify({email:t,sessionToken:e})),i&&Pl()}function xl(){G.email=null,G.sessionToken=null,G.isVerified=!1,be=Yn({isResolved:!0}),localStorage.removeItem(Zr),localStorage.removeItem(Qr)}function gf(){try{const t=localStorage.getItem(Zr);if(!t)return{email:null,sessionToken:null};const e=JSON.parse(t);return!e.email||!e.sessionToken?{email:null,sessionToken:null}:e}catch(t){return console.warn("getStoredSession: failed to parse auth session:",t),localStorage.removeItem(Zr),{email:null,sessionToken:null}}}async function wy(){const e=new URLSearchParams(window.location.search).get("token");if(e){window.history.replaceState({},"",window.location.pathname+window.location.hash);try{const{email:n,sessionToken:i}=await _y(e);Tu(n,i)}catch(n){ke(n.message||"Sign-in link invalid or expired.","error")}}else{const{email:n,sessionToken:i}=gf();if(n&&i){const r=await yy(i);r?Tu(r.email,r.sessionToken):xl()}}Il()}function kl(){const t=document.getElementById("signin-modal");t&&tt(t)}function by(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("signin-modal");e&&ct(e)}async function Ey(){const t=document.getElementById("signin-email-input"),e=document.getElementById("signin-submit-btn"),n=document.getElementById("signin-message"),i=ms(t?.value);if(!i||!/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/.test(i)||i.length>254){n&&(n.textContent="Please enter a valid email address.");return}e&&(e.disabled=!0,e.textContent="Sending…");const s=Bh(i);n&&s&&(n.textContent=s);try{const o=await vy(i);t&&o?.code!==_r&&(t.value=""),n&&(n.textContent=Mv(o,i)),e&&(e.textContent=o?.code===_r?"Send Link":"Sent!"),e&&o?.code===_r&&(e.disabled=!1)}catch(o){console.error("handleMagicLinkRequest: sendMagicLink failed",{email:i,err:o}),n&&(n.textContent="Something went wrong. Please try again."),e&&(e.disabled=!1,e.textContent="Send Link")}}function Sy(){xl(),Pl(),Il(),Ts()}function Il(){const t=G.isVerified&&!!G.email,e=document.getElementById("auth-signedout"),n=document.getElementById("auth-signedin"),i=document.getElementById("auth-guest-usage");e&&e.classList.toggle("hidden",t),n&&n.classList.toggle("hidden",!t),i&&i.classList.toggle("hidden",t);const r=document.getElementById("auth-user-email");r&&(r.textContent=G.email||""),Ty(),Ts()}async function mf(){try{if(typeof FingerprintJS>"u"){console.warn("resolveIdentity: FingerprintJS not loaded, skipping");return}const e=await(await FingerprintJS.load()).get(),n=e.visitorId,i=await fetch(m_,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({fingerprint:e.visitorId,cookie_id:n})});if(!i.ok)throw new Error(`Identity check HTTP ${i.status}`);const r=await i.json();if(st.userId=r.user_id,st.token=r.identity_token||null,st.status=r.status,st.resolved=!0,sessionStorage.setItem(p_,r.user_id),st.token&&sessionStorage.setItem(g_,st.token),r.usage_count!==void 0){const s=tn(),a=(r.usage_month||s)===s?r.usage_count:0;localStorage.setItem(yn,JSON.stringify({count:a,month:s})),qt()}console.log(`Identity resolved: ${r.status} (${r.user_id.slice(0,8)}...) usage: ${r.usage_count??"n/a"}`)}catch(t){console.error("resolveIdentity failed:",t)}}let Fo=null;function xy(t=5e3){return st.resolved?Promise.resolve():(Fo||(Fo=mf().catch(e=>{console.warn("ensureIdentityReady: identity resolution failed",e)})),Promise.race([Fo,new Promise(e=>setTimeout(e,t))]))}function vf(){const t=tn();try{const e=localStorage.getItem(yn);return e?JSON.parse(e):{count:0,month:t}}catch(e){return console.warn("getUsageData: failed to parse usage storage",{key:yn,month:t,err:e}),localStorage.removeItem(yn),{count:0,month:t}}}function tn(){const t=new Date;return`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,"0")}`}function Rs(){const t=vf();return t.month!==tn()?{count:0,month:tn()}:t}function ky(){const e={count:Rs().count+1,month:tn()};return localStorage.setItem(yn,JSON.stringify(e)),e}function qi(){return!!be.isLoading}function Vt(){return!!be.isResolved}function Iy(t){if(!t)return null;const e=String(t).toLowerCase().replace(/[^a-z0-9]+/g,"_");return e==="pro"||e==="professional_plan"?"professional":e==="power_developer"||e==="power_plan"?"power":Object.prototype.hasOwnProperty.call(Xr,e)?e:null}function Cy(t){return t&&Object.entries(Vh).find(([,e])=>e===t)?.[0]||null}function cr(...t){return t.find(e=>e!=null&&e!=="")}function Ay(...t){return t.find(e=>e&&typeof e=="object")||{}}function Py(t){const e=t.data&&typeof t.data=="object"?t.data:t,n=Ay(e.subscription,e.stripeSubscription,e.currentSubscription,e.customer?.subscriptions?.data?.[0],e.subscriptions?.data?.[0],e.subscriptions?.[0]),i=e.metadata||n.metadata||e.customer?.metadata||{},r=cr(e.priceId,e.price_id,e.stripePriceId,e.stripe_price_id,n.priceId,n.price_id,n.plan?.id,n.price?.id,n.items?.data?.[0]?.price?.id,n.items?.[0]?.price?.id,n.lines?.data?.[0]?.price?.id),s=cr(e.status,e.subscriptionStatus,e.subscription_status,n.status,"none"),o=Iy(cr(e.tier,e.plan,e.planId,e.plan_id,e.subscriptionTier,e.subscription_tier,e.product,e.productName,n.tier,n.plan,i.tier,i.plan)),a=v_.has(String(s).toLowerCase()),l=e.active===!0||e.isSubscribed===!0||e.subscribed===!0||e.hasSubscription===!0,u=o||Cy(r)||(a||l?"professional":"free");return Yn({tier:u,status:s,periodEnd:cr(e.periodEnd,e.currentPeriodEnd,e.current_period_end,n.current_period_end,n.periodEnd,null),isResolved:!0})}function Cl(){return Xr[be.tier]??Xr.free}async function Fy(){if(G.isVerified&&(!Vt()||qi())&&(await yf({force:!0}),Ts()),G.isVerified&&!Vt())return ke("Could not verify your subscription. Please refresh or try Manage billing.","error"),!1;const{count:t}=Rs(),e=Cl();if(t>=e)return _f(t,e,{openModal:!0}),!1;const n=Math.floor(e*.8);if(t>=n){const i=e-t;ke(`${i} run${i===1?"":"s"} remaining this month.`,"warning")}return!0}function $u(){const t=document.getElementById("paywall-exhausted");t&&t.classList.add("hidden")}function _f(t,e,n={}){nn(!0);const i=document.getElementById("walkthrough-modal");i&&ct(i,{restoreFocus:!1});const r=document.getElementById("ready-state");r&&r.classList.add("hidden");const s=document.getElementById("preview-frame-container");s&&(s.style.display="none");const o=document.getElementById("main-stage-container");o&&o.classList.add("visible");const a=document.getElementById("results-view");a&&a.classList.remove("visible"),document.body.classList.remove("results-fullscreen","results-with-sidebar");const l=document.getElementById("pipeline-progress");l&&l.classList.remove("visible");const u=document.getElementById("paywall-exhausted");if(!u){ke(`You've used all ${e} runs for this month. Upgrade to continue.`,"error"),ji();return}const c=document.getElementById("paywall-exhausted-text");if(c){const h=be.tier;h==="free"?c.textContent=`You've used all ${e} free generations this month. Upgrade to Pro for 50 generations/month and access to all AI models.`:c.textContent=`You've used all ${e} generations this month on your ${h} plan. Your limit resets next month.`}const d=document.getElementById("paywall-signin-btn");d&&d.classList.toggle("hidden",G.isVerified),u.classList.remove("hidden"),n.openModal&&ji()}function Fa(t){return be.tier==="free"&&yr.includes(t)?es:t}function Ry(){const t=document.getElementById("code-options-content"),e=document.getElementById("code-generator-model");if(!t||!e)return;const n=be.tier,r=!(G.isVerified&&!Vt())&&n==="free";Array.from(e.options).forEach(o=>{const a=Jt(o.value),l=yr.includes(o.value);o.textContent=l&&r?`${a} (PRO)`:a,o.disabled=!1}),r&&yr.includes(e.value)&&(e.value=es),e.disabled=!1,xu.has(e)||(e.addEventListener("change",()=>{Vt()&&be.tier==="free"&&yr.includes(e.value)&&(e.value=es,ji()),Pa(e.value),Kh()}),xu.add(e));let s=document.getElementById("model-selector-free-notice");r?(s||(s=document.createElement("p"),s.id="model-selector-free-notice",s.className="text-xs text-gray-400 mt-1",t.appendChild(s)),s.innerHTML='Free plan — Gemini only. '):s&&s.remove(),Pa(e.value)}function Al(){const t=G.isVerified&&!!G.email,e=t&&qi(),n=!t||Vt(),i=Rs(),r=n?i.count:0,s=n?Cl():0,o=Math.max(0,s-r),a=`${r} / ${s} runs this month`,l={free:"Free",professional:"Pro",power:"Power"},u=n?be.tier||"free":null,c=document.getElementById("topbar-credits-count");c&&(e?c.textContent="…":n?c.textContent=String(o):c.textContent="—");const d=document.getElementById("credits-balance");d&&(e?d.textContent="Checking plan…":n?d.textContent=a:d.textContent="Plan check failed");const h=document.getElementById("usage-dialog-tier");h&&(e?h.textContent="Checking…":n?h.textContent=l[u]||"Free":h.textContent="Unavailable");const f=document.getElementById("usage-dialog-status");f&&(e?f.textContent="Verifying your subscription…":n?f.textContent="Runs reset at the start of each month.":f.textContent="Could not verify your subscription. Try again or sign out.");const p=document.getElementById("usage-counter");if(p)if(e&&t)p.textContent="Checking plan…",p.className="text-xs text-gray-500";else if(!n&&t)p.textContent="Plan check failed",p.className="text-xs text-red-600 font-medium";else{p.textContent=a;const g=s>0?r/s:0;p.className=g>=1?"text-xs text-red-600 font-medium":g>=.8?"text-xs text-yellow-600 font-medium":"text-xs text-gray-500"}if(!t){const g=document.getElementById("guest-usage-text");if(g){const m=vf(),v=m.month===tn()?m.count??0:0;g.textContent=`${v} / ${Xr.free} generations used`}}}function qt(){if(Al(),G.isVerified&&(qi()||!Vt())){$u();return}const{count:t}=Rs(),e=Cl();t>=e&&!y.isRunning?_f(t,e):$u()}function Ty(){Al()}async function yf(t={}){const e=t.force===!0;if(!G.isVerified||!G.sessionToken){be=Yn({isResolved:!0});return}be={...be,isLoading:!0,error:null};const n=localStorage.getItem(Qr);if(!e&&n)try{const{data:i,email:r,ts:s,version:o}=JSON.parse(n);if(o===ku&&r===G.email&&Date.now()-s<300*1e3){be={...i,isLoading:!1,isResolved:i.isResolved!==!1};return}}catch(i){console.warn("Failed to parse subscription cache:",i,"| raw value:",n)}try{const r=await(await fetch(`${lt}/stripe/get-subscription`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:G.sessionToken,user_id:st.userId})})).json();if(r.error){if(["unauthorized","invalid session","expired session"].some(o=>String(r.error).toLowerCase().includes(o))){xl(),Il();return}be=Yn({isResolved:!1,error:r.error});return}be=Py(r),localStorage.setItem(Qr,JSON.stringify({version:ku,data:be,email:G.email,ts:Date.now()}))}catch(i){console.error("fetchSubscription failed:",i),be={...be,isLoading:!1,isResolved:!1,error:i.message}}}function Pl(){localStorage.removeItem(Qr)}async function $y(t){if(!G.isVerified||!G.sessionToken){wf(),kl();return}if(!Vh[t]){ke("Invalid plan selected.","error");return}const e=document.getElementById(`checkout-btn-${t}`);e&&(e.disabled=!0,e.textContent="Redirecting…");try{const i=await(await fetch(`${lt}/stripe/create-checkout-session-intl`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tierId:t,sessionToken:G.sessionToken,currency:Zh()})})).json();if(i.error||!i.url)throw new Error(i.error||"Failed to create checkout session");const{url:r}=i;window.location.href=r}catch(n){console.error("startCheckout failed:",n),e&&(e.disabled=!1,e.textContent="Subscribe"),ke("Could not start checkout. Please try again.","error")}}async function My(t){if(!G.isVerified||!G.sessionToken){kl();return}const e=t||document.getElementById("manage-billing-btn"),n=e?e.textContent:"";e&&(e.disabled=!0,e.textContent="Loading…");try{const r=await(await fetch(`${lt}/stripe/create-portal-session`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:G.sessionToken})})).json();if(r.error||!r.url)throw new Error(r.error||"Failed to open billing portal");const{url:s}=r;window.location.href=s}catch(i){console.error("openCustomerPortal failed:",i),e&&(e.disabled=!1,e.textContent=n),ke("Could not open billing portal. Please try again.","error")}}const as=new Set;function Ly(){as.forEach(t=>t.abort()),as.clear()}async function ls(t,e,n,i={},r=[]){const o=new AbortController;as.add(o);let a=!1;const l=setTimeout(()=>{a=!0,o.abort()},12e4);try{const u=await fetch(f_,{method:"POST",headers:{"Content-Type":"application/json",...st.token?{Authorization:`Bearer ${st.token}`}:{}},signal:o.signal,body:JSON.stringify({user_id:st.userId,step:t,model:e,prompt:n,images:r,context:i})}),c=await u.text();let d={};try{d=c?JSON.parse(c):{}}catch{d={}}if(u.status===429){d.serverCount!==void 0&&(localStorage.setItem(yn,JSON.stringify({count:d.serverCount,month:tn()})),qt());const p=new Error(d.message||"Monthly usage limit reached. Upgrade to continue.");throw p.isUsageLimit=!0,p.pipelineStep=t,p}const h=Im(d,t);if(h)throw h;if(console.log(`[BuildShip] ${t} response keys:`,Object.keys(d),"content type:",typeof d.content),!u.ok)throw new Error(`${d.message||d.error||"BuildShip pipeline error"} (HTTP ${u.status})`);if(t==="generator")if(d.usage_status==="success"&&Number.isFinite(d.usage_count)){const p=tn();(d.usage_month||p)===p&&(localStorage.setItem(yn,JSON.stringify({count:d.usage_count,month:p})),qt())}else ky(),qt();let f=d.output||d.content;if(!f){const p=c?` (body: ${c.slice(0,120)})`:"";throw new Error(`BuildShip returned no output for step "${t}"${p}`)}return Array.isArray(f)&&(f=f.map(p=>typeof p=="string"?p:p.text||"").join("")),typeof f!="string"&&(f=JSON.stringify(f)),f}catch(u){if(u.name==="AbortError"){if(a)throw new Error(`BuildShip ${t} timed out after ${12e4/1e3}s`);const c=new Error(`BuildShip ${t} request cancelled`);throw c.isPipelineCancel=!0,c}throw u instanceof TypeError?new Error(`BuildShip unreachable: ${u.message}`):u}finally{clearTimeout(l),as.delete(o)}}function Ny(){const e=new URLSearchParams(window.location.search).get("checkout");e==="success"?(window.history.replaceState({},"",window.location.pathname+window.location.hash),Pl(),ke("Subscription active! Welcome aboard.","success")):e==="cancel"&&(window.history.replaceState({},"",window.location.pathname+window.location.hash),ke("Checkout cancelled.","info"))}function Ts(){const t=G.isVerified&&!!G.email,e=be.tier,n=t&&qi(),i=!t||Vt(),r=document.getElementById("subscription-tier-badge");if(r){const a={free:"Free",professional:"Professional",power:"Power Developer"},l={free:"bg-gray-100 text-gray-600",professional:"bg-indigo-100 text-indigo-700",power:"bg-purple-100 text-purple-700",unresolved:"bg-red-50 text-red-600"};r.textContent=n?"Checking…":i?a[e]||"Free":"Plan unavailable",r.className=`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${i?l[e]||l.free:l.unresolved}`}const s=document.getElementById("upgrade-prompt");s&&s.classList.toggle("hidden",!t||n||!i||e!=="free");const o=document.getElementById("manage-billing-btn");o&&o.classList.toggle("hidden",!t||n||i&&e==="free"),Oy(i?e:null),Ry(),Kh(),qt(),Rf()}function Oy(t){const e=["bg-gray-100","text-gray-500","cursor-default"];Object.entries({professional:{btnId:"checkout-btn-professional",defaultText:"Subscribe"},power:{btnId:"checkout-btn-power",defaultText:"Subscribe"}}).forEach(([r,{btnId:s,defaultText:o}])=>{const a=document.getElementById(s);a&&(r===t?(a.disabled=!0,a.textContent="Current plan",a.classList.add(...e)):(a.disabled=!1,a.textContent=o,a.classList.remove(...e)))});const i=document.getElementById("free-tier-current");i&&i.classList.toggle("hidden",t!=="free")}function Ra(){const t=Zh(),e=document.getElementById("pro-price"),n=document.getElementById("power-price"),i=document.getElementById("plans-pro-price"),r=document.getElementById("plans-power-price"),s=document.getElementById("pro-price-note"),o=document.getElementById("power-price-note"),a=document.getElementById("plans-pro-price-note"),l=document.getElementById("plans-power-price-note");e&&(e.textContent=lr(ar.professional,t)),n&&(n.textContent=lr(ar.power,t)),i&&(i.textContent=lr(ar.professional,t)),r&&(r.textContent=lr(ar.power,t));const u="billed monthly";s&&(s.textContent=u),o&&(o.textContent=u),a&&(a.textContent=u),l&&(l.textContent=u)}function ji(){Ra();const t=document.getElementById("pricing-modal");t&&tt(t),I_().then(()=>Ra())}function wf(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("pricing-modal");e&&ct(e)}function ke(t,e="info"){const n={success:"bg-green-600 text-white",error:"bg-red-600 text-white",warning:"bg-amber-500 text-white",info:"bg-gray-800 text-white"},i=document.createElement("div");i.className=`fixed bottom-6 left-1/2 -translate-x-1/2 px-5 py-3 rounded-lg text-sm font-medium shadow-lg z-50 transition-opacity duration-300 ${n[e]||n.info}`,i.textContent=t,document.body.appendChild(i),setTimeout(()=>{i.style.opacity="0",setTimeout(()=>i.remove(),300)},3500)}document.addEventListener("DOMContentLoaded",async()=>{fm(),hljs.configure({tabReplace:" ",classPrefix:"hljs-"}),By(),window.__heroField=Yv(),await wy(),Ny(),await yf(),Ts(),Ra(),await Z_(),V_();const t=document.getElementById("flutterflow-endpoint-select");if(t){const n=Hi();t.value=n}rf(),mf();const e=document.getElementById("pipeline-input");e&&(e.addEventListener("input",()=>{Wt===2&&e.value.trim().length>0&&(fl(),Ss())}),e.addEventListener("blur",()=>{const n=document.getElementById("walkthrough-modal");Wt===2&&n&&tt(n)}),e.addEventListener("keydown",n=>{if(n.key==="Tab"){const i=document.getElementById("walkthrough-modal");Wt===2&&i&&setTimeout(()=>{tt(i)},100)}})),window.addEventListener("commitStateChange",n=>{const{state:i}=n.detail;i===X.PREPARING||i===X.VALIDATING||i===X.PUSHING?($e.phaseId||Ef(),Lu(i)):(i===X.SUCCESS||i===X.ERROR)&&(Lu(i),setTimeout(cs,1e3))}),y0(),Dl()});function By(){const t=document.getElementById("preview-frame-container");t&&(t.style.display="")}function Dy(){const t=document.getElementById("welcome-video-player");t&&(t.addEventListener("click",Sn),document.addEventListener("keydown",Sn))}function Sn(){const t=document.getElementById("preview-frame-container"),e=document.getElementById("main-stage-container"),n=document.getElementById("ready-state");t&&(t.style.display="none"),e&&e.classList.add("visible"),n&&n.classList.remove("hidden");const i=document.getElementById("welcome-video-player");i&&i.removeEventListener("click",Sn),document.removeEventListener("keydown",Sn),rf()}let Ii=null;async function jy(){const t=document.getElementById("confirm-project-select");if(!t)return;const e=++Fu,n=()=>e===Fu,i=await Me("flutterflow"),r=await Me("flutterflow_project_id");if(n()){if(!i){t.innerHTML='',t.disabled=!0;return}t.disabled=!1,t.innerHTML='';try{const o=await new Wi(i,"").listProjects();if(!n())return;if(!o||o.length===0){t.innerHTML='';return}t.innerHTML='',o.forEach(a=>{const l=document.createElement("option");l.value=a.id||a.projectId||"",l.textContent=a.name||a.projectName||`Project ${a.id}`,t.appendChild(l)}),r&&(t.value=r)}catch(s){if(!n())return;console.error("Failed to load projects for deploy:",s),t.innerHTML=''}}}function Uy(){return document.getElementById("confirm-project-select")?.value?.trim()||null}function Fl(t,e,n,i=null){Ii={codeInfo:t,checks:e,deps:n,bundlePlan:i},document.getElementById("confirm-file-name").textContent=t.fileName,document.getElementById("confirm-artifact-type").textContent=t.artifactType,document.getElementById("confirm-file-size").textContent=`${(t.content.length/1024).toFixed(1)} KB`,document.getElementById("confirm-line-count").textContent=i?`${i.fileEntries.length} files`:t.content.split(` -`).length,jy();const r=document.getElementById("confirm-deps-list"),s=document.getElementById("confirm-deps-section");n&&Object.keys(n).length>0?(r.innerHTML=Object.entries(n).map(([u,c])=>{const d=c?`at least ${Ht(c)}`:"version resolved from your project";return`
  • • ${Ht(u)}: ${d}
  • `}).join(""),s.classList.remove("hidden")):s.classList.add("hidden");const o=document.getElementById("confirm-warnings-list"),a=document.getElementById("confirm-warnings-section");e.warnings&&e.warnings.length>0?(o.innerHTML=e.warnings.map(u=>`
  • • ${Ht(u)}
  • `).join(""),a.classList.remove("hidden")):a.classList.add("hidden"),document.getElementById("confirm-code-preview").textContent=t.content,document.getElementById("code-preview-content").classList.add("hidden"),document.getElementById("code-preview-chevron").style.transform="rotate(0deg)";const l=document.getElementById("commit-confirm-modal");l&&tt(l)}function bf(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("commit-confirm-modal");e&&ct(e),Ii=null}function Hy(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("commit-success-modal");e&&ct(e);const n=["success-message","success-project-id","success-file-name","success-artifact-type","success-time","success-size"];for(const s of n){const o=document.getElementById(s);o&&(o.textContent="")}const i=document.getElementById("success-warnings-section");i&&i.classList.add("hidden");const r=document.getElementById("success-warnings-list");r&&(r.innerHTML="")}function Ta(t){const e=(m,v)=>{const w=document.getElementById(m);w&&(w.textContent=v||"")},n=t.metadata?.fileName||"",i=t.metadata?.projectId||"",r=t.metadata?.artifactType||"",s=t.elapsedTime?`${(t.elapsedTime/1e3).toFixed(1)}s`:"",o=t.metadata?.codeSize?`${(t.metadata.codeSize/1024).toFixed(1)} KB`:"";e("success-message",t.message||"Code committed successfully!"),e("success-project-id",i),e("success-file-name",n),e("success-artifact-type",r),e("success-time",s),e("success-size",o);const a=t.addedDependencies||[],l=document.getElementById("success-deps-row");l&&l.classList.toggle("hidden",a.length===0),e("success-deps",a.join(", "));const u=document.getElementById("success-open-ff-link");u&&i&&(u.href=`https://app.flutterflow.io/project/${i}`);const c=document.getElementById("success-warnings-section"),d=document.getElementById("success-warnings-list"),h=t.unverified||[],f=t.approximate||[],p=t.warnings||[];(p.length>0||h.length>0||f.length>0)&&c&&d&&(d.innerHTML=[...h.map(m=>`
  • Not verified before deploying: ${W(String(m))}
  • `),...f.map(m=>`
  • Verified approximately: ${W(String(m))}
  • `),...p.map(([m,v])=>`
  • ${W(m)}: ${W(String(v))}
  • `)].join(""),c.classList.remove("hidden"));const g=document.getElementById("commit-success-modal");g&&tt(g)}function $a(t){cs(),gy(t)}function Wy(){const t=document.getElementById("code-preview-content"),e=document.getElementById("code-preview-chevron");t.classList.contains("hidden")?(t.classList.remove("hidden"),e.style.transform="rotate(90deg)"):(t.classList.add("hidden"),e.style.transform="rotate(0deg)")}const Mu={prepare:{message:"Preparing your code...",start:4,end:14},validate:{message:"Checking FlutterFlow credentials...",start:14,end:22},project:{message:"Reading your FlutterFlow project...",start:22,end:40},provision:{message:"Creating custom classes in FlutterFlow...",start:40,end:82},package:{message:"Packaging files for upload...",start:82,end:88},push:{message:"Pushing to FlutterFlow...",start:88,end:97},done:{message:"Complete!",start:100,end:100}},qy=[{after:0,text:"Starting a FlutterFlow build runner..."},{after:12,text:"Preparing the FlutterFlow AI workspace..."},{after:35,text:"Uploading your custom classes..."},{after:60,text:"FlutterFlow is applying the changes..."},{after:100,text:"Still working — this can take a couple of minutes..."}],$e={sequence:[],phaseId:null,phaseStartedAt:null,timer:null,substatus:null,liveSubstatus:!1,start({withProvisioning:t=!1}={}){this.sequence=["prepare","validate","project"],t&&this.sequence.push("provision"),this.sequence.push("package","push","done");const e=document.getElementById("commit-progress-overlay");e&&(ru(e,!0,"Deploying to FlutterFlow"),tt(e)),this.set("prepare")},set(t,e=null){if(!(!Mu[t]||t===this.phaseId)){if(!this.sequence.includes(t)){const n=this.sequence.indexOf("package");this.sequence.splice(n===-1?this.sequence.length:n,0,t)}this.phaseId=t,this.phaseStartedAt=Date.now(),this.substatus=e,this.liveSubstatus=!1,this.render(),this.timer&&clearInterval(this.timer),t!=="done"&&(this.timer=setInterval(()=>this.render(),500))}},setSubstatus(t){t&&(this.liveSubstatus=!0,this.substatus=t,this.render())},render(){const t=Mu[this.phaseId];if(!t)return;const e=(Date.now()-this.phaseStartedAt)/1e3,n=t.start+(t.end-t.start)*(1-Math.exp(-e/25));if(this.phaseId==="provision"&&!this.liveSubstatus){const o=qy.filter(a=>e>=a.after).pop();o&&(this.substatus=o.text)}const i=this.sequence.indexOf(this.phaseId),s=[`Step ${i===-1?1:i+1} of ${this.sequence.length}`];e>=5&&s.push(zy(e)),Sf(this.phaseId==="done"?100:n,t.message,s.join(" · "),this.substatus)},stop(){this.timer&&clearInterval(this.timer),this.timer=null,this.phaseId=null;const t=document.getElementById("commit-progress-overlay");t&&(ru(t,!1),ct(t,{force:!0,restoreFocus:!1}))}};function zy(t){const e=Math.floor(t);return e<60?`${e}s elapsed`:`${Math.floor(e/60)}m ${String(e%60).padStart(2,"0")}s elapsed`}function Ef(t){$e.start(t)}function cs(){$e.stop()}function Sf(t,e,n,i=null){const r=document.getElementById("commit-progress-bar"),s=document.getElementById("progress-message"),o=document.getElementById("progress-detail"),a=document.getElementById("progress-substatus");r&&(r.style.width=`${Math.round(t*10)/10}%`),s&&(s.textContent=e),o&&(o.textContent=n),a&&(a.textContent=i||"",a.classList.toggle("hidden",!i))}function Lu(t){const e={[X.PREPARING]:"prepare",[X.VALIDATING]:"validate",[X.PUSHING]:"project",[X.SUCCESS]:"done"};if(t===X.ERROR){$e.timer&&clearInterval($e.timer),$e.timer=null,Sf(100,"Failed","Error occurred");return}const n=e[t];n&&$e.set(n)}function Vy(t){return t.bundlePlan?t.bundlePlan.fileEntries.some(e=>e.type===z.CODE_FILE):t.codeInfo?.codeType===z.CODE_FILE}async function Gy(){if(!Ii){console.error("No pending commit data");return}const t=Ii;if(Ii=null,ki=Uy(),bf(),Ef({withProvisioning:Vy(t)}),t.bundlePlan){const o=await oy(t.bundlePlan,{pipelineResult:{step1Result:y.step1Result,selectedModel:document.getElementById("code-generator-model")?.value}});ki=null,cs(),o.success?Ta(o):$a(o);return}const{codeInfo:e}=t,{artifactType:n,artifactName:i,fileName:r}=of(),s=await sy(e.content,{artifactType:n,artifactName:i,fileName:r,pipelineResult:{step1Result:y.step1Result,selectedModel:document.getElementById("code-generator-model")?.value}});ki=null,cs(),s.success?Ta(s):$a(s)}window.runThinkingPipeline=os;window.toggleStep=cy;window.toggleSection=ly;window.selectWorkflowStep=De;window.copyCode=uy;window.retryWithDifferentModel=hy;window.openApiKeysModal=hl;window.closeApiKeysModal=tf;window.closeWalkthroughModal=j_;window.openWalkthroughModal=D_;window.advanceWalkthrough=fl;window.commitToFlutterFlow=ry;function Ky(){const t=document.getElementById("pipeline-input");t&&t.focus()}function Yy(){const t=document.getElementById("advanced-settings");t&&(t.open=!0);const e=document.getElementById("code-generator-model");e&&(e.scrollIntoView({behavior:"smooth",block:"center"}),e.focus(),e.click())}window.focusPromptInput=Ky;window.openModelSelector=Yy;window.handlePromptImageSelect=x_;window.removePromptImage=k_;window.saveApiKeys=W_;window.clearAllApiKeys=q_;window.toggleKeyVisibility=K_;window.handleWelcomeVideoEnd=Dy;window.dismissWelcomeVideo=Sn;window.initiateCommitToFlutterFlow=fy;window.updateFlutterFlowCredentialStatus=my;window.openCommitConfirmModal=Fl;window.closeCommitConfirmModal=bf;window.closeCommitSuccessModal=Hy;window.showCommitSuccessModal=Ta;window.showCommitFailureModal=$a;window.toggleCodePreview=Wy;window.confirmCommitToFlutterFlow=Gy;window.runRefinement=hf;window.regenerateFromPastedErrors=ff;window.clearErrorInput=dy;window.setFlutterFlowEndpoint=B_;window.getFlutterFlowEndpoint=Hi;window.commitProgress=$e;window.openSignInModal=kl;window.closeSignInModal=by;window.handleMagicLinkRequest=Ey;window.handleSignOut=Sy;window.startCheckout=$y;window.openCustomerPortal=My;window.openPricingModal=ji;window.closePricingModal=wf;let Sr=null,xf=null,xn={1:"pending",2:"pending",3:"pending"},Rl=1,Tl=null;const $l={1:"Prompt Architect",2:"Code Generator",3:"Code Review"},Jy={1:"Understanding your prompt",2:"Generating Dart code",3:"Running the code audit"},Zy={1:"Prompt understood",2:"Dart code generated",3:"Code audit complete"};function $s(){return y.runId+=1,y.runId}function me(t){return t===void 0||t===y.runId}function Xy(){y.runId+=1}function Ml(t){return document.getElementById(`pdot-${t}`)}function Ma(t){const e=document.getElementById("btn-run-pipeline")||document.getElementById("hero-send");e&&(e.disabled=t,e.classList.toggle("is-busy",t),t?e.setAttribute("aria-busy","true"):e.removeAttribute("aria-busy"))}function Ms(t){const e=document.getElementById("pipeline-progress");e&&(e.dataset.runState=t)}function wn(t,e){xn[t]=e;const n=Ml(t);if(!n)return;n.dataset.state=e,n.disabled=e==="pending"||e==="skipped";const i=$l[t],r={pending:"not started",active:"in progress",done:"complete",failed:"failed",skipped:"not run"};n.setAttribute("aria-label",`Step ${t} of 3, ${i}: ${r[e]||e}`),e==="active"?n.setAttribute("aria-current","step"):n.removeAttribute("aria-current")}function Qy(){return[1,2,3].filter(t=>xn[t]==="done").length}function Ls(){const t=document.getElementById("pipeline-progress-fill");t&&(t.style.width=`${Qy()/3*100}%`);const e=document.getElementById("progress-stage-count");e&&(e.textContent=`Step ${Rl} of 3`)}function Ns(t,{done:e=!1}={}){const n=document.getElementById("progress-title-text"),i=document.getElementById("progress-substep-text"),r=xn[t],s=e||r==="done";if(n&&(n.textContent=s?Zy[t]:Jy[t]),i){const o=s?" — complete":r==="failed"?" — stopped":"";i.textContent=`Step ${t} of 3 — ${$l[t]}${o}`}}function e0(t){xn[t]==="pending"||xn[t]==="skipped"||(Tl=t,[1,2,3].forEach(e=>{const n=Ml(e);n&&n.setAttribute("aria-pressed",String(e===t))}),Ns(t))}function Ll(){Tl=null,[1,2,3].forEach(t=>{const e=Ml(t);e&&e.removeAttribute("aria-pressed")})}function kf(t){const e=document.getElementById("pipeline-note");e&&(e.textContent=t||"",e.hidden=!t)}function t0(t,e,n){me(n)&&kf(`${Jt(t)} did not answer. Continuing on ${Jt(e)}.`)}function Nl(){const t=document.getElementById("pipeline-failure");if(!t)return;t.hidden=!0;const e=document.getElementById("pipeline-failure-actions");e&&e.replaceChildren()}const n0=1120;function i0(){const t=getComputedStyle(document.documentElement).getPropertyValue("--t-morph").trim(),e=Number.parseFloat(t);return Number.isFinite(e)&&e>0?e:n0}let jn=null,xr=null;function r0(){return window.matchMedia?.("(prefers-reduced-motion: reduce)").matches===!0}function Xt(){if(xr){try{xr.cancel()}catch{}xr=null}jn&&(jn.remove(),jn=null),window.removeEventListener("resize",Xt)}function If(t,e){if(Xt(),r0()||!t||!e||!document.body||typeof Element.prototype.animate!="function")return;const n=t.getBoundingClientRect(),i=e.getBoundingClientRect();if(!n.width||!n.height||!i.width||!i.height)return;const r=document.createElement("div");r.className="composer-morph",r.setAttribute("aria-hidden","true"),r.style.cssText=`left:${i.left}px;top:${i.top}px;width:${i.width}px;height:${i.height}px;opacity:0;`,document.body.appendChild(r);const s=n.left+n.width/2-(i.left+i.width/2),o=n.top+n.height/2-(i.top+i.height/2),a=n.width/i.width,l=n.height/i.height,u=`translate(${s}px,${o}px) scale(${a},${l})`,c=r.animate([{transform:u,opacity:0,offset:0,easing:"cubic-bezier(.2,0,0,1)"},{transform:u,opacity:1,offset:.14,easing:"cubic-bezier(.4,0,.2,1)"},{transform:`translate(${s}px,${o}px) scale(${a*.93},${l*.93})`,opacity:1,offset:.28,easing:"cubic-bezier(.32,1.38,.5,1)"},{transform:"translate(0px,0px) scale(1,1)",opacity:1,offset:1}],{duration:i0(),fill:"both"});jn=r,xr=c,window.addEventListener("resize",Xt),c.onfinish=()=>{if(jn!==r)return;const d=r.animate([{opacity:1},{opacity:0}],{duration:260,fill:"forwards"});d.onfinish=()=>{jn===r&&Xt()}}}function s0(){const e=document.getElementById("composer")?.getBoundingClientRect();e&&requestAnimationFrame(()=>{requestAnimationFrame(()=>{If({getBoundingClientRect:()=>e},document.getElementById("main-stage-container"))})})}function o0(){If(document.getElementById("pipeline-progress"),document.getElementById("main-stage-container"))}window.addEventListener("hashchange",Xt);window.addEventListener("popstate",Xt);function Os(t={}){const{prompt:e=null,runId:n}=t;if(!me(n))return;js(),nn(!0);const i=document.getElementById("pipeline-progress"),r=document.getElementById("results-view"),s=document.getElementById("ready-state");if(s&&s.classList.add("hidden"),r&&r.classList.remove("visible"),document.body.classList.remove("results-fullscreen","results-with-sidebar"),i&&i.classList.add("visible"),Ms("running"),e!==null){const a=document.getElementById("pipeline-submitted-prompt");a&&(a.textContent=e)}xf=Date.now();const o=document.getElementById("progress-elapsed");o&&(o.textContent="0s"),xn={1:"pending",2:"pending",3:"pending"},Ll(),Nl(),kf(""),[1,2,3].forEach(a=>wn(a,"pending")),yt(1,n),a0()}function yt(t,e){me(e)&&(Rl=t,Ll(),[1,2,3].forEach(n=>{n===t?wn(n,"active"):nt&&wn(n,"pending")}),Ns(t),Ls())}function zt(t,e){me(e)&&(wn(t,"done"),Tl===null&&Ns(t,{done:!0}),Ls())}function Bs(t,{stage:e=1,runId:n,retry:i=Cf}={}){if(!me(n))return;Ds(),js(),Xt(),Ms("failed"),nn(!0);const r=document.getElementById("pipeline-progress");r&&r.classList.add("visible");const s=document.getElementById("results-view");s&&s.classList.remove("visible"),document.body.classList.remove("results-fullscreen","results-with-sidebar"),wn(e,"failed"),[1,2,3].forEach(p=>{p>e&&wn(p,"pending")}),Rl=e,Ll(),Ns(e),Ls();const o=l_(t),a=document.getElementById("pipeline-failure"),l=document.getElementById("pipeline-failure-title"),u=document.getElementById("pipeline-failure-message"),c=document.getElementById("pipeline-failure-hint"),d=document.getElementById("pipeline-failure-actions");if(!a||!l||!u||!d)return;if(a.dataset.kind=o.kind,l.textContent=`${$l[e]}: ${o.title}`,u.textContent=o.message,c){const p=o.detail&&o.detail!==o.message?o.detail:"";c.textContent=p,c.hidden=!p}d.replaceChildren();const h=[o.canUpgrade&&{id:"upgrade",label:"View plans",variant:"primary",onClick:()=>ji()},o.canRetry&&{id:"retry",label:"Retry",variant:o.canUpgrade?"secondary":"primary",onClick:i},o.canEdit&&{id:"edit",label:"Edit prompt",variant:"secondary",onClick:La}].filter(Boolean);!o.canEdit&&!o.canRetry&&h.push({id:"edit",label:"Back to prompt",variant:"secondary",onClick:La}),h.forEach(p=>{const g=document.createElement("button");g.type="button",g.textContent=p.label,g.dataset.action=p.id,g.dataset.variant=p.variant,g.addEventListener("click",p.onClick),d.appendChild(g)}),a.hidden=!1;const f=d.querySelector("button");f&&f.focus({preventScroll:!0})}function La(){Xy(),Ly(),y.isRunning=!1,Ma(!1),rn(),Ms("settled"),Xt(),Ds(),js(),Nl();const t=document.getElementById("pipeline-progress");t&&t.classList.remove("visible"),nn(!1);const e=document.getElementById("pipeline-input");e&&(y.submittedPrompt&&(e.value=y.submittedPrompt),e.focus({preventScroll:!0}),e.setSelectionRange(e.value.length,e.value.length))}function Cf(){const t=document.getElementById("pipeline-input");t&&y.submittedPrompt&&(t.value=y.submittedPrompt),wt=y.submittedImages.slice(),Es(),Nl(),os()}function a0(){Ds(),Sr=setInterval(()=>{const t=(Date.now()-xf)/1e3,e=document.getElementById("progress-elapsed");e&&(e.textContent=`${Math.floor(t)}s`)},250)}function Ds(){Sr&&(clearInterval(Sr),Sr=null)}let Ci=null;function js(){Ci&&(clearTimeout(Ci),Ci=null)}function Us(){Ds(),js(),Ms("settled"),Ls();const t=document.getElementById("pipeline-progress-fill");Ci=setTimeout(()=>{Ci=null;const e=document.getElementById("pipeline-progress");e&&e.classList.remove("visible"),t&&(t.style.width="0%")},400)}function bn(t,e=""){const n={pass:'',warning:'',fail:'',info:''};return``}function Af(t){return{pass:"Passed review",warning:"Needs attention",fail:"Blocking issues"}[t]||"Needs attention"}function l0(){return _v({bundle:y.artifactBundle,reviewResult:y.step3Result})}function c0(t){return` -
    - ${bn(t.severity)} -
    -
    ${W(t.message)}
    - ${t.suggestion?`
    ${W(t.suggestion)}
    `:""} - ${W(t.source)} -
    -
    - `}function u0(t){return` -
  • -
    - ${W(t.title)} - ${t.detail&&t.detail!==t.title?`

    ${W(t.detail)}

    `:""} -
    -
  • - `}function d0(t){const e=document.getElementById("results-summary-detail"),n=document.getElementById("results-title");if(!e)return;n&&(n.textContent=t.title);const i=t.score,r=i==null?"neutral":i>=80?"pass":i>=60?"warning":"fail",s=i==null?"":i>=80?"Strong":i>=60?"Needs work":"High risk",o=t.findings.length?` -
      - ${t.findings.map(u=>` -
    • - ${bn(u.severity)} - - ${W(u.message)} - ${u.suggestion?`${W(u.suggestion)}`:""} - -
    • - `).join("")} -
    - `:"",a=t.warnings.length?` -
    -

    ${bn("warning")} Bundle

    -
      - ${t.warnings.map(u=>`
    • ${W(u)}
    • `).join("")} -
    -
    - `:"",l=t.manualSteps.length?` -
    -

    ${bn("info")} Complete in FlutterFlow

    -

    For your information — these don't block the deploy. Finish them by hand in the FlutterFlow editor once the code is pushed.

    -
      - ${t.manualSteps.map(u=>` -
    • - ${W(u.title)} - ${u.detail&&u.detail!==u.title?`${W(u.detail)}`:""} -
    • - `).join("")} -
    -
    - `:"";e.innerHTML=` -
    -
    -

    ${W(t.summary)}

    - ${o} - ${a} - ${l} -
    -
    - -
    - Is the generated code correct? -
    - - -
    -
    -
    -
    - `}function h0(t){const e=t.artifacts.find(l=>l.id===y.selectedArtifactId)||t.artifacts[0];if(!e)return"";const n={pass:{icon:"pass",message:"No file-specific issues were found."},warning:{icon:"warning",message:"This file needs attention, but Code Review did not return a specific finding."},fail:{icon:"fail",message:"This file is blocked, but Code Review did not return a specific finding."}}[e.status],i=e.findings.length?e.findings.map(c0).join(""):`
    ${bn(n.icon)} ${W(n.message)}
    `,r=e.dependencies?.length?e.dependencies.map(l=>` -
  • ${W(l.name)}${l.version?` ${W(l.version)}`:""}${l.reason?`

    ${W(l.reason)}

    `:""}
  • - `).join(""):'
  • No external packages
  • ',s=e.imports?.length?e.imports.map(l=>`${W(l)}`).join(""):'No imports returned',o=e.publicApi?.length?e.publicApi.map(l=>`${W(l)}`).join(""):'No public API signature returned',a=e.relationships.length?e.relationships.map(l=>` -
  • ${W(l.from||"Bundle")} ${W(l.type)} ${W(l.to||"Bundle")}${l.description?`

    ${W(l.description)}

    `:""}
  • - `).join(""):'
  • No relationships for this file
  • ';return` -
    -
    - ${bn(e.status)} ${W(Af(e.status))} -

    ${W(e.artifactName)}

    - ${e.description?`

    ${W(e.description)}

    `:""} -
    -
    - ${W(e.artifactType)} - ${W(e.fileName)} -
    -
    -
    -

    Code Review findings

    - ${i} -
    - ${e.manualSteps.length?` -
    -

    Manual FlutterFlow steps for this file

    -
      ${e.manualSteps.map(u0).join("")}
    -
    - `:""} -
    - File details -
    -
    -

    Dependencies

    -
      ${r}
    -
    -
    -

    Deployment

    -
    -
    Status
    ${W(e.deployStatus||"pending")}
    -
    Order
    ${e.index+1} of ${t.artifacts.length}
    -
    Path hint
    ${W(e.pathHint||"Not returned")}
    -
    -
    -
    -
    -

    Public API

    -
    ${o}
    -
    -
    -

    Imports

    -
    ${s}
    -
    -
    -

    Relationships

    -
      ${a}
    -
    -
    - `}function f0(t){const e=document.getElementById("bundle-strip"),n=document.getElementById("results-summary-tab"),i=document.getElementById("artifact-tabs"),r=document.getElementById("results-file-count");if(n){const s=y.resultsViewMode==="summary";n.classList.toggle("active",s),n.setAttribute("role","tab"),n.setAttribute("aria-selected",String(s)),n.setAttribute("aria-controls","results-summary-detail"),n.tabIndex=s?0:-1}if(i&&(i.setAttribute("role","tablist"),i.setAttribute("aria-label","Artifacts in this bundle")),!t.artifacts.length){r&&(r.textContent="0 files"),e&&e.classList.remove("visible"),i&&(i.innerHTML=""),Nu();return}if(r){const s=t.artifacts.length;r.textContent=`${s} ${s===1?"file":"files"}`}i&&(i.innerHTML=t.artifacts.map(s=>{const o=y.resultsViewMode==="file"&&s.id===y.selectedArtifactId;return` - - `}).join(""),i.onclick=s=>{const o=s.target.closest(".artifact-tab");o?.dataset?.artifactId&&Bl(o.dataset.artifactId)},Nu()),e&&e.classList.add("visible")}function Nu(){const t=document.getElementById("bundle-strip");!t||t.dataset.tabKeyboard==="bound"||(t.dataset.tabKeyboard="bound",t.addEventListener("keydown",e=>{if(e.defaultPrevented)return;const n=[document.getElementById("results-summary-tab"),...Array.from(document.querySelectorAll("#artifact-tabs .artifact-tab"))].filter(Boolean);if(!n.length||!n.includes(document.activeElement))return;let i=-1;const r=n.indexOf(document.activeElement);if(e.key==="ArrowRight")i=(r+1)%n.length;else if(e.key==="ArrowLeft")i=(r-1+n.length)%n.length;else if(e.key==="Home")i=0;else if(e.key==="End")i=n.length-1;else return;e.preventDefault();const s=n[i];if(!s)return;if(s.id==="results-summary-tab")Pf();else{const a=s.dataset.artifactId;a&&Bl(a)}const o=s.id==="results-summary-tab"?document.getElementById("results-summary-tab"):document.querySelector(`#artifact-tabs .artifact-tab[data-artifact-id="${s.dataset.artifactId}"]`);o&&o.focus()}))}function Ol(){document.body.classList.add("results-fullscreen"),document.body.classList.add("results-with-sidebar");const t=document.getElementById("results-view"),e=document.getElementById("results-code-output"),n=document.getElementById("results-audit-output"),i=document.getElementById("results-summary-detail"),r=document.getElementById("artifact-results-split"),s=l0(),o=ml();if(i&&(i.setAttribute("role","tabpanel"),i.setAttribute("aria-labelledby","results-summary-tab")),r){r.setAttribute("role","tabpanel");const a=s?.artifacts?.find(l=>l.id===y.selectedArtifactId);r.setAttribute("aria-labelledby",a?`artifact-tab-${a.id}`:"results-summary-tab")}if(d0(s),f0(s),e&&(e.textContent=""),e){const a=zh(o);e.innerHTML=a}n&&(n.innerHTML=h0(s)),i&&i.classList.toggle("hidden",y.resultsViewMode!=="summary"),r&&r.classList.toggle("hidden",y.resultsViewMode!=="file"),t&&t.classList.add("visible")}function Hs(t,e){nn(!0),y.selectedArtifactId||(y.selectedArtifactId=Kr(y.artifactBundle).id),y.resultsViewMode="summary",document.body.classList.add("results-fullscreen");const n=document.getElementById("step3-output");n&&(n.textContent=""),Ol(),rn();const i=document.getElementById("btn-feedback-up"),r=document.getElementById("btn-feedback-down");i&&(i.className="feedback-btn"),r&&(r.className="feedback-btn")}function Bl(t){y.selectedArtifactId=t,y.resultsViewMode="file",Ol()}function Pf(){y.resultsViewMode="summary",Ol()}function p0(){const t=document.getElementById("btn-copy-results"),e=document.getElementById("results-copy-status"),n=ml(),i=(r,s)=>{e&&(e.textContent=r,e.classList.toggle("ok",!!s),e.classList.toggle("fail",!s))};if(!navigator.clipboard?.writeText){i("Copying isn't supported in this browser.",!1);return}navigator.clipboard.writeText(n).then(()=>{if(i("Copied to clipboard",!0),t){t.classList.add("copied");const r=t.querySelector("span");if(r){const s=r.textContent;r.textContent="Copied!",setTimeout(()=>{t.classList.remove("copied"),r.textContent=s},2e3)}}}).catch(()=>{i("Clipboard permission was denied. Select the code to copy it manually.",!1)})}function g0(t){const e=document.getElementById("btn-feedback-up"),n=document.getElementById("btn-feedback-down");t==="up"?(e.classList.toggle("active-up"),n.classList.remove("active-down")):(n.classList.toggle("active-down"),e.classList.remove("active-up")),Sl(t==="up"?"thumbsUp":"thumbsDown",y.step2Result,y.step1Result)}function m0(){const t=document.getElementById("error-input-panel");if(t){t.classList.remove("hidden"),t.style.display="flex";const e=document.getElementById("ff-error-paste-input");e&&setTimeout(()=>e.focus(),100)}}function Ff(){const t=document.getElementById("error-input-panel");t&&(t.classList.add("hidden"),t.style.display="none")}function nn(t){const e=document.getElementById("generation-stage");e&&(t?(e.hidden=!1,e.inert=!1,requestAnimationFrame(()=>e.classList.add("is-active"))):(e.classList.remove("is-active"),e.inert=!0,setTimeout(()=>{e.classList.contains("is-active")||(e.hidden=!0)},260)))}function Rf(){const t=G.isVerified&&!!G.email,e=be.tier||"free",n=t&&qi(),i=!t||Vt(),s=n?"Checking…":i?{free:"Free",professional:"Pro",power:"Power"}[e]||"Free":"—",o=document.getElementById("topbar-plan");o&&(o.textContent=s);const a=document.getElementById("topbar-avatar");a&&(a.textContent=(G.email||"?")[0].toUpperCase()),Al();const l=document.getElementById("plans-free-current");l&&l.classList.toggle("hidden",e!=="free"||!i);const u=document.getElementById("plans-checkout-btn-professional");if(u){const d=e==="professional"&&i;u.disabled=d,u.textContent=d?"Current plan":"Subscribe"}const c=document.getElementById("plans-checkout-btn-power");if(c){const d=e==="power"&&i;c.disabled=d,c.textContent=d?"Current plan":"Subscribe"}}function v0(){Rf();const t=document.getElementById("credits-modal");t&&tt(t)}function _0(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("credits-modal");e&&ct(e)}function Tf(t,e=!0,n=!0){if(t=["home","account","plans"].includes(t)?t:"home",document.querySelectorAll(".view[data-view]").forEach(r=>{r.dataset.view===t?(r.hidden=!1,r.removeAttribute("inert"),requestAnimationFrame(()=>{r.classList.add("is-active"),n&&r.focus({preventScroll:!0})})):(r.classList.remove("is-active"),r.setAttribute("inert","true"),setTimeout(()=>{r.classList.contains("is-active")||(r.hidden=!0)},260))}),t!=="home")nn(!1);else{const r=document.getElementById("main-stage-container");r&&r.classList.contains("visible")&&nn(!0)}if(document.querySelectorAll(".nav-link[data-view]").forEach(r=>{const s=r.dataset.view===t;r.setAttribute("aria-current",s?"page":null),s||r.removeAttribute("aria-current")}),e){const r=t==="home"?"":`#${t}`;window.location.hash!==r&&window.history.pushState({view:t},"",r||"#")}}let Ou=!1;function Dl(){const t=window.location.hash.replace(/^#/,"");Tf(t||"home",!1,Ou),Ou=!0}window.addEventListener("popstate",t=>{Dl()});window.addEventListener("hashchange",()=>{Dl()});function y0(){const t=document.querySelectorAll("#example-chips .chip"),e=document.getElementById("pipeline-input");t.forEach(n=>{n.addEventListener("click",()=>{e&&(e.value=n.dataset.prompt||""),e?.focus()})})}window.copyResultsCode=p0;window.selectArtifact=Bl;window.selectResultsSummary=Pf;window.submitResultsFeedback=g0;window.showErrorInputPanel=m0;window.hideErrorInputPanel=Ff;window.setGenerationStageVisible=nn;window.switchView=Tf;window.selectPipelineStage=e0;window.editPipelinePrompt=La;window.retryPipelineRun=Cf;window.openCreditsModal=v0;window.closeCreditsModal=_0; diff --git a/dist/assets/index-DMRXA2V6.js b/dist/assets/index-DMRXA2V6.js deleted file mode 100644 index 9340b43..0000000 --- a/dist/assets/index-DMRXA2V6.js +++ /dev/null @@ -1,320 +0,0 @@ -(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const s of document.querySelectorAll('link[rel="modulepreload"]'))i(s);new MutationObserver(s=>{for(const r of s)if(r.type==="childList")for(const o of r.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&i(o)}).observe(document,{childList:!0,subtree:!0});function n(s){const r={};return s.integrity&&(r.integrity=s.integrity),s.referrerPolicy&&(r.referrerPolicy=s.referrerPolicy),s.crossOrigin==="use-credentials"?r.credentials="include":s.crossOrigin==="anonymous"?r.credentials="omit":r.credentials="same-origin",r}function i(s){if(s.ep)return;s.ep=!0;const r=n(s);fetch(s.href,r)}})();var _=typeof window<"u"?window:void 0,we=typeof globalThis<"u"?globalThis:_,ke=we?.navigator,C=we?.document,se=we?.location,Ko=we?.fetch,Wr=we!=null&&we.XMLHttpRequest&&"withCredentials"in new we.XMLHttpRequest?we.XMLHttpRequest:void 0,Ka=we?.AbortController,Ih=we?.CompressionStream,Fe=ke?.userAgent;function Dc(){return!(!_||_.navigator.onLine===!1)}var Tn=typeof globalThis<"u"?globalThis:_;Tn&&typeof self>"u"&&(Tn.self=Tn),Tn&&typeof File>"u"&&(Tn.File=function(){});var R=_??{},Y={DEBUG:!1,LIB_VERSION:"0.5.0",LIB_NAME:"browser-common"};function Ja(t,e,n,i,s,r,o){try{var a=t[r](o),l=a.value}catch(u){return void n(u)}a.done?e(l):Promise.resolve(l).then(i,s)}function X(t){return function(){var e=this,n=arguments;return new Promise((function(i,s){var r=t.apply(e,n);function o(l){Ja(r,i,s,o,a,"next",l)}function a(l){Ja(r,i,s,o,a,"throw",l)}o(void 0)}))}}function b(){return b=Object.assign?Object.assign.bind():function(t){for(var e=1;arguments.length>e;e++){var n=arguments[e];for(var i in n)({}).hasOwnProperty.call(n,i)&&(t[i]=n[i])}return t},b.apply(null,arguments)}function jc(t,e){if(t==null)return{};var n={};for(var i in t)if({}.hasOwnProperty.call(t,i)){if(e.indexOf(i)!==-1)continue;n[i]=t[i]}return n}var Ya=t=>{if(typeof t!="string")return t;try{return JSON.parse(t)}catch{return t}};function Za(t){return typeof t=="string"||t}function Xa(t){return typeof t=="string"?t:void 0}var Rn,Ch=["$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","irclid","_kx","$session_id","$window_id","$lib","$lib_version","$device_id","$is_server"],pt=(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.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.SurveysSeen="surveys_seen",t.Surveys="surveys",t.RemoteConfig="remote_config",t.FlagsEndpointWasHit="flags_endpoint_was_hit",t.DeviceId="device_id",t})({}),Qa=(function(t){return t.GZipJS="gzip-js",t.Base64="base64",t})({}),Ah=["$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"],Fh=["token"],Uc="NativeGzipValidationError",zr=t=>t.length>=2&&t[0]===31&&t[1]===139,el=(t,e)=>t===Qa.GZipJS||e===Qa.GZipJS||e==="gzip",tl=t=>!(!t||typeof t!="object")&&("name"in t?String(t.name):"")==="NotReadableError",ki=t=>{var e=new Error("Native gzip produced invalid output: "+t);throw e.name=Uc,e},Ph=(function(){var t=X((function*(e,n){18>e.size&&ki("too-short");var i=new Uint8Array(yield e.slice(0,10).arrayBuffer());zr(i)&&i[2]===8||ki("invalid-header");var s=new DataView(yield e.slice(e.size-8).arrayBuffer());s.getUint32(0,!0)!==(o=>{for(var a=(()=>{if(Rn)return Rn;Rn=[];for(var c=0;256>c;c++){for(var d=c,h=0;8>h;h++)d=1&d?3988292384^d>>>1:d>>>1;Rn[c]=d>>>0}return Rn})(),l=4294967295,u=0;o.length>u;u++)l=a[255&(l^o[u])]^l>>>8;return(4294967295^l)>>>0})(n)&&ki("invalid-crc");var r=n.length>>>0;s.getUint32(4,!0)!==r&&ki("invalid-size")}));return function(e,n){return t.apply(this,arguments)}})();function qr(){return qr=X((function*(t,e,n){e===void 0&&(e=!0);try{var i=new TextEncoder().encode(t),s=new globalThis.CompressionStream("gzip"),r=s.writable.getWriter(),o=r.write(i).then((()=>r.close())).catch((function(){var u=X((function*(c){try{yield r.abort(c)}catch{}throw c}));return function(c){return u.apply(this,arguments)}})()),a=new Response(s.readable).blob(),l=(yield Promise.all([a,o]))[0];return yield Ph(l,i),l}catch(u){if(n!=null&&n.rethrow)throw u;return e&&console.error("Failed to gzip compress data",u),null}})),qr.apply(this,arguments)}var $h=["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","pinterest","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"],nl=function(t,e){if(e===void 0&&(e=[]),!t)return!1;var n=t.toLowerCase();return $h.concat(e).some((i=>{var s=i.toLowerCase();return n.indexOf(s)!==-1}))};function L(t,e){return t.indexOf(e)!==-1}var Bs=function(t){return t.trim()},Vr=function(t){return t.replace(/^\$/,"")};function Hc(t){var e,n=[];return(e=JSON.stringify(t,(function(i,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"}var Wc=Object.prototype,zc=Wc.hasOwnProperty,Ds=Wc.toString,O=Array.isArray||function(t){return Ds.call(t)==="[object Array]"},Se=t=>typeof t=="function",ne=t=>t===Object(t)&&!O(t),yt=t=>{if(ne(t)){for(var e in t)if(zc.call(t,e))return!1;return!0}return!1},x=t=>t===void 0,q=t=>Ds.call(t)=="[object String]",Gr=t=>q(t)&&t.trim().length===0,$e=t=>t===null,B=t=>x(t)||$e(t),he=t=>Ds.call(t)=="[object Number]"&&t==t,dt=t=>he(t)&&t>0,Ye=t=>Ds.call(t)==="[object Boolean]",Th=t=>t instanceof FormData,Rh=t=>L(Ah,t),Nh=t=>L(Fh,t);function qc(t){return t===null||typeof t!="object"}function es(t,e){return{}.toString.call(t)==="[object "+e+"]"}function Jo(t){return typeof Event<"u"&&Vc(t,Event)}function Vc(t,e){try{return t instanceof e}catch{return!1}}var Mh=[!0,"true",1,"1","yes"],cr=t=>L(Mh,t),Lh=[!1,"false",0,"0","no"];function ot(t,e,n,i,s){return e>n&&(i.warn("min cannot be greater than max."),e=n),he(t)?t>n?(i.warn(" cannot be greater than max: "+n+". Using max value instead."),n):e>t?(i.warn(" cannot be less than min: "+e+". Using min value instead."),e):t:(i.warn(" must be a number. using max or fallback. max: "+n+", fallback: "+s),ot(s||n,e,n,i))}class Oh{constructor(e){this.tt={},this.et=e.et,this.it=ot(e.bucketSize,0,100,e.rt),this.nt=ot(e.refillRate,0,this.it,e.rt),this.st=ot(e.refillInterval,0,864e5,e.rt)}ot(e,n){var i=Math.floor((n-e.lastAccess)/this.st);i>0&&(e.tokens=Math.min(e.tokens+i*this.nt,this.it),e.lastAccess=e.lastAccess+i*this.st)}consumeRateLimit(e){var n,i=Date.now(),s=String(e),r=this.tt[s];return r?this.ot(r,i):this.tt[s]=r={tokens:this.it,lastAccess:i},r.tokens===0||(r.tokens--,r.tokens===0&&((n=this.et)==null||n.call(this,e)),r.tokens===0)}stop(){this.tt={}}}var Oe="Mobile",ts="iOS",wt="Android",vn="Tablet",Gc=wt+" "+vn,Kc="iPad",Jc="Apple",Yc=Jc+" Watch",Yn="Safari",_n="BlackBerry",Zc="Samsung",Xc=Zc+"Browser",Qc=Zc+" Internet",Yt="Chrome",Bh=Yt+" OS",eu=Yt+" "+ts,Yo="Internet Explorer",tu=Yo+" "+Oe,Zo="Opera",Dh=Zo+" Mini",Xo="Edge",nu="Microsoft "+Xo,fn="Firefox",iu=fn+" "+ts,ri="Nintendo",oi="PlayStation",gn="Xbox",su=wt+" "+Oe,ru=Oe+" "+Yn,Wn="Windows",Kr=Wn+" Phone",il="Nokia",Jr="Ouya",ou="Generic",jh=ou+" "+Oe.toLowerCase(),au=ou+" "+vn.toLowerCase(),Yr="Konqueror",lu="Oculus Browser",ns="Vivaldi",cu="Yandex",is="Whale",Zr="DuckDuckGo",uu="Pale Moon",ss="Waterfox",Zn="Brave",du="Google Search App",le="(\\d+(\\.\\d+)?)",ur=new RegExp("Version/"+le),Uh=new RegExp(gn,"i"),Hh=new RegExp(oi+" \\w+","i"),Wh=new RegExp(ri+" \\w+","i"),Qo=new RegExp(_n+"|PlayBook|BB10","i"),zh={"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"},hu=function(t,e,n,i){e=e||"";var s=(function(r){return r!=null&&r.brave?Zn:null})(n);return s||(i!=null&&i.detectGoogleSearchApp&&L(t,"GSA/")?du:L(t," OPR/")&&L(t,"Mini")?Dh:L(t," OPR/")?Zo:Qo.test(t)?_n:L(t,"IE"+Oe)||L(t,"WPDesktop")?tu:L(t,"OculusBrowser")?lu:L(t,Xc)?Qc:L(t,Xo)||L(t,"Edg/")?nu:L(t,ns+"/")?ns:L(t,"YaBrowser/")?cu:L(t,is+"/")?is:L(t,Zr+"/")||L(t,"Ddg/")?Zr:L(t,"FBIOS")?"Facebook "+Oe:L(t,"UCWEB")||L(t,"UCBrowser")?"UC Browser":L(t,"CriOS")?eu:L(t,"CrMo")||L(t,Yt)?Yt:L(t,wt)&&L(t,Yn)?su:L(t,"FxiOS")?iu:L(t.toLowerCase(),Yr.toLowerCase())?Yr:L(t,Zn+"/")?Zn:((r,o)=>o&&L(o,Jc)||(function(a){return L(a,Yn)&&!L(a,Yt)&&!L(a,wt)})(r))(t,e)?L(t,Oe)?ru:Yn:L(t,"PaleMoon/")?uu:L(t,ss+"/")?ss:L(t,fn)?fn:L(t,"MSIE")||L(t,"Trident/")?Yo:L(t,"Gecko")?fn:"")},qh={[tu]:[new RegExp("rv:"+le)],[nu]:[new RegExp(Xo+"?\\/"+le)],[Yt]:[new RegExp("("+Yt+"|CrMo)\\/"+le)],[eu]:[new RegExp("CriOS\\/"+le)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+le)],[Yn]:[ur],[ru]:[ur],[Zo]:[new RegExp("(Opera|OPR)\\/"+le)],[fn]:[new RegExp(fn+"\\/"+le)],[iu]:[new RegExp("FxiOS\\/"+le)],[Yr]:[new RegExp("Konqueror[:/]?"+le,"i")],[_n]:[new RegExp(_n+" "+le),ur],[su]:[new RegExp("android\\s"+le,"i")],[Qc]:[new RegExp(Xc+"\\/"+le)],[lu]:[new RegExp("OculusBrowser\\/"+le)],[ns]:[new RegExp(ns+"\\/"+le)],[cu]:[new RegExp("YaBrowser\\/"+le)],[is]:[new RegExp(is+"\\/"+le)],[Zn]:[new RegExp(Zn+"\\/"+le)],[Zr]:[new RegExp("(DuckDuckGo|Ddg)\\/"+le)],[uu]:[new RegExp("PaleMoon\\/"+le)],[ss]:[new RegExp(ss+"\\/"+le)],[du]:[new RegExp("GSA\\/"+le)],[Yo]:[new RegExp("(rv:|MSIE )"+le)],Mozilla:[new RegExp("rv:"+le)]},Vh=function(t,e,n,i){var s=hu(t,e,n,i),r=qh[s];if(x(r))return null;for(var o=0;r.length>o;o++){var a=t.match(r[o]);if(a)return parseFloat(a[a.length-2])}return null},sl=[[new RegExp(gn+"; "+gn+" (.*?)[);]","i"),t=>[gn,t&&t[1]||""]],[new RegExp(ri,"i"),[ri,""]],[new RegExp(oi,"i"),[oi,""]],[Qo,[_n,""]],[new RegExp(Wn,"i"),(t,e)=>{if(/Phone/.test(e)||/WPDesktop/.test(e))return[Kr,""];if(new RegExp(Oe).test(e)&&!/IEMobile\b/.test(e))return[Wn+" "+Oe,""];var n=/Windows NT ([0-9.]+)/i.exec(e);if(n&&n[1]){var i=zh[n[1]]||"";return/arm/i.test(e)&&(i="RT"),[Wn,i]}return[Wn,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,t=>t&&t[3]?[ts,[t[3],t[4],t[5]||"0"].join(".")]:[ts,""]],[/(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i,t=>{var e="";return t&&t.length>=3&&(e=x(t[2])?t[3]:t[2]),["watchOS",e]}],[new RegExp("("+wt+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+wt+")","i"),t=>t&&t[2]?[wt,[t[2],t[3],t[4]||"0"].join(".")]:[wt,""]],[/Mac OS X (\d+)[_.](\d+)[_.]?(\d+)?/i,t=>{var 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/,[Bh,""]],[/Linux|debian/i,["Linux",""]]],rl=function(t){return Wh.test(t)?ri:Hh.test(t)?oi:Uh.test(t)?gn:new RegExp(Jr,"i").test(t)?Jr:new RegExp("("+Kr+"|WPDesktop)","i").test(t)?Kr:/iPad/.test(t)?Kc:/iPod/.test(t)?"iPod Touch":/iPhone/.test(t)?"iPhone":/(watch)(?: ?os[,/]|\d,\d\/)[\d.]+/i.test(t)?Yc:Qo.test(t)?_n:/(kobo)\s(ereader|touch)/i.test(t)?"Kobo":new RegExp(il,"i").test(t)?il:/(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(Oe).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)?wt:Gc:new RegExp("(pda|"+Oe+")","i").test(t)?jh:new RegExp(vn,"i").test(t)&&!new RegExp(vn+" pc","i").test(t)?au:""},Gh=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function ol(t,e){return typeof(n=t)=="string"&&Gh.test(n)?t:e();var n}function Pt(t){return t&&t.split("#")[0]}function ea(t,e){var n=setTimeout(t,e);return n?.unref&&n?.unref(),n}function al(t,e,n){return pu.apply(this,arguments)}function pu(){return(pu=X((function*(t,e,n){var i;try{return yield Promise.race([t,new Promise(((s,r)=>{i=ea((()=>{try{n?.(),s()}catch(o){r(o)}}),e)}))])}finally{clearTimeout(i)}}))).apply(this,arguments)}var Kh=t=>t instanceof Error,fu={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}},Jh=fu.info;function gu(t){if(Ye(t))return{boolValue:t};if(typeof t=="number")return Number.isFinite(t)?Number.isInteger(t)?{intValue:t}:{doubleValue:t}:{stringValue:String(t)};if(typeof t=="string")return{stringValue:t};if(O(t))return{arrayValue:{values:t.map((e=>gu(e)))}};try{return{stringValue:JSON.stringify(t)}}catch{return{stringValue:String(t)}}}function rs(t){var e=[];for(var n in t){var i=t[n];$e(i)||x(i)||e.push({key:n,value:gu(i)})}return e}function Yh(t,e){var n=fu[t.level||"info"]||Jh,i=n.text,s=n.number,r=String(Date.now())+"000000",o={};e.distinctId&&(o.posthogDistinctId=e.distinctId),e.sessionId&&(o.sessionId=e.sessionId),e.windowId&&(o["window.id"]=e.windowId),B(e.sessionStartTimestamp)||(o.sessionStartTimestamp=String(e.sessionStartTimestamp)),B(e.lastActivityTimestamp)||(o.lastActivityTimestamp=String(e.lastActivityTimestamp)),e.currentUrl&&(o["url.full"]=e.currentUrl),e.screenName&&(o["screen.name"]=e.screenName),e.appState&&(o["app.state"]=e.appState),e.activeFeatureFlags&&e.activeFeatureFlags.length>0&&(o.feature_flags=e.activeFeatureFlags);var a=b({},o,t.attributes||{}),l={timeUnixNano:r,observedTimeUnixNano:r,severityNumber:s,severityText:i,body:{stringValue:t.body},attributes:rs(a)};return t.trace_id&&(l.traceId=t.trace_id),t.span_id&&(l.spanId=t.span_id),x(t.trace_flags)||(l.flags=t.trace_flags),l}function mu(t,e,n){return b({},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})}function vu(t,e,n,i){return{resourceLogs:[{resource:{attributes:rs(e)},scopeLogs:[{scope:{name:n,version:i},logRecords:t}]}]}}let Zh=class{constructor(t,e,n,i,s,r,o){var a;r===void 0&&(r=()=>Promise.resolve()),this._instance=t,this.Ne=e,this.rt=n,this.ut=i,this.ht=s,this.dt=r,this.vt=o,this.ct=null,this.ft=0,this.yt=0,this.bt=0,this._t=0,this.wt=!1,this.kt=e.maxBufferSize,this.xt=Math.max((a=e.maxQueueSize)!==null&&a!==void 0?a:e.maxBufferSize,e.maxBufferSize),this.St=e.flushIntervalMs,this.Ct=e.maxBatchRecordsPerPost,this.Mt=e.rateCapWindowMs,this.Tt=e.maxLogsPerInterval}reset(){this.Et(),this.ct=null,this.bt=0,this._t=0,this.wt=!1,this.ft=0,this.yt=0,this.Ct=this.Ne.maxBatchRecordsPerPost}onReconnect(){this.yt=0,this.It()}captureLog(t){if(!this._instance.isDisabled&&!this._instance.optedOut&&t!=null&&t.body){var e=this.Pt(t);if(e!==null)if(e.body){if(this.Rt()){var n={record:Yh(e,this.ut())};this.ht((()=>this.At(n)))}}else this.rt.info("Log was rejected in beforeSend function")}}Pt(t){var e=this.Ne.beforeSend;if(!e)return t;var n=O(e)?e:[e],i=t;for(var s of n)try{var r=s(i);if(!r)return this.rt.info("Log was rejected in beforeSend function"),null;i=r}catch(o){return this.rt.error("Error in beforeSend function for log:",o),null}return i}Rt(){if(this.Tt===void 0)return!0;var t=Date.now(),e=t-this.bt;return this.Mt>e&&e>=0||(this.bt=t,this._t=0,this.wt=!1),this.Tt>this._t?(this._t++,!0):(this.wt||(this.rt.warn("captureLog dropping logs: exceeded "+this.Tt+" logs per "+this.Mt+"ms"),this.wt=!0),!1)}flush(){var t=this;return X((function*(){if(!t._instance.isDisabled)return t.ct||(t.ct=t.Ft().finally((()=>{t.ct=null}))),t.ct}))()}Ft(){var t=this;return X((function*(){var e;t.Et();var n=(e=t._instance.getPersistedProperty(pt.LogsQueue))!==null&&e!==void 0?e:[];if(n.length!==0)for(var i=n.length,s=0;n.length>0&&i>s;){var r,o;t.ft=0;var a=Math.min(n.length,t.Ct),l=n.slice(0,a),u=vu(l.map((d=>d.record)),t.Lt(),(r=t.vt)!==null&&r!==void 0?r:t._instance.getLibraryId(),t._instance.getLibraryVersion()),c=yield t._instance.Ot(u);if(c.kind==="too-large"&&l.length>1)t.Ct=Math.max(1,Math.floor(l.length/2)),t.rt.warn("Received 413 when sending logs batch of size "+l.length+", reducing batch size to "+t.Ct);else if(c.kind==="retry-later"||(c.kind==="too-large"?t.rt.warn("Dropping a single log record after 413 with batch size 1 — the record is larger than the server cap and cannot be split further."):c.kind==="ok"&&t.Ne.maxBatchRecordsPerPost>t.Ct&&(t.Ct=Math.min(t.Ne.maxBatchRecordsPerPost,t.Ct+1)),yield t.Dt(l.length),n=(o=t._instance.getPersistedProperty(pt.LogsQueue))!==null&&o!==void 0?o:[],s+=l.length,c.kind==="fatal"))throw c.error}}))()}Dt(t){var e=this;return X((function*(){var n,i=Math.max(0,t-e.ft),s=(n=e._instance.getPersistedProperty(pt.LogsQueue))!==null&&n!==void 0?n:[];e._instance.setPersistedProperty(pt.LogsQueue,s.slice(i)),yield e.dt()}))()}Lt(){return mu(this.Ne,this._instance.getLibraryId(),this._instance.getLibraryVersion())}At(t){var e;if(!this._instance.optedOut){var n=(e=this._instance.getPersistedProperty(pt.LogsQueue))!==null&&e!==void 0?e:[];this.xt>n.length||(n.shift(),this.ft++,this.rt.info("Logs queue is full, dropping oldest record.")),n.push(t),this._instance.setPersistedProperty(pt.LogsQueue,n),this.kt>n.length?this.$t():this.It()}}$t(t){t===void 0&&(t=this.St),this.Nt||(this.Nt=ea((()=>{this.Nt=void 0,this.It()}),t))}qt(){var t=Math.min(Math.max(0,this.yt-1),6);return this.St*Math.pow(2,t)}jt(){var t=this._instance.getPersistedProperty(pt.LogsQueue);return!!t&&t.length>0}shutdown(t){var e=this;return X((function*(){e.Et();var n=e.flush().catch((()=>{}));t!==void 0?yield al(n,t):yield n}))()}flushWithTimeout(t){var e=this;return X((function*(){var n=e.flush();yield al(n,t,(()=>{n.catch((()=>{}))}))}))()}It(){this.flush().then((()=>{this.yt=0}),(t=>{this.yt++,this.rt.error("PostHog logs flush failed:",t)})).finally((()=>{!this._instance.isDisabled&&this.jt()&&this.$t(this.qt())}))}Et(){this.Nt&&(clearTimeout(this.Nt),this.Nt=void 0)}};var dr=[0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4];function ll(t){return String(t)+"000000"}function cl(t,e,n,i){var s="";return i&&(s=Object.keys(i).sort().map((r=>JSON.stringify(r)+":"+JSON.stringify(i[r]))).join(",")),t+"\0"+e+"\0"+(n??"")+"\0"+s}let Xh=class{constructor(t,e,n){this._instance=t,this.Ne=e,this.rt=n,this.Bt=new Map,this.ct=null,this.Ht=!1,this.Ut=new Map,this.zt=new Set,this.Wt=0}count(t,e,n){e===void 0&&(e=1),this.Vt({name:t,type:"count",value:e,unit:n?.unit,attributes:n?.attributes})}gauge(t,e,n){this.Vt({name:t,type:"gauge",value:e,unit:n?.unit,attributes:n?.attributes})}histogram(t,e,n){this.Vt({name:t,type:"histogram",value:e,unit:n?.unit,attributes:n?.attributes})}flush(){var t=this,e=this.ct,n=(function(){var s=X((function*(){e&&(yield e.catch((()=>{}))),yield t.Zt()}));return function(){return s.apply(this,arguments)}})(),i=n().finally((()=>{this.ct===i&&(this.ct=null)}));return this.ct=i,i}drainWindow(){if(this.Bt.size===0)return null;var t=this.Bt;return this.Bt=new Map,this.Ht=!1,this.Ut=new Map,this.zt=new Set,this.Gt(t)}reset(){this.Wt++,this.Et(),this.Bt=new Map,this.ct=null,this.Ht=!1,this.Ut=new Map,this.zt=new Set}Vt(t){if(!this._instance.isDisabled&&!this._instance.optedOut){var e=this.Pt(t);if(e!==null)if(e.name&&typeof e.name=="string")if(typeof e.value=="number"&&Number.isFinite(e.value))if(e.type==="count"&&0>e.value)this.rt.warn("Dropping count '"+e.name+"': counters are monotonic, value must be >= 0");else{var n,i;try{n=e.attributes?b({},e.attributes):void 0,i=cl(e.type,e.name,e.unit,n)}catch(o){return void this.rt.warn("Dropping metric '"+e.name+"': attributes could not be serialized",o)}var s=this.Bt.get(i);if(!s){if(!this.Qt())return;s={name:e.name,type:e.type,unit:e.unit,attributes:n,windowStartMs:Date.now()},this.Bt.set(i,s)}var r=this.Ut.get(e.name);r===void 0?this.Ut.set(e.name,e.type):r===e.type||this.zt.has(e.name)||(this.zt.add(e.name),this.rt.warn("Metric name '"+e.name+"' is already used as a "+r+"; recording it as a "+e.type+" too will blend both series in charts. Use a distinct name.")),this.Kt(s,e.value),this.$t()}else this.rt.warn("Dropping metric '"+e.name+"': value must be a finite number");else this.rt.warn("Dropping metric with empty name")}}Qt(){return this.Ne.maxSeriesPerFlush>this.Bt.size||(this.Ht||(this.Ht=!0,this.rt.warn("Metric series cap reached ("+this.Ne.maxSeriesPerFlush+" per flush window); dropping new series until the next flush. Reduce attribute cardinality.")),!1)}Kt(t,e){var n;switch(t.type){case"count":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(dr.length+1).fill(0)});var i=t.hist;i.count+=1,i.sum+=e,i.min=Math.min(i.min,e),i.max=Math.max(i.max,e),i.bucketCounts[(function(s,r){for(var o=0;r.length>o;o++)if(r[o]>=s)return o;return r.length})(e,dr)]+=1}}Pt(t){var e=this.Ne.beforeSend;if(!e)return t;var n=O(e)?e:[e],i=t;for(var s of n)try{var r=s(i);if(!r)return this.rt.info("Metric was rejected in beforeSend function"),null;i=r}catch(o){return this.rt.error("Error in beforeSend function for metric:",o),null}return i}$t(){this.Nt||(this.Nt=ea((()=>{this.Nt=void 0,this.flush().catch((t=>{this.rt.error("Metrics flush failed:",t)}))}),this.Ne.flushIntervalMs))}Et(){this.Nt&&(clearTimeout(this.Nt),this.Nt=void 0)}Zt(){var t=this;return X((function*(){if(t.Bt.size!==0){var e=t.Bt;t.Bt=new Map,t.Ht=!1,t.Ut=new Map,t.zt=new Set;var n=t.Wt,i=yield t._instance.Jt(t.Gt(e));if(n===t.Wt)switch(i.kind){case"ok":return;case"retry-later":return t.Yt(e),void t.$t();case"too-large":return void t.rt.warn("Metrics batch exceeded the server size limit and was dropped");case"fatal":return void t.rt.error("Failed to send metrics batch:",i.error)}}}))()}Gt(t){return e=this.Xt(t),n=(function(r,o,a){return b({},r.resourceAttributes,{"service.name":r.serviceName||"unknown_service"},r.environment&&{"deployment.environment":r.environment},r.serviceVersion&&{"service.version":r.serviceVersion},{"telemetry.sdk.name":o,"telemetry.sdk.version":a})})(this.Ne,this._instance.getLibraryId(),this._instance.getLibraryVersion()),i=this._instance.getLibraryId(),s=this._instance.getLibraryVersion(),{resourceMetrics:[{resource:{attributes:rs(n)},scopeMetrics:[{scope:{name:i,version:s},metrics:e}]}]};var e,n,i,s}Xt(t){var e=ll(Date.now()),n=new Map;for(var i of t.values()){var s,r=cl(i.type,i.name,i.unit,void 0),o=n.get(r);o||(o=b({name:i.name},i.unit&&{unit:i.unit}),i.type==="count"?o.sum={aggregationTemporality:1,isMonotonic:!0,dataPoints:[]}:i.type==="gauge"?o.gauge={dataPoints:[]}:o.histogram={aggregationTemporality:1,dataPoints:[]},n.set(r,o));var a=rs((s=i.attributes)!==null&&s!==void 0?s:{}),l=ll(i.windowStartMs);if(i.type==="count"){var u,c={attributes:a,startTimeUnixNano:l,timeUnixNano:e,asDouble:(u=i.total)!==null&&u!==void 0?u:0};o.sum.dataPoints.push(c)}else if(i.type==="gauge"){var d,h={attributes:a,timeUnixNano:e,asDouble:(d=i.last)!==null&&d!==void 0?d:0};o.gauge.dataPoints.push(h)}else i.hist&&o.histogram.dataPoints.push({attributes:a,startTimeUnixNano:l,timeUnixNano:e,count:i.hist.count,sum:i.hist.sum,min:i.hist.min,max:i.hist.max,bucketCounts:i.hist.bucketCounts,explicitBounds:dr})}return Array.from(n.values())}Yt(t){var e,n;for(var i of t){var s=i[0],r=i[1],o=this.Bt.get(s);if(o)switch(o.windowStartMs=Math.min(o.windowStartMs,r.windowStartMs),o.type){case"count":o.total=((e=o.total)!==null&&e!==void 0?e:0)+((n=r.total)!==null&&n!==void 0?n:0);break;case"gauge":break;case"histogram":if(r.hist)if(o.hist){o.hist.count+=r.hist.count,o.hist.sum+=r.hist.sum,o.hist.min=Math.min(o.hist.min,r.hist.min),o.hist.max=Math.max(o.hist.max,r.hist.max);for(var a=0;o.hist.bucketCounts.length>a;a++)o.hist.bucketCounts[a]+=r.hist.bucketCounts[a]}else o.hist=r.hist}else this.Qt()&&this.Bt.set(s,r)}}};var Ii,ul,hr;function Qh(t){var e=globalThis._posthogChunkIds;if(e){var n=Object.keys(e);return hr&&n.length===ul||(ul=n.length,hr=n.reduce(((i,s)=>{Ii||(Ii={});var r=Ii[s];if(r)i[r[0]]=r[1];else for(var o=t(s),a=o.length-1;a>=0;a--){var l=o[a],u=l?.filename,c=e[s];if(u&&c){i[u]=c,Ii[s]=[u,c];break}}return i}),{})),hr}}class ep{constructor(e,n,i){i===void 0&&(i=[]),this.coercers=e,this.stackParser=n,this.modifiers=i}buildFromUnknown(e,n){n===void 0&&(n={});var i=n&&n.mechanism||{handled:!0,type:"generic"},s=this.buildCoercingContext(i,n,0).apply(e),r=this.buildParsingContext(n),o=this.parseStacktrace(s,r);return{$exception_list:this.convertToExceptionList(o,i),$exception_level:"error"}}modifyFrames(e){var n=this;return X((function*(){for(var i of e)i.stacktrace&&i.stacktrace.frames&&O(i.stacktrace.frames)&&(i.stacktrace.frames=yield n.applyModifiers(i.stacktrace.frames));return e}))()}coerceFallback(e){var n;return{type:"Error",value:"Unknown error",stack:(n=e.syntheticException)==null?void 0:n.stack,synthetic:!0}}parseStacktrace(e,n){var i,s;return e.cause!=null&&(i=this.parseStacktrace(e.cause,n)),e.stack!=""&&e.stack!=null&&(s=this.applyChunkIds(this.stackParser(e.stack,e.synthetic?n.skipFirstLines:0),n.chunkIdMap)),b({},e,{cause:i,stack:s})}applyChunkIds(e,n){return e.map((i=>(i.filename&&n&&(i.chunk_id=n[i.filename]),i)))}applyCoercers(e,n){for(var i of this.coercers)if(i.match(e))return i.coerce(e,n);return this.coerceFallback(n)}applyModifiers(e){var n=this;return X((function*(){var i=e;for(var s of n.modifiers)i=yield s(i);return i}))()}convertToExceptionList(e,n){var i,s,r,o={type:e.type,value:e.value,mechanism:{type:(i=n.type)!==null&&i!==void 0?i:"generic",handled:(s=n.handled)===null||s===void 0||s,synthetic:(r=e.synthetic)!==null&&r!==void 0&&r}};e.stack&&(o.stacktrace={type:"raw",frames:e.stack});var a=[o];return e.cause!=null&&a.push(...this.convertToExceptionList(e.cause,b({},n,{handled:!0}))),a}buildParsingContext(e){var n;return{chunkIdMap:Qh(this.stackParser),skipFirstLines:(n=e.skipFirstLines)!==null&&n!==void 0?n:1}}buildCoercingContext(e,n,i){i===void 0&&(i=0);var s=(r,o)=>{if(4>=o){var a=this.buildCoercingContext(e,n,o);return this.applyCoercers(r,a)}};return b({},n,{syntheticException:i==0?n.syntheticException:void 0,mechanism:e,apply:r=>s(r,i),next:r=>s(r,i+1)})}}var yn="?";function Xr(t,e,n,i,s){var r={platform:t,filename:e,function:n===""?yn:n,in_app:!0};return x(i)||(r.lineno=i),x(s)||(r.colno=s),r}var _u=(t,e)=>{var n=t.indexOf("safari-extension")!==-1,i=t.indexOf("safari-web-extension")!==-1;return n||i?[t.indexOf("@")!==-1?t.split("@")[0]:yn,n?"safari-extension:"+e:"safari-web-extension:"+e]:[t,e]},tp=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,np=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,ip=/\((\S*)(?::(\d+))(?::(\d+))\)/,sp=(t,e)=>{var n=tp.exec(t);if(n)return Xr(e,n[1],yn,+n[2],+n[3]);var i=np.exec(t);if(i){if(i[2]&&i[2].indexOf("eval")===0){var s=ip.exec(i[2]);s&&(i[2]=s[1],i[3]=s[2],i[4]=s[3])}var r=_u(i[1]||yn,i[2]);return Xr(e,r[1],r[0],i[3]?+i[3]:void 0,i[4]?+i[4]:void 0)}},rp=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,op=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,ap=(t,e)=>{var n=rp.exec(t);if(n){if(n[3]&&n[3].indexOf(" > eval")>-1){var i=op.exec(n[3]);i&&(n[1]=n[1]||"eval",n[3]=i[1],n[4]=i[2],n[5]="")}var s=n[3],r=n[1]||yn,o=_u(r,s);return Xr(e,s=o[1],r=o[0],n[4]?+n[4]:void 0,n[5]?+n[5]:void 0)}},dl=/\(error: (.*)\)/;class lp{match(e){return this.isDOMException(e)||this.isDOMError(e)}coerce(e,n){var i=q(e.stack);return{type:this.getType(e),value:this.getValue(e),stack:i?e.stack:void 0,cause:e.cause?n.next(e.cause):void 0,synthetic:!1}}getType(e){return this.isDOMError(e)?"DOMError":"DOMException"}getValue(e){var n=e.name||(this.isDOMError(e)?"DOMError":"DOMException");return e.message?n+": "+e.message:n}isDOMException(e){return es(e,"DOMException")}isDOMError(e){return es(e,"DOMError")}}class cp{match(e){return(function(n){switch({}.toString.call(n)){case"[object Error]":case"[object Exception]":case"[object DOMException]":case"[object DOMError]":case"[object WebAssembly.Exception]":return!0;default:return Vc(n,Error)}})(e)}coerce(e,n){return{type:this.getType(e),value:this.getMessage(e,n),stack:this.getStack(e),cause:e.cause?n.next(e.cause):void 0,synthetic:!1}}getType(e){return e.name||e.constructor.name}getMessage(e,n){var i=e.message;return String(i.error&&typeof i.error.message=="string"?i.error.message:i)}getStack(e){return e.stacktrace||e.stack||void 0}}class up{constructor(){}match(e){return!!es(e,"ErrorEvent")&&(e.error!=null||this.fe(e))}coerce(e,n){var i;if(e.error!=null)return n.apply(e.error);var s=n.apply(e.message);return b({},s,{stack:(i=this.pe(e))!==null&&i!==void 0?i:s.stack,synthetic:!0})}fe(e){return q(e.message)&&e.message.length>0}pe(e){var n=e;if(q(n.filename)&&n.filename.length>0){var i,s,r=(i=n.lineno)!==null&&i!==void 0?i:0,o=(s=n.colno)!==null&&s!==void 0?s:0;return`Error - at `+n.filename+":"+r+":"+o}}}var dp=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;class hp{match(e){return typeof e=="string"}coerce(e,n){var i,s=this.getInfos(e),r=s[0],o=s[1];return{type:r??"Error",value:o??e,stack:(i=n.syntheticException)==null?void 0:i.stack,synthetic:!0}}getInfos(e){var n="Error",i=e,s=e.match(dp);return s&&(n=s[1],i=s[2]),[n,i]}}var pp=["fatal","error","warning","log","info","debug"];function yu(t,e){e===void 0&&(e=40);var n=Object.keys(t);if(n.sort(),!n.length)return"[object has no keys]";for(var i=n.length;i>0;i--){var s=n.slice(0,i).join(", ");if(e>=s.length)return i===n.length?s:s.length>e?s.slice(0,e)+"...":s}return""}class fp{match(e){return typeof e=="object"&&e!==null}coerce(e,n){var i,s,r=this.getErrorPropertyFromObject(e);return r?n.apply(r):{type:this.getType(e),value:this.getValue(e),stack:(i=this.getStack(e))!==null&&i!==void 0?i:(s=n.syntheticException)==null?void 0:s.stack,level:this.isSeverityLevel(e.level)?e.level:"error",synthetic:!0}}getType(e){return Jo(e)?e.constructor.name:"Error"}getValue(e){if("name"in e&&typeof e.name=="string"){var n="'"+e.name+"' captured as exception";return"message"in e&&typeof e.message=="string"&&(n+=" with message: '"+e.message+"'"),n}if("message"in e&&typeof e.message=="string")return e.message;var i=this.getObjectClassName(e);return(i&&i!=="Object"?"'"+i+"'":"Object")+" captured as exception with keys: "+yu(e)}isSeverityLevel(e){return q(e)&&!Gr(e)&&pp.indexOf(e)>=0}getStack(e){try{return q(e.stacktrace)&&e.stacktrace.length>0?e.stacktrace:q(e.stack)&&e.stack.length>0?e.stack:void 0}catch{return}}getErrorPropertyFromObject(e){for(var n in e)if({}.hasOwnProperty.call(e,n)){var i=e[n];if(Kh(i))return i}}getObjectClassName(e){try{var n=Object.getPrototypeOf(e);return n?n.constructor.name:void 0}catch{return}}}class gp{match(e){return Jo(e)}coerce(e,n){var i,s=e.constructor.name;return{type:s,value:s+" captured as exception with keys: "+yu(e),stack:(i=n.syntheticException)==null?void 0:i.stack,synthetic:!0}}}class mp{match(e){return qc(e)}coerce(e,n){var i;return{type:"Error",value:"Primitive value captured as exception: "+String(e),stack:(i=n.syntheticException)==null?void 0:i.stack,synthetic:!0}}}class vp{match(e){return es(e,"PromiseRejectionEvent")||this.isCustomEventWrappingRejection(e)}isCustomEventWrappingRejection(e){if(!Jo(e))return!1;try{var n=e.detail;return n!=null&&typeof n=="object"&&"reason"in n}catch{return!1}}coerce(e,n){var i,s=this.getUnhandledRejectionReason(e);return qc(s)?{type:"UnhandledRejection",value:"Non-Error promise rejection captured with value: "+String(s),stack:(i=n.syntheticException)==null?void 0:i.stack,synthetic:!0}:n.apply(s)}getUnhandledRejectionReason(e){try{if("reason"in e)return e.reason;if("detail"in e&&e.detail!=null&&typeof e.detail=="object"&&"reason"in e.detail)return e.detail.reason}catch{}return e}}var os="$message",as="$timestamp",_p=new Set([os,as]),pr={enabled:!0,max_bytes:32768};function ls(t){var e;return t?{enabled:(e=t.enabled)!==null&&e!==void 0?e:pr.enabled,max_bytes:wp(t.max_bytes,pr.max_bytes)}:b({},pr)}class yp{constructor(e){this.Ke=[],this.Je=0,this.Ne=ls(e)}setConfig(e){this.Ne=ls(e),this.Xe()}add(e){var n=(function(s){var r;try{r=Hc(s)}catch{return}try{var o=JSON.parse(r);if(!ne(o))return;var a=o,l=a[os],u=a[as];return!q(l)||l.trim().length===0||!q(u)&&!he(u)?void 0:{step:a,json:r}}catch{return}})(e);if(n){var i=(function(s){if(typeof TextEncoder<"u")return new TextEncoder().encode(s).length;for(var r=encodeURIComponent(s),o=0,a=0;r.length>a;a++)r[a]==="%"?(o+=1,a+=2):o+=1;return o})(n.json);i>this.Ne.max_bytes||(this.Ke.push({step:n.step,bytes:i}),this.Je+=i,this.Xe())}}getAttachable(){return this.Ke.map((e=>e.step))}clear(){this.Ke=[],this.Je=0}size(){return this.Ke.length}Xe(){for(;this.Je>this.Ne.max_bytes&&this.Ke.length>0;){var e=this.Ke.shift();e&&(this.Je-=e.bytes)}}}function wp(t,e){if(!he(t)||t===1/0||t===-1/0)return e;var n=Math.floor(t);return 0>n?e:n}var wu=function(t,e){var n=(e===void 0?{}:e).debugEnabled,i={k(s){if(_&&(Y.DEBUG||_.POSTHOG_DEBUG||n)&&!x(_.console)&&_.console){for(var r=("__rrweb_original__"in _.console[s])?_.console[s].__rrweb_original__:_.console[s],o=arguments.length,a=new Array(o>1?o-1:0),l=1;o>l;l++)a[l-1]=arguments[l];r(t,...a)}},debug(){for(var s=arguments.length,r=new Array(s),o=0;s>o;o++)r[o]=arguments[o];i.k("debug",...r)},info(){for(var s=arguments.length,r=new Array(s),o=0;s>o;o++)r[o]=arguments[o];i.k("log",...r)},warn(){for(var s=arguments.length,r=new Array(s),o=0;s>o;o++)r[o]=arguments[o];i.k("warn",...r)},error(){for(var s=arguments.length,r=new Array(s),o=0;s>o;o++)r[o]=arguments[o];i.k("error",...r)},critical(){for(var s=arguments.length,r=new Array(s),o=0;s>o;o++)r[o]=arguments[o];console.error(t,...r)},uninitializedWarning(s){i.error("You must initialize PostHog before calling "+s)},createLogger:(s,r)=>wu(t+" "+s,r)};return i},k=wu("[PostHog.js]"),ie=k.createLogger,bp=ie("[ExternalScriptsLoader]"),fr=(t,e,n)=>{if(t.config.disable_external_dependency_loading)return bp.warn(e+" was requested but loading of external scripts is disabled."),n("Loading of external scripts is disabled");var i=C?.querySelectorAll("script");if(i){for(var s,r=function(){if(i[o].src===e){var l=i[o];return l.__posthog_loading_callback_fired?{v:n()}:(l.addEventListener("load",(u=>{l.__posthog_loading_callback_fired=!0,n(void 0,u)})),l.onerror=u=>n(u),{v:void 0})}},o=0;i.length>o;o++)if(s=r())return s.v}var a=()=>{if(!C)return n("document not found");var l=C.createElement("script");if(l.type="text/javascript",l.crossOrigin="anonymous",l.src=e,l.onload=d=>{l.__posthog_loading_callback_fired=!0,n(void 0,d)},l.onerror=d=>n(d),t.config.prepare_external_dependency_script&&(l=t.config.prepare_external_dependency_script(l)),!l)return n("prepare_external_dependency_script returned null");if(t.config.external_scripts_inject_target==="head")C.head.appendChild(l);else{var u,c=C.querySelectorAll("body > script");c.length>0?(u=c[0].parentNode)==null||u.insertBefore(l,c[0]):C.body.appendChild(l)}};C!=null&&C.body?a():C?.addEventListener("DOMContentLoaded",a)};R.__PosthogExtensions__=R.__PosthogExtensions__||{},R.__PosthogExtensions__.loadExternalDependency=(t,e,n)=>{if(e!=="remote-config"){var i;if(t.config.strict_script_versioning)i=t.requestRouter.endpointFor("assets","/static/"+t.version+"/"+e+".js");else{var s="/static/"+e+".js?v="+t.version;if(e==="toolbar"){var r=3e5;s=s+"&t="+Math.floor(Date.now()/r)*r}i=t.requestRouter.endpointFor("assets",s)}fr(t,i,n)}else{var o=t.requestRouter.endpointFor("assets","/array/"+t.config.token+"/config.js");fr(t,o,n)}},R.__PosthogExtensions__.loadSiteApp=(t,e,n)=>{var i=t.requestRouter.endpointFor("api",e);fr(t,i,n)};Y.DEBUG=!1,Y.LIB_VERSION="1.415.7",Y.LIB_NAME="web";var bu="$people_distinct_id",ai="$device_id",gr="$device_model",zn="__alias",qn="__timers",Qr="$autocapture_disabled_server_side",eo="$heatmaps_enabled_server_side",to="$exception_capture_enabled_server_side",no="$error_tracking_suppression_rules",io="$error_tracking_capture_extension_exceptions",so="$web_vitals_enabled_server_side",ta="$dead_clicks_enabled_server_side",na="$product_tours_enabled_server_side",ro="$web_vitals_allowed_metrics",Jt="$session_recording_remote_config",Eu="$replay_sample_rate",Su="$replay_override_sampling",xu="$replay_override_linked_flag",ku="$replay_override_url_trigger",Iu="$replay_override_event_trigger",hn="$sesid",ia="$session_is_sampled",Wt="$enabled_feature_flags",Vn="$active_feature_flags",ji="$early_access_features",oo="$feature_flag_details",Gn="$feature_flag_payloads",Ui="$feature_flag_request_id",cs="$minimal_flag_called_events",it="$override_feature_flags",zt="$override_feature_flag_payloads",ht="$stored_person_properties",qt="$stored_group_properties",ao="$surveys",us="$surveys_loaded_at",lo="$surveys_activated",Hi="$surveys_activated_session",Wi="$surveys_activated_timestamps",Kn="ph_product_tours",Gt="$flag_call_reported",Jn="$flag_call_reported_session_id",zi="$feature_flag_errors",Xn="$feature_flag_evaluated_at",He="$user_state",co="$client_session_props",uo="$capture_rate_limit",ho="$initial_campaign_params",po="$initial_referrer_info",ds="$initial_person_info",hs="$epp",Ci="$posthog_cookieless",Cu="$cookieless_mode",Au="$sdk_debug_extensions_init_method",Fu="$sdk_debug_extensions_init_time_ms",Pu="$sdk_debug_recording_script_not_loaded",sa="PostHog loadExternalDependency extension not found.",Vt="on_reject",gt="always",sn="anonymous",Ot="identified",fo="identified_only",ps="visibilitychange",fs="beforeunload",cn="$pageview",mr="$pageleave",vr="$identify",hl="$groupidentify";function Ai(t,e){O(t)&&t.forEach(e)}function Z(t,e){if(!B(t))if(O(t))t.forEach(e);else if(Th(t))t.forEach(((i,s)=>e(i,s)));else for(var n in t)zc.call(t,n)&&e(t[n],n)}var te=function(t){for(var e=arguments.length,n=new Array(e>1?e-1:0),i=1;e>i;i++)n[i-1]=arguments[i];for(var s of n)for(var r in s)s[r]!==void 0&&(t[r]=s[r]);return t};function qi(t){for(var e=Object.keys(t),n=e.length,i=new Array(n);n--;)i[n]=[e[n],t[e[n]]];return i}var pl=function(t){try{return t()}catch{return}},Ep=function(t){return function(){try{for(var e=arguments.length,n=new Array(e),i=0;e>i;i++)n[i]=arguments[i];return t.apply(this,n)}catch(s){k.critical("Implementation error. Please turn on debug mode and open a ticket on https://app.posthog.com/home#panel=support%3Asupport%3A."),k.critical(s)}}},ra=function(t){var e={};return Z(t,(function(n,i){(q(n)&&n.length>0||he(n))&&(e[i]=n)})),e},Sp=["herokuapp.com","vercel.app","netlify.app"];function xp(t){var e=t?.hostname;if(!q(e))return!1;var n=e.split(".").slice(-2).join(".");for(var i of Sp)if(n===i)return!1;return!0}function re(t,e,n,i){var s=i??{},r=s.capture,o=s.passive;t?.addEventListener(e,n,{capture:r!==void 0&&r,passive:o===void 0||o})}function go(t){return t.name==="ph_toolbar_internal"}var $u=t=>{if(C){try{for(var e=t+"=",n=C.cookie.split(";").filter((r=>r.length)),i=0;n.length>i;i++){for(var s=n[i];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}};Math.trunc||(Math.trunc=function(t){return 0>t?Math.ceil(t):Math.floor(t)}),Number.isInteger||(Number.isInteger=function(t){return he(t)&&isFinite(t)&&Math.floor(t)===t});class gs{constructor(e){if(this.bytes=e,e.length!==16)throw new TypeError("not 128-bit length")}static fromFieldsV7(e,n,i,s){if(!Number.isInteger(e)||!Number.isInteger(n)||!Number.isInteger(i)||!Number.isInteger(s)||0>e||0>n||0>i||0>s||e>0xffffffffffff||n>4095||i>1073741823||s>4294967295)throw new RangeError("invalid field value");var r=new Uint8Array(16);return r[0]=e/Math.pow(2,40),r[1]=e/Math.pow(2,32),r[2]=e/Math.pow(2,24),r[3]=e/Math.pow(2,16),r[4]=e/256,r[5]=e,r[6]=112|n>>>8,r[7]=n,r[8]=128|i>>>24,r[9]=i>>>16,r[10]=i>>>8,r[11]=i,r[12]=s>>>24,r[13]=s>>>16,r[14]=s>>>8,r[15]=s,new gs(r)}toString(){for(var e="",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 gs(this.bytes.slice(0))}equals(e){return this.compareTo(e)===0}compareTo(e){for(var n=0;16>n;n++){var i=this.bytes[n]-e.bytes[n];if(i!==0)return Math.sign(i)}return 0}}class kp{generate(){var e=this.generateOrAbort();if(!x(e))return e;this.S=0;var n=this.generateOrAbort();if(x(n))throw new Error("Could not generate UUID after timestamp reset");return n}generateOrAbort(){var e=Date.now();if(e>this.S)this.S=e,this.C();else{if(this.S>=e+1e4)return;this.I++,this.I>4398046511103&&(this.S++,this.C())}return gs.fromFieldsV7(this.S,Math.trunc(this.I/Math.pow(2,30)),this.I&Math.pow(2,30)-1,this.A.nextUint32())}C(){this.I=1024*this.A.nextUint32()+(1023&this.A.nextUint32())}constructor(){this.S=0,this.I=0,this.A=new Ip}}var fl,Tu=t=>{if(typeof UUIDV7_DENY_WEAK_RNG<"u"&&UUIDV7_DENY_WEAK_RNG)throw new Error("no cryptographically strong RNG available");for(var e=0;t.length>e;e++)t[e]=65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random());return t};_&&!x(_.crypto)&&crypto.getRandomValues&&(Tu=t=>crypto.getRandomValues(t));class Ip{nextUint32(){return this.R.length>this.O||(Tu(this.R),this.O=0),this.R[this.O++]}constructor(){this.R=new Uint32Array(8),this.O=1/0}}var ft=()=>Cp().toString(),Cp=()=>(fl||(fl=new kp)).generate(),Nn="",Ap=/[a-z0-9][a-z0-9-]+\.[a-z]{2,}$/i,mt={N:()=>!!C,j(t){k.error("cookieStore error: "+t)},P:$u,H(t){var e;try{e=JSON.parse(mt.P(t))||{}}catch{}return e},F(t,e,n,i,s){if(!C)return!1;try{var r="",o="",a=(function(c,d){if(d){var h=(function(f,g){if(g===void 0&&(g=C),Nn)return Nn;if(!g||["localhost","127.0.0.1"].includes(f))return"";for(var m=f.split("."),v=Math.min(m.length,8),E="dmn_chk_"+ft();!Nn&&v--;){var w=m.slice(v).join("."),I=E+"=1;domain=."+w+";path=/";g.cookie=I+";max-age=3",g.cookie.includes(E)&&(g.cookie=I+";max-age=0",Nn=w)}return Nn})(c);if(!h){var p=(f=>{var g=f.match(Ap);return g?g[0]:""})(c);p!==h&&k.info("Warning: cookie subdomain discovery mismatch",p,h),h=p}return h?"; domain=."+h:""}return""})(C.location.hostname,i);if(n){var l=new Date;l.setTime(l.getTime()+864e5*n),r="; expires="+l.toUTCString()}s&&(o="; secure");var u=t+"="+encodeURIComponent(JSON.stringify(e))+r+"; SameSite=Lax; path=/"+a+o;return u.length>3686.4&&k.warn("cookieStore warning: large cookie, len="+u.length),C.cookie=u,!0}catch{return!1}},q(t,e){if(C!=null&&C.cookie)try{mt.F(t,"",-1,e)}catch{return}}},_r=null,ee={N(){if(!$e(_r))return _r;var t=!0;if(x(_))t=!1;else try{var e="__mplssupport__";ee.F(e,"xyz"),ee.P(e)!=='"xyz"'&&(t=!1),ee.q(e)}catch{t=!1}return t||k.error("localStorage unsupported; falling back to cookie store"),_r=t,t},j(t){k.error("localStorage error: "+t)},P(t){try{return _?.localStorage.getItem(t)}catch(e){ee.j(e)}return null},H(t){try{return JSON.parse(ee.P(t))||{}}catch{}return null},F(t,e){try{return _?.localStorage.setItem(t,JSON.stringify(e)),!0}catch(n){ee.j(n)}return!1},q(t){try{_?.localStorage.removeItem(t)}catch(e){ee.j(e)}}},Fp=[ai,"distinct_id",hn,ia,hs,ds,He],Fi={},Pp={N:()=>!0,j(t){k.error("memoryStorage error: "+t)},P:t=>Fi[t]||null,H:t=>Fi[t]||null,F:(t,e)=>(Fi[t]=e,!0),q(t){delete Fi[t]}},Bt=null,ce={N(){if(!$e(Bt))return Bt;if(Bt=!0,x(_))Bt=!1;else try{var t="__support__";ce.F(t,"xyz"),ce.P(t)!=='"xyz"'&&(Bt=!1),ce.q(t)}catch{Bt=!1}return Bt},j(t){k.error("sessionStorage error: ",t)},P(t){try{return _?.sessionStorage.getItem(t)}catch(e){ce.j(e)}return null},H(t){try{return JSON.parse(ce.P(t))||null}catch{}return null},F(t,e){try{return _?.sessionStorage.setItem(t,JSON.stringify(e)),!0}catch(n){ce.j(n)}return!1},q(t){try{_?.sessionStorage.removeItem(t)}catch(e){ce.j(e)}}};class $p{constructor(e){this._instance=e}get Ne(){return this._instance.config}get consent(){return this.ti()?0:this.ei}isOptedOut(){return this.Ne.cookieless_mode===gt||this.isRejected()||this.consent===-1&&this.Ne.cookieless_mode===Vt}isOptedIn(){return!this.isOptedOut()}isExplicitlyOptedOut(){return this.consent===0}isRejected(){return this.consent===0||this.consent===-1&&this.Ne.opt_out_capturing_by_default}optInOut(e){this.ii.F(this.ri,e?1:0,this.Ne.cookie_expiration,this.Ne.cross_subdomain_cookie,this.Ne.secure_cookie)}reset(){this.ii.q(this.ri,this.Ne.cross_subdomain_cookie)}get ri(){var e=this._instance.config,n=e.token,i=e.opt_out_capturing_cookie_prefix;return e.consent_persistence_name||(i?i+n:"__ph_opt_in_out_"+n)}get ei(){var e=this.ii.P(this.ri);return cr(e)?1:L(Lh,e)?0:-1}get ii(){var e=this.Ne.opt_out_capturing_persistence_type,n=e==="localStorage"?ee:mt;if(!this.ni||this.ni!==n){this.ni=n;var i=e==="localStorage"?mt:ee;i.P(this.ri)&&(this.ni.P(this.ri)||this.optInOut(cr(i.P(this.ri))),i.q(this.ri,this.Ne.cross_subdomain_cookie))}return this.ni}ti(){return!!this.Ne.respect_dnt&&[ke?.doNotTrack,ke?.msDoNotTrack,R.doNotTrack].some((e=>cr(e)))}}function Ru(t,e){var n,i=t==null||(n=t.config)==null?void 0:n.get_current_url;if(!Se(i))return e;try{var s=i(e);return q(s)&&s?s:e}catch(r){return k.error("Error in get_current_url, falling back to window.location.href",r),e}}var Nu="__POSTHOG_TOOLBAR__",Tp=1,Rp=3,Np=11;function gl(t){return t instanceof Element&&(t.id===Nu||!(t.closest==null||!t.closest(".toolbar-global-fade-container")))}function $t(t){return!!t&&t.nodeType===Tp}function Me(t,e){return!!t&&!!t.tagName&&t.tagName.toLowerCase()===e.toLowerCase()}function Mu(t){return!!t&&t.nodeType===Rp}function Lu(t){return!!t&&t.nodeType===Np&&$t(t.host)}var Ou=1e3;function oa(t){return t?Bs(t).split(/\s+/):[]}function ml(t,e){var n=(function(i){var s,r=_==null||(s=_.location)==null?void 0:s.href;return x(r)?void 0:Ru(i,r)})(e);return!!(n&&t&&t.some((i=>n.match(i))))}function ms(t){var 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 oa(e)}function Bu(t){return B(t)?null:Bs(t).split(/(\s+)/).filter((e=>Qn(e))).join("").replace(/[\r\n]/g," ").replace(/[ ]+/g," ").substring(0,255)}function li(t){var e="";return vo(t)&&!Hu(t)&&t.childNodes&&t.childNodes.length&&Z(t.childNodes,(function(n){var i;Mu(n)&&n.textContent&&(e+=(i=Bu(n.textContent))!==null&&i!==void 0?i:"")})),Bs(e)}function yr(t){var e;return x(t.target)?t.srcElement||null:(e=t.target)!=null&&e.shadowRoot?t.composedPath()[0]||null:t.target||null}var aa=["a","button","form","input","select","textarea","label"];function mo(t,e){if(x(e))return!0;var n,i=function(r){if(e.some((o=>(function(a,l){var u=a.matches||a.matchesSelector||a.msMatchesSelector||a.mozMatchesSelector||a.webkitMatchesSelector||a.oMatchesSelector;try{return!!u&&u.call(a,l)}catch{return!1}})(r,o))))return{v:!0}};for(var s of t)if(n=i(s))return n.v;return!1}function Du(t){var e=t.parentNode;return!(!e||!$t(e))&&e}var Mp=[".ph-no-autocapture","[data-ph-no-autocapture]"],ju=["next","previous","prev",">","<"],Lp=[...ju,"+","-","−","–"],vl=(t,e)=>/[a-z0-9]/i.test(e)?t.includes(e):t===e,_l=[".ph-no-rageclick",".ph-no-capture"],Op=["","text","search","email","password","url","tel","number"];function yl(t,e){if(!_||la(t))return!1;var n,i,s,r,o;if(Ye(e)?(n=!!e&&_l,i=void 0,s=!1):(n=(r=e?.css_selector_ignorelist)!==null&&r!==void 0?r:_l,i=e?.content_ignorelist,s=(o=e?.ignore_text_selection)!==null&&o!==void 0&&o),n===!1||s&&(function(l){return!(!l||!$t(l))&&(!!Me(l,"textarea")||(Me(l,"input")?L(Op,(l.getAttribute("type")||"").toLowerCase()):(function(u){if(u.isContentEditable)return!0;var c=u.getAttribute==null?void 0:u.getAttribute("contenteditable");return c==="true"||c===""})(l)))})(t))return!1;var a=Uu(t,!1).targetElementList;return!(function(l,u){if(l===!1||x(l))return!1;var c;if(l===!0)c=ju;else{if(!O(l))return!1;if(l.length>10)return k.error("[PostHog] content_ignorelist array cannot exceed 10 items. Use css_selector_ignorelist for more complex matching."),!1;c=l.map((d=>d.toLowerCase()))}return u.some((d=>{var h=d.safeText,p=d.ariaLabel;return c.some((f=>vl(h,f)||vl(p,f)))}))})(i,a.map((l=>{var u;return{safeText:li(l).toLowerCase(),ariaLabel:((u=l.getAttribute("aria-label"))==null?void 0:u.toLowerCase().trim())||""}})))&&!mo(a,n)}var la=t=>!t||Me(t,"html")||!$t(t),Uu=(t,e)=>{if(!_||la(t))return{parentIsUsefulElement:!1,targetElementList:[]};for(var n=!1,i=[t],s=t;s.parentNode&&!Me(s,"body");)if(Lu(s.parentNode))i.push(s.parentNode.host),s=s.parentNode.host;else{var r=Du(s);if(!r)break;if(e||aa.indexOf(r.tagName.toLowerCase())>-1)n=!0;else try{var o=_.getComputedStyle(r);o&&o.getPropertyValue("cursor")==="pointer"&&(n=!0)}catch{}i.push(r),s=r}return{parentIsUsefulElement:n,targetElementList:i}};function vo(t){for(var e=new Set,n=0,i=t;i.parentNode&&!Me(i,"body");i=i.parentNode){if(n++>=Ou||e.has(i))return!1;e.add(i);var s=ms(i);if(L(s,"ph-sensitive")||L(s,"ph-no-capture"))return!1}if(L(ms(t),"ph-include"))return!0;var r=t.type||"";if(q(r))switch(r.toLowerCase()){case"hidden":case"password":return!1}var o=t.name||t.id||"";return!q(o)||!/^cc|cardnum|ccnum|creditcard|csc|cvc|cvv|exp|pass|pwd|routing|seccode|securitycode|securitynum|socialsec|socsec|ssn/i.test(o.replace(/[^a-zA-Z0-9]/g,""))}function Hu(t){return!!(Me(t,"input")&&!["button","checkbox","submit","reset"].includes(t.type)||Me(t,"select")||Me(t,"textarea")||t.getAttribute("contenteditable")==="true")}var wl=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}))$"),bl=/(^|[^0-9A-Za-z_])([0-9][0-9 -]*[0-9])(?=$|[^0-9A-Za-z_])/g,Bp=[16,15,14,13],Dp=new RegExp("^(\\d{3}-?\\d{2}-?\\d{4})$"),El=new RegExp("(^|[^0-9])((?!000|666)[0-9]{3}-?(?!00)[0-9]{2}-?(?!0000)[0-9]{4})(?=$|([^0-9]))","g"),Sl=/[0-9A-Za-z_]/;function jp(t){for(var e=0,n=!1,i=t.length-1;i>=0;i--){var s=t.charCodeAt(i)-48;n&&(s*=2)>9&&(s-=9),e+=s,n=!n}return e%10==0}function Qn(t,e){if(e===void 0&&(e=!0),B(t))return!1;if(q(t)){t=Bs(t);var n=e?wl.test((t||"").replace(/[- ]/g,"")):(function(s){var r;for(bl.lastIndex=0;r=bl.exec(s);){var o=r[2];if(o)for(var a=o.replace(/[- ]/g,""),l=0;a.length>l;l++)for(var u of Bp){var c=l+u;if(a.length>=c){var d=a.slice(l,c);if(wl.test(d)&&jp(d))return!0}}}return!1})(t);if(n)return!1;var i=e?Dp.test(t):(function(s){var r;for(El.lastIndex=0;r=El.exec(s);){var o=r[1],a=r[3];if(!(o&&a&&Sl.test(o)&&Sl.test(a)))return!0}return!1})(t);if(i)return!1}return!0}function xl(t){var e=li(t);return Qn(e=(e+" "+Wu(t)).trim())?e:""}function Wu(t){var e="";return t&&t.childNodes&&t.childNodes.length&&Z(t.childNodes,(function(n){var i;if(n&&((i=n.tagName)==null?void 0:i.toLowerCase())==="span")try{var s=li(n);e=(e+" "+s).trim(),n.childNodes&&n.childNodes.length&&(e=(e+" "+Wu(n)).trim())}catch(r){k.error("[AutoCapture]",r)}})),e}function kl(t){return t.replace(/"|\\"/g,'\\"')}function Up(t){var e=t.attr__class;if(e)return O(e)?e:oa(e)}var Pi=ie("[Dead Clicks]"),Hp=()=>!0,Wp=t=>{var e,n=!((e=t.instance.persistence)==null||!e.get_property(ta)),i=t.instance.config.capture_dead_clicks;return Ye(i)?i:!!ne(i)||n};class Il{get lazyLoadedDeadClicksAutocapture(){return this.si}constructor(e,n,i){this.instance=e,this.isEnabled=n,this.onCapture=i,this.startIfEnabledOrStop()}onRemoteConfig(e){if(e.ok){var n=e.config;"captureDeadClicks"in n&&(this.instance.persistence&&this.instance.persistence.register({[ta]:n.captureDeadClicks}),this.startIfEnabledOrStop())}}startIfEnabledOrStop(){this.isEnabled(this)?this.ai((()=>{this.oi()})):this.stop()}ai(e){var n,i;(n=R.__PosthogExtensions__)!=null&&n.initDeadClicksAutocapture?e():(i=R.__PosthogExtensions__)==null||i.loadExternalDependency==null||i.loadExternalDependency(this.instance,"dead-clicks-autocapture",(s=>{s?Pi.error("failed to load script",s):e()}))}oi(){var e;if(C){if(!this.si&&(e=R.__PosthogExtensions__)!=null&&e.initDeadClicksAutocapture){var n=ne(this.instance.config.capture_dead_clicks)?b({},this.instance.config.capture_dead_clicks):{};n.__onCapture=this.onCapture,this.onCapture&&(n.capture_dead_swipes=!1),this.si=R.__PosthogExtensions__.initDeadClicksAutocapture(this.instance,n),this.si.start(C),Pi.info("starting...")}}else Pi.error("`document` not found. Cannot start.")}stop(){this.si&&(this.si.stop(),this.si=void 0,Pi.info("stopping..."))}}var wr=ie("[SegmentIntegration]"),zu="posthog-js";function qu(t,e){var n=e===void 0?{}:e,i=n.organization,s=n.projectId,r=n.prefix,o=n.severityAllowList,a=o===void 0?["error"]:o,l=n.sendExceptionsToPostHog,u=l===void 0||l;return c=>{var d,h,p,f,g;if(a!=="*"&&!a.includes(c.level)||!t.__loaded)return c;c.tags||(c.tags={});var m=t.requestRouter.endpointFor("ui","/project/"+t.config.token+"/person/"+t.get_distinct_id());c.tags["PostHog Person URL"]=m,t.sessionRecordingStarted()&&(c.tags["PostHog Recording URL"]=t.get_session_replay_url({withTimestamp:!0}));var v,E=((d=c.exception)==null?void 0:d.values)||[],w=E.map((A=>b({},A,{stacktrace:A.stacktrace?b({},A.stacktrace,{type:"raw",frames:(A.stacktrace.frames||[]).map((F=>b({},F,{platform:"web:javascript"})))}):void 0}))),I={$exception_message:((h=E[0])==null?void 0:h.value)||c.message,$exception_type:(p=E[0])==null?void 0:p.type,$exception_level:c.level,$exception_list:w,$sentry_event_id:c.event_id,$sentry_exception:c.exception,$sentry_exception_message:((f=E[0])==null?void 0:f.value)||c.message,$sentry_exception_type:(g=E[0])==null?void 0:g.type,$sentry_tags:c.tags};return i&&s&&(I.$sentry_url=(r||"https://sentry.io/organizations/")+i+"/issues/?project="+s+"&query="+c.event_id),u&&((v=t.exceptions)==null||v.sendExceptionEvent(I)),c}}class zp{constructor(e,n,i,s,r,o){this.name=zu,this.setupOnce=function(a){a(qu(e,{organization:n,projectId:i,prefix:s,severityAllowList:r,sendExceptionsToPostHog:o==null||o}))}}}class Cl{constructor(e){this.li=(n,i,s)=>{s&&(s.noSessionId||s.activityTimeout||s.sessionPastMaximumLength||s.crossTabAdoption)&&(k.info("[PageViewManager] Session rotated, clearing pageview state",{sessionId:n,changeReason:s}),this.ui=void 0,this._instance.scrollManager.resetContext())},this._instance=e,this.hi()}hi(){var e;this.di=(e=this._instance.sessionManager)==null?void 0:e.onSessionId(this.li)}destroy(){var e;(e=this.di)==null||e.call(this),this.di=void 0}doPageView(e,n){var i,s=this.vi(e,n);return this.ui={pathname:(i=_?.location.pathname)!==null&&i!==void 0?i:"",pageViewId:n,timestamp:e},this._instance.scrollManager.resetContext(),s}doPageLeave(e){var n;return this.vi(e,(n=this.ui)==null?void 0:n.pageViewId)}doEvent(){var e;return{$pageview_id:(e=this.ui)==null?void 0:e.pageViewId}}vi(e,n){var i=this.ui;if(!i)return{$pageview_id:n};var s={$pageview_id:n,$prev_pageview_id:i.pageViewId},r=this._instance.scrollManager.getContext();if(r&&!this._instance.config.disable_scroll_properties){var o=r.maxScrollHeight,a=r.lastScrollY,l=r.maxScrollY,u=r.maxContentHeight,c=r.lastContentY,d=r.maxContentY;if(!(x(o)||x(a)||x(l)||x(u)||x(c)||x(d))){o=Math.ceil(o),a=Math.ceil(a),l=Math.ceil(l),u=Math.ceil(u),c=Math.ceil(c),d=Math.ceil(d);var h=o>1?ot(a/o,0,1,k):1,p=o>1?ot(l/o,0,1,k):1,f=u>1?ot(c/u,0,1,k):1,g=u>1?ot(d/u,0,1,k):1;s=te(s,{$prev_pageview_last_scroll:a,$prev_pageview_last_scroll_percentage:h,$prev_pageview_max_scroll:l,$prev_pageview_max_scroll_percentage:p,$prev_pageview_last_content:c,$prev_pageview_last_content_percentage:f,$prev_pageview_max_content:d,$prev_pageview_max_content_percentage:g})}}return i.pathname&&(s.$prev_pageview_pathname=i.pathname),i.timestamp&&(s.$prev_pageview_duration=(e.getTime()-i.timestamp.getTime())/1e3),s}}var br=["flags","surveys"],qp={[bu]:{exposure:"hidden"},[zn]:{exposure:"hidden"},__cmpns:{exposure:"hidden"},[qn]:{exposure:"hidden"},[Qr]:{exposure:"event"},[eo]:{exposure:"hidden"},[to]:{exposure:"event"},[no]:{exposure:"hidden"},[io]:{exposure:"event"},[so]:{exposure:"event"},[ta]:{exposure:"event"},[na]:{exposure:"hidden"},[ro]:{exposure:"event"},[Jt]:{exposure:"hidden"},$session_recording_enabled_server_side:{exposure:"hidden"},[hn]:{exposure:"hidden"},[ia]:{exposure:"event"},[Eu]:{exposure:"event",shouldSkipFromEventProperties:t=>$e(t)},$session_past_minimum_duration:{exposure:"event"},$session_recording_url_trigger_activated_session:{exposure:"event"},$session_recording_event_trigger_activated_session:{exposure:"event"},$debug_first_full_snapshot_timestamp:{exposure:"event"},$sess_rec_flush_size:{exposure:"hidden"},[Wt]:{exposure:"hidden",storageGroup:"flags"},[Vn]:{exposure:"hidden",storageGroup:"flags"},[ji]:{exposure:"hidden"},[oo]:{exposure:"hidden",storageGroup:"flags"},[Gn]:{exposure:"hidden",storageGroup:"flags"},[Ui]:{exposure:"hidden",storageGroup:"flags",volatile:!0},[cs]:{exposure:"hidden",storageGroup:"flags"},[it]:{exposure:"hidden"},[zt]:{exposure:"hidden"},[ht]:{exposure:"hidden"},[qt]:{exposure:"hidden"},[ao]:{exposure:"hidden",storageGroup:"surveys"},[us]:{exposure:"hidden",storageGroup:"surveys",volatile:!0},[lo]:{exposure:"event"},[Hi]:{exposure:"hidden"},[Wi]:{exposure:"hidden"},[Kn]:{exposure:"hidden"},$product_tours_activated:{exposure:"hidden"},$product_tours_activated_session:{exposure:"hidden"},$conversations_widget_session_id:{exposure:"event"},$conversations_ticket_id:{exposure:"event"},$conversations_widget_state:{exposure:"event"},$conversations_user_traits:{exposure:"event"},[Gt]:{exposure:"hidden"},[Jn]:{exposure:"hidden"},[zi]:{exposure:"hidden"},[Xn]:{exposure:"hidden",storageGroup:"flags",volatile:!0},[He]:{exposure:"hidden"},[co]:{exposure:"hidden"},[uo]:{exposure:"hidden"},[ho]:{exposure:"hidden"},[po]:{exposure:"hidden"},[ds]:{exposure:"hidden"},[hs]:{exposure:"hidden"},[Su]:{exposure:"event"},[xu]:{exposure:"event"},[ku]:{exposure:"event"},[Iu]:{exposure:"event"},[Au]:{exposure:"event"},[Fu]:{exposure:"event"},[Pu]:{exposure:"event"},$sdk_debug_replay_event_trigger_status:{exposure:"event"},$sdk_debug_replay_linked_flag_trigger_status:{exposure:"event"},$sdk_debug_replay_matched_recording_trigger_groups:{exposure:"event"},$sdk_debug_replay_remote_trigger_matching_config:{exposure:"event"},$sdk_debug_replay_trigger_groups_count:{exposure:"event"},$sdk_debug_replay_url_trigger_status:{exposure:"event"},$session_recording_start_reason:{exposure:"event"}},Vp=[["$posthog_sr_group_event_trigger_",{exposure:"hidden"}],["$posthog_sr_group_url_trigger_",{exposure:"hidden"}],["$posthog_sr_group_sampling_",{exposure:"hidden"}]],Dt=t=>{var e=qp[t];if(e)return e;for(var n of Vp){var i=n[1];if(t.indexOf(n[0])===0)return i}},pn=(t,e)=>{try{return JSON.stringify(t,((n,i)=>typeof i=="bigint"?i.toString():i),e)}catch{return Hc(t)}},vs=t=>{var e=C?.createElement("a");return x(e)?null:(e.href=t,e)},wn=function(t,e){for(var n,i=((t.split("#")[0]||"").split(/\?(.*)/)[1]||"").replace(/^\?+/g,"").split("&"),s=0;i.length>s;s++){var r=i[s].split("=");if(r[0]===e){n=r;break}}if(!O(n)||2>n.length)return"";var o=n[1];try{o=decodeURIComponent(o)}catch{k.error("Skipping decoding for malformed query param: "+o)}return o.replace(/\+/g," ")},ci=function(t,e,n){if(!t||!e||!e.length)return t;for(var i=t.split("#"),s=i[1],r=(i[0]||"").split("?"),o=r[1],a=r[0],l=(o||"").split("&"),u=[],c=0;l.length>c;c++){var d=l[c].split("=");O(d)&&(e.includes(d[0])?u.push(d[0]+"="+n):u.push(l[c]))}var h=a;return o!=null&&(h+="?"+u.join("&")),s!=null&&(h+="#"+s),h},_s=function(t,e){var n=t.match(new RegExp(e+"=([^&]*)"));return n?n[1]:null},Vu=(t,e)=>t>=e&&Dc(),Gu=(t,e,n,i)=>{if(t===0){if(Dc()){var s=e+1;return s===n&&i(),s}return e}return 0},$i="https?://(.*)",bn=["gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","irclid","_kx"],Gp=["utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid",...bn],ui="",Kp=["li_fat_id"];function Ku(t,e,n){if(!C)return{};var i,s=e?[...bn,...n||[]]:[],r=Ju(ci(C.URL,s,ui),t),o=(i={},Z(Kp,(function(a){var l=$u(a);i[a]=l||null})),i);return te(o,r)}function Ju(t,e){var n=Gp.concat(e||[]),i={};return Z(n,(function(s){var r=wn(t,s);i[s]=r||null})),i}function Yu(t){var e=(function(r){return r?r.search($i+"google.([^/?]*)")===0?"google":r.search($i+"bing.com")===0?"bing":r.search($i+"yahoo.com")===0?"yahoo":r.search($i+"duckduckgo.com")===0?"duckduckgo":null:null})(t),n=e!="yahoo"?"q":"p",i={};if(!$e(e)){i.$search_engine=e;var s=C?wn(C.referrer,n):"";s.length&&(i.ph_keyword=s)}return i}function Al(){return navigator.language||navigator.userLanguage}var ys="$direct";function Zu(){return C?.referrer||ys}function Xu(t,e,n){n===void 0&&(n=!1);var i=t?[...bn,...e||[]]:[],s=n?Pt(se?.href):se?.href,r=s?.substring(0,1e3);return{r:Zu().substring(0,1e3),u:r?ci(r,i,ui):void 0}}function Qu(t,e){var n;e===void 0&&(e=!1);var i=t.r,s=t.u,r=e?Pt(s):s,o={$referrer:i,$referring_domain:i==null?void 0:i==ys?ys:(n=vs(i))==null?void 0:n.host};if(r){o.$current_url=r;var a=vs(r);o.$host=a?.host,o.$pathname=a?.pathname;var l=Ju(r);te(o,l)}if(i){var u=Yu(i);te(o,u)}return o}function ed(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return}}function Jp(){try{return new Date().getTimezoneOffset()}catch{return}}var Yp={flags:Xn,surveys:us},Zp=["cookie","localstorage","localstorage+cookie","sessionstorage","memory"],rn="main";class Er{constructor(e,n,i){if(i===void 0&&(i=!0),this.ci={},this.fi=!1,this.pi=!1,this.Ne=e,this.gi=i,this.props={},this.mi=void 0,this.yi=(r=>{var o="";return r.token&&(o=r.token.replace(/\+/g,"PL").replace(/\//g,"SL").replace(/=/g,"EQ")),r.persistence_name?"ph_"+r.persistence_name:"ph_"+o+"_posthog"})(e),this.ii=this.bi(e),this.pi=this.wi(e),this.load(),e.debug&&k.info("Persistence loaded",e.persistence,b({},this.props)),this.update_config(e,e,n),this.save(),_){var s=()=>this.flush();re(_,"beforeunload",s,{capture:!1}),re(_,"pagehide",s,{capture:!1})}}ki(){var e,n=(e=this.Ne)==null?void 0:e.persistence_save_debounce_ms;return he(n)&&n>0?n:0}isDisabled(){return!!this.xi}bi(e){Zp.indexOf(e.persistence.toLowerCase())===-1&&(k.critical("Unknown persistence type "+e.persistence+"; falling back to localStorage+cookie"),e.persistence="localStorage+cookie");var n,i=(function(o,a){o===void 0&&(o=[]),a===void 0&&(a=!1);var l=[...Fp,...o];return b({},ee,{H(u){try{var c={};try{c=mt.H(u)||{}}catch{}var d,h=JSON.parse(ee.P(u)||"{}");if(a){var p={};for(var f in c){var g=c[f];$e(g)||g===""||(p[f]=g)}d=te(h,p)}else d=te(c,h);return ee.F(u,d),d}catch{}return null},F(u,c,d,h,p,f){var g=ee.F(u,c,void 0,void 0,f);try{var m={};l.forEach((v=>{c[v]&&(m[v]=c[v])})),Object.keys(m).length&&mt.F(u,m,d,h,p,f)}catch(v){ee.j(v)}return g},q(u,c){try{_?.localStorage.removeItem(u),mt.q(u,c)}catch(d){ee.j(d)}}})})(e.cookie_persisted_properties||[],e.__preview_cookie_wins_on_conflict||!1),s=!1,r=e.persistence.toLowerCase();return r==="localstorage"&&ee.N()?(n=ee,s=!0):r==="localstorage+cookie"&&i.N()?(n=i,s=!0):r==="sessionstorage"&&ce.N()?n=ce:r==="memory"?n=Pp:r==="cookie"?n=mt:i.N()?(n=i,s=!0):n=mt,this.fi=s,n}Si(e){return this.yi+"__"+e}wi(e){return this.fi&&!!e.split_storage}properties(){var e={};return Z(this.props,((n,i)=>{var s=Dt(i);if(!s||s.exposure==="event"){if(s!=null&&s.shouldSkipFromEventProperties!=null&&s.shouldSkipFromEventProperties(n))return;e[i]=n}})),e}load(){if(!this.xi){var e=this.ii.H(this.yi);e&&(this.props=te({},e)),this.pi&&this.Ci()}}Ci(){for(var e of br){var n=ee.H(this.Si(e));if(n&&!yt(n)){var i=this.Mi(e);i.persisted=!0,this.Ti(e)||(i.fingerprint=this.Ei(n,e)),this.Ii(e,n)||te(this.props,n)}}}Ti(e){return Object.keys(this.props).some((n=>{var i;return((i=Dt(n))==null?void 0:i.storageGroup)===e}))}Ii(e,n){var i=Yp[e];if(!i)return!1;var s=n[i],r=this.props[i];return he(s)&&he(r)&&r>s}refreshKey(e){var n;if(!this.xi){var i=this.pi?(n=Dt(e))==null?void 0:n.storageGroup:void 0,s=i?ee.H(this.Si(i)):this.ii.H(this.yi);if(s&&e in s)this.Pi(e,s[e]);else{if(i){var r=this.ii.H(this.yi);if(r&&e in r)return void this.Pi(e,r[e])}this.Ri(e)}}}save(){if(!this.xi){var e=this.ki();e>0?x(this.Ai)&&(this.Ai=setTimeout((()=>{this.Ai=void 0,this.Fi()}),e)):this.Fi()}}flush(){x(this.Ai)||(clearTimeout(this.Ai),this.Ai=void 0,this.Fi())}Fi(){this.xi||(this.pi?this.Li():this.Oi(this.ii,this.yi,this.props,rn))}Li(){var e=this.Di(),n=e.main,i=e.groups;for(var s of(this.Oi(this.ii,this.yi,n,rn),br)){var r,o=i[s];(!yt(o)||(r=this.ci[s])!=null&&r.persisted)&&this.Oi(ee,this.Si(s),o,s)}}Di(){var e={},n={flags:{},surveys:{}};return Z(this.props,((i,s)=>{var r,o=(r=Dt(s))==null?void 0:r.storageGroup;o?n[o][s]=i:e[s]=i})),{main:e,groups:n}}Ei(e,n){if(n===rn)return JSON.stringify(e)+"|"+this.$i+"|"+this.Ni+"|"+this.qi;var i={};return Z(e,((s,r)=>{var o;i[r]=(o=Dt(r))!=null&&o.volatile?"__volatile__":s})),JSON.stringify(i)}Oi(e,n,i,s){var r=this.Mi(s);if(s===rn||r.dirty||x(r.fingerprint)){var o;try{if((o=this.Ei(i,s))===r.fingerprint)return void(r.dirty=!1)}catch{o=void 0}e.F(n,i,this.$i,this.Ni,this.qi,this.Ne.debug)?(r.dirty=!1,s!==rn&&(r.persisted=!0),x(o)||(r.fingerprint=o)):this.Ne.debug&&k.warn('failed to persist storage entry "'+n+'"; will retry on next save')}}remove(e){var n=(e===void 0?{}:e).keepGroupEntries,i=n!==void 0&&n;if(x(this.Ai)||(clearTimeout(this.Ai),this.Ai=void 0),this.ii.q(this.yi,!1),this.ii.q(this.yi,!0),!i&&this.gi)for(var s of br)ee.q(this.Si(s));i?delete this.ci[rn]:this.ci={}}clear(){this.remove(),this.props={}}register_once(e,n,i){if(ne(e)){x(n)&&(n="None"),this.$i=x(i)?this.ji:i;var s=!1;if(Z(e,((r,o)=>{this.props.hasOwnProperty(o)&&this.props[o]!==n||(this.Pi(o,r),s=!0)})),s)return this.save(),!0}return!1}register(e,n){if(ne(e)){this.$i=x(n)?this.ji:n;var i=!1;if(Z(e,((s,r)=>{e.hasOwnProperty(r)&&(this.props[r]!==s||ne(s)||O(s))&&(this.Pi(r,s),i=!0)})),i)return this.save(),!0}return!1}unregister(e){var n=typeof e=="string"?[e]:e,i=!1;for(var s of n)s in this.props&&(this.Ri(s),i=!0);i&&this.save()}update_campaign_params(){var e=C?.URL;if(e!==this.mi){var n=Ku(this.Ne.custom_campaign_params,this.Ne.mask_personal_data_properties,this.Ne.custom_personal_data_properties);yt(ra(n))||this.register(n),this.mi=e}}update_search_keyword(){var e;this.register((e=C?.referrer)?Yu(e):{})}update_referrer_info(){var e;this.register_once({$referrer:Zu(),$referring_domain:C!=null&&C.referrer&&((e=vs(C.referrer))==null?void 0:e.host)||ys},void 0)}set_initial_person_info(){this.props[ho]||this.props[po]||this.register_once({[ds]:Xu(this.Ne.mask_personal_data_properties,this.Ne.custom_personal_data_properties,this.Ne.disable_capture_url_hashes)},void 0)}get_initial_props(){var e={};Z([po,ho],(s=>{var r=this.props[s];r&&Z(r,(function(o,a){e["$initial_"+Vr(a)]=o}))}));var n=this.props[ds];if(n){var i=(function(s,r){r===void 0&&(r=!1);var o=Qu(s,r),a={};return Z(o,(function(l,u){a["$initial_"+Vr(u)]=l})),a})(n,this.Ne.disable_capture_url_hashes);te(e,i)}return e}safe_merge(e){return Z(this.props,(function(n,i){i in e||(e[i]=n)})),e}update_config(e,n,i){this.ji=this.$i=e.cookie_expiration,this.set_disabled(e.disable_persistence||!!i),this.set_cross_subdomain(e.cross_subdomain_cookie),this.set_secure(e.secure_cookie);var s=e.persistence!==n.persistence||!((l,u)=>{if(l.length!==u.length)return!1;var c=[...l].sort(),d=[...u].sort();return c.every(((h,p)=>h===d[p]))})(e.cookie_persisted_properties||[],n.cookie_persisted_properties||[]),r=s?this.bi(e):this.ii,o=this.wi(e);if(s||o!==this.pi){var a=this.props;this.clear(),this.ii=r,this.pi=o,this.props=a,this.save()}}set_disabled(e){this.xi=e,this.xi?this.remove():this.save()}set_cross_subdomain(e){e!==this.Ni&&(this.Ni=e,this.remove({keepGroupEntries:!0}),this.save())}set_secure(e){e!==this.qi&&(this.qi=e,this.remove({keepGroupEntries:!0}),this.save())}set_event_timer(e,n){var i=this.props[qn]||{};i[e]=n,this.Pi(qn,i),this.save()}remove_event_timer(e){var n=this.props[qn]||{},i=n[e];return x(i)||(delete n[e],this.Pi(qn,n),this.save()),i}get_property(e){return this.props[e]}set_property(e,n){this.Pi(e,n),this.save()}Pi(e,n){var i;this.props[e]=n,(i=Dt(e))!=null&&i.volatile||this.Bi(e)}Ri(e){delete this.props[e],this.Bi(e)}Bi(e){var n,i=(n=Dt(e))==null?void 0:n.storageGroup;i&&(this.Mi(i).dirty=!0)}Mi(e){return this.ci[e]||(this.ci[e]={})}}function Ti(t){var e=!0;return{dispose(){if(e){e=!1;var n=t();n&&Se(n.then)&&n.then(void 0,(()=>{}))}}}}var xe={GZipJS:"gzip-js",Base64:"base64"},Mn={Activation:"events",Cancellation:"cancelEvents"},Sr={Popover:"popover",API:"api",Widget:"widget"},vt={SHOWN:"survey shown",DISMISSED:"survey dismissed",SENT:"survey sent"},xr={SURVEY_ID:"$survey_id",SURVEY_ITERATION:"$survey_iteration",SURVEY_LAST_SEEN_DATE:"$survey_last_seen_date"},_o={Popover:"popover",Inline:"inline"},Xp={SHOWN:"product tour shown"},Fl={TOUR_LAST_SEEN_DATE:"$product_tour_last_seen_date",TOUR_TYPE:"$product_tour_type"},Pl=ie("[RateLimiter]");class Qp{constructor(e){this.serverLimits={},this.lastEventRateLimited=!1,this.checkForLimiting=n=>{var i=n.text;if(i&&i.length)try{(JSON.parse(i).quota_limited||[]).forEach((s=>{Pl.info((s||"events")+" is quota limited."),this.serverLimits[s]=new Date().getTime()+6e4}))}catch(s){return void Pl.warn('could not rate limit - continuing. Error: "'+s?.message+'"',{text:i})}},this.instance=e,this.lastEventRateLimited=this.clientRateLimitContext(!0).isRateLimited}get captureEventsPerSecond(){var e;return((e=this.instance.config.rate_limiting)==null?void 0:e.events_per_second)||10}get captureEventsBurstLimit(){var e;return Math.max(((e=this.instance.config.rate_limiting)==null?void 0:e.events_burst_limit)||10*this.captureEventsPerSecond,this.captureEventsPerSecond)}clientRateLimitContext(e){var n,i,s;e===void 0&&(e=!1);var r=this.captureEventsBurstLimit,o=this.captureEventsPerSecond,a=new Date().getTime(),l=(n=(i=this.instance.persistence)==null?void 0:i.get_property(uo))!==null&&n!==void 0?n:{tokens:r,last:a};l.tokens+=(a-l.last)/1e3*o,l.last=a,l.tokens>r&&(l.tokens=r);var u=1>l.tokens;if(u||e||(l.tokens=Math.max(0,l.tokens-1)),u&&!e){var c=(he(l.dropped)?l.dropped:0)+1;l.dropped=c,!this.lastEventRateLimited&&this.Hi(c)&&(l.dropped=0)}return this.lastEventRateLimited=u,(s=this.instance.persistence)==null||s.set_property(uo,l),{isRateLimited:u,remainingTokens:l.tokens}}Ui(e){var n=this.instance.config.property_denylist;return!O(n)||!n.includes(e)}zi(){var e;if(this.Ui("$current_url")&&this.Ui("$pathname")&&se!=null&&se.pathname)return""+((e=se.origin)!==null&&e!==void 0?e:"")+se.pathname}Hi(e){var n,i,s=this.captureEventsBurstLimit,r=this.captureEventsPerSecond,o=this.zi(),a=this.Ui("$session_id")?(n=(i=this.instance).get_session_id)==null?void 0:n.call(i):void 0,l=[e+" event(s) dropped since the last warning",o?"triggered on "+o:void 0,a?"session "+a: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 "+r+" events per second and "+s+" events burst limit."},{skip_client_rate_limiting:!0})}isServerRateLimited(e){var n=this.serverLimits[e||"events"]||!1;return n!==!1&&new Date().getTime()e(this.remoteConfig))):e()}Vi(e){this._instance._send_request({method:"GET",url:this._instance.requestRouter.endpointFor("assets","/array/"+this._instance.config.token+"/config"),callback:e})}load(){try{if(this.remoteConfig)return Ct.info("Using preloaded remote config",this.remoteConfig),this.Zi(this.remoteConfig),void this.Gi();if(this._instance.Qi())return void Ct.warn("Remote config is disabled. Falling back to local config.");this.Wi((e=>{if(!e)return Ct.info("No config found after loading remote JS config. Falling back to JSON."),void this.Vi((n=>{this.Zi(n.json,n),this.Gi()}));this.Zi(e),this.Gi()}))}catch(e){Ct.error("Error loading remote config",e),this.Zi()}}stop(){this.Ki&&(clearInterval(this.Ki),this.Ki=void 0)}refresh(){!this._instance.Qi()&&C&&C.visibilityState!=="hidden"&&this._instance.reloadFeatureFlags()}Gi(){var e;if(!this.Ki){var n=(e=this._instance.config.remote_config_refresh_interval_ms)!==null&&e!==void 0?e:3e5;n!==0&&(this.Ki=setInterval((()=>{this.refresh()}),n))}}Zi(e,n){!e&&n&&(n.statusCode===0?n.error||Ct.warn("Failed to fetch remote config from PostHog."):Ct.error("Failed to fetch remote config from PostHog."));try{this._instance.Zi(e?{ok:!0,config:e}:{ok:!1})}catch(s){Ct.error("Error applying remote config",s)}if(e?.hasFeatureFlags!==!1&&!this._instance.config.advanced_disable_feature_flags_on_first_load)try{var i;(i=this._instance.featureFlags)==null||i.ensureFlagsLoaded()}catch(s){Ct.error("Error loading feature flags",s)}}}var qe=Uint8Array,Pe=Uint16Array,En=Uint32Array,ca=new qe([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]),ua=new qe([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]),$l=new qe([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),nd=function(t,e){for(var n=new Pe(31),i=0;31>i;++i)n[i]=e+=1<i;++i)for(var r=n[i];n[i+1]>r;++r)s[r]=r-n[i]<<5|i;return[n,s]},id=nd(ca,2),yo=id[1];id[0][28]=258,yo[258]=28;for(var Tl=nd(ua,0)[1],sd=new Pe(32768),oe=0;32768>oe;++oe){var on=(43690&oe)>>>1|(21845&oe)<<1;sd[oe]=((65280&(on=(61680&(on=(52428&on)>>>2|(13107&on)<<2))>>>4|(3855&on)<<4))>>>8|(255&on)<<8)>>>1}var ei=function(t,e,n){for(var i=t.length,s=0,r=new Pe(e);i>s;++s)++r[t[s]-1];var o,a=new Pe(e);for(s=0;e>s;++s)a[s]=a[s-1]+r[s-1]<<1;for(o=new Pe(i),s=0;i>s;++s)o[s]=sd[a[t[s]-1]++]>>>15-t[s];return o},Xt=new qe(288);for(oe=0;144>oe;++oe)Xt[oe]=8;for(oe=144;256>oe;++oe)Xt[oe]=9;for(oe=256;280>oe;++oe)Xt[oe]=7;for(oe=280;288>oe;++oe)Xt[oe]=8;var ws=new qe(32);for(oe=0;32>oe;++oe)ws[oe]=5;var ef=ei(Xt,9),tf=ei(ws,5),rd=function(t){return(t/8>>0)+(7&t&&1)},od=function(t,e,n){(n==null||n>t.length)&&(n=t.length);var i=new(t instanceof Pe?Pe:t instanceof En?En:qe)(n-e);return i.set(t.subarray(e,n)),i},ct=function(t,e,n){var i=e/8>>0;t[i]|=n<<=7&e,t[i+1]|=n>>>8},Ln=function(t,e,n){var i=e/8>>0;t[i]|=n<<=7&e,t[i+1]|=n>>>8,t[i+2]|=n>>>16},kr=function(t,e){for(var n=[],i=0;t.length>i;++i)t[i]&&n.push({s:i,f:t[i]});var s=n.length,r=n.slice();if(!s)return[new qe(0),0];if(s==1){var o=new qe(n[0].s+1);return o[n[0].s]=1,[o,1]}n.sort((function(A,F){return A.f-F.f})),n.push({s:-1,f:25001});var a=n[0],l=n[1],u=0,c=1,d=2;for(n[0]={s:-1,f:a.f+l.f,l:a,r:l};c!=s-1;)a=n[n[d].f>n[u].f?u++:d++],l=n[u!=c&&n[d].f>n[u].f?u++:d++],n[c++]={s:-1,f:a.f+l.f,l:a,r:l};var h=r[0].s;for(i=1;s>i;++i)r[i].s>h&&(h=r[i].s);var p=new Pe(h+1),f=wo(n[c-1],p,0);if(f>e){i=0;var g=0,m=f-e,v=1<i;++i){var E=r[i].s;if(e>=p[E])break;g+=v-(1<>>=m;g>0;){var w=r[i].s;e>p[w]?g-=1<=0&&g;--i){var I=r[i].s;p[I]==e&&(--p[I],++g)}f=e}return[new qe(p),f]},wo=function(t,e,n){return t.s==-1?Math.max(wo(t.l,e,n+1),wo(t.r,e,n+1)):e[t.s]=n},Rl=function(t){for(var e=t.length;e&&!t[--e];);for(var n=new Pe(++e),i=0,s=t[0],r=1,o=function(l){n[i++]=l},a=1;e>=a;++a)if(t[a]==s&&a!=e)++r;else{if(!s&&r>2){for(;r>138;r-=138)o(32754);r>2&&(o(r>10?r-11<<5|28690:r-3<<5|12305),r=0)}else if(r>3){for(o(s),--r;r>6;r-=6)o(8304);r>2&&(o(r-3<<5|8208),r=0)}for(;r--;)o(s);r=1,s=t[a]}return[n.subarray(0,i),e]},On=function(t,e){for(var n=0,i=0;e.length>i;++i)n+=t[i]*e[i];return n},bo=function(t,e,n){var i=n.length,s=rd(e+2);t[s]=255&i,t[s+1]=i>>>8,t[s+2]=255^t[s],t[s+3]=255^t[s+1];for(var r=0;i>r;++r)t[s+r+4]=n[r];return 8*(s+4+i)},Nl=function(t,e,n,i,s,r,o,a,l,u,c){ct(e,c++,n),++s[256];for(var d=kr(s,15),h=d[0],p=d[1],f=kr(r,15),g=f[0],m=f[1],v=Rl(h),E=v[0],w=v[1],I=Rl(g),A=I[0],F=I[1],D=new Pe(19),S=0;E.length>S;++S)D[31&E[S]]++;for(S=0;A.length>S;++S)D[31&A[S]]++;for(var $=kr(D,7),T=$[0],M=$[1],N=19;N>4&&!T[$l[N-1]];--N);var P,z,H,U,Q=u+5<<3,fe=On(s,Xt)+On(r,ws)+o,Ie=On(s,h)+On(r,g)+o+14+3*N+On(D,T)+(2*D[16]+3*D[17]+7*D[18]);if(fe>=Q&&Ie>=Q)return bo(e,c,t.subarray(l,l+u));if(ct(e,c,1+(fe>Ie)),c+=2,fe>Ie){P=ei(h,p),z=h,H=ei(g,m),U=g;var _e=ei(T,M);for(ct(e,c,w-257),ct(e,c+5,F-1),ct(e,c+10,N-4),c+=14,S=0;N>S;++S)ct(e,c+3*S,T[$l[S]]);c+=3*N;for(var Ce=[E,A],Te=0;2>Te;++Te){var ae=Ce[Te];for(S=0;ae.length>S;++S)ct(e,c,_e[me=31&ae[S]]),c+=T[me],me>15&&(ct(e,c,ae[S]>>>5&127),c+=ae[S]>>>12)}}else P=ef,z=Xt,H=tf,U=ws;for(S=0;a>S;++S)if(i[S]>255){var me;Ln(e,c,P[257+(me=i[S]>>>18&31)]),c+=z[me+257],me>7&&(ct(e,c,i[S]>>>23&31),c+=ca[me]);var ge=31&i[S];Ln(e,c,H[ge]),c+=U[ge],ge>3&&(Ln(e,c,i[S]>>>5&8191),c+=ua[ge])}else Ln(e,c,P[i[S]]),c+=z[i[S]];return Ln(e,c,P[256]),c+z[256]},nf=new En([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),sf=(function(){for(var t=new En(256),e=0;256>e;++e){for(var n=e,i=9;--i;)n=(1&n&&3988292384)^n>>>1;t[e]=n}return t})(),Ir=function(t,e,n){for(;n;++e)t[e]=n,n>>>=8};function rf(t,e){e===void 0&&(e={});var n=(function(){var d=4294967295;return{p(h){for(var p=d,f=0;h.length>f;++f)p=sf[255&p^h[f]]^p>>>8;d=p},d(){return 4294967295^d}}})(),i=t.length;n.p(t);var s,r,o,a,l,u=(a=10+((s=e).filename&&s.filename.length+1||0),l=8,(function(d,h,p,f,g,m){var v=d.length,E=new qe(f+v+5*(1+Math.floor(v/7e3))+g),w=E.subarray(f,E.length-g),I=0;if(!h||8>v)for(var A=0;v>=A;A+=65535){var F=A+65535;v>F?I=bo(w,I,d.subarray(A,F)):(w[A]=!0,I=bo(w,I,d.subarray(A,v)))}else{for(var D=nf[h-1],S=D>>>13,$=8191&D,T=(1<A;++A){var me=H(A),ge=32767&A,Qe=N[me];if(M[ge]=Qe,N[me]=ge,A>=Te){var Lt=v-A;if((Ie>7e3||Ce>24576)&&Lt>423){I=Nl(d,w,0,U,Q,fe,_e,Ce,ae,A-ae,I),Ce=Ie=_e=0,ae=A;for(var de=0;286>de;++de)Q[de]=0;for(de=0;30>de;++de)fe[de]=0}var Ge=2,It=0,Pn=$,De=ge-Qe&32767;if(Lt>2&&me==H(A-De))for(var Ae=Math.min(S,Lt)-1,Ei=Math.min(32767,A),Si=Math.min(258,Lt);Ei>=De&&--Pn&&ge!=Qe;){if(d[A+Ge]==d[A+Ge-De]){for(var je=0;Si>je&&d[A+je]==d[A+je-De];++je);if(je>Ge){if(Ge=je,It=De,je>Ae)break;var xi=Math.min(De,je-2),tn=0;for(de=0;xi>de;++de){var nn=A-De+de+32768&32767,$n=nn-M[nn]+32768&32767;$n>tn&&(tn=$n,Qe=nn)}}}De+=(ge=Qe)-(Qe=M[ge])+32768&32767}if(It){U[Ce++]=268435456|yo[Ge]<<18|Tl[It];var Va=31&yo[Ge],Ga=31&Tl[It];_e+=ca[Va]+ua[Ga],++Q[257+Va],++fe[Ga],Te=A+Ge,++Ie}else U[Ce++]=d[A],++Q[d[A]]}}I=Nl(d,w,!0,U,Q,fe,_e,Ce,ae,A-ae,I)}return od(E,0,f+rd(I)+g)})(r=t,(o=e).level==null?6:o.level,o.mem==null?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(r.length)))):12+o.mem,a,l)),c=u.length;return(function(d,h){var p=h.filename;if(d[0]=31,d[1]=139,d[2]=8,d[8]=2>h.level?4:h.level==9?2:0,d[9]=3,h.mtime!=0&&Ir(d,4,Math.floor(new Date(h.mtime||Date.now())/1e3)),p){d[3]=8;for(var f=0;p.length>=f;++f)d[f+10]=p.charCodeAt(f)}})(u,e),Ir(u,c-8,n.d()),Ir(u,c-4,i),u}var of=!!Wr||!!Ko,ad="text/plain",Vi=!1,ld=(t,e)=>{var n=t.split("#"),i=n[1],s=n[0].split("?"),r=s[0],o=s[1];if(!o)return t;var a=o.split("&").filter((l=>l.split("=")[0]!==e)).join("&");return r+(a?"?"+a:"")+(i?"#"+i:"")},js=function(t,e,n){var i;n===void 0&&(n=!0);var s=t.split("?"),r=s[0],o=s[1],a=b({},e),l=(i=o?.split("&").map((c=>{var d,h=c.split("="),p=h[0],f=n&&(d=a[p])!==null&&d!==void 0?d:h[1];return delete a[p],p+"="+f})))!==null&&i!==void 0?i:[],u=(function(c,d){var h,p;d===void 0&&(d="&");var f=[];return Z(c,(function(g,m){x(g)||x(m)||m==="undefined"||(h=encodeURIComponent((v=>v instanceof File)(g)?g.name:g.toString()),p=encodeURIComponent(m),f[f.length]=p+"="+h)})),f.join(d)})(a);return u&&l.push(u),l.length>0?r+"?"+l.join("&"):r},Cr=t=>{if(t.Ji)return t.Ji;var e=t.data,n=t.compression;if(e){if(n===xe.GZipJS){var i=rf((function(a,l){var u=a.length;if(typeof TextEncoder<"u")return new TextEncoder().encode(a);for(var c=new qe(a.length+(a.length>>>1)),d=0,h=function(m){c[d++]=m},p=0;u>p;++p){if(d+5>c.length){var f=new qe(d+8+(u-p<<1));f.set(c),c=f}var g=a.charCodeAt(p);128>g?h(g):2048>g?(h(192|g>>>6),h(128|63&g)):g>55295&&57344>g?(h(240|(g=65536+(1047552&g)|1023&a.charCodeAt(++p))>>>18),h(128|g>>>12&63),h(128|g>>>6&63),h(128|63&g)):(h(224|g>>>12),h(128|g>>>6&63),h(128|63&g))}return od(c,0,d)})(pn(e)),{mtime:0});return{contentType:ad,body:i.buffer.slice(i.byteOffset,i.byteOffset+i.byteLength),estimatedSize:i.byteLength}}if(n===xe.Base64){var s=(function(a){return a&&btoa(encodeURIComponent(a).replace(/%([0-9A-F]{2})/g,((l,u)=>String.fromCharCode(parseInt(u,16)))))})(pn(e)),r=(a=>"data="+encodeURIComponent(typeof a=="string"?a:pn(a)))(s);return{contentType:"application/x-www-form-urlencoded",body:r,estimatedSize:new Blob([r]).size}}var o=pn(e);return{contentType:"application/json",body:o,estimatedSize:new Blob([o]).size}}},cd=t=>{var e,n,i=()=>t.transport==="sendBeacon"?{url:js(t.url,{compression:xe.Base64}),encodedBody:Cr(b({},t,{compression:xe.Base64,Ji:void 0}))}:{url:ld(t.url,"compression"),encodedBody:Cr(b({},t,{compression:void 0,Ji:void 0}))};try{e=Cr(t)}catch(s){if(el(t.compression,wn(t.url,"compression")))return k.error("Failed to gzip request body, sending uncompressed payload",s),i();throw s}return e&&el(t.compression,wn(t.url,"compression"))&&!((n=e.body)instanceof ArrayBuffer?zr(new Uint8Array(n)):ArrayBuffer.isView(n)&&zr(new Uint8Array(n.buffer,n.byteOffset,n.byteLength)))?(Vi=!0,i()):{url:t.url,encodedBody:e}},ud=t=>{try{return cd(t)}catch(e){return k.error(e),void(t.callback==null||t.callback({statusCode:0,error:e}))}},af=(function(){var t=X((function*(e){var n=pn(e.data),i=yield(function(r,o,a){return qr.apply(this,arguments)})(n,Y.DEBUG,{rethrow:!0});if(!i)return e;var s=yield i.arrayBuffer();return b({},e,{Ji:{contentType:ad,body:s,estimatedSize:s.byteLength}})}));return function(e){return t.apply(this,arguments)}})(),lf=/Failed to fetch|NetworkError|Load failed/i,dd=t=>t?.name==="TypeError"&&lf.test(t?.message||""),hd=t=>{var e=ud(t);if(e){var n=e.url,i=e.encodedBody,s=i??{},r=s.contentType,o=s.body,a=s.estimatedSize,l=new Headers;Z(t.headers,(function(f,g){l.append(g,f)})),r&&l.append("Content-Type",r);var u=null,c=!1;if(Ka){var d=new Ka;u={signal:d.signal,timeout:setTimeout((()=>{var f,g;c=!0,d.abort((f=t.timeout,(g=new Error("PostHog request timed out"+(f?" after "+f+"ms":""))).name="AbortError",g))}),t.timeout)}}var h=f=>{c&&f?.name==="AbortError"||dd(f)?k.warn(f):k.error(f),t.callback==null||t.callback({statusCode:0,error:f})};try{var p;Ko(n,b({method:t?.method||"GET",headers:l,keepalive:t.method==="POST"&&!t.Yi&&52428.8>(a||0),body:o,signal:(p=u)==null?void 0:p.signal},t.fetchOptions)).then((f=>f.text().then((g=>{var m={statusCode:f.status,text:g};if(f.status===200)try{m.json=JSON.parse(g)}catch(v){k.error(v)}t.callback==null||t.callback(m)})))).catch(h).finally((()=>u?clearTimeout(u.timeout):null))}catch(f){u&&clearTimeout(u.timeout),h(f)}}},Eo=t=>{try{var e,n=cd(t),i=n.url,s=n.encodedBody,r=s??{},o=r.body,a=r.estimatedSize;if(!o)return;var l=o instanceof Blob?o:new Blob([o],{type:r.contentType});if(ke.sendBeacon(i,l))return;var u=O(t.data)?t.data:(e=t.data)==null?void 0:e.batch;if(O(u)&&u.length>1&&(a??0)>16384){var c=Math.ceil(u.length/2),d=h=>O(t.data)?h:b({},t.data,{batch:h});return Eo(b({},t,{data:d(u.slice(0,c))})),void Eo(b({},t,{data:d(u.slice(c))}))}k.warn("Beacon of ~"+(a??0)+" bytes was rejected by the browser, falling back to fetch"),hd(b({},t,{Yi:!0}))}catch(h){k.warn("Beacon send failed",h)}},Ml=(t,e,n,i)=>{var s=i==="query"?e==="POST"?"sent_at":"_":void 0;return js(n===xe.GZipJS?ld(t,"compression"):t,b({},s?{[s]:Date.now().toString()}:{},n===xe.GZipJS?{}:{compression:n}))},Gi=[];Ko&&Gi.push({transport:"fetch",method:hd}),Wr&&Gi.push({transport:"XHR",method(t){var e=ud(t);if(e){var n=new Wr,i=e.encodedBody;n.open(t.method||"GET",e.url,!0);var s=i??{},r=s.contentType,o=s.body;Z(t.headers,(function(a,l){n.setRequestHeader(l,a)})),r&&n.setRequestHeader("Content-Type",r),t.timeout&&(n.timeout=t.timeout),n.onreadystatechange=()=>{if(n.readyState===4){var a={statusCode:n.status,text:n.responseText};if(n.status===200)try{a.json=JSON.parse(n.responseText)}catch{}t.callback==null||t.callback(a)}},n.send(o)}}}),ke!=null&&ke.sendBeacon&&Gi.push({transport:"sendBeacon",method:Eo});var So=3e3;class cf{constructor(e,n){this.Xi=!0,this.tr=[],this.er=ot(n?.flush_interval_ms||So,250,5e3,k.createLogger("flush interval"),So),this.ir=e}enqueue(e){this.tr.push(e),this.rr||this.nr()}unload(){this.sr();var e=this.tr.length>0?this.ar():{},n=Object.values(e);[...n.filter((i=>i.url.indexOf("/e")===0)),...n.filter((i=>i.url.indexOf("/e")!==0))].map((i=>{this.lr(b({},i,{transport:"sendBeacon"}))}))}enable(){this.Xi=!1,this.nr()}nr(){var e=this;this.Xi||(this.rr=setTimeout((()=>{if(this.sr(),this.tr.length>0){var n=this.ar(),i=function(){var r=n[s],o=new Date().getTime();r.data&&O(r.data)&&Z(r.data,(a=>{a.offset=Math.abs(a.timestamp-o),delete a.timestamp})),e.lr(r)};for(var s in n)i()}}),this.er))}lr(e){try{this.ir(e)}catch(n){k.error(n)}}sr(){clearTimeout(this.rr),this.rr=void 0}ar(){var e={};return Z(this.tr,(n=>{var i,s=n,r=(s?s.batchKey:null)||s.url;x(e[r])&&(e[r]=b({},s,{data:[]})),(i=e[r].data)==null||i.push(s.data)})),this.tr=[],e}}var uf=["retriesPerformedSoFar"];class df{constructor(e){this.ur=!1,this.hr=3e3,this.tr=[],this._instance=e,this.tr=[],this.dr=!0,!x(_)&&"onLine"in _.navigator&&(this.dr=_.navigator.onLine,this.vr=()=>{this.dr=!0,this.cr()},this.pr=()=>{this.dr=!1},re(_,"online",this.vr),re(_,"offline",this.pr))}get length(){return this.tr.length}retriableRequest(e){var n=e.retriesPerformedSoFar,i=jc(e,uf);dt(n)&&(i.url=js(i.url,{retry_count:n})),this._instance._send_request(b({},i,{callback:s=>{if(s.statusCode!==200&&(400>s.statusCode||s.statusCode>=500)){if((s.statusCode===0?3:10)>(n??0))return void this.At(b({retriesPerformedSoFar:n},i));s.statusCode===0&&k.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.")}i.callback==null||i.callback(s)}}))}At(e){var n=e.retriesPerformedSoFar||0;e.retriesPerformedSoFar=n+1;var i=(function(o){var a=3e3*Math.pow(2,o),l=a/2,u=Math.min(18e5,a),c=Math.random()-.5;return Math.ceil(u+c*(u-l))})(n),s=Date.now()+i;this.tr.push({retryAt:s,requestOptions:e});var r="Enqueued failed request for retry in "+i;navigator.onLine||(r+=" (Browser is offline)"),k.warn(r),this.ur||(this.ur=!0,this.gr())}gr(){if(this.mr&&clearTimeout(this.mr),this.tr.length===0)return this.ur=!1,void(this.mr=void 0);this.mr=setTimeout((()=>{this.dr&&this.tr.length>0&&this.cr(),this.gr()}),this.hr)}cr(){var e=Date.now(),n=[],i=this.tr.filter((r=>e>r.retryAt||(n.push(r),!1)));if(this.tr=n,i.length>0)for(var s of i)this.retriableRequest(s.requestOptions)}unload(){for(var e of(this.mr&&(clearTimeout(this.mr),this.mr=void 0),this.ur=!1,x(_)||(this.vr&&(_.removeEventListener("online",this.vr),this.vr=void 0),this.pr&&(_.removeEventListener("offline",this.pr),this.pr=void 0)),this.tr)){var n=e.requestOptions;try{this._instance._send_request(b({},n,{transport:"sendBeacon"}))}catch(i){k.error(i)}}this.tr=[]}}class hf{constructor(e){this.yr=()=>{var n,i,s,r;this.br||(this.br={});var o=this.scrollElement(),a=this.scrollY(),l=o?Math.max(0,o.scrollHeight-o.clientHeight):0,u=a+(o?.clientHeight||0),c=o?.scrollHeight||0;this.br.lastScrollY=Math.ceil(a),this.br.maxScrollY=Math.max(a,(n=this.br.maxScrollY)!==null&&n!==void 0?n:0),this.br.maxScrollHeight=Math.max(l,(i=this.br.maxScrollHeight)!==null&&i!==void 0?i:0),this.br.lastContentY=u,this.br.maxContentY=Math.max(u,(s=this.br.maxContentY)!==null&&s!==void 0?s:0),this.br.maxContentHeight=Math.max(c,(r=this.br.maxContentHeight)!==null&&r!==void 0?r:0)},this._instance=e}get _r(){return this._instance.config.scroll_root_selector}getContext(){return this.br}resetContext(){var e=this.br;return setTimeout(this.yr,0),e}startMeasuringScrollPosition(){re(_,"scroll",this.yr,{capture:!0}),re(_,"scrollend",this.yr,{capture:!0}),re(_,"resize",this.yr)}scrollElement(){if(!this._r)return _?.document.documentElement;var e=O(this._r)?this._r:[this._r];for(var n of e){var i=_?.document.querySelector(n);if(i)return i}}wr(e){var n=e==="y"?"scrollTop":"scrollLeft";if(this._r){var i=this.scrollElement();return i&&i[n]||0}return _?e==="y"?_.scrollY||_.pageYOffset||_.document.documentElement.scrollTop||0:_.scrollX||_.pageXOffset||_.document.documentElement.scrollLeft||0:0}scrollY(){return this.wr("y")}scrollX(){return this.wr("x")}}var pf=t=>Xu(t?.config.mask_personal_data_properties,t?.config.custom_personal_data_properties,t?.config.disable_capture_url_hashes);class Ll{constructor(e,n,i,s){this.kr=r=>{var o=this.Sr();if(!o||o.sessionId!==r){var a={sessionId:r,props:this.Cr(this._instance)};this.Mr.register({[co]:a})}},this._instance=e,this.Tr=n,this.Mr=i,this.Cr=s||pf,this.Tr.onSessionId(this.kr)}Sr(){return this.Mr.props[co]}getSetOnceProps(){var e,n=(e=this.Sr())==null?void 0:e.props;return n?"r"in n?Qu(n,this._instance.config.disable_capture_url_hashes):{$referring_domain:n.referringDomain,$pathname:n.initialPathName,utm_source:n.utm_source,utm_campaign:n.utm_campaign,utm_medium:n.utm_medium,utm_content:n.utm_content,utm_term:n.utm_term}:{}}getSessionProps(){var e={};return Z(ra(this.getSetOnceProps()),((n,i)=>{i==="$current_url"&&(i="url"),e["$session_entry_"+Vr(i)]=n})),e}}class da{on(e,n){return this.Er[e]||(this.Er[e]=[]),this.Er[e].push(n),()=>{this.Er[e]=this.Er[e].filter((i=>i!==n))}}emit(e,n){for(var i of this.Er[e]||[])i(n);for(var s of this.Er["*"]||[])s(e,n)}constructor(){this.Er={}}}var Bn=ie("[SessionId]");class Ol{on(e,n){return this.Ir.on(e,n)}constructor(e,n,i){var s;if(this.Pr=null,this.Rr=[],this.Ar=void 0,this.Fr=!1,this.Ir=new da,this.Lr=(u,c)=>!(!dt(u)||!dt(c))&&Math.abs(u-c)>this.sessionTimeoutMs,!e.persistence)throw new Error("SessionIdManager requires a PostHogPersistence instance");if(e.config.cookieless_mode===gt)throw new Error('SessionIdManager cannot be used with cookieless_mode="always"');this.Ne=e.config,this.Mr=e.persistence,this.Or=void 0,this.Dr=void 0,this._sessionStartTimestamp=null,this._sessionActivityTimestamp=null,this.$r=n||ft,this.Nr=i||ft;var r=this.Ne.persistence_name||this.Ne.token;if(this._sessionTimeoutMs=1e3*ot(this.Ne.session_idle_timeout_seconds||1800,60,36e3,Bn.createLogger("session_idle_timeout_seconds"),1800),e.register({$configured_session_timeout_ms:this._sessionTimeoutMs}),this.qr(),this.jr="ph_"+r+"_window_id",this.Br="ph_"+r+"_primary_window_exists",this.Hr()){var o=ce.H(this.jr),a=ce.H(this.Br);o&&!a?this.Or=o:ce.q(this.jr),ce.F(this.Br,!0)}if((s=this.Ne.bootstrap)!=null&&s.sessionID)try{var l=(u=>{var c=this.Ne.bootstrap.sessionID.replace(/-/g,"");if(c.length!==32)throw new Error("Not a valid UUID");if(c[12]!=="7")throw new Error("Not a UUIDv7");return parseInt(c.substring(0,12),16)})();this.Ur(this.Ne.bootstrap.sessionID,new Date().getTime(),l)}catch(u){Bn.error("Invalid sessionID in bootstrap",u)}this.zr()}get sessionTimeoutMs(){return this._sessionTimeoutMs}onSessionId(e){return x(this.Rr)&&(this.Rr=[]),this.Rr.push(e),this.Dr&&e(this.Dr,this.Or),()=>{this.Rr=this.Rr.filter((n=>n!==e))}}Hr(){return this.Ne.persistence!=="memory"&&!this.Mr.xi&&ce.N()}Wr(e){e!==this.Or&&(this.Or=e,this.Hr()&&ce.F(this.jr,e))}Vr(){return this.Or?this.Or:this.Hr()?ce.H(this.jr):null}Zr(e){var n=this.Pr;return!$e(n)&&!$e(e)&&5e3>Math.abs(e-n)}Ur(e,n,i){var s=n!==this._sessionActivityTimestamp,r=!(e!==this.Dr||i!==this._sessionStartTimestamp);this._sessionStartTimestamp=i,this._sessionActivityTimestamp=n,this.Dr=e,r&&!s||r&&this.Zr(n)||(this.Pr=n,this.Mr.register({[hn]:[n,e,i]}))}Gr(){var e,n=(e=this.Ne)==null?void 0:e.persistence_save_debounce_ms;return dt(n)&&n>0}Qr(){this.Gr()?this.Mr.refreshKey(hn):(this.Mr.flush(),this.Mr.load())}Kr(){var e;if(!$e(this._sessionActivityTimestamp)&&this._sessionActivityTimestamp!==this.Pr){this.Qr();var n=this.Jr();n[1]===this.Dr&&n[2]===this._sessionStartTimestamp&&(this.Pr=this._sessionActivityTimestamp,this.Mr.register({[hn]:[this._sessionActivityTimestamp,(e=this.Dr)!==null&&e!==void 0?e:null,this._sessionStartTimestamp]}),this.Mr.flush())}}Yr(){var e=this.Jr()[0],n=dt(e)?e:0,i=dt(this._sessionActivityTimestamp)?this._sessionActivityTimestamp:0;return Math.max(n,i)}Xr(e){return this.Qr(),this.Lr(e,this.Yr())}Jr(){var e=this.Mr.props[hn];return O(e)&&e.length===2&&e.push(e[0]),e||[0,null,0]}resetSessionId(){this.Pr=null,clearTimeout(this.tn),this.tn=void 0,this.Ur(null,null,null)}destroy(){this.Fr=!0,this.Kr(),clearTimeout(this.tn),this.tn=void 0,this.Ar&&_&&(_.removeEventListener(fs,this.Ar,{capture:!1}),this.Ar=void 0),this.Rr=[]}zr(){this.Ar=()=>{this.Kr(),this.Hr()&&ce.q(this.Br)},re(_,fs,this.Ar,{capture:!1})}checkAndGetSessionAndWindowId(e,n){if(e===void 0&&(e=!1),n===void 0&&(n=null),this.Ne.cookieless_mode===gt)throw new Error('checkAndGetSessionAndWindowId should not be called with cookieless_mode="always"');var i=n||new Date().getTime(),s=this.Jr(),r=s[1],o=s[2],a=this.Yr(),l=this.Vr(),u=dt(o)&&Math.abs(i-o)>864e5,c=!1,d=!1,h=!r,p=r,f=!h&&!e&&this.Lr(i,a);if(f){(f=this.Xr(i))||Bn.info("cross-tab refresh kept the session alive",{sessionId:r});var g=this.Jr();r=g[1],o=g[2]}h||f||u?(r=this.$r(),l=this.Nr(),Bn.info("new session ID generated",{sessionId:r,windowId:l,changeReason:{noSessionId:h,activityTimeout:f,sessionPastMaximumLength:u}}),o=i,c=!0):(l||(l=this.Nr(),c=!0),(d=r!==p)&&(Bn.info("adopted cross-tab session id",{sessionId:r,windowId:l}),c=!0));var m=dt(a)&&e&&!u?a:i,v=dt(o)?o:new Date().getTime();this.Wr(l),this.Ur(r,m,v),e||this.qr();var E={noSessionId:h,activityTimeout:f,sessionPastMaximumLength:u,crossTabAdoption:d};return c&&this.Rr.forEach((w=>w(r,l,E))),{sessionId:r,windowId:l,sessionStartTimestamp:v,changeReason:c?E:void 0,lastActivityTimestamp:a}}qr(){this.Fr||(clearTimeout(this.tn),this.tn=setTimeout((()=>{if(!this.Fr)if(this.Xr(new Date().getTime())){var e=this.Dr;this.resetSessionId(),this.Ir.emit("forcedIdleReset",{idleSessionId:e})}else this.qr()}),1.1*this.sessionTimeoutMs))}}var pd=function(t,e){if(!t)return!1;var n=t.userAgent;if(n&&nl(n,e))return!0;try{var i=t?.userAgentData;if(i!=null&&i.brands&&i.brands.some((s=>nl(s?.brand,e))))return!0}catch{}return!!t.webdriver};function fd(){return(fd=X((function*(){var t=ke?.userAgentData;if(t!=null&&t.getHighEntropyValues)try{var e=yield t.getHighEntropyValues(["model"]),n=e?.model;return q(n)&&n.length>0?n:void 0}catch(i){return void k.info("Unable to resolve $device_model from userAgentData.getHighEntropyValues",i)}}))).apply(this,arguments)}var bs=function(t,e){if(!(function(n){try{new RegExp(n)}catch{return!1}return!0})(e))return!1;try{return new RegExp(e).test(t)}catch{return!1}};function Ar(t,e,n){return pn({distinct_id:t,userPropertiesToSet:e,userPropertiesToSetOnce:n})}var gd={exact:(t,e)=>e.some((n=>t.some((i=>n===i)))),is_not:(t,e)=>e.every((n=>t.every((i=>n!==i)))),regex:(t,e)=>e.some((n=>t.some((i=>bs(n,i))))),not_regex:(t,e)=>e.every((n=>t.every((i=>!bs(n,i))))),icontains:(t,e)=>e.map(Ri).some((n=>t.map(Ri).some((i=>n.includes(i))))),not_icontains:(t,e)=>e.map(Ri).every((n=>t.map(Ri).every((i=>!n.includes(i))))),gt:(t,e)=>e.some((n=>{var i=parseFloat(n);return!isNaN(i)&&t.some((s=>i>parseFloat(s)))})),lt:(t,e)=>e.some((n=>{var i=parseFloat(n);return!isNaN(i)&&t.some((s=>it.toLowerCase();function md(t,e){return!t||Object.entries(t).every((n=>{var i=n[1],s=e?.[n[0]];if(x(s)||$e(s))return!1;var r=[String(s)],o=gd[i.operator];return!!o&&o(i.values,r)}))}var xo="custom",Bl="i.posthog.com",ff=/^\/static\//;class gf{constructor(e){this.en={},this.instance=e}get apiHost(){var e=this.instance.config.api_host.trim().replace(/\/$/,"");return e==="https://app.posthog.com"?"https://us.i.posthog.com":e}get flagsApiHost(){var e=this.instance.config.flags_api_host;return e?e.trim().replace(/\/$/,""):this.apiHost}get uiHost(){var e,n=(e=this.instance.config.ui_host)==null?void 0:e.replace(/\/$/,"");return n||(n=this.apiHost.replace("."+Bl,".posthog.com")),n==="https://app.posthog.com"?"https://us.posthog.com":n}get region(){return this.en[this.apiHost]||(this.en[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":xo),this.en[this.apiHost]}rn(e){if(ff.test(e)){var n=this.instance.config.asset_host;if(typeof n=="string")return n.trim().replace(/\/$/,"")||void 0}}endpointFor(e,n){if(n===void 0&&(n=""),n&&(n=n[0]==="/"?n:"/"+n),e==="ui")return this.uiHost+n;if(e==="flags")return this.flagsApiHost+n;if(e==="assets"){var i=this.rn(n);if(i)return""+i+n}if(this.region===xo)return this.apiHost+n;var s=Bl+n;switch(e){case"assets":return"https://"+this.region+"-assets."+s;case"api":return"https://"+this.region+"."+s}}}function vd(t){var e;return!((e=t.conditions)==null||(e=e.events)==null||(e=e.values)==null||!e.length)}var G=ie("[Surveys]"),_d="seenSurvey_",yd=t=>{try{var e=(n=>((i,s)=>""+_d+(function(r){return r.current_iteration&&r.current_iteration>0?r.id+"_"+r.current_iteration:r.id})(s))(0,n))(t);if(localStorage.getItem(e))return;localStorage.setItem(e,"true")}catch(n){G.error("Failed to persist survey seen state",n)}},mf=[Sr.Popover,Sr.Widget,Sr.API],vf={ignoreConditions:!1,ignoreDelay:!1,displayType:_o.Popover},_f=ie("[PostHog ExternalIntegrations]"),yf={intercom:"intercom-integration",crispChat:"crisp-chat-integration"};class wf{constructor(e){this._instance=e}ai(e,n){var i;(i=R.__PosthogExtensions__)==null||i.loadExternalDependency==null||i.loadExternalDependency(this._instance,e,(s=>{if(s)return _f.error("failed to load script",s);n()}))}startIfEnabledOrStop(){var e=this,n=function(){var r,o,a,l=i[0],u=i[1];!u||(r=R.__PosthogExtensions__)!=null&&(r=r.integrations)!=null&&r[l]||e.ai(yf[l],(()=>{var c;(c=R.__PosthogExtensions__)==null||(c=c.integrations)==null||(c=c[l])==null||c.start(e._instance)})),!u&&(o=R.__PosthogExtensions__)!=null&&(o=o.integrations)!=null&&o[l]&&((a=R.__PosthogExtensions__)==null||(a=a.integrations)==null||(a=a[l])==null||a.stop())};for(var i of Object.entries((s=this._instance.config.integrations)!==null&&s!==void 0?s:{})){var s;n()}}}class bf{constructor(e,n){this.rt=e,this.nn=n,this.sn=new Map,this.an=!1}add(e){var n=this;return X((function*(){if(n.an)throw new Error("Cannot add an extension to a disposed ExtensionRuntime");if(n.sn.has(e.name))throw new Error('Browser extension "'+e.name+'" is already registered');n.sn.set(e.name,e);try{var i=e.setup(n.nn);i&&(yield i)}catch(r){var s=n.sn.get(e.name)===e;s&&n.sn.delete(e.name),n.rt.error('Failed to set up browser extension "'+e.name+'"',r),s&&n.ln(e)}}))()}dispose(){if(!this.an){this.an=!0;var e=Array.from(this.sn.values()).reverse();for(var n of(this.sn.clear(),e))this.ln(n)}}ln(e){try{var n=e.dispose==null?void 0:e.dispose();n&&Se(n.then)&&n.then(void 0,(i=>{this.rt.error('Failed to dispose browser extension "'+e.name+'"',i)}))}catch(i){this.rt.error('Failed to dispose browser extension "'+e.name+'"',i)}}}class Ef{constructor(e){this._instance=e}initialize(){}get(e){var n=this._instance.persistence;if(typeof e=="string")return n?.get_property(e);var i={};for(var s of e){var r=n?.get_property(s);x(r)||(i[s]=r)}return i}set(e,n){var i;(i=this._instance.persistence)==null||i.register(typeof e=="string"?{[e]:n}:e)}remove(e){var n;(n=this._instance.persistence)==null||n.unregister(e)}}var Dl="extensionsRemoteConfig";class Sf{constructor(e){this.an=!1,this.instance=e,this.rt=k,this.un=e.hn,this.kv=new Ef(e),this.onEvent=n=>Ti(this.instance.on("eventCaptured",(i=>{try{n({event:i.event,properties:i.properties})}catch(s){this.rt.error("Browser extension event listener failed",s)}}))),this.onRemoteConfig=n=>{if(this.an)return Ti((()=>{}));var i=r=>{try{n(r)}catch(o){this.rt.error("Browser extension remote config listener failed",o)}},s=this.instance.dn.on(Dl,i);return this.un&&i(this.un),Ti(s)},this.vn=new bf(k.createLogger("[BrowserExtensions]"),this)}get logger(){return this.rt}get distinctId(){return this.instance.get_distinct_id()}get anonymousId(){var e;return(e=this.instance.get_property(ai))!==null&&e!==void 0?e:this.distinctId}get deviceId(){var e=this.instance.get_property(ai);return typeof e=="string"?e:void 0}get library(){return{name:Y.LIB_NAME,version:Y.LIB_VERSION}}get initialPersonProperties(){var e,n;return(e=(n=this.instance.persistence)==null?void 0:n.get_initial_props())!==null&&e!==void 0?e:{}}get groups(){return this.instance.getGroups()}get session(){try{var e,n,i,s,r=(e=this.instance.sessionManager)==null?void 0:e.checkAndGetSessionAndWindowId(!0);return{sessionId:(n=r?.sessionId)!==null&&n!==void 0?n:"",windowId:(i=r?.windowId)!==null&&i!==void 0?i:"",sessionStartTimestamp:(s=r?.sessionStartTimestamp)!==null&&s!==void 0?s:0}}catch{return{sessionId:"",windowId:"",sessionStartTimestamp:0}}}get projectToken(){return this.instance.config.token}add(e){return this.vn.add(e)}capture(e,n,i){var s=this;return X((function*(){i?s.instance.capture(e,n,{timestamp:i.timestamp,uuid:i.uuid,$set:i.set,$set_once:i.setOnce}):s.instance.capture(e,n)}))()}registerDynamicEventProperties(e){return Ti(this.instance.cn(e))}handleRemoteConfig(e){this.an||(this.un=e,this.instance.dn.emit(Dl,e))}sendRequest(e,n){var i=this;return X((function*(){var s;n===void 0&&(n={});var r=i.instance.requestRouter.endpointFor((s=n.target)!==null&&s!==void 0?s:"api",e),o={method:n.method,url:n.query?js(r,n.query):r,data:n.body,headers:n.headers,timeout:n.timeoutMs,fireCallbackOnDrop:!0,transport:n.transport,compression:n.compression,timestampMode:n.sentAt};return n.transport==="sendBeacon"?(i.instance._send_request(o),{statusCode:202}):new Promise((a=>{o.callback=a,i.instance._send_request(o)}))}))()}dispose(){this.an||(this.an=!0,this.vn.dispose())}}var ti={},Fr=0,Es=()=>{},jl='Consent opt in/out is not valid with cookieless_mode="always" and will be ignored',Dn="Surveys module not available",Ul="sanitize_properties is deprecated. Use before_send instead",wd="Invalid value for property_denylist config: ",xf=["token","distinct_id",Cu],un="posthog",bd=!of&&Fe?.indexOf("MSIE")===-1&&Fe?.indexOf("Mozilla")===-1,Pr=t=>{var e;return b({api_host:"https://us.i.posthog.com",flags_api_host:null,ui_host:null,asset_host:null,token:"",autocapture:!0,cross_subdomain_cookie:xp(C?.location),persistence:"localStorage+cookie",persistence_name:"",cookie_persisted_properties:[],loaded:Es,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_external_dependency_versioned_paths:!1,__preview_cookie_wins_on_conflict:!1,debug:se&&q(se?.search)&&se.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,disable_external_dependency_loading:!1,strict_script_versioning:!1,enable_recording_console_log:void 0,secure_cookie:(_==null||(e=_.location)==null?void 0:e.protocol)==="https:",ip:!1,opt_out_capturing_by_default:!1,opt_out_persistence_by_default:!1,opt_out_useragent_filter:!1,opt_out_capturing_persistence_type:"localStorage",consent_persistence_name:null,opt_out_capturing_cookie_prefix:null,opt_in_site_apps:!1,property_denylist:[],respect_dnt:!1,sanitize_properties:null,request_headers:{},request_batching:!0,properties_string_max_length:65535,mask_all_element_attributes:!1,mask_all_text:!1,mask_personal_data_properties:!1,custom_personal_data_properties:[],advanced_disable_flags:!1,advanced_disable_decide:!1,advanced_disable_feature_flags:!1,advanced_disable_feature_flags_on_first_load:!1,advanced_only_evaluate_survey_feature_flags:!1,advanced_feature_flags_dedup_per_session:!1,advanced_enable_surveys:!1,advanced_disable_toolbar_metrics:!1,feature_flag_request_timeout_ms:3e3,surveys_request_timeout_ms:1e4,on_request_error(n){k.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:fo,before_send:void 0,get_current_url:void 0,request_queue_config:{flush_interval_ms:So},error_tracking:{},_onCapture:Es},(n=>({rageclick:n&&n>="2026-05-30"?{content_ignorelist:Lp,ignore_text_selection:!0}:!n||"2025-11-30">n||{content_ignorelist:!0},capture_pageview:!n||"2025-05-24">n||"history_change",session_recording:n&&n>="2026-06-25"?{strictMinimumDuration:!0,canvasCapture:{resolutionScale:.6},streamNetworkBody:!0}:n&&n>="2026-05-30"?{strictMinimumDuration:!0,canvasCapture:{resolutionScale:.6}}:n&&n>="2025-11-30"?{strictMinimumDuration:!0}:{},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)}))(t))},kf=[["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"]],Hl=t=>{var e={};for(var n of kf){var i=n[0],s=n[1];x(t[i])||(e[s]=t[i])}var r=te({},e,t),o=t.__preview_external_dependency_versioned_paths;return x(o)||(x(t.strict_script_versioning)&&(r.strict_script_versioning=!!o),q(o)&&x(t.asset_host)&&(r.asset_host=o)),O(t.property_blacklist)&&(x(t.property_denylist)?r.property_denylist=t.property_blacklist:O(t.property_denylist)?r.property_denylist=[...t.property_blacklist,...t.property_denylist]:k.error(wd+t.property_denylist)),r};class If{constructor(){this.__forceAllowLocalhost=!1}get fn(){return this.__forceAllowLocalhost}set fn(e){k.error("WebPerformanceObserver is deprecated and has no impact on network capture. Use `_forceAllowLocalhostNetworkCapture` on `posthog.sessionRecording`"),this.__forceAllowLocalhost=e}}class Re{pn(e,n){if(e){var i=this.sn.indexOf(e);i!==-1&&this.sn.splice(i,1)}return this.sn.push(n),n.initialize==null||n.initialize(),n}gn(){return this.config.cookieless_mode===gt||this.config.cookieless_mode===Vt&&this.consent.isRejected()}get decideEndpointWasHit(){var e,n;return(e=(n=this.featureFlags)==null?void 0:n.hasLoadedFlags)!==null&&e!==void 0&&e}get flagsEndpointWasHit(){var e,n;return(e=(n=this.featureFlags)==null?void 0:n.hasLoadedFlags)!==null&&e!==void 0&&e}constructor(){var e;this.webPerformance=new If,this.mn=!1,this.version=Y.LIB_VERSION,this.yn=new Set,this.bn="",this.dn=new da,this.sn=[],this._n=[],this._calculate_event_properties=this.calculateEventProperties.bind(this),this.config=Pr(),this.SentryIntegration=zp,this.sentryIntegration=i=>(function(s,r){var o=qu(s,r);return{name:zu,processEvent:a=>o(a)}})(this,i),this.__request_queue=[],this.__loaded=!1,this.analyticsDefaultEndpoint="/e/",this.wn=!1,this.kn=null,this.xn=null,this.Sn=null,this.scrollManager=new hf(this),this.pageViewManager=new Cl(this),this.rateLimiter=new Qp(this),this.requestRouter=new gf(this),this.consent=new $p(this),this.externalIntegrations=new wf(this);var n=(e=Re.__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:(i,s,r)=>{var o=q(i)?{[i]:s}:i;this.setPersonProperties(o),r?.({})},set_once:(i,s,r)=>{var o=q(i)?{[i]:s}:i;this.setPersonProperties(void 0,o),r?.({})}},this.on("eventCaptured",(i=>k.info('send "'+i?.event+'"',i)))}init(e,n,i){if(i&&i!==un){var s,r=(s=ti[i])!==null&&s!==void 0?s:new Re;return r._init(e,n,i),ti[i]=r,ti[un][i]=r,r}return this._init(e,n,i)}_init(e,n,i){var s,r;n===void 0&&(n={});var o,a=q(e)?e.trim():"";if(!a)return k.critical("PostHog was initialized without a token. This likely indicates a misconfiguration. Please check the first argument passed to posthog.init()"),this;if(this.__loaded)return a!==((o=this.config)==null?void 0:o.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('"+a+"', { ... }, 'project2')"):console.warn("[PostHog.js]","You have already initialized PostHog! Re-initializing is a no-op"),this;this.__loaded=!0,this.config=Pr(n.defaults),n.debug=this.Cn(n.debug),this.Mn=n,this.Tn=[],n.person_profiles?this.xn=n.person_profiles:n.process_person&&(this.xn=n.process_person);var l=Pr(n.defaults),u=Hl(n),c=te({},l,u,{name:i,token:a});ne(l.rageclick)&&ne(u.rageclick)&&(c.rageclick=te({},l.rageclick,u.rageclick)),ne(l.session_recording)&&ne(u.session_recording)&&(c.session_recording=te({},l.session_recording,u.session_recording)),this.set_config(c),this.config.on_xhr_error&&k.error("on_xhr_error is deprecated. Use on_request_error instead"),this.compression=n.disable_compression?void 0:xe.GZipJS;var d=this.En();if(this.persistence=new Er(this.config,d),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new Er(b({},this.config,{persistence:"sessionStorage"}),d,!1),this.bn="ph_"+(this.config.persistence_name||this.config.token)+"_session_registered_properties",this.config.persistence!=="memory"&&!d&&ce.N()){var h=ce.H(this.bn);O(h)&&h.forEach((F=>{q(F)&&this.yn.add(F)}))}else ce.q(this.bn);var p=b({},this.persistence.props),f=b({},this.sessionPersistence.props);this.register({$initialization_time:new Date().toISOString()}),this.In=new cf((F=>this.Pn(F)),this.config.request_queue_config),this.Rn=new df(this),this.__request_queue=[];var g=this.gn();if(g||(this.sessionManager=new Ol(this),this.sessionPropsManager=new Ll(this,this.sessionManager,this.persistence),this.sessionManager.onSessionId(((F,D,S)=>{(S!=null&&S.activityTimeout||S!=null&&S.sessionPastMaximumLength||S!=null&&S.crossTabAdoption)&&this.An()}))),this.Fn(),this.config.__preview_deferred_init_extensions?(k.info("Deferring extension initialization to improve startup performance"),setTimeout((()=>{this.Ln(g)}),0)):(k.info("Initializing extensions synchronously"),this.Ln(g)),Y.DEBUG=Y.DEBUG||this.config.debug,Y.DEBUG&&k.info("Starting in debug mode",{this:this,config:n,thisC:b({},this.config),p,s:f}),!this.config.identity_distinct_id||(s=n.bootstrap)!=null&&s.distinctID||(n.bootstrap=b({},n.bootstrap,{distinctID:this.config.identity_distinct_id,isIdentifiedID:!0})),((r=n.bootstrap)==null?void 0:r.distinctID)!==void 0){var m=n.bootstrap.distinctID,v=this.get_distinct_id(),E=this.persistence.get_property(He);if(n.bootstrap.isIdentifiedID&&v!=null&&v!==m&&E===sn)this.identify(m);else if(n.bootstrap.isIdentifiedID&&v!=null&&v!==m&&E===Ot)k.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{var w=this.config.get_device_id(ft()),I=n.bootstrap.isIdentifiedID?w:m;this.persistence.set_property(He,n.bootstrap.isIdentifiedID?Ot:sn),this.register({distinct_id:m,$device_id:I})}}if(g)this.register_once({distinct_id:Ci,$device_id:null},"");else if(!this.get_distinct_id()){var A=this.config.get_device_id(ft());this.register_once({distinct_id:A,$device_id:A},""),this.persistence.set_property(He,sn)}return re(_,"onpagehide"in self?"pagehide":"unload",this._handle_unload.bind(this),{passive:!1}),n.segment?(function(F,D){var S=F.config.segment;if(!S)return D();(function($,T){var M=$.config.segment;if(!M)return T();var N=z=>{var H=()=>z.anonymousId()||ft();$.config.get_device_id=H,z.id()&&($.register({distinct_id:z.id(),$device_id:H()}),$.persistence.set_property(He,Ot)),T()},P=M.user();"then"in P&&Se(P.then)?P.then(N):N(P)})(F,(()=>{S.register(($=>{typeof Promise<"u"&&Promise.resolve||wr.warn("This browser does not have Promise support, and can not use the segment integration");var T=(M,N)=>{if(!N)return M;M.event.userId||M.event.anonymousId===$.get_distinct_id()||(wr.info("No userId set, resetting PostHog"),$.reset()),M.event.userId&&M.event.userId!==$.get_distinct_id()&&(wr.info("UserId set, identifying with PostHog"),$.identify(M.event.userId));var P=$.calculateEventProperties(N,M.event.properties);return M.event.properties=Object.assign({},P,M.event.properties),M};return{name:"PostHog JS",type:"enrichment",version:"1.0.0",isLoaded:()=>!0,load:()=>Promise.resolve(),track:M=>T(M,M.event.event),page:M=>T(M,cn),identify:M=>T(M,vr),screen:M=>T(M,"$screen")}})(F)).then((()=>{D()}))}))})(this,(()=>this.On())):this.On(),Se(this.config._onCapture)&&this.config._onCapture!==Es&&(k.warn("onCapture is deprecated. Please use `before_send` instead"),this.on("eventCaptured",(F=>this.config._onCapture(F.event,F)))),this.config.ip&&k.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 fd.apply(this,arguments)})().then((F=>{F&&this.register({[gr]:F})})).catch(Es),this}Fn(){var e,n,i,s,r,o,a=(e=(n=this.config.__extensionClasses)==null?void 0:n.featureFlags)!==null&&e!==void 0?e:(i=Re.__defaultExtensionClasses)==null?void 0:i.featureFlags;a&&(this.featureFlags&&this.featureFlags instanceof a||((s=this.Dn)==null||s.call(this),this.Dn=void 0,this.featureFlags=new a(this)),Se(this.featureFlags.onReloading)&&Se(this.featureFlags.setup)?this.Dn||(this.Dn=this.featureFlags.onReloading((()=>{this.dn.emit("featureFlagsReloading",!0)})),this.$n().add(this.featureFlags)):(r=(o=this.featureFlags).initialize)==null||r.call(o))}Ln(e){var n,i,s,r,o,a,l,u=performance.now(),c=b({},Re.__defaultExtensionClasses,this.config.__extensionClasses),d=[];c.exceptions&&this.sn.push(this.exceptions=(n=this.exceptions)!==null&&n!==void 0?n:new c.exceptions(this)),c.historyAutocapture&&this.sn.push(this.historyAutocapture=new c.historyAutocapture(this)),c.tracingHeaders&&this.sn.push(this.tracingHeaders=new c.tracingHeaders(this)),c.siteApps&&this.sn.push(this.siteApps=new c.siteApps(this)),c.sessionRecording&&!e&&this.sn.push(this.sessionRecording=new c.sessionRecording(this)),this.config.disable_scroll_properties||d.push((()=>{this.scrollManager.startMeasuringScrollPosition()})),c.autocapture&&this.sn.push(this.autocapture=new c.autocapture(this)),c.surveys&&this.sn.push(this.surveys=(i=this.surveys)!==null&&i!==void 0?i:new c.surveys(this)),c.logs&&this.sn.push(this.logs=(s=this.logs)!==null&&s!==void 0?s:new c.logs(this)),c.metrics&&this.sn.push(this.metrics=(r=this.metrics)!==null&&r!==void 0?r:new c.metrics(this)),c.conversations&&this.sn.push(this.conversations=(o=this.conversations)!==null&&o!==void 0?o:new c.conversations(this)),c.productTours&&this.sn.push(this.productTours=new c.productTours(this)),c.heatmaps&&this.sn.push(this.heatmaps=new c.heatmaps(this)),c.webVitalsAutocapture&&this.sn.push(this.webVitalsAutocapture=new c.webVitalsAutocapture(this)),c.exceptionObserver&&this.sn.push(this.exceptionObserver=new c.exceptionObserver(this)),c.deadClicksAutocapture&&this.sn.push(this.deadClicksAutocapture=new c.deadClicksAutocapture(this,Wp)),c.toolbar&&this.sn.push(this.toolbar=(a=this.toolbar)!==null&&a!==void 0?a:new c.toolbar(this)),c.experiments&&this.sn.push(this.experiments=(l=this.experiments)!==null&&l!==void 0?l:new c.experiments(this)),this.sn.forEach((h=>{h.initialize&&d.push((()=>{h.initialize==null||h.initialize()}))})),d.push((()=>{if(this.Nn){var h=this.Nn;this.Nn=void 0,this.sn.forEach((p=>p.onRemoteConfig==null?void 0:p.onRemoteConfig(h)))}})),this.qn(d,u)}qn(e,n){for(;e.length>0;){if(this.config.__preview_deferred_init_extensions&&performance.now()-n>=30&&e.length>0)return void setTimeout((()=>{this.qn(e,n)}),0);var i=e.shift();if(i)try{i()}catch(r){k.error("Error initializing extension:",r)}}var s=Math.round(performance.now()-n);this.register_for_session({[Au]:this.config.__preview_deferred_init_extensions?"deferred":"synchronous",[Fu]:s}),this.config.__preview_deferred_init_extensions&&k.info("PostHog extensions initialized ("+s+"ms)")}Zi(e){var n;if(!C||!C.body)return k.info("document not ready yet, trying again in 500 milliseconds..."),void setTimeout((()=>{this.Zi(e)}),500);if(this.config.__preview_deferred_init_extensions&&(this.Nn=e),this.hn=e,this.compression=void 0,e.ok){var i,s=e.config;s.supportedCompression&&!this.config.disable_compression&&(this.compression=L(s.supportedCompression,xe.GZipJS)?xe.GZipJS:L(s.supportedCompression,xe.Base64)?xe.Base64:void 0),(i=s.analytics)!=null&&i.endpoint&&(this.analyticsDefaultEndpoint=s.analytics.endpoint)}this.set_config({person_profiles:this.xn?this.xn:fo}),(n=this.jn)==null||n.handleRemoteConfig(e),this.sn.forEach((r=>r.onRemoteConfig==null?void 0:r.onRemoteConfig(e)))}On(){try{this.config.loaded(this)}catch(i){k.critical("`loaded` function failed",i)}if(this.Bn(),this.config.internal_or_test_user_hostname&&se!=null&&se.hostname){var e=se.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.gn())&&this.Hn()}),1),this.Un=new td(this),this.Un.load()}Bn(){var e;this.is_capturing()&&this.config.request_batching&&((e=this.In)==null||e.enable())}_dom_loaded(){this.is_capturing()&&Ai(this.__request_queue,(e=>this.Pn(e))),this.__request_queue=[],this.Bn()}_handle_unload(){var e,n,i,s,r;(e=this.surveys)==null||e.handlePageUnload==null||e.handlePageUnload(),(n=this.metrics)==null||n.flush("sendBeacon"),this.config.request_batching?(this.zn()&&this.capture(mr),(i=this.logs)==null||i.flushLogs("sendBeacon"),(s=this.In)==null||s.unload(),(r=this.Rn)==null||r.unload()):this.zn()&&this.capture(mr,null,{transport:"sendBeacon"})}_send_request(e){this.__loaded?bd?this.__request_queue.push(e):this.rateLimiter.isServerRateLimited(e.batchKey)?e.fireCallbackOnDrop&&(e.callback==null||e.callback({statusCode:429})):(e.transport=e.transport||this.config.api_transport,e.headers=b({},this.config.request_headers,e.headers),e.compression=e.compression==="best-available"?this.compression:e.compression,(x(this.config.disable_beacon)?this.config.__preview_disable_beacon:this.config.disable_beacon)&&(e.disableTransport=["sendBeacon"]),e.fetchOptions=e.fetchOptions||this.config.fetch_options,(n=>{var i,s,r,o=b({},n);o.timeout=o.timeout||6e4;var a,l,u,c,d,h=(i=o.transport)!==null&&i!==void 0?i:"fetch";h==="sendBeacon"&&x(o.compression)&&o.data&&(o.compression=xe.Base64),o.method==="POST"&&o.data&&(o.timestampMode==="capture-body"?o.data={api_key:(l=(d=(c=O(a=o.data)?a:[a])[0])==null||(u=d.properties)==null?void 0:u.token)!==null&&l!==void 0?l:d?.token,batch:c,sent_at:new Date().toISOString()}:o.timestampMode==="body"&&(o.data=(function(m,v){return v===void 0&&(v=new Date().toISOString()),O(m)?m.map((E=>b({},E,{sent_at:v}))):b({},m,{sent_at:v})})(o.data))),o.url=Ml(o.url,o.method,o.compression,o.timestampMode);var p=Gi.filter((m=>!o.disableTransport||!m.transport||!o.disableTransport.includes(m.transport))),f=(s=(r=(function(m,v){for(var E=0;m.length>E;E++)if(m[E].transport===h)return m[E]})(p))==null?void 0:r.method)!==null&&s!==void 0?s:p[0].method;if(!f)throw new Error("No available transport method");var g=m=>{try{f(m)}catch(v){dd(v)?k.warn(v):k.error(v),o.callback==null||o.callback({statusCode:0,error:v})}};h!=="sendBeacon"&&o.data&&o.compression===xe.GZipJS&&Ih&&typeof Promise<"u"&&!Vi?af(o).then((m=>{g(m)})).catch((m=>{if(tl(m))return Vi=!0,void g(b({},o,{compression:void 0,url:Ml(n.url,n.method,void 0,n.timestampMode)}));(v=>{if(!v||typeof v!="object")return!1;var E="name"in v?String(v.name):"";return tl(v)||E===Uc})(m)&&(Vi=!0),g(o)})):f(o)})(b({},e,{callback:n=>{var i,s;this.rateLimiter.checkForLimiting(n),400>n.statusCode||(i=(s=this.config).on_request_error)==null||i.call(s,n),e.callback==null||e.callback(n)}}))):e.fireCallbackOnDrop&&(e.callback==null||e.callback({statusCode:0}))}Pn(e){this.Rn?this.Rn.retriableRequest(e):this._send_request(e)}_execute_array(e){Fr++;try{var n,i=[],s=[],r=[];Ai(e,(a=>{if(a)if(O(n=a[0]))r.push(a);else if(Se(a))try{a.call(this)}catch(l){k.error("Error executing queued PostHog call",a,l)}else O(a)&&n==="alias"?i.push(a):O(a)&&n.indexOf("capture")!==-1&&Se(this[n])?r.push(a):s.push(a)}));var o=function(a,l){Ai(a,(function(u){try{if(O(u[0])){var c=l;Z(u,(function(d){c=c[d[0]].apply(c,d.slice(1))}))}else l[u[0]].apply(l,u.slice(1))}catch(d){k.error("Error executing queued PostHog call",u,d)}}))};o(i,this),o(s,this),o(r,this)}finally{Fr--}}push(e){if(Fr>0&&O(e)&&q(e[0])){var n=Re.prototype[e[0]];Se(n)&&n.apply(this,e.slice(1))}else this._execute_array([e])}capture(e,n,i){var s,r,o,a,l;if(this.__loaded&&this.persistence&&this.sessionPersistence&&this.In){if(this.is_capturing())if(!x(e)&&q(e)){var u=!this.config.opt_out_useragent_filter&&this._is_bot();if(!u||this.config.__preview_capture_bot_pageviews){var c=i!=null&&i.skip_client_rate_limiting?void 0:this.rateLimiter.clientRateLimitContext();if(c==null||!c.isRateLimited){n!=null&&n.$current_url&&!q(n?.$current_url)&&(k.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"||i!=null&&i.Wn||k.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&&this.sessionPersistence.update_campaign_params(),this.config.save_referrer&&this.sessionPersistence.update_referrer_info(),(this.config.save_campaign_params||this.config.save_referrer)&&this.persistence.set_initial_person_info();var d=new Date,h=i?.timestamp||d,p=ol(i?.uuid,ft),f={uuid:p,event:e,properties:this.calculateEventProperties(e,n||{},h,p)};e===cn&&this.config.__preview_capture_bot_pageviews&&u&&(f.event="$bot_pageview",f.properties.$browser_type="bot"),c&&(f.properties.$lib_rate_limit_remaining_tokens=c.remainingTokens);var g=e==="$feature_flag_called"&&f.properties.$feature_flag_has_experiment===!1&&this.get_property(cs)===!0;i?.$set&&!g&&(f.$set=i?.$set);var m=i?.$unset;m&&(f.$unset=m);var v,E,w,I=g?void 0:this.Vn(i?.$set_once,e!==hl,e===vr);if(I&&(f.$set_once=I),i!=null&&i._noTruncate||(r=this.config.properties_string_max_length,o=f,a=N=>q(N)?N.slice(0,r):N,l=new Set,f=(function N(P,z){if(P!==Object(P))return a?a(P):P;if(!l.has(P)){var H;if(l.add(P),O(P))H=[],Ai(P,(Q=>{H.push(N(Q))}));else{var U={};Z(P,((Q,fe)=>{l.has(Q)||(U[fe]=N(Q))})),H=U}return H}})(o)),f.timestamp=h,x(i?.timestamp)||(f.properties.$event_time_override_provided=!0,f.properties.$event_time_override_system_time=d),g&&(f.properties=(function(N,P){P===void 0&&(P=[]);var z={},H=U=>{N[U]!==void 0&&(z[U]=N[U])};return Ch.forEach(H),P.forEach(H),z})(f.properties,xf)),e===vt.DISMISSED||e===vt.SENT){var A=n?.[xr.SURVEY_ID],F=n?.[xr.SURVEY_ITERATION];yd({id:A,current_iteration:F}),f.$set=b({},f.$set,{[(v={id:A,current_iteration:F},E=e===vt.SENT?"responded":"dismissed",w="$survey_"+E+"/"+v.id,v.current_iteration&&v.current_iteration>0&&(w="$survey_"+E+"/"+v.id+"/"+v.current_iteration),w)]:!0})}else e===vt.SHOWN&&(f.$set=b({},f.$set,{[xr.SURVEY_LAST_SEEN_DATE]:new Date().toISOString()}));if(e===Xp.SHOWN){var D=n?.[Fl.TOUR_TYPE];D&&(f.$set=b({},f.$set,{[Fl.TOUR_LAST_SEEN_DATE+"/"+D]:new Date().toISOString()}))}var S=b({},f.properties.$set,f.$set);if(yt(S)||this.setPersonPropertiesForFlags(S),!B(this.config.before_send)){var $=this.Pt(f);if(!$)return;(f=$).uuid=ol(f.uuid,ft)}this.dn.emit("eventCaptured",f);var T=(s=i?._url)!==null&&s!==void 0?s:this.requestRouter.endpointFor("api",this.analyticsDefaultEndpoint),M={method:"POST",url:T,data:f,compression:"best-available",timestampMode:i?._batchKey==="recordings"||/\/s\/(?:\?|$)/.test(T)?"body":"capture-body",batchKey:i?._batchKey,transport:i?.transport};return!this.config.request_batching||i&&(i==null||!i._batchKey)||i!=null&&i.send_instantly?this.Pn(M):this.In.enqueue(M),f}k.critical("This capture call is ignored due to client rate limiting.")}}else k.error("No event name provided to posthog.capture")}else k.uninitializedWarning("posthog.capture")}_addCaptureHook(e){return this.on("eventCaptured",(n=>e(n.event,n)))}$n(){var e;return(e=this.jn)!==null&&e!==void 0?e:this.jn=new Sf(this)}cn(e){this._n.push(e);var n=!0;return()=>{if(n){n=!1;var i=this._n.indexOf(e);i!==-1&&this._n.splice(i,1)}}}calculateEventProperties(e,n,i,s,r){if(i=i||new Date,!this.persistence||!this.sessionPersistence)return n;var o=r?void 0:this.persistence.remove_event_timer(e),a=b({},n);if(a.token=this.config.token,a.$config_defaults=this.config.defaults,this.gn()&&(a[Cu]=!0),e==="$snapshot"){var l=b({},this.persistence.properties(),this.sessionPersistence.properties());return a.distinct_id=l.distinct_id,(!q(a.distinct_id)&&!he(a.distinct_id)||Gr(a.distinct_id))&&k.error("Invalid distinct_id for replay event. This indicates a bug in your implementation"),a}var u,c=(function(A,F,D,S){var $,T,M,N;if(S===void 0&&(S=!1),!Fe)return{};var P,z=A?[...bn,...F||[]]:[],H=(function(Si){for(var je=0;sl.length>je;je++){var xi=sl[je],tn=xi[1],nn=xi[0].exec(Si),$n=nn&&(Se(tn)?tn(nn,Si):tn);if($n)return $n}return["",""]})(Fe),U=H[0],Q=H[1],fe=(P=typeof navigator<"u"?navigator:void 0)!=null&&P.brave?{brave:!0}:{},Ie={};x(D)||(Ie.detectGoogleSearchApp=D);var _e={},Ce=($=navigator)==null||($=$.userAgentData)==null?void 0:$.platform,Te=(T=navigator)==null?void 0:T.maxTouchPoints,ae=_==null||(M=_.screen)==null?void 0:M.width,me=_==null||(N=_.screen)==null?void 0:N.height,ge=_?.devicePixelRatio;x(Ce)||(_e.userAgentDataPlatform=Ce),x(Te)||(_e.maxTouchPoints=Te),x(ae)||(_e.screenWidth=ae),x(me)||(_e.screenHeight=me),x(ge)||(_e.devicePixelRatio=ge);var Qe,Lt,de,Ge,It,Pn,De,Ae,Ei=te(ra({$os:U,$os_version:Q,$browser:hu(Fe,navigator.vendor,fe,Ie),$device:rl(Fe),$device_type:(Lt=Fe,de=_e,Ae=rl(Lt),Ae===Kc||Ae===Gc||Ae==="Kobo"||Ae==="Kindle Fire"||Ae===au?vn:Ae===ri||Ae===gn||Ae===oi||Ae===Jr?"Console":Ae===Yc?"Wearable":Ae?Oe:de?.userAgentDataPlatform==="Android"&&((Ge=de?.maxTouchPoints)!==null&&Ge!==void 0?Ge:0)>0?600>Math.min((It=de?.screenWidth)!==null&&It!==void 0?It:0,(Pn=de?.screenHeight)!==null&&Pn!==void 0?Pn:0)/((De=de?.devicePixelRatio)!==null&&De!==void 0?De:1)?Oe:vn:"Desktop"),$timezone:ed(),$timezone_offset:Jp()}),{$current_url:ci(S?Pt(se?.href):se?.href,z,ui),$host:se?.host,$pathname:se?.pathname,$raw_user_agent:Fe.length>1e3?Fe.substring(0,997)+"...":Fe,$browser_version:Vh(Fe,navigator.vendor,fe,Ie),$browser_language:Al(),$browser_language_prefix:(Qe=Al(),typeof Qe=="string"?Qe.split("-")[0]:void 0),$screen_height:_?.screen.height,$screen_width:_?.screen.width,$viewport_height:_?.innerHeight,$viewport_width:_?.innerWidth,$lib:Y.LIB_NAME,$lib_version:Y.LIB_VERSION,$insert_id:Math.random().toString(36).substring(2,10)+Math.random().toString(36).substring(2,10),$time:Date.now()/1e3});return Y.SDK_DIST_CHANNEL&&(Ei.$sdk_dist_channel=Y.SDK_DIST_CHANNEL),Ei})(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){var d=this.sessionManager.checkAndGetSessionAndWindowId(r,i.getTime()),h=d.windowId;a.$session_id=d.sessionId,a.$window_id=h}this.sessionPropsManager&&te(a,this.sessionPropsManager.getSessionProps());try{var p;this.sessionRecording&&te(a,this.sessionRecording.sdkDebugProperties),a.$sdk_debug_retry_queue_size=(p=this.Rn)==null?void 0:p.length}catch(A){a.$sdk_debug_error_capturing_properties=String(A)}if(this.requestRouter.region===xo&&(a.$lib_custom_api_host=this.config.api_host),u=e!==cn||r?e!==mr||r?this.pageViewManager.doEvent():this.pageViewManager.doPageLeave(i):this.pageViewManager.doPageView(i,s),a=te(a,u),e===cn&&C&&(a.title=C.title),!x(o)){var f=i.getTime()-o;a.$duration=parseFloat((f/1e3).toFixed(3))}Fe&&this.config.opt_out_useragent_filter&&(a.$browser_type=this._is_bot()?"bot":"browser");var g=this.persistence.properties(),m=this.sessionPersistence.properties();Z(["$referrer","$referring_domain"],(A=>{A in g&&delete m[A]}));var v={};if(this._n.length>0)for(var E of this._n.slice())try{te(v,E())}catch(A){k.error("Failed to produce browser extension event properties",A)}(a=te({},c,g,m,b({},v,a))).$is_identified=this._isIdentified(),O(this.config.property_denylist)?Z(this.config.property_denylist,(function(A){delete a[A]})):k.error(wd+this.config.property_denylist+" or property_blacklist config: "+this.config.property_blacklist);var w=this.config.sanitize_properties;w&&(k.error(Ul),a=w(a,e));var I=this.Zn();return a.$process_person_profile=I,I&&!r&&this.Gn("_calculate_event_properties"),a}Vn(e,n,i){var s;if(n===void 0&&(n=!0),i===void 0&&(i=!1),!this.persistence||!this.Zn()||this.mn&&!i)return e;var r=this.persistence.get_initial_props(),o=(s=this.sessionPropsManager)==null?void 0:s.getSetOnceProps(),a=te({},r,o||{},e||{}),l=this.config.sanitize_properties;return l&&(k.error(Ul),a=l(a,"$set_once")),n&&(this.mn=!0),yt(a)?void 0:a}register(e,n){var i;(i=this.persistence)==null||i.register(e,n)}register_once(e,n,i){var s;(s=this.persistence)==null||s.register_once(e,n,i)}register_for_session(e){var n;(n=this.sessionPersistence)==null||n.register(e),Object.keys(e).forEach((i=>this.yn.add(i))),this.Qn()}unregister(e){var n;(n=this.persistence)==null||n.unregister(e)}unregister_for_session(e){var n;(n=this.sessionPersistence)==null||n.unregister(e),this.yn.delete(e),this.Qn()}Kn(e,n){this.register({[e]:n})}An(){this.yn.forEach((e=>{var n;(n=this.sessionPersistence)==null||n.unregister(e)})),this.yn.clear(),this.Qn()}Qn(){var e;if(this.bn)if(this.config.persistence==="memory"||(e=this.sessionPersistence)!=null&&e.xi||!ce.N())ce.q(this.bn);else{var n=[];this.yn.forEach((i=>n.push(i))),n.length>0?ce.F(this.bn,n):ce.q(this.bn)}}getFeatureFlag(e,n){var i;return(i=this.featureFlags)==null?void 0:i.getFeatureFlag(e,n)}getFeatureFlagPayload(e){var n;return(n=this.featureFlags)==null?void 0:n.getFeatureFlagPayload(e)}getFeatureFlagResult(e,n){var i;return(i=this.featureFlags)==null?void 0:i.getFeatureFlagResult(e,n)}getAllFeatureFlags(){var e,n;return(e=(n=this.featureFlags)==null?void 0:n.getAllFeatureFlags())!==null&&e!==void 0?e:[]}isFeatureEnabled(e,n){var i,s;return(i=(s=this.featureFlags)==null?void 0:s.isFeatureEnabled(e,n))!==null&&i!==void 0?i:n?.defaultValue}reloadFeatureFlags(){var e;(e=this.featureFlags)==null||e.reloadFeatureFlags()}updateFlags(e,n,i){var s;(s=this.featureFlags)==null||s.updateFlags(e,n,i)}updateEarlyAccessFeatureEnrollment(e,n,i){var s;(s=this.featureFlags)==null||s.updateEarlyAccessFeatureEnrollment(e,n,i)}getEarlyAccessFeatures(e,n,i){var s;return n===void 0&&(n=!1),(s=this.featureFlags)==null?void 0:s.getEarlyAccessFeatures(e,n,i)}on(e,n){return this.dn.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:Dn}),()=>{})}onSessionId(e){var n,i;return(n=(i=this.sessionManager)==null?void 0:i.onSessionId(e))!==null&&n!==void 0?n:()=>{}}getSurveys(e,n){n===void 0&&(n=!1),this.surveys?this.surveys.getSurveys(e,n):e([],{isLoaded:!1,error:Dn})}getActiveMatchingSurveys(e,n){n===void 0&&(n=!1),this.surveys?this.surveys.getActiveMatchingSurveys(e,n):e([],{isLoaded:!1,error:Dn})}renderSurvey(e,n){var i;(i=this.surveys)==null||i.renderSurvey(e,n)}displaySurvey(e,n){var i;n===void 0&&(n=vf),(i=this.surveys)==null||i.displaySurvey(e,n)}cancelPendingSurvey(e){var n;(n=this.surveys)==null||n.cancelPendingSurvey(e)}canRenderSurvey(e){var n,i;return(n=(i=this.surveys)==null?void 0:i.canRenderSurvey(e))!==null&&n!==void 0?n:{visible:!1,disabledReason:Dn}}canRenderSurveyAsync(e,n){var i,s;return n===void 0&&(n=!1),(i=(s=this.surveys)==null?void 0:s.canRenderSurveyAsync(e,n))!==null&&i!==void 0?i:Promise.resolve({visible:!1,disabledReason:Dn})}Jn(e){return!e||Gr(e)?(k.critical("Unique user id has not been set in posthog.identify"),!1):e===Ci?(k.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())||(k.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,i){if(!this.__loaded||!this.persistence)return k.uninitializedWarning("posthog.identify");if(he(e)&&(e=e.toString(),k.warn("The first argument to posthog.identify was a number, but it should be a string. It has been converted to a string.")),this.Jn(e)&&this.Gn("posthog.identify")){var s=this.get_distinct_id();this.register({$user_id:e}),this.get_property(ai)||this.register_once({$had_persisted_distinct_id:!0,$device_id:s},""),e!==s&&e!==this.get_property(zn)&&(this.unregister(zn),this.register({distinct_id:e}));var r,o=(this.persistence.get_property(He)||sn)===sn,a=e!==s,l=!a&&o;if(a&&o)this.persistence.set_property(He,Ot),this.setPersonPropertiesForFlags({$set:n||{},$set_once:i||{}},!1),this.capture(vr,{distinct_id:e,$anon_distinct_id:s},{$set:n||{},$set_once:i||{}}),this.Sn=Ar(e,n,i),(r=this.featureFlags)==null||r.setAnonymousDistinctId(s);else if(l){this.persistence.set_property(He,Ot);var u=n||{},c=i||{};this.setPersonPropertiesForFlags({$set:u,$set_once:c},!1),this.capture("$set",{$set:u,$set_once:c}),this.Sn=Ar(e,n,i)}else(n||i)&&this.setPersonProperties(n,i);a?(this.reloadFeatureFlags(),this.featureFlags?this.featureFlags.resetFlagCallReported():this.unregister(Gt)):l&&(n||i)&&this.reloadFeatureFlags()}}setPersonProperties(e,n){if((e||n)&&this.Gn("posthog.setPersonProperties")){var i=Ar(this.get_distinct_id(),e,n);this.Sn!==i?(this.setPersonPropertiesForFlags({$set:e||{},$set_once:n||{}},!0),this.capture("$set",{$set:e||{},$set_once:n||{}}),this.Sn=i):k.info("A duplicate setPersonProperties call was made with the same properties. It has been ignored.")}}unsetPersonProperties(e){var n,i=(O(e)?e:[e]).filter((s=>q(s)&&s.length>0));i.length!==0&&this.Gn("posthog.unsetPersonProperties")&&((n=this.featureFlags)==null||n.unsetPersonPropertiesForFlags(i,!0),this.capture("$set",{$unset:i}),this.Sn=null)}group(e,n,i){if(e&&n){var s=this.getGroups(),r=s[e]!==n;if(r&&this.resetGroupPropertiesForFlags(e),this.register({$groups:b({},s,{[e]:n})}),r||i){var o={$group_type:e,$group_key:n};i&&(o.$group_set=i),this.capture(hl,o)}i&&this.setGroupPropertiesForFlags({[e]:i}),r&&!i&&this.reloadFeatureFlags()}else k.error("posthog.group requires a group type and group key")}resetGroups(){this.register({$groups:{}}),this.resetGroupPropertiesForFlags(),this.reloadFeatureFlags()}setPersonPropertiesForFlags(e,n){var i;n===void 0&&(n=!0),(i=this.featureFlags)==null||i.setPersonPropertiesForFlags(e,n)}resetPersonPropertiesForFlags(e){var n;e===void 0&&(e=!0),(n=this.featureFlags)==null||n.resetPersonPropertiesForFlags(e)}setGroupPropertiesForFlags(e,n){var i;n===void 0&&(n=!0),this.Gn("posthog.setGroupPropertiesForFlags")&&((i=this.featureFlags)==null||i.setGroupPropertiesForFlags(e,n))}resetGroupPropertiesForFlags(e){var n;(n=this.featureFlags)==null||n.resetGroupPropertiesForFlags(e)}reset(e){this.Yn(e)}Yn(e,n){var i,s,r,o,a,l,u,c,d,h;if(n===void 0&&(n=!1),k.info("reset"),!this.__loaded)return k.uninitializedWarning("posthog.reset");var p,f=this.get_property(ai),g=this.get_property(gr),m=this.get_property(Jt),v=this.is_capturing();if(this.consent.reset(),n||!v||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."),(i=this.persistence)==null||i.clear(),(s=this.sessionPersistence)==null||s.clear(),this.yn.clear(),this.Qn(),x(m)||(p=this.persistence)==null||p.register({[Jt]:m}),(r=this.surveys)==null||r.reset(),(o=this.Un)==null||o.stop(),(a=this.featureFlags)==null||a.reset(),(l=this.conversations)==null||l.reset(),(u=this.logs)==null||u.reset(),(c=this.metrics)==null||c.reset(),(d=this.persistence)==null||d.set_property(He,sn),(h=this.sessionManager)==null||h.resetSessionId(),this.Sn=null,this.config.cookieless_mode===gt)this.register_once({distinct_id:Ci,$device_id:null},"");else{var E=this.config.get_device_id(ft());this.register_once({distinct_id:E,$device_id:e?E:f},""),e||x(g)||this.register({[gr]:g})}this.register({$last_posthog_reset:new Date().toISOString()},1),delete this.config.identity_distinct_id,delete this.config.identity_hash,this.reloadFeatureFlags()}shutdown(e){var n=this;return X((function*(){var i,s,r,o,a,l,u;if(n.__loaded){(i=n.Un)==null||i.stop(),(s=n.jn)==null||s.dispose(),(r=n.sessionRecording)==null||r.dispose(),(o=n.logs)==null||o.flushLogs("sendBeacon"),(a=n.metrics)==null||a.flush("sendBeacon"),(l=n.In)==null||l.unload(),(u=n.Rn)==null||u.unload();try{var c;(c=n.featureFlags)==null||c.destroy()}catch(d){k.error("Error while destroying feature flags",d)}}else k.uninitializedWarning("posthog.shutdown")}))()}setIdentity(e,n){var i;this.config.identity_distinct_id=e,this.config.identity_hash=n,this.alias(e),(i=this.conversations)==null||i.Xn()}clearIdentity(){var e;delete this.config.identity_distinct_id,delete this.config.identity_hash,(e=this.conversations)==null||e.ts()}get_distinct_id(){return this.get_property("distinct_id")}getGroups(){return this.get_property("$groups")||{}}get_session_id(){var e,n;return(e=(n=this.sessionManager)==null?void 0:n.checkAndGetSessionAndWindowId(!0).sessionId)!==null&&e!==void 0?e:""}get_session_replay_url(e){if(!this.sessionManager)return"";var n=this.sessionManager.checkAndGetSessionAndWindowId(!0),i=n.sessionStartTimestamp,s=this.requestRouter.endpointFor("ui","/project/"+this.config.token+"/replay/"+n.sessionId);if(e!=null&&e.withTimestamp&&i){var r,o=(r=e.timestampLookBack)!==null&&r!==void 0?r:10;if(!i)return s;s+="?t="+Math.max(Math.floor((new Date().getTime()-i)/1e3)-o,0)}return s}alias(e,n){return e===this.get_property(bu)?(k.critical("Attempting to create alias for existing People user - aborting."),-2):this.Gn("posthog.alias")?(x(n)&&(n=this.get_distinct_id()),e!==n?(this.Kn(zn,e),this.capture("$create_alias",{alias:e,distinct_id:n})):(k.warn("alias matches current distinct_id - skipping api call."),this.identify(e),-1)):void 0}set_config(e){var n=b({},this.config);if(ne(e)){var i,s,r,o,a,l,u,c,d,h,p,f;te(this.config,Hl(e));var g=this.En();(i=this.persistence)==null||i.update_config(this.config,n,g),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new Er(b({},this.config,{persistence:"sessionStorage"}),g,!1);var m=this.Cn(this.config.debug);Ye(m)&&(this.config.debug=m),Ye(this.config.debug)&&(this.config.debug?(Y.DEBUG=!0,ee.N()&&ee.F("ph_debug",!0),k.info("set_config",{config:e,oldConfig:n,newConfig:b({},this.config)})):(Y.DEBUG=!1,ee.N()&&ee.q("ph_debug"))),(s=this.featureFlags)==null||s.updateConfig==null||s.updateConfig(this.config,this.Qi()),(r=this.exceptionObserver)==null||r.onConfigChange(),(o=this.exceptions)==null||o.onConfigChange(),(a=this.sessionRecording)==null||a.startIfEnabledOrStop(),(l=this.tracingHeaders)==null||l.startIfEnabledOrStop(),(u=this.autocapture)==null||u.startIfEnabled(),(c=this.heatmaps)==null||c.startIfEnabled(),(d=this.exceptionObserver)==null||d.startIfEnabledOrStop(),(h=this.deadClicksAutocapture)==null||h.startIfEnabledOrStop(),(p=this.surveys)==null||p.loadIfEnabled(),this.es(),(f=this.externalIntegrations)==null||f.startIfEnabledOrStop()}}_overrideSDKInfo(e,n){Y.LIB_NAME=e,Y.LIB_VERSION=n}startSessionRecording(e){var n,i,s,r,o,a=e===!0,l={sampling:a||!(e==null||!e.sampling),linked_flag:a||!(e==null||!e.linked_flag),url_trigger:a||!(e==null||!e.url_trigger),event_trigger:a||!(e==null||!e.event_trigger)};Object.values(l).some(Boolean)&&((n=this.sessionManager)==null||n.checkAndGetSessionAndWindowId(),l.sampling&&((i=this.sessionRecording)==null||i.overrideSampling()),l.linked_flag&&((s=this.sessionRecording)==null||s.overrideLinkedFlag()),l.url_trigger&&((r=this.sessionRecording)==null||r.overrideTrigger("url")),l.event_trigger&&((o=this.sessionRecording)==null||o.overrideTrigger("event"))),this.set_config({disable_session_recording:!1})}stopSessionRecording(){this.set_config({disable_session_recording:!0})}sessionRecordingStarted(){var e;return!((e=this.sessionRecording)==null||!e.started)}captureException(e,n){if(this.exceptions){var i=new Error("PostHog syntheticException"),s=this.exceptions.buildProperties(e,{handled:!0,syntheticException:i});return this.exceptions.sendExceptionEvent(b({},s,n))}}addExceptionStep(e,n){var i;(i=this.exceptions)==null||i.addExceptionStep(e,n)}captureLog(e){var n;(n=this.logs)==null||n.captureLog(e)}get logger(){var e,n;return(e=(n=this.logs)==null?void 0:n.logger)!==null&&e!==void 0?e:Re.rs}startExceptionAutocapture(e){this.set_config({capture_exceptions:e==null||e})}stopExceptionAutocapture(){this.set_config({capture_exceptions:!1})}loadToolbar(e){var n,i;return(n=(i=this.toolbar)==null?void 0:i.loadToolbar(e))!==null&&n!==void 0&&n}get_property(e){var n;return(n=this.persistence)==null?void 0:n.props[e]}getSessionProperty(e){var n;return(n=this.sessionPersistence)==null?void 0:n.props[e]}toString(){var e,n=(e=this.config.name)!==null&&e!==void 0?e:un;return n!==un&&(n=un+"."+n),n}_isIdentified(){var e,n;return((e=this.persistence)==null?void 0:e.get_property(He))===Ot||((n=this.sessionPersistence)==null?void 0:n.get_property(He))===Ot}Zn(){var e,n;return!(this.config.person_profiles==="never"||this.config.person_profiles===fo&&!this._isIdentified()&&yt(this.getGroups())&&((e=this.persistence)==null||(e=e.props)==null||!e[zn])&&((n=this.persistence)==null||(n=n.props)==null||!n[hs]))}zn(){return this.config.capture_pageleave===!0||this.config.capture_pageleave==="if_capture_pageview"&&(this.config.capture_pageview===!0||this.config.capture_pageview==="history_change")}createPersonProfile(){this.Zn()||this.Gn("posthog.createPersonProfile")&&this.setPersonProperties({},{})}setInternalOrTestUser(){this.Gn("posthog.setInternalOrTestUser")&&this.setPersonProperties({$internal_or_test_user:!0})}Gn(e){return this.config.person_profiles==="never"?(k.error(e+' was called, but process_person is set to "never". This call will be ignored.'),!1):(this.Kn(hs,!0),!0)}En(){if(this.config.cookieless_mode==="always")return!0;var e=this.consent.isOptedOut();return this.config.disable_persistence||e&&!(!this.config.opt_out_persistence_by_default&&this.config.cookieless_mode!==Vt)}es(){var e,n,i,s,r=this.En();return((e=this.persistence)==null?void 0:e.xi)!==r&&((i=this.persistence)==null||i.set_disabled(r)),((n=this.sessionPersistence)==null?void 0:n.xi)!==r&&((s=this.sessionPersistence)==null||s.set_disabled(r)),r&&(this.yn.clear(),this.Qn()),r}opt_in_capturing(e){var n;if(this.config.cookieless_mode!==gt){if(this.gn()){var i,s,r,o,a;this.Yn(!0,!0),(i=this.sessionManager)==null||i.destroy(),(s=this.pageViewManager)==null||s.destroy(),this.sessionManager=new Ol(this),this.pageViewManager=new Cl(this),this.persistence&&(this.sessionPropsManager=new Ll(this,this.sessionManager,this.persistence));var l,u=(r=(o=this.config.__extensionClasses)==null?void 0:o.sessionRecording)!==null&&r!==void 0?r:(a=Re.__defaultExtensionClasses)==null?void 0:a.sessionRecording;u&&(this.sessionRecording=this.pn(this.sessionRecording,new u(this)),this.hn&&((l=this.sessionRecording)==null||l.onRemoteConfig==null||l.onRemoteConfig(this.hn)))}var c,d;this.consent.optInOut(!0),this.es(),this.Bn(),(n=this.sessionRecording)==null||n.startIfEnabledOrStop(),this.config.cookieless_mode==Vt&&((c=this.surveys)==null||c.loadIfEnabled()),(x(e?.captureEventName)||e!=null&&e.captureEventName)&&this.capture((d=e?.captureEventName)!==null&&d!==void 0?d:"$opt_in",e?.captureProperties,{send_instantly:!0}),this.config.capture_pageview&&this.Hn()}else k.warn(jl)}opt_out_capturing(){var e,n,i;this.config.cookieless_mode!==gt?(this.config.cookieless_mode===Vt&&this.consent.isOptedIn()&&this.Yn(!0,!0),this.consent.optInOut(!1),this.es(),this.config.cookieless_mode===Vt&&(this.register({distinct_id:Ci,$device_id:null}),(e=this.sessionRecording)==null||e.stopRecording(),this.sessionRecording=void 0,(n=this.sessionManager)==null||n.destroy(),(i=this.pageViewManager)==null||i.destroy(),this.sessionManager=void 0,this.sessionPropsManager=void 0,this.config.capture_pageview&&this.Hn(),this.Bn())):k.warn(jl)}has_opted_in_capturing(){return this.consent.isOptedIn()}has_opted_out_capturing(){return this.consent.isOptedOut()}get_explicit_consent_status(){var e=this.consent.consent;return e===1?"granted":e===0?"denied":"pending"}is_capturing(){return this.config.cookieless_mode===gt||(this.config.cookieless_mode===Vt?this.consent.isRejected()||this.consent.isOptedIn():!this.has_opted_out_capturing())}clear_opt_in_out_capturing(){this.consent.reset(),this.es()}_is_bot(){return ke?pd(ke,this.config.custom_blocked_useragents):void 0}Hn(){C&&(C.visibilityState==="visible"?this.wn||(this.wn=!0,this.capture(cn,{title:C.title},{send_instantly:!0}),this.kn&&(C.removeEventListener(ps,this.kn),this.kn=null)):this.kn||(this.kn=this.Hn.bind(this),re(C,ps,this.kn)))}debug(e){e===!1?(_?.console.log("You've disabled debug mode."),this.set_config({debug:!1})):(_?.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}))}Qi(){var e=this.Mn||{};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?(k.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,i,s,r,o){var a=i in n&&!B(n[i]),l=s in n&&!B(n[s]);return a?n[i]:!!l&&(o&&o.warn("Config field '"+s+"' is deprecated. Please use '"+i+"' instead. The old field will be removed in a future major version."),n[s])})(e,"advanced_disable_flags","advanced_disable_decide",0,k)}Pt(e){var n;if(B(this.config.before_send))return e;var i=Object.keys((n=e.properties)!==null&&n!==void 0?n:{}).filter(Nh),s=O(this.config.before_send)?this.config.before_send:[this.config.before_send],r=e;for(var o of s){if(r=o(r),B(r)){var a="Event '"+e.event+"' was rejected in beforeSend function";return Rh(e.event)?k.warn(a+". This can cause unexpected behavior."):k.info(a),null}r.properties&&!yt(r.properties)||k.warn("Event '"+e.event+"' has no properties after beforeSend function, this is likely an error.")}for(var l of i)if(r.properties&&B(r.properties[l]))return k.warn("Event '"+e.event+"' had its '"+l+"' property removed in a beforeSend function. This property is required for ingestion, so the event will be dropped."),null;return r}getPageViewId(){var e;return(e=this.pageViewManager.ui)==null?void 0:e.pageViewId}captureTraceFeedback(e,n){this.capture("$ai_feedback",{$ai_trace_id:String(e),$ai_feedback_text:n})}captureTraceMetric(e,n,i){this.capture("$ai_metric",{$ai_trace_id:String(e),$ai_metric_name:n,$ai_metric_value:String(i)})}Cn(e){var n=Ye(e)&&!e,i=ee.N()&&ee.P("ph_debug")==="true";return!n&&(!!i||e)}}Re.__defaultExtensionClasses={},Re.rs=(()=>{var t=()=>{};return{trace:t,debug:t,info:t,warn:t,error:t,fatal:t}})(),(function(t,e){for(var n=0;e.length>n;n++)t.prototype[e[n]]=Ep(t.prototype[e[n]])})(Re,["identify"]);class Wl{constructor(e){this.disabled=e===!1;var n=ne(e)?e:{};this.thresholdPx=n.threshold_px||30,this.timeoutMs=n.timeout_ms||1e3,this.clickCount=n.click_count||3,this.clicks=[]}isRageClick(e,n,i){if(this.disabled)return!1;var s=this.clicks[this.clicks.length-1];if(s&&Math.abs(e-s.x)+Math.abs(n-s.y)i-s.timestamp){if(this.clicks.push({x:e,y:n,timestamp:i}),this.clicks.length===this.clickCount)return!0}else this.clicks=[{x:e,y:n,timestamp:i}];return!1}}var $r="$copy_autocapture",Tr=ie("[AutoCapture]");function Rr(t,e){return e.length>t?e.slice(0,t)+"...":e}function Cf(t){if(t.previousElementSibling)return t.previousElementSibling;var e=t;do e=e.previousSibling;while(e&&!$t(e));return e}function Af(t,e){var n,i,s=e.e,r=e.maskAllElementAttributes,o=e.maskAllText,a=e.elementAttributeIgnoreList,l=e.elementsChainAsString,u=e.disableCaptureUrlHashes;if(!$t(t))return{props:{}};for(var c=[t],d=new Set([t]),h=t;h.parentNode&&!Me(h,"body")&&Ou>c.length;)if(Lu(h.parentNode)){var p=h.parentNode.host;if(d.has(p))break;d.add(p),c.push(p),h=p}else{if(!$t(h.parentNode)||d.has(h.parentNode))break;d.add(h.parentNode),c.push(h.parentNode),h=h.parentNode}var f,g,m=[],v={},E=!1,w=!1;if(Z(c,(S=>{var $=vo(S);if(Me(S,"a")){var T=S.getAttribute("href");E=!!($&&T&&Qn(T))&&(u?Pt(T):T)}L(ms(S),"ph-no-capture")&&(w=!0),m.push((function(N,P,z,H,U){U===void 0&&(U=!1);var Q=N.tagName.toLowerCase(),fe={tag_name:Q};aa.indexOf(Q)>-1&&!z&&(fe.$el_text=Q.toLowerCase()==="a"||Q.toLowerCase()==="button"?Rr(1024,xl(N)):Rr(1024,li(N)));var Ie=ms(N);Ie.length>0&&(fe.classes=Ie.filter((function(ae){return ae!==""}))),Z(N.attributes,(function(ae){var me;if((!Hu(N)||["name","id","class","aria-label"].indexOf(ae.name)!==-1)&&(H==null||!H.includes(ae.name))&&!P&&Qn(ae.value)&&(!q(me=ae.name)||me.substring(0,10)!=="_ngcontent"&&me.substring(0,7)!=="_nghost")){var ge=ae.value;ae.name==="class"&&(ge=oa(ge).join(" ")),fe["attr__"+ae.name]=Rr(1024,ae.name==="href"&&U?Pt(ge):ge)}}));for(var _e=1,Ce=1,Te=N;Te=Cf(Te);)_e++,Te.tagName===N.tagName&&Ce++;return fe.nth_child=_e,fe.nth_of_type=Ce,fe})(S,r,o,a,u));var M=(function(N){if(!vo(N))return{};var P={};return Z(N.attributes,(function(z){if(z.name&&z.name.indexOf("data-ph-capture-attribute")===0){var H=z.name.replace("data-ph-capture-attribute-",""),U=z.value;H&&U&&Qn(U)&&(P[H]=U)}})),P})(S);te(v,M)})),w)return{props:{},explicitNoCapture:w};if(o||(m[0].$el_text=Me(t,"a")||Me(t,"button")?xl(t):li(t)),E){var I,A;m[0].attr__href=E;var F=(I=vs(E))==null?void 0:I.host,D=_==null||(A=_.location)==null?void 0:A.host;F&&D&&F!==D&&(f=E)}return{props:te({$event_type:s.type,$ce_version:1},l?{}:{$elements:m},{$elements_chain:(g=m,(function(S){return S.map(($=>{var T,M,N="";if($.tag_name&&(N+=$.tag_name),$.attr_class)for(var P of($.attr_class.sort(),$.attr_class))N+="."+P.replace(/"/g,"");var z=b({},$.text?{text:$.text}:{},{"nth-child":(T=$.nth_child)!==null&&T!==void 0?T:0,"nth-of-type":(M=$.nth_of_type)!==null&&M!==void 0?M:0},$.href?{href:$.href}:{},$.attr_id?{attr_id:$.attr_id}:{},$.attributes),H={};return qi(z).sort(((U,Q)=>U[0].localeCompare(Q[0]))).forEach((U=>{var Q=U[1];return H[kl(U[0].toString())]=kl(Q.toString())})),(N+=":")+qi(H).map((U=>U[0]+'="'+U[1]+'"')).join("")})).join(";")})((function(S){return S.map(($=>{var T,M,N={text:(T=$.$el_text)==null?void 0:T.slice(0,400),tag_name:$.tag_name,href:(M=$.attr__href)==null?void 0:M.slice(0,2048),attr_class:Up($),attr_id:$.attr__id,nth_child:$.nth_child,nth_of_type:$.nth_of_type,attributes:{}};return qi($).filter((P=>P[0].indexOf("attr__")===0)).forEach((P=>N.attributes[P[0]]=P[1])),N}))})(g)))},(n=m[0])!=null&&n.$el_text?{$el_text:(i=m[0])==null?void 0:i.$el_text}:{},f&&s.type==="click"?{$external_click_url:f}:{},v)}}var jn=ie("[ExceptionAutocapture]"),zl=()=>{},Ff=ie("[TracingHeaders]"),jt=ie("[Web Vitals]"),ql=9e5,Vl="disabled",Gl="lazy_loading",Un="awaiting_config",Ni="missing_config";ie("[SessionRecording]"),ie("[SessionRecording]");var ko="[SessionRecording]",ut=ie(ko),Pf=ie("[Heatmaps]");function Nr(t){return ne(t)&&"clientX"in t&&"clientY"in t&&he(t.clientX)&&he(t.clientY)}var Mi=ie("[Product Tours]"),Mr=t=>{var e;return!t.config.disable_product_tours&&!((e=t.persistence)==null||!e.get_property(na))},$f=["$set_once","$set"],et=ie("[SiteApps]"),Kl="Error while initializing PostHog app with config id ";function an(t,e,n){if(B(t))return!1;switch(n){case"exact":return t===e;case"contains":var i=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/_/g,".").replace(/%/g,".*");return new RegExp(i,"i").test(t);case"regex":try{return new RegExp(e).test(t)}catch{return!1}default:return!1}}class Tf{constructor(e){this.ns=new da,this.ss=(n,i)=>this.os(n,i)&&this.ls(n,i)&&this.us(n,i)&&this.hs(n,i),this.os=(n,i)=>i==null||!i.event||n?.event===i?.event,this._instance=e,this.ds=new Set,this.vs=new Set}init(){var e,n;x((e=this._instance)==null?void 0:e._addCaptureHook)||(n=this._instance)==null||n._addCaptureHook(((i,s)=>{this.on(i,s)}))}register(e){var n,i;if(!x((n=this._instance)==null?void 0:n._addCaptureHook)&&(e.forEach((o=>{var a,l;(a=this.vs)==null||a.add(o),(l=o.steps)==null||l.forEach((u=>{var c;(c=this.ds)==null||c.add(u?.event||"")}))})),(i=this._instance)!=null&&i.autocapture)){var s,r=new Set;e.forEach((o=>{var a;(a=o.steps)==null||a.forEach((l=>{l!=null&&l.selector&&r.add(l?.selector)}))})),(s=this._instance)==null||s.autocapture.setElementSelectors(r)}}on(e,n){var i;n!=null&&e.length!=0&&(this.ds.has(e)||this.ds.has(n.event))&&this.vs&&((i=this.vs)==null?void 0:i.size)>0&&this.vs.forEach((s=>{this.cs(n,s)&&this.ns.emit("actionCaptured",s.name)}))}fs(e){this.onAction("actionCaptured",(n=>e(n)))}cs(e,n){if(n?.steps==null)return!1;for(var i of n.steps)if(this.ss(e,i))return!0;return!1}onAction(e,n){return this.ns.on(e,n)}ls(e,n){if(n!=null&&n.url){var i,s=e==null||(i=e.properties)==null?void 0:i.$current_url;if(!s||typeof s!="string"||!an(s,n.url,n.url_matching||"contains"))return!1}return!0}us(e,n){return!!this.ps(e,n)&&!!this.gs(e,n)&&!!this.ys(e,n)}ps(e,n){var i;if(n==null||!n.href)return!0;var s=this.bs(e);if(s.length>0)return s.some((a=>an(a.href,n.href,n.href_matching||"exact")));var r,o=(e==null||(i=e.properties)==null?void 0:i.$elements_chain)||"";return!!o&&an((r=o.match(/(?::|")href="(.*?)"/))?r[1]:"",n.href,n.href_matching||"exact")}gs(e,n){var i;if(n==null||!n.text)return!0;var s=this.bs(e);if(s.length>0)return s.some((u=>an(u.text,n.text,n.text_matching||"exact")||an(u.$el_text,n.text,n.text_matching||"exact")));var r,o,a,l=(e==null||(i=e.properties)==null?void 0:i.$elements_chain)||"";return!!l&&(r=(function(u){for(var c,d=[],h=/(?::|")text="(.*?)"/g;!B(c=h.exec(u));)d.includes(c[1])||d.push(c[1]);return d})(l),o=n.text,a=n.text_matching||"exact",r.some((u=>an(u,o,a))))}ys(e,n){var i,s;if(n==null||!n.selector)return!0;var r=e==null||(i=e.properties)==null?void 0:i.$element_selectors;if(r!=null&&r.includes(n.selector))return!0;var o=(e==null||(s=e.properties)==null?void 0:s.$elements_chain)||"";if(n.selector_regex&&o)try{return new RegExp(n.selector_regex).test(o)}catch{return!1}return!1}bs(e){var n;return(e==null||(n=e.properties)==null?void 0:n.$elements)==null?[]:e?.properties.$elements}hs(e,n){return n==null||!n.properties||n.properties.length===0||md(n.properties.reduce(((i,s)=>{var r=O(s.value)?s.value.map(String):s.value!=null?[String(s.value)]:[];return i[s.key]={values:r,operator:s.operator||"exact"},i}),{}),e?.properties)}}class Rf{constructor(e){var n;this._s=[],this._instance=e,this.ws=new Map,this.ks=new Map,this.xs=new Map,(n=this._instance)==null||n.onSessionId==null||n.onSessionId((i=>this.Ss(i)))}Cs(e){return!1}Ms(){return null}Ts(e){}Es(){}Is(e,n){return!!e&&md(e.propertyFilters,n?.properties)}Ps(e,n){var i=new Map;return e.forEach((s=>{var r;(r=s.conditions)==null||(r=r[n])==null||(r=r.values)==null||r.forEach((o=>{if(o!=null&&o.name){var a=i.get(o.name)||[];a.push(s.id),i.set(o.name,a)}}))})),i}Rs(e,n,i){var s=(i===Mn.Activation?this.ws:this.ks).get(e),r=[];return this.As((o=>{r=o.filter((a=>s?.includes(a.id)))})),r.filter((o=>{var a,l=(a=o.conditions)==null||(a=a[i])==null||(a=a.values)==null?void 0:a.find((u=>u.name===e));return this.Is(l,n)}))}register(e){var n;x((n=this._instance)==null?void 0:n._addCaptureHook)||(this.Fs(e),this.Ls(e))}Ls(e){var n=e.filter((i=>{var s,r;return((s=i.conditions)==null?void 0:s.actions)&&((r=i.conditions)==null||(r=r.actions)==null||(r=r.values)==null?void 0:r.length)>0}));n.length!==0&&(this.Os==null&&(this.Os=new Tf(this._instance),this.Os.init(),this.Os.fs((i=>{this.onAction(i)}))),n.forEach((i=>{var s,r,o,a,l;i.conditions&&(s=i.conditions)!=null&&s.actions&&(r=i.conditions)!=null&&(r=r.actions)!=null&&r.values&&((o=i.conditions)==null||(o=o.actions)==null||(o=o.values)==null?void 0:o.length)>0&&((a=this.Os)==null||a.register(i.conditions.actions.values),(l=i.conditions)==null||(l=l.actions)==null||(l=l.values)==null||l.forEach((u=>{if(u&&u.name){var c=this.xs.get(u.name);c&&c.push(i.id),this.xs.set(u.name,c||[i.id])}})))})))}Fs(e){var n,i=e.filter((r=>{var o,a;return((o=r.conditions)==null?void 0:o.events)&&((a=r.conditions)==null||(a=a.events)==null||(a=a.values)==null?void 0:a.length)>0})),s=e.filter((r=>{var o,a;return((o=r.conditions)==null?void 0:o.cancelEvents)&&((a=r.conditions)==null||(a=a.cancelEvents)==null||(a=a.values)==null?void 0:a.length)>0}));i.length===0&&s.length===0||((n=this._instance)==null||n._addCaptureHook(((r,o)=>{this.onEvent(r,o)})),this.ws=this.Ps(e,Mn.Activation),this.ks=this.Ps(e,Mn.Cancellation))}onEvent(e,n){var i,s,r=this.Ds(),o=(n==null||(i=n.properties)==null?void 0:i.$survey_id)||(n==null||(s=n.properties)==null?void 0:s.$product_tour_id);if(o&&this.getActivatedIds().includes(o)){var a=this.$s(e,o);if(a==="consume")return r.info("event consumed activated item, removing it",{event:e,itemId:o}),void this.Ns([o]);if(a==="persist")return r.info("shown item promoted to persisted activation",{event:e,itemId:o}),this.qs(o),void this.js([o])}if(this.ks.has(e)){var l=this.Rs(e,n,Mn.Cancellation);l.length>0&&(r.info("cancel event matched, cancelling items",{event:e,itemsToCancel:l.map((c=>c.id))}),this.Ns(l.map((c=>c.id))),l.forEach((c=>this.Bs(c.id))))}if(this.ws.has(e)){r.info("event name matched",{event:e,eventPayload:n,items:this.ws.get(e)});var u=this.Rs(e,n,Mn.Activation);this.Hs(u.map((c=>c.id)))}}onAction(e){this.xs.has(e)&&this.Hs(this.xs.get(e)||[])}Hs(e){var n;if(e.length!==0){var i=!((n=this._instance)==null||n.get_session_id==null||!n.get_session_id()),s=[];for(var r of e)i&&this.Cs(r)?this.qs(r)&&this.Us(r):s.push(r);s.length>0&&(this._s=[...new Set([...this._s,...s])]),this.Ds().info("updating activated items",{activatedItems:this.getActivatedIds()})}}qs(e){this._s=this._s.filter((i=>i!==e));var n=this.zs();return!n.includes(e)&&(this.Ws([...n,e]),this.Vs(),!0)}Ns(e){var n=new Set(e);this._s=this._s.filter((r=>!n.has(r)));var i=this.Zs(),s=i.filter((r=>!n.has(r)));s.length!==i.length&&(this.Ws(s),s.length===0&&this.Gs()),this.js(e)}Qs(){var e,n=this.Ms();if(!n)return{};var i=(e=this._instance)==null||(e=e.persistence)==null?void 0:e.props[n];return i&&typeof i=="object"?i:{}}Us(e){if(this.Ms()){var n=this.Qs();this.Ts(b({},n,{[e]:Date.now()}))}}js(e){if(this.Ms()){var n=this.Qs(),i={},s=!1;for(var r of Object.entries(n)){var o=r[0],a=r[1];e.includes(o)?s=!0:i[o]=a}s&&(yt(i)?this.Es():this.Ts(i))}}Ks(){this.Ms()&&this.Es()}getActivationTimestamp(e){if(this.zs().includes(e)){var n=this.Qs()[e];return he(n)?n:void 0}}Zs(){var e,n=this.Js();return((e=this._instance)==null||(e=e.persistence)==null?void 0:e.props[n])||[]}zs(){var e,n,i=this.Zs();if(i.length===0)return[];var s=(e=this._instance)==null||(e=e.persistence)==null?void 0:e.props[this.Ys()],r=(n=this._instance)==null||n.get_session_id==null?void 0:n.get_session_id();return r&&s===r?i:[]}Vs(){var e,n=(e=this._instance)==null||e.get_session_id==null?void 0:e.get_session_id();n&&this.Xs(n)}Gs(){this.ta()}Ss(e){var n,i=(n=this._instance)==null||(n=n.persistence)==null?void 0:n.props[this.Ys()];if(i&&i!==e){var s=this.Zs(),r=this.Qs();s.length>0&&(this.Ws([]),s.filter((o=>he(r[o]))).forEach((o=>this.Bs(o)))),this.Gs(),this.Ks()}}getActivatedIds(){return[...new Set([...this.zs(),...this._s])].filter((e=>!this.ea(e)))}reset(){this._s=[],this.Zs().length>0&&this.Ws([]),this.Gs(),this.Ks()}getEventToItemsMap(){return this.ws}ia(){return this.Os}}class Nf extends Rf{constructor(e){super(e)}Js(){return lo}Ys(){return Hi}Ms(){return Wi}Ts(e){var n;(n=this._instance)==null||(n=n.persistence)==null||n.register({[Wi]:e})}Es(){var e;(e=this._instance)==null||(e=e.persistence)==null||e.unregister(Wi)}Cs(e){var n,i;this.As((r=>{i=r.find((o=>o.id===e))}));var s=(n=i)==null||(n=n.appearance)==null?void 0:n.surveyPopupDelaySeconds;return he(s)&&s>0}ra(){return vt.SHOWN}As(e){var n;(n=this._instance)==null||n.getSurveys(e)}Bs(e){var n;(n=this._instance)==null||n.cancelPendingSurvey(e)}Ds(){return G}Ws(e){var n;(n=this._instance)==null||(n=n.persistence)==null||n.register({[lo]:e})}Xs(e){var n;(n=this._instance)==null||(n=n.persistence)==null||n.register({[Hi]:e})}ta(){var e;(e=this._instance)==null||(e=e.persistence)==null||e.unregister(Hi)}ea(){return!1}$s(e,n){var i;this.As((r=>{i=r.find((o=>o.id===n))}));var s=!i||(function(r){var o;return vd(r)&&!((o=r.conditions)==null||(o=o.events)==null||!o.repeatedActivation)||r.schedule==="always"})(i);return s?e===vt.SHOWN?"consume":"ignore":e===vt.SHOWN?"persist":e===vt.DISMISSED||e===vt.SENT?"consume":"ignore"}getSurveys(){return this.getActivatedIds()}getEventToSurveys(){return this.getEventToItemsMap()}}var Li="SDK is not enabled or survey functionality is not yet loaded",Jl="Disabled. Not loading surveys.",Mf=_!=null&&_.location?_s(_.location.hash,"__posthog")||_s(location.hash,"state"):null,Yl="_postHogToolbarParams",Zl=ie("[Toolbar]"),Xl=ie("[FeatureFlags]");class Lf{constructor(e,n){n===void 0&&(n=!1),this.na=!1,this.update(e,n)}update(e,n){this.sa=((i,s)=>{var r,o,a,l;return{bootstrap:{featureFlags:(r=i.bootstrap)==null?void 0:r.featureFlags,featureFlagPayloads:(o=i.bootstrap)==null?void 0:o.featureFlagPayloads},remoteRequestsDisabled:s,featureFlagsDisabled:!!i.advanced_disable_feature_flags,onlyEvaluateSurveyFeatureFlags:!!i.advanced_only_evaluate_survey_feature_flags,deduplicateCallsPerSession:!!i.advanced_feature_flags_dedup_per_session,cacheTtlMs:i.feature_flag_cache_ttl_ms,requestTimeoutMs:i.feature_flag_request_timeout_ms,compression:i.disable_compression?"none":"base64",evaluationContexts:(a=(l=i.evaluation_contexts)!==null&&l!==void 0?l:i.evaluation_environments)!==null&&a!==void 0?a:[],flagKeys:O(i.flag_keys)?i.flag_keys:void 0}})(e,n),!e.evaluation_environments||e.evaluation_contexts||this.na||(Xl.warn("evaluation_environments is deprecated. Use evaluation_contexts instead. evaluation_environments will be removed in a future version."),this.na=!0),x(e.flag_keys)||O(e.flag_keys)||Xl.error("Invalid flag_keys found:",e.flag_keys,"Expected array of non-empty strings")}get(){return this.sa}}var Ql=ie("[FeatureFlags]"),Ut=ie("[FeatureFlags]",{debugEnabled:!0}),Lr=`" failed. Feature flags didn't load in time.`,ec="connection_error",tc=t=>{for(var e={},n=0;t.length>n;n++)e[t[n]]=!0;return e},nc=t=>{var e={};for(var n of qi(t||{})){var i=n[1];i&&(e[n[0]]=i)}return e},tt=ie("[Error tracking]"),ic="Refusing to render web experiment since the viewer is a likely bot",Of={icontains:(t,e)=>e.toLowerCase().indexOf(t.toLowerCase())>-1,not_icontains:(t,e)=>e.toLowerCase().indexOf(t.toLowerCase())===-1,regex:(t,e)=>bs(e,t),not_regex:(t,e)=>!bs(e,t),exact:(t,e)=>e===t,is_not:(t,e)=>e!==t};class ye{get Ne(){return this._instance.config}constructor(e){var n=this;this.getWebExperimentsAndEvaluateDisplayLogic=function(i){i===void 0&&(i=!1),n.getWebExperiments((s=>{ye.aa("retrieved web experiments from the server"),n.oa=new Map,s.forEach((r=>{if(r.feature_flag_key){var o;n.oa&&(ye.aa("setting flag key ",r.feature_flag_key," to web experiment ",r),(o=n.oa)==null||o.set(r.feature_flag_key,r));var a=n._instance.getFeatureFlag(r.feature_flag_key);q(a)&&r.variants[a]&&n.la(r.name,a,r.variants[a].transforms)}else if(r.variants)for(var l in r.variants){var u=r.variants[l];ye.ua(u,n._instance)&&n.la(r.name,l,u.transforms)}}))}),i)},this._instance=e,this._instance.onFeatureFlags((i=>{this.onFeatureFlags(i)}))}initialize(){}onFeatureFlags(e){if(this._is_bot())ye.aa(ic);else if(!this.Ne.disable_web_experiments){if(B(this.oa))return this.oa=new Map,this.loadIfEnabled(),void this.previewWebExperiment();ye.aa("applying feature flags",e),e.forEach((n=>{var i;if(this.oa&&(i=this.oa)!=null&&i.has(n)){var s,r=this._instance.getFeatureFlag(n),o=(s=this.oa)==null?void 0:s.get(n);r&&o!=null&&o.variants[r]&&this.la(o.name,r,o.variants[r].transforms)}}))}}previewWebExperiment(){var e=ye.getWindowLocation();if(e!=null&&e.search){var n=wn(e?.search,"__experiment_id"),i=wn(e?.search,"__experiment_variant");n&&i&&(ye.aa("previewing web experiments "+n+" && "+i),this.getWebExperiments((s=>{this.ha(parseInt(n),i,s)}),!1,!0))}}loadIfEnabled(){this.Ne.disable_web_experiments||this.getWebExperimentsAndEvaluateDisplayLogic()}getWebExperiments(e,n,i){if(this.Ne.disable_web_experiments&&!i)return e([]);var 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.Ne.token),method:"GET",timestampMode:"query",callback:r=>e(r.statusCode===200&&r.json&&r.json.experiments||[])})}ha(e,n,i){var s=i.filter((r=>r.id===e));s&&s.length>0&&(ye.aa("Previewing web experiment ["+s[0].name+"] with variant ["+n+"]"),this.la(s[0].name,n,s[0].variants[n].transforms))}static ua(e,n){return!B(e.conditions)&&ye.da(e,n)&&ye.va(e)}static da(e,n){var i;if(B(e.conditions)||B((i=e.conditions)==null?void 0:i.url))return!0;var s=ye.getWindowLocation();if(s){var r,o,a,l=Ru(n,s.href);return(r=e.conditions)==null||!r.url||Of[(o=(a=e.conditions)==null?void 0:a.urlMatchType)!==null&&o!==void 0?o:"icontains"](e.conditions.url,l)}return!1}static getWindowLocation(){return _?.location}static va(e){var n;if(B(e.conditions)||B((n=e.conditions)==null?void 0:n.utm))return!0;var i=Ku();if(i.utm_source){var s,r,o,a,l,u,c,d,h=(s=e.conditions)==null||(s=s.utm)==null||!s.utm_campaign||((r=e.conditions)==null||(r=r.utm)==null?void 0:r.utm_campaign)==i.utm_campaign,p=(o=e.conditions)==null||(o=o.utm)==null||!o.utm_source||((a=e.conditions)==null||(a=a.utm)==null?void 0:a.utm_source)==i.utm_source,f=(l=e.conditions)==null||(l=l.utm)==null||!l.utm_medium||((u=e.conditions)==null||(u=u.utm)==null?void 0:u.utm_medium)==i.utm_medium,g=(c=e.conditions)==null||(c=c.utm)==null||!c.utm_term||((d=e.conditions)==null||(d=d.utm)==null?void 0:d.utm_term)==i.utm_term;return h&&f&&g&&p}return!1}static aa(e){for(var n=arguments.length,i=new Array(n>1?n-1:0),s=1;n>s;s++)i[s-1]=arguments[s];k.info("[WebExperiments] "+e,i)}la(e,n,i){this._is_bot()?ye.aa(ic):n!=="control"?i.forEach((s=>{if(s.selector){var r;ye.aa("applying transform of variant "+n+" for experiment "+e+" ",s);var o=(r=document)==null?void 0:r.querySelectorAll(s.selector);o?.forEach((a=>{var l=a;s.html&&(l.innerHTML=s.html),s.css&&l.setAttribute("style",s.css)}))}})):ye.aa("Control variants leave the page unmodified.")}_is_bot(){return ke&&this._instance?pd(ke,this.Ne.custom_blocked_useragents):void 0}}var Ue=ie("[Conversations]"),Ht="Conversations not available yet.",sc="console",Ed="__posthogHandledLogsRequestError",Or=(t,e)=>{var n=t instanceof Error?t:new Error(e);return n[Ed]=!0,n},rc=t=>!!t&&typeof t=="object"&&t[Ed]===!0,Us={featureFlags:class{constructor(t){this.name="featureFlags",this.ca=!1,this.featureFlagEventHandlers=[],this.rt=Ql,this.fa={},this.pa={},this.ga=[],this.ma=!1,this.ya=!1,this.ba=0,this._a=!1,this.wa=!1,this.ka=!1,this.xa=!1,this.Sa=0,this.Ca=()=>{var e=this.Ma();this.Sa=0,e&&this.reloadFeatureFlags()},"get"in t?this.Ta=t:(this.Ea=new Lf(t.config,t.Qi()),this.Ta=this.Ea)}updateConfig(t,e){var n;(n=this.Ea)==null||n.update(t,e)}setup(t){return this.Ia=t,this.rt=t.logger.createLogger("[FeatureFlags]"),n=()=>{this.Ia===t&&(this.Ia=void 0,this.nn=t,this.Pa(t))},(e=t.kv.initialize())!=null&&e.then?e.then(n):n();var e,n}Pa(t){if(this.nn===t)return _&&re(_,"online",this.Ca),this.Ra=t.registerDynamicEventProperties((()=>this.Aa()?this.fa:this.pa)),this.Fa(),this.initialize()}destroy(){_?.removeEventListener("online",this.Ca)}dispose(){var t;this.ba++,this.wa=!1,this.Ia=void 0,this.nn&&(this.La(),(t=this.Ra)==null||t.dispose(),this.Ra=void 0,this.ga=[],_?.removeEventListener("online",this.Ca),this.nn=void 0)}get Ne(){return this.Ta.get()}Oa(t){var e;return(e=this.nn)==null?void 0:e.kv.get(t)}F(t){this.Da((()=>{var e;return(e=this.nn)==null?void 0:e.kv.set(t)}))}q(t){this.Da((()=>{var e;return(e=this.nn)==null?void 0:e.kv.remove(t)}))}Da(t){try{t()}catch(e){this.rt.error("Failed to update feature flag persistence",e)}}Fa(){var t={};for(var e of[Vn,Gn,Ui,it]){var n=this.Oa(e);x(n)||(t[e]=n)}this.fa=t;var i=b({},t),s=this.Oa(Wt);if(s)for(var r of Object.entries(s))i["$feature/"+r[0]]=r[1];this.pa=i}Aa(){var t=this.Ne.cacheTtlMs;if(!t||0>=t)return!1;var e=this.Oa(Xn);return typeof e!="number"||Date.now()-e>t}$a(){return!!this.Aa()&&(this.xa||this.ya||(this.xa=!0,this.rt.warn("Feature flag cache is stale, triggering refresh..."),this.reloadFeatureFlags()),!0)}Na(){var t=this.Ne.evaluationContexts;return t!=null&&t.length?t.filter((e=>{var n=e&&typeof e=="string"&&e.trim().length>0;return n||this.rt.error("Invalid evaluation context found:",e,"Expected non-empty string"),n})):[]}qa(){var t=this.Ne.flagKeys;if(!x(t))return t.filter((e=>{var n=e&&typeof e=="string"&&e.trim().length>0;return n||this.rt.error("Invalid flag key found:",e,"Expected non-empty string"),n}))}initialize(){var t,e,n=this.Ne,i=(t=(e=n.bootstrap)==null?void 0:e.featureFlags)!==null&&t!==void 0?t:{};if(Object.keys(i).length){var s,r,o=(s=(r=n.bootstrap)==null?void 0:r.featureFlagPayloads)!==null&&s!==void 0?s:{},a=Object.keys(i).filter((u=>!!i[u])).reduce(((u,c)=>(u[c]=i[c]||!1,u)),{}),l=Object.keys(o).filter((u=>a[u])).reduce(((u,c)=>(o[c]&&(u[c]=o[c]),u)),{});return this.ja({featureFlags:a,featureFlagPayloads:l})}}updateFlags(t,e,n){var i,s,r=n!=null&&n.merge&&(i=this.Oa(Wt))!==null&&i!==void 0?i:{},o=n!=null&&n.merge&&(s=this.Oa(Gn))!==null&&s!==void 0?s:{},a=b({},r,t),l=b({},o,e),u={};for(var c of Object.entries(a)){var d=c[0],h=c[1];u[d]={key:d,enabled:Za(h),variant:Xa(h),reason:void 0,metadata:x(l?.[d])?void 0:{id:0,version:void 0,description:void 0,payload:l[d]}}}this.ja({flags:u})}get hasLoadedFlags(){return this.ma}getFlags(){return Object.keys(this.getFlagVariants())}getFlagsWithDetails(){var t=this.Oa(oo),e=this.Oa(it),n=this.Oa(zt);if(!n&&!e)return t||{};var i=te({},t||{}),s=[...new Set([...Object.keys(n||{}),...Object.keys(e||{})])];for(var r of s){var o,a,l=i[r],u=e?.[r],c=x(u)?(o=l?.enabled)!==null&&o!==void 0&&o:!!u,d=x(u)?l?.variant:typeof u=="string"?u:void 0,h=n?.[r],p=b({},l,{enabled:c,variant:c?d??l?.variant:void 0});c!==l?.enabled&&(p.original_enabled=l?.enabled),d!==l?.variant&&(p.original_variant=l?.variant),h&&(p.metadata=b({},l?.metadata,{payload:h,original_payload:l==null||(a=l.metadata)==null?void 0:a.payload})),i[r]=p}return this.ca||(this.rt.warn(" Overriding feature flag details!",{flagDetails:t,overriddenPayloads:n,finalDetails:i}),this.ca=!0),i}getAllFeatureFlags(){var t=this.getFlagVariants(),e=this.getFlagPayloads();return Object.keys(t).map((n=>{var i=t[n];return{key:n,enabled:Za(i),variant:Xa(i),payload:Ya(e[n])}}))}getFlagVariants(){var t=this.Oa(Wt),e=this.Oa(it);if(!e)return t||{};for(var n=te({},t||{}),i=Object.keys(e),s=0;i.length>s;s++)n[i[s]]=e[i[s]];return this.ca||(this.rt.warn(" Overriding feature flags!",{enabledFlags:t,overriddenFlags:e,finalFlags:n}),this.ca=!0),n}getFlagPayloads(){var t=this.Oa(Gn),e=this.Oa(zt);if(!e)return t||{};for(var n=te({},t||{}),i=Object.keys(e),s=0;i.length>s;s++)n[i[s]]=e[i[s]];return this.ca||(this.rt.warn(" Overriding feature flag payloads!",{flagPayloads:t,overriddenPayloads:e,finalPayloads:n}),this.ca=!0),n}reloadFeatureFlags(){this._a||this.Ne.featureFlagsDisabled||this.Ma()||this.Ba||(this.ga.slice().forEach((t=>{try{t()}catch(e){this.rt.error("Error while running feature flags reloading callback",e)}})),this.Ba=setTimeout((()=>{this.Ha()}),5))}La(){clearTimeout(this.Ba),this.Ba=void 0}onReloading(t){return this.ga.push(t),()=>{this.ga=this.ga.filter((e=>e!==t))}}ensureFlagsLoaded(){this.ma||this.ya||this.Ba||this.reloadFeatureFlags()}setAnonymousDistinctId(t){this.$anon_distinct_id=t}setReloadingPaused(t){this._a=t}resetFlagCallReported(){this.q(Gt)}Ha(t){this.La();var e=this.nn;if(e&&!this.Ne.remoteRequestsDisabled&&!this.Ma())if(this.ya)this.wa=!0;else{var n={token:e.projectToken,distinct_id:e.distinctId,groups:e.groups,$anon_distinct_id:this.$anon_distinct_id,person_properties:b({},e.initialPersonProperties,this.Oa(ht)||{},{$lib:e.library.name,$lib_version:e.library.version}),group_properties:this.Oa(qt),timezone:ed()};x(e.deviceId)||(n.$device_id=e.deviceId),(t!=null&&t.disableFlags||this.Ne.featureFlagsDisabled)&&(n.disable_flags=!0);var i=this.Na();i.length&&(n.evaluation_contexts=i);var s=this.qa();x(s)||(n.flag_keys=s);var r=this.Ne.onlyEvaluateSurveyFeatureFlags,o="/flags/?v=2"+(r?"&only_evaluate_survey_feature_flags=true":""),a=this.ba;this.ya=!0;var l=()=>{this.wa&&(this.wa=!1,this.Ha())},u=c=>{this.ya=!1,a===this.ba&&(this.F({[zi]:[ec]}),this.rt.error("Feature flag request failed",c)),l()};try{e.sendRequest(o,{target:"flags",method:"POST",body:n,compression:this.Ne.compression==="base64"?xe.Base64:void 0,sentAt:"body",timeoutMs:this.Ne.requestTimeoutMs}).then((c=>{var d,h,p=(d=c.json)!==null&&d!==void 0?d:{},f=c.statusCode!==200;if(this.ya=!1,a===this.ba){if(this.Ua(c.statusCode),f||this.wa||(this.$anon_distinct_id=void 0),!n.disable_flags||this.wa){this.ka=!f;var g=[];c.error?g.push(c.error instanceof Error&&c.error.name==="AbortError"?"timeout":c.error instanceof Error?ec:"unknown_error"):c.statusCode!==200&&g.push("api_error_"+c.statusCode),p.errorsWhileComputingFlags&&g.push("errors_while_computing_flags");var m=!((h=p.quotaLimited)==null||!h.includes("feature_flags"));m&&g.push("quota_limited"),this.F({[zi]:g}),m?this.rt.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."):n.disable_flags||this.ja(p,f,{partialResponse:r}),l()}}else l()})).catch(u)}catch(c){u(c)}}}Ma(){return Vu(this.Sa,3)}Ua(t){this.Sa=Gu(t,this.Sa,3,(()=>this.rt.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===void 0&&(e={}),!e.fresh||this.ka)if(this.ma||this.getFlags()&&this.getFlags().length>0){if(!this.$a()){var i=this.getFeatureFlagResult(t,e);return(n=i?.variant)!==null&&n!==void 0?n:i?.enabled}}else this.rt.warn('getFeatureFlag for key "'+t+Lr)}getFeatureFlagDetails(t){return this.getFlagsWithDetails()[t]}getFeatureFlagPayload(t){var e=this.getFeatureFlagResult(t,{send_event:!1});return e?.payload}getFeatureFlagResult(t,e){if(e===void 0&&(e={}),!e.fresh||this.ka)if(this.ma||this.getFlags()&&this.getFlags().length>0){if(!this.$a()){var n,i=this.getFlagVariants(),s=t in i,r=i[t],o=this.getFlagPayloads()[t],a=String(r),l=this.Oa(Ui)||void 0,u=this.Oa(Xn)||void 0,c=this.Oa(Gt)||{};if(this.Ne.deduplicateCallsPerSession){var d,h=(d=this.nn)==null?void 0:d.session.sessionId,p=this.Oa(Jn);h&&h!==p&&(c={},n=h)}if(e.send_event||!("send_event"in e))if(t in c&&c[t].includes(a))n&&this.F({[Gt]:c,[Jn]:n});else{var f,g,m,v,E,w,I,A,F,D;O(c[t])?c[t].push(a):c[t]=[a],this.F(b({[Gt]:c},n?{[Jn]:n}:{}));var S=this.getFeatureFlagDetails(t),$=[...(f=this.Oa(zi))!==null&&f!==void 0?f:[]];x(r)&&$.push("flag_missing");var T={$feature_flag:t,$feature_flag_response:r,$feature_flag_payload:o||null,$feature_flag_request_id:l,$feature_flag_evaluated_at:u,$feature_flag_bootstrapped_response:((g=this.Ne.bootstrap)==null||(g=g.featureFlags)==null?void 0:g[t])||null,$feature_flag_bootstrapped_payload:((m=this.Ne.bootstrap)==null||(m=m.featureFlagPayloads)==null?void 0:m[t])||null,$used_bootstrap_value:!this.ka};x(S==null||(v=S.metadata)==null?void 0:v.has_experiment)||(T.$feature_flag_has_experiment=S.metadata.has_experiment),x(S==null||(E=S.metadata)==null?void 0:E.version)||(T.$feature_flag_version=S.metadata.version);var M,N=(w=S==null||(I=S.reason)==null?void 0:I.description)!==null&&w!==void 0?w:S==null||(A=S.reason)==null?void 0:A.code;N&&(T.$feature_flag_reason=N),S!=null&&(F=S.metadata)!=null&&F.id&&(T.$feature_flag_id=S.metadata.id),x(S?.original_variant)&&x(S?.original_enabled)||(T.$feature_flag_original_response=x(S.original_variant)?S.original_enabled:S.original_variant),S!=null&&(D=S.metadata)!=null&&D.original_payload&&(T.$feature_flag_original_payload=S==null||(M=S.metadata)==null?void 0:M.original_payload),$.length&&(T.$feature_flag_error=$.join(",")),this.za(T)}else n&&this.F({[Gt]:c,[Jn]:n});if(s)return{key:t,enabled:!!r,variant:typeof r=="string"?r:void 0,payload:Ya(o)}}}else this.rt.warn('getFeatureFlagResult for key "'+t+Lr)}za(t){try{var e;(e=this.nn)==null||e.capture("$feature_flag_called",t).catch((n=>{this.rt.error("Failed to capture feature flag call",n)}))}catch(n){this.rt.error("Failed to capture feature flag call",n)}}getRemoteConfigPayload(t,e){this.Wa(t,e)}Wa(t,e){var n=this;return X((function*(){var i=n.nn;if(i){var s={distinct_id:i.distinctId,token:i.projectToken,person_properties:{$lib:i.library.name,$lib_version:i.library.version}},r=n.Na();r.length&&(s.evaluation_contexts=r);var o,a=n.qa();x(a)||(s.flag_keys=a);try{var l,u=(l=(yield i.sendRequest("/flags/?v=2",{target:"flags",method:"POST",body:s,compression:n.Ne.compression==="base64"?xe.Base64:void 0,sentAt:"body",timeoutMs:n.Ne.requestTimeoutMs})).json)==null?void 0:l.featureFlagPayloads;o=u?.[t]||void 0}catch(c){return void n.rt.error("Remote config feature flag request failed",c)}try{e(o)}catch(c){n.rt.error("Remote config feature flag callback failed",c)}}}))()}isFeatureEnabled(t,e){if(e===void 0&&(e={}),e.fresh&&!this.ka)return e.defaultValue;if(!(this.ma||this.getFlags()&&this.getFlags().length>0))return this.rt.warn('isFeatureEnabled for key "'+t+Lr),e.defaultValue;var n=this.getFeatureFlag(t,e);return x(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.ja(t,e,n)}ja(t,e,n){if(this.nn){this.ma=!0;var i=(function(s,r,o,a,l,u){r===void 0&&(r={}),o===void 0&&(o={}),a===void 0&&(a={}),u===void 0&&(u=Ql);var c=((F,D)=>{var S=F.flags;return S?b({},F,{featureFlags:Object.fromEntries(Object.keys(S).map(($=>{var T;return[$,(T=S[$].variant)!==null&&T!==void 0?T:S[$].enabled]}))),featureFlagPayloads:Object.fromEntries(Object.keys(S).filter(($=>S[$].enabled)).filter(($=>{var T;return(T=S[$].metadata)==null?void 0:T.payload})).map(($=>{var T;return[$,(T=S[$].metadata)==null?void 0:T.payload]})))}):(F.featureFlags&&D.warn("Using an older version of the feature flags endpoint. Please upgrade your PostHog server to the latest version"),F)})(s,u),d=c.flags,h=c.featureFlags,p=c.featureFlagPayloads;if(h){var f=s.requestId,g=s.evaluatedAt;if(O(h)){u.warn("v1 of the feature flags endpoint is deprecated. Please use the latest version.");var m={};if(h)for(var v=0;h.length>v;v++)m[h[v]]=!0;return{[Vn]:h,[Wt]:m,[cs]:!1}}var E=h,w=p,I=d;if(l!=null&&l.partialResponse)E=b({},r,E),w=b({},o,w),I=b({},a,I);else if(s.errorsWhileComputingFlags)if(d){var A=new Set(Object.keys(d).filter((F=>{var D;return!((D=d[F])!=null&&D.failed)})));E=b({},r,Object.fromEntries(Object.entries(E).filter((F=>A.has(F[0]))))),w=b({},o,Object.fromEntries(Object.entries(w||{}).filter((F=>A.has(F[0]))))),I=b({},a,Object.fromEntries(Object.entries(I||{}).filter((F=>A.has(F[0])))))}else E=b({},r,E),w=b({},o,w),I=b({},a,I);return b({[Vn]:Object.keys(nc(E)),[Wt]:E||{},[Gn]:w||{},[oo]:I||{},[cs]:s.minimalFlagCalledEvents===!0},f?{[Ui]:f}:{},g?{[Xn]:g}:{})}})(t,this.getFlagVariants(),this.getFlagPayloads(),this.getFlagsWithDetails(),n,this.rt);i&&this.F(i),e||(this.xa=!1),this.Va(e)}}override(t,e){e===void 0&&(e=!1),this.rt.warn("override is deprecated. Please use overrideFeatureFlags instead."),this.overrideFeatureFlags({flags:t,suppressWarning:e})}overrideFeatureFlags(t){this.Za(t)}Za(t){if(this.nn){if(t===!1)return this.q([it,zt]),this.Va(),void Ut.info("All overrides cleared");if(O(t))return this.F({[it]:tc(t)}),this.Va(),void Ut.info("Flag overrides set",{flags:t});if(t&&typeof t=="object"&&("flags"in t||"payloads"in t)){var e,n=t;this.ca=!!((e=n.suppressWarning)!==null&&e!==void 0&&e);var i={},s=n.flags,r=n.payloads;return s&&(i[it]=O(s)?tc(s):s),r&&(i[zt]=r),Object.keys(i).length&&this.F(i),s===!1&&r===!1?this.q([it,zt]):s===!1?this.q(it):r===!1&&this.q(zt),this.Va(),s===!1?Ut.info("Flag overrides cleared"):s&&Ut.info("Flag overrides set",{flags:s}),void(r===!1?Ut.info("Payload overrides cleared"):r&&Ut.info("Payload overrides set",{payloads:r}))}if(t&&typeof t=="object")return this.F({[it]:t}),this.Va(),void Ut.info("Flag overrides set",{flags:t});this.rt.warn("Invalid overrideOptions provided to overrideFeatureFlags",{overrideOptions:t})}else this.rt.warn("posthog.featureFlags.overrideFeatureFlags called before feature flags were ready")}onFeatureFlags(t){if(this.addFeatureFlagsHandler(t),this.ma){var e=this.Ga(),n=e.flags,i=e.flagVariants;try{t(n,i)}catch(s){this.rt.error("Error while running feature flags callback",s)}}return()=>this.removeFeatureFlagsHandler(t)}updateEarlyAccessFeatureEnrollment(t,e,n){var i=(this.Oa(ji)||[]).find((l=>l.flagKey===t)),s={["$feature_enrollment/"+t]:e},r={$feature_flag:t,$feature_enrollment:e,$set:s};i&&(r.$early_access_feature_name=i.name),n&&(r.$feature_enrollment_stage=n);var o=b({},this.getFlagVariants(),{[t]:e});this.F({[Vn]:Object.keys(nc(o)),[Wt]:o,[ht]:b({},this.Oa(ht)||{},s)}),this.Va();try{var a;(a=this.nn)==null||a.capture("$feature_enrollment_update",r).catch((l=>{this.rt.error("Failed to capture early access feature enrollment",l)}))}catch(l){this.rt.error("Failed to capture early access feature enrollment",l)}}getEarlyAccessFeatures(t,e,n){e===void 0&&(e=!1);var i=this.Oa(ji);!i||e?this.Qa(t,n):t(i)}Qa(t,e){var n=this;return X((function*(){var i=n.nn;if(i){var s,r=e?"&"+e.map((a=>"stage="+a)).join("&"):"";try{var o=yield i.sendRequest("/api/early_access_features/?token="+i.projectToken+r,{target:"api",method:"GET",sentAt:"query"});if(!o.json)return;n.F({[ji]:s=o.json.earlyAccessFeatures})}catch(a){return void n.rt.error("Early access feature request failed",a)}try{t(s)}catch(a){n.rt.error("Early access feature callback failed",a)}}}))()}Ga(){var t=this.getFlags(),e=this.getFlagVariants();return{flags:t.filter((n=>e[n])),flagVariants:Object.keys(e).filter((n=>e[n])).reduce(((n,i)=>(n[i]=e[i],n)),{})}}Va(t){this.Fa();var e=this.Ga(),n=e.flags,i=e.flagVariants;this.featureFlagEventHandlers.forEach((s=>{try{s(n,i,{errorsLoading:t})}catch(r){this.rt.error("Error while running feature flags callback",r)}}))}setPersonPropertiesForFlags(t,e){e===void 0&&(e=!0),this.Ka(t,e)}Ka(t,e){e===void 0&&(e=!0);var n=this.Oa(ht)||{},i=t?.$set||(t!=null&&t.$set_once?{}:t),s=t?.$set_once,r={};if(s)for(var o in s)({}).hasOwnProperty.call(s,o)&&(o in n||(r[o]=s[o]));this.F({[ht]:b({},n,r,i)}),e&&this.reloadFeatureFlags()}unsetPersonPropertiesForFlags(t,e){e===void 0&&(e=!0);var n=b({},this.Oa(ht)||{});t.forEach((i=>{delete n[i]})),this.F({[ht]:n}),e&&this.reloadFeatureFlags()}resetPersonPropertiesForFlags(t){t===void 0&&(t=!0),this.q(ht),t&&this.reloadFeatureFlags()}setGroupPropertiesForFlags(t,e){e===void 0&&(e=!0);var n=this.Oa(qt)||{},i=b({},n);for(var s of Object.keys(t))i[s]=b({},n[s],t[s]);this.F({[qt]:i}),e&&this.reloadFeatureFlags()}resetGroupPropertiesForFlags(t){if(t){var e=this.Oa(qt)||{};this.F({[qt]:b({},e,{[t]:{}})})}else this.q(qt)}reset(){this.ba++,this.wa=!1,this.Fa(),this.ma=!1,this._a=!1,this.ka=!1,this.$anon_distinct_id=void 0,this.La(),this.ca=!1,this.Sa=0}}},Bf={sessionRecording:class{get Ne(){return this._instance.config}get Mr(){return this._instance.persistence}get started(){var t;return!((t=this.Ja)==null||!t.isStarted)}get status(){var t,e;return this.Ya===Un||this.Ya===Ni?this.Ya:(t=(e=this.Ja)==null?void 0:e.status)!==null&&t!==void 0?t:this.Ya}constructor(t){if(this._forceAllowLocalhostNetworkCapture=!1,this.Ya=Vl,this.Xa=void 0,this.eo=!1,this.io=(()=>{var e;if(C==null||!C.visibilityState||C.visibilityState==="visible")return!0;var n=_==null||(e=_.performance)==null||e.getEntriesByType==null?void 0:e.getEntriesByType("visibility-state");return!(n!=null&&n.length)||n.some((i=>i.name==="visible"))})(),this.Ie=()=>{var e;C?.visibilityState==="visible"&&(this.io=!0,(e=this.Ja)==null||e.setDocumentWasEverVisible==null||e.setDocumentWasEverVisible(!0))},this._instance=t,!this._instance.sessionManager)throw ut.error("started without valid sessionManager"),new Error(ko+" started without valid sessionManager. This is a bug.");if(this.Ne.cookieless_mode===gt)throw new Error(ko+' cannot be used with cookieless_mode="always"');C!=null&&C.addEventListener&&re(C,"visibilitychange",this.Ie)}initialize(){this.startIfEnabledOrStop()}dispose(){this.eo=!0,C==null||C.removeEventListener==null||C.removeEventListener("visibilitychange",this.Ie),this.stopRecording()}get ro(){var t,e=!((t=this._instance.get_property(Jt))==null||!t.enabled),n=!this.Ne.disable_session_recording,i=this.Ne.disable_session_recording||this._instance.consent.isOptedOut();return _&&e&&n&&!i}startIfEnabledOrStop(t){var e;if(!(this.eo||this.ro&&(e=this.Ja)!=null&&e.isStarted)){var n=!x(Object.assign)&&!x(Array.from);this.ro&&n?(this.no(t),ut.info("starting")):(this.Ya=Vl,this.stopRecording())}}no(t){var e,n,i;this.ro&&(this.Ya!==Un&&this.Ya!==Ni&&(this.Ya=Gl),R!=null&&(e=R.__PosthogExtensions__)!=null&&(e=e.rrweb)!=null&&e.record&&(n=R.__PosthogExtensions__)!=null&&n.initSessionRecording?this.so(t):(i=R.__PosthogExtensions__)==null||i.loadExternalDependency==null||i.loadExternalDependency(this._instance,this.ao,(s=>{if(s)return ut.error("could not load recorder",s);this.so(t)})))}stopRecording(){var t,e;(t=this.Xa)==null||t.call(this),this.Xa=void 0,(e=this.Ja)==null||e.stop()}oo(){var t,e;(t=this.Xa)==null||t.call(this),this.Xa=void 0,(e=this.Ja)==null||e.discard()}lo(){var t,e;(t=this.Mr)==null||t.unregister(ia),(e=this.Mr)==null||e.unregister(Eu)}uo(t,e){if(B(t))return null;var n,i=he(t)?t:parseFloat(t);return typeof(n=i)!="number"||!Number.isFinite(n)||0>n||n>1?(ut.warn(e+" must be between 0 and 1. Ignoring invalid value:",t),null):i}ho(t){if(this.Mr){var e,n,i=this.Mr,s=()=>{var r,o=t.sessionRecording===!1?void 0:t.sessionRecording,a=this.uo((r=this.Ne.session_recording)==null?void 0:r.sampleRate,"session_recording.sampleRate"),l=this.uo(o?.sampleRate,"remote config sampleRate"),u=a??l;B(u)&&this.lo();var c=o?.minimumDurationMilliseconds;i.register({[Jt]:b({cache_timestamp:Date.now(),enabled:!!o},o,{networkPayloadCapture:b({capturePerformance:t.capturePerformance},o?.networkPayloadCapture),canvasRecording:{enabled:o?.recordCanvas,fps:o?.canvasFps,quality:o?.canvasQuality},sampleRate:u,minimumDurationMilliseconds:x(c)?null:c,endpoint:o?.endpoint,triggerMatchType:o?.triggerMatchType,masking:o?.masking,urlTriggers:o?.urlTriggers,version:o?.version,triggerGroups:o?.triggerGroups})})};s(),(e=this.Xa)==null||e.call(this),this.Xa=(n=this._instance.sessionManager)==null?void 0:n.onSessionId(s)}}onRemoteConfig(t){var e=t.ok?t.config:void 0;return e&&"sessionRecording"in e?e.sessionRecording===!1?(this.ho(e),void this.oo()):(this.ho(e),void this.startIfEnabledOrStop()):(this.Ya===Un&&(this.Ya=Ni,ut.warn("config refresh failed, recording will not start until page reload")),void this.startIfEnabledOrStop())}log(t,e){var n;e===void 0&&(e="log"),(n=this.Ja)!=null&&n.log?this.Ja.log(t,e):ut.warn("log called before recorder was ready")}get ao(){var t,e,n=(t=this._instance)==null||(t=t.persistence)==null?void 0:t.get_property(Jt);return(n==null||(e=n.scriptConfig)==null?void 0:e.script)||"lazy-recorder"}do(){var t,e=this._instance.get_property(Jt);if(!e)return!1;try{t=typeof e=="object"?e:JSON.parse(e)}catch(n){return ut.warn("persisted remote config for session recording is invalid and will be ignored",n),!1}return!B(t.cache_timestamp)&&36e5>=Date.now()-t.cache_timestamp}so(t){var e,n,i;if(!this.eo){if((e=R.__PosthogExtensions__)==null||!e.initSessionRecording)return ut.warn("Called on script loaded before session recording is available. This can be caused by adblockers."),void this._instance.register_for_session({[Pu]:!0});var s;if(this.Ja||(this.Ja=(s=R.__PosthogExtensions__)==null?void 0:s.initSessionRecording(this._instance,this.io),this.Ja._forceAllowLocalhostNetworkCapture=this._forceAllowLocalhostNetworkCapture),!this.do())return this.Ya===Ni||this.Ya===Un?void 0:(this.Ya=Un,ut.info("persisted remote config is stale, requesting fresh config before starting"),void new td(this._instance).load());this.Ya=Gl,(n=(i=this.Ja).setDocumentWasEverVisible)==null||n.call(i,this.io),this.Ja.start(t)}}onRRwebEmit(t){var e;(e=this.Ja)==null||e.onRRwebEmit==null||e.onRRwebEmit(t)}overrideLinkedFlag(){var t,e;this.Ja||(e=this.Mr)==null||e.register({[xu]:!0}),(t=this.Ja)==null||t.overrideLinkedFlag()}overrideSampling(){var t,e;this.Ja||(e=this.Mr)==null||e.register({[Su]:!0}),(t=this.Ja)==null||t.overrideSampling()}overrideTrigger(t){var e,n;this.Ja||(n=this.Mr)==null||n.register({[t==="url"?ku:Iu]:!0}),(e=this.Ja)==null||e.overrideTrigger(t)}get sdkDebugProperties(){var t;return((t=this.Ja)==null?void 0:t.sdkDebugProperties)||{$recording_status:this.status}}tryAddCustomEvent(t,e){var n;return!((n=this.Ja)==null||!n.tryAddCustomEvent(t,e))}}},Df={autocapture:class{constructor(t){this.vo=!1,this.co=null,this.fo=!1,this.po=!1,this.instance=t,this.rageclicks=new Wl(t.config.rageclick),this.mo=null}initialize(){this.startIfEnabled()}get Ne(){var t,e,n=ne(this.instance.config.autocapture)?this.instance.config.autocapture:{};return n.url_allowlist=(t=n.url_allowlist)==null?void 0:t.map((i=>new RegExp(i))),n.url_ignorelist=(e=n.url_ignorelist)==null?void 0:e.map((i=>new RegExp(i))),n}yo(){if(this.isBrowserSupported()){if(_&&C){var t=n=>{n=n||_?.event;try{this.bo(n)}catch(i){Tr.error("Failed to capture event",i)}};if(re(C,"submit",t,{capture:!0}),re(C,"change",t,{capture:!0}),re(C,"click",t,{capture:!0}),this.Ne.capture_copied_text){var e=n=>{n=n||_?.event;try{this.bo(n,$r)}catch(i){Tr.error("Failed to capture copy/cut event",i)}};re(C,"copy",e,{capture:!0}),re(C,"cut",e,{capture:!0})}}}else Tr.info("Disabling Automatic Event Collection because this browser is not supported")}startIfEnabled(){this.isEnabled&&!this.vo&&(this.yo(),this.vo=!0)}onRemoteConfig(t){if(this.fo=!0,t.ok){var e=t.config;e.elementsChainAsString&&(this.po=e.elementsChainAsString);var n=e.autocapture_opt_out;Ye(n)&&(this.instance.persistence&&this.instance.persistence.register({[Qr]:n}),this.co=n),this.startIfEnabled()}else this.startIfEnabled()}setElementSelectors(t){this.mo=t}getElementSelectors(t){var e,n=[];return(e=this.mo)==null||e.forEach((i=>{var s=C?.querySelectorAll(i);s?.forEach((r=>{t===r&&n.push(i)}))})),n}get isEnabled(){var t,e,n=(t=this.instance.persistence)==null?void 0:t.props[Qr],i=this.co,s=this.instance.Qi()&&!this.fo;if($e(i)&&!Ye(n)&&!s)return!1;var r=(e=this.co)!==null&&e!==void 0?e:!!n;return!!this.instance.config.autocapture&&!r}bo(t,e){if(e===void 0&&(e="$autocapture"),this.isEnabled){var n,i=yr(t);Mu(i)&&(i=i.parentNode||null),e==="$autocapture"&&t.type==="click"&&t instanceof MouseEvent&&this.instance.config.rageclick&&(n=this.rageclicks)!=null&&n.isRageClick(t.clientX,t.clientY,t.timeStamp||new Date().getTime())&&yl(i,this.instance.config.rageclick)&&this.bo(t,"$rageclick");var s=e===$r;if(i&&(function(d,h,p,f,g,m){var v;if(!_||la(d)||p!=null&&p.url_allowlist&&!ml(p.url_allowlist,m)||p!=null&&p.url_ignorelist&&ml(p.url_ignorelist,m))return!1;if(p!=null&&p.dom_event_allowlist){var E=p.dom_event_allowlist;if(E&&!E.some((S=>h.type===S)))return!1}var w=Uu(d,f),I=w.parentIsUsefulElement,A=w.targetElementList;if(!(function(S,$){var T=$?.element_allowlist;if(x(T))return!0;var M,N=function(z){if(T.some((H=>z.tagName.toLowerCase()===H)))return{v:!0}};for(var P of S)if(M=N(P))return M.v;return!1})(A,p)||!mo(A,p?.css_selector_allowlist)||mo(A,(v=p?.css_selector_ignorelist)!==null&&v!==void 0?v:Mp))return!1;try{var F=_.getComputedStyle(d);if(F&&F.getPropertyValue("cursor")==="pointer"&&h.type==="click")return!0}catch{}var D=d.tagName.toLowerCase();switch(D){case"html":return!1;case"form":return(g||["submit"]).indexOf(h.type)>=0;case"input":case"select":case"textarea":return(g||["change","click"]).indexOf(h.type)>=0;default:return I?(g||["click"]).indexOf(h.type)>=0:(g||["click"]).indexOf(h.type)>=0&&(aa.indexOf(D)>-1||d.getAttribute("contenteditable")==="true")}})(i,t,this.Ne,s,s?["copy","cut"]:void 0,this.instance)){var r=Af(i,{e:t,maskAllElementAttributes:this.instance.config.mask_all_element_attributes,maskAllText:this.instance.config.mask_all_text,elementAttributeIgnoreList:this.Ne.element_attribute_ignorelist,elementsChainAsString:this.po,disableCaptureUrlHashes:this.instance.config.disable_capture_url_hashes}),o=r.props;if(r.explicitNoCapture)return!1;var a=this.getElementSelectors(i);if(a&&a.length>0&&(o.$element_selectors=a),e===$r){var l,u=Bu(_==null||(l=_.getSelection())==null?void 0:l.toString()),c=t.type||"clipboard";if(!u)return!1;o.$selected_content=u,o.$copy_type=c}return this.instance.capture(e,o),!0}}}isBrowserSupported(){return Se(C?.querySelectorAll)}},historyAutocapture:class{constructor(t){var e;this._instance=t,this._o=(_==null||(e=_.location)==null?void 0:e.pathname)||""}initialize(){this.startIfEnabled()}get isEnabled(){return this._instance.config.capture_pageview==="history_change"}startIfEnabled(){this.isEnabled&&(k.info("History API monitoring enabled, starting..."),this.monitorHistoryChanges())}stop(){this.wo&&this.wo(),this.wo=void 0,k.info("History API monitoring stopped")}monitorHistoryChanges(){_&&_.history&&(this.ko("pushState"),this.ko("replaceState"),this.xo())}ko(t){var e;if(_&&((e=_.history[t])==null||!e.__posthog_wrapped__)){var n=this;(function(i,s,r){try{if(!(s in i))return zl;var o={next:i[s]},a=r((function(){for(var l=arguments.length,u=new Array(l),c=0;l>c;c++)u[c]=arguments[c];return o.next.apply(this,u)}));return Se(a)&&(a.prototype=a.prototype||{},Object.defineProperties(a,{__posthog_wrapped__:{enumerable:!1,value:!0},__posthog_layer__:{enumerable:!1,value:o}})),i[s]=a,()=>{if(i[s]!==a)for(var l=i[s];Se(l)&&l.__posthog_layer__;){var u=l.__posthog_layer__;if(u.next===a)return void(u.next=o.next);l=u.next}else i[s]=o.next}}catch{return zl}})(_.history,t,(i=>function(s,r,o){i.call(this,s,r,o),n.So(t)}))}}So(t){try{var e,n=_==null||(e=_.location)==null?void 0:e.pathname;if(!n)return;n!==this._o&&this.isEnabled&&this._instance.capture(cn,{navigation_type:t}),this._o=n}catch(i){k.error("Error capturing "+t+" pageview",i)}}xo(){if(!this.wo){var t=()=>{this.So("popstate")};re(_,"popstate",t),this.wo=()=>{_&&_.removeEventListener("popstate",t)}}}},heatmaps:class{get Ne(){return this.instance.config}constructor(t){var e;this.Co=!1,this.vo=!1,this.Mo=null,this.instance=t,this.Co=!((e=this.instance.persistence)==null||!e.props[eo]),this.rageclicks=new Wl(t.config.rageclick)}initialize(){this.startIfEnabled()}get flushIntervalMilliseconds(){var t=5e3;return ne(this.Ne.capture_heatmaps)&&this.Ne.capture_heatmaps.flush_interval_milliseconds&&(t=this.Ne.capture_heatmaps.flush_interval_milliseconds),t}get isEnabled(){return B(this.Ne.capture_heatmaps)?B(this.Ne.enable_heatmaps)?this.Co:this.Ne.enable_heatmaps:this.Ne.capture_heatmaps!==!1}startIfEnabled(){if(this.isEnabled){if(this.vo)return;Pf.info("starting..."),this.To(),this.Ie()}else{var t;clearInterval((t=this.Mo)!==null&&t!==void 0?t:void 0),this.Eo(),this.getAndClearBuffer()}}onRemoteConfig(t){if(t.ok){var e=t.config;if("heatmaps"in e){var n=!!e.heatmaps;this.instance.persistence&&this.instance.persistence.register({[eo]:n}),this.Co=n,this.startIfEnabled()}}}getAndClearBuffer(){var t=this.R;return this.R=void 0,t}Io(t){Nr(t.originalEvent)&&this.ke(t.originalEvent,"deadclick")}Ie(){this.Mo&&clearInterval(this.Mo),this.Mo=C?.visibilityState==="visible"?setInterval(this.cr.bind(this),this.flushIntervalMilliseconds):null}To(){_&&C&&(this.Po=this.cr.bind(this),re(_,fs,this.Po),this.Ro=t=>this.ke(t||_?.event),re(C,"click",this.Ro,{capture:!0}),this.Ao=t=>this.Fo(t||_?.event),re(C,"mousemove",this.Ao,{capture:!0}),this.Lo=new Il(this.instance,Hp,this.Io.bind(this)),this.Lo.startIfEnabledOrStop(),this.Oo=this.Ie.bind(this),re(C,ps,this.Oo),this.vo=!0)}Eo(){var t;_&&C&&(this.Po&&_.removeEventListener(fs,this.Po),this.Ro&&C.removeEventListener("click",this.Ro,{capture:!0}),this.Ao&&C.removeEventListener("mousemove",this.Ao,{capture:!0}),this.Oo&&C.removeEventListener(ps,this.Oo),clearTimeout(this.Do),(t=this.Lo)==null||t.stop(),this.vo=!1)}$o(t,e){var n=this.instance.scrollManager.scrollY(),i=this.instance.scrollManager.scrollX(),s=this.instance.scrollManager.scrollElement(),r=(function(o,a,l){for(var u=o;u&&$t(u)&&!Me(u,"body");){if(u===l)return!1;var c=void 0;try{var d,h,p;c=(d=(h=(p=u.ownerDocument)==null?void 0:p.defaultView)!==null&&h!==void 0?h:_)==null?void 0:d.getComputedStyle(u).position}catch{return!1}if(L(a,c))return!0;u=Du(u)}return!1})(yr(t),["fixed","sticky"],s);return{x:t.clientX+(r?0:i),y:t.clientY+(r?0:n),target_fixed:r,type:e}}ke(t,e){var n;if(e===void 0&&(e="click"),!gl(t.target)&&Nr(t)){var i=this.$o(t,e);(n=this.rageclicks)!=null&&n.isRageClick(t.clientX,t.clientY,new Date().getTime())&&yl(yr(t),this.instance.config.rageclick)&&this.Vt(b({},i,{type:"rageclick"})),this.Vt(i)}}Fo(t){!gl(t.target)&&Nr(t)&&(clearTimeout(this.Do),this.Do=setTimeout((()=>{this.Vt(this.$o(t,"mousemove"))}),500))}Vt(t){if(_){var e=this.Ne.disable_capture_url_hashes?Pt(_.location.href):_.location.href,n=this.Ne.custom_personal_data_properties,i=this.Ne.mask_personal_data_properties?[...bn,...n||[]]:[],s=ci(e,i,ui);this.R=this.R||{},this.R[s]||(this.R[s]=[]),this.R[s].push(t)}}cr(){this.R&&!yt(this.R)&&this.instance.capture("$$heatmap",{$heatmap_data:this.getAndClearBuffer()})}},deadClicksAutocapture:Il,webVitalsAutocapture:class{constructor(t){var e;this.Co=!1,this.vo=!1,this.R={navigationKey:void 0,url:void 0,metrics:[],firstMetricTimestamp:void 0},this.No=()=>{clearTimeout(this.qo),this.qo=void 0,this.R.metrics.length!==0&&(this._instance.capture("$web_vitals",b({$current_url:this.R.url},this.R.metrics.reduce(((n,i)=>b({},n,{["$web_vitals_"+i.name+"_event"]:b({},i),["$web_vitals_"+i.name+"_value"]:i.value})),{}))),this.R={navigationKey:void 0,url:void 0,metrics:[],firstMetricTimestamp:void 0})},this.jo=n=>{var i;if(this.R=this.R||{navigationKey:void 0,url:void 0,metrics:[],firstMetricTimestamp:void 0},B(n?.name)||B(n?.value))jt.error("Invalid metric received",n);else{var s=typeof n.navigationURL=="string"?n.navigationURL:void 0,r=this.Bo(s);if(!x(r)){var o=he(n.navigationId)||typeof n.navigationId=="string"?"navigation:"+n.navigationId:"url:"+r;if(!this.Ho||this.Ho>n.value){this.R.navigationKey!==o&&(this.No(),this.qo=setTimeout(this.No,this.flushToCaptureTimeoutMs)),x(this.R.navigationKey)&&(this.R.navigationKey=o,this.R.url=r),this.R.firstMetricTimestamp=x(this.R.firstMetricTimestamp)?Date.now():this.R.firstMetricTimestamp,n.attribution&&n.attribution.interactionTargetElement&&(n.attribution.interactionTargetElement=void 0);var a=(i=this._instance.sessionManager)==null?void 0:i.checkAndGetSessionAndWindowId(!0),l=b({},n,s?{navigationURL:r}:{},{$current_url:r,timestamp:Date.now()});x(a)||(l.$session_id=a.sessionId,l.$window_id=a.windowId),this.R.metrics.push(l),this.R.metrics.length===this.allowedMetrics.length&&this.No()}else jt.error("Ignoring metric with value >= "+this.Ho,n)}}},this.Uo=()=>{if(!this.vo){var n,i,s,r,o=R.__PosthogExtensions__,a=o?.postHogWebVitalsCallbacksByFlavor,l=a?.[this.zo]||(this.zo==="web-vitals"&&x(a)?o?.postHogWebVitalsCallbacks:void 0);if(x(l)||(n=l.onLCP,i=l.onCLS,s=l.onFCP,r=l.onINP),n&&i&&s&&r){var u={reportSoftNavs:this.useSoftNavs};this.allowedMetrics.indexOf("LCP")>-1&&n(this.jo.bind(this),u),this.allowedMetrics.indexOf("CLS")>-1&&i(this.jo.bind(this),u),this.allowedMetrics.indexOf("FCP")>-1&&s(this.jo.bind(this),u),this.allowedMetrics.indexOf("INP")>-1&&r(this.jo.bind(this),u),this.vo=!0}else jt.error("web vitals callbacks not loaded - not starting")}},this._instance=t,this.Co=!((e=this._instance.persistence)==null||!e.props[so]),this.startIfEnabled()}get Wo(){return this._instance.config.capture_performance}get allowedMetrics(){var t,e,n=ne(this.Wo)?(t=this.Wo)==null?void 0:t.web_vitals_allowed_metrics:void 0;return B(n)?((e=this._instance.persistence)==null?void 0:e.props[ro])||["CLS","FCP","INP","LCP"]:n}get flushToCaptureTimeoutMs(){return(ne(this.Wo)?this.Wo.web_vitals_delayed_flush_ms:void 0)||5e3}get useAttribution(){var t=ne(this.Wo)?this.Wo.web_vitals_attribution:void 0;return t!=null&&t}get useSoftNavs(){var t=ne(this.Wo)?this.Wo.__preview_web_vitals_soft_navs:void 0;return t!=null&&t}get Ho(){var t=ne(this.Wo)&&he(this.Wo.__web_vitals_max_value)?this.Wo.__web_vitals_max_value:ql;return t>0&&6e4>=t?ql:t}get isEnabled(){var t=se?.protocol;if(t!=="http:"&&t!=="https:")return jt.info("Web Vitals are disabled on non-http/https protocols"),!1;var e=ne(this.Wo)?this.Wo.web_vitals:Ye(this.Wo)?this.Wo:void 0;return Ye(e)?e:this.Co}startIfEnabled(){this.isEnabled&&!this.vo&&(jt.info("enabled, starting..."),this.ai(this.Uo))}onRemoteConfig(t){if(t.ok){var e=t.config;if("capturePerformance"in e){var n=ne(e.capturePerformance)&&!!e.capturePerformance.web_vitals,i=ne(e.capturePerformance)?e.capturePerformance.web_vitals_allowed_metrics:void 0;this._instance.persistence&&(this._instance.persistence.register({[so]:n}),this._instance.persistence.register({[ro]:i})),this.Co=n,this.startIfEnabled()}}}get zo(){return this.useSoftNavs?this.useAttribution?"web-vitals-with-attribution-soft-navs":"web-vitals-soft-navs":this.useAttribution?"web-vitals-with-attribution":"web-vitals"}ai(t){var e=R.__PosthogExtensions__,n=this.zo,i=e?.postHogWebVitalsCallbacksByFlavor;i!=null&&i[n]||n==="web-vitals"&&x(i)&&e!=null&&e.postHogWebVitalsCallbacks?t():e==null||e.loadExternalDependency==null||e.loadExternalDependency(this._instance,n,(s=>{s?jt.error("failed to load script",s):t()}))}Bo(t){var e=t||_?.location.href;if(e){var n=this._instance.config.disable_capture_url_hashes?Pt(e):e,i=this._instance.config.custom_personal_data_properties,s=this._instance.config.mask_personal_data_properties?[...bn,...i||[]]:[];return ci(n,s,ui)}jt.error("Could not determine current URL")}}},jf={exceptionObserver:class{constructor(t){var e;this.Uo=()=>{var n;if(_&&this.isEnabled&&(n=R.__PosthogExtensions__)!=null&&n.errorWrappingFunctions){var i=R.__PosthogExtensions__.errorWrappingFunctions.wrapOnError,s=R.__PosthogExtensions__.errorWrappingFunctions.wrapUnhandledRejection,r=R.__PosthogExtensions__.errorWrappingFunctions.wrapConsoleError;try{!this.Vo&&this.Ne.capture_unhandled_errors&&(this.Vo=i(this.captureException.bind(this))),!this.Zo&&this.Ne.capture_unhandled_rejections&&(this.Zo=s(this.captureException.bind(this))),!this.Go&&this.Ne.capture_console_errors&&(this.Go=r(this.captureException.bind(this)))}catch(o){jn.error("failed to start",o),this.Qo()}}},this._instance=t,this.Ko=!((e=this._instance.persistence)==null||!e.props[to]),this.Jo=new Oh(b({},(function(n){var i,s,r,o;return n===void 0&&(n={}),{refillRate:(i=(s=n.exceptionRateLimiterRefillRate)!==null&&s!==void 0?s:n.__exceptionRateLimiterRefillRate)!==null&&i!==void 0?i:1,bucketSize:(r=(o=n.exceptionRateLimiterBucketSize)!==null&&o!==void 0?o:n.__exceptionRateLimiterBucketSize)!==null&&r!==void 0?r:10}})(this._instance.config.error_tracking),{refillInterval:1e4,rt:jn})),this.Ne=this.Yo(),this.startIfEnabledOrStop()}Yo(){var t=this._instance.config.capture_exceptions,e={capture_unhandled_errors:!1,capture_unhandled_rejections:!1,capture_console_errors:!1};return ne(t)?e=b({},e,t):(x(t)?this.Ko:t)&&(e=b({},e,{capture_unhandled_errors:!0,capture_unhandled_rejections:!0})),e}get isEnabled(){return this.Ne.capture_console_errors||this.Ne.capture_unhandled_errors||this.Ne.capture_unhandled_rejections}startIfEnabledOrStop(){this.isEnabled?(jn.info("enabled"),this.Qo(),this.ai(this.Uo)):this.Qo()}ai(t){var e,n;(e=R.__PosthogExtensions__)!=null&&e.errorWrappingFunctions?t():(n=R.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,"exception-autocapture",(i=>{if(i)return jn.error("failed to load script",i);t()}))}Qo(){var t,e,n;(t=this.Vo)==null||t.call(this),this.Vo=void 0,(e=this.Zo)==null||e.call(this),this.Zo=void 0,(n=this.Go)==null||n.call(this),this.Go=void 0}onRemoteConfig(t){if(t.ok){var e=t.config;"autocaptureExceptions"in e&&(this.Ko=!!e.autocaptureExceptions||!1,this._instance.persistence&&this._instance.persistence.register({[to]:this.Ko}),this.Ne=this.Yo(),this.startIfEnabledOrStop())}}onConfigChange(){this.Ne=this.Yo()}captureException(t){var e,n,i,s=(e=t==null||(n=t.$exception_list)==null||(n=n[0])==null?void 0:n.type)!==null&&e!==void 0?e:"Exception";this.Jo.consumeRateLimit(s)?jn.info("Skipping exception capture because of client rate limiting.",{exception:s}):(i=this._instance.exceptions)==null||i.sendExceptionEvent(t)}},exceptions:class{constructor(t){var e,n;this.Xo=[],this.tl=new ep([new lp,new vp,new up,new cp,new gp,new fp,new hp,new mp],(function(i){for(var s=arguments.length,r=new Array(s>1?s-1:0),o=1;s>o;o++)r[o-1]=arguments[o];return function(a,l){l===void 0&&(l=0);for(var u=[],c=a.split(` -`),d=l;c.length>d;d++){var h=c[d];if(1024>=h.length){var p=dl.test(h)?h.replace(dl,"$1"):h;if(!p.match(/\S*Error: /)){for(var f of r){var g=f(p,i);if(g){u.push(g);break}}if(u.length>=50)break}}}return(function(m){if(!m.length)return[];var v=Array.from(m);return v.reverse(),v.slice(0,50).map((E=>{return b({},E,{filename:E.filename||(w=v,w[w.length-1]||{}).filename,function:E.function||yn});var w}))})(u)}})("web:javascript",sp,ap)),this._instance=t,this.Xo=(e=(n=this._instance.persistence)==null?void 0:n.get_property(no))!==null&&e!==void 0?e:[],this.el=ls(this.il()),this.rl=new yp(this.el)}onConfigChange(){this.el=ls(this.il()),this.rl.setConfig(this.el)}onRemoteConfig(t){var e,n,i;if(t.ok){var s=t.config;if("errorTracking"in s){var r=(e=(n=s.errorTracking)==null?void 0:n.suppressionRules)!==null&&e!==void 0?e:[],o=(i=s.errorTracking)==null?void 0:i.captureExtensionExceptions;this.Xo=r,this._instance.persistence&&this._instance.persistence.register({[no]:this.Xo,[io]:o})}}}get nl(){var t,e=!!this._instance.get_property(io),n=this._instance.config.error_tracking.captureExtensionExceptions;return(t=n??e)!==null&&t!==void 0&&t}buildProperties(t,e){return this.tl.buildFromUnknown(t,{syntheticException:e?.syntheticException,mechanism:{handled:e?.handled}})}addExceptionStep(t,e){if(this.el.enabled)try{if(!q(t)||t.trim().length===0)return void tt.warn("Ignoring exception step because message must be a non-empty string");var n=(function(r){if(!r)return{sanitizedProperties:{},droppedKeys:[]};var o=[];return{sanitizedProperties:Object.keys(r).reduce(((a,l)=>_p.has(l)?(o.push(l),a):(a[l]=r[l],a)),{}),droppedKeys:o}})(this.sl(e)),i=n.sanitizedProperties,s=n.droppedKeys;s.length>0&&tt.warn("Ignoring reserved exception step fields",{droppedKeys:s}),this.rl.add(b({[os]:t,[as]:new Date().toISOString()},i))}catch(r){tt.error("Failed to add exception step. Ignoring breadcrumb.",r)}}sendExceptionEvent(t){try{var e=t.$exception_list;if(this.al(e)){if(this.ol(e))return this.ll("Exception dropped: matched a suppression rule"),void tt.info("Skipping exception capture because a suppression rule matched");if(!this.nl&&this.ul(e))return this.ll("Exception dropped: thrown by a browser extension"),void tt.info("Skipping exception capture because it was thrown by an extension");if(!this._instance.config.error_tracking.__capturePostHogExceptions&&this.hl(e))return this.ll("Exception dropped: thrown by the PostHog SDK"),void tt.info("Skipping exception capture because it was thrown by the PostHog SDK")}var n=this.el.enabled&&B(t.$exception_steps)?this.dl(t):t,i=typeof(r=globalThis._posthogReleaseId)=="string"&&r.length>0?r:void 0;i&&(n.$release_id=i);try{var s=this._instance.capture("$exception",n,{_noTruncate:!0,_batchKey:"exceptionEvent",Wn:!0});return s&&this.rl.clear(),s}catch(o){return tt.error("Failed to capture exception event. Dropping this exception.",o),void this.rl.clear()}}catch(o){return void tt.error("Failed to process exception event. Ignoring this exception.",o)}var r}dl(t){try{var e=this.rl.getAttachable();return e.length===0?t:b({},t,{$exception_steps:e})}catch(n){return tt.error("Failed to read buffered exception steps. Capturing exception without steps.",n),t}}ll(t){this.el.enabled&&this.rl.add({[os]:t,[as]:new Date().toISOString()})}sl(t){return ne(t)?b({},t):{}}il(){var t,e;return(t=(e=this._instance.config.error_tracking)==null?void 0:e.exception_steps)!==null&&t!==void 0?t:{}}ol(t){if(t.length===0)return!1;try{var e=t.reduce(((n,i)=>{var s=i.type,r=i.value;return q(s)&&s.length>0&&n.$exception_types.push(s),q(r)&&r.length>0&&n.$exception_values.push(r),n}),{$exception_types:[],$exception_values:[]});return this.Xo.some((n=>{var i=n.values.map((s=>{var r=gd[s.operator],o=e[s.key];if(!r||!o)return!1;var a=O(s.value)?s.value:[s.value];return a.length>0&&r(a,o)}));return n.type==="OR"?i.some(Boolean):i.every(Boolean)}))}catch(n){return tt.warn("Failed to evaluate suppression rules. Capturing the exception.",n),!1}}ul(t){return t.flatMap((e=>{var n,i;return(n=(i=e.stacktrace)==null?void 0:i.frames)!==null&&n!==void 0?n:[]})).some((e=>e.filename&&e.filename.startsWith("chrome-extension://")))}hl(t){if(t.length>0){var e,n,i,s,r=(e=(n=t[0].stacktrace)==null?void 0:n.frames)!==null&&e!==void 0?e:[],o=r[r.length-1];return(i=o==null||(s=o.filename)==null?void 0:s.includes("posthog.com/static"))!==null&&i!==void 0&&i}return!1}al(t){return!B(t)&&O(t)}}},Uf=b({productTours:class{get Mr(){return this._instance.persistence}constructor(t){this.vl=null,this.cl=null,this._instance=t}initialize(){this.loadIfEnabled()}onRemoteConfig(t){if(t.ok){var e=t.config;if("productTours"in e){var n,i;if(this.Mr&&this.Mr.register({[na]:!!e.productTours}),!Mr(this._instance))return!this.vl&&B((n=this.Mr)==null?void 0:n.props[Kn])||Mi.info("product tours disabled; stopping and clearing cached tours"),(i=this.vl)==null||i.stop(),this.vl=null,void this.clearCache();this.loadIfEnabled()}}}loadIfEnabled(){!this.vl&&Mr(this._instance)&&this.ai((()=>this.fl()))}ai(t){var e,n;(e=R.__PosthogExtensions__)!=null&&e.generateProductTours?t():(n=R.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,"product-tours",(i=>{i?Mi.error("Could not load product tours script",i):t()}))}fl(){var t;!this.vl&&(t=R.__PosthogExtensions__)!=null&&t.generateProductTours&&(this.vl=R.__PosthogExtensions__.generateProductTours(this._instance,!0))}getProductTours(t,e){if(e===void 0&&(e=!1),!O(this.cl)||e){var n=this.Mr;if(n){var i=n.props[Kn];if(O(i)&&!e)return this.cl=i,void t(i,{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:s=>{if(Mr(this._instance)){var r=s.statusCode;if(r!==200||!s.json){var o="Product Tours API could not be loaded, status: "+r;return r===0?s.error||Mi.warn(o):Mi.error(o),void t([],{isLoaded:!1,error:o})}var a=O(s.json.product_tours)?s.json.product_tours:[];this.cl=a,n&&n.register({[Kn]:a}),t(a,{isLoaded:!0})}else t([],{isLoaded:!0})}})}else t(this.cl,{isLoaded:!0})}getActiveProductTours(t){B(this.vl)?t([],{isLoaded:!1,error:"Product tours not loaded"}):this.vl.getActiveProductTours(t)}showProductTour(t){var e;(e=this.vl)==null||e.showTourById(t)}previewTour(t){this.vl?this.vl.previewTour(t):this.ai((()=>{var e;this.fl(),(e=this.vl)==null||e.previewTour(t)}))}dismissProductTour(){var t;(t=this.vl)==null||t.dismissTour("user_clicked_skip")}nextStep(){var t;(t=this.vl)==null||t.nextStep()}previousStep(){var t;(t=this.vl)==null||t.previousStep()}clearCache(){var t;this.cl=null,(t=this.Mr)==null||t.unregister(Kn)}resetTour(t){var e;(e=this.vl)==null||e.resetTour(t)}resetAllTours(){var t;(t=this.vl)==null||t.resetAllTours()}cancelPendingTour(t){var e;(e=this.vl)==null||e.cancelPendingTour(t)}}},Us),Hf={siteApps:class{constructor(t){this.pl=0,this._instance=t,this.gl=[],this.apps={}}get isEnabled(){return!!this._instance.config.opt_in_site_apps}ml(t,e){if(e){var n=this.globalsForEvent(e);this.gl.push(n),this.gl.length>1e3&&(this.gl=this.gl.slice(10))}}get siteAppLoaders(){var t;return(t=R._POSTHOG_REMOTE_CONFIG)==null||(t=t[this._instance.config.token])==null?void 0:t.siteApps}initialize(){if(this.isEnabled){var t=this._instance._addCaptureHook(this.ml.bind(this));this.yl=()=>{t(),this.gl=[],this.yl=void 0}}}globalsForEvent(t){var e,n,i,s,r,o,a;if(!t)throw new Error("Event payload is required");var l={},u=this._instance.get_property("$groups")||[],c=this._instance.get_property("$stored_group_properties")||{};for(var d of Object.entries(c)){var h=d[0];l[h]={id:u[h],type:h,properties:d[1]}}var p=t.$set_once,f=t.$set;return{event:b({},jc(t,$f),{properties:b({},t.properties,f?{$set:b({},(e=(n=t.properties)==null?void 0:n.$set)!==null&&e!==void 0?e:{},f)}:{},p?{$set_once:b({},(i=(s=t.properties)==null?void 0:s.$set_once)!==null&&i!==void 0?i:{},p)}:{}),elements_chain:(r=(o=t.properties)==null?void 0:o.$elements_chain)!==null&&r!==void 0?r:"",distinct_id:(a=t.properties)==null?void 0:a.distinct_id}),person:{properties:this._instance.get_property("$stored_person_properties")},groups:l}}bl(t){var e,n=(e=t.tagName)==null?void 0:e.toLowerCase();return n==="style"&&this._instance.config.prepare_external_dependency_stylesheet?this._instance.config.prepare_external_dependency_stylesheet(t)||(et.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)||(et.error("prepare_external_dependency_script returned null"),null):t}_l(){var t,e,n,i,s,r,o,a;if(!this._instance.config.prepare_external_dependency_stylesheet&&!this._instance.config.prepare_external_dependency_script)return()=>{};var l=C?.defaultView,u=l==null||(t=l.Node)==null?void 0:t.prototype;if(!l||!u)return()=>{};if(this.pl++,this.wl)return this.kl();var c=[],d=this,h=new WeakSet,p=(m,v,E)=>{if(m!=null&&m[v]){var w=m[v];m[v]=E(w),c.push((()=>{m[v]=w}))}},f=m=>{if(h.has(m))return m;var v=d.bl(m);return v&&h.add(v),v},g=m=>m.map((v=>typeof v=="string"?v:f(v))).filter((v=>!$e(v)));return p(u,"appendChild",(m=>function(v){var E=f(v);return E?m.call(this,E):v})),p(u,"insertBefore",(m=>function(v,E){var w=f(v);return w?m.call(this,w,E):v})),p(u,"replaceChild",(m=>function(v,E){var w=f(v);return w?m.call(this,w,E):E})),[(e=l.Element)==null?void 0:e.prototype,(n=l.Document)==null?void 0:n.prototype,(i=l.DocumentFragment)==null?void 0:i.prototype].forEach((m=>{p(m,"append",(v=>function(){for(var E=arguments.length,w=new Array(E),I=0;E>I;I++)w[I]=arguments[I];return v.apply(this,g(w))})),p(m,"prepend",(v=>function(){for(var E=arguments.length,w=new Array(E),I=0;E>I;I++)w[I]=arguments[I];return v.apply(this,g(w))}))})),[(s=l.Element)==null?void 0:s.prototype,(r=l.CharacterData)==null?void 0:r.prototype,(o=l.DocumentType)==null?void 0:o.prototype].forEach((m=>{p(m,"before",(v=>function(){for(var E=arguments.length,w=new Array(E),I=0;E>I;I++)w[I]=arguments[I];return v.apply(this,g(w))})),p(m,"after",(v=>function(){for(var E=arguments.length,w=new Array(E),I=0;E>I;I++)w[I]=arguments[I];return v.apply(this,g(w))})),p(m,"replaceWith",(v=>function(){for(var E=arguments.length,w=new Array(E),I=0;E>I;I++)w[I]=arguments[I];var A=g(w);return w.length&&!A.length?void 0:v.apply(this,A)}))})),p((a=l.Element)==null?void 0:a.prototype,"insertAdjacentElement",(m=>function(v,E){var w=f(E);return w?m.call(this,v,w):null})),this.wl=()=>{c.forEach((m=>m())),this.wl=void 0},this.kl()}kl(){var t=!1;return()=>{var e;t||(t=!0,this.pl--,this.pl===0&&((e=this.wl)==null||e.call(this)))}}xl(t,e){e===void 0&&(e=!0);var n=this._l();try{var i=t(n);return e&&n(),i}catch(s){throw n(),s}}setupSiteApp(t){var e=this.apps[t.id],n=()=>{var o;!e.errored&&this.gl.length&&(et.info("Processing "+this.gl.length+" events for site app with id "+t.id),this.gl.forEach((a=>this.xl((()=>e.processEvent==null?void 0:e.processEvent(a))))),e.processedBuffer=!0),Object.values(this.apps).every((a=>a.processedBuffer||a.errored))&&((o=this.yl)==null||o.call(this))},i=!1,s=o=>{e.errored=!o,e.loaded=!0,et.info("Site app with id "+t.id+" "+(o?"loaded":"errored")),i&&n()};try{var r=this.xl((o=>t.init({posthog:this._instance,callback(a){o(),s(a)}})),!1).processEvent;r&&(e.processEvent=r),i=!0}catch(o){et.error(Kl+t.id,o),s(!1)}if(i&&e.loaded)try{n()}catch(o){et.error("Error while processing buffered events PostHog app with config id "+t.id,o),e.errored=!0}}Sl(){var t=this.siteAppLoaders||[];for(var e of t)this.apps[e.id]={id:e.id,loaded:!1,errored:!1,processedBuffer:!1};for(var n of t)this.setupSiteApp(n)}Cl(t){var e=this;if(Object.keys(this.apps).length!==0){var n=this.globalsForEvent(t),i=function(r){try{e.xl((()=>r.processEvent==null?void 0:r.processEvent(n)))}catch(o){et.error("Error while processing event "+t.event+" for site app "+r.id,o)}};for(var s of Object.values(this.apps))i(s)}}onRemoteConfig(t){var e,n,i,s=this;if((e=this.siteAppLoaders)!=null&&e.length)return this.isEnabled?(this.Sl(),void this._instance.on("eventCaptured",(l=>this.Cl(l)))):void et.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.');if((n=this.yl)==null||n.call(this),t.ok){var r=t.config;if((i=r.siteApps)!=null&&i.length)if(this.isEnabled){var o=function(){var l,u=a.id,c=a.url;R["__$$ph_site_app_"+u]=s._instance,(l=R.__PosthogExtensions__)==null||l.loadSiteApp==null||l.loadSiteApp(s._instance,c,(d=>{if(d)return et.error(Kl+u,d)}))};for(var a of r.siteApps)o()}else et.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.')}}}},Wf={tracingHeaders:class{constructor(t){this.Ml=void 0,this.Tl=void 0,this.El=void 0,this.Uo=()=>{var e,n,i=this.Il();i?(x(this.Ml)&&(this.Ml=(e=R.__PosthogExtensions__)==null||(e=e.tracingHeadersPatchFns)==null?void 0:e._patchXHR(i,(()=>this._instance.get_distinct_id()),this._instance.sessionManager)),x(this.Tl)&&(this.Tl=(n=R.__PosthogExtensions__)==null||(n=n.tracingHeadersPatchFns)==null?void 0:n._patchFetch(i,(()=>this._instance.get_distinct_id()),this._instance.sessionManager))):this.Qo()},this._instance=t}initialize(){this.startIfEnabledOrStop()}ai(t){var e,n;(e=R.__PosthogExtensions__)!=null&&e.tracingHeadersPatchFns?t():(n=R.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,"tracing-headers",(i=>{if(i)return Ff.error("failed to load script",i);t()}))}Pl(){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}Il(){var t=this.Pl();return O(t)?(O(this.El)?this.El.splice(0,this.El.length,...t):this.El=[...t],t.length>0?this.El:void 0):(O(this.El)&&this.El.splice(0),this.El=t||void 0,this.El)}Qo(){var t,e;(t=this.Ml)==null||t.call(this),(e=this.Tl)==null||e.call(this),this.Ml=void 0,this.Tl=void 0}startIfEnabledOrStop(){this.Il()?this.ai(this.Uo):this.Qo()}}},zf=b({surveys:class{get Ne(){return this._instance.config}constructor(t){this.Rl=void 0,this._surveyManager=null,this.Al=!1,this.Fl=[],this.Ll=null,this.Ol=null,this._instance=t,this._surveyEventReceiver=null}initialize(){this.loadIfEnabled()}onRemoteConfig(t){if(!this.Ne.disable_surveys){if(!t.ok)return G.warn("Remote config unavailable. Not loading surveys.");var e=t.config.surveys;if(B(e))return G.warn("Flags not loaded yet. Not loading surveys.");var n=O(e);this.Rl=n?e.length>0:e,G.info("flags response received, isSurveysEnabled: "+this.Rl),this.loadIfEnabled()}}reset(){try{var t;(t=this._surveyEventReceiver)==null||t.reset(),localStorage.removeItem("lastSeenSurveyDate");for(var e=[],n=0;nlocalStorage.removeItem(s)))}catch{}}loadIfEnabled(){if(!this._surveyManager)if(this.Al)G.info("Already initializing surveys, skipping...");else if(this.Ne.disable_surveys)G.info(Jl);else if(this.Ne.cookieless_mode&&this._instance.consent.isOptedOut())G.info("Not loading surveys in cookieless mode without consent.");else{var t=R?.__PosthogExtensions__;if(t){if(!x(this.Rl)||this.Ne.advanced_enable_surveys){var e=this.Rl||this.Ne.advanced_enable_surveys;this.Al=!0;try{var n=t.generateSurveys;if(n)return void this.Dl(n,e);var i=t.loadExternalDependency;if(!i)return void this.$l(sa);i(this._instance,"surveys",(s=>{s||!t.generateSurveys?this.$l("Could not load surveys script",s):this.Dl(t.generateSurveys,e)}))}catch(s){throw this.$l("Error initializing surveys",s),s}finally{this.Al=!1}}}else G.error("PostHog Extensions not found.")}}Dl(t,e){this._surveyManager=t(this._instance,e),this._surveyEventReceiver=new Nf(this._instance),G.info("Surveys loaded successfully"),this.Nl({isLoaded:!0})}$l(t,e){G.error(t,e),this.Nl({isLoaded:!1,error:t})}onSurveysLoaded(t){return this.Fl.push(t),this._surveyManager&&this.Nl({isLoaded:!0}),()=>{this.Fl=this.Fl.filter((e=>e!==t))}}getSurveys(t,e){if(e===void 0&&(e=!1),this.Ne.disable_surveys)return G.info(Jl),t([]);var n,i=this._instance.get_property(ao);if(i&&!e)return t(i,{isLoaded:!0}),void(this.ql()&&this.getSurveys((()=>{}),!0));typeof Promise<"u"&&this.Ll?this.Ll.then((s=>t(s.surveys,s.context))):(typeof Promise<"u"&&(this.Ll=new Promise((s=>{n=s}))),this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/surveys/?token="+this.Ne.token),method:"GET",timestampMode:"query",timeout:this.Ne.surveys_request_timeout_ms,callback:s=>{var r;this.Ll=null;var o=s.statusCode;if(o!==200||!s.json){var a="Surveys API could not be loaded, status: "+o;o!==0?G.error(a):s.error||G.warn(a),this.Ol=Date.now();var l={isLoaded:!1,error:a};return t([],l),void(n==null||n({surveys:[],context:l}))}this.Ol=null;var u,c=s.json.surveys||[],d=c.filter((p=>(function(f){return!(!f.start_date||f.end_date)})(p)&&(vd(p)||(function(f){var g;return!((g=f.conditions)==null||(g=g.actions)==null||(g=g.values)==null||!g.length)})(p))));d.length>0&&((u=this._surveyEventReceiver)==null||u.register(d)),(r=this._instance.persistence)==null||r.register({[ao]:c,[us]:Date.now()});var h={isLoaded:!0};t(c,h),n?.({surveys:c,context:h})}}))}ql(){return this.jl()&&!this.Ll&&!this.Bl()}jl(){var t=this._instance.get_property(us);return he(t)&&Date.now()-t>3e5}Bl(){return he(this.Ol)&&3e5>Date.now()-this.Ol}markSurveyAsSeen(t,e){var n,i={id:t,current_iteration:(n=e?.iteration)!==null&&n!==void 0?n:null};yd(i);try{localStorage.setItem("lastSeenSurveyDate",new Date().toISOString())}catch{}}Nl(t){for(var e of this.Fl)try{if(!t.isLoaded)return e([],t);this.getSurveys(e)}catch(n){G.error("Error in survey callback",n)}}getActiveMatchingSurveys(t,e){if(e===void 0&&(e=!1),!B(this._surveyManager))return this._surveyManager.getActiveMatchingSurveys(t,e);G.warn("init was not called")}Hl(t){var e=null;return this.getSurveys((n=>{var i;e=(i=n.find((s=>s.id===t)))!==null&&i!==void 0?i:null})),e}Ul(t){if(B(this._surveyManager))return{eligible:!1,reason:Li};var e=typeof t=="string"?this.Hl(t):t;return e?this._surveyManager.checkSurveyEligibility(e):{eligible:!1,reason:"Survey not found"}}zl(t){if(B(this._surveyManager))return{eligible:!1,reason:Li};var e=typeof t=="string"?this.Hl(t):t;return e?this._surveyManager.checkSurveyRenderability(e):{eligible:!1,reason:"Survey not found"}}canRenderSurvey(t){if(B(this._surveyManager))return G.warn("init was not called"),{visible:!1,disabledReason:Li};var e=this.zl(t);return{visible:e.eligible,disabledReason:e.reason}}canRenderSurveyAsync(t,e){return B(this._surveyManager)?(G.warn("init was not called"),Promise.resolve({visible:!1,disabledReason:Li})):new Promise((n=>{this.getSurveys((i=>{var s,r=(s=i.find((a=>a.id===t)))!==null&&s!==void 0?s:null;if(r){var o=this.zl(r);n({visible:o.eligible,disabledReason:o.reason})}else n({visible:!1,disabledReason:"Survey not found"})}),e)}))}renderSurvey(t,e,n){var i;if(B(this._surveyManager))G.warn("init was not called");else{var s=typeof t=="string"?this.Hl(t):t;if(s!=null&&s.id)if(mf.includes(s.type)){var r=C?.querySelector(e);if(r)return(i=s.appearance)!=null&&i.surveyPopupDelaySeconds?(G.info("Rendering survey "+s.id+" with delay of "+s.appearance.surveyPopupDelaySeconds+" seconds"),void setTimeout((()=>{var o,a;G.info("Rendering survey "+s.id+" with delay of "+((o=s.appearance)==null?void 0:o.surveyPopupDelaySeconds)+" seconds"),(a=this._surveyManager)==null||a.renderSurvey(s,r,n),G.info("Survey "+s.id+" rendered")}),1e3*s.appearance.surveyPopupDelaySeconds)):void this._surveyManager.renderSurvey(s,r,n);G.warn("Survey element not found")}else G.warn("Surveys of type "+s.type+" cannot be rendered in the app");else G.warn("Survey not found")}}displaySurvey(t,e){var n;if(B(this._surveyManager))G.warn("init was not called");else{var i=this.Hl(t);if(i){var s=i;if((n=i.appearance)!=null&&n.surveyPopupDelaySeconds&&e.ignoreDelay&&(s=b({},i,{appearance:b({},i.appearance,{surveyPopupDelaySeconds:0})})),e.displayType!==_o.Popover&&e.initialResponses&&G.warn("initialResponses is only supported for popover surveys. prefill will not be applied."),e.ignoreConditions===!1){var r=this.Ul(i);if(!r.eligible)return void G.warn("Survey is not eligible to be displayed: ",r.reason)}e.displayType!==_o.Inline?this._surveyManager.handlePopoverSurvey(s,e):this.renderSurvey(s,e.selector,e.properties)}else G.warn("Survey not found")}}cancelPendingSurvey(t){B(this._surveyManager)?G.warn("init was not called"):this._surveyManager.cancelSurvey(t)}handlePageUnload(){var t;(t=this._surveyManager)==null||t.handlePageUnload==null||t.handlePageUnload()}}},Us),qf={toolbar:class{constructor(t){this.instance=t}Wl(t){R.ph_toolbar_state=t}Vl(){var t;return(t=R.ph_toolbar_state)!==null&&t!==void 0?t:0}initialize(){return this.maybeLoadToolbar()}maybeLoadToolbar(t,e,n){if(t===void 0&&(t=void 0),e===void 0&&(e=void 0),n===void 0&&(n=void 0),go(this.instance.config)||!_||!C)return!1;t=t??_.location,n=n??_.history;try{if(!e){try{_.localStorage.setItem("test","test"),_.localStorage.removeItem("test")}catch{return!1}e=_?.localStorage}var i,s=Mf||_s(t.hash,"__posthog")||_s(t.hash,"state"),r=s?pl((()=>JSON.parse(atob(decodeURIComponent(s)))))||pl((()=>JSON.parse(decodeURIComponent(s)))):null;return r&&r.action==="ph_authorize"?((i=r).source="url",i&&Object.keys(i).length>0&&(r.desiredHash?t.hash=r.desiredHash:n?n.replaceState(n.state,"",t.pathname+t.search):t.hash="")):((i=JSON.parse(e.getItem(Yl)||"{}")).source="localstorage",delete i.userIntent),!(!i.token||this.instance.config.token!==i.token||(this.loadToolbar(i),0))}catch{return!1}}Zl(t){var e=R.ph_load_toolbar||R.ph_load_editor;!B(e)&&Se(e)?e(t,this.instance):Zl.warn("No toolbar load function found")}loadToolbar(t){var e=!(C==null||!C.getElementById(Nu));if(!_||e)return!1;var n=this.instance.requestRouter.region==="custom"&&this.instance.config.advanced_disable_toolbar_metrics,i=b({token:this.instance.config.token},t,{apiURL:this.instance.requestRouter.endpointFor("ui")},n?{instrument:!1}:{});if(_.localStorage.setItem(Yl,JSON.stringify(b({},i,{source:void 0}))),this.Vl()===2)this.Zl(i);else if(this.Vl()===0){var s;this.Wl(1),(s=R.__PosthogExtensions__)==null||s.loadExternalDependency==null||s.loadExternalDependency(this.instance,"toolbar",(r=>{if(r)return Zl.error("[Toolbar] Failed to load",r),void this.Wl(0);this.Wl(2),this.Zl(i)})),re(_,"turbolinks:load",(()=>{this.Wl(0),this.loadToolbar(i)}))}return!0}Gl(t){return this.loadToolbar(t)}maybeLoadEditor(t,e,n){return t===void 0&&(t=void 0),e===void 0&&(e=void 0),n===void 0&&(n=void 0),this.maybeLoadToolbar(t,e,n)}}},Vf=b({experiments:ye},Us),Gf={conversations:class{constructor(t){this.Ql=void 0,this._conversationsManager=null,this.Kl=!1,this.Jl=null,this.Yl=!1,this._instance=t}initialize(){this.loadIfEnabled()}onRemoteConfig(t){if(!this._instance.config.disable_conversations&&(this.Xl=t.ok,t.ok)){var e=t.config.conversations;B(e)||(Ye(e)?this.Ql=e:(this.Ql=e.enabled,this.Jl=e),this.loadIfEnabled())}}reset(){var t;(t=this._conversationsManager)==null||t.reset(),this._conversationsManager=null,this.Ql=void 0,this.Jl=null,this.Xl=void 0,this.Yl=!1}loadIfEnabled(){if(!(this._conversationsManager||this.Kl||this._instance.config.disable_conversations||go(this._instance.config)||this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut())){var t=R?.__PosthogExtensions__;if(t&&!x(this.Ql)&&this.Ql)if(this.Jl&&this.Jl.token){this.Kl=!0;try{var e=t.initConversations;if(e)return this.tu(e),void(this.Kl=!1);var n=t.loadExternalDependency;if(!n)return void this.eu(sa);n(this._instance,"conversations",(i=>{i||!t.initConversations?this.eu("Could not load conversations script",i):this.tu(t.initConversations),this.Kl=!1}))}catch(i){this.eu("Error initializing conversations",i),this.Kl=!1}}else Ue.error("Conversations enabled but missing token in remote config.")}}tu(t){if(this.Jl)try{this._conversationsManager=t(this.Jl,this._instance),this.Yl=!1,Ue.info("Conversations loaded successfully")}catch(e){this.eu("Error completing conversations initialization",e)}else Ue.error("Cannot complete initialization: remote config is null")}eu(t,e){Ue.error(t,e),this._conversationsManager=null,this.Kl=!1,this.Yl=!0}show(){this._conversationsManager?this._conversationsManager.show():Ue.warn("Conversations not loaded yet.")}hide(){this._conversationsManager&&this._conversationsManager.hide()}isAvailable(){return this.Ql===!0&&!$e(this._conversationsManager)}getUnavailableReason(){return this.isAvailable()?null:this._instance.config.disable_conversations?"disabled_by_config":go(this._instance.config)?"disabled_for_toolbar":this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut()?"consent_opted_out":this.Xl===!1?"remote_config_failed":x(this.Ql)?this.Xl?"disabled_in_project":"remote_config_pending":this.Ql?B(this.Jl)||!this.Jl.token?"missing_token":R!=null&&R.__PosthogExtensions__?this.Kl?"initializing":this.Yl?"load_failed":"not_loaded":"extensions_unavailable":"disabled_in_project"}isVisible(){var t,e;return(t=(e=this._conversationsManager)==null?void 0:e.isVisible())!==null&&t!==void 0&&t}sendMessage(t,e,n){var i=this;return X((function*(){return i._conversationsManager?i._conversationsManager.sendMessage(t,e,n):(Ue.warn(Ht),null)}))()}getMessages(t,e){var n=this;return X((function*(){return n._conversationsManager?n._conversationsManager.getMessages(t,e):(Ue.warn(Ht),null)}))()}markAsRead(t){var e=this;return X((function*(){return e._conversationsManager?e._conversationsManager.markAsRead(t):(Ue.warn(Ht),null)}))()}getTickets(t){var e=this;return X((function*(){return e._conversationsManager?e._conversationsManager.getTickets(t):(Ue.warn(Ht),null)}))()}requestRestoreLink(t){var e=this;return X((function*(){return e._conversationsManager?e._conversationsManager.requestRestoreLink(t):(Ue.warn(Ht),null)}))()}restoreFromToken(t){var e=this;return X((function*(){return e._conversationsManager?e._conversationsManager.restoreFromToken(t):(Ue.warn(Ht),null)}))()}restoreFromUrlToken(){var t=this;return X((function*(){return t._conversationsManager?t._conversationsManager.restoreFromUrlToken():(Ue.warn(Ht),null)}))()}getCurrentTicketId(){var t,e;return(t=(e=this._conversationsManager)==null?void 0:e.getCurrentTicketId())!==null&&t!==void 0?t:null}getWidgetSessionId(){var t,e;return(t=(e=this._conversationsManager)==null?void 0:e.getWidgetSessionId())!==null&&t!==void 0?t:null}Xn(){var t;(t=this._conversationsManager)==null||t.setIdentity()}ts(){var t;(t=this._conversationsManager)==null||t.clearIdentity()}}},Kf={logs:class{constructor(t){var e,n=this;this.iu=!1,this.ru=!1,this.rt=ie("[logs]"),this.nu=b({},this.rt,{error(){for(var i=arguments.length,s=new Array(i),r=0;i>r;r++)s[r]=arguments[r];s.some(rc)||n.rt.error(...s)}}),this.tr=[],this.su=[],this.Sa=0,this.au=()=>{var i,s;this.Sa=0,(i=this.ou)==null||i.onReconnect(),(s=this.lu)==null||s.onReconnect()},this._instance=t,this._instance&&(e=this._instance.config.logs)!=null&&e.captureConsoleLogs&&(this.iu=!0),_&&re(_,"online",this.au)}uu(t,e,n,i){var s,r=(function(o,a){var l,u,c,d,h,p,f,g=(l=o?.flushIntervalMs)!==null&&l!==void 0?l:3e3,m=(u=o?.maxBufferSize)!==null&&u!==void 0?u:100,v=a!=null&&a.consoleCapture?void 0:(c=o?.maxLogsPerInterval)!==null&&c!==void 0?c:1e3,E=x(v)?Math.max(m,2048):Math.max(m,v),w=o?.resourceAttributes;return{serviceName:(d=(h=w?.["service.name"])!==null&&h!==void 0?h:o?.serviceName)!==null&&d!==void 0?d:a?.serviceNameDefault,serviceVersion:(p=w?.["service.version"])!==null&&p!==void 0?p:o?.serviceVersion,environment:(f=w?.["deployment.environment"])!==null&&f!==void 0?f:o?.environment,resourceAttributes:w,beforeSend:o?.beforeSend,flushIntervalMs:g,maxBufferSize:m,maxQueueSize:E,maxBatchRecordsPerPost:100,rateCapWindowMs:g,maxLogsPerInterval:v,backgroundFlushBudgetMs:0,terminationFlushBudgetMs:0}})((s=this._instance)==null||(s=s.config)==null?void 0:s.logs,n);return[new Zh(this.hu(t,e),r,this.nu,(()=>this.du()),(o=>o()),void 0,i),r]}vu(){var t,e=(t=this._instance)==null||(t=t.config)==null?void 0:t.logs;if(!this.ou||this.cu!==e){var n;(n=this.ou)==null||n.reset(),this.cu=e;var i=this.uu((()=>this.tr),(s=>{this.tr=s}));this.ou=i[0],this.fu=i[1]}return this.ou}pu(){var t,e=(t=this._instance)==null||(t=t.config)==null?void 0:t.logs;if(!this.lu||this.gu!==e){var n;(n=this.lu)==null||n.reset(),this.gu=e;var i=this.uu((()=>this.su),(s=>{this.su=s}),{serviceNameDefault:"posthog-browser-logs",consoleCapture:!0},sc);this.lu=i[0],this.mu=i[1]}return this.lu}initialize(){this.loadIfEnabled()}onRemoteConfig(t){var e;if(t.ok){var n=(e=t.config.logs)==null?void 0:e.captureConsoleLogs;!B(n)&&n&&(this.iu=!0,this.loadIfEnabled())}}reset(){var t,e;this.tr=[],(t=this.ou)==null||t.reset(),this.su=[],(e=this.lu)==null||e.reset(),this.Sa=0}captureLog(t){this.vu().captureLog(t)}he(t){this.pu().captureLog(t)}get logger(){return this.yu||(this.yu={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.yu}flushLogs(t){t?this.bu(t):(this.ou&&this.ou.flush().catch((e=>this._u(e))),this.lu&&this.lu.flush().catch((e=>this._u(e))))}_u(t){rc(t)||this.rt.error("PostHog logs flush failed:",t)}loadIfEnabled(){if(this.iu&&!this.ru){var t=R?.__PosthogExtensions__;if(t){var e=t.loadExternalDependency;e?e(this._instance,"logs",(n=>{var i;n||(i=t.logs)==null||!i.initializeLogs?this.rt.error("Could not load logs script",n):(t.logs.initializeLogs(this._instance),this.ru=!0)})):this.rt.error(sa)}else this.rt.error("PostHog Extensions not found.")}}hu(t,e){var n=this._instance;return{get isDisabled(){return!1},get optedOut(){return!n.is_capturing()},getPersistedProperty:i=>i===pt.LogsQueue?t():void 0,setPersistedProperty(i,s){var r;i===pt.LogsQueue&&e((r=s)!==null&&r!==void 0?r:[])},Ot:i=>this.Ot(i),getLibraryId:()=>Y.LIB_NAME,getLibraryVersion:()=>Y.LIB_VERSION}}Ot(t){return new Promise((e=>{if(Vu(this.Sa,3))e({kind:"fatal",error:Or(void 0,"logs endpoint is unreachable, dropping batch")});else{var n=!1,i=r=>{n||(n=!0,clearTimeout(s),e(r))},s=setTimeout((()=>{this.rt.warn("Logs request timed out before receiving a response"),i({kind:"retry-later",error:Or(void 0,"logs request timed out")})}),9e4);this._instance._send_request({method:"POST",url:this.wu(),data:t,compression:"best-available",batchKey:"logs",fireCallbackOnDrop:!0,callback:r=>{var o=r.statusCode;if(this.ku(o),o>=200&&300>o)i({kind:"ok"});else if(o===413)i({kind:"too-large"});else if(o!==0&&o!==429&&500>o)i({kind:"fatal",error:new Error("logs request failed with status "+o)});else{var a;o===0?(r.error||this.rt.warn("Logs request failed before receiving an HTTP response"),i({kind:"retry-later",error:Or(r.error,"logs request failed before receiving an HTTP response")})):i({kind:"retry-later",error:(a=r.error)!==null&&a!==void 0?a:new Error("logs request failed with status "+o)})}}})}}))}ku(t){(t!==0||this._instance.__loaded)&&(this.Sa=Gu(t,this.Sa,3,(()=>this.rt.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."))))}bu(t){this.tr.length>0&&this.xu(t,this.tr,this.fu,Y.LIB_NAME,(e=>{this.tr=e})),this.su.length>0&&this.xu(t,this.su,this.mu,sc,(e=>{this.su=e}))}xu(t,e,n,i,s){if(e.length!==0){var r=e.map((a=>a.record));s([]);var o=vu(r,mu(n,Y.LIB_NAME,Y.LIB_VERSION),i,Y.LIB_VERSION);this._instance._send_request({method:"POST",url:this.wu(),data:o,compression:"best-available",batchKey:"logs",transport:t})}}wu(){return this._instance.requestRouter.endpointFor("api","/i/v1/logs")+"?token="+encodeURIComponent(this._instance.config.token)}du(){var t,e={};if(e.distinctId=this._instance.get_distinct_id(),this._instance.sessionManager){var n=this._instance.sessionManager.checkAndGetSessionAndWindowId(!0),i=n.windowId,s=n.sessionStartTimestamp,r=n.lastActivityTimestamp;e.sessionId=n.sessionId,e.windowId=i,B(s)||(e.sessionStartTimestamp=s),B(r)||(e.lastActivityTimestamp=r)}if(R!=null&&(t=R.location)!=null&&t.href&&(e.currentUrl=this._instance.config.disable_capture_url_hashes?Pt(R.location.href):R.location.href),this._instance.featureFlags){var o=this._instance.featureFlags.getFlags();o&&o.length>0&&(e.activeFeatureFlags=o)}return e}}},Jf={metrics:class{constructor(t){this.rt=ie("[metrics]"),this._instance=t}initialize(){}vu(){var t,e,n=(t=this._instance)==null||(t=t.config)==null?void 0:t.metrics;return this.ou&&this.cu===n||((e=this.ou)==null||e.reset(),this.cu=n,this.ou=new Xh(this.hu(),(function(i){var s,r,o,a,l,u=i?.resourceAttributes;return{serviceName:(s=u?.["service.name"])!==null&&s!==void 0?s:i?.serviceName,serviceVersion:(r=u?.["service.version"])!==null&&r!==void 0?r:i?.serviceVersion,environment:(o=u?.["deployment.environment"])!==null&&o!==void 0?o:i?.environment,resourceAttributes:u,beforeSend:i?.beforeSend,flushIntervalMs:(a=i?.flushIntervalMs)!==null&&a!==void 0?a:1e4,maxSeriesPerFlush:(l=i?.maxSeriesPerFlush)!==null&&l!==void 0?l:1e3}})(n),this.rt)),this.ou}count(t,e,n){e===void 0&&(e=1),this.vu().count(t,e,n)}gauge(t,e,n){this.vu().gauge(t,e,n)}histogram(t,e,n){this.vu().histogram(t,e,n)}flush(t){if(!this.ou)return Promise.resolve();if(t){var e=this.ou.drainWindow();return e&&this.Jt(e,t),Promise.resolve()}return this.ou.flush().catch((n=>this.rt.error("PostHog metrics flush failed:",n)))}reset(){var t;(t=this.ou)==null||t.reset()}hu(){var t=this._instance,e=this;return{get isDisabled(){return!1},get optedOut(){return!t.is_capturing()},Jt:n=>e.Jt(n),getLibraryId:()=>Y.LIB_NAME,getLibraryVersion:()=>Y.LIB_VERSION}}Jt(t,e){return new Promise((n=>{var i=!1,s=o=>{i||(i=!0,clearTimeout(r),n(o))},r=setTimeout((()=>s({kind:"retry-later",error:new Error("metrics request timed out")})),9e4);this._instance._send_request(b({method:"POST",url:this.Su(),data:t,compression:"best-available",batchKey:"metrics"},e&&{transport:e},{fireCallbackOnDrop:!0,callback(o){var a=o.statusCode;if(a>=200&&300>a)s({kind:"ok"});else if(a===413)s({kind:"too-large"});else if(a!==0&&a!==429&&500>a)s({kind:"fatal",error:new Error("metrics request failed with status "+a)});else{var l;s({kind:"retry-later",error:(l=o.error)!==null&&l!==void 0?l:new Error("metrics request failed with status "+a)})}}}))}))}Su(){return this._instance.requestRouter.endpointFor("api","/i/v1/metrics")+"?token="+encodeURIComponent(this._instance.config.token)}}},Yf=b({},Us,Bf,Df,jf,Uf,Hf,zf,Wf,qf,Vf,Gf,Kf,Jf);Re.__defaultExtensionClasses=b({},Yf);(function(){Y.SDK_DIST_CHANNEL="npm";var t=ti[un]=new Re;return(function(){function e(){e.done||(e.done=!0,bd=!1,Z(ti,(function(n){n._dom_loaded()})))}C!=null&&C.addEventListener?C.readyState==="complete"?e():re(C,"DOMContentLoaded",e,{capture:!1}):_&&k.error("Browser doesn't support `document.addEventListener` so PostHog couldn't be initialized")})(),t})();const Zf=["a[href]","button:not([disabled])","input:not([disabled]):not([type='hidden'])","select:not([disabled])","textarea:not([disabled])","[tabindex]:not([tabindex='-1'])"].join(",");let Je=null,Io=null,Sd="";const Co=new Map;function xd(t){return[...t.querySelectorAll(Zf)].filter(e=>!e.hidden&&e.getAttribute("aria-hidden")!=="true"&&e.getClientRects().length>0)}function Xf(t){for(const e of document.body.children)e===t||e.tagName==="SCRIPT"||(Co.set(e,{inert:e.inert,ariaHidden:e.getAttribute("aria-hidden")}),e.inert=!0,e.setAttribute("aria-hidden","true"))}function Qf(){for(const[t,e]of Co)t.inert=e.inert,e.ariaHidden===null?t.removeAttribute("aria-hidden"):t.setAttribute("aria-hidden",e.ariaHidden);Co.clear()}function kd(t){return t?.dataset.modalDismissible!=="false"&&t?.getAttribute("aria-busy")!=="true"}function Ve(t,e={}){const n=typeof t=="string"?document.getElementById(t):t;if(!n)return!1;Je&&Je!==n&&Xe(Je,{restoreFocus:!1,force:!0}),Io=e.trigger||document.activeElement,Je=n,Sd=document.body.style.overflow,Xf(n),document.body.style.overflow="hidden",n.classList.add("open"),n.setAttribute("aria-hidden","false");const i=n.querySelector(".modal-content");i&&(i.style.transform="scale(1) translateY(0)");const s=()=>{if(Je!==n)return;((e.initialFocus?n.querySelector(e.initialFocus):n.querySelector("[data-modal-initial-focus]"))||xd(n)[0]||n.querySelector(".modal-content")||n).focus({preventScroll:!0})};return requestAnimationFrame(s),setTimeout(s,260),!0}function Xe(t,e={}){const n=typeof t=="string"?document.getElementById(t):t;if(!n||!e.force&&!kd(n))return!1;n.classList.remove("open"),n.setAttribute("aria-hidden","true"),Qf(),document.body.style.overflow=Sd,Je=null;const i=Io;return Io=null,e.restoreFocus!==!1&&i?.isConnected&&i.focus({preventScroll:!0}),!0}function oc(t,e,n="Operation in progress"){const i=typeof t=="string"?document.getElementById(t):t;i&&(i.dataset.modalDismissible=e?"false":"true",i.setAttribute("aria-busy",String(!!e)),e?i.setAttribute("aria-label",n):i.removeAttribute("aria-label"))}function eg(t){if(!kd(t))return;const e=t.dataset.modalCloseHandler;e&&typeof window[e]=="function"?window[e]():Xe(t)}document.addEventListener("keydown",t=>{if(!Je)return;if(t.key==="Escape"){t.preventDefault(),t.stopImmediatePropagation(),eg(Je);return}if(t.key!=="Tab"){t.stopPropagation();return}const e=xd(Je);if(!e.length){t.preventDefault(),(Je.querySelector(".modal-content")||Je).focus();return}const n=e[0],i=e[e.length-1];t.shiftKey&&document.activeElement===n?(t.preventDefault(),i.focus()):!t.shiftKey&&document.activeElement===i&&(t.preventDefault(),n.focus())},!0);function tg(){document.querySelectorAll(".modal-overlay").forEach(t=>{t.setAttribute("role","dialog"),t.setAttribute("aria-modal","true"),t.setAttribute("aria-hidden",t.classList.contains("open")?"false":"true");const e=t.querySelector(".modal-content");e&&!e.hasAttribute("tabindex")&&(e.tabIndex=-1);const n=t.querySelector("h1, h2, h3");n&&(n.id||(n.id=`${t.id}-title`),t.setAttribute("aria-labelledby",n.id)),t.querySelectorAll(".modal-close").forEach(i=>{i.getAttribute("aria-label")||i.setAttribute("aria-label","Close dialog")})})}const Id="CodeFile",Cd="GeneratedCode",ng={CustomAction:"A",CustomWidget:"W",CustomFunction:"F",CustomClass:"C",CodeFile:"C"};function At(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function Ao(t){return String(t||"").trim().replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function ig(t={},e=0){const n=Ao(t.artifactType||t.type||Id),i=Ao(t.artifactName||t.name||t.fileName||`${Cd}-${e+1}`);return`${n||"artifact"}-${i||e+1}`}function Ad(t={},e=0){const n=At(t),i=n.artifactType||n.type||Id,s=n.artifactName||n.name||Cd;let r=n.fileName||s;return r.endsWith(".dart")||(r+=".dart"),{id:Ao(n.id)||ig({...n,artifactType:i,artifactName:s,fileName:r},e),artifactType:i,artifactName:s,fileName:r,deployPath:n.deployPath||"",description:n.description||"",code:n.code||n.content||"",dependencies:Fd(n.dependencies),imports:Array.isArray(n.imports)?n.imports:[],publicApi:Array.isArray(n.publicApi)?n.publicApi:[],relationships:Pd(n.relationships),deployStatus:n.deployStatus||"pending",review:n.review||null,metadata:At(n.metadata),codeType:n.codeType||ng[i]||"O"}}function Fd(t){return t?Array.isArray(t)?t.map(e=>{if(typeof e=="string")return{name:e,version:null,inferred:!1};const n=At(e),i=n.name||n.package;return i?{name:i,version:n.version||null,versionRequired:!!(n.versionRequired||n.required),inferred:!!n.inferred,...n.reason?{reason:n.reason}:{}}:null}).filter(Boolean):Object.entries(At(t)).map(([e,n])=>({name:e,version:n||null,inferred:!1})):[]}function Pd(t){return t?(Array.isArray(t)?t:[t]).map(e=>{const n=At(e);return!n.from&&!n.to?null:{from:n.from||null,to:n.to||null,type:n.type||"uses",description:n.description||""}}).filter(Boolean):[]}function Fo(t){if(typeof t!="string")return null;const e=t.trim();if(!e)return null;try{return JSON.parse(e)}catch{const n=e.match(/```(?:json)?\s*([\s\S]*?)```/i);if(!n)return null;try{return JSON.parse(n[1].trim())}catch{return null}}}function di(t,e={}){const n=[],i=typeof t=="string"?Fo(t):t,r=At(i||{});!i&&typeof t=="string"&&n.push("Structured bundle parse failed; using legacy single-artifact fallback.");const o=Array.isArray(r.artifacts)?r.artifacts:[{artifactType:r.artifactType||e.artifactType,artifactName:r.artifactName||e.artifactName,fileName:r.fileName||e.fileName,description:r.description,code:r.code||e.code||(typeof t=="string"?t:""),dependencies:r.dependencies||e.dependencies,relationships:r.relationships||e.relationships}];o.forEach((d,h)=>{!d?.artifactType&&!d?.type&&n.push(`Artifact ${h+1} has no artifactType; it will deploy as a standalone code file under lib/custom_code/ root.`)});const a=o.map((d,h)=>Ad(d,h)),l=new Map(o.map((d,h)=>[At(d).id,a[h]?.id]).filter(([d,h])=>d&&h)),u=d=>l.get(d)||d,c=Pd(r.relationships||e.relationships).map(d=>({...d,from:d.from?u(d.from):d.from,to:d.to?u(d.to):d.to}));return{schemaVersion:r.schemaVersion||e.schemaVersion||null,id:r.id||e.id||"bundle-current",title:r.title||r.name||e.title||"Generated artifact bundle",description:r.description||e.description||"",artifacts:a,dependencies:Fd(r.dependencies||e.dependencies),relationships:c,deployOrder:Array.isArray(r.deployOrder)?r.deployOrder.map(u):a.map(d=>d.id),warnings:[...n,...Array.isArray(r.warnings)?r.warnings:[]],metadata:At(r.metadata)}}function Ss(t){return di(t).artifacts[0]||Ad()}function Et(t){if(typeof t!="string")return t??"";const e=t.trim();if(!e)return"";try{return JSON.parse(e)}catch{return t}}function Sn(t){return JSON.stringify(t,null,2)}function sg(t){return Sn({task:"architect",userRequest:String(t??"")})}function rg(t){const e=Et(t);return e&&typeof e=="object"&&typeof e.task=="string"?Sn(e):Sn({task:"generate_bundle",bundleSpec:e})}function og(t){return Sn({task:"review_bundle",generatedBundle:Et(t),outputRequirements:{bundleReview:["status","score","summary","manualActions","findings"],scoreRange:[0,100],eachArtifact:["id","review.status","review.findings"],manualActions:{definition:"Setup the developer must perform by hand in the FlutterFlow editor that FlutterFlow will NOT do for them.",exclude:["creating the Custom Action, Widget or Code File itself - deploying the code creates it","declaring parameters or return values FlutterFlow derives from the function signature","anything that resolves as a side effect of using the action or widget in the editor","generic advice such as testing, reviewing or rebuilding the app"],preferEmpty:"Return an empty array when nothing qualifies - an empty list is the expected result for most bundles."}}})}function ha(t,e=null){const n={stage:t};return e!=null&&(n.bundle=Et(e)),n}function ag({bundleSpec:t,artifactBundle:e,bundleReview:n,artifactId:i,userFeedback:s}){return Sn({task:"regenerate_artifact",artifactId:i,bundleSpec:Et(t),artifactBundle:Et(e),bundleReview:Et(n),userFeedback:String(s)})}function $d({bundleSpec:t,artifactBundle:e,bundleReview:n,userFeedback:i}){return Sn({task:"regenerate_bundle",bundleSpec:Et(t),artifactBundle:Et(e),bundleReview:Et(n),userFeedback:String(i??"")})}const ac={csam:"child-safety content",dangerous:"dangerous content",harassment:"harassment",hate_speech:"hate speech",maliciousUrls:"a potentially malicious URL",malicious_uris:"a potentially malicious URL",pi_and_jailbreak:"prompt-injection or jailbreak instructions",promptInjection:"prompt-injection or jailbreak instructions",rai:"restricted content",sdp:"sensitive personal data",sexually_explicit:"sexually explicit content",virus_scan:"potentially malicious file content"},lg=["sanitizationResult","modelArmor","modelArmorResult","data","result","error"];function Le(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function cg(t){return Le(t)?typeof t.filterMatchState=="string"||typeof t.invocationResult=="string"||Array.isArray(t.matchedFilters)||Le(t.filterSummary)||Le(t.filterResults):!1}function Td(t,e=0){if(!Le(t)||e>3)return null;if(cg(t))return t;for(const n of lg){const i=t[n];if(Le(i)){const s=Td(i,e+1);if(s)return s}}return null}function xs(t){return Array.isArray(t)?t.some(xs):Le(t)?t.matched===!0||t.matchState==="MATCH_FOUND"?!0:Object.values(t).some(xs):!1}function Po(t){return Array.isArray(t)?t.some(Po):Le(t)?typeof t.executionState=="string"&&t.executionState!=="EXECUTION_SUCCESS"?!0:Object.values(t).some(Po):!1}function Rd(t){return{csamFilterFilterResult:"csam",maliciousUriFilterResult:"malicious_uris",piAndJailbreakFilterResult:"pi_and_jailbreak",raiFilterResult:"rai",sdpFilterResult:"sdp",virusScanFilterResult:"virus_scan"}[t]||t}function ug(t,e){if(Le(t))for(const[n,i]of Object.entries(t)){if(!Le(i))continue;const s=Le(i.categories)?i.categories:{},r=Object.entries(s).filter(([,o])=>Le(o)&&o.matched===!0).map(([o])=>o);r.length>0?r.forEach(o=>e.add(o)):i.matched===!0&&e.add(Rd(n))}}function dg(t,e){if(!t)return;const n=Array.isArray(t)?t.flatMap(i=>Le(i)?Object.entries(i):[]):Object.entries(t);for(const[i,s]of n){if(!xs(s))continue;const r=Rd(i),o=s?.raiFilterResult?.raiFilterTypeResults||(r==="rai"?s?.raiFilterTypeResults:null),a=Le(o)?Object.entries(o).filter(([,l])=>xs(l)).map(([l])=>l):[];a.length>0?a.forEach(l=>e.add(l)):e.add(r)}}function hg(t){return ac[t]?ac[t]:String(t).replace(/([a-z])([A-Z])/g,"$1 $2").replace(/_/g," ").toLowerCase()}function lc(t){return t.length<=1?t[0]||"content that did not pass":t.length===2?`${t[0]} and ${t[1]}`:`${t.slice(0,-1).join(", ")}, and ${t.at(-1)}`}function pg(t){const e=Td(t);if(!e)return null;const n=new Set(Array.isArray(e.matchedFilters)?e.matchedFilters:[]);ug(e.filterSummary,n),dg(e.filterResults,n);const i=e.blocked===!0||e.filterMatchState==="MATCH_FOUND"||n.size>0,s=e.invocationResult||null,r=Po(e.filterSummary||e.filterResults);return!i&&!r&&!["PARTIAL","FAILURE"].includes(s)?null:{kind:i?"blocked":"unavailable",invocationResult:s,matchedFilters:[...n]}}function fg(t,e){const n=pg(t);if(!n)return null;const i=[...new Set(n.matchedFilters.map(hg))],s=n.kind==="blocked",r=new Error(s?`Safety screening blocked this pipeline step for ${lc(i)}.`:"Safety screening could not be completed. Please try again.");return r.name="ModelArmorError",r.code=s?"MODEL_ARMOR_BLOCKED":"MODEL_ARMOR_UNAVAILABLE",r.isModelArmor=!0,r.pipelineStep=e,r.userTitle=s?"Request blocked for safety":"Safety check unavailable",r.userMessage=s?`The safety check detected ${lc(i)}. Edit your request to remove or rephrase the flagged content, then run the pipeline again.`:"The safety service did not finish all of its checks. Please wait a moment and run the pipeline again.",r.retryExplanation=s?"Trying another model would not change this safety decision.":"A fallback model was not attempted because safety screening must complete first.",r.matchedFilters=n.matchedFilters,r}function gg(t){return String(t||"").replace(/\/\*[\s\S]*?\*\//g,"").replace(/\/\/[^\n]*/g,"")}function cc(t){const e=/^(import|export|part|library|class|enum|extension|typedef|mixin|abstract|const|final|var|late)\b/,n=[];for(const i of gg(t).split(` -`)){if(!/^[A-Za-z_$]/.test(i)||e.test(i))continue;const s=i.match(/^[\w$<>,?\s[\]]+?\s([a-zA-Z_$][\w$]*)\s*\(/);s&&n.push(s[1])}return n}function pa(t,e){const n=t.replace(/\.dart$/,"");if(e==="W")return n.replace(/(^|_)(\w)/g,(i,s,r)=>r.toUpperCase());if(e==="A"){const i=n.replace(/(^|_)(\w)/g,(s,r,o)=>o.toUpperCase());return i.charAt(0).toLowerCase()+i.slice(1)}return e==="F"?"CustomFunctions":e==="C"?t.endsWith(".dart")?t:`${t}.dart`:n}async function uc(t){const e=new TextEncoder().encode(String(t||"")),n=await globalThis.crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(n),i=>i.toString(16).padStart(2,"0")).join("")}async function mg(t,e=new Map){const n={},i=new Set;for(const[o,a]of t.entries()){if(a.type==="D"||a.type==="O")continue;const l=pa(o,a.type),u={old_identifier_name:l,new_identifier_name:l,type:a.type,is_deleted:!1,current_checksum:await uc(a.content)},c=e.get(a.path);if(c!==void 0&&(u.original_checksum=await uc(c)),n[o]=u,a.type==="F"){const d=cc(a.content);(d.length>0?d:[a.functionName].filter(Boolean)).forEach(p=>i.add(p))}}const s=new Set(cc(e.get("lib/flutter_flow/custom_functions.dart")||"")),r={functions_to_rename:[],functions_to_delete:[],functions_to_add:Array.from(i).filter(o=>!s.has(o))};return{fileMapContents:JSON.stringify(n),functionsMapContents:JSON.stringify(r)}}const vg=new Set(["CustomWidget","CustomAction","CustomFunction","CustomClass","CodeFile"]),dc={CustomWidget:"custom_code/widgets/",CustomAction:"custom_code/actions/",CustomFunction:"flutter_flow/custom_functions.dart",CustomClass:"custom_code/",CodeFile:"custom_code/"},_g=new Set(["void","dynamic","String","int","double","num","bool","Color","DateTime","DateTimeRange","LatLng","FFPlace","FFUploadedFile","DocumentReference","List"]),yg=["Struct","Record"],wg=[{id:"required-public-param",severity:"error",message:"CustomWidget constructor uses `required` on a parameter FlutterFlow can leave unset. FlutterFlow omits unset Define Parameters fields from the constructor call, so the widget will not compile when placed. Make the parameter optional and nullable (`this.value` with `final double? value`), or give it a constructor default (`this.value = 0.0`).",detect:t=>Br(t).some(e=>/\brequired\s+this\.\w+/.test(e)),pos:"class W extends StatefulWidget { const W({required this.value}); final double value; }",neg:`class _P { const _P({required this.t}); final double t; } -class W extends StatefulWidget { const W({this.value}); final double? value; }`},{id:"non-nullable-public-field",severity:"error",message:"CustomWidget declares a non-nullable field with no constructor default. FlutterFlow omits unset Define Parameters fields, so the emitted call cannot supply it. Make the field nullable (`final double? value`) or give the parameter a default (`this.value = 0.0`).",detect:t=>Br(t).some(e=>{const n=/^\s*final\s+(?:double|int|String|bool|Color|num)\s+(\w+)\s*;/gm;let i;for(;(i=n.exec(e))!==null;){const s=i[1];if(!(new RegExp(`this\\.${s}\\s*=(?!=)`).test(e)||new RegExp(`[:,]\\s*${s}\\s*=(?!=)`).test(e)))return!0}return!1}),pos:`class W extends StatefulWidget { - const W({required this.value}); - final double value; -}`,neg:`class _P { - const _P({required this.t}); - final double t; -} -class W extends StatefulWidget { - const W({this.value = 1.0}); - final double value; -}`},{id:"asset-without-anchor",severity:"warning",message:'CustomWidget calls Image.asset with a path arriving as a String parameter. An asset reaches the build only when a FlutterFlow widget NODE references it - a filename passed as a parameter does not count, so the image renders as a broken-image icon on device. "Download Unused Project Assets" does not fix it (FlutterFlow issues 522, 2271, 3799). Keep something in the UI referencing the file, or load it over the network instead.',detect:t=>/Image\.asset\s*\(/.test(t)&&/final\s+String\??\s+\w*[Pp]ath\b/.test(t),pos:`class W extends StatefulWidget { final String? imagePath; } -var x = Image.asset(widget.imagePath);`,neg:`class W extends StatefulWidget { final String? imagePath; } -var x = Image.network(widget.imagePath);`},{id:"unsupported-param-type",severity:"error",message:"CustomWidget exposes a Flutter data type FlutterFlow cannot express as a Define Parameter: TextStyle, BoxShadow, FontWeight, FontStyle, TextDirection, TextAlign, EdgeInsets, Offset, Alignment/AlignmentGeometry, Border, BorderRadius, BoxDecoration, BoxConstraints, BorderSide, Gradient, or ThemeData. FlutterFlow's supported data types (docs.flutterflow.io/resources/data-representation/data-types) are only int, double, bool, string, Color, Image, DateTime, Json, LatLng, and the FF objects, so this parameter cannot be configured in the editor and the widget will not place or compile. Expose primitives instead (color, fontSize as double?, fontWeight via a custom enum, doubles for spacing).",detect:t=>Br(t).some(e=>/final\s+(TextStyle|BoxShadow|FontWeight|FontStyle|TextDirection|TextAlign|EdgeInsets|Offset|Alignment(?:Geometry)?|Border(?:Radius|Side)?|BoxDecoration|BoxConstraints|Gradient|LinearGradient|RadialGradient|ThemeData)\??\s+\w+\s*;/.test(e)),pos:`class W extends StatefulWidget { - const W({this.textStyle}); - final TextStyle? textStyle; - @override _S createState() => _S(); -} -class _S extends State { @override Widget build(BuildContext c) => const SizedBox(); }`,neg:`class W extends StatefulWidget { - const W({this.width}); - final double? width; - @override _S createState() => _S(); -} -class _S extends State { @override Widget build(BuildContext c) => Padding(padding: const EdgeInsets.all(8), child: const SizedBox()); }`}];function nt(t,e,n){return{artifactId:t.id,artifactName:t.artifactName,artifactType:t.artifactType,severity:e,message:n}}function hi(t){let e="",n=0;for(;n"&&(n--,n===0))return{inner:t.slice(e+1,i),end:i+1};return null}function Eg(t,e){const n=new RegExp(`class\\s+${e}\\b[^{]*\\{`).exec(t);if(!n)return null;let i=0;for(let s=n.index+n[0].length-1;sSg(t).usable);function kg(t=""){const e=hi(t);return xg.filter(n=>n.detect(e)).map(({id:n,severity:i,message:s})=>({id:n,severity:i,message:s}))}function Ig(t){const e=[],n=t.matchAll(/\bFuture\b/g);for(const i of n){let s=i.index+6,r=null;const o=s;for(;so;if(t[s]==="<"){const u=bg(t,s);if(!u||(r=u.inner.replace(/\s+/g," ").trim(),s=u.end,!/\s/.test(t[s]||"")))continue;for(;shc(o.functionName)===i);if(s)return s;const r=o=>!o.functionName.startsWith("_");return n.find(r)||n[0]}function Hs(t=""){return Array.from(hi(t).matchAll(/\b(?:class|enum)\s+([A-Za-z_]\w*)/g),e=>e[1])}function Cg(t="",e=""){return fa(t,e)?.returnType||null}function pc(t){return String(t||"").replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2").toLowerCase()}function Ag(t,e){const n=Hs(e);if(n.length===0)return null;const s=String(t||"").split("/").pop().replace(/\.dart$/,"");if(n.some(l=>pc(l)===s)||n.length>1)return null;const[o]=n,a=`${pc(o)}.dart`;return`File name "${t}" does not match declared class "${o}". FlutterFlow accepts this, but naming the file "${a}" keeps the Code File recognisable in the editor.`}function ga(t){return String(t||"").replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,"")}function Fg(t,e,n=""){const i=fa(e,n)?.functionName;if(!i)return null;const s=String(t||"").split("/").pop(),r=pa(s,"A");if(r===i)return null;const o=`${ga(i)}.dart`;return`File name "${s}" does not match Action "${i}". FlutterFlow derives the action from the file name, so it looks for "${r}" and reports Action "${r}" declaration not found. Rename the file to "${o}" - FlutterFlow puts an underscore before every capital - or rename the function to "${r}".`}function Pg(t="",e=""){return fa(t,e)!==null}function $g(t,e=new Set){return(t?.match(/[A-Za-z_]\w*/g)||[]).filter(i=>_g.has(i)?!1:!yg.some(r=>i.endsWith(r))||e.has(i))}function Tg(t,{functionName:e="",declaredTypes:n=new Set}={}){const i=Cg(t,e),s=$g(i,n);if(s.length===0)return null;const[r]=s;let o;return n.has(r)?o=`uses Code File type "${r}", which FlutterFlow cannot process as an Action Return Value`:i===r?o="is not a FlutterFlow Action Return Value":o=`uses type "${r}", which is not a FlutterFlow Action Return Value`,`CustomAction return type "${i}" ${o}. Return JSON (Future) or an existing FlutterFlow Data Type (*Struct) instead.`}function Rg(t,e={}){const n=[],i=t.fileName||"",s=t.code||"";if(vg.has(t.artifactType)||n.push(nt(t,"error",`Unsupported artifact type "${t.artifactType}".`)),i.endsWith(".dart")||n.push(nt(t,"error","FlutterFlow custom code artifacts must use .dart files.")),!s.trim())return n.push(nt(t,"warning","Generated artifact has no Dart code yet.")),n;if(t.artifactType==="CustomWidget"){/class\s+\w+\s+extends\s+(StatelessWidget|StatefulWidget)/.test(s)||n.push(nt(t,"warning","CustomWidget code should declare a widget class extending StatelessWidget or StatefulWidget."));for(const r of kg(s))n.push(nt(t,r.severity,r.message))}if(t.artifactType==="CustomAction"&&!Pg(s,t.artifactName)&&n.push(nt(t,"warning","CustomAction code should expose an async Future function callable from FlutterFlow.")),t.artifactType==="CustomAction"){const r=e.declaredTypes||new Set(Hs(s)),o=Tg(s,{functionName:t.artifactName,declaredTypes:r});o&&n.push(nt(t,"error",o));const a=Fg(i,s,t.artifactName);a&&n.push(nt(t,"error",a))}if(t.artifactType==="CustomFunction"&&/class\s+\w+\s+extends\s+(StatelessWidget|StatefulWidget)/.test(s)&&n.push(nt(t,"warning","CustomFunction should be a callable function, not a widget class.")),t.artifactType==="CustomClass"||t.artifactType==="CodeFile"){const r=Ag(i,s);r&&n.push(nt(t,"info",r))}return n}function Ng(t){const e=Array.isArray(t?.artifacts)?t.artifacts:[],n=new Set(e.flatMap(r=>Hs(r.code||""))),i=e.flatMap(r=>Rg(r,{declaredTypes:n})),s=e.map(r=>({artifactId:r.id,fileName:r.fileName,pathHint:dc[r.artifactType]||dc.CodeFile}));return{valid:i.every(r=>r.severity!=="error"),findings:i,deployHints:s}}const fc="// DO NOT REMOVE OR MODIFY THE CODE ABOVE!";function gc(t){return(/^\s*import\s+['"]([^'"]+)['"]/.exec(t)||[])[1]||null}function Mg(t=""){const e=t.indexOf(fc);return e===-1?t:t.slice(e+fc.length).replace(/^\s*\n/,"")}const Lg=/^\s*import\s+['"][^'"]+['"]\s*;\s*(?:\/\/.*)?$/;function Og(t="",e=""){const n=Mg(t),i=new Set((e.match(/^\s*import .*$/gm)||[]).map(gc).filter(Boolean)),s=n.split(` -`).filter(r=>{const o=gc(r);return o===null||!i.has(o)?!0:!Lg.test(r)}).join(` -`).replace(/^\s*\/\/ Automatic FlutterFlow imports\s*$/m,"").replace(/^\s*\n+/,"");return e+s}const Bg=new Set(["flutter","flutter_test","flutter_driver","flutter_localizations"]);function Nd(t){let e="",n=0;for(;n{const i=n.name||n.package;if(!i||i==="flutter")return e;const s=n.versionRequired||n.required;return e[i]=s&&n.version||"",e},{})}function Wg(t){const e=new Map,n=new Map,i=[];for(const s of t)e.has(s.fileName)?i.push(`Duplicate deploy file name "${s.fileName}" for artifacts "${e.get(s.fileName)}" and "${s.artifactId}".`):e.set(s.fileName,s.artifactId),n.has(s.path)?i.push(`Duplicate deploy path "${s.path}" for artifacts "${n.get(s.path)}" and "${s.artifactId}".`):n.set(s.path,s.artifactId);return i}function zg(t,e={}){const n=Array.isArray(t?.artifacts)?t.artifacts:[],s=(e.selectedArtifactIds||t?.deployOrder||n.map(p=>p.id)).map(p=>n.find(f=>f.id===p)).filter(Boolean),r=[...t?.warnings||[]];let o=[];s.forEach(p=>{const f=Hg(p),g=p.fixedCode||p.code||"",m=p.codeType||jg[p.artifactType]||Ne.OTHER;g.trim()||r.push(`${p.artifactName||p.id} has no generated code.`),o.push({artifactId:p.id,artifactName:p.artifactName,artifactType:p.artifactType,fileName:f,content:g,type:m,path:p.deployPath||Ug(f,m),deployPath:p.deployPath||"",deployMode:"customCodeSync"})});const a="lib/flutter_flow/custom_functions.dart",l=o.map((p,f)=>({entry:p,index:f})).filter(({entry:p})=>p.type===Ne.FUNCTION&&p.path===a);if(l.length>1){const p=l[0],f={...p.entry,artifactId:l.map(({entry:m})=>m.artifactId).join("+"),artifactName:p.entry.artifactName,content:l.map(({entry:m})=>`// ${m.artifactId} -${m.content}`).join(` - -`)},g=new Set(l.slice(1).map(({index:m})=>m));o=o.filter((m,v)=>!g.has(v)),o[p.index]=f}const u={...mc(t?.dependencies),...s.reduce((p,f)=>({...p,...mc(f.dependencies)}),{})},c={};s.forEach(p=>{ma(p.code||"").forEach(f=>{f in u||(c[f]="")})});const d={...c,...u},h=Wg(o);return{bundleId:t?.id||"bundle-current",title:t?.title||"Generated artifact bundle",fileEntries:o,dependencies:d,relationships:t?.relationships||[],warnings:r,errors:h}}function qg(t){return String(t||"").match(/\bclass\s+([A-Z][A-Za-z0-9_]*)\b/)?.[1]}function Vg(t){return String(t||"").split("/").pop().replace(/\.dart$/,"").split(/[^A-Za-z0-9]+/).filter(Boolean).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join("")}function Gg(t,e){const i=[Vg(t),qg(e.content),e.artifactName].find(s=>/^[A-Z][A-Za-z0-9_]*$/.test(String(s||"")));if(!i)throw new Error(`Cannot derive a FlutterFlow custom class name for ${t}.`);return i}function Kg(t,e=new Map){const n=[];for(const[i,s]of t.entries())s.type!=="C"||e.has(s.path)||n.push({artifactId:s.artifactId||i,className:Gg(i,s),content:s.content,fileName:i,path:s.path});return n}function Jg(t,e){const n=new Set(e.map(i=>i.path));return new Map(Array.from(t.entries()).filter(([,i])=>!n.has(i.path)))}const vc={pass:0,warning:1,fail:2},Yg=["manualActions"];function Be(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function _t(...t){for(const e of t){if(typeof e=="string"&&e.trim())return e.trim();if(Array.isArray(e)&&e.length>0){const n=e.filter(i=>typeof i=="string").join(` -`);if(n)return n}}return""}function st(t){return t==null?[]:Array.isArray(t)?t:[t]}function Zg(t){const e=Be(t).value??t;if(e==null||typeof e=="string"&&e.trim()==="")return null;const n=Number(e);if(Number.isFinite(n))return n;const i=String(t||"").match(/\bscore\b[^\d]{0,12}(\d{1,3})(?:\s*\/\s*100)?/i);return i?Number(i[1]):null}function We(t){return String(t||"").trim().replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function va(t){const e=String(t||"").toLowerCase();return/(fail|error|critical|block|reject|invalid)/.test(e)?"fail":/(warn|attention|manual|partial|incomplete|concern)/.test(e)?"warning":/(pass|success|ready|approve|valid|clean|info|notice)/.test(e)?"pass":null}function $o(...t){return t.filter(Boolean).reduce((e,n)=>vc[n]>vc[e]?n:e,"pass")}function Md(t,e="warning",n="review"){if(typeof t=="string")return{severity:e,message:t,suggestion:"",source:n};const i=Be(t),s=_t(i.message,i.title,i.issue,i.description,i.summary);return s?{severity:va(i.severity||i.status||i.level)||e,message:s,suggestion:_t(i.suggestion,i.fix,i.recommendation,i.action),source:i.source||n}:null}function To(t,e="review"){const n=Be(t);return[["findings","warning"],["issues","warning"],["criticalIssues","fail"],["errors","fail"],["warnings","warning"],["recommendations","warning"],["requiredFixes","fail"],["suggestions","warning"]].flatMap(([s,r])=>st(n[s]).map(o=>Md(o,r,e)).filter(Boolean))}function Xg(t,e,n=null){if(typeof t=="string")return{id:`${n||"bundle"}-manual-${e+1}`,title:t,detail:"",location:"",timing:"unspecified",artifactId:n,source:"Code Review"};const i=Be(t),s=_t(i.title,i.action,i.step,i.message,i.name,i.description);return s?{id:i.id||`${n||"bundle"}-manual-${e+1}`,title:s,detail:_t(i.detail,i.instructions,i.description),location:_t(i.location,i.flutterFlowPath,i.path),timing:_t(i.timing,i.phase)||"unspecified",artifactId:n,source:_t(i.source)||"Code Review"}:null}function Ro(t,e=null){const n=Be(t);return Yg.flatMap(i=>st(n[i])).map((i,s)=>Xg(i,s,e)).filter(Boolean)}function Qg(t){let e=typeof t=="string"?Fo(t):t;if(!e&&typeof t=="string")return{rawText:t,root:{}};const n=Be(e);typeof n.content=="string"&&(e=Fo(n.content)||e);const i=Be(e),s=Be(i.reviewResult||i.codeReview||i.result);return{rawText:"",root:Object.keys(s).length?s:i}}function em(t,e){const n=[e.id,e.fileName,e.artifactName].map(We);return t.find(i=>{const s=Be(i);return[s.id,s.fileName,s.artifactName,s.name].map(We).some(r=>r&&n.includes(r))})||null}function tm(t,e){return st(t?.metadata?.compatibility?.deployHints).find(s=>We(s?.artifactId)===We(e.id)||We(s?.fileName)===We(e.fileName))?.pathHint||""}function nm(t,e){return st(t?.relationships).filter(n=>We(n?.from)===We(e.id)||We(n?.to)===We(e.id))}function im(t,e){return st(t?.metadata?.compatibility?.findings).filter(n=>!n?.artifactId||We(n.artifactId)===We(e.id)).map(n=>Md(n,"warning","Compatibility check")).filter(Boolean)}function sm(t,e,n,i){const s=em(e,n),r=Be(s?.review||s||n.review),o=Object.keys(r).length>0,a=[...To(r),...im(t,n)],l=Ro(r,n.id),u=va(r.status||r.verdict||r.outcome||r.result),c=a.length?$o(...a.map(h=>h.severity)):null,d=$o(u,c,o?null:"warning");return{...n,index:i,status:d,statusReason:o?_t(r.summary,r.overview,r.assessment,r.conclusion)||(a.length?`${a.length} review finding${a.length===1?"":"s"}`:"No file-level findings"):"No file-level verdict was returned",reviewComplete:o,findings:a,manualSteps:l,fixedSource:typeof r.fixedSource=="string"&&r.fixedSource.trim()?r.fixedSource.trim():null,pathHint:tm(t,n),relationships:nm(t,n)}}function rm({status:t,score:e,artifactPresentations:n,manualSteps:i}){const s=n.length;if(s===0&&i.length===0)return e==null?"Code review returned no overall summary and no score.":`Reviewed bundle with score ${e}/100.`;const r=n.reduce((a,l)=>(a[l.status]+=1,a),{pass:0,warning:0,fail:0}),o=[];return t&&o.push(`Overall verdict: ${t}.`),s&&o.push(`${s} artifact${s===1?"":"s"}: ${r.pass} pass, ${r.warning} warn, ${r.fail} fail.`),i.length&&o.push(`Do before deploy: ${i.map(a=>a.title).join("; ")}.`),e==null&&o.push("No numeric score (0-100) was returned."),o.join(" ")}function om({bundle:t,reviewResult:e}){const n=Be(t),i=st(n.artifacts),{root:s,rawText:r}=Qg(e),o=[s.bundleReview,s.overallReview,s.overall,s.bundleSummary,s.summaryReview,s.review].map(Be).find(w=>Object.keys(w).length)||{},a=st(s.artifacts||s.files||s.reviews),l=i.map((w,I)=>sm(n,a,w,I)),u=To(s),d=[...To(o),...u],h=[...Ro(o),...Ro(s),...l.flatMap(w=>w.manualSteps)].filter((w,I,A)=>A.findIndex(F=>F.title===w.title&&F.artifactId===w.artifactId)===I),p=va(o.status||o.verdict||o.overallStatus||s.status||s.verdict||s.overallStatus||s.outcome),f=$o(p,...d.map(w=>w.severity),...l.map(w=>w.status)),g=o.score??s.score??s.overallScore??r,m=Zg(g),v=_t(o.headline,o.summary,o.executiveSummary,o.overview,o.assessment,o.conclusion,s.overallSummary,s.headline,s.summary,s.executiveSummary,s.overview,s.assessment,s.conclusion,r)||rm({status:f,score:m,artifactPresentations:l,manualSteps:h}),E=l.reduce((w,I)=>(w[I.status]+=1,w),{pass:0,warning:0,fail:0});return{title:n.title||"Generated artifact bundle",description:n.description||"",status:f,score:m,summary:v,findings:d,manualSteps:h,artifacts:l,counts:E,reviewCoverage:{reviewed:l.filter(w=>w.reviewComplete).length,total:l.length},deployOrder:st(n.deployOrder),relationships:st(n.relationships),warnings:st(n.warnings),compatibility:Be(n.metadata?.compatibility)}}const am=/^\uFEFF/;function Hn(t){let e=0,n=t.length;for(;ee&&!t[n-1].trim();)n--;return t.slice(e,n).join(` -`)}function lm(t){const e=String(t??"").replace(am,"");if(!e.trim())return"";const n=e.split(` -`),i=c=>{const d=c.trim();return/^`{3,}[A-Za-z0-9+#_.-]*$/.test(d)?c.length-c.trimStart().length:-1};let s=0,r=-1;const o=[];{let c=0;for(let d=0;d=0&&(s++,r<0&&(r=d),o.push(c+h)),c+=n[d].length+1}}if(s===0)return Hn(n);{const c=No(e);if(!c.error&&o.every(h=>yc(h,c.commentAndStringRanges)))return Hn(n)}if(s===1){const c=Hn(n.slice(0,r)),d=Hn(n.slice(r+1));return d.length>=c.length?d:c}const a=[];let l=null;for(let c=0;cc.length>0);return u.length===0?"":u.join(` - -`)}function cm(t){return String(t??"").replace(/\/\*[\s\S]*?\*\//g," ").replace(/\/\/[^\n]*/g,"").replace(/'''[\s\S]*?'''/g,'""').replace(/"""[\s\S]*?"""/g,'""').replace(/'(?:\\.|[^'\\\n])*'/g,'""').replace(/"(?:\\.|[^"\\\n])*"/g,'""')}function Ld(t){const e=cm(t);return Array.from(e.matchAll(/class\s+([A-Z]\w*)\s+extends\s+[A-Za-z_]\w*Widget\b/g),n=>n[1])}function Od(t){return`${ga(t)}.dart`}function um(t){return pa(t,"W")}const _c={"(":")","[":"]","{":"}"},dm={")":"(","]":"[","}":"{"},hm=/[A-Za-z0-9_]/;function No(t){const e=[{kind:"code",opener:null,openedLine:0}],n=[];let i=1,s=0;const r=(c,d)=>{(c===` -`||c==="\r"&&d!==` -`)&&i++};let o=null;const a=()=>{for(const c of e)(c.kind==="string"||c.kind==="block-comment"||c.kind==="line-comment")&&n.push({start:c.startIndex,end:t.length})};for(;s0?t[s-1]:"",f=s>1?t[s-2]:"",g=(p==="r"||p==="R")&&!hm.test(f);e.push({kind:"string",quote:c,triple:h,raw:g,startIndex:s,openedLine:i}),s+=h?3:1;continue}if(_c[c]){e.push({kind:"code",opener:c,openedLine:i}),s++;continue}if(dm[c]){if(d.interpolation&&c==="}"){e.pop(),s++;continue}if(d.opener&&_c[d.opener]===c){e.pop(),s++;continue}return d.opener?(a(),{error:o??`line ${i}: "${c}" closes nothing - "${d.opener}" opened on line ${d.openedLine} is still open`,commentAndStringRanges:n}):(a(),{error:o??`line ${i}: unexpected "${c}" with no matching opener`,commentAndStringRanges:n})}r(c,t[s+1]),s++}a();let l=e.length-1;for(;l>0&&e[l].kind==="line-comment";)l--;let u=o;if(!u){const c=e[l];if(!(c.kind==="code"&&!c.opener&&!c.interpolation))if(c.kind==="string")u=`unclosed ${c.triple?"triple-quoted ":""}string starting on line ${c.openedLine} was never closed`;else if(c.kind==="block-comment")u=`unterminated /* comment starting on line ${c.openedLine}`;else if(c.interpolation){const d=e.findLast(p=>p.opener);u=`unclosed "\${" expression${d?` opened on line ${d.openedLine}`:""} was never closed`}else u=`"${c.opener}" opened on line ${c.openedLine} is never closed`}return{error:u,commentAndStringRanges:n}}function pm(t){return No(String(t??"")).error}function yc(t,e){return e.some(({start:n,end:i})=>t>=n&&ttypeof n=="string"?n:n?.errorMessage).filter(Boolean);return e.length>0?e.join("; "):JSON.stringify(t)}return t&&typeof t=="object"?t.errorMessage||JSON.stringify(t):String(t??"")}const fm=["gmail.com","googlemail.com","outlook.com","hotmail.com","live.com","msn.com"],gm="MAGIC_LINK_SENT",mm="PLUS_ALIAS_REJECTED",vm="Please enter your primary email address. Plus aliases (such as {email}) are not allowed for {domain} accounts.",Ws={allowlistedDomains:fm,successCode:gm,validationCode:mm,messageTemplate:vm},_m=new Set(Ws.allowlistedDomains),ym=Ws.successCode,Ki=Ws.validationCode;function zs(t){return typeof t=="string"?t.trim():""}function wm(t){const e=zs(t),n=e.lastIndexOf("@");if(n<=0||n===e.length-1)return!1;const i=e.slice(0,n),s=e.slice(n+1).toLowerCase();return _m.has(s)?i.includes("+"):!1}function bm(t,e){return Ws.messageTemplate.replaceAll("{email}",t).replaceAll("{domain}",e)}function Dd(t){if(!wm(t))return null;const e=zs(t),n=e.lastIndexOf("@"),i=e.slice(n+1).toLowerCase();return bm(e,i)}function Em(t,e){return t?.code===Ki?t.message||Dd(e)||"Please enter your primary email address.":t?.code===ym||!t?.code?`Check your email — we sent a link to ${zs(e)}`:t.message||"Something went wrong. Please try again."}const Sm=/^dependencies\s*:\s*(?:#.*)?$/,xm=/^(?:"([^"]+)"|'([^']+)'|([A-Za-z_][A-Za-z0-9_-]*))\s*:/;function qs(t){const e=t.match(xm);return e?e[1]??e[2]??e[3]:null}function _i(t){const e=t.trim();return e===""||e.startsWith("#")}function Fn(t){const e=t.match(/^(\s*)/);return e?e[1].length:0}function _a(t,e){const n=t.findIndex(r=>e.test(r));if(n===-1)return null;let i=n,s=null;for(let r=n+1;r=0.0.0"}`}function Am(t,e={}){const n=String(t||""),i=Object.entries(e).filter(([u])=>u&&u!=="flutter");if(i.length===0)return{yaml:n,added:[],alreadyPresent:[]};const s=n.split(` -`),r=new Set(Ud(n)),o=[],a=[];for(const[u,c]of i)r.has(u)?a.push(u):(o.push([u,c]),r.add(u));if(o.length===0)return{yaml:n,added:[],alreadyPresent:a};const l=ya(s);if(l){const u=o.map(([c,d])=>wc(l.childIndent,c,d));s.splice(l.endIndex,0,...u)}else s.length>0&&s[s.length-1].trim()!==""&&s.push(""),s.push("dependencies:"),o.forEach(([u,c])=>{s.push(wc(" ",u,c))});return{yaml:s.join(` -`),added:o.map(([u])=>u),alreadyPresent:a}}function Fm(t,e={}){const n=String(t||""),i=Object.entries(e).filter(([l])=>l&&l!=="flutter");if(i.length===0)return{yaml:n,overridden:[],skipped:[]};const s=n.split(` -`),r=Gs(n),o=[],a=[];for(const[l,u]of i){const c=r.get(l);if(!c||!c.isScalar||!String(u||"").trim()){a.push(l);continue}const d=" ".repeat(Fn(s[c.lineIndex]));s[c.lineIndex]=`${d}${l}: ${Wd(String(u).trim())}${c.comment}`,o.push({name:l,from:c.constraint,to:u})}return{yaml:s.join(` -`),overridden:o,skipped:a}}function zd(t){const e=String(t||""),n=[];return e.trim()?(/^name:\s*\S+/m.test(e)||n.push("pubspec.yaml missing name field"),ya(e.split(` -`))||n.push("pubspec.yaml missing dependencies section"),Ud(e).includes("flutter")||n.push("pubspec.yaml missing Flutter SDK dependency"),{valid:n.length===0,errors:n}):(n.push("pubspec.yaml is empty"),{valid:!1,errors:n})}const Pm=">=3.0.0 <4.0.0";function Mo(t){const e=String(t||"").trim(),n=e[0];return n!=="'"&&n!=='"'||e[e.length-1]!==n?e:e.slice(1,-1).replaceAll(`${n}${n}`,n)}function $m(t=""){const e=Dg(t).filter(n=>!n.startsWith("dart:")&&!n.startsWith("package:"));return{selfContained:e.length===0,unresolvableImports:e}}function bc(t,e,n){const i=[];for(const[s,r]of t){if(r.isScalar){e[s]=Mo(r.constraint);continue}if(r.sourceKey==="sdk"){n.add(s);continue}if(r.sourceKey===null&&r.version){e[s]=Mo(r.version);continue}i.push(s)}return i}function Tm(t){const e=new Set,n={},i={},s=bc(Gs(t),n,e);s.push(...bc(Im(t,"dependency_overrides"),i,e));const r=new Set([...Object.keys(n),...e]),{sdk:o}=Hd(t);return{sdkConstraint:Mo(o)||Pm,dependencies:n,overrides:i,sdkPackages:[...e].sort(),availablePackages:r,unrepresentable:s}}function Rm(t,e,n){return e.length>0?`${t} imports ${e.join(", ")}, which FlutterFlow only generates once the app is built, so it could not be compiled before the deploy.`:`${t} imports ${n.join(", ")}, which your project's pubspec.yaml does not declare with a version constraint, so it could not be compiled before the deploy.`}function Nm(t,e){const{sdkConstraint:n,dependencies:i,overrides:s,sdkPackages:r,availablePackages:o,unrepresentable:a}=Tm(e),l={sdkConstraint:n,dependencies:i,overrides:s,sdkPackages:r},u=[],c=[];for(const d of t){const{className:h,content:p}=d,f=ma(p);if(a.length>0&&f.length>0){const v=f.filter(E=>a.includes(E));c.push({className:h,reason:v.length>0?`${h} was not compiled before deploying: it imports ${v.join(", ")}, which your project declares from a source that cannot be reproduced outside it, so package resolution could not be matched exactly.`:`${h} was not compiled before deploying: your project declares ${a.join(", ")} from a source that cannot be reproduced outside it, so the package graph ${h} would compile against could not be matched exactly.`});continue}const{unresolvableImports:g}=$m(p),m=f.filter(v=>!o.has(v));if(g.length>0||m.length>0){c.push({className:h,reason:Rm(h,g,m)});continue}u.push({fileName:`${ga(h)}.dart`,content:p})}return{manifest:l,sources:u,skipped:c}}function Ec(t,e){const n=`${t}${e}`.split(` -`),i=n.pop()??"",s=[];for(const r of n){const o=qd(r);o&&s.push(o)}return{events:s,buffer:i}}function Mm(t){const e=qd(t);return e?[e]:[]}function qd(t){const e=t.trim();if(!e)return null;try{const n=JSON.parse(e);return n&&typeof n=="object"&&!Array.isArray(n)?n:null}catch{return null}}async function Lm(t,e={}){const{onPhase:n,onLog:i}=e;let s=null,r="";const o=a=>{if(a.event==="phase"){a.message&&n&&n(a.message);return}if(a.event==="log"){a.message&&i&&i(a.message);return}s=a};if(t.body?.getReader){const a=t.body.getReader(),l=new TextDecoder;for(;;){const{done:u,value:c}=await a.read();if(u)break;const d=Ec(r,l.decode(c,{stream:!0}));r=d.buffer,d.events.forEach(o)}}else{const a=Ec("",await t.text());r=a.buffer,a.events.forEach(o)}return Mm(r).forEach(o),s?{...s,success:s.success===!0||s.success===void 0&&t.ok}:{success:!1,error:t.ok?"The FlutterFlow deploy runner closed the connection before it finished.":`FlutterFlow custom class provisioning failed (HTTP ${t.status}).`}}const Om=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;function St(t){const e=String(t||"").trim().match(Om);return e?{major:Number(e[1]),minor:Number(e[2]),patch:Number(e[3]),prerelease:e[4]?e[4].split("."):[]}:null}function Bm(t,e){if(t.length===0&&e.length===0)return 0;if(t.length===0)return 1;if(e.length===0)return-1;for(let n=0;n0)}function jm(t){const e=St(t);return e?e.major>0?`${e.major+1}.0.0`:`0.${e.minor+1}.0`:null}function wa(t){let e=String(t??"").trim();if((e.startsWith("'")||e.startsWith('"'))&&(e=e.slice(1,-1).trim()),e===""||e==="any"||e==="*")return{min:null,minInclusive:!1,max:null,maxInclusive:!1};if(e.startsWith("^")){const o=e.slice(1).trim();return St(o)?{min:o,minInclusive:!0,max:jm(o),maxInclusive:!1}:null}if(St(e))return{min:e,minInclusive:!0,max:e,maxInclusive:!0};const n={min:null,minInclusive:!1,max:null,maxInclusive:!1},i=/(>=|<=|>|<)\s*([0-9][0-9A-Za-z.+-]*)/g;let s=!1,r;for(;(r=i.exec(e))!==null;){const[,o,a]=r;if(!St(a))return null;s=!0,o===">="||o===">"?(n.min=a,n.minInclusive=o===">="):(n.max=a,n.maxInclusive=o==="<=")}return s?n:null}function Sc(t,e){const n=wa(t);if(!n||!St(e))return!1;if(n.min!==null){const i=ks(e,n.min);if(i<0||i===0&&!n.minInclusive)return!1}if(n.max!==null){const i=ks(e,n.max);if(i>0||i===0&&!n.maxInclusive)return!1}return!0}function Um(t,e){const n=wa(t);if(!n||!St(e))return!1;if(n.max===null)return!0;const i=ks(n.max,e);return i>0?!0:i===0&&n.maxInclusive}function ln(t){const e=wa(t);return e?e.min:null}const Hm="https://pub.dev/api/packages/",Wm=8e3;function zm(t,e={}){const{dartSdkFloor:n=null,flutterSdkFloor:i=null}=e,s=Array.isArray(t?.versions)?t.versions:[];let r=null;for(const o of s){const a=o?.version;if(!a||o.retracted||Dm(a))continue;const l=o.pubspec?.environment||{};n&&l.sdk&&!Sc(l.sdk,n)||i&&l.flutter&&!Sc(l.flutter,i)||(!r||ks(a,r)>0)&&(r=a)}return r?{version:r,constraint:`^${r}`}:null}async function qm(t,e={}){const{dartSdkFloor:n=null,flutterSdkFloor:i=null,fetchImpl:s=fetch}=e;let r;try{const a=await s(`${Hm}${encodeURIComponent(t)}`,{signal:AbortSignal.timeout(Wm)});if(!a.ok)return{name:t,constraint:null,version:null,error:a.status===404?`"${t}" was not found on pub.dev`:`pub.dev returned ${a.status} for "${t}"`};r=await a.json()}catch(a){return{name:t,constraint:null,version:null,error:`could not reach pub.dev for "${t}" (${a.message})`}}const o=zm(r,{dartSdkFloor:n,flutterSdkFloor:i});return o?{name:t,...o,error:null}:{name:t,constraint:null,version:null,error:n?`no published "${t}" release supports Dart ${n}`:`no published "${t}" release could be read`}}async function Vm(t,e={}){const n=await Promise.all(t.map(i=>qm(i,e)));return new Map(n.map(({name:i,...s})=>[i,s]))}async function Gm(t,e={},n={}){const{resolveVersions:i=Vm}=n,s=Object.entries(e).filter(([c])=>c&&c!=="flutter"),r=Hd(t),o={dartSdkFloor:ln(r.sdk),flutterSdkFloor:ln(r.flutter)},a={additions:{},overrides:{},kept:[],warnings:[],sdk:o};if(s.length===0)return a;const l=Gs(t),u=[];for(const[c,d]of s){const h=l.get(c);if(!h){u.push(c);continue}const p=ln(d);if(!p){a.kept.push({name:c,constraint:h.constraint});continue}if(!h.isScalar){a.warnings.push(`"${c}" is declared in your project from a git, path, or SDK source, but the generated code needs at least ${p}. Left as-is — update it yourself if the build fails.`),a.kept.push({name:c,constraint:h.constraint});continue}if(Um(h.constraint,p)){a.kept.push({name:c,constraint:h.constraint});continue}a.overrides[c]=`^${p}`,a.warnings.push(`"${c}" was pinned to ${h.constraint} in your project, which cannot resolve the ${p} the generated code needs. Raising it to ^${p} — this changes a dependency the rest of your app also uses.`)}if(u.length>0){const c=await i(u,o);for(const d of u){const h=c.get(d);if(h?.constraint){a.additions[d]=h.constraint;continue}const p=e[d]||"";if(ln(p)){a.additions[d]=`^${ln(p)}`,a.warnings.push(`Could not confirm "${d}" version on pub.dev (${h?.error||"lookup failed"}). Using ^${ln(p)} from the AI's recommendation — verify this is current.`);continue}a.additions[d]=">=0.0.0",a.warnings.push(`Could not determine a version for "${d}" (${h?.error||"lookup failed"}) and the AI supplied none. Added with a wide-open >=0.0.0 constraint — pin a concrete version in FlutterFlow before deploying.`)}}return a}const Km={"&":"&","<":"<",">":">",'"':""","'":"'"};function xt(t){return String(t??"").replace(/[&<>"']/g,e=>Km[e])}function j(t){return t?xt(t).replace(/\n/g,"
    "):""}function Ft(t){return xt(t).replace(/\r?\n/g," ")}function Jm(t,e={}){const n=t?.pipelineStep;if(n!=null&&e[n]!=null)return e[n];const i=t?.message||"";return i.includes("Code Generator")?2:i.includes("Code Review")?3:1}function Ym(t){const e={"Integration Audit Report":"📋","Critical Issues":"❌",Warnings:"⚠️",Recommendations:"✅","Overall Score":"📊"};for(const[n,i]of Object.entries(e))if(t.toLowerCase().includes(n.toLowerCase()))return i;return"📄"}function Zm(t){const e={critical:"❌",warning:"⚠️",recommendation:"✅",score:"📊",issue:"🔍",fix:"🔧"};for(const[n,i]of Object.entries(e))if(t.toLowerCase().includes(n.toLowerCase()))return i;return"📝"}function Xm(t){return t.includes("class ")&&t.includes("extends ")||t.includes("StatelessWidget")||t.includes("StatefulWidget")||t.includes("import 'package:flutter/")?"dart":t.includes("def ")||t.includes("import ")||t.includes("print(")?"python":t.includes("function ")||t.includes("const ")||t.includes("console.")?"javascript":"dart"}function xn(t){if(!t)return"";if(typeof t!="string")return String(t);const e=/```(?:\w+)?\n?([\s\S]*?)```/,n=t.match(e);return n?n[1].trim():t.trim()}function xc(t){return t=xt(t),t=t.replace(/\*\*(.*?)\*\*/g,'$1'),t=t.replace(/\*(.*?)\*/g,'$1'),t=t.replace(/`(.*?)`/g,'$1'),t=t.replace(/\b(FAIL|ERROR|CRITICAL)\b/g,'$1'),t=t.replace(/\b(WARN|WARNING)\b/g,'$1'),t=t.replace(/\b(PASS|SUCCESS|OK)\b/g,'$1'),t}function Vd(t,e="dart",n=globalThis.hljs){if(!t)return"";const i=xn(t);try{return n.highlight(i,{language:e}).value}catch(s){console.warn("Syntax highlighting failed:",s);try{return n.highlight(i,{language:"json"}).value}catch{return xt(i)}}}function Ks(t,e={}){const{highlighter:n=globalThis.hljs}=e;let i='
    ';const s=String(t??"").split(` -`);let r=!1,o="";for(const a of s){if(a.startsWith("```")){if(r){const l=Xm(o),u=Vd(o.trim(),l,n);i+=`
    -
    ${u}
    -
    `,o="",r=!1}else r=!0;continue}if(r){o+=a+` -`;continue}if(a.startsWith("# ")){const l=a.substring(2).trim();i+=`
    -

    - ${Ym(l)} - ${xt(l)} -

    -
    `;continue}if(a.startsWith("## ")){const l=a.substring(3).trim();i+=`
    -

    - ${Zm(l)} - ${xt(l)} -

    -
    `;continue}if(/^[-*+]\s+/.test(a)||/^\d+\.\s+/.test(a)){const l=a.replace(/^([-*+]|\d+\.)\s+/,"").trim();i+=`
    - • - ${xc(l)} -
    `;continue}a.trim()!==""&&(i+=`

    ${xc(a)}

    `)}return i+="
    ",` -
    -
    -
    - Live Audit Report -
    - ${i} -
    - `}const Qm=[[/gradient stroke\s*$/i," and an animated percentage label"],[/gauge\s*$/i," with a gradient stroke and animated fill"],[/rating\s*(bar|widget)?\s*$/i," with half-star support and haptic feedback"],[/list\s*$/i," with swipe-to-delete and an undo snackbar"],[/pad\s*$/i," that exports a transparent PNG"],[/carousel\s*$/i," with parallax cards and page indicators"],[/(button|cta)\s*$/i," with a loading spinner and success state"],[/(chart|graph)\s*$/i," that animates from a Firestore stream"],[/action\s*(that|to)?\s*$/i," uploads an image to Firebase Storage and returns the URL"],[/timer\s*$/i," with pause, resume and a completion callback"],[/map\s*$/i," with clustered markers and a custom info window"],[/^a\s+\w*$/i," widget that"],[/(picker|selector)\s*$/i," with search and multi-select"]],ev=220,tv=6;function kc(t,e){return!!(t&&t.trim())&&!e}function nv(t,e=""){if(typeof t!="string"||!t||t===e||t.trim().lengthi.test(t));return n?n[1]:null}function iv(){let t="",e="";return{get active(){return t},resolve(n){return t=nv(n,e)??"",t},dismiss(){t=""},accept(n){if(!t)return null;const i=n+t;return e=i,t="",i}}}function sv({onSubmit:t}){const e=document.getElementById("composer"),n=document.getElementById("pipeline-input"),i=document.getElementById("hero-send");if(!e||!n||!i||typeof t!="function")return;const s=e.querySelector(".ghost .typed"),r=e.querySelector(".ghost .suggest"),o=document.getElementById("tab-hint"),a=document.getElementById("suggest-status"),l=Array.from(document.querySelectorAll("#example-chips .chip")),u=window.matchMedia("(prefers-reduced-motion: reduce)"),c=iv();let d=!1,h=!1,p=null,f=null;function g(){i.disabled=!kc(n.value,h)}function m(){s&&(s.textContent=n.value)}function v(){r&&(r.textContent=""),m(),e.classList.remove("has-suggest"),o&&(o.hidden=!0,o.tabIndex=-1),a&&(a.textContent="")}function E(P){r&&(r.textContent=P),m(),e.classList.add("has-suggest"),o&&(o.hidden=!1,o.tabIndex=0,o.setAttribute("aria-label","Accept suggestion: "+P.trim())),a&&(a.textContent="Suggestion: "+P+". Press Tab to accept.")}function w(){c.dismiss(),v()}function I(){if(d||h)return;const P=c.resolve(n.value);P&&E(P)}function A(){clearTimeout(p),!d&&(p=setTimeout(I,ev))}function F(){const P=c.accept(n.value);return P===null?!1:(n.value=P,v(),g(),!0)}function D(P){h=P,e.classList.toggle("is-busy",P),i.classList.toggle("is-busy",P),i.setAttribute("aria-label",P?"Generating":"Generate"),g()}async function S(){if(kc(n.value,h)){w(),D(!0);try{await t()}finally{D(!1)}}}function $(){f&&(clearInterval(f),f=null),e.classList.remove("is-demo-typing")}function T(){l.forEach(P=>{P.classList.remove("is-active"),P.setAttribute("aria-pressed","false")})}function M(){try{n.focus({preventScroll:!0}),n.setSelectionRange(n.value.length,n.value.length)}catch{}}function N(P){const z=P.dataset.prompt||"";if($(),w(),l.forEach(U=>{const Q=U===P;U.classList.toggle("is-active",Q),U.setAttribute("aria-pressed",String(Q))}),u.matches||!z){n.value=z,m(),g(),M();return}n.value="",m(),g(),e.classList.add("is-demo-typing");let H=0;f=setInterval(()=>{H+=1,n.value=z.slice(0,H),m(),g(),H>=z.length&&($(),M())},22)}l.forEach(P=>{P.setAttribute("aria-pressed","false"),P.addEventListener("click",()=>N(P))}),n.addEventListener("keydown",P=>{$(),P.key==="Tab"&&!P.shiftKey&&c.active?(P.preventDefault(),F()):P.key==="Escape"?(clearTimeout(p),p=null,w()):P.key==="Enter"&&!P.shiftKey&&!P.isComposing&&!d&&(P.preventDefault(),S())}),n.addEventListener("input",()=>{$(),T(),w(),g(),A()}),n.addEventListener("compositionstart",()=>{d=!0}),n.addEventListener("compositionend",()=>{d=!1,w(),g(),A()}),n.addEventListener("scroll",()=>{s&&s.parentNode&&(s.parentNode.scrollTop=n.scrollTop)}),o&&o.addEventListener("click",()=>{F(),n.focus({preventScroll:!0})}),i.addEventListener("click",S),n.addEventListener("pointerdown",()=>{$(),T()}),m(),g()}const rv="https://ccc-ffai-runner-y5cyj3473a-uw.a.run.app/deployCustomClasses";const Ze="https://4tgke4.buildship.run",Gd={professional:"price_1T2ldCKszA2slvDXatdeCpbI",power:"price_1T2le9KszA2slvDXR4mPvw7M"},Is="ccc_auth_session",Ic=new WeakSet;let V={email:null,sessionToken:null,isVerified:!1};function kn(t={}){return{tier:"free",status:"none",periodEnd:null,isLoading:!1,isResolved:!1,error:null,...t}}let pe=kn({isResolved:!0});const ov=`${Ze}/service/runpipeline`,av="bs_user_id",lv="bs_identity_token",cv=`${Ze}/authUserCheck`;let Ke={userId:null,token:null,status:null,resolved:!1};const Cs={free:2,professional:50,power:2e3},As="ccc_subscription",Cc=3,uv=new Set(["active","trialing","paid"]),pi="google/gemini-3.7-flash",Ji=["anthropic/claude-opus-5","openai/gpt-5.6-sol","z-ai/glm-5.2","moonshotai/kimi-k3","openrouter/auto-beta","openrouter/free","openrouter/deepseek/deepseek-v4-pro"],dv={"google/gemini-3.7-flash":"Gemini 3.7 Flash","anthropic/claude-opus-5":"Claude Opus 5","openai/gpt-5.6-sol":"GPT-5.6 Sol","z-ai/glm-5.2":"GLM 5.2","moonshotai/kimi-k3":"Kimi K3","openrouter/auto-beta":"OpenRouter: Auto Router","openrouter/free":"OpenRouter: Free Models","openrouter/deepseek/deepseek-v4-pro":"DeepSeek v4 Pro"};function Kt(t){return dv[t]||t}const hv=new Set(["google/gemini-3.7-flash","anthropic/claude-opus-5","openai/gpt-5.6-sol","z-ai/glm-5.2","moonshotai/kimi-k3","openrouter/auto-beta"]);function Kd(t){return hv.has(t)}const Lo=4,Dr=8*1024*1024,pv="https://4tgke4.buildship.run/service/runpipeline-image";let Tt=[];function fv(t){return new Promise(e=>{const n=new FileReader;n.onload=()=>e(n.result),n.onerror=()=>e(null),n.readAsDataURL(t)})}async function gv(t){const e=new FormData;return e.append("file",t),(await fetch(pv,{method:"POST",body:e})).json()}function mv(t){if(Array.isArray(t)){const e=t[0];if(e&&typeof e=="object")for(const n of Object.keys(e)){if(n==="item"||n==="index")continue;const i=e[n];if(i&&typeof i=="object"){if(typeof i.file=="string")return i.file;if(typeof i.url=="string")return i.url}if(typeof i=="string")return i}return""}return typeof t=="string"?t:t&&typeof t=="object"&&(t.url||t.fileUrl||t.file_url||t.downloadUrl||t.imageUrl||t.image_url||t.file)||""}async function vv(t){const e=Array.from(t.target.files||[]);if(!e.length)return;const n=e.filter(l=>l.size>Dr);n.length&&ue(`Skipped ${n.length} image(s) over the ${(Dr/1024/1024).toFixed(0)} MB limit.`,"warning");const i=e.filter(l=>l.size<=Dr);if(!i.length){t.target.value="";return}const s=Lo-Tt.length,o=i.slice(0,s).map(async l=>{const u=await fv(l);if(!u)return null;let c="";try{c=mv(await gv(l))}catch{c=""}return{dataUrl:u,name:l.name,url:c}}),a=(await Promise.all(o)).filter(Boolean);t.target.value="",!(a.length&&!Kd(document.getElementById("code-generator-model")?.value))&&(Tt.push(...a),i.length>s&&ue(`You can attach up to ${Lo} images.`,"info"),ba())}function _v(t){Tt.splice(t,1),ba()}function ba(){const t=document.getElementById("prompt-image-thumbnails"),e=document.getElementById("prompt-image-btn-label");t&&(t.innerHTML="",Tt.forEach((n,i)=>{const s=document.createElement("div");s.className="prompt-img-thumb",s.innerHTML=`Prompt image`,t.appendChild(s)}),e&&(e.textContent=Tt.length>=Lo?"Image limit reached":"Add images"))}function Jd(){const t=document.getElementById("prompt-image-upload");if(!t)return;const e=document.getElementById("code-generator-model"),n=Kd(e?.value);t.classList.toggle("hidden",!n),!n&&Tt.length&&(Tt=[],ba())}const Zt="ccc_usage",Yd="google/gemini-3.7-flash",Zd="google/gemini-3.7-flash",jr="google/gemini-3.7-flash",Oi={professional:11,power:49},Oo={en_US:"USD",en_GB:"GBP",en_AU:"AUD",en_NZ:"NZD",en_CA:"CAD",en_IN:"INR",en_SG:"SGD",en_HK:"HKD",en_PH:"PHP",en_ZA:"ZAR",en:"USD",de:"EUR",fr:"EUR",es:"EUR",it:"EUR",nl:"EUR",pt_PT:"EUR",pt_BR:"BRL",pt:"BRL",ja:"JPY",ko:"KRW",zh_CN:"CNY",zh_TW:"TWD",zh:"CNY",th:"THB",vi:"VND",id:"IDR",ms_MY:"MYR",ms:"MYR",sv:"SEK",nb:"NOK",da:"DKK",pl:"PLN",cs:"CZK",hu:"HUF",ro:"RON",tr:"TRY",ar:"AED",he:"ILS",ru:"RUB",uk:"UAH"},Yi={AUD:1,USD:.65,EUR:.6,GBP:.52,CAD:.88,NZD:1.08,JPY:97,KRW:870,INR:54,SGD:.87,HKD:5.08,BRL:3.18,CNY:4.7,TWD:20.5,THB:22.5,VND:16200,IDR:10200,MYR:2.88,SEK:6.8,NOK:6.95,DKK:4.48,PLN:2.6,CZK:15.2,HUF:238,RON:2.98,TRY:20.9,AED:2.39,ILS:2.38,PHP:36.4,ZAR:11.8,RUB:58,UAH:26.8,CHF:.57,MXN:11.1,ARS:580,CLP:610,COP:2700,PEN:2.44};let Zi={...Yi};async function yv(){const t=new AbortController,e=setTimeout(()=>t.abort(),5e3);try{const n=await fetch("https://open.er-api.com/v6/latest/AUD",{signal:t.signal});if(!n.ok)return;const i=await n.json();if(i.result!=="success"||!i.rates)return;const s=i.rates,r={AUD:1},o=new Set([...Object.keys(Yi),...Object.values(Bo),...Object.values(Oo)]);for(const a of o)a!=="AUD"&&(typeof s[a]=="number"&&s[a]>0?r[a]=s[a]:Yi[a]&&(r[a]=Yi[a]));Zi=r}catch{}finally{clearTimeout(e)}}const Bo={"America/Sao_Paulo":"BRL","America/Fortaleza":"BRL","America/Recife":"BRL","America/Bahia":"BRL","America/Belem":"BRL","America/Manaus":"BRL","America/Cuiaba":"BRL","America/Campo_Grande":"BRL","America/Araguaina":"BRL","America/Noronha":"BRL","America/Rio_Branco":"BRL","America/Porto_Velho":"BRL","America/Boa_Vista":"BRL","America/Maceio":"BRL","America/Santarem":"BRL","America/Eirunepe":"BRL","Europe/London":"GBP","Europe/Paris":"EUR","Europe/Berlin":"EUR","Europe/Madrid":"EUR","Europe/Rome":"EUR","Europe/Amsterdam":"EUR","Europe/Brussels":"EUR","Europe/Vienna":"EUR","Europe/Lisbon":"EUR","Europe/Dublin":"EUR","Europe/Helsinki":"EUR","Europe/Athens":"EUR","Europe/Bucharest":"RON","Europe/Budapest":"HUF","Europe/Warsaw":"PLN","Europe/Prague":"CZK","Europe/Copenhagen":"DKK","Europe/Stockholm":"SEK","Europe/Oslo":"NOK","Europe/Zurich":"CHF","Europe/Istanbul":"TRY","Europe/Moscow":"RUB","Europe/Kiev":"UAH","Europe/Kyiv":"UAH","Asia/Tokyo":"JPY","Asia/Seoul":"KRW","Asia/Shanghai":"CNY","Asia/Taipei":"TWD","Asia/Hong_Kong":"HKD","Asia/Singapore":"SGD","Asia/Kolkata":"INR","Asia/Calcutta":"INR","Asia/Bangkok":"THB","Asia/Ho_Chi_Minh":"VND","Asia/Jakarta":"IDR","Asia/Kuala_Lumpur":"MYR","Asia/Dubai":"AED","Asia/Jerusalem":"ILS","Asia/Tel_Aviv":"ILS","Asia/Manila":"PHP","Pacific/Auckland":"NZD","Australia/Sydney":"AUD","Australia/Melbourne":"AUD","Australia/Brisbane":"AUD","Australia/Perth":"AUD","Australia/Adelaide":"AUD","Australia/Hobart":"AUD","Australia/Darwin":"AUD","Australia/Lord_Howe":"AUD","America/Toronto":"CAD","America/Vancouver":"CAD","America/Edmonton":"CAD","America/Winnipeg":"CAD","America/Halifax":"CAD","America/St_Johns":"CAD","America/Regina":"CAD","America/New_York":"USD","America/Chicago":"USD","America/Denver":"USD","America/Los_Angeles":"USD","America/Phoenix":"USD","America/Anchorage":"USD","Pacific/Honolulu":"USD","America/Mexico_City":"MXN","America/Cancun":"MXN","America/Tijuana":"MXN","America/Argentina/Buenos_Aires":"ARS","America/Santiago":"CLP","America/Bogota":"COP","America/Lima":"PEN","Africa/Johannesburg":"ZAR"};function Xd(){try{const r=Intl.DateTimeFormat().resolvedOptions().timeZone;if(r&&Bo[r])return Bo[r]}catch{}const e=(navigator.language||"en-US").replace("-","_"),n=Oo[e];if(n)return n;const i=e.split("_")[0],s=Oo[i];return s||"USD"}function Bi(t,e){const n=Zi[e]??Zi.USD,i=t*n,s=Math.round(i*100)/100;try{return new Intl.NumberFormat("en-US",{style:"currency",currency:e,minimumFractionDigits:0,maximumFractionDigits:s>=100||s%1===0?0:2}).format(s)}catch{return new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",minimumFractionDigits:0,maximumFractionDigits:2}).format(t*Zi.USD)}}const rt="ccc_api_key_",bt="ccc_session_api_key_",lt="ccc_encryption_key",fi="ccc_encryption_key_scope",wv="ccc_keystore",Fs="keys",gi="ccc_encryption_key_version";let Do=null,Ps=null,mi=!1,$s=!1,Ac=!1;class Ts extends Error{constructor(){super("Secure browser key storage is unavailable."),this.name="CredentialStorageUnavailableError"}}function Fc(){if(Ac)return;Ac=!0;const t="Secure browser key storage is unavailable. Existing credentials were left untouched; new credentials will be available only in this tab session.";console.warn(t),document.body&&ue(t,"warning")}function Qd(){return localStorage.getItem(gi)||""}function jo(){return crypto.randomUUID?.()||th(crypto.getRandomValues(new Uint8Array(16)))}function bv(){const t=Qd();if(t)return t;const e=jo();return localStorage.setItem(gi,e),e}function In(){Do=null,Ps=null,mi=!1,$s=!1}window.addEventListener("storage",t=>{t.key===gi&&In()});function Ev(){return new Promise((t,e)=>{const n=indexedDB.open(wv,1);n.onupgradeneeded=()=>{const i=n.result;i.objectStoreNames.contains(Fs)||i.createObjectStore(Fs)},n.onsuccess=()=>t(n.result),n.onerror=()=>e(n.error)})}async function Ea(t,e){const n=await Ev();return new Promise((i,s)=>{const r=n.transaction(Fs,t);let o;try{o=e(r.objectStore(Fs))}catch(l){n.close(),s(l);return}let a;o.onsuccess=()=>{a=o.result},o.onerror=()=>s(o.error),r.oncomplete=()=>{n.close(),i(a)},r.onerror=()=>{n.close(),s(r.error||new Error("Encryption key transaction failed."))},r.onabort=()=>{n.close(),s(r.error||new Error("Encryption key transaction aborted."))}})}function Sv(t){return t instanceof CryptoKey&&t.algorithm?.name==="AES-GCM"&&t.extractable===!1&&t.usages.includes("encrypt")&&t.usages.includes("decrypt")}async function xv(){const t=await Ea("readonly",e=>e.get(lt));return Sv(t)?t:null}async function eh(t){await Ea("readwrite",e=>e.put(t,lt))}async function kv(){In();try{await Ea("readwrite",t=>t.delete(lt))}catch(t){console.warn("Could not delete the stored encryption key:",t)}}async function Iv(){const t=sessionStorage.getItem(lt);if(!t)return null;const e=await crypto.subtle.importKey("jwk",JSON.parse(t),{name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);return await eh(e),sessionStorage.removeItem(lt),sessionStorage.removeItem(fi),localStorage.removeItem(rt+"salt"),e}async function Pc(t){const e=sessionStorage.getItem(lt);if(e)return $s=sessionStorage.getItem(fi)!=="session",crypto.subtle.importKey("jwk",JSON.parse(e),{name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);if(!t)throw new Ts;const n=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!0,["encrypt","decrypt"]),i=await crypto.subtle.exportKey("jwk",n);return sessionStorage.setItem(lt,JSON.stringify(i)),sessionStorage.setItem(fi,"session"),$s=!1,crypto.subtle.importKey("jwk",i,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}async function Cv(t){if(sessionStorage.getItem(fi)==="session"&&sessionStorage.getItem(lt))return Fc(),mi=!0,Pc(t);try{const e=await xv();if(e)return e;const n=await Iv();if(n)return n;const i=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);return await eh(i),i}catch(e){return console.warn("IndexedDB encryption-key storage failed:",e),Fc(),mi=!0,Pc(t)}}async function Sa(t={}){const{allowSessionFallbackCreation:e=!0}=t,n=bv();Ps!==n&&In();const i=Do||Cv(e);Do=i,Ps=n;try{return await i}catch(s){throw In(),s}}async function Av(t){const e=await Sa(),n=Ps,i=new TextEncoder,s=crypto.getRandomValues(new Uint8Array(12)),r=await crypto.subtle.encrypt({name:"AES-GCM",iv:s},e,i.encode(t)),o=new Uint8Array(s.length+r.byteLength);return o.set(s),o.set(new Uint8Array(r),s.length),{ciphertext:th(o),keyVersion:n,sessionFallback:mi}}async function Fv(t,e={}){const{isSessionCredential:n=!1}=e;try{const i=await Sa({allowSessionFallbackCreation:!1});if(mi&&!n&&!$s)throw new Ts;const s=Pv(t),r=s.slice(0,12),o=s.slice(12),a=await crypto.subtle.decrypt({name:"AES-GCM",iv:r},i,o);return new TextDecoder().decode(a)}catch(i){if(i instanceof Ts)throw i;return console.error("Decryption failed:",i),null}}function th(t){const e=new Uint8Array(t);let n="";for(let i=0;i0}let vi="",Rs="",ni=null,Tc=0;async function xa(){sessionStorage.getItem(lt)&&await Sa(),vi=await Ee("flutterflow"),Rs=await Ee("flutterflow_project_id"),Mv(),en()}function ka(){const t=document.getElementById("api-keys-modal");Ve(t),Ca(),vi&&rh(vi)}function nh(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("api-keys-modal");e&&Xe(e);const n=document.getElementById("walkthrough-modal");n&&(Ia(),Ve(n))}let kt=1;function ih(){const t=document.querySelector(".wt-steps");return t?Array.from(t.querySelectorAll(".wt-step-card")):[]}function Js(){const t=ih();t.length&&t.forEach((e,n)=>{const i=n+1;if(i===kt){e.classList.remove("opacity-60","bg-gray-50","border-gray-200"),e.classList.add("bg-blue-50","border-blue-200");const s=e.querySelector("div:first-child");s&&(s.classList.remove("bg-gray-400"),s.classList.add("bg-blue-500"),s.innerHTML=i)}else if(i0&&kt<=t&&(kt++,Js())}function Tv(){const t=document.getElementById("walkthrough-modal");t&&(kt=1,Js(),Ve(t))}function Rv(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("walkthrough-modal");e&&Xe(e);const n=document.getElementById("walkthrough-dont-show");n&&n.checked&&localStorage.setItem("hasSeenWalkthrough","true")}function sh(){if(V.isVerified&&Nt()&&pe.tier!=="free")return;if(!localStorage.getItem("hasSeenWalkthrough")){const e=document.getElementById("walkthrough-modal");e&&(kt=1,Js(),Ve(e))}}async function Ca(){const t=document.getElementById("flutterflow-api-key-input");vi?(t.value="",t.placeholder="Key saved (enter new to replace)"):t.placeholder="Enter your FlutterFlow API key",Nv()}function Nv(){Rc("flutterflow","flutterflow-key-status"),Rc("flutterflow_project_id","flutterflow-project-status")}function Rc(t,e){const n=document.getElementById(e);if(!n)return;const i=n.querySelector(".key-status-dot"),s=n.querySelector("span");dn(t)?(i.className="key-status-dot configured",s.className="text-green-600",s.textContent="User key configured"):(i.className="key-status-dot missing",s.className="text-gray-500",s.textContent="Not configured")}function en(){const t=y.step2Result&&y.step2Result.length>0,e=document.getElementById("btn-deploy-to-ff"),n=document.getElementById("btn-run-pipeline");n&&n.classList.remove("hidden"),e&&e.classList.toggle("hidden",!t)}function Mv(){const t=document.getElementById("api-keys-status");if(!t)return;const e=t.querySelectorAll(".key-status-dot"),n=["flutterflow"];e.forEach((i,s)=>{const r=n[s];r==="flutterflow"?dn("flutterflow")&&dn("flutterflow_project_id")?(i.className="key-status-dot configured",i.title="FlutterFlow (Fully configured)"):dn("flutterflow")||dn("flutterflow_project_id")?(i.className="key-status-dot env",i.title="FlutterFlow (Partially configured)"):(i.className="key-status-dot missing",i.title="FlutterFlow (Not configured)"):dn(r)?(i.className="key-status-dot configured",i.title=r.charAt(0).toUpperCase()+r.slice(1)+" (User key)"):(i.className="key-status-dot missing",i.title=r.charAt(0).toUpperCase()+r.slice(1)+" (Not configured)")}),en()}async function Lv(){const t=document.getElementById("flutterflow-api-key-input"),e=document.getElementById("flutterflow-projects-select");t.value.trim()&&await $c("flutterflow",t.value);const n=e?.value.trim()||"";if(n){if(!Ys(n)){ue("The selected FlutterFlow project has an unexpected ID format.","error"),e.focus();return}await $c("flutterflow_project_id",n)}await xa(),Ca();const i=document.querySelector("#api-keys-modal .bg-blue-500"),s=i.textContent;i.textContent="Saved!",i.classList.remove("bg-blue-500","hover:bg-blue-600"),i.classList.add("bg-green-500"),setTimeout(()=>{i.textContent=s,i.classList.remove("bg-green-500"),i.classList.add("bg-blue-500","hover:bg-blue-600"),nh()},1e3)}async function Ov(){if(!confirm("Are you sure you want to clear all stored API keys?"))return;localStorage.setItem(gi,jo()),In(),localStorage.removeItem(rt+"flutterflow"),localStorage.removeItem(rt+"flutterflow_project_id"),sessionStorage.removeItem(bt+"flutterflow"),sessionStorage.removeItem(bt+"flutterflow_project_id"),sessionStorage.removeItem(lt),sessionStorage.removeItem(fi),localStorage.removeItem(rt+"salt"),await kv(),localStorage.setItem(gi,jo()),localStorage.removeItem(rt+"flutterflow"),localStorage.removeItem(rt+"flutterflow_project_id"),sessionStorage.removeItem(bt+"flutterflow"),sessionStorage.removeItem(bt+"flutterflow_project_id"),await xa();const t=document.getElementById("flutterflow-projects-select");t&&(t.innerHTML=''),Ca()}function Ys(t){return!t||t.trim().length<5||t.includes(" ")?!1:/^[a-zA-Z0-9-]+$/.test(t)}function Bv(t,e){const n=document.getElementById(t);n&&(n.value?e?n.style.borderColor="#22c55e":n.style.borderColor="#ef4444":n.style.borderColor="")}function Dv(){const t=document.getElementById("flutterflow-api-key-input");t&&(t.addEventListener("input",e=>{const n=e.target.value.trim().length>0;Bv("flutterflow-api-key-input",n)}),t.addEventListener("blur",jv(async e=>{const n=e.target.value.trim();n&&await rh(n)},500)))}function jv(t,e){let n;return function(...s){const r=()=>{clearTimeout(n),t(...s)};clearTimeout(n),n=setTimeout(r,e)}}async function rh(t){const e=document.getElementById("flutterflow-projects-select"),n=document.getElementById("flutterflow-projects-error");if(!e){console.error("Projects dropdown element not found");return}e.innerHTML='',n&&n.classList.add("hidden");try{const s=await new wi(t,"").listProjects();if(!s||s.length===0){e.innerHTML='';return}e.innerHTML='',s.forEach(r=>{const o=document.createElement("option");o.value=r.id||r.projectId||"",o.textContent=r.name||r.projectName||`Project ${r.id}`,e.appendChild(o)}),Rs&&(e.value=Rs)}catch(i){console.error("Failed to fetch projects:",i),e.innerHTML='',n&&(n.textContent=`Failed to load projects: ${i.message}`,n.classList.remove("hidden"))}}function Uv(t){const e=document.getElementById(t),i=e.nextElementSibling.querySelector("svg");e.type==="password"?(e.type="text",i.innerHTML=` - - `):(e.type="password",i.innerHTML=` - - - `)}let y={step1Result:null,step2Result:null,step3Result:null,bundleSpec:null,artifactBundle:null,bundleReview:null,selectedArtifactId:null,resultsViewMode:"summary",currentStep:0,isRunning:!1};function Hv(){y.step1Result=null,y.step2Result=null,y.step3Result=null,y.bundleSpec=null,y.artifactBundle=null,y.bundleReview=null,y.selectedArtifactId=null,y.resultsViewMode="summary"}function Wv(){y.bundleSpec=di(y.step1Result,{artifactType:"CustomWidget",artifactName:"GeneratedWidget"})}function Zs(){const t=Ss(y.bundleSpec);y.artifactBundle=di(y.step2Result,{id:y.bundleSpec?.id,title:y.bundleSpec?.title,description:y.bundleSpec?.description,artifactType:t.artifactType,artifactName:t.artifactName,fileName:t.fileName,dependencies:t.dependencies,relationships:y.bundleSpec?.relationships,code:y.step2Result||""});const e=Ng(y.artifactBundle);y.artifactBundle={...y.artifactBundle,warnings:[...y.artifactBundle.warnings,...e.findings.map(n=>n.message)],metadata:{...y.artifactBundle.metadata,compatibility:e}},y.selectedArtifactId=Ss(y.artifactBundle).id}function Xs(){const t=di(y.step3Result,{id:y.artifactBundle?.id,title:y.artifactBundle?.title}),e=new Map(t.artifacts.map(i=>[i.id,i.review])),n=new Map(t.artifacts.filter(i=>{const s=i.review;return s&&typeof s.fixedSource=="string"&&s.fixedSource.trim()}).map(i=>[i.id,i.review.fixedSource.trim()]));y.bundleReview=di({id:y.artifactBundle?.id,title:y.artifactBundle?.title,artifacts:y.artifactBundle?.artifacts?.map(i=>{const s=n.get(i.id)||null;return{...i,review:e.get(i.id)||i.review||y.step3Result||null,...s?{fixedCode:s}:{}}})||[],relationships:y.artifactBundle?.relationships,warnings:y.artifactBundle?.warnings})}function oh(){const t=Aa();return{artifactType:t.artifactType||"CustomWidget",artifactName:t.artifactName||"GeneratedWidget",fileName:t.fileName||""}}function Aa(){const t=y.artifactBundle||y.bundleSpec||null;return(Array.isArray(t?.artifacts)?t.artifacts:[]).find(n=>n.id===y.selectedArtifactId)||Ss(t)}function Fa(){return Aa().code||y.step2Result||""}async function zv(){try{await xa()}catch(t){return console.error("checkConnection: initializeApiKeys failed:",t),!1}return!0}const Xi={production:"https://api.flutterflow.io/v2/",staging:"https://api.flutterflow.io/v2-staging/"};function qv(t,e){const n=e?.trim()?` (${e.trim().slice(0,200)})`:"";return t===401?`Your FlutterFlow API key was rejected (401 Unauthorized)${n}. Re-enter a current key under API Keys settings, then try again.`:`Listing FlutterFlow projects was denied (403)${n}. The key may be scoped to sync a single project without list permission - verify the key's access in FlutterFlow, re-enter it under API Keys settings, then retry.`}class wi{constructor(e,n,i="main",s=Xi.production){this.apiKey=e,this.baseUrl=s,this._projectId=n,this._branchName=i,this._endpoint=s}get projectId(){return this._projectId}get branchName(){return this._branchName==="main"?"":this._branchName}async exportProjectZip(){console.log(`Exporting code from FlutterFlow project: ${this.projectId}, branch: ${this.branchName||"main"}`);const e=[{project:{path:`projects/${this.projectId}`},...this.branchName?{branch_name:this.branchName}:{},export_as_module:!1,include_assets_map:!1,format:!1,export_as_debug:!1},{project_id:this.projectId,branch_name:this.branchName,include_assets:!1,export_as_module:!1}];let n=null;for(const i of e)try{const s=await fetch(`${this.baseUrl}exportCode`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify(i)});if(!s.ok){const a=await s.text();n=new Error(`Export failed: ${s.status} - ${a}`);continue}const r=await s.json(),o=r?.value?.project_zip||r?.project_zip;if(!o){n=new Error("Export response did not include project source.");continue}return o}catch(s){n=s}throw n||new Error("Export failed for an unknown reason.")}async fetchProjectSource(){const e=await this.exportProjectZip(),n=await JSZip.loadAsync(e,{base64:!0}),i=Object.keys(n.files).filter(a=>!n.files[a].dir&&(a==="pubspec.yaml"||a.endsWith("/pubspec.yaml"))).sort((a,l)=>a.split("/").length-l.split("/").length)[0];if(!i)throw new Error("Export did not contain a pubspec.yaml.");const s=i.slice(0,i.length-12),r=new Map,o=Object.keys(n.files).filter(a=>{if(n.files[a].dir||!a.startsWith(s))return!1;const l=a.slice(s.length);return l==="lib/flutter_flow/custom_functions.dart"||l.startsWith("lib/custom_code/")&&l.endsWith(".dart")});return await Promise.all(o.map(async a=>{r.set(a.slice(s.length),await n.files[a].async("string"))})),{pubspecYaml:await n.files[i].async("string"),files:r}}async pushCodeWithRetry(e,n=3){const i=[Xi.production,Xi.staging],s=Math.max(0,i.indexOf(this._endpoint));for(let r=0;rsetTimeout(d,1e3*(r+1)));continue}return l}catch(l){console.warn(`Push to ${a} failed: ${l.message}, trying next...`),await new Promise(u=>setTimeout(u,1e3*(r+1)))}}throw new Error("All API endpoints failed after retries")}async pushCode(e){return this.pushCodeWithRetry(e)}parseProjectsResponse(e){if(e?.success&&typeof e.value=="string")try{const i=JSON.parse(e.value);if(i&&Array.isArray(i.entries))return i.entries.map(s=>({id:s.id,name:s.project?.name||s.id}))}catch(i){console.error("Failed to parse stringified project value:",i)}const n=e?.projects||e?.items||e?.entries||(Array.isArray(e)?e:[]);return Array.isArray(n)?n:[]}async listProjects(){console.log("Listing projects for API key");const e=[`${this.baseUrl}listProjects`,"https://api.flutterflow.io/v2/l/listProjects"];let n=0,i="";for(const s of e){const r=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify({project_type:"ALL",deserialize_response:!0})});if(r.ok)return s!==e[0]&&console.log(`listProjects answered on legacy path ${s}`),this.parseProjectsResponse(await r.json());if(n=r.status,i=await r.text(),console.warn(`listProjects via ${s} returned ${n}: ${i}`),r.status===401||r.status===403)throw new Error(qv(r.status,i));if(r.status!==404)throw new Error(`List projects failed: ${r.status} - ${i}`)}throw new Error(`List projects failed: ${n} - ${i}`)}}async function Pa(t){const e=t.clone();let n;try{n=await t.json()}catch{const r=await e.text();if(!t.ok)return{success:!1,responseCode:t.status,errorMessage:r||`HTTP ${t.status}`,errorMap:new Map};throw new Error(`Invalid JSON response: ${r}`)}if(!t.ok){let s=n.message||`HTTP ${t.status}`,r=new Map;if(n.errors)r=new Map(Object.entries(n.errors));else if(!n.message&&typeof n=="object"){const o=Object.keys(n).filter(a=>a.endsWith(".dart")&&Array.isArray(n[a]));o.length>0&&(r=new Map(Object.entries(n)),s=o.flatMap(l=>n[l].map(u=>`${l}: ${u.errorMessage}`)).join(` -`)||`HTTP ${t.status}`)}return{success:!1,responseCode:t.status,errorMessage:s,errorMap:r}}let i={};if(n.value)try{i=typeof n.value=="string"?JSON.parse(n.value):n.value}catch(s){console.warn("Ignoring malformed push response value:",s)}return{success:!0,responseCode:t.status,errorMap:new Map(Object.entries(i))}}function $a(t,e){return{401:"Authentication failed. Please check your FlutterFlow API key.",403:"Access denied. You may not have permission to modify this project.",404:"Project not found. Please check your Project ID.",409:"Conflict detected. The project may have been modified elsewhere.",422:"Validation failed: Invalid request format",429:"Rate limit exceeded. Please try again in a few minutes.",500:"FlutterFlow server error. Please try again later.",503:"FlutterFlow service temporarily unavailable."}[t]||`FlutterFlow API error: ${`HTTP ${t}`}`}const W={ACTION:"A",WIDGET:"W",FUNCTION:"F",CODE_FILE:"C",DEPENDENCIES:"D",OTHER:"O"},ah=/class\s+\w+\s+extends\s+(?:StatelessWidget|StatefulWidget)\b/,lh=/extends\s+State<\w+>/;function Vv(t,e=""){if(t==="pubspec.yaml")return W.DEPENDENCIES;if(!t.endsWith(".dart")||t.endsWith("index.dart"))return W.OTHER;if(t==="custom_functions.dart")return W.FUNCTION;if(e){const n=ah.test(e),i=lh.test(e);if(n||i)return W.WIDGET;if(/^\s*Future(?:<[^>]+>)?\s+\w+\s*\(/m.test(e))return W.ACTION;if(e.match(/^\s*(String|int|double|bool|List|Map|dynamic|void)\s+\w+\s*\(/m))return W.FUNCTION}return W.CODE_FILE}function ch(t,e){switch(e){case W.ACTION:return`lib/custom_code/actions/${t}`;case W.WIDGET:return`lib/custom_code/widgets/${t}`;case W.FUNCTION:return"lib/flutter_flow/custom_functions.dart";case W.CODE_FILE:return`lib/custom_code/${t}`;case W.DEPENDENCIES:return"pubspec.yaml";case W.OTHER:return`lib/custom_code/${t}`;default:return t}}async function Ta(t,e=new Map){return mg(t,e)}const Uo=new Map;function uh(t){return`${t.baseUrl}|${t.projectId}|${t.branchName}`}function Qs(t){Uo.delete(uh(t))}async function Ra(t,e,n,i,s=""){const r=Kg(e,n);if(r.length===0)return{remoteFiles:n,syncFileMap:e,unverified:[]};const o=Nm(r,s),a={...o.manifest,sources:o.sources},l=o.skipped.map(d=>d.reason);l.forEach(d=>console.warn(`[custom class deploy] ${d}`)),console.log(`Provisioning ${r.length} new FlutterFlow custom code file(s) before sync.`),be.set("provision");const u=await fetch(rv,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:t.apiKey,projectId:t.projectId,baseUrl:t.baseUrl,commitMessage:i,customClasses:r,verification:a,stream:!0})}),c=await Lm(u,{onPhase:d=>be.setSubstatus(d),onLog:d=>console.log(`[custom class deploy] ${d}`)});if(!c.success){const d=c.details?` ${c.details}`:"";throw new Error(`${c.error||"FlutterFlow custom class provisioning failed."}${d}`)}return Qs(t),c.verificationSkipped&&(console.warn(`[custom class deploy] ${c.verificationSkipped}`),l.push(c.verificationSkipped)),{remoteFiles:n,syncFileMap:Jg(e,r),unverified:l}}async function Na(t,e={}){const n=uh(t);let i=Uo.get(n);if(i===void 0){try{i=await t.fetchProjectSource()}catch(l){throw new Error(`Could not read your project's pubspec.yaml (${l.message}). Deploy was stopped so your existing package dependencies aren't overwritten. Check your FlutterFlow API key and project, then try again.`)}const a=zd(i.pubspecYaml);if(!a.valid)throw new Error(`Your project's pubspec.yaml could not be read reliably (${a.errors.join("; ")}). Deploy was stopped so your existing package dependencies aren't overwritten.`);Uo.set(n,i)}const s=await Gm(i.pubspecYaml,e),r=Fm(i.pubspecYaml,s.overrides),o=Am(r.yaml,s.additions);return s.warnings.forEach(a=>console.warn(`[pubspec] ${a}`)),o.added.length>0&&console.log("Adding dependencies:",o.added.map(a=>`${a}: ${s.additions[a]||"any"}`).join(", "),s.sdk.dartSdkFloor?`(resolved for Dart ${s.sdk.dartSdkFloor})`:""),s.kept.forEach(({name:a,constraint:l})=>console.log(`Keeping your existing ${a}: ${l||"(non-version source)"}`)),{...o,overridden:r.overridden,warnings:s.warnings,remoteFiles:i.files}}function Gv(t){const e=[],n=[];t.content.length>5e4&&n.push("Code file is large (>50KB). This may take longer to commit."),t.content.length>1e5&&e.push("Code file is too large (>100KB). Consider splitting into smaller components.");const i=t.content.split(` -`).length;i>500&&n.push(`Code has ${i} lines. Consider breaking it into smaller widgets.`),t.content.includes("setState")&&t.codeType===W.ACTION&&n.push("Using setState in a Custom Action may not work as expected. Consider using a Custom Widget."),t.content.includes("dynamic")&&!t.content.includes("?")&&n.push('Code uses "dynamic" types. Consider adding explicit types for better null safety.'),t.content.match(/Color\(0xFF[0-9A-Fa-f]{6}\)/)&&n.push("Code contains hardcoded colors. Consider using FlutterFlowTheme.of(context) for theme consistency.");const s=t.content.match(/print\s*\(/g);s&&s.length>3&&n.push(`Code contains ${s.length} print statements. Consider removing debug prints before committing.`);const r=pm(t.content);if(r&&e.push(`FlutterFlow cannot format this code - ${r}. Fix or regenerate before committing.`),t.codeType===W.WIDGET){const o=Ld(t.content),a=um(t.fileName);if(o.length===0)e.push("No public widget class found (must extend StatelessWidget or StatefulWidget).");else if(!o.includes(a)){const l=`${Od(o[0])}`;e.push(`Widget class name "${o[0]}" does not match the file name "${t.fileName}". FlutterFlow derives the widget from the file name, so it will report "No widget ${a} found". Rename the file to "${l}" or the class to match before committing.`)}}return{canProceed:e.length===0,issues:e,warnings:n}}function dh(t,e={}){const{artifactType:n="CustomWidget",artifactName:i="GeneratedCode",fileName:s}=e,r=lm(t);let o=s||i;if(n==="CustomFunction")o="custom_functions.dart";else if(n==="CustomWidget"){const u=Ld(r)[0],c=u?Od(u):null;c&&o!==c?(console.warn(`Commit file name "${o}" does not match declared widget class "${u}"; renaming to "${c}" so FlutterFlow can find the widget.`),o=c):o.endsWith(".dart")||(o+=".dart")}else o.endsWith(".dart")||(o+=".dart");let a=W.CODE_FILE;switch(n){case"CustomAction":a=W.ACTION;break;case"CustomWidget":a=W.WIDGET;break;case"CustomFunction":a=W.FUNCTION;break;case"CustomClass":case"CodeFile":a=W.CODE_FILE;break}let l="";return a===W.WIDGET?l=`// Automatic FlutterFlow imports -import '/flutter_flow/flutter_flow_theme.dart'; -import '/flutter_flow/flutter_flow_util.dart'; -import 'package:flutter/material.dart'; -// Begin custom widget code -// DO NOT REMOVE OR MODIFY THE CODE ABOVE! - -`:a===W.ACTION?l=`// Automatic FlutterFlow imports -import '/flutter_flow/flutter_flow_theme.dart'; -import '/flutter_flow/flutter_flow_util.dart'; -import 'package:flutter/material.dart'; -// Begin custom action code -// DO NOT REMOVE OR MODIFY THE CODE ABOVE! - -`:a===W.FUNCTION&&(l=`// Automatic FlutterFlow imports -import 'dart:convert'; -import 'dart:math' as math; - -import 'package:flutter/material.dart'; -import 'package:google_fonts/google_fonts.dart'; -import 'package:intl/intl.dart'; -import 'package:timeago/timeago.dart' as timeago; -import '/flutter_flow/lat_lng.dart'; -import '/flutter_flow/place.dart'; -import '/flutter_flow/uploaded_file.dart'; - -`),{content:Og(r,l),fileName:o,codeType:a,artifactType:n,artifactName:i}}function Kv(t){const e={};for(const n of ma(t))e[n]="";return e}function Jv(t,e={}){return{timestamp:new Date().toISOString(),artifactType:t.artifactType,artifactName:t.artifactName,codeType:t.codeType,fileName:t.fileName,generatedFrom:e.step1Result?"pipeline":"direct",model:e.selectedModel||"unknown",codeSize:t.content.length}}function Yv(t,e,n,i=new Set,s=""){const r=[],o=ah.test(e),a=lh.test(e);return n===W.WIDGET&&!o&&!a&&r.push("No widget class definition found (must extend StatelessWidget or StatefulWidget)"),{valid:r.length===0,errors:r}}function er(t){const e=[],n=[];if(!t||t.size===0)return e.push("No files to commit"),{valid:!1,errors:e,warnings:n};const i=new Set(Array.from(t.values()).flatMap(s=>Hs(s.content||"")));for(const[s,r]of t.entries()){if((!r.content||r.content.trim().length===0)&&e.push(`File ${s} is empty`),r.content&&r.content.length>1e5&&n.push(`File ${s} is very large (>100KB)`),s.endsWith(".dart")){const o=Yv(s,r.content,r.type,i,r.artifactName);o.valid||e.push(...o.errors.map(a=>`${s}: ${a}`))}if(s==="pubspec.yaml"){const o=zd(r.content);o.valid||e.push(...o.errors)}}return{valid:e.length===0,errors:e,warnings:n}}const K={IDLE:"IDLE",PREPARING:"PREPARING",VALIDATING:"VALIDATING",PUSHING:"PUSHING",SUCCESS:"SUCCESS",ERROR:"ERROR"},J={currentState:K.IDLE,startTime:null,endTime:null,error:null,result:null,filesProcessed:0,totalFiles:0,reset(){this.currentState=K.IDLE,this.startTime=null,this.endTime=null,this.error=null,this.result=null,this.filesProcessed=0,this.totalFiles=0},setState(t){if(!Object.values(K).includes(t)){console.error(`Invalid commit state: ${t}`);return}this.currentState=t,t===K.PREPARING&&(this.startTime=Date.now()),(t===K.SUCCESS||t===K.ERROR)&&(this.endTime=Date.now()),typeof window<"u"&&window.dispatchEvent&&window.dispatchEvent(new CustomEvent("commitStateChange",{detail:{state:t,commitState:this}})),console.log(`Commit state changed to: ${t}`)},setError(t){this.error=t,this.setState(K.ERROR)},setSuccess(t){this.result=t,this.setState(K.SUCCESS)},setProgress(t,e){this.filesProcessed=t,this.totalFiles=e},getElapsedTime(){return this.startTime?(this.endTime||Date.now())-this.startTime:null},isInProgress(){return this.currentState===K.PREPARING||this.currentState===K.VALIDATING||this.currentState===K.PUSHING}};async function Zv(t,e,n={}){let{codeType:i="W"}=n;const{pubspecDeps:s={},artifactName:r=e}=n;i==="CustomWidget"&&(i=W.WIDGET),i==="CustomAction"&&(i=W.ACTION),i==="CustomFunction"&&(i=W.FUNCTION),i==="CustomClass"&&(i=W.CODE_FILE),i==="CodeFile"&&(i=W.CODE_FILE),J.reset(),J.setState(K.PREPARING);try{const o=await Ee("flutterflow"),a=await Ee("flutterflow_project_id");if(!o||!a)throw new Error("FlutterFlow credentials not configured. Please set your API key and Project ID in the API Keys settings.");if(!Ys(a))throw new Error("Invalid FlutterFlow Project ID format.");const l=yi(),u=new wi(o,a,"main",l);J.setState(K.VALIDATING);const c=new Map,d=i||Vv(e,t),h=ch(e,d);c.set(e,{artifactName:r,content:t,type:d,path:h}),J.setProgress(0,c.size);const p=er(c);if(!p.valid)throw new Error(`Validation failed: -${p.errors.join(` -`)}`);const f=await Na(u,s),g=f.yaml,m=await Ra(u,c,f.remoteFiles,`Provision ${r} custom class`,g),v=await Ta(m.syncFileMap,m.remoteFiles),E=new Map(m.syncFileMap);E.set("pubspec.yaml",{content:g,type:"D",path:"pubspec.yaml"}),be.set("package");const w=await Ma(E),I={project_id:a,zipped_custom_code:w,uid:`web_${Date.now()}`,branch_name:u.branchName,serialized_yaml:g,file_map:v.fileMapContents,functions_map:v.functionsMapContents};J.setState(K.PUSHING),J.setProgress(1,c.size),Qs(u),be.set("push");const A=await u.pushCode(I),F=await Pa(A);if(F.success)J.setSuccess({fileCount:c.size,projectId:a,warnings:F.errorMap&&F.errorMap.size>0?Array.from(F.errorMap.entries()):[]});else{const D=F.errorMessage||$a(F.responseCode);throw new Error(D)}return{success:!0,message:`Successfully committed ${e} to FlutterFlow project ${a}`,addedDependencies:f.added,unverified:m.unverified,warnings:F.errorMap?Array.from(F.errorMap.entries()):[]}}catch(o){return console.error("Commit failed:",o),J.setError(o),{success:!1,error:o.message,state:J.currentState}}}async function Ma(t){const e=new JSZip;for(const[n,i]of t.entries())e.file(n,i.content);return e.generateAsync({type:"base64",compression:"DEFLATE",compressionOptions:{level:6}})}async function Xv(t,e={}){const{artifactType:n,artifactName:i,fileName:s,pipelineResult:r}=e;console.log(`Starting commit for ${i} (${n})`);try{J.setState(K.PREPARING);const o=dh(t,{artifactType:n,artifactName:i,fileName:s}),a=Kv(o.content);console.log("Detected dependencies:",a),J.setState(K.VALIDATING);const l=await Ee("flutterflow"),u=ni||await Ee("flutterflow_project_id");if(!l)throw new Error("FlutterFlow API Key not configured. Please add it in API Keys settings.");if(!u)throw new Error("FlutterFlow Project ID not configured. Please add it in API Keys settings.");if(!Ys(u))throw new Error("Invalid FlutterFlow Project ID format.");const c=new Map;c.set(o.fileName,{artifactName:i,content:o.content,type:o.codeType,path:ch(o.fileName,o.codeType),functionName:o.codeType===W.FUNCTION?i:void 0}),J.setProgress(0,c.size);const d=er(c);if(!d.valid)throw new Error(`File validation failed: -${d.errors.join(` -`)}`);d.warnings.length>0&&console.warn("Validation warnings:",d.warnings),J.setState(K.PUSHING);const h=yi(),p=new wi(l,u,"main",h),f=await Na(p,a),g=f.yaml,m=await Ra(p,c,f.remoteFiles,`Provision ${i} custom class`,g),v=await Ta(m.syncFileMap,m.remoteFiles),E=new Map(m.syncFileMap);E.set("pubspec.yaml",{content:g,type:W.DEPENDENCIES,path:"pubspec.yaml"}),be.set("package");const w=await Ma(E),I={project_id:u,zipped_custom_code:w,uid:`web_${Date.now()}`,branch_name:p.branchName,serialized_yaml:g,file_map:v.fileMapContents,functions_map:v.functionsMapContents};J.setProgress(1,c.size),Qs(p),be.set("push");const A=await p.pushCode(I),F=await Pa(A);if(F.success){const D={...Jv(o,r),projectId:u};return J.setSuccess({...D,fileCount:c.size,warnings:F.errorMap?Array.from(F.errorMap.entries()):[]}),{success:!0,message:`Successfully committed ${o.fileName} to FlutterFlow`,metadata:D,addedDependencies:f.added,unverified:m.unverified,warnings:F.errorMap?Array.from(F.errorMap.entries()):[],elapsedTime:J.getElapsedTime()}}else{const D=F.errorMessage||$a(F.responseCode),S=new Error(D);throw S.errorMap=F.errorMap,S}}catch(o){console.error("Commit execution failed:",o),J.setError(o);let a=new Map;if(o.errorMap)a=o.errorMap;else if(o.message&&o.message.includes("{"))try{const l=o.message.match(/\{[\s\S]*\}/);if(l){const u=JSON.parse(l[0]);a=new Map(Object.entries(u))}}catch(l){console.warn("Failed to parse error map from commit response:",l)}return{success:!1,error:o.message,errorMap:a,state:J.currentState,elapsedTime:J.getElapsedTime()}}}async function Qv(t,e={}){const{pipelineResult:n}=e;try{if(J.setState(K.PREPARING),t.errors?.length>0)throw new Error(`Bundle validation failed: -${t.errors.join(` -`)}`);const i=new Map(t.fileEntries.map(I=>[I.fileName,{artifactId:I.artifactId,artifactName:I.artifactName,content:I.content,type:I.type,path:I.path,functionName:I.type===W.FUNCTION?I.artifactName:void 0}]));J.setProgress(0,i.size);const s=er(i);if(!s.valid)throw new Error(`File validation failed: -${s.errors.join(` -`)}`);J.setState(K.VALIDATING);const r=await Ee("flutterflow"),o=ni||await Ee("flutterflow_project_id");if(!r)throw new Error("FlutterFlow API Key not configured. Please add it in API Keys settings.");if(!o)throw new Error("FlutterFlow Project ID not configured. Please add it in API Keys settings.");if(!Ys(o))throw new Error("Invalid FlutterFlow Project ID format.");J.setState(K.PUSHING);const a=yi(),l=new wi(r,o,"main",a),u=await Na(l,t.dependencies),c=u.yaml,d=await Ra(l,i,u.remoteFiles,`Provision ${t.title} custom classes`,c),h=await Ta(d.syncFileMap,d.remoteFiles),p=new Map(d.syncFileMap);p.set("pubspec.yaml",{content:c,type:W.DEPENDENCIES,path:"pubspec.yaml"}),be.set("package");const f=await Ma(p),g={project_id:o,zipped_custom_code:f,uid:`web_${Date.now()}`,branch_name:l.branchName,serialized_yaml:c,file_map:h.fileMapContents,functions_map:h.functionsMapContents};J.setProgress(1,i.size),Qs(l),be.set("push");const m=await l.pushCode(g),v=await Pa(m);if(v.success){const I={...n,artifactType:"Bundle",artifactName:t.title,fileName:`${t.fileEntries.length} artifacts`,codeSize:t.fileEntries.reduce((A,F)=>A+F.content.length,0),projectId:o};return J.setSuccess({...I,fileCount:i.size,warnings:v.errorMap?Array.from(v.errorMap.entries()):[]}),{success:!0,message:`Successfully committed ${t.fileEntries.length} artifacts to FlutterFlow`,metadata:I,addedDependencies:u.added,unverified:d.unverified,warnings:v.errorMap?Array.from(v.errorMap.entries()):[],elapsedTime:J.getElapsedTime()}}const E=v.errorMessage||$a(v.responseCode),w=new Error(E);throw w.errorMap=v.errorMap,w}catch(i){return console.error("Bundle commit execution failed:",i),J.setError(i),{success:!1,error:i.message,errorMap:i.errorMap||new Map,state:J.currentState,elapsedTime:J.getElapsedTime()}}}async function e_(t,e=[]){const n=ha("architect");try{return await Ms("architect",Yd,sg(t),n,e)}catch(i){throw i.isModelArmor?i:new Error(`Prompt Architect failed: ${i.message}`)}}async function tr(t,e,n=[]){const i=rg(t),s=ha("generator",y.bundleSpec);try{return await Ms("generator",e,i,s,n)}catch(r){if(r.isModelArmor)throw r;if(e!==jr){console.warn(`Code Generator failed with ${e}, retrying with fallback model:`,r.message);try{return await Ms("generator",jr,i,s,n)}catch(o){throw o.isModelArmor?o:new Error(`Code Generator failed: primary (${e}): ${r.message} | fallback (${jr}): ${o.message}`)}}throw new Error(`Code Generator failed: ${r.message}`)}}async function nr(t,e=null){const n={...ha("review",y.artifactBundle||y.bundleSpec),architect_output:e};try{return await Ms("review",Zd,og(t),n)}catch(i){throw i.isModelArmor?i:new Error(`Code Review failed: ${i.message}`)}}function La(t,e){return t.isModelArmor?`${t.userTitle}: ${t.userMessage}`:`${e}: ${t.message}`}function Ho(t,e){const n=document.getElementById(`step${t}-item`),i=document.getElementById(`step${t}-status`);!n||!i||(n.classList.remove("active","completed","error"),i.classList.remove("running","completed","error"),e==="active"?(n.classList.add("active"),i.classList.add("running"),i.innerHTML=` - - `):e==="completed"?(n.classList.add("completed"),i.classList.add("completed"),i.innerHTML=` - - `):e==="error"?(n.classList.add("error"),i.classList.add("error"),i.innerHTML=` - - `):i.innerHTML=` - - `)}function ve(t,e){const n=document.getElementById(`step${t}-loading`),i=document.getElementById(`step${t}-result`);e?(n.classList.remove("hidden"),i.classList.add("hidden"),Ho(t,"active")):(n.classList.add("hidden"),i.classList.remove("hidden"),Ho(t,"completed"))}function t_(t){const e=document.getElementById(`${t}-content`),n=document.getElementById(`${t}-chevron`);e.classList.contains("open")?(e.classList.remove("open"),n&&(n.style.transform="rotate(0deg)")):(e.classList.add("open"),n&&(n.style.transform="rotate(180deg)"))}function n_(t){ze(parseInt(t.replace("step","")))}function ze(t){for(let o=1;o<=3;o++){const a=document.getElementById(`step${o}-item`);a&&a.classList.remove("active")}const e=document.getElementById(`step${t}-item`);e&&e.classList.add("active"),Qt();const n=document.getElementById("ready-state");n&&n.classList.add("hidden");for(let o=1;o<=3;o++){const a=document.getElementById(`step${o}-content`);a&&a.classList.add("hidden")}const i=document.getElementById(`step${t}-content`);i&&i.classList.remove("hidden");const s=document.getElementById("stage-title"),r={1:"Prompt Architect",2:"Code Generator",3:"Code Review"};s&&(s.textContent=r[t]||"Active Workflow Stage")}function i_(t){const e=document.getElementById(t);if(!e)return;const n=e.dataset.raw||e.textContent;navigator.clipboard.writeText(n).then(()=>{const s=e.closest(".code-container")?.querySelector(".copy-btn");s&&(s.classList.add("copied"),s.innerHTML=' Copied!',setTimeout(()=>{s.classList.remove("copied"),s.innerHTML=' Copy'},2e3))}).catch(i=>{console.warn("Failed to copy to clipboard:",i)})}function Wo(t){const e=zo(t);console.log(`Step 1 (Prompt Architect): ${Kt(Yd)}`),console.log(e!==t?`Step 2 (Code Generator): ${Kt(t)} → ${Kt(e)} (Free Tier fallback)`:`Step 2 (Code Generator): ${Kt(t)}`),console.log(`Step 3 (Code Review): ${Kt(Zd)}`)}async function s_(){if(console.log("runRefinement called"),y.isRunning)return;const t=document.getElementById("code-generator-model").value;y.isRunning=!0,Oa("standardRegenerate",y.step2Result,y.step1Result);const e=document.querySelectorAll(".btn-refine-action");e.forEach(n=>{n.disabled=!0,n.innerHTML=` - - - Refining...`});try{const n=Aa(),i=ag({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,artifactId:n.id,userFeedback:"Fix the issues listed in the audit report."});or(),at(2),ze(2),ve(2,!0),y.step2Result=await tr(i,t),Zs();const s=document.getElementById("step2-output"),r=xn(y.step2Result);s.textContent=r,s.dataset.raw=r,ve(2,!1),ze(3),at(3),ve(3,!0),y.step3Result=await nr(y.step2Result,y.step1Result),Xs();const o=document.getElementById("step3-output");o.textContent=y.step3Result,ve(3,!1),Mt();const a=Ks(y.step3Result);ar(r,a)}catch(n){console.error("Refinement failed:",n),Mt(),ue(La(n,"Refinement failed"),"error")}finally{y.isRunning=!1,e.forEach(n=>{n.disabled=!1,n.textContent="Refine & Regenerate"}),en()}}async function Oa(t,e,n){const i=`${Ze}/connectFeedback`,s={type:t,code:e,input:n};try{const r=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)});if(!r.ok){const a=await r.text();return console.error(`callEndpoint failed: ${r.status} ${r.statusText}`,a),{success:!1,status:r.status,error:a}}const o=await r.json();return console.log("Telemetry success:",o),o}catch(r){return console.error("callEndpoint failed:",r),{success:!1,error:r.message}}}function r_(){const t=document.getElementById("ff-error-paste-input");t&&(t.value="")}async function o_(){const t=document.getElementById("ff-error-paste-input"),e=t?.value?.trim();if(!e){t?.focus(),t?.classList.add("ring-2","ring-red-400","border-red-300"),setTimeout(()=>t?.classList.remove("ring-2","ring-red-400","border-red-300"),2e3);return}if(!y.step2Result){ue("No generated code found. Please run the full pipeline first.","warning");return}if(y.isRunning)return;const n=document.getElementById("code-generator-model").value;y.isRunning=!0,Oa("flutterflowError",y.step2Result,e);const i=document.getElementById("btn-fix-from-errors");i&&(i.disabled=!0,i.innerHTML=` - - Fixing…`);try{const s=$d({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,userFeedback:e});Sh(),or(),at(2),ze(2),ve(2,!0),y.step2Result=await tr(s,n),Zs();const r=document.getElementById("step2-output"),o=xn(y.step2Result);r.textContent=o,r.dataset.raw=o,ve(2,!1),ze(3),at(3),ve(3,!0),y.step3Result=await nr(y.step2Result,y.step1Result),Xs();const a=document.getElementById("step3-output");a.textContent=y.step3Result,ve(3,!1),Mt();const l=Ks(y.step3Result);ar(o,l),t&&(t.value="")}catch(s){console.error("Fix from errors failed:",s),Mt(),ue(La(s,"Failed to fix errors"),"error")}finally{y.isRunning=!1,i&&(i.disabled=!1,i.textContent="Fix Errors & Regenerate"),en()}}async function Ns(){if(console.log("runThinkingPipeline called"),y.isRunning)return;localStorage.setItem("hasSeenWalkthrough","true");const t=document.getElementById("pipeline-input").value,e=document.getElementById("code-generator-model").value;if(!t.trim()){ue("Please describe your FlutterFlow widget first.","warning");return}if(!await I_())return;await w_();const n=zo(e);t.length;const i=document.getElementById("btn-run-pipeline");y.isRunning=!0,Hv(),i&&(i.disabled=!0,i.innerHTML=` - - - Running...`),Wo(n);try{Qt();const s=document.getElementById("ready-state");s&&s.classList.add("hidden");const r=document.getElementById("paywall-exhausted");r&&r.classList.add("hidden"),or(),ze(1),at(1),ve(1,!0);const o=Tt.filter(p=>p.url).map(p=>({url:p.url}));y.step1Result=await e_(t,o),Wv();const a=document.getElementById("step1-output"),l=xn(y.step1Result);a.textContent=l,a.dataset.raw=l,ve(1,!1),ze(2),at(2),ve(2,!0),y.step2Result=await tr(y.step1Result,n,o),Zs();const u=document.getElementById("step2-output"),c=xn(y.step2Result);u.textContent=c,u.dataset.raw=c,ve(2,!1),ze(3),at(3),ve(3,!0),y.step3Result=await nr(y.step2Result,y.step1Result),Xs();const d=document.getElementById("step3-output");d.textContent=y.step3Result,ve(3,!1),Mt();const h=Ks(y.step3Result);ar(c,h)}catch(s){if(console.error("Pipeline failed:",s),Mt(),s.isUsageLimit){const{count:c}=bi();Ua(c,sr(),{openModal:!0});return}s.message,zo(document.getElementById("code-generator-model").value);const o=Jm(s,{architect:1,generator:2,review:3});ze(o);const a=document.getElementById(`step${o}-result`),l=document.getElementById(`step${o}-loading`),u=document.getElementById(`step${o}-output`);if(l&&l.classList.add("hidden"),a&&a.classList.remove("hidden"),u)if(s.isModelArmor)u.innerHTML=``;else{let c=s.message;s.message.includes("image input")?c=`This model doesn't support image input. Please use ${Kt(pi)} for image-based requests or remove image references from your prompt.`:(s.message.includes("Load failed")||s.message.includes("CORS"))&&(c="API connection failed. This might be due to CORS restrictions or network issues. Please check your API key and try again."),u.innerHTML=`
    -

    Connection Error

    -

    ${j(c)}

    -
    -

    Check if API key is valid

    -

    Try using a different model

    -

    Ensure network allows API calls

    -
    -
    `}Ho(o,"error")}finally{y.isRunning=!1,i&&(i.disabled=!1,i.innerHTML=` - - - Run Pipeline`),en()}}function a_(){const t=document.getElementById("code-generator-model").value,e=[pi,"anthropic/claude-opus-5","openai/gpt-5.6-sol"].filter(i=>i!==t),n=prompt(`Retry with different model? - -Current: ${t} - -Options: -1. ${e[0]} -2. ${e[1]} - -Enter 1 or 2:`);n==="1"?(document.getElementById("code-generator-model").value=e[0],Ns()):n==="2"&&(document.getElementById("code-generator-model").value=e[1],Ns())}async function l_(){const t=Fa();if(!t){ue("No code to commit. Please run the pipeline first.","warning");return}const e=await Ee("flutterflow"),n=await Ee("flutterflow_project_id");if(!e||!n){ue("FlutterFlow credentials not configured. Add your API Key and Project ID in settings.","warning"),ka();return}if(y.artifactBundle?.artifacts?.length>1){await c_();return}const{artifactType:i,artifactName:s,fileName:r}=oh(),o=dh(t,{artifactType:i,artifactName:s,fileName:r}),a=Gv(o);if(!a.canProceed){ue(`Pre-commit checks failed: ${a.issues.join("; ")}`,"error");return}Wa(o,a,null,null)}async function c_(){const t=await Ee("flutterflow"),e=await Ee("flutterflow_project_id");if(!t||!e){ue("FlutterFlow credentials not configured. Add your API Key and Project ID in settings.","warning"),ka();return}const n=zg(y.artifactBundle);if(n.errors.length>0){ue(`Bundle validation failed: ${n.errors.join("; ")}`,"error");return}const i=new Map(n.fileEntries.map(a=>[a.fileName,{content:a.content,type:a.type,path:a.path}])),s=er(i),r={canProceed:s.valid&&n.errors.length===0,issues:[...n.errors,...s.errors],warnings:[...n.warnings,...s.warnings]};if(!r.canProceed){ue(`Bundle validation failed: ${r.issues.join("; ")}`,"error");return}const o={content:n.fileEntries.map(a=>`// ${a.fileName} -${a.content}`).join(` - -`),fileName:`${n.fileEntries.length} files`,codeType:"bundle",artifactType:"Bundle",artifactName:n.title};Wa(o,r,n.dependencies,n)}function u_(t){let e=t.errorMap||new Map;!(e instanceof Map)&&typeof e=="object"&&(e=new Map(Object.entries(e)));let n=`
    -

    FlutterFlow Commit Failed

    -

    ${j(t.error)}

    `;if(e&&e.size>0){n+=`
    -

    Errors:

    -
      `;for(const[s,r]of e.entries()){const o=Bd(r);n+=`
    • - ${j(s)}: ${j(o)} -
    • `}n+="
    "}n+="
    ",n+=`
    - -
    `;const i=document.getElementById("step3-output");i&&(i.innerHTML=n,document.getElementById("btn-regenerate-from-error")?.addEventListener("click",()=>{d_(t.error,e)}))}async function d_(t,e){if(y.isRunning)return;const n=document.getElementById("code-generator-model").value;y.isRunning=!0;const i=document.getElementById("btn-regenerate-from-error");i&&(i.disabled=!0,i.innerHTML=` - - Fixing...`);try{let s=`The previous code had the following errors when committing to FlutterFlow: - -`;if(e&&e.size>0)for(const[c,d]of e.entries()){const h=Bd(d);s+=`File: ${c} -Error: ${h} - -`}else s+=`${t} -`;const r=$d({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,userFeedback:s});or(),at(2),ze(2),ve(2,!0),y.step2Result=await tr(r,n),Zs();const o=document.getElementById("step2-output"),a=xn(y.step2Result);o.textContent=a,o.dataset.raw=a,ve(2,!1),ze(3),at(3),ve(3,!0),y.step3Result=await nr(y.step2Result,y.step1Result),Xs();const l=document.getElementById("step3-output");l.textContent=y.step3Result,ve(3,!1),Mt();const u=Ks(y.step3Result);ar(a,u)}catch(s){console.error("Regeneration failed:",s),Mt(),ue(La(s,"Regeneration failed"),"error")}finally{y.isRunning=!1,i&&(i.disabled=!1,i.textContent="Fix Errors & Regenerate"),en()}}async function h_(){const t=document.getElementById("ff-status-dot"),e=document.getElementById("ff-status-text");if(!t||!e)return;const n=await Ee("flutterflow"),i=await Ee("flutterflow_project_id");n&&i?(t.className="w-2 h-2 rounded-full bg-green-500",e.textContent="FlutterFlow credentials configured",e.className="text-green-600"):n||i?(t.className="w-2 h-2 rounded-full bg-yellow-500",e.textContent="FlutterFlow credentials incomplete",e.className="text-yellow-600"):(t.className="w-2 h-2 rounded-full bg-red-500",e.textContent="FlutterFlow credentials not configured",e.className="text-red-600")}async function p_(t){try{const e=await fetch(`${Ze}/auth/send-magic-link`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:t})});if(!e.ok)throw new Error(`Failed to send magic link: HTTP ${e.status}`);return e.json()}catch(e){throw console.error("sendMagicLink failed:",{email:t,message:e.message,stack:e.stack}),e}}async function f_(t){try{const n=await(await fetch(`${Ze}/auth/verify-magic-link`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:t})})).json();if(n.error||!n.email||!n.sessionToken)throw new Error(n.error||"Invalid or expired link");return n}catch(e){throw console.error("verifyMagicLink failed:",{message:e.message,stack:e.stack}),e}}async function g_(t){try{const e=await fetch(`${Ze}/auth/refresh-session`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:t})});if(!e.ok)return console.error("refreshSession: non-OK response",{url:`${Ze}/auth/refresh-session`,status:e.status}),null;const n=await e.json();return n.error||!n.email||!n.sessionToken?(console.warn("refreshSession: validation failed",{error:n.error,hasEmail:!!n.email,hasToken:!!n.sessionToken}),null):n}catch(e){return console.error("refreshSession: fetch failed",{url:`${Ze}/auth/refresh-session`,message:e.message,stack:e.stack}),null}}function Nc(t,e){const n=hh(),i=(V.email||n.email)!==t;V.email=t,V.sessionToken=e,V.isVerified=!0,pe=kn({isLoading:!0}),localStorage.setItem(Is,JSON.stringify({email:t,sessionToken:e})),i&&Ha()}function Ba(){V.email=null,V.sessionToken=null,V.isVerified=!1,pe=kn({isResolved:!0}),localStorage.removeItem(Is),localStorage.removeItem(As)}function hh(){try{const t=localStorage.getItem(Is);if(!t)return{email:null,sessionToken:null};const e=JSON.parse(t);return!e.email||!e.sessionToken?{email:null,sessionToken:null}:e}catch(t){return console.warn("getStoredSession: failed to parse auth session:",t),localStorage.removeItem(Is),{email:null,sessionToken:null}}}async function m_(){const e=new URLSearchParams(window.location.search).get("token");if(e){window.history.replaceState({},"",window.location.pathname+window.location.hash);try{const{email:n,sessionToken:i}=await f_(e);Nc(n,i)}catch(n){ue(n.message||"Sign-in link invalid or expired.","error")}}else{const{email:n,sessionToken:i}=hh();if(n&&i){const s=await g_(i);s?Nc(s.email,s.sessionToken):Ba()}}ja()}function Da(){const t=document.getElementById("signin-modal");t&&Ve(t)}function v_(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("signin-modal");e&&Xe(e)}async function __(){const t=document.getElementById("signin-email-input"),e=document.getElementById("signin-submit-btn"),n=document.getElementById("signin-message"),i=zs(t?.value);if(!i||!/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/.test(i)||i.length>254){n&&(n.textContent="Please enter a valid email address.");return}e&&(e.disabled=!0,e.textContent="Sending…");const r=Dd(i);n&&r&&(n.textContent=r);try{const o=await p_(i);t&&o?.code!==Ki&&(t.value=""),n&&(n.textContent=Em(o,i)),e&&(e.textContent=o?.code===Ki?"Send Link":"Sent!"),e&&o?.code===Ki&&(e.disabled=!1)}catch(o){console.error("handleMagicLinkRequest: sendMagicLink failed",{email:i,err:o}),n&&(n.textContent="Something went wrong. Please try again."),e&&(e.disabled=!1,e.textContent="Send Link")}}function y_(){Ba(),Ha(),ja(),rr()}function ja(){const t=V.isVerified&&!!V.email,e=document.getElementById("auth-signedout"),n=document.getElementById("auth-signedin"),i=document.getElementById("auth-guest-usage");e&&e.classList.toggle("hidden",t),n&&n.classList.toggle("hidden",!t),i&&i.classList.toggle("hidden",t);const s=document.getElementById("auth-user-email");s&&(s.textContent=V.email||""),Qi(),rr()}async function ph(){try{if(typeof FingerprintJS>"u"){console.warn("resolveIdentity: FingerprintJS not loaded, skipping");return}const e=await(await FingerprintJS.load()).get(),n=e.visitorId,i=await fetch(cv,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({fingerprint:e.visitorId,cookie_id:n})});if(!i.ok)throw new Error(`Identity check HTTP ${i.status}`);const s=await i.json();if(Ke.userId=s.user_id,Ke.token=s.identity_token||null,Ke.status=s.status,Ke.resolved=!0,sessionStorage.setItem(av,s.user_id),Ke.token&&sessionStorage.setItem(lv,Ke.token),s.usage_count!==void 0){const r=Rt(),a=(s.usage_month||r)===r?s.usage_count:0;localStorage.setItem(Zt,JSON.stringify({count:a,month:r})),ii()}console.log(`Identity resolved: ${s.status} (${s.user_id.slice(0,8)}...) usage: ${s.usage_count??"n/a"}`)}catch(t){console.error("resolveIdentity failed:",t)}}let Ur=null;function w_(t=5e3){return Ke.resolved?Promise.resolve():(Ur||(Ur=ph().catch(e=>{console.warn("ensureIdentityReady: identity resolution failed",e)})),Promise.race([Ur,new Promise(e=>setTimeout(e,t))]))}function fh(){const t=Rt();try{const e=localStorage.getItem(Zt);return e?JSON.parse(e):{count:0,month:t}}catch(e){return console.warn("getUsageData: failed to parse usage storage",{key:Zt,month:t,err:e}),localStorage.removeItem(Zt),{count:0,month:t}}}function Rt(){const t=new Date;return`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,"0")}`}function bi(){const t=fh();return t.month!==Rt()?{count:0,month:Rt()}:t}function b_(){const e={count:bi().count+1,month:Rt()};return localStorage.setItem(Zt,JSON.stringify(e)),e}function ir(){return!!pe.isLoading}function Nt(){return!!pe.isResolved}function E_(t){if(!t)return null;const e=String(t).toLowerCase().replace(/[^a-z0-9]+/g,"_");return e==="pro"||e==="professional_plan"?"professional":e==="power_developer"||e==="power_plan"?"power":Object.prototype.hasOwnProperty.call(Cs,e)?e:null}function S_(t){return t&&Object.entries(Gd).find(([,e])=>e===t)?.[0]||null}function Di(...t){return t.find(e=>e!=null&&e!=="")}function x_(...t){return t.find(e=>e&&typeof e=="object")||{}}function k_(t){const e=t.data&&typeof t.data=="object"?t.data:t,n=x_(e.subscription,e.stripeSubscription,e.currentSubscription,e.customer?.subscriptions?.data?.[0],e.subscriptions?.data?.[0],e.subscriptions?.[0]),i=e.metadata||n.metadata||e.customer?.metadata||{},s=Di(e.priceId,e.price_id,e.stripePriceId,e.stripe_price_id,n.priceId,n.price_id,n.plan?.id,n.price?.id,n.items?.data?.[0]?.price?.id,n.items?.[0]?.price?.id,n.lines?.data?.[0]?.price?.id),r=Di(e.status,e.subscriptionStatus,e.subscription_status,n.status,"none"),o=E_(Di(e.tier,e.plan,e.planId,e.plan_id,e.subscriptionTier,e.subscription_tier,e.product,e.productName,n.tier,n.plan,i.tier,i.plan)),a=uv.has(String(r).toLowerCase()),l=e.active===!0||e.isSubscribed===!0||e.subscribed===!0||e.hasSubscription===!0,u=o||S_(s)||(a||l?"professional":"free");return kn({tier:u,status:r,periodEnd:Di(e.periodEnd,e.currentPeriodEnd,e.current_period_end,n.current_period_end,n.periodEnd,null),isResolved:!0})}function sr(){return Cs[pe.tier]??Cs.free}async function I_(){if(V.isVerified&&(!Nt()||ir())&&(await gh({force:!0}),rr()),V.isVerified&&!Nt())return ue("Could not verify your subscription. Please refresh or try Manage billing.","error"),!1;const{count:t}=bi(),e=sr();if(t>=e)return Ua(t,e,{openModal:!0}),!1;const n=Math.floor(e*.8);if(t>=n){const i=e-t;ue(`${i} run${i===1?"":"s"} remaining this month.`,"warning")}return!0}function Hr(){const t=document.getElementById("paywall-exhausted");t&&t.classList.add("hidden")}function Ua(t,e,n={}){An(!0);const i=document.getElementById("walkthrough-modal");i&&Xe(i,{restoreFocus:!1});const s=document.getElementById("ready-state");s&&s.classList.add("hidden");const r=document.getElementById("preview-frame-container");r&&(r.style.display="none");const o=document.getElementById("main-stage-container");o&&o.classList.add("visible");const a=document.getElementById("results-view");a&&a.classList.remove("visible"),document.body.classList.remove("results-fullscreen","results-with-sidebar");const l=document.getElementById("pipeline-progress");l&&l.classList.remove("visible");const u=document.getElementById("paywall-exhausted");if(!u){ue(`You've used all ${e} runs for this month. Upgrade to continue.`,"error"),Ls();return}const c=document.getElementById("paywall-exhausted-text");if(c){const h=pe.tier;h==="free"?c.textContent=`You've used all ${e} free generations this month. Upgrade to Pro for 50 generations/month and access to all AI models.`:c.textContent=`You've used all ${e} generations this month on your ${h} plan. Your limit resets next month.`}const d=document.getElementById("paywall-signin-btn");d&&d.classList.toggle("hidden",V.isVerified),u.classList.remove("hidden"),n.openModal&&Ls()}function zo(t){return pe.tier==="free"&&Ji.includes(t)?pi:t}function C_(){const t=document.getElementById("code-options-content"),e=document.getElementById("code-generator-model");if(!t||!e)return;const n=pe.tier,s=!(V.isVerified&&!Nt())&&n==="free";Array.from(e.options).forEach(o=>{const a=Kt(o.value),l=Ji.includes(o.value);o.textContent=l&&s?`${a} (PRO)`:a,o.disabled=!1}),s&&Ji.includes(e.value)&&(e.value=pi),e.disabled=!1,Ic.has(e)||(e.addEventListener("change",()=>{Nt()&&pe.tier==="free"&&Ji.includes(e.value)&&(e.value=pi,Ls()),Wo(e.value),Jd()}),Ic.add(e));let r=document.getElementById("model-selector-free-notice");s?(r||(r=document.createElement("p"),r.id="model-selector-free-notice",r.className="text-xs text-gray-400 mt-1",t.appendChild(r)),r.innerHTML='Free plan — Gemini only. '):r&&r.remove(),Wo(e.value)}function ii(){const t=document.getElementById("usage-counter");if(!t)return;if(V.isVerified&&ir()){t.textContent="Checking plan…",t.className="text-xs text-gray-500",Qi(),Hr();return}if(V.isVerified&&!Nt()){t.textContent="Plan check failed",t.className="text-xs text-red-600 font-medium",Qi(),Hr();return}const{count:e}=bi(),n=sr();t.textContent=`${e} / ${n} runs this month`;const i=n>0?e/n:0;t.className=i>=1?"text-xs text-red-600 font-medium":i>=.8?"text-xs text-yellow-600 font-medium":"text-xs text-gray-500",Qi(),e>=n&&!y.isRunning?Ua(e,n):Hr()}function Qi(){const t=document.getElementById("guest-usage-text");if(!t)return;const e=fh(),n=e.month===Rt()?e.count??0:0,i=Cs.free;t.textContent=`${n} / ${i} generations used`}async function gh(t={}){const e=t.force===!0;if(!V.isVerified||!V.sessionToken){pe=kn({isResolved:!0});return}pe={...pe,isLoading:!0,error:null};const n=localStorage.getItem(As);if(!e&&n)try{const{data:i,email:s,ts:r,version:o}=JSON.parse(n);if(o===Cc&&s===V.email&&Date.now()-r<300*1e3){pe={...i,isLoading:!1,isResolved:i.isResolved!==!1};return}}catch(i){console.warn("Failed to parse subscription cache:",i,"| raw value:",n)}try{const s=await(await fetch(`${Ze}/stripe/get-subscription`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:V.sessionToken,user_id:Ke.userId})})).json();if(s.error){if(["unauthorized","invalid session","expired session"].some(o=>String(s.error).toLowerCase().includes(o))){Ba(),ja();return}pe=kn({isResolved:!1,error:s.error});return}pe=k_(s),localStorage.setItem(As,JSON.stringify({version:Cc,data:pe,email:V.email,ts:Date.now()}))}catch(i){console.error("fetchSubscription failed:",i),pe={...pe,isLoading:!1,isResolved:!1,error:i.message}}}function Ha(){localStorage.removeItem(As)}async function A_(t){if(!V.isVerified||!V.sessionToken){mh(),Da();return}if(!Gd[t]){ue("Invalid plan selected.","error");return}const e=document.getElementById(`checkout-btn-${t}`);e&&(e.disabled=!0,e.textContent="Redirecting…");try{const i=await(await fetch(`${Ze}/stripe/create-checkout-session-intl`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tierId:t,sessionToken:V.sessionToken,currency:Xd()})})).json();if(i.error||!i.url)throw new Error(i.error||"Failed to create checkout session");const{url:s}=i;window.location.href=s}catch(n){console.error("startCheckout failed:",n),e&&(e.disabled=!1,e.textContent="Subscribe"),ue("Could not start checkout. Please try again.","error")}}async function F_(){if(!V.isVerified||!V.sessionToken){Da();return}const t=document.getElementById("manage-billing-btn");t&&(t.disabled=!0,t.textContent="Loading…");try{const n=await(await fetch(`${Ze}/stripe/create-portal-session`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:V.sessionToken})})).json();if(n.error||!n.url)throw new Error(n.error||"Failed to open billing portal");const{url:i}=n;window.location.href=i}catch(e){console.error("openCustomerPortal failed:",e),t&&(t.disabled=!1,t.textContent="Manage billing"),ue("Could not open billing portal. Please try again.","error")}}async function Ms(t,e,n,i={},s=[]){const o=new AbortController,a=setTimeout(()=>o.abort(),12e4);try{const l=await fetch(ov,{method:"POST",headers:{"Content-Type":"application/json",...Ke.token?{Authorization:`Bearer ${Ke.token}`}:{}},signal:o.signal,body:JSON.stringify({user_id:Ke.userId,step:t,model:e,prompt:n,images:s,context:i})}),u=await l.text();let c={};try{c=u?JSON.parse(u):{}}catch{c={}}if(l.status===429){c.serverCount!==void 0&&(localStorage.setItem(Zt,JSON.stringify({count:c.serverCount,month:Rt()})),ii());const p=new Error(c.message||"Monthly usage limit reached. Upgrade to continue.");throw p.isUsageLimit=!0,p}const d=fg(c,t);if(d)throw d;if(console.log(`[BuildShip] ${t} response keys:`,Object.keys(c),"content type:",typeof c.content),!l.ok)throw new Error(`${c.message||c.error||"BuildShip pipeline error"} (HTTP ${l.status})`);if(t==="generator")if(c.usage_status==="success"&&Number.isFinite(c.usage_count)){const p=Rt();(c.usage_month||p)===p&&(localStorage.setItem(Zt,JSON.stringify({count:c.usage_count,month:p})),ii())}else b_(),ii();let h=c.output||c.content;if(!h){const p=u?` (body: ${u.slice(0,120)})`:"";throw new Error(`BuildShip returned no output for step "${t}"${p}`)}return Array.isArray(h)&&(h=h.map(p=>typeof p=="string"?p:p.text||"").join("")),typeof h!="string"&&(h=JSON.stringify(h)),h}catch(l){throw l.name==="AbortError"?new Error(`BuildShip ${t} timed out after ${12e4/1e3}s`):l instanceof TypeError?new Error(`BuildShip unreachable: ${l.message}`):l}finally{clearTimeout(a)}}function P_(){const e=new URLSearchParams(window.location.search).get("checkout");e==="success"?(window.history.replaceState({},"",window.location.pathname+window.location.hash),Ha(),ue("Subscription active! Welcome aboard.","success")):e==="cancel"&&(window.history.replaceState({},"",window.location.pathname+window.location.hash),ue("Checkout cancelled.","info"))}function rr(){const t=V.isVerified&&!!V.email,e=pe.tier,n=t&&ir(),i=!t||Nt(),s=document.getElementById("subscription-tier-badge");if(s){const a={free:"Free",professional:"Professional",power:"Power Developer"},l={free:"bg-gray-100 text-gray-600",professional:"bg-indigo-100 text-indigo-700",power:"bg-purple-100 text-purple-700",unresolved:"bg-red-50 text-red-600"};s.textContent=n?"Checking…":i?a[e]||"Free":"Plan unavailable",s.className=`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${i?l[e]||l.free:l.unresolved}`}const r=document.getElementById("upgrade-prompt");r&&r.classList.toggle("hidden",!t||n||!i||e!=="free");const o=document.getElementById("manage-billing-btn");o&&o.classList.toggle("hidden",!t||n||i&&e==="free"),$_(i?e:null),C_(),Jd(),ii(),xh()}function $_(t){const e=["bg-gray-100","text-gray-500","cursor-default"];Object.entries({professional:{btnId:"checkout-btn-professional",defaultText:"Subscribe"},power:{btnId:"checkout-btn-power",defaultText:"Subscribe"}}).forEach(([s,{btnId:r,defaultText:o}])=>{const a=document.getElementById(r);a&&(s===t?(a.disabled=!0,a.textContent="Current plan",a.classList.add(...e)):(a.disabled=!1,a.textContent=o,a.classList.remove(...e)))});const i=document.getElementById("free-tier-current");i&&i.classList.toggle("hidden",t!=="free")}function qo(){const t=Xd(),e=document.getElementById("pro-price"),n=document.getElementById("power-price"),i=document.getElementById("plans-pro-price"),s=document.getElementById("plans-power-price"),r=document.getElementById("pro-price-note"),o=document.getElementById("power-price-note"),a=document.getElementById("plans-pro-price-note"),l=document.getElementById("plans-power-price-note");e&&(e.textContent=Bi(Oi.professional,t)),n&&(n.textContent=Bi(Oi.power,t)),i&&(i.textContent=Bi(Oi.professional,t)),s&&(s.textContent=Bi(Oi.power,t));const u="billed monthly";r&&(r.textContent=u),o&&(o.textContent=u),a&&(a.textContent=u),l&&(l.textContent=u)}function Ls(){qo();const t=document.getElementById("pricing-modal");t&&Ve(t),yv().then(()=>qo())}function mh(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("pricing-modal");e&&Xe(e)}function ue(t,e="info"){const n={success:"bg-green-600 text-white",error:"bg-red-600 text-white",warning:"bg-amber-500 text-white",info:"bg-gray-800 text-white"},i=document.createElement("div");i.className=`fixed bottom-6 left-1/2 -translate-x-1/2 px-5 py-3 rounded-lg text-sm font-medium shadow-lg z-50 transition-opacity duration-300 ${n[e]||n.info}`,i.textContent=t,document.body.appendChild(i),setTimeout(()=>{i.style.opacity="0",setTimeout(()=>i.remove(),300)},3500)}document.addEventListener("DOMContentLoaded",async()=>{tg(),hljs.configure({tabReplace:" ",classPrefix:"hljs-"}),T_(),await m_(),P_(),await gh(),rr(),qo(),await zv(),Dv();const t=document.getElementById("flutterflow-endpoint-select");if(t){const n=yi();t.value=n}sh(),ph();const e=document.getElementById("pipeline-input");e&&(e.addEventListener("input",()=>{kt===2&&e.value.trim().length>0&&(Ia(),Js())}),e.addEventListener("blur",()=>{const n=document.getElementById("walkthrough-modal");kt===2&&n&&Ve(n)}),e.addEventListener("keydown",n=>{if(n.key==="Tab"){const i=document.getElementById("walkthrough-modal");kt===2&&i&&setTimeout(()=>{Ve(i)},100)}})),window.addEventListener("commitStateChange",n=>{const{state:i}=n.detail;i===K.PREPARING||i===K.VALIDATING||i===K.PUSHING?(be.phaseId||_h(),Lc(i)):(i===K.SUCCESS||i===K.ERROR)&&(Lc(i),setTimeout(Os,1e3))}),sv({onSubmit:Ns}),qa()});function T_(){const t=document.getElementById("preview-frame-container");t&&(t.style.display="")}function R_(){const t=document.getElementById("welcome-video-player");t&&(t.addEventListener("click",Qt),document.addEventListener("keydown",Qt))}function Qt(){const t=document.getElementById("preview-frame-container"),e=document.getElementById("main-stage-container"),n=document.getElementById("ready-state");t&&(t.style.display="none"),e&&e.classList.add("visible"),n&&n.classList.remove("hidden");const i=document.getElementById("welcome-video-player");i&&i.removeEventListener("click",Qt),document.removeEventListener("keydown",Qt),sh()}let si=null;async function N_(){const t=document.getElementById("confirm-project-select");if(!t)return;const e=++Tc,n=()=>e===Tc,i=await Ee("flutterflow"),s=await Ee("flutterflow_project_id");if(n()){if(!i){t.innerHTML='',t.disabled=!0;return}t.disabled=!1,t.innerHTML='';try{const o=await new wi(i,"").listProjects();if(!n())return;if(!o||o.length===0){t.innerHTML='';return}t.innerHTML='',o.forEach(a=>{const l=document.createElement("option");l.value=a.id||a.projectId||"",l.textContent=a.name||a.projectName||`Project ${a.id}`,t.appendChild(l)}),s&&(t.value=s)}catch(r){if(!n())return;console.error("Failed to load projects for deploy:",r),t.innerHTML=''}}}function M_(){return document.getElementById("confirm-project-select")?.value?.trim()||null}function Wa(t,e,n,i=null){si={codeInfo:t,checks:e,deps:n,bundlePlan:i},document.getElementById("confirm-file-name").textContent=t.fileName,document.getElementById("confirm-artifact-type").textContent=t.artifactType,document.getElementById("confirm-file-size").textContent=`${(t.content.length/1024).toFixed(1)} KB`,document.getElementById("confirm-line-count").textContent=i?`${i.fileEntries.length} files`:t.content.split(` -`).length,N_();const s=document.getElementById("confirm-deps-list"),r=document.getElementById("confirm-deps-section");n&&Object.keys(n).length>0?(s.innerHTML=Object.entries(n).map(([u,c])=>{const d=c?`at least ${xt(c)}`:"version resolved from your project";return`
  • • ${xt(u)}: ${d}
  • `}).join(""),r.classList.remove("hidden")):r.classList.add("hidden");const o=document.getElementById("confirm-warnings-list"),a=document.getElementById("confirm-warnings-section");e.warnings&&e.warnings.length>0?(o.innerHTML=e.warnings.map(u=>`
  • • ${xt(u)}
  • `).join(""),a.classList.remove("hidden")):a.classList.add("hidden"),document.getElementById("confirm-code-preview").textContent=t.content,document.getElementById("code-preview-content").classList.add("hidden"),document.getElementById("code-preview-chevron").style.transform="rotate(0deg)";const l=document.getElementById("commit-confirm-modal");l&&Ve(l)}function vh(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("commit-confirm-modal");e&&Xe(e),si=null}function L_(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("commit-success-modal");e&&Xe(e);const n=["success-message","success-project-id","success-file-name","success-artifact-type","success-time","success-size"];for(const r of n){const o=document.getElementById(r);o&&(o.textContent="")}const i=document.getElementById("success-warnings-section");i&&i.classList.add("hidden");const s=document.getElementById("success-warnings-list");s&&(s.innerHTML="")}function Vo(t){const e=(g,m)=>{const v=document.getElementById(g);v&&(v.textContent=m||"")},n=t.metadata?.fileName||"",i=t.metadata?.projectId||"",s=t.metadata?.artifactType||"",r=t.elapsedTime?`${(t.elapsedTime/1e3).toFixed(1)}s`:"",o=t.metadata?.codeSize?`${(t.metadata.codeSize/1024).toFixed(1)} KB`:"";e("success-message",t.message||"Code committed successfully!"),e("success-project-id",i),e("success-file-name",n),e("success-artifact-type",s),e("success-time",r),e("success-size",o);const a=t.addedDependencies||[],l=document.getElementById("success-deps-row");l&&l.classList.toggle("hidden",a.length===0),e("success-deps",a.join(", "));const u=document.getElementById("success-open-ff-link");u&&i&&(u.href=`https://app.flutterflow.io/project/${i}`);const c=document.getElementById("success-warnings-section"),d=document.getElementById("success-warnings-list"),h=t.unverified||[],p=t.warnings||[];(p.length>0||h.length>0)&&c&&d&&(d.innerHTML=[...h.map(g=>`
  • Not verified before deploying: ${j(String(g))}
  • `),...p.map(([g,m])=>`
  • ${j(g)}: ${j(String(m))}
  • `)].join(""),c.classList.remove("hidden"));const f=document.getElementById("commit-success-modal");f&&Ve(f)}function Go(t){Os(),u_(t)}function O_(){const t=document.getElementById("code-preview-content"),e=document.getElementById("code-preview-chevron");t.classList.contains("hidden")?(t.classList.remove("hidden"),e.style.transform="rotate(90deg)"):(t.classList.add("hidden"),e.style.transform="rotate(0deg)")}const Mc={prepare:{message:"Preparing your code...",start:4,end:14},validate:{message:"Checking FlutterFlow credentials...",start:14,end:22},project:{message:"Reading your FlutterFlow project...",start:22,end:40},provision:{message:"Creating custom classes in FlutterFlow...",start:40,end:82},package:{message:"Packaging files for upload...",start:82,end:88},push:{message:"Pushing to FlutterFlow...",start:88,end:97},done:{message:"Complete!",start:100,end:100}},B_=[{after:0,text:"Starting a FlutterFlow build runner..."},{after:12,text:"Preparing the FlutterFlow AI workspace..."},{after:35,text:"Uploading your custom classes..."},{after:60,text:"FlutterFlow is applying the changes..."},{after:100,text:"Still working — this can take a couple of minutes..."}],be={sequence:[],phaseId:null,phaseStartedAt:null,timer:null,substatus:null,liveSubstatus:!1,start({withProvisioning:t=!1}={}){this.sequence=["prepare","validate","project"],t&&this.sequence.push("provision"),this.sequence.push("package","push","done");const e=document.getElementById("commit-progress-overlay");e&&(oc(e,!0,"Deploying to FlutterFlow"),Ve(e)),this.set("prepare")},set(t,e=null){if(!(!Mc[t]||t===this.phaseId)){if(!this.sequence.includes(t)){const n=this.sequence.indexOf("package");this.sequence.splice(n===-1?this.sequence.length:n,0,t)}this.phaseId=t,this.phaseStartedAt=Date.now(),this.substatus=e,this.liveSubstatus=!1,this.render(),this.timer&&clearInterval(this.timer),t!=="done"&&(this.timer=setInterval(()=>this.render(),500))}},setSubstatus(t){t&&(this.liveSubstatus=!0,this.substatus=t,this.render())},render(){const t=Mc[this.phaseId];if(!t)return;const e=(Date.now()-this.phaseStartedAt)/1e3,n=t.start+(t.end-t.start)*(1-Math.exp(-e/25));if(this.phaseId==="provision"&&!this.liveSubstatus){const o=B_.filter(a=>e>=a.after).pop();o&&(this.substatus=o.text)}const i=this.sequence.indexOf(this.phaseId),r=[`Step ${i===-1?1:i+1} of ${this.sequence.length}`];e>=5&&r.push(D_(e)),yh(this.phaseId==="done"?100:n,t.message,r.join(" · "),this.substatus)},stop(){this.timer&&clearInterval(this.timer),this.timer=null,this.phaseId=null;const t=document.getElementById("commit-progress-overlay");t&&(oc(t,!1),Xe(t,{force:!0,restoreFocus:!1}))}};function D_(t){const e=Math.floor(t);return e<60?`${e}s elapsed`:`${Math.floor(e/60)}m ${String(e%60).padStart(2,"0")}s elapsed`}function _h(t){be.start(t)}function Os(){be.stop()}function yh(t,e,n,i=null){const s=document.getElementById("commit-progress-bar"),r=document.getElementById("progress-message"),o=document.getElementById("progress-detail"),a=document.getElementById("progress-substatus");s&&(s.style.width=`${Math.round(t*10)/10}%`),r&&(r.textContent=e),o&&(o.textContent=n),a&&(a.textContent=i||"",a.classList.toggle("hidden",!i))}function Lc(t){const e={[K.PREPARING]:"prepare",[K.VALIDATING]:"validate",[K.PUSHING]:"project",[K.SUCCESS]:"done"};if(t===K.ERROR){be.timer&&clearInterval(be.timer),be.timer=null,yh(100,"Failed","Error occurred");return}const n=e[t];n&&be.set(n)}function j_(t){return t.bundlePlan?t.bundlePlan.fileEntries.some(e=>e.type===W.CODE_FILE):t.codeInfo?.codeType===W.CODE_FILE}async function U_(){if(!si){console.error("No pending commit data");return}const t=si;if(si=null,ni=M_(),vh(),_h({withProvisioning:j_(t)}),t.bundlePlan){const o=await Qv(t.bundlePlan,{pipelineResult:{step1Result:y.step1Result,selectedModel:document.getElementById("code-generator-model")?.value}});ni=null,Os(),o.success?Vo(o):Go(o);return}const{codeInfo:e}=t,{artifactType:n,artifactName:i,fileName:s}=oh(),r=await Xv(e.content,{artifactType:n,artifactName:i,fileName:s,pipelineResult:{step1Result:y.step1Result,selectedModel:document.getElementById("code-generator-model")?.value}});ni=null,Os(),r.success?Vo(r):Go(r)}window.runThinkingPipeline=Ns;window.toggleStep=n_;window.toggleSection=t_;window.selectWorkflowStep=ze;window.copyCode=i_;window.retryWithDifferentModel=a_;window.openApiKeysModal=ka;window.closeApiKeysModal=nh;window.closeWalkthroughModal=Rv;window.openWalkthroughModal=Tv;window.advanceWalkthrough=Ia;window.commitToFlutterFlow=Zv;function H_(){const t=document.getElementById("pipeline-input");t&&t.focus()}function W_(){const t=document.getElementById("advanced-settings");t&&(t.open=!0);const e=document.getElementById("code-generator-model");e&&(e.scrollIntoView({behavior:"smooth",block:"center"}),e.focus(),e.click())}window.focusPromptInput=H_;window.openModelSelector=W_;window.handlePromptImageSelect=vv;window.removePromptImage=_v;window.saveApiKeys=Lv;window.clearAllApiKeys=Ov;window.toggleKeyVisibility=Uv;window.handleWelcomeVideoEnd=R_;window.dismissWelcomeVideo=Qt;window.initiateCommitToFlutterFlow=l_;window.updateFlutterFlowCredentialStatus=h_;window.openCommitConfirmModal=Wa;window.closeCommitConfirmModal=vh;window.closeCommitSuccessModal=L_;window.showCommitSuccessModal=Vo;window.showCommitFailureModal=Go;window.toggleCodePreview=O_;window.confirmCommitToFlutterFlow=U_;window.runRefinement=s_;window.regenerateFromPastedErrors=o_;window.clearErrorInput=r_;window.setFlutterFlowEndpoint=$v;window.getFlutterFlowEndpoint=yi;window.commitProgress=be;window.openSignInModal=Da;window.closeSignInModal=v_;window.handleMagicLinkRequest=__;window.handleSignOut=y_;window.startCheckout=A_;window.openCustomerPortal=F_;window.openPricingModal=Ls;window.closePricingModal=mh;let mn=null,wh=null;const Oc=120;function or(){An(!0);const t=document.getElementById("pipeline-progress"),e=document.getElementById("results-view"),n=document.getElementById("ready-state");n&&n.classList.add("hidden"),e&&e.classList.remove("visible"),document.body.classList.remove("results-fullscreen","results-with-sidebar"),t&&t.classList.add("visible"),wh=Date.now();for(let i=1;i<=3;i++){const s=document.getElementById(`pdot-${i}`);s&&(s.className="progress-dot")}at(1),z_()}function at(t){const e={1:"Analyzing your prompt...",2:"Generating Dart code...",3:"Running code audit..."},n={1:"Step 1 of 3 — Prompt Architect",2:"Step 2 of 3 — Code Generator",3:"Step 3 of 3 — Code Review"},i=document.getElementById("progress-title-text"),s=document.getElementById("progress-substep-text");i&&(i.textContent=e[t]||e[1]),s&&(s.textContent=n[t]||n[1]);for(let r=1;r<=3;r++){const o=document.getElementById(`pdot-${r}`);o&&(r{const t=(Date.now()-wh)/1e3,e=document.getElementById("progress-elapsed"),n=document.getElementById("pipeline-progress-fill");e&&(e.textContent=`${Math.floor(t)}s`);const i=t/Oc*100,s=Math.min(95,i*(1-Math.exp(-t/(Oc*.6)))*1.2);n&&(n.style.width=`${s}%`)},250)}function Mt(){mn&&(clearInterval(mn),mn=null);const t=document.getElementById("pipeline-progress-fill");t&&(t.style.width="100%");for(let e=1;e<=3;e++){const n=document.getElementById(`pdot-${e}`);n&&(n.className="progress-dot completed")}setTimeout(()=>{const e=document.getElementById("pipeline-progress");e&&e.classList.remove("visible"),t&&(t.style.width="0%")},400)}function Cn(t,e=""){const n={pass:'',warning:'',fail:'',info:''};return``}function bh(t){return{pass:"Passed review",warning:"Needs attention",fail:"Blocking issues"}[t]||"Needs attention"}function q_(){return om({bundle:y.artifactBundle,reviewResult:y.step3Result})}function V_(t){return` -
    - ${Cn(t.severity)} -
    -
    ${j(t.message)}
    - ${t.suggestion?`
    ${j(t.suggestion)}
    `:""} - ${j(t.source)} -
    -
    - `}function G_(t){return` -
  • -
    - ${j(t.title)} - ${t.detail&&t.detail!==t.title?`

    ${j(t.detail)}

    `:""} -
    -
  • - `}function K_(t){const e=document.getElementById("results-summary-detail"),n=document.getElementById("results-title");if(!e)return;n&&(n.textContent=t.title);const i=t.score,s=i==null?"neutral":i>=80?"pass":i>=60?"warning":"fail",r=i==null?"":i>=80?"Strong":i>=60?"Needs work":"High risk",o=t.findings.length?` -
      - ${t.findings.map(l=>` -
    • - ${Cn(l.severity)} - - ${j(l.message)} - ${l.suggestion?`${j(l.suggestion)}`:""} - -
    • - `).join("")} -
    - `:"",a=t.manualSteps.length?` -
    -

    ${Cn("info")} Complete in FlutterFlow

    -

    For your information — these don't block the deploy. Finish them by hand in the FlutterFlow editor once the code is pushed.

    -
      - ${t.manualSteps.map(l=>` -
    • - ${j(l.title)} - ${l.detail&&l.detail!==l.title?`${j(l.detail)}`:""} -
    • - `).join("")} -
    -
    - `:"";e.innerHTML=` -
    -
    -

    ${j(t.summary)}

    - ${o} - ${a} -
    -
    - -
    - Is the generated code correct? -
    - - -
    -
    -
    -
    - `}function J_(t){const e=t.artifacts.find(l=>l.id===y.selectedArtifactId)||t.artifacts[0];if(!e)return"";const n={pass:{icon:"pass",message:"No file-specific issues were found."},warning:{icon:"warning",message:"This file needs attention, but Code Review did not return a specific finding."},fail:{icon:"fail",message:"This file is blocked, but Code Review did not return a specific finding."}}[e.status],i=e.findings.length?e.findings.map(V_).join(""):`
    ${Cn(n.icon)} ${j(n.message)}
    `,s=e.dependencies?.length?e.dependencies.map(l=>` -
  • ${j(l.name)}${l.version?` ${j(l.version)}`:""}${l.reason?`

    ${j(l.reason)}

    `:""}
  • - `).join(""):'
  • No external packages
  • ',r=e.imports?.length?e.imports.map(l=>`${j(l)}`).join(""):'No imports returned',o=e.publicApi?.length?e.publicApi.map(l=>`${j(l)}`).join(""):'No public API signature returned',a=e.relationships.length?e.relationships.map(l=>` -
  • ${j(l.from||"Bundle")} ${j(l.type)} ${j(l.to||"Bundle")}${l.description?`

    ${j(l.description)}

    `:""}
  • - `).join(""):'
  • No relationships for this file
  • ';return` -
    -
    - ${Cn(e.status)} ${j(bh(e.status))} -

    ${j(e.artifactName)}

    - ${e.description?`

    ${j(e.description)}

    `:""} -
    -
    - ${j(e.artifactType)} - ${j(e.fileName)} -
    -
    -
    -

    Code Review findings

    - ${i} -
    - ${e.manualSteps.length?` -
    -

    Manual FlutterFlow steps for this file

    -
      ${e.manualSteps.map(G_).join("")}
    -
    - `:""} -
    - File details -
    -
    -

    Dependencies

    -
      ${s}
    -
    -
    -

    Deployment

    -
    -
    Status
    ${j(e.deployStatus||"pending")}
    -
    Order
    ${e.index+1} of ${t.artifacts.length}
    -
    Path hint
    ${j(e.pathHint||"Not returned")}
    -
    -
    -
    -
    -

    Public API

    -
    ${o}
    -
    -
    -

    Imports

    -
    ${r}
    -
    -
    -

    Relationships

    -
      ${a}
    -
    -
    - `}function Y_(t){const e=document.getElementById("bundle-strip"),n=document.getElementById("results-summary-tab"),i=document.getElementById("artifact-tabs"),s=document.getElementById("results-file-count");if(n&&n.classList.toggle("active",y.resultsViewMode==="summary"),!t.artifacts.length){s&&(s.textContent="0 files"),e&&e.classList.remove("visible"),i&&(i.innerHTML="");return}if(s){const r=t.artifacts.length;s.textContent=`${r} ${r===1?"file":"files"}`}i&&(i.innerHTML=t.artifacts.map(r=>` - - `).join(""),i.onclick=r=>{const o=r.target.closest(".artifact-tab");o?.dataset?.artifactId&&Eh(o.dataset.artifactId)}),e&&e.classList.add("visible")}function za(){document.body.classList.add("results-fullscreen"),document.body.classList.add("results-with-sidebar");const t=document.getElementById("results-view"),e=document.getElementById("results-code-output"),n=document.getElementById("results-audit-output"),i=document.getElementById("results-summary-detail"),s=document.getElementById("artifact-results-split"),r=q_(),o=Fa();if(K_(r),Y_(r),e&&(e.textContent=""),e){const a=Vd(o);e.innerHTML=a}n&&(n.innerHTML=J_(r)),i&&i.classList.toggle("hidden",y.resultsViewMode!=="summary"),s&&s.classList.toggle("hidden",y.resultsViewMode!=="file"),t&&t.classList.add("visible")}function ar(t,e){An(!0),y.selectedArtifactId||(y.selectedArtifactId=Ss(y.artifactBundle).id),y.resultsViewMode="summary",document.body.classList.add("results-fullscreen");const n=document.getElementById("step3-output");n&&(n.textContent=""),za(),en();const i=document.getElementById("btn-feedback-up"),s=document.getElementById("btn-feedback-down");i&&(i.className="feedback-btn"),s&&(s.className="feedback-btn")}function Eh(t){y.selectedArtifactId=t,y.resultsViewMode="file",za()}function Z_(){y.resultsViewMode="summary",za()}function X_(){const t=document.getElementById("btn-copy-results"),e=Fa();navigator.clipboard.writeText(e).then(()=>{if(t){t.classList.add("copied");const n=t.querySelector("span");if(n){const i=n.textContent;n.textContent="Copied!",setTimeout(()=>{t.classList.remove("copied"),n.textContent=i},2e3)}}})}function Q_(t){const e=document.getElementById("btn-feedback-up"),n=document.getElementById("btn-feedback-down");t==="up"?(e.classList.toggle("active-up"),n.classList.remove("active-down")):(n.classList.toggle("active-down"),e.classList.remove("active-up")),Oa(t==="up"?"thumbsUp":"thumbsDown",y.step2Result,y.step1Result)}function ey(){const t=document.getElementById("error-input-panel");if(t){t.classList.remove("hidden"),t.style.display="flex";const e=document.getElementById("ff-error-paste-input");e&&setTimeout(()=>e.focus(),100)}}function Sh(){const t=document.getElementById("error-input-panel");t&&(t.classList.add("hidden"),t.style.display="none")}function An(t){const e=document.getElementById("generation-stage");e&&(t?(e.hidden=!1,e.inert=!1,requestAnimationFrame(()=>e.classList.add("is-active"))):(e.classList.remove("is-active"),e.inert=!0,setTimeout(()=>{e.classList.contains("is-active")||(e.hidden=!0)},260)))}function xh(){const t=V.isVerified&&!!V.email,e=pe.tier||"free",n=t&&ir(),i=!t||Nt(),r=n?"Checking…":i?{free:"Free",professional:"Pro",power:"Power"}[e]||"Free":"—",o=document.getElementById("topbar-plan");o&&(o.textContent=r);const a=document.getElementById("topbar-avatar");a&&(a.textContent=(V.email||"?")[0].toUpperCase());const l=bi(),u=`${l.count} / ${sr()} runs this month`,c=document.getElementById("topbar-credits-count");c&&(c.textContent=String(l.count));const d=document.getElementById("credits-balance");d&&(d.textContent=u);const h=document.getElementById("plans-free-current");h&&h.classList.toggle("hidden",e!=="free"||!i);const p=document.getElementById("plans-checkout-btn-professional");if(p){const g=e==="professional"&&i;p.disabled=g,p.textContent=g?"Current plan":"Subscribe"}const f=document.getElementById("plans-checkout-btn-power");if(f){const g=e==="power"&&i;f.disabled=g,f.textContent=g?"Current plan":"Subscribe"}}function ty(){xh();const t=document.getElementById("credits-modal");t&&Ve(t)}function ny(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("credits-modal");e&&Xe(e)}function kh(t,e=!0,n=!0){if(t=["home","account","plans"].includes(t)?t:"home",document.querySelectorAll(".view[data-view]").forEach(s=>{s.dataset.view===t?(s.hidden=!1,s.removeAttribute("inert"),requestAnimationFrame(()=>{s.classList.add("is-active"),n&&s.focus({preventScroll:!0})})):(s.classList.remove("is-active"),s.setAttribute("inert","true"),setTimeout(()=>{s.classList.contains("is-active")||(s.hidden=!0)},260))}),t!=="home")An(!1);else{const s=document.getElementById("main-stage-container");s&&s.classList.contains("visible")&&An(!0)}if(document.querySelectorAll(".nav-link[data-view]").forEach(s=>{const r=s.dataset.view===t;s.setAttribute("aria-current",r?"page":null),r||s.removeAttribute("aria-current")}),e){const s=t==="home"?"":`#${t}`;window.location.hash!==s&&window.history.pushState({view:t},"",s||"#")}}let Bc=!1;function qa(){const t=window.location.hash.replace(/^#/,"");kh(t||"home",!1,Bc),Bc=!0}window.addEventListener("popstate",t=>{qa()});window.addEventListener("hashchange",()=>{qa()});window.copyResultsCode=X_;window.selectArtifact=Eh;window.selectResultsSummary=Z_;window.submitResultsFeedback=Q_;window.showErrorInputPanel=ey;window.hideErrorInputPanel=Sh;window.setGenerationStageVisible=An;window.switchView=kh;window.openCreditsModal=ty;window.closeCreditsModal=ny; diff --git a/dist/assets/index-CleimGxe.css b/dist/assets/index-DcLSblVK.css similarity index 85% rename from dist/assets/index-CleimGxe.css rename to dist/assets/index-DcLSblVK.css index 70dbd25..dcb3d83 100644 --- a/dist/assets/index-CleimGxe.css +++ b/dist/assets/index-DcLSblVK.css @@ -1 +1 @@ -@font-face{font-family:Delight;src:url(/assets/Delight-VF-CnVpVuQk.ttf) format("truetype");font-weight:100 900;font-display:swap}:root{--bg: oklch(96.65% .0074 260.73);--surface: oklch(100% 0 0);--surface-translucent: oklch(100% 0 0 / .65);--surface-glass: oklch(100% 0 0 / .72);--surface-sunken: oklch(98.4% .004 260);--fg: oklch(20.77% .0398 265.75);--muted: oklch(48% .02 260);--muted-2: oklch(68% .018 260);--on-dark: oklch(100% 0 0);--border: oklch(90% .012 260);--border-strong: oklch(80% .02 260);--fill-hover: color-mix(in oklch, var(--fg) 5%, var(--surface));--fill-subtle: color-mix(in oklch, var(--fg) 6%, var(--surface));--fill-selected: color-mix(in oklch, var(--fg) 4%, var(--surface));--track: color-mix(in oklch, var(--fg) 7%, var(--surface));--avatar: oklch(88% .02 260);--accent: oklch(63% .22 32);--accent-soft: oklch(from var(--accent) l c h / .18);--accent-ring: oklch(from var(--accent) l c h / .45);--fx-ink: oklch(70% .13 250);--ok: oklch(52% .11 165);--ok-soft: oklch(52% .11 165 / .12);--warn: oklch(66% .13 70);--warn-soft: oklch(66% .13 70 / .14);--bad: oklch(55% .19 25);--bad-soft: oklch(55% .19 25 / .1);--disabled-bg: oklch(88% .015 260);--disabled-fg: oklch(58% .02 260);--font-display: "Delight", "Outfit", "DM Sans", system-ui, sans-serif;--font-body: "Delight", "Outfit", "DM Sans", system-ui, sans-serif;--font-mono: "DM Mono", ui-monospace, SFMono-Regular, Menlo, monospace;--fw-ui: 560;--fw-bold: 620;--fw-black: 700;--ls-display: -.04em;--ls-heading: -.03em;--ls-mono: .13em;--fs-display: 54px;--fs-h2: 28px;--fs-h3: 22px;--fs-h4: 18px;--fs-lead: 17px;--fs-body: 14.5px;--fs-small: 13.5px;--fs-caption: 12.5px;--fs-mono: 11.5px;--fs-micro: 10.5px;--lh-display: 1.04;--lh-heading: 1.15;--lh-body: 1.6;--radius-xl: 22px;--radius-lg: 20px;--radius-md: 16px;--radius-sm: 14px;--radius-control: 12px;--radius-nav: 11px;--radius-icon: 10px;--radius-chip: 999px;--radius-badge: 7px;--shadow-sm: 0 1px 2px oklch(20% .03 260 / .06);--shadow-md: 0 1px 2px oklch(20% .03 260 / .06), 0 18px 46px -22px oklch(20% .03 260 / .3);--shadow-control: 0 2px 6px oklch(20% .03 260 / .22);--shadow-composer: 0 0 0 3px var(--accent-soft), 0 1px 2px oklch(20% .03 260 / .06), 0 0 44px -8px oklch(63% .22 32 / .16), 0 20px 52px -20px oklch(63% .22 32 / .18);--blur-chrome: 14px;--ease: cubic-bezier(.2, 0, 0, 1);--ease-overshoot: cubic-bezier(.32, 1.38, .5, 1);--t-fast: .15s;--t-enter: .22s;--t-reveal: .5s;--t-progress: .7s;--t-ring: .9s;--t-morph: 1.12s;--touch: 44px;--control-h: 46px;--stage-w: 1920px;--stage-h: 1080px;--measure-prose: 62ch;--measure-lead: 68ch}:focus-visible{outline:2px solid var(--accent);outline-offset:2px}@media(prefers-reduced-motion:reduce){*,*:before,*:after{scroll-behavior:auto!important;transition-duration:.01ms!important;transition-delay:0ms!important;animation-duration:.01ms!important;animation-iteration-count:1!important}}:where(button,[role=button],input,select,textarea,a){-webkit-tap-highlight-color:transparent}:where(button,[role=button],.control-button,.icon-button){min-height:44px;border-radius:var(--radius-md, 12px);transition:color var(--motion-fast, .16s) ease,background-color var(--motion-fast, .16s) ease,border-color var(--motion-fast, .16s) ease,box-shadow var(--motion-fast, .16s) ease,transform var(--motion-fast, .16s) ease,opacity var(--motion-fast, .16s) ease}:where(.icon-button,.modal-close,button:has(>svg:only-child)){min-width:44px;min-height:44px;display:inline-flex;align-items:center;justify-content:center}:where(button,[role=button],input,select,textarea,a[href]):focus-visible{outline:3px solid color-mix(in srgb,var(--accent, #3b82f6) 45%,transparent);outline-offset:2px}:where(button,[role=button]):active:not(:disabled){transform:scale(.98)}:where(button,[role=button]):disabled,:where(button,[role=button])[aria-disabled=true]{cursor:not-allowed;opacity:.5;box-shadow:none}:where(button,[role=button])[aria-busy=true]{cursor:progress;pointer-events:none}:where(button,[role=button])[aria-busy=true]:after{content:"";width:1em;height:1em;margin-inline-start:.55em;border:2px solid currentColor;border-right-color:transparent;border-radius:50%;animation:shared-control-spin .7s linear infinite}:where(input,select,textarea,.control-field){min-height:44px;border:1px solid var(--border, #dfe3ea);border-radius:var(--radius-md, 12px);background:var(--surface-sunken, #f8fafc)}:where(.badge,.sb-section-badge,.results-file-count,.pm-popular-badge){display:inline-flex;align-items:center;border-radius:999px;font-weight:600}:where(.panel,.results-panel,.pm-card){border:1px solid var(--border, #dfe3ea);border-radius:var(--radius-lg, 16px);background:var(--surface, #fff)}.modal-overlay{overflow:auto;overscroll-behavior:contain;padding:max(16px,env(safe-area-inset-top)) max(16px,env(safe-area-inset-right)) max(16px,env(safe-area-inset-bottom)) max(16px,env(safe-area-inset-left))}.modal-overlay.open .modal-content{transform:scale(1) translateY(0)!important}.modal-overlay[aria-hidden=true]{pointer-events:none}.modal-overlay[aria-busy=true]{cursor:progress}.modal-content{width:min(100%,680px);max-height:calc(100dvh - 32px)!important;overflow:auto!important;overscroll-behavior:contain}.modal-content>:is(.border-t,.wt-footer){position:sticky;bottom:0;z-index:2;background:#fff}.modal-content>:is(.border-b,.pm-header){position:sticky;top:0;z-index:2;background:#fff}@media(max-width:480px),(max-height:600px){.modal-overlay{align-items:flex-start;padding:8px}.modal-content{max-height:calc(100dvh - 16px)!important;border-radius:14px}}@media(hover:hover){:where(button,[role=button]):hover:not(:disabled):not([aria-disabled=true]){filter:brightness(.97)}}@media(prefers-reduced-motion:reduce){*,*:before,*:after{scroll-behavior:auto!important;animation-duration:.01ms!important;transition-duration:.01ms!important}}@keyframes shared-control-spin{to{transform:rotate(360deg)}}.hero-field{position:absolute;inset:0;overflow:hidden;z-index:-2;pointer-events:none}.fx-grid{position:absolute;inset:0;width:100%;height:100%;display:block;z-index:-2;pointer-events:none;opacity:0;transition:opacity var(--t-reveal) var(--ease)}.fx-grid.is-ready{opacity:1}.fx-mask{position:absolute;z-index:-1;pointer-events:none;background:var(--bg);filter:blur(46px)}.fx-mask-hero{left:50%;top:50%;width:980px;height:520px;transform:translate(-50%,-54%)}.fx-mask-top{left:-48px;right:-48px;top:-48px;height:132px}.fx-mask-bottom{left:-48px;right:-48px;bottom:-48px;height:132px}@media(max-width:920px){.fx-mask{filter:blur(36px)}.fx-mask-hero{width:92%;height:62%;top:50%;transform:translate(-50%,-50%)}.fx-mask-top{height:104px}.fx-mask-bottom{height:124px}}@media(prefers-reduced-motion:reduce){.hero-field,.fx-grid,.fx-mask{display:none}} +@font-face{font-family:Delight;src:url(/assets/Delight-VF-CnVpVuQk.ttf) format("truetype");font-weight:100 900;font-display:swap}:root{--bg: oklch(96.65% .0074 260.73);--surface: oklch(100% 0 0);--surface-translucent: oklch(100% 0 0 / .65);--surface-glass: oklch(100% 0 0 / .72);--surface-sunken: oklch(98.4% .004 260);--fg: oklch(20.77% .0398 265.75);--muted: oklch(48% .02 260);--muted-2: oklch(68% .018 260);--on-dark: oklch(100% 0 0);--border: oklch(90% .012 260);--border-strong: oklch(80% .02 260);--fill-hover: color-mix(in oklch, var(--fg) 5%, var(--surface));--fill-subtle: color-mix(in oklch, var(--fg) 6%, var(--surface));--fill-selected: color-mix(in oklch, var(--fg) 4%, var(--surface));--track: color-mix(in oklch, var(--fg) 7%, var(--surface));--avatar: oklch(88% .02 260);--accent: oklch(63% .22 32);--accent-soft: oklch(from var(--accent) l c h / .18);--accent-ring: oklch(from var(--accent) l c h / .45);--fx-ink: oklch(70% .13 250);--ok: oklch(52% .11 165);--ok-soft: oklch(52% .11 165 / .12);--warn: oklch(66% .13 70);--warn-soft: oklch(66% .13 70 / .14);--bad: oklch(55% .19 25);--bad-soft: oklch(55% .19 25 / .1);--disabled-bg: oklch(88% .015 260);--disabled-fg: oklch(58% .02 260);--font-display: "Delight", "Outfit", "DM Sans", system-ui, sans-serif;--font-body: "Delight", "Outfit", "DM Sans", system-ui, sans-serif;--font-mono: "DM Mono", ui-monospace, SFMono-Regular, Menlo, monospace;--fw-ui: 560;--fw-bold: 620;--fw-black: 700;--ls-display: -.04em;--ls-heading: -.03em;--ls-mono: .13em;--fs-display: 54px;--fs-h2: 28px;--fs-h3: 22px;--fs-h4: 18px;--fs-lead: 17px;--fs-body: 14.5px;--fs-small: 13.5px;--fs-caption: 12.5px;--fs-mono: 11.5px;--fs-micro: 10.5px;--lh-display: 1.04;--lh-heading: 1.15;--lh-body: 1.6;--radius-xl: 22px;--radius-lg: 20px;--radius-md: 16px;--radius-sm: 14px;--radius-control: 12px;--radius-nav: 11px;--radius-icon: 10px;--radius-chip: 999px;--radius-badge: 7px;--shadow-sm: 0 1px 2px oklch(20% .03 260 / .06);--shadow-md: 0 1px 2px oklch(20% .03 260 / .06), 0 18px 46px -22px oklch(20% .03 260 / .3);--shadow-control: 0 2px 6px oklch(20% .03 260 / .22);--shadow-composer: 0 0 0 3px var(--accent-soft), 0 1px 2px oklch(20% .03 260 / .06), 0 0 44px -8px oklch(63% .22 32 / .16), 0 20px 52px -20px oklch(63% .22 32 / .18);--blur-chrome: 14px;--ease: cubic-bezier(.2, 0, 0, 1);--ease-overshoot: cubic-bezier(.32, 1.38, .5, 1);--t-fast: .15s;--t-enter: .22s;--t-reveal: .5s;--t-progress: .7s;--t-ring: .9s;--t-morph: 1.12s;--touch: 44px;--control-h: 46px;--stage-w: 1920px;--stage-h: 1080px;--measure-prose: 62ch;--measure-lead: 68ch}:focus-visible{outline:2px solid var(--accent);outline-offset:2px}@media(prefers-reduced-motion:reduce){*,*:before,*:after{scroll-behavior:auto!important;transition-duration:.01ms!important;transition-delay:0ms!important;animation-duration:.01ms!important;animation-iteration-count:1!important}}:where(button,[role=button],input,select,textarea,a){-webkit-tap-highlight-color:transparent}:where(button,[role=button],.control-button,.icon-button){min-height:44px;border-radius:var(--radius-md, 12px);transition:color var(--motion-fast, .16s) ease,background-color var(--motion-fast, .16s) ease,border-color var(--motion-fast, .16s) ease,box-shadow var(--motion-fast, .16s) ease,transform var(--motion-fast, .16s) ease,opacity var(--motion-fast, .16s) ease}:where(.icon-button,.modal-close,button:has(>svg:only-child)){min-width:44px;min-height:44px;display:inline-flex;align-items:center;justify-content:center}:where(button,[role=button],input,select,textarea,a[href]):focus-visible{outline:3px solid color-mix(in srgb,var(--accent, #3b82f6) 45%,transparent);outline-offset:2px}:where(button,[role=button]):active:not(:disabled){transform:scale(.98)}:where(button,[role=button]):disabled,:where(button,[role=button])[aria-disabled=true]{cursor:not-allowed;opacity:.5;box-shadow:none}:where(button,[role=button])[aria-busy=true]{cursor:progress;pointer-events:none}:where(button,[role=button])[aria-busy=true]:after{content:"";width:1em;height:1em;margin-inline-start:.55em;border:2px solid currentColor;border-right-color:transparent;border-radius:50%;animation:shared-control-spin .7s linear infinite}:where(input,select,textarea,.control-field){min-height:44px;border:1px solid var(--border, #dfe3ea);border-radius:var(--radius-md, 12px);background:var(--surface-sunken, #f8fafc)}:where(.badge,.sb-section-badge,.results-file-count,.pm-popular-badge){display:inline-flex;align-items:center;border-radius:999px;font-weight:600}:where(.panel,.results-panel,.pm-card){border:1px solid var(--border, #dfe3ea);border-radius:var(--radius-lg, 16px);background:var(--surface, #fff)}.modal-overlay{overflow:auto;overscroll-behavior:contain;padding:max(16px,env(safe-area-inset-top)) max(16px,env(safe-area-inset-right)) max(16px,env(safe-area-inset-bottom)) max(16px,env(safe-area-inset-left))}.modal-overlay.open .modal-content{transform:scale(1) translateY(0)!important}.modal-overlay[aria-hidden=true]{pointer-events:none}.modal-overlay[aria-busy=true]{cursor:progress}.modal-content{width:min(100%,680px);max-height:calc(100dvh - 32px)!important;overflow:auto!important;overscroll-behavior:contain}.modal-content>:is(.border-t,.wt-footer){position:sticky;bottom:0;z-index:2;background:#fff}.modal-content>:is(.border-b,.pm-header){position:sticky;top:0;z-index:2;background:#fff}@media(max-width:480px),(max-height:600px){.modal-overlay{align-items:flex-start;padding:8px}.modal-content{max-height:calc(100dvh - 16px)!important;border-radius:14px}}@media(hover:hover){:where(button,[role=button]):hover:not(:disabled):not([aria-disabled=true]){filter:brightness(.97)}}@media(prefers-reduced-motion:reduce){*,*:before,*:after{scroll-behavior:auto!important;animation-duration:.01ms!important;transition-duration:.01ms!important}}@keyframes shared-control-spin{to{transform:rotate(360deg)}}.hero-field{position:absolute;inset:0;overflow:hidden;z-index:-2;pointer-events:none}.fx-grid{position:absolute;inset:0;width:100%;height:100%;display:block;z-index:-2;pointer-events:none;opacity:0;transition:opacity var(--t-reveal) var(--ease)}.fx-grid.is-ready{opacity:1}.fx-mask{position:absolute;z-index:-1;pointer-events:none;background:var(--bg);filter:blur(46px)}.fx-mask-hero{left:50%;top:50%;width:980px;height:520px;transform:translate(-50%,-54%)}.fx-mask-top{left:-48px;right:-48px;top:-48px;height:132px}.fx-mask-bottom{left:-48px;right:-48px;bottom:-48px;height:132px}@media(max-width:920px){.fx-mask{filter:blur(36px)}.fx-mask-hero{width:92%;height:62%;top:50%;transform:translate(-50%,-50%)}.fx-mask-top{height:104px}.fx-mask-bottom{height:124px}}@media(prefers-reduced-motion:reduce){.hero-field,.fx-grid,.fx-mask{display:none}}.pipeline-glyph.logo-loop{position:relative;width:100%;height:88px;margin:0 0 12px;overflow:hidden;pointer-events:none;color:var(--fg)}.loop-mark,.loop-shadow{position:absolute}.loop-mark{left:0;top:50%;width:52px;height:52px;margin:-26px 0 0;will-change:transform}.loop-piece{position:absolute;inset:0;display:block;will-change:transform,opacity}.loop-piece svg{display:block;width:100%;height:100%;overflow:visible}.loop-halo{position:absolute;left:50%;top:50%;width:74px;height:74px;margin:-37px 0 0 -37px;border-radius:50%;background:radial-gradient(circle,color-mix(in oklch,var(--accent) 60%,transparent),transparent 64%);filter:blur(5px);opacity:.09;will-change:transform,opacity}.loop-shadow{left:var(--mark-c, 26px);bottom:13px;width:46px;height:6px;margin-left:-23px;border-radius:50%;background:color-mix(in oklch,var(--fg) 26%,transparent);opacity:0;will-change:transform,opacity}@media(max-width:920px){.pipeline-glyph.logo-loop{height:66px;margin-bottom:8px}.loop-mark{width:40px;height:40px;margin:-20px 0 0}.loop-halo{width:58px;height:58px;margin:-29px 0 0 -29px}.loop-shadow{bottom:6px}} diff --git a/dist/index.html b/dist/index.html index 6633c19..82fb04d 100644 --- a/dist/index.html +++ b/dist/index.html @@ -916,6 +916,99 @@ .results-action-bar .btn-error-regen { flex-grow: 1.45; } + .results-action-scope { + flex: 0 0 auto; + display: block; + margin: 10px 24px 4px; + font-size: 11px; + color: var(--muted, #64748b); + text-align: center; + } + .results-replacement-error { + border: 1px solid #fbbf24; + background: #fffbeb; + border-radius: var(--radius-lg, 16px); + margin: 0 24px 12px; + padding: 12px 14px; + } + .results-replacement-error-body { + display: flex; + align-items: center; + gap: 10px; + flex-wrap: wrap; + } + .results-replacement-error-icon { + width: 20px; + height: 20px; + flex: 0 0 20px; + color: #d97706; + } + .results-replacement-error-text { + display: flex; + flex-direction: column; + gap: 2px; + flex: 1 1 200px; + min-width: 180px; + } + .results-replacement-error-text strong { + color: #b45309; + font-size: 12.5px; + } + .results-replacement-error-text span { + color: #92400e; + font-size: 12px; + } + .results-replacement-error .btn-header-action { + min-height: 36px; + padding: 6px 14px; + } + /* The shared .btn-header-action sets display:flex, which would otherwise + override the hidden attribute; the replacement banner shows only the + action that can resolve the failure (upgrade vs retry). */ + .results-replacement-error .btn-header-action[hidden] { + display: none; + } + + /* Shared-control styling for the pasted-build-error input overlay. */ + .error-input-card { + background: var(--surface, #fff); + border: 1px solid var(--border, #e5e7eb); + border-radius: var(--radius-lg, 16px); + box-shadow: 0 16px 48px -12px rgba(0, 0, 0, 0.18); + padding: 20px; + display: flex; + flex-direction: column; + gap: 12px; + } + .error-input-header { + display: flex; + align-items: center; + justify-content: space-between; + gap: 10px; + } + .error-input-textarea { + width: 100%; + min-height: 160px; + resize: vertical; + background: #fffbf0; + border-color: #fcd34d; + color: #78350f; + font-family: "DM Mono", "SFMono-Regular", ui-monospace, monospace; + font-size: 12.5px; + line-height: 1.6; + } + .error-input-textarea:focus-visible { + border-color: #f59e0b; + box-shadow: 0 0 0 3px color-mix(in srgb, #f59e0b 35%, transparent); + } + .btn-error-input-cancel { + background: transparent; + color: var(--muted, #64748b); + border: 1px solid var(--border, #e5e7eb); + } + .btn-error-input-cancel:hover:not(:disabled) { + background: var(--surface-sunken, #f1f5f9); + } .btn-deploy-results { background: linear-gradient(135deg, #6366f1 0%, #4f46e5 100%); color: #fff; @@ -1346,6 +1439,36 @@ line-height: 1.45; } .summary-findings .review-status-icon { margin-top: 2px; } + .summary-bundle-warnings { + margin: 16px 0 0; + padding: 12px 14px; + border: 1px solid #fcd34d; + border-radius: 10px; + background: #fffbeb; + } + .summary-bundle-warnings h4 { + display: flex; + align-items: center; + gap: 6px; + margin: 0 0 6px; + font-size: 12px; + font-weight: 700; + letter-spacing: 0.06em; + text-transform: uppercase; + color: #92400e; + } + .summary-bundle-warnings ul { + margin: 0; + padding: 0; + list-style: none; + display: grid; + gap: 5px; + } + .summary-bundle-warnings li { + color: #78350f; + font-size: 13.5px; + line-height: 1.45; + } .review-score-feedback { width: 100%; margin-top: 10px; @@ -1432,6 +1555,19 @@ } .code-copy-button:hover { color: #fff; border-color: #6b7280; background: #333544; } .code-copy-button.copied { color: #bbf7d0; border-color: #166534; background: #14532d; } + .results-copy-status { + position: absolute; + z-index: 2; + top: 16px; + left: 16px; + max-width: calc(100% - 140px); + font-size: 11.5px; + font-weight: 600; + line-height: 1.3; + color: #99a0b5; + } + .results-copy-status.ok { color: #4ade80; } + .results-copy-status.fail { color: #fca5a5; } body.results-fullscreen .panel-code-wrap pre { padding-top: 56px; } body.results-fullscreen .results-action-bar { display: grid; @@ -1538,6 +1674,11 @@ color: #dc2626; border-color: #fca5a5; } + .feedback-btn:disabled { + opacity: 0.5; + cursor: default; + pointer-events: none; + } /* ── Pipeline Progress Bar ───────────────────────── */ .pipeline-progress { @@ -1648,6 +1789,189 @@ background: #22c55e; } + /* ── Pipeline: real stage, note and failure states (STU-377) ── */ + .pipeline-progress { + overflow-y: auto; + gap: 0; + } + .pipeline-prompt-recap { + width: 100%; + max-width: 400px; + margin-bottom: 24px; + text-align: left; + padding: 14px 16px; + border: 1px solid var(--border); + border-radius: var(--radius-md, 12px); + background: var(--surface); + } + .pipeline-prompt-kicker { + font-family: var(--font-mono); + font-size: 11px; + letter-spacing: var(--ls-mono); + text-transform: uppercase; + color: var(--muted); + margin-bottom: 6px; + } + .pipeline-prompt-text { + font-size: 14px; + color: var(--fg); + overflow-wrap: anywhere; + } + .pipeline-prompt-edit { + margin-top: 8px; + padding: 0; + min-height: 44px; + background: none; + border: none; + color: var(--accent); + font: inherit; + font-size: 13px; + cursor: pointer; + text-decoration: underline; + text-underline-offset: 3px; + } + /* A finished or failed run has nothing left to spin for. */ + .pipeline-progress[data-run-state="failed"] .pipeline-progress-icon::after, + .pipeline-progress[data-run-state="settled"] .pipeline-progress-icon::after { + animation: none; + border-top-color: var(--border); + } + .pipeline-progress[data-run-state="failed"] .progress-fill { + animation: none; + background: var(--bad); + } + + .progress-steps-dots { + flex-wrap: wrap; + justify-content: center; + gap: 4px; + } + .progress-stage { + display: inline-flex; + flex-direction: column; + align-items: center; + gap: 6px; + min-height: 44px; + padding: 6px 10px; + background: none; + border: none; + font: inherit; + font-size: 11px; + color: var(--muted-2); + cursor: pointer; + } + .progress-stage:disabled { + cursor: default; + } + .progress-stage[data-state="active"] .progress-dot { + background: #6366f1; + box-shadow: 0 0 8px rgba(99, 102, 241, 0.4); + } + .progress-stage[data-state="done"] .progress-dot { + background: #22c55e; + } + .progress-stage[data-state="failed"] .progress-dot { + background: var(--bad); + } + .progress-stage[data-state="active"] .progress-stage-label, + .progress-stage[data-state="done"] .progress-stage-label { + color: var(--fg); + } + .progress-stage[aria-pressed="true"] .progress-stage-label { + text-decoration: underline; + text-underline-offset: 3px; + } + + .pipeline-note { + margin-top: 16px; + max-width: 400px; + font-size: 12.5px; + color: var(--muted); + } + + .pipeline-failure { + margin-top: 24px; + width: 100%; + max-width: 420px; + text-align: left; + padding: 16px; + border: 1px solid var(--bad); + border-radius: var(--radius-md, 12px); + background: var(--bad-soft); + } + .pipeline-failure-title { + font-family: var(--font-display); + font-size: 15px; + font-weight: var(--fw-bold); + color: var(--fg); + margin-bottom: 6px; + } + .pipeline-failure-message, + .pipeline-failure-hint { + font-size: 13.5px; + line-height: 1.5; + color: var(--fg); + overflow-wrap: anywhere; + } + .pipeline-failure-hint { + margin-top: 8px; + color: var(--muted); + font-size: 12.5px; + } + .pipeline-failure-actions { + display: flex; + flex-wrap: wrap; + gap: 10px; + margin-top: 14px; + } + .pipeline-failure-actions button { + flex: 1 1 140px; + min-height: 44px; + padding: 0 16px; + border-radius: var(--radius-md, 12px); + border: 1px solid var(--border); + background: var(--surface); + color: var(--fg); + font: inherit; + font-size: 13.5px; + font-weight: var(--fw-ui); + cursor: pointer; + } + .pipeline-failure-actions button[data-variant="primary"] { + background: var(--accent); + border-color: var(--accent); + color: #fff; + } + + /* The authored coral outline that morphs the composer into the pipeline + panel, and the pipeline panel into the expanded Results view. */ + /* The composer's send button carries its own busy spinner, so the shared + control spinner must not double it up. */ + .send[aria-busy="true"]::after { content: none; } + + /* Outline only: the destination surface is already in place underneath, + so the morph never hides real state while it plays. */ + .composer-morph { + position: fixed; + z-index: 45; + pointer-events: none; + border: 2px solid var(--accent); + border-radius: 20px; + box-shadow: var(--shadow-composer); + background: transparent; + } + + @media (max-width: 640px) { + .pipeline-progress { padding: 24px 16px 32px; justify-content: flex-start; } + .pipeline-progress-icon { width: 56px; height: 56px; margin-bottom: 18px; } + .pipeline-failure-actions button { flex: 1 1 100%; } + } + @media (prefers-reduced-motion: reduce) { + .pipeline-progress-icon::after, + .progress-fill { animation: none; } + .composer-morph { display: none; } + } + /* ── Modals ────────────────────────────────────────── */ .modal-overlay { position: fixed; @@ -1719,357 +2043,257 @@ font-family: "Delight", "DM Sans", sans-serif; } - #usage-counter { font-size: 12px; color: var(--muted-2); } - #subscription-tier-badge { - display: inline-flex; - align-items: center; - padding: 3px 10px; - border-radius: 12px; - font-size: 11px; - font-weight: 600; - background: var(--accent-soft); - color: var(--accent); - } - - /* ── Walkthrough Modal Redesign ─────────────────────── */ - .wt-hero { - display: flex; - align-items: center; - gap: 28px; - padding: 32px 32px 24px; - background: linear-gradient(168deg, #f0f4ff 0%, #f8f9ff 40%, #fff 100%); - position: relative; - overflow: hidden; + /* ── Sign In Modal ─────────────────────────────────── */ + .signin-modal-content { + max-width: 420px; + border-radius: var(--radius-xl); + background: var(--surface); } - - .wt-hero::before { - content: ''; - position: absolute; - top: -40px; - right: -40px; - width: 180px; - height: 180px; - background: radial-gradient(circle, rgba(139, 92, 246, 0.06) 0%, transparent 70%); - border-radius: 50%; - pointer-events: none; + .signin-modal-body { + padding: clamp(24px, 5vw, 32px); } - - .wt-illustration { - position: relative; - width: 200px; - height: 200px; - flex-shrink: 0; + .signin-modal-header { + display: flex; + align-items: flex-start; + justify-content: space-between; + gap: 16px; + margin-bottom: 24px; } - - .wt-orbit { - position: absolute; - inset: 0; - border-radius: 50%; - border: 2px solid transparent; - animation: wt-orbit-spin 20s linear infinite; + .signin-modal-header h2 { + font-family: var(--font-display); + font-size: var(--fs-h4); + font-weight: var(--fw-bold); + color: var(--fg); + letter-spacing: var(--ls-heading); + margin-bottom: 6px; } - - .wt-orbit-1 { - border-image: linear-gradient(135deg, rgba(99, 102, 241, 0.3), rgba(168, 85, 247, 0.15), transparent 60%) 1; - border-radius: 50%; - border: 2px solid rgba(99, 102, 241, 0.15); + .signin-modal-header p { + font-size: var(--fs-small); + color: var(--muted-2); + line-height: var(--lh-body); } - - .wt-orbit-2 { - inset: 16px; - border: 2px dashed rgba(139, 92, 246, 0.12); - animation-direction: reverse; - animation-duration: 28s; + .signin-label { + display: block; + font-size: var(--fs-caption); + font-weight: var(--fw-ui); + color: var(--muted); + margin-bottom: 8px; } - - .wt-orbit-3 { - inset: 32px; - border: 1.5px solid rgba(59, 130, 246, 0.1); - animation-duration: 15s; + .signin-input { + width: 100%; + min-height: var(--control-h); + padding: 12px 16px; + margin-bottom: 18px; + font-family: var(--font-body); + font-size: var(--fs-body); + color: var(--fg); + background: var(--surface-sunken); + border: 1px solid var(--border); + border-radius: var(--radius-control); + transition: border-color var(--t-fast) var(--ease), box-shadow var(--t-fast) var(--ease); } - - @keyframes wt-orbit-spin { - to { transform: rotate(360deg); } + .signin-input::placeholder { color: var(--muted-2); } + .signin-input:focus { + outline: none; + border-color: var(--accent); + box-shadow: 0 0 0 4px var(--accent-soft); } - - .wt-center-gem { - position: absolute; - top: 50%; - left: 50%; - transform: translate(-50%, -50%); - width: 72px; - height: 72px; + .signin-input[aria-invalid="true"] { + border-color: var(--bad); + box-shadow: 0 0 0 4px var(--bad-soft); } - - .wt-gem-shape { + .signin-submit { width: 100%; - height: 100%; - filter: drop-shadow(0 4px 12px rgba(99, 102, 241, 0.3)); - } - - .wt-code-tag { - position: absolute; - font-family: 'DM Mono', monospace; - font-size: 13px; - font-weight: 500; - color: #8b5cf6; - background: rgba(255, 255, 255, 0.9); - backdrop-filter: blur(4px); - padding: 4px 8px; - border-radius: 6px; - box-shadow: 0 1px 4px rgba(0, 0, 0, 0.06); - line-height: 1; - } - - .wt-code-tag-1 { bottom: 28px; left: 4px; color: #6366f1; } - .wt-code-tag-2 { bottom: 32px; right: 0px; color: #7c3aed; } - - .wt-gear { - position: absolute; - color: #94a3b8; - opacity: 0.5; - animation: wt-gear-spin 8s linear infinite; + font-size: var(--fs-body); } - .wt-gear-1 { top: 12px; right: 28px; width: 22px; height: 22px; } - .wt-gear-2 { top: 36px; right: 8px; width: 16px; height: 16px; animation-direction: reverse; animation-duration: 12s; } - - @keyframes wt-gear-spin { - to { transform: rotate(360deg); } + .signin-message { + min-height: 1.5em; + margin-top: 16px; + text-align: center; + font-size: var(--fs-small); + line-height: var(--lh-body); + color: var(--muted-2); } + .signin-message-success { color: var(--ok); } + .signin-message-error { color: var(--bad); } - .wt-sparkle { - position: absolute; - width: 8px; - height: 8px; - animation: wt-sparkle-pulse 2s ease-in-out infinite; - } - .wt-sparkle::before, - .wt-sparkle::after { - content: ''; - position: absolute; - background: currentColor; - border-radius: 1px; - } - .wt-sparkle::before { - width: 2px; - height: 100%; - left: 50%; - transform: translateX(-50%); - } - .wt-sparkle::after { - width: 100%; - height: 2px; - top: 50%; - transform: translateY(-50%); + #usage-counter { font-size: 12px; color: var(--muted-2); } + #subscription-tier-badge { + display: inline-flex; + align-items: center; + padding: 3px 10px; + border-radius: 12px; + font-size: 11px; + font-weight: 600; + background: var(--accent-soft); + color: var(--accent); } - .wt-sparkle-1 { top: 20px; left: 24px; color: #818cf8; animation-delay: 0s; } - .wt-sparkle-2 { top: 8px; left: 80px; color: #a78bfa; animation-delay: 0.6s; } - .wt-sparkle-3 { top: 44px; left: 56px; color: #6366f1; animation-delay: 1.2s; font-size: 6px; } - .wt-sparkle-4 { bottom: 16px; right: 44px; color: #818cf8; animation-delay: 0.3s; } + /* ── Walkthrough / Tutorial Modal (new visual system) ─── */ + .wt-modal { max-width: 640px; overflow: hidden; background: var(--surface); } - @keyframes wt-sparkle-pulse { - 0%, 100% { opacity: 0.3; transform: scale(0.8); } - 50% { opacity: 1; transform: scale(1.2); } + .wt-topbar { + display: flex; align-items: center; justify-content: space-between; + gap: 16px; padding: 18px 24px; + border-bottom: 1px solid var(--border); } - - .wt-free-badge { - position: absolute; - top: 8px; - left: 50%; - transform: translateX(-50%); - background: linear-gradient(135deg, #22c55e, #16a34a); - color: #fff; - font-family: 'Delight', 'Outfit', sans-serif; - font-size: 10px; - font-weight: 700; - letter-spacing: 0.08em; - padding: 3px 12px; - border-radius: 4px; - box-shadow: 0 2px 8px rgba(34, 197, 94, 0.3); - z-index: 2; + .wt-title { + font-family: var(--font-display); + font-size: var(--fs-h4); + font-weight: var(--fw-bold); + color: var(--fg); + letter-spacing: var(--ls-heading); } - .wt-hero-text { - flex: 1; - min-width: 0; + .wt-hero { padding: 22px 24px 0; } + .wt-hero-kicker { + font-family: var(--font-mono); + font-size: var(--fs-micro); + font-weight: 600; + letter-spacing: var(--ls-mono); + text-transform: uppercase; + color: var(--accent); + margin-bottom: 8px; } - .wt-hero-heading { - font-family: 'Delight', 'Outfit', sans-serif; - font-size: 26px; - font-weight: 700; + font-family: var(--font-display); + font-size: var(--fs-h3); + font-weight: var(--fw-black); color: var(--fg); - letter-spacing: -0.03em; - line-height: 1.2; - } - - .wt-info-card { - margin: 0 24px; - padding: 20px 24px; - background: linear-gradient(135deg, #eef2ff 0%, #f0f4ff 50%, #ede9fe 100%); - border-radius: 14px; - text-align: center; - position: relative; - } - - .wt-info-text { - font-family: 'Delight', 'DM Sans', sans-serif; - font-size: 14px; - color: #334155; - line-height: 1.6; - margin-bottom: 16px; - } - - .wt-info-text strong { - font-weight: 700; - color: #1e293b; + letter-spacing: var(--ls-heading); + line-height: 1.15; } - - .wt-upgrade-btn { - display: block; - width: 100%; - padding: 14px 24px; - background: linear-gradient(135deg, #8b5cf6 0%, #6366f1 50%, #4f46e5 100%); - color: #fff; - font-family: 'Delight', 'DM Sans', sans-serif; - font-size: 14px; - font-weight: 600; - border: none; - border-radius: 10px; - cursor: pointer; - letter-spacing: -0.01em; - transition: all 0.2s ease; - box-shadow: 0 4px 14px -3px rgba(99, 102, 241, 0.4); + .wt-hero-sub { + margin: 8px 0 16px; + font-size: var(--fs-small); + color: var(--muted); + line-height: var(--lh-body); + max-width: 58ch; } - - .wt-upgrade-btn:hover { - transform: translateY(-1px); - box-shadow: 0 6px 20px -3px rgba(99, 102, 241, 0.5); - background: linear-gradient(135deg, #7c3aed 0%, #4f46e5 50%, #4338ca 100%); + .wt-video { + border-radius: var(--radius-md); + overflow: hidden; + border: 1px solid var(--border-strong); + background: oklch(16% 0.02 265); + aspect-ratio: 16 / 9; } + .wt-video video { display: block; width: 100%; height: 100%; object-fit: cover; } .wt-steps { - display: grid; - grid-template-columns: 1fr 1fr; - gap: 14px; - padding: 20px 24px 0; + list-style: none; + margin: 20px 0 0; + padding: 0 24px; + display: grid; gap: 10px; } - .wt-step-card { - background: #fff; - border: 1px solid #e8ebf0; - border-radius: 12px; - padding: 18px; - transition: border-color 0.2s, box-shadow 0.2s; - } - - .wt-step-card:hover { - border-color: #c7d2fe; - box-shadow: 0 2px 8px rgba(99, 102, 241, 0.08); - } - - .wt-step-num { - width: 28px; - height: 28px; - background: #3b82f6; - color: #fff; - border-radius: 50%; - display: flex; - align-items: center; - justify-content: center; - font-size: 13px; - font-weight: 700; - font-family: 'Delight', 'DM Sans', sans-serif; - margin-bottom: 10px; + display: flex; align-items: flex-start; gap: 14px; + padding: 14px 16px; + border: 1px solid var(--border); + border-radius: var(--radius-sm); + background: var(--surface); + transition: border-color var(--t-fast) var(--ease), + box-shadow var(--t-fast) var(--ease), + opacity var(--t-fast) var(--ease); + } + .wt-step-card.wt-current { + border-color: var(--accent); + box-shadow: 0 0 0 3px var(--accent-soft); } + .wt-step-card.wt-pending { opacity: 0.72; } - .wt-step-title { - font-family: 'Delight', 'Outfit', sans-serif; - font-size: 14px; + .wt-step-num { + flex: none; width: 28px; height: 28px; border-radius: 50%; + display: grid; place-items: center; + font-family: var(--font-mono); + font-size: var(--fs-caption); font-weight: 600; - color: #1e293b; - margin-bottom: 4px; + color: var(--fg); + border: 1px solid var(--border-strong); + background: var(--surface-sunken); } + .wt-current .wt-step-num { background: var(--accent); border-color: var(--accent); color: var(--on-dark); } + .wt-done .wt-step-num { background: var(--ok); border-color: var(--ok); color: var(--on-dark); } + .wt-step-body { flex: 1; min-width: 0; } + .wt-step-title { + display: block; + font-family: var(--font-body); + font-size: var(--fs-body); + font-weight: var(--fw-bold); + color: var(--fg); + letter-spacing: -0.01em; + } .wt-step-desc { - font-size: 12.5px; - color: #64748b; + display: block; margin-top: 3px; + font-size: var(--fs-caption); + color: var(--muted); line-height: 1.5; - margin-bottom: 10px; } - .wt-step-link { - font-size: 12.5px; - font-weight: 600; - color: #3b82f6; + margin-top: 9px; padding: 0; + background: none; border: none; cursor: pointer; + font-family: var(--font-body); + font-size: var(--fs-small); + font-weight: var(--fw-bold); + color: var(--accent); text-decoration: none; - cursor: pointer; - background: none; - border: none; - padding: 0; - font-family: 'Delight', 'DM Sans', sans-serif; - transition: color 0.15s; } - .wt-step-link:hover { color: #2563eb; } + .wt-step-link:hover { text-decoration: underline; } - .wt-footer { - display: flex; - align-items: center; - justify-content: space-between; - padding: 16px 24px 20px; + .wt-upgrade { + margin: 16px 24px 0; padding: 14px 18px; + border: 1px dashed var(--border-strong); + border-radius: var(--radius-sm); + background: var(--surface-sunken); + display: flex; flex-wrap: wrap; align-items: center; + justify-content: space-between; gap: 12px; } - - .wt-dont-show { - display: flex; - align-items: center; - gap: 8px; - cursor: pointer; + .wt-info-text { + flex: 1 1 250px; + font-size: var(--fs-small); color: var(--muted); + line-height: var(--lh-body); } - - .wt-dont-show input[type="checkbox"] { - width: 16px; - height: 16px; - border-radius: 4px; - border: 1.5px solid #cbd5e1; - accent-color: #3b82f6; + .wt-info-text strong { font-weight: var(--fw-bold); color: var(--fg); } + .wt-upgrade-btn { + padding: 10px 16px; + background: var(--accent); color: var(--on-dark); + font-family: var(--font-body); + font-size: var(--fs-small); font-weight: var(--fw-bold); + border: none; border-radius: var(--radius-control); cursor: pointer; + transition: box-shadow var(--t-fast) var(--ease), transform var(--t-fast) var(--ease); } + .wt-upgrade-btn:hover { box-shadow: var(--shadow-control); } - .wt-dont-show span { - font-size: 12px; - color: #94a3b8; - font-family: 'Delight', 'DM Sans', sans-serif; + .wt-footer { + display: flex; align-items: center; justify-content: space-between; + gap: 12px; padding: 16px 24px 20px; } - + .wt-dont-show { display: flex; align-items: center; gap: 8px; cursor: pointer; } + .wt-dont-show input[type="checkbox"] { + width: 16px; height: 16px; accent-color: var(--accent); cursor: pointer; + } + .wt-dont-show span { font-size: var(--fs-caption); color: var(--muted-2); } .wt-gotit-btn { - padding: 10px 22px; - background: #3b82f6; - color: #fff; - font-family: 'Delight', 'DM Sans', sans-serif; - font-size: 14px; - font-weight: 600; - border: none; - border-radius: 10px; + min-height: var(--control-h); + padding: 10px 20px; + background: var(--fg); color: var(--surface); + font-family: var(--font-body); + font-size: var(--fs-body); font-weight: var(--fw-bold); + border: none; border-radius: var(--radius-control); cursor: pointer; - transition: background 0.15s; - display: flex; - align-items: center; - gap: 6px; - } - .wt-gotit-btn:hover { background: #2563eb; } - - .wt-gotit-btn svg { - width: 16px; - height: 16px; + display: flex; align-items: center; gap: 6px; + transition: background-color var(--t-fast) var(--ease); } + .wt-gotit-btn:hover { background: oklch(from var(--fg) calc(l + 0.12) c h); } + .wt-gotit-btn svg { width: 15px; height: 15px; } @media (max-width: 640px) { - .wt-hero { flex-direction: column; text-align: center; gap: 16px; padding: 24px; } - .wt-illustration { width: 160px; height: 160px; } - .wt-hero-heading { font-size: 22px; } - .wt-steps { grid-template-columns: 1fr; } - .wt-info-card { margin: 0 16px; } + .wt-hero { padding: 18px 16px 0; } + .wt-steps { padding: 0 16px; } + .wt-upgrade { margin-left: 16px; margin-right: 16px; flex-direction: column; align-items: stretch; } + .wt-upgrade-btn { text-align: center; } + .wt-footer { padding-left: 16px; padding-right: 16px; } } /* ── Pricing Modal Redesign ─────────────────────── */ @@ -2850,7 +3074,205 @@ color: var(--accent); } + /* Account overview — real identity, plan, usage and honest history. + Every number below is written by renderAccountOverview() from the same + metered/session/subscription state the topbar reads; nothing here is + illustrative, and no renewal/member date is ever fabricated. */ + .acct-head { padding: 4px 0 22px; } + .acct-eyebrow { + font-family: var(--font-mono); + font-size: 11.5px; + font-weight: 500; + letter-spacing: 0.15em; + text-transform: uppercase; + color: var(--accent); + margin-bottom: 12px; + } + .acct-title { + font-family: var(--font-display); + font-size: clamp(28px, 5vw, 40px); + line-height: 1.06; + letter-spacing: -0.03em; + font-weight: var(--fw-bold); + margin: 0; + } + .acct-lead { + margin: 14px 0 0; + font-size: 15px; + line-height: 1.6; + color: var(--muted); + max-width: 62ch; + } + + .acct-grid { + display: grid; + grid-template-columns: minmax(0, 1.4fr) repeat(2, minmax(0, 1fr)); + gap: 16px; + margin: 0 0 16px; + } + .acct-card { + border: 1px solid var(--border); + border-radius: var(--radius-md); + background: var(--surface); + padding: 20px; + } + .acct-card-head { + display: flex; + align-items: center; + justify-content: space-between; + gap: 12px; + } + .acct-card-head h2 { + font-family: var(--font-display); + font-size: 17px; + font-weight: var(--fw-bold); + letter-spacing: -0.02em; + margin: 0; + } + .acct-card-head .acct-meta { + font-family: var(--font-mono); + font-size: 11px; + color: var(--muted-2); + } + + .acct-who { display: flex; align-items: center; gap: 14px; } + .acct-avatar { + width: 52px; height: 52px; flex: none; + border-radius: 50%; + display: grid; place-items: center; + background: var(--fg); color: var(--surface); + font-size: 19px; font-weight: 600; + } + .acct-name { + font-family: var(--font-display); + font-size: 19px; font-weight: var(--fw-bold); + letter-spacing: -0.02em; margin: 0; + } + .acct-email { + font-family: var(--font-mono); + font-size: 12.5px; color: var(--muted); + margin: 3px 0 0; overflow-wrap: anywhere; + } + .acct-since { + font-size: 12.5px; color: var(--muted-2); margin: 7px 0 0; + } + + .acct-k { + font-family: var(--font-mono); + font-size: 10.5px; letter-spacing: 0.11em; text-transform: uppercase; + color: var(--muted-2); margin: 0; + } + .acct-v { + font-size: clamp(26px, 3vw, 32px); + font-weight: var(--fw-bold); + letter-spacing: -0.035em; + line-height: 1.05; + margin: 10px 0 0; + overflow-wrap: anywhere; + } + .acct-v .acct-unit { font-size: 15px; color: var(--muted); font-weight: 500; letter-spacing: 0; } + .acct-n { + font-size: 12.5px; color: var(--muted); margin: 8px 0 0; + } + + .acct-identity { margin-bottom: 16px; } + .acct-usage-meter { margin-bottom: 16px; } + .acct-meter { margin-top: 18px; } + .acct-meter-track { + height: 10px; border-radius: 999px; + background: var(--track); overflow: hidden; + } + .acct-meter-fill { + height: 100%; border-radius: 999px; + background: var(--accent); + width: 0%; + transition: width 700ms var(--ease, ease); + } + .acct-meter-meta { + display: flex; align-items: baseline; justify-content: space-between; + gap: 14px; flex-wrap: wrap; + margin-top: 12px; font-size: 13px; color: var(--muted); + } + .acct-meter-meta .acct-num { font-family: var(--font-mono); font-size: 13px; color: var(--fg); } + .acct-counter { font-family: var(--font-mono); font-size: 12px; } + + .acct-empty { + margin-top: 14px; + padding: 16px; + border: 1px dashed var(--border-strong); + border-radius: var(--radius-sm, 10px); + background: var(--surface-sunken); + font-size: 13.5px; + line-height: 1.6; + color: var(--muted); + } + .acct-empty p { margin: 0 0 6px; } + .acct-empty p:last-child { margin-bottom: 0; } + .acct-empty a { color: var(--accent); text-decoration: underline; } + + .acct-connection { margin-bottom: 16px; } + .acct-conn-row { + display: flex; align-items: center; gap: 10px; + margin-top: 14px; font-size: 14px; + } + .acct-dot { + width: 9px; height: 9px; border-radius: 50%; flex: none; + background: var(--muted-2); + } + .acct-dot.ok { background: var(--ok); } + .acct-dot.warn { background: var(--warn); } + .acct-dot.bad { background: var(--bad); } + .acct-conn-spacer { flex: 1; } + .acct-kv { margin: 12px 0 0; } + .acct-row { + display: flex; align-items: baseline; justify-content: space-between; + gap: 16px; padding: 8px 0; border-bottom: 1px solid var(--border); + font-size: 13.5px; + } + .acct-row:last-child { border-bottom: 0; } + .acct-row dt { color: var(--muted); } + .acct-row dd { margin: 0; font-family: var(--font-mono); font-size: 13px; text-align: right; overflow-wrap: anywhere; } + + .acct-actions { display: flex; flex-wrap: wrap; gap: 10px; margin-top: 18px; } + .acct-actions .btn-action { flex: 1 1 auto; } + .btn-action.ghost { + background: transparent; color: var(--muted); + border: 1px solid var(--border); + } + .btn-action.sm { padding: 7px 12px; font-size: 12.5px; flex: none; } + + .acct-access-row { + display: flex; align-items: baseline; justify-content: space-between; + gap: 16px; padding: 11px 0; border-bottom: 1px solid var(--border); + font-size: 13.5px; + } + .acct-access-row:last-child { border-bottom: 0; } + .acct-access-row p { margin: 0; color: var(--muted); } + .acct-access-row p:first-child { color: var(--fg); font-weight: 500; flex: none; } + .acct-access-action { align-items: center; } + .acct-access-action .btn-action { flex: none; } + .acct-access-desc { font-size: 12px !important; line-height: 1.45; } + .acct-access-msg { + min-height: 1.25rem; margin: 0 0 10px 0; padding-top: 2px; + font-size: 12.5px; color: var(--muted); + } + .acct-access-msg.error { color: var(--bad); } + .acct-danger-zone { + border: 1px solid var(--bad-soft); + background: color-mix(in oklab, var(--bad-soft), transparent 55%); + } + .acct-danger-zone .acct-card-head h2 { color: var(--bad); } + .acct-danger-note { font-size: 12.5px; line-height: 1.55; color: var(--muted); margin: 0 0 14px 0; max-width: 52ch; } + /* Mobile compact */ + @media (max-width: 920px) { + .acct-grid { grid-template-columns: 1fr; } + /* The connection row's Configure button is non-shrinking (flex: none); + on narrow screens the long status text pushes it past the viewport, + so drop it onto its own full-width line instead. */ + .acct-conn-row { flex-wrap: wrap; } + .acct-conn-row .btn-action { flex: 1 1 100%; } + } @media (max-width: 920px) { .hero { padding: 24px 16px 28px; } .headline { font-size: clamp(34px, 10vw, 56px); line-height: 1.08; } @@ -2876,8 +3298,8 @@ .send.is-busy .send-spin { animation: none; opacity: 0.6; } } - - + +

    + + +
    +
    
                         
    @@ -3082,43 +3564,44 @@

    Generation Results

    - - -
    +

    Refine & Regenerate acts on the selected artifact · build-error fixes regenerate the whole bundle.