diff --git a/DEPLOYMENT.md b/DEPLOYMENT.md index 44943e4..c659a8d 100644 --- a/DEPLOYMENT.md +++ b/DEPLOYMENT.md @@ -97,18 +97,26 @@ reported rather than silently dropped: package would resolve different code, and a check against the wrong version reports a result that does not describe what ships. -The second case is decided **per class**, from that class's own imports. A -`git:` dependency stops only the classes that import it; classes that do not are -still compiled. Deciding it once for the whole project meant one such entry left -an entire deploy uncompiled. +The second case poisons the whole resolution graph, so it is decided **at the +graph level**. A git or path dependency's own pubspec still constrains every +package it shares with a class's imports - even ones the class never names - +and only the project's `pubspec.lock`, which is never uploaded, records which +versions actually resolved. A check that cannot reproduce the graph cannot +distinguish "clean" from "clean under different code", so any class importing +a `package:` URI is reported unverified. A class using only `dart:` imports +resolves nothing through pub and is still compiled, and a class naming the +unreproducible entry directly gets a reason that says so. **Which packages the Flutter SDK supplies is read from the project's own pubspec** - a dependency written in block form under `sdk:` is an SDK package by -definition. Nothing keeps a list of SDK package names, because a list goes stale -the moment the SDK ships one it has not heard of, and a stale list reads a -perfectly valid package as unreproducible. That is not hypothetical: a list -missing `flutter_web_plugins` refused whole deploys for projects that declared -it. +definition. A small name list still exists, but only for names the pubspec does +not declare at all: a package the code imports and the project lacks is written +as `sdk: flutter` when the SDK supplies it, so discovery never emits a hosted +constraint pub.dev cannot resolve. A name the list has not heard of degrades to +the ordinary hosted lookup, not a wrong answer. For declared dependencies the +list plays no part - the pubspec's own keys are the authority, because a stale +list read a perfectly valid `flutter_web_plugins` declaration as +unreproducible and refused whole deploys over it. The manifest is sent as package names and version constraints, never as pubspec.yaml text, and the runner builds the document itself - it runs diff --git a/app.js b/app.js index e4a5f13..a4f106b 100644 --- a/app.js +++ b/app.js @@ -3127,7 +3127,11 @@ async function resolveProjectPubspec(apiClient, newDependencies = {}) { if (merged.added.length > 0) { console.log( "Adding dependencies:", - merged.added.map((name) => `${name}: ${plan.additions[name] || "any"}`).join(", "), + merged.added.map((name) => { + const addition = plan.additions[name]; + const display = addition?.sdk ? `sdk: ${addition.sdk}` : (addition || "any"); + return `${name}: ${display}`; + }).join(", "), plan.sdk.dartSdkFloor ? `(resolved for Dart ${plan.sdk.dartSdkFloor})` : "", ); } diff --git a/cloud-run/ffai-runner/bin/server.dart b/cloud-run/ffai-runner/bin/server.dart index 44e5525..8eec571 100644 --- a/cloud-run/ffai-runner/bin/server.dart +++ b/cloud-run/ffai-runner/bin/server.dart @@ -5,6 +5,8 @@ import 'dart:io'; const maxClassesPerRequest = 20; const maxCodeBytes = 500000; const maxDependenciesPerRequest = 200; +// pub.dev's own ceiling on a package name. +const maxPackageNameLength = 64; const analysisPackageName = 'ccc_custom_code_analysis'; const defaultSdkConstraint = '>=3.0.0 <4.0.0'; @@ -524,7 +526,8 @@ _VerificationRequest? _normalizeVerification(Object? value) { value['dependencyOverrides'], 'dependencyOverrides', ), - sdkPackages: _normalizeSdkPackages(value['sdkPackages']), + sdkPackages: _normalizeSdkPackages(value['sdkPackages'], 'sdkPackages'), + sdkOverrides: _normalizeSdkPackages(value['sdkOverrides'], 'sdkOverrides'), sources: sources, ); } @@ -551,7 +554,7 @@ Map _normalizeDependencyMap(Object? value, String field) { final result = {}; for (final entry in value.entries) { final name = '${entry.key}'; - if (!_packageNamePattern.hasMatch(name)) { + if (!_isValidPackageName(name)) { throw FormatException('Invalid package name in verification.$field: $name.'); } final constraint = '${entry.value}'.trim(); @@ -572,10 +575,16 @@ Map _normalizeDependencyMap(Object? value, String field) { /// `pub get` with an honest error, whereas a list refuses correct deploys the /// moment it falls behind the SDK. The pattern is the load-bearing check - each /// name becomes a key in the generated pubspec. -List _normalizeSdkPackages(Object? value) { +List _normalizeSdkPackages(Object? value, String field) { if (value == null) return const []; if (value is! List) { - throw const FormatException('verification.sdkPackages must be an array.'); + throw FormatException('verification.$field must be an array.'); + } + // Bounded like the dependency maps: each entry expands into the generated + // pubspec, so an unbounded array is caller-controlled work before pub get + // ever sees it. + if (value.length > maxDependenciesPerRequest) { + throw FormatException('Too many entries in verification.$field.'); } if (value.length > maxDependenciesPerRequest) { throw const FormatException('Too many entries in verification.sdkPackages.'); @@ -584,7 +593,7 @@ List _normalizeSdkPackages(Object? value) { final result = {}; for (final raw in value) { final name = '$raw'; - if (!_packageNamePattern.hasMatch(name)) { + if (!_isValidPackageName(name)) { throw FormatException('Invalid SDK package name: $name.'); } result.add(name); @@ -592,6 +601,9 @@ List _normalizeSdkPackages(Object? value) { return result.toList(); } +bool _isValidPackageName(String name) => + name.length <= maxPackageNameLength && _packageNamePattern.hasMatch(name); + String _validateConstraint( String field, String value, { @@ -983,6 +995,7 @@ final class _VerificationRequest { required this.dependencies, required this.overrides, required this.sdkPackages, + required this.sdkOverrides, required this.sources, }) : unavailableReason = null; @@ -992,6 +1005,7 @@ final class _VerificationRequest { dependencies = const {}, overrides = const {}, sdkPackages = const [], + sdkOverrides = const [], sources = const <_VerificationSource>[]; /// Why this request cannot be compiled, or null when it can. @@ -1001,6 +1015,7 @@ final class _VerificationRequest { final Map dependencies; final Map overrides; final List sdkPackages; + final List sdkOverrides; final List<_VerificationSource> sources; /// Builds the pubspec the scratch package is compiled from. @@ -1037,13 +1052,21 @@ final class _VerificationRequest { lines.add(' $name: ${_yamlScalar(dependencies[name]!)}'); } - if (overrides.isNotEmpty) { + // SDK-sourced overrides belong in dependency_overrides, not in + // `dependencies` with sdkPackages: an override can share its name with a + // direct dependency, and emitting both under one map writes the key twice. + if (overrides.isNotEmpty || sdkOverrides.isNotEmpty) { lines ..add('') ..add('dependency_overrides:'); for (final name in overrides.keys.toList()..sort()) { lines.add(' $name: ${_yamlScalar(overrides[name]!)}'); } + for (final name in sdkOverrides.toList()..sort()) { + lines + ..add(' $name:') + ..add(' sdk: flutter'); + } } return '${lines.join('\n')}\n'; diff --git a/dist/assets/index-Df7z0XS6.js b/dist/assets/index-CCswOqT6.js similarity index 53% rename from dist/assets/index-Df7z0XS6.js rename to dist/assets/index-CCswOqT6.js index b598b36..7f459fd 100644 --- a/dist/assets/index-Df7z0XS6.js +++ b/dist/assets/index-CCswOqT6.js @@ -1,7 +1,7 @@ -(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,Ne=typeof globalThis<"u"?globalThis:w,He=Ne?.navigator,P=Ne?.document,me=Ne?.location,il=Ne?.fetch,Jo=Ne!=null&&Ne.XMLHttpRequest&&"withCredentials"in new Ne.XMLHttpRequest?Ne.XMLHttpRequest:void 0,vc=Ne?.AbortController,zp=Ne?.CompressionStream,Ge=He?.userAgent;function yd(){return!(!w||w.navigator.onLine===!1)}var wi=typeof globalThis<"u"?globalThis:w;wi&&typeof self>"u"&&(wi.self=wi),wi&&typeof File>"u"&&(wi.File=function(){});var B=w??{},ne={DEBUG:!1,LIB_VERSION:"0.5.0",LIB_NAME:"browser-common"};function _c(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 se(t){return function(){var e=this,n=arguments;return new Promise((function(i,r){var s=t.apply(e,n);function o(l){_c(s,i,r,o,a,"next",l)}function a(l){_c(s,i,r,o,a,"throw",l)}o(void 0)}))}}function I(){return I=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},I.apply(null,arguments)}function wd(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 yc=t=>{if(typeof t!="string")return t;try{return JSON.parse(t)}catch{return t}};function wc(t){return typeof t=="string"||t}function bc(t){return typeof t=="string"?t:void 0}var bi,qp=["$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"],Ut=(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})({}),Ec=(function(t){return t.GZipJS="gzip-js",t.Base64="base64",t})({}),Vp=["$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"],Gp=["token"],bd="NativeGzipValidationError",Zo=t=>t.length>=2&&t[0]===31&&t[1]===139,Sc=(t,e)=>t===Ec.GZipJS||e===Ec.GZipJS||e==="gzip",xc=t=>!(!t||typeof t!="object")&&("name"in t?String(t.name):"")==="NotReadableError",_r=t=>{var e=new Error("Native gzip produced invalid output: "+t);throw e.name=bd,e},Kp=(function(){var t=se((function*(e,n){18>e.size&&_r("too-short");var i=new Uint8Array(yield e.slice(0,10).arrayBuffer());Zo(i)&&i[2]===8||_r("invalid-header");var r=new DataView(yield e.slice(e.size-8).arrayBuffer());r.getUint32(0,!0)!==(o=>{for(var a=(()=>{if(bi)return bi;bi=[];for(var c=0;256>c;c++){for(var d=c,f=0;8>f;f++)d=1&d?3988292384^d>>>1:d>>>1;bi[c]=d>>>0}return bi})(),l=4294967295,u=0;o.length>u;u++)l=a[255&(l^o[u])]^l>>>8;return(4294967295^l)>>>0})(n)&&_r("invalid-crc");var s=n.length>>>0;r.getUint32(4,!0)!==s&&_r("invalid-size")}));return function(e,n){return t.apply(this,arguments)}})();function Xo(){return Xo=se((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=se((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 Kp(l,i),l}catch(u){if(n!=null&&n.rethrow)throw u;return e&&console.error("Failed to gzip compress data",u),null}})),Xo.apply(this,arguments)}var Yp=["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"],Ic=function(t,e){if(e===void 0&&(e=[]),!t)return!1;var n=t.toLowerCase();return Yp.concat(e).some((i=>{var r=i.toLowerCase();return n.indexOf(r)!==-1}))};function j(t,e){return t.indexOf(e)!==-1}var Fs=function(t){return t.trim()},Qo=function(t){return t.replace(/^\$/,"")};function Ed(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 Sd=Object.prototype,xd=Sd.hasOwnProperty,Rs=Sd.toString,U=Array.isArray||function(t){return Rs.call(t)==="[object Array]"},je=t=>typeof t=="function",he=t=>t===Object(t)&&!U(t),Kt=t=>{if(he(t)){for(var e in t)if(xd.call(t,e))return!1;return!0}return!1},C=t=>t===void 0,X=t=>Rs.call(t)=="[object String]",ea=t=>X(t)&&t.trim().length===0,Je=t=>t===null,W=t=>C(t)||Je(t),ke=t=>Rs.call(t)=="[object Number]"&&t==t,Dt=t=>ke(t)&&t>0,mt=t=>Rs.call(t)==="[object Boolean]",Jp=t=>t instanceof FormData,Zp=t=>j(Vp,t),Xp=t=>j(Gp,t);function Id(t){return t===null||typeof t!="object"}function Gr(t,e){return{}.toString.call(t)==="[object "+e+"]"}function rl(t){return typeof Event<"u"&&kd(t,Event)}function kd(t,e){try{return t instanceof e}catch{return!1}}var Qp=[!0,"true",1,"1","yes"],vo=t=>j(Qp,t),eg=[!1,"false",0,"0","no"];function At(t,e,n,i,r){return e>n&&(i.warn("min cannot be greater than max."),e=n),ke(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),At(r||n,e,n,i))}class tg{constructor(e){this.tt={},this.et=e.et,this.it=At(e.bucketSize,0,100,e.rt),this.nt=At(e.refillRate,0,this.it,e.rt),this.st=At(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 st="Mobile",Kr="iOS",Yt="Android",ni="Tablet",Cd=Yt+" "+ni,Ad="iPad",Pd="Apple",Fd=Pd+" Watch",Ui="Safari",ii="BlackBerry",Rd="Samsung",Td=Rd+"Browser",$d=Rd+" Internet",Pn="Chrome",ng=Pn+" OS",Md=Pn+" "+Kr,sl="Internet Explorer",Ld=sl+" "+st,ol="Opera",ig=ol+" Mini",al="Edge",Nd="Microsoft "+al,Zn="Firefox",Od=Zn+" "+Kr,Zi="Nintendo",Xi="PlayStation",Xn="Xbox",Bd=Yt+" "+st,Dd=st+" "+Ui,Ti="Windows",ta=Ti+" Phone",kc="Nokia",na="Ouya",jd="Generic",rg=jd+" "+st.toLowerCase(),Ud=jd+" "+ni.toLowerCase(),ia="Konqueror",Hd="Oculus Browser",Yr="Vivaldi",Wd="Yandex",Jr="Whale",ra="DuckDuckGo",zd="Pale Moon",Zr="Waterfox",Hi="Brave",qd="Google Search App",we="(\\d+(\\.\\d+)?)",_o=new RegExp("Version/"+we),sg=new RegExp(Xn,"i"),og=new RegExp(Xi+" \\w+","i"),ag=new RegExp(Zi+" \\w+","i"),ll=new RegExp(ii+"|PlayBook|BB10","i"),lg={"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"},Vd=function(t,e,n,i){e=e||"";var r=(function(s){return s!=null&&s.brave?Hi:null})(n);return r||(i!=null&&i.detectGoogleSearchApp&&j(t,"GSA/")?qd:j(t," OPR/")&&j(t,"Mini")?ig:j(t," OPR/")?ol:ll.test(t)?ii:j(t,"IE"+st)||j(t,"WPDesktop")?Ld:j(t,"OculusBrowser")?Hd:j(t,Td)?$d:j(t,al)||j(t,"Edg/")?Nd:j(t,Yr+"/")?Yr:j(t,"YaBrowser/")?Wd:j(t,Jr+"/")?Jr:j(t,ra+"/")||j(t,"Ddg/")?ra:j(t,"FBIOS")?"Facebook "+st:j(t,"UCWEB")||j(t,"UCBrowser")?"UC Browser":j(t,"CriOS")?Md:j(t,"CrMo")||j(t,Pn)?Pn:j(t,Yt)&&j(t,Ui)?Bd:j(t,"FxiOS")?Od:j(t.toLowerCase(),ia.toLowerCase())?ia:j(t,Hi+"/")?Hi:((s,o)=>o&&j(o,Pd)||(function(a){return j(a,Ui)&&!j(a,Pn)&&!j(a,Yt)})(s))(t,e)?j(t,st)?Dd:Ui:j(t,"PaleMoon/")?zd:j(t,Zr+"/")?Zr:j(t,Zn)?Zn:j(t,"MSIE")||j(t,"Trident/")?sl:j(t,"Gecko")?Zn:"")},cg={[Ld]:[new RegExp("rv:"+we)],[Nd]:[new RegExp(al+"?\\/"+we)],[Pn]:[new RegExp("("+Pn+"|CrMo)\\/"+we)],[Md]:[new RegExp("CriOS\\/"+we)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+we)],[Ui]:[_o],[Dd]:[_o],[ol]:[new RegExp("(Opera|OPR)\\/"+we)],[Zn]:[new RegExp(Zn+"\\/"+we)],[Od]:[new RegExp("FxiOS\\/"+we)],[ia]:[new RegExp("Konqueror[:/]?"+we,"i")],[ii]:[new RegExp(ii+" "+we),_o],[Bd]:[new RegExp("android\\s"+we,"i")],[$d]:[new RegExp(Td+"\\/"+we)],[Hd]:[new RegExp("OculusBrowser\\/"+we)],[Yr]:[new RegExp(Yr+"\\/"+we)],[Wd]:[new RegExp("YaBrowser\\/"+we)],[Jr]:[new RegExp(Jr+"\\/"+we)],[Hi]:[new RegExp(Hi+"\\/"+we)],[ra]:[new RegExp("(DuckDuckGo|Ddg)\\/"+we)],[zd]:[new RegExp("PaleMoon\\/"+we)],[Zr]:[new RegExp(Zr+"\\/"+we)],[qd]:[new RegExp("GSA\\/"+we)],[sl]:[new RegExp("(rv:|MSIE )"+we)],Mozilla:[new RegExp("rv:"+we)]},ug=function(t,e,n,i){var r=Vd(t,e,n,i),s=cg[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},Cc=[[new RegExp(Xn+"; "+Xn+" (.*?)[);]","i"),t=>[Xn,t&&t[1]||""]],[new RegExp(Zi,"i"),[Zi,""]],[new RegExp(Xi,"i"),[Xi,""]],[ll,[ii,""]],[new RegExp(Ti,"i"),(t,e)=>{if(/Phone/.test(e)||/WPDesktop/.test(e))return[ta,""];if(new RegExp(st).test(e)&&!/IEMobile\b/.test(e))return[Ti+" "+st,""];var n=/Windows NT ([0-9.]+)/i.exec(e);if(n&&n[1]){var i=lg[n[1]]||"";return/arm/i.test(e)&&(i="RT"),[Ti,i]}return[Ti,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,t=>t&&t[3]?[Kr,[t[3],t[4],t[5]||"0"].join(".")]:[Kr,""]],[/(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("("+Yt+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+Yt+")","i"),t=>t&&t[2]?[Yt,[t[2],t[3],t[4]||"0"].join(".")]:[Yt,""]],[/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/,[ng,""]],[/Linux|debian/i,["Linux",""]]],Ac=function(t){return ag.test(t)?Zi:og.test(t)?Xi:sg.test(t)?Xn:new RegExp(na,"i").test(t)?na:new RegExp("("+ta+"|WPDesktop)","i").test(t)?ta:/iPad/.test(t)?Ad:/iPod/.test(t)?"iPod Touch":/iPhone/.test(t)?"iPhone":/(watch)(?: ?os[,/]|\d,\d\/)[\d.]+/i.test(t)?Fd:ll.test(t)?ii:/(kobo)\s(ereader|touch)/i.test(t)?"Kobo":new RegExp(kc,"i").test(t)?kc:/(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(st).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)?Yt:Cd:new RegExp("(pda|"+st+")","i").test(t)?rg:new RegExp(ni,"i").test(t)&&!new RegExp(ni+" pc","i").test(t)?Ud:""},dg=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Pc(t,e){return typeof(n=t)=="string"&&dg.test(n)?t:e();var n}function fn(t){return t&&t.split("#")[0]}function cl(t,e){var n=setTimeout(t,e);return n?.unref&&n?.unref(),n}function Fc(t,e,n){return Gd.apply(this,arguments)}function Gd(){return(Gd=se((function*(t,e,n){var i;try{return yield Promise.race([t,new Promise(((r,s)=>{i=cl((()=>{try{n?.(),r()}catch(o){s(o)}}),e)}))])}finally{clearTimeout(i)}}))).apply(this,arguments)}var fg=t=>t instanceof Error,Kd={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}},hg=Kd.info;function Yd(t){if(mt(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=>Yd(e)))}};try{return{stringValue:JSON.stringify(t)}}catch{return{stringValue:String(t)}}}function Xr(t){var e=[];for(var n in t){var i=t[n];Je(i)||C(i)||e.push({key:n,value:Yd(i)})}return e}function pg(t,e){var n=Kd[t.level||"info"]||hg,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),W(e.sessionStartTimestamp)||(o.sessionStartTimestamp=String(e.sessionStartTimestamp)),W(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=I({},o,t.attributes||{}),l={timeUnixNano:s,observedTimeUnixNano:s,severityNumber:r,severityText:i,body:{stringValue:t.body},attributes:Xr(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 Jd(t,e,n){return I({},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 Zd(t,e,n,i){return{resourceLogs:[{resource:{attributes:Xr(e)},scopeLogs:[{scope:{name:n,version:i},logRecords:t}]}]}}let gg=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:pg(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 se((function*(){if(!t._instance.isDisabled)return t.ct||(t.ct=t.Ft().finally((()=>{t.ct=null}))),t.ct}))()}Ft(){var t=this;return se((function*(){var e;t.Et();var n=(e=t._instance.getPersistedProperty(Ut.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=Zd(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(Ut.LogsQueue))!==null&&o!==void 0?o:[],r+=l.length,c.kind==="fatal"))throw c.error}}))()}Dt(t){var e=this;return se((function*(){var n,i=Math.max(0,t-e.ft),r=(n=e._instance.getPersistedProperty(Ut.LogsQueue))!==null&&n!==void 0?n:[];e._instance.setPersistedProperty(Ut.LogsQueue,r.slice(i)),yield e.dt()}))()}Lt(){return Jd(this.Ne,this._instance.getLibraryId(),this._instance.getLibraryVersion())}At(t){var e;if(!this._instance.optedOut){var n=(e=this._instance.getPersistedProperty(Ut.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(Ut.LogsQueue,n),this.kt>n.length?this.$t():this.It()}}$t(t){t===void 0&&(t=this.St),this.Nt||(this.Nt=cl((()=>{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(Ut.LogsQueue);return!!t&&t.length>0}shutdown(t){var e=this;return se((function*(){e.Et();var n=e.flush().catch((()=>{}));t!==void 0?yield Fc(n,t):yield n}))()}flushWithTimeout(t){var e=this;return se((function*(){var n=e.flush();yield Fc(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 yo=[0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4];function Rc(t){return String(t)+"000000"}function Tc(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 mg=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=se((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?I({},e.attributes):void 0,i=Tc(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(yo.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,yo)]+=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=cl((()=>{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 se((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 I({},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:Xr(n)},scopeMetrics:[{scope:{name:i,version:r},metrics:e}]}]};var e,n,i,r}Xt(t){var e=Rc(Date.now()),n=new Map;for(var i of t.values()){var r,s=Tc(i.type,i.name,i.unit,void 0),o=n.get(s);o||(o=I({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=Xr((r=i.attributes)!==null&&r!==void 0?r:{}),l=Rc(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:yo})}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 yr,$c,wo;function vg(t){var e=globalThis._posthogChunkIds;if(e){var n=Object.keys(e);return wo&&n.length===$c||($c=n.length,wo=n.reduce(((i,r)=>{yr||(yr={});var s=yr[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,yr[r]=[u,c];break}}return i}),{})),wo}}class _g{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 se((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)),I({},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 se((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,I({},n,{handled:!0}))),a}buildParsingContext(e){var n;return{chunkIdMap:vg(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 I({},n,{syntheticException:i==0?n.syntheticException:void 0,mechanism:e,apply:s=>r(s,i),next:s=>r(s,i+1)})}}var ri="?";function sa(t,e,n,i,r){var s={platform:t,filename:e,function:n===""?ri:n,in_app:!0};return C(i)||(s.lineno=i),C(r)||(s.colno=r),s}var Xd=(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]:ri,n?"safari-extension:"+e:"safari-web-extension:"+e]:[t,e]},yg=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,wg=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,bg=/\((\S*)(?::(\d+))(?::(\d+))\)/,Eg=(t,e)=>{var n=yg.exec(t);if(n)return sa(e,n[1],ri,+n[2],+n[3]);var i=wg.exec(t);if(i){if(i[2]&&i[2].indexOf("eval")===0){var r=bg.exec(i[2]);r&&(i[2]=r[1],i[3]=r[2],i[4]=r[3])}var s=Xd(i[1]||ri,i[2]);return sa(e,s[1],s[0],i[3]?+i[3]:void 0,i[4]?+i[4]:void 0)}},Sg=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,xg=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,Ig=(t,e)=>{var n=Sg.exec(t);if(n){if(n[3]&&n[3].indexOf(" > eval")>-1){var i=xg.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]||ri,o=Xd(s,r);return sa(e,r=o[1],s=o[0],n[4]?+n[4]:void 0,n[5]?+n[5]:void 0)}},Mc=/\(error: (.*)\)/;class kg{match(e){return this.isDOMException(e)||this.isDOMError(e)}coerce(e,n){var i=X(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 Gr(e,"DOMException")}isDOMError(e){return Gr(e,"DOMError")}}class Cg{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 kd(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 Ag{constructor(){}match(e){return!!Gr(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 I({},r,{stack:(i=this.pe(e))!==null&&i!==void 0?i:r.stack,synthetic:!0})}fe(e){return X(e.message)&&e.message.length>0}pe(e){var n=e;if(X(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 Pg=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;class Fg{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(Pg);return r&&(n=r[1],i=r[2]),[n,i]}}var Rg=["fatal","error","warning","log","info","debug"];function Qd(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 Tg{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 rl(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: "+Qd(e)}isSeverityLevel(e){return X(e)&&!ea(e)&&Rg.indexOf(e)>=0}getStack(e){try{return X(e.stacktrace)&&e.stacktrace.length>0?e.stacktrace:X(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(fg(i))return i}}getObjectClassName(e){try{var n=Object.getPrototypeOf(e);return n?n.constructor.name:void 0}catch{return}}}class $g{match(e){return rl(e)}coerce(e,n){var i,r=e.constructor.name;return{type:r,value:r+" captured as exception with keys: "+Qd(e),stack:(i=n.syntheticException)==null?void 0:i.stack,synthetic:!0}}}class Mg{match(e){return Id(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 Lg{match(e){return Gr(e,"PromiseRejectionEvent")||this.isCustomEventWrappingRejection(e)}isCustomEventWrappingRejection(e){if(!rl(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 Id(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 Qr="$message",es="$timestamp",Ng=new Set([Qr,es]),bo={enabled:!0,max_bytes:32768};function ts(t){var e;return t?{enabled:(e=t.enabled)!==null&&e!==void 0?e:bo.enabled,max_bytes:Bg(t.max_bytes,bo.max_bytes)}:I({},bo)}class Og{constructor(e){this.Ke=[],this.Je=0,this.Ne=ts(e)}setConfig(e){this.Ne=ts(e),this.Xe()}add(e){var n=(function(r){var s;try{s=Ed(r)}catch{return}try{var o=JSON.parse(s);if(!he(o))return;var a=o,l=a[Qr],u=a[es];return!X(l)||l.trim().length===0||!X(u)&&!ke(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 Bg(t,e){if(!ke(t)||t===1/0||t===-1/0)return e;var n=Math.floor(t);return 0>n?e:n}var ef=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)=>ef(t+" "+r,s)};return i},A=ef("[PostHog.js]"),pe=A.createLogger,Dg=pe("[ExternalScriptsLoader]"),Eo=(t,e,n)=>{if(t.config.disable_external_dependency_loading)return Dg.warn(e+" was requested but loading of external scripts is disabled."),n("Loading of external scripts is disabled");var i=P?.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(!P)return n("document not found");var l=P.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")P.head.appendChild(l);else{var u,c=P.querySelectorAll("body > script");c.length>0?(u=c[0].parentNode)==null||u.insertBefore(l,c[0]):P.body.appendChild(l)}};P!=null&&P.body?a():P?.addEventListener("DOMContentLoaded",a)};B.__PosthogExtensions__=B.__PosthogExtensions__||{},B.__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)}Eo(t,i,n)}else{var o=t.requestRouter.endpointFor("assets","/array/"+t.config.token+"/config.js");Eo(t,o,n)}},B.__PosthogExtensions__.loadSiteApp=(t,e,n)=>{var i=t.requestRouter.endpointFor("api",e);Eo(t,i,n)};ne.DEBUG=!1,ne.LIB_VERSION="1.415.7",ne.LIB_NAME="web";var tf="$people_distinct_id",Qi="$device_id",So="$device_model",$i="__alias",Mi="__timers",oa="$autocapture_disabled_server_side",aa="$heatmaps_enabled_server_side",la="$exception_capture_enabled_server_side",ca="$error_tracking_suppression_rules",ua="$error_tracking_capture_extension_exceptions",da="$web_vitals_enabled_server_side",ul="$dead_clicks_enabled_server_side",dl="$product_tours_enabled_server_side",fa="$web_vitals_allowed_metrics",An="$session_recording_remote_config",nf="$replay_sample_rate",rf="$replay_override_sampling",sf="$replay_override_linked_flag",of="$replay_override_url_trigger",af="$replay_override_event_trigger",Kn="$sesid",fl="$session_is_sampled",Sn="$enabled_feature_flags",Li="$active_feature_flags",Tr="$early_access_features",ha="$feature_flag_details",Ni="$feature_flag_payloads",$r="$feature_flag_request_id",ns="$minimal_flag_called_events",It="$override_feature_flags",xn="$override_feature_flag_payloads",jt="$stored_person_properties",In="$stored_group_properties",pa="$surveys",is="$surveys_loaded_at",ga="$surveys_activated",Mr="$surveys_activated_session",Lr="$surveys_activated_timestamps",Oi="ph_product_tours",Cn="$flag_call_reported",Bi="$flag_call_reported_session_id",Nr="$feature_flag_errors",Wi="$feature_flag_evaluated_at",lt="$user_state",ma="$client_session_props",va="$capture_rate_limit",_a="$initial_campaign_params",ya="$initial_referrer_info",rs="$initial_person_info",ss="$epp",wr="$posthog_cookieless",lf="$cookieless_mode",cf="$sdk_debug_extensions_init_method",uf="$sdk_debug_extensions_init_time_ms",df="$sdk_debug_recording_script_not_loaded",hl="PostHog loadExternalDependency extension not found.",kn="on_reject",Wt="always",Un="anonymous",vn="identified",wa="identified_only",os="visibilitychange",as="beforeunload",Vn="$pageview",xo="$pageleave",Io="$identify",Lc="$groupidentify";function br(t,e){U(t)&&t.forEach(e)}function ie(t,e){if(!W(t))if(U(t))t.forEach(e);else if(Jp(t))t.forEach(((i,r)=>e(i,r)));else for(var n in t)xd.call(t,n)&&e(t[n],n)}var fe=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 Or(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 Nc=function(t){try{return t()}catch{return}},jg=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)}}},pl=function(t){var e={};return ie(t,(function(n,i){(X(n)&&n.length>0||ke(n))&&(e[i]=n)})),e},Ug=["herokuapp.com","vercel.app","netlify.app"];function Hg(t){var e=t?.hostname;if(!X(e))return!1;var n=e.split(".").slice(-2).join(".");for(var i of Ug)if(n===i)return!1;return!0}function ve(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 ba(t){return t.name==="ph_toolbar_internal"}var ff=t=>{if(P){try{for(var e=t+"=",n=P.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 ke(t)&&isFinite(t)&&Math.floor(t)===t});class ls{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 ls(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 ls(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 ls.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 zg}}var Oc,hf=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&&(hf=t=>crypto.getRandomValues(t));class zg{nextUint32(){return this.R.length>this.O||(hf(this.R),this.O=0),this.R[this.O++]}constructor(){this.R=new Uint32Array(8),this.O=1/0}}var Ht=()=>qg().toString(),qg=()=>(Oc||(Oc=new Wg)).generate(),Ei="",Vg=/[a-z0-9][a-z0-9-]+\.[a-z]{2,}$/i,zt={N:()=>!!P,j(t){A.error("cookieStore error: "+t)},P:ff,H(t){var e;try{e=JSON.parse(zt.P(t))||{}}catch{}return e},F(t,e,n,i,r){if(!P)return!1;try{var s="",o="",a=(function(c,d){if(d){var f=(function(p,g){if(g===void 0&&(g=P),Ei)return Ei;if(!g||["localhost","127.0.0.1"].includes(p))return"";for(var m=p.split("."),v=Math.min(m.length,8),E="dmn_chk_"+Ht();!Ei&&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",Ei=S)}return Ei})(c);if(!f){var h=(p=>{var g=p.match(Vg);return g?g[0]:""})(c);h!==f&&A.info("Warning: cookie subdomain discovery mismatch",h,f),f=h}return f?"; domain=."+f:""}return""})(P.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),P.cookie=u,!0}catch{return!1}},q(t,e){if(P!=null&&P.cookie)try{zt.F(t,"",-1,e)}catch{return}}},ko=null,le={N(){if(!Je(ko))return ko;var t=!0;if(C(w))t=!1;else try{var e="__mplssupport__";le.F(e,"xyz"),le.P(e)!=='"xyz"'&&(t=!1),le.q(e)}catch{t=!1}return t||A.error("localStorage unsupported; falling back to cookie store"),ko=t,t},j(t){A.error("localStorage error: "+t)},P(t){try{return w?.localStorage.getItem(t)}catch(e){le.j(e)}return null},H(t){try{return JSON.parse(le.P(t))||{}}catch{}return null},F(t,e){try{return w?.localStorage.setItem(t,JSON.stringify(e)),!0}catch(n){le.j(n)}return!1},q(t){try{w?.localStorage.removeItem(t)}catch(e){le.j(e)}}},Gg=[Qi,"distinct_id",Kn,fl,ss,rs,lt],Er={},Kg={N:()=>!0,j(t){A.error("memoryStorage error: "+t)},P:t=>Er[t]||null,H:t=>Er[t]||null,F:(t,e)=>(Er[t]=e,!0),q(t){delete Er[t]}},_n=null,be={N(){if(!Je(_n))return _n;if(_n=!0,C(w))_n=!1;else try{var t="__support__";be.F(t,"xyz"),be.P(t)!=='"xyz"'&&(_n=!1),be.q(t)}catch{_n=!1}return _n},j(t){A.error("sessionStorage error: ",t)},P(t){try{return w?.sessionStorage.getItem(t)}catch(e){be.j(e)}return null},H(t){try{return JSON.parse(be.P(t))||null}catch{}return null},F(t,e){try{return w?.sessionStorage.setItem(t,JSON.stringify(e)),!0}catch(n){be.j(n)}return!1},q(t){try{w?.sessionStorage.removeItem(t)}catch(e){be.j(e)}}};class Yg{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===Wt||this.isRejected()||this.consent===-1&&this.Ne.cookieless_mode===kn}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 vo(e)?1:j(eg,e)?0:-1}get ii(){var e=this.Ne.opt_out_capturing_persistence_type,n=e==="localStorage"?le:zt;if(!this.ni||this.ni!==n){this.ni=n;var i=e==="localStorage"?zt:le;i.P(this.ri)&&(this.ni.P(this.ri)||this.optInOut(vo(i.P(this.ri))),i.q(this.ri,this.Ne.cross_subdomain_cookie))}return this.ni}ti(){return!!this.Ne.respect_dnt&&[He?.doNotTrack,He?.msDoNotTrack,B.doNotTrack].some((e=>vo(e)))}}function pf(t,e){var n,i=t==null||(n=t.config)==null?void 0:n.get_current_url;if(!je(i))return e;try{var r=i(e);return X(r)&&r?r:e}catch(s){return A.error("Error in get_current_url, falling back to window.location.href",s),e}}var gf="__POSTHOG_TOOLBAR__",Jg=1,Zg=3,Xg=11;function Bc(t){return t instanceof Element&&(t.id===gf||!(t.closest==null||!t.closest(".toolbar-global-fade-container")))}function hn(t){return!!t&&t.nodeType===Jg}function tt(t,e){return!!t&&!!t.tagName&&t.tagName.toLowerCase()===e.toLowerCase()}function mf(t){return!!t&&t.nodeType===Zg}function vf(t){return!!t&&t.nodeType===Xg&&hn(t.host)}var _f=1e3;function gl(t){return t?Fs(t).split(/\s+/):[]}function Dc(t,e){var n=(function(i){var r,s=w==null||(r=w.location)==null?void 0:r.href;return C(s)?void 0:pf(i,s)})(e);return!!(n&&t&&t.some((i=>n.match(i))))}function cs(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 gl(e)}function yf(t){return W(t)?null:Fs(t).split(/(\s+)/).filter((e=>zi(e))).join("").replace(/[\r\n]/g," ").replace(/[ ]+/g," ").substring(0,255)}function er(t){var e="";return Sa(t)&&!Sf(t)&&t.childNodes&&t.childNodes.length&&ie(t.childNodes,(function(n){var i;mf(n)&&n.textContent&&(e+=(i=yf(n.textContent))!==null&&i!==void 0?i:"")})),Fs(e)}function Co(t){var e;return C(t.target)?t.srcElement||null:(e=t.target)!=null&&e.shadowRoot?t.composedPath()[0]||null:t.target||null}var ml=["a","button","form","input","select","textarea","label"];function Ea(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 wf(t){var e=t.parentNode;return!(!e||!hn(e))&&e}var Qg=[".ph-no-autocapture","[data-ph-no-autocapture]"],bf=["next","previous","prev",">","<"],em=[...bf,"+","-","−","–"],jc=(t,e)=>/[a-z0-9]/i.test(e)?t.includes(e):t===e,Uc=[".ph-no-rageclick",".ph-no-capture"],tm=["","text","search","email","password","url","tel","number"];function Hc(t,e){if(!w||vl(t))return!1;var n,i,r,s,o;if(mt(e)?(n=!!e&&Uc,i=void 0,r=!1):(n=(s=e?.css_selector_ignorelist)!==null&&s!==void 0?s:Uc,i=e?.content_ignorelist,r=(o=e?.ignore_text_selection)!==null&&o!==void 0&&o),n===!1||r&&(function(l){return!(!l||!hn(l))&&(!!tt(l,"textarea")||(tt(l,"input")?j(tm,(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=Ef(t,!1).targetElementList;return!(function(l,u){if(l===!1||C(l))return!1;var c;if(l===!0)c=bf;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=>jc(f,p)||jc(h,p)))}))})(i,a.map((l=>{var u;return{safeText:er(l).toLowerCase(),ariaLabel:((u=l.getAttribute("aria-label"))==null?void 0:u.toLowerCase().trim())||""}})))&&!Ea(a,n)}var vl=t=>!t||tt(t,"html")||!hn(t),Ef=(t,e)=>{if(!w||vl(t))return{parentIsUsefulElement:!1,targetElementList:[]};for(var n=!1,i=[t],r=t;r.parentNode&&!tt(r,"body");)if(vf(r.parentNode))i.push(r.parentNode.host),r=r.parentNode.host;else{var s=wf(r);if(!s)break;if(e||ml.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 Sa(t){for(var e=new Set,n=0,i=t;i.parentNode&&!tt(i,"body");i=i.parentNode){if(n++>=_f||e.has(i))return!1;e.add(i);var r=cs(i);if(j(r,"ph-sensitive")||j(r,"ph-no-capture"))return!1}if(j(cs(t),"ph-include"))return!0;var s=t.type||"";if(X(s))switch(s.toLowerCase()){case"hidden":case"password":return!1}var o=t.name||t.id||"";return!X(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 Sf(t){return!!(tt(t,"input")&&!["button","checkbox","submit","reset"].includes(t.type)||tt(t,"select")||tt(t,"textarea")||t.getAttribute("contenteditable")==="true")}var Wc=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}))$"),zc=/(^|[^0-9A-Za-z_])([0-9][0-9 -]*[0-9])(?=$|[^0-9A-Za-z_])/g,nm=[16,15,14,13],im=new RegExp("^(\\d{3}-?\\d{2}-?\\d{4})$"),qc=new RegExp("(^|[^0-9])((?!000|666)[0-9]{3}-?(?!00)[0-9]{2}-?(?!0000)[0-9]{4})(?=$|([^0-9]))","g"),Vc=/[0-9A-Za-z_]/;function rm(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 zi(t,e){if(e===void 0&&(e=!0),W(t))return!1;if(X(t)){t=Fs(t);var n=e?Wc.test((t||"").replace(/[- ]/g,"")):(function(r){var s;for(zc.lastIndex=0;s=zc.exec(r);){var o=s[2];if(o)for(var a=o.replace(/[- ]/g,""),l=0;a.length>l;l++)for(var u of nm){var c=l+u;if(a.length>=c){var d=a.slice(l,c);if(Wc.test(d)&&rm(d))return!0}}}return!1})(t);if(n)return!1;var i=e?im.test(t):(function(r){var s;for(qc.lastIndex=0;s=qc.exec(r);){var o=s[1],a=s[3];if(!(o&&a&&Vc.test(o)&&Vc.test(a)))return!0}return!1})(t);if(i)return!1}return!0}function Gc(t){var e=er(t);return zi(e=(e+" "+xf(t)).trim())?e:""}function xf(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=er(n);e=(e+" "+r).trim(),n.childNodes&&n.childNodes.length&&(e=(e+" "+xf(n)).trim())}catch(s){A.error("[AutoCapture]",s)}})),e}function Kc(t){return t.replace(/"|\\"/g,'\\"')}function sm(t){var e=t.attr__class;if(e)return U(e)?e:gl(e)}var Sr=pe("[Dead Clicks]"),om=()=>!0,am=t=>{var e,n=!((e=t.instance.persistence)==null||!e.get_property(ul)),i=t.instance.config.capture_dead_clicks;return mt(i)?i:!!he(i)||n};class Yc{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({[ul]:n.captureDeadClicks}),this.startIfEnabledOrStop())}}startIfEnabledOrStop(){this.isEnabled(this)?this.ai((()=>{this.oi()})):this.stop()}ai(e){var n,i;(n=B.__PosthogExtensions__)!=null&&n.initDeadClicksAutocapture?e():(i=B.__PosthogExtensions__)==null||i.loadExternalDependency==null||i.loadExternalDependency(this.instance,"dead-clicks-autocapture",(r=>{r?Sr.error("failed to load script",r):e()}))}oi(){var e;if(P){if(!this.si&&(e=B.__PosthogExtensions__)!=null&&e.initDeadClicksAutocapture){var n=he(this.instance.config.capture_dead_clicks)?I({},this.instance.config.capture_dead_clicks):{};n.__onCapture=this.onCapture,this.onCapture&&(n.capture_dead_swipes=!1),this.si=B.__PosthogExtensions__.initDeadClicksAutocapture(this.instance,n),this.si.start(P),Sr.info("starting...")}}else Sr.error("`document` not found. Cannot start.")}stop(){this.si&&(this.si.stop(),this.si=void 0,Sr.info("stopping..."))}}var Ao=pe("[SegmentIntegration]"),If="posthog-js";function kf(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((b=>I({},b,{stacktrace:b.stacktrace?I({},b.stacktrace,{type:"raw",frames:(b.stacktrace.frames||[]).map((k=>I({},k,{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 lm{constructor(e,n,i,r,s,o){this.name=If,this.setupOnce=function(a){a(kf(e,{organization:n,projectId:i,prefix:r,severityAllowList:s,sendExceptionsToPostHog:o==null||o}))}}}class Jc{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?At(a/o,0,1,A):1,h=o>1?At(l/o,0,1,A):1,p=u>1?At(c/u,0,1,A):1,g=u>1?At(d/u,0,1,A):1;r=fe(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 Po=["flags","surveys"],cm={[tf]:{exposure:"hidden"},[$i]:{exposure:"hidden"},__cmpns:{exposure:"hidden"},[Mi]:{exposure:"hidden"},[oa]:{exposure:"event"},[aa]:{exposure:"hidden"},[la]:{exposure:"event"},[ca]:{exposure:"hidden"},[ua]:{exposure:"event"},[da]:{exposure:"event"},[ul]:{exposure:"event"},[dl]:{exposure:"hidden"},[fa]:{exposure:"event"},[An]:{exposure:"hidden"},$session_recording_enabled_server_side:{exposure:"hidden"},[Kn]:{exposure:"hidden"},[fl]:{exposure:"event"},[nf]:{exposure:"event",shouldSkipFromEventProperties:t=>Je(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"},[Sn]:{exposure:"hidden",storageGroup:"flags"},[Li]:{exposure:"hidden",storageGroup:"flags"},[Tr]:{exposure:"hidden"},[ha]:{exposure:"hidden",storageGroup:"flags"},[Ni]:{exposure:"hidden",storageGroup:"flags"},[$r]:{exposure:"hidden",storageGroup:"flags",volatile:!0},[ns]:{exposure:"hidden",storageGroup:"flags"},[It]:{exposure:"hidden"},[xn]:{exposure:"hidden"},[jt]:{exposure:"hidden"},[In]:{exposure:"hidden"},[pa]:{exposure:"hidden",storageGroup:"surveys"},[is]:{exposure:"hidden",storageGroup:"surveys",volatile:!0},[ga]:{exposure:"event"},[Mr]:{exposure:"hidden"},[Lr]:{exposure:"hidden"},[Oi]:{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"},[Cn]:{exposure:"hidden"},[Bi]:{exposure:"hidden"},[Nr]:{exposure:"hidden"},[Wi]:{exposure:"hidden",storageGroup:"flags",volatile:!0},[lt]:{exposure:"hidden"},[ma]:{exposure:"hidden"},[va]:{exposure:"hidden"},[_a]:{exposure:"hidden"},[ya]:{exposure:"hidden"},[rs]:{exposure:"hidden"},[ss]:{exposure:"hidden"},[rf]:{exposure:"event"},[sf]:{exposure:"event"},[of]:{exposure:"event"},[af]:{exposure:"event"},[cf]:{exposure:"event"},[uf]:{exposure:"event"},[df]:{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"}},um=[["$posthog_sr_group_event_trigger_",{exposure:"hidden"}],["$posthog_sr_group_url_trigger_",{exposure:"hidden"}],["$posthog_sr_group_sampling_",{exposure:"hidden"}]],yn=t=>{var e=cm[t];if(e)return e;for(var n of um){var i=n[1];if(t.indexOf(n[0])===0)return i}},Yn=(t,e)=>{try{return JSON.stringify(t,((n,i)=>typeof i=="bigint"?i.toString():i),e)}catch{return Ed(t)}},us=t=>{var e=P?.createElement("a");return C(e)?null:(e.href=t,e)},si=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," ")},tr=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},ds=function(t,e){var n=t.match(new RegExp(e+"=([^&]*)"));return n?n[1]:null},Cf=(t,e)=>t>=e&&yd(),Af=(t,e,n,i)=>{if(t===0){if(yd()){var r=e+1;return r===n&&i(),r}return e}return 0},xr="https?://(.*)",oi=["gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","irclid","_kx"],dm=["utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid",...oi],nr="",fm=["li_fat_id"];function Pf(t,e,n){if(!P)return{};var i,r=e?[...oi,...n||[]]:[],s=Ff(tr(P.URL,r,nr),t),o=(i={},ie(fm,(function(a){var l=ff(a);i[a]=l||null})),i);return fe(o,s)}function Ff(t,e){var n=dm.concat(e||[]),i={};return ie(n,(function(r){var s=si(t,r);i[r]=s||null})),i}function Rf(t){var e=(function(s){return s?s.search(xr+"google.([^/?]*)")===0?"google":s.search(xr+"bing.com")===0?"bing":s.search(xr+"yahoo.com")===0?"yahoo":s.search(xr+"duckduckgo.com")===0?"duckduckgo":null:null})(t),n=e!="yahoo"?"q":"p",i={};if(!Je(e)){i.$search_engine=e;var r=P?si(P.referrer,n):"";r.length&&(i.ph_keyword=r)}return i}function Zc(){return navigator.language||navigator.userLanguage}var fs="$direct";function Tf(){return P?.referrer||fs}function $f(t,e,n){n===void 0&&(n=!1);var i=t?[...oi,...e||[]]:[],r=n?fn(me?.href):me?.href,s=r?.substring(0,1e3);return{r:Tf().substring(0,1e3),u:s?tr(s,i,nr):void 0}}function Mf(t,e){var n;e===void 0&&(e=!1);var i=t.r,r=t.u,s=e?fn(r):r,o={$referrer:i,$referring_domain:i==null?void 0:i==fs?fs:(n=us(i))==null?void 0:n.host};if(s){o.$current_url=s;var a=us(s);o.$host=a?.host,o.$pathname=a?.pathname;var l=Ff(s);fe(o,l)}if(i){var u=Rf(i);fe(o,u)}return o}function Lf(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return}}function hm(){try{return new Date().getTimezoneOffset()}catch{return}}var pm={flags:Wi,surveys:is},gm=["cookie","localstorage","localstorage+cookie","sessionstorage","memory"],Hn="main";class Fo{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,I({},this.props)),this.update_config(e,e,n),this.save(),w){var r=()=>this.flush();ve(w,"beforeunload",r,{capture:!1}),ve(w,"pagehide",r,{capture:!1})}}ki(){var e,n=(e=this.Ne)==null?void 0:e.persistence_save_debounce_ms;return ke(n)&&n>0?n:0}isDisabled(){return!!this.xi}bi(e){gm.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=[...Gg,...o];return I({},le,{H(u){try{var c={};try{c=zt.H(u)||{}}catch{}var d,f=JSON.parse(le.P(u)||"{}");if(a){var h={};for(var p in c){var g=c[p];Je(g)||g===""||(h[p]=g)}d=fe(f,h)}else d=fe(c,f);return le.F(u,d),d}catch{}return null},F(u,c,d,f,h,p){var g=le.F(u,c,void 0,void 0,p);try{var m={};l.forEach((v=>{c[v]&&(m[v]=c[v])})),Object.keys(m).length&&zt.F(u,m,d,f,h,p)}catch(v){le.j(v)}return g},q(u,c){try{w?.localStorage.removeItem(u),zt.q(u,c)}catch(d){le.j(d)}}})})(e.cookie_persisted_properties||[],e.__preview_cookie_wins_on_conflict||!1),r=!1,s=e.persistence.toLowerCase();return s==="localstorage"&&le.N()?(n=le,r=!0):s==="localstorage+cookie"&&i.N()?(n=i,r=!0):s==="sessionstorage"&&be.N()?n=be:s==="memory"?n=Kg:s==="cookie"?n=zt:i.N()?(n=i,r=!0):n=zt,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=yn(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=fe({},e)),this.pi&&this.Ci()}}Ci(){for(var e of Po){var n=le.H(this.Si(e));if(n&&!Kt(n)){var i=this.Mi(e);i.persisted=!0,this.Ti(e)||(i.fingerprint=this.Ei(n,e)),this.Ii(e,n)||fe(this.props,n)}}}Ti(e){return Object.keys(this.props).some((n=>{var i;return((i=yn(n))==null?void 0:i.storageGroup)===e}))}Ii(e,n){var i=pm[e];if(!i)return!1;var r=n[i],s=this.props[i];return ke(r)&&ke(s)&&s>r}refreshKey(e){var n;if(!this.xi){var i=this.pi?(n=yn(e))==null?void 0:n.storageGroup:void 0,r=i?le.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,Hn))}Li(){var e=this.Di(),n=e.main,i=e.groups;for(var r of(this.Oi(this.ii,this.yi,n,Hn),Po)){var s,o=i[r];(!Kt(o)||(s=this.ci[r])!=null&&s.persisted)&&this.Oi(le,this.Si(r),o,r)}}Di(){var e={},n={flags:{},surveys:{}};return ie(this.props,((i,r)=>{var s,o=(s=yn(r))==null?void 0:s.storageGroup;o?n[o][r]=i:e[r]=i})),{main:e,groups:n}}Ei(e,n){if(n===Hn)return JSON.stringify(e)+"|"+this.$i+"|"+this.Ni+"|"+this.qi;var i={};return ie(e,((r,s)=>{var o;i[s]=(o=yn(s))!=null&&o.volatile?"__volatile__":r})),JSON.stringify(i)}Oi(e,n,i,r){var s=this.Mi(r);if(r===Hn||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!==Hn&&(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 Po)le.q(this.Si(r));i?delete this.ci[Hn]:this.ci={}}clear(){this.remove(),this.props={}}register_once(e,n,i){if(he(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(he(e)){this.$i=C(n)?this.ji:n;var i=!1;if(ie(e,((r,s)=>{e.hasOwnProperty(s)&&(this.props[s]!==r||he(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=P?.URL;if(e!==this.mi){var n=Pf(this.Ne.custom_campaign_params,this.Ne.mask_personal_data_properties,this.Ne.custom_personal_data_properties);Kt(pl(n))||this.register(n),this.mi=e}}update_search_keyword(){var e;this.register((e=P?.referrer)?Rf(e):{})}update_referrer_info(){var e;this.register_once({$referrer:Tf(),$referring_domain:P!=null&&P.referrer&&((e=us(P.referrer))==null?void 0:e.host)||fs},void 0)}set_initial_person_info(){this.props[_a]||this.props[ya]||this.register_once({[rs]:$f(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([ya,_a],(r=>{var s=this.props[r];s&&ie(s,(function(o,a){e["$initial_"+Qo(a)]=o}))}));var n=this.props[rs];if(n){var i=(function(r,s){s===void 0&&(s=!1);var o=Mf(r,s),a={};return ie(o,(function(l,u){a["$initial_"+Qo(u)]=l})),a})(n,this.Ne.disable_capture_url_hashes);fe(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[Mi]||{};i[e]=n,this.Pi(Mi,i),this.save()}remove_event_timer(e){var n=this.props[Mi]||{},i=n[e];return C(i)||(delete n[e],this.Pi(Mi,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=yn(e))!=null&&i.volatile||this.Bi(e)}Ri(e){delete this.props[e],this.Bi(e)}Bi(e){var n,i=(n=yn(e))==null?void 0:n.storageGroup;i&&(this.Mi(i).dirty=!0)}Mi(e){return this.ci[e]||(this.ci[e]={})}}function Ir(t){var e=!0;return{dispose(){if(e){e=!1;var n=t();n&&je(n.then)&&n.then(void 0,(()=>{}))}}}}var Ue={GZipJS:"gzip-js",Base64:"base64"},Si={Activation:"events",Cancellation:"cancelEvents"},Ro={Popover:"popover",API:"api",Widget:"widget"},qt={SHOWN:"survey shown",DISMISSED:"survey dismissed",SENT:"survey sent"},To={SURVEY_ID:"$survey_id",SURVEY_ITERATION:"$survey_iteration",SURVEY_LAST_SEEN_DATE:"$survey_last_seen_date"},xa={Popover:"popover",Inline:"inline"},mm={SHOWN:"product tour shown"},Xc={TOUR_LAST_SEEN_DATE:"$product_tour_last_seen_date",TOUR_TYPE:"$product_tour_type"},Qc=pe("[RateLimiter]");class vm{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=>{Qc.info((r||"events")+" is quota limited."),this.serverLimits[r]=new Date().getTime()+6e4}))}catch(r){return void Qc.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(va))!==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=(ke(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(va,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")&&me!=null&&me.pathname)return""+((e=me.origin)!==null&&e!==void 0?e:"")+me.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 an.info("Using preloaded remote config",this.remoteConfig),this.Zi(this.remoteConfig),void this.Gi();if(this._instance.Qi())return void an.warn("Remote config is disabled. Falling back to local config.");this.Wi((e=>{if(!e)return an.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){an.error("Error loading remote config",e),this.Zi()}}stop(){this.Ki&&(clearInterval(this.Ki),this.Ki=void 0)}refresh(){!this._instance.Qi()&&P&&P.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||an.warn("Failed to fetch remote config from PostHog."):an.error("Failed to fetch remote config from PostHog."));try{this._instance.Zi(e?{ok:!0,config:e}:{ok:!1})}catch(r){an.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){an.error("Error loading feature flags",r)}}}var ut=Uint8Array,Ye=Uint16Array,ai=Uint32Array,_l=new ut([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]),yl=new ut([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]),eu=new ut([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Of=function(t,e){for(var n=new Ye(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=Of(_l,2),Ia=Bf[1];Bf[0][28]=258,Ia[258]=28;for(var tu=Of(yl,0)[1],Df=new Ye(32768),_e=0;32768>_e;++_e){var Wn=(43690&_e)>>>1|(21845&_e)<<1;Df[_e]=((65280&(Wn=(61680&(Wn=(52428&Wn)>>>2|(13107&Wn)<<2))>>>4|(3855&Wn)<<4))>>>8|(255&Wn)<<8)>>>1}var qi=function(t,e,n){for(var i=t.length,r=0,s=new Ye(e);i>r;++r)++s[t[r]-1];var o,a=new Ye(e);for(r=0;e>r;++r)a[r]=a[r-1]+s[r-1]<<1;for(o=new Ye(i),r=0;i>r;++r)o[r]=Df[a[t[r]-1]++]>>>15-t[r];return o},$n=new ut(288);for(_e=0;144>_e;++_e)$n[_e]=8;for(_e=144;256>_e;++_e)$n[_e]=9;for(_e=256;280>_e;++_e)$n[_e]=7;for(_e=280;288>_e;++_e)$n[_e]=8;var hs=new ut(32);for(_e=0;32>_e;++_e)hs[_e]=5;var _m=qi($n,9),ym=qi(hs,5),jf=function(t){return(t/8>>0)+(7&t&&1)},Uf=function(t,e,n){(n==null||n>t.length)&&(n=t.length);var i=new(t instanceof Ye?Ye:t instanceof ai?ai:ut)(n-e);return i.set(t.subarray(e,n)),i},Ot=function(t,e,n){var i=e/8>>0;t[i]|=n<<=7&e,t[i+1]|=n>>>8},xi=function(t,e,n){var i=e/8>>0;t[i]|=n<<=7&e,t[i+1]|=n>>>8,t[i+2]|=n>>>16},$o=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 ut(0),0];if(r==1){var o=new ut(n[0].s+1);return o[n[0].s]=1,[o,1]}n.sort((function(b,k){return b.f-k.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 Ye(f+1),p=ka(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 ut(h),p]},ka=function(t,e,n){return t.s==-1?Math.max(ka(t.l,e,n+1),ka(t.r,e,n+1)):e[t.s]=n},nu=function(t){for(var e=t.length;e&&!t[--e];);for(var n=new Ye(++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]},Ii=function(t,e){for(var n=0,i=0;e.length>i;++i)n+=t[i]*e[i];return n},Ca=function(t,e,n){var i=n.length,r=jf(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)},iu=function(t,e,n,i,r,s,o,a,l,u,c){Ot(e,c++,n),++r[256];for(var d=$o(r,15),f=d[0],h=d[1],p=$o(s,15),g=p[0],m=p[1],v=nu(f),E=v[0],S=v[1],_=nu(g),b=_[0],k=_[1],T=new Ye(19),x=0;E.length>x;++x)T[31&E[x]]++;for(x=0;b.length>x;++x)T[31&b[x]]++;for(var F=$o(T,7),$=F[0],O=F[1],L=19;L>4&&!$[eu[L-1]];--L);var N,K,V,M,R=u+5<<3,Z=Ii(r,$n)+Ii(s,hs)+o,Ce=Ii(r,f)+Ii(s,g)+o+14+3*L+Ii(T,$)+(2*T[16]+3*T[17]+7*T[18]);if(Z>=R&&Ce>=R)return Ca(e,c,t.subarray(l,l+u));if(Ot(e,c,1+(Z>Ce)),c+=2,Z>Ce){N=qi(f,h),K=f,V=qi(g,m),M=g;var oe=qi($,O);for(Ot(e,c,S-257),Ot(e,c+5,k-1),Ot(e,c+10,L-4),c+=14,x=0;L>x;++x)Ot(e,c+3*x,$[eu[x]]);c+=3*L;for(var ye=[E,b],$e=0;2>$e;++$e){var ae=ye[$e];for(x=0;ae.length>x;++x)Ot(e,c,oe[Ie=31&ae[x]]),c+=$[Ie],Ie>15&&(Ot(e,c,ae[x]>>>5&127),c+=ae[x]>>>12)}}else N=_m,K=$n,V=ym,M=hs;for(x=0;a>x;++x)if(i[x]>255){var Ie;xi(e,c,N[257+(Ie=i[x]>>>18&31)]),c+=K[Ie+257],Ie>7&&(Ot(e,c,i[x]>>>23&31),c+=_l[Ie]);var Se=31&i[x];xi(e,c,V[Se]),c+=M[Se],Se>3&&(xi(e,c,i[x]>>>5&8191),c+=yl[Se])}else xi(e,c,N[i[x]]),c+=K[i[x]];return xi(e,c,N[256]),c+K[256]},wm=new ai([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),bm=(function(){for(var t=new ai(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 Em(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=bm[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 ut(p+v+5*(1+Math.floor(v/7e3))+g),S=E.subarray(p,E.length-g),_=0;if(!f||8>v)for(var b=0;v>=b;b+=65535){var k=b+65535;v>k?_=Ca(S,_,d.subarray(b,k)):(S[b]=!0,_=Ca(S,_,d.subarray(b,v)))}else{for(var T=wm[f-1],x=T>>>13,F=8191&T,$=(1<b;++b){var Ie=V(b),Se=32767&b,De=L[Ie];if(O[Se]=De,L[Ie]=Se,b>=$e){var wt=v-b;if((Ce>7e3||ye>24576)&&wt>423){_=iu(d,S,0,M,R,Z,oe,ye,ae,b-ae,_),ye=Ce=oe=0,ae=b;for(var ge=0;286>ge;++ge)R[ge]=0;for(ge=0;30>ge;++ge)Z[ge]=0}var Ze=2,bt=0,mn=F,Te=Se-De&32767;if(wt>2&&Ie==V(b-Te))for(var Pe=Math.min(x,wt)-1,$t=Math.min(32767,b),Bn=Math.min(258,wt);$t>=Te&&--mn&&Se!=De;){if(d[b+Ze]==d[b+Ze-Te]){for(var qe=0;Bn>qe&&d[b+qe]==d[b+qe-Te];++qe);if(qe>Ze){if(Ze=qe,bt=Te,qe>Pe)break;var Dn=Math.min(Te,qe-2),Mt=0;for(ge=0;Dn>ge;++ge){var Lt=b-Te+ge+32768&32767,dt=Lt-O[Lt]+32768&32767;dt>Mt&&(Mt=dt,De=Lt)}}}Te+=(Se=De)-(De=O[Se])+32768&32767}if(bt){M[ye++]=268435456|Ia[Ze]<<18|tu[bt];var sn=31&Ia[Ze],_i=31&tu[bt];oe+=_l[sn]+yl[_i],++R[257+sn],++Z[_i],$e=b+Ze,++Ce}else M[ye++]=d[b],++R[d[b]]}}_=iu(d,S,!0,M,R,Z,oe,ye,ae,b-ae,_)}return Uf(E,0,p+jf(_)+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&&Mo(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),Mo(u,c-8,n.d()),Mo(u,c-4,i),u}var Sm=!!Jo||!!il,Hf="text/plain",Br=!1,Wf=(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:"")},Ts=function(t,e,n){var i;n===void 0&&(n=!0);var r=t.split("?"),s=r[0],o=r[1],a=I({},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},Lo=t=>{if(t.Ji)return t.Ji;var e=t.data,n=t.compression;if(e){if(n===Ue.GZipJS){var i=Em((function(a,l){var u=a.length;if(typeof TextEncoder<"u")return new TextEncoder().encode(a);for(var c=new ut(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 ut(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 Uf(c,0,d)})(Yn(e)),{mtime:0});return{contentType:Hf,body:i.buffer.slice(i.byteOffset,i.byteOffset+i.byteLength),estimatedSize:i.byteLength}}if(n===Ue.Base64){var r=(function(a){return a&&btoa(encodeURIComponent(a).replace(/%([0-9A-F]{2})/g,((l,u)=>String.fromCharCode(parseInt(u,16)))))})(Yn(e)),s=(a=>"data="+encodeURIComponent(typeof a=="string"?a:Yn(a)))(r);return{contentType:"application/x-www-form-urlencoded",body:s,estimatedSize:new Blob([s]).size}}var o=Yn(e);return{contentType:"application/json",body:o,estimatedSize:new Blob([o]).size}}},zf=t=>{var e,n,i=()=>t.transport==="sendBeacon"?{url:Ts(t.url,{compression:Ue.Base64}),encodedBody:Lo(I({},t,{compression:Ue.Base64,Ji:void 0}))}:{url:Wf(t.url,"compression"),encodedBody:Lo(I({},t,{compression:void 0,Ji:void 0}))};try{e=Lo(t)}catch(r){if(Sc(t.compression,si(t.url,"compression")))return A.error("Failed to gzip request body, sending uncompressed payload",r),i();throw r}return e&&Sc(t.compression,si(t.url,"compression"))&&!((n=e.body)instanceof ArrayBuffer?Zo(new Uint8Array(n)):ArrayBuffer.isView(n)&&Zo(new Uint8Array(n.buffer,n.byteOffset,n.byteLength)))?(Br=!0,i()):{url:t.url,encodedBody:e}},qf=t=>{try{return zf(t)}catch(e){return A.error(e),void(t.callback==null||t.callback({statusCode:0,error:e}))}},xm=(function(){var t=se((function*(e){var n=Yn(e.data),i=yield(function(s,o,a){return Xo.apply(this,arguments)})(n,ne.DEBUG,{rethrow:!0});if(!i)return e;var r=yield i.arrayBuffer();return I({},e,{Ji:{contentType:Hf,body:r,estimatedSize:r.byteLength}})}));return function(e){return t.apply(this,arguments)}})(),Im=/Failed to fetch|NetworkError|Load failed/i,Vf=t=>t?.name==="TypeError"&&Im.test(t?.message||""),Gf=t=>{var e=qf(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(vc){var d=new vc;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"||Vf(p)?A.warn(p):A.error(p),t.callback==null||t.callback({statusCode:0,error:p})};try{var h;il(n,I({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)}}},Aa=t=>{try{var e,n=zf(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(He.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:I({},t.data,{batch:f});return Aa(I({},t,{data:d(u.slice(0,c))})),void Aa(I({},t,{data:d(u.slice(c))}))}A.warn("Beacon of ~"+(a??0)+" bytes was rejected by the browser, falling back to fetch"),Gf(I({},t,{Yi:!0}))}catch(f){A.warn("Beacon send failed",f)}},ru=(t,e,n,i)=>{var r=i==="query"?e==="POST"?"sent_at":"_":void 0;return Ts(n===Ue.GZipJS?Wf(t,"compression"):t,I({},r?{[r]:Date.now().toString()}:{},n===Ue.GZipJS?{}:{compression:n}))},Dr=[];il&&Dr.push({transport:"fetch",method:Gf}),Jo&&Dr.push({transport:"XHR",method(t){var e=qf(t);if(e){var n=new Jo,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)}}}),He!=null&&He.sendBeacon&&Dr.push({transport:"sendBeacon",method:Aa});var Pa=3e3;class km{constructor(e,n){this.Xi=!0,this.tr=[],this.er=At(n?.flush_interval_ms||Pa,250,5e3,A.createLogger("flush interval"),Pa),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(I({},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]=I({},r,{data:[]})),(i=e[s].data)==null||i.push(r.data)})),this.tr=[],e}}var Cm=["retriesPerformedSoFar"];class Am{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},ve(w,"online",this.vr),ve(w,"offline",this.pr))}get length(){return this.tr.length}retriableRequest(e){var n=e.retriesPerformedSoFar,i=wd(e,Cm);Dt(n)&&(i.url=Ts(i.url,{retry_count:n})),this._instance._send_request(I({},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(I({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(I({},n,{transport:"sendBeacon"}))}catch(i){A.error(i)}}this.tr=[]}}class Pm{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(){ve(w,"scroll",this.yr,{capture:!0}),ve(w,"scrollend",this.yr,{capture:!0}),ve(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 Fm=t=>$f(t?.config.mask_personal_data_properties,t?.config.custom_personal_data_properties,t?.config.disable_capture_url_hashes);class su{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({[ma]:a})}},this._instance=e,this.Tr=n,this.Mr=i,this.Cr=r||Fm,this.Tr.onSessionId(this.kr)}Sr(){return this.Mr.props[ma]}getSetOnceProps(){var e,n=(e=this.Sr())==null?void 0:e.props;return n?"r"in n?Mf(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(pl(this.getSetOnceProps()),((n,i)=>{i==="$current_url"&&(i="url"),e["$session_entry_"+Qo(i)]=n})),e}}class wl{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 ki=pe("[SessionId]");class ou{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 wl,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===Wt)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||Ht,this.Nr=i||Ht;var s=this.Ne.persistence_name||this.Ne.token;if(this._sessionTimeoutMs=1e3*At(this.Ne.session_idle_timeout_seconds||1800,60,36e3,ki.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=be.H(this.jr),a=be.H(this.Br);o&&!a?this.Or=o:be.q(this.jr),be.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){ki.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&&be.N()}Wr(e){e!==this.Or&&(this.Or=e,this.Hr()&&be.F(this.jr,e))}Vr(){return this.Or?this.Or:this.Hr()?be.H(this.jr):null}Zr(e){var n=this.Pr;return!Je(n)&&!Je(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({[Kn]:[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(Kn):(this.Mr.flush(),this.Mr.load())}Kr(){var e;if(!Je(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({[Kn]:[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[Kn];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(as,this.Ar,{capture:!1}),this.Ar=void 0),this.Rr=[]}zr(){this.Ar=()=>{this.Kr(),this.Hr()&&be.q(this.Br)},ve(w,as,this.Ar,{capture:!1})}checkAndGetSessionAndWindowId(e,n){if(e===void 0&&(e=!1),n===void 0&&(n=null),this.Ne.cookieless_mode===Wt)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=Dt(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))||ki.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(),ki.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)&&(ki.info("adopted cross-tab session id",{sessionId:s,windowId:l}),c=!0));var m=Dt(a)&&e&&!u?a:i,v=Dt(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 Kf=function(t,e){if(!t)return!1;var n=t.userAgent;if(n&&Ic(n,e))return!0;try{var i=t?.userAgentData;if(i!=null&&i.brands&&i.brands.some((r=>Ic(r?.brand,e))))return!0}catch{}return!!t.webdriver};function Yf(){return(Yf=se((function*(){var t=He?.userAgentData;if(t!=null&&t.getHighEntropyValues)try{var e=yield t.getHighEntropyValues(["model"]),n=e?.model;return X(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 ps=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 No(t,e,n){return Yn({distinct_id:t,userPropertiesToSet:e,userPropertiesToSetOnce:n})}var Jf={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=>ps(n,i))))),not_regex:(t,e)=>e.every((n=>t.every((i=>!ps(n,i))))),icontains:(t,e)=>e.map(kr).some((n=>t.map(kr).some((i=>n.includes(i))))),not_icontains:(t,e)=>e.map(kr).every((n=>t.map(kr).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 Zf(t,e){return!t||Object.entries(t).every((n=>{var i=n[1],r=e?.[n[0]];if(C(r)||Je(r))return!1;var s=[String(r)],o=Jf[i.operator];return!!o&&o(i.values,s)}))}var Fa="custom",au="i.posthog.com",Rm=/^\/static\//;class Tm{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("."+au,".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":Fa),this.en[this.apiHost]}rn(e){if(Rm.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===Fa)return this.apiHost+n;var r=au+n;switch(e){case"assets":return"https://"+this.region+"-assets."+r;case"api":return"https://"+this.region+"."+r}}}function Xf(t){var e;return!((e=t.conditions)==null||(e=e.events)==null||(e=e.values)==null||!e.length)}var Q=pe("[Surveys]"),Qf="seenSurvey_",eh=t=>{try{var e=(n=>((i,r)=>""+Qf+(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){Q.error("Failed to persist survey seen state",n)}},$m=[Ro.Popover,Ro.Widget,Ro.API],Mm={ignoreConditions:!1,ignoreDelay:!1,displayType:xa.Popover},Lm=pe("[PostHog ExternalIntegrations]"),Nm={intercom:"intercom-integration",crispChat:"crisp-chat-integration"};class Om{constructor(e){this._instance=e}ai(e,n){var i;(i=B.__PosthogExtensions__)==null||i.loadExternalDependency==null||i.loadExternalDependency(this._instance,e,(r=>{if(r)return Lm.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=B.__PosthogExtensions__)!=null&&(s=s.integrations)!=null&&s[l]||e.ai(Nm[l],(()=>{var c;(c=B.__PosthogExtensions__)==null||(c=c.integrations)==null||(c=c[l])==null||c.start(e._instance)})),!u&&(o=B.__PosthogExtensions__)!=null&&(o=o.integrations)!=null&&o[l]&&((a=B.__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 Bm{constructor(e,n){this.rt=e,this.nn=n,this.sn=new Map,this.an=!1}add(e){var n=this;return se((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&&je(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 Dm{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 lu="extensionsRemoteConfig";class jm{constructor(e){this.an=!1,this.instance=e,this.rt=A,this.un=e.hn,this.kv=new Dm(e),this.onEvent=n=>Ir(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 Ir((()=>{}));var i=s=>{try{n(s)}catch(o){this.rt.error("Browser extension remote config listener failed",o)}},r=this.instance.dn.on(lu,i);return this.un&&i(this.un),Ir(r)},this.vn=new Bm(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(Qi))!==null&&e!==void 0?e:this.distinctId}get deviceId(){var e=this.instance.get_property(Qi);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 se((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 Ir(this.instance.cn(e))}handleRemoteConfig(e){this.an||(this.un=e,this.instance.dn.emit(lu,e))}sendRequest(e,n){var i=this;return se((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?Ts(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 Vi={},Oo=0,gs=()=>{},cu='Consent opt in/out is not valid with cookieless_mode="always" and will be ignored',Ci="Surveys module not available",uu="sanitize_properties is deprecated. Use before_send instead",th="Invalid value for property_denylist config: ",Um=["token","distinct_id",lf],Gn="posthog",nh=!Sm&&Ge?.indexOf("MSIE")===-1&&Ge?.indexOf("Mozilla")===-1,Bo=t=>{var e;return I({api_host:"https://us.i.posthog.com",flags_api_host:null,ui_host:null,asset_host:null,token:"",autocapture:!0,cross_subdomain_cookie:Hg(P?.location),persistence:"localStorage+cookie",persistence_name:"",cookie_persisted_properties:[],loaded:gs,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:me&&X(me?.search)&&me.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:wa,before_send:void 0,get_current_url:void 0,request_queue_config:{flush_interval_ms:Pa},error_tracking:{},_onCapture:gs},(n=>({rageclick:n&&n>="2026-05-30"?{content_ignorelist:em,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))},Hm=[["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"]],du=t=>{var e={};for(var n of Hm){var i=n[0],r=n[1];C(t[i])||(e[r]=t[i])}var s=fe({},e,t),o=t.__preview_external_dependency_versioned_paths;return C(o)||(C(t.strict_script_versioning)&&(s.strict_script_versioning=!!o),X(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(th+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 Xe{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===Wt||this.config.cookieless_mode===kn&&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 wl,this.sn=[],this._n=[],this._calculate_event_properties=this.calculateEventProperties.bind(this),this.config=Bo(),this.SentryIntegration=lm,this.sentryIntegration=i=>(function(r,s){var o=kf(r,s);return{name:If,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 Pm(this),this.pageViewManager=new Jc(this),this.rateLimiter=new vm(this),this.requestRouter=new Tm(this),this.consent=new Yg(this),this.externalIntegrations=new Om(this);var n=(e=Xe.__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=X(i)?{[i]:r}:i;this.setPersonProperties(o),s?.({})},set_once:(i,r,s)=>{var o=X(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!==Gn){var r,s=(r=Vi[i])!==null&&r!==void 0?r:new Xe;return s._init(e,n,i),Vi[i]=s,Vi[Gn][i]=s,s}return this._init(e,n,i)}_init(e,n,i){var r,s;n===void 0&&(n={});var o,a=X(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=Bo(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=Bo(n.defaults),u=du(n),c=fe({},l,u,{name:i,token:a});he(l.rageclick)&&he(u.rageclick)&&(c.rageclick=fe({},l.rageclick,u.rageclick)),he(l.session_recording)&&he(u.session_recording)&&(c.session_recording=fe({},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:Ue.GZipJS;var d=this.En();if(this.persistence=new Fo(this.config,d),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new Fo(I({},this.config,{persistence:"sessionStorage"}),d,!1),this.bn="ph_"+(this.config.persistence_name||this.config.token)+"_session_registered_properties",this.config.persistence!=="memory"&&!d&&be.N()){var f=be.H(this.bn);U(f)&&f.forEach((k=>{X(k)&&this.yn.add(k)}))}else be.q(this.bn);var h=I({},this.persistence.props),p=I({},this.sessionPersistence.props);this.register({$initialization_time:new Date().toISOString()}),this.In=new km((k=>this.Pn(k)),this.config.request_queue_config),this.Rn=new Am(this),this.__request_queue=[];var g=this.gn();if(g||(this.sessionManager=new ou(this),this.sessionPropsManager=new su(this,this.sessionManager,this.persistence),this.sessionManager.onSessionId(((k,T,x)=>{(x!=null&&x.activityTimeout||x!=null&&x.sessionPastMaximumLength||x!=null&&x.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:I({},this.config),p:h,s:p}),!this.config.identity_distinct_id||(r=n.bootstrap)!=null&&r.distinctID||(n.bootstrap=I({},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(lt);if(n.bootstrap.isIdentifiedID&&v!=null&&v!==m&&E===Un)this.identify(m);else if(n.bootstrap.isIdentifiedID&&v!=null&&v!==m&&E===vn)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(Ht()),_=n.bootstrap.isIdentifiedID?S:m;this.persistence.set_property(lt,n.bootstrap.isIdentifiedID?vn:Un),this.register({distinct_id:m,$device_id:_})}}if(g)this.register_once({distinct_id:wr,$device_id:null},"");else if(!this.get_distinct_id()){var b=this.config.get_device_id(Ht());this.register_once({distinct_id:b,$device_id:b},""),this.persistence.set_property(lt,Un)}return ve(w,"onpagehide"in self?"pagehide":"unload",this._handle_unload.bind(this),{passive:!1}),n.segment?(function(k,T){var x=k.config.segment;if(!x)return T();(function(F,$){var O=F.config.segment;if(!O)return $();var L=K=>{var V=()=>K.anonymousId()||Ht();F.config.get_device_id=V,K.id()&&(F.register({distinct_id:K.id(),$device_id:V()}),F.persistence.set_property(lt,vn)),$()},N=O.user();"then"in N&&je(N.then)?N.then(L):L(N)})(k,(()=>{x.register((F=>{typeof Promise<"u"&&Promise.resolve||Ao.warn("This browser does not have Promise support, and can not use the segment integration");var $=(O,L)=>{if(!L)return O;O.event.userId||O.event.anonymousId===F.get_distinct_id()||(Ao.info("No userId set, resetting PostHog"),F.reset()),O.event.userId&&O.event.userId!==F.get_distinct_id()&&(Ao.info("UserId set, identifying with PostHog"),F.identify(O.event.userId));var N=F.calculateEventProperties(L,O.event.properties);return O.event.properties=Object.assign({},N,O.event.properties),O};return{name:"PostHog JS",type:"enrichment",version:"1.0.0",isLoaded:()=>!0,load:()=>Promise.resolve(),track:O=>$(O,O.event.event),page:O=>$(O,Vn),identify:O=>$(O,Io),screen:O=>$(O,"$screen")}})(k)).then((()=>{T()}))}))})(this,(()=>this.On())):this.On(),je(this.config._onCapture)&&this.config._onCapture!==gs&&(A.warn("onCapture is deprecated. Please use `before_send` instead"),this.on("eventCaptured",(k=>this.config._onCapture(k.event,k)))),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 Yf.apply(this,arguments)})().then((k=>{k&&this.register({[So]:k})})).catch(gs),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=Xe.__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)),je(this.featureFlags.onReloading)&&je(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=I({},Xe.__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,am)),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({[cf]:this.config.__preview_deferred_init_extensions?"deferred":"synchronous",[uf]:r}),this.config.__preview_deferred_init_extensions&&A.info("PostHog extensions initialized ("+r+"ms)")}Zi(e){var n;if(!P||!P.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,Ue.GZipJS)?Ue.GZipJS:j(r.supportedCompression,Ue.Base64)?Ue.Base64:void 0),(i=r.analytics)!=null&&i.endpoint&&(this.analyticsDefaultEndpoint=r.analytics.endpoint)}this.set_config({person_profiles:this.xn?this.xn:wa}),(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&&me!=null&&me.hostname){var e=me.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 Nf(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()&&br(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(xo),(i=this.logs)==null||i.flushLogs("sendBeacon"),(r=this.In)==null||r.unload(),(s=this.Rn)==null||s.unload()):this.zn()&&this.capture(xo,null,{transport:"sendBeacon"})}_send_request(e){this.__loaded?nh?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=I({},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=I({},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=Ue.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=>I({},E,{sent_at:v}))):I({},m,{sent_at:v})})(o.data))),o.url=ru(o.url,o.method,o.compression,o.timestampMode);var h=Dr.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){Vf(v)?A.warn(v):A.error(v),o.callback==null||o.callback({statusCode:0,error:v})}};f!=="sendBeacon"&&o.data&&o.compression===Ue.GZipJS&&zp&&typeof Promise<"u"&&!Br?xm(o).then((m=>{g(m)})).catch((m=>{if(xc(m))return Br=!0,void g(I({},o,{compression:void 0,url:ru(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 xc(v)||E===bd})(m)&&(Br=!0),g(o)})):p(o)})(I({},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){Oo++;try{var n,i=[],r=[],s=[];br(e,(a=>{if(a)if(U(n=a[0]))s.push(a);else if(je(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&&je(this[n])?s.push(a):r.push(a)}));var o=function(a,l){br(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{Oo--}}push(e){if(Oo>0&&U(e)&&X(e[0])){var n=Xe.prototype[e[0]];je(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)&&X(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&&!X(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=Pc(i?.uuid,Ht),p={uuid:h,event:e,properties:this.calculateEventProperties(e,n||{},f,h)};e===Vn&&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(ns)===!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!==Lc,e===Io);if(_&&(p.$set_once=_),i!=null&&i._noTruncate||(s=this.config.properties_string_max_length,o=p,a=L=>X(L)?L.slice(0,s):L,l=new Set,p=(function L(N,K){if(N!==Object(N))return a?a(N):N;if(!l.has(N)){var V;if(l.add(N),U(N))V=[],br(N,(R=>{V.push(L(R))}));else{var M={};ie(N,((R,Z)=>{l.has(R)||(M[Z]=L(R))})),V=M}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,N){N===void 0&&(N=[]);var K={},V=M=>{L[M]!==void 0&&(K[M]=L[M])};return qp.forEach(V),N.forEach(V),K})(p.properties,Um)),e===qt.DISMISSED||e===qt.SENT){var b=n?.[To.SURVEY_ID],k=n?.[To.SURVEY_ITERATION];eh({id:b,current_iteration:k}),p.$set=I({},p.$set,{[(v={id:b,current_iteration:k},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=I({},p.$set,{[To.SURVEY_LAST_SEEN_DATE]:new Date().toISOString()}));if(e===mm.SHOWN){var T=n?.[Xc.TOUR_TYPE];T&&(p.$set=I({},p.$set,{[Xc.TOUR_LAST_SEEN_DATE+"/"+T]:new Date().toISOString()}))}var x=I({},p.properties.$set,p.$set);if(Kt(x)||this.setPersonPropertiesForFlags(x),!W(this.config.before_send)){var F=this.Pt(p);if(!F)return;(p=F).uuid=Pc(p.uuid,Ht)}this.dn.emit("eventCaptured",p);var $=(r=i?._url)!==null&&r!==void 0?r:this.requestRouter.endpointFor("api",this.analyticsDefaultEndpoint),O={method:"POST",url:$,data:p,compression:"best-available",timestampMode:i?._batchKey==="recordings"||/\/s\/(?:\?|$)/.test($)?"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(O):this.In.enqueue(O),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 jm(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=I({},n);if(a.token=this.config.token,a.$config_defaults=this.config.defaults,this.gn()&&(a[lf]=!0),e==="$snapshot"){var l=I({},this.persistence.properties(),this.sessionPersistence.properties());return a.distinct_id=l.distinct_id,(!X(a.distinct_id)&&!ke(a.distinct_id)||ea(a.distinct_id))&&A.error("Invalid distinct_id for replay event. This indicates a bug in your implementation"),a}var u,c=(function(b,k,T,x){var F,$,O,L;if(x===void 0&&(x=!1),!Ge)return{};var N,K=b?[...oi,...k||[]]:[],V=(function(Bn){for(var qe=0;Cc.length>qe;qe++){var Dn=Cc[qe],Mt=Dn[1],Lt=Dn[0].exec(Bn),dt=Lt&&(je(Mt)?Mt(Lt,Bn):Mt);if(dt)return dt}return["",""]})(Ge),M=V[0],R=V[1],Z=(N=typeof navigator<"u"?navigator:void 0)!=null&&N.brave?{brave:!0}:{},Ce={};C(T)||(Ce.detectGoogleSearchApp=T);var oe={},ye=(F=navigator)==null||(F=F.userAgentData)==null?void 0:F.platform,$e=($=navigator)==null?void 0:$.maxTouchPoints,ae=w==null||(O=w.screen)==null?void 0:O.width,Ie=w==null||(L=w.screen)==null?void 0:L.height,Se=w?.devicePixelRatio;C(ye)||(oe.userAgentDataPlatform=ye),C($e)||(oe.maxTouchPoints=$e),C(ae)||(oe.screenWidth=ae),C(Ie)||(oe.screenHeight=Ie),C(Se)||(oe.devicePixelRatio=Se);var De,wt,ge,Ze,bt,mn,Te,Pe,$t=fe(pl({$os:M,$os_version:R,$browser:Vd(Ge,navigator.vendor,Z,Ce),$device:Ac(Ge),$device_type:(wt=Ge,ge=oe,Pe=Ac(wt),Pe===Ad||Pe===Cd||Pe==="Kobo"||Pe==="Kindle Fire"||Pe===Ud?ni:Pe===Zi||Pe===Xn||Pe===Xi||Pe===na?"Console":Pe===Fd?"Wearable":Pe?st:ge?.userAgentDataPlatform==="Android"&&((Ze=ge?.maxTouchPoints)!==null&&Ze!==void 0?Ze:0)>0?600>Math.min((bt=ge?.screenWidth)!==null&&bt!==void 0?bt:0,(mn=ge?.screenHeight)!==null&&mn!==void 0?mn:0)/((Te=ge?.devicePixelRatio)!==null&&Te!==void 0?Te:1)?st:ni:"Desktop"),$timezone:Lf(),$timezone_offset:hm()}),{$current_url:tr(x?fn(me?.href):me?.href,K,nr),$host:me?.host,$pathname:me?.pathname,$raw_user_agent:Ge.length>1e3?Ge.substring(0,997)+"...":Ge,$browser_version:ug(Ge,navigator.vendor,Z,Ce),$browser_language:Zc(),$browser_language_prefix:(De=Zc(),typeof De=="string"?De.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&&($t.$sdk_dist_channel=ne.SDK_DIST_CHANNEL),$t})(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&&fe(a,this.sessionPropsManager.getSessionProps());try{var h;this.sessionRecording&&fe(a,this.sessionRecording.sdkDebugProperties),a.$sdk_debug_retry_queue_size=(h=this.Rn)==null?void 0:h.length}catch(b){a.$sdk_debug_error_capturing_properties=String(b)}if(this.requestRouter.region===Fa&&(a.$lib_custom_api_host=this.config.api_host),u=e!==Vn||s?e!==xo||s?this.pageViewManager.doEvent():this.pageViewManager.doPageLeave(i):this.pageViewManager.doPageView(i,r),a=fe(a,u),e===Vn&&P&&(a.title=P.title),!C(o)){var p=i.getTime()-o;a.$duration=parseFloat((p/1e3).toFixed(3))}Ge&&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"],(b=>{b in g&&delete m[b]}));var v={};if(this._n.length>0)for(var E of this._n.slice())try{fe(v,E())}catch(b){A.error("Failed to produce browser extension event properties",b)}(a=fe({},c,g,m,I({},v,a))).$is_identified=this._isIdentified(),U(this.config.property_denylist)?ie(this.config.property_denylist,(function(b){delete a[b]})):A.error(th+this.config.property_denylist+" or property_blacklist config: "+this.config.property_blacklist);var S=this.config.sanitize_properties;S&&(A.error(uu),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=fe({},s,o||{},e||{}),l=this.config.sanitize_properties;return l&&(A.error(uu),a=l(a,"$set_once")),n&&(this.mn=!0),Kt(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||!be.N())be.q(this.bn);else{var n=[];this.yn.forEach((i=>n.push(i))),n.length>0?be.F(this.bn,n):be.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:Ci}),()=>{})}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:Ci})}getActiveMatchingSurveys(e,n){n===void 0&&(n=!1),this.surveys?this.surveys.getActiveMatchingSurveys(e,n):e([],{isLoaded:!1,error:Ci})}renderSurvey(e,n){var i;(i=this.surveys)==null||i.renderSurvey(e,n)}displaySurvey(e,n){var i;n===void 0&&(n=Mm),(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:Ci}}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:Ci})}Jn(e){return!e||ea(e)?(A.critical("Unique user id has not been set in posthog.identify"),!1):e===wr?(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(ke(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(Qi)||this.register_once({$had_persisted_distinct_id:!0,$device_id:r},""),e!==r&&e!==this.get_property($i)&&(this.unregister($i),this.register({distinct_id:e}));var s,o=(this.persistence.get_property(lt)||Un)===Un,a=e!==r,l=!a&&o;if(a&&o)this.persistence.set_property(lt,vn),this.setPersonPropertiesForFlags({$set:n||{},$set_once:i||{}},!1),this.capture(Io,{distinct_id:e,$anon_distinct_id:r},{$set:n||{},$set_once:i||{}}),this.Sn=No(e,n,i),(s=this.featureFlags)==null||s.setAnonymousDistinctId(r);else if(l){this.persistence.set_property(lt,vn);var u=n||{},c=i||{};this.setPersonPropertiesForFlags({$set:u,$set_once:c},!1),this.capture("$set",{$set:u,$set_once:c}),this.Sn=No(e,n,i)}else(n||i)&&this.setPersonProperties(n,i);a?(this.reloadFeatureFlags(),this.featureFlags?this.featureFlags.resetFlagCallReported():this.unregister(Cn)):l&&(n||i)&&this.reloadFeatureFlags()}}setPersonProperties(e,n){if((e||n)&&this.Gn("posthog.setPersonProperties")){var i=No(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=>X(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:I({},r,{[e]:n})}),s||i){var o={$group_type:e,$group_key:n};i&&(o.$group_set=i),this.capture(Lc,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(Qi),g=this.get_property(So),m=this.get_property(An),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({[An]: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(lt,Un),(f=this.sessionManager)==null||f.resetSessionId(),this.Sn=null,this.config.cookieless_mode===Wt)this.register_once({distinct_id:wr,$device_id:null},"");else{var E=this.config.get_device_id(Ht());this.register_once({distinct_id:E,$device_id:e?E:p},""),e||C(g)||this.register({[So]: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 se((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(tf)?(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($i,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=I({},this.config);if(he(e)){var i,r,s,o,a,l,u,c,d,f,h,p;fe(this.config,du(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 Fo(I({},this.config,{persistence:"sessionStorage"}),g,!1);var m=this.Cn(this.config.debug);mt(m)&&(this.config.debug=m),mt(this.config.debug)&&(this.config.debug?(ne.DEBUG=!0,le.N()&&le.F("ph_debug",!0),A.info("set_config",{config:e,oldConfig:n,newConfig:I({},this.config)})):(ne.DEBUG=!1,le.N()&&le.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(I({},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:Xe.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:Gn;return n!==Gn&&(n=Gn+"."+n),n}_isIdentified(){var e,n;return((e=this.persistence)==null?void 0:e.get_property(lt))===vn||((n=this.sessionPersistence)==null?void 0:n.get_property(lt))===vn}Zn(){var e,n;return!(this.config.person_profiles==="never"||this.config.person_profiles===wa&&!this._isIdentified()&&Kt(this.getGroups())&&((e=this.persistence)==null||(e=e.props)==null||!e[$i])&&((n=this.persistence)==null||(n=n.props)==null||!n[ss]))}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(ss,!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!==kn)}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!==Wt){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 ou(this),this.pageViewManager=new Jc(this),this.persistence&&(this.sessionPropsManager=new su(this,this.sessionManager,this.persistence));var l,u=(s=(o=this.config.__extensionClasses)==null?void 0:o.sessionRecording)!==null&&s!==void 0?s:(a=Xe.__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==kn&&((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(cu)}opt_out_capturing(){var e,n,i;this.config.cookieless_mode!==Wt?(this.config.cookieless_mode===kn&&this.consent.isOptedIn()&&this.Yn(!0,!0),this.consent.optInOut(!1),this.es(),this.config.cookieless_mode===kn&&(this.register({distinct_id:wr,$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(cu)}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===Wt||(this.config.cookieless_mode===kn?this.consent.isRejected()||this.consent.isOptedIn():!this.has_opted_out_capturing())}clear_opt_in_out_capturing(){this.consent.reset(),this.es()}_is_bot(){return He?Kf(He,this.config.custom_blocked_useragents):void 0}Hn(){P&&(P.visibilityState==="visible"?this.wn||(this.wn=!0,this.capture(Vn,{title:P.title},{send_instantly:!0}),this.kn&&(P.removeEventListener(os,this.kn),this.kn=null)):this.kn||(this.kn=this.Hn.bind(this),ve(P,os,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&&!W(n[i]),l=r in n&&!W(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(W(this.config.before_send))return e;var i=Object.keys((n=e.properties)!==null&&n!==void 0?n:{}).filter(Xp),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),W(s)){var a="Event '"+e.event+"' was rejected in beforeSend function";return Zp(e.event)?A.warn(a+". This can cause unexpected behavior."):A.info(a),null}s.properties&&!Kt(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&&W(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=mt(e)&&!e,i=le.N()&&le.P("ph_debug")==="true";return!n&&(!!i||e)}}Xe.__defaultExtensionClasses={},Xe.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]]=jg(t.prototype[e[n]])})(Xe,["identify"]);class fu{constructor(e){this.disabled=e===!1;var n=he(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 Do="$copy_autocapture",jo=pe("[AutoCapture]");function Uo(t,e){return e.length>t?e.slice(0,t)+"...":e}function zm(t){if(t.previousElementSibling)return t.previousElementSibling;var e=t;do e=e.previousSibling;while(e&&!hn(e));return e}function qm(t,e){var n,i,r=e.e,s=e.maskAllElementAttributes,o=e.maskAllText,a=e.elementAttributeIgnoreList,l=e.elementsChainAsString,u=e.disableCaptureUrlHashes;if(!hn(t))return{props:{}};for(var c=[t],d=new Set([t]),f=t;f.parentNode&&!tt(f,"body")&&_f>c.length;)if(vf(f.parentNode)){var h=f.parentNode.host;if(d.has(h))break;d.add(h),c.push(h),f=h}else{if(!hn(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,(x=>{var F=Sa(x);if(tt(x,"a")){var $=x.getAttribute("href");E=!!(F&&$&&zi($))&&(u?fn($):$)}j(cs(x),"ph-no-capture")&&(S=!0),m.push((function(L,N,K,V,M){M===void 0&&(M=!1);var R=L.tagName.toLowerCase(),Z={tag_name:R};ml.indexOf(R)>-1&&!K&&(Z.$el_text=R.toLowerCase()==="a"||R.toLowerCase()==="button"?Uo(1024,Gc(L)):Uo(1024,er(L)));var Ce=cs(L);Ce.length>0&&(Z.classes=Ce.filter((function(ae){return ae!==""}))),ie(L.attributes,(function(ae){var Ie;if((!Sf(L)||["name","id","class","aria-label"].indexOf(ae.name)!==-1)&&(V==null||!V.includes(ae.name))&&!N&&zi(ae.value)&&(!X(Ie=ae.name)||Ie.substring(0,10)!=="_ngcontent"&&Ie.substring(0,7)!=="_nghost")){var Se=ae.value;ae.name==="class"&&(Se=gl(Se).join(" ")),Z["attr__"+ae.name]=Uo(1024,ae.name==="href"&&M?fn(Se):Se)}}));for(var oe=1,ye=1,$e=L;$e=zm($e);)oe++,$e.tagName===L.tagName&&ye++;return Z.nth_child=oe,Z.nth_of_type=ye,Z})(x,s,o,a,u));var O=(function(L){if(!Sa(L))return{};var N={};return ie(L.attributes,(function(K){if(K.name&&K.name.indexOf("data-ph-capture-attribute")===0){var V=K.name.replace("data-ph-capture-attribute-",""),M=K.value;V&&M&&zi(M)&&(N[V]=M)}})),N})(x);fe(v,O)})),S)return{props:{},explicitNoCapture:S};if(o||(m[0].$el_text=tt(t,"a")||tt(t,"button")?Gc(t):er(t)),E){var _,b;m[0].attr__href=E;var k=(_=us(E))==null?void 0:_.host,T=w==null||(b=w.location)==null?void 0:b.host;k&&T&&k!==T&&(p=E)}return{props:fe({$event_type:r.type,$ce_version:1},l?{}:{$elements:m},{$elements_chain:(g=m,(function(x){return x.map((F=>{var $,O,L="";if(F.tag_name&&(L+=F.tag_name),F.attr_class)for(var N of(F.attr_class.sort(),F.attr_class))L+="."+N.replace(/"/g,"");var K=I({},F.text?{text:F.text}:{},{"nth-child":($=F.nth_child)!==null&&$!==void 0?$:0,"nth-of-type":(O=F.nth_of_type)!==null&&O!==void 0?O:0},F.href?{href:F.href}:{},F.attr_id?{attr_id:F.attr_id}:{},F.attributes),V={};return Or(K).sort(((M,R)=>M[0].localeCompare(R[0]))).forEach((M=>{var R=M[1];return V[Kc(M[0].toString())]=Kc(R.toString())})),(L+=":")+Or(V).map((M=>M[0]+'="'+M[1]+'"')).join("")})).join(";")})((function(x){return x.map((F=>{var $,O,L={text:($=F.$el_text)==null?void 0:$.slice(0,400),tag_name:F.tag_name,href:(O=F.attr__href)==null?void 0:O.slice(0,2048),attr_class:sm(F),attr_id:F.attr__id,nth_child:F.nth_child,nth_of_type:F.nth_of_type,attributes:{}};return Or(F).filter((N=>N[0].indexOf("attr__")===0)).forEach((N=>L.attributes[N[0]]=N[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 Ai=pe("[ExceptionAutocapture]"),hu=()=>{},Vm=pe("[TracingHeaders]"),wn=pe("[Web Vitals]"),pu=9e5,gu="disabled",mu="lazy_loading",Pi="awaiting_config",Cr="missing_config";pe("[SessionRecording]"),pe("[SessionRecording]");var Ra="[SessionRecording]",Bt=pe(Ra),Gm=pe("[Heatmaps]");function Ho(t){return he(t)&&"clientX"in t&&"clientY"in t&&ke(t.clientX)&&ke(t.clientY)}var Ar=pe("[Product Tours]"),Wo=t=>{var e;return!t.config.disable_product_tours&&!((e=t.persistence)==null||!e.get_property(dl))},Km=["$set_once","$set"],Et=pe("[SiteApps]"),vu="Error while initializing PostHog app with config id ";function zn(t,e,n){if(W(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 Ym{constructor(e){this.ns=new wl,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"||!zn(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=>zn(a.href,n.href,n.href_matching||"exact")));var s,o=(e==null||(i=e.properties)==null?void 0:i.$elements_chain)||"";return!!o&&zn((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=>zn(u.text,n.text,n.text_matching||"exact")||zn(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;!W(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=>zn(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||Zf(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 Jm{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&&Zf(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===Si.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 Ym(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,Si.Activation),this.ks=this.Ps(e,Si.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,Si.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,Si.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(I({},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&&(Kt(i)?this.Es():this.Ts(i))}}Ks(){this.Ms()&&this.Es()}getActivationTimestamp(e){if(this.zs().includes(e)){var n=this.Qs()[e];return ke(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=>ke(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 Zm extends Jm{constructor(e){super(e)}Js(){return ga}Ys(){return Mr}Ms(){return Lr}Ts(e){var n;(n=this._instance)==null||(n=n.persistence)==null||n.register({[Lr]:e})}Es(){var e;(e=this._instance)==null||(e=e.persistence)==null||e.unregister(Lr)}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 ke(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 Q}Ws(e){var n;(n=this._instance)==null||(n=n.persistence)==null||n.register({[ga]:e})}Xs(e){var n;(n=this._instance)==null||(n=n.persistence)==null||n.register({[Mr]:e})}ta(){var e;(e=this._instance)==null||(e=e.persistence)==null||e.unregister(Mr)}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 Xf(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 Pr="SDK is not enabled or survey functionality is not yet loaded",_u="Disabled. Not loading surveys.",Xm=w!=null&&w.location?ds(w.location.hash,"__posthog")||ds(location.hash,"state"):null,yu="_postHogToolbarParams",wu=pe("[Toolbar]"),bu=pe("[FeatureFlags]");class Qm{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||(bu.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)||bu.error("Invalid flag_keys found:",e.flag_keys,"Expected array of non-empty strings")}get(){return this.sa}}var Eu=pe("[FeatureFlags]"),bn=pe("[FeatureFlags]",{debugEnabled:!0}),zo=`" failed. Feature flags didn't load in time.`,Su="connection_error",xu=t=>{for(var e={},n=0;t.length>n;n++)e[t[n]]=!0;return e},Iu=t=>{var e={};for(var n of Or(t||{})){var i=n[1];i&&(e[n[0]]=i)}return e},St=pe("[Error tracking]"),ku="Refusing to render web experiment since the viewer is a likely bot",ev={icontains:(t,e)=>e.toLowerCase().indexOf(t.toLowerCase())>-1,not_icontains:(t,e)=>e.toLowerCase().indexOf(t.toLowerCase())===-1,regex:(t,e)=>ps(e,t),not_regex:(t,e)=>!ps(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);X(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(ku);else if(!this.Ne.disable_web_experiments){if(W(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=si(e?.search,"__experiment_id"),i=si(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!W(e.conditions)&&Me.da(e,n)&&Me.va(e)}static da(e,n){var i;if(W(e.conditions)||W((i=e.conditions)==null?void 0:i.url))return!0;var r=Me.getWindowLocation();if(r){var s,o,a,l=pf(n,r.href);return(s=e.conditions)==null||!s.url||ev[(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(W(e.conditions)||W((n=e.conditions)==null?void 0:n.utm))return!0;var i=Pf();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(ku):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 He&&this._instance?Kf(He,this.Ne.custom_blocked_useragents):void 0}}var at=pe("[Conversations]"),En="Conversations not available yet.",Cu="console",ih="__posthogHandledLogsRequestError",qo=(t,e)=>{var n=t instanceof Error?t:new Error(e);return n[ih]=!0,n},Au=t=>!!t&&typeof t=="object"&&t[ih]===!0,$s={featureFlags:class{constructor(t){this.name="featureFlags",this.ca=!1,this.featureFlagEventHandlers=[],this.rt=Eu,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 Qm(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&&ve(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[Li,Ni,$r,It]){var n=this.Oa(e);C(n)||(t[e]=n)}this.fa=t;var i=I({},t),r=this.Oa(Sn);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(Wi);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(Sn))!==null&&i!==void 0?i:{},o=n!=null&&n.merge&&(r=this.Oa(Ni))!==null&&r!==void 0?r:{},a=I({},s,t),l=I({},o,e),u={};for(var c of Object.entries(a)){var d=c[0],f=c[1];u[d]={key:d,enabled:wc(f),variant:bc(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(ha),e=this.Oa(It),n=this.Oa(xn);if(!n&&!e)return t||{};var i=fe({},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=I({},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=I({},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:wc(i),variant:bc(i),payload:yc(e[n])}}))}getFlagVariants(){var t=this.Oa(Sn),e=this.Oa(It);if(!e)return t||{};for(var n=fe({},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(Ni),e=this.Oa(xn);if(!e)return t||{};for(var n=fe({},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(Cn)}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:I({},e.initialPersonProperties,this.Oa(jt)||{},{$lib:e.library.name,$lib_version:e.library.version}),group_properties:this.Oa(In),timezone:Lf()};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({[Nr]:[Su]}),this.rt.error("Feature flag request failed",c)),l()};try{e.sendRequest(o,{target:"flags",method:"POST",body:n,compression:this.Ne.compression==="base64"?Ue.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?Su:"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({[Nr]: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 Cf(this.Sa,3)}Ua(t){this.Sa=Af(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+zo)}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($r)||void 0,u=this.Oa(Wi)||void 0,c=this.Oa(Cn)||{};if(this.Ne.deduplicateCallsPerSession){var d,f=(d=this.nn)==null?void 0:d.session.sessionId,h=this.Oa(Bi);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({[Cn]:c,[Bi]:n});else{var p,g,m,v,E,S,_,b,k,T;U(c[t])?c[t].push(a):c[t]=[a],this.F(I({[Cn]:c},n?{[Bi]:n}:{}));var x=this.getFeatureFlagDetails(t),F=[...(p=this.Oa(Nr))!==null&&p!==void 0?p:[]];C(s)&&F.push("flag_missing");var $={$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(x==null||(v=x.metadata)==null?void 0:v.has_experiment)||($.$feature_flag_has_experiment=x.metadata.has_experiment),C(x==null||(E=x.metadata)==null?void 0:E.version)||($.$feature_flag_version=x.metadata.version);var O,L=(S=x==null||(_=x.reason)==null?void 0:_.description)!==null&&S!==void 0?S:x==null||(b=x.reason)==null?void 0:b.code;L&&($.$feature_flag_reason=L),x!=null&&(k=x.metadata)!=null&&k.id&&($.$feature_flag_id=x.metadata.id),C(x?.original_variant)&&C(x?.original_enabled)||($.$feature_flag_original_response=C(x.original_variant)?x.original_enabled:x.original_variant),x!=null&&(T=x.metadata)!=null&&T.original_payload&&($.$feature_flag_original_payload=x==null||(O=x.metadata)==null?void 0:O.original_payload),F.length&&($.$feature_flag_error=F.join(",")),this.za($)}else n&&this.F({[Cn]:c,[Bi]:n});if(r)return{key:t,enabled:!!s,variant:typeof s=="string"?s:void 0,payload:yc(o)}}}else this.rt.warn('getFeatureFlagResult for key "'+t+zo)}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 se((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"?Ue.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+zo),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=Eu);var c=((k,T)=>{var x=k.flags;return x?I({},k,{featureFlags:Object.fromEntries(Object.keys(x).map((F=>{var $;return[F,($=x[F].variant)!==null&&$!==void 0?$:x[F].enabled]}))),featureFlagPayloads:Object.fromEntries(Object.keys(x).filter((F=>x[F].enabled)).filter((F=>{var $;return($=x[F].metadata)==null?void 0:$.payload})).map((F=>{var $;return[F,($=x[F].metadata)==null?void 0:$.payload]})))}):(k.featureFlags&&T.warn("Using an older version of the feature flags endpoint. Please upgrade your PostHog server to the latest version"),k)})(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{[Li]:f,[Sn]:m,[ns]:!1}}var E=f,S=h,_=d;if(l!=null&&l.partialResponse)E=I({},s,E),S=I({},o,S),_=I({},a,_);else if(r.errorsWhileComputingFlags)if(d){var b=new Set(Object.keys(d).filter((k=>{var T;return!((T=d[k])!=null&&T.failed)})));E=I({},s,Object.fromEntries(Object.entries(E).filter((k=>b.has(k[0]))))),S=I({},o,Object.fromEntries(Object.entries(S||{}).filter((k=>b.has(k[0]))))),_=I({},a,Object.fromEntries(Object.entries(_||{}).filter((k=>b.has(k[0])))))}else E=I({},s,E),S=I({},o,S),_=I({},a,_);return I({[Li]:Object.keys(Iu(E)),[Sn]:E||{},[Ni]:S||{},[ha]:_||{},[ns]:r.minimalFlagCalledEvents===!0},p?{[$r]:p}:{},g?{[Wi]: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,xn]),this.Va(),void bn.info("All overrides cleared");if(U(t))return this.F({[It]:xu(t)}),this.Va(),void bn.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[It]=U(r)?xu(r):r),s&&(i[xn]=s),Object.keys(i).length&&this.F(i),r===!1&&s===!1?this.q([It,xn]):r===!1?this.q(It):s===!1&&this.q(xn),this.Va(),r===!1?bn.info("Flag overrides cleared"):r&&bn.info("Flag overrides set",{flags:r}),void(s===!1?bn.info("Payload overrides cleared"):s&&bn.info("Payload overrides set",{payloads:s}))}if(t&&typeof t=="object")return this.F({[It]:t}),this.Va(),void bn.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(Tr)||[]).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=I({},this.getFlagVariants(),{[t]:e});this.F({[Li]:Object.keys(Iu(o)),[Sn]:o,[jt]:I({},this.Oa(jt)||{},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(Tr);!i||e?this.Qa(t,n):t(i)}Qa(t,e){var n=this;return se((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({[Tr]: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(jt)||{},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({[jt]:I({},n,s,i)}),e&&this.reloadFeatureFlags()}unsetPersonPropertiesForFlags(t,e){e===void 0&&(e=!0);var n=I({},this.Oa(jt)||{});t.forEach((i=>{delete n[i]})),this.F({[jt]:n}),e&&this.reloadFeatureFlags()}resetPersonPropertiesForFlags(t){t===void 0&&(t=!0),this.q(jt),t&&this.reloadFeatureFlags()}setGroupPropertiesForFlags(t,e){e===void 0&&(e=!0);var n=this.Oa(In)||{},i=I({},n);for(var r of Object.keys(t))i[r]=I({},n[r],t[r]);this.F({[In]:i}),e&&this.reloadFeatureFlags()}resetGroupPropertiesForFlags(t){if(t){var e=this.Oa(In)||{};this.F({[In]:I({},e,{[t]:{}})})}else this.q(In)}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}}},tv={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===Pi||this.Ya===Cr?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=gu,this.Xa=void 0,this.eo=!1,this.io=(()=>{var e;if(P==null||!P.visibilityState||P.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;P?.visibilityState==="visible"&&(this.io=!0,(e=this.Ja)==null||e.setDocumentWasEverVisible==null||e.setDocumentWasEverVisible(!0))},this._instance=t,!this._instance.sessionManager)throw Bt.error("started without valid sessionManager"),new Error(Ra+" started without valid sessionManager. This is a bug.");if(this.Ne.cookieless_mode===Wt)throw new Error(Ra+' cannot be used with cookieless_mode="always"');P!=null&&P.addEventListener&&ve(P,"visibilitychange",this.Ie)}initialize(){this.startIfEnabledOrStop()}dispose(){this.eo=!0,P==null||P.removeEventListener==null||P.removeEventListener("visibilitychange",this.Ie),this.stopRecording()}get ro(){var t,e=!((t=this._instance.get_property(An))==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),Bt.info("starting")):(this.Ya=gu,this.stopRecording())}}no(t){var e,n,i;this.ro&&(this.Ya!==Pi&&this.Ya!==Cr&&(this.Ya=mu),B!=null&&(e=B.__PosthogExtensions__)!=null&&(e=e.rrweb)!=null&&e.record&&(n=B.__PosthogExtensions__)!=null&&n.initSessionRecording?this.so(t):(i=B.__PosthogExtensions__)==null||i.loadExternalDependency==null||i.loadExternalDependency(this._instance,this.ao,(r=>{if(r)return Bt.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(fl),(e=this.Mr)==null||e.unregister(nf)}uo(t,e){if(W(t))return null;var n,i=ke(t)?t:parseFloat(t);return typeof(n=i)!="number"||!Number.isFinite(n)||0>n||n>1?(Bt.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;W(u)&&this.lo();var c=o?.minimumDurationMilliseconds;i.register({[An]:I({cache_timestamp:Date.now(),enabled:!!o},o,{networkPayloadCapture:I({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===Pi&&(this.Ya=Cr,Bt.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):Bt.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(An);return(n==null||(e=n.scriptConfig)==null?void 0:e.script)||"lazy-recorder"}do(){var t,e=this._instance.get_property(An);if(!e)return!1;try{t=typeof e=="object"?e:JSON.parse(e)}catch(n){return Bt.warn("persisted remote config for session recording is invalid and will be ignored",n),!1}return!W(t.cache_timestamp)&&36e5>=Date.now()-t.cache_timestamp}so(t){var e,n,i;if(!this.eo){if((e=B.__PosthogExtensions__)==null||!e.initSessionRecording)return Bt.warn("Called on script loaded before session recording is available. This can be caused by adblockers."),void this._instance.register_for_session({[df]:!0});var r;if(this.Ja||(this.Ja=(r=B.__PosthogExtensions__)==null?void 0:r.initSessionRecording(this._instance,this.io),this.Ja._forceAllowLocalhostNetworkCapture=this._forceAllowLocalhostNetworkCapture),!this.do())return this.Ya===Cr||this.Ya===Pi?void 0:(this.Ya=Pi,Bt.info("persisted remote config is stale, requesting fresh config before starting"),void new Nf(this._instance).load());this.Ya=mu,(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({[sf]:!0}),(t=this.Ja)==null||t.overrideLinkedFlag()}overrideSampling(){var t,e;this.Ja||(e=this.Mr)==null||e.register({[rf]:!0}),(t=this.Ja)==null||t.overrideSampling()}overrideTrigger(t){var e,n;this.Ja||(n=this.Mr)==null||n.register({[t==="url"?of:af]:!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))}}},nv={autocapture:class{constructor(t){this.vo=!1,this.co=null,this.fo=!1,this.po=!1,this.instance=t,this.rageclicks=new fu(t.config.rageclick),this.mo=null}initialize(){this.startIfEnabled()}get Ne(){var t,e,n=he(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&&P){var t=n=>{n=n||w?.event;try{this.bo(n)}catch(i){jo.error("Failed to capture event",i)}};if(ve(P,"submit",t,{capture:!0}),ve(P,"change",t,{capture:!0}),ve(P,"click",t,{capture:!0}),this.Ne.capture_copied_text){var e=n=>{n=n||w?.event;try{this.bo(n,Do)}catch(i){jo.error("Failed to capture copy/cut event",i)}};ve(P,"copy",e,{capture:!0}),ve(P,"cut",e,{capture:!0})}}}else jo.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;mt(n)&&(this.instance.persistence&&this.instance.persistence.register({[oa]: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=P?.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[oa],i=this.co,r=this.instance.Qi()&&!this.fo;if(Je(i)&&!mt(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=Co(t);mf(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())&&Hc(i,this.instance.config.rageclick)&&this.bo(t,"$rageclick");var r=e===Do;if(i&&(function(d,f,h,p,g,m){var v;if(!w||vl(d)||h!=null&&h.url_allowlist&&!Dc(h.url_allowlist,m)||h!=null&&h.url_ignorelist&&Dc(h.url_ignorelist,m))return!1;if(h!=null&&h.dom_event_allowlist){var E=h.dom_event_allowlist;if(E&&!E.some((x=>f.type===x)))return!1}var S=Ef(d,p),_=S.parentIsUsefulElement,b=S.targetElementList;if(!(function(x,F){var $=F?.element_allowlist;if(C($))return!0;var O,L=function(K){if($.some((V=>K.tagName.toLowerCase()===V)))return{v:!0}};for(var N of x)if(O=L(N))return O.v;return!1})(b,h)||!Ea(b,h?.css_selector_allowlist)||Ea(b,(v=h?.css_selector_ignorelist)!==null&&v!==void 0?v:Qg))return!1;try{var k=w.getComputedStyle(d);if(k&&k.getPropertyValue("cursor")==="pointer"&&f.type==="click")return!0}catch{}var T=d.tagName.toLowerCase();switch(T){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&&(ml.indexOf(T)>-1||d.getAttribute("contenteditable")==="true")}})(i,t,this.Ne,r,r?["copy","cut"]:void 0,this.instance)){var s=qm(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===Do){var l,u=yf(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 je(P?.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 hu;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 je(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];je(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 hu}})(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(Vn,{navigation_type:t}),this._o=n}catch(i){A.error("Error capturing "+t+" pageview",i)}}xo(){if(!this.wo){var t=()=>{this.So("popstate")};ve(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[aa]),this.rageclicks=new fu(t.config.rageclick)}initialize(){this.startIfEnabled()}get flushIntervalMilliseconds(){var t=5e3;return he(this.Ne.capture_heatmaps)&&this.Ne.capture_heatmaps.flush_interval_milliseconds&&(t=this.Ne.capture_heatmaps.flush_interval_milliseconds),t}get isEnabled(){return W(this.Ne.capture_heatmaps)?W(this.Ne.enable_heatmaps)?this.Co:this.Ne.enable_heatmaps:this.Ne.capture_heatmaps!==!1}startIfEnabled(){if(this.isEnabled){if(this.vo)return;Gm.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({[aa]:n}),this.Co=n,this.startIfEnabled()}}}getAndClearBuffer(){var t=this.R;return this.R=void 0,t}Io(t){Ho(t.originalEvent)&&this.ke(t.originalEvent,"deadclick")}Ie(){this.Mo&&clearInterval(this.Mo),this.Mo=P?.visibilityState==="visible"?setInterval(this.cr.bind(this),this.flushIntervalMilliseconds):null}To(){w&&P&&(this.Po=this.cr.bind(this),ve(w,as,this.Po),this.Ro=t=>this.ke(t||w?.event),ve(P,"click",this.Ro,{capture:!0}),this.Ao=t=>this.Fo(t||w?.event),ve(P,"mousemove",this.Ao,{capture:!0}),this.Lo=new Yc(this.instance,om,this.Io.bind(this)),this.Lo.startIfEnabledOrStop(),this.Oo=this.Ie.bind(this),ve(P,os,this.Oo),this.vo=!0)}Eo(){var t;w&&P&&(this.Po&&w.removeEventListener(as,this.Po),this.Ro&&P.removeEventListener("click",this.Ro,{capture:!0}),this.Ao&&P.removeEventListener("mousemove",this.Ao,{capture:!0}),this.Oo&&P.removeEventListener(os,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&&hn(u)&&!tt(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=wf(u)}return!1})(Co(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"),!Bc(t.target)&&Ho(t)){var i=this.$o(t,e);(n=this.rageclicks)!=null&&n.isRageClick(t.clientX,t.clientY,new Date().getTime())&&Hc(Co(t),this.instance.config.rageclick)&&this.Vt(I({},i,{type:"rageclick"})),this.Vt(i)}}Fo(t){!Bc(t.target)&&Ho(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?fn(w.location.href):w.location.href,n=this.Ne.custom_personal_data_properties,i=this.Ne.mask_personal_data_properties?[...oi,...n||[]]:[],r=tr(e,i,nr);this.R=this.R||{},this.R[r]||(this.R[r]=[]),this.R[r].push(t)}}cr(){this.R&&!Kt(this.R)&&this.instance.capture("$$heatmap",{$heatmap_data:this.getAndClearBuffer()})}},deadClicksAutocapture:Yc,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",I({$current_url:this.R.url},this.R.metrics.reduce(((n,i)=>I({},n,{["$web_vitals_"+i.name+"_event"]:I({},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},W(n?.name)||W(n?.value))wn.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=ke(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=I({},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 wn.error("Ignoring metric with value >= "+this.Ho,n)}}},this.Uo=()=>{if(!this.vo){var n,i,r,s,o=B.__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 wn.error("web vitals callbacks not loaded - not starting")}},this._instance=t,this.Co=!((e=this._instance.persistence)==null||!e.props[da]),this.startIfEnabled()}get Wo(){return this._instance.config.capture_performance}get allowedMetrics(){var t,e,n=he(this.Wo)?(t=this.Wo)==null?void 0:t.web_vitals_allowed_metrics:void 0;return W(n)?((e=this._instance.persistence)==null?void 0:e.props[fa])||["CLS","FCP","INP","LCP"]:n}get flushToCaptureTimeoutMs(){return(he(this.Wo)?this.Wo.web_vitals_delayed_flush_ms:void 0)||5e3}get useAttribution(){var t=he(this.Wo)?this.Wo.web_vitals_attribution:void 0;return t!=null&&t}get useSoftNavs(){var t=he(this.Wo)?this.Wo.__preview_web_vitals_soft_navs:void 0;return t!=null&&t}get Ho(){var t=he(this.Wo)&&ke(this.Wo.__web_vitals_max_value)?this.Wo.__web_vitals_max_value:pu;return t>0&&6e4>=t?pu:t}get isEnabled(){var t=me?.protocol;if(t!=="http:"&&t!=="https:")return wn.info("Web Vitals are disabled on non-http/https protocols"),!1;var e=he(this.Wo)?this.Wo.web_vitals:mt(this.Wo)?this.Wo:void 0;return mt(e)?e:this.Co}startIfEnabled(){this.isEnabled&&!this.vo&&(wn.info("enabled, starting..."),this.ai(this.Uo))}onRemoteConfig(t){if(t.ok){var e=t.config;if("capturePerformance"in e){var n=he(e.capturePerformance)&&!!e.capturePerformance.web_vitals,i=he(e.capturePerformance)?e.capturePerformance.web_vitals_allowed_metrics:void 0;this._instance.persistence&&(this._instance.persistence.register({[da]:n}),this._instance.persistence.register({[fa]: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=B.__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?wn.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?fn(e):e,i=this._instance.config.custom_personal_data_properties,r=this._instance.config.mask_personal_data_properties?[...oi,...i||[]]:[];return tr(n,r,nr)}wn.error("Could not determine current URL")}}},iv={exceptionObserver:class{constructor(t){var e;this.Uo=()=>{var n;if(w&&this.isEnabled&&(n=B.__PosthogExtensions__)!=null&&n.errorWrappingFunctions){var i=B.__PosthogExtensions__.errorWrappingFunctions.wrapOnError,r=B.__PosthogExtensions__.errorWrappingFunctions.wrapUnhandledRejection,s=B.__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){Ai.error("failed to start",o),this.Qo()}}},this._instance=t,this.Ko=!((e=this._instance.persistence)==null||!e.props[la]),this.Jo=new tg(I({},(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:Ai})),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 he(t)?e=I({},e,t):(C(t)?this.Ko:t)&&(e=I({},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?(Ai.info("enabled"),this.Qo(),this.ai(this.Uo)):this.Qo()}ai(t){var e,n;(e=B.__PosthogExtensions__)!=null&&e.errorWrappingFunctions?t():(n=B.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,"exception-autocapture",(i=>{if(i)return Ai.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({[la]: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)?Ai.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 _g([new kg,new Lg,new Ag,new Cg,new $g,new Tg,new Fg,new Mg],(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=Mc.test(f)?f.replace(Mc,"$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 I({},E,{filename:E.filename||(S=v,S[S.length-1]||{}).filename,function:E.function||ri});var S}))})(u)}})("web:javascript",Eg,Ig)),this._instance=t,this.Xo=(e=(n=this._instance.persistence)==null?void 0:n.get_property(ca))!==null&&e!==void 0?e:[],this.el=ts(this.il()),this.rl=new Og(this.el)}onConfigChange(){this.el=ts(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({[ca]:this.Xo,[ua]:o})}}}get nl(){var t,e=!!this._instance.get_property(ua),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(!X(t)||t.trim().length===0)return void St.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)=>Ng.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&&St.warn("Ignoring reserved exception step fields",{droppedKeys:r}),this.rl.add(I({[Qr]:t,[es]:new Date().toISOString()},i))}catch(s){St.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 St.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 St.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 St.info("Skipping exception capture because it was thrown by the PostHog SDK")}var n=this.el.enabled&&W(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 St.error("Failed to capture exception event. Dropping this exception.",o),void this.rl.clear()}}catch(o){return void St.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:I({},t,{$exception_steps:e})}catch(n){return St.error("Failed to read buffered exception steps. Capturing exception without steps.",n),t}}ll(t){this.el.enabled&&this.rl.add({[Qr]:t,[es]:new Date().toISOString()})}sl(t){return he(t)?I({},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 X(r)&&r.length>0&&n.$exception_types.push(r),X(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=Jf[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 St.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!W(t)&&U(t)}}},rv=I({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({[dl]:!!e.productTours}),!Wo(this._instance))return!this.vl&&W((n=this.Mr)==null?void 0:n.props[Oi])||Ar.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&&Wo(this._instance)&&this.ai((()=>this.fl()))}ai(t){var e,n;(e=B.__PosthogExtensions__)!=null&&e.generateProductTours?t():(n=B.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,"product-tours",(i=>{i?Ar.error("Could not load product tours script",i):t()}))}fl(){var t;!this.vl&&(t=B.__PosthogExtensions__)!=null&&t.generateProductTours&&(this.vl=B.__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[Oi];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(Wo(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||Ar.warn(o):Ar.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({[Oi]:a}),t(a,{isLoaded:!0})}else t([],{isLoaded:!0})}})}else t(this.cl,{isLoaded:!0})}getActiveProductTours(t){W(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(Oi)}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)}}},$s),sv={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=B._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:I({},wd(t,Km),{properties:I({},t.properties,p?{$set:I({},(e=(n=t.properties)==null?void 0:n.$set)!==null&&e!==void 0?e:{},p)}:{},h?{$set_once:I({},(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)||(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,r,s,o,a;if(!this._instance.config.prepare_external_dependency_stylesheet&&!this._instance.config.prepare_external_dependency_script)return()=>{};var l=P?.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=>!Je(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 b=g(S);return S.length&&!b.length?void 0:v.apply(this,b)}))})),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&&(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,r=o=>{e.errored=!o,e.loaded=!0,Et.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){Et.error(vu+t.id,o),r(!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(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 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 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((i=s.siteApps)!=null&&i.length)if(this.isEnabled){var o=function(){var l,u=a.id,c=a.url;B["__$$ph_site_app_"+u]=r._instance,(l=B.__PosthogExtensions__)==null||l.loadSiteApp==null||l.loadSiteApp(r._instance,c,(d=>{if(d)return Et.error(vu+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.')}}}},ov={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=B.__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=B.__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=B.__PosthogExtensions__)!=null&&e.tracingHeadersPatchFns?t():(n=B.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,"tracing-headers",(i=>{if(i)return Vm.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()}}},av=I({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 Q.warn("Remote config unavailable. Not loading surveys.");var e=t.config.surveys;if(W(e))return Q.warn("Flags not loaded yet. Not loading surveys.");var n=U(e);this.Rl=n?e.length>0:e,Q.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)Q.info("Already initializing surveys, skipping...");else if(this.Ne.disable_surveys)Q.info(_u);else if(this.Ne.cookieless_mode&&this._instance.consent.isOptedOut())Q.info("Not loading surveys in cookieless mode without consent.");else{var t=B?.__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(hl);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 Q.error("PostHog Extensions not found.")}}Dl(t,e){this._surveyManager=t(this._instance,e),this._surveyEventReceiver=new Zm(this._instance),Q.info("Surveys loaded successfully"),this.Nl({isLoaded:!0})}$l(t,e){Q.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 Q.info(_u),t([]);var n,i=this._instance.get_property(pa);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?Q.error(a):r.error||Q.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)&&(Xf(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({[pa]:c,[is]: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(is);return ke(t)&&Date.now()-t>3e5}Bl(){return ke(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};eh(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){Q.error("Error in survey callback",n)}}getActiveMatchingSurveys(t,e){if(e===void 0&&(e=!1),!W(this._surveyManager))return this._surveyManager.getActiveMatchingSurveys(t,e);Q.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(W(this._surveyManager))return{eligible:!1,reason:Pr};var e=typeof t=="string"?this.Hl(t):t;return e?this._surveyManager.checkSurveyEligibility(e):{eligible:!1,reason:"Survey not found"}}zl(t){if(W(this._surveyManager))return{eligible:!1,reason:Pr};var e=typeof t=="string"?this.Hl(t):t;return e?this._surveyManager.checkSurveyRenderability(e):{eligible:!1,reason:"Survey not found"}}canRenderSurvey(t){if(W(this._surveyManager))return Q.warn("init was not called"),{visible:!1,disabledReason:Pr};var e=this.zl(t);return{visible:e.eligible,disabledReason:e.reason}}canRenderSurveyAsync(t,e){return W(this._surveyManager)?(Q.warn("init was not called"),Promise.resolve({visible:!1,disabledReason:Pr})):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(W(this._surveyManager))Q.warn("init was not called");else{var r=typeof t=="string"?this.Hl(t):t;if(r!=null&&r.id)if($m.includes(r.type)){var s=P?.querySelector(e);if(s)return(i=r.appearance)!=null&&i.surveyPopupDelaySeconds?(Q.info("Rendering survey "+r.id+" with delay of "+r.appearance.surveyPopupDelaySeconds+" seconds"),void setTimeout((()=>{var o,a;Q.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),Q.info("Survey "+r.id+" rendered")}),1e3*r.appearance.surveyPopupDelaySeconds)):void this._surveyManager.renderSurvey(r,s,n);Q.warn("Survey element not found")}else Q.warn("Surveys of type "+r.type+" cannot be rendered in the app");else Q.warn("Survey not found")}}displaySurvey(t,e){var n;if(W(this._surveyManager))Q.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=I({},i,{appearance:I({},i.appearance,{surveyPopupDelaySeconds:0})})),e.displayType!==xa.Popover&&e.initialResponses&&Q.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 Q.warn("Survey is not eligible to be displayed: ",s.reason)}e.displayType!==xa.Inline?this._surveyManager.handlePopoverSurvey(r,e):this.renderSurvey(r,e.selector,e.properties)}else Q.warn("Survey not found")}}cancelPendingSurvey(t){W(this._surveyManager)?Q.warn("init was not called"):this._surveyManager.cancelSurvey(t)}handlePageUnload(){var t;(t=this._surveyManager)==null||t.handlePageUnload==null||t.handlePageUnload()}}},$s),lv={toolbar:class{constructor(t){this.instance=t}Wl(t){B.ph_toolbar_state=t}Vl(){var t;return(t=B.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),ba(this.instance.config)||!w||!P)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=Xm||ds(t.hash,"__posthog")||ds(t.hash,"state"),s=r?Nc((()=>JSON.parse(atob(decodeURIComponent(r)))))||Nc((()=>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(yu)||"{}")).source="localstorage",delete i.userIntent),!(!i.token||this.instance.config.token!==i.token||(this.loadToolbar(i),0))}catch{return!1}}Zl(t){var e=B.ph_load_toolbar||B.ph_load_editor;!W(e)&&je(e)?e(t,this.instance):wu.warn("No toolbar load function found")}loadToolbar(t){var e=!(P==null||!P.getElementById(gf));if(!w||e)return!1;var n=this.instance.requestRouter.region==="custom"&&this.instance.config.advanced_disable_toolbar_metrics,i=I({token:this.instance.config.token},t,{apiURL:this.instance.requestRouter.endpointFor("ui")},n?{instrument:!1}:{});if(w.localStorage.setItem(yu,JSON.stringify(I({},i,{source:void 0}))),this.Vl()===2)this.Zl(i);else if(this.Vl()===0){var r;this.Wl(1),(r=B.__PosthogExtensions__)==null||r.loadExternalDependency==null||r.loadExternalDependency(this.instance,"toolbar",(s=>{if(s)return wu.error("[Toolbar] Failed to load",s),void this.Wl(0);this.Wl(2),this.Zl(i)})),ve(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)}}},cv=I({experiments:Me},$s),uv={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;W(e)||(mt(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||ba(this._instance.config)||this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut())){var t=B?.__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(hl);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 at.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,at.info("Conversations loaded successfully")}catch(e){this.eu("Error completing conversations initialization",e)}else at.error("Cannot complete initialization: remote config is null")}eu(t,e){at.error(t,e),this._conversationsManager=null,this.Kl=!1,this.Yl=!0}show(){this._conversationsManager?this._conversationsManager.show():at.warn("Conversations not loaded yet.")}hide(){this._conversationsManager&&this._conversationsManager.hide()}isAvailable(){return this.Ql===!0&&!Je(this._conversationsManager)}getUnavailableReason(){return this.isAvailable()?null:this._instance.config.disable_conversations?"disabled_by_config":ba(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?W(this.Jl)||!this.Jl.token?"missing_token":B!=null&&B.__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 se((function*(){return i._conversationsManager?i._conversationsManager.sendMessage(t,e,n):(at.warn(En),null)}))()}getMessages(t,e){var n=this;return se((function*(){return n._conversationsManager?n._conversationsManager.getMessages(t,e):(at.warn(En),null)}))()}markAsRead(t){var e=this;return se((function*(){return e._conversationsManager?e._conversationsManager.markAsRead(t):(at.warn(En),null)}))()}getTickets(t){var e=this;return se((function*(){return e._conversationsManager?e._conversationsManager.getTickets(t):(at.warn(En),null)}))()}requestRestoreLink(t){var e=this;return se((function*(){return e._conversationsManager?e._conversationsManager.requestRestoreLink(t):(at.warn(En),null)}))()}restoreFromToken(t){var e=this;return se((function*(){return e._conversationsManager?e._conversationsManager.restoreFromToken(t):(at.warn(En),null)}))()}restoreFromUrlToken(){var t=this;return se((function*(){return t._conversationsManager?t._conversationsManager.restoreFromUrlToken():(at.warn(En),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()}}},dv={logs:class{constructor(t){var e,n=this;this.iu=!1,this.ru=!1,this.rt=pe("[logs]"),this.nu=I({},this.rt,{error(){for(var i=arguments.length,r=new Array(i),s=0;i>s;s++)r[s]=arguments[s];r.some(Au)||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&&ve(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 gg(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},Cu);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;!W(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){Au(t)||this.rt.error("PostHog logs flush failed:",t)}loadIfEnabled(){if(this.iu&&!this.ru){var t=B?.__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(hl)}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===Ut.LogsQueue?t():void 0,setPersistedProperty(i,r){var s;i===Ut.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(Cf(this.Sa,3))e({kind:"fatal",error:qo(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:qo(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:qo(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=Af(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,Cu,(e=>{this.su=e}))}xu(t,e,n,i,r){if(e.length!==0){var s=e.map((a=>a.record));r([]);var o=Zd(s,Jd(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,W(r)||(e.sessionStartTimestamp=r),W(s)||(e.lastActivityTimestamp=s)}if(B!=null&&(t=B.location)!=null&&t.href&&(e.currentUrl=this._instance.config.disable_capture_url_hashes?fn(B.location.href):B.location.href),this._instance.featureFlags){var o=this._instance.featureFlags.getFlags();o&&o.length>0&&(e.activeFeatureFlags=o)}return e}}},fv={metrics:class{constructor(t){this.rt=pe("[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 mg(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(I({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)}}},hv=I({},$s,tv,nv,iv,rv,sv,av,ov,lv,cv,uv,dv,fv);Xe.__defaultExtensionClasses=I({},hv);(function(){ne.SDK_DIST_CHANNEL="npm";var t=Vi[Gn]=new Xe;return(function(){function e(){e.done||(e.done=!0,nh=!1,ie(Vi,(function(n){n._dom_loaded()})))}P!=null&&P.addEventListener?P.readyState==="complete"?e():ve(P,"DOMContentLoaded",e,{capture:!1}):w&&A.error("Browser doesn't support `document.addEventListener` so PostHog couldn't be initialized")})(),t})();const pv=["a[href]","button:not([disabled])","input:not([disabled]):not([type='hidden'])","select:not([disabled])","textarea:not([disabled])","[tabindex]:not([tabindex='-1'])"].join(",");let Ke=null,ms=null,rh="";const Ta=new Map;function sh(t){return[...t.querySelectorAll(pv)].filter(e=>!e.hidden&&e.getAttribute("aria-hidden")!=="true"&&e.getClientRects().length>0)}function gv(t){for(const e of document.body.children)e===t||e.tagName==="SCRIPT"||(Ta.set(e,{inert:e.inert,ariaHidden:e.getAttribute("aria-hidden")}),e.inert=!0,e.setAttribute("aria-hidden","true"))}function mv(){for(const[t,e]of Ta)t.inert=e.inert,e.ariaHidden===null?t.removeAttribute("aria-hidden"):t.setAttribute("aria-hidden",e.ariaHidden);Ta.clear()}function oh(t){return t?.dataset.modalDismissible!=="false"&&t?.getAttribute("aria-busy")!=="true"}function We(t,e={}){const n=typeof t=="string"?document.getElementById(t):t;if(!n)return!1;const i=Ke&&Ke!==n?Ke:null,r=ms;if(i&&ze(i,{restoreFocus:!1,force:!0}),Ke!==n){let a=e.trigger||document.activeElement;a&&(i?.contains(a)||n.contains(a))&&(a=r),ms=a,rh=document.body.style.overflow,gv(n),document.body.style.overflow="hidden"}Ke=n,n.classList.add("open"),n.setAttribute("aria-hidden","false");const s=n.querySelector(".modal-content");s&&(s.style.transform="scale(1) translateY(0)");const o=()=>{if(Ke!==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(o),setTimeout(o,260),!0}function ze(t,e={}){const n=typeof t=="string"?document.getElementById(t):t;if(!n||!e.force&&!oh(n))return!1;if(n.classList.remove("open"),n.setAttribute("aria-hidden","true"),n!==Ke)return!0;mv(),document.body.style.overflow=rh,Ke=null;const i=ms;return ms=null,e.restoreFocus!==!1&&i?.isConnected&&i.focus({preventScroll:!0}),!0}function vv(){return!!Ke}function Pu(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 _v(t){if(!oh(t))return;const e=t.dataset.modalCloseHandler;e&&typeof window[e]=="function"?window[e]():ze(t)}document.addEventListener("keydown",t=>{if(!Ke)return;if(t.key==="Escape"){t.preventDefault(),t.stopImmediatePropagation(),_v(Ke);return}if(t.key!=="Tab"){t.stopPropagation();return}const e=sh(Ke);if(!e.length){t.preventDefault(),(Ke.querySelector(".modal-content")||Ke).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 yv(){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 bl=Object.freeze({free:"Free",professional:"Pro",power:"Power"}),wv=Object.freeze({free:2,professional:50,power:2e3}),bv="(contact us)",Ev=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 ${bv}`])}),ah="CodeFile",lh="GeneratedCode",Sv={CustomAction:"A",CustomWidget:"W",CustomFunction:"F",CustomClass:"C",CodeFile:"C"};function ln(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function $a(t){return String(t||"").trim().replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function xv(t={},e=0){const n=$a(t.artifactType||t.type||ah),i=$a(t.artifactName||t.name||t.fileName||`${lh}-${e+1}`);return`${n||"artifact"}-${i||e+1}`}function ch(t={},e=0){const n=ln(t),i=n.artifactType||n.type||ah,r=n.artifactName||n.name||lh;let s=n.fileName||r;return s.endsWith(".dart")||(s+=".dart"),{id:$a(n.id)||xv({...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:uh(n.dependencies),imports:Array.isArray(n.imports)?n.imports:[],publicApi:Array.isArray(n.publicApi)?n.publicApi:[],relationships:dh(n.relationships),deployStatus:n.deployStatus||"pending",review:n.review||null,metadata:ln(n.metadata),codeType:n.codeType||Sv[i]||"O"}}function uh(t){return t?Array.isArray(t)?t.map(e=>{if(typeof e=="string")return{name:e,version:null,inferred:!1};const n=ln(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(ln(t)).map(([e,n])=>({name:e,version:n||null,inferred:!1})):[]}function dh(t){return t?(Array.isArray(t)?t:[t]).map(e=>{const n=ln(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 ir(t,e={}){const n=[],i=typeof t=="string"?Ma(t):t,s=ln(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)=>ch(d,f)),l=new Map(o.map((d,f)=>[ln(d).id,a[f]?.id]).filter(([d,f])=>d&&f)),u=d=>l.get(d)||d,c=dh(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:uh(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:ln(s.metadata)}}function li(t){return ir(t).artifacts[0]||ch()}function Zt(t){if(typeof t!="string")return t??"";const e=t.trim();if(!e)return"";try{return JSON.parse(e)}catch{return t}}function ci(t){return JSON.stringify(t,null,2)}function Iv(t){return ci({task:"architect",userRequest:String(t??"")})}function kv(t){const e=Zt(t);return e&&typeof e=="object"&&typeof e.task=="string"?ci(e):ci({task:"generate_bundle",bundleSpec:e})}function Cv(t){return ci({task:"review_bundle",generatedBundle:Zt(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=Zt(e)),n}function Av({bundleSpec:t,artifactBundle:e,bundleReview:n,artifactId:i,userFeedback:r}){return ci({task:"regenerate_artifact",artifactId:i,bundleSpec:Zt(t),artifactBundle:Zt(e),bundleReview:Zt(n),userFeedback:String(r)})}function fh({bundleSpec:t,artifactBundle:e,bundleReview:n,userFeedback:i}){return ci({task:"regenerate_bundle",bundleSpec:Zt(t),artifactBundle:Zt(e),bundleReview:Zt(n),userFeedback:String(i??"")})}const Fu={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"},Pv=["sanitizationResult","modelArmor","modelArmorResult","data","result","error"];function nt(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function Fv(t){return nt(t)?typeof t.filterMatchState=="string"||typeof t.invocationResult=="string"||Array.isArray(t.matchedFilters)||nt(t.filterSummary)||nt(t.filterResults):!1}function hh(t,e=0){if(!nt(t)||e>3)return null;if(Fv(t))return t;for(const n of Pv){const i=t[n];if(nt(i)){const r=hh(i,e+1);if(r)return r}}return null}function vs(t){return Array.isArray(t)?t.some(vs):nt(t)?t.matched===!0||t.matchState==="MATCH_FOUND"?!0:Object.values(t).some(vs):!1}function La(t){return Array.isArray(t)?t.some(La):nt(t)?typeof t.executionState=="string"&&t.executionState!=="EXECUTION_SUCCESS"?!0:Object.values(t).some(La):!1}function ph(t){return{csamFilterFilterResult:"csam",maliciousUriFilterResult:"malicious_uris",piAndJailbreakFilterResult:"pi_and_jailbreak",raiFilterResult:"rai",sdpFilterResult:"sdp",virusScanFilterResult:"virus_scan"}[t]||t}function Rv(t,e){if(nt(t))for(const[n,i]of Object.entries(t)){if(!nt(i))continue;const r=nt(i.categories)?i.categories:{},s=Object.entries(r).filter(([,o])=>nt(o)&&o.matched===!0).map(([o])=>o);s.length>0?s.forEach(o=>e.add(o)):i.matched===!0&&e.add(ph(n))}}function Tv(t,e){if(!t)return;const n=Array.isArray(t)?t.flatMap(i=>nt(i)?Object.entries(i):[]):Object.entries(t);for(const[i,r]of n){if(!vs(r))continue;const s=ph(i),o=r?.raiFilterResult?.raiFilterTypeResults||(s==="rai"?r?.raiFilterTypeResults:null),a=nt(o)?Object.entries(o).filter(([,l])=>vs(l)).map(([l])=>l):[];a.length>0?a.forEach(l=>e.add(l)):e.add(s)}}function $v(t){return Fu[t]?Fu[t]:String(t).replace(/([a-z])([A-Z])/g,"$1 $2").replace(/_/g," ").toLowerCase()}function Ru(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 Mv(t){const e=hh(t);if(!e)return null;const n=new Set(Array.isArray(e.matchedFilters)?e.matchedFilters:[]);Rv(e.filterSummary,n),Tv(e.filterResults,n);const i=e.blocked===!0||e.filterMatchState==="MATCH_FOUND"||n.size>0,r=e.invocationResult||null,s=La(e.filterSummary||e.filterResults);return!i&&!s&&!["PARTIAL","FAILURE"].includes(r)?null:{kind:i?"blocked":"unavailable",invocationResult:r,matchedFilters:[...n]}}function Lv(t,e){const n=Mv(t);if(!n)return null;const i=[...new Set(n.matchedFilters.map($v))],r=n.kind==="blocked",s=new Error(r?`Safety screening blocked this pipeline step for ${Ru(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 ${Ru(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 Nv(t){return String(t||"").replace(/\/\*[\s\S]*?\*\//g,"").replace(/\/\/[^\n]*/g,"")}function Tu(t){const e=/^(import|export|part|library|class|enum|extension|typedef|mixin|abstract|const|final|var|late)\b/,n=[];for(const i of Nv(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 Sl(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 $u(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 Ov(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=Sl(o,a.type),u={old_identifier_name:l,new_identifier_name:l,type:a.type,is_deleted:!1,current_checksum:await $u(a.content)},c=e.get(a.path);if(c!==void 0&&(u.original_checksum=await $u(c)),n[o]=u,a.type==="F"){const d=Tu(a.content);(d.length>0?d:[a.functionName].filter(Boolean)).forEach(h=>i.add(h))}}const r=new Set(Tu(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 Bv=new Set(["CustomWidget","CustomAction","CustomFunction","CustomClass","CodeFile"]),Mu={CustomWidget:"custom_code/widgets/",CustomAction:"custom_code/actions/",CustomFunction:"flutter_flow/custom_functions.dart",CustomClass:"custom_code/",CodeFile:"custom_code/"},Dv=new Set(["void","dynamic","String","int","double","num","bool","Color","DateTime","DateTimeRange","LatLng","FFPlace","FFUploadedFile","DocumentReference","List"]),jv=["Struct","Record"],Uv=[{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=>Vo(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; } +(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,Ne=typeof globalThis<"u"?globalThis:w,He=Ne?.navigator,P=Ne?.document,me=Ne?.location,il=Ne?.fetch,Jo=Ne!=null&&Ne.XMLHttpRequest&&"withCredentials"in new Ne.XMLHttpRequest?Ne.XMLHttpRequest:void 0,_c=Ne?.AbortController,Yp=Ne?.CompressionStream,Ge=He?.userAgent;function wd(){return!(!w||w.navigator.onLine===!1)}var wi=typeof globalThis<"u"?globalThis:w;wi&&typeof self>"u"&&(wi.self=wi),wi&&typeof File>"u"&&(wi.File=function(){});var B=w??{},ne={DEBUG:!1,LIB_VERSION:"0.5.0",LIB_NAME:"browser-common"};function yc(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 se(t){return function(){var e=this,n=arguments;return new Promise((function(i,r){var s=t.apply(e,n);function o(l){yc(s,i,r,o,a,"next",l)}function a(l){yc(s,i,r,o,a,"throw",l)}o(void 0)}))}}function I(){return I=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},I.apply(null,arguments)}function bd(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 wc=t=>{if(typeof t!="string")return t;try{return JSON.parse(t)}catch{return t}};function bc(t){return typeof t=="string"||t}function Ec(t){return typeof t=="string"?t:void 0}var bi,Jp=["$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"],Ut=(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})({}),Sc=(function(t){return t.GZipJS="gzip-js",t.Base64="base64",t})({}),Zp=["$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"],Ed="NativeGzipValidationError",Zo=t=>t.length>=2&&t[0]===31&&t[1]===139,xc=(t,e)=>t===Sc.GZipJS||e===Sc.GZipJS||e==="gzip",Ic=t=>!(!t||typeof t!="object")&&("name"in t?String(t.name):"")==="NotReadableError",wr=t=>{var e=new Error("Native gzip produced invalid output: "+t);throw e.name=Ed,e},Qp=(function(){var t=se((function*(e,n){18>e.size&&wr("too-short");var i=new Uint8Array(yield e.slice(0,10).arrayBuffer());Zo(i)&&i[2]===8||wr("invalid-header");var r=new DataView(yield e.slice(e.size-8).arrayBuffer());r.getUint32(0,!0)!==(o=>{for(var a=(()=>{if(bi)return bi;bi=[];for(var c=0;256>c;c++){for(var d=c,f=0;8>f;f++)d=1&d?3988292384^d>>>1:d>>>1;bi[c]=d>>>0}return bi})(),l=4294967295,u=0;o.length>u;u++)l=a[255&(l^o[u])]^l>>>8;return(4294967295^l)>>>0})(n)&&wr("invalid-crc");var s=n.length>>>0;r.getUint32(4,!0)!==s&&wr("invalid-size")}));return function(e,n){return t.apply(this,arguments)}})();function Xo(){return Xo=se((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=se((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 Qp(l,i),l}catch(u){if(n!=null&&n.rethrow)throw u;return e&&console.error("Failed to gzip compress data",u),null}})),Xo.apply(this,arguments)}var eg=["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"],kc=function(t,e){if(e===void 0&&(e=[]),!t)return!1;var n=t.toLowerCase();return eg.concat(e).some((i=>{var r=i.toLowerCase();return n.indexOf(r)!==-1}))};function j(t,e){return t.indexOf(e)!==-1}var Ts=function(t){return t.trim()},Qo=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 xd=Object.prototype,Id=xd.hasOwnProperty,$s=xd.toString,U=Array.isArray||function(t){return $s.call(t)==="[object Array]"},je=t=>typeof t=="function",he=t=>t===Object(t)&&!U(t),Kt=t=>{if(he(t)){for(var e in t)if(Id.call(t,e))return!1;return!0}return!1},C=t=>t===void 0,X=t=>$s.call(t)=="[object String]",ea=t=>X(t)&&t.trim().length===0,Je=t=>t===null,W=t=>C(t)||Je(t),ke=t=>$s.call(t)=="[object Number]"&&t==t,Dt=t=>ke(t)&&t>0,mt=t=>$s.call(t)==="[object Boolean]",tg=t=>t instanceof FormData,ng=t=>j(Zp,t),ig=t=>j(Xp,t);function kd(t){return t===null||typeof t!="object"}function Yr(t,e){return{}.toString.call(t)==="[object "+e+"]"}function rl(t){return typeof Event<"u"&&Cd(t,Event)}function Cd(t,e){try{return t instanceof e}catch{return!1}}var rg=[!0,"true",1,"1","yes"],vo=t=>j(rg,t),sg=[!1,"false",0,"0","no"];function At(t,e,n,i,r){return e>n&&(i.warn("min cannot be greater than max."),e=n),ke(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),At(r||n,e,n,i))}class og{constructor(e){this.tt={},this.et=e.et,this.it=At(e.bucketSize,0,100,e.rt),this.nt=At(e.refillRate,0,this.it,e.rt),this.st=At(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 st="Mobile",Jr="iOS",Yt="Android",ii="Tablet",Ad=Yt+" "+ii,Pd="iPad",Fd="Apple",Rd=Fd+" Watch",Ui="Safari",ri="BlackBerry",Td="Samsung",$d=Td+"Browser",Md=Td+" Internet",Fn="Chrome",ag=Fn+" OS",Ld=Fn+" "+Jr,sl="Internet Explorer",Nd=sl+" "+st,ol="Opera",lg=ol+" Mini",al="Edge",Od="Microsoft "+al,Xn="Firefox",Bd=Xn+" "+Jr,Zi="Nintendo",Xi="PlayStation",Qn="Xbox",Dd=Yt+" "+st,jd=st+" "+Ui,Ti="Windows",ta=Ti+" Phone",Cc="Nokia",na="Ouya",Ud="Generic",cg=Ud+" "+st.toLowerCase(),Hd=Ud+" "+ii.toLowerCase(),ia="Konqueror",Wd="Oculus Browser",Zr="Vivaldi",qd="Yandex",Xr="Whale",ra="DuckDuckGo",zd="Pale Moon",Qr="Waterfox",Hi="Brave",Vd="Google Search App",we="(\\d+(\\.\\d+)?)",_o=new RegExp("Version/"+we),ug=new RegExp(Qn,"i"),dg=new RegExp(Xi+" \\w+","i"),fg=new RegExp(Zi+" \\w+","i"),ll=new RegExp(ri+"|PlayBook|BB10","i"),hg={"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"},Gd=function(t,e,n,i){e=e||"";var r=(function(s){return s!=null&&s.brave?Hi:null})(n);return r||(i!=null&&i.detectGoogleSearchApp&&j(t,"GSA/")?Vd:j(t," OPR/")&&j(t,"Mini")?lg:j(t," OPR/")?ol:ll.test(t)?ri:j(t,"IE"+st)||j(t,"WPDesktop")?Nd:j(t,"OculusBrowser")?Wd:j(t,$d)?Md:j(t,al)||j(t,"Edg/")?Od:j(t,Zr+"/")?Zr:j(t,"YaBrowser/")?qd:j(t,Xr+"/")?Xr:j(t,ra+"/")||j(t,"Ddg/")?ra:j(t,"FBIOS")?"Facebook "+st:j(t,"UCWEB")||j(t,"UCBrowser")?"UC Browser":j(t,"CriOS")?Ld:j(t,"CrMo")||j(t,Fn)?Fn:j(t,Yt)&&j(t,Ui)?Dd:j(t,"FxiOS")?Bd:j(t.toLowerCase(),ia.toLowerCase())?ia:j(t,Hi+"/")?Hi:((s,o)=>o&&j(o,Fd)||(function(a){return j(a,Ui)&&!j(a,Fn)&&!j(a,Yt)})(s))(t,e)?j(t,st)?jd:Ui:j(t,"PaleMoon/")?zd:j(t,Qr+"/")?Qr:j(t,Xn)?Xn:j(t,"MSIE")||j(t,"Trident/")?sl:j(t,"Gecko")?Xn:"")},pg={[Nd]:[new RegExp("rv:"+we)],[Od]:[new RegExp(al+"?\\/"+we)],[Fn]:[new RegExp("("+Fn+"|CrMo)\\/"+we)],[Ld]:[new RegExp("CriOS\\/"+we)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+we)],[Ui]:[_o],[jd]:[_o],[ol]:[new RegExp("(Opera|OPR)\\/"+we)],[Xn]:[new RegExp(Xn+"\\/"+we)],[Bd]:[new RegExp("FxiOS\\/"+we)],[ia]:[new RegExp("Konqueror[:/]?"+we,"i")],[ri]:[new RegExp(ri+" "+we),_o],[Dd]:[new RegExp("android\\s"+we,"i")],[Md]:[new RegExp($d+"\\/"+we)],[Wd]:[new RegExp("OculusBrowser\\/"+we)],[Zr]:[new RegExp(Zr+"\\/"+we)],[qd]:[new RegExp("YaBrowser\\/"+we)],[Xr]:[new RegExp(Xr+"\\/"+we)],[Hi]:[new RegExp(Hi+"\\/"+we)],[ra]:[new RegExp("(DuckDuckGo|Ddg)\\/"+we)],[zd]:[new RegExp("PaleMoon\\/"+we)],[Qr]:[new RegExp(Qr+"\\/"+we)],[Vd]:[new RegExp("GSA\\/"+we)],[sl]:[new RegExp("(rv:|MSIE )"+we)],Mozilla:[new RegExp("rv:"+we)]},gg=function(t,e,n,i){var r=Gd(t,e,n,i),s=pg[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},Ac=[[new RegExp(Qn+"; "+Qn+" (.*?)[);]","i"),t=>[Qn,t&&t[1]||""]],[new RegExp(Zi,"i"),[Zi,""]],[new RegExp(Xi,"i"),[Xi,""]],[ll,[ri,""]],[new RegExp(Ti,"i"),(t,e)=>{if(/Phone/.test(e)||/WPDesktop/.test(e))return[ta,""];if(new RegExp(st).test(e)&&!/IEMobile\b/.test(e))return[Ti+" "+st,""];var n=/Windows NT ([0-9.]+)/i.exec(e);if(n&&n[1]){var i=hg[n[1]]||"";return/arm/i.test(e)&&(i="RT"),[Ti,i]}return[Ti,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,t=>t&&t[3]?[Jr,[t[3],t[4],t[5]||"0"].join(".")]:[Jr,""]],[/(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("("+Yt+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+Yt+")","i"),t=>t&&t[2]?[Yt,[t[2],t[3],t[4]||"0"].join(".")]:[Yt,""]],[/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/,[ag,""]],[/Linux|debian/i,["Linux",""]]],Pc=function(t){return fg.test(t)?Zi:dg.test(t)?Xi:ug.test(t)?Qn:new RegExp(na,"i").test(t)?na:new RegExp("("+ta+"|WPDesktop)","i").test(t)?ta:/iPad/.test(t)?Pd:/iPod/.test(t)?"iPod Touch":/iPhone/.test(t)?"iPhone":/(watch)(?: ?os[,/]|\d,\d\/)[\d.]+/i.test(t)?Rd:ll.test(t)?ri:/(kobo)\s(ereader|touch)/i.test(t)?"Kobo":new RegExp(Cc,"i").test(t)?Cc:/(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(st).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)?Yt:Ad:new RegExp("(pda|"+st+")","i").test(t)?cg:new RegExp(ii,"i").test(t)&&!new RegExp(ii+" pc","i").test(t)?Hd:""},mg=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Fc(t,e){return typeof(n=t)=="string"&&mg.test(n)?t:e();var n}function fn(t){return t&&t.split("#")[0]}function cl(t,e){var n=setTimeout(t,e);return n?.unref&&n?.unref(),n}function Rc(t,e,n){return Kd.apply(this,arguments)}function Kd(){return(Kd=se((function*(t,e,n){var i;try{return yield Promise.race([t,new Promise(((r,s)=>{i=cl((()=>{try{n?.(),r()}catch(o){s(o)}}),e)}))])}finally{clearTimeout(i)}}))).apply(this,arguments)}var vg=t=>t instanceof Error,Yd={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}},_g=Yd.info;function Jd(t){if(mt(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=>Jd(e)))}};try{return{stringValue:JSON.stringify(t)}}catch{return{stringValue:String(t)}}}function es(t){var e=[];for(var n in t){var i=t[n];Je(i)||C(i)||e.push({key:n,value:Jd(i)})}return e}function yg(t,e){var n=Yd[t.level||"info"]||_g,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),W(e.sessionStartTimestamp)||(o.sessionStartTimestamp=String(e.sessionStartTimestamp)),W(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=I({},o,t.attributes||{}),l={timeUnixNano:s,observedTimeUnixNano:s,severityNumber:r,severityText:i,body:{stringValue:t.body},attributes:es(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 Zd(t,e,n){return I({},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 Xd(t,e,n,i){return{resourceLogs:[{resource:{attributes:es(e)},scopeLogs:[{scope:{name:n,version:i},logRecords:t}]}]}}let wg=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:yg(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 se((function*(){if(!t._instance.isDisabled)return t.ct||(t.ct=t.Ft().finally((()=>{t.ct=null}))),t.ct}))()}Ft(){var t=this;return se((function*(){var e;t.Et();var n=(e=t._instance.getPersistedProperty(Ut.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=Xd(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(Ut.LogsQueue))!==null&&o!==void 0?o:[],r+=l.length,c.kind==="fatal"))throw c.error}}))()}Dt(t){var e=this;return se((function*(){var n,i=Math.max(0,t-e.ft),r=(n=e._instance.getPersistedProperty(Ut.LogsQueue))!==null&&n!==void 0?n:[];e._instance.setPersistedProperty(Ut.LogsQueue,r.slice(i)),yield e.dt()}))()}Lt(){return Zd(this.Ne,this._instance.getLibraryId(),this._instance.getLibraryVersion())}At(t){var e;if(!this._instance.optedOut){var n=(e=this._instance.getPersistedProperty(Ut.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(Ut.LogsQueue,n),this.kt>n.length?this.$t():this.It()}}$t(t){t===void 0&&(t=this.St),this.Nt||(this.Nt=cl((()=>{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(Ut.LogsQueue);return!!t&&t.length>0}shutdown(t){var e=this;return se((function*(){e.Et();var n=e.flush().catch((()=>{}));t!==void 0?yield Rc(n,t):yield n}))()}flushWithTimeout(t){var e=this;return se((function*(){var n=e.flush();yield Rc(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 yo=[0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4];function Tc(t){return String(t)+"000000"}function $c(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 bg=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=se((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?I({},e.attributes):void 0,i=$c(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(yo.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,yo)]+=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=cl((()=>{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 se((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 I({},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:es(n)},scopeMetrics:[{scope:{name:i,version:r},metrics:e}]}]};var e,n,i,r}Xt(t){var e=Tc(Date.now()),n=new Map;for(var i of t.values()){var r,s=$c(i.type,i.name,i.unit,void 0),o=n.get(s);o||(o=I({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=es((r=i.attributes)!==null&&r!==void 0?r:{}),l=Tc(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:yo})}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 br,Mc,wo;function Eg(t){var e=globalThis._posthogChunkIds;if(e){var n=Object.keys(e);return wo&&n.length===Mc||(Mc=n.length,wo=n.reduce(((i,r)=>{br||(br={});var s=br[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,br[r]=[u,c];break}}return i}),{})),wo}}class Sg{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 se((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)),I({},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 se((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,I({},n,{handled:!0}))),a}buildParsingContext(e){var n;return{chunkIdMap:Eg(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 I({},n,{syntheticException:i==0?n.syntheticException:void 0,mechanism:e,apply:s=>r(s,i),next:s=>r(s,i+1)})}}var si="?";function sa(t,e,n,i,r){var s={platform:t,filename:e,function:n===""?si:n,in_app:!0};return C(i)||(s.lineno=i),C(r)||(s.colno=r),s}var Qd=(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]:si,n?"safari-extension:"+e:"safari-web-extension:"+e]:[t,e]},xg=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,Ig=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,kg=/\((\S*)(?::(\d+))(?::(\d+))\)/,Cg=(t,e)=>{var n=xg.exec(t);if(n)return sa(e,n[1],si,+n[2],+n[3]);var i=Ig.exec(t);if(i){if(i[2]&&i[2].indexOf("eval")===0){var r=kg.exec(i[2]);r&&(i[2]=r[1],i[3]=r[2],i[4]=r[3])}var s=Qd(i[1]||si,i[2]);return sa(e,s[1],s[0],i[3]?+i[3]:void 0,i[4]?+i[4]:void 0)}},Ag=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,Pg=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,Fg=(t,e)=>{var n=Ag.exec(t);if(n){if(n[3]&&n[3].indexOf(" > eval")>-1){var i=Pg.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]||si,o=Qd(s,r);return sa(e,r=o[1],s=o[0],n[4]?+n[4]:void 0,n[5]?+n[5]:void 0)}},Lc=/\(error: (.*)\)/;class Rg{match(e){return this.isDOMException(e)||this.isDOMError(e)}coerce(e,n){var i=X(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 Yr(e,"DOMException")}isDOMError(e){return Yr(e,"DOMError")}}class Tg{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 $g{constructor(){}match(e){return!!Yr(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 I({},r,{stack:(i=this.pe(e))!==null&&i!==void 0?i:r.stack,synthetic:!0})}fe(e){return X(e.message)&&e.message.length>0}pe(e){var n=e;if(X(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 Mg=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;class Lg{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(Mg);return r&&(n=r[1],i=r[2]),[n,i]}}var Ng=["fatal","error","warning","log","info","debug"];function ef(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 Og{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 rl(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: "+ef(e)}isSeverityLevel(e){return X(e)&&!ea(e)&&Ng.indexOf(e)>=0}getStack(e){try{return X(e.stacktrace)&&e.stacktrace.length>0?e.stacktrace:X(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(vg(i))return i}}getObjectClassName(e){try{var n=Object.getPrototypeOf(e);return n?n.constructor.name:void 0}catch{return}}}class Bg{match(e){return rl(e)}coerce(e,n){var i,r=e.constructor.name;return{type:r,value:r+" captured as exception with keys: "+ef(e),stack:(i=n.syntheticException)==null?void 0:i.stack,synthetic:!0}}}class Dg{match(e){return kd(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 jg{match(e){return Yr(e,"PromiseRejectionEvent")||this.isCustomEventWrappingRejection(e)}isCustomEventWrappingRejection(e){if(!rl(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 kd(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 ts="$message",ns="$timestamp",Ug=new Set([ts,ns]),bo={enabled:!0,max_bytes:32768};function is(t){var e;return t?{enabled:(e=t.enabled)!==null&&e!==void 0?e:bo.enabled,max_bytes:Wg(t.max_bytes,bo.max_bytes)}:I({},bo)}class Hg{constructor(e){this.Ke=[],this.Je=0,this.Ne=is(e)}setConfig(e){this.Ne=is(e),this.Xe()}add(e){var n=(function(r){var s;try{s=Sd(r)}catch{return}try{var o=JSON.parse(s);if(!he(o))return;var a=o,l=a[ts],u=a[ns];return!X(l)||l.trim().length===0||!X(u)&&!ke(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 Wg(t,e){if(!ke(t)||t===1/0||t===-1/0)return e;var n=Math.floor(t);return 0>n?e:n}var tf=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)=>tf(t+" "+r,s)};return i},A=tf("[PostHog.js]"),pe=A.createLogger,qg=pe("[ExternalScriptsLoader]"),Eo=(t,e,n)=>{if(t.config.disable_external_dependency_loading)return qg.warn(e+" was requested but loading of external scripts is disabled."),n("Loading of external scripts is disabled");var i=P?.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(!P)return n("document not found");var l=P.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")P.head.appendChild(l);else{var u,c=P.querySelectorAll("body > script");c.length>0?(u=c[0].parentNode)==null||u.insertBefore(l,c[0]):P.body.appendChild(l)}};P!=null&&P.body?a():P?.addEventListener("DOMContentLoaded",a)};B.__PosthogExtensions__=B.__PosthogExtensions__||{},B.__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)}Eo(t,i,n)}else{var o=t.requestRouter.endpointFor("assets","/array/"+t.config.token+"/config.js");Eo(t,o,n)}},B.__PosthogExtensions__.loadSiteApp=(t,e,n)=>{var i=t.requestRouter.endpointFor("api",e);Eo(t,i,n)};ne.DEBUG=!1,ne.LIB_VERSION="1.415.7",ne.LIB_NAME="web";var nf="$people_distinct_id",Qi="$device_id",So="$device_model",$i="__alias",Mi="__timers",oa="$autocapture_disabled_server_side",aa="$heatmaps_enabled_server_side",la="$exception_capture_enabled_server_side",ca="$error_tracking_suppression_rules",ua="$error_tracking_capture_extension_exceptions",da="$web_vitals_enabled_server_side",ul="$dead_clicks_enabled_server_side",dl="$product_tours_enabled_server_side",fa="$web_vitals_allowed_metrics",Pn="$session_recording_remote_config",rf="$replay_sample_rate",sf="$replay_override_sampling",of="$replay_override_linked_flag",af="$replay_override_url_trigger",lf="$replay_override_event_trigger",Yn="$sesid",fl="$session_is_sampled",xn="$enabled_feature_flags",Li="$active_feature_flags",Mr="$early_access_features",ha="$feature_flag_details",Ni="$feature_flag_payloads",Lr="$feature_flag_request_id",rs="$minimal_flag_called_events",It="$override_feature_flags",In="$override_feature_flag_payloads",jt="$stored_person_properties",kn="$stored_group_properties",pa="$surveys",ss="$surveys_loaded_at",ga="$surveys_activated",Nr="$surveys_activated_session",Or="$surveys_activated_timestamps",Oi="ph_product_tours",An="$flag_call_reported",Bi="$flag_call_reported_session_id",Br="$feature_flag_errors",Wi="$feature_flag_evaluated_at",lt="$user_state",ma="$client_session_props",va="$capture_rate_limit",_a="$initial_campaign_params",ya="$initial_referrer_info",os="$initial_person_info",as="$epp",Er="$posthog_cookieless",cf="$cookieless_mode",uf="$sdk_debug_extensions_init_method",df="$sdk_debug_extensions_init_time_ms",ff="$sdk_debug_recording_script_not_loaded",hl="PostHog loadExternalDependency extension not found.",Cn="on_reject",Wt="always",Hn="anonymous",_n="identified",wa="identified_only",ls="visibilitychange",cs="beforeunload",Gn="$pageview",xo="$pageleave",Io="$identify",Nc="$groupidentify";function Sr(t,e){U(t)&&t.forEach(e)}function ie(t,e){if(!W(t))if(U(t))t.forEach(e);else if(tg(t))t.forEach(((i,r)=>e(i,r)));else for(var n in t)Id.call(t,n)&&e(t[n],n)}var fe=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 Dr(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 Oc=function(t){try{return t()}catch{return}},zg=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)}}},pl=function(t){var e={};return ie(t,(function(n,i){(X(n)&&n.length>0||ke(n))&&(e[i]=n)})),e},Vg=["herokuapp.com","vercel.app","netlify.app"];function Gg(t){var e=t?.hostname;if(!X(e))return!1;var n=e.split(".").slice(-2).join(".");for(var i of Vg)if(n===i)return!1;return!0}function ve(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 ba(t){return t.name==="ph_toolbar_internal"}var hf=t=>{if(P){try{for(var e=t+"=",n=P.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 ke(t)&&isFinite(t)&&Math.floor(t)===t});class us{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 us(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 us(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 Kg{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 us.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 Yg}}var Bc,pf=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&&(pf=t=>crypto.getRandomValues(t));class Yg{nextUint32(){return this.R.length>this.O||(pf(this.R),this.O=0),this.R[this.O++]}constructor(){this.R=new Uint32Array(8),this.O=1/0}}var Ht=()=>Jg().toString(),Jg=()=>(Bc||(Bc=new Kg)).generate(),Ei="",Zg=/[a-z0-9][a-z0-9-]+\.[a-z]{2,}$/i,qt={N:()=>!!P,j(t){A.error("cookieStore error: "+t)},P:hf,H(t){var e;try{e=JSON.parse(qt.P(t))||{}}catch{}return e},F(t,e,n,i,r){if(!P)return!1;try{var s="",o="",a=(function(c,d){if(d){var f=(function(h,g){if(g===void 0&&(g=P),Ei)return Ei;if(!g||["localhost","127.0.0.1"].includes(h))return"";for(var m=h.split("."),v=Math.min(m.length,8),E="dmn_chk_"+Ht();!Ei&&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",Ei=S)}return Ei})(c);if(!f){var p=(h=>{var g=h.match(Zg);return g?g[0]:""})(c);p!==f&&A.info("Warning: cookie subdomain discovery mismatch",p,f),f=p}return f?"; domain=."+f:""}return""})(P.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),P.cookie=u,!0}catch{return!1}},q(t,e){if(P!=null&&P.cookie)try{qt.F(t,"",-1,e)}catch{return}}},ko=null,le={N(){if(!Je(ko))return ko;var t=!0;if(C(w))t=!1;else try{var e="__mplssupport__";le.F(e,"xyz"),le.P(e)!=='"xyz"'&&(t=!1),le.q(e)}catch{t=!1}return t||A.error("localStorage unsupported; falling back to cookie store"),ko=t,t},j(t){A.error("localStorage error: "+t)},P(t){try{return w?.localStorage.getItem(t)}catch(e){le.j(e)}return null},H(t){try{return JSON.parse(le.P(t))||{}}catch{}return null},F(t,e){try{return w?.localStorage.setItem(t,JSON.stringify(e)),!0}catch(n){le.j(n)}return!1},q(t){try{w?.localStorage.removeItem(t)}catch(e){le.j(e)}}},Xg=[Qi,"distinct_id",Yn,fl,as,os,lt],xr={},Qg={N:()=>!0,j(t){A.error("memoryStorage error: "+t)},P:t=>xr[t]||null,H:t=>xr[t]||null,F:(t,e)=>(xr[t]=e,!0),q(t){delete xr[t]}},yn=null,be={N(){if(!Je(yn))return yn;if(yn=!0,C(w))yn=!1;else try{var t="__support__";be.F(t,"xyz"),be.P(t)!=='"xyz"'&&(yn=!1),be.q(t)}catch{yn=!1}return yn},j(t){A.error("sessionStorage error: ",t)},P(t){try{return w?.sessionStorage.getItem(t)}catch(e){be.j(e)}return null},H(t){try{return JSON.parse(be.P(t))||null}catch{}return null},F(t,e){try{return w?.sessionStorage.setItem(t,JSON.stringify(e)),!0}catch(n){be.j(n)}return!1},q(t){try{w?.sessionStorage.removeItem(t)}catch(e){be.j(e)}}};class em{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===Wt||this.isRejected()||this.consent===-1&&this.Ne.cookieless_mode===Cn}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 vo(e)?1:j(sg,e)?0:-1}get ii(){var e=this.Ne.opt_out_capturing_persistence_type,n=e==="localStorage"?le:qt;if(!this.ni||this.ni!==n){this.ni=n;var i=e==="localStorage"?qt:le;i.P(this.ri)&&(this.ni.P(this.ri)||this.optInOut(vo(i.P(this.ri))),i.q(this.ri,this.Ne.cross_subdomain_cookie))}return this.ni}ti(){return!!this.Ne.respect_dnt&&[He?.doNotTrack,He?.msDoNotTrack,B.doNotTrack].some((e=>vo(e)))}}function gf(t,e){var n,i=t==null||(n=t.config)==null?void 0:n.get_current_url;if(!je(i))return e;try{var r=i(e);return X(r)&&r?r:e}catch(s){return A.error("Error in get_current_url, falling back to window.location.href",s),e}}var mf="__POSTHOG_TOOLBAR__",tm=1,nm=3,im=11;function Dc(t){return t instanceof Element&&(t.id===mf||!(t.closest==null||!t.closest(".toolbar-global-fade-container")))}function hn(t){return!!t&&t.nodeType===tm}function tt(t,e){return!!t&&!!t.tagName&&t.tagName.toLowerCase()===e.toLowerCase()}function vf(t){return!!t&&t.nodeType===nm}function _f(t){return!!t&&t.nodeType===im&&hn(t.host)}var yf=1e3;function gl(t){return t?Ts(t).split(/\s+/):[]}function jc(t,e){var n=(function(i){var r,s=w==null||(r=w.location)==null?void 0:r.href;return C(s)?void 0:gf(i,s)})(e);return!!(n&&t&&t.some((i=>n.match(i))))}function ds(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 gl(e)}function wf(t){return W(t)?null:Ts(t).split(/(\s+)/).filter((e=>qi(e))).join("").replace(/[\r\n]/g," ").replace(/[ ]+/g," ").substring(0,255)}function er(t){var e="";return Sa(t)&&!xf(t)&&t.childNodes&&t.childNodes.length&&ie(t.childNodes,(function(n){var i;vf(n)&&n.textContent&&(e+=(i=wf(n.textContent))!==null&&i!==void 0?i:"")})),Ts(e)}function Co(t){var e;return C(t.target)?t.srcElement||null:(e=t.target)!=null&&e.shadowRoot?t.composedPath()[0]||null:t.target||null}var ml=["a","button","form","input","select","textarea","label"];function Ea(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 bf(t){var e=t.parentNode;return!(!e||!hn(e))&&e}var rm=[".ph-no-autocapture","[data-ph-no-autocapture]"],Ef=["next","previous","prev",">","<"],sm=[...Ef,"+","-","−","–"],Uc=(t,e)=>/[a-z0-9]/i.test(e)?t.includes(e):t===e,Hc=[".ph-no-rageclick",".ph-no-capture"],om=["","text","search","email","password","url","tel","number"];function Wc(t,e){if(!w||vl(t))return!1;var n,i,r,s,o;if(mt(e)?(n=!!e&&Hc,i=void 0,r=!1):(n=(s=e?.css_selector_ignorelist)!==null&&s!==void 0?s:Hc,i=e?.content_ignorelist,r=(o=e?.ignore_text_selection)!==null&&o!==void 0&&o),n===!1||r&&(function(l){return!(!l||!hn(l))&&(!!tt(l,"textarea")||(tt(l,"input")?j(om,(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=Ef;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,p=d.ariaLabel;return c.some((h=>Uc(f,h)||Uc(p,h)))}))})(i,a.map((l=>{var u;return{safeText:er(l).toLowerCase(),ariaLabel:((u=l.getAttribute("aria-label"))==null?void 0:u.toLowerCase().trim())||""}})))&&!Ea(a,n)}var vl=t=>!t||tt(t,"html")||!hn(t),Sf=(t,e)=>{if(!w||vl(t))return{parentIsUsefulElement:!1,targetElementList:[]};for(var n=!1,i=[t],r=t;r.parentNode&&!tt(r,"body");)if(_f(r.parentNode))i.push(r.parentNode.host),r=r.parentNode.host;else{var s=bf(r);if(!s)break;if(e||ml.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 Sa(t){for(var e=new Set,n=0,i=t;i.parentNode&&!tt(i,"body");i=i.parentNode){if(n++>=yf||e.has(i))return!1;e.add(i);var r=ds(i);if(j(r,"ph-sensitive")||j(r,"ph-no-capture"))return!1}if(j(ds(t),"ph-include"))return!0;var s=t.type||"";if(X(s))switch(s.toLowerCase()){case"hidden":case"password":return!1}var o=t.name||t.id||"";return!X(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 xf(t){return!!(tt(t,"input")&&!["button","checkbox","submit","reset"].includes(t.type)||tt(t,"select")||tt(t,"textarea")||t.getAttribute("contenteditable")==="true")}var qc=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}))$"),zc=/(^|[^0-9A-Za-z_])([0-9][0-9 -]*[0-9])(?=$|[^0-9A-Za-z_])/g,am=[16,15,14,13],lm=new RegExp("^(\\d{3}-?\\d{2}-?\\d{4})$"),Vc=new RegExp("(^|[^0-9])((?!000|666)[0-9]{3}-?(?!00)[0-9]{2}-?(?!0000)[0-9]{4})(?=$|([^0-9]))","g"),Gc=/[0-9A-Za-z_]/;function cm(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 qi(t,e){if(e===void 0&&(e=!0),W(t))return!1;if(X(t)){t=Ts(t);var n=e?qc.test((t||"").replace(/[- ]/g,"")):(function(r){var s;for(zc.lastIndex=0;s=zc.exec(r);){var o=s[2];if(o)for(var a=o.replace(/[- ]/g,""),l=0;a.length>l;l++)for(var u of am){var c=l+u;if(a.length>=c){var d=a.slice(l,c);if(qc.test(d)&&cm(d))return!0}}}return!1})(t);if(n)return!1;var i=e?lm.test(t):(function(r){var s;for(Vc.lastIndex=0;s=Vc.exec(r);){var o=s[1],a=s[3];if(!(o&&a&&Gc.test(o)&&Gc.test(a)))return!0}return!1})(t);if(i)return!1}return!0}function Kc(t){var e=er(t);return qi(e=(e+" "+If(t)).trim())?e:""}function If(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=er(n);e=(e+" "+r).trim(),n.childNodes&&n.childNodes.length&&(e=(e+" "+If(n)).trim())}catch(s){A.error("[AutoCapture]",s)}})),e}function Yc(t){return t.replace(/"|\\"/g,'\\"')}function um(t){var e=t.attr__class;if(e)return U(e)?e:gl(e)}var Ir=pe("[Dead Clicks]"),dm=()=>!0,fm=t=>{var e,n=!((e=t.instance.persistence)==null||!e.get_property(ul)),i=t.instance.config.capture_dead_clicks;return mt(i)?i:!!he(i)||n};class Jc{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({[ul]:n.captureDeadClicks}),this.startIfEnabledOrStop())}}startIfEnabledOrStop(){this.isEnabled(this)?this.ai((()=>{this.oi()})):this.stop()}ai(e){var n,i;(n=B.__PosthogExtensions__)!=null&&n.initDeadClicksAutocapture?e():(i=B.__PosthogExtensions__)==null||i.loadExternalDependency==null||i.loadExternalDependency(this.instance,"dead-clicks-autocapture",(r=>{r?Ir.error("failed to load script",r):e()}))}oi(){var e;if(P){if(!this.si&&(e=B.__PosthogExtensions__)!=null&&e.initDeadClicksAutocapture){var n=he(this.instance.config.capture_dead_clicks)?I({},this.instance.config.capture_dead_clicks):{};n.__onCapture=this.onCapture,this.onCapture&&(n.capture_dead_swipes=!1),this.si=B.__PosthogExtensions__.initDeadClicksAutocapture(this.instance,n),this.si.start(P),Ir.info("starting...")}}else Ir.error("`document` not found. Cannot start.")}stop(){this.si&&(this.si.stop(),this.si=void 0,Ir.info("stopping..."))}}var Ao=pe("[SegmentIntegration]"),kf="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,p,h,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((b=>I({},b,{stacktrace:b.stacktrace?I({},b.stacktrace,{type:"raw",frames:(b.stacktrace.frames||[]).map((k=>I({},k,{platform:"web:javascript"})))}):void 0}))),_={$exception_message:((f=E[0])==null?void 0:f.value)||c.message,$exception_type:(p=E[0])==null?void 0:p.type,$exception_level:c.level,$exception_list:S,$sentry_event_id:c.event_id,$sentry_exception:c.exception,$sentry_exception_message:((h=E[0])==null?void 0:h.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 hm{constructor(e,n,i,r,s,o){this.name=kf,this.setupOnce=function(a){a(Cf(e,{organization:n,projectId:i,prefix:r,severityAllowList:s,sendExceptionsToPostHog:o==null||o}))}}}class Zc{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?At(a/o,0,1,A):1,p=o>1?At(l/o,0,1,A):1,h=u>1?At(c/u,0,1,A):1,g=u>1?At(d/u,0,1,A):1;r=fe(r,{$prev_pageview_last_scroll:a,$prev_pageview_last_scroll_percentage:f,$prev_pageview_max_scroll:l,$prev_pageview_max_scroll_percentage:p,$prev_pageview_last_content:c,$prev_pageview_last_content_percentage:h,$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 Po=["flags","surveys"],pm={[nf]:{exposure:"hidden"},[$i]:{exposure:"hidden"},__cmpns:{exposure:"hidden"},[Mi]:{exposure:"hidden"},[oa]:{exposure:"event"},[aa]:{exposure:"hidden"},[la]:{exposure:"event"},[ca]:{exposure:"hidden"},[ua]:{exposure:"event"},[da]:{exposure:"event"},[ul]:{exposure:"event"},[dl]:{exposure:"hidden"},[fa]:{exposure:"event"},[Pn]:{exposure:"hidden"},$session_recording_enabled_server_side:{exposure:"hidden"},[Yn]:{exposure:"hidden"},[fl]:{exposure:"event"},[rf]:{exposure:"event",shouldSkipFromEventProperties:t=>Je(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"},[xn]:{exposure:"hidden",storageGroup:"flags"},[Li]:{exposure:"hidden",storageGroup:"flags"},[Mr]:{exposure:"hidden"},[ha]:{exposure:"hidden",storageGroup:"flags"},[Ni]:{exposure:"hidden",storageGroup:"flags"},[Lr]:{exposure:"hidden",storageGroup:"flags",volatile:!0},[rs]:{exposure:"hidden",storageGroup:"flags"},[It]:{exposure:"hidden"},[In]:{exposure:"hidden"},[jt]:{exposure:"hidden"},[kn]:{exposure:"hidden"},[pa]:{exposure:"hidden",storageGroup:"surveys"},[ss]:{exposure:"hidden",storageGroup:"surveys",volatile:!0},[ga]:{exposure:"event"},[Nr]:{exposure:"hidden"},[Or]:{exposure:"hidden"},[Oi]:{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"},[An]:{exposure:"hidden"},[Bi]:{exposure:"hidden"},[Br]:{exposure:"hidden"},[Wi]:{exposure:"hidden",storageGroup:"flags",volatile:!0},[lt]:{exposure:"hidden"},[ma]:{exposure:"hidden"},[va]:{exposure:"hidden"},[_a]:{exposure:"hidden"},[ya]:{exposure:"hidden"},[os]:{exposure:"hidden"},[as]:{exposure:"hidden"},[sf]:{exposure:"event"},[of]:{exposure:"event"},[af]:{exposure:"event"},[lf]:{exposure:"event"},[uf]:{exposure:"event"},[df]:{exposure:"event"},[ff]:{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"}},gm=[["$posthog_sr_group_event_trigger_",{exposure:"hidden"}],["$posthog_sr_group_url_trigger_",{exposure:"hidden"}],["$posthog_sr_group_sampling_",{exposure:"hidden"}]],wn=t=>{var e=pm[t];if(e)return e;for(var n of gm){var i=n[1];if(t.indexOf(n[0])===0)return i}},Jn=(t,e)=>{try{return JSON.stringify(t,((n,i)=>typeof i=="bigint"?i.toString():i),e)}catch{return Sd(t)}},fs=t=>{var e=P?.createElement("a");return C(e)?null:(e.href=t,e)},oi=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," ")},tr=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},hs=function(t,e){var n=t.match(new RegExp(e+"=([^&]*)"));return n?n[1]:null},Af=(t,e)=>t>=e&&wd(),Pf=(t,e,n,i)=>{if(t===0){if(wd()){var r=e+1;return r===n&&i(),r}return e}return 0},kr="https?://(.*)",ai=["gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","irclid","_kx"],mm=["utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid",...ai],nr="",vm=["li_fat_id"];function Ff(t,e,n){if(!P)return{};var i,r=e?[...ai,...n||[]]:[],s=Rf(tr(P.URL,r,nr),t),o=(i={},ie(vm,(function(a){var l=hf(a);i[a]=l||null})),i);return fe(o,s)}function Rf(t,e){var n=mm.concat(e||[]),i={};return ie(n,(function(r){var s=oi(t,r);i[r]=s||null})),i}function Tf(t){var e=(function(s){return s?s.search(kr+"google.([^/?]*)")===0?"google":s.search(kr+"bing.com")===0?"bing":s.search(kr+"yahoo.com")===0?"yahoo":s.search(kr+"duckduckgo.com")===0?"duckduckgo":null:null})(t),n=e!="yahoo"?"q":"p",i={};if(!Je(e)){i.$search_engine=e;var r=P?oi(P.referrer,n):"";r.length&&(i.ph_keyword=r)}return i}function Xc(){return navigator.language||navigator.userLanguage}var ps="$direct";function $f(){return P?.referrer||ps}function Mf(t,e,n){n===void 0&&(n=!1);var i=t?[...ai,...e||[]]:[],r=n?fn(me?.href):me?.href,s=r?.substring(0,1e3);return{r:$f().substring(0,1e3),u:s?tr(s,i,nr):void 0}}function Lf(t,e){var n;e===void 0&&(e=!1);var i=t.r,r=t.u,s=e?fn(r):r,o={$referrer:i,$referring_domain:i==null?void 0:i==ps?ps:(n=fs(i))==null?void 0:n.host};if(s){o.$current_url=s;var a=fs(s);o.$host=a?.host,o.$pathname=a?.pathname;var l=Rf(s);fe(o,l)}if(i){var u=Tf(i);fe(o,u)}return o}function Nf(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return}}function _m(){try{return new Date().getTimezoneOffset()}catch{return}}var ym={flags:Wi,surveys:ss},wm=["cookie","localstorage","localstorage+cookie","sessionstorage","memory"],Wn="main";class Fo{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,I({},this.props)),this.update_config(e,e,n),this.save(),w){var r=()=>this.flush();ve(w,"beforeunload",r,{capture:!1}),ve(w,"pagehide",r,{capture:!1})}}ki(){var e,n=(e=this.Ne)==null?void 0:e.persistence_save_debounce_ms;return ke(n)&&n>0?n:0}isDisabled(){return!!this.xi}bi(e){wm.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 I({},le,{H(u){try{var c={};try{c=qt.H(u)||{}}catch{}var d,f=JSON.parse(le.P(u)||"{}");if(a){var p={};for(var h in c){var g=c[h];Je(g)||g===""||(p[h]=g)}d=fe(f,p)}else d=fe(c,f);return le.F(u,d),d}catch{}return null},F(u,c,d,f,p,h){var g=le.F(u,c,void 0,void 0,h);try{var m={};l.forEach((v=>{c[v]&&(m[v]=c[v])})),Object.keys(m).length&&qt.F(u,m,d,f,p,h)}catch(v){le.j(v)}return g},q(u,c){try{w?.localStorage.removeItem(u),qt.q(u,c)}catch(d){le.j(d)}}})})(e.cookie_persisted_properties||[],e.__preview_cookie_wins_on_conflict||!1),r=!1,s=e.persistence.toLowerCase();return s==="localstorage"&&le.N()?(n=le,r=!0):s==="localstorage+cookie"&&i.N()?(n=i,r=!0):s==="sessionstorage"&&be.N()?n=be:s==="memory"?n=Qg:s==="cookie"?n=qt:i.N()?(n=i,r=!0):n=qt,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=wn(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=fe({},e)),this.pi&&this.Ci()}}Ci(){for(var e of Po){var n=le.H(this.Si(e));if(n&&!Kt(n)){var i=this.Mi(e);i.persisted=!0,this.Ti(e)||(i.fingerprint=this.Ei(n,e)),this.Ii(e,n)||fe(this.props,n)}}}Ti(e){return Object.keys(this.props).some((n=>{var i;return((i=wn(n))==null?void 0:i.storageGroup)===e}))}Ii(e,n){var i=ym[e];if(!i)return!1;var r=n[i],s=this.props[i];return ke(r)&&ke(s)&&s>r}refreshKey(e){var n;if(!this.xi){var i=this.pi?(n=wn(e))==null?void 0:n.storageGroup:void 0,r=i?le.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,Wn))}Li(){var e=this.Di(),n=e.main,i=e.groups;for(var r of(this.Oi(this.ii,this.yi,n,Wn),Po)){var s,o=i[r];(!Kt(o)||(s=this.ci[r])!=null&&s.persisted)&&this.Oi(le,this.Si(r),o,r)}}Di(){var e={},n={flags:{},surveys:{}};return ie(this.props,((i,r)=>{var s,o=(s=wn(r))==null?void 0:s.storageGroup;o?n[o][r]=i:e[r]=i})),{main:e,groups:n}}Ei(e,n){if(n===Wn)return JSON.stringify(e)+"|"+this.$i+"|"+this.Ni+"|"+this.qi;var i={};return ie(e,((r,s)=>{var o;i[s]=(o=wn(s))!=null&&o.volatile?"__volatile__":r})),JSON.stringify(i)}Oi(e,n,i,r){var s=this.Mi(r);if(r===Wn||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!==Wn&&(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 Po)le.q(this.Si(r));i?delete this.ci[Wn]:this.ci={}}clear(){this.remove(),this.props={}}register_once(e,n,i){if(he(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(he(e)){this.$i=C(n)?this.ji:n;var i=!1;if(ie(e,((r,s)=>{e.hasOwnProperty(s)&&(this.props[s]!==r||he(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=P?.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);Kt(pl(n))||this.register(n),this.mi=e}}update_search_keyword(){var e;this.register((e=P?.referrer)?Tf(e):{})}update_referrer_info(){var e;this.register_once({$referrer:$f(),$referring_domain:P!=null&&P.referrer&&((e=fs(P.referrer))==null?void 0:e.host)||ps},void 0)}set_initial_person_info(){this.props[_a]||this.props[ya]||this.register_once({[os]: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([ya,_a],(r=>{var s=this.props[r];s&&ie(s,(function(o,a){e["$initial_"+Qo(a)]=o}))}));var n=this.props[os];if(n){var i=(function(r,s){s===void 0&&(s=!1);var o=Lf(r,s),a={};return ie(o,(function(l,u){a["$initial_"+Qo(u)]=l})),a})(n,this.Ne.disable_capture_url_hashes);fe(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,p)=>f===d[p]))})(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[Mi]||{};i[e]=n,this.Pi(Mi,i),this.save()}remove_event_timer(e){var n=this.props[Mi]||{},i=n[e];return C(i)||(delete n[e],this.Pi(Mi,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=wn(e))!=null&&i.volatile||this.Bi(e)}Ri(e){delete this.props[e],this.Bi(e)}Bi(e){var n,i=(n=wn(e))==null?void 0:n.storageGroup;i&&(this.Mi(i).dirty=!0)}Mi(e){return this.ci[e]||(this.ci[e]={})}}function Cr(t){var e=!0;return{dispose(){if(e){e=!1;var n=t();n&&je(n.then)&&n.then(void 0,(()=>{}))}}}}var Ue={GZipJS:"gzip-js",Base64:"base64"},Si={Activation:"events",Cancellation:"cancelEvents"},Ro={Popover:"popover",API:"api",Widget:"widget"},zt={SHOWN:"survey shown",DISMISSED:"survey dismissed",SENT:"survey sent"},To={SURVEY_ID:"$survey_id",SURVEY_ITERATION:"$survey_iteration",SURVEY_LAST_SEEN_DATE:"$survey_last_seen_date"},xa={Popover:"popover",Inline:"inline"},bm={SHOWN:"product tour shown"},Qc={TOUR_LAST_SEEN_DATE:"$product_tour_last_seen_date",TOUR_TYPE:"$product_tour_type"},eu=pe("[RateLimiter]");class Em{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=>{eu.info((r||"events")+" is quota limited."),this.serverLimits[r]=new Date().getTime()+6e4}))}catch(r){return void eu.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(va))!==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=(ke(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(va,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")&&me!=null&&me.pathname)return""+((e=me.origin)!==null&&e!==void 0?e:"")+me.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 an.info("Using preloaded remote config",this.remoteConfig),this.Zi(this.remoteConfig),void this.Gi();if(this._instance.Qi())return void an.warn("Remote config is disabled. Falling back to local config.");this.Wi((e=>{if(!e)return an.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){an.error("Error loading remote config",e),this.Zi()}}stop(){this.Ki&&(clearInterval(this.Ki),this.Ki=void 0)}refresh(){!this._instance.Qi()&&P&&P.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||an.warn("Failed to fetch remote config from PostHog."):an.error("Failed to fetch remote config from PostHog."));try{this._instance.Zi(e?{ok:!0,config:e}:{ok:!1})}catch(r){an.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){an.error("Error loading feature flags",r)}}}var ut=Uint8Array,Ye=Uint16Array,li=Uint32Array,_l=new ut([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]),yl=new ut([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]),tu=new ut([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Bf=function(t,e){for(var n=new Ye(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]},Df=Bf(_l,2),Ia=Df[1];Df[0][28]=258,Ia[258]=28;for(var nu=Bf(yl,0)[1],jf=new Ye(32768),_e=0;32768>_e;++_e){var qn=(43690&_e)>>>1|(21845&_e)<<1;jf[_e]=((65280&(qn=(61680&(qn=(52428&qn)>>>2|(13107&qn)<<2))>>>4|(3855&qn)<<4))>>>8|(255&qn)<<8)>>>1}var zi=function(t,e,n){for(var i=t.length,r=0,s=new Ye(e);i>r;++r)++s[t[r]-1];var o,a=new Ye(e);for(r=0;e>r;++r)a[r]=a[r-1]+s[r-1]<<1;for(o=new Ye(i),r=0;i>r;++r)o[r]=jf[a[t[r]-1]++]>>>15-t[r];return o},Mn=new ut(288);for(_e=0;144>_e;++_e)Mn[_e]=8;for(_e=144;256>_e;++_e)Mn[_e]=9;for(_e=256;280>_e;++_e)Mn[_e]=7;for(_e=280;288>_e;++_e)Mn[_e]=8;var gs=new ut(32);for(_e=0;32>_e;++_e)gs[_e]=5;var Sm=zi(Mn,9),xm=zi(gs,5),Uf=function(t){return(t/8>>0)+(7&t&&1)},Hf=function(t,e,n){(n==null||n>t.length)&&(n=t.length);var i=new(t instanceof Ye?Ye:t instanceof li?li:ut)(n-e);return i.set(t.subarray(e,n)),i},Ot=function(t,e,n){var i=e/8>>0;t[i]|=n<<=7&e,t[i+1]|=n>>>8},xi=function(t,e,n){var i=e/8>>0;t[i]|=n<<=7&e,t[i+1]|=n>>>8,t[i+2]|=n>>>16},$o=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 ut(0),0];if(r==1){var o=new ut(n[0].s+1);return o[n[0].s]=1,[o,1]}n.sort((function(b,k){return b.f-k.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 p=new Ye(f+1),h=ka(n[c-1],p,0);if(h>e){i=0;var g=0,m=h-e,v=1<i;++i){var E=s[i].s;if(e>=p[E])break;g+=v-(1<>>=m;g>0;){var S=s[i].s;e>p[S]?g-=1<=0&&g;--i){var _=s[i].s;p[_]==e&&(--p[_],++g)}h=e}return[new ut(p),h]},ka=function(t,e,n){return t.s==-1?Math.max(ka(t.l,e,n+1),ka(t.r,e,n+1)):e[t.s]=n},iu=function(t){for(var e=t.length;e&&!t[--e];);for(var n=new Ye(++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]},Ii=function(t,e){for(var n=0,i=0;e.length>i;++i)n+=t[i]*e[i];return n},Ca=function(t,e,n){var i=n.length,r=Uf(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)},ru=function(t,e,n,i,r,s,o,a,l,u,c){Ot(e,c++,n),++r[256];for(var d=$o(r,15),f=d[0],p=d[1],h=$o(s,15),g=h[0],m=h[1],v=iu(f),E=v[0],S=v[1],_=iu(g),b=_[0],k=_[1],T=new Ye(19),x=0;E.length>x;++x)T[31&E[x]]++;for(x=0;b.length>x;++x)T[31&b[x]]++;for(var F=$o(T,7),$=F[0],O=F[1],L=19;L>4&&!$[tu[L-1]];--L);var N,K,V,M,R=u+5<<3,Z=Ii(r,Mn)+Ii(s,gs)+o,Ce=Ii(r,f)+Ii(s,g)+o+14+3*L+Ii(T,$)+(2*T[16]+3*T[17]+7*T[18]);if(Z>=R&&Ce>=R)return Ca(e,c,t.subarray(l,l+u));if(Ot(e,c,1+(Z>Ce)),c+=2,Z>Ce){N=zi(f,p),K=f,V=zi(g,m),M=g;var oe=zi($,O);for(Ot(e,c,S-257),Ot(e,c+5,k-1),Ot(e,c+10,L-4),c+=14,x=0;L>x;++x)Ot(e,c+3*x,$[tu[x]]);c+=3*L;for(var ye=[E,b],$e=0;2>$e;++$e){var ae=ye[$e];for(x=0;ae.length>x;++x)Ot(e,c,oe[Ie=31&ae[x]]),c+=$[Ie],Ie>15&&(Ot(e,c,ae[x]>>>5&127),c+=ae[x]>>>12)}}else N=Sm,K=Mn,V=xm,M=gs;for(x=0;a>x;++x)if(i[x]>255){var Ie;xi(e,c,N[257+(Ie=i[x]>>>18&31)]),c+=K[Ie+257],Ie>7&&(Ot(e,c,i[x]>>>23&31),c+=_l[Ie]);var Se=31&i[x];xi(e,c,V[Se]),c+=M[Se],Se>3&&(xi(e,c,i[x]>>>5&8191),c+=yl[Se])}else xi(e,c,N[i[x]]),c+=K[i[x]];return xi(e,c,N[256]),c+K[256]},Im=new li([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),km=(function(){for(var t=new li(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 Cm(t,e){e===void 0&&(e={});var n=(function(){var d=4294967295;return{p(f){for(var p=d,h=0;f.length>h;++h)p=km[255&p^f[h]]^p>>>8;d=p},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,p,h,g,m){var v=d.length,E=new ut(h+v+5*(1+Math.floor(v/7e3))+g),S=E.subarray(h,E.length-g),_=0;if(!f||8>v)for(var b=0;v>=b;b+=65535){var k=b+65535;v>k?_=Ca(S,_,d.subarray(b,k)):(S[b]=!0,_=Ca(S,_,d.subarray(b,v)))}else{for(var T=Im[f-1],x=T>>>13,F=8191&T,$=(1<b;++b){var Ie=V(b),Se=32767&b,De=L[Ie];if(O[Se]=De,L[Ie]=Se,b>=$e){var wt=v-b;if((Ce>7e3||ye>24576)&&wt>423){_=ru(d,S,0,M,R,Z,oe,ye,ae,b-ae,_),ye=Ce=oe=0,ae=b;for(var ge=0;286>ge;++ge)R[ge]=0;for(ge=0;30>ge;++ge)Z[ge]=0}var Ze=2,bt=0,vn=F,Te=Se-De&32767;if(wt>2&&Ie==V(b-Te))for(var Pe=Math.min(x,wt)-1,$t=Math.min(32767,b),Dn=Math.min(258,wt);$t>=Te&&--vn&&Se!=De;){if(d[b+Ze]==d[b+Ze-Te]){for(var ze=0;Dn>ze&&d[b+ze]==d[b+ze-Te];++ze);if(ze>Ze){if(Ze=ze,bt=Te,ze>Pe)break;var jn=Math.min(Te,ze-2),Mt=0;for(ge=0;jn>ge;++ge){var Lt=b-Te+ge+32768&32767,dt=Lt-O[Lt]+32768&32767;dt>Mt&&(Mt=dt,De=Lt)}}}Te+=(Se=De)-(De=O[Se])+32768&32767}if(bt){M[ye++]=268435456|Ia[Ze]<<18|nu[bt];var sn=31&Ia[Ze],_i=31&nu[bt];oe+=_l[sn]+yl[_i],++R[257+sn],++Z[_i],$e=b+Ze,++Ce}else M[ye++]=d[b],++R[d[b]]}}_=ru(d,S,!0,M,R,Z,oe,ye,ae,b-ae,_)}return Hf(E,0,h+Uf(_)+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 p=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&&Mo(d,4,Math.floor(new Date(f.mtime||Date.now())/1e3)),p){d[3]=8;for(var h=0;p.length>=h;++h)d[h+10]=p.charCodeAt(h)}})(u,e),Mo(u,c-8,n.d()),Mo(u,c-4,i),u}var Am=!!Jo||!!il,Wf="text/plain",jr=!1,qf=(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:"")},Ms=function(t,e,n){var i;n===void 0&&(n=!0);var r=t.split("?"),s=r[0],o=r[1],a=I({},e),l=(i=o?.split("&").map((c=>{var d,f=c.split("="),p=f[0],h=n&&(d=a[p])!==null&&d!==void 0?d:f[1];return delete a[p],p+"="+h})))!==null&&i!==void 0?i:[],u=(function(c,d){var f,p;d===void 0&&(d="&");var h=[];return ie(c,(function(g,m){C(g)||C(m)||m==="undefined"||(f=encodeURIComponent((v=>v instanceof File)(g)?g.name:g.toString()),p=encodeURIComponent(m),h[h.length]=p+"="+f)})),h.join(d)})(a);return u&&l.push(u),l.length>0?s+"?"+l.join("&"):s},Lo=t=>{if(t.Ji)return t.Ji;var e=t.data,n=t.compression;if(e){if(n===Ue.GZipJS){var i=Cm((function(a,l){var u=a.length;if(typeof TextEncoder<"u")return new TextEncoder().encode(a);for(var c=new ut(a.length+(a.length>>>1)),d=0,f=function(m){c[d++]=m},p=0;u>p;++p){if(d+5>c.length){var h=new ut(d+8+(u-p<<1));h.set(c),c=h}var g=a.charCodeAt(p);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(++p))>>>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 Hf(c,0,d)})(Jn(e)),{mtime:0});return{contentType:Wf,body:i.buffer.slice(i.byteOffset,i.byteOffset+i.byteLength),estimatedSize:i.byteLength}}if(n===Ue.Base64){var r=(function(a){return a&&btoa(encodeURIComponent(a).replace(/%([0-9A-F]{2})/g,((l,u)=>String.fromCharCode(parseInt(u,16)))))})(Jn(e)),s=(a=>"data="+encodeURIComponent(typeof a=="string"?a:Jn(a)))(r);return{contentType:"application/x-www-form-urlencoded",body:s,estimatedSize:new Blob([s]).size}}var o=Jn(e);return{contentType:"application/json",body:o,estimatedSize:new Blob([o]).size}}},zf=t=>{var e,n,i=()=>t.transport==="sendBeacon"?{url:Ms(t.url,{compression:Ue.Base64}),encodedBody:Lo(I({},t,{compression:Ue.Base64,Ji:void 0}))}:{url:qf(t.url,"compression"),encodedBody:Lo(I({},t,{compression:void 0,Ji:void 0}))};try{e=Lo(t)}catch(r){if(xc(t.compression,oi(t.url,"compression")))return A.error("Failed to gzip request body, sending uncompressed payload",r),i();throw r}return e&&xc(t.compression,oi(t.url,"compression"))&&!((n=e.body)instanceof ArrayBuffer?Zo(new Uint8Array(n)):ArrayBuffer.isView(n)&&Zo(new Uint8Array(n.buffer,n.byteOffset,n.byteLength)))?(jr=!0,i()):{url:t.url,encodedBody:e}},Vf=t=>{try{return zf(t)}catch(e){return A.error(e),void(t.callback==null||t.callback({statusCode:0,error:e}))}},Pm=(function(){var t=se((function*(e){var n=Jn(e.data),i=yield(function(s,o,a){return Xo.apply(this,arguments)})(n,ne.DEBUG,{rethrow:!0});if(!i)return e;var r=yield i.arrayBuffer();return I({},e,{Ji:{contentType:Wf,body:r,estimatedSize:r.byteLength}})}));return function(e){return t.apply(this,arguments)}})(),Fm=/Failed to fetch|NetworkError|Load failed/i,Gf=t=>t?.name==="TypeError"&&Fm.test(t?.message||""),Kf=t=>{var e=Vf(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(h,g){l.append(g,h)})),s&&l.append("Content-Type",s);var u=null,c=!1;if(_c){var d=new _c;u={signal:d.signal,timeout:setTimeout((()=>{var h,g;c=!0,d.abort((h=t.timeout,(g=new Error("PostHog request timed out"+(h?" after "+h+"ms":""))).name="AbortError",g))}),t.timeout)}}var f=h=>{c&&h?.name==="AbortError"||Gf(h)?A.warn(h):A.error(h),t.callback==null||t.callback({statusCode:0,error:h})};try{var p;il(n,I({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((h=>h.text().then((g=>{var m={statusCode:h.status,text:g};if(h.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(h){u&&clearTimeout(u.timeout),f(h)}}},Aa=t=>{try{var e,n=zf(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(He.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:I({},t.data,{batch:f});return Aa(I({},t,{data:d(u.slice(0,c))})),void Aa(I({},t,{data:d(u.slice(c))}))}A.warn("Beacon of ~"+(a??0)+" bytes was rejected by the browser, falling back to fetch"),Kf(I({},t,{Yi:!0}))}catch(f){A.warn("Beacon send failed",f)}},su=(t,e,n,i)=>{var r=i==="query"?e==="POST"?"sent_at":"_":void 0;return Ms(n===Ue.GZipJS?qf(t,"compression"):t,I({},r?{[r]:Date.now().toString()}:{},n===Ue.GZipJS?{}:{compression:n}))},Ur=[];il&&Ur.push({transport:"fetch",method:Kf}),Jo&&Ur.push({transport:"XHR",method(t){var e=Vf(t);if(e){var n=new Jo,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)}}}),He!=null&&He.sendBeacon&&Ur.push({transport:"sendBeacon",method:Aa});var Pa=3e3;class Rm{constructor(e,n){this.Xi=!0,this.tr=[],this.er=At(n?.flush_interval_ms||Pa,250,5e3,A.createLogger("flush interval"),Pa),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(I({},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]=I({},r,{data:[]})),(i=e[s].data)==null||i.push(r.data)})),this.tr=[],e}}var Tm=["retriesPerformedSoFar"];class $m{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},ve(w,"online",this.vr),ve(w,"offline",this.pr))}get length(){return this.tr.length}retriableRequest(e){var n=e.retriesPerformedSoFar,i=bd(e,Tm);Dt(n)&&(i.url=Ms(i.url,{retry_count:n})),this._instance._send_request(I({},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(I({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(I({},n,{transport:"sendBeacon"}))}catch(i){A.error(i)}}this.tr=[]}}class Mm{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(){ve(w,"scroll",this.yr,{capture:!0}),ve(w,"scrollend",this.yr,{capture:!0}),ve(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 Lm=t=>Mf(t?.config.mask_personal_data_properties,t?.config.custom_personal_data_properties,t?.config.disable_capture_url_hashes);class ou{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({[ma]:a})}},this._instance=e,this.Tr=n,this.Mr=i,this.Cr=r||Lm,this.Tr.onSessionId(this.kr)}Sr(){return this.Mr.props[ma]}getSetOnceProps(){var e,n=(e=this.Sr())==null?void 0:e.props;return n?"r"in n?Lf(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(pl(this.getSetOnceProps()),((n,i)=>{i==="$current_url"&&(i="url"),e["$session_entry_"+Qo(i)]=n})),e}}class wl{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 ki=pe("[SessionId]");class au{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 wl,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===Wt)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||Ht,this.Nr=i||Ht;var s=this.Ne.persistence_name||this.Ne.token;if(this._sessionTimeoutMs=1e3*At(this.Ne.session_idle_timeout_seconds||1800,60,36e3,ki.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=be.H(this.jr),a=be.H(this.Br);o&&!a?this.Or=o:be.q(this.jr),be.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){ki.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&&be.N()}Wr(e){e!==this.Or&&(this.Or=e,this.Hr()&&be.F(this.jr,e))}Vr(){return this.Or?this.Or:this.Hr()?be.H(this.jr):null}Zr(e){var n=this.Pr;return!Je(n)&&!Je(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({[Yn]:[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(Yn):(this.Mr.flush(),this.Mr.load())}Kr(){var e;if(!Je(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({[Yn]:[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[Yn];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(cs,this.Ar,{capture:!1}),this.Ar=void 0),this.Rr=[]}zr(){this.Ar=()=>{this.Kr(),this.Hr()&&be.q(this.Br)},ve(w,cs,this.Ar,{capture:!1})}checkAndGetSessionAndWindowId(e,n){if(e===void 0&&(e=!1),n===void 0&&(n=null),this.Ne.cookieless_mode===Wt)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=Dt(o)&&Math.abs(i-o)>864e5,c=!1,d=!1,f=!s,p=s,h=!f&&!e&&this.Lr(i,a);if(h){(h=this.Xr(i))||ki.info("cross-tab refresh kept the session alive",{sessionId:s});var g=this.Jr();s=g[1],o=g[2]}f||h||u?(s=this.$r(),l=this.Nr(),ki.info("new session ID generated",{sessionId:s,windowId:l,changeReason:{noSessionId:f,activityTimeout:h,sessionPastMaximumLength:u}}),o=i,c=!0):(l||(l=this.Nr(),c=!0),(d=s!==p)&&(ki.info("adopted cross-tab session id",{sessionId:s,windowId:l}),c=!0));var m=Dt(a)&&e&&!u?a:i,v=Dt(o)?o:new Date().getTime();this.Wr(l),this.Ur(s,m,v),e||this.qr();var E={noSessionId:f,activityTimeout:h,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 Yf=function(t,e){if(!t)return!1;var n=t.userAgent;if(n&&kc(n,e))return!0;try{var i=t?.userAgentData;if(i!=null&&i.brands&&i.brands.some((r=>kc(r?.brand,e))))return!0}catch{}return!!t.webdriver};function Jf(){return(Jf=se((function*(){var t=He?.userAgentData;if(t!=null&&t.getHighEntropyValues)try{var e=yield t.getHighEntropyValues(["model"]),n=e?.model;return X(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 ms=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 No(t,e,n){return Jn({distinct_id:t,userPropertiesToSet:e,userPropertiesToSetOnce:n})}var Zf={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=>ms(n,i))))),not_regex:(t,e)=>e.every((n=>t.every((i=>!ms(n,i))))),icontains:(t,e)=>e.map(Ar).some((n=>t.map(Ar).some((i=>n.includes(i))))),not_icontains:(t,e)=>e.map(Ar).every((n=>t.map(Ar).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 Xf(t,e){return!t||Object.entries(t).every((n=>{var i=n[1],r=e?.[n[0]];if(C(r)||Je(r))return!1;var s=[String(r)],o=Zf[i.operator];return!!o&&o(i.values,s)}))}var Fa="custom",lu="i.posthog.com",Nm=/^\/static\//;class Om{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("."+lu,".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":Fa),this.en[this.apiHost]}rn(e){if(Nm.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===Fa)return this.apiHost+n;var r=lu+n;switch(e){case"assets":return"https://"+this.region+"-assets."+r;case"api":return"https://"+this.region+"."+r}}}function Qf(t){var e;return!((e=t.conditions)==null||(e=e.events)==null||(e=e.values)==null||!e.length)}var Q=pe("[Surveys]"),eh="seenSurvey_",th=t=>{try{var e=(n=>((i,r)=>""+eh+(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){Q.error("Failed to persist survey seen state",n)}},Bm=[Ro.Popover,Ro.Widget,Ro.API],Dm={ignoreConditions:!1,ignoreDelay:!1,displayType:xa.Popover},jm=pe("[PostHog ExternalIntegrations]"),Um={intercom:"intercom-integration",crispChat:"crisp-chat-integration"};class Hm{constructor(e){this._instance=e}ai(e,n){var i;(i=B.__PosthogExtensions__)==null||i.loadExternalDependency==null||i.loadExternalDependency(this._instance,e,(r=>{if(r)return jm.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=B.__PosthogExtensions__)!=null&&(s=s.integrations)!=null&&s[l]||e.ai(Um[l],(()=>{var c;(c=B.__PosthogExtensions__)==null||(c=c.integrations)==null||(c=c[l])==null||c.start(e._instance)})),!u&&(o=B.__PosthogExtensions__)!=null&&(o=o.integrations)!=null&&o[l]&&((a=B.__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 Wm{constructor(e,n){this.rt=e,this.nn=n,this.sn=new Map,this.an=!1}add(e){var n=this;return se((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&&je(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 qm{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 cu="extensionsRemoteConfig";class zm{constructor(e){this.an=!1,this.instance=e,this.rt=A,this.un=e.hn,this.kv=new qm(e),this.onEvent=n=>Cr(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 Cr((()=>{}));var i=s=>{try{n(s)}catch(o){this.rt.error("Browser extension remote config listener failed",o)}},r=this.instance.dn.on(cu,i);return this.un&&i(this.un),Cr(r)},this.vn=new Wm(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(Qi))!==null&&e!==void 0?e:this.distinctId}get deviceId(){var e=this.instance.get_property(Qi);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 se((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 Cr(this.instance.cn(e))}handleRemoteConfig(e){this.an||(this.un=e,this.instance.dn.emit(cu,e))}sendRequest(e,n){var i=this;return se((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?Ms(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 Vi={},Oo=0,vs=()=>{},uu='Consent opt in/out is not valid with cookieless_mode="always" and will be ignored',Ci="Surveys module not available",du="sanitize_properties is deprecated. Use before_send instead",nh="Invalid value for property_denylist config: ",Vm=["token","distinct_id",cf],Kn="posthog",ih=!Am&&Ge?.indexOf("MSIE")===-1&&Ge?.indexOf("Mozilla")===-1,Bo=t=>{var e;return I({api_host:"https://us.i.posthog.com",flags_api_host:null,ui_host:null,asset_host:null,token:"",autocapture:!0,cross_subdomain_cookie:Gg(P?.location),persistence:"localStorage+cookie",persistence_name:"",cookie_persisted_properties:[],loaded:vs,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:me&&X(me?.search)&&me.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:wa,before_send:void 0,get_current_url:void 0,request_queue_config:{flush_interval_ms:Pa},error_tracking:{},_onCapture:vs},(n=>({rageclick:n&&n>="2026-05-30"?{content_ignorelist:sm,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))},Gm=[["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"]],fu=t=>{var e={};for(var n of Gm){var i=n[0],r=n[1];C(t[i])||(e[r]=t[i])}var s=fe({},e,t),o=t.__preview_external_dependency_versioned_paths;return C(o)||(C(t.strict_script_versioning)&&(s.strict_script_versioning=!!o),X(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(nh+t.property_denylist)),s};class Km{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 Xe{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===Wt||this.config.cookieless_mode===Cn&&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 Km,this.mn=!1,this.version=ne.LIB_VERSION,this.yn=new Set,this.bn="",this.dn=new wl,this.sn=[],this._n=[],this._calculate_event_properties=this.calculateEventProperties.bind(this),this.config=Bo(),this.SentryIntegration=hm,this.sentryIntegration=i=>(function(r,s){var o=Cf(r,s);return{name:kf,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 Mm(this),this.pageViewManager=new Zc(this),this.rateLimiter=new Em(this),this.requestRouter=new Om(this),this.consent=new em(this),this.externalIntegrations=new Hm(this);var n=(e=Xe.__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=X(i)?{[i]:r}:i;this.setPersonProperties(o),s?.({})},set_once:(i,r,s)=>{var o=X(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!==Kn){var r,s=(r=Vi[i])!==null&&r!==void 0?r:new Xe;return s._init(e,n,i),Vi[i]=s,Vi[Kn][i]=s,s}return this._init(e,n,i)}_init(e,n,i){var r,s;n===void 0&&(n={});var o,a=X(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=Bo(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=Bo(n.defaults),u=fu(n),c=fe({},l,u,{name:i,token:a});he(l.rageclick)&&he(u.rageclick)&&(c.rageclick=fe({},l.rageclick,u.rageclick)),he(l.session_recording)&&he(u.session_recording)&&(c.session_recording=fe({},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:Ue.GZipJS;var d=this.En();if(this.persistence=new Fo(this.config,d),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new Fo(I({},this.config,{persistence:"sessionStorage"}),d,!1),this.bn="ph_"+(this.config.persistence_name||this.config.token)+"_session_registered_properties",this.config.persistence!=="memory"&&!d&&be.N()){var f=be.H(this.bn);U(f)&&f.forEach((k=>{X(k)&&this.yn.add(k)}))}else be.q(this.bn);var p=I({},this.persistence.props),h=I({},this.sessionPersistence.props);this.register({$initialization_time:new Date().toISOString()}),this.In=new Rm((k=>this.Pn(k)),this.config.request_queue_config),this.Rn=new $m(this),this.__request_queue=[];var g=this.gn();if(g||(this.sessionManager=new au(this),this.sessionPropsManager=new ou(this,this.sessionManager,this.persistence),this.sessionManager.onSessionId(((k,T,x)=>{(x!=null&&x.activityTimeout||x!=null&&x.sessionPastMaximumLength||x!=null&&x.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:I({},this.config),p,s:h}),!this.config.identity_distinct_id||(r=n.bootstrap)!=null&&r.distinctID||(n.bootstrap=I({},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(lt);if(n.bootstrap.isIdentifiedID&&v!=null&&v!==m&&E===Hn)this.identify(m);else if(n.bootstrap.isIdentifiedID&&v!=null&&v!==m&&E===_n)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(Ht()),_=n.bootstrap.isIdentifiedID?S:m;this.persistence.set_property(lt,n.bootstrap.isIdentifiedID?_n:Hn),this.register({distinct_id:m,$device_id:_})}}if(g)this.register_once({distinct_id:Er,$device_id:null},"");else if(!this.get_distinct_id()){var b=this.config.get_device_id(Ht());this.register_once({distinct_id:b,$device_id:b},""),this.persistence.set_property(lt,Hn)}return ve(w,"onpagehide"in self?"pagehide":"unload",this._handle_unload.bind(this),{passive:!1}),n.segment?(function(k,T){var x=k.config.segment;if(!x)return T();(function(F,$){var O=F.config.segment;if(!O)return $();var L=K=>{var V=()=>K.anonymousId()||Ht();F.config.get_device_id=V,K.id()&&(F.register({distinct_id:K.id(),$device_id:V()}),F.persistence.set_property(lt,_n)),$()},N=O.user();"then"in N&&je(N.then)?N.then(L):L(N)})(k,(()=>{x.register((F=>{typeof Promise<"u"&&Promise.resolve||Ao.warn("This browser does not have Promise support, and can not use the segment integration");var $=(O,L)=>{if(!L)return O;O.event.userId||O.event.anonymousId===F.get_distinct_id()||(Ao.info("No userId set, resetting PostHog"),F.reset()),O.event.userId&&O.event.userId!==F.get_distinct_id()&&(Ao.info("UserId set, identifying with PostHog"),F.identify(O.event.userId));var N=F.calculateEventProperties(L,O.event.properties);return O.event.properties=Object.assign({},N,O.event.properties),O};return{name:"PostHog JS",type:"enrichment",version:"1.0.0",isLoaded:()=>!0,load:()=>Promise.resolve(),track:O=>$(O,O.event.event),page:O=>$(O,Gn),identify:O=>$(O,Io),screen:O=>$(O,"$screen")}})(k)).then((()=>{T()}))}))})(this,(()=>this.On())):this.On(),je(this.config._onCapture)&&this.config._onCapture!==vs&&(A.warn("onCapture is deprecated. Please use `before_send` instead"),this.on("eventCaptured",(k=>this.config._onCapture(k.event,k)))),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 Jf.apply(this,arguments)})().then((k=>{k&&this.register({[So]:k})})).catch(vs),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=Xe.__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)),je(this.featureFlags.onReloading)&&je(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=I({},Xe.__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,fm)),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((p=>p.onRemoteConfig==null?void 0:p.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({[uf]:this.config.__preview_deferred_init_extensions?"deferred":"synchronous",[df]:r}),this.config.__preview_deferred_init_extensions&&A.info("PostHog extensions initialized ("+r+"ms)")}Zi(e){var n;if(!P||!P.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,Ue.GZipJS)?Ue.GZipJS:j(r.supportedCompression,Ue.Base64)?Ue.Base64:void 0),(i=r.analytics)!=null&&i.endpoint&&(this.analyticsDefaultEndpoint=r.analytics.endpoint)}this.set_config({person_profiles:this.xn?this.xn:wa}),(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&&me!=null&&me.hostname){var e=me.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 Of(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()&&Sr(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(xo),(i=this.logs)==null||i.flushLogs("sendBeacon"),(r=this.In)==null||r.unload(),(s=this.Rn)==null||s.unload()):this.zn()&&this.capture(xo,null,{transport:"sendBeacon"})}_send_request(e){this.__loaded?ih?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=I({},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=I({},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=Ue.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=>I({},E,{sent_at:v}))):I({},m,{sent_at:v})})(o.data))),o.url=su(o.url,o.method,o.compression,o.timestampMode);var p=Ur.filter((m=>!o.disableTransport||!m.transport||!o.disableTransport.includes(m.transport))),h=(r=(s=(function(m,v){for(var E=0;m.length>E;E++)if(m[E].transport===f)return m[E]})(p))==null?void 0:s.method)!==null&&r!==void 0?r:p[0].method;if(!h)throw new Error("No available transport method");var g=m=>{try{h(m)}catch(v){Gf(v)?A.warn(v):A.error(v),o.callback==null||o.callback({statusCode:0,error:v})}};f!=="sendBeacon"&&o.data&&o.compression===Ue.GZipJS&&Yp&&typeof Promise<"u"&&!jr?Pm(o).then((m=>{g(m)})).catch((m=>{if(Ic(m))return jr=!0,void g(I({},o,{compression:void 0,url:su(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 Ic(v)||E===Ed})(m)&&(jr=!0),g(o)})):h(o)})(I({},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){Oo++;try{var n,i=[],r=[],s=[];Sr(e,(a=>{if(a)if(U(n=a[0]))s.push(a);else if(je(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&&je(this[n])?s.push(a):r.push(a)}));var o=function(a,l){Sr(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{Oo--}}push(e){if(Oo>0&&U(e)&&X(e[0])){var n=Xe.prototype[e[0]];je(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)&&X(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&&!X(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,p=Fc(i?.uuid,Ht),h={uuid:p,event:e,properties:this.calculateEventProperties(e,n||{},f,p)};e===Gn&&this.config.__preview_capture_bot_pageviews&&u&&(h.event="$bot_pageview",h.properties.$browser_type="bot"),c&&(h.properties.$lib_rate_limit_remaining_tokens=c.remainingTokens);var g=e==="$feature_flag_called"&&h.properties.$feature_flag_has_experiment===!1&&this.get_property(rs)===!0;i?.$set&&!g&&(h.$set=i?.$set);var m=i?.$unset;m&&(h.$unset=m);var v,E,S,_=g?void 0:this.Vn(i?.$set_once,e!==Nc,e===Io);if(_&&(h.$set_once=_),i!=null&&i._noTruncate||(s=this.config.properties_string_max_length,o=h,a=L=>X(L)?L.slice(0,s):L,l=new Set,h=(function L(N,K){if(N!==Object(N))return a?a(N):N;if(!l.has(N)){var V;if(l.add(N),U(N))V=[],Sr(N,(R=>{V.push(L(R))}));else{var M={};ie(N,((R,Z)=>{l.has(R)||(M[Z]=L(R))})),V=M}return V}})(o)),h.timestamp=f,C(i?.timestamp)||(h.properties.$event_time_override_provided=!0,h.properties.$event_time_override_system_time=d),g&&(h.properties=(function(L,N){N===void 0&&(N=[]);var K={},V=M=>{L[M]!==void 0&&(K[M]=L[M])};return Jp.forEach(V),N.forEach(V),K})(h.properties,Vm)),e===zt.DISMISSED||e===zt.SENT){var b=n?.[To.SURVEY_ID],k=n?.[To.SURVEY_ITERATION];th({id:b,current_iteration:k}),h.$set=I({},h.$set,{[(v={id:b,current_iteration:k},E=e===zt.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===zt.SHOWN&&(h.$set=I({},h.$set,{[To.SURVEY_LAST_SEEN_DATE]:new Date().toISOString()}));if(e===bm.SHOWN){var T=n?.[Qc.TOUR_TYPE];T&&(h.$set=I({},h.$set,{[Qc.TOUR_LAST_SEEN_DATE+"/"+T]:new Date().toISOString()}))}var x=I({},h.properties.$set,h.$set);if(Kt(x)||this.setPersonPropertiesForFlags(x),!W(this.config.before_send)){var F=this.Pt(h);if(!F)return;(h=F).uuid=Fc(h.uuid,Ht)}this.dn.emit("eventCaptured",h);var $=(r=i?._url)!==null&&r!==void 0?r:this.requestRouter.endpointFor("api",this.analyticsDefaultEndpoint),O={method:"POST",url:$,data:h,compression:"best-available",timestampMode:i?._batchKey==="recordings"||/\/s\/(?:\?|$)/.test($)?"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(O):this.In.enqueue(O),h}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 zm(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=I({},n);if(a.token=this.config.token,a.$config_defaults=this.config.defaults,this.gn()&&(a[cf]=!0),e==="$snapshot"){var l=I({},this.persistence.properties(),this.sessionPersistence.properties());return a.distinct_id=l.distinct_id,(!X(a.distinct_id)&&!ke(a.distinct_id)||ea(a.distinct_id))&&A.error("Invalid distinct_id for replay event. This indicates a bug in your implementation"),a}var u,c=(function(b,k,T,x){var F,$,O,L;if(x===void 0&&(x=!1),!Ge)return{};var N,K=b?[...ai,...k||[]]:[],V=(function(Dn){for(var ze=0;Ac.length>ze;ze++){var jn=Ac[ze],Mt=jn[1],Lt=jn[0].exec(Dn),dt=Lt&&(je(Mt)?Mt(Lt,Dn):Mt);if(dt)return dt}return["",""]})(Ge),M=V[0],R=V[1],Z=(N=typeof navigator<"u"?navigator:void 0)!=null&&N.brave?{brave:!0}:{},Ce={};C(T)||(Ce.detectGoogleSearchApp=T);var oe={},ye=(F=navigator)==null||(F=F.userAgentData)==null?void 0:F.platform,$e=($=navigator)==null?void 0:$.maxTouchPoints,ae=w==null||(O=w.screen)==null?void 0:O.width,Ie=w==null||(L=w.screen)==null?void 0:L.height,Se=w?.devicePixelRatio;C(ye)||(oe.userAgentDataPlatform=ye),C($e)||(oe.maxTouchPoints=$e),C(ae)||(oe.screenWidth=ae),C(Ie)||(oe.screenHeight=Ie),C(Se)||(oe.devicePixelRatio=Se);var De,wt,ge,Ze,bt,vn,Te,Pe,$t=fe(pl({$os:M,$os_version:R,$browser:Gd(Ge,navigator.vendor,Z,Ce),$device:Pc(Ge),$device_type:(wt=Ge,ge=oe,Pe=Pc(wt),Pe===Pd||Pe===Ad||Pe==="Kobo"||Pe==="Kindle Fire"||Pe===Hd?ii:Pe===Zi||Pe===Qn||Pe===Xi||Pe===na?"Console":Pe===Rd?"Wearable":Pe?st:ge?.userAgentDataPlatform==="Android"&&((Ze=ge?.maxTouchPoints)!==null&&Ze!==void 0?Ze:0)>0?600>Math.min((bt=ge?.screenWidth)!==null&&bt!==void 0?bt:0,(vn=ge?.screenHeight)!==null&&vn!==void 0?vn:0)/((Te=ge?.devicePixelRatio)!==null&&Te!==void 0?Te:1)?st:ii:"Desktop"),$timezone:Nf(),$timezone_offset:_m()}),{$current_url:tr(x?fn(me?.href):me?.href,K,nr),$host:me?.host,$pathname:me?.pathname,$raw_user_agent:Ge.length>1e3?Ge.substring(0,997)+"...":Ge,$browser_version:gg(Ge,navigator.vendor,Z,Ce),$browser_language:Xc(),$browser_language_prefix:(De=Xc(),typeof De=="string"?De.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&&($t.$sdk_dist_channel=ne.SDK_DIST_CHANNEL),$t})(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&&fe(a,this.sessionPropsManager.getSessionProps());try{var p;this.sessionRecording&&fe(a,this.sessionRecording.sdkDebugProperties),a.$sdk_debug_retry_queue_size=(p=this.Rn)==null?void 0:p.length}catch(b){a.$sdk_debug_error_capturing_properties=String(b)}if(this.requestRouter.region===Fa&&(a.$lib_custom_api_host=this.config.api_host),u=e!==Gn||s?e!==xo||s?this.pageViewManager.doEvent():this.pageViewManager.doPageLeave(i):this.pageViewManager.doPageView(i,r),a=fe(a,u),e===Gn&&P&&(a.title=P.title),!C(o)){var h=i.getTime()-o;a.$duration=parseFloat((h/1e3).toFixed(3))}Ge&&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"],(b=>{b in g&&delete m[b]}));var v={};if(this._n.length>0)for(var E of this._n.slice())try{fe(v,E())}catch(b){A.error("Failed to produce browser extension event properties",b)}(a=fe({},c,g,m,I({},v,a))).$is_identified=this._isIdentified(),U(this.config.property_denylist)?ie(this.config.property_denylist,(function(b){delete a[b]})):A.error(nh+this.config.property_denylist+" or property_blacklist config: "+this.config.property_blacklist);var S=this.config.sanitize_properties;S&&(A.error(du),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=fe({},s,o||{},e||{}),l=this.config.sanitize_properties;return l&&(A.error(du),a=l(a,"$set_once")),n&&(this.mn=!0),Kt(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||!be.N())be.q(this.bn);else{var n=[];this.yn.forEach((i=>n.push(i))),n.length>0?be.F(this.bn,n):be.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:Ci}),()=>{})}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:Ci})}getActiveMatchingSurveys(e,n){n===void 0&&(n=!1),this.surveys?this.surveys.getActiveMatchingSurveys(e,n):e([],{isLoaded:!1,error:Ci})}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:Ci}}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:Ci})}Jn(e){return!e||ea(e)?(A.critical("Unique user id has not been set in posthog.identify"),!1):e===Er?(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(ke(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(Qi)||this.register_once({$had_persisted_distinct_id:!0,$device_id:r},""),e!==r&&e!==this.get_property($i)&&(this.unregister($i),this.register({distinct_id:e}));var s,o=(this.persistence.get_property(lt)||Hn)===Hn,a=e!==r,l=!a&&o;if(a&&o)this.persistence.set_property(lt,_n),this.setPersonPropertiesForFlags({$set:n||{},$set_once:i||{}},!1),this.capture(Io,{distinct_id:e,$anon_distinct_id:r},{$set:n||{},$set_once:i||{}}),this.Sn=No(e,n,i),(s=this.featureFlags)==null||s.setAnonymousDistinctId(r);else if(l){this.persistence.set_property(lt,_n);var u=n||{},c=i||{};this.setPersonPropertiesForFlags({$set:u,$set_once:c},!1),this.capture("$set",{$set:u,$set_once:c}),this.Sn=No(e,n,i)}else(n||i)&&this.setPersonProperties(n,i);a?(this.reloadFeatureFlags(),this.featureFlags?this.featureFlags.resetFlagCallReported():this.unregister(An)):l&&(n||i)&&this.reloadFeatureFlags()}}setPersonProperties(e,n){if((e||n)&&this.Gn("posthog.setPersonProperties")){var i=No(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=>X(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:I({},r,{[e]:n})}),s||i){var o={$group_type:e,$group_key:n};i&&(o.$group_set=i),this.capture(Nc,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 p,h=this.get_property(Qi),g=this.get_property(So),m=this.get_property(Pn),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)||(p=this.persistence)==null||p.register({[Pn]: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(lt,Hn),(f=this.sessionManager)==null||f.resetSessionId(),this.Sn=null,this.config.cookieless_mode===Wt)this.register_once({distinct_id:Er,$device_id:null},"");else{var E=this.config.get_device_id(Ht());this.register_once({distinct_id:E,$device_id:e?E:h},""),e||C(g)||this.register({[So]: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 se((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(nf)?(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($i,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=I({},this.config);if(he(e)){var i,r,s,o,a,l,u,c,d,f,p,h;fe(this.config,fu(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 Fo(I({},this.config,{persistence:"sessionStorage"}),g,!1);var m=this.Cn(this.config.debug);mt(m)&&(this.config.debug=m),mt(this.config.debug)&&(this.config.debug?(ne.DEBUG=!0,le.N()&&le.F("ph_debug",!0),A.info("set_config",{config:e,oldConfig:n,newConfig:I({},this.config)})):(ne.DEBUG=!1,le.N()&&le.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(),(p=this.surveys)==null||p.loadIfEnabled(),this.es(),(h=this.externalIntegrations)==null||h.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(I({},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:Xe.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:Kn;return n!==Kn&&(n=Kn+"."+n),n}_isIdentified(){var e,n;return((e=this.persistence)==null?void 0:e.get_property(lt))===_n||((n=this.sessionPersistence)==null?void 0:n.get_property(lt))===_n}Zn(){var e,n;return!(this.config.person_profiles==="never"||this.config.person_profiles===wa&&!this._isIdentified()&&Kt(this.getGroups())&&((e=this.persistence)==null||(e=e.props)==null||!e[$i])&&((n=this.persistence)==null||(n=n.props)==null||!n[as]))}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(as,!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!==Cn)}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!==Wt){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 au(this),this.pageViewManager=new Zc(this),this.persistence&&(this.sessionPropsManager=new ou(this,this.sessionManager,this.persistence));var l,u=(s=(o=this.config.__extensionClasses)==null?void 0:o.sessionRecording)!==null&&s!==void 0?s:(a=Xe.__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==Cn&&((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(uu)}opt_out_capturing(){var e,n,i;this.config.cookieless_mode!==Wt?(this.config.cookieless_mode===Cn&&this.consent.isOptedIn()&&this.Yn(!0,!0),this.consent.optInOut(!1),this.es(),this.config.cookieless_mode===Cn&&(this.register({distinct_id:Er,$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(uu)}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===Wt||(this.config.cookieless_mode===Cn?this.consent.isRejected()||this.consent.isOptedIn():!this.has_opted_out_capturing())}clear_opt_in_out_capturing(){this.consent.reset(),this.es()}_is_bot(){return He?Yf(He,this.config.custom_blocked_useragents):void 0}Hn(){P&&(P.visibilityState==="visible"?this.wn||(this.wn=!0,this.capture(Gn,{title:P.title},{send_instantly:!0}),this.kn&&(P.removeEventListener(ls,this.kn),this.kn=null)):this.kn||(this.kn=this.Hn.bind(this),ve(P,ls,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&&!W(n[i]),l=r in n&&!W(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(W(this.config.before_send))return e;var i=Object.keys((n=e.properties)!==null&&n!==void 0?n:{}).filter(ig),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),W(s)){var a="Event '"+e.event+"' was rejected in beforeSend function";return ng(e.event)?A.warn(a+". This can cause unexpected behavior."):A.info(a),null}s.properties&&!Kt(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&&W(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=mt(e)&&!e,i=le.N()&&le.P("ph_debug")==="true";return!n&&(!!i||e)}}Xe.__defaultExtensionClasses={},Xe.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]]=zg(t.prototype[e[n]])})(Xe,["identify"]);class hu{constructor(e){this.disabled=e===!1;var n=he(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 Do="$copy_autocapture",jo=pe("[AutoCapture]");function Uo(t,e){return e.length>t?e.slice(0,t)+"...":e}function Ym(t){if(t.previousElementSibling)return t.previousElementSibling;var e=t;do e=e.previousSibling;while(e&&!hn(e));return e}function Jm(t,e){var n,i,r=e.e,s=e.maskAllElementAttributes,o=e.maskAllText,a=e.elementAttributeIgnoreList,l=e.elementsChainAsString,u=e.disableCaptureUrlHashes;if(!hn(t))return{props:{}};for(var c=[t],d=new Set([t]),f=t;f.parentNode&&!tt(f,"body")&&yf>c.length;)if(_f(f.parentNode)){var p=f.parentNode.host;if(d.has(p))break;d.add(p),c.push(p),f=p}else{if(!hn(f.parentNode)||d.has(f.parentNode))break;d.add(f.parentNode),c.push(f.parentNode),f=f.parentNode}var h,g,m=[],v={},E=!1,S=!1;if(ie(c,(x=>{var F=Sa(x);if(tt(x,"a")){var $=x.getAttribute("href");E=!!(F&&$&&qi($))&&(u?fn($):$)}j(ds(x),"ph-no-capture")&&(S=!0),m.push((function(L,N,K,V,M){M===void 0&&(M=!1);var R=L.tagName.toLowerCase(),Z={tag_name:R};ml.indexOf(R)>-1&&!K&&(Z.$el_text=R.toLowerCase()==="a"||R.toLowerCase()==="button"?Uo(1024,Kc(L)):Uo(1024,er(L)));var Ce=ds(L);Ce.length>0&&(Z.classes=Ce.filter((function(ae){return ae!==""}))),ie(L.attributes,(function(ae){var Ie;if((!xf(L)||["name","id","class","aria-label"].indexOf(ae.name)!==-1)&&(V==null||!V.includes(ae.name))&&!N&&qi(ae.value)&&(!X(Ie=ae.name)||Ie.substring(0,10)!=="_ngcontent"&&Ie.substring(0,7)!=="_nghost")){var Se=ae.value;ae.name==="class"&&(Se=gl(Se).join(" ")),Z["attr__"+ae.name]=Uo(1024,ae.name==="href"&&M?fn(Se):Se)}}));for(var oe=1,ye=1,$e=L;$e=Ym($e);)oe++,$e.tagName===L.tagName&&ye++;return Z.nth_child=oe,Z.nth_of_type=ye,Z})(x,s,o,a,u));var O=(function(L){if(!Sa(L))return{};var N={};return ie(L.attributes,(function(K){if(K.name&&K.name.indexOf("data-ph-capture-attribute")===0){var V=K.name.replace("data-ph-capture-attribute-",""),M=K.value;V&&M&&qi(M)&&(N[V]=M)}})),N})(x);fe(v,O)})),S)return{props:{},explicitNoCapture:S};if(o||(m[0].$el_text=tt(t,"a")||tt(t,"button")?Kc(t):er(t)),E){var _,b;m[0].attr__href=E;var k=(_=fs(E))==null?void 0:_.host,T=w==null||(b=w.location)==null?void 0:b.host;k&&T&&k!==T&&(h=E)}return{props:fe({$event_type:r.type,$ce_version:1},l?{}:{$elements:m},{$elements_chain:(g=m,(function(x){return x.map((F=>{var $,O,L="";if(F.tag_name&&(L+=F.tag_name),F.attr_class)for(var N of(F.attr_class.sort(),F.attr_class))L+="."+N.replace(/"/g,"");var K=I({},F.text?{text:F.text}:{},{"nth-child":($=F.nth_child)!==null&&$!==void 0?$:0,"nth-of-type":(O=F.nth_of_type)!==null&&O!==void 0?O:0},F.href?{href:F.href}:{},F.attr_id?{attr_id:F.attr_id}:{},F.attributes),V={};return Dr(K).sort(((M,R)=>M[0].localeCompare(R[0]))).forEach((M=>{var R=M[1];return V[Yc(M[0].toString())]=Yc(R.toString())})),(L+=":")+Dr(V).map((M=>M[0]+'="'+M[1]+'"')).join("")})).join(";")})((function(x){return x.map((F=>{var $,O,L={text:($=F.$el_text)==null?void 0:$.slice(0,400),tag_name:F.tag_name,href:(O=F.attr__href)==null?void 0:O.slice(0,2048),attr_class:um(F),attr_id:F.attr__id,nth_child:F.nth_child,nth_of_type:F.nth_of_type,attributes:{}};return Dr(F).filter((N=>N[0].indexOf("attr__")===0)).forEach((N=>L.attributes[N[0]]=N[1])),L}))})(g)))},(n=m[0])!=null&&n.$el_text?{$el_text:(i=m[0])==null?void 0:i.$el_text}:{},h&&r.type==="click"?{$external_click_url:h}:{},v)}}var Ai=pe("[ExceptionAutocapture]"),pu=()=>{},Zm=pe("[TracingHeaders]"),bn=pe("[Web Vitals]"),gu=9e5,mu="disabled",vu="lazy_loading",Pi="awaiting_config",Pr="missing_config";pe("[SessionRecording]"),pe("[SessionRecording]");var Ra="[SessionRecording]",Bt=pe(Ra),Xm=pe("[Heatmaps]");function Ho(t){return he(t)&&"clientX"in t&&"clientY"in t&&ke(t.clientX)&&ke(t.clientY)}var Fr=pe("[Product Tours]"),Wo=t=>{var e;return!t.config.disable_product_tours&&!((e=t.persistence)==null||!e.get_property(dl))},Qm=["$set_once","$set"],Et=pe("[SiteApps]"),_u="Error while initializing PostHog app with config id ";function zn(t,e,n){if(W(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 ev{constructor(e){this.ns=new wl,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"||!zn(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=>zn(a.href,n.href,n.href_matching||"exact")));var s,o=(e==null||(i=e.properties)==null?void 0:i.$elements_chain)||"";return!!o&&zn((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=>zn(u.text,n.text,n.text_matching||"exact")||zn(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;!W(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=>zn(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||Xf(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 tv{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&&Xf(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===Si.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 ev(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,Si.Activation),this.ks=this.Ps(e,Si.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,Si.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,Si.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(I({},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&&(Kt(i)?this.Es():this.Ts(i))}}Ks(){this.Ms()&&this.Es()}getActivationTimestamp(e){if(this.zs().includes(e)){var n=this.Qs()[e];return ke(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=>ke(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 nv extends tv{constructor(e){super(e)}Js(){return ga}Ys(){return Nr}Ms(){return Or}Ts(e){var n;(n=this._instance)==null||(n=n.persistence)==null||n.register({[Or]:e})}Es(){var e;(e=this._instance)==null||(e=e.persistence)==null||e.unregister(Or)}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 ke(r)&&r>0}ra(){return zt.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 Q}Ws(e){var n;(n=this._instance)==null||(n=n.persistence)==null||n.register({[ga]:e})}Xs(e){var n;(n=this._instance)==null||(n=n.persistence)==null||n.register({[Nr]:e})}ta(){var e;(e=this._instance)==null||(e=e.persistence)==null||e.unregister(Nr)}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 Qf(s)&&!((o=s.conditions)==null||(o=o.events)==null||!o.repeatedActivation)||s.schedule==="always"})(i);return r?e===zt.SHOWN?"consume":"ignore":e===zt.SHOWN?"persist":e===zt.DISMISSED||e===zt.SENT?"consume":"ignore"}getSurveys(){return this.getActivatedIds()}getEventToSurveys(){return this.getEventToItemsMap()}}var Rr="SDK is not enabled or survey functionality is not yet loaded",yu="Disabled. Not loading surveys.",iv=w!=null&&w.location?hs(w.location.hash,"__posthog")||hs(location.hash,"state"):null,wu="_postHogToolbarParams",bu=pe("[Toolbar]"),Eu=pe("[FeatureFlags]");class rv{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||(Eu.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)||Eu.error("Invalid flag_keys found:",e.flag_keys,"Expected array of non-empty strings")}get(){return this.sa}}var Su=pe("[FeatureFlags]"),En=pe("[FeatureFlags]",{debugEnabled:!0}),qo=`" failed. Feature flags didn't load in time.`,xu="connection_error",Iu=t=>{for(var e={},n=0;t.length>n;n++)e[t[n]]=!0;return e},ku=t=>{var e={};for(var n of Dr(t||{})){var i=n[1];i&&(e[n[0]]=i)}return e},St=pe("[Error tracking]"),Cu="Refusing to render web experiment since the viewer is a likely bot",sv={icontains:(t,e)=>e.toLowerCase().indexOf(t.toLowerCase())>-1,not_icontains:(t,e)=>e.toLowerCase().indexOf(t.toLowerCase())===-1,regex:(t,e)=>ms(e,t),not_regex:(t,e)=>!ms(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);X(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(Cu);else if(!this.Ne.disable_web_experiments){if(W(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=oi(e?.search,"__experiment_id"),i=oi(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!W(e.conditions)&&Me.da(e,n)&&Me.va(e)}static da(e,n){var i;if(W(e.conditions)||W((i=e.conditions)==null?void 0:i.url))return!0;var r=Me.getWindowLocation();if(r){var s,o,a,l=gf(n,r.href);return(s=e.conditions)==null||!s.url||sv[(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(W(e.conditions)||W((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,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,h=(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&&h&&g&&p}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(Cu):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 He&&this._instance?Yf(He,this.Ne.custom_blocked_useragents):void 0}}var at=pe("[Conversations]"),Sn="Conversations not available yet.",Au="console",rh="__posthogHandledLogsRequestError",zo=(t,e)=>{var n=t instanceof Error?t:new Error(e);return n[rh]=!0,n},Pu=t=>!!t&&typeof t=="object"&&t[rh]===!0,Ls={featureFlags:class{constructor(t){this.name="featureFlags",this.ca=!1,this.featureFlagEventHandlers=[],this.rt=Su,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 rv(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&&ve(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[Li,Ni,Lr,It]){var n=this.Oa(e);C(n)||(t[e]=n)}this.fa=t;var i=I({},t),r=this.Oa(xn);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(Wi);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(xn))!==null&&i!==void 0?i:{},o=n!=null&&n.merge&&(r=this.Oa(Ni))!==null&&r!==void 0?r:{},a=I({},s,t),l=I({},o,e),u={};for(var c of Object.entries(a)){var d=c[0],f=c[1];u[d]={key:d,enabled:bc(f),variant:Ec(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(ha),e=this.Oa(It),n=this.Oa(In);if(!n&&!e)return t||{};var i=fe({},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],p=I({},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),f&&(p.metadata=I({},l?.metadata,{payload:f,original_payload:l==null||(a=l.metadata)==null?void 0:a.payload})),i[s]=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:bc(i),variant:Ec(i),payload:wc(e[n])}}))}getFlagVariants(){var t=this.Oa(xn),e=this.Oa(It);if(!e)return t||{};for(var n=fe({},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(Ni),e=this.Oa(In);if(!e)return t||{};for(var n=fe({},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(An)}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:I({},e.initialPersonProperties,this.Oa(jt)||{},{$lib:e.library.name,$lib_version:e.library.version}),group_properties:this.Oa(kn),timezone:Nf()};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({[Br]:[xu]}),this.rt.error("Feature flag request failed",c)),l()};try{e.sendRequest(o,{target:"flags",method:"POST",body:n,compression:this.Ne.compression==="base64"?Ue.Base64:void 0,sentAt:"body",timeoutMs:this.Ne.requestTimeoutMs}).then((c=>{var d,f,p=(d=c.json)!==null&&d!==void 0?d:{},h=c.statusCode!==200;if(this.ya=!1,a===this.ba){if(this.Ua(c.statusCode),h||this.wa||(this.$anon_distinct_id=void 0),!n.disable_flags||this.wa){this.ka=!h;var g=[];c.error?g.push(c.error instanceof Error&&c.error.name==="AbortError"?"timeout":c.error instanceof Error?xu:"unknown_error"):c.statusCode!==200&&g.push("api_error_"+c.statusCode),p.errorsWhileComputingFlags&&g.push("errors_while_computing_flags");var m=!((f=p.quotaLimited)==null||!f.includes("feature_flags"));m&&g.push("quota_limited"),this.F({[Br]: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,h,{partialResponse:s}),l()}}else l()})).catch(u)}catch(c){u(c)}}}Ma(){return Af(this.Sa,3)}Ua(t){this.Sa=Pf(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+qo)}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(Lr)||void 0,u=this.Oa(Wi)||void 0,c=this.Oa(An)||{};if(this.Ne.deduplicateCallsPerSession){var d,f=(d=this.nn)==null?void 0:d.session.sessionId,p=this.Oa(Bi);f&&f!==p&&(c={},n=f)}if(e.send_event||!("send_event"in e))if(t in c&&c[t].includes(a))n&&this.F({[An]:c,[Bi]:n});else{var h,g,m,v,E,S,_,b,k,T;U(c[t])?c[t].push(a):c[t]=[a],this.F(I({[An]:c},n?{[Bi]:n}:{}));var x=this.getFeatureFlagDetails(t),F=[...(h=this.Oa(Br))!==null&&h!==void 0?h:[]];C(s)&&F.push("flag_missing");var $={$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(x==null||(v=x.metadata)==null?void 0:v.has_experiment)||($.$feature_flag_has_experiment=x.metadata.has_experiment),C(x==null||(E=x.metadata)==null?void 0:E.version)||($.$feature_flag_version=x.metadata.version);var O,L=(S=x==null||(_=x.reason)==null?void 0:_.description)!==null&&S!==void 0?S:x==null||(b=x.reason)==null?void 0:b.code;L&&($.$feature_flag_reason=L),x!=null&&(k=x.metadata)!=null&&k.id&&($.$feature_flag_id=x.metadata.id),C(x?.original_variant)&&C(x?.original_enabled)||($.$feature_flag_original_response=C(x.original_variant)?x.original_enabled:x.original_variant),x!=null&&(T=x.metadata)!=null&&T.original_payload&&($.$feature_flag_original_payload=x==null||(O=x.metadata)==null?void 0:O.original_payload),F.length&&($.$feature_flag_error=F.join(",")),this.za($)}else n&&this.F({[An]:c,[Bi]:n});if(r)return{key:t,enabled:!!s,variant:typeof s=="string"?s:void 0,payload:wc(o)}}}else this.rt.warn('getFeatureFlagResult for key "'+t+qo)}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 se((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"?Ue.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+qo),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=Su);var c=((k,T)=>{var x=k.flags;return x?I({},k,{featureFlags:Object.fromEntries(Object.keys(x).map((F=>{var $;return[F,($=x[F].variant)!==null&&$!==void 0?$:x[F].enabled]}))),featureFlagPayloads:Object.fromEntries(Object.keys(x).filter((F=>x[F].enabled)).filter((F=>{var $;return($=x[F].metadata)==null?void 0:$.payload})).map((F=>{var $;return[F,($=x[F].metadata)==null?void 0:$.payload]})))}):(k.featureFlags&&T.warn("Using an older version of the feature flags endpoint. Please upgrade your PostHog server to the latest version"),k)})(r,u),d=c.flags,f=c.featureFlags,p=c.featureFlagPayloads;if(f){var h=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{[Li]:f,[xn]:m,[rs]:!1}}var E=f,S=p,_=d;if(l!=null&&l.partialResponse)E=I({},s,E),S=I({},o,S),_=I({},a,_);else if(r.errorsWhileComputingFlags)if(d){var b=new Set(Object.keys(d).filter((k=>{var T;return!((T=d[k])!=null&&T.failed)})));E=I({},s,Object.fromEntries(Object.entries(E).filter((k=>b.has(k[0]))))),S=I({},o,Object.fromEntries(Object.entries(S||{}).filter((k=>b.has(k[0]))))),_=I({},a,Object.fromEntries(Object.entries(_||{}).filter((k=>b.has(k[0])))))}else E=I({},s,E),S=I({},o,S),_=I({},a,_);return I({[Li]:Object.keys(ku(E)),[xn]:E||{},[Ni]:S||{},[ha]:_||{},[rs]:r.minimalFlagCalledEvents===!0},h?{[Lr]:h}:{},g?{[Wi]: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,In]),this.Va(),void En.info("All overrides cleared");if(U(t))return this.F({[It]:Iu(t)}),this.Va(),void En.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[It]=U(r)?Iu(r):r),s&&(i[In]=s),Object.keys(i).length&&this.F(i),r===!1&&s===!1?this.q([It,In]):r===!1?this.q(It):s===!1&&this.q(In),this.Va(),r===!1?En.info("Flag overrides cleared"):r&&En.info("Flag overrides set",{flags:r}),void(s===!1?En.info("Payload overrides cleared"):s&&En.info("Payload overrides set",{payloads:s}))}if(t&&typeof t=="object")return this.F({[It]:t}),this.Va(),void En.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(Mr)||[]).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=I({},this.getFlagVariants(),{[t]:e});this.F({[Li]:Object.keys(ku(o)),[xn]:o,[jt]:I({},this.Oa(jt)||{},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(Mr);!i||e?this.Qa(t,n):t(i)}Qa(t,e){var n=this;return se((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({[Mr]: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(jt)||{},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({[jt]:I({},n,s,i)}),e&&this.reloadFeatureFlags()}unsetPersonPropertiesForFlags(t,e){e===void 0&&(e=!0);var n=I({},this.Oa(jt)||{});t.forEach((i=>{delete n[i]})),this.F({[jt]:n}),e&&this.reloadFeatureFlags()}resetPersonPropertiesForFlags(t){t===void 0&&(t=!0),this.q(jt),t&&this.reloadFeatureFlags()}setGroupPropertiesForFlags(t,e){e===void 0&&(e=!0);var n=this.Oa(kn)||{},i=I({},n);for(var r of Object.keys(t))i[r]=I({},n[r],t[r]);this.F({[kn]:i}),e&&this.reloadFeatureFlags()}resetGroupPropertiesForFlags(t){if(t){var e=this.Oa(kn)||{};this.F({[kn]:I({},e,{[t]:{}})})}else this.q(kn)}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}}},ov={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===Pi||this.Ya===Pr?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=mu,this.Xa=void 0,this.eo=!1,this.io=(()=>{var e;if(P==null||!P.visibilityState||P.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;P?.visibilityState==="visible"&&(this.io=!0,(e=this.Ja)==null||e.setDocumentWasEverVisible==null||e.setDocumentWasEverVisible(!0))},this._instance=t,!this._instance.sessionManager)throw Bt.error("started without valid sessionManager"),new Error(Ra+" started without valid sessionManager. This is a bug.");if(this.Ne.cookieless_mode===Wt)throw new Error(Ra+' cannot be used with cookieless_mode="always"');P!=null&&P.addEventListener&&ve(P,"visibilitychange",this.Ie)}initialize(){this.startIfEnabledOrStop()}dispose(){this.eo=!0,P==null||P.removeEventListener==null||P.removeEventListener("visibilitychange",this.Ie),this.stopRecording()}get ro(){var t,e=!((t=this._instance.get_property(Pn))==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),Bt.info("starting")):(this.Ya=mu,this.stopRecording())}}no(t){var e,n,i;this.ro&&(this.Ya!==Pi&&this.Ya!==Pr&&(this.Ya=vu),B!=null&&(e=B.__PosthogExtensions__)!=null&&(e=e.rrweb)!=null&&e.record&&(n=B.__PosthogExtensions__)!=null&&n.initSessionRecording?this.so(t):(i=B.__PosthogExtensions__)==null||i.loadExternalDependency==null||i.loadExternalDependency(this._instance,this.ao,(r=>{if(r)return Bt.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(fl),(e=this.Mr)==null||e.unregister(rf)}uo(t,e){if(W(t))return null;var n,i=ke(t)?t:parseFloat(t);return typeof(n=i)!="number"||!Number.isFinite(n)||0>n||n>1?(Bt.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;W(u)&&this.lo();var c=o?.minimumDurationMilliseconds;i.register({[Pn]:I({cache_timestamp:Date.now(),enabled:!!o},o,{networkPayloadCapture:I({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===Pi&&(this.Ya=Pr,Bt.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):Bt.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(Pn);return(n==null||(e=n.scriptConfig)==null?void 0:e.script)||"lazy-recorder"}do(){var t,e=this._instance.get_property(Pn);if(!e)return!1;try{t=typeof e=="object"?e:JSON.parse(e)}catch(n){return Bt.warn("persisted remote config for session recording is invalid and will be ignored",n),!1}return!W(t.cache_timestamp)&&36e5>=Date.now()-t.cache_timestamp}so(t){var e,n,i;if(!this.eo){if((e=B.__PosthogExtensions__)==null||!e.initSessionRecording)return Bt.warn("Called on script loaded before session recording is available. This can be caused by adblockers."),void this._instance.register_for_session({[ff]:!0});var r;if(this.Ja||(this.Ja=(r=B.__PosthogExtensions__)==null?void 0:r.initSessionRecording(this._instance,this.io),this.Ja._forceAllowLocalhostNetworkCapture=this._forceAllowLocalhostNetworkCapture),!this.do())return this.Ya===Pr||this.Ya===Pi?void 0:(this.Ya=Pi,Bt.info("persisted remote config is stale, requesting fresh config before starting"),void new Of(this._instance).load());this.Ya=vu,(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({[of]:!0}),(t=this.Ja)==null||t.overrideLinkedFlag()}overrideSampling(){var t,e;this.Ja||(e=this.Mr)==null||e.register({[sf]:!0}),(t=this.Ja)==null||t.overrideSampling()}overrideTrigger(t){var e,n;this.Ja||(n=this.Mr)==null||n.register({[t==="url"?af:lf]:!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))}}},av={autocapture:class{constructor(t){this.vo=!1,this.co=null,this.fo=!1,this.po=!1,this.instance=t,this.rageclicks=new hu(t.config.rageclick),this.mo=null}initialize(){this.startIfEnabled()}get Ne(){var t,e,n=he(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&&P){var t=n=>{n=n||w?.event;try{this.bo(n)}catch(i){jo.error("Failed to capture event",i)}};if(ve(P,"submit",t,{capture:!0}),ve(P,"change",t,{capture:!0}),ve(P,"click",t,{capture:!0}),this.Ne.capture_copied_text){var e=n=>{n=n||w?.event;try{this.bo(n,Do)}catch(i){jo.error("Failed to capture copy/cut event",i)}};ve(P,"copy",e,{capture:!0}),ve(P,"cut",e,{capture:!0})}}}else jo.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;mt(n)&&(this.instance.persistence&&this.instance.persistence.register({[oa]: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=P?.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[oa],i=this.co,r=this.instance.Qi()&&!this.fo;if(Je(i)&&!mt(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=Co(t);vf(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())&&Wc(i,this.instance.config.rageclick)&&this.bo(t,"$rageclick");var r=e===Do;if(i&&(function(d,f,p,h,g,m){var v;if(!w||vl(d)||p!=null&&p.url_allowlist&&!jc(p.url_allowlist,m)||p!=null&&p.url_ignorelist&&jc(p.url_ignorelist,m))return!1;if(p!=null&&p.dom_event_allowlist){var E=p.dom_event_allowlist;if(E&&!E.some((x=>f.type===x)))return!1}var S=Sf(d,h),_=S.parentIsUsefulElement,b=S.targetElementList;if(!(function(x,F){var $=F?.element_allowlist;if(C($))return!0;var O,L=function(K){if($.some((V=>K.tagName.toLowerCase()===V)))return{v:!0}};for(var N of x)if(O=L(N))return O.v;return!1})(b,p)||!Ea(b,p?.css_selector_allowlist)||Ea(b,(v=p?.css_selector_ignorelist)!==null&&v!==void 0?v:rm))return!1;try{var k=w.getComputedStyle(d);if(k&&k.getPropertyValue("cursor")==="pointer"&&f.type==="click")return!0}catch{}var T=d.tagName.toLowerCase();switch(T){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&&(ml.indexOf(T)>-1||d.getAttribute("contenteditable")==="true")}})(i,t,this.Ne,r,r?["copy","cut"]:void 0,this.instance)){var s=Jm(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===Do){var l,u=wf(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 je(P?.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 pu;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 je(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];je(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 pu}})(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(Gn,{navigation_type:t}),this._o=n}catch(i){A.error("Error capturing "+t+" pageview",i)}}xo(){if(!this.wo){var t=()=>{this.So("popstate")};ve(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[aa]),this.rageclicks=new hu(t.config.rageclick)}initialize(){this.startIfEnabled()}get flushIntervalMilliseconds(){var t=5e3;return he(this.Ne.capture_heatmaps)&&this.Ne.capture_heatmaps.flush_interval_milliseconds&&(t=this.Ne.capture_heatmaps.flush_interval_milliseconds),t}get isEnabled(){return W(this.Ne.capture_heatmaps)?W(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({[aa]:n}),this.Co=n,this.startIfEnabled()}}}getAndClearBuffer(){var t=this.R;return this.R=void 0,t}Io(t){Ho(t.originalEvent)&&this.ke(t.originalEvent,"deadclick")}Ie(){this.Mo&&clearInterval(this.Mo),this.Mo=P?.visibilityState==="visible"?setInterval(this.cr.bind(this),this.flushIntervalMilliseconds):null}To(){w&&P&&(this.Po=this.cr.bind(this),ve(w,cs,this.Po),this.Ro=t=>this.ke(t||w?.event),ve(P,"click",this.Ro,{capture:!0}),this.Ao=t=>this.Fo(t||w?.event),ve(P,"mousemove",this.Ao,{capture:!0}),this.Lo=new Jc(this.instance,dm,this.Io.bind(this)),this.Lo.startIfEnabledOrStop(),this.Oo=this.Ie.bind(this),ve(P,ls,this.Oo),this.vo=!0)}Eo(){var t;w&&P&&(this.Po&&w.removeEventListener(cs,this.Po),this.Ro&&P.removeEventListener("click",this.Ro,{capture:!0}),this.Ao&&P.removeEventListener("mousemove",this.Ao,{capture:!0}),this.Oo&&P.removeEventListener(ls,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&&hn(u)&&!tt(u,"body");){if(u===l)return!1;var c=void 0;try{var d,f,p;c=(d=(f=(p=u.ownerDocument)==null?void 0:p.defaultView)!==null&&f!==void 0?f:w)==null?void 0:d.getComputedStyle(u).position}catch{return!1}if(j(a,c))return!0;u=bf(u)}return!1})(Co(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"),!Dc(t.target)&&Ho(t)){var i=this.$o(t,e);(n=this.rageclicks)!=null&&n.isRageClick(t.clientX,t.clientY,new Date().getTime())&&Wc(Co(t),this.instance.config.rageclick)&&this.Vt(I({},i,{type:"rageclick"})),this.Vt(i)}}Fo(t){!Dc(t.target)&&Ho(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?fn(w.location.href):w.location.href,n=this.Ne.custom_personal_data_properties,i=this.Ne.mask_personal_data_properties?[...ai,...n||[]]:[],r=tr(e,i,nr);this.R=this.R||{},this.R[r]||(this.R[r]=[]),this.R[r].push(t)}}cr(){this.R&&!Kt(this.R)&&this.instance.capture("$$heatmap",{$heatmap_data:this.getAndClearBuffer()})}},deadClicksAutocapture:Jc,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",I({$current_url:this.R.url},this.R.metrics.reduce(((n,i)=>I({},n,{["$web_vitals_"+i.name+"_event"]:I({},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},W(n?.name)||W(n?.value))bn.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=ke(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=I({},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 bn.error("Ignoring metric with value >= "+this.Ho,n)}}},this.Uo=()=>{if(!this.vo){var n,i,r,s,o=B.__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 bn.error("web vitals callbacks not loaded - not starting")}},this._instance=t,this.Co=!((e=this._instance.persistence)==null||!e.props[da]),this.startIfEnabled()}get Wo(){return this._instance.config.capture_performance}get allowedMetrics(){var t,e,n=he(this.Wo)?(t=this.Wo)==null?void 0:t.web_vitals_allowed_metrics:void 0;return W(n)?((e=this._instance.persistence)==null?void 0:e.props[fa])||["CLS","FCP","INP","LCP"]:n}get flushToCaptureTimeoutMs(){return(he(this.Wo)?this.Wo.web_vitals_delayed_flush_ms:void 0)||5e3}get useAttribution(){var t=he(this.Wo)?this.Wo.web_vitals_attribution:void 0;return t!=null&&t}get useSoftNavs(){var t=he(this.Wo)?this.Wo.__preview_web_vitals_soft_navs:void 0;return t!=null&&t}get Ho(){var t=he(this.Wo)&&ke(this.Wo.__web_vitals_max_value)?this.Wo.__web_vitals_max_value:gu;return t>0&&6e4>=t?gu:t}get isEnabled(){var t=me?.protocol;if(t!=="http:"&&t!=="https:")return bn.info("Web Vitals are disabled on non-http/https protocols"),!1;var e=he(this.Wo)?this.Wo.web_vitals:mt(this.Wo)?this.Wo:void 0;return mt(e)?e:this.Co}startIfEnabled(){this.isEnabled&&!this.vo&&(bn.info("enabled, starting..."),this.ai(this.Uo))}onRemoteConfig(t){if(t.ok){var e=t.config;if("capturePerformance"in e){var n=he(e.capturePerformance)&&!!e.capturePerformance.web_vitals,i=he(e.capturePerformance)?e.capturePerformance.web_vitals_allowed_metrics:void 0;this._instance.persistence&&(this._instance.persistence.register({[da]:n}),this._instance.persistence.register({[fa]: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=B.__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?bn.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?fn(e):e,i=this._instance.config.custom_personal_data_properties,r=this._instance.config.mask_personal_data_properties?[...ai,...i||[]]:[];return tr(n,r,nr)}bn.error("Could not determine current URL")}}},lv={exceptionObserver:class{constructor(t){var e;this.Uo=()=>{var n;if(w&&this.isEnabled&&(n=B.__PosthogExtensions__)!=null&&n.errorWrappingFunctions){var i=B.__PosthogExtensions__.errorWrappingFunctions.wrapOnError,r=B.__PosthogExtensions__.errorWrappingFunctions.wrapUnhandledRejection,s=B.__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){Ai.error("failed to start",o),this.Qo()}}},this._instance=t,this.Ko=!((e=this._instance.persistence)==null||!e.props[la]),this.Jo=new og(I({},(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:Ai})),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 he(t)?e=I({},e,t):(C(t)?this.Ko:t)&&(e=I({},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?(Ai.info("enabled"),this.Qo(),this.ai(this.Uo)):this.Qo()}ai(t){var e,n;(e=B.__PosthogExtensions__)!=null&&e.errorWrappingFunctions?t():(n=B.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,"exception-autocapture",(i=>{if(i)return Ai.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({[la]: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)?Ai.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 Sg([new Rg,new jg,new $g,new Tg,new Bg,new Og,new Lg,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 p=Lc.test(f)?f.replace(Lc,"$1"):f;if(!p.match(/\S*Error: /)){for(var h of s){var g=h(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 I({},E,{filename:E.filename||(S=v,S[S.length-1]||{}).filename,function:E.function||si});var S}))})(u)}})("web:javascript",Cg,Fg)),this._instance=t,this.Xo=(e=(n=this._instance.persistence)==null?void 0:n.get_property(ca))!==null&&e!==void 0?e:[],this.el=is(this.il()),this.rl=new Hg(this.el)}onConfigChange(){this.el=is(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({[ca]:this.Xo,[ua]:o})}}}get nl(){var t,e=!!this._instance.get_property(ua),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(!X(t)||t.trim().length===0)return void St.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)=>Ug.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&&St.warn("Ignoring reserved exception step fields",{droppedKeys:r}),this.rl.add(I({[ts]:t,[ns]:new Date().toISOString()},i))}catch(s){St.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 St.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 St.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 St.info("Skipping exception capture because it was thrown by the PostHog SDK")}var n=this.el.enabled&&W(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 St.error("Failed to capture exception event. Dropping this exception.",o),void this.rl.clear()}}catch(o){return void St.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:I({},t,{$exception_steps:e})}catch(n){return St.error("Failed to read buffered exception steps. Capturing exception without steps.",n),t}}ll(t){this.el.enabled&&this.rl.add({[ts]:t,[ns]:new Date().toISOString()})}sl(t){return he(t)?I({},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 X(r)&&r.length>0&&n.$exception_types.push(r),X(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=Zf[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 St.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!W(t)&&U(t)}}},cv=I({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({[dl]:!!e.productTours}),!Wo(this._instance))return!this.vl&&W((n=this.Mr)==null?void 0:n.props[Oi])||Fr.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&&Wo(this._instance)&&this.ai((()=>this.fl()))}ai(t){var e,n;(e=B.__PosthogExtensions__)!=null&&e.generateProductTours?t():(n=B.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,"product-tours",(i=>{i?Fr.error("Could not load product tours script",i):t()}))}fl(){var t;!this.vl&&(t=B.__PosthogExtensions__)!=null&&t.generateProductTours&&(this.vl=B.__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[Oi];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(Wo(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||Fr.warn(o):Fr.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({[Oi]:a}),t(a,{isLoaded:!0})}else t([],{isLoaded:!0})}})}else t(this.cl,{isLoaded:!0})}getActiveProductTours(t){W(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(Oi)}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)}}},Ls),uv={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=B._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 p=t.$set_once,h=t.$set;return{event:I({},bd(t,Qm),{properties:I({},t.properties,h?{$set:I({},(e=(n=t.properties)==null?void 0:n.$set)!==null&&e!==void 0?e:{},h)}:{},p?{$set_once:I({},(i=(r=t.properties)==null?void 0:r.$set_once)!==null&&i!==void 0?i:{},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,i,r,s,o,a;if(!this._instance.config.prepare_external_dependency_stylesheet&&!this._instance.config.prepare_external_dependency_script)return()=>{};var l=P?.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,p=(m,v,E)=>{if(m!=null&&m[v]){var S=m[v];m[v]=E(S),c.push((()=>{m[v]=S}))}},h=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:h(v))).filter((v=>!Je(v)));return p(u,"appendChild",(m=>function(v){var E=h(v);return E?m.call(this,E):v})),p(u,"insertBefore",(m=>function(v,E){var S=h(v);return S?m.call(this,S,E):v})),p(u,"replaceChild",(m=>function(v,E){var S=h(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=>{p(m,"append",(v=>function(){for(var E=arguments.length,S=new Array(E),_=0;E>_;_++)S[_]=arguments[_];return v.apply(this,g(S))})),p(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=>{p(m,"before",(v=>function(){for(var E=arguments.length,S=new Array(E),_=0;E>_;_++)S[_]=arguments[_];return v.apply(this,g(S))})),p(m,"after",(v=>function(){for(var E=arguments.length,S=new Array(E),_=0;E>_;_++)S[_]=arguments[_];return v.apply(this,g(S))})),p(m,"replaceWith",(v=>function(){for(var E=arguments.length,S=new Array(E),_=0;E>_;_++)S[_]=arguments[_];var b=g(S);return S.length&&!b.length?void 0:v.apply(this,b)}))})),p((a=l.Element)==null?void 0:a.prototype,"insertAdjacentElement",(m=>function(v,E){var S=h(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&&(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,r=o=>{e.errored=!o,e.loaded=!0,Et.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){Et.error(_u+t.id,o),r(!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(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 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 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((i=s.siteApps)!=null&&i.length)if(this.isEnabled){var o=function(){var l,u=a.id,c=a.url;B["__$$ph_site_app_"+u]=r._instance,(l=B.__PosthogExtensions__)==null||l.loadSiteApp==null||l.loadSiteApp(r._instance,c,(d=>{if(d)return Et.error(_u+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.')}}}},dv={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=B.__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=B.__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=B.__PosthogExtensions__)!=null&&e.tracingHeadersPatchFns?t():(n=B.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,"tracing-headers",(i=>{if(i)return Zm.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()}}},fv=I({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 Q.warn("Remote config unavailable. Not loading surveys.");var e=t.config.surveys;if(W(e))return Q.warn("Flags not loaded yet. Not loading surveys.");var n=U(e);this.Rl=n?e.length>0:e,Q.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)Q.info("Already initializing surveys, skipping...");else if(this.Ne.disable_surveys)Q.info(yu);else if(this.Ne.cookieless_mode&&this._instance.consent.isOptedOut())Q.info("Not loading surveys in cookieless mode without consent.");else{var t=B?.__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(hl);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 Q.error("PostHog Extensions not found.")}}Dl(t,e){this._surveyManager=t(this._instance,e),this._surveyEventReceiver=new nv(this._instance),Q.info("Surveys loaded successfully"),this.Nl({isLoaded:!0})}$l(t,e){Q.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 Q.info(yu),t([]);var n,i=this._instance.get_property(pa);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?Q.error(a):r.error||Q.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((p=>(function(h){return!(!h.start_date||h.end_date)})(p)&&(Qf(p)||(function(h){var g;return!((g=h.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({[pa]:c,[ss]: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(ss);return ke(t)&&Date.now()-t>3e5}Bl(){return ke(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};th(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){Q.error("Error in survey callback",n)}}getActiveMatchingSurveys(t,e){if(e===void 0&&(e=!1),!W(this._surveyManager))return this._surveyManager.getActiveMatchingSurveys(t,e);Q.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(W(this._surveyManager))return{eligible:!1,reason:Rr};var e=typeof t=="string"?this.Hl(t):t;return e?this._surveyManager.checkSurveyEligibility(e):{eligible:!1,reason:"Survey not found"}}zl(t){if(W(this._surveyManager))return{eligible:!1,reason:Rr};var e=typeof t=="string"?this.Hl(t):t;return e?this._surveyManager.checkSurveyRenderability(e):{eligible:!1,reason:"Survey not found"}}canRenderSurvey(t){if(W(this._surveyManager))return Q.warn("init was not called"),{visible:!1,disabledReason:Rr};var e=this.zl(t);return{visible:e.eligible,disabledReason:e.reason}}canRenderSurveyAsync(t,e){return W(this._surveyManager)?(Q.warn("init was not called"),Promise.resolve({visible:!1,disabledReason:Rr})):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(W(this._surveyManager))Q.warn("init was not called");else{var r=typeof t=="string"?this.Hl(t):t;if(r!=null&&r.id)if(Bm.includes(r.type)){var s=P?.querySelector(e);if(s)return(i=r.appearance)!=null&&i.surveyPopupDelaySeconds?(Q.info("Rendering survey "+r.id+" with delay of "+r.appearance.surveyPopupDelaySeconds+" seconds"),void setTimeout((()=>{var o,a;Q.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),Q.info("Survey "+r.id+" rendered")}),1e3*r.appearance.surveyPopupDelaySeconds)):void this._surveyManager.renderSurvey(r,s,n);Q.warn("Survey element not found")}else Q.warn("Surveys of type "+r.type+" cannot be rendered in the app");else Q.warn("Survey not found")}}displaySurvey(t,e){var n;if(W(this._surveyManager))Q.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=I({},i,{appearance:I({},i.appearance,{surveyPopupDelaySeconds:0})})),e.displayType!==xa.Popover&&e.initialResponses&&Q.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 Q.warn("Survey is not eligible to be displayed: ",s.reason)}e.displayType!==xa.Inline?this._surveyManager.handlePopoverSurvey(r,e):this.renderSurvey(r,e.selector,e.properties)}else Q.warn("Survey not found")}}cancelPendingSurvey(t){W(this._surveyManager)?Q.warn("init was not called"):this._surveyManager.cancelSurvey(t)}handlePageUnload(){var t;(t=this._surveyManager)==null||t.handlePageUnload==null||t.handlePageUnload()}}},Ls),hv={toolbar:class{constructor(t){this.instance=t}Wl(t){B.ph_toolbar_state=t}Vl(){var t;return(t=B.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),ba(this.instance.config)||!w||!P)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=iv||hs(t.hash,"__posthog")||hs(t.hash,"state"),s=r?Oc((()=>JSON.parse(atob(decodeURIComponent(r)))))||Oc((()=>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(wu)||"{}")).source="localstorage",delete i.userIntent),!(!i.token||this.instance.config.token!==i.token||(this.loadToolbar(i),0))}catch{return!1}}Zl(t){var e=B.ph_load_toolbar||B.ph_load_editor;!W(e)&&je(e)?e(t,this.instance):bu.warn("No toolbar load function found")}loadToolbar(t){var e=!(P==null||!P.getElementById(mf));if(!w||e)return!1;var n=this.instance.requestRouter.region==="custom"&&this.instance.config.advanced_disable_toolbar_metrics,i=I({token:this.instance.config.token},t,{apiURL:this.instance.requestRouter.endpointFor("ui")},n?{instrument:!1}:{});if(w.localStorage.setItem(wu,JSON.stringify(I({},i,{source:void 0}))),this.Vl()===2)this.Zl(i);else if(this.Vl()===0){var r;this.Wl(1),(r=B.__PosthogExtensions__)==null||r.loadExternalDependency==null||r.loadExternalDependency(this.instance,"toolbar",(s=>{if(s)return bu.error("[Toolbar] Failed to load",s),void this.Wl(0);this.Wl(2),this.Zl(i)})),ve(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)}}},pv=I({experiments:Me},Ls),gv={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;W(e)||(mt(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||ba(this._instance.config)||this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut())){var t=B?.__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(hl);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 at.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,at.info("Conversations loaded successfully")}catch(e){this.eu("Error completing conversations initialization",e)}else at.error("Cannot complete initialization: remote config is null")}eu(t,e){at.error(t,e),this._conversationsManager=null,this.Kl=!1,this.Yl=!0}show(){this._conversationsManager?this._conversationsManager.show():at.warn("Conversations not loaded yet.")}hide(){this._conversationsManager&&this._conversationsManager.hide()}isAvailable(){return this.Ql===!0&&!Je(this._conversationsManager)}getUnavailableReason(){return this.isAvailable()?null:this._instance.config.disable_conversations?"disabled_by_config":ba(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?W(this.Jl)||!this.Jl.token?"missing_token":B!=null&&B.__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 se((function*(){return i._conversationsManager?i._conversationsManager.sendMessage(t,e,n):(at.warn(Sn),null)}))()}getMessages(t,e){var n=this;return se((function*(){return n._conversationsManager?n._conversationsManager.getMessages(t,e):(at.warn(Sn),null)}))()}markAsRead(t){var e=this;return se((function*(){return e._conversationsManager?e._conversationsManager.markAsRead(t):(at.warn(Sn),null)}))()}getTickets(t){var e=this;return se((function*(){return e._conversationsManager?e._conversationsManager.getTickets(t):(at.warn(Sn),null)}))()}requestRestoreLink(t){var e=this;return se((function*(){return e._conversationsManager?e._conversationsManager.requestRestoreLink(t):(at.warn(Sn),null)}))()}restoreFromToken(t){var e=this;return se((function*(){return e._conversationsManager?e._conversationsManager.restoreFromToken(t):(at.warn(Sn),null)}))()}restoreFromUrlToken(){var t=this;return se((function*(){return t._conversationsManager?t._conversationsManager.restoreFromUrlToken():(at.warn(Sn),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()}}},mv={logs:class{constructor(t){var e,n=this;this.iu=!1,this.ru=!1,this.rt=pe("[logs]"),this.nu=I({},this.rt,{error(){for(var i=arguments.length,r=new Array(i),s=0;i>s;s++)r[s]=arguments[s];r.some(Pu)||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&&ve(w,"online",this.au)}uu(t,e,n,i){var r,s=(function(o,a){var l,u,c,d,f,p,h,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:(p=S?.["service.version"])!==null&&p!==void 0?p:o?.serviceVersion,environment:(h=S?.["deployment.environment"])!==null&&h!==void 0?h: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 wg(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},Au);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;!W(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){Pu(t)||this.rt.error("PostHog logs flush failed:",t)}loadIfEnabled(){if(this.iu&&!this.ru){var t=B?.__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(hl)}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===Ut.LogsQueue?t():void 0,setPersistedProperty(i,r){var s;i===Ut.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(Af(this.Sa,3))e({kind:"fatal",error:zo(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:zo(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:zo(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=Pf(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,Au,(e=>{this.su=e}))}xu(t,e,n,i,r){if(e.length!==0){var s=e.map((a=>a.record));r([]);var o=Xd(s,Zd(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,W(r)||(e.sessionStartTimestamp=r),W(s)||(e.lastActivityTimestamp=s)}if(B!=null&&(t=B.location)!=null&&t.href&&(e.currentUrl=this._instance.config.disable_capture_url_hashes?fn(B.location.href):B.location.href),this._instance.featureFlags){var o=this._instance.featureFlags.getFlags();o&&o.length>0&&(e.activeFeatureFlags=o)}return e}}},vv={metrics:class{constructor(t){this.rt=pe("[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 bg(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(I({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)}}},_v=I({},Ls,ov,av,lv,cv,uv,fv,dv,hv,pv,gv,mv,vv);Xe.__defaultExtensionClasses=I({},_v);(function(){ne.SDK_DIST_CHANNEL="npm";var t=Vi[Kn]=new Xe;return(function(){function e(){e.done||(e.done=!0,ih=!1,ie(Vi,(function(n){n._dom_loaded()})))}P!=null&&P.addEventListener?P.readyState==="complete"?e():ve(P,"DOMContentLoaded",e,{capture:!1}):w&&A.error("Browser doesn't support `document.addEventListener` so PostHog couldn't be initialized")})(),t})();const yv=["a[href]","button:not([disabled])","input:not([disabled]):not([type='hidden'])","select:not([disabled])","textarea:not([disabled])","[tabindex]:not([tabindex='-1'])"].join(",");let Ke=null,_s=null,sh="";const Ta=new Map;function oh(t){return[...t.querySelectorAll(yv)].filter(e=>!e.hidden&&e.getAttribute("aria-hidden")!=="true"&&e.getClientRects().length>0)}function wv(t){for(const e of document.body.children)e===t||e.tagName==="SCRIPT"||(Ta.set(e,{inert:e.inert,ariaHidden:e.getAttribute("aria-hidden")}),e.inert=!0,e.setAttribute("aria-hidden","true"))}function bv(){for(const[t,e]of Ta)t.inert=e.inert,e.ariaHidden===null?t.removeAttribute("aria-hidden"):t.setAttribute("aria-hidden",e.ariaHidden);Ta.clear()}function ah(t){return t?.dataset.modalDismissible!=="false"&&t?.getAttribute("aria-busy")!=="true"}function We(t,e={}){const n=typeof t=="string"?document.getElementById(t):t;if(!n)return!1;const i=Ke&&Ke!==n?Ke:null,r=_s;if(i&&qe(i,{restoreFocus:!1,force:!0}),Ke!==n){let a=e.trigger||document.activeElement;a&&(i?.contains(a)||n.contains(a))&&(a=r),_s=a,sh=document.body.style.overflow,wv(n),document.body.style.overflow="hidden"}Ke=n,n.classList.add("open"),n.setAttribute("aria-hidden","false");const s=n.querySelector(".modal-content");s&&(s.style.transform="scale(1) translateY(0)");const o=()=>{if(Ke!==n)return;((e.initialFocus?n.querySelector(e.initialFocus):n.querySelector("[data-modal-initial-focus]"))||oh(n)[0]||n.querySelector(".modal-content")||n).focus({preventScroll:!0})};return requestAnimationFrame(o),setTimeout(o,260),!0}function qe(t,e={}){const n=typeof t=="string"?document.getElementById(t):t;if(!n||!e.force&&!ah(n))return!1;if(n.classList.remove("open"),n.setAttribute("aria-hidden","true"),n!==Ke)return!0;bv(),document.body.style.overflow=sh,Ke=null;const i=_s;return _s=null,e.restoreFocus!==!1&&i?.isConnected&&i.focus({preventScroll:!0}),!0}function Ev(){return!!Ke}function Fu(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 Sv(t){if(!ah(t))return;const e=t.dataset.modalCloseHandler;e&&typeof window[e]=="function"?window[e]():qe(t)}document.addEventListener("keydown",t=>{if(!Ke)return;if(t.key==="Escape"){t.preventDefault(),t.stopImmediatePropagation(),Sv(Ke);return}if(t.key!=="Tab"){t.stopPropagation();return}const e=oh(Ke);if(!e.length){t.preventDefault(),(Ke.querySelector(".modal-content")||Ke).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 xv(){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 bl=Object.freeze({free:"Free",professional:"Pro",power:"Power"}),Iv=Object.freeze({free:2,professional:50,power:2e3}),kv="(contact us)",Cv=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 ${kv}`])}),lh="CodeFile",ch="GeneratedCode",Av={CustomAction:"A",CustomWidget:"W",CustomFunction:"F",CustomClass:"C",CodeFile:"C"};function ln(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function $a(t){return String(t||"").trim().replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function Pv(t={},e=0){const n=$a(t.artifactType||t.type||lh),i=$a(t.artifactName||t.name||t.fileName||`${ch}-${e+1}`);return`${n||"artifact"}-${i||e+1}`}function uh(t={},e=0){const n=ln(t),i=n.artifactType||n.type||lh,r=n.artifactName||n.name||ch;let s=n.fileName||r;return s.endsWith(".dart")||(s+=".dart"),{id:$a(n.id)||Pv({...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:dh(n.dependencies),imports:Array.isArray(n.imports)?n.imports:[],publicApi:Array.isArray(n.publicApi)?n.publicApi:[],relationships:fh(n.relationships),deployStatus:n.deployStatus||"pending",review:n.review||null,metadata:ln(n.metadata),codeType:n.codeType||Av[i]||"O"}}function dh(t){return t?Array.isArray(t)?t.map(e=>{if(typeof e=="string")return{name:e,version:null,inferred:!1};const n=ln(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(ln(t)).map(([e,n])=>({name:e,version:n||null,inferred:!1})):[]}function fh(t){return t?(Array.isArray(t)?t:[t]).map(e=>{const n=ln(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 ir(t,e={}){const n=[],i=typeof t=="string"?Ma(t):t,s=ln(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)=>uh(d,f)),l=new Map(o.map((d,f)=>[ln(d).id,a[f]?.id]).filter(([d,f])=>d&&f)),u=d=>l.get(d)||d,c=fh(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:dh(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:ln(s.metadata)}}function ci(t){return ir(t).artifacts[0]||uh()}function Zt(t){if(typeof t!="string")return t??"";const e=t.trim();if(!e)return"";try{return JSON.parse(e)}catch{return t}}function ui(t){return JSON.stringify(t,null,2)}function Fv(t){return ui({task:"architect",userRequest:String(t??"")})}function Rv(t){const e=Zt(t);return e&&typeof e=="object"&&typeof e.task=="string"?ui(e):ui({task:"generate_bundle",bundleSpec:e})}function Tv(t){return ui({task:"review_bundle",generatedBundle:Zt(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=Zt(e)),n}function $v({bundleSpec:t,artifactBundle:e,bundleReview:n,artifactId:i,userFeedback:r}){return ui({task:"regenerate_artifact",artifactId:i,bundleSpec:Zt(t),artifactBundle:Zt(e),bundleReview:Zt(n),userFeedback:String(r)})}function hh({bundleSpec:t,artifactBundle:e,bundleReview:n,userFeedback:i}){return ui({task:"regenerate_bundle",bundleSpec:Zt(t),artifactBundle:Zt(e),bundleReview:Zt(n),userFeedback:String(i??"")})}const Ru={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"},Mv=["sanitizationResult","modelArmor","modelArmorResult","data","result","error"];function nt(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function Lv(t){return nt(t)?typeof t.filterMatchState=="string"||typeof t.invocationResult=="string"||Array.isArray(t.matchedFilters)||nt(t.filterSummary)||nt(t.filterResults):!1}function ph(t,e=0){if(!nt(t)||e>3)return null;if(Lv(t))return t;for(const n of Mv){const i=t[n];if(nt(i)){const r=ph(i,e+1);if(r)return r}}return null}function ys(t){return Array.isArray(t)?t.some(ys):nt(t)?t.matched===!0||t.matchState==="MATCH_FOUND"?!0:Object.values(t).some(ys):!1}function La(t){return Array.isArray(t)?t.some(La):nt(t)?typeof t.executionState=="string"&&t.executionState!=="EXECUTION_SUCCESS"?!0:Object.values(t).some(La):!1}function gh(t){return{csamFilterFilterResult:"csam",maliciousUriFilterResult:"malicious_uris",piAndJailbreakFilterResult:"pi_and_jailbreak",raiFilterResult:"rai",sdpFilterResult:"sdp",virusScanFilterResult:"virus_scan"}[t]||t}function Nv(t,e){if(nt(t))for(const[n,i]of Object.entries(t)){if(!nt(i))continue;const r=nt(i.categories)?i.categories:{},s=Object.entries(r).filter(([,o])=>nt(o)&&o.matched===!0).map(([o])=>o);s.length>0?s.forEach(o=>e.add(o)):i.matched===!0&&e.add(gh(n))}}function Ov(t,e){if(!t)return;const n=Array.isArray(t)?t.flatMap(i=>nt(i)?Object.entries(i):[]):Object.entries(t);for(const[i,r]of n){if(!ys(r))continue;const s=gh(i),o=r?.raiFilterResult?.raiFilterTypeResults||(s==="rai"?r?.raiFilterTypeResults:null),a=nt(o)?Object.entries(o).filter(([,l])=>ys(l)).map(([l])=>l):[];a.length>0?a.forEach(l=>e.add(l)):e.add(s)}}function Bv(t){return Ru[t]?Ru[t]:String(t).replace(/([a-z])([A-Z])/g,"$1 $2").replace(/_/g," ").toLowerCase()}function Tu(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 Dv(t){const e=ph(t);if(!e)return null;const n=new Set(Array.isArray(e.matchedFilters)?e.matchedFilters:[]);Nv(e.filterSummary,n),Ov(e.filterResults,n);const i=e.blocked===!0||e.filterMatchState==="MATCH_FOUND"||n.size>0,r=e.invocationResult||null,s=La(e.filterSummary||e.filterResults);return!i&&!s&&!["PARTIAL","FAILURE"].includes(r)?null:{kind:i?"blocked":"unavailable",invocationResult:r,matchedFilters:[...n]}}function jv(t,e){const n=Dv(t);if(!n)return null;const i=[...new Set(n.matchedFilters.map(Bv))],r=n.kind==="blocked",s=new Error(r?`Safety screening blocked this pipeline step for ${Tu(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 ${Tu(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 Uv(t){return String(t||"").replace(/\/\*[\s\S]*?\*\//g,"").replace(/\/\/[^\n]*/g,"")}function $u(t){const e=/^(import|export|part|library|class|enum|extension|typedef|mixin|abstract|const|final|var|late)\b/,n=[];for(const i of Uv(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 Sl(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 Mu(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=Sl(o,a.type),u={old_identifier_name:l,new_identifier_name:l,type:a.type,is_deleted:!1,current_checksum:await Mu(a.content)},c=e.get(a.path);if(c!==void 0&&(u.original_checksum=await Mu(c)),n[o]=u,a.type==="F"){const d=$u(a.content);(d.length>0?d:[a.functionName].filter(Boolean)).forEach(p=>i.add(p))}}const r=new Set($u(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 Wv=new Set(["CustomWidget","CustomAction","CustomFunction","CustomClass","CodeFile"]),Lu={CustomWidget:"custom_code/widgets/",CustomAction:"custom_code/actions/",CustomFunction:"flutter_flow/custom_functions.dart",CustomClass:"custom_code/",CodeFile:"custom_code/"},qv=new Set(["void","dynamic","String","int","double","num","bool","Color","DateTime","DateTimeRange","LatLng","FFPlace","FFUploadedFile","DocumentReference","List"]),zv=["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=>Vo(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=>Vo(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; @@ -25,52 +25,53 @@ class _S extends State { @override Widget build(BuildContext c) => const Size @override _S createState() => _S(); } class _S extends State { @override Widget build(BuildContext c) => Padding(padding: const EdgeInsets.all(8), child: const SizedBox()); }`}];function xt(t,e,n){return{artifactId:t.id,artifactName:t.artifactName,artifactType:t.artifactType,severity:e,message:n}}function rr(t){let e="",n=0;for(;n"&&(n--,n===0))return{inner:t.slice(e+1,i),end:i+1};return null}function Wv(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;rzv(t).usable);function Vv(t=""){const e=rr(t);return qv.filter(n=>n.detect(e)).map(({id:n,severity:i,message:r})=>({id:n,severity:i,message:r}))}function Gv(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=Hv(t,r);if(!u||(s=u.inner.replace(/\s+/g," ").trim(),r=u.end,!/\s/.test(t[r]||"")))continue;for(;rLu(o.functionName)===i);if(r)return r;const s=o=>!o.functionName.startsWith("_");return n.find(s)||n[0]}function Ms(t=""){return Array.from(rr(t).matchAll(/\b(?:class|enum)\s+([A-Za-z_]\w*)/g),e=>e[1])}function Kv(t="",e=""){return xl(t,e)?.returnType||null}function Nu(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 Yv(t,e){const n=Ms(e);if(n.length===0)return null;const r=String(t||"").split("/").pop().replace(/\.dart$/,"");if(n.some(l=>Nu(l)===r)||n.length>1)return null;const[o]=n,a=`${Nu(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 Jv(t,e,n=""){const i=xl(e,n)?.functionName;if(!i)return null;const r=String(t||"").split("/").pop(),s=Sl(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 Zv(t="",e=""){return xl(t,e)!==null}function Xv(t,e=new Set){return(t?.match(/[A-Za-z_]\w*/g)||[]).filter(i=>Dv.has(i)?!1:!jv.some(s=>i.endsWith(s))||e.has(i))}function Qv(t,{functionName:e="",declaredTypes:n=new Set}={}){const i=Kv(t,e),r=Xv(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 e_(t,e={}){const n=[],i=t.fileName||"",r=t.code||"";if(Bv.has(t.artifactType)||n.push(xt(t,"error",`Unsupported artifact type "${t.artifactType}".`)),i.endsWith(".dart")||n.push(xt(t,"error","FlutterFlow custom code artifacts must use .dart files.")),!r.trim())return n.push(xt(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(xt(t,"warning","CustomWidget code should declare a widget class extending StatelessWidget or StatefulWidget."));for(const s of Vv(r))n.push(xt(t,s.severity,s.message))}if(t.artifactType==="CustomAction"&&!Zv(r,t.artifactName)&&n.push(xt(t,"warning","CustomAction code should expose an async Future function callable from FlutterFlow.")),t.artifactType==="CustomAction"){const s=e.declaredTypes||new Set(Ms(r)),o=Qv(r,{functionName:t.artifactName,declaredTypes:s});o&&n.push(xt(t,"error",o));const a=Jv(i,r,t.artifactName);a&&n.push(xt(t,"error",a))}if(t.artifactType==="CustomFunction"&&/class\s+\w+\s+extends\s+(StatelessWidget|StatefulWidget)/.test(r)&&n.push(xt(t,"warning","CustomFunction should be a callable function, not a widget class.")),t.artifactType==="CustomClass"||t.artifactType==="CodeFile"){const s=Yv(i,r);s&&n.push(xt(t,"info",s))}return n}function t_(t){const e=Array.isArray(t?.artifacts)?t.artifacts:[],n=new Set(e.flatMap(s=>Ms(s.code||""))),i=e.flatMap(s=>e_(s,{declaredTypes:n})),r=e.map(s=>({artifactId:s.id,fileName:s.fileName,pathHint:Mu[s.artifactType]||Mu.CodeFile}));return{valid:i.every(s=>s.severity!=="error"),findings:i,deployHints:r}}const Ou="// DO NOT REMOVE OR MODIFY THE CODE ABOVE!";function Bu(t){return(/^\s*import\s+['"]([^'"]+)['"]/.exec(t)||[])[1]||null}function n_(t=""){const e=t.indexOf(Ou);return e===-1?t:t.slice(e+Ou.length).replace(/^\s*\n/,"")}const i_=/^\s*import\s+['"][^'"]+['"]\s*;\s*(?:\/\/.*)?$/;function r_(t="",e=""){const n=n_(t),i=new Set((e.match(/^\s*import .*$/gm)||[]).map(Bu).filter(Boolean)),r=n.split(` -`).filter(s=>{const o=Bu(s);return o===null||!i.has(o)?!0:!i_.test(s)}).join(` -`).replace(/^\s*\/\/ Automatic FlutterFlow imports\s*$/m,"").replace(/^\s*\n+/,"");return e+r}const s_=new Set(["flutter","flutter_test","flutter_driver","flutter_localizations"]);function gh(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 u_(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 d_(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=c_(h),g=h.fixedCode||h.code||"",m=h.codeType||a_[h.artifactType]||Qe.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||l_(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===Qe.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} +`;)n++;e+=" "}else if(i==="/*"){for(n+=2;n"&&(n--,n===0))return{inner:t.slice(e+1,i),end:i+1};return null}function Kv(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;rYv(t).usable);function Zv(t=""){const e=rr(t);return Jv.filter(n=>n.detect(e)).map(({id:n,severity:i,message:r})=>({id:n,severity:i,message:r}))}function Xv(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=Gv(t,r);if(!u||(s=u.inner.replace(/\s+/g," ").trim(),r=u.end,!/\s/.test(t[r]||"")))continue;for(;rNu(o.functionName)===i);if(r)return r;const s=o=>!o.functionName.startsWith("_");return n.find(s)||n[0]}function Ns(t=""){return Array.from(rr(t).matchAll(/\b(?:class|enum)\s+([A-Za-z_]\w*)/g),e=>e[1])}function Qv(t="",e=""){return xl(t,e)?.returnType||null}function Ou(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 e_(t,e){const n=Ns(e);if(n.length===0)return null;const r=String(t||"").split("/").pop().replace(/\.dart$/,"");if(n.some(l=>Ou(l)===r)||n.length>1)return null;const[o]=n,a=`${Ou(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 t_(t,e,n=""){const i=xl(e,n)?.functionName;if(!i)return null;const r=String(t||"").split("/").pop(),s=Sl(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 n_(t="",e=""){return xl(t,e)!==null}function i_(t,e=new Set){return(t?.match(/[A-Za-z_]\w*/g)||[]).filter(i=>qv.has(i)?!1:!zv.some(s=>i.endsWith(s))||e.has(i))}function r_(t,{functionName:e="",declaredTypes:n=new Set}={}){const i=Qv(t,e),r=i_(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 s_(t,e={}){const n=[],i=t.fileName||"",r=t.code||"";if(Wv.has(t.artifactType)||n.push(xt(t,"error",`Unsupported artifact type "${t.artifactType}".`)),i.endsWith(".dart")||n.push(xt(t,"error","FlutterFlow custom code artifacts must use .dart files.")),!r.trim())return n.push(xt(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(xt(t,"warning","CustomWidget code should declare a widget class extending StatelessWidget or StatefulWidget."));for(const s of Zv(r))n.push(xt(t,s.severity,s.message))}if(t.artifactType==="CustomAction"&&!n_(r,t.artifactName)&&n.push(xt(t,"warning","CustomAction code should expose an async Future function callable from FlutterFlow.")),t.artifactType==="CustomAction"){const s=e.declaredTypes||new Set(Ns(r)),o=r_(r,{functionName:t.artifactName,declaredTypes:s});o&&n.push(xt(t,"error",o));const a=t_(i,r,t.artifactName);a&&n.push(xt(t,"error",a))}if(t.artifactType==="CustomFunction"&&/class\s+\w+\s+extends\s+(StatelessWidget|StatefulWidget)/.test(r)&&n.push(xt(t,"warning","CustomFunction should be a callable function, not a widget class.")),t.artifactType==="CustomClass"||t.artifactType==="CodeFile"){const s=e_(i,r);s&&n.push(xt(t,"info",s))}return n}function o_(t){const e=Array.isArray(t?.artifacts)?t.artifacts:[],n=new Set(e.flatMap(s=>Ns(s.code||""))),i=e.flatMap(s=>s_(s,{declaredTypes:n})),r=e.map(s=>({artifactId:s.id,fileName:s.fileName,pathHint:Lu[s.artifactType]||Lu.CodeFile}));return{valid:i.every(s=>s.severity!=="error"),findings:i,deployHints:r}}const Bu="// DO NOT REMOVE OR MODIFY THE CODE ABOVE!";function Du(t){return(/^\s*import\s+['"]([^'"]+)['"]/.exec(t)||[])[1]||null}function a_(t=""){const e=t.indexOf(Bu);return e===-1?t:t.slice(e+Bu.length).replace(/^\s*\n/,"")}const l_=/^\s*import\s+['"][^'"]+['"]\s*;\s*(?:\/\/.*)?$/;function c_(t="",e=""){const n=a_(t),i=new Set((e.match(/^\s*import .*$/gm)||[]).map(Du).filter(Boolean)),r=n.split(` +`).filter(s=>{const o=Du(s);return o===null||!i.has(o)?!0:!l_.test(s)}).join(` +`).replace(/^\s*\/\/ Automatic FlutterFlow imports\s*$/m,"").replace(/^\s*\n+/,"");return e+r}const u_=new Set(["flutter","flutter_test","flutter_driver","flutter_localizations","flutter_web_plugins","integration_test","sky_engine"]);function d_(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 y_(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 w_(t,e={}){const n=Array.isArray(t?.artifacts)?t.artifacts:[],r=(e.selectedArtifactIds||t?.deployOrder||n.map(p=>p.id)).map(p=>n.find(h=>h.id===p)).filter(Boolean),s=[...t?.warnings||[]];let o=[];r.forEach(p=>{const h=__(p),g=p.fixedCode||p.code||"",m=p.codeType||m_[p.artifactType]||Qe.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:h,content:g,type:m,path:p.deployPath||v_(h,m),deployPath:p.deployPath||"",deployMode:"customCodeSync"})});const a="lib/flutter_flow/custom_functions.dart",l=o.map((p,h)=>({entry:p,index:h})).filter(({entry:p})=>p.type===Qe.FUNCTION&&p.path===a);if(l.length>1){const p=l[0],h={...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[h.index]=p}const u={...Du(t?.dependencies),...r.reduce((h,p)=>({...h,...Du(p.dependencies)}),{})},c={};r.forEach(h=>{kl(h.code||"").forEach(p=>{p in u||(c[p]="")})});const d={...c,...u},f=u_(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 f_(t){return String(t||"").match(/\bclass\s+([A-Z][A-Za-z0-9_]*)\b/)?.[1]}function h_(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 p_(t,e){const i=[h_(t),f_(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 g_(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:p_(i,r),content:r.content,fileName:i,path:r.path});return n}function m_(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 ju={pass:0,warning:1,fail:2},v_=["manualActions"];function ot(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function Vt(...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 kt(t){return t==null?[]:Array.isArray(t)?t:[t]}function __(t){const e=ot(t).value??t;if(e==null||typeof e=="string"&&e.trim()==="")return null;const n=Number(e);if(Number.isFinite(n))return Uu(n);const i=String(t||"").match(/\bscore\b[^\d]{0,12}(\d{1,3})(?:\s*\/\s*100)?/i);return i?Uu(Number(i[1])):null}function Uu(t){return t>=0&&t<=100?t:null}function ct(t){return String(t||"").trim().replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function Cl(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 Na(...t){return t.filter(Boolean).reduce((e,n)=>ju[n]>ju[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=ot(t),r=Vt(i.message,i.title,i.issue,i.description,i.summary);return r?{severity:Cl(i.severity||i.status||i.level)||e,message:r,suggestion:Vt(i.suggestion,i.fix,i.recommendation,i.action),source:i.source||n}:null}function Oa(t,e="review"){const n=ot(t);return[["findings","warning"],["issues","warning"],["criticalIssues","fail"],["errors","fail"],["warnings","warning"],["recommendations","warning"],["requiredFixes","fail"],["suggestions","warning"]].flatMap(([r,s])=>kt(n[r]).map(o=>mh(o,s,e)).filter(Boolean))}function y_(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=ot(t),r=Vt(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:Vt(i.detail,i.instructions,i.description),location:Vt(i.location,i.flutterFlowPath,i.path),timing:Vt(i.timing,i.phase)||"unspecified",artifactId:n,source:Vt(i.source)||"Code Review"}:null}function Ba(t,e=null){const n=ot(t);return v_.flatMap(i=>kt(n[i])).map((i,r)=>y_(i,r,e)).filter(Boolean)}function w_(t){let e=typeof t=="string"?Ma(t):t;if(!e&&typeof t=="string")return{rawText:t,root:{}};const n=ot(e);typeof n.content=="string"&&(e=Ma(n.content)||e);const i=ot(e),r=ot(i.reviewResult||i.codeReview||i.result);return{rawText:"",root:Object.keys(r).length?r:i}}function b_(t,e){const n=[e.id,e.fileName,e.artifactName].map(ct);return t.find(i=>{const r=ot(i);return[r.id,r.fileName,r.artifactName,r.name].map(ct).some(s=>s&&n.includes(s))})||null}function E_(t,e){return kt(t?.metadata?.compatibility?.deployHints).find(r=>ct(r?.artifactId)===ct(e.id)||ct(r?.fileName)===ct(e.fileName))?.pathHint||""}function S_(t,e){return kt(t?.relationships).filter(n=>ct(n?.from)===ct(e.id)||ct(n?.to)===ct(e.id))}function x_(t,e){return kt(t?.metadata?.compatibility?.findings).filter(n=>!n?.artifactId||ct(n.artifactId)===ct(e.id)).map(n=>mh(n,"warning","Compatibility check")).filter(Boolean)}function I_(t,e,n,i){const r=b_(e,n),s=ot(r?.review||r||n.review),o=Object.keys(s).length>0,a=[...Oa(s),...x_(t,n)],l=Ba(s,n.id),u=Cl(s.status||s.verdict||s.outcome||s.result),c=a.length?Na(...a.map(f=>f.severity)):null,d=Na(u,c,o?null:"warning");return{...n,index:i,status:d,statusReason:o?Vt(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:E_(t,n),relationships:S_(t,n)}}function k_({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 C_({bundle:t,reviewResult:e}){const n=ot(t),i=kt(n.artifacts),{root:r,rawText:s}=w_(e),o=[r.bundleReview,r.overallReview,r.overall,r.bundleSummary,r.summaryReview,r.review].map(ot).find(S=>Object.keys(S).length)||{},a=kt(r.artifacts||r.files||r.reviews),l=i.map((S,_)=>I_(n,a,S,_)),u=Oa(r),d=[...Oa(o),...u],f=[...Ba(o),...Ba(r),...l.flatMap(S=>S.manualSteps)].filter((S,_,b)=>b.findIndex(k=>k.title===S.title&&k.artifactId===S.artifactId)===_),h=Cl(o.status||o.verdict||o.overallStatus||r.status||r.verdict||r.overallStatus||r.outcome),p=Na(h,...d.map(S=>S.severity),...l.map(S=>S.status)),g=o.score??r.score??r.overallScore??s,m=__(g),v=Vt(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)||k_({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:kt(n.deployOrder),relationships:kt(n.relationships),warnings:kt(n.warnings),compatibility:ot(n.metadata?.compatibility)}}const A_=/^\uFEFF/;function Fi(t){let e=0,n=t.length;for(;ee&&!t[n-1].trim();)n--;return t.slice(e,n).join(` -`)}function P_(t){const e=String(t??"").replace(A_,"");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 Fi(n);{const c=Da(e);if(!c.error&&o.every(f=>Wu(f,c.commentAndStringRanges)))return Fi(n)}if(r===1){const c=Fi(n.slice(0,s)),d=Fi(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(` +`)},g=new Set(l.slice(1).map(({index:m})=>m));o=o.filter((m,v)=>!g.has(v)),o[p.index]=h}const u={...ju(t?.dependencies),...r.reduce((p,h)=>({...p,...ju(h.dependencies)}),{})},c={};r.forEach(p=>{kl(p.fixedCode||p.code||"").forEach(h=>{h in u||(c[h]="")})});const d={...c,...u},f=y_(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 b_(t){return String(t||"").match(/\bclass\s+([A-Z][A-Za-z0-9_]*)\b/)?.[1]}function E_(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 S_(t,e){const i=[E_(t),b_(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 x_(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:S_(i,r),content:r.content,fileName:i,path:r.path});return n}function I_(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 Uu={pass:0,warning:1,fail:2},k_=["manualActions"];function ot(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function Vt(...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 kt(t){return t==null?[]:Array.isArray(t)?t:[t]}function C_(t){const e=ot(t).value??t;if(e==null||typeof e=="string"&&e.trim()==="")return null;const n=Number(e);if(Number.isFinite(n))return Hu(n);const i=String(t||"").match(/\bscore\b[^\d]{0,12}(\d{1,3})(?:\s*\/\s*100)?/i);return i?Hu(Number(i[1])):null}function Hu(t){return t>=0&&t<=100?t:null}function ct(t){return String(t||"").trim().replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function Cl(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 Na(...t){return t.filter(Boolean).reduce((e,n)=>Uu[n]>Uu[e]?n:e,"pass")}function _h(t,e="warning",n="review"){if(typeof t=="string")return{severity:e,message:t,suggestion:"",source:n};const i=ot(t),r=Vt(i.message,i.title,i.issue,i.description,i.summary);return r?{severity:Cl(i.severity||i.status||i.level)||e,message:r,suggestion:Vt(i.suggestion,i.fix,i.recommendation,i.action),source:i.source||n}:null}function Oa(t,e="review"){const n=ot(t);return[["findings","warning"],["issues","warning"],["criticalIssues","fail"],["errors","fail"],["warnings","warning"],["recommendations","warning"],["requiredFixes","fail"],["suggestions","warning"]].flatMap(([r,s])=>kt(n[r]).map(o=>_h(o,s,e)).filter(Boolean))}function A_(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=ot(t),r=Vt(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:Vt(i.detail,i.instructions,i.description),location:Vt(i.location,i.flutterFlowPath,i.path),timing:Vt(i.timing,i.phase)||"unspecified",artifactId:n,source:Vt(i.source)||"Code Review"}:null}function Ba(t,e=null){const n=ot(t);return k_.flatMap(i=>kt(n[i])).map((i,r)=>A_(i,r,e)).filter(Boolean)}function P_(t){let e=typeof t=="string"?Ma(t):t;if(!e&&typeof t=="string")return{rawText:t,root:{}};const n=ot(e);typeof n.content=="string"&&(e=Ma(n.content)||e);const i=ot(e),r=ot(i.reviewResult||i.codeReview||i.result);return{rawText:"",root:Object.keys(r).length?r:i}}function F_(t,e){const n=[e.id,e.fileName,e.artifactName].map(ct);return t.find(i=>{const r=ot(i);return[r.id,r.fileName,r.artifactName,r.name].map(ct).some(s=>s&&n.includes(s))})||null}function R_(t,e){return kt(t?.metadata?.compatibility?.deployHints).find(r=>ct(r?.artifactId)===ct(e.id)||ct(r?.fileName)===ct(e.fileName))?.pathHint||""}function T_(t,e){return kt(t?.relationships).filter(n=>ct(n?.from)===ct(e.id)||ct(n?.to)===ct(e.id))}function $_(t,e){return kt(t?.metadata?.compatibility?.findings).filter(n=>!n?.artifactId||ct(n.artifactId)===ct(e.id)).map(n=>_h(n,"warning","Compatibility check")).filter(Boolean)}function M_(t,e,n,i){const r=F_(e,n),s=ot(r?.review||r||n.review),o=Object.keys(s).length>0,a=[...Oa(s),...$_(t,n)],l=Ba(s,n.id),u=Cl(s.status||s.verdict||s.outcome||s.result),c=a.length?Na(...a.map(f=>f.severity)):null,d=Na(u,c,o?null:"warning");return{...n,index:i,status:d,statusReason:o?Vt(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:R_(t,n),relationships:T_(t,n)}}function L_({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 N_({bundle:t,reviewResult:e}){const n=ot(t),i=kt(n.artifacts),{root:r,rawText:s}=P_(e),o=[r.bundleReview,r.overallReview,r.overall,r.bundleSummary,r.summaryReview,r.review].map(ot).find(S=>Object.keys(S).length)||{},a=kt(r.artifacts||r.files||r.reviews),l=i.map((S,_)=>M_(n,a,S,_)),u=Oa(r),d=[...Oa(o),...u],f=[...Ba(o),...Ba(r),...l.flatMap(S=>S.manualSteps)].filter((S,_,b)=>b.findIndex(k=>k.title===S.title&&k.artifactId===S.artifactId)===_),p=Cl(o.status||o.verdict||o.overallStatus||r.status||r.verdict||r.overallStatus||r.outcome),h=Na(p,...d.map(S=>S.severity),...l.map(S=>S.status)),g=o.score??r.score??r.overallScore??s,m=C_(g),v=Vt(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)||L_({status:h,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:h,score:m,summary:v,findings:d,manualSteps:f,artifacts:l,counts:E,reviewCoverage:{reviewed:l.filter(S=>S.reviewComplete).length,total:l.length},deployOrder:kt(n.deployOrder),relationships:kt(n.relationships),warnings:kt(n.warnings),compatibility:ot(n.metadata?.compatibility)}}const O_=/^\uFEFF/;function Fi(t){let e=0,n=t.length;for(;ee&&!t[n-1].trim();)n--;return t.slice(e,n).join(` +`)}function B_(t){const e=String(t??"").replace(O_,"");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 Fi(n);{const c=Da(e);if(!c.error&&o.every(f=>qu(f,c.commentAndStringRanges)))return Fi(n)}if(r===1){const c=Fi(n.slice(0,s)),d=Fi(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 F_(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 vh(t){const e=F_(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 _h(t){return`${Il(t)}.dart`}function R_(t){return Sl(t,"W")}const Hu={"(":")","[":"]","{":"}"},T_={")":"(","]":"[","}":"{"},$_=/[A-Za-z0-9_]/;function Da(t){const e=[{kind:"code",opener:null,openedLine:0}],n=[];let i=1,r=0;const s=(c,d)=>{(c===` +`)}function D_(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 yh(t){const e=D_(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 wh(t){return`${Il(t)}.dart`}function j_(t){return Sl(t,"W")}const Wu={"(":")","[":"]","{":"}"},U_={")":"(","]":"[","}":"{"},H_=/[A-Za-z0-9_]/;function Da(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")&&!$_.test(p);e.push({kind:"string",quote:c,triple:f,raw:g,startIndex:r,openedLine:i}),r+=f?3:1;continue}if(Hu[c]){e.push({kind:"code",opener:c,openedLine:i}),r++;continue}if(T_[c]){if(d.interpolation&&c==="}"){e.pop(),r++;continue}if(d.opener&&Hu[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 M_(t){return Da(String(t??"")).error}function Wu(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 L_=["gmail.com","googlemail.com","outlook.com","hotmail.com","live.com","msn.com"],N_="MAGIC_LINK_SENT",O_="PLUS_ALIAS_REJECTED",B_="Please enter your primary email address. Plus aliases (such as {email}) are not allowed for {domain} accounts.",Ls={allowlistedDomains:L_,successCode:N_,validationCode:O_,messageTemplate:B_},D_=new Set(Ls.allowlistedDomains),j_=Ls.successCode,yh=Ls.validationCode;function Ns(t){return typeof t=="string"?t.trim():""}function U_(t){const e=Ns(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 D_.has(r)?i.includes("+"):!1}function H_(t,e){return Ls.messageTemplate.replaceAll("{email}",t).replaceAll("{domain}",e)}function wh(t){if(!U_(t))return null;const e=Ns(t),n=e.lastIndexOf("@"),i=e.slice(n+1).toLowerCase();return H_(e,i)}function bh(t,e){return t?.code===yh?t.message||wh(e)||"Please enter your primary email address.":t?.code===j_||!t?.code?`Check your email — we sent a link to ${Ns(e)}`:t.message||"Something went wrong. Please try again."}const W_="ccc_auth_session",z_="ccc_subscription",q_=Object.freeze(["hasSeenWalkthrough"]);function V_(t){const e=[];for(const n of q_)t.getItem(n)!==null&&(t.removeItem(n),e.push(n));return e}function G_(){return[W_,z_]}function K_({storage:t,onIdentityChanged:e,onPlanChanged:n}){for(const i of G_())t.removeItem(i);typeof e=="function"&&e(),typeof n=="function"&&n()}function Y_({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 J_=/^dependencies\s*:\s*(?:#.*)?$/,Z_=/^(?:"([^"]+)"|'([^']+)'|([A-Za-z_][A-Za-z0-9_-]*))\s*:/;function Os(t){const e=t.match(Z_);return e?e[1]??e[2]??e[3]:null}function ur(t){const e=t.trim();return e===""||e.startsWith("#")}function gi(t){const e=t.match(/^(\s*)/);return e?e[1].length:0}function Pl(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 ty(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(Sh(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=Fl(r);if(l){const u=o.map(([c,d])=>zu(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(zu(" ",u,c))});return{yaml:r.join(` -`),added:o.map(([u])=>u),alreadyPresent:a}}function ny(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=Ds(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(gi(r[c.lineIndex]));r[c.lineIndex]=`${d}${l}: ${Ih(String(u).trim())}${c.comment}`,o.push({name:l,from:c.constraint,to:u})}return{yaml:r.join(` -`),overridden:o,skipped:a}}function kh(t){const e=String(t||""),n=[];return e.trim()?(/^name:\s*\S+/m.test(e)||n.push("pubspec.yaml missing name field"),Fl(e.split(` -`))||n.push("pubspec.yaml missing dependencies section"),Sh(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 iy=">=3.0.0 <4.0.0";function ja(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 ry(t=""){const e=o_(t).filter(n=>!n.startsWith("dart:")&&!n.startsWith("package:"));return{selfContained:e.length===0,unresolvableImports:e}}function qu(t,e,n){const i=[];for(const[r,s]of t){if(s.isScalar){e[r]=ja(s.constraint);continue}if(s.sourceKey==="sdk"){n.add(r);continue}if(s.sourceKey===null&&s.version){e[r]=ja(s.version);continue}i.push(r)}return i}function sy(t){const e=new Set,n={},i={},r=qu(Ds(t),n,e);r.push(...qu(Q_(t,"dependency_overrides"),i,e));const s=new Set([...Object.keys(n),...e]),{sdk:o}=xh(t);return{sdkConstraint:ja(o)||iy,dependencies:n,overrides:i,sdkPackages:[...e].sort(),availablePackages:s,unrepresentable:r}}function oy(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 ay(t,e){const{sdkConstraint:n,dependencies:i,overrides:r,sdkPackages:s,availablePackages:o,unrepresentable:a}=sy(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=kl(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}=ry(p),E=g.filter(S=>!o.has(S));if(v.length>0||E.length>0){c.push({className:h,reason:oy(h,v,E)});continue}u.push({fileName:`${Il(h)}.dart`,content:p})}return{manifest:l,sources:u,skipped:c,approximate:d}}function Vu(t,e){const n=`${t}${e}`.split(` -`),i=n.pop()??"",r=[];for(const s of n){const o=Ch(s);o&&r.push(o)}return{events:r,buffer:i}}function ly(t){const e=Ch(t);return e?[e]:[]}function Ch(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 Le=Object.freeze({COMMITTED:"committed",PARTIAL:"partial",FAILED:"failed",UNCONFIRMED:"unconfirmed"}),Ah=12e4,Ph=1e4;function Fh(t){return t?.unconfirmed===!0||t?.outcome===Le.UNCONFIRMED?Le.UNCONFIRMED:t?.partial===!0||t?.outcome===Le.PARTIAL?Le.PARTIAL:t?.success===!0?Le.COMMITTED:Le.FAILED}class et extends Error{constructor(e){super(e),this.name="UnconfirmedDeployError",this.outcome=Le.UNCONFIRMED}}function Gu({httpStatus:t}={}){return new et(`Every FlutterFlow sync endpoint lost its response or ended in a server error${t?` (last: HTTP ${t})`:""} — neither can prove the push was refused, so it may already have been applied. Open the FlutterFlow project to reconcile before retrying.`)}async function cy(t,e={}){const{onPhase:n,onLog:i}=e;let r=null,s=null,o="";const a=u=>{if(u.event==="phase"){u.phase&&(s=u.phase),u.message&&n&&n(u.message);return}if(u.event==="log"){u.message&&i&&i(u.message);return}r=u};let l=null;try{if(t.body?.getReader){const u=t.body.getReader(),c=new TextDecoder;for(;;){const{done:d,value:f}=await u.read();if(d)break;const h=Vu(o,c.decode(f,{stream:!0}));o=h.buffer,h.events.forEach(a)}}else{const u=Vu("",await t.text());o=u.buffer,u.events.forEach(a)}}catch(u){l=u}return ly(o).forEach(a),r?{...r,success:r.success===!0||r.success===void 0&&t.ok,finalResultReceived:!0,runnerPhase:s,httpStatus:t.status}:{success:!1,finalResultReceived:!1,httpRejected:!t.ok,httpStatus:t.status,runnerPhase:s,error:t.ok?l?"The connection to the FlutterFlow deploy runner dropped before it reported a result.":"The FlutterFlow deploy runner closed the connection before it finished.":`FlutterFlow custom class provisioning failed (HTTP ${t.status}).`}}const uy=new Set(["connected","workspace_init","workspace_ready","verifying"]);function Rh(t){return t?.preWrite===!0||Array.isArray(t?.analyzerErrors)&&t.analyzerErrors.length>0?!0:typeof t?.runnerPhase=="string"?uy.has(t.runnerPhase):typeof t?.httpStatus=="number"?t.httpStatus>=400&&t.httpStatus<500:!1}function Ku(t){if(t?.finalResultReceived){const e=Fh(t);return e===Le.FAILED&&!Rh(t)?Le.UNCONFIRMED:e}return t?.httpRejected?Le.FAILED:Le.UNCONFIRMED}function dy(){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 +`){n.push({start:d.startIndex,end:r}),o??=`line ${i}: string starting on line ${d.openedLine} is never closed`,e.pop();continue}if(!d.raw&&c==="\\"){s(t[r+1]??"",t[r+2]??""),r+=2;continue}if(!d.raw&&c==="$"&&t[r+1]==="{"){e.push({kind:"code",opener:null,interpolation:!0}),r+=2;continue}const f=d.triple?3:1;if(c===d.quote&&t.slice(r,r+f)===d.quote.repeat(f)){n.push({start:d.startIndex,end:r+f}),e.pop(),r+=f;continue}s(c,t[r+1]),r++;continue}if(c==="/"&&t[r+1]==="/"){e.push({kind:"line-comment",startIndex:r}),r+=2;continue}if(c==="/"&&t[r+1]==="*"){e.push({kind:"block-comment",startIndex:r,openedLine:i,depth:1}),r+=2;continue}if(c==="'"||c==='"'){const f=t.slice(r,r+3)===c.repeat(3),p=r>0?t[r-1]:"",h=r>1?t[r-2]:"",g=(p==="r"||p==="R")&&!H_.test(h);e.push({kind:"string",quote:c,triple:f,raw:g,startIndex:r,openedLine:i}),r+=f?3:1;continue}if(Wu[c]){e.push({kind:"code",opener:c,openedLine:i}),r++;continue}if(U_[c]){if(d.interpolation&&c==="}"){e.pop(),r++;continue}if(d.opener&&Wu[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(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 W_(t){return Da(String(t??"")).error}function qu(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 q_=["gmail.com","googlemail.com","outlook.com","hotmail.com","live.com","msn.com"],z_="MAGIC_LINK_SENT",V_="PLUS_ALIAS_REJECTED",G_="Please enter your primary email address. Plus aliases (such as {email}) are not allowed for {domain} accounts.",Os={allowlistedDomains:q_,successCode:z_,validationCode:V_,messageTemplate:G_},K_=new Set(Os.allowlistedDomains),Y_=Os.successCode,bh=Os.validationCode;function Bs(t){return typeof t=="string"?t.trim():""}function J_(t){const e=Bs(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 K_.has(r)?i.includes("+"):!1}function Z_(t,e){return Os.messageTemplate.replaceAll("{email}",t).replaceAll("{domain}",e)}function Eh(t){if(!J_(t))return null;const e=Bs(t),n=e.lastIndexOf("@"),i=e.slice(n+1).toLowerCase();return Z_(e,i)}function Sh(t,e){return t?.code===bh?t.message||Eh(e)||"Please enter your primary email address.":t?.code===Y_||!t?.code?`Check your email — we sent a link to ${Bs(e)}`:t.message||"Something went wrong. Please try again."}const X_="ccc_auth_session",Q_="ccc_subscription",ey=Object.freeze(["hasSeenWalkthrough"]);function ty(t){const e=[];for(const n of ey)t.getItem(n)!==null&&(t.removeItem(n),e.push(n));return e}function ny(){return[X_,Q_]}function iy({storage:t,onIdentityChanged:e,onPlanChanged:n}){for(const i of ny())t.removeItem(i);typeof e=="function"&&e(),typeof n=="function"&&n()}function ry({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 sy=/^dependencies\s*:\s*(?:#.*)?$/,oy=/^(?:"([^"]+)"|'([^']+)'|([A-Za-z_][A-Za-z0-9_-]*))\s*:/;function ur(t){const e=t.match(oy);return e?e[1]??e[2]??e[3]:null}function dr(t){const e=t.trim();return e===""||e.startsWith("#")}function pn(t){const e=t.match(/^(\s*)/);return e?e[1].length:0}function Pl(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;su&&/\s/.test(s[c-1]);)c-=1}return t[r]=s.slice(0,u)+Rl(n)+s.slice(c),!0}return!1}function zu(t,e,n){if(n&&typeof n=="object"&&n.sdk)return[`${t}${e}:`,`${t} sdk: ${n.sdk}`];const i=String(n||"").trim();return[`${t}${e}: ${i?Rl(i):">=0.0.0"}`]}function uy(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(Ph(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=Fl(r);if(l){const u=o.flatMap(([c,d])=>zu(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(...zu(" ",u,c))});return{yaml:r.join(` +`),added:o.map(([u])=>u),alreadyPresent:a}}function dy(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=Ds(n),o=[],a=[];for(const[l,u]of i){const c=s.get(l),d=c&&!c.isScalar&&c.sourceKey===null&&c.version!==null;if(!c||!c.isScalar&&!d||!String(u||"").trim()){a.push(l);continue}if(d){cy(r,c,String(u).trim())?o.push({name:l,from:c.version,to:u}):a.push(l);continue}const f=" ".repeat(pn(r[c.lineIndex]));r[c.lineIndex]=`${f}${l}: ${Rl(String(u).trim())}${c.comment}`,o.push({name:l,from:c.constraint,to:u})}return{yaml:r.join(` +`),overridden:o,skipped:a}}function Rh(t){const e=String(t||""),n=[];return e.trim()?(/^name:\s*\S+/m.test(e)||n.push("pubspec.yaml missing name field"),Fl(e.split(` +`))||n.push("pubspec.yaml missing dependencies section"),Ph(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 fy=">=3.0.0 <4.0.0";function ja(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 hy(t=""){const e=g_(t).filter(n=>!n.startsWith("dart:")&&!n.startsWith("package:"));return{selfContained:e.length===0,unresolvableImports:e}}function Vu(t,e,n){const i=[];for(const[r,s]of t){if(s.isScalar){e[r]=ja(s.constraint);continue}if(s.sourceKey==="sdk"){n.add(r);continue}if(s.sourceKey===null&&s.version){e[r]=ja(s.version);continue}i.push(r)}return i}function py(t){const e=new Set,n=new Set,i={},r={},s=Vu(Ds(t),i,e),o=Vu(ay(t,"dependency_overrides"),r,n),a=[...s,...o],l=new Set([...Object.keys(i),...e]),{sdk:u}=Fh(t);return{sdkConstraint:ja(u)||fy,dependencies:i,dependencyOverrides:r,sdkPackages:[...e].sort(),sdkOverrides:[...n].sort(),availablePackages:l,unrepresentable:a,unrepresentableOverrides:o}}function gy(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 my(t,e){const{sdkConstraint:n,dependencies:i,dependencyOverrides:r,sdkPackages:s,sdkOverrides:o,availablePackages:a,unrepresentable:l}=py(e),u={sdkConstraint:n,dependencies:i,dependencyOverrides:r,sdkPackages:s,sdkOverrides:o},c=[],d=[],f=l.map(p=>`Your project declares ${p} from a source that cannot be reproduced outside it, so the pre-deploy compile check runs against a scratch package graph that omits ${p}. Classes that do not import ${p} 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 p of t){const{className:h,content:g}=p,m=kl(g),v=m.filter(_=>l.includes(_));if(v.length>0){d.push({className:h,reason:`${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.`});continue}const{unresolvableImports:E}=hy(g),S=m.filter(_=>!a.has(_));if(E.length>0||S.length>0){d.push({className:h,reason:gy(h,E,S)});continue}c.push({fileName:`${Il(h)}.dart`,content:g})}return{manifest:u,sources:c,skipped:d,approximate:f}}function Gu(t,e){const n=`${t}${e}`.split(` +`),i=n.pop()??"",r=[];for(const s of n){const o=Th(s);o&&r.push(o)}return{events:r,buffer:i}}function vy(t){const e=Th(t);return e?[e]:[]}function Th(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 Le=Object.freeze({COMMITTED:"committed",PARTIAL:"partial",FAILED:"failed",UNCONFIRMED:"unconfirmed"}),$h=12e4,Mh=1e4;function Lh(t){return t?.unconfirmed===!0||t?.outcome===Le.UNCONFIRMED?Le.UNCONFIRMED:t?.partial===!0||t?.outcome===Le.PARTIAL?Le.PARTIAL:t?.success===!0?Le.COMMITTED:Le.FAILED}class et extends Error{constructor(e){super(e),this.name="UnconfirmedDeployError",this.outcome=Le.UNCONFIRMED}}function Ku({httpStatus:t}={}){return new et(`Every FlutterFlow sync endpoint lost its response or ended in a server error${t?` (last: HTTP ${t})`:""} — neither can prove the push was refused, so it may already have been applied. Open the FlutterFlow project to reconcile before retrying.`)}async function _y(t,e={}){const{onPhase:n,onLog:i}=e;let r=null,s=null,o="";const a=u=>{if(u.event==="phase"){u.phase&&(s=u.phase),u.message&&n&&n(u.message);return}if(u.event==="log"){u.message&&i&&i(u.message);return}r=u};let l=null;try{if(t.body?.getReader){const u=t.body.getReader(),c=new TextDecoder;for(;;){const{done:d,value:f}=await u.read();if(d)break;const p=Gu(o,c.decode(f,{stream:!0}));o=p.buffer,p.events.forEach(a)}}else{const u=Gu("",await t.text());o=u.buffer,u.events.forEach(a)}}catch(u){l=u}return vy(o).forEach(a),r?{...r,success:r.success===!0||r.success===void 0&&t.ok,finalResultReceived:!0,runnerPhase:s,httpStatus:t.status}:{success:!1,finalResultReceived:!1,httpRejected:!t.ok,httpStatus:t.status,runnerPhase:s,error:t.ok?l?"The connection to the FlutterFlow deploy runner dropped before it reported a result.":"The FlutterFlow deploy runner closed the connection before it finished.":`FlutterFlow custom class provisioning failed (HTTP ${t.status}).`}}const yy=new Set(["connected","workspace_init","workspace_ready","verifying"]);function Nh(t){return t?.preWrite===!0||Array.isArray(t?.analyzerErrors)&&t.analyzerErrors.length>0?!0:typeof t?.runnerPhase=="string"?yy.has(t.runnerPhase):typeof t?.httpStatus=="number"?t.httpStatus>=400&&t.httpStatus<500:!1}function Yu(t){if(t?.finalResultReceived){const e=Lh(t);return e===Le.FAILED&&!Nh(t)?Le.UNCONFIRMED:e}return t?.httpRejected?Le.FAILED:Le.UNCONFIRMED}function wy(){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(Y,z){if(!i)return null;const D=i.createShader(Y);return i.shaderSource(D,z),i.compileShader(D),i.getShaderParameter(D,i.COMPILE_STATUS)?D:(window.console&&console.warn("fx-grid shader: "+i.getShaderInfoLog(D)),null)}if(i){const Y=E(i.VERTEX_SHADER,o),z=E(i.FRAGMENT_SHADER,a());if(Y&&z&&(l=i.createProgram(),i.attachShader(l,Y),i.attachShader(l,z),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(Y){if(!Y)return null;const z=/^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(Y);if(z){let D=z[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 ue=D.getContext("2d");ue.fillStyle="rgb(9, 8, 7)";const xe=String(ue.fillStyle);ue.fillStyle=Y;const Fe=String(ue.fillStyle);if(Fe===xe)return null;const ft=/^#([0-9a-f]{6})$/i.exec(Fe);if(ft){const ht=ft[1];return[parseInt(ht.slice(0,2),16)/255,parseInt(ht.slice(2,4),16)/255,parseInt(ht.slice(4,6),16)/255]}const Nt=/rgba?\(\s*([\d.]+)[,\s]+([\d.]+)[,\s]+([\d.]+)/i.exec(Fe);if(Nt)return[Number(Nt[1])/255,Number(Nt[2])/255,Number(Nt[3])/255]}catch{}return null}function _(){let Y="";try{const z=getComputedStyle(document.documentElement);Y=(z.getPropertyValue("--fx-ink")||"").trim()||(z.getPropertyValue("--fg")||"").trim()}catch{}return S(Y)||[.56,.68,.88]}const b=_();let k=1920,T=1080,x=960,F=540,$=960,O=540,L=.66,N=0,K=-1e9,V=!1,M=0,R=0,Z=null,Ce=!1,oe=!1,ye=!1;const $e=64,ae=15.2;let Ie=0,Se=0;const De=.0032,wt=0,ge=.56,Ze=.26,bt=.32,mn=.16,Te=.349;let Pe=wt;function $t(){const Y=t.getBoundingClientRect(),z=t.clientWidth,D=t.clientHeight;if(!Y.width||!z||!D)return;const ue=Math.min(window.devicePixelRatio||1,2),xe=Math.max(.2,Math.min(2,Y.width/z*ue)),Fe=Math.max(2,Math.round(z*xe)),ft=Math.max(2,Math.round(D*xe));(Fe!==t.width||ft!==t.height)&&(t.width=Fe,t.height=ft,i&&i.viewport(0,0,Fe,ft)),k=z,T=D,V||(x=$=k/2,F=O=T/2,V=!0)}function Bn(Y){!l||!Ce||!i||(i.uniform2f(u,t.width,t.height),i.uniform2f(c,k,T),i.uniform2f(d,x,F),i.uniform1f(f,L),i.uniform1f(h,N),i.uniform2f(v,Math.cos(Pe),Math.sin(Pe)),i.uniform1f(p,Y),i.uniform3f(g,b[0],b[1],b[2]),i.clear(i.COLOR_BUFFER_BIT),i.drawArrays(i.TRIANGLES,0,3))}function qe(Y,z,D){const ue=Math.max(0,Math.min(1,(D-Y)/(z-Y)));return ue*ue*(3-2*ue)}function Dn(Y){if(!Z||!r)return;const z=r;z.setTransform(1,0,0,1,0,0),z.clearRect(0,0,t.width,t.height);const D=t.width/k;z.setTransform(D,0,0,D,0,0),z.globalAlpha=1;const ue=Math.min(k,T),xe=Math.max(64,Math.min(118,ue/10)),Fe=xe*2.9,ft=2*Fe*Fe,Nt=Math.sin(Y*.11)*7,ht=Math.cos(Y*.09)*7-N,gr=x+Nt,mr=F+ht,lo=Fe*Math.sqrt(2*Math.log(1/.06)),yi=lo+De*lo*lo+xe,Dp=Math.floor((gr-yi)/xe)-1,jp=Math.ceil((gr+yi)/xe)+1,Up=Math.floor((mr-yi)/xe)-1,Hp=Math.ceil((mr+yi)/xe)+1;for(let co=Up;co<=Hp;co++){const Wp=(co+.5)*xe;for(let uo=Dp;uo<=jp;uo++){const fo=(uo+.5)*xe-gr,ho=Wp-mr,po=Math.sqrt(fo*fo+ho*ho)+1e-5;if(po>yi)continue;const vr=(-1+Math.sqrt(1+4*De*po))/(2*De),pc=Math.exp(-(vr*vr)/ft),gc=qe(.06,.8,pc)*L*.26;if(gc<.004)continue;const on=xe/(1+2*De*vr)*.26*(.32+1.1*pc),mc=vr/po,go=gr+fo*mc,mo=mr+ho*mc;go<-on*1.6||go>k+on*1.6||mo<-on*1.6||mo>T+on*1.6||(z.globalAlpha=gc,z.save(),z.translate(go,mo),z.rotate(Pe),z.drawImage(Z,-on,-on,on*2,on*2),z.restore())}}z.globalAlpha=1}function Mt(Y){if(!oe)return;const z=R?Math.min(.05,(Y-R)/1e3):.016;R=Y;const ue=Y-K>2400?.6:1;L+=(ue-L)*Math.min(1,z*3.2);const xe=Math.min(.05,z);Ie+=(($-x)*$e-Ie*ae)*xe,Se+=((O-F)*$e-Se*ae)*xe,x+=Ie*xe,F+=Se*xe,N=(window.scrollY||window.pageYOffset||0)*.55;const Fe=Y/1e3,ft=x/(k||1)-.5,Nt=F/(T||1)-.5;let ht=ft*(ft>=0?ge:Ze)+Nt*(Nt>=0?bt:mn);ht>Te?ht=Te:ht<-Te&&(ht=-Te),Pe=wt+ht-N*6e-4,$t(),i?Bn(Fe):Dn(Fe),M=requestAnimationFrame(Mt)}function Lt(Y){if(!oe)return;const z=t.getBoundingClientRect();!z.width||!k||!T||($=(Y.clientX-z.left)/z.width*k,O=(Y.clientY-z.top)/z.height*T,K=performance.now())}function dt(){oe||ao||e.matches||n.matches||!ye||document.hidden||(oe=!0,R=0,M=requestAnimationFrame(Mt))}function sn(){oe=!1,M&&(cancelAnimationFrame(M),M=0),R=0}function _i(){e.matches?(sn(),t.classList.remove("is-ready")):ye&&dt()}function jn(){n.matches?sn():ye&&dt()}function dc(){document.hidden?sn():ye&&dt()}const fc=new IntersectionObserver(Y=>{ye=Y[0]?.isIntersecting||!1,ye?dt():sn()},{threshold:0});fc.observe(t),window.addEventListener("pointermove",Lt,{passive:!0,capture:!0}),window.addEventListener("resize",$t),e.addEventListener("change",_i),n.addEventListener("change",jn),document.addEventListener("visibilitychange",dc);function Bp(){const Y=(s.match(/\sd="([^"]+)"/)||[])[1],z=document.createElement("canvas");z.width=256,z.height=256;const D=z.getContext("2d");if(Y&&window.Path2D){const ue=Math.min(8.533333333333333,8.421052631578947);D.setTransform(ue,0,0,ue,ue+(256-30*ue)/2,-6.4*ue),D.fillStyle="rgb(255,255,255)",D.fill(new Path2D(Y),"evenodd"),D.setTransform(1,0,0,1,0,0)}try{const ue=D.getImageData(0,0,256,256),xe=ue.data;for(let Fe=3;Feoe}}const fy=120;function hy(t,e,n){return tn?n:t}function de(t,e,n){return hy((t-e)/(n-e),0,1)}function py(t){return t<.5?2*t*t:1-Math.pow(-2*t+2,2)/2}function Go(t){return 1-Math.pow(1-t,3)}function Ve(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 Yu(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(de(_,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:Ve}]),d=te(_,[{t:0,v:0},{t:2,v:.3},{t:4.6,v:.16,e:Ve},{t:10.6,v:0}]),h=te(_,[{t:0,v:0},{t:2,v:-40},{t:4.6,v:0,e:Ve}]),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 b=de(_,.45,2.2);a=b>0?-2.6*(1-Yu(b)):0,g=te(_,[{t:0,v:1},{t:.57,v:0},{t:.67,v:0},{t:.92,v:1}]);const k=de(_,.67,2.42);f=k>0?-2.6*(1-Yu(k)):0,s=1-.05*(Math.sin(de(_,1.9,2.5)*Math.PI)+Math.sin(de(_,2.5,3.1)*Math.PI))}else if(t<74){let b=function(F){return[te(F,[{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(F,[{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=b;const _=t-60,k=1-de(_,12,14),T=b(de(_,0,12)),x=b(de(_-.5,0,12));n=T[0]*k,i=(T[1]+.05*Math.sin(_*7))*k,o=(x[0]-T[0])*.6*k,a=(x[1]-T[1])*.6*k,h=(x[0]-T[0])*30*k,E=de(_,0,.4)*k}else if(t<85.4){const _=t-74,b=te(_,[{t:0,v:0},{t:4,v:1},{t:8,v:.24},{t:9.6,v:1,e:Ve},{t:11.4,v:0}]);o=b*.5,d=-b*.5,l=te(_,[{t:0,v:0},{t:4,v:6},{t:8,v:20},{t:9.6,v:38,e:Ve},{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,b=de(_,0,5.6),k=de(_,5.6,7.6),T=.72*Math.min(1,_/.6)*(1-k);d=Math.cos(b*Math.PI*2)*T,f=Math.sin(b*Math.PI*2)*T*.55,h=b*360*(1-k);const x=te(_,[{t:0,v:0},{t:7.6,v:0},{t:8.2,v:1,e:Go},{t:8.6,v:.55},{t:9.4,v:0}]);o=-.16*x,d+=.16*x,l=-6*x,h+=6*x,s=1+.05*x,m=1+.9*x}else if(t<108.6){const _=t-96.4,b=de(_,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-b),i=-.35*Math.abs(Math.sin(de(_,0,9.6)*Math.PI*3))*(1-b);const k=Math.sin(_*6.2)*(1-b);u=1+.12*k,p=1-.12*k,l=k*8,h=-k*8,o=.06*k,d=-.06*k,E=de(_,0,.4)*(1-b)}else{const _=t-108.6,b=Math.sin(de(_,0,8)*Math.PI),k=1-de(_,8,11.4);s=1+.04*b*k,i=-.1*b*k,r=2*b*k,m=1+.5*Math.sin(de(_,0,6)*Math.PI),v=1+.1*Math.sin(de(_,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 gy(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=fy;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(M){const R=Math.min(1,Math.max(0,M.x))*c,Z=M.y*d;n.style.transform="translate3d("+R.toFixed(2)+"px,"+Z.toFixed(2)+"px,0) rotate("+M.rot.toFixed(2)+"deg) scale("+M.scale.toFixed(3)+")",i.style.transform="translate3d("+(M.ax*u).toFixed(2)+"px,"+(M.ay*u).toFixed(2)+"px,0) rotate("+M.ar.toFixed(2)+"deg) scale("+M.asc.toFixed(3)+")",i.style.opacity=M.afade.toFixed(3),r.style.transform="translate3d("+(M.bx*u).toFixed(2)+"px,"+(M.by*u).toFixed(2)+"px,0) rotate("+M.br.toFixed(2)+"deg) scale("+M.bsc.toFixed(3)+")",r.style.opacity=M.bfade.toFixed(3),s.style.transform="scale("+M.hsc.toFixed(3)+")",s.style.opacity=(.09*M.hfade).toFixed(3),o.style.transform="translateX("+R.toFixed(2)+"px) scaleX("+(.75+.4*Math.abs(M.x)).toFixed(3)+")",o.style.opacity=(M.shd*.5).toFixed(3)}let p=0,g=0,m=0,v=!1,E=!1,S=!1,_=0;function b(){return S||a.matches||document.hidden||!e.offsetParent?!1:E}function k(M){if(!v)return;if(m=requestAnimationFrame(k),!b()){x();return}const R=g?(M-g)/1e3:0;g=M,p=(p+Math.min(R,.1))%l,_+=1,h(Ri(p))}function T(){v||S||b()&&(v=!0,g=0,m=requestAnimationFrame(k))}function x(){v=!1,m&&(cancelAnimationFrame(m),m=0),g=0}function F(){b()?T():x()}function $(){a.matches?(x(),h(Ri(0))):F()}function O(){f(),v&&h(Ri(p))}function L(){g=0,F()}const N=new IntersectionObserver(M=>{E=M[0]?M[0].isIntersecting:!1,F()},{threshold:0});N.observe(e),window.addEventListener("resize",O),a.addEventListener("change",$),document.addEventListener("visibilitychange",L);function K(){S||(S=!0,x(),N.disconnect(),window.removeEventListener("resize",O),a.removeEventListener("change",$),document.removeEventListener("visibilitychange",L))}window.addEventListener("pagehide",K);function V(M){p=(M%l+l)%l,h(Ri(p))}return f(),h(Ri(0)),F(),{isRunning:()=>v,currentTime:()=>p,frameCount:()=>_,seek:V,dispose:K}}const my=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;function Xt(t){const e=String(t||"").trim().match(my);return e?{major:Number(e[1]),minor:Number(e[2]),patch:Number(e[3]),prerelease:e[4]?e[4].split("."):[]}:null}function vy(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 yy(t){const e=Xt(t);return e?e.major>0?`${e.major+1}.0.0`:`0.${e.minor+1}.0`:null}function Rl(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 Xt(o)?{min:o,minInclusive:!0,max:yy(o),maxInclusive:!1}:null}if(Xt(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(!Xt(a))return null;r=!0,o===">="||o===">"?(n.min=a,n.minInclusive=o===">="):(n.max=a,n.maxInclusive=o==="<=")}return r?n:null}function Ju(t,e){const n=Rl(t);if(!n||!Xt(e))return!1;if(n.min!==null){const i=_s(e,n.min);if(i<0||i===0&&!n.minInclusive)return!1}if(n.max!==null){const i=_s(e,n.max);if(i>0||i===0&&!n.maxInclusive)return!1}return!0}function wy(t,e){const n=Rl(t);if(!n||!Xt(e))return!1;if(n.max===null)return!0;const i=_s(n.max,e);return i>0?!0:i===0&&n.maxInclusive}function qn(t){const e=Rl(t);return e?e.min:null}const by="https://pub.dev/api/packages/",Ey=8e3;function Sy(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&&!Ju(l.sdk,n)||i&&l.flutter&&!Ju(l.flutter,i)||(!s||_s(a,s)>0)&&(s=a)}return s?{version:s,constraint:`^${s}`}:null}async function xy(t,e={}){const{dartSdkFloor:n=null,flutterSdkFloor:i=null,fetchImpl:r=fetch}=e;let s;try{const a=await r(`${by}${encodeURIComponent(t)}`,{signal:AbortSignal.timeout(Ey)});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=Sy(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 Iy(t,e={}){const n=await Promise.all(t.map(i=>xy(i,e)));return new Map(n.map(({name:i,...r})=>[i,r]))}async function ky(t,e={},n={}){const{resolveVersions:i=Iy}=n,r=Object.entries(e).filter(([c])=>c&&c!=="flutter"),s=xh(t),o={dartSdkFloor:qn(s.sdk),flutterSdkFloor:qn(s.flutter)},a={additions:{},overrides:{},kept:[],warnings:[],sdk:o};if(r.length===0)return a;const l=Ds(t),u=[];for(const[c,d]of r){const f=l.get(c);if(!f){u.push(c);continue}const h=qn(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(wy(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(qn(h)){a.additions[d]=`^${qn(h)}`,a.warnings.push(`Could not confirm "${d}" version on pub.dev (${f?.error||"lookup failed"}). Using ^${qn(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 Cy={"&":"&","<":"<",">":">",'"':""","'":"'"};function Qt(t){return String(t??"").replace(/[&<>"']/g,e=>Cy[e])}function q(t){return t?Qt(t).replace(/\n/g,"
"):""}function Jt(t){return Qt(t).replace(/\r?\n/g," ")}function js(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 $h(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 Ay(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 Py(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 Fy(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 ui(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 Zu(t){return t=Qt(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 Mh(t,e="dart",n=globalThis.hljs){if(!t)return"";const i=ui(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 Qt(i)}}}function Us(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=Fy(o),u=Mh(o.trim(),l,n);i+=`
+`)}let l=null,u,c,d,f,p,h,g,m,v;function E(Y,q){if(!i)return null;const D=i.createShader(Y);return i.shaderSource(D,q),i.compileShader(D),i.getShaderParameter(D,i.COMPILE_STATUS)?D:(window.console&&console.warn("fx-grid shader: "+i.getShaderInfoLog(D)),null)}if(i){const Y=E(i.VERTEX_SHADER,o),q=E(i.FRAGMENT_SHADER,a());if(Y&&q&&(l=i.createProgram(),i.attachShader(l,Y),i.attachShader(l,q),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"),p=i.getUniformLocation(l,"parallax"),h=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(Y){if(!Y)return null;const q=/^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(Y);if(q){let D=q[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 ue=D.getContext("2d");ue.fillStyle="rgb(9, 8, 7)";const xe=String(ue.fillStyle);ue.fillStyle=Y;const Fe=String(ue.fillStyle);if(Fe===xe)return null;const ft=/^#([0-9a-f]{6})$/i.exec(Fe);if(ft){const ht=ft[1];return[parseInt(ht.slice(0,2),16)/255,parseInt(ht.slice(2,4),16)/255,parseInt(ht.slice(4,6),16)/255]}const Nt=/rgba?\(\s*([\d.]+)[,\s]+([\d.]+)[,\s]+([\d.]+)/i.exec(Fe);if(Nt)return[Number(Nt[1])/255,Number(Nt[2])/255,Number(Nt[3])/255]}catch{}return null}function _(){let Y="";try{const q=getComputedStyle(document.documentElement);Y=(q.getPropertyValue("--fx-ink")||"").trim()||(q.getPropertyValue("--fg")||"").trim()}catch{}return S(Y)||[.56,.68,.88]}const b=_();let k=1920,T=1080,x=960,F=540,$=960,O=540,L=.66,N=0,K=-1e9,V=!1,M=0,R=0,Z=null,Ce=!1,oe=!1,ye=!1;const $e=64,ae=15.2;let Ie=0,Se=0;const De=.0032,wt=0,ge=.56,Ze=.26,bt=.32,vn=.16,Te=.349;let Pe=wt;function $t(){const Y=t.getBoundingClientRect(),q=t.clientWidth,D=t.clientHeight;if(!Y.width||!q||!D)return;const ue=Math.min(window.devicePixelRatio||1,2),xe=Math.max(.2,Math.min(2,Y.width/q*ue)),Fe=Math.max(2,Math.round(q*xe)),ft=Math.max(2,Math.round(D*xe));(Fe!==t.width||ft!==t.height)&&(t.width=Fe,t.height=ft,i&&i.viewport(0,0,Fe,ft)),k=q,T=D,V||(x=$=k/2,F=O=T/2,V=!0)}function Dn(Y){!l||!Ce||!i||(i.uniform2f(u,t.width,t.height),i.uniform2f(c,k,T),i.uniform2f(d,x,F),i.uniform1f(f,L),i.uniform1f(p,N),i.uniform2f(v,Math.cos(Pe),Math.sin(Pe)),i.uniform1f(h,Y),i.uniform3f(g,b[0],b[1],b[2]),i.clear(i.COLOR_BUFFER_BIT),i.drawArrays(i.TRIANGLES,0,3))}function ze(Y,q,D){const ue=Math.max(0,Math.min(1,(D-Y)/(q-Y)));return ue*ue*(3-2*ue)}function jn(Y){if(!Z||!r)return;const q=r;q.setTransform(1,0,0,1,0,0),q.clearRect(0,0,t.width,t.height);const D=t.width/k;q.setTransform(D,0,0,D,0,0),q.globalAlpha=1;const ue=Math.min(k,T),xe=Math.max(64,Math.min(118,ue/10)),Fe=xe*2.9,ft=2*Fe*Fe,Nt=Math.sin(Y*.11)*7,ht=Math.cos(Y*.09)*7-N,vr=x+Nt,_r=F+ht,lo=Fe*Math.sqrt(2*Math.log(1/.06)),yi=lo+De*lo*lo+xe,qp=Math.floor((vr-yi)/xe)-1,zp=Math.ceil((vr+yi)/xe)+1,Vp=Math.floor((_r-yi)/xe)-1,Gp=Math.ceil((_r+yi)/xe)+1;for(let co=Vp;co<=Gp;co++){const Kp=(co+.5)*xe;for(let uo=qp;uo<=zp;uo++){const fo=(uo+.5)*xe-vr,ho=Kp-_r,po=Math.sqrt(fo*fo+ho*ho)+1e-5;if(po>yi)continue;const yr=(-1+Math.sqrt(1+4*De*po))/(2*De),gc=Math.exp(-(yr*yr)/ft),mc=ze(.06,.8,gc)*L*.26;if(mc<.004)continue;const on=xe/(1+2*De*yr)*.26*(.32+1.1*gc),vc=yr/po,go=vr+fo*vc,mo=_r+ho*vc;go<-on*1.6||go>k+on*1.6||mo<-on*1.6||mo>T+on*1.6||(q.globalAlpha=mc,q.save(),q.translate(go,mo),q.rotate(Pe),q.drawImage(Z,-on,-on,on*2,on*2),q.restore())}}q.globalAlpha=1}function Mt(Y){if(!oe)return;const q=R?Math.min(.05,(Y-R)/1e3):.016;R=Y;const ue=Y-K>2400?.6:1;L+=(ue-L)*Math.min(1,q*3.2);const xe=Math.min(.05,q);Ie+=(($-x)*$e-Ie*ae)*xe,Se+=((O-F)*$e-Se*ae)*xe,x+=Ie*xe,F+=Se*xe,N=(window.scrollY||window.pageYOffset||0)*.55;const Fe=Y/1e3,ft=x/(k||1)-.5,Nt=F/(T||1)-.5;let ht=ft*(ft>=0?ge:Ze)+Nt*(Nt>=0?bt:vn);ht>Te?ht=Te:ht<-Te&&(ht=-Te),Pe=wt+ht-N*6e-4,$t(),i?Dn(Fe):jn(Fe),M=requestAnimationFrame(Mt)}function Lt(Y){if(!oe)return;const q=t.getBoundingClientRect();!q.width||!k||!T||($=(Y.clientX-q.left)/q.width*k,O=(Y.clientY-q.top)/q.height*T,K=performance.now())}function dt(){oe||ao||e.matches||n.matches||!ye||document.hidden||(oe=!0,R=0,M=requestAnimationFrame(Mt))}function sn(){oe=!1,M&&(cancelAnimationFrame(M),M=0),R=0}function _i(){e.matches?(sn(),t.classList.remove("is-ready")):ye&&dt()}function Un(){n.matches?sn():ye&&dt()}function fc(){document.hidden?sn():ye&&dt()}const hc=new IntersectionObserver(Y=>{ye=Y[0]?.isIntersecting||!1,ye?dt():sn()},{threshold:0});hc.observe(t),window.addEventListener("pointermove",Lt,{passive:!0,capture:!0}),window.addEventListener("resize",$t),e.addEventListener("change",_i),n.addEventListener("change",Un),document.addEventListener("visibilitychange",fc);function Wp(){const Y=(s.match(/\sd="([^"]+)"/)||[])[1],q=document.createElement("canvas");q.width=256,q.height=256;const D=q.getContext("2d");if(Y&&window.Path2D){const ue=Math.min(8.533333333333333,8.421052631578947);D.setTransform(ue,0,0,ue,ue+(256-30*ue)/2,-6.4*ue),D.fillStyle="rgb(255,255,255)",D.fill(new Path2D(Y),"evenodd"),D.setTransform(1,0,0,1,0,0)}try{const ue=D.getImageData(0,0,256,256),xe=ue.data;for(let Fe=3;Feoe}}const by=120;function Ey(t,e,n){return tn?n:t}function de(t,e,n){return Ey((t-e)/(n-e),0,1)}function Sy(t){return t<.5?2*t*t:1-Math.pow(-2*t+2,2)/2}function Go(t){return 1-Math.pow(1-t,3)}function Ve(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 Ju(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(de(_,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}]),h=te(_,[{t:0,v:1},{t:2,v:.3},{t:4.6,v:1,e:Ve}]),d=te(_,[{t:0,v:0},{t:2,v:.3},{t:4.6,v:.16,e:Ve},{t:10.6,v:0}]),p=te(_,[{t:0,v:0},{t:2,v:-40},{t:4.6,v:0,e:Ve}]),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 b=de(_,.45,2.2);a=b>0?-2.6*(1-Ju(b)):0,g=te(_,[{t:0,v:1},{t:.57,v:0},{t:.67,v:0},{t:.92,v:1}]);const k=de(_,.67,2.42);f=k>0?-2.6*(1-Ju(k)):0,s=1-.05*(Math.sin(de(_,1.9,2.5)*Math.PI)+Math.sin(de(_,2.5,3.1)*Math.PI))}else if(t<74){let b=function(F){return[te(F,[{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(F,[{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=b;const _=t-60,k=1-de(_,12,14),T=b(de(_,0,12)),x=b(de(_-.5,0,12));n=T[0]*k,i=(T[1]+.05*Math.sin(_*7))*k,o=(x[0]-T[0])*.6*k,a=(x[1]-T[1])*.6*k,p=(x[0]-T[0])*30*k,E=de(_,0,.4)*k}else if(t<85.4){const _=t-74,b=te(_,[{t:0,v:0},{t:4,v:1},{t:8,v:.24},{t:9.6,v:1,e:Ve},{t:11.4,v:0}]);o=b*.5,d=-b*.5,l=te(_,[{t:0,v:0},{t:4,v:6},{t:8,v:20},{t:9.6,v:38,e:Ve},{t:11.4,v:0}]),p=-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,b=de(_,0,5.6),k=de(_,5.6,7.6),T=.72*Math.min(1,_/.6)*(1-k);d=Math.cos(b*Math.PI*2)*T,f=Math.sin(b*Math.PI*2)*T*.55,p=b*360*(1-k);const x=te(_,[{t:0,v:0},{t:7.6,v:0},{t:8.2,v:1,e:Go},{t:8.6,v:.55},{t:9.4,v:0}]);o=-.16*x,d+=.16*x,l=-6*x,p+=6*x,s=1+.05*x,m=1+.9*x}else if(t<108.6){const _=t-96.4,b=de(_,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-b),i=-.35*Math.abs(Math.sin(de(_,0,9.6)*Math.PI*3))*(1-b);const k=Math.sin(_*6.2)*(1-b);u=1+.12*k,h=1-.12*k,l=k*8,p=-k*8,o=.06*k,d=-.06*k,E=de(_,0,.4)*(1-b)}else{const _=t-108.6,b=Math.sin(de(_,0,8)*Math.PI),k=1-de(_,8,11.4);s=1+.04*b*k,i=-.1*b*k,r=2*b*k,m=1+.5*Math.sin(de(_,0,6)*Math.PI),v=1+.1*Math.sin(de(_,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=p,e.bsc=h,e.bfade=g,e.hfade=m,e.hsc=v,e.shd=E,e}function xy(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=by;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 p(M){const R=Math.min(1,Math.max(0,M.x))*c,Z=M.y*d;n.style.transform="translate3d("+R.toFixed(2)+"px,"+Z.toFixed(2)+"px,0) rotate("+M.rot.toFixed(2)+"deg) scale("+M.scale.toFixed(3)+")",i.style.transform="translate3d("+(M.ax*u).toFixed(2)+"px,"+(M.ay*u).toFixed(2)+"px,0) rotate("+M.ar.toFixed(2)+"deg) scale("+M.asc.toFixed(3)+")",i.style.opacity=M.afade.toFixed(3),r.style.transform="translate3d("+(M.bx*u).toFixed(2)+"px,"+(M.by*u).toFixed(2)+"px,0) rotate("+M.br.toFixed(2)+"deg) scale("+M.bsc.toFixed(3)+")",r.style.opacity=M.bfade.toFixed(3),s.style.transform="scale("+M.hsc.toFixed(3)+")",s.style.opacity=(.09*M.hfade).toFixed(3),o.style.transform="translateX("+R.toFixed(2)+"px) scaleX("+(.75+.4*Math.abs(M.x)).toFixed(3)+")",o.style.opacity=(M.shd*.5).toFixed(3)}let h=0,g=0,m=0,v=!1,E=!1,S=!1,_=0;function b(){return S||a.matches||document.hidden||!e.offsetParent?!1:E}function k(M){if(!v)return;if(m=requestAnimationFrame(k),!b()){x();return}const R=g?(M-g)/1e3:0;g=M,h=(h+Math.min(R,.1))%l,_+=1,p(Ri(h))}function T(){v||S||b()&&(v=!0,g=0,m=requestAnimationFrame(k))}function x(){v=!1,m&&(cancelAnimationFrame(m),m=0),g=0}function F(){b()?T():x()}function $(){a.matches?(x(),p(Ri(0))):F()}function O(){f(),v&&p(Ri(h))}function L(){g=0,F()}const N=new IntersectionObserver(M=>{E=M[0]?M[0].isIntersecting:!1,F()},{threshold:0});N.observe(e),window.addEventListener("resize",O),a.addEventListener("change",$),document.addEventListener("visibilitychange",L);function K(){S||(S=!0,x(),N.disconnect(),window.removeEventListener("resize",O),a.removeEventListener("change",$),document.removeEventListener("visibilitychange",L))}window.addEventListener("pagehide",K);function V(M){h=(M%l+l)%l,p(Ri(h))}return f(),p(Ri(0)),F(),{isRunning:()=>v,currentTime:()=>h,frameCount:()=>_,seek:V,dispose:K}}const Iy=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;function Xt(t){const e=String(t||"").trim().match(Iy);return e?{major:Number(e[1]),minor:Number(e[2]),patch:Number(e[3]),prerelease:e[4]?e[4].split("."):[]}:null}function ky(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 Ay(t){const e=Xt(t);return e?e.major>0?`${e.major+1}.0.0`:`0.${e.minor+1}.0`:null}function Tl(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 Xt(o)?{min:o,minInclusive:!0,max:Ay(o),maxInclusive:!1}:null}if(Xt(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(!Xt(a))return null;r=!0,o===">="||o===">"?(n.min=a,n.minInclusive=o===">="):(n.max=a,n.maxInclusive=o==="<=")}return r?n:null}function Zu(t,e){const n=Tl(t);if(!n||!Xt(e))return!1;if(n.min!==null){const i=ws(e,n.min);if(i<0||i===0&&!n.minInclusive)return!1}if(n.max!==null){const i=ws(e,n.max);if(i>0||i===0&&!n.maxInclusive)return!1}return!0}function Py(t,e){const n=Tl(t);if(!n||!Xt(e))return!1;if(n.max===null)return!0;const i=ws(n.max,e);return i>0?!0:i===0&&n.maxInclusive}function Vn(t){const e=Tl(t);return e?e.min:null}const Fy="https://pub.dev/api/packages/",Ry=8e3;function Ty(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||Cy(a))continue;const l=o.pubspec?.environment||{};n&&l.sdk&&!Zu(l.sdk,n)||i&&l.flutter&&!Zu(l.flutter,i)||(!s||ws(a,s)>0)&&(s=a)}return s?{version:s,constraint:`^${s}`}:null}async function $y(t,e={}){const{dartSdkFloor:n=null,flutterSdkFloor:i=null,fetchImpl:r=fetch}=e;let s;try{const a=await r(`${Fy}${encodeURIComponent(t)}`,{signal:AbortSignal.timeout(Ry)});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=Ty(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 My(t,e={}){const n=await Promise.all(t.map(i=>$y(i,e)));return new Map(n.map(({name:i,...r})=>[i,r]))}async function Ly(t,e={},n={}){const{resolveVersions:i=My}=n,r=Object.entries(e).filter(([d])=>d&&d!=="flutter"),s=Fh(t),o={dartSdkFloor:Vn(s.sdk),flutterSdkFloor:Vn(s.flutter)},a={additions:{},overrides:{},kept:[],warnings:[],sdk:o};if(r.length===0)return a;const l=Ds(t),u=[],c=[];for(const[d,f]of r){const p=l.get(d);if(!p){(u_.has(d)?c:u).push(d);continue}const h=Vn(f);if(!h){a.kept.push({name:d,constraint:p.constraint});continue}const g=p.isScalar?p.constraint:p.sourceKey===null?p.version:null;if(g===null){a.warnings.push(`"${d}" 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:d,constraint:p.constraint});continue}if(Py(g,h)){a.kept.push({name:d,constraint:g});continue}a.overrides[d]=`^${h}`,a.warnings.push(`"${d}" was pinned to ${g} 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.`)}for(const d of c)a.additions[d]={sdk:"flutter"};if(u.length>0){const d=await i(u,o);for(const f of u){const p=d.get(f);if(p?.constraint){a.additions[f]=p.constraint;continue}const h=e[f]||"";if(Vn(h)){a.additions[f]=`^${Vn(h)}`,a.warnings.push(`Could not confirm "${f}" version on pub.dev (${p?.error||"lookup failed"}). Using ^${Vn(h)} from the AI's recommendation — verify this is current.`);continue}a.additions[f]=">=0.0.0",a.warnings.push(`Could not determine a version for "${f}" (${p?.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 Ny={"&":"&","<":"<",">":">",'"':""","'":"'"};function Qt(t){return String(t??"").replace(/[&<>"']/g,e=>Ny[e])}function z(t){return t?Qt(t).replace(/\n/g,"
"):""}function Jt(t){return Qt(t).replace(/\r?\n/g," ")}function js(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 Bh(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 Oy(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 By(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 Dy(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 di(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 Xu(t){return t=Qt(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 Dh(t,e="dart",n=globalThis.hljs){if(!t)return"";const i=di(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 Qt(i)}}}function Us(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=Dy(o),u=Dh(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+=`

- ${Ay(l)} + ${Oy(l)} ${Qt(l)}

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

- ${Py(l)} + ${By(l)} ${Qt(l)}

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

${Zu(a)}

`)}return i+="
",` + ${Xu(l)} +
`;continue}a.trim()!==""&&(i+=`

${Xu(a)}

`)}return i+="
",`
@@ -78,14 +79,14 @@ in vec2 p; void main(){ gl_Position = vec4(p, 0.0, 1.0); }`;function a(){return[
${i}
- `}const Ry=[[/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"]],Ty=220,$y=6;function Xu(t,e){return!!(t&&t.trim())&&!e}function My(t,e=""){if(typeof t!="string"||!t||t===e||t.trim().length<$y||/[.!?]\s*$/.test(t))return null;const n=Ry.find(([i])=>i.test(t));return n?n[1]:null}function Ly(){let t="",e="";return{get active(){return t},resolve(n){return t=My(n,e)??"",t},dismiss(){t=""},accept(n){if(!t)return null;const i=n+t;return e=i,t="",i}}}function Ny({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=document.getElementById("btn-add-images"),c=document.getElementById("prompt-image-input"),d=window.matchMedia("(prefers-reduced-motion: reduce)"),f=Ly();let h=!1,p=!1,g=!1,m=!1,v=null,E=null;function S(){i.disabled=!Xu(n.value,p||g||m)}function _(){r&&(r.textContent=n.value)}function b(){s&&(s.textContent=""),_(),e.classList.remove("has-suggest"),o&&(o.hidden=!0,o.tabIndex=-1),a&&(a.textContent="")}function k(R){s&&(s.textContent=R),_(),e.classList.add("has-suggest"),o&&(o.hidden=!1,o.tabIndex=0,o.setAttribute("aria-label","Accept suggestion: "+R.trim())),a&&(a.textContent="Suggestion: "+R+". Press Tab to accept.")}function T(){f.dismiss(),b()}function x(){if(h||p)return;const R=f.resolve(n.value);R&&k(R)}function F(){clearTimeout(v),!h&&(v=setTimeout(x,Ty))}function $(){const R=f.accept(n.value);return R===null?!1:(n.value=R,b(),S(),!0)}function O(R){p=R,e.classList.toggle("is-busy",R),i.classList.toggle("is-busy",R),i.setAttribute("aria-label",R?"Generating":"Generate"),n.readOnly=R,l.forEach(Z=>{Z.disabled=R}),u&&(u.disabled=R),c&&(c.disabled=R),S()}async function L(){if(Xu(n.value,p||g||m)){T(),O(!0);try{await t()}finally{O(!1)}}}function N(){g=!1,E&&(clearInterval(E),E=null),e.classList.remove("is-demo-typing"),S()}function K(){l.forEach(R=>{R.classList.remove("is-active"),R.setAttribute("aria-pressed","false")})}function V(){try{n.focus({preventScroll:!0}),n.setSelectionRange(n.value.length,n.value.length)}catch{}}function M(R){const Z=R.dataset.prompt||"";if(N(),clearTimeout(v),v=null,T(),l.forEach(oe=>{const ye=oe===R;oe.classList.toggle("is-active",ye),oe.setAttribute("aria-pressed",String(ye))}),d.matches||!Z){n.value=Z,_(),S(),V();return}n.value="",_(),g=!0,S(),e.classList.add("is-demo-typing");let Ce=0;E=setInterval(()=>{Ce+=1,n.value=Z.slice(0,Ce),_(),Ce>=Z.length?(N(),V()):S()},22)}return l.forEach(R=>{R.setAttribute("aria-pressed","false"),R.addEventListener("click",()=>M(R))}),n.addEventListener("keydown",R=>{if(g&&R.key==="Enter"&&!R.shiftKey&&!R.isComposing&&!h){R.preventDefault();return}N(),R.key==="Tab"&&!R.shiftKey&&f.active?(R.preventDefault(),$()):R.key==="Escape"?(clearTimeout(v),v=null,T()):R.key==="Enter"&&!R.shiftKey&&!R.isComposing&&!h&&(R.preventDefault(),L())}),n.addEventListener("input",()=>{N(),K(),T(),S(),F()}),n.addEventListener("compositionstart",()=>{h=!0}),n.addEventListener("compositionend",()=>{h=!1,T(),S(),F()}),n.addEventListener("scroll",()=>{r&&r.parentNode&&(r.parentNode.scrollTop=n.scrollTop)}),o&&o.addEventListener("click",()=>{$(),n.focus({preventScroll:!0})}),i.addEventListener("click",L),n.addEventListener("pointerdown",()=>{N(),K()}),_(),S(),{setAttachmentsPending(R){m=!!R,S()}}}const Oy="https://ccc-ffai-runner-y5cyj3473a-uw.a.run.app/deployCustomClasses";const _t="https://4tgke4.buildship.run",Lh={professional:"price_1T2ldCKszA2slvDXatdeCpbI",power:"price_1T2le9KszA2slvDXR4mPvw7M"},ys="ccc_auth_session",Ua="ccc_signin_return",By=1800*1e3,Qu=new WeakSet;let H={email:null,sessionToken:null,isVerified:!1};function Mn(t={}){return{tier:"free",status:"none",periodEnd:null,isLoading:!1,isResolved:!1,error:null,...t}}let ce=Mn({isResolved:!0}),Ha=Promise.resolve();const Dy=`${_t}/service/runpipeline`,jy="bs_user_id",Uy="bs_identity_token",Hy=`${_t}/authUserCheck`;let pt={userId:null,token:null,status:null,resolved:!1};const ws=wv,bs="ccc_subscription",ed=3,Wy=new Set(["active","trialing","paid"]),Es="google/gemini-3.7-flash",jr=["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"],zy={"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 Gt(t){return zy[t]||t}const qy=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 Nh(t){return qy.has(t)}const Wa=4,Ko=8*1024*1024,Vy="https://4tgke4.buildship.run/service/runpipeline-image";let Oe=[];const pn=[],Gy=3e4;let Oh=null;function Ky(t){return new Promise(e=>{const n=new FileReader;n.onload=()=>e(n.result),n.onerror=()=>e(null),n.readAsDataURL(t)})}async function Yy(t,e){const n=new FormData;return n.append("file",t),(await fetch(Vy,{method:"POST",body:n,signal:e})).json()}function Jy(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 Zy(t,e,n){const i=await Ky(t);i&&Oe.includes(e)&&(e.dataUrl=i,cn());let r="";if(i)try{r=Jy(await Yy(t,n))}catch{r=""}return Oe.includes(e)?!i||!r?(Oe.splice(Oe.indexOf(e),1),cn(),"failed"):(e.url=r,cn(),"added"):"dropped"}function Bh(t){const e=pn.indexOf(t);e>=0&&pn.splice(e,1),jh()}function Dh(t){t.controller.abort(),Bh(t);const e=Oe.indexOf(t.slot);e>=0&&(Oe.splice(e,1),cn())}function jh(){Oh?.setAttachmentsPending(pn.length>0)}async function Xy(t){const e=Array.from(t.target.files||[]);if(!e.length)return;if(t.target.value="",y.isRunning){Ee("Wait for the current generation to finish before attaching images.","info");return}const n=e.filter(u=>u.size>Ko);n.length&&Ee(`Skipped ${n.length} image(s) over the ${(Ko/1024/1024).toFixed(0)} MB limit.`,"warning");const i=e.filter(u=>u.size<=Ko);if(!i.length)return;const r=Wa-Oe.length,s=i.slice(0,r);if(i.length>r&&Ee(`You can attach up to ${Wa} images.`,"info"),!s.length)return;const o=s.map(u=>{const c={dataUrl:null,name:u.name,url:null};Oe.push(c);const d={slot:c,controller:new AbortController},f=setTimeout(()=>d.controller.abort(),Gy);return d.job=Zy(u,c,d.controller.signal),pn.push(d),d.job.finally(()=>{clearTimeout(f),Bh(d)}),d.job});cn(),jh();const l=(await Promise.all(o)).filter(u=>u==="failed").length;l&&Ee(`${l} image(s) could not be uploaded and were not attached.`,"error")}function Qy(t){const e=Oe[t],n=pn.find(i=>i.slot===e);if(n){Dh(n);return}Oe.splice(t,1),cn()}function cn(){const t=document.getElementById("prompt-image-thumbnails"),e=document.getElementById("prompt-image-btn-label");t&&(t.innerHTML="",Oe.forEach((n,i)=>{const r=document.createElement("div");r.className="prompt-img-thumb"+(n.url?"":" is-pending"),r.innerHTML=(n.dataUrl?`Prompt image`:"")+``,t.appendChild(r)}),e&&(e.textContent=Oe.length>=Wa?"Image limit reached":"Add images"))}function Tl(){const t=document.getElementById("prompt-image-upload");if(!t)return;const e=document.getElementById("code-generator-model"),n=Nh(e?.value);t.classList.toggle("hidden",!n),!n&&Oe.length&&(pn.slice().forEach(Dh),Oe=[],cn())}const Fn="ccc_usage",Uh="google/gemini-3.7-flash",Hh="google/gemini-3.7-flash",Fr="google/gemini-3.7-flash",Di={professional:11,power:49},za={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"},Ur={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 Hr={...Ur};async function e0(){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(Ur),...Object.values(qa),...Object.values(za)]);for(const a of o)a!=="AUD"&&(typeof r[a]=="number"&&r[a]>0?s[a]=r[a]:Ur[a]&&(s[a]=Ur[a]));Hr=s}catch{}finally{clearTimeout(e)}}const qa={"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 $l(){try{const s=Intl.DateTimeFormat().resolvedOptions().timeZone;if(s&&qa[s])return qa[s]}catch{}const e=(navigator.language||"en-US").replace("-","_"),n=za[e];if(n)return n;const i=e.split("_")[0],r=za[i];return r||"USD"}function ji(t,e){const n=Hr[e]??Hr.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*Hr.USD)}}const gt="ccc_api_key_",Pt="ccc_session_api_key_",Rt="ccc_encryption_key",sr="ccc_encryption_key_scope",t0="ccc_keystore",Ss="keys",or="ccc_encryption_key_version";let Va=null,xs=null,ar=!1,Is=!1,td=!1;class ks extends Error{constructor(){super("Secure browser key storage is unavailable."),this.name="CredentialStorageUnavailableError"}}function nd(){if(td)return;td=!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&&Ee(t,"warning")}function Wh(){return localStorage.getItem(or)||""}function Ga(){return crypto.randomUUID?.()||qh(crypto.getRandomValues(new Uint8Array(16)))}function n0(){const t=Wh();if(t)return t;const e=Ga();return localStorage.setItem(or,e),e}function di(){Va=null,xs=null,ar=!1,Is=!1}window.addEventListener("storage",t=>{t.key===or&&di()});function i0(){return new Promise((t,e)=>{const n=indexedDB.open(t0,1);n.onupgradeneeded=()=>{const i=n.result;i.objectStoreNames.contains(Ss)||i.createObjectStore(Ss)},n.onsuccess=()=>t(n.result),n.onerror=()=>e(n.error)})}async function Ml(t,e){const n=await i0();return new Promise((i,r)=>{const s=n.transaction(Ss,t);let o;try{o=e(s.objectStore(Ss))}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 r0(t){return t instanceof CryptoKey&&t.algorithm?.name==="AES-GCM"&&t.extractable===!1&&t.usages.includes("encrypt")&&t.usages.includes("decrypt")}async function s0(){const t=await Ml("readonly",e=>e.get(Rt));return r0(t)?t:null}async function zh(t){await Ml("readwrite",e=>e.put(t,Rt))}async function o0(){di();try{await Ml("readwrite",t=>t.delete(Rt))}catch(t){console.warn("Could not delete the stored encryption key:",t)}}async function a0(){const t=sessionStorage.getItem(Rt);if(!t)return null;const e=await crypto.subtle.importKey("jwk",JSON.parse(t),{name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);return await zh(e),sessionStorage.removeItem(Rt),sessionStorage.removeItem(sr),localStorage.removeItem(gt+"salt"),e}async function id(t){const e=sessionStorage.getItem(Rt);if(e)return Is=sessionStorage.getItem(sr)!=="session",crypto.subtle.importKey("jwk",JSON.parse(e),{name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);if(!t)throw new ks;const n=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!0,["encrypt","decrypt"]),i=await crypto.subtle.exportKey("jwk",n);return sessionStorage.setItem(Rt,JSON.stringify(i)),sessionStorage.setItem(sr,"session"),Is=!1,crypto.subtle.importKey("jwk",i,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}async function l0(t){if(sessionStorage.getItem(sr)==="session"&&sessionStorage.getItem(Rt))return nd(),ar=!0,id(t);try{const e=await s0();if(e)return e;const n=await a0();if(n)return n;const i=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);return await zh(i),i}catch(e){return console.warn("IndexedDB encryption-key storage failed:",e),nd(),ar=!0,id(t)}}async function Ll(t={}){const{allowSessionFallbackCreation:e=!0}=t,n=n0();xs!==n&&di();const i=Va||l0(e);Va=i,xs=n;try{return await i}catch(r){throw di(),r}}async function c0(t){const e=await Ll(),n=xs,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:qh(o),keyVersion:n,sessionFallback:ar}}async function u0(t,e={}){const{isSessionCredential:n=!1}=e;try{const i=await Ll({allowSessionFallbackCreation:!1});if(ar&&!n&&!Is)throw new ks;const r=d0(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 ks)throw i;return console.error("Decryption failed:",i),null}}function qh(t){const e=new Uint8Array(t);let n="";for(let i=0;i0}let Ln="",fi="",Gi=null,sd=0,it="not-configured";async function Nl(){sessionStorage.getItem(Rt)&&await Ll(),Ln=await Re("flutterflow"),fi=await Re("flutterflow_project_id"),y0(),rn(),Ln?jl():(it="not-configured",vt())}let lr=!1;function Vh(){const t=document.getElementById("api-keys-modal");We(t),Dl(),Ln&&Ul(Ln)}function Ol(){lr=!1,Vh()}function h0(){lr=!0;const t=document.getElementById("walkthrough-modal");t&&ze(t),Vh()}let od=!1;function ad(){const t=document.getElementById("code-generator-model"),e=document.getElementById("composer-settings-model");if(!t||!e)return;e.value=t.value;const n=Array.from(t.options);Array.from(e.options).forEach((r,s)=>{const o=n[s];o&&(r.textContent=o.textContent)});const i=document.getElementById("composer-settings-free-notice");i&&(document.getElementById("model-selector-free-notice")?(i.hidden=!1,i.innerHTML='Free plan — Gemini only. '):i.hidden=!0)}function ld(){const t=document.getElementById("code-generator-model"),e=document.getElementById("composer-image-capability"),n=document.getElementById("composer-image-capability-note");if(!t)return;const i=Gt(t.value),r=Nh(t.value);e&&(e.textContent=r?"Supported":"Not supported"),n&&(n.textContent=r?`${i} accepts reference images you attach to the prompt.`:`Images can't be attached with ${i}. Attached images are removed when you switch to it.`),Tl()}function p0(){if(lr=!1,ad(),ld(),!od){const e=document.getElementById("composer-settings-model");e&&e.addEventListener("change",()=>{const n=document.getElementById("code-generator-model");n.value=e.value,n.dispatchEvent(new Event("change")),ad(),ld()}),od=!0}const t=document.querySelector('.composer [aria-label="Generation settings"]');We("composer-settings-modal",{trigger:t})}function g0(t){t&&t.target!==t.currentTarget||ze("composer-settings-modal")}function Gh(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("api-keys-modal");e&&ze(e);const n=lr;if(lr=!1,n){const i=document.getElementById("walkthrough-modal");i&&(it==="connected"&&Bl(),We(i))}}let en=1;function Kh(){const t=document.querySelector(".wt-steps");return t?Array.from(t.querySelectorAll(".wt-step-card")):[]}function Hs(){const t=Kh();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===en?(e.classList.add("wt-current"),r&&(r.textContent=i)):i0&&en<=t&&(en++,Hs())}function m0(){const t=document.getElementById("walkthrough-modal");t&&(en=1,Hs(),We(t))}function v0(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("walkthrough-modal");e&&ze(e);const n=document.getElementById("walkthrough-dont-show");n&&n.checked&&localStorage.setItem("hasSeenWalkthrough","true")}function Yh(){if(H.isVerified&&Tt()&&ce.tier!=="free")return;if(!localStorage.getItem("hasSeenWalkthrough")){const e=document.getElementById("walkthrough-modal");e&&(en=1,Hs(),We(e))}}async function Dl(){const t=document.getElementById("flutterflow-api-key-input");Ln?(t.value="",t.placeholder="Key saved (enter new to replace)"):t.placeholder="Enter your FlutterFlow API key",_0()}function _0(){cd("flutterflow","flutterflow-key-status"),cd("flutterflow_project_id","flutterflow-project-status")}function cd(t,e){const n=document.getElementById(e);if(!n)return;const i=n.querySelector(".key-status-dot"),r=n.querySelector("span");Ct(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 y0(){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"?Ct("flutterflow")&&Ct("flutterflow_project_id")?(i.className="key-status-dot configured",i.title="FlutterFlow (Fully configured)"):Ct("flutterflow")||Ct("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)"):Ct(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 w0(){const t=document.getElementById("flutterflow-api-key-input"),e=document.getElementById("flutterflow-projects-select"),n=t.value.trim(),i=e?.value.trim()||"";if(n){const o=await Re("flutterflow").catch(()=>"");await rd("flutterflow",n),n!==o&&!i&&Jh()}if(i){if(!Ws(i)){Ee("The selected FlutterFlow project has an unexpected ID format.","error"),e.focus();return}await rd("flutterflow_project_id",i)}await Nl(),n&&await jl(),Dl();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"),Gh()},1e3)}async function b0(){if(!confirm("Are you sure you want to clear all stored API keys?"))return;localStorage.setItem(or,Ga()),di(),localStorage.removeItem(gt+"flutterflow"),localStorage.removeItem(gt+"flutterflow_project_id"),sessionStorage.removeItem(Pt+"flutterflow"),sessionStorage.removeItem(Pt+"flutterflow_project_id"),sessionStorage.removeItem(Rt),sessionStorage.removeItem(sr),localStorage.removeItem(gt+"salt"),await o0(),localStorage.setItem(or,Ga()),localStorage.removeItem(gt+"flutterflow"),localStorage.removeItem(gt+"flutterflow_project_id"),sessionStorage.removeItem(Pt+"flutterflow"),sessionStorage.removeItem(Pt+"flutterflow_project_id"),await Nl();const t=document.getElementById("flutterflow-projects-select");t&&(t.innerHTML=''),Dl()}function Ws(t){return!t||t.trim().length<5||t.includes(" ")?!1:/^[a-zA-Z0-9-]+$/.test(t)}function vt(){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=yt();n.textContent=o.includes("staging")?"Staging":"Production"}if(i&&(i.textContent=fi||"—"),!e)return;let r,s;if(!Ct("flutterflow"))r="Not connected — add your FlutterFlow API key",s="";else switch(it){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 jl(){const t=await Re("flutterflow");if(!t||!Ct("flutterflow"))return it="not-configured",vt(),null;it="validating",vt();try{const n=await new mi(t,"","main",yt()).listProjects();return it=n&&n.length>0?"connected":"no-projects",vt(),n}catch(e){const n=String(e&&e.message||"");return it=/(401|403)|denied|unauthorized|scoped|list permission/i.test(n)?"unauthorized":"network-error",vt(),null}}function Jh(){fi="",localStorage.removeItem(gt+"flutterflow_project_id"),sessionStorage.removeItem(Pt+"flutterflow_project_id")}function E0(){Jh();const t=document.getElementById("flutterflow-projects-select");t&&(t.innerHTML='',t.value=""),Ct("flutterflow")?(it="validating",Ul(Ln)):it="not-configured",vt()}function S0(t,e){const n=document.getElementById(t);n&&(n.value?e?n.style.borderColor="#22c55e":n.style.borderColor="#ef4444":n.style.borderColor="")}function x0(){const t=document.getElementById("flutterflow-api-key-input");t&&(t.addEventListener("input",e=>{const n=e.target.value.trim().length>0;S0("flutterflow-api-key-input",n)}),t.addEventListener("blur",I0(async e=>{const n=e.target.value.trim();n&&await Ul(n)},500)))}function I0(t,e){let n;return function(...r){const s=()=>{clearTimeout(n),t(...r)};clearTimeout(n),n=setTimeout(s,e)}}async function Ul(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"),(Ct("flutterflow")||t)&&(it="validating"),vt();try{const r=await new mi(t,"","main",yt()).listProjects();if(!r||r.length===0){it="no-projects",vt(),e.innerHTML='';return}it="connected",vt(),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)}),fi&&(e.value=fi)}catch(i){console.error("Failed to fetch projects:",i);const r=String(i&&i.message||"");it=/(401|403)|denied|unauthorized|scoped|list permission/i.test(r)?"unauthorized":"network-error",vt(),e.innerHTML='',n&&(n.textContent=`Failed to load projects: ${i.message}`,n.classList.remove("hidden"))}}function k0(t){const e=document.getElementById(t),i=e.nextElementSibling.querySelector("svg");e.type==="password"?(e.type="text",i.innerHTML=` + `}const jy=[[/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"]],Uy=220,Hy=6;function Qu(t,e){return!!(t&&t.trim())&&!e}function Wy(t,e=""){if(typeof t!="string"||!t||t===e||t.trim().lengthi.test(t));return n?n[1]:null}function qy(){let t="",e="";return{get active(){return t},resolve(n){return t=Wy(n,e)??"",t},dismiss(){t=""},accept(n){if(!t)return null;const i=n+t;return e=i,t="",i}}}function zy({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=document.getElementById("btn-add-images"),c=document.getElementById("prompt-image-input"),d=window.matchMedia("(prefers-reduced-motion: reduce)"),f=qy();let p=!1,h=!1,g=!1,m=!1,v=null,E=null;function S(){i.disabled=!Qu(n.value,h||g||m)}function _(){r&&(r.textContent=n.value)}function b(){s&&(s.textContent=""),_(),e.classList.remove("has-suggest"),o&&(o.hidden=!0,o.tabIndex=-1),a&&(a.textContent="")}function k(R){s&&(s.textContent=R),_(),e.classList.add("has-suggest"),o&&(o.hidden=!1,o.tabIndex=0,o.setAttribute("aria-label","Accept suggestion: "+R.trim())),a&&(a.textContent="Suggestion: "+R+". Press Tab to accept.")}function T(){f.dismiss(),b()}function x(){if(p||h)return;const R=f.resolve(n.value);R&&k(R)}function F(){clearTimeout(v),!p&&(v=setTimeout(x,Uy))}function $(){const R=f.accept(n.value);return R===null?!1:(n.value=R,b(),S(),!0)}function O(R){h=R,e.classList.toggle("is-busy",R),i.classList.toggle("is-busy",R),i.setAttribute("aria-label",R?"Generating":"Generate"),n.readOnly=R,l.forEach(Z=>{Z.disabled=R}),u&&(u.disabled=R),c&&(c.disabled=R),S()}async function L(){if(Qu(n.value,h||g||m)){T(),O(!0);try{await t()}finally{O(!1)}}}function N(){g=!1,E&&(clearInterval(E),E=null),e.classList.remove("is-demo-typing"),S()}function K(){l.forEach(R=>{R.classList.remove("is-active"),R.setAttribute("aria-pressed","false")})}function V(){try{n.focus({preventScroll:!0}),n.setSelectionRange(n.value.length,n.value.length)}catch{}}function M(R){const Z=R.dataset.prompt||"";if(N(),clearTimeout(v),v=null,T(),l.forEach(oe=>{const ye=oe===R;oe.classList.toggle("is-active",ye),oe.setAttribute("aria-pressed",String(ye))}),d.matches||!Z){n.value=Z,_(),S(),V();return}n.value="",_(),g=!0,S(),e.classList.add("is-demo-typing");let Ce=0;E=setInterval(()=>{Ce+=1,n.value=Z.slice(0,Ce),_(),Ce>=Z.length?(N(),V()):S()},22)}return l.forEach(R=>{R.setAttribute("aria-pressed","false"),R.addEventListener("click",()=>M(R))}),n.addEventListener("keydown",R=>{if(g&&R.key==="Enter"&&!R.shiftKey&&!R.isComposing&&!p){R.preventDefault();return}N(),R.key==="Tab"&&!R.shiftKey&&f.active?(R.preventDefault(),$()):R.key==="Escape"?(clearTimeout(v),v=null,T()):R.key==="Enter"&&!R.shiftKey&&!R.isComposing&&!p&&(R.preventDefault(),L())}),n.addEventListener("input",()=>{N(),K(),T(),S(),F()}),n.addEventListener("compositionstart",()=>{p=!0}),n.addEventListener("compositionend",()=>{p=!1,T(),S(),F()}),n.addEventListener("scroll",()=>{r&&r.parentNode&&(r.parentNode.scrollTop=n.scrollTop)}),o&&o.addEventListener("click",()=>{$(),n.focus({preventScroll:!0})}),i.addEventListener("click",L),n.addEventListener("pointerdown",()=>{N(),K()}),_(),S(),{setAttachmentsPending(R){m=!!R,S()}}}const Vy="https://ccc-ffai-runner-y5cyj3473a-uw.a.run.app/deployCustomClasses";const _t="https://4tgke4.buildship.run",jh={professional:"price_1T2ldCKszA2slvDXatdeCpbI",power:"price_1T2le9KszA2slvDXR4mPvw7M"},bs="ccc_auth_session",Ua="ccc_signin_return",Gy=1800*1e3,ed=new WeakSet;let H={email:null,sessionToken:null,isVerified:!1};function Ln(t={}){return{tier:"free",status:"none",periodEnd:null,isLoading:!1,isResolved:!1,error:null,...t}}let ce=Ln({isResolved:!0}),Ha=Promise.resolve();const Ky=`${_t}/service/runpipeline`,Yy="bs_user_id",Jy="bs_identity_token",Zy=`${_t}/authUserCheck`;let pt={userId:null,token:null,status:null,resolved:!1};const Es=Iv,Ss="ccc_subscription",td=3,Xy=new Set(["active","trialing","paid"]),xs="google/gemini-3.7-flash",Hr=["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"],Qy={"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 Gt(t){return Qy[t]||t}const e0=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 Uh(t){return e0.has(t)}const Wa=4,Ko=8*1024*1024,t0="https://4tgke4.buildship.run/service/runpipeline-image";let Oe=[];const gn=[],n0=3e4;let Hh=null;function i0(t){return new Promise(e=>{const n=new FileReader;n.onload=()=>e(n.result),n.onerror=()=>e(null),n.readAsDataURL(t)})}async function r0(t,e){const n=new FormData;return n.append("file",t),(await fetch(t0,{method:"POST",body:n,signal:e})).json()}function s0(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 o0(t,e,n){const i=await i0(t);i&&Oe.includes(e)&&(e.dataUrl=i,cn());let r="";if(i)try{r=s0(await r0(t,n))}catch{r=""}return Oe.includes(e)?!i||!r?(Oe.splice(Oe.indexOf(e),1),cn(),"failed"):(e.url=r,cn(),"added"):"dropped"}function Wh(t){const e=gn.indexOf(t);e>=0&&gn.splice(e,1),zh()}function qh(t){t.controller.abort(),Wh(t);const e=Oe.indexOf(t.slot);e>=0&&(Oe.splice(e,1),cn())}function zh(){Hh?.setAttachmentsPending(gn.length>0)}async function a0(t){const e=Array.from(t.target.files||[]);if(!e.length)return;if(t.target.value="",y.isRunning){Ee("Wait for the current generation to finish before attaching images.","info");return}const n=e.filter(u=>u.size>Ko);n.length&&Ee(`Skipped ${n.length} image(s) over the ${(Ko/1024/1024).toFixed(0)} MB limit.`,"warning");const i=e.filter(u=>u.size<=Ko);if(!i.length)return;const r=Wa-Oe.length,s=i.slice(0,r);if(i.length>r&&Ee(`You can attach up to ${Wa} images.`,"info"),!s.length)return;const o=s.map(u=>{const c={dataUrl:null,name:u.name,url:null};Oe.push(c);const d={slot:c,controller:new AbortController},f=setTimeout(()=>d.controller.abort(),n0);return d.job=o0(u,c,d.controller.signal),gn.push(d),d.job.finally(()=>{clearTimeout(f),Wh(d)}),d.job});cn(),zh();const l=(await Promise.all(o)).filter(u=>u==="failed").length;l&&Ee(`${l} image(s) could not be uploaded and were not attached.`,"error")}function l0(t){const e=Oe[t],n=gn.find(i=>i.slot===e);if(n){qh(n);return}Oe.splice(t,1),cn()}function cn(){const t=document.getElementById("prompt-image-thumbnails"),e=document.getElementById("prompt-image-btn-label");t&&(t.innerHTML="",Oe.forEach((n,i)=>{const r=document.createElement("div");r.className="prompt-img-thumb"+(n.url?"":" is-pending"),r.innerHTML=(n.dataUrl?`Prompt image`:"")+``,t.appendChild(r)}),e&&(e.textContent=Oe.length>=Wa?"Image limit reached":"Add images"))}function $l(){const t=document.getElementById("prompt-image-upload");if(!t)return;const e=document.getElementById("code-generator-model"),n=Uh(e?.value);t.classList.toggle("hidden",!n),!n&&Oe.length&&(gn.slice().forEach(qh),Oe=[],cn())}const Rn="ccc_usage",Vh="google/gemini-3.7-flash",Gh="google/gemini-3.7-flash",Tr="google/gemini-3.7-flash",Di={professional:11,power:49},qa={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 qr={...Wr};async function c0(){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(za),...Object.values(qa)]);for(const a of o)a!=="AUD"&&(typeof r[a]=="number"&&r[a]>0?s[a]=r[a]:Wr[a]&&(s[a]=Wr[a]));qr=s}catch{}finally{clearTimeout(e)}}const za={"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 Ml(){try{const s=Intl.DateTimeFormat().resolvedOptions().timeZone;if(s&&za[s])return za[s]}catch{}const e=(navigator.language||"en-US").replace("-","_"),n=qa[e];if(n)return n;const i=e.split("_")[0],r=qa[i];return r||"USD"}function ji(t,e){const n=qr[e]??qr.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*qr.USD)}}const gt="ccc_api_key_",Pt="ccc_session_api_key_",Rt="ccc_encryption_key",sr="ccc_encryption_key_scope",u0="ccc_keystore",Is="keys",or="ccc_encryption_key_version";let Va=null,ks=null,ar=!1,Cs=!1,nd=!1;class As extends Error{constructor(){super("Secure browser key storage is unavailable."),this.name="CredentialStorageUnavailableError"}}function id(){if(nd)return;nd=!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&&Ee(t,"warning")}function Kh(){return localStorage.getItem(or)||""}function Ga(){return crypto.randomUUID?.()||Jh(crypto.getRandomValues(new Uint8Array(16)))}function d0(){const t=Kh();if(t)return t;const e=Ga();return localStorage.setItem(or,e),e}function fi(){Va=null,ks=null,ar=!1,Cs=!1}window.addEventListener("storage",t=>{t.key===or&&fi()});function f0(){return new Promise((t,e)=>{const n=indexedDB.open(u0,1);n.onupgradeneeded=()=>{const i=n.result;i.objectStoreNames.contains(Is)||i.createObjectStore(Is)},n.onsuccess=()=>t(n.result),n.onerror=()=>e(n.error)})}async function Ll(t,e){const n=await f0();return new Promise((i,r)=>{const s=n.transaction(Is,t);let o;try{o=e(s.objectStore(Is))}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 h0(t){return t instanceof CryptoKey&&t.algorithm?.name==="AES-GCM"&&t.extractable===!1&&t.usages.includes("encrypt")&&t.usages.includes("decrypt")}async function p0(){const t=await Ll("readonly",e=>e.get(Rt));return h0(t)?t:null}async function Yh(t){await Ll("readwrite",e=>e.put(t,Rt))}async function g0(){fi();try{await Ll("readwrite",t=>t.delete(Rt))}catch(t){console.warn("Could not delete the stored encryption key:",t)}}async function m0(){const t=sessionStorage.getItem(Rt);if(!t)return null;const e=await crypto.subtle.importKey("jwk",JSON.parse(t),{name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);return await Yh(e),sessionStorage.removeItem(Rt),sessionStorage.removeItem(sr),localStorage.removeItem(gt+"salt"),e}async function rd(t){const e=sessionStorage.getItem(Rt);if(e)return Cs=sessionStorage.getItem(sr)!=="session",crypto.subtle.importKey("jwk",JSON.parse(e),{name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);if(!t)throw new As;const n=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!0,["encrypt","decrypt"]),i=await crypto.subtle.exportKey("jwk",n);return sessionStorage.setItem(Rt,JSON.stringify(i)),sessionStorage.setItem(sr,"session"),Cs=!1,crypto.subtle.importKey("jwk",i,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}async function v0(t){if(sessionStorage.getItem(sr)==="session"&&sessionStorage.getItem(Rt))return id(),ar=!0,rd(t);try{const e=await p0();if(e)return e;const n=await m0();if(n)return n;const i=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);return await Yh(i),i}catch(e){return console.warn("IndexedDB encryption-key storage failed:",e),id(),ar=!0,rd(t)}}async function Nl(t={}){const{allowSessionFallbackCreation:e=!0}=t,n=d0();ks!==n&&fi();const i=Va||v0(e);Va=i,ks=n;try{return await i}catch(r){throw fi(),r}}async function _0(t){const e=await Nl(),n=ks,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:Jh(o),keyVersion:n,sessionFallback:ar}}async function y0(t,e={}){const{isSessionCredential:n=!1}=e;try{const i=await Nl({allowSessionFallbackCreation:!1});if(ar&&!n&&!Cs)throw new As;const r=w0(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 As)throw i;return console.error("Decryption failed:",i),null}}function Jh(t){const e=new Uint8Array(t);let n="";for(let i=0;i0}let Nn="",hi="",Gi=null,od=0,it="not-configured";async function Ol(){sessionStorage.getItem(Rt)&&await Nl(),Nn=await Re("flutterflow"),hi=await Re("flutterflow_project_id"),A0(),rn(),Nn?Ul():(it="not-configured",vt())}let lr=!1;function Zh(){const t=document.getElementById("api-keys-modal");We(t),jl(),Nn&&Hl(Nn)}function Bl(){lr=!1,Zh()}function E0(){lr=!0;const t=document.getElementById("walkthrough-modal");t&&qe(t),Zh()}let ad=!1;function ld(){const t=document.getElementById("code-generator-model"),e=document.getElementById("composer-settings-model");if(!t||!e)return;e.value=t.value;const n=Array.from(t.options);Array.from(e.options).forEach((r,s)=>{const o=n[s];o&&(r.textContent=o.textContent)});const i=document.getElementById("composer-settings-free-notice");i&&(document.getElementById("model-selector-free-notice")?(i.hidden=!1,i.innerHTML='Free plan — Gemini only. '):i.hidden=!0)}function cd(){const t=document.getElementById("code-generator-model"),e=document.getElementById("composer-image-capability"),n=document.getElementById("composer-image-capability-note");if(!t)return;const i=Gt(t.value),r=Uh(t.value);e&&(e.textContent=r?"Supported":"Not supported"),n&&(n.textContent=r?`${i} accepts reference images you attach to the prompt.`:`Images can't be attached with ${i}. Attached images are removed when you switch to it.`),$l()}function S0(){if(lr=!1,ld(),cd(),!ad){const e=document.getElementById("composer-settings-model");e&&e.addEventListener("change",()=>{const n=document.getElementById("code-generator-model");n.value=e.value,n.dispatchEvent(new Event("change")),ld(),cd()}),ad=!0}const t=document.querySelector('.composer [aria-label="Generation settings"]');We("composer-settings-modal",{trigger:t})}function x0(t){t&&t.target!==t.currentTarget||qe("composer-settings-modal")}function Xh(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("api-keys-modal");e&&qe(e);const n=lr;if(lr=!1,n){const i=document.getElementById("walkthrough-modal");i&&(it==="connected"&&Dl(),We(i))}}let en=1;function Qh(){const t=document.querySelector(".wt-steps");return t?Array.from(t.querySelectorAll(".wt-step-card")):[]}function Hs(){const t=Qh();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===en?(e.classList.add("wt-current"),r&&(r.textContent=i)):i0&&en<=t&&(en++,Hs())}function I0(){const t=document.getElementById("walkthrough-modal");t&&(en=1,Hs(),We(t))}function k0(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("walkthrough-modal");e&&qe(e);const n=document.getElementById("walkthrough-dont-show");n&&n.checked&&localStorage.setItem("hasSeenWalkthrough","true")}function ep(){if(H.isVerified&&Tt()&&ce.tier!=="free")return;if(!localStorage.getItem("hasSeenWalkthrough")){const e=document.getElementById("walkthrough-modal");e&&(en=1,Hs(),We(e))}}async function jl(){const t=document.getElementById("flutterflow-api-key-input");Nn?(t.value="",t.placeholder="Key saved (enter new to replace)"):t.placeholder="Enter your FlutterFlow API key",C0()}function C0(){ud("flutterflow","flutterflow-key-status"),ud("flutterflow_project_id","flutterflow-project-status")}function ud(t,e){const n=document.getElementById(e);if(!n)return;const i=n.querySelector(".key-status-dot"),r=n.querySelector("span");Ct(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 A0(){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"?Ct("flutterflow")&&Ct("flutterflow_project_id")?(i.className="key-status-dot configured",i.title="FlutterFlow (Fully configured)"):Ct("flutterflow")||Ct("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)"):Ct(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 P0(){const t=document.getElementById("flutterflow-api-key-input"),e=document.getElementById("flutterflow-projects-select"),n=t.value.trim(),i=e?.value.trim()||"";if(n){const o=await Re("flutterflow").catch(()=>"");await sd("flutterflow",n),n!==o&&!i&&tp()}if(i){if(!Ws(i)){Ee("The selected FlutterFlow project has an unexpected ID format.","error"),e.focus();return}await sd("flutterflow_project_id",i)}await Ol(),n&&await Ul(),jl();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 F0(){if(!confirm("Are you sure you want to clear all stored API keys?"))return;localStorage.setItem(or,Ga()),fi(),localStorage.removeItem(gt+"flutterflow"),localStorage.removeItem(gt+"flutterflow_project_id"),sessionStorage.removeItem(Pt+"flutterflow"),sessionStorage.removeItem(Pt+"flutterflow_project_id"),sessionStorage.removeItem(Rt),sessionStorage.removeItem(sr),localStorage.removeItem(gt+"salt"),await g0(),localStorage.setItem(or,Ga()),localStorage.removeItem(gt+"flutterflow"),localStorage.removeItem(gt+"flutterflow_project_id"),sessionStorage.removeItem(Pt+"flutterflow"),sessionStorage.removeItem(Pt+"flutterflow_project_id"),await Ol();const t=document.getElementById("flutterflow-projects-select");t&&(t.innerHTML=''),jl()}function Ws(t){return!t||t.trim().length<5||t.includes(" ")?!1:/^[a-zA-Z0-9-]+$/.test(t)}function vt(){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=yt();n.textContent=o.includes("staging")?"Staging":"Production"}if(i&&(i.textContent=hi||"—"),!e)return;let r,s;if(!Ct("flutterflow"))r="Not connected — add your FlutterFlow API key",s="";else switch(it){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 Ul(){const t=await Re("flutterflow");if(!t||!Ct("flutterflow"))return it="not-configured",vt(),null;it="validating",vt();try{const n=await new mi(t,"","main",yt()).listProjects();return it=n&&n.length>0?"connected":"no-projects",vt(),n}catch(e){const n=String(e&&e.message||"");return it=/(401|403)|denied|unauthorized|scoped|list permission/i.test(n)?"unauthorized":"network-error",vt(),null}}function tp(){hi="",localStorage.removeItem(gt+"flutterflow_project_id"),sessionStorage.removeItem(Pt+"flutterflow_project_id")}function R0(){tp();const t=document.getElementById("flutterflow-projects-select");t&&(t.innerHTML='',t.value=""),Ct("flutterflow")?(it="validating",Hl(Nn)):it="not-configured",vt()}function T0(t,e){const n=document.getElementById(t);n&&(n.value?e?n.style.borderColor="#22c55e":n.style.borderColor="#ef4444":n.style.borderColor="")}function $0(){const t=document.getElementById("flutterflow-api-key-input");t&&(t.addEventListener("input",e=>{const n=e.target.value.trim().length>0;T0("flutterflow-api-key-input",n)}),t.addEventListener("blur",M0(async e=>{const n=e.target.value.trim();n&&await Hl(n)},500)))}function M0(t,e){let n;return function(...r){const s=()=>{clearTimeout(n),t(...r)};clearTimeout(n),n=setTimeout(s,e)}}async function Hl(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"),(Ct("flutterflow")||t)&&(it="validating"),vt();try{const r=await new mi(t,"","main",yt()).listProjects();if(!r||r.length===0){it="no-projects",vt(),e.innerHTML='';return}it="connected",vt(),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)}),hi&&(e.value=hi)}catch(i){console.error("Failed to fetch projects:",i);const r=String(i&&i.message||"");it=/(401|403)|denied|unauthorized|scoped|list permission/i.test(r)?"unauthorized":"network-error",vt(),e.innerHTML='',n&&(n.textContent=`Failed to load projects: ${i.message}`,n.classList.remove("hidden"))}}function L0(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 C0(){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 A0(){y.bundleSpec=ir(y.step1Result,{artifactType:"CustomWidget",artifactName:"GeneratedWidget"})}function zs(){const t=li(y.bundleSpec);y.artifactBundle=ir(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=t_(y.artifactBundle);y.artifactBundle={...y.artifactBundle,warnings:[...y.artifactBundle.warnings,...e.findings.map(n=>n.message)],metadata:{...y.artifactBundle.metadata,compatibility:e}},y.selectedArtifactId=li(y.artifactBundle).id}function qs(){const t=ir(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=ir({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 Zh(){const t=Hl();return{artifactType:t.artifactType||"CustomWidget",artifactName:t.artifactName||"GeneratedWidget",fileName:t.fileName||""}}function Hl(){const t=y.artifactBundle||y.bundleSpec||null;return(Array.isArray(t?.artifacts)?t.artifacts:[]).find(n=>n.id===y.selectedArtifactId)||li(t)}function Wl(){return Hl().code||y.step2Result||""}async function P0(){try{await Nl()}catch(t){return console.error("checkConnection: initializeApiKeys failed:",t),!1}return!0}const Wr={production:"https://api.flutterflow.io/v2/",staging:"https://api.flutterflow.io/v2-staging/"};function F0(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 mi{constructor(e,n,i="main",r=Wr.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,i=null){const r=[Wr.production,Wr.staging],s=Math.max(0,r.indexOf(this._endpoint));let o=!1,a=null;for(let l=0;lsetTimeout(p,1e3*(l+1)));continue}if(d.ok)return console.log(`Push to ${c} succeeded!`),d;a=d.status;const f=d.status<500&&!o;if(Ka(f?d.clone():d,Ph).then(h=>console.log(`Push to ${c} returned ${d.status}: ${h}`),()=>console.log(`Push to ${c} returned ${d.status} (unreadable response body)`)),d.status>=500&&(o=!0),d.status===500){console.warn(`Endpoint ${c} returned 500, trying next...`),await new Promise(h=>setTimeout(h,1e3*(l+1)));continue}if(d.status>=500)throw new et(`FlutterFlow reported a server error (HTTP ${d.status}), which cannot prove the push was refused — the write may have been applied before the failure. Open your FlutterFlow project to reconcile before retrying.`);if(o)throw new et(`The push was refused (HTTP ${d.status}), but an earlier sync attempt may already have applied it — server errors and dropped responses cannot prove a refusal. Open your FlutterFlow project to reconcile before retrying.`);return d}throw Gu({httpStatus:a})}async pushCode(e,n=null){return this.pushCodeWithRetry(e,3,n)}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(F0(s.status,i));if(s.status!==404)throw new Error(`List projects failed: ${s.status} - ${i}`)}throw new Error(`List projects failed: ${n} - ${i}`)}}function Ka(t,e){const n=t.body?.getReader?.(),i=n?(async()=>{const r=new TextDecoder;let s="";for(;;){const{done:o,value:a}=await n.read();if(o)break;s+=r.decode(a,{stream:!0})}return s+r.decode()})():Promise.resolve("");return Vl(i,e,(r,s)=>{try{n?.cancel()?.catch?.(()=>{})}catch{}s(new Error("The response body stalled before it finished."))})}async function R0(t,e=Ph){const n=t.clone();let i;try{i=JSON.parse(await Ka(t,e))}catch{let o="";try{o=await Ka(n,e)}catch{}if(!t.ok)return{success:!1,responseCode:t.status,errorMessage:o||`HTTP ${t.status}`,errorMap:new Map};throw new et(`FlutterFlow accepted the sync but returned an unreadable response${o?`: ${o.slice(0,200)}`:"."}`)}if(!t.ok){let s=i.message||`HTTP ${t.status}`,o=new Map;if(i.errors)o=new Map(Object.entries(i.errors));else if(!i.message&&typeof i=="object"){const a=Object.keys(i).filter(l=>l.endsWith(".dart")&&Array.isArray(i[l]));a.length>0&&(o=new Map(Object.entries(i)),s=a.flatMap(u=>i[u].map(c=>`${u}: ${c.errorMessage}`)).join(` -`)||`HTTP ${t.status}`)}return{success:!1,responseCode:t.status,errorMessage:s,errorMap:o}}let r={};if(i.value)try{r=typeof i.value=="string"?JSON.parse(i.value):i.value}catch(s){console.warn("Ignoring malformed push response value:",s)}return{success:!0,responseCode:t.status,errorMap:new Map(Object.entries(r))}}function zl(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"},Xh=/class\s+\w+\s+extends\s+(?:StatelessWidget|StatefulWidget)\b/,Qh=/extends\s+State<\w+>/;function T0(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=Xh.test(e),i=Qh.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 ep(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 ql(t,e=new Map){return Ov(t,e)}const Ya=new Map,Qn=new Map,ei=new Map;function dr(t){return`${t.baseUrl}|${t.projectId}|${t.branchName}`}function hi(t){Ya.delete(dr(t))}function zr(t,e,n){const i=dr(t),r=Qn.get(i)??new Map;for(const{path:s,content:o}of e){const a=r.get(s)??new Map,l=a.get(o)??{uncertain:0,verified:0};n.uncertain&&(l.uncertain+=n.uncertain),n.verified&&(l.verified+=n.verified),l.uncertain<=0&&l.verified<=0?a.delete(o):a.set(o,l),a.size===0?r.delete(s):r.set(s,a)}r.size===0?Qn.delete(i):Qn.set(i,r)}function $0(t,e){zr(t,e,{uncertain:1})}function M0(t){const e=dr(t);ei.set(e,(ei.get(e)??0)+1)}function ud(t){const e=dr(t),n=(ei.get(e)??0)-1;n<=0?ei.delete(e):ei.set(e,n)}function Vl(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 Gl(t,e,n=Ah){const i={stop:!1},r=(async()=>{const s=await t.pushCode(e,i);return R0(s)})();return Vl(r,n,(s,o)=>{i.stop=!0,hi(t),M0(t),r.then(()=>ud(t),()=>ud(t)),o(new et("FlutterFlow did not answer the sync in time — the push may still have been applied. The outcome is not yet known: open your FlutterFlow project to reconcile before retrying the deploy."))})}async function Kl(t,e,n,i,r="",s=Ah){const o=g_(e,n);if(o.length===0)return{remoteFiles:n,syncFileMap:e,unverified:[],approximate:[]};const a=ay(o,r),l={...a.manifest,sources:a.sources},u=a.skipped.map(p=>p.reason);u.forEach(p=>console.warn(`[custom class deploy] ${p}`));const c=a.approximate;c.forEach(p=>console.warn(`[custom class deploy] ${p}`)),console.log(`Provisioning ${o.length} new FlutterFlow custom code file(s) before sync.`),Be.set("provision");let d=!0,f,h;try{if(h=(async()=>{let p;try{p=await fetch(Oy,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:t.apiKey,projectId:t.projectId,baseUrl:t.baseUrl,commitMessage:i,customClasses:o,verification:l,stream:!0})})}catch{throw new et("The provisioning request did not return a response. The deploy may have reached the FlutterFlow server — open your FlutterFlow project to reconcile before retrying.")}return cy(p,{onPhase:g=>{d&&Be.setSubstatus(g)},onLog:g=>{d&&console.log(`[custom class deploy] ${g}`)}})})(),f=await Vl(h,s,(p,g)=>{d=!1,g(new et("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."))}),!f.finalResultReceived)throw Ku(f)===Le.FAILED?new Error(f.error||`FlutterFlow custom class provisioning failed (HTTP ${f.httpStatus}).`):new et("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(!f.success){const p=f.details?` ${f.details}`:"",g=`${f.error||"FlutterFlow custom class provisioning failed."}${p}`;throw Ku(f)===Le.UNCONFIRMED?new et(`${g} The failure arrived after the deploy began — custom classes may already be written. Open your FlutterFlow project to reconcile before retrying.`):new Error(g)}}catch(p){throw p instanceof et&&(hi(t),$0(t,o),h?.then(g=>{g?.finalResultReceived&&g.success?zr(t,o,{uncertain:-1,verified:1}):g?.finalResultReceived&&Rh(g)&&zr(t,o,{uncertain:-1})},()=>{})),p}return hi(t),zr(t,o,{verified:1}),f.verificationSkipped&&(console.warn(`[custom class deploy] ${f.verificationSkipped}`),u.push(f.verificationSkipped)),{remoteFiles:n,syncFileMap:m_(e,o),unverified:u,approximate:c,provisionSucceeded:!0}}async function Yl(t,e={}){const n=dr(t);let i=Ya.get(n);if(i===void 0){try{i=await t.fetchProjectSource()}catch(u){throw new Error(`Could not read your project's pubspec.yaml (${u.message}). Deploy was stopped so your existing package dependencies aren't overwritten. Check your FlutterFlow API key and project, then try again.`)}const a=kh(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.`);const l=Qn.get(n);if(l){for(const[u,c]of[...l]){const d=i.files.get(u);if(d!==void 0){const f=c.get(d);f&&(f.verified>0?f.verified-=1:f.uncertain-=1,f.uncertain<=0&&f.verified<=0&&c.delete(d))}c.size===0&&l.delete(u)}l.size===0&&Qn.delete(n)}!Qn.has(n)&&!ei.has(n)&&Ya.set(n,i)}const r=await ky(i.pubspecYaml,e),s=ny(i.pubspecYaml,r.overrides),o=ty(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 L0(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=M_(t.content);if(s&&e.push(`FlutterFlow cannot format this code - ${s}. Fix or regenerate before committing.`),t.codeType===J.WIDGET){const o=vh(t.content),a=R_(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=`${_h(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 tp(t,e={}){const{artifactType:n="CustomWidget",artifactName:i="GeneratedCode",fileName:r}=e,s=P_(t);let o=r||i;if(n==="CustomFunction")o="custom_functions.dart";else if(n==="CustomWidget"){const u=vh(s)[0],c=u?_h(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 + `)}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 N0(){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 O0(){y.bundleSpec=ir(y.step1Result,{artifactType:"CustomWidget",artifactName:"GeneratedWidget"})}function qs(){const t=ci(y.bundleSpec);y.artifactBundle=ir(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=o_(y.artifactBundle);y.artifactBundle={...y.artifactBundle,warnings:[...y.artifactBundle.warnings,...e.findings.map(n=>n.message)],metadata:{...y.artifactBundle.metadata,compatibility:e}},y.selectedArtifactId=ci(y.artifactBundle).id}function zs(){const t=ir(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=ir({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 np(){const t=Wl();return{artifactType:t.artifactType||"CustomWidget",artifactName:t.artifactName||"GeneratedWidget",fileName:t.fileName||""}}function Wl(){const t=y.artifactBundle||y.bundleSpec||null;return(Array.isArray(t?.artifacts)?t.artifacts:[]).find(n=>n.id===y.selectedArtifactId)||ci(t)}function ql(){return Wl().code||y.step2Result||""}async function B0(){try{await Ol()}catch(t){return console.error("checkConnection: initializeApiKeys failed:",t),!1}return!0}const zr={production:"https://api.flutterflow.io/v2/",staging:"https://api.flutterflow.io/v2-staging/"};function D0(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 mi{constructor(e,n,i="main",r=zr.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,i=null){const r=[zr.production,zr.staging],s=Math.max(0,r.indexOf(this._endpoint));let o=!1,a=null;for(let l=0;lsetTimeout(h,1e3*(l+1)));continue}if(d.ok)return console.log(`Push to ${c} succeeded!`),d;a=d.status;const f=d.status<500&&!o;if(Ka(f?d.clone():d,Mh).then(p=>console.log(`Push to ${c} returned ${d.status}: ${p}`),()=>console.log(`Push to ${c} returned ${d.status} (unreadable response body)`)),d.status>=500&&(o=!0),d.status===500){console.warn(`Endpoint ${c} returned 500, trying next...`),await new Promise(p=>setTimeout(p,1e3*(l+1)));continue}if(d.status>=500)throw new et(`FlutterFlow reported a server error (HTTP ${d.status}), which cannot prove the push was refused — the write may have been applied before the failure. Open your FlutterFlow project to reconcile before retrying.`);if(o)throw new et(`The push was refused (HTTP ${d.status}), but an earlier sync attempt may already have applied it — server errors and dropped responses cannot prove a refusal. Open your FlutterFlow project to reconcile before retrying.`);return d}throw Ku({httpStatus:a})}async pushCode(e,n=null){return this.pushCodeWithRetry(e,3,n)}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(D0(s.status,i));if(s.status!==404)throw new Error(`List projects failed: ${s.status} - ${i}`)}throw new Error(`List projects failed: ${n} - ${i}`)}}function Ka(t,e){const n=t.body?.getReader?.(),i=n?(async()=>{const r=new TextDecoder;let s="";for(;;){const{done:o,value:a}=await n.read();if(o)break;s+=r.decode(a,{stream:!0})}return s+r.decode()})():Promise.resolve("");return Gl(i,e,(r,s)=>{try{n?.cancel()?.catch?.(()=>{})}catch{}s(new Error("The response body stalled before it finished."))})}async function j0(t,e=Mh){const n=t.clone();let i;try{i=JSON.parse(await Ka(t,e))}catch{let o="";try{o=await Ka(n,e)}catch{}if(!t.ok)return{success:!1,responseCode:t.status,errorMessage:o||`HTTP ${t.status}`,errorMap:new Map};throw new et(`FlutterFlow accepted the sync but returned an unreadable response${o?`: ${o.slice(0,200)}`:"."}`)}if(!t.ok){let s=i.message||`HTTP ${t.status}`,o=new Map;if(i.errors)o=new Map(Object.entries(i.errors));else if(!i.message&&typeof i=="object"){const a=Object.keys(i).filter(l=>l.endsWith(".dart")&&Array.isArray(i[l]));a.length>0&&(o=new Map(Object.entries(i)),s=a.flatMap(u=>i[u].map(c=>`${u}: ${c.errorMessage}`)).join(` +`)||`HTTP ${t.status}`)}return{success:!1,responseCode:t.status,errorMessage:s,errorMap:o}}let r={};if(i.value)try{r=typeof i.value=="string"?JSON.parse(i.value):i.value}catch(s){console.warn("Ignoring malformed push response value:",s)}return{success:!0,responseCode:t.status,errorMap:new Map(Object.entries(r))}}function zl(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"},ip=/class\s+\w+\s+extends\s+(?:StatelessWidget|StatefulWidget)\b/,rp=/extends\s+State<\w+>/;function U0(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=ip.test(e),i=rp.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 sp(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 Vl(t,e=new Map){return Hv(t,e)}const Ya=new Map,ei=new Map,ti=new Map;function hr(t){return`${t.baseUrl}|${t.projectId}|${t.branchName}`}function pi(t){Ya.delete(hr(t))}function Vr(t,e,n){const i=hr(t),r=ei.get(i)??new Map;for(const{path:s,content:o}of e){const a=r.get(s)??new Map,l=a.get(o)??{uncertain:0,verified:0};n.uncertain&&(l.uncertain+=n.uncertain),n.verified&&(l.verified+=n.verified),l.uncertain<=0&&l.verified<=0?a.delete(o):a.set(o,l),a.size===0?r.delete(s):r.set(s,a)}r.size===0?ei.delete(i):ei.set(i,r)}function H0(t,e){Vr(t,e,{uncertain:1})}function W0(t){const e=hr(t);ti.set(e,(ti.get(e)??0)+1)}function dd(t){const e=hr(t),n=(ti.get(e)??0)-1;n<=0?ti.delete(e):ti.set(e,n)}function Gl(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 Kl(t,e,n=$h){const i={stop:!1},r=(async()=>{const s=await t.pushCode(e,i);return j0(s)})();return Gl(r,n,(s,o)=>{i.stop=!0,pi(t),W0(t),r.then(()=>dd(t),()=>dd(t)),o(new et("FlutterFlow did not answer the sync in time — the push may still have been applied. The outcome is not yet known: open your FlutterFlow project to reconcile before retrying the deploy."))})}async function Yl(t,e,n,i,r="",s=$h){const o=x_(e,n);if(o.length===0)return{remoteFiles:n,syncFileMap:e,unverified:[],approximate:[]};const a=my(o,r),l={...a.manifest,sources:a.sources},u=a.skipped.map(h=>h.reason);u.forEach(h=>console.warn(`[custom class deploy] ${h}`));const c=a.approximate;c.forEach(h=>console.warn(`[custom class deploy] ${h}`)),console.log(`Provisioning ${o.length} new FlutterFlow custom code file(s) before sync.`),Be.set("provision");let d=!0,f,p;try{if(p=(async()=>{let h;try{h=await fetch(Vy,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:t.apiKey,projectId:t.projectId,baseUrl:t.baseUrl,commitMessage:i,customClasses:o,verification:l,stream:!0})})}catch{throw new et("The provisioning request did not return a response. The deploy may have reached the FlutterFlow server — open your FlutterFlow project to reconcile before retrying.")}return _y(h,{onPhase:g=>{d&&Be.setSubstatus(g)},onLog:g=>{d&&console.log(`[custom class deploy] ${g}`)}})})(),f=await Gl(p,s,(h,g)=>{d=!1,g(new et("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."))}),!f.finalResultReceived)throw Yu(f)===Le.FAILED?new Error(f.error||`FlutterFlow custom class provisioning failed (HTTP ${f.httpStatus}).`):new et("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(!f.success){const h=f.details?` ${f.details}`:"",g=`${f.error||"FlutterFlow custom class provisioning failed."}${h}`;throw Yu(f)===Le.UNCONFIRMED?new et(`${g} The failure arrived after the deploy began — custom classes may already be written. Open your FlutterFlow project to reconcile before retrying.`):new Error(g)}}catch(h){throw h instanceof et&&(pi(t),H0(t,o),p?.then(g=>{g?.finalResultReceived&&g.success?Vr(t,o,{uncertain:-1,verified:1}):g?.finalResultReceived&&Nh(g)&&Vr(t,o,{uncertain:-1})},()=>{})),h}return pi(t),Vr(t,o,{verified:1}),f.verificationSkipped&&(console.warn(`[custom class deploy] ${f.verificationSkipped}`),u.push(f.verificationSkipped)),{remoteFiles:n,syncFileMap:I_(e,o),unverified:u,approximate:c,provisionSucceeded:!0}}async function Jl(t,e={}){const n=hr(t);let i=Ya.get(n);if(i===void 0){try{i=await t.fetchProjectSource()}catch(u){throw new Error(`Could not read your project's pubspec.yaml (${u.message}). Deploy was stopped so your existing package dependencies aren't overwritten. Check your FlutterFlow API key and project, then try again.`)}const a=Rh(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.`);const l=ei.get(n);if(l){for(const[u,c]of[...l]){const d=i.files.get(u);if(d!==void 0){const f=c.get(d);f&&(f.verified>0?f.verified-=1:f.uncertain-=1,f.uncertain<=0&&f.verified<=0&&c.delete(d))}c.size===0&&l.delete(u)}l.size===0&&ei.delete(n)}!ei.has(n)&&!ti.has(n)&&Ya.set(n,i)}const r=await Ly(i.pubspecYaml,e),s=dy(i.pubspecYaml,r.overrides),o=uy(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=>{const l=r.additions[a],u=l?.sdk?`sdk: ${l.sdk}`:l||"any";return`${a}: ${u}`}).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 q0(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=W_(t.content);if(s&&e.push(`FlutterFlow cannot format this code - ${s}. Fix or regenerate before committing.`),t.codeType===J.WIDGET){const o=yh(t.content),a=j_(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=`${wh(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 op(t,e={}){const{artifactType:n="CustomWidget",artifactName:i="GeneratedCode",fileName:r}=e,s=B_(t);let o=r||i;if(n==="CustomFunction")o="custom_functions.dart";else if(n==="CustomWidget"){const u=yh(s)[0],c=u?wh(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'; @@ -111,15 +112,15 @@ import '/flutter_flow/lat_lng.dart'; import '/flutter_flow/place.dart'; import '/flutter_flow/uploaded_file.dart'; -`),{content:r_(s,l),fileName:o,codeType:a,artifactType:n,artifactName:i}}function N0(t){const e={};for(const n of kl(t))e[n]="";return e}function O0(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 B0(t,e,n,i=new Set,r=""){const s=[],o=Xh.test(e),a=Qh.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 Vs(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=>Ms(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=B0(r,s.content,s.type,i,s.artifactName);o.valid||e.push(...o.errors.map(a=>`${r}: ${a}`))}if(r==="pubspec.yaml"){const o=kh(s.content);o.valid||e.push(...o.errors)}}return{valid:e.length===0,errors:e,warnings:n}}const ee={IDLE:"IDLE",PREPARING:"PREPARING",VALIDATING:"VALIDATING",PUSHING:"PUSHING",SUCCESS:"SUCCESS",ERROR:"ERROR"},G={currentState:ee.IDLE,startTime:null,endTime:null,error:null,result:null,filesProcessed:0,totalFiles:0,reset(){this.currentState=ee.IDLE,this.startTime=null,this.endTime=null,this.error=null,this.result=null,this.filesProcessed=0,this.totalFiles=0},setState(t){if(!Object.values(ee).includes(t)){console.error(`Invalid commit state: ${t}`);return}this.currentState=t,t===ee.PREPARING&&(this.startTime=Date.now()),(t===ee.SUCCESS||t===ee.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(ee.ERROR)},setSuccess(t){this.result=t,this.setState(ee.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===ee.PREPARING||this.currentState===ee.VALIDATING||this.currentState===ee.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),G.reset(),G.setState(ee.PREPARING);try{const o=await Re("flutterflow"),a=await Re("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(!Ws(a))throw new Error("Invalid FlutterFlow Project ID format.");const l=yt(),u=new mi(o,a,"main",l);G.setState(ee.VALIDATING);const c=new Map,d=i||T0(e,t),f=ep(e,d);c.set(e,{artifactName:s,content:t,type:d,path:f}),G.setProgress(0,c.size);const h=Vs(c);if(!h.valid)throw new Error(`Validation failed: -${h.errors.join(` -`)}`);const p=await Yl(u,r),g=p.yaml,m=await Kl(u,c,p.remoteFiles,`Provision ${s} custom class`,g),v=await ql(m.syncFileMap,m.remoteFiles),E=new Map(m.syncFileMap);E.set("pubspec.yaml",{content:g,type:"D",path:"pubspec.yaml"}),Be.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};G.setState(ee.PUSHING),G.setProgress(1,c.size),hi(u),Be.set("push");const b=await Gl(u,_);if(b.success)G.setSuccess({fileCount:c.size,projectId:a,warnings:b.errorMap&&b.errorMap.size>0?Array.from(b.errorMap.entries()):[]});else{const k=b.errorMessage||zl(b.responseCode),T=new Error(k);throw T.remoteRefusal=!0,T}return{success:!0,message:`Successfully committed ${e} to FlutterFlow project ${a}`,addedDependencies:p.added,unverified:m.unverified,approximate:m.approximate,warnings:b.errorMap?Array.from(b.errorMap.entries()):[]}}catch(o){return console.error("Commit failed:",o),G.setError(o),o instanceof et?{success:!1,unconfirmed:!0,error:o.message,state:G.currentState}:{success:!1,error:o.message,remoteRefusal:o.remoteRefusal===!0,state:G.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 j0(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:yt(),artifactType:n,artifactName:i,fileName:r};try{G.setState(ee.PREPARING);const l=tp(t,{artifactType:n,artifactName:i,fileName:r}),u=N0(l.content);console.log("Detected dependencies:",u),G.setState(ee.VALIDATING);const c=await Re("flutterflow"),d=Gi||await Re("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(!Ws(d))throw new Error("Invalid FlutterFlow Project ID format.");a.projectId=d;const f=new Map;f.set(l.fileName,{artifactName:i,content:l.content,type:l.codeType,path:ep(l.fileName,l.codeType),functionName:l.codeType===J.FUNCTION?i:void 0}),G.setProgress(0,f.size);const h=Vs(f);if(!h.valid)throw new Error(`File validation failed: -${h.errors.join(` -`)}`);h.warnings.length>0&&console.warn("Validation warnings:",h.warnings),G.setState(ee.PUSHING);const p=yt(),g=new mi(c,d,"main",p),m=await Yl(g,u),v=m.yaml,E=await Kl(g,f,m.remoteFiles,`Provision ${i} custom class`,v);o=E.provisionSucceeded===!0;const S=await ql(E.syncFileMap,E.remoteFiles),_=new Map(E.syncFileMap);_.set("pubspec.yaml",{content:v,type:J.DEPENDENCIES,path:"pubspec.yaml"}),Be.set("package");const b=await Jl(_),k={project_id:d,zipped_custom_code:b,uid:`web_${Date.now()}`,branch_name:g.branchName,serialized_yaml:v,file_map:S.fileMapContents,functions_map:S.functionsMapContents};G.setProgress(1,f.size),hi(g),Be.set("push");const T=await Gl(g,k);if(T.success){const x={...O0(l,s),projectId:d};return G.setSuccess({...x,fileCount:f.size,warnings:T.errorMap?Array.from(T.errorMap.entries()):[]}),{success:!0,message:`Successfully committed ${l.fileName} to FlutterFlow`,metadata:x,targetIdentity:a,addedDependencies:m.added,unverified:E.unverified,approximate:E.approximate,warnings:T.errorMap?Array.from(T.errorMap.entries()):[],elapsedTime:G.getElapsedTime()}}else{const x=T.errorMessage||zl(T.responseCode),F=new Error(x);throw F.errorMap=T.errorMap,F.remoteRefusal=!0,F}}catch(l){console.error("Commit execution failed:",l),G.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 et?{success:!1,unconfirmed:!0,error:l.message,errorMap:u,targetIdentity:a,state:G.currentState,elapsedTime:G.getElapsedTime()}:o?{success:!1,partial:!0,error:l.message,errorMap:u,targetIdentity:a,state:G.currentState,elapsedTime:G.getElapsedTime()}:{success:!1,error:l.message,errorMap:u,remoteRefusal:l.remoteRefusal===!0,targetIdentity:a,state:G.currentState,elapsedTime:G.getElapsedTime()}}}async function U0(t,e={}){const{pipelineResult:n}=e;let i=!1;const r={projectId:null,endpoint:yt(),artifactType:"Bundle",artifactName:t?.title,fileName:t?.fileEntries?`${t.fileEntries.length} artifacts`:"bundle"};try{if(G.setState(ee.PREPARING),t.errors?.length>0)throw new Error(`Bundle validation failed: +`),{content:c_(s,l),fileName:o,codeType:a,artifactType:n,artifactName:i}}function z0(t){const e={};for(const n of kl(t))e[n]="";return e}function V0(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 G0(t,e,n,i=new Set,r=""){const s=[],o=ip.test(e),a=rp.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 Vs(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=>Ns(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=G0(r,s.content,s.type,i,s.artifactName);o.valid||e.push(...o.errors.map(a=>`${r}: ${a}`))}if(r==="pubspec.yaml"){const o=Rh(s.content);o.valid||e.push(...o.errors)}}return{valid:e.length===0,errors:e,warnings:n}}const ee={IDLE:"IDLE",PREPARING:"PREPARING",VALIDATING:"VALIDATING",PUSHING:"PUSHING",SUCCESS:"SUCCESS",ERROR:"ERROR"},G={currentState:ee.IDLE,startTime:null,endTime:null,error:null,result:null,filesProcessed:0,totalFiles:0,reset(){this.currentState=ee.IDLE,this.startTime=null,this.endTime=null,this.error=null,this.result=null,this.filesProcessed=0,this.totalFiles=0},setState(t){if(!Object.values(ee).includes(t)){console.error(`Invalid commit state: ${t}`);return}this.currentState=t,t===ee.PREPARING&&(this.startTime=Date.now()),(t===ee.SUCCESS||t===ee.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(ee.ERROR)},setSuccess(t){this.result=t,this.setState(ee.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===ee.PREPARING||this.currentState===ee.VALIDATING||this.currentState===ee.PUSHING}};async function K0(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),G.reset(),G.setState(ee.PREPARING);try{const o=await Re("flutterflow"),a=await Re("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(!Ws(a))throw new Error("Invalid FlutterFlow Project ID format.");const l=yt(),u=new mi(o,a,"main",l);G.setState(ee.VALIDATING);const c=new Map,d=i||U0(e,t),f=sp(e,d);c.set(e,{artifactName:s,content:t,type:d,path:f}),G.setProgress(0,c.size);const p=Vs(c);if(!p.valid)throw new Error(`Validation failed: +${p.errors.join(` +`)}`);const h=await Jl(u,r),g=h.yaml,m=await Yl(u,c,h.remoteFiles,`Provision ${s} custom class`,g),v=await Vl(m.syncFileMap,m.remoteFiles),E=new Map(m.syncFileMap);E.set("pubspec.yaml",{content:g,type:"D",path:"pubspec.yaml"}),Be.set("package");const S=await Zl(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};G.setState(ee.PUSHING),G.setProgress(1,c.size),pi(u),Be.set("push");const b=await Kl(u,_);if(b.success)G.setSuccess({fileCount:c.size,projectId:a,warnings:b.errorMap&&b.errorMap.size>0?Array.from(b.errorMap.entries()):[]});else{const k=b.errorMessage||zl(b.responseCode),T=new Error(k);throw T.remoteRefusal=!0,T}return{success:!0,message:`Successfully committed ${e} to FlutterFlow project ${a}`,addedDependencies:h.added,unverified:m.unverified,approximate:m.approximate,warnings:b.errorMap?Array.from(b.errorMap.entries()):[]}}catch(o){return console.error("Commit failed:",o),G.setError(o),o instanceof et?{success:!1,unconfirmed:!0,error:o.message,state:G.currentState}:{success:!1,error:o.message,remoteRefusal:o.remoteRefusal===!0,state:G.currentState}}}async function Zl(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 Y0(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:yt(),artifactType:n,artifactName:i,fileName:r};try{G.setState(ee.PREPARING);const l=op(t,{artifactType:n,artifactName:i,fileName:r}),u=z0(l.content);console.log("Detected dependencies:",u),G.setState(ee.VALIDATING);const c=await Re("flutterflow"),d=Gi||await Re("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(!Ws(d))throw new Error("Invalid FlutterFlow Project ID format.");a.projectId=d;const f=new Map;f.set(l.fileName,{artifactName:i,content:l.content,type:l.codeType,path:sp(l.fileName,l.codeType),functionName:l.codeType===J.FUNCTION?i:void 0}),G.setProgress(0,f.size);const p=Vs(f);if(!p.valid)throw new Error(`File validation failed: +${p.errors.join(` +`)}`);p.warnings.length>0&&console.warn("Validation warnings:",p.warnings),G.setState(ee.PUSHING);const h=yt(),g=new mi(c,d,"main",h),m=await Jl(g,u),v=m.yaml,E=await Yl(g,f,m.remoteFiles,`Provision ${i} custom class`,v);o=E.provisionSucceeded===!0;const S=await Vl(E.syncFileMap,E.remoteFiles),_=new Map(E.syncFileMap);_.set("pubspec.yaml",{content:v,type:J.DEPENDENCIES,path:"pubspec.yaml"}),Be.set("package");const b=await Zl(_),k={project_id:d,zipped_custom_code:b,uid:`web_${Date.now()}`,branch_name:g.branchName,serialized_yaml:v,file_map:S.fileMapContents,functions_map:S.functionsMapContents};G.setProgress(1,f.size),pi(g),Be.set("push");const T=await Kl(g,k);if(T.success){const x={...V0(l,s),projectId:d};return G.setSuccess({...x,fileCount:f.size,warnings:T.errorMap?Array.from(T.errorMap.entries()):[]}),{success:!0,message:`Successfully committed ${l.fileName} to FlutterFlow`,metadata:x,targetIdentity:a,addedDependencies:m.added,unverified:E.unverified,approximate:E.approximate,warnings:T.errorMap?Array.from(T.errorMap.entries()):[],elapsedTime:G.getElapsedTime()}}else{const x=T.errorMessage||zl(T.responseCode),F=new Error(x);throw F.errorMap=T.errorMap,F.remoteRefusal=!0,F}}catch(l){console.error("Commit execution failed:",l),G.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 et?{success:!1,unconfirmed:!0,error:l.message,errorMap:u,targetIdentity:a,state:G.currentState,elapsedTime:G.getElapsedTime()}:o?{success:!1,partial:!0,error:l.message,errorMap:u,targetIdentity:a,state:G.currentState,elapsedTime:G.getElapsedTime()}:{success:!1,error:l.message,errorMap:u,remoteRefusal:l.remoteRefusal===!0,targetIdentity:a,state:G.currentState,elapsedTime:G.getElapsedTime()}}}async function J0(t,e={}){const{pipelineResult:n}=e;let i=!1;const r={projectId:null,endpoint:yt(),artifactType:"Bundle",artifactName:t?.title,fileName:t?.fileEntries?`${t.fileEntries.length} artifacts`:"bundle"};try{if(G.setState(ee.PREPARING),t.errors?.length>0)throw new Error(`Bundle validation failed: ${t.errors.join(` `)}`);const s=new Map(t.fileEntries.map(b=>[b.fileName,{artifactId:b.artifactId,artifactName:b.artifactName,content:b.content,type:b.type,path:b.path,functionName:b.type===J.FUNCTION?b.artifactName:void 0}]));G.setProgress(0,s.size);const o=Vs(s);if(!o.valid)throw new Error(`File validation failed: ${o.errors.join(` -`)}`);G.setState(ee.VALIDATING);const a=await Re("flutterflow"),l=Gi||await Re("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(!Ws(l))throw new Error("Invalid FlutterFlow Project ID format.");r.projectId=l,G.setState(ee.PUSHING);const u=yt(),c=new mi(a,l,"main",u),d=await Yl(c,t.dependencies),f=d.yaml,h=await Kl(c,s,d.remoteFiles,`Provision ${t.title} custom classes`,f);i=h.provisionSucceeded===!0;const p=await ql(h.syncFileMap,h.remoteFiles),g=new Map(h.syncFileMap);g.set("pubspec.yaml",{content:f,type:J.DEPENDENCIES,path:"pubspec.yaml"}),Be.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};G.setProgress(1,s.size),hi(c),Be.set("push");const E=await Gl(c,v);if(E.success){const b={...n,artifactType:"Bundle",artifactName:t.title,fileName:`${t.fileEntries.length} artifacts`,codeSize:t.fileEntries.reduce((k,T)=>k+T.content.length,0),projectId:l};return G.setSuccess({...b,fileCount:s.size,warnings:E.errorMap?Array.from(E.errorMap.entries()):[]}),{success:!0,message:`Successfully committed ${t.fileEntries.length} artifacts to FlutterFlow`,metadata:b,targetIdentity:r,addedDependencies:d.added,unverified:h.unverified,approximate:h.approximate,warnings:E.errorMap?Array.from(E.errorMap.entries()):[],elapsedTime:G.getElapsedTime()}}const S=E.errorMessage||zl(E.responseCode),_=new Error(S);throw _.errorMap=E.errorMap,_.remoteRefusal=!0,_}catch(s){console.error("Bundle commit execution failed:",s),G.setError(s);const o=s.errorMap||new Map;return s instanceof et?{success:!1,unconfirmed:!0,error:s.message,errorMap:o,targetIdentity:r,state:G.currentState,elapsedTime:G.getElapsedTime()}:i?{success:!1,partial:!0,error:s.message,errorMap:o,targetIdentity:r,state:G.currentState,elapsedTime:G.getElapsedTime()}:{success:!1,error:s.message,errorMap:o,targetIdentity:r,state:G.currentState,elapsedTime:G.getElapsedTime()}}}async function H0(t,e=[]){const n=El("architect");try{return await Ps("architect",Uh,Iv(t),n,e)}catch(i){throw i.isModelArmor||i.isUsageLimit||i.isPipelineCancel?i:new Error(`Prompt Architect failed: ${i.message}`)}}async function Gs(t,e,n=[],i){const r=kv(t),s=El("generator",y.bundleSpec);try{return await Ps("generator",e,r,s,n)}catch(o){if(o.isModelArmor||o.isUsageLimit||o.isPipelineCancel)throw o;if(e!==Fr){console.warn(`Code Generator failed with ${e}, retrying with fallback model:`,o.message),Gw(e,Fr,i);try{return await Ps("generator",Fr,r,s,n)}catch(a){throw a.isModelArmor||a.isUsageLimit||a.isPipelineCancel?a:new Error(`Code Generator failed: primary (${e}): ${o.message} | fallback (${Fr}): ${a.message}`)}}throw new Error(`Code Generator failed: ${o.message}`)}}async function Ks(t,e=null){const n={...El("review",y.artifactBundle||y.bundleSpec),architect_output:e};try{return await Ps("review",Hh,Cv(t),n)}catch(i){throw i.isModelArmor||i.isUsageLimit||i.isPipelineCancel?i:new Error(`Code Review failed: ${i.message}`)}}function Cs(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=` +`)}`);G.setState(ee.VALIDATING);const a=await Re("flutterflow"),l=Gi||await Re("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(!Ws(l))throw new Error("Invalid FlutterFlow Project ID format.");r.projectId=l,G.setState(ee.PUSHING);const u=yt(),c=new mi(a,l,"main",u),d=await Jl(c,t.dependencies),f=d.yaml,p=await Yl(c,s,d.remoteFiles,`Provision ${t.title} custom classes`,f);i=p.provisionSucceeded===!0;const h=await Vl(p.syncFileMap,p.remoteFiles),g=new Map(p.syncFileMap);g.set("pubspec.yaml",{content:f,type:J.DEPENDENCIES,path:"pubspec.yaml"}),Be.set("package");const m=await Zl(g),v={project_id:l,zipped_custom_code:m,uid:`web_${Date.now()}`,branch_name:c.branchName,serialized_yaml:f,file_map:h.fileMapContents,functions_map:h.functionsMapContents};G.setProgress(1,s.size),pi(c),Be.set("push");const E=await Kl(c,v);if(E.success){const b={...n,artifactType:"Bundle",artifactName:t.title,fileName:`${t.fileEntries.length} artifacts`,codeSize:t.fileEntries.reduce((k,T)=>k+T.content.length,0),projectId:l};return G.setSuccess({...b,fileCount:s.size,warnings:E.errorMap?Array.from(E.errorMap.entries()):[]}),{success:!0,message:`Successfully committed ${t.fileEntries.length} artifacts to FlutterFlow`,metadata:b,targetIdentity:r,addedDependencies:d.added,unverified:p.unverified,approximate:p.approximate,warnings:E.errorMap?Array.from(E.errorMap.entries()):[],elapsedTime:G.getElapsedTime()}}const S=E.errorMessage||zl(E.responseCode),_=new Error(S);throw _.errorMap=E.errorMap,_.remoteRefusal=!0,_}catch(s){console.error("Bundle commit execution failed:",s),G.setError(s);const o=s.errorMap||new Map;return s instanceof et?{success:!1,unconfirmed:!0,error:s.message,errorMap:o,targetIdentity:r,state:G.currentState,elapsedTime:G.getElapsedTime()}:i?{success:!1,partial:!0,error:s.message,errorMap:o,targetIdentity:r,state:G.currentState,elapsedTime:G.getElapsedTime()}:{success:!1,error:s.message,errorMap:o,targetIdentity:r,state:G.currentState,elapsedTime:G.getElapsedTime()}}}async function Z0(t,e=[]){const n=El("architect");try{return await Rs("architect",Vh,Fv(t),n,e)}catch(i){throw i.isModelArmor||i.isUsageLimit||i.isPipelineCancel?i:new Error(`Prompt Architect failed: ${i.message}`)}}async function Gs(t,e,n=[],i){const r=Rv(t),s=El("generator",y.bundleSpec);try{return await Rs("generator",e,r,s,n)}catch(o){if(o.isModelArmor||o.isUsageLimit||o.isPipelineCancel)throw o;if(e!==Tr){console.warn(`Code Generator failed with ${e}, retrying with fallback model:`,o.message),nb(e,Tr,i);try{return await Rs("generator",Tr,r,s,n)}catch(a){throw a.isModelArmor||a.isUsageLimit||a.isPipelineCancel?a:new Error(`Code Generator failed: primary (${e}): ${o.message} | fallback (${Tr}): ${a.message}`)}}throw new Error(`Code Generator failed: ${o.message}`)}}async function Ks(t,e=null){const n={...El("review",y.artifactBundle||y.bundleSpec),architect_output:e};try{return await Rs("review",Gh,Tv(t),n)}catch(i){throw i.isModelArmor||i.isUsageLimit||i.isPipelineCancel?i:new Error(`Code Review failed: ${i.message}`)}}function Ps(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=` @@ -127,12 +128,12 @@ ${o.errors.join(` `):i.innerHTML=` - `)}function Ae(t,e){const n=document.getElementById(`step${t}-loading`),i=document.getElementById(`step${t}-result`);e?(n.classList.remove("hidden"),i.classList.add("hidden"),Cs(t,"active")):(n.classList.add("hidden"),i.classList.remove("hidden"),Cs(t,"completed"))}function W0(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 z0(t){rt(parseInt(t.replace("step","")))}function rt(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"),Nn();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 q0(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 Ja(t){const e=Za(t);console.log(`Step 1 (Prompt Architect): ${Gt(Uh)}`),console.log(e!==t?`Step 2 (Code Generator): ${Gt(t)} → ${Gt(e)} (Free Tier fallback)`:`Step 2 (Code Generator): ${Gt(t)}`),console.log(`Step 3 (Code Review): ${Gt(Hh)}`)}function np(){return{step1Result:y.step1Result,step2Result:y.step2Result,step3Result:y.step3Result,artifactBundle:y.artifactBundle,bundleReview:y.bundleReview,selectedArtifactId:y.selectedArtifactId}}function V0(t){if(!t)return;Object.assign(y,t),new Set((y.artifactBundle?.artifacts||[]).map(n=>n.id)).has(y.selectedArtifactId)||(y.selectedArtifactId=li(y.artifactBundle)?.id||null)}const ip="results-replacement-error";function G0(t,{stage:e=2,runId:n,retry:i}){if(!re(n))return;const r=document.getElementById(ip);if(!r)return;const s=$h(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=`${Xs[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=()=>pi(),c=u)),l&&(l.hidden=s.canUpgrade,s.canUpgrade||(l.onclick=()=>{Zl(),typeof i=="function"&&i()},l.textContent="Retry",c=l)),(c||r).focus({preventScroll:!0})}function Zl(){const t=document.getElementById(ip);t&&(t.hidden=!0)}function rp(t,{previous:e,stage:n,runId:i,retry:r}){re(i)&&(t.isUsageLimit&&un(),V0(e),hr(),nn(!0),pr(),oo(),G0(t,{stage:n,runId:i,retry:r}),rn())}async function sp(){if(console.log("runRefinement called"),y.isRunning)return;const t=document.getElementById("code-generator-model").value;y.isRunning=!0;const e=Qs();Xl("standardRegenerate",y.step2Result,y.step1Result);const n=document.querySelectorAll(".btn-refine-action"),i=np();n.forEach(r=>{r.disabled=!0,r.innerHTML=` + `)}function Ae(t,e){const n=document.getElementById(`step${t}-loading`),i=document.getElementById(`step${t}-result`);e?(n.classList.remove("hidden"),i.classList.add("hidden"),Ps(t,"active")):(n.classList.add("hidden"),i.classList.remove("hidden"),Ps(t,"completed"))}function X0(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 Q0(t){rt(parseInt(t.replace("step","")))}function rt(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"),On();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 ew(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 Ja(t){const e=Za(t);console.log(`Step 1 (Prompt Architect): ${Gt(Vh)}`),console.log(e!==t?`Step 2 (Code Generator): ${Gt(t)} → ${Gt(e)} (Free Tier fallback)`:`Step 2 (Code Generator): ${Gt(t)}`),console.log(`Step 3 (Code Review): ${Gt(Gh)}`)}function ap(){return{step1Result:y.step1Result,step2Result:y.step2Result,step3Result:y.step3Result,artifactBundle:y.artifactBundle,bundleReview:y.bundleReview,selectedArtifactId:y.selectedArtifactId}}function tw(t){if(!t)return;Object.assign(y,t),new Set((y.artifactBundle?.artifacts||[]).map(n=>n.id)).has(y.selectedArtifactId)||(y.selectedArtifactId=ci(y.artifactBundle)?.id||null)}const lp="results-replacement-error";function nw(t,{stage:e=2,runId:n,retry:i}){if(!re(n))return;const r=document.getElementById(lp);if(!r)return;const s=Bh(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=`${Xs[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=()=>gi(),c=u)),l&&(l.hidden=s.canUpgrade,s.canUpgrade||(l.onclick=()=>{Xl(),typeof i=="function"&&i()},l.textContent="Retry",c=l)),(c||r).focus({preventScroll:!0})}function Xl(){const t=document.getElementById(lp);t&&(t.hidden=!0)}function cp(t,{previous:e,stage:n,runId:i,retry:r}){re(i)&&(t.isUsageLimit&&un(),tw(e),gr(),nn(!0),mr(),oo(),nw(t,{stage:n,runId:i,retry:r}),rn())}async function up(){if(console.log("runRefinement called"),y.isRunning)return;const t=document.getElementById("code-generator-model").value;y.isRunning=!0;const e=Qs();Ql("standardRegenerate",y.step2Result,y.step1Result);const n=document.querySelectorAll(".btn-refine-action"),i=ap();n.forEach(r=>{r.disabled=!0,r.innerHTML=` - Refining...`});try{Zl();const r=Hl(),s=r.id,o=Av({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."});io({runId:e}),Ft(2,e),rt(2),Ae(2,!0);const a=await Gs(o,t,[],e);if(!re(e))return;y.step2Result=a,zs(),tn(2,e);const l=document.getElementById("step2-output"),u=ui(y.step2Result);l.textContent=u,l.dataset.raw=u,Ae(2,!1),rt(3),Ft(3,e),Ae(3,!0);const c=await Ks(y.step2Result,y.step1Result);if(!re(e))return;y.step3Result=c,qs(),tn(3,e),y.artifactBundle?.artifacts?.some(h=>h.id===s)?y.selectedArtifactId=s:y.selectedArtifactId=li(y.artifactBundle)?.id||null;const d=document.getElementById("step3-output");d.textContent=y.step3Result,Ae(3,!1),hr();const f=Us(y.step3Result);pr(u,f)}catch(r){if(console.error("Refinement failed:",r),!re(e))return;const s=js(r,{architect:2,generator:2,review:3});rp(r,{previous:i,stage:s,runId:e,retry:sp})}finally{n.forEach(r=>{r.disabled=!1,r.textContent="Refine & Regenerate"}),re(e)&&(y.isRunning=!1,rn())}}async function Xl(t,e,n){const i=`${_t}/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 K0(){const t=document.getElementById("ff-error-paste-input");t&&(t.value="")}async function op(){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){Ee("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=Qs();Xl("flutterflowError",y.step2Result,e);const r=document.getElementById("btn-fix-from-errors");r&&(r.disabled=!0,r.innerHTML=` + Refining...`});try{Xl();const r=Wl(),s=r.id,o=$v({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."});io({runId:e}),Ft(2,e),rt(2),Ae(2,!0);const a=await Gs(o,t,[],e);if(!re(e))return;y.step2Result=a,qs(),tn(2,e);const l=document.getElementById("step2-output"),u=di(y.step2Result);l.textContent=u,l.dataset.raw=u,Ae(2,!1),rt(3),Ft(3,e),Ae(3,!0);const c=await Ks(y.step2Result,y.step1Result);if(!re(e))return;y.step3Result=c,zs(),tn(3,e),y.artifactBundle?.artifacts?.some(p=>p.id===s)?y.selectedArtifactId=s:y.selectedArtifactId=ci(y.artifactBundle)?.id||null;const d=document.getElementById("step3-output");d.textContent=y.step3Result,Ae(3,!1),gr();const f=Us(y.step3Result);mr(u,f)}catch(r){if(console.error("Refinement failed:",r),!re(e))return;const s=js(r,{architect:2,generator:2,review:3});cp(r,{previous:i,stage:s,runId:e,retry:up})}finally{n.forEach(r=>{r.disabled=!1,r.textContent="Refine & Regenerate"}),re(e)&&(y.isRunning=!1,rn())}}async function Ql(t,e,n){const i=`${_t}/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 iw(){const t=document.getElementById("ff-error-paste-input");t&&(t.value="")}async function dp(){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){Ee("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=Qs();Ql("flutterflowError",y.step2Result,e);const r=document.getElementById("btn-fix-from-errors");r&&(r.disabled=!0,r.innerHTML=` - Fixing…`);const s=np();try{Zl();const o=fh({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,userFeedback:e});Lp(),io({runId:i}),Ft(2,i),rt(2),Ae(2,!0);const a=await Gs(o,n,[],i);if(!re(i))return;y.step2Result=a,zs(),tn(2,i);const l=document.getElementById("step2-output"),u=ui(y.step2Result);l.textContent=u,l.dataset.raw=u,Ae(2,!1),rt(3),Ft(3,i),Ae(3,!0);const c=await Ks(y.step2Result,y.step1Result);if(!re(i))return;y.step3Result=c,qs(),tn(3,i);const d=document.getElementById("step3-output");d.textContent=y.step3Result,Ae(3,!1),hr();const f=Us(y.step3Result);pr(u,f),t&&(t.value="")}catch(o){if(console.error("Fix from errors failed:",o),!re(i))return;const a=js(o,{architect:2,generator:2,review:3});rp(o,{previous:s,stage:a,runId:i,retry:op})}finally{r&&(r.disabled=!1,r.textContent="Fix Errors & Regenerate"),re(i)&&(y.isRunning=!1,rn())}}async function cr(){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,n=Oe.slice();if(!t.trim()){Ee("Please describe your FlutterFlow widget first.","warning");return}y.isRunning=!0;const i=Qs();try{if(await Ha,!re(i)||(pn.length&&await Promise.allSettled(pn.map(v=>v.job)),!re(i))||!await _w()||!re(i)||(await fw(),!re(i)))return;const r=Za(e);t.length,C0(),y.submittedPrompt=t,y.submittedImages=n.filter(v=>v.url),el(!0),Ja(r),Nn();const s=document.getElementById("ready-state");s&&s.classList.add("hidden");const o=document.getElementById("paywall-exhausted");o&&o.classList.add("hidden"),io({prompt:t,runId:i}),Zw(),rt(1),Ft(1,i),Ae(1,!0);const a=y.submittedImages.map(v=>({url:v.url})),l=await H0(t,a);if(!re(i))return;y.step1Result=l,A0(),tn(1,i);const u=document.getElementById("step1-output"),c=ui(y.step1Result);u.textContent=c,u.dataset.raw=c,Ae(1,!1),rt(2),Ft(2,i),Ae(2,!0);const d=await Gs(y.step1Result,r,a,i);if(!re(i))return;y.step2Result=d,zs(),tn(2,i);const f=document.getElementById("step2-output"),h=ui(y.step2Result);f.textContent=h,f.dataset.raw=h,Ae(2,!1),rt(3),Ft(3,i),Ae(3,!0);const p=await Ks(y.step2Result,y.step1Result);if(!re(i))return;y.step3Result=p,qs(),tn(3,i);const g=document.getElementById("step3-output");g.textContent=y.step3Result,Ae(3,!1),hr();const m=Us(y.step3Result);Xw(),pr(h,m)}catch(r){if(r.isPipelineCancel||console.error("Pipeline failed:",r),!re(i))return;const s=js(r,{architect:1,generator:2,review:3});r.isUsageLimit?un():(r.message,Za(document.getElementById("code-generator-model").value),void 0),rt(s),Ae(s,!1),Rp(r,{stage:s,runId:i}),Cs(s,"error")}finally{re(i)&&(y.isRunning=!1,el(!1),rn())}}function Y0(){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? + Fixing…`);const s=ap();try{Xl();const o=hh({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,userFeedback:e});jp(),io({runId:i}),Ft(2,i),rt(2),Ae(2,!0);const a=await Gs(o,n,[],i);if(!re(i))return;y.step2Result=a,qs(),tn(2,i);const l=document.getElementById("step2-output"),u=di(y.step2Result);l.textContent=u,l.dataset.raw=u,Ae(2,!1),rt(3),Ft(3,i),Ae(3,!0);const c=await Ks(y.step2Result,y.step1Result);if(!re(i))return;y.step3Result=c,zs(),tn(3,i);const d=document.getElementById("step3-output");d.textContent=y.step3Result,Ae(3,!1),gr();const f=Us(y.step3Result);mr(u,f),t&&(t.value="")}catch(o){if(console.error("Fix from errors failed:",o),!re(i))return;const a=js(o,{architect:2,generator:2,review:3});cp(o,{previous:s,stage:a,runId:i,retry:dp})}finally{r&&(r.disabled=!1,r.textContent="Fix Errors & Regenerate"),re(i)&&(y.isRunning=!1,rn())}}async function cr(){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,n=Oe.slice();if(!t.trim()){Ee("Please describe your FlutterFlow widget first.","warning");return}y.isRunning=!0;const i=Qs();try{if(await Ha,!re(i)||(gn.length&&await Promise.allSettled(gn.map(v=>v.job)),!re(i))||!await Cw()||!re(i)||(await bw(),!re(i)))return;const r=Za(e);t.length,N0(),y.submittedPrompt=t,y.submittedImages=n.filter(v=>v.url),el(!0),Ja(r),On();const s=document.getElementById("ready-state");s&&s.classList.add("hidden");const o=document.getElementById("paywall-exhausted");o&&o.classList.add("hidden"),io({prompt:t,runId:i}),ob(),rt(1),Ft(1,i),Ae(1,!0);const a=y.submittedImages.map(v=>({url:v.url})),l=await Z0(t,a);if(!re(i))return;y.step1Result=l,O0(),tn(1,i);const u=document.getElementById("step1-output"),c=di(y.step1Result);u.textContent=c,u.dataset.raw=c,Ae(1,!1),rt(2),Ft(2,i),Ae(2,!0);const d=await Gs(y.step1Result,r,a,i);if(!re(i))return;y.step2Result=d,qs(),tn(2,i);const f=document.getElementById("step2-output"),p=di(y.step2Result);f.textContent=p,f.dataset.raw=p,Ae(2,!1),rt(3),Ft(3,i),Ae(3,!0);const h=await Ks(y.step2Result,y.step1Result);if(!re(i))return;y.step3Result=h,zs(),tn(3,i);const g=document.getElementById("step3-output");g.textContent=y.step3Result,Ae(3,!1),gr();const m=Us(y.step3Result);ab(),mr(p,m)}catch(r){if(r.isPipelineCancel||console.error("Pipeline failed:",r),!re(i))return;const s=js(r,{architect:1,generator:2,review:3});r.isUsageLimit?un():(r.message,Za(document.getElementById("code-generator-model").value),void 0),rt(s),Ae(s,!1),Np(r,{stage:s,runId:i}),Ps(s,"error")}finally{re(i)&&(y.isRunning=!1,el(!1),rn())}}function rw(){const t=document.getElementById("code-generator-model").value,e=[xs,"anthropic/claude-opus-5","openai/gpt-5.6-sol"].filter(i=>i!==t),n=prompt(`Retry with different model? Current: ${t} @@ -140,15 +141,15 @@ Options: 1. ${e[0]} 2. ${e[1]} -Enter 1 or 2:`);n==="1"?(document.getElementById("code-generator-model").value=e[0],cr()):n==="2"&&(document.getElementById("code-generator-model").value=e[1],cr())}async function J0(){const t=Wl();if(!t){Ee("No code to commit. Please run the pipeline first.","warning");return}const e=await Re("flutterflow"),n=await Re("flutterflow_project_id");if(!e||!n){Ee("FlutterFlow credentials not configured. Add your API Key and Project ID in settings.","warning"),Ol();return}if(y.artifactBundle?.artifacts?.length>1){await Z0();return}const{artifactType:i,artifactName:r,fileName:s}=Zh(),o=tp(t,{artifactType:i,artifactName:r,fileName:s}),a=L0(o);if(!a.canProceed){Ee(`Pre-commit checks failed: ${a.issues.join("; ")}`,"error");return}tc(o,a,null,null)}async function Z0(){const t=await Re("flutterflow"),e=await Re("flutterflow_project_id");if(!t||!e){Ee("FlutterFlow credentials not configured. Add your API Key and Project ID in settings.","warning"),Ol();return}const n=d_(y.artifactBundle);if(n.errors.length>0){Ee(`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=Vs(i),s={canProceed:r.valid&&n.errors.length===0,issues:[...n.errors,...r.errors],warnings:[...n.warnings,...r.warnings]};if(!s.canProceed){Ee(`Bundle validation failed: ${s.issues.join("; ")}`,"error");return}const o={content:n.fileEntries.map(a=>`// ${a.fileName} +Enter 1 or 2:`);n==="1"?(document.getElementById("code-generator-model").value=e[0],cr()):n==="2"&&(document.getElementById("code-generator-model").value=e[1],cr())}async function sw(){const t=ql();if(!t){Ee("No code to commit. Please run the pipeline first.","warning");return}const e=await Re("flutterflow"),n=await Re("flutterflow_project_id");if(!e||!n){Ee("FlutterFlow credentials not configured. Add your API Key and Project ID in settings.","warning"),Bl();return}if(y.artifactBundle?.artifacts?.length>1){await ow();return}const{artifactType:i,artifactName:r,fileName:s}=np(),o=op(t,{artifactType:i,artifactName:r,fileName:s}),a=q0(o);if(!a.canProceed){Ee(`Pre-commit checks failed: ${a.issues.join("; ")}`,"error");return}nc(o,a,null,null)}async function ow(){const t=await Re("flutterflow"),e=await Re("flutterflow_project_id");if(!t||!e){Ee("FlutterFlow credentials not configured. Add your API Key and Project ID in settings.","warning"),Bl();return}const n=w_(y.artifactBundle);if(n.errors.length>0){Ee(`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=Vs(i),s={canProceed:r.valid&&n.errors.length===0,issues:[...n.errors,...r.errors],warnings:[...n.warnings,...r.warnings]};if(!s.canProceed){Ee(`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};tc(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=`
+`),fileName:`${n.fileEntries.length} files`,codeType:"bundle",artifactType:"Bundle",artifactName:n.title};nc(o,s,n.dependencies,n)}function aw(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+=`
+

${z(t.error)}

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

Errors:

    `;for(const[r,s]of e.entries()){const o=Al(s);n+=`
  • - ${q(r)}: ${q(o)} + ${z(r)}: ${z(o)}
  • `}n+="
"}n+="
",n+=`
-
`;const i=document.getElementById("step3-output");i&&(i.innerHTML=n,document.getElementById("btn-regenerate-from-error")?.addEventListener("click",()=>{ap(t.error,e)}))}async function ap(t,e){if(y.isRunning)return;const n=document.getElementById("code-generator-model").value;y.isRunning=!0;const i=Qs(),r=document.getElementById("btn-regenerate-from-error");r&&(r.disabled=!0,r.innerHTML=` +
`;const i=document.getElementById("step3-output");i&&(i.innerHTML=n,document.getElementById("btn-regenerate-from-error")?.addEventListener("click",()=>{fp(t.error,e)}))}async function fp(t,e){if(y.isRunning)return;const n=document.getElementById("code-generator-model").value;y.isRunning=!0;const i=Qs(),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=Al(p);s+=`File: ${h} +`;if(e&&e.size>0)for(const[p,h]of e.entries()){const g=Al(h);s+=`File: ${p} Error: ${g} `}else s+=`${t} -`;const o=fh({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,userFeedback:s});io({runId:i}),Ft(2,i),rt(2),Ae(2,!0);const a=await Gs(o,n,[],i);if(!re(i))return;y.step2Result=a,zs(),tn(2,i);const l=document.getElementById("step2-output"),u=ui(y.step2Result);l.textContent=u,l.dataset.raw=u,Ae(2,!1),rt(3),Ft(3,i),Ae(3,!0);const c=await Ks(y.step2Result,y.step1Result);if(!re(i))return;y.step3Result=c,qs(),tn(3,i);const d=document.getElementById("step3-output");d.textContent=y.step3Result,Ae(3,!1),hr();const f=Us(y.step3Result);pr(u,f)}catch(s){if(console.error("Regeneration failed:",s),!re(i))return;const o=js(s,{architect:2,generator:2,review:3});s.isUsageLimit&&un(),rt(o),Ae(o,!1),Rp(s,{stage:o,runId:i,retry:()=>ap(t,e)}),Cs(o,"error")}finally{r&&(r.disabled=!1,r.textContent="Fix Errors & Regenerate"),re(i)&&(y.isRunning=!1,rn())}}async function Q0(){const t=document.getElementById("ff-status-dot"),e=document.getElementById("ff-status-text");if(!t||!e)return;const n=await Re("flutterflow"),i=await Re("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 lp(t){try{const e=await fetch(`${_t}/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 ew(t){try{const n=await(await fetch(`${_t}/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 tw(t){try{const e=await fetch(`${_t}/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:`${_t}/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:`${_t}/auth/refresh-session`,message:e.message,stack:e.stack}),null}}function dd(t,e){const n=up(),i=(H.email||n.email)!==t;H.email=t,H.sessionToken=e,H.isVerified=!0,ce=Mn({isLoading:!0}),localStorage.setItem(ys,JSON.stringify({email:t,sessionToken:e})),i&&mp()}function cp(){H.email=null,H.sessionToken=null,H.isVerified=!1,ce=Mn({isResolved:!0}),localStorage.removeItem(ys),localStorage.removeItem(bs)}function up(){try{const t=localStorage.getItem(ys);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(ys),{email:null,sessionToken:null}}}async function nw(){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 ew(e);dd(n,i),dp();const r=fd();r&&!window.location.hash&&(window.location.hash=r)}catch(n){fd();const i=n.message||"Sign-in link invalid or expired.";Ee(i,"error"),Ys(),Jn(i,"error")}}else{const{email:n,sessionToken:i}=up();if(n&&i){const r=await tw(i);r?dd(r.email,r.sessionToken):cp()}}Ql()}function iw(){try{localStorage.setItem(Ua,JSON.stringify({hash:window.location.hash||"#home",ts:Date.now()}))}catch(t){console.warn("rememberSignInReturnSurface: failed to persist return surface:",t)}}function fd(){try{const t=localStorage.getItem(Ua);if(localStorage.removeItem(Ua),!t)return null;const{hash:e,ts:n}=JSON.parse(t);return!e||typeof n!="number"||Date.now()-n>By?null:e}catch(t){return console.warn("consumeSignInReturnSurface: failed to read return surface:",t),null}}function Ys(){const t=document.getElementById("signin-modal");if(!t)return;iw(),document.getElementById("signin-email-input")?.removeAttribute("aria-invalid"),Jn(""),We(t)}function dp(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("signin-modal");e&&ze(e)}function Jn(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 rw(){const t=document.getElementById("signin-email-input"),e=document.getElementById("signin-submit-btn"),n=Ns(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"),Jn("Please enter a valid email address.","error");return}t?.removeAttribute("aria-invalid"),e&&(e.disabled=!0,e.textContent="Sending…");const r=wh(n);r&&Jn(r,"error");try{const s=await lp(n),o=s?.code===yh;t&&!o&&(t.value=""),t?.setAttribute("aria-invalid",String(o)),Jn(bh(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}),Jn("Something went wrong. Please try again.","error"),e&&(e.disabled=!1,e.textContent="Send Sign-in Link")}}function sw(){H.email=null,H.sessionToken=null,H.isVerified=!1,ce=Mn({isResolved:!0}),K_({storage:window.localStorage,onIdentityChanged:Ql,onPlanChanged:Zs})}const ow=Y_({sendLink:lp,getEmail:()=>H.email||"",onState:aw});function aw(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=bh(t.data,H.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 lw(){await ow()}function cw(){const t=V_(window.localStorage),e=t.length?`Cleared disposable UI caches: ${t.join(", ")}.`:"Nothing disposable to clear.";Ee(`${e} Your run count, identity and stored keys are kept.`,"info")}function uw(){const t=document.getElementById("delete-unavailable-modal");t&&We(t,{trigger:document.activeElement})}function dw(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("delete-unavailable-modal");e&&ze(e)}function Ql(){const t=H.isVerified&&!!H.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=H.email||"");const s=document.getElementById("access-signed-email");s&&(s.textContent=H.email||""),bw(),Zs()}async function fp(){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(Hy,{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(pt.userId=r.user_id,pt.token=r.identity_token||null,pt.status=r.status,pt.resolved=!0,sessionStorage.setItem(jy,r.user_id),pt.token&&sessionStorage.setItem(Uy,pt.token),r.usage_count!==void 0){const s=gn(),a=(r.usage_month||s)===s?r.usage_count:0;localStorage.setItem(Fn,JSON.stringify({count:a,month:s})),un()}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 Yo=null;function fw(t=5e3){return pt.resolved?Promise.resolve():(Yo||(Yo=fp().catch(e=>{console.warn("ensureIdentityReady: identity resolution failed",e)})),Promise.race([Yo,new Promise(e=>setTimeout(e,t))]))}function hp(){const t=gn();try{const e=localStorage.getItem(Fn);return e?JSON.parse(e):{count:0,month:t}}catch(e){return console.warn("getUsageData: failed to parse usage storage",{key:Fn,month:t,err:e}),localStorage.removeItem(Fn),{count:0,month:t}}}function gn(){const t=new Date;return`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,"0")}`}function fr(){const t=hp();return t.month!==gn()?{count:0,month:gn()}:t}function hw(){const e={count:fr().count+1,month:gn()};return localStorage.setItem(Fn,JSON.stringify(e)),e}function vi(){return!!ce.isLoading}function Tt(){return!!ce.isResolved}function pw(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(ws,e)?e:null}function gw(t){return t&&Object.entries(Lh).find(([,e])=>e===t)?.[0]||null}function Rr(...t){return t.find(e=>e!=null&&e!=="")}function mw(...t){return t.find(e=>e&&typeof e=="object")||{}}function vw(t){const e=t.data&&typeof t.data=="object"?t.data:t,n=mw(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=Rr(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=Rr(e.status,e.subscriptionStatus,e.subscription_status,n.status,"none"),o=pw(Rr(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||gw(r)||(a||l?"professional":"free");return Mn({tier:u,status:s,periodEnd:Rr(e.periodEnd,e.currentPeriodEnd,e.current_period_end,n.current_period_end,n.periodEnd,null),isResolved:!0})}function Js(){return ws[ce.tier]??ws.free}async function _w(){if(H.isVerified&&(!Tt()||vi())&&(await gp({force:!0}),Zs()),H.isVerified&&!Tt())return Ee("Could not verify your subscription. Please refresh or try Manage billing.","error"),!1;const{count:t}=fr(),e=Js();if(t>=e)return pp(t,e,{openModal:!0}),!1;const n=Math.floor(e*.8);if(t>=n){const i=e-t;Ee(`${i} run${i===1?"":"s"} remaining this month.`,"warning")}return!0}function hd(){const t=document.getElementById("paywall-exhausted");t&&t.classList.add("hidden")}function pp(t,e,n={}){nn(!0);const i=document.getElementById("walkthrough-modal");i&&ze(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){Ee(`You've used all ${e} runs for this month. Upgrade to continue.`,"error"),pi();return}const c=document.getElementById("paywall-exhausted-text");if(c){const f=ce.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",H.isVerified),u.classList.remove("hidden"),n.openModal&&pi()}function Za(t){return ce.tier==="free"&&jr.includes(t)?Es:t}function yw(){const t=document.getElementById("code-options-content"),e=document.getElementById("code-generator-model");if(!t||!e)return;const n=ce.tier,r=!(H.isVerified&&!Tt())&&n==="free";Array.from(e.options).forEach(o=>{const a=Gt(o.value),l=jr.includes(o.value);o.textContent=l&&r?`${a} (PRO)`:a,o.disabled=!1}),r&&jr.includes(e.value)&&(e.value=Es),e.disabled=!1,Qu.has(e)||(e.addEventListener("change",()=>{Tt()&&ce.tier==="free"&&jr.includes(e.value)&&(e.value=Es,pi()),Ja(e.value),Tl()}),Qu.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(),Ja(e.value)}function ec(){const t=H.isVerified&&!!H.email,e=t&&vi(),n=!t||Tt(),i=fr(),r=n?i.count:0,s=n?Js():0,o=Math.max(0,s-r),a=`${r} / ${s} runs this month`,l=bl,u=n?ce.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=hp(),v=m.month===gn()?m.count??0:0;g.textContent=`${v} / ${ws.free} generations used`}}ww()}function ww(){if(!(H.isVerified&&!!H.email))return;const e=vi(),n=Tt(),i=fr(),r=n?i.count:0,s=n?Js():0,o=Math.max(0,s-r),a=n?ce.tier||"free":null,l={free:"Free",professional:"Pro",power:"Power"}[a]||"Free",u=H.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 x=ji(Di[a]??0,$l());p.textContent=`${x} / 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 x=Date.parse(ce.periodEnd||""),F=n&&a!=="free"&&!!ce.periodEnd&&!Number.isNaN(x);if(e)m.textContent="";else if(!n)m.textContent="";else if(a==="free")m.textContent="";else if(F){const $=new Date(x).toLocaleDateString(void 0,{year:"numeric",month:"long",day:"numeric"});m.textContent=`Renews ${$} · 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"),b=document.getElementById("acct-meter-fill"),k=document.getElementById("acct-meter-meta"),T=document.getElementById("acct-meter-track");if(_&&(_.textContent=e?"…":n?String(r):"—"),b){const x=n&&s>0?Math.min(100,Math.round(r/s*100)):0;b.style.width=`${x}%`}if(k)if(e)k.textContent="Checking…";else if(!n)k.textContent="Plan check failed";else if(s===0)k.textContent=`${r} of ${s}`;else{const x=Math.round(r/s*100);k.textContent=`${r} of ${s} · ${x}%`}T&&(e?T.setAttribute("aria-label","Checking usage…"):n?T.setAttribute("aria-label",`${r} of ${s} generations used`):T.setAttribute("aria-label","Usage unavailable")),vt()}function un(){if(ec(),H.isVerified&&(vi()||!Tt())){hd();return}const{count:t}=fr(),e=Js();t>=e&&!y.isRunning&&!vv()?pp(t,e):hd()}function bw(){ec()}async function gp(t={}){const e=t.force===!0;if(!H.isVerified||!H.sessionToken){ce=Mn({isResolved:!0});return}ce={...ce,isLoading:!0,error:null};const n=H.sessionToken,i=localStorage.getItem(bs);if(!e&&i)try{const{data:r,email:s,ts:o,version:a}=JSON.parse(i);if(a===ed&&s===H.email&&Date.now()-o<300*1e3){ce={...r,isLoading:!1,isResolved:r.isResolved!==!1};return}}catch(r){console.warn("Failed to parse subscription cache:",r,"| raw value:",i)}try{const s=await(await fetch(`${_t}/stripe/get-subscription`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:H.sessionToken,user_id:pt.userId})})).json();if(!H.isVerified||H.sessionToken!==n)return;if(s.error){if(["unauthorized","invalid session","expired session"].some(a=>String(s.error).toLowerCase().includes(a))){cp(),Ql();return}ce=Mn({isResolved:!1,error:s.error});return}ce=vw(s),localStorage.setItem(bs,JSON.stringify({version:ed,data:ce,email:H.email,ts:Date.now()}))}catch(r){if(!H.isVerified||H.sessionToken!==n)return;console.error("fetchSubscription failed:",r),ce={...ce,isLoading:!1,isResolved:!1,error:r.message}}}function mp(){localStorage.removeItem(bs)}async function Ew(t){if(!H.isVerified||!H.sessionToken){vp(),Ys();return}if(!Lh[t]){Ee("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(`${_t}/stripe/create-checkout-session-intl`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tierId:t,sessionToken:H.sessionToken,currency:$l()})})).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"),Ee("Could not start checkout. Please try again.","error")}}async function Sw(t){if(!H.isVerified||!H.sessionToken){Ys();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(`${_t}/stripe/create-portal-session`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:H.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),Ee("Could not open billing portal. Please try again.","error")}}const As=new Set;function xw(){As.forEach(t=>t.abort()),As.clear()}async function Ps(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(Dy,{method:"POST",headers:{"Content-Type":"application/json",...pt.token?{Authorization:`Bearer ${pt.token}`}:{}},signal:o.signal,body:JSON.stringify({user_id:pt.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(Fn,JSON.stringify({count:d.serverCount,month:gn()})),un());const p=new Error(d.message||"Monthly usage limit reached. Upgrade to continue.");throw p.isUsageLimit=!0,p.pipelineStep=t,p}const f=Lv(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=gn();(d.usage_month||p)===p&&(localStorage.setItem(Fn,JSON.stringify({count:d.usage_count,month:p})),un())}else hw(),un();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),As.delete(o)}}let Xa=!1;function Iw(){const e=new URLSearchParams(window.location.search).get("checkout");return e==="success"?(window.history.replaceState({},"",window.location.pathname+window.location.hash),mp(),Xa=!0):e==="cancel"&&(window.history.replaceState({},"",window.location.pathname+window.location.hash),Ee("Checkout cancelled.","info")),e}function kw(){if(!Xa)return;Xa=!1;const t=ce.tier!=="free";Ee(t?"Subscription active! Your plan is live.":"Checkout complete — confirming your subscription. Check Manage billing if it does not update.",t?"success":"info")}function Zs(){const t=H.isVerified&&!!H.email,e=ce.tier,n=t&&vi(),i=!t||Tt(),r=document.getElementById("subscription-tier-badge");if(r){const a=bl,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"),Cw(i?e:null),yw(),Tl(),un(),Np()}function Cw(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 Aw(){document.querySelectorAll(".pm-card[data-tier]").forEach(t=>{const e=t.dataset.tier,n=Ev[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 Qa(){const t=$l(),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=ji(Di.professional,t)),n&&(n.textContent=ji(Di.power,t)),i&&(i.textContent=ji(Di.professional,t)),r&&(r.textContent=ji(Di.power,t));const u="billed monthly";s&&(s.textContent=u),o&&(o.textContent=u),a&&(a.textContent=u),l&&(l.textContent=u)}function pi(){Qa();const t=document.getElementById("pricing-modal");t&&We(t),e0().then(()=>Qa())}function vp(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("pricing-modal");e&&ze(e)}function Ee(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()=>{yv(),hljs.configure({tabReplace:" ",classPrefix:"hljs-"}),Pw(),window.__heroField=dy(),window.__pipelineLogo=gy(),Oh=Ny({onSubmit:cr}),Ha=(async()=>{try{await nw(),Iw(),await gp()}catch(n){console.warn("Startup auth/subscription initialization failed:",n)}})(),await Ha,kw(),Zs(),Qa(),Aw(),await P0(),x0();const t=document.getElementById("flutterflow-endpoint-select");if(t){const n=yt();t.value=n}Yh(),fp();const e=document.getElementById("pipeline-input");e&&(e.addEventListener("input",()=>{en===2&&e.value.trim().length>0&&(Bl(),Hs())}),e.addEventListener("blur",()=>{const n=document.getElementById("walkthrough-modal");en===2&&n&&We(n)}),e.addEventListener("keydown",n=>{if(n.key==="Tab"){const i=document.getElementById("walkthrough-modal");en===2&&i&&setTimeout(()=>{We(i)},100)}})),window.addEventListener("commitStateChange",n=>{const{state:i}=n.detail;i===ee.PREPARING||i===ee.VALIDATING||i===ee.PUSHING?(Sp(),Be.phaseId||xp(),gd(i)):(i===ee.SUCCESS||i===ee.ERROR)&&(gd(i),Yi=setTimeout(()=>{Yi=null,ic()},1e3))}),uc()});function Pw(){const t=document.getElementById("preview-frame-container");t&&(t.style.display="")}function Fw(){const t=document.getElementById("welcome-video-player");t&&(t.addEventListener("click",Nn),document.addEventListener("keydown",Nn))}function Nn(){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",Nn),document.removeEventListener("keydown",Nn),Yh()}let Ki=null;async function Rw(){const t=document.getElementById("confirm-project-select");if(!t)return;const e=++sd,n=()=>e===sd,i=await Re("flutterflow"),r=await Re("flutterflow_project_id");if(n()){if(!i){t.innerHTML='',t.disabled=!0;return}t.disabled=!1,t.innerHTML='';try{const o=await new mi(i,"","main",yt()).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 Tw(){return document.getElementById("confirm-project-select")?.value?.trim()||null}function tc(t,e,n,i=null){Ki={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,Rw();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 ${Qt(c)}`:"version resolved from your project";return`
  • • ${Qt(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=>`
  • • ${Qt(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&&We(l)}function _p(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("commit-confirm-modal");e&&ze(e),Ki=null}function $w(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("commit-success-modal");e&&ze(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 yp(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&&We(g)}function wp(t){ic(),X0(t);const e=t.remoteRefusal===!0;nc(t,{heading:"Deploy failed",title:e?"FlutterFlow refused this deploy — nothing was confirmed written.":"The deploy failed before FlutterFlow confirmed anything.",guidance:e?"Review the error and any per-file outcomes above, fix them in your code or in FlutterFlow, then deploy again. A refusal is definitive: no part of this deploy was applied, so retrying is safe once the problem is fixed.":"Review the error above, fix it, then deploy again. The deploy stopped before a write was confirmed, so nothing was applied."})}function nc(t,{heading:e,title:n,guidance:i}){const r=t.targetIdentity||{},s=document.getElementById("commit-terminal-modal");if(!s)return!1;const o=(p,g)=>{const m=document.getElementById(p);m&&(m.textContent=g||"")};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 p=[["Project",r.projectId||t.metadata?.projectId],["Endpoint",r.endpoint],["File",r.fileName||t.metadata?.fileName],["Artifact",r.artifactType||t.metadata?.artifactType]];a.innerHTML=p.map(([g,m])=>`
    ${q(g)}:${q(String(m??"—"))}
    `).join("")}const l=document.getElementById("terminal-file-outcomes");let u=t.errorMap;u&&!(u instanceof Map)&&(u=new Map(Object.entries(u)));const c=l?.querySelector("ul");l&&c&&u&&u.size>0?(c.innerHTML=[...u.entries()].map(([p,g])=>`
  • ${q(p)}: ${q(Al(g))}
  • `).join(""),l.classList.remove("hidden")):l&&(c&&(c.innerHTML=""),l.classList.add("hidden"));const d=document.getElementById("terminal-guidance");d&&(d.innerHTML=i);const f=document.getElementById("terminal-open-ff-link"),h=r.projectId||t.metadata?.projectId;return f&&(f.href=h?`https://app.flutterflow.io/project/${h}`:"https://app.flutterflow.io/"),We(s),!0}function bp(t){nc(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){nc(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 Mw(t){t&&t.target!==t.currentTarget||ze(document.getElementById("commit-terminal-modal"))}function Lw(){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 pd={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}},Nw=[{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..."}];let Yi=null;function Sp(){Yi&&clearTimeout(Yi),Yi=null}const Be={sequence:[],phaseId:null,phaseStartedAt:null,timer:null,substatus:null,liveSubstatus:!1,start({withProvisioning:t=!1}={}){Sp(),this.sequence=["prepare","validate","project"],t&&this.sequence.push("provision"),this.sequence.push("package","push","done");const e=document.getElementById("commit-progress-overlay");e&&(Pu(e,!0,"Deploying to FlutterFlow"),We(e)),this.set("prepare")},set(t,e=null){if(!(!pd[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=pd[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=Nw.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(Ow(e)),Ip(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&&(Pu(t,!1),ze(t,{force:!0,restoreFocus:!1}))}};function Ow(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 xp(t){Be.start(t)}function ic(){Be.stop()}function Ip(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 gd(t){const e={[ee.PREPARING]:"prepare",[ee.VALIDATING]:"validate",[ee.PUSHING]:"project",[ee.SUCCESS]:"done"};if(t===ee.ERROR){Be.timer&&clearInterval(Be.timer),Be.timer=null,Ip(100,"Failed","Error occurred");return}const n=e[t];n&&Be.set(n)}function Bw(t){return t.bundlePlan?t.bundlePlan.fileEntries.some(e=>e.type===J.CODE_FILE):t.codeInfo?.codeType===J.CODE_FILE}let kp=!1;function Cp(t){kp=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 md(t){ic(),Cp(!1);const e=Fh(t);e===Le.COMMITTED?yp(t):e===Le.PARTIAL?bp(t):e===Le.UNCONFIRMED?Ep(t):wp(t)}async function Dw(){if(!Ki){console.error("No pending commit data");return}if(kp){console.warn("Deploy already in flight; ignoring duplicate confirm.");return}const t=Ki;if(Ki=null,Gi=Tw(),_p(),Cp(!0),xp({withProvisioning:Bw(t)}),t.bundlePlan){const o=await U0(t.bundlePlan,{pipelineResult:{step1Result:y.step1Result,selectedModel:document.getElementById("code-generator-model")?.value}});Gi=null,md(o);return}const{codeInfo:e}=t,{artifactType:n,artifactName:i,fileName:r}=Zh(),s=await j0(e.content,{artifactType:n,artifactName:i,fileName:r,pipelineResult:{step1Result:y.step1Result,selectedModel:document.getElementById("code-generator-model")?.value}});Gi=null,md(s)}window.runThinkingPipeline=cr;window.toggleStep=z0;window.toggleSection=W0;window.selectWorkflowStep=rt;window.copyCode=q0;window.retryWithDifferentModel=Y0;window.openApiKeysModal=Ol;window.closeApiKeysModal=Gh;window.openComposerSettings=p0;window.closeComposerSettings=g0;window.walkthroughConnectAccount=h0;window.closeWalkthroughModal=v0;window.openWalkthroughModal=m0;window.advanceWalkthrough=Bl;window.commitToFlutterFlow=D0;function jw(){const t=document.getElementById("pipeline-input");t&&t.focus()}function Uw(){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=jw;window.openModelSelector=Uw;window.handlePromptImageSelect=Xy;window.removePromptImage=Qy;window.saveApiKeys=w0;window.validateFlutterFlowConnection=jl;window.clearAllApiKeys=b0;window.toggleKeyVisibility=k0;window.handleWelcomeVideoEnd=Fw;window.dismissWelcomeVideo=Nn;window.initiateCommitToFlutterFlow=J0;window.updateFlutterFlowCredentialStatus=Q0;window.openCommitConfirmModal=tc;window.closeCommitConfirmModal=_p;window.closeCommitSuccessModal=$w;window.closeCommitTerminalModal=Mw;window.showCommitPartialModal=bp;window.showCommitUnconfirmedModal=Ep;window.showCommitSuccessModal=yp;window.showCommitFailureModal=wp;window.toggleCodePreview=Lw;window.confirmCommitToFlutterFlow=Dw;window.runRefinement=sp;window.regenerateFromPastedErrors=op;window.clearErrorInput=K0;window.setFlutterFlowEndpoint=f0;window.getFlutterFlowEndpoint=yt;window.commitProgress=Be;window.openSignInModal=Ys;window.closeSignInModal=dp;window.handleMagicLinkRequest=rw;window.handleSignOut=sw;window.handleSendNewLink=lw;window.handleClearCache=cw;window.handleDeleteAccount=uw;window.closeDeleteUnavailableModal=dw;window.startCheckout=Ew;window.openCustomerPortal=Sw;window.openPricingModal=pi;window.closePricingModal=vp;let qr=null,Ap=null,On={1:"pending",2:"pending",3:"pending"},rc=1,sc=null;const Xs={1:"Prompt Architect",2:"Code Generator",3:"Code Review"},Hw={1:"Understanding your prompt",2:"Generating Dart code",3:"Running the code audit"},Ww={1:"Prompt understood",2:"Dart code generated",3:"Code audit complete"};function Qs(){return y.runId+=1,y.runId}function re(t){return t===void 0||t===y.runId}function zw(){y.runId+=1}function oc(t){return document.getElementById(`pdot-${t}`)}function el(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 eo(t){const e=document.getElementById("pipeline-progress");e&&(e.dataset.runState=t)}function Rn(t,e){On[t]=e;const n=oc(t);if(!n)return;n.dataset.state=e,n.disabled=e==="pending"||e==="skipped";const i=Xs[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 qw(){return[1,2,3].filter(t=>On[t]==="done").length}function to(){const t=document.getElementById("pipeline-progress-fill");t&&(t.style.width=`${qw()/3*100}%`);const e=document.getElementById("progress-stage-count");e&&(e.textContent=`Step ${rc} of 3`)}function no(t,{done:e=!1}={}){const n=document.getElementById("progress-title-text"),i=document.getElementById("progress-substep-text"),r=On[t],s=e||r==="done";if(n&&(n.textContent=s?Ww[t]:Hw[t]),i){const o=s?" — complete":r==="failed"?" — stopped":"";i.textContent=`Step ${t} of 3 — ${Xs[t]}${o}`}}function Vw(t){On[t]==="pending"||On[t]==="skipped"||(sc=t,[1,2,3].forEach(e=>{const n=oc(e);n&&n.setAttribute("aria-pressed",String(e===t))}),no(t))}function ac(){sc=null,[1,2,3].forEach(t=>{const e=oc(t);e&&e.removeAttribute("aria-pressed")})}function Pp(t){const e=document.getElementById("pipeline-note");e&&(e.textContent=t||"",e.hidden=!t)}function Gw(t,e,n){re(n)&&Pp(`${Gt(t)} did not answer. Continuing on ${Gt(e)}.`)}function lc(){const t=document.getElementById("pipeline-failure");if(!t)return;t.hidden=!0;const e=document.getElementById("pipeline-failure-actions");e&&e.replaceChildren()}const Kw=1120;function Yw(){const t=getComputedStyle(document.documentElement).getPropertyValue("--t-morph").trim(),e=Number.parseFloat(t);return Number.isFinite(e)&&e>0?e:Kw}let ti=null,Vr=null;function Jw(){return window.matchMedia?.("(prefers-reduced-motion: reduce)").matches===!0}function dn(){if(Vr){try{Vr.cancel()}catch{}Vr=null}ti&&(ti.remove(),ti=null),window.removeEventListener("resize",dn)}function Fp(t,e){if(dn(),Jw()||!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:Yw(),fill:"both"});ti=r,Vr=c,window.addEventListener("resize",dn),c.onfinish=()=>{if(ti!==r)return;const d=r.animate([{opacity:1},{opacity:0}],{duration:260,fill:"forwards"});d.onfinish=()=>{ti===r&&dn()}}}function Zw(){const e=document.getElementById("composer")?.getBoundingClientRect();e&&requestAnimationFrame(()=>{requestAnimationFrame(()=>{Fp({getBoundingClientRect:()=>e},document.getElementById("main-stage-container"))})})}function Xw(){Fp(document.getElementById("pipeline-progress"),document.getElementById("main-stage-container"))}window.addEventListener("hashchange",dn);window.addEventListener("popstate",dn);function io(t={}){const{prompt:e=null,runId:n}=t;if(!re(n))return;so(),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"),eo("running"),e!==null){const a=document.getElementById("pipeline-submitted-prompt");a&&(a.textContent=e)}Ap=Date.now();const o=document.getElementById("progress-elapsed");o&&(o.textContent="0s"),On={1:"pending",2:"pending",3:"pending"},ac(),lc(),Pp(""),[1,2,3].forEach(a=>Rn(a,"pending")),Ft(1,n),Qw()}function Ft(t,e){re(e)&&(rc=t,ac(),[1,2,3].forEach(n=>{n===t?Rn(n,"active"):nt&&Rn(n,"pending")}),no(t),to())}function tn(t,e){re(e)&&(Rn(t,"done"),sc===null&&no(t,{done:!0}),to())}function Rp(t,{stage:e=1,runId:n,retry:i=Tp}={}){if(!re(n))return;ro(),so(),dn(),eo("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"),Rn(e,"failed"),[1,2,3].forEach(p=>{p>e&&Rn(p,"pending")}),rc=e,ac(),no(e),to();const o=$h(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=`${Xs[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:()=>pi()},o.canRetry&&{id:"retry",label:"Retry",variant:o.canUpgrade?"secondary":"primary",onClick:i},o.canEdit&&{id:"edit",label:"Edit prompt",variant:"secondary",onClick:tl}].filter(Boolean);!o.canEdit&&!o.canRetry&&f.push({id:"edit",label:"Back to prompt",variant:"secondary",onClick:tl}),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 tl(){zw(),xw(),y.isRunning=!1,el(!1),rn(),eo("settled"),dn(),ro(),so(),lc();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.dispatchEvent(new Event("input",{bubbles:!0}))),e.focus({preventScroll:!0}),e.setSelectionRange(e.value.length,e.value.length))}function Tp(){const t=document.getElementById("pipeline-input");t&&y.submittedPrompt&&(t.value=y.submittedPrompt,t.dispatchEvent(new Event("input",{bubbles:!0}))),Oe=y.submittedImages.slice(),cn(),lc(),cr()}function Qw(){ro(),qr=setInterval(()=>{const t=(Date.now()-Ap)/1e3,e=document.getElementById("progress-elapsed");e&&(e.textContent=`${Math.floor(t)}s`)},250)}function ro(){qr&&(clearInterval(qr),qr=null)}let Ji=null;function so(){Ji&&(clearTimeout(Ji),Ji=null)}function hr(){ro(),so(),eo("settled"),to();const t=document.getElementById("pipeline-progress-fill");Ji=setTimeout(()=>{Ji=null;const e=document.getElementById("pipeline-progress");e&&e.classList.remove("visible"),t&&(t.style.width="0%")},400)}function Tn(t,e=""){const n={pass:'',warning:'',fail:'',info:''};return``}function $p(t){return{pass:"Passed review",warning:"Needs attention",fail:"Blocking issues"}[t]||"Needs attention"}function eb(){return C_({bundle:y.artifactBundle,reviewResult:y.step3Result})}function tb(t){return` +`;const o=hh({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,userFeedback:s});io({runId:i}),Ft(2,i),rt(2),Ae(2,!0);const a=await Gs(o,n,[],i);if(!re(i))return;y.step2Result=a,qs(),tn(2,i);const l=document.getElementById("step2-output"),u=di(y.step2Result);l.textContent=u,l.dataset.raw=u,Ae(2,!1),rt(3),Ft(3,i),Ae(3,!0);const c=await Ks(y.step2Result,y.step1Result);if(!re(i))return;y.step3Result=c,zs(),tn(3,i);const d=document.getElementById("step3-output");d.textContent=y.step3Result,Ae(3,!1),gr();const f=Us(y.step3Result);mr(u,f)}catch(s){if(console.error("Regeneration failed:",s),!re(i))return;const o=js(s,{architect:2,generator:2,review:3});s.isUsageLimit&&un(),rt(o),Ae(o,!1),Np(s,{stage:o,runId:i,retry:()=>fp(t,e)}),Ps(o,"error")}finally{r&&(r.disabled=!1,r.textContent="Fix Errors & Regenerate"),re(i)&&(y.isRunning=!1,rn())}}async function lw(){const t=document.getElementById("ff-status-dot"),e=document.getElementById("ff-status-text");if(!t||!e)return;const n=await Re("flutterflow"),i=await Re("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 hp(t){try{const e=await fetch(`${_t}/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 cw(t){try{const n=await(await fetch(`${_t}/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 uw(t){try{const e=await fetch(`${_t}/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:`${_t}/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:`${_t}/auth/refresh-session`,message:e.message,stack:e.stack}),null}}function fd(t,e){const n=gp(),i=(H.email||n.email)!==t;H.email=t,H.sessionToken=e,H.isVerified=!0,ce=Ln({isLoading:!0}),localStorage.setItem(bs,JSON.stringify({email:t,sessionToken:e})),i&&bp()}function pp(){H.email=null,H.sessionToken=null,H.isVerified=!1,ce=Ln({isResolved:!0}),localStorage.removeItem(bs),localStorage.removeItem(Ss)}function gp(){try{const t=localStorage.getItem(bs);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(bs),{email:null,sessionToken:null}}}async function dw(){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 cw(e);fd(n,i),mp();const r=hd();r&&!window.location.hash&&(window.location.hash=r)}catch(n){hd();const i=n.message||"Sign-in link invalid or expired.";Ee(i,"error"),Ys(),Zn(i,"error")}}else{const{email:n,sessionToken:i}=gp();if(n&&i){const r=await uw(i);r?fd(r.email,r.sessionToken):pp()}}ec()}function fw(){try{localStorage.setItem(Ua,JSON.stringify({hash:window.location.hash||"#home",ts:Date.now()}))}catch(t){console.warn("rememberSignInReturnSurface: failed to persist return surface:",t)}}function hd(){try{const t=localStorage.getItem(Ua);if(localStorage.removeItem(Ua),!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 Ys(){const t=document.getElementById("signin-modal");if(!t)return;fw(),document.getElementById("signin-email-input")?.removeAttribute("aria-invalid"),Zn(""),We(t)}function mp(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("signin-modal");e&&qe(e)}function Zn(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 hw(){const t=document.getElementById("signin-email-input"),e=document.getElementById("signin-submit-btn"),n=Bs(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"),Zn("Please enter a valid email address.","error");return}t?.removeAttribute("aria-invalid"),e&&(e.disabled=!0,e.textContent="Sending…");const r=Eh(n);r&&Zn(r,"error");try{const s=await hp(n),o=s?.code===bh;t&&!o&&(t.value=""),t?.setAttribute("aria-invalid",String(o)),Zn(Sh(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}),Zn("Something went wrong. Please try again.","error"),e&&(e.disabled=!1,e.textContent="Send Sign-in Link")}}function pw(){H.email=null,H.sessionToken=null,H.isVerified=!1,ce=Ln({isResolved:!0}),iy({storage:window.localStorage,onIdentityChanged:ec,onPlanChanged:Zs})}const gw=ry({sendLink:hp,getEmail:()=>H.email||"",onState:mw});function mw(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=Sh(t.data,H.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 vw(){await gw()}function _w(){const t=ty(window.localStorage),e=t.length?`Cleared disposable UI caches: ${t.join(", ")}.`:"Nothing disposable to clear.";Ee(`${e} Your run count, identity and stored keys are kept.`,"info")}function yw(){const t=document.getElementById("delete-unavailable-modal");t&&We(t,{trigger:document.activeElement})}function ww(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("delete-unavailable-modal");e&&qe(e)}function ec(){const t=H.isVerified&&!!H.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=H.email||"");const s=document.getElementById("access-signed-email");s&&(s.textContent=H.email||""),Fw(),Zs()}async function vp(){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(Zy,{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(pt.userId=r.user_id,pt.token=r.identity_token||null,pt.status=r.status,pt.resolved=!0,sessionStorage.setItem(Yy,r.user_id),pt.token&&sessionStorage.setItem(Jy,pt.token),r.usage_count!==void 0){const s=mn(),a=(r.usage_month||s)===s?r.usage_count:0;localStorage.setItem(Rn,JSON.stringify({count:a,month:s})),un()}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 Yo=null;function bw(t=5e3){return pt.resolved?Promise.resolve():(Yo||(Yo=vp().catch(e=>{console.warn("ensureIdentityReady: identity resolution failed",e)})),Promise.race([Yo,new Promise(e=>setTimeout(e,t))]))}function _p(){const t=mn();try{const e=localStorage.getItem(Rn);return e?JSON.parse(e):{count:0,month:t}}catch(e){return console.warn("getUsageData: failed to parse usage storage",{key:Rn,month:t,err:e}),localStorage.removeItem(Rn),{count:0,month:t}}}function mn(){const t=new Date;return`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,"0")}`}function pr(){const t=_p();return t.month!==mn()?{count:0,month:mn()}:t}function Ew(){const e={count:pr().count+1,month:mn()};return localStorage.setItem(Rn,JSON.stringify(e)),e}function vi(){return!!ce.isLoading}function Tt(){return!!ce.isResolved}function Sw(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(Es,e)?e:null}function xw(t){return t&&Object.entries(jh).find(([,e])=>e===t)?.[0]||null}function $r(...t){return t.find(e=>e!=null&&e!=="")}function Iw(...t){return t.find(e=>e&&typeof e=="object")||{}}function kw(t){const e=t.data&&typeof t.data=="object"?t.data:t,n=Iw(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=$r(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=$r(e.status,e.subscriptionStatus,e.subscription_status,n.status,"none"),o=Sw($r(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=Xy.has(String(s).toLowerCase()),l=e.active===!0||e.isSubscribed===!0||e.subscribed===!0||e.hasSubscription===!0,u=o||xw(r)||(a||l?"professional":"free");return Ln({tier:u,status:s,periodEnd:$r(e.periodEnd,e.currentPeriodEnd,e.current_period_end,n.current_period_end,n.periodEnd,null),isResolved:!0})}function Js(){return Es[ce.tier]??Es.free}async function Cw(){if(H.isVerified&&(!Tt()||vi())&&(await wp({force:!0}),Zs()),H.isVerified&&!Tt())return Ee("Could not verify your subscription. Please refresh or try Manage billing.","error"),!1;const{count:t}=pr(),e=Js();if(t>=e)return yp(t,e,{openModal:!0}),!1;const n=Math.floor(e*.8);if(t>=n){const i=e-t;Ee(`${i} run${i===1?"":"s"} remaining this month.`,"warning")}return!0}function pd(){const t=document.getElementById("paywall-exhausted");t&&t.classList.add("hidden")}function yp(t,e,n={}){nn(!0);const i=document.getElementById("walkthrough-modal");i&&qe(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){Ee(`You've used all ${e} runs for this month. Upgrade to continue.`,"error"),gi();return}const c=document.getElementById("paywall-exhausted-text");if(c){const f=ce.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",H.isVerified),u.classList.remove("hidden"),n.openModal&&gi()}function Za(t){return ce.tier==="free"&&Hr.includes(t)?xs:t}function Aw(){const t=document.getElementById("code-options-content"),e=document.getElementById("code-generator-model");if(!t||!e)return;const n=ce.tier,r=!(H.isVerified&&!Tt())&&n==="free";Array.from(e.options).forEach(o=>{const a=Gt(o.value),l=Hr.includes(o.value);o.textContent=l&&r?`${a} (PRO)`:a,o.disabled=!1}),r&&Hr.includes(e.value)&&(e.value=xs),e.disabled=!1,ed.has(e)||(e.addEventListener("change",()=>{Tt()&&ce.tier==="free"&&Hr.includes(e.value)&&(e.value=xs,gi()),Ja(e.value),$l()}),ed.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(),Ja(e.value)}function tc(){const t=H.isVerified&&!!H.email,e=t&&vi(),n=!t||Tt(),i=pr(),r=n?i.count:0,s=n?Js():0,o=Math.max(0,s-r),a=`${r} / ${s} runs this month`,l=bl,u=n?ce.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 p=document.getElementById("usage-dialog-status");p&&(e?p.textContent="Verifying your subscription…":n?p.textContent="Runs reset at the start of each month.":p.textContent="Could not verify your subscription. Try again or sign out.");const h=document.getElementById("usage-counter");if(h)if(e&&t)h.textContent="Checking plan…",h.className="text-xs text-gray-500";else if(!n&&t)h.textContent="Plan check failed",h.className="text-xs text-red-600 font-medium";else{h.textContent=a;const g=s>0?r/s:0;h.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=_p(),v=m.month===mn()?m.count??0:0;g.textContent=`${v} / ${Es.free} generations used`}}Pw()}function Pw(){if(!(H.isVerified&&!!H.email))return;const e=vi(),n=Tt(),i=pr(),r=n?i.count:0,s=n?Js():0,o=Math.max(0,s-r),a=n?ce.tier||"free":null,l={free:"Free",professional:"Pro",power:"Power"}[a]||"Free",u=H.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 p=document.getElementById("acct-plan-tier"),h=document.getElementById("acct-plan-price"),g=document.getElementById("acct-plan-note"),m=document.getElementById("acct-renewal");if(p&&(p.textContent=e?"Checking…":n?l:"Plan unavailable"),h)if(e)h.textContent="—";else if(!n)h.textContent="—";else if(a==="free")h.textContent="$0 / month";else{const x=ji(Di[a]??0,Ml());h.textContent=`${x} / 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 x=Date.parse(ce.periodEnd||""),F=n&&a!=="free"&&!!ce.periodEnd&&!Number.isNaN(x);if(e)m.textContent="";else if(!n)m.textContent="";else if(a==="free")m.textContent="";else if(F){const $=new Date(x).toLocaleDateString(void 0,{year:"numeric",month:"long",day:"numeric"});m.textContent=`Renews ${$} · 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"),b=document.getElementById("acct-meter-fill"),k=document.getElementById("acct-meter-meta"),T=document.getElementById("acct-meter-track");if(_&&(_.textContent=e?"…":n?String(r):"—"),b){const x=n&&s>0?Math.min(100,Math.round(r/s*100)):0;b.style.width=`${x}%`}if(k)if(e)k.textContent="Checking…";else if(!n)k.textContent="Plan check failed";else if(s===0)k.textContent=`${r} of ${s}`;else{const x=Math.round(r/s*100);k.textContent=`${r} of ${s} · ${x}%`}T&&(e?T.setAttribute("aria-label","Checking usage…"):n?T.setAttribute("aria-label",`${r} of ${s} generations used`):T.setAttribute("aria-label","Usage unavailable")),vt()}function un(){if(tc(),H.isVerified&&(vi()||!Tt())){pd();return}const{count:t}=pr(),e=Js();t>=e&&!y.isRunning&&!Ev()?yp(t,e):pd()}function Fw(){tc()}async function wp(t={}){const e=t.force===!0;if(!H.isVerified||!H.sessionToken){ce=Ln({isResolved:!0});return}ce={...ce,isLoading:!0,error:null};const n=H.sessionToken,i=localStorage.getItem(Ss);if(!e&&i)try{const{data:r,email:s,ts:o,version:a}=JSON.parse(i);if(a===td&&s===H.email&&Date.now()-o<300*1e3){ce={...r,isLoading:!1,isResolved:r.isResolved!==!1};return}}catch(r){console.warn("Failed to parse subscription cache:",r,"| raw value:",i)}try{const s=await(await fetch(`${_t}/stripe/get-subscription`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:H.sessionToken,user_id:pt.userId})})).json();if(!H.isVerified||H.sessionToken!==n)return;if(s.error){if(["unauthorized","invalid session","expired session"].some(a=>String(s.error).toLowerCase().includes(a))){pp(),ec();return}ce=Ln({isResolved:!1,error:s.error});return}ce=kw(s),localStorage.setItem(Ss,JSON.stringify({version:td,data:ce,email:H.email,ts:Date.now()}))}catch(r){if(!H.isVerified||H.sessionToken!==n)return;console.error("fetchSubscription failed:",r),ce={...ce,isLoading:!1,isResolved:!1,error:r.message}}}function bp(){localStorage.removeItem(Ss)}async function Rw(t){if(!H.isVerified||!H.sessionToken){Ep(),Ys();return}if(!jh[t]){Ee("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(`${_t}/stripe/create-checkout-session-intl`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tierId:t,sessionToken:H.sessionToken,currency:Ml()})})).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"),Ee("Could not start checkout. Please try again.","error")}}async function Tw(t){if(!H.isVerified||!H.sessionToken){Ys();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(`${_t}/stripe/create-portal-session`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:H.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),Ee("Could not open billing portal. Please try again.","error")}}const Fs=new Set;function $w(){Fs.forEach(t=>t.abort()),Fs.clear()}async function Rs(t,e,n,i={},r=[]){const o=new AbortController;Fs.add(o);let a=!1;const l=setTimeout(()=>{a=!0,o.abort()},12e4);try{const u=await fetch(Ky,{method:"POST",headers:{"Content-Type":"application/json",...pt.token?{Authorization:`Bearer ${pt.token}`}:{}},signal:o.signal,body:JSON.stringify({user_id:pt.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(Rn,JSON.stringify({count:d.serverCount,month:mn()})),un());const h=new Error(d.message||"Monthly usage limit reached. Upgrade to continue.");throw h.isUsageLimit=!0,h.pipelineStep=t,h}const f=jv(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 h=mn();(d.usage_month||h)===h&&(localStorage.setItem(Rn,JSON.stringify({count:d.usage_count,month:h})),un())}else Ew(),un();let p=d.output||d.content;if(!p){const h=c?` (body: ${c.slice(0,120)})`:"";throw new Error(`BuildShip returned no output for step "${t}"${h}`)}return Array.isArray(p)&&(p=p.map(h=>typeof h=="string"?h:h.text||"").join("")),typeof p!="string"&&(p=JSON.stringify(p)),p}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),Fs.delete(o)}}let Xa=!1;function Mw(){const e=new URLSearchParams(window.location.search).get("checkout");return e==="success"?(window.history.replaceState({},"",window.location.pathname+window.location.hash),bp(),Xa=!0):e==="cancel"&&(window.history.replaceState({},"",window.location.pathname+window.location.hash),Ee("Checkout cancelled.","info")),e}function Lw(){if(!Xa)return;Xa=!1;const t=ce.tier!=="free";Ee(t?"Subscription active! Your plan is live.":"Checkout complete — confirming your subscription. Check Manage billing if it does not update.",t?"success":"info")}function Zs(){const t=H.isVerified&&!!H.email,e=ce.tier,n=t&&vi(),i=!t||Tt(),r=document.getElementById("subscription-tier-badge");if(r){const a=bl,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"),Nw(i?e:null),Aw(),$l(),un(),Up()}function Nw(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 Ow(){document.querySelectorAll(".pm-card[data-tier]").forEach(t=>{const e=t.dataset.tier,n=Cv[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 Qa(){const t=Ml(),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=ji(Di.professional,t)),n&&(n.textContent=ji(Di.power,t)),i&&(i.textContent=ji(Di.professional,t)),r&&(r.textContent=ji(Di.power,t));const u="billed monthly";s&&(s.textContent=u),o&&(o.textContent=u),a&&(a.textContent=u),l&&(l.textContent=u)}function gi(){Qa();const t=document.getElementById("pricing-modal");t&&We(t),c0().then(()=>Qa())}function Ep(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("pricing-modal");e&&qe(e)}function Ee(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()=>{xv(),hljs.configure({tabReplace:" ",classPrefix:"hljs-"}),Bw(),window.__heroField=wy(),window.__pipelineLogo=xy(),Hh=zy({onSubmit:cr}),Ha=(async()=>{try{await dw(),Mw(),await wp()}catch(n){console.warn("Startup auth/subscription initialization failed:",n)}})(),await Ha,Lw(),Zs(),Qa(),Ow(),await B0(),$0();const t=document.getElementById("flutterflow-endpoint-select");if(t){const n=yt();t.value=n}ep(),vp();const e=document.getElementById("pipeline-input");e&&(e.addEventListener("input",()=>{en===2&&e.value.trim().length>0&&(Dl(),Hs())}),e.addEventListener("blur",()=>{const n=document.getElementById("walkthrough-modal");en===2&&n&&We(n)}),e.addEventListener("keydown",n=>{if(n.key==="Tab"){const i=document.getElementById("walkthrough-modal");en===2&&i&&setTimeout(()=>{We(i)},100)}})),window.addEventListener("commitStateChange",n=>{const{state:i}=n.detail;i===ee.PREPARING||i===ee.VALIDATING||i===ee.PUSHING?(Ap(),Be.phaseId||Pp(),md(i)):(i===ee.SUCCESS||i===ee.ERROR)&&(md(i),Yi=setTimeout(()=>{Yi=null,rc()},1e3))}),dc()});function Bw(){const t=document.getElementById("preview-frame-container");t&&(t.style.display="")}function Dw(){const t=document.getElementById("welcome-video-player");t&&(t.addEventListener("click",On),document.addEventListener("keydown",On))}function On(){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",On),document.removeEventListener("keydown",On),ep()}let Ki=null;async function jw(){const t=document.getElementById("confirm-project-select");if(!t)return;const e=++od,n=()=>e===od,i=await Re("flutterflow"),r=await Re("flutterflow_project_id");if(n()){if(!i){t.innerHTML='',t.disabled=!0;return}t.disabled=!1,t.innerHTML='';try{const o=await new mi(i,"","main",yt()).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 Uw(){return document.getElementById("confirm-project-select")?.value?.trim()||null}function nc(t,e,n,i=null){Ki={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,jw();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 ${Qt(c)}`:"version resolved from your project";return`
  • • ${Qt(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=>`
  • • ${Qt(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&&We(l)}function Sp(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("commit-confirm-modal");e&&qe(e),Ki=null}function Hw(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("commit-success-modal");e&&qe(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 xp(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||[],p=t.approximate||[],h=t.warnings||[];(h.length>0||f.length>0||p.length>0)&&c&&d&&(d.innerHTML=[...f.map(m=>`
  • Not verified before deploying: ${z(String(m))}
  • `),...p.map(m=>`
  • Verified approximately: ${z(String(m))}
  • `),...h.map(([m,v])=>`
  • ${z(m)}: ${z(String(v))}
  • `)].join(""),c.classList.remove("hidden"));const g=document.getElementById("commit-success-modal");g&&We(g)}function Ip(t){rc(),aw(t);const e=t.remoteRefusal===!0;ic(t,{heading:"Deploy failed",title:e?"FlutterFlow refused this deploy — nothing was confirmed written.":"The deploy failed before FlutterFlow confirmed anything.",guidance:e?"Review the error and any per-file outcomes above, fix them in your code or in FlutterFlow, then deploy again. A refusal is definitive: no part of this deploy was applied, so retrying is safe once the problem is fixed.":"Review the error above, fix it, then deploy again. The deploy stopped before a write was confirmed, so nothing was applied."})}function ic(t,{heading:e,title:n,guidance:i}){const r=t.targetIdentity||{},s=document.getElementById("commit-terminal-modal");if(!s)return!1;const o=(h,g)=>{const m=document.getElementById(h);m&&(m.textContent=g||"")};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(([g,m])=>`
    ${z(g)}:${z(String(m??"—"))}
    `).join("")}const l=document.getElementById("terminal-file-outcomes");let u=t.errorMap;u&&!(u instanceof Map)&&(u=new Map(Object.entries(u)));const c=l?.querySelector("ul");l&&c&&u&&u.size>0?(c.innerHTML=[...u.entries()].map(([h,g])=>`
  • ${z(h)}: ${z(Al(g))}
  • `).join(""),l.classList.remove("hidden")):l&&(c&&(c.innerHTML=""),l.classList.add("hidden"));const d=document.getElementById("terminal-guidance");d&&(d.innerHTML=i);const f=document.getElementById("terminal-open-ff-link"),p=r.projectId||t.metadata?.projectId;return f&&(f.href=p?`https://app.flutterflow.io/project/${p}`:"https://app.flutterflow.io/"),We(s),!0}function kp(t){ic(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 Cp(t){ic(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 Ww(t){t&&t.target!==t.currentTarget||qe(document.getElementById("commit-terminal-modal"))}function qw(){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 gd={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}},zw=[{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..."}];let Yi=null;function Ap(){Yi&&clearTimeout(Yi),Yi=null}const Be={sequence:[],phaseId:null,phaseStartedAt:null,timer:null,substatus:null,liveSubstatus:!1,start({withProvisioning:t=!1}={}){Ap(),this.sequence=["prepare","validate","project"],t&&this.sequence.push("provision"),this.sequence.push("package","push","done");const e=document.getElementById("commit-progress-overlay");e&&(Fu(e,!0,"Deploying to FlutterFlow"),We(e)),this.set("prepare")},set(t,e=null){if(!(!gd[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=gd[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=zw.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(Vw(e)),Fp(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&&(Fu(t,!1),qe(t,{force:!0,restoreFocus:!1}))}};function Vw(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 Pp(t){Be.start(t)}function rc(){Be.stop()}function Fp(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 md(t){const e={[ee.PREPARING]:"prepare",[ee.VALIDATING]:"validate",[ee.PUSHING]:"project",[ee.SUCCESS]:"done"};if(t===ee.ERROR){Be.timer&&clearInterval(Be.timer),Be.timer=null,Fp(100,"Failed","Error occurred");return}const n=e[t];n&&Be.set(n)}function Gw(t){return t.bundlePlan?t.bundlePlan.fileEntries.some(e=>e.type===J.CODE_FILE):t.codeInfo?.codeType===J.CODE_FILE}let Rp=!1;function Tp(t){Rp=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 vd(t){rc(),Tp(!1);const e=Lh(t);e===Le.COMMITTED?xp(t):e===Le.PARTIAL?kp(t):e===Le.UNCONFIRMED?Cp(t):Ip(t)}async function Kw(){if(!Ki){console.error("No pending commit data");return}if(Rp){console.warn("Deploy already in flight; ignoring duplicate confirm.");return}const t=Ki;if(Ki=null,Gi=Uw(),Sp(),Tp(!0),Pp({withProvisioning:Gw(t)}),t.bundlePlan){const o=await J0(t.bundlePlan,{pipelineResult:{step1Result:y.step1Result,selectedModel:document.getElementById("code-generator-model")?.value}});Gi=null,vd(o);return}const{codeInfo:e}=t,{artifactType:n,artifactName:i,fileName:r}=np(),s=await Y0(e.content,{artifactType:n,artifactName:i,fileName:r,pipelineResult:{step1Result:y.step1Result,selectedModel:document.getElementById("code-generator-model")?.value}});Gi=null,vd(s)}window.runThinkingPipeline=cr;window.toggleStep=Q0;window.toggleSection=X0;window.selectWorkflowStep=rt;window.copyCode=ew;window.retryWithDifferentModel=rw;window.openApiKeysModal=Bl;window.closeApiKeysModal=Xh;window.openComposerSettings=S0;window.closeComposerSettings=x0;window.walkthroughConnectAccount=E0;window.closeWalkthroughModal=k0;window.openWalkthroughModal=I0;window.advanceWalkthrough=Dl;window.commitToFlutterFlow=K0;function Yw(){const t=document.getElementById("pipeline-input");t&&t.focus()}function Jw(){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=Yw;window.openModelSelector=Jw;window.handlePromptImageSelect=a0;window.removePromptImage=l0;window.saveApiKeys=P0;window.validateFlutterFlowConnection=Ul;window.clearAllApiKeys=F0;window.toggleKeyVisibility=L0;window.handleWelcomeVideoEnd=Dw;window.dismissWelcomeVideo=On;window.initiateCommitToFlutterFlow=sw;window.updateFlutterFlowCredentialStatus=lw;window.openCommitConfirmModal=nc;window.closeCommitConfirmModal=Sp;window.closeCommitSuccessModal=Hw;window.closeCommitTerminalModal=Ww;window.showCommitPartialModal=kp;window.showCommitUnconfirmedModal=Cp;window.showCommitSuccessModal=xp;window.showCommitFailureModal=Ip;window.toggleCodePreview=qw;window.confirmCommitToFlutterFlow=Kw;window.runRefinement=up;window.regenerateFromPastedErrors=dp;window.clearErrorInput=iw;window.setFlutterFlowEndpoint=b0;window.getFlutterFlowEndpoint=yt;window.commitProgress=Be;window.openSignInModal=Ys;window.closeSignInModal=mp;window.handleMagicLinkRequest=hw;window.handleSignOut=pw;window.handleSendNewLink=vw;window.handleClearCache=_w;window.handleDeleteAccount=yw;window.closeDeleteUnavailableModal=ww;window.startCheckout=Rw;window.openCustomerPortal=Tw;window.openPricingModal=gi;window.closePricingModal=Ep;let Gr=null,$p=null,Bn={1:"pending",2:"pending",3:"pending"},sc=1,oc=null;const Xs={1:"Prompt Architect",2:"Code Generator",3:"Code Review"},Zw={1:"Understanding your prompt",2:"Generating Dart code",3:"Running the code audit"},Xw={1:"Prompt understood",2:"Dart code generated",3:"Code audit complete"};function Qs(){return y.runId+=1,y.runId}function re(t){return t===void 0||t===y.runId}function Qw(){y.runId+=1}function ac(t){return document.getElementById(`pdot-${t}`)}function el(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 eo(t){const e=document.getElementById("pipeline-progress");e&&(e.dataset.runState=t)}function Tn(t,e){Bn[t]=e;const n=ac(t);if(!n)return;n.dataset.state=e,n.disabled=e==="pending"||e==="skipped";const i=Xs[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 eb(){return[1,2,3].filter(t=>Bn[t]==="done").length}function to(){const t=document.getElementById("pipeline-progress-fill");t&&(t.style.width=`${eb()/3*100}%`);const e=document.getElementById("progress-stage-count");e&&(e.textContent=`Step ${sc} of 3`)}function no(t,{done:e=!1}={}){const n=document.getElementById("progress-title-text"),i=document.getElementById("progress-substep-text"),r=Bn[t],s=e||r==="done";if(n&&(n.textContent=s?Xw[t]:Zw[t]),i){const o=s?" — complete":r==="failed"?" — stopped":"";i.textContent=`Step ${t} of 3 — ${Xs[t]}${o}`}}function tb(t){Bn[t]==="pending"||Bn[t]==="skipped"||(oc=t,[1,2,3].forEach(e=>{const n=ac(e);n&&n.setAttribute("aria-pressed",String(e===t))}),no(t))}function lc(){oc=null,[1,2,3].forEach(t=>{const e=ac(t);e&&e.removeAttribute("aria-pressed")})}function Mp(t){const e=document.getElementById("pipeline-note");e&&(e.textContent=t||"",e.hidden=!t)}function nb(t,e,n){re(n)&&Mp(`${Gt(t)} did not answer. Continuing on ${Gt(e)}.`)}function cc(){const t=document.getElementById("pipeline-failure");if(!t)return;t.hidden=!0;const e=document.getElementById("pipeline-failure-actions");e&&e.replaceChildren()}const ib=1120;function rb(){const t=getComputedStyle(document.documentElement).getPropertyValue("--t-morph").trim(),e=Number.parseFloat(t);return Number.isFinite(e)&&e>0?e:ib}let ni=null,Kr=null;function sb(){return window.matchMedia?.("(prefers-reduced-motion: reduce)").matches===!0}function dn(){if(Kr){try{Kr.cancel()}catch{}Kr=null}ni&&(ni.remove(),ni=null),window.removeEventListener("resize",dn)}function Lp(t,e){if(dn(),sb()||!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:rb(),fill:"both"});ni=r,Kr=c,window.addEventListener("resize",dn),c.onfinish=()=>{if(ni!==r)return;const d=r.animate([{opacity:1},{opacity:0}],{duration:260,fill:"forwards"});d.onfinish=()=>{ni===r&&dn()}}}function ob(){const e=document.getElementById("composer")?.getBoundingClientRect();e&&requestAnimationFrame(()=>{requestAnimationFrame(()=>{Lp({getBoundingClientRect:()=>e},document.getElementById("main-stage-container"))})})}function ab(){Lp(document.getElementById("pipeline-progress"),document.getElementById("main-stage-container"))}window.addEventListener("hashchange",dn);window.addEventListener("popstate",dn);function io(t={}){const{prompt:e=null,runId:n}=t;if(!re(n))return;so(),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"),eo("running"),e!==null){const a=document.getElementById("pipeline-submitted-prompt");a&&(a.textContent=e)}$p=Date.now();const o=document.getElementById("progress-elapsed");o&&(o.textContent="0s"),Bn={1:"pending",2:"pending",3:"pending"},lc(),cc(),Mp(""),[1,2,3].forEach(a=>Tn(a,"pending")),Ft(1,n),lb()}function Ft(t,e){re(e)&&(sc=t,lc(),[1,2,3].forEach(n=>{n===t?Tn(n,"active"):nt&&Tn(n,"pending")}),no(t),to())}function tn(t,e){re(e)&&(Tn(t,"done"),oc===null&&no(t,{done:!0}),to())}function Np(t,{stage:e=1,runId:n,retry:i=Op}={}){if(!re(n))return;ro(),so(),dn(),eo("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"),Tn(e,"failed"),[1,2,3].forEach(h=>{h>e&&Tn(h,"pending")}),sc=e,lc(),no(e),to();const o=Bh(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=`${Xs[e]}: ${o.title}`,u.textContent=o.message,c){const h=o.detail&&o.detail!==o.message?o.detail:"";c.textContent=h,c.hidden=!h}d.replaceChildren();const f=[o.canUpgrade&&{id:"upgrade",label:"View plans",variant:"primary",onClick:()=>gi()},o.canRetry&&{id:"retry",label:"Retry",variant:o.canUpgrade?"secondary":"primary",onClick:i},o.canEdit&&{id:"edit",label:"Edit prompt",variant:"secondary",onClick:tl}].filter(Boolean);!o.canEdit&&!o.canRetry&&f.push({id:"edit",label:"Back to prompt",variant:"secondary",onClick:tl}),f.forEach(h=>{const g=document.createElement("button");g.type="button",g.textContent=h.label,g.dataset.action=h.id,g.dataset.variant=h.variant,g.addEventListener("click",h.onClick),d.appendChild(g)}),a.hidden=!1;const p=d.querySelector("button");p&&p.focus({preventScroll:!0})}function tl(){Qw(),$w(),y.isRunning=!1,el(!1),rn(),eo("settled"),dn(),ro(),so(),cc();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.dispatchEvent(new Event("input",{bubbles:!0}))),e.focus({preventScroll:!0}),e.setSelectionRange(e.value.length,e.value.length))}function Op(){const t=document.getElementById("pipeline-input");t&&y.submittedPrompt&&(t.value=y.submittedPrompt,t.dispatchEvent(new Event("input",{bubbles:!0}))),Oe=y.submittedImages.slice(),cn(),cc(),cr()}function lb(){ro(),Gr=setInterval(()=>{const t=(Date.now()-$p)/1e3,e=document.getElementById("progress-elapsed");e&&(e.textContent=`${Math.floor(t)}s`)},250)}function ro(){Gr&&(clearInterval(Gr),Gr=null)}let Ji=null;function so(){Ji&&(clearTimeout(Ji),Ji=null)}function gr(){ro(),so(),eo("settled"),to();const t=document.getElementById("pipeline-progress-fill");Ji=setTimeout(()=>{Ji=null;const e=document.getElementById("pipeline-progress");e&&e.classList.remove("visible"),t&&(t.style.width="0%")},400)}function $n(t,e=""){const n={pass:'',warning:'',fail:'',info:''};return``}function Bp(t){return{pass:"Passed review",warning:"Needs attention",fail:"Blocking issues"}[t]||"Needs attention"}function cb(){return N_({bundle:y.artifactBundle,reviewResult:y.step3Result})}function ub(t){return`
    - ${Tn(t.severity)} + ${$n(t.severity)}
    -
    ${q(t.message)}
    - ${t.suggestion?`
    ${q(t.suggestion)}
    `:""} - ${q(t.source)} +
    ${z(t.message)}
    + ${t.suggestion?`
    ${z(t.suggestion)}
    `:""} + ${z(t.source)}
    - `}function nb(t){return` + `}function db(t){return`
  • - ${q(t.title)} - ${t.detail&&t.detail!==t.title?`

    ${q(t.detail)}

    `:""} + ${z(t.title)} + ${t.detail&&t.detail!==t.title?`

    ${z(t.detail)}

    `:""}
  • - `}function ib(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?` + `}function fb(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=>`
    • - ${Tn(u.severity)} + ${$n(u.severity)} - ${q(u.message)} - ${u.suggestion?`${q(u.suggestion)}`:""} + ${z(u.message)} + ${u.suggestion?`${z(u.suggestion)}`:""}
    • `).join("")}
    `:"",a=t.warnings.length?`
    -

    ${Tn("warning")} Bundle

    +

    ${$n("warning")} Bundle

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

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

    +

    ${$n("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)}`:""} + ${z(u.title)} + ${u.detail&&u.detail!==u.title?`${z(u.detail)}`:""}
    • `).join("")}
    @@ -216,7 +217,7 @@ Error: ${g} `:"";e.innerHTML=`
    -

    ${q(t.summary)}

    +

    ${z(t.summary)}

    ${o} ${a} ${l} @@ -224,9 +225,9 @@ Error: ${g}
    Is the generated code correct? @@ -242,20 +243,20 @@ Error: ${g}
    - `}function rb(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(tb).join(""):`
    ${Tn(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)}

    `:""}
  • + `}function hb(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(ub).join(""):`
    ${$n(n.icon)} ${z(n.message)}
    `,r=e.dependencies?.length?e.dependencies.map(l=>` +
  • ${z(l.name)}${l.version?` ${z(l.version)}`:""}${l.reason?`

    ${z(l.reason)}

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

    ${z(l.description)}

    `:""}
  • `).join(""):'
  • No relationships for this file
  • ';return`
    - ${Tn(e.status)} ${q($p(e.status))} -

    ${q(e.artifactName)}

    - ${e.description?`

    ${q(e.description)}

    `:""} + ${$n(e.status)} ${z(Bp(e.status))} +

    ${z(e.artifactName)}

    + ${e.description?`

    ${z(e.description)}

    `:""}
    - ${q(e.artifactType)} - ${q(e.fileName)} + ${z(e.artifactType)} + ${z(e.fileName)}
    @@ -265,7 +266,7 @@ Error: ${g} ${e.manualSteps.length?`

    Manual FlutterFlow steps for this file

    -
      ${e.manualSteps.map(nb).join("")}
    +
      ${e.manualSteps.map(db).join("")}
    `:""}
    @@ -278,9 +279,9 @@ Error: ${g}

    Deployment

    -
    Status
    ${q(e.deployStatus||"pending")}
    +
    Status
    ${z(e.deployStatus||"pending")}
    Order
    ${e.index+1} of ${t.artifacts.length}
    -
    Path hint
    ${q(e.pathHint||"Not returned")}
    +
    Path hint
    ${z(e.pathHint||"Not returned")}
    @@ -297,7 +298,7 @@ Error: ${g}
      ${a}
    - `}function sb(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=""),vd();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` + `}function pb(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=""),_d();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&&cc(o.dataset.artifactId)},vd()),e&&e.classList.add("visible")}function vd(){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")Mp();else{const a=s.dataset.artifactId;a&&cc(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 oo(){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=eb(),o=Wl();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(ib(s),sb(s),e&&(e.textContent=""),e){const a=Mh(o);e.innerHTML=a}n&&(n.innerHTML=rb(s)),i&&i.classList.toggle("hidden",y.resultsViewMode!=="summary"),r&&r.classList.toggle("hidden",y.resultsViewMode!=="file"),t&&t.classList.add("visible")}function pr(t,e){nn(!0),y.selectedArtifactId||(y.selectedArtifactId=li(y.artifactBundle).id),y.resultsViewMode="summary",document.body.classList.add("results-fullscreen");const n=document.getElementById("step3-output");n&&(n.textContent=""),oo(),rn(),ob()}function ob(){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=""),nl=!1}function cc(t){y.selectedArtifactId=t,y.resultsViewMode="file",oo()}function Mp(){y.resultsViewMode="summary",oo()}function ab(){const t=document.getElementById("btn-copy-results"),e=document.getElementById("results-copy-status"),n=Wl(),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 nl=!1;async function lb(t){const e=document.getElementById("btn-feedback-up"),n=document.getElementById("btn-feedback-down"),i=document.getElementById("results-feedback-status");if(!e||!n||nl)return;const r=l=>{i&&(i.textContent="",i.offsetWidth,i.textContent=l)},s=l=>{nl=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 Xl(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 cb(){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 Lp(){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 Np(){const t=H.isVerified&&!!H.email,e=ce.tier||"free",n=t&&vi(),i=!t||Tt(),s=n?"Checking…":i?bl[e]||"Free":"—",o=document.getElementById("topbar-plan");o&&(o.textContent=s);const a=document.getElementById("topbar-avatar");a&&(a.textContent=(H.email||"?")[0].toUpperCase()),ec();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 ub(){Np();const t=document.getElementById("credits-modal");t&&We(t)}function db(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("credits-modal");e&&ze(e)}function Op(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 _d=!1;function uc(){const t=window.location.hash.replace(/^#/,"");Op(t||"home",!1,_d),_d=!0}window.addEventListener("popstate",t=>{uc()});window.addEventListener("hashchange",()=>{uc()});window.copyResultsCode=ab;window.selectArtifact=cc;window.selectResultsSummary=Mp;window.submitResultsFeedback=lb;window.showErrorInputPanel=cb;window.hideErrorInputPanel=Lp;window.setGenerationStageVisible=nn;window.switchView=Op;window.selectPipelineStage=Vw;window.editPipelinePrompt=tl;window.retryPipelineRun=Tp;window.openCreditsModal=ub;window.closeCreditsModal=db; + `}).join(""),i.onclick=s=>{const o=s.target.closest(".artifact-tab");o?.dataset?.artifactId&&uc(o.dataset.artifactId)},_d()),e&&e.classList.add("visible")}function _d(){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&&uc(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 oo(){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=cb(),o=ql();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(fb(s),pb(s),e&&(e.textContent=""),e){const a=Dh(o);e.innerHTML=a}n&&(n.innerHTML=hb(s)),i&&i.classList.toggle("hidden",y.resultsViewMode!=="summary"),r&&r.classList.toggle("hidden",y.resultsViewMode!=="file"),t&&t.classList.add("visible")}function mr(t,e){nn(!0),y.selectedArtifactId||(y.selectedArtifactId=ci(y.artifactBundle).id),y.resultsViewMode="summary",document.body.classList.add("results-fullscreen");const n=document.getElementById("step3-output");n&&(n.textContent=""),oo(),rn(),gb()}function gb(){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=""),nl=!1}function uc(t){y.selectedArtifactId=t,y.resultsViewMode="file",oo()}function Dp(){y.resultsViewMode="summary",oo()}function mb(){const t=document.getElementById("btn-copy-results"),e=document.getElementById("results-copy-status"),n=ql(),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 nl=!1;async function vb(t){const e=document.getElementById("btn-feedback-up"),n=document.getElementById("btn-feedback-down"),i=document.getElementById("results-feedback-status");if(!e||!n||nl)return;const r=l=>{i&&(i.textContent="",i.offsetWidth,i.textContent=l)},s=l=>{nl=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 Ql(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 _b(){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 jp(){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 Up(){const t=H.isVerified&&!!H.email,e=ce.tier||"free",n=t&&vi(),i=!t||Tt(),s=n?"Checking…":i?bl[e]||"Free":"—",o=document.getElementById("topbar-plan");o&&(o.textContent=s);const a=document.getElementById("topbar-avatar");a&&(a.textContent=(H.email||"?")[0].toUpperCase()),tc();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 yb(){Up();const t=document.getElementById("credits-modal");t&&We(t)}function wb(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("credits-modal");e&&qe(e)}function Hp(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 yd=!1;function dc(){const t=window.location.hash.replace(/^#/,"");Hp(t||"home",!1,yd),yd=!0}window.addEventListener("popstate",t=>{dc()});window.addEventListener("hashchange",()=>{dc()});window.copyResultsCode=mb;window.selectArtifact=uc;window.selectResultsSummary=Dp;window.submitResultsFeedback=vb;window.showErrorInputPanel=_b;window.hideErrorInputPanel=jp;window.setGenerationStageVisible=nn;window.switchView=Hp;window.selectPipelineStage=tb;window.editPipelinePrompt=tl;window.retryPipelineRun=Op;window.openCreditsModal=yb;window.closeCreditsModal=wb; diff --git a/dist/index.html b/dist/index.html index 513a792..0893e8f 100644 --- a/dist/index.html +++ b/dist/index.html @@ -3313,7 +3313,7 @@ .send.is-busy .send-spin { animation: none; opacity: 0.6; } } - + diff --git a/src/bundleDeployPlanner.js b/src/bundleDeployPlanner.js index eb18a7a..63348d6 100644 --- a/src/bundleDeployPlanner.js +++ b/src/bundleDeployPlanner.js @@ -154,7 +154,9 @@ export function buildBundleDeployPlan(bundle, options = {}) { // the guess this replaced (`^1.0.0`) pinned every package to its first major. const detectedDependencies = {}; selected.forEach((artifact) => { - extractPackageImports(artifact.code || "").forEach((name) => { + // The same expression that fills the file entry above - an import added by + // a review fix must be discovered like any other. + extractPackageImports(artifact.fixedCode || artifact.code || "").forEach((name) => { if (!(name in declaredDependencies)) { detectedDependencies[name] = ""; } diff --git a/src/bundleDeployPlanner.test.js b/src/bundleDeployPlanner.test.js index f50150d..9283cc1 100644 --- a/src/bundleDeployPlanner.test.js +++ b/src/bundleDeployPlanner.test.js @@ -175,6 +175,26 @@ test("prefers artifact.fixedCode over artifact.code for deploy content", () => { assert.equal(plan.fileEntries[0].content, "class WidgetA extends StatelessWidget {}"); }); +test("discovers dependencies from fixedCode, the content actually deployed", () => { + // A review fix can add an import the original code never had; scanning only + // `code` would deploy the import while omitting its package. + const plan = buildBundleDeployPlan({ + artifacts: [ + { + id: "widget-a", + artifactType: "CustomWidget", + artifactName: "WidgetA", + fileName: "widget_a.dart", + code: "class WidgetA extends StatelessWidget {}", + fixedCode: + "import 'package:http/http.dart';\nclass WidgetA extends StatelessWidget {}", + }, + ], + }); + + assert.equal(plan.dependencies.http, ""); +}); + test("falls back to artifact.code when fixedCode is absent", () => { const plan = buildBundleDeployPlan({ artifacts: [ diff --git a/src/cloudRunRunner.test.js b/src/cloudRunRunner.test.js index 9f8f222..dfdb100 100644 --- a/src/cloudRunRunner.test.js +++ b/src/cloudRunRunner.test.js @@ -138,6 +138,16 @@ test("Cloud Run builds the analysis manifest itself rather than running caller-s /dependency_overrides:/, "the project's overrides must be reproduced, or resolution differs", ); + assert.match( + runnerSource, + /value\['sdkOverrides'\]/, + "sdk-sourced overrides must ride their own channel - merged into sdkPackages they land under dependencies: and duplicate a same-named scalar key", + ); + assert.match( + runnerSource, + /for \(final name in sdkOverrides[\s\S]*?sdk: flutter/, + "an sdk: override must be emitted under dependency_overrides, preserving override precedence", + ); // The previous wire format sent pubspec text. It must degrade to // "unavailable" rather than being executed, so a cached client neither keeps // the vulnerability open nor has its deploys rejected mid-rollout. diff --git a/src/customCodeVerification.js b/src/customCodeVerification.js index 6813705..5a10ab7 100644 --- a/src/customCodeVerification.js +++ b/src/customCodeVerification.js @@ -111,29 +111,42 @@ function collect(declared, into, sdkPackages) { * @returns {{ * sdkConstraint: string, * dependencies: Object, - * overrides: Object, + * dependencyOverrides: Object, * sdkPackages: string[], + * sdkOverrides: string[], * availablePackages: Set, * unrepresentable: string[], + * unrepresentableOverrides: string[], * }} */ export function buildAnalysisManifest(projectPubspecYaml) { const sdkPackages = new Set(); + const sdkOverrides = new Set(); const dependencies = {}; - const overrides = {}; + const dependencyOverrides = {}; - const unrepresentable = collect( + // The two blocks are kept apart: a direct dependency only reaches a class + // that names it, but a dependency_overrides entry rewrites resolution for + // every package in the graph that depends on the overridden name, so the + // consequences of dropping one are much wider than dropping the other. SDK + // entries are kept apart too: the runner emits sdkPackages under + // `dependencies:` and sdkOverrides under `dependency_overrides:`, and an + // `sdk:` override sharing a name with a scalar dependency must land in the + // second list or the generated pubspec declares the name twice. + const unrepresentableDependencies = collect( parseExistingDependencies(projectPubspecYaml), dependencies, sdkPackages, ); - unrepresentable.push( - ...collect( - parseDependencyBlock(projectPubspecYaml, "dependency_overrides"), - overrides, - sdkPackages, - ), + const unrepresentableOverrides = collect( + parseDependencyBlock(projectPubspecYaml, "dependency_overrides"), + dependencyOverrides, + sdkOverrides, ); + const unrepresentable = [ + ...unrepresentableDependencies, + ...unrepresentableOverrides, + ]; const availablePackages = new Set([ ...Object.keys(dependencies), @@ -145,10 +158,12 @@ export function buildAnalysisManifest(projectPubspecYaml) { return { sdkConstraint: unquoteConstraint(sdk) || FALLBACK_SDK_CONSTRAINT, dependencies, - overrides, + dependencyOverrides, sdkPackages: [...sdkPackages].sort(), + sdkOverrides: [...sdkOverrides].sort(), availablePackages, unrepresentable, + unrepresentableOverrides, }; } @@ -199,13 +214,20 @@ export function planCustomCodeVerification(classes, projectPubspecYaml) { const { sdkConstraint, dependencies, - overrides, + dependencyOverrides, sdkPackages, + sdkOverrides, availablePackages, unrepresentable, } = buildAnalysisManifest(projectPubspecYaml); - const manifest = { sdkConstraint, dependencies, overrides, sdkPackages }; + const manifest = { + sdkConstraint, + dependencies, + dependencyOverrides, + sdkPackages, + sdkOverrides, + }; const sources = []; const skipped = []; @@ -222,6 +244,11 @@ export function planCustomCodeVerification(classes, projectPubspecYaml) { for (const entry of classes) { const { className, content } = entry; + // SDK names must reach the unrepresentable check: a project can declare + // `flutter` or `flutter_localizations` from git or hosted, and a name + // filtered out here would slip past that check and reach the analyzer as + // a missing-URI error, refusing the deploy instead of reporting the class + // unverified. const importedPackages = extractPackageImports(content); // A direct import of a dependency the manifest cannot express is this diff --git a/src/customCodeVerification.test.js b/src/customCodeVerification.test.js index baaff8c..256f66c 100644 --- a/src/customCodeVerification.test.js +++ b/src/customCodeVerification.test.js @@ -91,7 +91,7 @@ test("the manifest carries the project's own constraints and SDK range", () => { test("the manifest carries dependency_overrides, which change resolved APIs", () => { const manifest = buildAnalysisManifest(PROJECT_PUBSPEC); - assert.deepEqual(manifest.overrides, { intl: "0.20.1" }); + assert.deepEqual(manifest.dependencyOverrides, { intl: "0.20.1" }); }); test("the manifest is structured data, never pubspec.yaml text", () => { @@ -368,7 +368,7 @@ test("plans a real compile for a class whose imports all resolve", () => { }, ]); assert.deepEqual(plan.skipped, []); - assert.deepEqual(plan.manifest.overrides, {}); + assert.deepEqual(plan.manifest.dependencyOverrides, {}); }); test("names the file the way FlutterFlow would, an underscore before every capital", () => { @@ -431,3 +431,227 @@ test("compiles the verifiable classes even when a sibling cannot be verified", ( ); assert.equal(plan.skipped.length, 1); }); +test("a class that exports the unreproducible dependency is skipped, not refused", () => { + // `export` pulls the package in exactly as `import` does. If exports were + // not read, the class would be compiled against a manifest missing the + // package and the analyzer would refuse the deploy over a URI it could not + // resolve, instead of the class being reported as unverified. + const exportsPrivateThing = `export 'package:private_thing/private_thing.dart'; + +class ReExportsPrivateThing {} +`; + + const plan = planCustomCodeVerification( + [{ className: "ReExportsPrivateThing", content: exportsPrivateThing }], + PROJECT_PUBSPEC, + ); + + assert.deepEqual(plan.sources, []); + assert.equal(plan.skipped.length, 1); + assert.match(plan.skipped[0].reason, /it imports private_thing/); +}); + +test("a dart:-only class still verifies under an unreproducible override", () => { + // dart: URIs come from the SDK itself, which no dependency_overrides entry + // can re-source, so nothing the class resolves can be redirected. + const pubspec = `name: my_app + +environment: + sdk: '>=3.0.0 <4.0.0' + +dependencies: + flutter: + sdk: flutter + +dependency_overrides: + core_types: + git: https://example.invalid/core.git +`; + const dartOnly = `import 'dart:async'; + +class SchedulesWork {} +`; + + const plan = planCustomCodeVerification( + [{ className: "SchedulesWork", content: dartOnly }], + pubspec, + ); + + assert.equal(plan.sources.length, 1); + assert.deepEqual(plan.skipped, []); +}); + +test("a version-constraint override is carried and does not skip anything", () => { + // The override rewrites intl to a constraint the manifest can express, so + // resolution already matches the project's and the class verifies - the + // graph-poison skip only applies to sources the manifest cannot carry. + const pubspec = `${REPRESENTABLE_PUBSPEC} +dependency_overrides: + intl: 0.20.1 +`; + + const plan = planCustomCodeVerification( + [{ className: "BackgroundDownloaderService", content: SELF_CONTAINED }], + pubspec, + ); + + assert.equal(plan.sources.length, 1); + assert.deepEqual(plan.skipped, []); +}); + +test("an sdk: override keeps its own channel instead of duplicating a scalar dependency", () => { + // A project that declares `flutter_web_plugins: any` and then overrides it + // to `{sdk: flutter}` must not emit the name under `dependencies:` twice - + // the generated pubspec would carry a duplicate key and `pub get` would + // fail, skipping the check over a manifest bug, not the project's code. + const pubspec = `name: my_app + +environment: + sdk: '>=3.0.0 <4.0.0' + +dependencies: + flutter: + sdk: flutter + flutter_web_plugins: any + +dependency_overrides: + flutter_web_plugins: + sdk: flutter +`; + + const manifest = buildAnalysisManifest(pubspec); + + assert.equal(manifest.dependencies.flutter_web_plugins, "any"); + assert.deepEqual(manifest.sdkPackages, ["flutter"]); + assert.deepEqual(manifest.sdkOverrides, ["flutter_web_plugins"]); + assert.deepEqual(manifest.dependencyOverrides, {}); + assert.deepEqual(manifest.unrepresentable, []); + + // The name is still importable: the override only changes where it resolves + // from, not whether a class may name it. + const usesWebPlugins = `import 'package:flutter_web_plugins/flutter_web_plugins.dart'; + +class RegistersPlugin {} +`; + const plan = planCustomCodeVerification( + [{ className: "RegistersPlugin", content: usesWebPlugins }], + pubspec, + ); + assert.equal(plan.sources.length, 1); + assert.deepEqual(plan.skipped, []); +}); +test("an SDK package declared as a multiline flow mapping still verifies classes", () => { + // `{` alone on the dependency's own line used to read as an unclosed - + // unreadable - mapping, so the SDK package classified unrepresentable and + // every package-importing class was skipped over a reproducible source. + const pubspec = `name: my_app + +environment: + sdk: '>=3.0.0 <4.0.0' + +dependencies: + flutter: + sdk: flutter + flutter_web_plugins: { + sdk: flutter + } + background_downloader: ^8.0.0 +`; + + const manifest = buildAnalysisManifest(pubspec); + assert.deepEqual(manifest.sdkPackages, ["flutter", "flutter_web_plugins"]); + assert.deepEqual(manifest.unrepresentable, []); + + const plan = planCustomCodeVerification( + [{ className: "BackgroundDownloaderService", content: SELF_CONTAINED }], + pubspec, + ); + assert.equal(plan.sources.length, 1); + assert.deepEqual(plan.skipped, []); +}); + +test("a conditional import of the unreproducible dependency is skipped, not refused", () => { + // `if (...)` names a second URI the code needs when the condition holds; a + // scan that reads only the first URI would send the class to the runner + // without private_thing in its manifest, and the analyzer's missing-URI + // diagnostic would refuse the deploy instead of reporting it unverified. + const conditional = `import 'package:background_downloader/background_downloader.dart' if (dart.library.io) 'package:private_thing/private_thing.dart'; + +class ConditionallyPrivate {} +`; + + const plan = planCustomCodeVerification( + [{ className: "ConditionallyPrivate", content: conditional }], + PROJECT_PUBSPEC, + ); + + assert.deepEqual(plan.sources, []); + assert.equal(plan.skipped.length, 1); + assert.match(plan.skipped[0].reason, /private_thing/); +}); + +test("a git-forked SDK package is unrepresentable for a class that imports it", () => { + // The name list in the extractor says flutter_localizations is always an + // SDK package, but this project forks it from git - the pubspec source, not + // the name, decides. Filtering the name out here would send the class to + // the analyzer without the package and its missing-URI error would refuse + // the deploy instead of reporting the class unverified. + const pubspec = `name: my_app + +environment: + sdk: '>=3.0.0 <4.0.0' + +dependencies: + flutter: + sdk: flutter + flutter_localizations: + git: + url: https://example.invalid/flutter_localizations_fork.git + background_downloader: ^8.5.0 +`; + const usesFork = `import 'package:flutter_localizations/flutter_localizations.dart'; + +class LocalizesThings {} +`; + + const manifest = buildAnalysisManifest(pubspec); + assert.deepEqual(manifest.unrepresentable, ["flutter_localizations"]); + + const plan = planCustomCodeVerification( + [{ className: "LocalizesThings", content: usesFork }], + pubspec, + ); + + assert.deepEqual(plan.sources, []); + assert.equal(plan.skipped.length, 1); + assert.match(plan.skipped[0].reason, /it imports flutter_localizations/); +}); + +test("an SDK dependency declared inline reproduces instead of breaking the manifest", () => { + // `flutter_web_plugins: {sdk: flutter}` is the same declaration as the + // block form; treated as a scalar it would be forwarded as a constraint + // whose braces the runner rejects, refusing the whole deploy. + const pubspec = `name: my_app + +environment: + sdk: '>=3.0.0 <4.0.0' + +dependencies: + flutter: + sdk: flutter + flutter_web_plugins: {sdk: flutter} + background_downloader: ^8.5.0 +`; + + const manifest = buildAnalysisManifest(pubspec); + assert.ok(manifest.sdkPackages.includes("flutter_web_plugins")); + assert.deepEqual(manifest.unrepresentable, []); + assert.equal("flutter_web_plugins" in manifest.dependencies, false); + + const plan = planCustomCodeVerification( + [{ className: "BackgroundDownloaderService", content: SELF_CONTAINED }], + pubspec, + ); + assert.equal(plan.sources.length, 1); + assert.deepEqual(plan.skipped, []); +}); diff --git a/src/dartPackageImports.js b/src/dartPackageImports.js index 6f073be..e157614 100644 --- a/src/dartPackageImports.js +++ b/src/dartPackageImports.js @@ -1,10 +1,16 @@ -// Flutter SDK packages FlutterFlow's default pubspec.yaml always provides. -// Importing these needs no dependency entry. -const FLUTTER_SDK_PACKAGES = new Set([ +// The packages the Flutter SDK itself supplies. This list is consulted only +// when there is no pubspec entry to classify - the project's own `sdk:` +// declaration is the authority wherever one exists, so a name declared from +// git stays a git fork. A name missing from the list degrades to a hosted +// lookup, not a wrong answer. +export const FLUTTER_SDK_PACKAGES = new Set([ "flutter", "flutter_test", "flutter_driver", "flutter_localizations", + "flutter_web_plugins", + "integration_test", + "sky_engine", ]); /** @@ -56,19 +62,93 @@ function stripComments(code) { return out; } +// A directive can carry further URIs in its `if (...)` clauses - each names +// the file imported when the condition holds, so every quoted literal *outside +// the parentheses* is code the class needs. The directive regex +// runs to the closing `;`, stepping over quoted literals whole because a +// string is the one place a `;` is legal - `import 'src/a;b.dart';` names a +// file, and stopping at its `;` would lose the URI. String alternatives +// consume `\x` escape pairs so an escaped quote does not end the literal +// early - `'a\'b.dart'` is one URI, not `a\` followed by a stranded quote. +// A `r` prefix makes a raw string, legal in directives too - the lookahead +// accepts it and the `r` itself rides the bare-char alternative, while the +// literal scans like any other (a valid raw URI cannot contain its own quote, +// so escape handling never changes where one ends). URI literals are read +// with paren awareness rather than a pattern: a string inside an `if (...)` +// condition is a comparison value (`dart.library.io == 'true'`), not a file, +// so only literals outside the parentheses count - and a literal inside is +// still consumed whole, because `== 'a(b'` holds a paren that isn't syntax. +// The apostrophe inside a double-quoted URI (`"src/it's.dart"`) is a filename +// char, not a delimiter, so each literal ends at its own quote type. +const DIRECTIVE_PATTERN = + /\b(?:import|export)\s+(?=r?['"])(?:'(?:\\.|[^'\\\n])*'|"(?:\\.|[^"\\\n])*"|[^;'"])*;/g; + +// A directive keyword inside a *Dart string* is display text, not a +// directive - `final doc = "export 'package:ghost/ghost.dart';"` must not +// create a `ghost` dependency. The scan therefore steps over every ordinary +// string literal whole: at any position only one alternative can match, so a +// quoted `export` is consumed as string content and its keyword never starts +// a directive. A raw `r"..."` literal needs no alternative of its own - `r` +// matches nothing, and the quote after it opens the string alternative, whose +// escape-aware body ends at the same quote a raw literal would. +const STRING_PATTERN = /'(?:\\.|[^'\\\n])*'|"(?:\\.|[^"\\\n])*"/.source; +const SCAN_PATTERN = new RegExp(`${DIRECTIVE_PATTERN.source}|${STRING_PATTERN}`, "g"); + +function* directiveMatches(code) { + const stripped = stripComments(code); + let match; + while ((match = SCAN_PATTERN.exec(stripped)) !== null) { + // A string-literal match starts with a quote; only keyword matches yield. + if (!/^(?:import|export)\s/.test(match[0])) continue; + yield match[0]; + } +} + /** - * Scans Dart source for `package:name/...` imports and returns the - * third-party pub.dev packages it references, in first-seen order. - * - * This is what a generated action's real dependencies are - not whatever an - * AI-authored spec declared alongside it. A declared dependency list can miss - * a package the code actually imports (a manual edit, a regeneration cycle - * that added an import without updating the spec), and FlutterFlow rejects a - * push whose pubspec.yaml omits a package the code imports. + * Yields the contents of every quoted literal in a directive that names code - + * the primary URI and the alternative after each `if (...)` clause. * - * @param {string} code - Dart source - * @returns {string[]} Package names, deduplicated + * @param {string} text - A directive match from DIRECTIVE_PATTERN + * @yields {string} */ +function* directiveUriLiterals(text) { + let depth = 0; + for (let i = 0; i < text.length; i += 1) { + const char = text[i]; + if (char === "(") { + depth += 1; + continue; + } + if (char === ")") { + depth = Math.max(0, depth - 1); + continue; + } + + let raw = false; + let quoteAt = i; + if (char === "r") { + if (text[i + 1] !== "'" && text[i + 1] !== '"') continue; + raw = true; + quoteAt = i + 1; + } else if (char !== "'" && char !== '"') { + continue; + } + + // A literal is consumed at every depth so parentheses inside a comparison + // value (`== 'a(b'`) never count as syntax - only depth-0 literals are + // yielded, since only they name code. + const quote = text[quoteAt]; + let end = quoteAt + 1; + for (; end < text.length; end += 1) { + // Raw strings take no escape pairs - `r'a\'b'` ends at the quote. + if (!raw && text[end] === "\\") end += 1; + else if (text[end] === quote) break; + } + if (depth === 0) yield text.slice(quoteAt + 1, end); + i = end; + } +} + /** * Returns every URI the source imports or exports, in first-seen order. * @@ -83,32 +163,48 @@ function stripComments(code) { export function extractImportUris(code = "") { const uris = []; const seen = new Set(); - const directiveRegex = /\b(?:import|export)\s+(['"])([^'"\n]+)\1/g; - const stripped = stripComments(code); - let match; - while ((match = directiveRegex.exec(stripped)) !== null) { - const uri = match[2]; - if (seen.has(uri)) continue; - seen.add(uri); - uris.push(uri); + for (const directive of directiveMatches(code)) { + for (const uri of directiveUriLiterals(directive)) { + if (seen.has(uri)) continue; + seen.add(uri); + uris.push(uri); + } } return uris; } +/** + * Returns the package names a class's `package:` URIs belong to. + * + * SDK names are included for every caller: verification must see them because + * `flutter` is not always SDK-sourced, and discovery must see them because a + * project that never declared `flutter_web_plugins` still needs the merged + * pubspec to gain `sdk: flutter` - filtering the name out entirely would + * leave the push missing a package FlutterFlow requires, and treating it as a + * hosted name instead would write a constraint pub.dev cannot resolve. + * + * @param {string} code - Dart source + * @returns {string[]} Package names, deduplicated + */ export function extractPackageImports(code = "") { const names = []; const seen = new Set(); - const importRegex = /\bimport\s+['"]package:([a-zA-Z0-9_]+)\//g; - const stripped = stripComments(code); - let match; + // `export 'package:x/x.dart'` pulls the package in exactly as `import` does, + // and an `if (...)` clause's alternative URI does the same when its + // condition holds, so every package URI in a directive names a dependency. + const packageUriPattern = /^package:([a-zA-Z0-9_]+)\//; - while ((match = importRegex.exec(stripped)) !== null) { - const name = match[1]; - if (FLUTTER_SDK_PACKAGES.has(name) || seen.has(name)) continue; - seen.add(name); - names.push(name); + for (const directive of directiveMatches(code)) { + for (const uri of directiveUriLiterals(directive)) { + const match = packageUriPattern.exec(uri); + if (!match) continue; + const name = match[1]; + if (seen.has(name)) continue; + seen.add(name); + names.push(name); + } } return names; diff --git a/src/dartPackageImports.test.js b/src/dartPackageImports.test.js index 660fb40..d3f86e0 100644 --- a/src/dartPackageImports.test.js +++ b/src/dartPackageImports.test.js @@ -1,6 +1,9 @@ import assert from "node:assert/strict"; import test from "node:test"; -import { extractPackageImports } from "./dartPackageImports.js"; +import { + extractImportUris, + extractPackageImports, +} from "./dartPackageImports.js"; test("detects a single third-party package import", () => { assert.deepEqual( @@ -39,13 +42,16 @@ test("ignores dart: sdk and FlutterFlow-managed local imports", () => { assert.deepEqual(extractPackageImports(code), []); }); -test("ignores Flutter SDK packages that need no pubspec entry", () => { +test("returns SDK names too - their source is decided downstream", () => { + // Whether `flutter` needs a pubspec entry is not the extractor's call: a + // project can declare the name from git, and an undeclared SDK import must + // reach the dependency plan so the merged pubspec can gain `sdk: flutter`. const code = [ "import 'package:flutter/material.dart';", "import 'package:flutter_test/flutter_test.dart';", ].join("\n"); - assert.deepEqual(extractPackageImports(code), []); + assert.deepEqual(extractPackageImports(code), ["flutter", "flutter_test"]); }); test("returns an empty list for code with no package imports", () => { @@ -70,6 +76,144 @@ test("ignores an import mentioned only in a block comment", () => { assert.deepEqual(extractPackageImports(code), []); }); +test("reads every URI a directive carries, including conditional alternatives", () => { + // `if (dart.library.io) 'x.dart'` selects another file the code needs, so + // both URIs in the directive count. + const code = + "import 'package:public_api/public_api.dart' if (dart.library.io) 'package:private_types/private_types.dart';\n" + + "export 'src/iface.dart' if (dart.library.html) 'package:web_impl/web_impl.dart';\n" + + "class Conditional {}\n"; + + assert.deepEqual(extractPackageImports(code), [ + "public_api", + "private_types", + "web_impl", + ]); + assert.deepEqual(extractImportUris(code), [ + "package:public_api/public_api.dart", + "package:private_types/private_types.dart", + "src/iface.dart", + "package:web_impl/web_impl.dart", + ]); +}); + +test("a semicolon inside a quoted URI does not end the directive", () => { + // `;` is legal in a Dart URI - `src/a;b.dart` is a real filename. Cutting + // the directive there would lose the URI entirely, and a conditional + // alternative written after it would be lost with it. + const code = + "import 'src/a;b.dart' if (dart.library.io) 'package:io_impl/io_impl.dart' show A;\n" + + "export \"src/b;c.dart\";\n" + + "class Plain {}\n"; + + assert.deepEqual(extractImportUris(code), [ + "src/a;b.dart", + "package:io_impl/io_impl.dart", + "src/b;c.dart", + ]); + assert.deepEqual(extractPackageImports(code), ["io_impl"]); +}); + +test("an escaped quote inside a URI does not end the literal", () => { + // `'a\'b.dart'` is one URI: the escaped `'` is part of the path, not the + // terminator. Ending the literal early loses the rest of the directive. + const code = + "import 'package:private_thing/a\\'b.dart' show A;\n" + + 'import "src/c\\"d.dart";\n' + + "class Plain {}\n"; + + assert.deepEqual(extractImportUris(code), [ + "package:private_thing/a\\'b.dart", + 'src/c\\"d.dart', + ]); + assert.deepEqual(extractPackageImports(code), ["private_thing"]); +}); + +test("raw string literals in directives are still URIs", () => { + // `r'...'` is a legal Dart prefix - the URI inside is a dependency like any + // other, and a raw string takes no escape pairs. + const code = + "import r'package:foo/foo.dart';\n" + + 'export r"package:bar/bar.dart";\n' + + "import 'package:a/a.dart' if (dart.library.io) r'package:b/b.dart';\n" + + "class Plain {}\n"; + + assert.deepEqual(extractImportUris(code), [ + "package:foo/foo.dart", + "package:bar/bar.dart", + "package:a/a.dart", + "package:b/b.dart", + ]); + assert.deepEqual(extractPackageImports(code), ["foo", "bar", "a", "b"]); +}); + +test("a paren inside a condition's comparison string is not syntax", () => { + // `== 'a(b'` is a comparison against a literal that happens to contain `(` - + // counting it as syntax would leave depth positive past the `)` and lose + // the conditional URI that follows. + const code = + "import 'package:base/base.dart' if (flag.value == 'a(b') 'package:alternate/alternate.dart';\n" + + "class Plain {}\n"; + + assert.deepEqual(extractImportUris(code), [ + "package:base/base.dart", + "package:alternate/alternate.dart", + ]); + assert.deepEqual(extractPackageImports(code), ["base", "alternate"]); +}); + +test("a directive inside a Dart string literal is display text, not an import", () => { + // The quoted `export`/`import` below only exist as string content - treating + // them as directives would add `ghost`/`phantom` to the pubspec. + const code = + "class Doc extends StatelessWidget {\n" + + ' final example = "export \'package:ghost/ghost.dart\';";\n' + + " final sample = \"import 'package:phantom/x.dart';\";\n" + + ' final raw = r"export \'package:raw_ghost/r.dart\';";\n' + + "}\n" + + "import 'package:real/real.dart';\n"; + + assert.deepEqual(extractImportUris(code), ["package:real/real.dart"]); + assert.deepEqual(extractPackageImports(code), ["real"]); +}); + +test("a comparison literal inside `if (...)` is not a URI", () => { + // `== 'true'` compares a config variable with a string; the literal is not + // a file, and reading it as one would skip an otherwise verifiable class. + const code = + "import 'package:foo/foo.dart' if (dart.library.io == 'true') 'package:bar/bar.dart';\n" + + "class Plain {}\n"; + + assert.deepEqual(extractImportUris(code), [ + "package:foo/foo.dart", + "package:bar/bar.dart", + ]); + assert.deepEqual(extractPackageImports(code), ["foo", "bar"]); +}); + +test("the opposite quote inside a URI is a filename char, not a delimiter", () => { + // `"src/it's.dart"` is one URI - the apostrophe is legal inside a + // double-quoted string, and dropping it would lose the file entirely. + const code = + 'import "src/it\'s.dart";\n' + + "import 'say \"hi\".dart';\n" + + "class Plain {}\n"; + + assert.deepEqual(extractImportUris(code), [ + "src/it's.dart", + 'say "hi".dart', + ]); +}); + +test("a conditional URI in a comment is not a dependency", () => { + const code = [ + "// import 'package:a/a.dart' if (dart.library.io) 'package:b/b.dart';", + "class Plain {}", + ].join("\n"); + + assert.deepEqual(extractPackageImports(code), []); +}); + test("still detects a real import on the line after a comment mentioning a different package", () => { const code = [ "// consider package:geocoding/geocoding.dart later", diff --git a/src/dependencyResolution.js b/src/dependencyResolution.js index 5b39b17..e3847cc 100644 --- a/src/dependencyResolution.js +++ b/src/dependencyResolution.js @@ -23,10 +23,12 @@ import { } from "./pubspecSync.js"; import { constraintCanReach, constraintLowerBound } from "./pubVersions.js"; import { resolveLatestCompatibleVersions } from "./pubRegistry.js"; +import { FLUTTER_SDK_PACKAGES } from "./dartPackageImports.js"; /** * @typedef {Object} DependencyPlan - * @property {Object} additions - name -> constraint to add + * @property {Object} additions - name -> + * constraint to add, or `{sdk}` for a package the Flutter SDK supplies * @property {Object} overrides - name -> constraint to rewrite * @property {Array<{name: string, constraint: string}>} kept - left as declared * @property {string[]} warnings - what the deploying user needs to know @@ -73,11 +75,16 @@ export async function planDependencyChanges( const declared = parseExistingDependencies(yamlContent); const missing = []; + const missingSdk = []; for (const [name, requiredMinimum] of requested) { const existing = declared.get(name); if (!existing) { - missing.push(name); + // An SDK-supplied name absent from the project's pubspec is still + // SDK-sourced - pub.dev does not carry it, so a hosted constraint would + // name a source pub cannot resolve. The merged pubspec gets the same + // `sdk: flutter` entry the project would have declared itself. + (FLUTTER_SDK_PACKAGES.has(name) ? missingSdk : missing).push(name); continue; } @@ -92,9 +99,20 @@ export async function planDependencyChanges( continue; } + // A `version:` own-key - `intl: {version: 0.19.0}` or the same key on a + // block form's child line - is a hosted pin written in mapping shape, so + // it has no scalar constraint but still bounds what the project resolves + // and must be compared like one. Other block sources (git, path, SDK, + // hosted-without-version) carry no comparable version. + const effectiveConstraint = existing.isScalar + ? existing.constraint + : existing.sourceKey === null + ? existing.version + : null; + // Checked before the constraint itself: a block-form entry has no scalar // constraint, and an empty one would read as `any` and look satisfiable. - if (!existing.isScalar) { + if (effectiveConstraint === null) { plan.warnings.push( `"${name}" is declared in your project from a git, path, or SDK source, but the generated code needs at least ${minimum}. ` + "Left as-is — update it yourself if the build fails.", @@ -103,18 +121,22 @@ export async function planDependencyChanges( continue; } - if (constraintCanReach(existing.constraint, minimum)) { - plan.kept.push({ name, constraint: existing.constraint }); + if (constraintCanReach(effectiveConstraint, minimum)) { + plan.kept.push({ name, constraint: effectiveConstraint }); continue; } plan.overrides[name] = `^${minimum}`; plan.warnings.push( - `"${name}" was pinned to ${existing.constraint} in your project, which cannot resolve the ${minimum} the generated code needs. ` + + `"${name}" was pinned to ${effectiveConstraint} in your project, which cannot resolve the ${minimum} the generated code needs. ` + `Raising it to ^${minimum} — this changes a dependency the rest of your app also uses.`, ); } + for (const name of missingSdk) { + plan.additions[name] = { sdk: "flutter" }; + } + // Rule 3: everything the project does not have yet. if (missing.length > 0) { const resolved = await resolveVersions(missing, sdk); diff --git a/src/dependencyResolution.test.js b/src/dependencyResolution.test.js index dfe7bf4..b39fb69 100644 --- a/src/dependencyResolution.test.js +++ b/src/dependencyResolution.test.js @@ -51,6 +51,145 @@ test("rule 3: adds a missing package at the newest SDK-compatible release", asyn assert.deepEqual(plan.warnings, []); }); +test("rule 2: a {version: x} pin below the required floor is raised in place", async () => { + // A version written as a flow member is still a hosted pin - it must not be + // exempted from the compat check just because the entry is not scalar. + const pubspec = `name: my_app +dependencies: + flutter: + sdk: flutter + intl: {version: 0.19.0} + block_pinned: + version: 0.18.0 +`; + const plan = await planDependencyChanges(pubspec, { + intl: "0.20.0", + block_pinned: "0.20.0", + }); + + assert.deepEqual(plan.overrides, { intl: "^0.20.0", block_pinned: "^0.20.0" }); + + const merged = applyDependencyOverrides(pubspec, plan.overrides); + // The member is rewritten where it stands - the flow map keeps its braces + // and the block entry keeps its `version:` child line. + assert.match(merged.yaml, /intl: \{version: \^0\.20\.0\}/); + assert.match(merged.yaml, /block_pinned:\n version: \^0\.20\.0/); +}); + +test("rule 2: a quoted range in a version member is replaced whole, comment kept", async () => { + // A quoted range holds spaces - replacing only up to the first space would + // leave the old upper bound glued onto the new constraint. + const pubspec = `name: my_app +dependencies: + flutter: + sdk: flutter + intl: {version: '>=0.19.0 <0.20.0'} + block_pinned: + version: '>=0.18.0 <0.20.0' # deliberate cap +`; + const plan = await planDependencyChanges(pubspec, { + intl: "0.20.0", + block_pinned: "0.20.0", + }); + + assert.deepEqual(plan.overrides, { intl: "^0.20.0", block_pinned: "^0.20.0" }); + + const merged = applyDependencyOverrides(pubspec, plan.overrides); + assert.match(merged.yaml, /intl: \{version: \^0\.20\.0\}/); + assert.match(merged.yaml, /block_pinned:\n version: \^0\.20\.0 # deliberate cap/); +}); + +test("rule 2: a package named 'version' rewrites its member, not its key", async () => { + // `version` is a real pub.dev package; `version: {version: x}` must raise + // the member inside the map, not the entry's own key value. + const pubspec = `name: my_app +dependencies: + flutter: + sdk: flutter + version: {version: 0.19.0} +`; + const plan = await planDependencyChanges(pubspec, { version: "0.20.0" }); + + assert.deepEqual(plan.overrides, { version: "^0.20.0" }); + + const merged = applyDependencyOverrides(pubspec, plan.overrides); + assert.match(merged.yaml, /version: \{version: \^0\.20\.0\}/); +}); + +test("rule 2: a quoted 'version' key rewrites like a bare one", async () => { + const pubspec = `name: my_app +dependencies: + flutter: + sdk: flutter + intl: {'version': '0.19.0'} +`; + const plan = await planDependencyChanges(pubspec, { intl: "0.20.0" }); + + assert.deepEqual(plan.overrides, { intl: "^0.20.0" }); + + const merged = applyDependencyOverrides(pubspec, plan.overrides); + assert.match(merged.yaml, /intl: \{'version': \^0\.20\.0\}/); +}); + +test("rule 2: a multiline {version:} mapping is raised in place", async () => { + // The name line must anchor the entry: recording the flow map's closing + // line as lineIndex would leave rewriteVersionMember scanning from `}` and + // never finding the member. + const pubspec = `name: my_app +dependencies: + flutter: + sdk: flutter + intl: { + version: '>=0.19.0 <0.20.0' + } +`; + const plan = await planDependencyChanges(pubspec, { intl: "0.20.0" }); + + assert.deepEqual(plan.overrides, { intl: "^0.20.0" }); + + const merged = applyDependencyOverrides(pubspec, plan.overrides); + assert.match(merged.yaml, /intl: \{\n version: \^0\.20\.0\n \}/); +}); + +test("rule 2: a {version: x} pin satisfying the floor is kept", async () => { + const pubspec = `name: my_app +dependencies: + flutter: + sdk: flutter + intl: {version: ^0.19.0} +`; + const plan = await planDependencyChanges(pubspec, { intl: "0.19.0" }); + + assert.deepEqual(plan.overrides, {}); + assert.deepEqual(plan.kept, [{ name: "intl", constraint: "^0.19.0" }]); +}); + +test("rule 3: an SDK package missing from the pubspec is added as sdk: flutter", async () => { + // flutter_web_plugins is not on pub.dev, so a hosted constraint names a + // source pub cannot resolve. The SDK supplies it, so the merged pubspec + // gets the same `sdk: flutter` entry the project would have declared. + let queried = null; + const plan = await planDependencyChanges( + PROJECT_PUBSPEC, + { flutter_web_plugins: "", record: "" }, + { + resolveVersions: async (names) => { + queried = names; + return stubResolver({ record: "^6.2.1" })(names); + }, + }, + ); + + assert.deepEqual(plan.additions.flutter_web_plugins, { sdk: "flutter" }); + assert.deepEqual(plan.additions.record, "^6.2.1"); + assert.deepEqual(queried, ["record"]); + assert.deepEqual(plan.warnings, []); + + const merged = mergeDependenciesIntoYaml(PROJECT_PUBSPEC, plan.additions); + assert.match(merged.yaml, / flutter_web_plugins:\n sdk: flutter/); + assert.deepEqual(merged.added.sort(), ["flutter_web_plugins", "record"]); +}); + test("rule 3: passes the project's SDK floors to the registry lookup", async () => { let seen = null; await planDependencyChanges( diff --git a/src/pubspecSync.js b/src/pubspecSync.js index 52a69d3..15e5e51 100644 --- a/src/pubspecSync.js +++ b/src/pubspecSync.js @@ -127,6 +127,11 @@ const SOURCE_KEYS = new Set(["sdk", "git", "path", "hosted"]); * it goes stale the moment the SDK ships a package the list has not heard of, * and every project declaring that package then reads it as unreproducible. * + * YAML mapping order is not significant, so `version:` may precede `hosted:`. + * Every own-key is read and a source key (anything other than `version:`) + * wins over a bare `version:`; a constraint only stands on its own when no + * source accompanies it. + * * @param {string[]} lines - pubspec.yaml split into lines * @param {number} entryIndex - Index of the dependency entry's own line * @param {number} endIndex - Exclusive end of the enclosing block @@ -137,13 +142,21 @@ const SOURCE_KEYS = new Set(["sdk", "git", "path", "hosted"]); * when one appears */ function readSourceDirective(lines, entryIndex, endIndex, parentIndent) { + let ownIndent = null; let version = null; for (let i = entryIndex + 1; i < endIndex; i += 1) { const line = lines[i]; if (isBlankOrComment(line)) continue; + const indent = indentOf(line); // Shallower or equal indent means the entry's mapping has ended and this is // a sibling dependency, so there is nothing of this entry's own left to read. - if (indentOf(line) <= parentIndent) break; + if (indent <= parentIndent) break; + // The first mapping line fixes the own-key indent; anything deeper belongs + // to one of the own-keys (`git:` -> `url:`) and is not a source itself, so a + // nested `hosted:` inside an unrelated own-key cannot masquerade as the + // entry's source. + if (ownIndent === null) ownIndent = indent; + if (indent !== ownIndent) continue; const trimmed = line.trim(); const key = parseDependencyName(trimmed); if (!key) continue; @@ -156,14 +169,148 @@ function readSourceDirective(lines, entryIndex, endIndex, parentIndent) { return { key: null, value: null, version }; } +/** + * Reads the source key of a dependency written as an inline flow mapping. + * + * YAML allows the same mapping inline that readSourceDirective reads in block + * form: `name: {sdk: flutter}` is the same declaration as the block form, and + * `name: {version: ^1.0.0, hosted: {name: x, url: y}}` puts version beside its + * source exactly as the block form does. The same precedence applies: a source + * key wins over `version:`. + * + * Without this an inline mapping looks scalar - its value is nonempty - and + * gets forwarded as a version constraint, which the runner then rejects for + * containing braces. A map whose members cannot be read yields key null, so + * the entry is classified unrepresentable rather than sent downstream as + * something it is not. + * + * @param {string} value - The text after `name:` on the dependency's own line + * @returns {{key: string|null, value: string|null, version: string|null}|null} + * The source own-key and inline value — null when the mapping holds no + * sdk/git/path/hosted key — plus the `version:` member's value when one + * appears; key null for an unreadable mapping, or null when the value is + * not a flow mapping at all + */ +function parseFlowSourceDirective(value) { + const text = String(value || "").trim(); + if (!text.startsWith("{")) return null; + + const end = findFlowMappingEnd(text); + if (end === -1) return { key: null, value: null, version: null }; + + // Split the members on top-level commas only - a comma inside a nested map + // or a quote belongs to the member, not the map. + const inner = text.slice(1, end); + const segments = []; + let quote = null; + let depth = 0; + let start = 0; + for (let i = 0; i < inner.length; i += 1) { + const char = inner[i]; + if (quote) { + if (char === quote) quote = null; + continue; + } + if (char === "'" || char === '"') { + quote = char; + continue; + } + if (char === "{" || char === "[") depth += 1; + else if (char === "}" || char === "]") depth -= 1; + else if (char === "," && depth === 0) { + segments.push(inner.slice(start, i)); + start = i + 1; + } + } + segments.push(inner.slice(start)); + + let version = null; + for (const segment of segments) { + const trimmed = segment.trim(); + if (!trimmed) continue; + const key = parseDependencyName(trimmed); + if (!key) return { key: null, value: null, version: null }; + const { value: memberValue } = splitValueAndComment( + trimmed.slice(trimmed.indexOf(":") + 1), + ); + if (SOURCE_KEYS.has(key)) return { key, value: memberValue, version }; + if (key === "version" && version === null) version = memberValue; + } + return { key: null, value: null, version }; +} + +/** + * Finds the `}` closing the `{` at the start of the text, skipping nested + * mappings and quoted text. + * + * @param {string} text - Text starting with `{` + * @returns {number} Index of the closing brace, or -1 when unclosed + */ +function findFlowMappingEnd(text) { + let quote = null; + let depth = 0; + for (let i = 0; i < text.length; i += 1) { + const char = text[i]; + if (quote) { + if (char === quote) quote = null; + continue; + } + if (char === "'" || char === '"') { + quote = char; + continue; + } + if (char === "{") depth += 1; + else if (char === "}") { + depth -= 1; + if (depth === 0) return i; + if (depth < 0) return -1; + } + } + return -1; +} + +/** + * Reassembles a flow mapping that wraps members onto following lines. + * + * YAML allows the same `{...}` members on subsequent lines - `name: {`, then + * `sdk: flutter`, then `}` - and only the dependency's own line reaches + * parseFlowSourceDirective, so a lone `{` reads as an unclosed, hence + * unreadable, mapping and classifies the entry unrepresentable. Lines are + * pulled in only while the map is still open - a map that closes but is + * unreadable (`{sdk flutter}`) gets no more lines, so the dependencies after + * it are still read as themselves - and a map that never closes stays + * unreadable, which is the right answer for it anyway. + * + * @param {string[]} lines - All lines of the pubspec + * @param {number} startIndex - Index of the dependency's own line + * @param {number} endIndex - Index of the line that ends the block + * @param {string} value - The text after `name:` on the dependency's own line + * @returns {{text: string, lastIndex: number}} The joined flow text and the + * last line index consumed + */ +function collectFlowMappingText(lines, startIndex, endIndex, value) { + let text = value; + let i = startIndex; + while ( + text.trimStart().startsWith("{") && + findFlowMappingEnd(text) === -1 && + i + 1 < endIndex + ) { + i += 1; + text += "\n" + lines[i]; + } + return { text, lastIndex: i }; +} + /** * Reads every package declared under `dependencies:` with its constraint. * * A dependency written in block form (`sdk:`, `git:`, `path:`, a nested - * `hosted:`, or a `version:` on its own line) has no scalar constraint and - * must never be rewritten as one, so it is reported with `isScalar: false`. - * An entry whose own keys are only `version:` is a normal pub.dev dependency: - * `sourceKey` is null and the constraint travels in `version`. + * `hosted:`, or a `version:` on its own line) or as an inline flow mapping + * (`{sdk: flutter}`) has no scalar constraint and must never be rewritten as + * one, so it is reported with `isScalar: false`. An entry whose own keys are + * only `version:` is a normal pub.dev dependency: `sourceKey` is null and the + * constraint travels in `version`. * * @param {string} yamlContent - Raw pubspec.yaml content * @returns {Map} @@ -188,18 +335,26 @@ export function parseExistingDependencies(yamlContent) { const { value, comment } = splitValueAndComment( trimmed.slice(trimmed.indexOf(":") + 1), ); - const isScalar = value !== ""; + // An inline `{sdk: flutter}`-style mapping is not a constraint, so it is + // read for its own source keys like a block entry is. Its members may + // wrap onto following lines, which collectFlowMappingText reassembles. + const nameIndex = i; + const flow = collectFlowMappingText(lines, i, block.endIndex, value); + const flowSource = parseFlowSourceDirective(flow.text); + i = flow.lastIndex; + const isScalar = value !== "" && flowSource === null; // A block-form entry carries its source on the next line down. A scalar one // has nothing deeper, and looking anyway would walk into whichever // dependency follows. const directive = isScalar ? null - : readSourceDirective(lines, i, block.endIndex, block.childIndent.length); + : (flowSource ?? + readSourceDirective(lines, nameIndex, block.endIndex, block.childIndent.length)); declared.set(name, { constraint: value, comment, - lineIndex: i, + lineIndex: nameIndex, isScalar, sourceKey: directive ? directive.key : null, sourceValue: directive ? directive.value : null, @@ -247,18 +402,23 @@ export function parseDependencyBlock(yamlContent, blockName) { const { value, comment } = splitValueAndComment( trimmed.slice(trimmed.indexOf(":") + 1), ); - const isScalar = value !== ""; + const nameIndex = i; + const flow = collectFlowMappingText(lines, i, block.endIndex, value); + const flowSource = parseFlowSourceDirective(flow.text); + i = flow.lastIndex; + const isScalar = value !== "" && flowSource === null; // A block-form entry carries its source on the next line down. A scalar one // has nothing deeper, and looking anyway would walk into whichever // dependency follows. const directive = isScalar ? null - : readSourceDirective(lines, i, block.endIndex, block.childIndent.length); + : (flowSource ?? + readSourceDirective(lines, nameIndex, block.endIndex, block.childIndent.length)); declared.set(name, { constraint: value, comment, - lineIndex: i, + lineIndex: nameIndex, isScalar, sourceKey: directive ? directive.key : null, sourceValue: directive ? directive.value : null, @@ -309,9 +469,77 @@ export function formatConstraint(constraint) { return `'${constraint.replace(/'/g, "''")}'`; } -function formatDependencyLine(indent, name, version) { +// A `version:` member sits inside a `{...}` map on the name line or on a +// deeper child line in block form; only its value is rewritten so the entry +// keeps its declared shape. The value is read as a complete YAML scalar - +// a quoted range like `'>=0.19.0 <0.20.0'` must go whole, or its suffix would +// be left behind - and a trailing `,`, `}`, or comment stays untouched. +// Returns false when no member was found, so the caller never reports an +// override it did not write. +function rewriteVersionMember(lines, entry, constraint) { + const parentIndent = indentOf(lines[entry.lineIndex]); + for (let j = entry.lineIndex; j < lines.length; j += 1) { + const line = lines[j]; + if (j !== entry.lineIndex && indentOf(line) <= parentIndent) break; + // YAML permits quoted keys - `{'version': 0.19.0}` declares the same + // member as `{version: 0.19.0}`. + const isMember = + j === entry.lineIndex + ? /\{[^}]*(?:'version'|"version"|\bversion)\s*:/.test(line) + : /^\s*(?:'version'|"version"|version)\s*:/.test(line); + if (!isMember) continue; + // On the name line the member sits inside the `{...}` map - searching + // from `{` stops a package literally named `version` from matching its + // own key (`version: {version: x}` must rewrite the member, not the key). + const searchStart = j === entry.lineIndex ? line.indexOf("{") : 0; + const keyMatch = /(?:'version'|"version"|\bversion)\s*:\s*/.exec( + line.slice(searchStart), + ); + if (!keyMatch) continue; + const valueStart = searchStart + keyMatch.index + keyMatch[0].length; + let valueEnd = valueStart; + const first = line[valueStart]; + if (first === "'" || first === '"') { + valueEnd += 1; + while (valueEnd < line.length) { + if (line[valueEnd] === first) { + // YAML escapes a single quote by doubling it; a double-quoted + // scalar uses `\.` pairs. + if (first === "'" && line[valueEnd + 1] === "'") { + valueEnd += 2; + continue; + } + valueEnd += 1; + break; + } + if (first === '"' && line[valueEnd] === "\\") valueEnd += 1; + valueEnd += 1; + } + } else { + // Plain scalar: ends at a flow-map delimiter or a ` #` comment start. + while (valueEnd < line.length && line[valueEnd] !== "," && line[valueEnd] !== "}") { + if (line[valueEnd] === "#" && /\s/.test(line[valueEnd - 1] || " ")) break; + valueEnd += 1; + } + while (valueEnd > valueStart && /\s/.test(line[valueEnd - 1])) { + valueEnd -= 1; + } + } + lines[j] = + line.slice(0, valueStart) + formatConstraint(constraint) + line.slice(valueEnd); + return true; + } + return false; +} + +function formatDependencyLines(indent, name, version) { + // An SDK-supplied package takes a block entry - `name:` then its own + // `sdk:` key - not a version constraint. + if (version && typeof version === "object" && version.sdk) { + return [`${indent}${name}:`, `${indent} sdk: ${version.sdk}`]; + } const constraint = String(version || "").trim(); - return `${indent}${name}: ${constraint ? formatConstraint(constraint) : ">=0.0.0"}`; + return [`${indent}${name}: ${constraint ? formatConstraint(constraint) : ">=0.0.0"}`]; } /** @@ -323,7 +551,8 @@ function formatDependencyLine(indent, name, version) { * (or FlutterFlow) may have pinned it deliberately. * * @param {string} yamlContent - The project's current pubspec.yaml - * @param {Object} newDependencies - name -> version constraint + * @param {Object} newDependencies - name -> + * version constraint, or `{sdk}` for a package the Flutter SDK supplies * @returns {{yaml: string, added: string[], alreadyPresent: string[]}} */ export function mergeDependenciesIntoYaml(yamlContent, newDependencies = {}) { @@ -357,8 +586,8 @@ export function mergeDependenciesIntoYaml(yamlContent, newDependencies = {}) { const block = findDependenciesBlock(lines); if (block) { - const insertions = added.map(([name, version]) => - formatDependencyLine(block.childIndent, name, version), + const insertions = added.flatMap(([name, version]) => + formatDependencyLines(block.childIndent, name, version), ); lines.splice(block.endIndex, 0, ...insertions); } else { @@ -366,7 +595,7 @@ export function mergeDependenciesIntoYaml(yamlContent, newDependencies = {}) { if (lines.length > 0 && lines[lines.length - 1].trim() !== "") lines.push(""); lines.push("dependencies:"); added.forEach(([name, version]) => { - lines.push(formatDependencyLine(" ", name, version)); + lines.push(...formatDependencyLines(" ", name, version)); }); } @@ -404,10 +633,32 @@ export function applyDependencyOverrides(yamlContent, overrides = {}) { for (const [name, constraint] of entries) { const existing = declared.get(name); - if (!existing || !existing.isScalar || !String(constraint || "").trim()) { + // `name: {version: 0.19.0}` (or a `version:` own-key in block form) is a + // hosted pin in mapping shape: not isScalar, but raiseable - and only its + // `version:` member is rewritten, so the entry keeps its declared form. + const versionPinned = + existing && + !existing.isScalar && + existing.sourceKey === null && + existing.version !== null; + if ( + !existing || + (!existing.isScalar && !versionPinned) || + !String(constraint || "").trim() + ) { skipped.push(name); continue; } + if (versionPinned) { + if (rewriteVersionMember(lines, existing, String(constraint).trim())) { + overridden.push({ name, from: existing.version, to: constraint }); + } else { + // No member rewrite means the old pin stays - reporting it applied + // would let the deploy claim a raise the YAML never got. + skipped.push(name); + } + continue; + } const indent = " ".repeat(indentOf(lines[existing.lineIndex])); lines[existing.lineIndex] = `${indent}${name}: ${formatConstraint(String(constraint).trim())}${existing.comment}`; diff --git a/src/pubspecSync.test.js b/src/pubspecSync.test.js index a9b0e5b..f469930 100644 --- a/src/pubspecSync.test.js +++ b/src/pubspecSync.test.js @@ -268,6 +268,27 @@ test("a version written before an unrecognized key does not invent a source", () assert.equal(declared.get("odd_thing").version, "^5.0.0"); }); +test("a hosted source is read even when version: is written before it", () => { + // YAML mapping order is not significant, so this is the same dependency as + // hosted-then-version. Reading only the first own-key would classify it as a + // plain constraint and the verification manifest would resolve it from + // pub.dev instead of the project's own host. + const pubspec = `dependencies: + hosted_thing: + version: ^1.0.0 + hosted: + name: hosted_thing + url: https://example.invalid + plain_thing: + version: ^2.0.0 +`; + const declared = parseExistingDependencies(pubspec); + + assert.equal(declared.get("hosted_thing").sourceKey, "hosted"); + assert.equal(declared.get("plain_thing").sourceKey, null); + assert.equal(declared.get("plain_thing").version, "^2.0.0"); +}); + test("a git source keeps only its first key, whatever the nested shape", () => { const pubspec = `dependencies: private_thing: @@ -286,6 +307,62 @@ test("a git source keeps only its first key, whatever the nested shape", () => { assert.equal(declared.get("hosted_thing").sourceKey, "hosted"); }); +test("an inline flow mapping is read as a source, not a constraint", () => { + // YAML permits the same mapping inline: `name: {sdk: flutter}` declares the + // same thing as the block form. Reading it as a scalar would forward braces + // as a version constraint, which the runner rejects. + const pubspec = `dependencies: + flutter: + sdk: flutter + flutter_web_plugins: {sdk: flutter} + private_thing: {git: {url: https://example.invalid/private.git}} + pinned_thing: {version: ^1.2.0} + hosted_thing: {version: ^1.0.0, hosted: {name: hosted_thing, url: https://example.invalid}} +`; + const declared = parseExistingDependencies(pubspec); + + assert.equal(declared.get("flutter_web_plugins").sourceKey, "sdk"); + assert.equal(declared.get("flutter_web_plugins").isScalar, false); + assert.equal(declared.get("private_thing").sourceKey, "git"); + assert.equal(declared.get("pinned_thing").sourceKey, null); + assert.equal(declared.get("pinned_thing").version, "^1.2.0"); + // Mapping order is not significant, so a source key wins over a version + // written before it. + assert.equal(declared.get("hosted_thing").sourceKey, "hosted"); +}); + +test("a flow mapping that cannot be read is unrepresentable, not a constraint", () => { + const pubspec = `dependencies: + broken_thing: {sdk: flutter +`; + const declared = parseExistingDependencies(pubspec); + + assert.equal(declared.get("broken_thing").isScalar, false); + assert.equal(declared.get("broken_thing").sourceKey, null); +}); + +test("a flow mapping spanning lines is still read as a source", () => { + // YAML lets the same `{...}` members wrap onto following lines. Only the + // dependency's own line used to reach the reader, so the opening `{` alone + // looked unclosed and the entry classified unrepresentable. + const pubspec = `dependencies: + flutter: + sdk: flutter + flutter_web_plugins: { + sdk: flutter + } + intl: ^0.20.3 +`; + const declared = parseExistingDependencies(pubspec); + + assert.equal(declared.get("flutter_web_plugins").sourceKey, "sdk"); + assert.equal(declared.get("flutter_web_plugins").isScalar, false); + // Lines the wrapped map consumed must not reappear as dependencies. + assert.equal(declared.get("sdk"), undefined); + assert.equal(declared.get("intl").constraint, "^0.20.3"); + assert.equal(declared.get("intl").isScalar, true); +}); + test("reads a source from dependency_overrides too", () => { const overrides = parseDependencyBlock( `dependency_overrides: