From d1dc19cda9ac6fe2fea3f583ae0ff98633938343 Mon Sep 17 00:00:00 2001 From: Stuart Date: Mon, 21 Sep 2026 23:56:13 +1000 Subject: [PATCH 01/13] fix: classify SDK dependencies by their pubspec source, not a name list STU-368. Which packages the Flutter SDK supplies was decided by a hand-maintained name list kept in three places, and flutter_web_plugins was in none of them. Every project declaring it - which is every web-enabled project with a plugin - read it as a dependency that could not be reproduced, and the deploy was refused for a package most of its classes never imported. The project's own pubspec already says where each package comes from; the parser read those lines and threw them away. It now returns them as sourceKey/sourceValue, so the classification is exact and cannot fall behind the SDK: sdk: -> the Flutter SDK, reproduced from the name a nested version: -> a constraint written on its own line git: / path: / nested hosted: -> not expressible in the manifest SDK_DEPENDENCIES is gone. The runner's allowedSdkPackages is gone too - it independently refused the same deploy with 'Unsupported SDK package'. That allowlist was also the only validation of an sdkPackages entry, so the package name pattern now does that job; without the swap a caller-supplied name would reach the generated pubspec unchecked. The runner still writes 'sdk: flutter' itself, so that value never comes from a caller. Refusal is now scoped per class, to that class's own imports, so one git: entry no longer leaves an entire deploy uncompiled. The accept/warn split already existed and is unchanged: a real analyzer error refuses with 422, and a class that could not be compiled is pushed with its warning logged before the provisioning request. Corrects DEPLOYMENT.md, which still described the scaffolding-closure compilation that reverting a1238f0 removed, and still claimed that nothing unverified is deployed. Verified: 274/274 tests, deploy guard 9/9, proxies 30/30, build clean, dart analyze on the runner reports no issues. --- DEPLOYMENT.md | 46 ++++-- cloud-run/ffai-runner/bin/server.dart | 29 ++-- .../{index-BAqMCFqg.js => index-D4d_RpDK.js} | 156 +++++++++--------- dist/index.html | 2 +- src/customCodeVerification.js | 75 ++++++--- src/customCodeVerification.test.js | 119 ++++++++++++- src/pubspecSync.js | 68 +++++++- src/pubspecSync.test.js | 70 ++++++++ 8 files changed, 426 insertions(+), 139 deletions(-) rename dist/assets/{index-BAqMCFqg.js => index-D4d_RpDK.js} (56%) diff --git a/DEPLOYMENT.md b/DEPLOYMENT.md index e66f583..44943e4 100644 --- a/DEPLOYMENT.md +++ b/DEPLOYMENT.md @@ -79,34 +79,54 @@ in `.dart` untouched so a re-deploy is a no-op and an editor rename survives. Before writing anything to the project the runner compiles the generated classes in a throwaway Flutter package built from the project's own dependency -versions and refuses the deploy (HTTP 422) if the analyzer reports an error. +versions, and refuses the deploy (HTTP 422) if the analyzer reports an error. The FlutterFlow DSL only checks that code is formattable, which accepts a call to a named argument the package never declared. This needs the Flutter SDK in the image, so the runner takes longer to build and to cold-start, and the deploy script raises Cloud Run's request timeout to 900s. -A class that imports FlutterFlow scaffolding (`/backend/schema/structs/index.dart`) -is compiled too: the deploy gathers the transitive closure of each class's -project-relative imports from the export and ships it alongside, bounded by -file and byte caps. The class is written to `lib/custom_code/.dart` - -where FlutterFlow files it, so a relative import resolves from the right -directory - and the project's generated Dart under `lib/`, which is what the -leading slash resolves against. Analysis is scoped to the deployed class files -with `--no-fatal-warnings`, so an error inside the project's own scaffolding, -or a warning-only class, cannot refuse code that compiles. +A class is compiled when every package it imports resolves the same way the +project resolves it. Two cases are left out of the compile set, and each is +reported rather than silently dropped: + +* It imports something FlutterFlow only generates once the app is built - + `/backend/schema/structs/index.dart`, `../flutter_flow/lat_lng.dart`. Those + files do not exist until after the deploy. +* It imports a package the project declares from a source this manifest cannot + express: a `git:` or `path:` source, or a nested `hosted:` block. The scratch + 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. + +**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. The manifest is sent as package names and version constraints, never as pubspec.yaml text, and the runner builds the document itself - it runs `pub get` against it on a publicly reachable route, so a caller must not be able to name a git or path source. `dependency_overrides` are carried over, because a scratch package resolving different versions than the project would -approve code the project rejects. +approve code the project rejects. The runner validates each name against a +package-name pattern rather than against a list of SDK packages, and writes +`sdk: flutter` itself, so that value never comes from a caller. A client still sending the older `pubspec` format is recognized, never executed, and its deploy proceeds with the check reported as unavailable. -**Nothing unverified is deployed.** The web app refuses the deploy on any class -it cannot compile, naming each one and why, before the runner is called. +**What could not be verified still deploys, and is reported.** A class with a +real analyzer error refuses the deploy - HTTP 422, naming the error. A class the +deploy could not compile, for either reason above, does not: it is pushed, and +the warning naming it is logged *before* the provisioning request, so it +describes the mutation before it happens rather than after. The runner streams its progress. When the request body sets `"stream": true` the response is NDJSON — one `{"event":"phase"|"log"|"result"}` object per diff --git a/cloud-run/ffai-runner/bin/server.dart b/cloud-run/ffai-runner/bin/server.dart index 2b5a8e4..141b3bc 100644 --- a/cloud-run/ffai-runner/bin/server.dart +++ b/cloud-run/ffai-runner/bin/server.dart @@ -19,15 +19,13 @@ final _packageNamePattern = RegExp(r'^[a-z_][a-z0-9_]*$'); // unrepresentable rather than merely discouraged. final _constraintPattern = RegExp(r'^[A-Za-z0-9^~<>=*+._ -]+$'); -// The packages the Flutter SDK supplies, i.e. the only valid `sdk: flutter` -// entries besides `flutter` itself. -const allowedSdkPackages = { - 'flutter', - 'flutter_test', - 'flutter_driver', - 'flutter_localizations', - 'integration_test', -}; +// Which packages the Flutter SDK supplies is not decided here. A caller names +// the packages its project declares as `sdk: flutter`, and this runner emits +// them as `name: {sdk: flutter}` - a value it writes itself, never one a caller +// sent. There was an allowlist of SDK package names here, and it refused good +// deploys: the client classified a package correctly by its pubspec source, and +// the runner rejected it for not appearing on a list that had gone stale. +// `_packageNamePattern` is what actually keeps a key from carrying YAML. Future main() async { final port = int.tryParse(Platform.environment['PORT'] ?? '') ?? 8080; @@ -538,8 +536,13 @@ Map _normalizeDependencyMap(Object? value, String field) { return result; } -/// Reads the SDK-supplied package names. Restricted to the packages the Flutter -/// SDK actually provides, so a caller cannot request an arbitrary `sdk:` value. +/// Reads the SDK-supplied package names a caller's project declares. +/// +/// Validated as package names rather than against a list of the packages the +/// Flutter SDK happens to ship: a name the SDK does not provide fails +/// `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) { if (value == null) return const []; if (value is! List) { @@ -549,8 +552,8 @@ List _normalizeSdkPackages(Object? value) { final result = []; for (final raw in value) { final name = '$raw'; - if (!allowedSdkPackages.contains(name)) { - throw FormatException('Unsupported SDK package: $name.'); + if (!_packageNamePattern.hasMatch(name)) { + throw FormatException('Invalid SDK package name: $name.'); } if (!result.contains(name)) result.add(name); } diff --git a/dist/assets/index-BAqMCFqg.js b/dist/assets/index-D4d_RpDK.js similarity index 56% rename from dist/assets/index-BAqMCFqg.js rename to dist/assets/index-D4d_RpDK.js index 339dc59..efa7947 100644 --- a/dist/assets/index-BAqMCFqg.js +++ b/dist/assets/index-D4d_RpDK.js @@ -1,8 +1,8 @@ -(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const i of document.querySelectorAll('link[rel="modulepreload"]'))r(i);new MutationObserver(i=>{for(const n of i)if(n.type==="childList")for(const o of n.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&r(o)}).observe(document,{childList:!0,subtree:!0});function s(i){const n={};return i.integrity&&(n.integrity=i.integrity),i.referrerPolicy&&(n.referrerPolicy=i.referrerPolicy),i.crossOrigin==="use-credentials"?n.credentials="include":i.crossOrigin==="anonymous"?n.credentials="omit":n.credentials="same-origin",n}function r(i){if(i.ep)return;i.ep=!0;const n=s(i);fetch(i.href,n)}})();var v=typeof window<"u"?window:void 0,we=typeof globalThis<"u"?globalThis:v,ke=we?.navigator,C=we?.document,re=we?.location,To=we?.fetch,An=we!=null&&we.XMLHttpRequest&&"withCredentials"in new we.XMLHttpRequest?we.XMLHttpRequest:void 0,Ma=we?.AbortController,lh=we?.CompressionStream,Pe=ke?.userAgent;function kc(){return!(!v||v.navigator.onLine===!1)}var Cs=typeof globalThis<"u"?globalThis:v;Cs&&typeof self>"u"&&(Cs.self=Cs),Cs&&typeof File>"u"&&(Cs.File=function(){});var $=v??{},Y={DEBUG:!1,LIB_VERSION:"0.5.0",LIB_NAME:"browser-common"};function La(t,e,s,r,i,n,o){try{var a=t[n](o),l=a.value}catch(u){return void s(u)}a.done?e(l):Promise.resolve(l).then(r,i)}function X(t){return function(){var e=this,s=arguments;return new Promise((function(r,i){var n=t.apply(e,s);function o(l){La(n,r,i,o,a,"next",l)}function a(l){La(n,r,i,o,a,"throw",l)}o(void 0)}))}}function w(){return w=Object.assign?Object.assign.bind():function(t){for(var e=1;arguments.length>e;e++){var s=arguments[e];for(var r in s)({}).hasOwnProperty.call(s,r)&&(t[r]=s[r])}return t},w.apply(null,arguments)}function Ic(t,e){if(t==null)return{};var s={};for(var r in t)if({}.hasOwnProperty.call(t,r)){if(e.indexOf(r)!==-1)continue;s[r]=t[r]}return s}var Oa=t=>{if(typeof t!="string")return t;try{return JSON.parse(t)}catch{return t}};function Da(t){return typeof t=="string"||t}function Ba(t){return typeof t=="string"?t:void 0}var Fs,ch=["$feature_flag","$feature_flag_response","$feature_flag_has_experiment","$feature_flag_id","$feature_flag_version","$feature_flag_reason","$feature_flag_request_id","$feature_flag_evaluated_at","$feature_flag_error","locally_evaluated","$groups","$process_person_profile","$geoip_disable","$current_url","$pathname","$referring_domain","utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid","gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","irclid","_kx","$session_id","$window_id","$lib","$lib_version","$device_id","$is_server"],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})({}),ja=(function(t){return t.GZipJS="gzip-js",t.Base64="base64",t})({}),uh=["$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"],dh=["token"],Cc="NativeGzipValidationError",$n=t=>t.length>=2&&t[0]===31&&t[1]===139,Ua=(t,e)=>t===ja.GZipJS||e===ja.GZipJS||e==="gzip",Ha=t=>!(!t||typeof t!="object")&&("name"in t?String(t.name):"")==="NotReadableError",yr=t=>{var e=new Error("Native gzip produced invalid output: "+t);throw e.name=Cc,e},hh=(function(){var t=X((function*(e,s){18>e.size&&yr("too-short");var r=new Uint8Array(yield e.slice(0,10).arrayBuffer());$n(r)&&r[2]===8||yr("invalid-header");var i=new DataView(yield e.slice(e.size-8).arrayBuffer());i.getUint32(0,!0)!==(o=>{for(var a=(()=>{if(Fs)return Fs;Fs=[];for(var c=0;256>c;c++){for(var d=c,h=0;8>h;h++)d=1&d?3988292384^d>>>1:d>>>1;Fs[c]=d>>>0}return Fs})(),l=4294967295,u=0;o.length>u;u++)l=a[255&(l^o[u])]^l>>>8;return(4294967295^l)>>>0})(s)&&yr("invalid-crc");var n=s.length>>>0;i.getUint32(4,!0)!==n&&yr("invalid-size")}));return function(e,s){return t.apply(this,arguments)}})();function Rn(){return Rn=X((function*(t,e,s){e===void 0&&(e=!0);try{var r=new TextEncoder().encode(t),i=new globalThis.CompressionStream("gzip"),n=i.writable.getWriter(),o=n.write(r).then((()=>n.close())).catch((function(){var u=X((function*(c){try{yield n.abort(c)}catch{}throw c}));return function(c){return u.apply(this,arguments)}})()),a=new Response(i.readable).blob(),l=(yield Promise.all([a,o]))[0];return yield hh(l,r),l}catch(u){if(s!=null&&s.rethrow)throw u;return e&&console.error("Failed to gzip compress data",u),null}})),Rn.apply(this,arguments)}var ph=["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"],Wa=function(t,e){if(e===void 0&&(e=[]),!t)return!1;var s=t.toLowerCase();return ph.concat(e).some((r=>{var i=r.toLowerCase();return s.indexOf(i)!==-1}))};function M(t,e){return t.indexOf(e)!==-1}var Fi=function(t){return t.trim()},Tn=function(t){return t.replace(/^\$/,"")};function Fc(t){var e,s=[];return(e=JSON.stringify(t,(function(r,i){if(typeof i=="bigint")return i.toString();if(typeof i!="function"&&typeof i!="symbol"){if(i instanceof Error)return{name:i.name,message:i.message,stack:i.stack};if(i&&typeof i=="object"){for(;s.length>0&&s[s.length-1]!==this;)s.pop();if(s.includes(i))return"[Circular]";s.push(i)}return i}})))!==null&&e!==void 0?e:"null"}var Pc=Object.prototype,Ac=Pc.hasOwnProperty,Pi=Pc.toString,L=Array.isArray||function(t){return Pi.call(t)==="[object Array]"},Se=t=>typeof t=="function",te=t=>t===Object(t)&&!L(t),mt=t=>{if(te(t)){for(var e in t)if(Ac.call(t,e))return!1;return!0}return!1},x=t=>t===void 0,W=t=>Pi.call(t)=="[object String]",Nn=t=>W(t)&&t.trim().length===0,$e=t=>t===null,D=t=>x(t)||$e(t),he=t=>Pi.call(t)=="[object Number]"&&t==t,lt=t=>he(t)&&t>0,Ke=t=>Pi.call(t)==="[object Boolean]",fh=t=>t instanceof FormData,gh=t=>M(uh,t),mh=t=>M(dh,t);function $c(t){return t===null||typeof t!="object"}function qr(t,e){return{}.toString.call(t)==="[object "+e+"]"}function No(t){return typeof Event<"u"&&Rc(t,Event)}function Rc(t,e){try{return t instanceof e}catch{return!1}}var vh=[!0,"true",1,"1","yes"],Ji=t=>M(vh,t),_h=[!1,"false",0,"0","no"];function rt(t,e,s,r,i){return e>s&&(r.warn("min cannot be greater than max."),e=s),he(t)?t>s?(r.warn(" cannot be greater than max: "+s+". Using max value instead."),s):e>t?(r.warn(" cannot be less than min: "+e+". Using min value instead."),e):t:(r.warn(" must be a number. using max or fallback. max: "+s+", fallback: "+i),rt(i||s,e,s,r))}class yh{constructor(e){this.tt={},this.et=e.et,this.it=rt(e.bucketSize,0,100,e.rt),this.nt=rt(e.refillRate,0,this.it,e.rt),this.st=rt(e.refillInterval,0,864e5,e.rt)}ot(e,s){var r=Math.floor((s-e.lastAccess)/this.st);r>0&&(e.tokens=Math.min(e.tokens+r*this.nt,this.it),e.lastAccess=e.lastAccess+r*this.st)}consumeRateLimit(e){var s,r=Date.now(),i=String(e),n=this.tt[i];return n?this.ot(n,r):this.tt[i]=n={tokens:this.it,lastAccess:r},n.tokens===0||(n.tokens--,n.tokens===0&&((s=this.et)==null||s.call(this,e)),n.tokens===0)}stop(){this.tt={}}}var Oe="Mobile",Vr="iOS",vt="Android",fs="Tablet",Tc=vt+" "+fs,Nc="iPad",Mc="Apple",Lc=Mc+" Watch",qs="Safari",gs="BlackBerry",Oc="Samsung",Dc=Oc+"Browser",Bc=Oc+" Internet",Gt="Chrome",wh=Gt+" OS",jc=Gt+" "+Vr,Mo="Internet Explorer",Uc=Mo+" "+Oe,Lo="Opera",bh=Lo+" Mini",Oo="Edge",Hc="Microsoft "+Oo,ds="Firefox",Wc=ds+" "+Vr,er="Nintendo",tr="PlayStation",hs="Xbox",zc=vt+" "+Oe,qc=Oe+" "+qs,Ds="Windows",Mn=Ds+" Phone",za="Nokia",Ln="Ouya",Vc="Generic",Eh=Vc+" "+Oe.toLowerCase(),Gc=Vc+" "+fs.toLowerCase(),On="Konqueror",Kc="Oculus Browser",Gr="Vivaldi",Jc="Yandex",Kr="Whale",Dn="DuckDuckGo",Yc="Pale Moon",Jr="Waterfox",Vs="Brave",Zc="Google Search App",le="(\\d+(\\.\\d+)?)",Yi=new RegExp("Version/"+le),Sh=new RegExp(hs,"i"),xh=new RegExp(tr+" \\w+","i"),kh=new RegExp(er+" \\w+","i"),Do=new RegExp(gs+"|PlayBook|BB10","i"),Ih={"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"},Xc=function(t,e,s,r){e=e||"";var i=(function(n){return n!=null&&n.brave?Vs:null})(s);return i||(r!=null&&r.detectGoogleSearchApp&&M(t,"GSA/")?Zc:M(t," OPR/")&&M(t,"Mini")?bh:M(t," OPR/")?Lo:Do.test(t)?gs:M(t,"IE"+Oe)||M(t,"WPDesktop")?Uc:M(t,"OculusBrowser")?Kc:M(t,Dc)?Bc:M(t,Oo)||M(t,"Edg/")?Hc:M(t,Gr+"/")?Gr:M(t,"YaBrowser/")?Jc:M(t,Kr+"/")?Kr:M(t,Dn+"/")||M(t,"Ddg/")?Dn:M(t,"FBIOS")?"Facebook "+Oe:M(t,"UCWEB")||M(t,"UCBrowser")?"UC Browser":M(t,"CriOS")?jc:M(t,"CrMo")||M(t,Gt)?Gt:M(t,vt)&&M(t,qs)?zc:M(t,"FxiOS")?Wc:M(t.toLowerCase(),On.toLowerCase())?On:M(t,Vs+"/")?Vs:((n,o)=>o&&M(o,Mc)||(function(a){return M(a,qs)&&!M(a,Gt)&&!M(a,vt)})(n))(t,e)?M(t,Oe)?qc:qs:M(t,"PaleMoon/")?Yc:M(t,Jr+"/")?Jr:M(t,ds)?ds:M(t,"MSIE")||M(t,"Trident/")?Mo:M(t,"Gecko")?ds:"")},Ch={[Uc]:[new RegExp("rv:"+le)],[Hc]:[new RegExp(Oo+"?\\/"+le)],[Gt]:[new RegExp("("+Gt+"|CrMo)\\/"+le)],[jc]:[new RegExp("CriOS\\/"+le)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+le)],[qs]:[Yi],[qc]:[Yi],[Lo]:[new RegExp("(Opera|OPR)\\/"+le)],[ds]:[new RegExp(ds+"\\/"+le)],[Wc]:[new RegExp("FxiOS\\/"+le)],[On]:[new RegExp("Konqueror[:/]?"+le,"i")],[gs]:[new RegExp(gs+" "+le),Yi],[zc]:[new RegExp("android\\s"+le,"i")],[Bc]:[new RegExp(Dc+"\\/"+le)],[Kc]:[new RegExp("OculusBrowser\\/"+le)],[Gr]:[new RegExp(Gr+"\\/"+le)],[Jc]:[new RegExp("YaBrowser\\/"+le)],[Kr]:[new RegExp(Kr+"\\/"+le)],[Vs]:[new RegExp(Vs+"\\/"+le)],[Dn]:[new RegExp("(DuckDuckGo|Ddg)\\/"+le)],[Yc]:[new RegExp("PaleMoon\\/"+le)],[Jr]:[new RegExp(Jr+"\\/"+le)],[Zc]:[new RegExp("GSA\\/"+le)],[Mo]:[new RegExp("(rv:|MSIE )"+le)],Mozilla:[new RegExp("rv:"+le)]},Fh=function(t,e,s,r){var i=Xc(t,e,s,r),n=Ch[i];if(x(n))return null;for(var o=0;n.length>o;o++){var a=t.match(n[o]);if(a)return parseFloat(a[a.length-2])}return null},qa=[[new RegExp(hs+"; "+hs+" (.*?)[);]","i"),t=>[hs,t&&t[1]||""]],[new RegExp(er,"i"),[er,""]],[new RegExp(tr,"i"),[tr,""]],[Do,[gs,""]],[new RegExp(Ds,"i"),(t,e)=>{if(/Phone/.test(e)||/WPDesktop/.test(e))return[Mn,""];if(new RegExp(Oe).test(e)&&!/IEMobile\b/.test(e))return[Ds+" "+Oe,""];var s=/Windows NT ([0-9.]+)/i.exec(e);if(s&&s[1]){var r=Ih[s[1]]||"";return/arm/i.test(e)&&(r="RT"),[Ds,r]}return[Ds,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,t=>t&&t[3]?[Vr,[t[3],t[4],t[5]||"0"].join(".")]:[Vr,""]],[/(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i,t=>{var e="";return t&&t.length>=3&&(e=x(t[2])?t[3]:t[2]),["watchOS",e]}],[new RegExp("("+vt+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+vt+")","i"),t=>t&&t[2]?[vt,[t[2],t[3],t[4]||"0"].join(".")]:[vt,""]],[/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/,[wh,""]],[/Linux|debian/i,["Linux",""]]],Va=function(t){return kh.test(t)?er:xh.test(t)?tr:Sh.test(t)?hs:new RegExp(Ln,"i").test(t)?Ln:new RegExp("("+Mn+"|WPDesktop)","i").test(t)?Mn:/iPad/.test(t)?Nc:/iPod/.test(t)?"iPod Touch":/iPhone/.test(t)?"iPhone":/(watch)(?: ?os[,/]|\d,\d\/)[\d.]+/i.test(t)?Lc:Do.test(t)?gs:/(kobo)\s(ereader|touch)/i.test(t)?"Kobo":new RegExp(za,"i").test(t)?za:/(kf[a-z]{2}wi|aeo[c-r]{2})( bui|\))/i.test(t)||/(kf[a-z]+)( bui|\)).+silk\//i.test(t)?"Kindle Fire":/(Android|ZTE)/i.test(t)?new RegExp(Oe).test(t)&&!/(9138B|TB782B|Nexus [97]|pixel c|HUAWEISHT|BTV|noble nook|smart ultra 6)/i.test(t)||/pixel[\daxl ]{1,6}/i.test(t)&&!/pixel c/i.test(t)||/(huaweimed-al00|tah-|APA|SM-G92|i980|zte|U304AA)/i.test(t)||/lmy47v/i.test(t)&&!/QTAQZ3/i.test(t)?vt:Tc:new RegExp("(pda|"+Oe+")","i").test(t)?Eh:new RegExp(fs,"i").test(t)&&!new RegExp(fs+" pc","i").test(t)?Gc:""},Ph=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Ga(t,e){return typeof(s=t)=="string"&&Ph.test(s)?t:e();var s}function Ct(t){return t&&t.split("#")[0]}function Bo(t,e){var s=setTimeout(t,e);return s?.unref&&s?.unref(),s}function Ka(t,e,s){return Qc.apply(this,arguments)}function Qc(){return(Qc=X((function*(t,e,s){var r;try{return yield Promise.race([t,new Promise(((i,n)=>{r=Bo((()=>{try{s?.(),i()}catch(o){n(o)}}),e)}))])}finally{clearTimeout(r)}}))).apply(this,arguments)}var Ah=t=>t instanceof Error,eu={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}},$h=eu.info;function tu(t){if(Ke(t))return{boolValue:t};if(typeof t=="number")return Number.isFinite(t)?Number.isInteger(t)?{intValue:t}:{doubleValue:t}:{stringValue:String(t)};if(typeof t=="string")return{stringValue:t};if(L(t))return{arrayValue:{values:t.map((e=>tu(e)))}};try{return{stringValue:JSON.stringify(t)}}catch{return{stringValue:String(t)}}}function Yr(t){var e=[];for(var s in t){var r=t[s];$e(r)||x(r)||e.push({key:s,value:tu(r)})}return e}function Rh(t,e){var s=eu[t.level||"info"]||$h,r=s.text,i=s.number,n=String(Date.now())+"000000",o={};e.distinctId&&(o.posthogDistinctId=e.distinctId),e.sessionId&&(o.sessionId=e.sessionId),e.windowId&&(o["window.id"]=e.windowId),D(e.sessionStartTimestamp)||(o.sessionStartTimestamp=String(e.sessionStartTimestamp)),D(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=w({},o,t.attributes||{}),l={timeUnixNano:n,observedTimeUnixNano:n,severityNumber:i,severityText:r,body:{stringValue:t.body},attributes:Yr(a)};return t.trace_id&&(l.traceId=t.trace_id),t.span_id&&(l.spanId=t.span_id),x(t.trace_flags)||(l.flags=t.trace_flags),l}function su(t,e,s){return w({},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":s})}function ru(t,e,s,r){return{resourceLogs:[{resource:{attributes:Yr(e)},scopeLogs:[{scope:{name:s,version:r},logRecords:t}]}]}}let Th=class{constructor(t,e,s,r,i,n,o){var a;n===void 0&&(n=()=>Promise.resolve()),this._instance=t,this.Ne=e,this.rt=s,this.ut=r,this.ht=i,this.dt=n,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 s={record:Rh(e,this.ut())};this.ht((()=>this.At(s)))}}else this.rt.info("Log was rejected in beforeSend function")}}Pt(t){var e=this.Ne.beforeSend;if(!e)return t;var s=L(e)?e:[e],r=t;for(var i of s)try{var n=i(r);if(!n)return this.rt.info("Log was rejected in beforeSend function"),null;r=n}catch(o){return this.rt.error("Error in beforeSend function for log:",o),null}return r}Rt(){if(this.Tt===void 0)return!0;var t=Date.now(),e=t-this.bt;return this.Mt>e&&e>=0||(this.bt=t,this._t=0,this.wt=!1),this.Tt>this._t?(this._t++,!0):(this.wt||(this.rt.warn("captureLog dropping logs: exceeded "+this.Tt+" logs per "+this.Mt+"ms"),this.wt=!0),!1)}flush(){var t=this;return X((function*(){if(!t._instance.isDisabled)return t.ct||(t.ct=t.Ft().finally((()=>{t.ct=null}))),t.ct}))()}Ft(){var t=this;return X((function*(){var e;t.Et();var s=(e=t._instance.getPersistedProperty(ut.LogsQueue))!==null&&e!==void 0?e:[];if(s.length!==0)for(var r=s.length,i=0;s.length>0&&r>i;){var n,o;t.ft=0;var a=Math.min(s.length,t.Ct),l=s.slice(0,a),u=ru(l.map((d=>d.record)),t.Lt(),(n=t.vt)!==null&&n!==void 0?n: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),s=(o=t._instance.getPersistedProperty(ut.LogsQueue))!==null&&o!==void 0?o:[],i+=l.length,c.kind==="fatal"))throw c.error}}))()}Dt(t){var e=this;return X((function*(){var s,r=Math.max(0,t-e.ft),i=(s=e._instance.getPersistedProperty(ut.LogsQueue))!==null&&s!==void 0?s:[];e._instance.setPersistedProperty(ut.LogsQueue,i.slice(r)),yield e.dt()}))()}Lt(){return su(this.Ne,this._instance.getLibraryId(),this._instance.getLibraryVersion())}At(t){var e;if(!this._instance.optedOut){var s=(e=this._instance.getPersistedProperty(ut.LogsQueue))!==null&&e!==void 0?e:[];this.xt>s.length||(s.shift(),this.ft++,this.rt.info("Logs queue is full, dropping oldest record.")),s.push(t),this._instance.setPersistedProperty(ut.LogsQueue,s),this.kt>s.length?this.$t():this.It()}}$t(t){t===void 0&&(t=this.St),this.Nt||(this.Nt=Bo((()=>{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 X((function*(){e.Et();var s=e.flush().catch((()=>{}));t!==void 0?yield Ka(s,t):yield s}))()}flushWithTimeout(t){var e=this;return X((function*(){var s=e.flush();yield Ka(s,t,(()=>{s.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 Zi=[0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4];function Ja(t){return String(t)+"000000"}function Ya(t,e,s,r){var i="";return r&&(i=Object.keys(r).sort().map((n=>JSON.stringify(n)+":"+JSON.stringify(r[n]))).join(",")),t+"\0"+e+"\0"+(s??"")+"\0"+i}let Nh=class{constructor(t,e,s){this._instance=t,this.Ne=e,this.rt=s,this.Bt=new Map,this.ct=null,this.Ht=!1,this.Ut=new Map,this.zt=new Set,this.Wt=0}count(t,e,s){e===void 0&&(e=1),this.Vt({name:t,type:"count",value:e,unit:s?.unit,attributes:s?.attributes})}gauge(t,e,s){this.Vt({name:t,type:"gauge",value:e,unit:s?.unit,attributes:s?.attributes})}histogram(t,e,s){this.Vt({name:t,type:"histogram",value:e,unit:s?.unit,attributes:s?.attributes})}flush(){var t=this,e=this.ct,s=(function(){var i=X((function*(){e&&(yield e.catch((()=>{}))),yield t.Zt()}));return function(){return i.apply(this,arguments)}})(),r=s().finally((()=>{this.ct===r&&(this.ct=null)}));return this.ct=r,r}drainWindow(){if(this.Bt.size===0)return null;var t=this.Bt;return this.Bt=new Map,this.Ht=!1,this.Ut=new Map,this.zt=new Set,this.Gt(t)}reset(){this.Wt++,this.Et(),this.Bt=new Map,this.ct=null,this.Ht=!1,this.Ut=new Map,this.zt=new Set}Vt(t){if(!this._instance.isDisabled&&!this._instance.optedOut){var e=this.Pt(t);if(e!==null)if(e.name&&typeof e.name=="string")if(typeof e.value=="number"&&Number.isFinite(e.value))if(e.type==="count"&&0>e.value)this.rt.warn("Dropping count '"+e.name+"': counters are monotonic, value must be >= 0");else{var s,r;try{s=e.attributes?w({},e.attributes):void 0,r=Ya(e.type,e.name,e.unit,s)}catch(o){return void this.rt.warn("Dropping metric '"+e.name+"': attributes could not be serialized",o)}var i=this.Bt.get(r);if(!i){if(!this.Qt())return;i={name:e.name,type:e.type,unit:e.unit,attributes:s,windowStartMs:Date.now()},this.Bt.set(r,i)}var n=this.Ut.get(e.name);n===void 0?this.Ut.set(e.name,e.type):n===e.type||this.zt.has(e.name)||(this.zt.add(e.name),this.rt.warn("Metric name '"+e.name+"' is already used as a "+n+"; recording it as a "+e.type+" too will blend both series in charts. Use a distinct name.")),this.Kt(i,e.value),this.$t()}else this.rt.warn("Dropping metric '"+e.name+"': value must be a finite number");else this.rt.warn("Dropping metric with empty name")}}Qt(){return this.Ne.maxSeriesPerFlush>this.Bt.size||(this.Ht||(this.Ht=!0,this.rt.warn("Metric series cap reached ("+this.Ne.maxSeriesPerFlush+" per flush window); dropping new series until the next flush. Reduce attribute cardinality.")),!1)}Kt(t,e){var s;switch(t.type){case"count":t.total=((s=t.total)!==null&&s!==void 0?s: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(Zi.length+1).fill(0)});var r=t.hist;r.count+=1,r.sum+=e,r.min=Math.min(r.min,e),r.max=Math.max(r.max,e),r.bucketCounts[(function(i,n){for(var o=0;n.length>o;o++)if(n[o]>=i)return o;return n.length})(e,Zi)]+=1}}Pt(t){var e=this.Ne.beforeSend;if(!e)return t;var s=L(e)?e:[e],r=t;for(var i of s)try{var n=i(r);if(!n)return this.rt.info("Metric was rejected in beforeSend function"),null;r=n}catch(o){return this.rt.error("Error in beforeSend function for metric:",o),null}return r}$t(){this.Nt||(this.Nt=Bo((()=>{this.Nt=void 0,this.flush().catch((t=>{this.rt.error("Metrics flush failed:",t)}))}),this.Ne.flushIntervalMs))}Et(){this.Nt&&(clearTimeout(this.Nt),this.Nt=void 0)}Zt(){var t=this;return X((function*(){if(t.Bt.size!==0){var e=t.Bt;t.Bt=new Map,t.Ht=!1,t.Ut=new Map,t.zt=new Set;var s=t.Wt,r=yield t._instance.Jt(t.Gt(e));if(s===t.Wt)switch(r.kind){case"ok":return;case"retry-later":return t.Yt(e),void t.$t();case"too-large":return void t.rt.warn("Metrics batch exceeded the server size limit and was dropped");case"fatal":return void t.rt.error("Failed to send metrics batch:",r.error)}}}))()}Gt(t){return e=this.Xt(t),s=(function(n,o,a){return w({},n.resourceAttributes,{"service.name":n.serviceName||"unknown_service"},n.environment&&{"deployment.environment":n.environment},n.serviceVersion&&{"service.version":n.serviceVersion},{"telemetry.sdk.name":o,"telemetry.sdk.version":a})})(this.Ne,this._instance.getLibraryId(),this._instance.getLibraryVersion()),r=this._instance.getLibraryId(),i=this._instance.getLibraryVersion(),{resourceMetrics:[{resource:{attributes:Yr(s)},scopeMetrics:[{scope:{name:r,version:i},metrics:e}]}]};var e,s,r,i}Xt(t){var e=Ja(Date.now()),s=new Map;for(var r of t.values()){var i,n=Ya(r.type,r.name,r.unit,void 0),o=s.get(n);o||(o=w({name:r.name},r.unit&&{unit:r.unit}),r.type==="count"?o.sum={aggregationTemporality:1,isMonotonic:!0,dataPoints:[]}:r.type==="gauge"?o.gauge={dataPoints:[]}:o.histogram={aggregationTemporality:1,dataPoints:[]},s.set(n,o));var a=Yr((i=r.attributes)!==null&&i!==void 0?i:{}),l=Ja(r.windowStartMs);if(r.type==="count"){var u,c={attributes:a,startTimeUnixNano:l,timeUnixNano:e,asDouble:(u=r.total)!==null&&u!==void 0?u:0};o.sum.dataPoints.push(c)}else if(r.type==="gauge"){var d,h={attributes:a,timeUnixNano:e,asDouble:(d=r.last)!==null&&d!==void 0?d:0};o.gauge.dataPoints.push(h)}else r.hist&&o.histogram.dataPoints.push({attributes:a,startTimeUnixNano:l,timeUnixNano:e,count:r.hist.count,sum:r.hist.sum,min:r.hist.min,max:r.hist.max,bucketCounts:r.hist.bucketCounts,explicitBounds:Zi})}return Array.from(s.values())}Yt(t){var e,s;for(var r of t){var i=r[0],n=r[1],o=this.Bt.get(i);if(o)switch(o.windowStartMs=Math.min(o.windowStartMs,n.windowStartMs),o.type){case"count":o.total=((e=o.total)!==null&&e!==void 0?e:0)+((s=n.total)!==null&&s!==void 0?s:0);break;case"gauge":break;case"histogram":if(n.hist)if(o.hist){o.hist.count+=n.hist.count,o.hist.sum+=n.hist.sum,o.hist.min=Math.min(o.hist.min,n.hist.min),o.hist.max=Math.max(o.hist.max,n.hist.max);for(var a=0;o.hist.bucketCounts.length>a;a++)o.hist.bucketCounts[a]+=n.hist.bucketCounts[a]}else o.hist=n.hist}else this.Qt()&&this.Bt.set(i,n)}}};var wr,Za,Xi;function Mh(t){var e=globalThis._posthogChunkIds;if(e){var s=Object.keys(e);return Xi&&s.length===Za||(Za=s.length,Xi=s.reduce(((r,i)=>{wr||(wr={});var n=wr[i];if(n)r[n[0]]=n[1];else for(var o=t(i),a=o.length-1;a>=0;a--){var l=o[a],u=l?.filename,c=e[i];if(u&&c){r[u]=c,wr[i]=[u,c];break}}return r}),{})),Xi}}class Lh{constructor(e,s,r){r===void 0&&(r=[]),this.coercers=e,this.stackParser=s,this.modifiers=r}buildFromUnknown(e,s){s===void 0&&(s={});var r=s&&s.mechanism||{handled:!0,type:"generic"},i=this.buildCoercingContext(r,s,0).apply(e),n=this.buildParsingContext(s),o=this.parseStacktrace(i,n);return{$exception_list:this.convertToExceptionList(o,r),$exception_level:"error"}}modifyFrames(e){var s=this;return X((function*(){for(var r of e)r.stacktrace&&r.stacktrace.frames&&L(r.stacktrace.frames)&&(r.stacktrace.frames=yield s.applyModifiers(r.stacktrace.frames));return e}))()}coerceFallback(e){var s;return{type:"Error",value:"Unknown error",stack:(s=e.syntheticException)==null?void 0:s.stack,synthetic:!0}}parseStacktrace(e,s){var r,i;return e.cause!=null&&(r=this.parseStacktrace(e.cause,s)),e.stack!=""&&e.stack!=null&&(i=this.applyChunkIds(this.stackParser(e.stack,e.synthetic?s.skipFirstLines:0),s.chunkIdMap)),w({},e,{cause:r,stack:i})}applyChunkIds(e,s){return e.map((r=>(r.filename&&s&&(r.chunk_id=s[r.filename]),r)))}applyCoercers(e,s){for(var r of this.coercers)if(r.match(e))return r.coerce(e,s);return this.coerceFallback(s)}applyModifiers(e){var s=this;return X((function*(){var r=e;for(var i of s.modifiers)r=yield i(r);return r}))()}convertToExceptionList(e,s){var r,i,n,o={type:e.type,value:e.value,mechanism:{type:(r=s.type)!==null&&r!==void 0?r:"generic",handled:(i=s.handled)===null||i===void 0||i,synthetic:(n=e.synthetic)!==null&&n!==void 0&&n}};e.stack&&(o.stacktrace={type:"raw",frames:e.stack});var a=[o];return e.cause!=null&&a.push(...this.convertToExceptionList(e.cause,w({},s,{handled:!0}))),a}buildParsingContext(e){var s;return{chunkIdMap:Mh(this.stackParser),skipFirstLines:(s=e.skipFirstLines)!==null&&s!==void 0?s:1}}buildCoercingContext(e,s,r){r===void 0&&(r=0);var i=(n,o)=>{if(4>=o){var a=this.buildCoercingContext(e,s,o);return this.applyCoercers(n,a)}};return w({},s,{syntheticException:r==0?s.syntheticException:void 0,mechanism:e,apply:n=>i(n,r),next:n=>i(n,r+1)})}}var ms="?";function Bn(t,e,s,r,i){var n={platform:t,filename:e,function:s===""?ms:s,in_app:!0};return x(r)||(n.lineno=r),x(i)||(n.colno=i),n}var iu=(t,e)=>{var s=t.indexOf("safari-extension")!==-1,r=t.indexOf("safari-web-extension")!==-1;return s||r?[t.indexOf("@")!==-1?t.split("@")[0]:ms,s?"safari-extension:"+e:"safari-web-extension:"+e]:[t,e]},Oh=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,Dh=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,Bh=/\((\S*)(?::(\d+))(?::(\d+))\)/,jh=(t,e)=>{var s=Oh.exec(t);if(s)return Bn(e,s[1],ms,+s[2],+s[3]);var r=Dh.exec(t);if(r){if(r[2]&&r[2].indexOf("eval")===0){var i=Bh.exec(r[2]);i&&(r[2]=i[1],r[3]=i[2],r[4]=i[3])}var n=iu(r[1]||ms,r[2]);return Bn(e,n[1],n[0],r[3]?+r[3]:void 0,r[4]?+r[4]:void 0)}},Uh=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,Hh=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,Wh=(t,e)=>{var s=Uh.exec(t);if(s){if(s[3]&&s[3].indexOf(" > eval")>-1){var r=Hh.exec(s[3]);r&&(s[1]=s[1]||"eval",s[3]=r[1],s[4]=r[2],s[5]="")}var i=s[3],n=s[1]||ms,o=iu(n,i);return Bn(e,i=o[1],n=o[0],s[4]?+s[4]:void 0,s[5]?+s[5]:void 0)}},Xa=/\(error: (.*)\)/;class zh{match(e){return this.isDOMException(e)||this.isDOMError(e)}coerce(e,s){var r=W(e.stack);return{type:this.getType(e),value:this.getValue(e),stack:r?e.stack:void 0,cause:e.cause?s.next(e.cause):void 0,synthetic:!1}}getType(e){return this.isDOMError(e)?"DOMError":"DOMException"}getValue(e){var s=e.name||(this.isDOMError(e)?"DOMError":"DOMException");return e.message?s+": "+e.message:s}isDOMException(e){return qr(e,"DOMException")}isDOMError(e){return qr(e,"DOMError")}}class qh{match(e){return(function(s){switch({}.toString.call(s)){case"[object Error]":case"[object Exception]":case"[object DOMException]":case"[object DOMError]":case"[object WebAssembly.Exception]":return!0;default:return Rc(s,Error)}})(e)}coerce(e,s){return{type:this.getType(e),value:this.getMessage(e,s),stack:this.getStack(e),cause:e.cause?s.next(e.cause):void 0,synthetic:!1}}getType(e){return e.name||e.constructor.name}getMessage(e,s){var r=e.message;return String(r.error&&typeof r.error.message=="string"?r.error.message:r)}getStack(e){return e.stacktrace||e.stack||void 0}}class Vh{constructor(){}match(e){return!!qr(e,"ErrorEvent")&&(e.error!=null||this.fe(e))}coerce(e,s){var r;if(e.error!=null)return s.apply(e.error);var i=s.apply(e.message);return w({},i,{stack:(r=this.pe(e))!==null&&r!==void 0?r:i.stack,synthetic:!0})}fe(e){return W(e.message)&&e.message.length>0}pe(e){var s=e;if(W(s.filename)&&s.filename.length>0){var r,i,n=(r=s.lineno)!==null&&r!==void 0?r:0,o=(i=s.colno)!==null&&i!==void 0?i:0;return`Error - at `+s.filename+":"+n+":"+o}}}var Gh=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;class Kh{match(e){return typeof e=="string"}coerce(e,s){var r,i=this.getInfos(e),n=i[0],o=i[1];return{type:n??"Error",value:o??e,stack:(r=s.syntheticException)==null?void 0:r.stack,synthetic:!0}}getInfos(e){var s="Error",r=e,i=e.match(Gh);return i&&(s=i[1],r=i[2]),[s,r]}}var Jh=["fatal","error","warning","log","info","debug"];function nu(t,e){e===void 0&&(e=40);var s=Object.keys(t);if(s.sort(),!s.length)return"[object has no keys]";for(var r=s.length;r>0;r--){var i=s.slice(0,r).join(", ");if(e>=i.length)return r===s.length?i:i.length>e?i.slice(0,e)+"...":i}return""}class Yh{match(e){return typeof e=="object"&&e!==null}coerce(e,s){var r,i,n=this.getErrorPropertyFromObject(e);return n?s.apply(n):{type:this.getType(e),value:this.getValue(e),stack:(r=this.getStack(e))!==null&&r!==void 0?r:(i=s.syntheticException)==null?void 0:i.stack,level:this.isSeverityLevel(e.level)?e.level:"error",synthetic:!0}}getType(e){return No(e)?e.constructor.name:"Error"}getValue(e){if("name"in e&&typeof e.name=="string"){var s="'"+e.name+"' captured as exception";return"message"in e&&typeof e.message=="string"&&(s+=" with message: '"+e.message+"'"),s}if("message"in e&&typeof e.message=="string")return e.message;var r=this.getObjectClassName(e);return(r&&r!=="Object"?"'"+r+"'":"Object")+" captured as exception with keys: "+nu(e)}isSeverityLevel(e){return W(e)&&!Nn(e)&&Jh.indexOf(e)>=0}getStack(e){try{return W(e.stacktrace)&&e.stacktrace.length>0?e.stacktrace:W(e.stack)&&e.stack.length>0?e.stack:void 0}catch{return}}getErrorPropertyFromObject(e){for(var s in e)if({}.hasOwnProperty.call(e,s)){var r=e[s];if(Ah(r))return r}}getObjectClassName(e){try{var s=Object.getPrototypeOf(e);return s?s.constructor.name:void 0}catch{return}}}class Zh{match(e){return No(e)}coerce(e,s){var r,i=e.constructor.name;return{type:i,value:i+" captured as exception with keys: "+nu(e),stack:(r=s.syntheticException)==null?void 0:r.stack,synthetic:!0}}}class Xh{match(e){return $c(e)}coerce(e,s){var r;return{type:"Error",value:"Primitive value captured as exception: "+String(e),stack:(r=s.syntheticException)==null?void 0:r.stack,synthetic:!0}}}class Qh{match(e){return qr(e,"PromiseRejectionEvent")||this.isCustomEventWrappingRejection(e)}isCustomEventWrappingRejection(e){if(!No(e))return!1;try{var s=e.detail;return s!=null&&typeof s=="object"&&"reason"in s}catch{return!1}}coerce(e,s){var r,i=this.getUnhandledRejectionReason(e);return $c(i)?{type:"UnhandledRejection",value:"Non-Error promise rejection captured with value: "+String(i),stack:(r=s.syntheticException)==null?void 0:r.stack,synthetic:!0}:s.apply(i)}getUnhandledRejectionReason(e){try{if("reason"in e)return e.reason;if("detail"in e&&e.detail!=null&&typeof e.detail=="object"&&"reason"in e.detail)return e.detail.reason}catch{}return e}}var Zr="$message",Xr="$timestamp",ep=new Set([Zr,Xr]),Qi={enabled:!0,max_bytes:32768};function Qr(t){var e;return t?{enabled:(e=t.enabled)!==null&&e!==void 0?e:Qi.enabled,max_bytes:sp(t.max_bytes,Qi.max_bytes)}:w({},Qi)}class tp{constructor(e){this.Ke=[],this.Je=0,this.Ne=Qr(e)}setConfig(e){this.Ne=Qr(e),this.Xe()}add(e){var s=(function(i){var n;try{n=Fc(i)}catch{return}try{var o=JSON.parse(n);if(!te(o))return;var a=o,l=a[Zr],u=a[Xr];return!W(l)||l.trim().length===0||!W(u)&&!he(u)?void 0:{step:a,json:n}}catch{return}})(e);if(s){var r=(function(i){if(typeof TextEncoder<"u")return new TextEncoder().encode(i).length;for(var n=encodeURIComponent(i),o=0,a=0;n.length>a;a++)n[a]==="%"?(o+=1,a+=2):o+=1;return o})(s.json);r>this.Ne.max_bytes||(this.Ke.push({step:s.step,bytes:r}),this.Je+=r,this.Xe())}}getAttachable(){return this.Ke.map((e=>e.step))}clear(){this.Ke=[],this.Je=0}size(){return this.Ke.length}Xe(){for(;this.Je>this.Ne.max_bytes&&this.Ke.length>0;){var e=this.Ke.shift();e&&(this.Je-=e.bytes)}}}function sp(t,e){if(!he(t)||t===1/0||t===-1/0)return e;var s=Math.floor(t);return 0>s?e:s}var ou=function(t,e){var s=(e===void 0?{}:e).debugEnabled,r={k(i){if(v&&(Y.DEBUG||v.POSTHOG_DEBUG||s)&&!x(v.console)&&v.console){for(var n=("__rrweb_original__"in v.console[i])?v.console[i].__rrweb_original__:v.console[i],o=arguments.length,a=new Array(o>1?o-1:0),l=1;o>l;l++)a[l-1]=arguments[l];n(t,...a)}},debug(){for(var i=arguments.length,n=new Array(i),o=0;i>o;o++)n[o]=arguments[o];r.k("debug",...n)},info(){for(var i=arguments.length,n=new Array(i),o=0;i>o;o++)n[o]=arguments[o];r.k("log",...n)},warn(){for(var i=arguments.length,n=new Array(i),o=0;i>o;o++)n[o]=arguments[o];r.k("warn",...n)},error(){for(var i=arguments.length,n=new Array(i),o=0;i>o;o++)n[o]=arguments[o];r.k("error",...n)},critical(){for(var i=arguments.length,n=new Array(i),o=0;i>o;o++)n[o]=arguments[o];console.error(t,...n)},uninitializedWarning(i){r.error("You must initialize PostHog before calling "+i)},createLogger:(i,n)=>ou(t+" "+i,n)};return r},k=ou("[PostHog.js]"),se=k.createLogger,rp=se("[ExternalScriptsLoader]"),en=(t,e,s)=>{if(t.config.disable_external_dependency_loading)return rp.warn(e+" was requested but loading of external scripts is disabled."),s("Loading of external scripts is disabled");var r=C?.querySelectorAll("script");if(r){for(var i,n=function(){if(r[o].src===e){var l=r[o];return l.__posthog_loading_callback_fired?{v:s()}:(l.addEventListener("load",(u=>{l.__posthog_loading_callback_fired=!0,s(void 0,u)})),l.onerror=u=>s(u),{v:void 0})}},o=0;r.length>o;o++)if(i=n())return i.v}var a=()=>{if(!C)return s("document not found");var l=C.createElement("script");if(l.type="text/javascript",l.crossOrigin="anonymous",l.src=e,l.onload=d=>{l.__posthog_loading_callback_fired=!0,s(void 0,d)},l.onerror=d=>s(d),t.config.prepare_external_dependency_script&&(l=t.config.prepare_external_dependency_script(l)),!l)return s("prepare_external_dependency_script returned null");if(t.config.external_scripts_inject_target==="head")C.head.appendChild(l);else{var u,c=C.querySelectorAll("body > script");c.length>0?(u=c[0].parentNode)==null||u.insertBefore(l,c[0]):C.body.appendChild(l)}};C!=null&&C.body?a():C?.addEventListener("DOMContentLoaded",a)};$.__PosthogExtensions__=$.__PosthogExtensions__||{},$.__PosthogExtensions__.loadExternalDependency=(t,e,s)=>{if(e!=="remote-config"){var r;if(t.config.strict_script_versioning)r=t.requestRouter.endpointFor("assets","/static/"+t.version+"/"+e+".js");else{var i="/static/"+e+".js?v="+t.version;if(e==="toolbar"){var n=3e5;i=i+"&t="+Math.floor(Date.now()/n)*n}r=t.requestRouter.endpointFor("assets",i)}en(t,r,s)}else{var o=t.requestRouter.endpointFor("assets","/array/"+t.config.token+"/config.js");en(t,o,s)}},$.__PosthogExtensions__.loadSiteApp=(t,e,s)=>{var r=t.requestRouter.endpointFor("api",e);en(t,r,s)};Y.DEBUG=!1,Y.LIB_VERSION="1.415.7",Y.LIB_NAME="web";var au="$people_distinct_id",sr="$device_id",tn="$device_model",Bs="__alias",js="__timers",jn="$autocapture_disabled_server_side",Un="$heatmaps_enabled_server_side",Hn="$exception_capture_enabled_server_side",Wn="$error_tracking_suppression_rules",zn="$error_tracking_capture_extension_exceptions",qn="$web_vitals_enabled_server_side",jo="$dead_clicks_enabled_server_side",Uo="$product_tours_enabled_server_side",Vn="$web_vitals_allowed_metrics",Vt="$session_recording_remote_config",lu="$replay_sample_rate",cu="$replay_override_sampling",uu="$replay_override_linked_flag",du="$replay_override_url_trigger",hu="$replay_override_event_trigger",cs="$sesid",Ho="$session_is_sampled",Bt="$enabled_feature_flags",Us="$active_feature_flags",Rr="$early_access_features",Gn="$feature_flag_details",Hs="$feature_flag_payloads",Tr="$feature_flag_request_id",ei="$minimal_flag_called_events",et="$override_feature_flags",jt="$override_feature_flag_payloads",ct="$stored_person_properties",Ut="$stored_group_properties",Kn="$surveys",ti="$surveys_loaded_at",Jn="$surveys_activated",Nr="$surveys_activated_session",Mr="$surveys_activated_timestamps",Ws="ph_product_tours",Wt="$flag_call_reported",zs="$flag_call_reported_session_id",Lr="$feature_flag_errors",Gs="$feature_flag_evaluated_at",He="$user_state",Yn="$client_session_props",Zn="$capture_rate_limit",Xn="$initial_campaign_params",Qn="$initial_referrer_info",si="$initial_person_info",ri="$epp",br="$posthog_cookieless",pu="$cookieless_mode",fu="$sdk_debug_extensions_init_method",gu="$sdk_debug_extensions_init_time_ms",mu="$sdk_debug_recording_script_not_loaded",Wo="PostHog loadExternalDependency extension not found.",Ht="on_reject",ht="always",ts="anonymous",Tt="identified",eo="identified_only",ii="visibilitychange",ni="beforeunload",os="$pageview",sn="$pageleave",rn="$identify",Qa="$groupidentify";function Er(t,e){L(t)&&t.forEach(e)}function Z(t,e){if(!D(t))if(L(t))t.forEach(e);else if(fh(t))t.forEach(((r,i)=>e(r,i)));else for(var s in t)Ac.call(t,s)&&e(t[s],s)}var ee=function(t){for(var e=arguments.length,s=new Array(e>1?e-1:0),r=1;e>r;r++)s[r-1]=arguments[r];for(var i of s)for(var n in i)i[n]!==void 0&&(t[n]=i[n]);return t};function Or(t){for(var e=Object.keys(t),s=e.length,r=new Array(s);s--;)r[s]=[e[s],t[e[s]]];return r}var el=function(t){try{return t()}catch{return}},ip=function(t){return function(){try{for(var e=arguments.length,s=new Array(e),r=0;e>r;r++)s[r]=arguments[r];return t.apply(this,s)}catch(i){k.critical("Implementation error. Please turn on debug mode and open a ticket on https://app.posthog.com/home#panel=support%3Asupport%3A."),k.critical(i)}}},zo=function(t){var e={};return Z(t,(function(s,r){(W(s)&&s.length>0||he(s))&&(e[r]=s)})),e},np=["herokuapp.com","vercel.app","netlify.app"];function op(t){var e=t?.hostname;if(!W(e))return!1;var s=e.split(".").slice(-2).join(".");for(var r of np)if(s===r)return!1;return!0}function ie(t,e,s,r){var i=r??{},n=i.capture,o=i.passive;t?.addEventListener(e,s,{capture:n!==void 0&&n,passive:o===void 0||o})}function to(t){return t.name==="ph_toolbar_internal"}var vu=t=>{if(C){try{for(var e=t+"=",s=C.cookie.split(";").filter((n=>n.length)),r=0;s.length>r;r++){for(var i=s[r];i.charAt(0)==" ";)i=i.substring(1,i.length);if(i.indexOf(e)===0)return decodeURIComponent(i.substring(e.length,i.length))}}catch{}return null}};Math.trunc||(Math.trunc=function(t){return 0>t?Math.ceil(t):Math.floor(t)}),Number.isInteger||(Number.isInteger=function(t){return he(t)&&isFinite(t)&&Math.floor(t)===t});class oi{constructor(e){if(this.bytes=e,e.length!==16)throw new TypeError("not 128-bit length")}static fromFieldsV7(e,s,r,i){if(!Number.isInteger(e)||!Number.isInteger(s)||!Number.isInteger(r)||!Number.isInteger(i)||0>e||0>s||0>r||0>i||e>0xffffffffffff||s>4095||r>1073741823||i>4294967295)throw new RangeError("invalid field value");var n=new Uint8Array(16);return n[0]=e/Math.pow(2,40),n[1]=e/Math.pow(2,32),n[2]=e/Math.pow(2,24),n[3]=e/Math.pow(2,16),n[4]=e/256,n[5]=e,n[6]=112|s>>>8,n[7]=s,n[8]=128|r>>>24,n[9]=r>>>16,n[10]=r>>>8,n[11]=r,n[12]=i>>>24,n[13]=i>>>16,n[14]=i>>>8,n[15]=i,new oi(n)}toString(){for(var e="",s=0;this.bytes.length>s;s++)e=e+(this.bytes[s]>>>4).toString(16)+(15&this.bytes[s]).toString(16),s!==3&&s!==5&&s!==7&&s!==9||(e+="-");if(e.length!==36)throw new Error("Invalid UUIDv7 was generated");return e}clone(){return new oi(this.bytes.slice(0))}equals(e){return this.compareTo(e)===0}compareTo(e){for(var s=0;16>s;s++){var r=this.bytes[s]-e.bytes[s];if(r!==0)return Math.sign(r)}return 0}}class ap{generate(){var e=this.generateOrAbort();if(!x(e))return e;this.S=0;var s=this.generateOrAbort();if(x(s))throw new Error("Could not generate UUID after timestamp reset");return s}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 oi.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 lp}}var tl,_u=t=>{if(typeof UUIDV7_DENY_WEAK_RNG<"u"&&UUIDV7_DENY_WEAK_RNG)throw new Error("no cryptographically strong RNG available");for(var e=0;t.length>e;e++)t[e]=65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random());return t};v&&!x(v.crypto)&&crypto.getRandomValues&&(_u=t=>crypto.getRandomValues(t));class lp{nextUint32(){return this.R.length>this.O||(_u(this.R),this.O=0),this.R[this.O++]}constructor(){this.R=new Uint32Array(8),this.O=1/0}}var dt=()=>cp().toString(),cp=()=>(tl||(tl=new ap)).generate(),Ps="",up=/[a-z0-9][a-z0-9-]+\.[a-z]{2,}$/i,pt={N:()=>!!C,j(t){k.error("cookieStore error: "+t)},P:vu,H(t){var e;try{e=JSON.parse(pt.P(t))||{}}catch{}return e},F(t,e,s,r,i){if(!C)return!1;try{var n="",o="",a=(function(c,d){if(d){var h=(function(f,g){if(g===void 0&&(g=C),Ps)return Ps;if(!g||["localhost","127.0.0.1"].includes(f))return"";for(var m=f.split("."),_=Math.min(m.length,8),E="dmn_chk_"+dt();!Ps&&_--;){var b=m.slice(_).join("."),I=E+"=1;domain=."+b+";path=/";g.cookie=I+";max-age=3",g.cookie.includes(E)&&(g.cookie=I+";max-age=0",Ps=b)}return Ps})(c);if(!h){var p=(f=>{var g=f.match(up);return g?g[0]:""})(c);p!==h&&k.info("Warning: cookie subdomain discovery mismatch",p,h),h=p}return h?"; domain=."+h:""}return""})(C.location.hostname,r);if(s){var l=new Date;l.setTime(l.getTime()+864e5*s),n="; expires="+l.toUTCString()}i&&(o="; secure");var u=t+"="+encodeURIComponent(JSON.stringify(e))+n+"; SameSite=Lax; path=/"+a+o;return u.length>3686.4&&k.warn("cookieStore warning: large cookie, len="+u.length),C.cookie=u,!0}catch{return!1}},q(t,e){if(C!=null&&C.cookie)try{pt.F(t,"",-1,e)}catch{return}}},nn=null,Q={N(){if(!$e(nn))return nn;var t=!0;if(x(v))t=!1;else try{var e="__mplssupport__";Q.F(e,"xyz"),Q.P(e)!=='"xyz"'&&(t=!1),Q.q(e)}catch{t=!1}return t||k.error("localStorage unsupported; falling back to cookie store"),nn=t,t},j(t){k.error("localStorage error: "+t)},P(t){try{return v?.localStorage.getItem(t)}catch(e){Q.j(e)}return null},H(t){try{return JSON.parse(Q.P(t))||{}}catch{}return null},F(t,e){try{return v?.localStorage.setItem(t,JSON.stringify(e)),!0}catch(s){Q.j(s)}return!1},q(t){try{v?.localStorage.removeItem(t)}catch(e){Q.j(e)}}},dp=[sr,"distinct_id",cs,Ho,ri,si,He],Sr={},hp={N:()=>!0,j(t){k.error("memoryStorage error: "+t)},P:t=>Sr[t]||null,H:t=>Sr[t]||null,F:(t,e)=>(Sr[t]=e,!0),q(t){delete Sr[t]}},Nt=null,ce={N(){if(!$e(Nt))return Nt;if(Nt=!0,x(v))Nt=!1;else try{var t="__support__";ce.F(t,"xyz"),ce.P(t)!=='"xyz"'&&(Nt=!1),ce.q(t)}catch{Nt=!1}return Nt},j(t){k.error("sessionStorage error: ",t)},P(t){try{return v?.sessionStorage.getItem(t)}catch(e){ce.j(e)}return null},H(t){try{return JSON.parse(ce.P(t))||null}catch{}return null},F(t,e){try{return v?.sessionStorage.setItem(t,JSON.stringify(e)),!0}catch(s){ce.j(s)}return!1},q(t){try{v?.sessionStorage.removeItem(t)}catch(e){ce.j(e)}}};class pp{constructor(e){this._instance=e}get Ne(){return this._instance.config}get consent(){return this.ti()?0:this.ei}isOptedOut(){return this.Ne.cookieless_mode===ht||this.isRejected()||this.consent===-1&&this.Ne.cookieless_mode===Ht}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,s=e.token,r=e.opt_out_capturing_cookie_prefix;return e.consent_persistence_name||(r?r+s:"__ph_opt_in_out_"+s)}get ei(){var e=this.ii.P(this.ri);return Ji(e)?1:M(_h,e)?0:-1}get ii(){var e=this.Ne.opt_out_capturing_persistence_type,s=e==="localStorage"?Q:pt;if(!this.ni||this.ni!==s){this.ni=s;var r=e==="localStorage"?pt:Q;r.P(this.ri)&&(this.ni.P(this.ri)||this.optInOut(Ji(r.P(this.ri))),r.q(this.ri,this.Ne.cross_subdomain_cookie))}return this.ni}ti(){return!!this.Ne.respect_dnt&&[ke?.doNotTrack,ke?.msDoNotTrack,$.doNotTrack].some((e=>Ji(e)))}}function yu(t,e){var s,r=t==null||(s=t.config)==null?void 0:s.get_current_url;if(!Se(r))return e;try{var i=r(e);return W(i)&&i?i:e}catch(n){return k.error("Error in get_current_url, falling back to window.location.href",n),e}}var wu="__POSTHOG_TOOLBAR__",fp=1,gp=3,mp=11;function sl(t){return t instanceof Element&&(t.id===wu||!(t.closest==null||!t.closest(".toolbar-global-fade-container")))}function Ft(t){return!!t&&t.nodeType===fp}function Me(t,e){return!!t&&!!t.tagName&&t.tagName.toLowerCase()===e.toLowerCase()}function bu(t){return!!t&&t.nodeType===gp}function Eu(t){return!!t&&t.nodeType===mp&&Ft(t.host)}var Su=1e3;function qo(t){return t?Fi(t).split(/\s+/):[]}function rl(t,e){var s=(function(r){var i,n=v==null||(i=v.location)==null?void 0:i.href;return x(n)?void 0:yu(r,n)})(e);return!!(s&&t&&t.some((r=>s.match(r))))}function ai(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 qo(e)}function xu(t){return D(t)?null:Fi(t).split(/(\s+)/).filter((e=>Ks(e))).join("").replace(/[\r\n]/g," ").replace(/[ ]+/g," ").substring(0,255)}function rr(t){var e="";return ro(t)&&!Fu(t)&&t.childNodes&&t.childNodes.length&&Z(t.childNodes,(function(s){var r;bu(s)&&s.textContent&&(e+=(r=xu(s.textContent))!==null&&r!==void 0?r:"")})),Fi(e)}function on(t){var e;return x(t.target)?t.srcElement||null:(e=t.target)!=null&&e.shadowRoot?t.composedPath()[0]||null:t.target||null}var Vo=["a","button","form","input","select","textarea","label"];function so(t,e){if(x(e))return!0;var s,r=function(n){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}})(n,o))))return{v:!0}};for(var i of t)if(s=r(i))return s.v;return!1}function ku(t){var e=t.parentNode;return!(!e||!Ft(e))&&e}var vp=[".ph-no-autocapture","[data-ph-no-autocapture]"],Iu=["next","previous","prev",">","<"],_p=[...Iu,"+","-","−","–"],il=(t,e)=>/[a-z0-9]/i.test(e)?t.includes(e):t===e,nl=[".ph-no-rageclick",".ph-no-capture"],yp=["","text","search","email","password","url","tel","number"];function ol(t,e){if(!v||Go(t))return!1;var s,r,i,n,o;if(Ke(e)?(s=!!e&&nl,r=void 0,i=!1):(s=(n=e?.css_selector_ignorelist)!==null&&n!==void 0?n:nl,r=e?.content_ignorelist,i=(o=e?.ignore_text_selection)!==null&&o!==void 0&&o),s===!1||i&&(function(l){return!(!l||!Ft(l))&&(!!Me(l,"textarea")||(Me(l,"input")?M(yp,(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=Cu(t,!1).targetElementList;return!(function(l,u){if(l===!1||x(l))return!1;var c;if(l===!0)c=Iu;else{if(!L(l))return!1;if(l.length>10)return k.error("[PostHog] content_ignorelist array cannot exceed 10 items. Use css_selector_ignorelist for more complex matching."),!1;c=l.map((d=>d.toLowerCase()))}return u.some((d=>{var h=d.safeText,p=d.ariaLabel;return c.some((f=>il(h,f)||il(p,f)))}))})(r,a.map((l=>{var u;return{safeText:rr(l).toLowerCase(),ariaLabel:((u=l.getAttribute("aria-label"))==null?void 0:u.toLowerCase().trim())||""}})))&&!so(a,s)}var Go=t=>!t||Me(t,"html")||!Ft(t),Cu=(t,e)=>{if(!v||Go(t))return{parentIsUsefulElement:!1,targetElementList:[]};for(var s=!1,r=[t],i=t;i.parentNode&&!Me(i,"body");)if(Eu(i.parentNode))r.push(i.parentNode.host),i=i.parentNode.host;else{var n=ku(i);if(!n)break;if(e||Vo.indexOf(n.tagName.toLowerCase())>-1)s=!0;else try{var o=v.getComputedStyle(n);o&&o.getPropertyValue("cursor")==="pointer"&&(s=!0)}catch{}r.push(n),i=n}return{parentIsUsefulElement:s,targetElementList:r}};function ro(t){for(var e=new Set,s=0,r=t;r.parentNode&&!Me(r,"body");r=r.parentNode){if(s++>=Su||e.has(r))return!1;e.add(r);var i=ai(r);if(M(i,"ph-sensitive")||M(i,"ph-no-capture"))return!1}if(M(ai(t),"ph-include"))return!0;var n=t.type||"";if(W(n))switch(n.toLowerCase()){case"hidden":case"password":return!1}var o=t.name||t.id||"";return!W(o)||!/^cc|cardnum|ccnum|creditcard|csc|cvc|cvv|exp|pass|pwd|routing|seccode|securitycode|securitynum|socialsec|socsec|ssn/i.test(o.replace(/[^a-zA-Z0-9]/g,""))}function Fu(t){return!!(Me(t,"input")&&!["button","checkbox","submit","reset"].includes(t.type)||Me(t,"select")||Me(t,"textarea")||t.getAttribute("contenteditable")==="true")}var al=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}))$"),ll=/(^|[^0-9A-Za-z_])([0-9][0-9 -]*[0-9])(?=$|[^0-9A-Za-z_])/g,wp=[16,15,14,13],bp=new RegExp("^(\\d{3}-?\\d{2}-?\\d{4})$"),cl=new RegExp("(^|[^0-9])((?!000|666)[0-9]{3}-?(?!00)[0-9]{2}-?(?!0000)[0-9]{4})(?=$|([^0-9]))","g"),ul=/[0-9A-Za-z_]/;function Ep(t){for(var e=0,s=!1,r=t.length-1;r>=0;r--){var i=t.charCodeAt(r)-48;s&&(i*=2)>9&&(i-=9),e+=i,s=!s}return e%10==0}function Ks(t,e){if(e===void 0&&(e=!0),D(t))return!1;if(W(t)){t=Fi(t);var s=e?al.test((t||"").replace(/[- ]/g,"")):(function(i){var n;for(ll.lastIndex=0;n=ll.exec(i);){var o=n[2];if(o)for(var a=o.replace(/[- ]/g,""),l=0;a.length>l;l++)for(var u of wp){var c=l+u;if(a.length>=c){var d=a.slice(l,c);if(al.test(d)&&Ep(d))return!0}}}return!1})(t);if(s)return!1;var r=e?bp.test(t):(function(i){var n;for(cl.lastIndex=0;n=cl.exec(i);){var o=n[1],a=n[3];if(!(o&&a&&ul.test(o)&&ul.test(a)))return!0}return!1})(t);if(r)return!1}return!0}function dl(t){var e=rr(t);return Ks(e=(e+" "+Pu(t)).trim())?e:""}function Pu(t){var e="";return t&&t.childNodes&&t.childNodes.length&&Z(t.childNodes,(function(s){var r;if(s&&((r=s.tagName)==null?void 0:r.toLowerCase())==="span")try{var i=rr(s);e=(e+" "+i).trim(),s.childNodes&&s.childNodes.length&&(e=(e+" "+Pu(s)).trim())}catch(n){k.error("[AutoCapture]",n)}})),e}function hl(t){return t.replace(/"|\\"/g,'\\"')}function Sp(t){var e=t.attr__class;if(e)return L(e)?e:qo(e)}var xr=se("[Dead Clicks]"),xp=()=>!0,kp=t=>{var e,s=!((e=t.instance.persistence)==null||!e.get_property(jo)),r=t.instance.config.capture_dead_clicks;return Ke(r)?r:!!te(r)||s};class pl{get lazyLoadedDeadClicksAutocapture(){return this.si}constructor(e,s,r){this.instance=e,this.isEnabled=s,this.onCapture=r,this.startIfEnabledOrStop()}onRemoteConfig(e){if(e.ok){var s=e.config;"captureDeadClicks"in s&&(this.instance.persistence&&this.instance.persistence.register({[jo]:s.captureDeadClicks}),this.startIfEnabledOrStop())}}startIfEnabledOrStop(){this.isEnabled(this)?this.ai((()=>{this.oi()})):this.stop()}ai(e){var s,r;(s=$.__PosthogExtensions__)!=null&&s.initDeadClicksAutocapture?e():(r=$.__PosthogExtensions__)==null||r.loadExternalDependency==null||r.loadExternalDependency(this.instance,"dead-clicks-autocapture",(i=>{i?xr.error("failed to load script",i):e()}))}oi(){var e;if(C){if(!this.si&&(e=$.__PosthogExtensions__)!=null&&e.initDeadClicksAutocapture){var s=te(this.instance.config.capture_dead_clicks)?w({},this.instance.config.capture_dead_clicks):{};s.__onCapture=this.onCapture,this.onCapture&&(s.capture_dead_swipes=!1),this.si=$.__PosthogExtensions__.initDeadClicksAutocapture(this.instance,s),this.si.start(C),xr.info("starting...")}}else xr.error("`document` not found. Cannot start.")}stop(){this.si&&(this.si.stop(),this.si=void 0,xr.info("stopping..."))}}var an=se("[SegmentIntegration]"),Au="posthog-js";function $u(t,e){var s=e===void 0?{}:e,r=s.organization,i=s.projectId,n=s.prefix,o=s.severityAllowList,a=o===void 0?["error"]:o,l=s.sendExceptionsToPostHog,u=l===void 0||l;return c=>{var d,h,p,f,g;if(a!=="*"&&!a.includes(c.level)||!t.__loaded)return c;c.tags||(c.tags={});var m=t.requestRouter.endpointFor("ui","/project/"+t.config.token+"/person/"+t.get_distinct_id());c.tags["PostHog Person URL"]=m,t.sessionRecordingStarted()&&(c.tags["PostHog Recording URL"]=t.get_session_replay_url({withTimestamp:!0}));var _,E=((d=c.exception)==null?void 0:d.values)||[],b=E.map((F=>w({},F,{stacktrace:F.stacktrace?w({},F.stacktrace,{type:"raw",frames:(F.stacktrace.frames||[]).map((P=>w({},P,{platform:"web:javascript"})))}):void 0}))),I={$exception_message:((h=E[0])==null?void 0:h.value)||c.message,$exception_type:(p=E[0])==null?void 0:p.type,$exception_level:c.level,$exception_list:b,$sentry_event_id:c.event_id,$sentry_exception:c.exception,$sentry_exception_message:((f=E[0])==null?void 0:f.value)||c.message,$sentry_exception_type:(g=E[0])==null?void 0:g.type,$sentry_tags:c.tags};return r&&i&&(I.$sentry_url=(n||"https://sentry.io/organizations/")+r+"/issues/?project="+i+"&query="+c.event_id),u&&((_=t.exceptions)==null||_.sendExceptionEvent(I)),c}}class Ip{constructor(e,s,r,i,n,o){this.name=Au,this.setupOnce=function(a){a($u(e,{organization:s,projectId:r,prefix:i,severityAllowList:n,sendExceptionsToPostHog:o==null||o}))}}}class fl{constructor(e){this.li=(s,r,i)=>{i&&(i.noSessionId||i.activityTimeout||i.sessionPastMaximumLength||i.crossTabAdoption)&&(k.info("[PageViewManager] Session rotated, clearing pageview state",{sessionId:s,changeReason:i}),this.ui=void 0,this._instance.scrollManager.resetContext())},this._instance=e,this.hi()}hi(){var e;this.di=(e=this._instance.sessionManager)==null?void 0:e.onSessionId(this.li)}destroy(){var e;(e=this.di)==null||e.call(this),this.di=void 0}doPageView(e,s){var r,i=this.vi(e,s);return this.ui={pathname:(r=v?.location.pathname)!==null&&r!==void 0?r:"",pageViewId:s,timestamp:e},this._instance.scrollManager.resetContext(),i}doPageLeave(e){var s;return this.vi(e,(s=this.ui)==null?void 0:s.pageViewId)}doEvent(){var e;return{$pageview_id:(e=this.ui)==null?void 0:e.pageViewId}}vi(e,s){var r=this.ui;if(!r)return{$pageview_id:s};var i={$pageview_id:s,$prev_pageview_id:r.pageViewId},n=this._instance.scrollManager.getContext();if(n&&!this._instance.config.disable_scroll_properties){var o=n.maxScrollHeight,a=n.lastScrollY,l=n.maxScrollY,u=n.maxContentHeight,c=n.lastContentY,d=n.maxContentY;if(!(x(o)||x(a)||x(l)||x(u)||x(c)||x(d))){o=Math.ceil(o),a=Math.ceil(a),l=Math.ceil(l),u=Math.ceil(u),c=Math.ceil(c),d=Math.ceil(d);var h=o>1?rt(a/o,0,1,k):1,p=o>1?rt(l/o,0,1,k):1,f=u>1?rt(c/u,0,1,k):1,g=u>1?rt(d/u,0,1,k):1;i=ee(i,{$prev_pageview_last_scroll:a,$prev_pageview_last_scroll_percentage:h,$prev_pageview_max_scroll:l,$prev_pageview_max_scroll_percentage:p,$prev_pageview_last_content:c,$prev_pageview_last_content_percentage:f,$prev_pageview_max_content:d,$prev_pageview_max_content_percentage:g})}}return r.pathname&&(i.$prev_pageview_pathname=r.pathname),r.timestamp&&(i.$prev_pageview_duration=(e.getTime()-r.timestamp.getTime())/1e3),i}}var ln=["flags","surveys"],Cp={[au]:{exposure:"hidden"},[Bs]:{exposure:"hidden"},__cmpns:{exposure:"hidden"},[js]:{exposure:"hidden"},[jn]:{exposure:"event"},[Un]:{exposure:"hidden"},[Hn]:{exposure:"event"},[Wn]:{exposure:"hidden"},[zn]:{exposure:"event"},[qn]:{exposure:"event"},[jo]:{exposure:"event"},[Uo]:{exposure:"hidden"},[Vn]:{exposure:"event"},[Vt]:{exposure:"hidden"},$session_recording_enabled_server_side:{exposure:"hidden"},[cs]:{exposure:"hidden"},[Ho]:{exposure:"event"},[lu]:{exposure:"event",shouldSkipFromEventProperties:t=>$e(t)},$session_past_minimum_duration:{exposure:"event"},$session_recording_url_trigger_activated_session:{exposure:"event"},$session_recording_event_trigger_activated_session:{exposure:"event"},$debug_first_full_snapshot_timestamp:{exposure:"event"},$sess_rec_flush_size:{exposure:"hidden"},[Bt]:{exposure:"hidden",storageGroup:"flags"},[Us]:{exposure:"hidden",storageGroup:"flags"},[Rr]:{exposure:"hidden"},[Gn]:{exposure:"hidden",storageGroup:"flags"},[Hs]:{exposure:"hidden",storageGroup:"flags"},[Tr]:{exposure:"hidden",storageGroup:"flags",volatile:!0},[ei]:{exposure:"hidden",storageGroup:"flags"},[et]:{exposure:"hidden"},[jt]:{exposure:"hidden"},[ct]:{exposure:"hidden"},[Ut]:{exposure:"hidden"},[Kn]:{exposure:"hidden",storageGroup:"surveys"},[ti]:{exposure:"hidden",storageGroup:"surveys",volatile:!0},[Jn]:{exposure:"event"},[Nr]:{exposure:"hidden"},[Mr]:{exposure:"hidden"},[Ws]:{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"},[Wt]:{exposure:"hidden"},[zs]:{exposure:"hidden"},[Lr]:{exposure:"hidden"},[Gs]:{exposure:"hidden",storageGroup:"flags",volatile:!0},[He]:{exposure:"hidden"},[Yn]:{exposure:"hidden"},[Zn]:{exposure:"hidden"},[Xn]:{exposure:"hidden"},[Qn]:{exposure:"hidden"},[si]:{exposure:"hidden"},[ri]:{exposure:"hidden"},[cu]:{exposure:"event"},[uu]:{exposure:"event"},[du]:{exposure:"event"},[hu]:{exposure:"event"},[fu]:{exposure:"event"},[gu]:{exposure:"event"},[mu]:{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"}},Fp=[["$posthog_sr_group_event_trigger_",{exposure:"hidden"}],["$posthog_sr_group_url_trigger_",{exposure:"hidden"}],["$posthog_sr_group_sampling_",{exposure:"hidden"}]],Mt=t=>{var e=Cp[t];if(e)return e;for(var s of Fp){var r=s[1];if(t.indexOf(s[0])===0)return r}},us=(t,e)=>{try{return JSON.stringify(t,((s,r)=>typeof r=="bigint"?r.toString():r),e)}catch{return Fc(t)}},li=t=>{var e=C?.createElement("a");return x(e)?null:(e.href=t,e)},vs=function(t,e){for(var s,r=((t.split("#")[0]||"").split(/\?(.*)/)[1]||"").replace(/^\?+/g,"").split("&"),i=0;r.length>i;i++){var n=r[i].split("=");if(n[0]===e){s=n;break}}if(!L(s)||2>s.length)return"";var o=s[1];try{o=decodeURIComponent(o)}catch{k.error("Skipping decoding for malformed query param: "+o)}return o.replace(/\+/g," ")},ir=function(t,e,s){if(!t||!e||!e.length)return t;for(var r=t.split("#"),i=r[1],n=(r[0]||"").split("?"),o=n[1],a=n[0],l=(o||"").split("&"),u=[],c=0;l.length>c;c++){var d=l[c].split("=");L(d)&&(e.includes(d[0])?u.push(d[0]+"="+s):u.push(l[c]))}var h=a;return o!=null&&(h+="?"+u.join("&")),i!=null&&(h+="#"+i),h},ci=function(t,e){var s=t.match(new RegExp(e+"=([^&]*)"));return s?s[1]:null},Ru=(t,e)=>t>=e&&kc(),Tu=(t,e,s,r)=>{if(t===0){if(kc()){var i=e+1;return i===s&&r(),i}return e}return 0},kr="https?://(.*)",_s=["gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","irclid","_kx"],Pp=["utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid",..._s],nr="",Ap=["li_fat_id"];function Nu(t,e,s){if(!C)return{};var r,i=e?[..._s,...s||[]]:[],n=Mu(ir(C.URL,i,nr),t),o=(r={},Z(Ap,(function(a){var l=vu(a);r[a]=l||null})),r);return ee(o,n)}function Mu(t,e){var s=Pp.concat(e||[]),r={};return Z(s,(function(i){var n=vs(t,i);r[i]=n||null})),r}function Lu(t){var e=(function(n){return n?n.search(kr+"google.([^/?]*)")===0?"google":n.search(kr+"bing.com")===0?"bing":n.search(kr+"yahoo.com")===0?"yahoo":n.search(kr+"duckduckgo.com")===0?"duckduckgo":null:null})(t),s=e!="yahoo"?"q":"p",r={};if(!$e(e)){r.$search_engine=e;var i=C?vs(C.referrer,s):"";i.length&&(r.ph_keyword=i)}return r}function gl(){return navigator.language||navigator.userLanguage}var ui="$direct";function Ou(){return C?.referrer||ui}function Du(t,e,s){s===void 0&&(s=!1);var r=t?[..._s,...e||[]]:[],i=s?Ct(re?.href):re?.href,n=i?.substring(0,1e3);return{r:Ou().substring(0,1e3),u:n?ir(n,r,nr):void 0}}function Bu(t,e){var s;e===void 0&&(e=!1);var r=t.r,i=t.u,n=e?Ct(i):i,o={$referrer:r,$referring_domain:r==null?void 0:r==ui?ui:(s=li(r))==null?void 0:s.host};if(n){o.$current_url=n;var a=li(n);o.$host=a?.host,o.$pathname=a?.pathname;var l=Mu(n);ee(o,l)}if(r){var u=Lu(r);ee(o,u)}return o}function ju(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return}}function $p(){try{return new Date().getTimezoneOffset()}catch{return}}var Rp={flags:Gs,surveys:ti},Tp=["cookie","localstorage","localstorage+cookie","sessionstorage","memory"],ss="main";class cn{constructor(e,s,r){if(r===void 0&&(r=!0),this.ci={},this.fi=!1,this.pi=!1,this.Ne=e,this.gi=r,this.props={},this.mi=void 0,this.yi=(n=>{var o="";return n.token&&(o=n.token.replace(/\+/g,"PL").replace(/\//g,"SL").replace(/=/g,"EQ")),n.persistence_name?"ph_"+n.persistence_name:"ph_"+o+"_posthog"})(e),this.ii=this.bi(e),this.pi=this.wi(e),this.load(),e.debug&&k.info("Persistence loaded",e.persistence,w({},this.props)),this.update_config(e,e,s),this.save(),v){var i=()=>this.flush();ie(v,"beforeunload",i,{capture:!1}),ie(v,"pagehide",i,{capture:!1})}}ki(){var e,s=(e=this.Ne)==null?void 0:e.persistence_save_debounce_ms;return he(s)&&s>0?s:0}isDisabled(){return!!this.xi}bi(e){Tp.indexOf(e.persistence.toLowerCase())===-1&&(k.critical("Unknown persistence type "+e.persistence+"; falling back to localStorage+cookie"),e.persistence="localStorage+cookie");var s,r=(function(o,a){o===void 0&&(o=[]),a===void 0&&(a=!1);var l=[...dp,...o];return w({},Q,{H(u){try{var c={};try{c=pt.H(u)||{}}catch{}var d,h=JSON.parse(Q.P(u)||"{}");if(a){var p={};for(var f in c){var g=c[f];$e(g)||g===""||(p[f]=g)}d=ee(h,p)}else d=ee(c,h);return Q.F(u,d),d}catch{}return null},F(u,c,d,h,p,f){var g=Q.F(u,c,void 0,void 0,f);try{var m={};l.forEach((_=>{c[_]&&(m[_]=c[_])})),Object.keys(m).length&&pt.F(u,m,d,h,p,f)}catch(_){Q.j(_)}return g},q(u,c){try{v?.localStorage.removeItem(u),pt.q(u,c)}catch(d){Q.j(d)}}})})(e.cookie_persisted_properties||[],e.__preview_cookie_wins_on_conflict||!1),i=!1,n=e.persistence.toLowerCase();return n==="localstorage"&&Q.N()?(s=Q,i=!0):n==="localstorage+cookie"&&r.N()?(s=r,i=!0):n==="sessionstorage"&&ce.N()?s=ce:n==="memory"?s=hp:n==="cookie"?s=pt:r.N()?(s=r,i=!0):s=pt,this.fi=i,s}Si(e){return this.yi+"__"+e}wi(e){return this.fi&&!!e.split_storage}properties(){var e={};return Z(this.props,((s,r)=>{var i=Mt(r);if(!i||i.exposure==="event"){if(i!=null&&i.shouldSkipFromEventProperties!=null&&i.shouldSkipFromEventProperties(s))return;e[r]=s}})),e}load(){if(!this.xi){var e=this.ii.H(this.yi);e&&(this.props=ee({},e)),this.pi&&this.Ci()}}Ci(){for(var e of ln){var s=Q.H(this.Si(e));if(s&&!mt(s)){var r=this.Mi(e);r.persisted=!0,this.Ti(e)||(r.fingerprint=this.Ei(s,e)),this.Ii(e,s)||ee(this.props,s)}}}Ti(e){return Object.keys(this.props).some((s=>{var r;return((r=Mt(s))==null?void 0:r.storageGroup)===e}))}Ii(e,s){var r=Rp[e];if(!r)return!1;var i=s[r],n=this.props[r];return he(i)&&he(n)&&n>i}refreshKey(e){var s;if(!this.xi){var r=this.pi?(s=Mt(e))==null?void 0:s.storageGroup:void 0,i=r?Q.H(this.Si(r)):this.ii.H(this.yi);if(i&&e in i)this.Pi(e,i[e]);else{if(r){var n=this.ii.H(this.yi);if(n&&e in n)return void this.Pi(e,n[e])}this.Ri(e)}}}save(){if(!this.xi){var e=this.ki();e>0?x(this.Ai)&&(this.Ai=setTimeout((()=>{this.Ai=void 0,this.Fi()}),e)):this.Fi()}}flush(){x(this.Ai)||(clearTimeout(this.Ai),this.Ai=void 0,this.Fi())}Fi(){this.xi||(this.pi?this.Li():this.Oi(this.ii,this.yi,this.props,ss))}Li(){var e=this.Di(),s=e.main,r=e.groups;for(var i of(this.Oi(this.ii,this.yi,s,ss),ln)){var n,o=r[i];(!mt(o)||(n=this.ci[i])!=null&&n.persisted)&&this.Oi(Q,this.Si(i),o,i)}}Di(){var e={},s={flags:{},surveys:{}};return Z(this.props,((r,i)=>{var n,o=(n=Mt(i))==null?void 0:n.storageGroup;o?s[o][i]=r:e[i]=r})),{main:e,groups:s}}Ei(e,s){if(s===ss)return JSON.stringify(e)+"|"+this.$i+"|"+this.Ni+"|"+this.qi;var r={};return Z(e,((i,n)=>{var o;r[n]=(o=Mt(n))!=null&&o.volatile?"__volatile__":i})),JSON.stringify(r)}Oi(e,s,r,i){var n=this.Mi(i);if(i===ss||n.dirty||x(n.fingerprint)){var o;try{if((o=this.Ei(r,i))===n.fingerprint)return void(n.dirty=!1)}catch{o=void 0}e.F(s,r,this.$i,this.Ni,this.qi,this.Ne.debug)?(n.dirty=!1,i!==ss&&(n.persisted=!0),x(o)||(n.fingerprint=o)):this.Ne.debug&&k.warn('failed to persist storage entry "'+s+'"; will retry on next save')}}remove(e){var s=(e===void 0?{}:e).keepGroupEntries,r=s!==void 0&&s;if(x(this.Ai)||(clearTimeout(this.Ai),this.Ai=void 0),this.ii.q(this.yi,!1),this.ii.q(this.yi,!0),!r&&this.gi)for(var i of ln)Q.q(this.Si(i));r?delete this.ci[ss]:this.ci={}}clear(){this.remove(),this.props={}}register_once(e,s,r){if(te(e)){x(s)&&(s="None"),this.$i=x(r)?this.ji:r;var i=!1;if(Z(e,((n,o)=>{this.props.hasOwnProperty(o)&&this.props[o]!==s||(this.Pi(o,n),i=!0)})),i)return this.save(),!0}return!1}register(e,s){if(te(e)){this.$i=x(s)?this.ji:s;var r=!1;if(Z(e,((i,n)=>{e.hasOwnProperty(n)&&(this.props[n]!==i||te(i)||L(i))&&(this.Pi(n,i),r=!0)})),r)return this.save(),!0}return!1}unregister(e){var s=typeof e=="string"?[e]:e,r=!1;for(var i of s)i in this.props&&(this.Ri(i),r=!0);r&&this.save()}update_campaign_params(){var e=C?.URL;if(e!==this.mi){var s=Nu(this.Ne.custom_campaign_params,this.Ne.mask_personal_data_properties,this.Ne.custom_personal_data_properties);mt(zo(s))||this.register(s),this.mi=e}}update_search_keyword(){var e;this.register((e=C?.referrer)?Lu(e):{})}update_referrer_info(){var e;this.register_once({$referrer:Ou(),$referring_domain:C!=null&&C.referrer&&((e=li(C.referrer))==null?void 0:e.host)||ui},void 0)}set_initial_person_info(){this.props[Xn]||this.props[Qn]||this.register_once({[si]:Du(this.Ne.mask_personal_data_properties,this.Ne.custom_personal_data_properties,this.Ne.disable_capture_url_hashes)},void 0)}get_initial_props(){var e={};Z([Qn,Xn],(i=>{var n=this.props[i];n&&Z(n,(function(o,a){e["$initial_"+Tn(a)]=o}))}));var s=this.props[si];if(s){var r=(function(i,n){n===void 0&&(n=!1);var o=Bu(i,n),a={};return Z(o,(function(l,u){a["$initial_"+Tn(u)]=l})),a})(s,this.Ne.disable_capture_url_hashes);ee(e,r)}return e}safe_merge(e){return Z(this.props,(function(s,r){r in e||(e[r]=s)})),e}update_config(e,s,r){this.ji=this.$i=e.cookie_expiration,this.set_disabled(e.disable_persistence||!!r),this.set_cross_subdomain(e.cross_subdomain_cookie),this.set_secure(e.secure_cookie);var i=e.persistence!==s.persistence||!((l,u)=>{if(l.length!==u.length)return!1;var c=[...l].sort(),d=[...u].sort();return c.every(((h,p)=>h===d[p]))})(e.cookie_persisted_properties||[],s.cookie_persisted_properties||[]),n=i?this.bi(e):this.ii,o=this.wi(e);if(i||o!==this.pi){var a=this.props;this.clear(),this.ii=n,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,s){var r=this.props[js]||{};r[e]=s,this.Pi(js,r),this.save()}remove_event_timer(e){var s=this.props[js]||{},r=s[e];return x(r)||(delete s[e],this.Pi(js,s),this.save()),r}get_property(e){return this.props[e]}set_property(e,s){this.Pi(e,s),this.save()}Pi(e,s){var r;this.props[e]=s,(r=Mt(e))!=null&&r.volatile||this.Bi(e)}Ri(e){delete this.props[e],this.Bi(e)}Bi(e){var s,r=(s=Mt(e))==null?void 0:s.storageGroup;r&&(this.Mi(r).dirty=!0)}Mi(e){return this.ci[e]||(this.ci[e]={})}}function Ir(t){var e=!0;return{dispose(){if(e){e=!1;var s=t();s&&Se(s.then)&&s.then(void 0,(()=>{}))}}}}var xe={GZipJS:"gzip-js",Base64:"base64"},As={Activation:"events",Cancellation:"cancelEvents"},un={Popover:"popover",API:"api",Widget:"widget"},ft={SHOWN:"survey shown",DISMISSED:"survey dismissed",SENT:"survey sent"},dn={SURVEY_ID:"$survey_id",SURVEY_ITERATION:"$survey_iteration",SURVEY_LAST_SEEN_DATE:"$survey_last_seen_date"},io={Popover:"popover",Inline:"inline"},Np={SHOWN:"product tour shown"},ml={TOUR_LAST_SEEN_DATE:"$product_tour_last_seen_date",TOUR_TYPE:"$product_tour_type"},vl=se("[RateLimiter]");class Mp{constructor(e){this.serverLimits={},this.lastEventRateLimited=!1,this.checkForLimiting=s=>{var r=s.text;if(r&&r.length)try{(JSON.parse(r).quota_limited||[]).forEach((i=>{vl.info((i||"events")+" is quota limited."),this.serverLimits[i]=new Date().getTime()+6e4}))}catch(i){return void vl.warn('could not rate limit - continuing. Error: "'+i?.message+'"',{text:r})}},this.instance=e,this.lastEventRateLimited=this.clientRateLimitContext(!0).isRateLimited}get captureEventsPerSecond(){var e;return((e=this.instance.config.rate_limiting)==null?void 0:e.events_per_second)||10}get captureEventsBurstLimit(){var e;return Math.max(((e=this.instance.config.rate_limiting)==null?void 0:e.events_burst_limit)||10*this.captureEventsPerSecond,this.captureEventsPerSecond)}clientRateLimitContext(e){var s,r,i;e===void 0&&(e=!1);var n=this.captureEventsBurstLimit,o=this.captureEventsPerSecond,a=new Date().getTime(),l=(s=(r=this.instance.persistence)==null?void 0:r.get_property(Zn))!==null&&s!==void 0?s:{tokens:n,last:a};l.tokens+=(a-l.last)/1e3*o,l.last=a,l.tokens>n&&(l.tokens=n);var u=1>l.tokens;if(u||e||(l.tokens=Math.max(0,l.tokens-1)),u&&!e){var c=(he(l.dropped)?l.dropped:0)+1;l.dropped=c,!this.lastEventRateLimited&&this.Hi(c)&&(l.dropped=0)}return this.lastEventRateLimited=u,(i=this.instance.persistence)==null||i.set_property(Zn,l),{isRateLimited:u,remainingTokens:l.tokens}}Ui(e){var s=this.instance.config.property_denylist;return!L(s)||!s.includes(e)}zi(){var e;if(this.Ui("$current_url")&&this.Ui("$pathname")&&re!=null&&re.pathname)return""+((e=re.origin)!==null&&e!==void 0?e:"")+re.pathname}Hi(e){var s,r,i=this.captureEventsBurstLimit,n=this.captureEventsPerSecond,o=this.zi(),a=this.Ui("$session_id")?(s=(r=this.instance).get_session_id)==null?void 0:s.call(r):void 0,l=[e+" event(s) dropped since the last warning",o?"triggered on "+o:void 0,a?"session "+a:void 0].filter(Boolean).join(", ");return!!this.instance.capture("$$client_ingestion_warning",{$$client_ingestion_warning_message:"posthog-js client rate limited: "+l+". Config is set to "+n+" events per second and "+i+" events burst limit."},{skip_client_rate_limiting:!0})}isServerRateLimited(e){var s=this.serverLimits[e||"events"]||!1;return s!==!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 xt.info("Using preloaded remote config",this.remoteConfig),this.Zi(this.remoteConfig),void this.Gi();if(this._instance.Qi())return void xt.warn("Remote config is disabled. Falling back to local config.");this.Wi((e=>{if(!e)return xt.info("No config found after loading remote JS config. Falling back to JSON."),void this.Vi((s=>{this.Zi(s.json,s),this.Gi()}));this.Zi(e),this.Gi()}))}catch(e){xt.error("Error loading remote config",e),this.Zi()}}stop(){this.Ki&&(clearInterval(this.Ki),this.Ki=void 0)}refresh(){!this._instance.Qi()&&C&&C.visibilityState!=="hidden"&&this._instance.reloadFeatureFlags()}Gi(){var e;if(!this.Ki){var s=(e=this._instance.config.remote_config_refresh_interval_ms)!==null&&e!==void 0?e:3e5;s!==0&&(this.Ki=setInterval((()=>{this.refresh()}),s))}}Zi(e,s){!e&&s&&(s.statusCode===0?s.error||xt.warn("Failed to fetch remote config from PostHog."):xt.error("Failed to fetch remote config from PostHog."));try{this._instance.Zi(e?{ok:!0,config:e}:{ok:!1})}catch(i){xt.error("Error applying remote config",i)}if(e?.hasFeatureFlags!==!1&&!this._instance.config.advanced_disable_feature_flags_on_first_load)try{var r;(r=this._instance.featureFlags)==null||r.ensureFlagsLoaded()}catch(i){xt.error("Error loading feature flags",i)}}}var qe=Uint8Array,Ae=Uint16Array,ys=Uint32Array,Ko=new qe([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),Jo=new qe([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),_l=new qe([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Hu=function(t,e){for(var s=new Ae(31),r=0;31>r;++r)s[r]=e+=1<r;++r)for(var n=s[r];s[r+1]>n;++n)i[n]=n-s[r]<<5|r;return[s,i]},Wu=Hu(Ko,2),no=Wu[1];Wu[0][28]=258,no[258]=28;for(var yl=Hu(Jo,0)[1],zu=new Ae(32768),ne=0;32768>ne;++ne){var rs=(43690&ne)>>>1|(21845&ne)<<1;zu[ne]=((65280&(rs=(61680&(rs=(52428&rs)>>>2|(13107&rs)<<2))>>>4|(3855&rs)<<4))>>>8|(255&rs)<<8)>>>1}var Js=function(t,e,s){for(var r=t.length,i=0,n=new Ae(e);r>i;++i)++n[t[i]-1];var o,a=new Ae(e);for(i=0;e>i;++i)a[i]=a[i-1]+n[i-1]<<1;for(o=new Ae(r),i=0;r>i;++i)o[i]=zu[a[t[i]-1]++]>>>15-t[i];return o},Jt=new qe(288);for(ne=0;144>ne;++ne)Jt[ne]=8;for(ne=144;256>ne;++ne)Jt[ne]=9;for(ne=256;280>ne;++ne)Jt[ne]=7;for(ne=280;288>ne;++ne)Jt[ne]=8;var di=new qe(32);for(ne=0;32>ne;++ne)di[ne]=5;var Lp=Js(Jt,9),Op=Js(di,5),qu=function(t){return(t/8>>0)+(7&t&&1)},Vu=function(t,e,s){(s==null||s>t.length)&&(s=t.length);var r=new(t instanceof Ae?Ae:t instanceof ys?ys:qe)(s-e);return r.set(t.subarray(e,s)),r},ot=function(t,e,s){var r=e/8>>0;t[r]|=s<<=7&e,t[r+1]|=s>>>8},$s=function(t,e,s){var r=e/8>>0;t[r]|=s<<=7&e,t[r+1]|=s>>>8,t[r+2]|=s>>>16},hn=function(t,e){for(var s=[],r=0;t.length>r;++r)t[r]&&s.push({s:r,f:t[r]});var i=s.length,n=s.slice();if(!i)return[new qe(0),0];if(i==1){var o=new qe(s[0].s+1);return o[s[0].s]=1,[o,1]}s.sort((function(F,P){return F.f-P.f})),s.push({s:-1,f:25001});var a=s[0],l=s[1],u=0,c=1,d=2;for(s[0]={s:-1,f:a.f+l.f,l:a,r:l};c!=i-1;)a=s[s[d].f>s[u].f?u++:d++],l=s[u!=c&&s[d].f>s[u].f?u++:d++],s[c++]={s:-1,f:a.f+l.f,l:a,r:l};var h=n[0].s;for(r=1;i>r;++r)n[r].s>h&&(h=n[r].s);var p=new Ae(h+1),f=oo(s[c-1],p,0);if(f>e){r=0;var g=0,m=f-e,_=1<r;++r){var E=n[r].s;if(e>=p[E])break;g+=_-(1<>>=m;g>0;){var b=n[r].s;e>p[b]?g-=1<=0&&g;--r){var I=n[r].s;p[I]==e&&(--p[I],++g)}f=e}return[new qe(p),f]},oo=function(t,e,s){return t.s==-1?Math.max(oo(t.l,e,s+1),oo(t.r,e,s+1)):e[t.s]=s},wl=function(t){for(var e=t.length;e&&!t[--e];);for(var s=new Ae(++e),r=0,i=t[0],n=1,o=function(l){s[r++]=l},a=1;e>=a;++a)if(t[a]==i&&a!=e)++n;else{if(!i&&n>2){for(;n>138;n-=138)o(32754);n>2&&(o(n>10?n-11<<5|28690:n-3<<5|12305),n=0)}else if(n>3){for(o(i),--n;n>6;n-=6)o(8304);n>2&&(o(n-3<<5|8208),n=0)}for(;n--;)o(i);n=1,i=t[a]}return[s.subarray(0,r),e]},Rs=function(t,e){for(var s=0,r=0;e.length>r;++r)s+=t[r]*e[r];return s},ao=function(t,e,s){var r=s.length,i=qu(e+2);t[i]=255&r,t[i+1]=r>>>8,t[i+2]=255^t[i],t[i+3]=255^t[i+1];for(var n=0;r>n;++n)t[i+n+4]=s[n];return 8*(i+4+r)},bl=function(t,e,s,r,i,n,o,a,l,u,c){ot(e,c++,s),++i[256];for(var d=hn(i,15),h=d[0],p=d[1],f=hn(n,15),g=f[0],m=f[1],_=wl(h),E=_[0],b=_[1],I=wl(g),F=I[0],P=I[1],B=new Ae(19),S=0;E.length>S;++S)B[31&E[S]]++;for(S=0;F.length>S;++S)B[31&F[S]]++;for(var A=hn(B,7),R=A[0],N=A[1],T=19;T>4&&!R[_l[T-1]];--T);var O,J,z,H,oe=u+5<<3,pe=Rs(i,Jt)+Rs(n,di)+o,Ie=Rs(i,h)+Rs(n,g)+o+14+3*T+Rs(B,R)+(2*B[16]+3*B[17]+7*B[18]);if(pe>=oe&&Ie>=oe)return ao(e,c,t.subarray(l,l+u));if(ot(e,c,1+(pe>Ie)),c+=2,pe>Ie){O=Js(h,p),J=h,z=Js(g,m),H=g;var _e=Js(R,N);for(ot(e,c,b-257),ot(e,c+5,P-1),ot(e,c+10,T-4),c+=14,S=0;T>S;++S)ot(e,c+3*S,R[_l[S]]);c+=3*T;for(var Ce=[E,F],Re=0;2>Re;++Re){var ae=Ce[Re];for(S=0;ae.length>S;++S)ot(e,c,_e[me=31&ae[S]]),c+=R[me],me>15&&(ot(e,c,ae[S]>>>5&127),c+=ae[S]>>>12)}}else O=Lp,J=Jt,z=Op,H=di;for(S=0;a>S;++S)if(r[S]>255){var me;$s(e,c,O[257+(me=r[S]>>>18&31)]),c+=J[me+257],me>7&&(ot(e,c,r[S]>>>23&31),c+=Ko[me]);var ge=31&r[S];$s(e,c,z[ge]),c+=H[ge],ge>3&&($s(e,c,r[S]>>>5&8191),c+=Jo[ge])}else $s(e,c,O[r[S]]),c+=J[r[S]];return $s(e,c,O[256]),c+J[256]},Dp=new ys([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),Bp=(function(){for(var t=new ys(256),e=0;256>e;++e){for(var s=e,r=9;--r;)s=(1&s&&3988292384)^s>>>1;t[e]=s}return t})(),pn=function(t,e,s){for(;s;++e)t[e]=s,s>>>=8};function jp(t,e){e===void 0&&(e={});var s=(function(){var d=4294967295;return{p(h){for(var p=d,f=0;h.length>f;++f)p=Bp[255&p^h[f]]^p>>>8;d=p},d(){return 4294967295^d}}})(),r=t.length;s.p(t);var i,n,o,a,l,u=(a=10+((i=e).filename&&i.filename.length+1||0),l=8,(function(d,h,p,f,g,m){var _=d.length,E=new qe(f+_+5*(1+Math.floor(_/7e3))+g),b=E.subarray(f,E.length-g),I=0;if(!h||8>_)for(var F=0;_>=F;F+=65535){var P=F+65535;_>P?I=ao(b,I,d.subarray(F,P)):(b[F]=!0,I=ao(b,I,d.subarray(F,_)))}else{for(var B=Dp[h-1],S=B>>>13,A=8191&B,R=(1<F;++F){var me=z(F),ge=32767&F,Ye=T[me];if(N[ge]=Ye,T[me]=ge,F>=Re){var Rt=_-F;if((Ie>7e3||Ce>24576)&&Rt>423){I=bl(d,b,0,H,oe,pe,_e,Ce,ae,F-ae,I),Ce=Ie=_e=0,ae=F;for(var de=0;286>de;++de)oe[de]=0;for(de=0;30>de;++de)pe[de]=0}var Ve=2,St=0,ks=A,Be=ge-Ye&32767;if(Rt>2&&me==z(F-Be))for(var Fe=Math.min(S,Rt)-1,mr=Math.min(32767,F),vr=Math.min(258,Rt);mr>=Be&&--ks&&ge!=Ye;){if(d[F+Ve]==d[F+Ve-Be]){for(var je=0;vr>je&&d[F+je]==d[F+je-Be];++je);if(je>Ve){if(Ve=je,St=Be,je>Fe)break;var _r=Math.min(Be,je-2),Qt=0;for(de=0;_r>de;++de){var es=F-Be+de+32768&32767,Is=es-N[es]+32768&32767;Is>Qt&&(Qt=Is,Ye=es)}}}Be+=(ge=Ye)-(Ye=N[ge])+32768&32767}if(St){H[Ce++]=268435456|no[Ve]<<18|yl[St];var Ta=31&no[Ve],Na=31&yl[St];_e+=Ko[Ta]+Jo[Na],++oe[257+Ta],++pe[Na],Re=F+Ve,++Ie}else H[Ce++]=d[F],++oe[d[F]]}}I=bl(d,b,!0,H,oe,pe,_e,Ce,ae,F-ae,I)}return Vu(E,0,f+qu(I)+g)})(n=t,(o=e).level==null?6:o.level,o.mem==null?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(n.length)))):12+o.mem,a,l)),c=u.length;return(function(d,h){var p=h.filename;if(d[0]=31,d[1]=139,d[2]=8,d[8]=2>h.level?4:h.level==9?2:0,d[9]=3,h.mtime!=0&&pn(d,4,Math.floor(new Date(h.mtime||Date.now())/1e3)),p){d[3]=8;for(var f=0;p.length>=f;++f)d[f+10]=p.charCodeAt(f)}})(u,e),pn(u,c-8,s.d()),pn(u,c-4,r),u}var Up=!!An||!!To,Gu="text/plain",Dr=!1,Ku=(t,e)=>{var s=t.split("#"),r=s[1],i=s[0].split("?"),n=i[0],o=i[1];if(!o)return t;var a=o.split("&").filter((l=>l.split("=")[0]!==e)).join("&");return n+(a?"?"+a:"")+(r?"#"+r:"")},Ai=function(t,e,s){var r;s===void 0&&(s=!0);var i=t.split("?"),n=i[0],o=i[1],a=w({},e),l=(r=o?.split("&").map((c=>{var d,h=c.split("="),p=h[0],f=s&&(d=a[p])!==null&&d!==void 0?d:h[1];return delete a[p],p+"="+f})))!==null&&r!==void 0?r:[],u=(function(c,d){var h,p;d===void 0&&(d="&");var f=[];return Z(c,(function(g,m){x(g)||x(m)||m==="undefined"||(h=encodeURIComponent((_=>_ instanceof File)(g)?g.name:g.toString()),p=encodeURIComponent(m),f[f.length]=p+"="+h)})),f.join(d)})(a);return u&&l.push(u),l.length>0?n+"?"+l.join("&"):n},fn=t=>{if(t.Ji)return t.Ji;var e=t.data,s=t.compression;if(e){if(s===xe.GZipJS){var r=jp((function(a,l){var u=a.length;if(typeof TextEncoder<"u")return new TextEncoder().encode(a);for(var c=new qe(a.length+(a.length>>>1)),d=0,h=function(m){c[d++]=m},p=0;u>p;++p){if(d+5>c.length){var f=new qe(d+8+(u-p<<1));f.set(c),c=f}var g=a.charCodeAt(p);128>g?h(g):2048>g?(h(192|g>>>6),h(128|63&g)):g>55295&&57344>g?(h(240|(g=65536+(1047552&g)|1023&a.charCodeAt(++p))>>>18),h(128|g>>>12&63),h(128|g>>>6&63),h(128|63&g)):(h(224|g>>>12),h(128|g>>>6&63),h(128|63&g))}return Vu(c,0,d)})(us(e)),{mtime:0});return{contentType:Gu,body:r.buffer.slice(r.byteOffset,r.byteOffset+r.byteLength),estimatedSize:r.byteLength}}if(s===xe.Base64){var i=(function(a){return a&&btoa(encodeURIComponent(a).replace(/%([0-9A-F]{2})/g,((l,u)=>String.fromCharCode(parseInt(u,16)))))})(us(e)),n=(a=>"data="+encodeURIComponent(typeof a=="string"?a:us(a)))(i);return{contentType:"application/x-www-form-urlencoded",body:n,estimatedSize:new Blob([n]).size}}var o=us(e);return{contentType:"application/json",body:o,estimatedSize:new Blob([o]).size}}},Ju=t=>{var e,s,r=()=>t.transport==="sendBeacon"?{url:Ai(t.url,{compression:xe.Base64}),encodedBody:fn(w({},t,{compression:xe.Base64,Ji:void 0}))}:{url:Ku(t.url,"compression"),encodedBody:fn(w({},t,{compression:void 0,Ji:void 0}))};try{e=fn(t)}catch(i){if(Ua(t.compression,vs(t.url,"compression")))return k.error("Failed to gzip request body, sending uncompressed payload",i),r();throw i}return e&&Ua(t.compression,vs(t.url,"compression"))&&!((s=e.body)instanceof ArrayBuffer?$n(new Uint8Array(s)):ArrayBuffer.isView(s)&&$n(new Uint8Array(s.buffer,s.byteOffset,s.byteLength)))?(Dr=!0,r()):{url:t.url,encodedBody:e}},Yu=t=>{try{return Ju(t)}catch(e){return k.error(e),void(t.callback==null||t.callback({statusCode:0,error:e}))}},Hp=(function(){var t=X((function*(e){var s=us(e.data),r=yield(function(n,o,a){return Rn.apply(this,arguments)})(s,Y.DEBUG,{rethrow:!0});if(!r)return e;var i=yield r.arrayBuffer();return w({},e,{Ji:{contentType:Gu,body:i,estimatedSize:i.byteLength}})}));return function(e){return t.apply(this,arguments)}})(),Wp=/Failed to fetch|NetworkError|Load failed/i,Zu=t=>t?.name==="TypeError"&&Wp.test(t?.message||""),Xu=t=>{var e=Yu(t);if(e){var s=e.url,r=e.encodedBody,i=r??{},n=i.contentType,o=i.body,a=i.estimatedSize,l=new Headers;Z(t.headers,(function(f,g){l.append(g,f)})),n&&l.append("Content-Type",n);var u=null,c=!1;if(Ma){var d=new Ma;u={signal:d.signal,timeout:setTimeout((()=>{var f,g;c=!0,d.abort((f=t.timeout,(g=new Error("PostHog request timed out"+(f?" after "+f+"ms":""))).name="AbortError",g))}),t.timeout)}}var h=f=>{c&&f?.name==="AbortError"||Zu(f)?k.warn(f):k.error(f),t.callback==null||t.callback({statusCode:0,error:f})};try{var p;To(s,w({method:t?.method||"GET",headers:l,keepalive:t.method==="POST"&&!t.Yi&&52428.8>(a||0),body:o,signal:(p=u)==null?void 0:p.signal},t.fetchOptions)).then((f=>f.text().then((g=>{var m={statusCode:f.status,text:g};if(f.status===200)try{m.json=JSON.parse(g)}catch(_){k.error(_)}t.callback==null||t.callback(m)})))).catch(h).finally((()=>u?clearTimeout(u.timeout):null))}catch(f){u&&clearTimeout(u.timeout),h(f)}}},lo=t=>{try{var e,s=Ju(t),r=s.url,i=s.encodedBody,n=i??{},o=n.body,a=n.estimatedSize;if(!o)return;var l=o instanceof Blob?o:new Blob([o],{type:n.contentType});if(ke.sendBeacon(r,l))return;var u=L(t.data)?t.data:(e=t.data)==null?void 0:e.batch;if(L(u)&&u.length>1&&(a??0)>16384){var c=Math.ceil(u.length/2),d=h=>L(t.data)?h:w({},t.data,{batch:h});return lo(w({},t,{data:d(u.slice(0,c))})),void lo(w({},t,{data:d(u.slice(c))}))}k.warn("Beacon of ~"+(a??0)+" bytes was rejected by the browser, falling back to fetch"),Xu(w({},t,{Yi:!0}))}catch(h){k.warn("Beacon send failed",h)}},El=(t,e,s,r)=>{var i=r==="query"?e==="POST"?"sent_at":"_":void 0;return Ai(s===xe.GZipJS?Ku(t,"compression"):t,w({},i?{[i]:Date.now().toString()}:{},s===xe.GZipJS?{}:{compression:s}))},Br=[];To&&Br.push({transport:"fetch",method:Xu}),An&&Br.push({transport:"XHR",method(t){var e=Yu(t);if(e){var s=new An,r=e.encodedBody;s.open(t.method||"GET",e.url,!0);var i=r??{},n=i.contentType,o=i.body;Z(t.headers,(function(a,l){s.setRequestHeader(l,a)})),n&&s.setRequestHeader("Content-Type",n),t.timeout&&(s.timeout=t.timeout),s.onreadystatechange=()=>{if(s.readyState===4){var a={statusCode:s.status,text:s.responseText};if(s.status===200)try{a.json=JSON.parse(s.responseText)}catch{}t.callback==null||t.callback(a)}},s.send(o)}}}),ke!=null&&ke.sendBeacon&&Br.push({transport:"sendBeacon",method:lo});var co=3e3;class zp{constructor(e,s){this.Xi=!0,this.tr=[],this.er=rt(s?.flush_interval_ms||co,250,5e3,k.createLogger("flush interval"),co),this.ir=e}enqueue(e){this.tr.push(e),this.rr||this.nr()}unload(){this.sr();var e=this.tr.length>0?this.ar():{},s=Object.values(e);[...s.filter((r=>r.url.indexOf("/e")===0)),...s.filter((r=>r.url.indexOf("/e")!==0))].map((r=>{this.lr(w({},r,{transport:"sendBeacon"}))}))}enable(){this.Xi=!1,this.nr()}nr(){var e=this;this.Xi||(this.rr=setTimeout((()=>{if(this.sr(),this.tr.length>0){var s=this.ar(),r=function(){var n=s[i],o=new Date().getTime();n.data&&L(n.data)&&Z(n.data,(a=>{a.offset=Math.abs(a.timestamp-o),delete a.timestamp})),e.lr(n)};for(var i in s)r()}}),this.er))}lr(e){try{this.ir(e)}catch(s){k.error(s)}}sr(){clearTimeout(this.rr),this.rr=void 0}ar(){var e={};return Z(this.tr,(s=>{var r,i=s,n=(i?i.batchKey:null)||i.url;x(e[n])&&(e[n]=w({},i,{data:[]})),(r=e[n].data)==null||r.push(i.data)})),this.tr=[],e}}var qp=["retriesPerformedSoFar"];class Vp{constructor(e){this.ur=!1,this.hr=3e3,this.tr=[],this._instance=e,this.tr=[],this.dr=!0,!x(v)&&"onLine"in v.navigator&&(this.dr=v.navigator.onLine,this.vr=()=>{this.dr=!0,this.cr()},this.pr=()=>{this.dr=!1},ie(v,"online",this.vr),ie(v,"offline",this.pr))}get length(){return this.tr.length}retriableRequest(e){var s=e.retriesPerformedSoFar,r=Ic(e,qp);lt(s)&&(r.url=Ai(r.url,{retry_count:s})),this._instance._send_request(w({},r,{callback:i=>{if(i.statusCode!==200&&(400>i.statusCode||i.statusCode>=500)){if((i.statusCode===0?3:10)>(s??0))return void this.At(w({retriesPerformedSoFar:s},r));i.statusCode===0&&k.warn("Request failed before receiving an HTTP response; this can happen due to network issues, CORS, browser blocking, or ad blockers. Stopped retrying after "+(s??0)+" retries.")}r.callback==null||r.callback(i)}}))}At(e){var s=e.retriesPerformedSoFar||0;e.retriesPerformedSoFar=s+1;var r=(function(o){var a=3e3*Math.pow(2,o),l=a/2,u=Math.min(18e5,a),c=Math.random()-.5;return Math.ceil(u+c*(u-l))})(s),i=Date.now()+r;this.tr.push({retryAt:i,requestOptions:e});var n="Enqueued failed request for retry in "+r;navigator.onLine||(n+=" (Browser is offline)"),k.warn(n),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(),s=[],r=this.tr.filter((n=>e>n.retryAt||(s.push(n),!1)));if(this.tr=s,r.length>0)for(var i of r)this.retriableRequest(i.requestOptions)}unload(){for(var e of(this.mr&&(clearTimeout(this.mr),this.mr=void 0),this.ur=!1,x(v)||(this.vr&&(v.removeEventListener("online",this.vr),this.vr=void 0),this.pr&&(v.removeEventListener("offline",this.pr),this.pr=void 0)),this.tr)){var s=e.requestOptions;try{this._instance._send_request(w({},s,{transport:"sendBeacon"}))}catch(r){k.error(r)}}this.tr=[]}}class Gp{constructor(e){this.yr=()=>{var s,r,i,n;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,(s=this.br.maxScrollY)!==null&&s!==void 0?s:0),this.br.maxScrollHeight=Math.max(l,(r=this.br.maxScrollHeight)!==null&&r!==void 0?r:0),this.br.lastContentY=u,this.br.maxContentY=Math.max(u,(i=this.br.maxContentY)!==null&&i!==void 0?i:0),this.br.maxContentHeight=Math.max(c,(n=this.br.maxContentHeight)!==null&&n!==void 0?n:0)},this._instance=e}get _r(){return this._instance.config.scroll_root_selector}getContext(){return this.br}resetContext(){var e=this.br;return setTimeout(this.yr,0),e}startMeasuringScrollPosition(){ie(v,"scroll",this.yr,{capture:!0}),ie(v,"scrollend",this.yr,{capture:!0}),ie(v,"resize",this.yr)}scrollElement(){if(!this._r)return v?.document.documentElement;var e=L(this._r)?this._r:[this._r];for(var s of e){var r=v?.document.querySelector(s);if(r)return r}}wr(e){var s=e==="y"?"scrollTop":"scrollLeft";if(this._r){var r=this.scrollElement();return r&&r[s]||0}return v?e==="y"?v.scrollY||v.pageYOffset||v.document.documentElement.scrollTop||0:v.scrollX||v.pageXOffset||v.document.documentElement.scrollLeft||0:0}scrollY(){return this.wr("y")}scrollX(){return this.wr("x")}}var Kp=t=>Du(t?.config.mask_personal_data_properties,t?.config.custom_personal_data_properties,t?.config.disable_capture_url_hashes);class Sl{constructor(e,s,r,i){this.kr=n=>{var o=this.Sr();if(!o||o.sessionId!==n){var a={sessionId:n,props:this.Cr(this._instance)};this.Mr.register({[Yn]:a})}},this._instance=e,this.Tr=s,this.Mr=r,this.Cr=i||Kp,this.Tr.onSessionId(this.kr)}Sr(){return this.Mr.props[Yn]}getSetOnceProps(){var e,s=(e=this.Sr())==null?void 0:e.props;return s?"r"in s?Bu(s,this._instance.config.disable_capture_url_hashes):{$referring_domain:s.referringDomain,$pathname:s.initialPathName,utm_source:s.utm_source,utm_campaign:s.utm_campaign,utm_medium:s.utm_medium,utm_content:s.utm_content,utm_term:s.utm_term}:{}}getSessionProps(){var e={};return Z(zo(this.getSetOnceProps()),((s,r)=>{r==="$current_url"&&(r="url"),e["$session_entry_"+Tn(r)]=s})),e}}class Yo{on(e,s){return this.Er[e]||(this.Er[e]=[]),this.Er[e].push(s),()=>{this.Er[e]=this.Er[e].filter((r=>r!==s))}}emit(e,s){for(var r of this.Er[e]||[])r(s);for(var i of this.Er["*"]||[])i(e,s)}constructor(){this.Er={}}}var Ts=se("[SessionId]");class xl{on(e,s){return this.Ir.on(e,s)}constructor(e,s,r){var i;if(this.Pr=null,this.Rr=[],this.Ar=void 0,this.Fr=!1,this.Ir=new Yo,this.Lr=(u,c)=>!(!lt(u)||!lt(c))&&Math.abs(u-c)>this.sessionTimeoutMs,!e.persistence)throw new Error("SessionIdManager requires a PostHogPersistence instance");if(e.config.cookieless_mode===ht)throw new Error('SessionIdManager cannot be used with cookieless_mode="always"');this.Ne=e.config,this.Mr=e.persistence,this.Or=void 0,this.Dr=void 0,this._sessionStartTimestamp=null,this._sessionActivityTimestamp=null,this.$r=s||dt,this.Nr=r||dt;var n=this.Ne.persistence_name||this.Ne.token;if(this._sessionTimeoutMs=1e3*rt(this.Ne.session_idle_timeout_seconds||1800,60,36e3,Ts.createLogger("session_idle_timeout_seconds"),1800),e.register({$configured_session_timeout_ms:this._sessionTimeoutMs}),this.qr(),this.jr="ph_"+n+"_window_id",this.Br="ph_"+n+"_primary_window_exists",this.Hr()){var o=ce.H(this.jr),a=ce.H(this.Br);o&&!a?this.Or=o:ce.q(this.jr),ce.F(this.Br,!0)}if((i=this.Ne.bootstrap)!=null&&i.sessionID)try{var l=(u=>{var c=this.Ne.bootstrap.sessionID.replace(/-/g,"");if(c.length!==32)throw new Error("Not a valid UUID");if(c[12]!=="7")throw new Error("Not a UUIDv7");return parseInt(c.substring(0,12),16)})();this.Ur(this.Ne.bootstrap.sessionID,new Date().getTime(),l)}catch(u){Ts.error("Invalid sessionID in bootstrap",u)}this.zr()}get sessionTimeoutMs(){return this._sessionTimeoutMs}onSessionId(e){return x(this.Rr)&&(this.Rr=[]),this.Rr.push(e),this.Dr&&e(this.Dr,this.Or),()=>{this.Rr=this.Rr.filter((s=>s!==e))}}Hr(){return this.Ne.persistence!=="memory"&&!this.Mr.xi&&ce.N()}Wr(e){e!==this.Or&&(this.Or=e,this.Hr()&&ce.F(this.jr,e))}Vr(){return this.Or?this.Or:this.Hr()?ce.H(this.jr):null}Zr(e){var s=this.Pr;return!$e(s)&&!$e(e)&&5e3>Math.abs(e-s)}Ur(e,s,r){var i=s!==this._sessionActivityTimestamp,n=!(e!==this.Dr||r!==this._sessionStartTimestamp);this._sessionStartTimestamp=r,this._sessionActivityTimestamp=s,this.Dr=e,n&&!i||n&&this.Zr(s)||(this.Pr=s,this.Mr.register({[cs]:[s,e,r]}))}Gr(){var e,s=(e=this.Ne)==null?void 0:e.persistence_save_debounce_ms;return lt(s)&&s>0}Qr(){this.Gr()?this.Mr.refreshKey(cs):(this.Mr.flush(),this.Mr.load())}Kr(){var e;if(!$e(this._sessionActivityTimestamp)&&this._sessionActivityTimestamp!==this.Pr){this.Qr();var s=this.Jr();s[1]===this.Dr&&s[2]===this._sessionStartTimestamp&&(this.Pr=this._sessionActivityTimestamp,this.Mr.register({[cs]:[this._sessionActivityTimestamp,(e=this.Dr)!==null&&e!==void 0?e:null,this._sessionStartTimestamp]}),this.Mr.flush())}}Yr(){var e=this.Jr()[0],s=lt(e)?e:0,r=lt(this._sessionActivityTimestamp)?this._sessionActivityTimestamp:0;return Math.max(s,r)}Xr(e){return this.Qr(),this.Lr(e,this.Yr())}Jr(){var e=this.Mr.props[cs];return L(e)&&e.length===2&&e.push(e[0]),e||[0,null,0]}resetSessionId(){this.Pr=null,clearTimeout(this.tn),this.tn=void 0,this.Ur(null,null,null)}destroy(){this.Fr=!0,this.Kr(),clearTimeout(this.tn),this.tn=void 0,this.Ar&&v&&(v.removeEventListener(ni,this.Ar,{capture:!1}),this.Ar=void 0),this.Rr=[]}zr(){this.Ar=()=>{this.Kr(),this.Hr()&&ce.q(this.Br)},ie(v,ni,this.Ar,{capture:!1})}checkAndGetSessionAndWindowId(e,s){if(e===void 0&&(e=!1),s===void 0&&(s=null),this.Ne.cookieless_mode===ht)throw new Error('checkAndGetSessionAndWindowId should not be called with cookieless_mode="always"');var r=s||new Date().getTime(),i=this.Jr(),n=i[1],o=i[2],a=this.Yr(),l=this.Vr(),u=lt(o)&&Math.abs(r-o)>864e5,c=!1,d=!1,h=!n,p=n,f=!h&&!e&&this.Lr(r,a);if(f){(f=this.Xr(r))||Ts.info("cross-tab refresh kept the session alive",{sessionId:n});var g=this.Jr();n=g[1],o=g[2]}h||f||u?(n=this.$r(),l=this.Nr(),Ts.info("new session ID generated",{sessionId:n,windowId:l,changeReason:{noSessionId:h,activityTimeout:f,sessionPastMaximumLength:u}}),o=r,c=!0):(l||(l=this.Nr(),c=!0),(d=n!==p)&&(Ts.info("adopted cross-tab session id",{sessionId:n,windowId:l}),c=!0));var m=lt(a)&&e&&!u?a:r,_=lt(o)?o:new Date().getTime();this.Wr(l),this.Ur(n,m,_),e||this.qr();var E={noSessionId:h,activityTimeout:f,sessionPastMaximumLength:u,crossTabAdoption:d};return c&&this.Rr.forEach((b=>b(n,l,E))),{sessionId:n,windowId:l,sessionStartTimestamp:_,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 Qu=function(t,e){if(!t)return!1;var s=t.userAgent;if(s&&Wa(s,e))return!0;try{var r=t?.userAgentData;if(r!=null&&r.brands&&r.brands.some((i=>Wa(i?.brand,e))))return!0}catch{}return!!t.webdriver};function ed(){return(ed=X((function*(){var t=ke?.userAgentData;if(t!=null&&t.getHighEntropyValues)try{var e=yield t.getHighEntropyValues(["model"]),s=e?.model;return W(s)&&s.length>0?s:void 0}catch(r){return void k.info("Unable to resolve $device_model from userAgentData.getHighEntropyValues",r)}}))).apply(this,arguments)}var hi=function(t,e){if(!(function(s){try{new RegExp(s)}catch{return!1}return!0})(e))return!1;try{return new RegExp(e).test(t)}catch{return!1}};function gn(t,e,s){return us({distinct_id:t,userPropertiesToSet:e,userPropertiesToSetOnce:s})}var td={exact:(t,e)=>e.some((s=>t.some((r=>s===r)))),is_not:(t,e)=>e.every((s=>t.every((r=>s!==r)))),regex:(t,e)=>e.some((s=>t.some((r=>hi(s,r))))),not_regex:(t,e)=>e.every((s=>t.every((r=>!hi(s,r))))),icontains:(t,e)=>e.map(Cr).some((s=>t.map(Cr).some((r=>s.includes(r))))),not_icontains:(t,e)=>e.map(Cr).every((s=>t.map(Cr).every((r=>!s.includes(r))))),gt:(t,e)=>e.some((s=>{var r=parseFloat(s);return!isNaN(r)&&t.some((i=>r>parseFloat(i)))})),lt:(t,e)=>e.some((s=>{var r=parseFloat(s);return!isNaN(r)&&t.some((i=>rt.toLowerCase();function sd(t,e){return!t||Object.entries(t).every((s=>{var r=s[1],i=e?.[s[0]];if(x(i)||$e(i))return!1;var n=[String(i)],o=td[r.operator];return!!o&&o(r.values,n)}))}var uo="custom",kl="i.posthog.com",Jp=/^\/static\//;class Yp{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,s=(e=this.instance.config.ui_host)==null?void 0:e.replace(/\/$/,"");return s||(s=this.apiHost.replace("."+kl,".posthog.com")),s==="https://app.posthog.com"?"https://us.posthog.com":s}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":uo),this.en[this.apiHost]}rn(e){if(Jp.test(e)){var s=this.instance.config.asset_host;if(typeof s=="string")return s.trim().replace(/\/$/,"")||void 0}}endpointFor(e,s){if(s===void 0&&(s=""),s&&(s=s[0]==="/"?s:"/"+s),e==="ui")return this.uiHost+s;if(e==="flags")return this.flagsApiHost+s;if(e==="assets"){var r=this.rn(s);if(r)return""+r+s}if(this.region===uo)return this.apiHost+s;var i=kl+s;switch(e){case"assets":return"https://"+this.region+"-assets."+i;case"api":return"https://"+this.region+"."+i}}}function rd(t){var e;return!((e=t.conditions)==null||(e=e.events)==null||(e=e.values)==null||!e.length)}var q=se("[Surveys]"),id="seenSurvey_",nd=t=>{try{var e=(s=>((r,i)=>""+id+(function(n){return n.current_iteration&&n.current_iteration>0?n.id+"_"+n.current_iteration:n.id})(i))(0,s))(t);if(localStorage.getItem(e))return;localStorage.setItem(e,"true")}catch(s){q.error("Failed to persist survey seen state",s)}},Zp=[un.Popover,un.Widget,un.API],Xp={ignoreConditions:!1,ignoreDelay:!1,displayType:io.Popover},Qp=se("[PostHog ExternalIntegrations]"),ef={intercom:"intercom-integration",crispChat:"crisp-chat-integration"};class tf{constructor(e){this._instance=e}ai(e,s){var r;(r=$.__PosthogExtensions__)==null||r.loadExternalDependency==null||r.loadExternalDependency(this._instance,e,(i=>{if(i)return Qp.error("failed to load script",i);s()}))}startIfEnabledOrStop(){var e=this,s=function(){var n,o,a,l=r[0],u=r[1];!u||(n=$.__PosthogExtensions__)!=null&&(n=n.integrations)!=null&&n[l]||e.ai(ef[l],(()=>{var c;(c=$.__PosthogExtensions__)==null||(c=c.integrations)==null||(c=c[l])==null||c.start(e._instance)})),!u&&(o=$.__PosthogExtensions__)!=null&&(o=o.integrations)!=null&&o[l]&&((a=$.__PosthogExtensions__)==null||(a=a.integrations)==null||(a=a[l])==null||a.stop())};for(var r of Object.entries((i=this._instance.config.integrations)!==null&&i!==void 0?i:{})){var i;s()}}}class sf{constructor(e,s){this.rt=e,this.nn=s,this.sn=new Map,this.an=!1}add(e){var s=this;return X((function*(){if(s.an)throw new Error("Cannot add an extension to a disposed ExtensionRuntime");if(s.sn.has(e.name))throw new Error('Browser extension "'+e.name+'" is already registered');s.sn.set(e.name,e);try{var r=e.setup(s.nn);r&&(yield r)}catch(n){var i=s.sn.get(e.name)===e;i&&s.sn.delete(e.name),s.rt.error('Failed to set up browser extension "'+e.name+'"',n),i&&s.ln(e)}}))()}dispose(){if(!this.an){this.an=!0;var e=Array.from(this.sn.values()).reverse();for(var s of(this.sn.clear(),e))this.ln(s)}}ln(e){try{var s=e.dispose==null?void 0:e.dispose();s&&Se(s.then)&&s.then(void 0,(r=>{this.rt.error('Failed to dispose browser extension "'+e.name+'"',r)}))}catch(r){this.rt.error('Failed to dispose browser extension "'+e.name+'"',r)}}}class rf{constructor(e){this._instance=e}initialize(){}get(e){var s=this._instance.persistence;if(typeof e=="string")return s?.get_property(e);var r={};for(var i of e){var n=s?.get_property(i);x(n)||(r[i]=n)}return r}set(e,s){var r;(r=this._instance.persistence)==null||r.register(typeof e=="string"?{[e]:s}:e)}remove(e){var s;(s=this._instance.persistence)==null||s.unregister(e)}}var Il="extensionsRemoteConfig";class nf{constructor(e){this.an=!1,this.instance=e,this.rt=k,this.un=e.hn,this.kv=new rf(e),this.onEvent=s=>Ir(this.instance.on("eventCaptured",(r=>{try{s({event:r.event,properties:r.properties})}catch(i){this.rt.error("Browser extension event listener failed",i)}}))),this.onRemoteConfig=s=>{if(this.an)return Ir((()=>{}));var r=n=>{try{s(n)}catch(o){this.rt.error("Browser extension remote config listener failed",o)}},i=this.instance.dn.on(Il,r);return this.un&&r(this.un),Ir(i)},this.vn=new sf(k.createLogger("[BrowserExtensions]"),this)}get logger(){return this.rt}get distinctId(){return this.instance.get_distinct_id()}get anonymousId(){var e;return(e=this.instance.get_property(sr))!==null&&e!==void 0?e:this.distinctId}get deviceId(){var e=this.instance.get_property(sr);return typeof e=="string"?e:void 0}get library(){return{name:Y.LIB_NAME,version:Y.LIB_VERSION}}get initialPersonProperties(){var e,s;return(e=(s=this.instance.persistence)==null?void 0:s.get_initial_props())!==null&&e!==void 0?e:{}}get groups(){return this.instance.getGroups()}get session(){try{var e,s,r,i,n=(e=this.instance.sessionManager)==null?void 0:e.checkAndGetSessionAndWindowId(!0);return{sessionId:(s=n?.sessionId)!==null&&s!==void 0?s:"",windowId:(r=n?.windowId)!==null&&r!==void 0?r:"",sessionStartTimestamp:(i=n?.sessionStartTimestamp)!==null&&i!==void 0?i:0}}catch{return{sessionId:"",windowId:"",sessionStartTimestamp:0}}}get projectToken(){return this.instance.config.token}add(e){return this.vn.add(e)}capture(e,s,r){var i=this;return X((function*(){r?i.instance.capture(e,s,{timestamp:r.timestamp,uuid:r.uuid,$set:r.set,$set_once:r.setOnce}):i.instance.capture(e,s)}))()}registerDynamicEventProperties(e){return Ir(this.instance.cn(e))}handleRemoteConfig(e){this.an||(this.un=e,this.instance.dn.emit(Il,e))}sendRequest(e,s){var r=this;return X((function*(){var i;s===void 0&&(s={});var n=r.instance.requestRouter.endpointFor((i=s.target)!==null&&i!==void 0?i:"api",e),o={method:s.method,url:s.query?Ai(n,s.query):n,data:s.body,headers:s.headers,timeout:s.timeoutMs,fireCallbackOnDrop:!0,transport:s.transport,compression:s.compression,timestampMode:s.sentAt};return s.transport==="sendBeacon"?(r.instance._send_request(o),{statusCode:202}):new Promise((a=>{o.callback=a,r.instance._send_request(o)}))}))()}dispose(){this.an||(this.an=!0,this.vn.dispose())}}var Ys={},mn=0,pi=()=>{},Cl='Consent opt in/out is not valid with cookieless_mode="always" and will be ignored',Ns="Surveys module not available",Fl="sanitize_properties is deprecated. Use before_send instead",od="Invalid value for property_denylist config: ",of=["token","distinct_id",pu],as="posthog",ad=!Up&&Pe?.indexOf("MSIE")===-1&&Pe?.indexOf("Mozilla")===-1,vn=t=>{var e;return w({api_host:"https://us.i.posthog.com",flags_api_host:null,ui_host:null,asset_host:null,token:"",autocapture:!0,cross_subdomain_cookie:op(C?.location),persistence:"localStorage+cookie",persistence_name:"",cookie_persisted_properties:[],loaded:pi,save_campaign_params:!0,custom_campaign_params:[],custom_blocked_useragents:[],save_referrer:!0,capture_pageleave:"if_capture_pageview",defaults:t??"unset",__preview_deferred_init_extensions:!1,__preview_external_dependency_versioned_paths:!1,__preview_cookie_wins_on_conflict:!1,debug:re&&W(re?.search)&&re.search.indexOf("__posthog_debug=true")!==-1||!1,cookie_expiration:365,upgrade:!1,disable_session_recording:!1,disable_persistence:!1,disable_web_experiments:!0,disable_surveys:!1,disable_surveys_automatic_display:!1,disable_conversations:!1,disable_product_tours:!1,disableDeviceModel:!1,disable_external_dependency_loading:!1,strict_script_versioning:!1,enable_recording_console_log:void 0,secure_cookie:(v==null||(e=v.location)==null?void 0:e.protocol)==="https:",ip:!1,opt_out_capturing_by_default:!1,opt_out_persistence_by_default:!1,opt_out_useragent_filter:!1,opt_out_capturing_persistence_type:"localStorage",consent_persistence_name:null,opt_out_capturing_cookie_prefix:null,opt_in_site_apps:!1,property_denylist:[],respect_dnt:!1,sanitize_properties:null,request_headers:{},request_batching:!0,properties_string_max_length:65535,mask_all_element_attributes:!1,mask_all_text:!1,mask_personal_data_properties:!1,custom_personal_data_properties:[],advanced_disable_flags:!1,advanced_disable_decide:!1,advanced_disable_feature_flags:!1,advanced_disable_feature_flags_on_first_load:!1,advanced_only_evaluate_survey_feature_flags:!1,advanced_feature_flags_dedup_per_session:!1,advanced_enable_surveys:!1,advanced_disable_toolbar_metrics:!1,feature_flag_request_timeout_ms:3e3,surveys_request_timeout_ms:1e4,on_request_error(s){k.error("Bad HTTP status: "+s.statusCode+" "+s.text)},get_device_id:s=>s,capture_performance:void 0,name:"posthog",bootstrap:{},disable_compression:!1,session_idle_timeout_seconds:1800,person_profiles:eo,before_send:void 0,get_current_url:void 0,request_queue_config:{flush_interval_ms:co},error_tracking:{},_onCapture:pi},(s=>({rageclick:s&&s>="2026-05-30"?{content_ignorelist:_p,ignore_text_selection:!0}:!s||"2025-11-30">s||{content_ignorelist:!0},capture_pageview:!s||"2025-05-24">s||"history_change",session_recording:s&&s>="2026-06-25"?{strictMinimumDuration:!0,canvasCapture:{resolutionScale:.6},streamNetworkBody:!0}:s&&s>="2026-05-30"?{strictMinimumDuration:!0,canvasCapture:{resolutionScale:.6}}:s&&s>="2025-11-30"?{strictMinimumDuration:!0}:{},external_scripts_inject_target:s&&s>="2026-01-30"?"head":"body",internal_or_test_user_hostname:s&&s>="2026-01-30"?/^(localhost|127\.0\.0\.1)$/:void 0,persistence_save_debounce_ms:s&&s>="2026-05-30"?250:0,split_storage:!(!s||"2026-05-30">s),detect_google_search_app:!(!s||"2026-05-30">s),disable_capture_url_hashes:!(!s||"2026-06-25">s)}))(t))},af=[["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"]],Pl=t=>{var e={};for(var s of af){var r=s[0],i=s[1];x(t[r])||(e[i]=t[r])}var n=ee({},e,t),o=t.__preview_external_dependency_versioned_paths;return x(o)||(x(t.strict_script_versioning)&&(n.strict_script_versioning=!!o),W(o)&&x(t.asset_host)&&(n.asset_host=o)),L(t.property_blacklist)&&(x(t.property_denylist)?n.property_denylist=t.property_blacklist:L(t.property_denylist)?n.property_denylist=[...t.property_blacklist,...t.property_denylist]:k.error(od+t.property_denylist)),n};class lf{constructor(){this.__forceAllowLocalhost=!1}get fn(){return this.__forceAllowLocalhost}set fn(e){k.error("WebPerformanceObserver is deprecated and has no impact on network capture. Use `_forceAllowLocalhostNetworkCapture` on `posthog.sessionRecording`"),this.__forceAllowLocalhost=e}}class Te{pn(e,s){if(e){var r=this.sn.indexOf(e);r!==-1&&this.sn.splice(r,1)}return this.sn.push(s),s.initialize==null||s.initialize(),s}gn(){return this.config.cookieless_mode===ht||this.config.cookieless_mode===Ht&&this.consent.isRejected()}get decideEndpointWasHit(){var e,s;return(e=(s=this.featureFlags)==null?void 0:s.hasLoadedFlags)!==null&&e!==void 0&&e}get flagsEndpointWasHit(){var e,s;return(e=(s=this.featureFlags)==null?void 0:s.hasLoadedFlags)!==null&&e!==void 0&&e}constructor(){var e;this.webPerformance=new lf,this.mn=!1,this.version=Y.LIB_VERSION,this.yn=new Set,this.bn="",this.dn=new Yo,this.sn=[],this._n=[],this._calculate_event_properties=this.calculateEventProperties.bind(this),this.config=vn(),this.SentryIntegration=Ip,this.sentryIntegration=r=>(function(i,n){var o=$u(i,n);return{name:Au,processEvent:a=>o(a)}})(this,r),this.__request_queue=[],this.__loaded=!1,this.analyticsDefaultEndpoint="/e/",this.wn=!1,this.kn=null,this.xn=null,this.Sn=null,this.scrollManager=new Gp(this),this.pageViewManager=new fl(this),this.rateLimiter=new Mp(this),this.requestRouter=new Yp(this),this.consent=new pp(this),this.externalIntegrations=new tf(this);var s=(e=Te.__defaultExtensionClasses)!==null&&e!==void 0?e:{};this.featureFlags=s.featureFlags&&new s.featureFlags(this),this.toolbar=s.toolbar&&new s.toolbar(this),this.surveys=s.surveys&&new s.surveys(this),this.conversations=s.conversations&&new s.conversations(this),this.logs=s.logs&&new s.logs(this),this.metrics=s.metrics&&new s.metrics(this),this.experiments=s.experiments&&new s.experiments(this),this.exceptions=s.exceptions&&new s.exceptions(this),this.people={set:(r,i,n)=>{var o=W(r)?{[r]:i}:r;this.setPersonProperties(o),n?.({})},set_once:(r,i,n)=>{var o=W(r)?{[r]:i}:r;this.setPersonProperties(void 0,o),n?.({})}},this.on("eventCaptured",(r=>k.info('send "'+r?.event+'"',r)))}init(e,s,r){if(r&&r!==as){var i,n=(i=Ys[r])!==null&&i!==void 0?i:new Te;return n._init(e,s,r),Ys[r]=n,Ys[as][r]=n,n}return this._init(e,s,r)}_init(e,s,r){var i,n;s===void 0&&(s={});var o,a=W(e)?e.trim():"";if(!a)return k.critical("PostHog was initialized without a token. This likely indicates a misconfiguration. Please check the first argument passed to posthog.init()"),this;if(this.__loaded)return a!==((o=this.config)==null?void 0:o.token)?console.warn("[PostHog.js]","You have already initialized PostHog with a different project token! Re-initializing is a no-op, so events will keep going to the project this instance was initialized with. To capture into a second project, load PostHog once, then initialize a named instance after the SDK has loaded, e.g. posthog.init('"+a+"', { ... }, 'project2')"):console.warn("[PostHog.js]","You have already initialized PostHog! Re-initializing is a no-op"),this;this.__loaded=!0,this.config=vn(s.defaults),s.debug=this.Cn(s.debug),this.Mn=s,this.Tn=[],s.person_profiles?this.xn=s.person_profiles:s.process_person&&(this.xn=s.process_person);var l=vn(s.defaults),u=Pl(s),c=ee({},l,u,{name:r,token:a});te(l.rageclick)&&te(u.rageclick)&&(c.rageclick=ee({},l.rageclick,u.rageclick)),te(l.session_recording)&&te(u.session_recording)&&(c.session_recording=ee({},l.session_recording,u.session_recording)),this.set_config(c),this.config.on_xhr_error&&k.error("on_xhr_error is deprecated. Use on_request_error instead"),this.compression=s.disable_compression?void 0:xe.GZipJS;var d=this.En();if(this.persistence=new cn(this.config,d),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new cn(w({},this.config,{persistence:"sessionStorage"}),d,!1),this.bn="ph_"+(this.config.persistence_name||this.config.token)+"_session_registered_properties",this.config.persistence!=="memory"&&!d&&ce.N()){var h=ce.H(this.bn);L(h)&&h.forEach((P=>{W(P)&&this.yn.add(P)}))}else ce.q(this.bn);var p=w({},this.persistence.props),f=w({},this.sessionPersistence.props);this.register({$initialization_time:new Date().toISOString()}),this.In=new zp((P=>this.Pn(P)),this.config.request_queue_config),this.Rn=new Vp(this),this.__request_queue=[];var g=this.gn();if(g||(this.sessionManager=new xl(this),this.sessionPropsManager=new Sl(this,this.sessionManager,this.persistence),this.sessionManager.onSessionId(((P,B,S)=>{(S!=null&&S.activityTimeout||S!=null&&S.sessionPastMaximumLength||S!=null&&S.crossTabAdoption)&&this.An()}))),this.Fn(),this.config.__preview_deferred_init_extensions?(k.info("Deferring extension initialization to improve startup performance"),setTimeout((()=>{this.Ln(g)}),0)):(k.info("Initializing extensions synchronously"),this.Ln(g)),Y.DEBUG=Y.DEBUG||this.config.debug,Y.DEBUG&&k.info("Starting in debug mode",{this:this,config:s,thisC:w({},this.config),p,s:f}),!this.config.identity_distinct_id||(i=s.bootstrap)!=null&&i.distinctID||(s.bootstrap=w({},s.bootstrap,{distinctID:this.config.identity_distinct_id,isIdentifiedID:!0})),((n=s.bootstrap)==null?void 0:n.distinctID)!==void 0){var m=s.bootstrap.distinctID,_=this.get_distinct_id(),E=this.persistence.get_property(He);if(s.bootstrap.isIdentifiedID&&_!=null&&_!==m&&E===ts)this.identify(m);else if(s.bootstrap.isIdentifiedID&&_!=null&&_!==m&&E===Tt)k.warn("Bootstrap distinctID differs from an already-identified user. The existing identity is preserved. Call reset() before reinitializing if you intend to switch users.");else{var b=this.config.get_device_id(dt()),I=s.bootstrap.isIdentifiedID?b:m;this.persistence.set_property(He,s.bootstrap.isIdentifiedID?Tt:ts),this.register({distinct_id:m,$device_id:I})}}if(g)this.register_once({distinct_id:br,$device_id:null},"");else if(!this.get_distinct_id()){var F=this.config.get_device_id(dt());this.register_once({distinct_id:F,$device_id:F},""),this.persistence.set_property(He,ts)}return ie(v,"onpagehide"in self?"pagehide":"unload",this._handle_unload.bind(this),{passive:!1}),s.segment?(function(P,B){var S=P.config.segment;if(!S)return B();(function(A,R){var N=A.config.segment;if(!N)return R();var T=J=>{var z=()=>J.anonymousId()||dt();A.config.get_device_id=z,J.id()&&(A.register({distinct_id:J.id(),$device_id:z()}),A.persistence.set_property(He,Tt)),R()},O=N.user();"then"in O&&Se(O.then)?O.then(T):T(O)})(P,(()=>{S.register((A=>{typeof Promise<"u"&&Promise.resolve||an.warn("This browser does not have Promise support, and can not use the segment integration");var R=(N,T)=>{if(!T)return N;N.event.userId||N.event.anonymousId===A.get_distinct_id()||(an.info("No userId set, resetting PostHog"),A.reset()),N.event.userId&&N.event.userId!==A.get_distinct_id()&&(an.info("UserId set, identifying with PostHog"),A.identify(N.event.userId));var O=A.calculateEventProperties(T,N.event.properties);return N.event.properties=Object.assign({},O,N.event.properties),N};return{name:"PostHog JS",type:"enrichment",version:"1.0.0",isLoaded:()=>!0,load:()=>Promise.resolve(),track:N=>R(N,N.event.event),page:N=>R(N,os),identify:N=>R(N,rn),screen:N=>R(N,"$screen")}})(P)).then((()=>{B()}))}))})(this,(()=>this.On())):this.On(),Se(this.config._onCapture)&&this.config._onCapture!==pi&&(k.warn("onCapture is deprecated. Please use `before_send` instead"),this.on("eventCaptured",(P=>this.config._onCapture(P.event,P)))),this.config.ip&&k.warn('The `ip` config option has NO EFFECT AT ALL and has been deprecated. Use a custom transformation or "Discard IP data" project setting instead. See https://posthog.com/tutorials/web-redact-properties#hiding-customer-ip-address for more information.'),this.config.disableDeviceModel||(function(){return ed.apply(this,arguments)})().then((P=>{P&&this.register({[tn]:P})})).catch(pi),this}Fn(){var e,s,r,i,n,o,a=(e=(s=this.config.__extensionClasses)==null?void 0:s.featureFlags)!==null&&e!==void 0?e:(r=Te.__defaultExtensionClasses)==null?void 0:r.featureFlags;a&&(this.featureFlags&&this.featureFlags instanceof a||((i=this.Dn)==null||i.call(this),this.Dn=void 0,this.featureFlags=new a(this)),Se(this.featureFlags.onReloading)&&Se(this.featureFlags.setup)?this.Dn||(this.Dn=this.featureFlags.onReloading((()=>{this.dn.emit("featureFlagsReloading",!0)})),this.$n().add(this.featureFlags)):(n=(o=this.featureFlags).initialize)==null||n.call(o))}Ln(e){var s,r,i,n,o,a,l,u=performance.now(),c=w({},Te.__defaultExtensionClasses,this.config.__extensionClasses),d=[];c.exceptions&&this.sn.push(this.exceptions=(s=this.exceptions)!==null&&s!==void 0?s:new c.exceptions(this)),c.historyAutocapture&&this.sn.push(this.historyAutocapture=new c.historyAutocapture(this)),c.tracingHeaders&&this.sn.push(this.tracingHeaders=new c.tracingHeaders(this)),c.siteApps&&this.sn.push(this.siteApps=new c.siteApps(this)),c.sessionRecording&&!e&&this.sn.push(this.sessionRecording=new c.sessionRecording(this)),this.config.disable_scroll_properties||d.push((()=>{this.scrollManager.startMeasuringScrollPosition()})),c.autocapture&&this.sn.push(this.autocapture=new c.autocapture(this)),c.surveys&&this.sn.push(this.surveys=(r=this.surveys)!==null&&r!==void 0?r:new c.surveys(this)),c.logs&&this.sn.push(this.logs=(i=this.logs)!==null&&i!==void 0?i:new c.logs(this)),c.metrics&&this.sn.push(this.metrics=(n=this.metrics)!==null&&n!==void 0?n: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,kp)),c.toolbar&&this.sn.push(this.toolbar=(a=this.toolbar)!==null&&a!==void 0?a:new c.toolbar(this)),c.experiments&&this.sn.push(this.experiments=(l=this.experiments)!==null&&l!==void 0?l:new c.experiments(this)),this.sn.forEach((h=>{h.initialize&&d.push((()=>{h.initialize==null||h.initialize()}))})),d.push((()=>{if(this.Nn){var h=this.Nn;this.Nn=void 0,this.sn.forEach((p=>p.onRemoteConfig==null?void 0:p.onRemoteConfig(h)))}})),this.qn(d,u)}qn(e,s){for(;e.length>0;){if(this.config.__preview_deferred_init_extensions&&performance.now()-s>=30&&e.length>0)return void setTimeout((()=>{this.qn(e,s)}),0);var r=e.shift();if(r)try{r()}catch(n){k.error("Error initializing extension:",n)}}var i=Math.round(performance.now()-s);this.register_for_session({[fu]:this.config.__preview_deferred_init_extensions?"deferred":"synchronous",[gu]:i}),this.config.__preview_deferred_init_extensions&&k.info("PostHog extensions initialized ("+i+"ms)")}Zi(e){var s;if(!C||!C.body)return k.info("document not ready yet, trying again in 500 milliseconds..."),void setTimeout((()=>{this.Zi(e)}),500);if(this.config.__preview_deferred_init_extensions&&(this.Nn=e),this.hn=e,this.compression=void 0,e.ok){var r,i=e.config;i.supportedCompression&&!this.config.disable_compression&&(this.compression=M(i.supportedCompression,xe.GZipJS)?xe.GZipJS:M(i.supportedCompression,xe.Base64)?xe.Base64:void 0),(r=i.analytics)!=null&&r.endpoint&&(this.analyticsDefaultEndpoint=i.analytics.endpoint)}this.set_config({person_profiles:this.xn?this.xn:eo}),(s=this.jn)==null||s.handleRemoteConfig(e),this.sn.forEach((n=>n.onRemoteConfig==null?void 0:n.onRemoteConfig(e)))}On(){try{this.config.loaded(this)}catch(r){k.critical("`loaded` function failed",r)}if(this.Bn(),this.config.internal_or_test_user_hostname&&re!=null&&re.hostname){var e=re.hostname,s=this.config.internal_or_test_user_hostname;(typeof s=="string"?e===s:s.test(e))&&this.setInternalOrTestUser()}this.config.capture_pageview&&setTimeout((()=>{(this.consent.isOptedIn()||this.gn())&&this.Hn()}),1),this.Un=new Uu(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()&&Er(this.__request_queue,(e=>this.Pn(e))),this.__request_queue=[],this.Bn()}_handle_unload(){var e,s,r,i,n;(e=this.surveys)==null||e.handlePageUnload==null||e.handlePageUnload(),(s=this.metrics)==null||s.flush("sendBeacon"),this.config.request_batching?(this.zn()&&this.capture(sn),(r=this.logs)==null||r.flushLogs("sendBeacon"),(i=this.In)==null||i.unload(),(n=this.Rn)==null||n.unload()):this.zn()&&this.capture(sn,null,{transport:"sendBeacon"})}_send_request(e){this.__loaded?ad?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=w({},this.config.request_headers,e.headers),e.compression=e.compression==="best-available"?this.compression:e.compression,(x(this.config.disable_beacon)?this.config.__preview_disable_beacon:this.config.disable_beacon)&&(e.disableTransport=["sendBeacon"]),e.fetchOptions=e.fetchOptions||this.config.fetch_options,(s=>{var r,i,n,o=w({},s);o.timeout=o.timeout||6e4;var a,l,u,c,d,h=(r=o.transport)!==null&&r!==void 0?r:"fetch";h==="sendBeacon"&&x(o.compression)&&o.data&&(o.compression=xe.Base64),o.method==="POST"&&o.data&&(o.timestampMode==="capture-body"?o.data={api_key:(l=(d=(c=L(a=o.data)?a:[a])[0])==null||(u=d.properties)==null?void 0:u.token)!==null&&l!==void 0?l:d?.token,batch:c,sent_at:new Date().toISOString()}:o.timestampMode==="body"&&(o.data=(function(m,_){return _===void 0&&(_=new Date().toISOString()),L(m)?m.map((E=>w({},E,{sent_at:_}))):w({},m,{sent_at:_})})(o.data))),o.url=El(o.url,o.method,o.compression,o.timestampMode);var p=Br.filter((m=>!o.disableTransport||!m.transport||!o.disableTransport.includes(m.transport))),f=(i=(n=(function(m,_){for(var E=0;m.length>E;E++)if(m[E].transport===h)return m[E]})(p))==null?void 0:n.method)!==null&&i!==void 0?i:p[0].method;if(!f)throw new Error("No available transport method");var g=m=>{try{f(m)}catch(_){Zu(_)?k.warn(_):k.error(_),o.callback==null||o.callback({statusCode:0,error:_})}};h!=="sendBeacon"&&o.data&&o.compression===xe.GZipJS&&lh&&typeof Promise<"u"&&!Dr?Hp(o).then((m=>{g(m)})).catch((m=>{if(Ha(m))return Dr=!0,void g(w({},o,{compression:void 0,url:El(s.url,s.method,void 0,s.timestampMode)}));(_=>{if(!_||typeof _!="object")return!1;var E="name"in _?String(_.name):"";return Ha(_)||E===Cc})(m)&&(Dr=!0),g(o)})):f(o)})(w({},e,{callback:s=>{var r,i;this.rateLimiter.checkForLimiting(s),400>s.statusCode||(r=(i=this.config).on_request_error)==null||r.call(i,s),e.callback==null||e.callback(s)}}))):e.fireCallbackOnDrop&&(e.callback==null||e.callback({statusCode:0}))}Pn(e){this.Rn?this.Rn.retriableRequest(e):this._send_request(e)}_execute_array(e){mn++;try{var s,r=[],i=[],n=[];Er(e,(a=>{if(a)if(L(s=a[0]))n.push(a);else if(Se(a))try{a.call(this)}catch(l){k.error("Error executing queued PostHog call",a,l)}else L(a)&&s==="alias"?r.push(a):L(a)&&s.indexOf("capture")!==-1&&Se(this[s])?n.push(a):i.push(a)}));var o=function(a,l){Er(a,(function(u){try{if(L(u[0])){var c=l;Z(u,(function(d){c=c[d[0]].apply(c,d.slice(1))}))}else l[u[0]].apply(l,u.slice(1))}catch(d){k.error("Error executing queued PostHog call",u,d)}}))};o(r,this),o(i,this),o(n,this)}finally{mn--}}push(e){if(mn>0&&L(e)&&W(e[0])){var s=Te.prototype[e[0]];Se(s)&&s.apply(this,e.slice(1))}else this._execute_array([e])}capture(e,s,r){var i,n,o,a,l;if(this.__loaded&&this.persistence&&this.sessionPersistence&&this.In){if(this.is_capturing())if(!x(e)&&W(e)){var u=!this.config.opt_out_useragent_filter&&this._is_bot();if(!u||this.config.__preview_capture_bot_pageviews){var c=r!=null&&r.skip_client_rate_limiting?void 0:this.rateLimiter.clientRateLimitContext();if(c==null||!c.isRateLimited){s!=null&&s.$current_url&&!W(s?.$current_url)&&(k.error("Invalid `$current_url` property provided to `posthog.capture`. Input must be a string. Ignoring provided value."),s==null||delete s.$current_url),e!=="$exception"||r!=null&&r.Wn||k.warn("Using `posthog.capture('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureException(error)` instead, which attaches required metadata automatically."),this.sessionPersistence.update_search_keyword(),this.config.save_campaign_params&&this.sessionPersistence.update_campaign_params(),this.config.save_referrer&&this.sessionPersistence.update_referrer_info(),(this.config.save_campaign_params||this.config.save_referrer)&&this.persistence.set_initial_person_info();var d=new Date,h=r?.timestamp||d,p=Ga(r?.uuid,dt),f={uuid:p,event:e,properties:this.calculateEventProperties(e,s||{},h,p)};e===os&&this.config.__preview_capture_bot_pageviews&&u&&(f.event="$bot_pageview",f.properties.$browser_type="bot"),c&&(f.properties.$lib_rate_limit_remaining_tokens=c.remainingTokens);var g=e==="$feature_flag_called"&&f.properties.$feature_flag_has_experiment===!1&&this.get_property(ei)===!0;r?.$set&&!g&&(f.$set=r?.$set);var m=r?.$unset;m&&(f.$unset=m);var _,E,b,I=g?void 0:this.Vn(r?.$set_once,e!==Qa,e===rn);if(I&&(f.$set_once=I),r!=null&&r._noTruncate||(n=this.config.properties_string_max_length,o=f,a=T=>W(T)?T.slice(0,n):T,l=new Set,f=(function T(O,J){if(O!==Object(O))return a?a(O):O;if(!l.has(O)){var z;if(l.add(O),L(O))z=[],Er(O,(oe=>{z.push(T(oe))}));else{var H={};Z(O,((oe,pe)=>{l.has(oe)||(H[pe]=T(oe))})),z=H}return z}})(o)),f.timestamp=h,x(r?.timestamp)||(f.properties.$event_time_override_provided=!0,f.properties.$event_time_override_system_time=d),g&&(f.properties=(function(T,O){O===void 0&&(O=[]);var J={},z=H=>{T[H]!==void 0&&(J[H]=T[H])};return ch.forEach(z),O.forEach(z),J})(f.properties,of)),e===ft.DISMISSED||e===ft.SENT){var F=s?.[dn.SURVEY_ID],P=s?.[dn.SURVEY_ITERATION];nd({id:F,current_iteration:P}),f.$set=w({},f.$set,{[(_={id:F,current_iteration:P},E=e===ft.SENT?"responded":"dismissed",b="$survey_"+E+"/"+_.id,_.current_iteration&&_.current_iteration>0&&(b="$survey_"+E+"/"+_.id+"/"+_.current_iteration),b)]:!0})}else e===ft.SHOWN&&(f.$set=w({},f.$set,{[dn.SURVEY_LAST_SEEN_DATE]:new Date().toISOString()}));if(e===Np.SHOWN){var B=s?.[ml.TOUR_TYPE];B&&(f.$set=w({},f.$set,{[ml.TOUR_LAST_SEEN_DATE+"/"+B]:new Date().toISOString()}))}var S=w({},f.properties.$set,f.$set);if(mt(S)||this.setPersonPropertiesForFlags(S),!D(this.config.before_send)){var A=this.Pt(f);if(!A)return;(f=A).uuid=Ga(f.uuid,dt)}this.dn.emit("eventCaptured",f);var R=(i=r?._url)!==null&&i!==void 0?i:this.requestRouter.endpointFor("api",this.analyticsDefaultEndpoint),N={method:"POST",url:R,data:f,compression:"best-available",timestampMode:r?._batchKey==="recordings"||/\/s\/(?:\?|$)/.test(R)?"body":"capture-body",batchKey:r?._batchKey,transport:r?.transport};return!this.config.request_batching||r&&(r==null||!r._batchKey)||r!=null&&r.send_instantly?this.Pn(N):this.In.enqueue(N),f}k.critical("This capture call is ignored due to client rate limiting.")}}else k.error("No event name provided to posthog.capture")}else k.uninitializedWarning("posthog.capture")}_addCaptureHook(e){return this.on("eventCaptured",(s=>e(s.event,s)))}$n(){var e;return(e=this.jn)!==null&&e!==void 0?e:this.jn=new nf(this)}cn(e){this._n.push(e);var s=!0;return()=>{if(s){s=!1;var r=this._n.indexOf(e);r!==-1&&this._n.splice(r,1)}}}calculateEventProperties(e,s,r,i,n){if(r=r||new Date,!this.persistence||!this.sessionPersistence)return s;var o=n?void 0:this.persistence.remove_event_timer(e),a=w({},s);if(a.token=this.config.token,a.$config_defaults=this.config.defaults,this.gn()&&(a[pu]=!0),e==="$snapshot"){var l=w({},this.persistence.properties(),this.sessionPersistence.properties());return a.distinct_id=l.distinct_id,(!W(a.distinct_id)&&!he(a.distinct_id)||Nn(a.distinct_id))&&k.error("Invalid distinct_id for replay event. This indicates a bug in your implementation"),a}var u,c=(function(F,P,B,S){var A,R,N,T;if(S===void 0&&(S=!1),!Pe)return{};var O,J=F?[..._s,...P||[]]:[],z=(function(vr){for(var je=0;qa.length>je;je++){var _r=qa[je],Qt=_r[1],es=_r[0].exec(vr),Is=es&&(Se(Qt)?Qt(es,vr):Qt);if(Is)return Is}return["",""]})(Pe),H=z[0],oe=z[1],pe=(O=typeof navigator<"u"?navigator:void 0)!=null&&O.brave?{brave:!0}:{},Ie={};x(B)||(Ie.detectGoogleSearchApp=B);var _e={},Ce=(A=navigator)==null||(A=A.userAgentData)==null?void 0:A.platform,Re=(R=navigator)==null?void 0:R.maxTouchPoints,ae=v==null||(N=v.screen)==null?void 0:N.width,me=v==null||(T=v.screen)==null?void 0:T.height,ge=v?.devicePixelRatio;x(Ce)||(_e.userAgentDataPlatform=Ce),x(Re)||(_e.maxTouchPoints=Re),x(ae)||(_e.screenWidth=ae),x(me)||(_e.screenHeight=me),x(ge)||(_e.devicePixelRatio=ge);var Ye,Rt,de,Ve,St,ks,Be,Fe,mr=ee(zo({$os:H,$os_version:oe,$browser:Xc(Pe,navigator.vendor,pe,Ie),$device:Va(Pe),$device_type:(Rt=Pe,de=_e,Fe=Va(Rt),Fe===Nc||Fe===Tc||Fe==="Kobo"||Fe==="Kindle Fire"||Fe===Gc?fs:Fe===er||Fe===hs||Fe===tr||Fe===Ln?"Console":Fe===Lc?"Wearable":Fe?Oe:de?.userAgentDataPlatform==="Android"&&((Ve=de?.maxTouchPoints)!==null&&Ve!==void 0?Ve:0)>0?600>Math.min((St=de?.screenWidth)!==null&&St!==void 0?St:0,(ks=de?.screenHeight)!==null&&ks!==void 0?ks:0)/((Be=de?.devicePixelRatio)!==null&&Be!==void 0?Be:1)?Oe:fs:"Desktop"),$timezone:ju(),$timezone_offset:$p()}),{$current_url:ir(S?Ct(re?.href):re?.href,J,nr),$host:re?.host,$pathname:re?.pathname,$raw_user_agent:Pe.length>1e3?Pe.substring(0,997)+"...":Pe,$browser_version:Fh(Pe,navigator.vendor,pe,Ie),$browser_language:gl(),$browser_language_prefix:(Ye=gl(),typeof Ye=="string"?Ye.split("-")[0]:void 0),$screen_height:v?.screen.height,$screen_width:v?.screen.width,$viewport_height:v?.innerHeight,$viewport_width:v?.innerWidth,$lib:Y.LIB_NAME,$lib_version:Y.LIB_VERSION,$insert_id:Math.random().toString(36).substring(2,10)+Math.random().toString(36).substring(2,10),$time:Date.now()/1e3});return Y.SDK_DIST_CHANNEL&&(mr.$sdk_dist_channel=Y.SDK_DIST_CHANNEL),mr})(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(n,r.getTime()),h=d.windowId;a.$session_id=d.sessionId,a.$window_id=h}this.sessionPropsManager&&ee(a,this.sessionPropsManager.getSessionProps());try{var p;this.sessionRecording&&ee(a,this.sessionRecording.sdkDebugProperties),a.$sdk_debug_retry_queue_size=(p=this.Rn)==null?void 0:p.length}catch(F){a.$sdk_debug_error_capturing_properties=String(F)}if(this.requestRouter.region===uo&&(a.$lib_custom_api_host=this.config.api_host),u=e!==os||n?e!==sn||n?this.pageViewManager.doEvent():this.pageViewManager.doPageLeave(r):this.pageViewManager.doPageView(r,i),a=ee(a,u),e===os&&C&&(a.title=C.title),!x(o)){var f=r.getTime()-o;a.$duration=parseFloat((f/1e3).toFixed(3))}Pe&&this.config.opt_out_useragent_filter&&(a.$browser_type=this._is_bot()?"bot":"browser");var g=this.persistence.properties(),m=this.sessionPersistence.properties();Z(["$referrer","$referring_domain"],(F=>{F in g&&delete m[F]}));var _={};if(this._n.length>0)for(var E of this._n.slice())try{ee(_,E())}catch(F){k.error("Failed to produce browser extension event properties",F)}(a=ee({},c,g,m,w({},_,a))).$is_identified=this._isIdentified(),L(this.config.property_denylist)?Z(this.config.property_denylist,(function(F){delete a[F]})):k.error(od+this.config.property_denylist+" or property_blacklist config: "+this.config.property_blacklist);var b=this.config.sanitize_properties;b&&(k.error(Fl),a=b(a,e));var I=this.Zn();return a.$process_person_profile=I,I&&!n&&this.Gn("_calculate_event_properties"),a}Vn(e,s,r){var i;if(s===void 0&&(s=!0),r===void 0&&(r=!1),!this.persistence||!this.Zn()||this.mn&&!r)return e;var n=this.persistence.get_initial_props(),o=(i=this.sessionPropsManager)==null?void 0:i.getSetOnceProps(),a=ee({},n,o||{},e||{}),l=this.config.sanitize_properties;return l&&(k.error(Fl),a=l(a,"$set_once")),s&&(this.mn=!0),mt(a)?void 0:a}register(e,s){var r;(r=this.persistence)==null||r.register(e,s)}register_once(e,s,r){var i;(i=this.persistence)==null||i.register_once(e,s,r)}register_for_session(e){var s;(s=this.sessionPersistence)==null||s.register(e),Object.keys(e).forEach((r=>this.yn.add(r))),this.Qn()}unregister(e){var s;(s=this.persistence)==null||s.unregister(e)}unregister_for_session(e){var s;(s=this.sessionPersistence)==null||s.unregister(e),this.yn.delete(e),this.Qn()}Kn(e,s){this.register({[e]:s})}An(){this.yn.forEach((e=>{var s;(s=this.sessionPersistence)==null||s.unregister(e)})),this.yn.clear(),this.Qn()}Qn(){var e;if(this.bn)if(this.config.persistence==="memory"||(e=this.sessionPersistence)!=null&&e.xi||!ce.N())ce.q(this.bn);else{var s=[];this.yn.forEach((r=>s.push(r))),s.length>0?ce.F(this.bn,s):ce.q(this.bn)}}getFeatureFlag(e,s){var r;return(r=this.featureFlags)==null?void 0:r.getFeatureFlag(e,s)}getFeatureFlagPayload(e){var s;return(s=this.featureFlags)==null?void 0:s.getFeatureFlagPayload(e)}getFeatureFlagResult(e,s){var r;return(r=this.featureFlags)==null?void 0:r.getFeatureFlagResult(e,s)}getAllFeatureFlags(){var e,s;return(e=(s=this.featureFlags)==null?void 0:s.getAllFeatureFlags())!==null&&e!==void 0?e:[]}isFeatureEnabled(e,s){var r,i;return(r=(i=this.featureFlags)==null?void 0:i.isFeatureEnabled(e,s))!==null&&r!==void 0?r:s?.defaultValue}reloadFeatureFlags(){var e;(e=this.featureFlags)==null||e.reloadFeatureFlags()}updateFlags(e,s,r){var i;(i=this.featureFlags)==null||i.updateFlags(e,s,r)}updateEarlyAccessFeatureEnrollment(e,s,r){var i;(i=this.featureFlags)==null||i.updateEarlyAccessFeatureEnrollment(e,s,r)}getEarlyAccessFeatures(e,s,r){var i;return s===void 0&&(s=!1),(i=this.featureFlags)==null?void 0:i.getEarlyAccessFeatures(e,s,r)}on(e,s){return this.dn.on(e,s)}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:Ns}),()=>{})}onSessionId(e){var s,r;return(s=(r=this.sessionManager)==null?void 0:r.onSessionId(e))!==null&&s!==void 0?s:()=>{}}getSurveys(e,s){s===void 0&&(s=!1),this.surveys?this.surveys.getSurveys(e,s):e([],{isLoaded:!1,error:Ns})}getActiveMatchingSurveys(e,s){s===void 0&&(s=!1),this.surveys?this.surveys.getActiveMatchingSurveys(e,s):e([],{isLoaded:!1,error:Ns})}renderSurvey(e,s){var r;(r=this.surveys)==null||r.renderSurvey(e,s)}displaySurvey(e,s){var r;s===void 0&&(s=Xp),(r=this.surveys)==null||r.displaySurvey(e,s)}cancelPendingSurvey(e){var s;(s=this.surveys)==null||s.cancelPendingSurvey(e)}canRenderSurvey(e){var s,r;return(s=(r=this.surveys)==null?void 0:r.canRenderSurvey(e))!==null&&s!==void 0?s:{visible:!1,disabledReason:Ns}}canRenderSurveyAsync(e,s){var r,i;return s===void 0&&(s=!1),(r=(i=this.surveys)==null?void 0:i.canRenderSurveyAsync(e,s))!==null&&r!==void 0?r:Promise.resolve({visible:!1,disabledReason:Ns})}Jn(e){return!e||Nn(e)?(k.critical("Unique user id has not been set in posthog.identify"),!1):e===br?(k.critical('The string "'+e+'" was set in posthog.identify which indicates an error. This ID is only used as a sentinel value.'),!1):!["distinct_id","distinctid"].includes(e.toLowerCase())&&!["undefined","null"].includes(e.toLowerCase())||(k.critical('The string "'+e+'" was set in posthog.identify which indicates an error. This ID should be unique to the user and not a hardcoded string.'),!1)}identify(e,s,r){if(!this.__loaded||!this.persistence)return k.uninitializedWarning("posthog.identify");if(he(e)&&(e=e.toString(),k.warn("The first argument to posthog.identify was a number, but it should be a string. It has been converted to a string.")),this.Jn(e)&&this.Gn("posthog.identify")){var i=this.get_distinct_id();this.register({$user_id:e}),this.get_property(sr)||this.register_once({$had_persisted_distinct_id:!0,$device_id:i},""),e!==i&&e!==this.get_property(Bs)&&(this.unregister(Bs),this.register({distinct_id:e}));var n,o=(this.persistence.get_property(He)||ts)===ts,a=e!==i,l=!a&&o;if(a&&o)this.persistence.set_property(He,Tt),this.setPersonPropertiesForFlags({$set:s||{},$set_once:r||{}},!1),this.capture(rn,{distinct_id:e,$anon_distinct_id:i},{$set:s||{},$set_once:r||{}}),this.Sn=gn(e,s,r),(n=this.featureFlags)==null||n.setAnonymousDistinctId(i);else if(l){this.persistence.set_property(He,Tt);var u=s||{},c=r||{};this.setPersonPropertiesForFlags({$set:u,$set_once:c},!1),this.capture("$set",{$set:u,$set_once:c}),this.Sn=gn(e,s,r)}else(s||r)&&this.setPersonProperties(s,r);a?(this.reloadFeatureFlags(),this.featureFlags?this.featureFlags.resetFlagCallReported():this.unregister(Wt)):l&&(s||r)&&this.reloadFeatureFlags()}}setPersonProperties(e,s){if((e||s)&&this.Gn("posthog.setPersonProperties")){var r=gn(this.get_distinct_id(),e,s);this.Sn!==r?(this.setPersonPropertiesForFlags({$set:e||{},$set_once:s||{}},!0),this.capture("$set",{$set:e||{},$set_once:s||{}}),this.Sn=r):k.info("A duplicate setPersonProperties call was made with the same properties. It has been ignored.")}}unsetPersonProperties(e){var s,r=(L(e)?e:[e]).filter((i=>W(i)&&i.length>0));r.length!==0&&this.Gn("posthog.unsetPersonProperties")&&((s=this.featureFlags)==null||s.unsetPersonPropertiesForFlags(r,!0),this.capture("$set",{$unset:r}),this.Sn=null)}group(e,s,r){if(e&&s){var i=this.getGroups(),n=i[e]!==s;if(n&&this.resetGroupPropertiesForFlags(e),this.register({$groups:w({},i,{[e]:s})}),n||r){var o={$group_type:e,$group_key:s};r&&(o.$group_set=r),this.capture(Qa,o)}r&&this.setGroupPropertiesForFlags({[e]:r}),n&&!r&&this.reloadFeatureFlags()}else k.error("posthog.group requires a group type and group key")}resetGroups(){this.register({$groups:{}}),this.resetGroupPropertiesForFlags(),this.reloadFeatureFlags()}setPersonPropertiesForFlags(e,s){var r;s===void 0&&(s=!0),(r=this.featureFlags)==null||r.setPersonPropertiesForFlags(e,s)}resetPersonPropertiesForFlags(e){var s;e===void 0&&(e=!0),(s=this.featureFlags)==null||s.resetPersonPropertiesForFlags(e)}setGroupPropertiesForFlags(e,s){var r;s===void 0&&(s=!0),this.Gn("posthog.setGroupPropertiesForFlags")&&((r=this.featureFlags)==null||r.setGroupPropertiesForFlags(e,s))}resetGroupPropertiesForFlags(e){var s;(s=this.featureFlags)==null||s.resetGroupPropertiesForFlags(e)}reset(e){this.Yn(e)}Yn(e,s){var r,i,n,o,a,l,u,c,d,h;if(s===void 0&&(s=!1),k.info("reset"),!this.__loaded)return k.uninitializedWarning("posthog.reset");var p,f=this.get_property(sr),g=this.get_property(tn),m=this.get_property(Vt),_=this.is_capturing();if(this.consent.reset(),s||!_||this.is_capturing()||console.warn("[PostHog.js]","reset() cleared the stored consent, and capturing is now off because of `opt_out_capturing_by_default`. Call opt_in_capturing() again, and prefer calling reset() before opting in rather than after."),(r=this.persistence)==null||r.clear(),(i=this.sessionPersistence)==null||i.clear(),this.yn.clear(),this.Qn(),x(m)||(p=this.persistence)==null||p.register({[Vt]:m}),(n=this.surveys)==null||n.reset(),(o=this.Un)==null||o.stop(),(a=this.featureFlags)==null||a.reset(),(l=this.conversations)==null||l.reset(),(u=this.logs)==null||u.reset(),(c=this.metrics)==null||c.reset(),(d=this.persistence)==null||d.set_property(He,ts),(h=this.sessionManager)==null||h.resetSessionId(),this.Sn=null,this.config.cookieless_mode===ht)this.register_once({distinct_id:br,$device_id:null},"");else{var E=this.config.get_device_id(dt());this.register_once({distinct_id:E,$device_id:e?E:f},""),e||x(g)||this.register({[tn]: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 s=this;return X((function*(){var r,i,n,o,a,l,u;if(s.__loaded){(r=s.Un)==null||r.stop(),(i=s.jn)==null||i.dispose(),(n=s.sessionRecording)==null||n.dispose(),(o=s.logs)==null||o.flushLogs("sendBeacon"),(a=s.metrics)==null||a.flush("sendBeacon"),(l=s.In)==null||l.unload(),(u=s.Rn)==null||u.unload();try{var c;(c=s.featureFlags)==null||c.destroy()}catch(d){k.error("Error while destroying feature flags",d)}}else k.uninitializedWarning("posthog.shutdown")}))()}setIdentity(e,s){var r;this.config.identity_distinct_id=e,this.config.identity_hash=s,this.alias(e),(r=this.conversations)==null||r.Xn()}clearIdentity(){var e;delete this.config.identity_distinct_id,delete this.config.identity_hash,(e=this.conversations)==null||e.ts()}get_distinct_id(){return this.get_property("distinct_id")}getGroups(){return this.get_property("$groups")||{}}get_session_id(){var e,s;return(e=(s=this.sessionManager)==null?void 0:s.checkAndGetSessionAndWindowId(!0).sessionId)!==null&&e!==void 0?e:""}get_session_replay_url(e){if(!this.sessionManager)return"";var s=this.sessionManager.checkAndGetSessionAndWindowId(!0),r=s.sessionStartTimestamp,i=this.requestRouter.endpointFor("ui","/project/"+this.config.token+"/replay/"+s.sessionId);if(e!=null&&e.withTimestamp&&r){var n,o=(n=e.timestampLookBack)!==null&&n!==void 0?n:10;if(!r)return i;i+="?t="+Math.max(Math.floor((new Date().getTime()-r)/1e3)-o,0)}return i}alias(e,s){return e===this.get_property(au)?(k.critical("Attempting to create alias for existing People user - aborting."),-2):this.Gn("posthog.alias")?(x(s)&&(s=this.get_distinct_id()),e!==s?(this.Kn(Bs,e),this.capture("$create_alias",{alias:e,distinct_id:s})):(k.warn("alias matches current distinct_id - skipping api call."),this.identify(e),-1)):void 0}set_config(e){var s=w({},this.config);if(te(e)){var r,i,n,o,a,l,u,c,d,h,p,f;ee(this.config,Pl(e));var g=this.En();(r=this.persistence)==null||r.update_config(this.config,s,g),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new cn(w({},this.config,{persistence:"sessionStorage"}),g,!1);var m=this.Cn(this.config.debug);Ke(m)&&(this.config.debug=m),Ke(this.config.debug)&&(this.config.debug?(Y.DEBUG=!0,Q.N()&&Q.F("ph_debug",!0),k.info("set_config",{config:e,oldConfig:s,newConfig:w({},this.config)})):(Y.DEBUG=!1,Q.N()&&Q.q("ph_debug"))),(i=this.featureFlags)==null||i.updateConfig==null||i.updateConfig(this.config,this.Qi()),(n=this.exceptionObserver)==null||n.onConfigChange(),(o=this.exceptions)==null||o.onConfigChange(),(a=this.sessionRecording)==null||a.startIfEnabledOrStop(),(l=this.tracingHeaders)==null||l.startIfEnabledOrStop(),(u=this.autocapture)==null||u.startIfEnabled(),(c=this.heatmaps)==null||c.startIfEnabled(),(d=this.exceptionObserver)==null||d.startIfEnabledOrStop(),(h=this.deadClicksAutocapture)==null||h.startIfEnabledOrStop(),(p=this.surveys)==null||p.loadIfEnabled(),this.es(),(f=this.externalIntegrations)==null||f.startIfEnabledOrStop()}}_overrideSDKInfo(e,s){Y.LIB_NAME=e,Y.LIB_VERSION=s}startSessionRecording(e){var s,r,i,n,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)&&((s=this.sessionManager)==null||s.checkAndGetSessionAndWindowId(),l.sampling&&((r=this.sessionRecording)==null||r.overrideSampling()),l.linked_flag&&((i=this.sessionRecording)==null||i.overrideLinkedFlag()),l.url_trigger&&((n=this.sessionRecording)==null||n.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,s){if(this.exceptions){var r=new Error("PostHog syntheticException"),i=this.exceptions.buildProperties(e,{handled:!0,syntheticException:r});return this.exceptions.sendExceptionEvent(w({},i,s))}}addExceptionStep(e,s){var r;(r=this.exceptions)==null||r.addExceptionStep(e,s)}captureLog(e){var s;(s=this.logs)==null||s.captureLog(e)}get logger(){var e,s;return(e=(s=this.logs)==null?void 0:s.logger)!==null&&e!==void 0?e:Te.rs}startExceptionAutocapture(e){this.set_config({capture_exceptions:e==null||e})}stopExceptionAutocapture(){this.set_config({capture_exceptions:!1})}loadToolbar(e){var s,r;return(s=(r=this.toolbar)==null?void 0:r.loadToolbar(e))!==null&&s!==void 0&&s}get_property(e){var s;return(s=this.persistence)==null?void 0:s.props[e]}getSessionProperty(e){var s;return(s=this.sessionPersistence)==null?void 0:s.props[e]}toString(){var e,s=(e=this.config.name)!==null&&e!==void 0?e:as;return s!==as&&(s=as+"."+s),s}_isIdentified(){var e,s;return((e=this.persistence)==null?void 0:e.get_property(He))===Tt||((s=this.sessionPersistence)==null?void 0:s.get_property(He))===Tt}Zn(){var e,s;return!(this.config.person_profiles==="never"||this.config.person_profiles===eo&&!this._isIdentified()&&mt(this.getGroups())&&((e=this.persistence)==null||(e=e.props)==null||!e[Bs])&&((s=this.persistence)==null||(s=s.props)==null||!s[ri]))}zn(){return this.config.capture_pageleave===!0||this.config.capture_pageleave==="if_capture_pageview"&&(this.config.capture_pageview===!0||this.config.capture_pageview==="history_change")}createPersonProfile(){this.Zn()||this.Gn("posthog.createPersonProfile")&&this.setPersonProperties({},{})}setInternalOrTestUser(){this.Gn("posthog.setInternalOrTestUser")&&this.setPersonProperties({$internal_or_test_user:!0})}Gn(e){return this.config.person_profiles==="never"?(k.error(e+' was called, but process_person is set to "never". This call will be ignored.'),!1):(this.Kn(ri,!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!==Ht)}es(){var e,s,r,i,n=this.En();return((e=this.persistence)==null?void 0:e.xi)!==n&&((r=this.persistence)==null||r.set_disabled(n)),((s=this.sessionPersistence)==null?void 0:s.xi)!==n&&((i=this.sessionPersistence)==null||i.set_disabled(n)),n&&(this.yn.clear(),this.Qn()),n}opt_in_capturing(e){var s;if(this.config.cookieless_mode!==ht){if(this.gn()){var r,i,n,o,a;this.Yn(!0,!0),(r=this.sessionManager)==null||r.destroy(),(i=this.pageViewManager)==null||i.destroy(),this.sessionManager=new xl(this),this.pageViewManager=new fl(this),this.persistence&&(this.sessionPropsManager=new Sl(this,this.sessionManager,this.persistence));var l,u=(n=(o=this.config.__extensionClasses)==null?void 0:o.sessionRecording)!==null&&n!==void 0?n:(a=Te.__defaultExtensionClasses)==null?void 0:a.sessionRecording;u&&(this.sessionRecording=this.pn(this.sessionRecording,new u(this)),this.hn&&((l=this.sessionRecording)==null||l.onRemoteConfig==null||l.onRemoteConfig(this.hn)))}var c,d;this.consent.optInOut(!0),this.es(),this.Bn(),(s=this.sessionRecording)==null||s.startIfEnabledOrStop(),this.config.cookieless_mode==Ht&&((c=this.surveys)==null||c.loadIfEnabled()),(x(e?.captureEventName)||e!=null&&e.captureEventName)&&this.capture((d=e?.captureEventName)!==null&&d!==void 0?d:"$opt_in",e?.captureProperties,{send_instantly:!0}),this.config.capture_pageview&&this.Hn()}else k.warn(Cl)}opt_out_capturing(){var e,s,r;this.config.cookieless_mode!==ht?(this.config.cookieless_mode===Ht&&this.consent.isOptedIn()&&this.Yn(!0,!0),this.consent.optInOut(!1),this.es(),this.config.cookieless_mode===Ht&&(this.register({distinct_id:br,$device_id:null}),(e=this.sessionRecording)==null||e.stopRecording(),this.sessionRecording=void 0,(s=this.sessionManager)==null||s.destroy(),(r=this.pageViewManager)==null||r.destroy(),this.sessionManager=void 0,this.sessionPropsManager=void 0,this.config.capture_pageview&&this.Hn(),this.Bn())):k.warn(Cl)}has_opted_in_capturing(){return this.consent.isOptedIn()}has_opted_out_capturing(){return this.consent.isOptedOut()}get_explicit_consent_status(){var e=this.consent.consent;return e===1?"granted":e===0?"denied":"pending"}is_capturing(){return this.config.cookieless_mode===ht||(this.config.cookieless_mode===Ht?this.consent.isRejected()||this.consent.isOptedIn():!this.has_opted_out_capturing())}clear_opt_in_out_capturing(){this.consent.reset(),this.es()}_is_bot(){return ke?Qu(ke,this.config.custom_blocked_useragents):void 0}Hn(){C&&(C.visibilityState==="visible"?this.wn||(this.wn=!0,this.capture(os,{title:C.title},{send_instantly:!0}),this.kn&&(C.removeEventListener(ii,this.kn),this.kn=null)):this.kn||(this.kn=this.Hn.bind(this),ie(C,ii,this.kn)))}debug(e){e===!1?(v?.console.log("You've disabled debug mode."),this.set_config({debug:!1})):(v?.console.log("You're now in debug mode. All calls to PostHog will be logged in your console.\nYou can disable this with `posthog.debug(false)`."),this.set_config({debug:!0}))}Qi(){var e=this.Mn||{};return"advanced_disable_flags"in e?!!e.advanced_disable_flags:this.config.advanced_disable_flags!==!1?!!this.config.advanced_disable_flags:this.config.advanced_disable_decide===!0?(k.warn("Config field 'advanced_disable_decide' is deprecated. Please use 'advanced_disable_flags' instead. The old field will be removed in a future major version."),!0):(function(s,r,i,n,o){var a=r in s&&!D(s[r]),l=i in s&&!D(s[i]);return a?s[r]:!!l&&(o&&o.warn("Config field '"+i+"' is deprecated. Please use '"+r+"' instead. The old field will be removed in a future major version."),s[i])})(e,"advanced_disable_flags","advanced_disable_decide",0,k)}Pt(e){var s;if(D(this.config.before_send))return e;var r=Object.keys((s=e.properties)!==null&&s!==void 0?s:{}).filter(mh),i=L(this.config.before_send)?this.config.before_send:[this.config.before_send],n=e;for(var o of i){if(n=o(n),D(n)){var a="Event '"+e.event+"' was rejected in beforeSend function";return gh(e.event)?k.warn(a+". This can cause unexpected behavior."):k.info(a),null}n.properties&&!mt(n.properties)||k.warn("Event '"+e.event+"' has no properties after beforeSend function, this is likely an error.")}for(var l of r)if(n.properties&&D(n.properties[l]))return k.warn("Event '"+e.event+"' had its '"+l+"' property removed in a beforeSend function. This property is required for ingestion, so the event will be dropped."),null;return n}getPageViewId(){var e;return(e=this.pageViewManager.ui)==null?void 0:e.pageViewId}captureTraceFeedback(e,s){this.capture("$ai_feedback",{$ai_trace_id:String(e),$ai_feedback_text:s})}captureTraceMetric(e,s,r){this.capture("$ai_metric",{$ai_trace_id:String(e),$ai_metric_name:s,$ai_metric_value:String(r)})}Cn(e){var s=Ke(e)&&!e,r=Q.N()&&Q.P("ph_debug")==="true";return!s&&(!!r||e)}}Te.__defaultExtensionClasses={},Te.rs=(()=>{var t=()=>{};return{trace:t,debug:t,info:t,warn:t,error:t,fatal:t}})(),(function(t,e){for(var s=0;e.length>s;s++)t.prototype[e[s]]=ip(t.prototype[e[s]])})(Te,["identify"]);class Al{constructor(e){this.disabled=e===!1;var s=te(e)?e:{};this.thresholdPx=s.threshold_px||30,this.timeoutMs=s.timeout_ms||1e3,this.clickCount=s.click_count||3,this.clicks=[]}isRageClick(e,s,r){if(this.disabled)return!1;var i=this.clicks[this.clicks.length-1];if(i&&Math.abs(e-i.x)+Math.abs(s-i.y)r-i.timestamp){if(this.clicks.push({x:e,y:s,timestamp:r}),this.clicks.length===this.clickCount)return!0}else this.clicks=[{x:e,y:s,timestamp:r}];return!1}}var _n="$copy_autocapture",yn=se("[AutoCapture]");function wn(t,e){return e.length>t?e.slice(0,t)+"...":e}function cf(t){if(t.previousElementSibling)return t.previousElementSibling;var e=t;do e=e.previousSibling;while(e&&!Ft(e));return e}function uf(t,e){var s,r,i=e.e,n=e.maskAllElementAttributes,o=e.maskAllText,a=e.elementAttributeIgnoreList,l=e.elementsChainAsString,u=e.disableCaptureUrlHashes;if(!Ft(t))return{props:{}};for(var c=[t],d=new Set([t]),h=t;h.parentNode&&!Me(h,"body")&&Su>c.length;)if(Eu(h.parentNode)){var p=h.parentNode.host;if(d.has(p))break;d.add(p),c.push(p),h=p}else{if(!Ft(h.parentNode)||d.has(h.parentNode))break;d.add(h.parentNode),c.push(h.parentNode),h=h.parentNode}var f,g,m=[],_={},E=!1,b=!1;if(Z(c,(S=>{var A=ro(S);if(Me(S,"a")){var R=S.getAttribute("href");E=!!(A&&R&&Ks(R))&&(u?Ct(R):R)}M(ai(S),"ph-no-capture")&&(b=!0),m.push((function(T,O,J,z,H){H===void 0&&(H=!1);var oe=T.tagName.toLowerCase(),pe={tag_name:oe};Vo.indexOf(oe)>-1&&!J&&(pe.$el_text=oe.toLowerCase()==="a"||oe.toLowerCase()==="button"?wn(1024,dl(T)):wn(1024,rr(T)));var Ie=ai(T);Ie.length>0&&(pe.classes=Ie.filter((function(ae){return ae!==""}))),Z(T.attributes,(function(ae){var me;if((!Fu(T)||["name","id","class","aria-label"].indexOf(ae.name)!==-1)&&(z==null||!z.includes(ae.name))&&!O&&Ks(ae.value)&&(!W(me=ae.name)||me.substring(0,10)!=="_ngcontent"&&me.substring(0,7)!=="_nghost")){var ge=ae.value;ae.name==="class"&&(ge=qo(ge).join(" ")),pe["attr__"+ae.name]=wn(1024,ae.name==="href"&&H?Ct(ge):ge)}}));for(var _e=1,Ce=1,Re=T;Re=cf(Re);)_e++,Re.tagName===T.tagName&&Ce++;return pe.nth_child=_e,pe.nth_of_type=Ce,pe})(S,n,o,a,u));var N=(function(T){if(!ro(T))return{};var O={};return Z(T.attributes,(function(J){if(J.name&&J.name.indexOf("data-ph-capture-attribute")===0){var z=J.name.replace("data-ph-capture-attribute-",""),H=J.value;z&&H&&Ks(H)&&(O[z]=H)}})),O})(S);ee(_,N)})),b)return{props:{},explicitNoCapture:b};if(o||(m[0].$el_text=Me(t,"a")||Me(t,"button")?dl(t):rr(t)),E){var I,F;m[0].attr__href=E;var P=(I=li(E))==null?void 0:I.host,B=v==null||(F=v.location)==null?void 0:F.host;P&&B&&P!==B&&(f=E)}return{props:ee({$event_type:i.type,$ce_version:1},l?{}:{$elements:m},{$elements_chain:(g=m,(function(S){return S.map((A=>{var R,N,T="";if(A.tag_name&&(T+=A.tag_name),A.attr_class)for(var O of(A.attr_class.sort(),A.attr_class))T+="."+O.replace(/"/g,"");var J=w({},A.text?{text:A.text}:{},{"nth-child":(R=A.nth_child)!==null&&R!==void 0?R:0,"nth-of-type":(N=A.nth_of_type)!==null&&N!==void 0?N:0},A.href?{href:A.href}:{},A.attr_id?{attr_id:A.attr_id}:{},A.attributes),z={};return Or(J).sort(((H,oe)=>H[0].localeCompare(oe[0]))).forEach((H=>{var oe=H[1];return z[hl(H[0].toString())]=hl(oe.toString())})),(T+=":")+Or(z).map((H=>H[0]+'="'+H[1]+'"')).join("")})).join(";")})((function(S){return S.map((A=>{var R,N,T={text:(R=A.$el_text)==null?void 0:R.slice(0,400),tag_name:A.tag_name,href:(N=A.attr__href)==null?void 0:N.slice(0,2048),attr_class:Sp(A),attr_id:A.attr__id,nth_child:A.nth_child,nth_of_type:A.nth_of_type,attributes:{}};return Or(A).filter((O=>O[0].indexOf("attr__")===0)).forEach((O=>T.attributes[O[0]]=O[1])),T}))})(g)))},(s=m[0])!=null&&s.$el_text?{$el_text:(r=m[0])==null?void 0:r.$el_text}:{},f&&i.type==="click"?{$external_click_url:f}:{},_)}}var Ms=se("[ExceptionAutocapture]"),$l=()=>{},df=se("[TracingHeaders]"),Lt=se("[Web Vitals]"),Rl=9e5,Tl="disabled",Nl="lazy_loading",Ls="awaiting_config",Fr="missing_config";se("[SessionRecording]"),se("[SessionRecording]");var ho="[SessionRecording]",at=se(ho),hf=se("[Heatmaps]");function bn(t){return te(t)&&"clientX"in t&&"clientY"in t&&he(t.clientX)&&he(t.clientY)}var Pr=se("[Product Tours]"),En=t=>{var e;return!t.config.disable_product_tours&&!((e=t.persistence)==null||!e.get_property(Uo))},pf=["$set_once","$set"],Ze=se("[SiteApps]"),Ml="Error while initializing PostHog app with config id ";function is(t,e,s){if(D(t))return!1;switch(s){case"exact":return t===e;case"contains":var r=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/_/g,".").replace(/%/g,".*");return new RegExp(r,"i").test(t);case"regex":try{return new RegExp(e).test(t)}catch{return!1}default:return!1}}class ff{constructor(e){this.ns=new Yo,this.ss=(s,r)=>this.os(s,r)&&this.ls(s,r)&&this.us(s,r)&&this.hs(s,r),this.os=(s,r)=>r==null||!r.event||s?.event===r?.event,this._instance=e,this.ds=new Set,this.vs=new Set}init(){var e,s;x((e=this._instance)==null?void 0:e._addCaptureHook)||(s=this._instance)==null||s._addCaptureHook(((r,i)=>{this.on(r,i)}))}register(e){var s,r;if(!x((s=this._instance)==null?void 0:s._addCaptureHook)&&(e.forEach((o=>{var a,l;(a=this.vs)==null||a.add(o),(l=o.steps)==null||l.forEach((u=>{var c;(c=this.ds)==null||c.add(u?.event||"")}))})),(r=this._instance)!=null&&r.autocapture)){var i,n=new Set;e.forEach((o=>{var a;(a=o.steps)==null||a.forEach((l=>{l!=null&&l.selector&&n.add(l?.selector)}))})),(i=this._instance)==null||i.autocapture.setElementSelectors(n)}}on(e,s){var r;s!=null&&e.length!=0&&(this.ds.has(e)||this.ds.has(s.event))&&this.vs&&((r=this.vs)==null?void 0:r.size)>0&&this.vs.forEach((i=>{this.cs(s,i)&&this.ns.emit("actionCaptured",i.name)}))}fs(e){this.onAction("actionCaptured",(s=>e(s)))}cs(e,s){if(s?.steps==null)return!1;for(var r of s.steps)if(this.ss(e,r))return!0;return!1}onAction(e,s){return this.ns.on(e,s)}ls(e,s){if(s!=null&&s.url){var r,i=e==null||(r=e.properties)==null?void 0:r.$current_url;if(!i||typeof i!="string"||!is(i,s.url,s.url_matching||"contains"))return!1}return!0}us(e,s){return!!this.ps(e,s)&&!!this.gs(e,s)&&!!this.ys(e,s)}ps(e,s){var r;if(s==null||!s.href)return!0;var i=this.bs(e);if(i.length>0)return i.some((a=>is(a.href,s.href,s.href_matching||"exact")));var n,o=(e==null||(r=e.properties)==null?void 0:r.$elements_chain)||"";return!!o&&is((n=o.match(/(?::|")href="(.*?)"/))?n[1]:"",s.href,s.href_matching||"exact")}gs(e,s){var r;if(s==null||!s.text)return!0;var i=this.bs(e);if(i.length>0)return i.some((u=>is(u.text,s.text,s.text_matching||"exact")||is(u.$el_text,s.text,s.text_matching||"exact")));var n,o,a,l=(e==null||(r=e.properties)==null?void 0:r.$elements_chain)||"";return!!l&&(n=(function(u){for(var c,d=[],h=/(?::|")text="(.*?)"/g;!D(c=h.exec(u));)d.includes(c[1])||d.push(c[1]);return d})(l),o=s.text,a=s.text_matching||"exact",n.some((u=>is(u,o,a))))}ys(e,s){var r,i;if(s==null||!s.selector)return!0;var n=e==null||(r=e.properties)==null?void 0:r.$element_selectors;if(n!=null&&n.includes(s.selector))return!0;var o=(e==null||(i=e.properties)==null?void 0:i.$elements_chain)||"";if(s.selector_regex&&o)try{return new RegExp(s.selector_regex).test(o)}catch{return!1}return!1}bs(e){var s;return(e==null||(s=e.properties)==null?void 0:s.$elements)==null?[]:e?.properties.$elements}hs(e,s){return s==null||!s.properties||s.properties.length===0||sd(s.properties.reduce(((r,i)=>{var n=L(i.value)?i.value.map(String):i.value!=null?[String(i.value)]:[];return r[i.key]={values:n,operator:i.operator||"exact"},r}),{}),e?.properties)}}class gf{constructor(e){var s;this._s=[],this._instance=e,this.ws=new Map,this.ks=new Map,this.xs=new Map,(s=this._instance)==null||s.onSessionId==null||s.onSessionId((r=>this.Ss(r)))}Cs(e){return!1}Ms(){return null}Ts(e){}Es(){}Is(e,s){return!!e&&sd(e.propertyFilters,s?.properties)}Ps(e,s){var r=new Map;return e.forEach((i=>{var n;(n=i.conditions)==null||(n=n[s])==null||(n=n.values)==null||n.forEach((o=>{if(o!=null&&o.name){var a=r.get(o.name)||[];a.push(i.id),r.set(o.name,a)}}))})),r}Rs(e,s,r){var i=(r===As.Activation?this.ws:this.ks).get(e),n=[];return this.As((o=>{n=o.filter((a=>i?.includes(a.id)))})),n.filter((o=>{var a,l=(a=o.conditions)==null||(a=a[r])==null||(a=a.values)==null?void 0:a.find((u=>u.name===e));return this.Is(l,s)}))}register(e){var s;x((s=this._instance)==null?void 0:s._addCaptureHook)||(this.Fs(e),this.Ls(e))}Ls(e){var s=e.filter((r=>{var i,n;return((i=r.conditions)==null?void 0:i.actions)&&((n=r.conditions)==null||(n=n.actions)==null||(n=n.values)==null?void 0:n.length)>0}));s.length!==0&&(this.Os==null&&(this.Os=new ff(this._instance),this.Os.init(),this.Os.fs((r=>{this.onAction(r)}))),s.forEach((r=>{var i,n,o,a,l;r.conditions&&(i=r.conditions)!=null&&i.actions&&(n=r.conditions)!=null&&(n=n.actions)!=null&&n.values&&((o=r.conditions)==null||(o=o.actions)==null||(o=o.values)==null?void 0:o.length)>0&&((a=this.Os)==null||a.register(r.conditions.actions.values),(l=r.conditions)==null||(l=l.actions)==null||(l=l.values)==null||l.forEach((u=>{if(u&&u.name){var c=this.xs.get(u.name);c&&c.push(r.id),this.xs.set(u.name,c||[r.id])}})))})))}Fs(e){var s,r=e.filter((n=>{var o,a;return((o=n.conditions)==null?void 0:o.events)&&((a=n.conditions)==null||(a=a.events)==null||(a=a.values)==null?void 0:a.length)>0})),i=e.filter((n=>{var o,a;return((o=n.conditions)==null?void 0:o.cancelEvents)&&((a=n.conditions)==null||(a=a.cancelEvents)==null||(a=a.values)==null?void 0:a.length)>0}));r.length===0&&i.length===0||((s=this._instance)==null||s._addCaptureHook(((n,o)=>{this.onEvent(n,o)})),this.ws=this.Ps(e,As.Activation),this.ks=this.Ps(e,As.Cancellation))}onEvent(e,s){var r,i,n=this.Ds(),o=(s==null||(r=s.properties)==null?void 0:r.$survey_id)||(s==null||(i=s.properties)==null?void 0:i.$product_tour_id);if(o&&this.getActivatedIds().includes(o)){var a=this.$s(e,o);if(a==="consume")return n.info("event consumed activated item, removing it",{event:e,itemId:o}),void this.Ns([o]);if(a==="persist")return n.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,s,As.Cancellation);l.length>0&&(n.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)){n.info("event name matched",{event:e,eventPayload:s,items:this.ws.get(e)});var u=this.Rs(e,s,As.Activation);this.Hs(u.map((c=>c.id)))}}onAction(e){this.xs.has(e)&&this.Hs(this.xs.get(e)||[])}Hs(e){var s;if(e.length!==0){var r=!((s=this._instance)==null||s.get_session_id==null||!s.get_session_id()),i=[];for(var n of e)r&&this.Cs(n)?this.qs(n)&&this.Us(n):i.push(n);i.length>0&&(this._s=[...new Set([...this._s,...i])]),this.Ds().info("updating activated items",{activatedItems:this.getActivatedIds()})}}qs(e){this._s=this._s.filter((r=>r!==e));var s=this.zs();return!s.includes(e)&&(this.Ws([...s,e]),this.Vs(),!0)}Ns(e){var s=new Set(e);this._s=this._s.filter((n=>!s.has(n)));var r=this.Zs(),i=r.filter((n=>!s.has(n)));i.length!==r.length&&(this.Ws(i),i.length===0&&this.Gs()),this.js(e)}Qs(){var e,s=this.Ms();if(!s)return{};var r=(e=this._instance)==null||(e=e.persistence)==null?void 0:e.props[s];return r&&typeof r=="object"?r:{}}Us(e){if(this.Ms()){var s=this.Qs();this.Ts(w({},s,{[e]:Date.now()}))}}js(e){if(this.Ms()){var s=this.Qs(),r={},i=!1;for(var n of Object.entries(s)){var o=n[0],a=n[1];e.includes(o)?i=!0:r[o]=a}i&&(mt(r)?this.Es():this.Ts(r))}}Ks(){this.Ms()&&this.Es()}getActivationTimestamp(e){if(this.zs().includes(e)){var s=this.Qs()[e];return he(s)?s:void 0}}Zs(){var e,s=this.Js();return((e=this._instance)==null||(e=e.persistence)==null?void 0:e.props[s])||[]}zs(){var e,s,r=this.Zs();if(r.length===0)return[];var i=(e=this._instance)==null||(e=e.persistence)==null?void 0:e.props[this.Ys()],n=(s=this._instance)==null||s.get_session_id==null?void 0:s.get_session_id();return n&&i===n?r:[]}Vs(){var e,s=(e=this._instance)==null||e.get_session_id==null?void 0:e.get_session_id();s&&this.Xs(s)}Gs(){this.ta()}Ss(e){var s,r=(s=this._instance)==null||(s=s.persistence)==null?void 0:s.props[this.Ys()];if(r&&r!==e){var i=this.Zs(),n=this.Qs();i.length>0&&(this.Ws([]),i.filter((o=>he(n[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 mf extends gf{constructor(e){super(e)}Js(){return Jn}Ys(){return Nr}Ms(){return Mr}Ts(e){var s;(s=this._instance)==null||(s=s.persistence)==null||s.register({[Mr]:e})}Es(){var e;(e=this._instance)==null||(e=e.persistence)==null||e.unregister(Mr)}Cs(e){var s,r;this.As((n=>{r=n.find((o=>o.id===e))}));var i=(s=r)==null||(s=s.appearance)==null?void 0:s.surveyPopupDelaySeconds;return he(i)&&i>0}ra(){return ft.SHOWN}As(e){var s;(s=this._instance)==null||s.getSurveys(e)}Bs(e){var s;(s=this._instance)==null||s.cancelPendingSurvey(e)}Ds(){return q}Ws(e){var s;(s=this._instance)==null||(s=s.persistence)==null||s.register({[Jn]:e})}Xs(e){var s;(s=this._instance)==null||(s=s.persistence)==null||s.register({[Nr]:e})}ta(){var e;(e=this._instance)==null||(e=e.persistence)==null||e.unregister(Nr)}ea(){return!1}$s(e,s){var r;this.As((n=>{r=n.find((o=>o.id===s))}));var i=!r||(function(n){var o;return rd(n)&&!((o=n.conditions)==null||(o=o.events)==null||!o.repeatedActivation)||n.schedule==="always"})(r);return i?e===ft.SHOWN?"consume":"ignore":e===ft.SHOWN?"persist":e===ft.DISMISSED||e===ft.SENT?"consume":"ignore"}getSurveys(){return this.getActivatedIds()}getEventToSurveys(){return this.getEventToItemsMap()}}var Ar="SDK is not enabled or survey functionality is not yet loaded",Ll="Disabled. Not loading surveys.",vf=v!=null&&v.location?ci(v.location.hash,"__posthog")||ci(location.hash,"state"):null,Ol="_postHogToolbarParams",Dl=se("[Toolbar]"),Bl=se("[FeatureFlags]");class _f{constructor(e,s){s===void 0&&(s=!1),this.na=!1,this.update(e,s)}update(e,s){this.sa=((r,i)=>{var n,o,a,l;return{bootstrap:{featureFlags:(n=r.bootstrap)==null?void 0:n.featureFlags,featureFlagPayloads:(o=r.bootstrap)==null?void 0:o.featureFlagPayloads},remoteRequestsDisabled:i,featureFlagsDisabled:!!r.advanced_disable_feature_flags,onlyEvaluateSurveyFeatureFlags:!!r.advanced_only_evaluate_survey_feature_flags,deduplicateCallsPerSession:!!r.advanced_feature_flags_dedup_per_session,cacheTtlMs:r.feature_flag_cache_ttl_ms,requestTimeoutMs:r.feature_flag_request_timeout_ms,compression:r.disable_compression?"none":"base64",evaluationContexts:(a=(l=r.evaluation_contexts)!==null&&l!==void 0?l:r.evaluation_environments)!==null&&a!==void 0?a:[],flagKeys:L(r.flag_keys)?r.flag_keys:void 0}})(e,s),!e.evaluation_environments||e.evaluation_contexts||this.na||(Bl.warn("evaluation_environments is deprecated. Use evaluation_contexts instead. evaluation_environments will be removed in a future version."),this.na=!0),x(e.flag_keys)||L(e.flag_keys)||Bl.error("Invalid flag_keys found:",e.flag_keys,"Expected array of non-empty strings")}get(){return this.sa}}var jl=se("[FeatureFlags]"),Ot=se("[FeatureFlags]",{debugEnabled:!0}),Sn=`" failed. Feature flags didn't load in time.`,Ul="connection_error",Hl=t=>{for(var e={},s=0;t.length>s;s++)e[t[s]]=!0;return e},Wl=t=>{var e={};for(var s of Or(t||{})){var r=s[1];r&&(e[s[0]]=r)}return e},Xe=se("[Error tracking]"),zl="Refusing to render web experiment since the viewer is a likely bot",yf={icontains:(t,e)=>e.toLowerCase().indexOf(t.toLowerCase())>-1,not_icontains:(t,e)=>e.toLowerCase().indexOf(t.toLowerCase())===-1,regex:(t,e)=>hi(e,t),not_regex:(t,e)=>!hi(e,t),exact:(t,e)=>e===t,is_not:(t,e)=>e!==t};class ye{get Ne(){return this._instance.config}constructor(e){var s=this;this.getWebExperimentsAndEvaluateDisplayLogic=function(r){r===void 0&&(r=!1),s.getWebExperiments((i=>{ye.aa("retrieved web experiments from the server"),s.oa=new Map,i.forEach((n=>{if(n.feature_flag_key){var o;s.oa&&(ye.aa("setting flag key ",n.feature_flag_key," to web experiment ",n),(o=s.oa)==null||o.set(n.feature_flag_key,n));var a=s._instance.getFeatureFlag(n.feature_flag_key);W(a)&&n.variants[a]&&s.la(n.name,a,n.variants[a].transforms)}else if(n.variants)for(var l in n.variants){var u=n.variants[l];ye.ua(u,s._instance)&&s.la(n.name,l,u.transforms)}}))}),r)},this._instance=e,this._instance.onFeatureFlags((r=>{this.onFeatureFlags(r)}))}initialize(){}onFeatureFlags(e){if(this._is_bot())ye.aa(zl);else if(!this.Ne.disable_web_experiments){if(D(this.oa))return this.oa=new Map,this.loadIfEnabled(),void this.previewWebExperiment();ye.aa("applying feature flags",e),e.forEach((s=>{var r;if(this.oa&&(r=this.oa)!=null&&r.has(s)){var i,n=this._instance.getFeatureFlag(s),o=(i=this.oa)==null?void 0:i.get(s);n&&o!=null&&o.variants[n]&&this.la(o.name,n,o.variants[n].transforms)}}))}}previewWebExperiment(){var e=ye.getWindowLocation();if(e!=null&&e.search){var s=vs(e?.search,"__experiment_id"),r=vs(e?.search,"__experiment_variant");s&&r&&(ye.aa("previewing web experiments "+s+" && "+r),this.getWebExperiments((i=>{this.ha(parseInt(s),r,i)}),!1,!0))}}loadIfEnabled(){this.Ne.disable_web_experiments||this.getWebExperimentsAndEvaluateDisplayLogic()}getWebExperiments(e,s,r){if(this.Ne.disable_web_experiments&&!r)return e([]);var i=this._instance.get_property("$web_experiments");if(i&&!s)return e(i);this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/web_experiments/?token="+this.Ne.token),method:"GET",timestampMode:"query",callback:n=>e(n.statusCode===200&&n.json&&n.json.experiments||[])})}ha(e,s,r){var i=r.filter((n=>n.id===e));i&&i.length>0&&(ye.aa("Previewing web experiment ["+i[0].name+"] with variant ["+s+"]"),this.la(i[0].name,s,i[0].variants[s].transforms))}static ua(e,s){return!D(e.conditions)&&ye.da(e,s)&&ye.va(e)}static da(e,s){var r;if(D(e.conditions)||D((r=e.conditions)==null?void 0:r.url))return!0;var i=ye.getWindowLocation();if(i){var n,o,a,l=yu(s,i.href);return(n=e.conditions)==null||!n.url||yf[(o=(a=e.conditions)==null?void 0:a.urlMatchType)!==null&&o!==void 0?o:"icontains"](e.conditions.url,l)}return!1}static getWindowLocation(){return v?.location}static va(e){var s;if(D(e.conditions)||D((s=e.conditions)==null?void 0:s.utm))return!0;var r=Nu();if(r.utm_source){var i,n,o,a,l,u,c,d,h=(i=e.conditions)==null||(i=i.utm)==null||!i.utm_campaign||((n=e.conditions)==null||(n=n.utm)==null?void 0:n.utm_campaign)==r.utm_campaign,p=(o=e.conditions)==null||(o=o.utm)==null||!o.utm_source||((a=e.conditions)==null||(a=a.utm)==null?void 0:a.utm_source)==r.utm_source,f=(l=e.conditions)==null||(l=l.utm)==null||!l.utm_medium||((u=e.conditions)==null||(u=u.utm)==null?void 0:u.utm_medium)==r.utm_medium,g=(c=e.conditions)==null||(c=c.utm)==null||!c.utm_term||((d=e.conditions)==null||(d=d.utm)==null?void 0:d.utm_term)==r.utm_term;return h&&f&&g&&p}return!1}static aa(e){for(var s=arguments.length,r=new Array(s>1?s-1:0),i=1;s>i;i++)r[i-1]=arguments[i];k.info("[WebExperiments] "+e,r)}la(e,s,r){this._is_bot()?ye.aa(zl):s!=="control"?r.forEach((i=>{if(i.selector){var n;ye.aa("applying transform of variant "+s+" for experiment "+e+" ",i);var o=(n=document)==null?void 0:n.querySelectorAll(i.selector);o?.forEach((a=>{var l=a;i.html&&(l.innerHTML=i.html),i.css&&l.setAttribute("style",i.css)}))}})):ye.aa("Control variants leave the page unmodified.")}_is_bot(){return ke&&this._instance?Qu(ke,this.Ne.custom_blocked_useragents):void 0}}var Ue=se("[Conversations]"),Dt="Conversations not available yet.",ql="console",ld="__posthogHandledLogsRequestError",xn=(t,e)=>{var s=t instanceof Error?t:new Error(e);return s[ld]=!0,s},Vl=t=>!!t&&typeof t=="object"&&t[ld]===!0,$i={featureFlags:class{constructor(t){this.name="featureFlags",this.ca=!1,this.featureFlagEventHandlers=[],this.rt=jl,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 _f(t.config,t.Qi()),this.Ta=this.Ea)}updateConfig(t,e){var s;(s=this.Ea)==null||s.update(t,e)}setup(t){return this.Ia=t,this.rt=t.logger.createLogger("[FeatureFlags]"),s=()=>{this.Ia===t&&(this.Ia=void 0,this.nn=t,this.Pa(t))},(e=t.kv.initialize())!=null&&e.then?e.then(s):s();var e,s}Pa(t){if(this.nn===t)return v&&ie(v,"online",this.Ca),this.Ra=t.registerDynamicEventProperties((()=>this.Aa()?this.fa:this.pa)),this.Fa(),this.initialize()}destroy(){v?.removeEventListener("online",this.Ca)}dispose(){var t;this.ba++,this.wa=!1,this.Ia=void 0,this.nn&&(this.La(),(t=this.Ra)==null||t.dispose(),this.Ra=void 0,this.ga=[],v?.removeEventListener("online",this.Ca),this.nn=void 0)}get Ne(){return this.Ta.get()}Oa(t){var e;return(e=this.nn)==null?void 0:e.kv.get(t)}F(t){this.Da((()=>{var e;return(e=this.nn)==null?void 0:e.kv.set(t)}))}q(t){this.Da((()=>{var e;return(e=this.nn)==null?void 0:e.kv.remove(t)}))}Da(t){try{t()}catch(e){this.rt.error("Failed to update feature flag persistence",e)}}Fa(){var t={};for(var e of[Us,Hs,Tr,et]){var s=this.Oa(e);x(s)||(t[e]=s)}this.fa=t;var r=w({},t),i=this.Oa(Bt);if(i)for(var n of Object.entries(i))r["$feature/"+n[0]]=n[1];this.pa=r}Aa(){var t=this.Ne.cacheTtlMs;if(!t||0>=t)return!1;var e=this.Oa(Gs);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 s=e&&typeof e=="string"&&e.trim().length>0;return s||this.rt.error("Invalid evaluation context found:",e,"Expected non-empty string"),s})):[]}qa(){var t=this.Ne.flagKeys;if(!x(t))return t.filter((e=>{var s=e&&typeof e=="string"&&e.trim().length>0;return s||this.rt.error("Invalid flag key found:",e,"Expected non-empty string"),s}))}initialize(){var t,e,s=this.Ne,r=(t=(e=s.bootstrap)==null?void 0:e.featureFlags)!==null&&t!==void 0?t:{};if(Object.keys(r).length){var i,n,o=(i=(n=s.bootstrap)==null?void 0:n.featureFlagPayloads)!==null&&i!==void 0?i:{},a=Object.keys(r).filter((u=>!!r[u])).reduce(((u,c)=>(u[c]=r[c]||!1,u)),{}),l=Object.keys(o).filter((u=>a[u])).reduce(((u,c)=>(o[c]&&(u[c]=o[c]),u)),{});return this.ja({featureFlags:a,featureFlagPayloads:l})}}updateFlags(t,e,s){var r,i,n=s!=null&&s.merge&&(r=this.Oa(Bt))!==null&&r!==void 0?r:{},o=s!=null&&s.merge&&(i=this.Oa(Hs))!==null&&i!==void 0?i:{},a=w({},n,t),l=w({},o,e),u={};for(var c of Object.entries(a)){var d=c[0],h=c[1];u[d]={key:d,enabled:Da(h),variant:Ba(h),reason:void 0,metadata:x(l?.[d])?void 0:{id:0,version:void 0,description:void 0,payload:l[d]}}}this.ja({flags:u})}get hasLoadedFlags(){return this.ma}getFlags(){return Object.keys(this.getFlagVariants())}getFlagsWithDetails(){var t=this.Oa(Gn),e=this.Oa(et),s=this.Oa(jt);if(!s&&!e)return t||{};var r=ee({},t||{}),i=[...new Set([...Object.keys(s||{}),...Object.keys(e||{})])];for(var n of i){var o,a,l=r[n],u=e?.[n],c=x(u)?(o=l?.enabled)!==null&&o!==void 0&&o:!!u,d=x(u)?l?.variant:typeof u=="string"?u:void 0,h=s?.[n],p=w({},l,{enabled:c,variant:c?d??l?.variant:void 0});c!==l?.enabled&&(p.original_enabled=l?.enabled),d!==l?.variant&&(p.original_variant=l?.variant),h&&(p.metadata=w({},l?.metadata,{payload:h,original_payload:l==null||(a=l.metadata)==null?void 0:a.payload})),r[n]=p}return this.ca||(this.rt.warn(" Overriding feature flag details!",{flagDetails:t,overriddenPayloads:s,finalDetails:r}),this.ca=!0),r}getAllFeatureFlags(){var t=this.getFlagVariants(),e=this.getFlagPayloads();return Object.keys(t).map((s=>{var r=t[s];return{key:s,enabled:Da(r),variant:Ba(r),payload:Oa(e[s])}}))}getFlagVariants(){var t=this.Oa(Bt),e=this.Oa(et);if(!e)return t||{};for(var s=ee({},t||{}),r=Object.keys(e),i=0;r.length>i;i++)s[r[i]]=e[r[i]];return this.ca||(this.rt.warn(" Overriding feature flags!",{enabledFlags:t,overriddenFlags:e,finalFlags:s}),this.ca=!0),s}getFlagPayloads(){var t=this.Oa(Hs),e=this.Oa(jt);if(!e)return t||{};for(var s=ee({},t||{}),r=Object.keys(e),i=0;r.length>i;i++)s[r[i]]=e[r[i]];return this.ca||(this.rt.warn(" Overriding feature flag payloads!",{flagPayloads:t,overriddenPayloads:e,finalPayloads:s}),this.ca=!0),s}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(Wt)}Ha(t){this.La();var e=this.nn;if(e&&!this.Ne.remoteRequestsDisabled&&!this.Ma())if(this.ya)this.wa=!0;else{var s={token:e.projectToken,distinct_id:e.distinctId,groups:e.groups,$anon_distinct_id:this.$anon_distinct_id,person_properties:w({},e.initialPersonProperties,this.Oa(ct)||{},{$lib:e.library.name,$lib_version:e.library.version}),group_properties:this.Oa(Ut),timezone:ju()};x(e.deviceId)||(s.$device_id=e.deviceId),(t!=null&&t.disableFlags||this.Ne.featureFlagsDisabled)&&(s.disable_flags=!0);var r=this.Na();r.length&&(s.evaluation_contexts=r);var i=this.qa();x(i)||(s.flag_keys=i);var n=this.Ne.onlyEvaluateSurveyFeatureFlags,o="/flags/?v=2"+(n?"&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({[Lr]:[Ul]}),this.rt.error("Feature flag request failed",c)),l()};try{e.sendRequest(o,{target:"flags",method:"POST",body:s,compression:this.Ne.compression==="base64"?xe.Base64:void 0,sentAt:"body",timeoutMs:this.Ne.requestTimeoutMs}).then((c=>{var d,h,p=(d=c.json)!==null&&d!==void 0?d:{},f=c.statusCode!==200;if(this.ya=!1,a===this.ba){if(this.Ua(c.statusCode),f||this.wa||(this.$anon_distinct_id=void 0),!s.disable_flags||this.wa){this.ka=!f;var g=[];c.error?g.push(c.error instanceof Error&&c.error.name==="AbortError"?"timeout":c.error instanceof Error?Ul:"unknown_error"):c.statusCode!==200&&g.push("api_error_"+c.statusCode),p.errorsWhileComputingFlags&&g.push("errors_while_computing_flags");var m=!((h=p.quotaLimited)==null||!h.includes("feature_flags"));m&&g.push("quota_limited"),this.F({[Lr]: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."):s.disable_flags||this.ja(p,f,{partialResponse:n}),l()}}else l()})).catch(u)}catch(c){u(c)}}}Ma(){return Ru(this.Sa,3)}Ua(t){this.Sa=Tu(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 s;if(e===void 0&&(e={}),!e.fresh||this.ka)if(this.ma||this.getFlags()&&this.getFlags().length>0){if(!this.$a()){var r=this.getFeatureFlagResult(t,e);return(s=r?.variant)!==null&&s!==void 0?s:r?.enabled}}else this.rt.warn('getFeatureFlag for key "'+t+Sn)}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 s,r=this.getFlagVariants(),i=t in r,n=r[t],o=this.getFlagPayloads()[t],a=String(n),l=this.Oa(Tr)||void 0,u=this.Oa(Gs)||void 0,c=this.Oa(Wt)||{};if(this.Ne.deduplicateCallsPerSession){var d,h=(d=this.nn)==null?void 0:d.session.sessionId,p=this.Oa(zs);h&&h!==p&&(c={},s=h)}if(e.send_event||!("send_event"in e))if(t in c&&c[t].includes(a))s&&this.F({[Wt]:c,[zs]:s});else{var f,g,m,_,E,b,I,F,P,B;L(c[t])?c[t].push(a):c[t]=[a],this.F(w({[Wt]:c},s?{[zs]:s}:{}));var S=this.getFeatureFlagDetails(t),A=[...(f=this.Oa(Lr))!==null&&f!==void 0?f:[]];x(n)&&A.push("flag_missing");var R={$feature_flag:t,$feature_flag_response:n,$feature_flag_payload:o||null,$feature_flag_request_id:l,$feature_flag_evaluated_at:u,$feature_flag_bootstrapped_response:((g=this.Ne.bootstrap)==null||(g=g.featureFlags)==null?void 0:g[t])||null,$feature_flag_bootstrapped_payload:((m=this.Ne.bootstrap)==null||(m=m.featureFlagPayloads)==null?void 0:m[t])||null,$used_bootstrap_value:!this.ka};x(S==null||(_=S.metadata)==null?void 0:_.has_experiment)||(R.$feature_flag_has_experiment=S.metadata.has_experiment),x(S==null||(E=S.metadata)==null?void 0:E.version)||(R.$feature_flag_version=S.metadata.version);var N,T=(b=S==null||(I=S.reason)==null?void 0:I.description)!==null&&b!==void 0?b:S==null||(F=S.reason)==null?void 0:F.code;T&&(R.$feature_flag_reason=T),S!=null&&(P=S.metadata)!=null&&P.id&&(R.$feature_flag_id=S.metadata.id),x(S?.original_variant)&&x(S?.original_enabled)||(R.$feature_flag_original_response=x(S.original_variant)?S.original_enabled:S.original_variant),S!=null&&(B=S.metadata)!=null&&B.original_payload&&(R.$feature_flag_original_payload=S==null||(N=S.metadata)==null?void 0:N.original_payload),A.length&&(R.$feature_flag_error=A.join(",")),this.za(R)}else s&&this.F({[Wt]:c,[zs]:s});if(i)return{key:t,enabled:!!n,variant:typeof n=="string"?n:void 0,payload:Oa(o)}}}else this.rt.warn('getFeatureFlagResult for key "'+t+Sn)}za(t){try{var e;(e=this.nn)==null||e.capture("$feature_flag_called",t).catch((s=>{this.rt.error("Failed to capture feature flag call",s)}))}catch(s){this.rt.error("Failed to capture feature flag call",s)}}getRemoteConfigPayload(t,e){this.Wa(t,e)}Wa(t,e){var s=this;return X((function*(){var r=s.nn;if(r){var i={distinct_id:r.distinctId,token:r.projectToken,person_properties:{$lib:r.library.name,$lib_version:r.library.version}},n=s.Na();n.length&&(i.evaluation_contexts=n);var o,a=s.qa();x(a)||(i.flag_keys=a);try{var l,u=(l=(yield r.sendRequest("/flags/?v=2",{target:"flags",method:"POST",body:i,compression:s.Ne.compression==="base64"?xe.Base64:void 0,sentAt:"body",timeoutMs:s.Ne.requestTimeoutMs})).json)==null?void 0:l.featureFlagPayloads;o=u?.[t]||void 0}catch(c){return void s.rt.error("Remote config feature flag request failed",c)}try{e(o)}catch(c){s.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+Sn),e.defaultValue;var s=this.getFeatureFlag(t,e);return x(s)?e.defaultValue:!!s}addFeatureFlagsHandler(t){this.featureFlagEventHandlers.push(t)}removeFeatureFlagsHandler(t){this.featureFlagEventHandlers=this.featureFlagEventHandlers.filter((e=>e!==t))}receivedFeatureFlags(t,e,s){this.ja(t,e,s)}ja(t,e,s){if(this.nn){this.ma=!0;var r=(function(i,n,o,a,l,u){n===void 0&&(n={}),o===void 0&&(o={}),a===void 0&&(a={}),u===void 0&&(u=jl);var c=((P,B)=>{var S=P.flags;return S?w({},P,{featureFlags:Object.fromEntries(Object.keys(S).map((A=>{var R;return[A,(R=S[A].variant)!==null&&R!==void 0?R:S[A].enabled]}))),featureFlagPayloads:Object.fromEntries(Object.keys(S).filter((A=>S[A].enabled)).filter((A=>{var R;return(R=S[A].metadata)==null?void 0:R.payload})).map((A=>{var R;return[A,(R=S[A].metadata)==null?void 0:R.payload]})))}):(P.featureFlags&&B.warn("Using an older version of the feature flags endpoint. Please upgrade your PostHog server to the latest version"),P)})(i,u),d=c.flags,h=c.featureFlags,p=c.featureFlagPayloads;if(h){var f=i.requestId,g=i.evaluatedAt;if(L(h)){u.warn("v1 of the feature flags endpoint is deprecated. Please use the latest version.");var m={};if(h)for(var _=0;h.length>_;_++)m[h[_]]=!0;return{[Us]:h,[Bt]:m,[ei]:!1}}var E=h,b=p,I=d;if(l!=null&&l.partialResponse)E=w({},n,E),b=w({},o,b),I=w({},a,I);else if(i.errorsWhileComputingFlags)if(d){var F=new Set(Object.keys(d).filter((P=>{var B;return!((B=d[P])!=null&&B.failed)})));E=w({},n,Object.fromEntries(Object.entries(E).filter((P=>F.has(P[0]))))),b=w({},o,Object.fromEntries(Object.entries(b||{}).filter((P=>F.has(P[0]))))),I=w({},a,Object.fromEntries(Object.entries(I||{}).filter((P=>F.has(P[0])))))}else E=w({},n,E),b=w({},o,b),I=w({},a,I);return w({[Us]:Object.keys(Wl(E)),[Bt]:E||{},[Hs]:b||{},[Gn]:I||{},[ei]:i.minimalFlagCalledEvents===!0},f?{[Tr]:f}:{},g?{[Gs]:g}:{})}})(t,this.getFlagVariants(),this.getFlagPayloads(),this.getFlagsWithDetails(),s,this.rt);r&&this.F(r),e||(this.xa=!1),this.Va(e)}}override(t,e){e===void 0&&(e=!1),this.rt.warn("override is deprecated. Please use overrideFeatureFlags instead."),this.overrideFeatureFlags({flags:t,suppressWarning:e})}overrideFeatureFlags(t){this.Za(t)}Za(t){if(this.nn){if(t===!1)return this.q([et,jt]),this.Va(),void Ot.info("All overrides cleared");if(L(t))return this.F({[et]:Hl(t)}),this.Va(),void Ot.info("Flag overrides set",{flags:t});if(t&&typeof t=="object"&&("flags"in t||"payloads"in t)){var e,s=t;this.ca=!!((e=s.suppressWarning)!==null&&e!==void 0&&e);var r={},i=s.flags,n=s.payloads;return i&&(r[et]=L(i)?Hl(i):i),n&&(r[jt]=n),Object.keys(r).length&&this.F(r),i===!1&&n===!1?this.q([et,jt]):i===!1?this.q(et):n===!1&&this.q(jt),this.Va(),i===!1?Ot.info("Flag overrides cleared"):i&&Ot.info("Flag overrides set",{flags:i}),void(n===!1?Ot.info("Payload overrides cleared"):n&&Ot.info("Payload overrides set",{payloads:n}))}if(t&&typeof t=="object")return this.F({[et]:t}),this.Va(),void Ot.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(),s=e.flags,r=e.flagVariants;try{t(s,r)}catch(i){this.rt.error("Error while running feature flags callback",i)}}return()=>this.removeFeatureFlagsHandler(t)}updateEarlyAccessFeatureEnrollment(t,e,s){var r=(this.Oa(Rr)||[]).find((l=>l.flagKey===t)),i={["$feature_enrollment/"+t]:e},n={$feature_flag:t,$feature_enrollment:e,$set:i};r&&(n.$early_access_feature_name=r.name),s&&(n.$feature_enrollment_stage=s);var o=w({},this.getFlagVariants(),{[t]:e});this.F({[Us]:Object.keys(Wl(o)),[Bt]:o,[ct]:w({},this.Oa(ct)||{},i)}),this.Va();try{var a;(a=this.nn)==null||a.capture("$feature_enrollment_update",n).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,s){e===void 0&&(e=!1);var r=this.Oa(Rr);!r||e?this.Qa(t,s):t(r)}Qa(t,e){var s=this;return X((function*(){var r=s.nn;if(r){var i,n=e?"&"+e.map((a=>"stage="+a)).join("&"):"";try{var o=yield r.sendRequest("/api/early_access_features/?token="+r.projectToken+n,{target:"api",method:"GET",sentAt:"query"});if(!o.json)return;s.F({[Rr]:i=o.json.earlyAccessFeatures})}catch(a){return void s.rt.error("Early access feature request failed",a)}try{t(i)}catch(a){s.rt.error("Early access feature callback failed",a)}}}))()}Ga(){var t=this.getFlags(),e=this.getFlagVariants();return{flags:t.filter((s=>e[s])),flagVariants:Object.keys(e).filter((s=>e[s])).reduce(((s,r)=>(s[r]=e[r],s)),{})}}Va(t){this.Fa();var e=this.Ga(),s=e.flags,r=e.flagVariants;this.featureFlagEventHandlers.forEach((i=>{try{i(s,r,{errorsLoading:t})}catch(n){this.rt.error("Error while running feature flags callback",n)}}))}setPersonPropertiesForFlags(t,e){e===void 0&&(e=!0),this.Ka(t,e)}Ka(t,e){e===void 0&&(e=!0);var s=this.Oa(ct)||{},r=t?.$set||(t!=null&&t.$set_once?{}:t),i=t?.$set_once,n={};if(i)for(var o in i)({}).hasOwnProperty.call(i,o)&&(o in s||(n[o]=i[o]));this.F({[ct]:w({},s,n,r)}),e&&this.reloadFeatureFlags()}unsetPersonPropertiesForFlags(t,e){e===void 0&&(e=!0);var s=w({},this.Oa(ct)||{});t.forEach((r=>{delete s[r]})),this.F({[ct]:s}),e&&this.reloadFeatureFlags()}resetPersonPropertiesForFlags(t){t===void 0&&(t=!0),this.q(ct),t&&this.reloadFeatureFlags()}setGroupPropertiesForFlags(t,e){e===void 0&&(e=!0);var s=this.Oa(Ut)||{},r=w({},s);for(var i of Object.keys(t))r[i]=w({},s[i],t[i]);this.F({[Ut]:r}),e&&this.reloadFeatureFlags()}resetGroupPropertiesForFlags(t){if(t){var e=this.Oa(Ut)||{};this.F({[Ut]:w({},e,{[t]:{}})})}else this.q(Ut)}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}}},wf={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===Ls||this.Ya===Fr?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=Tl,this.Xa=void 0,this.eo=!1,this.io=(()=>{var e;if(C==null||!C.visibilityState||C.visibilityState==="visible")return!0;var s=v==null||(e=v.performance)==null||e.getEntriesByType==null?void 0:e.getEntriesByType("visibility-state");return!(s!=null&&s.length)||s.some((r=>r.name==="visible"))})(),this.Ie=()=>{var e;C?.visibilityState==="visible"&&(this.io=!0,(e=this.Ja)==null||e.setDocumentWasEverVisible==null||e.setDocumentWasEverVisible(!0))},this._instance=t,!this._instance.sessionManager)throw at.error("started without valid sessionManager"),new Error(ho+" started without valid sessionManager. This is a bug.");if(this.Ne.cookieless_mode===ht)throw new Error(ho+' cannot be used with cookieless_mode="always"');C!=null&&C.addEventListener&&ie(C,"visibilitychange",this.Ie)}initialize(){this.startIfEnabledOrStop()}dispose(){this.eo=!0,C==null||C.removeEventListener==null||C.removeEventListener("visibilitychange",this.Ie),this.stopRecording()}get ro(){var t,e=!((t=this._instance.get_property(Vt))==null||!t.enabled),s=!this.Ne.disable_session_recording,r=this.Ne.disable_session_recording||this._instance.consent.isOptedOut();return v&&e&&s&&!r}startIfEnabledOrStop(t){var e;if(!(this.eo||this.ro&&(e=this.Ja)!=null&&e.isStarted)){var s=!x(Object.assign)&&!x(Array.from);this.ro&&s?(this.no(t),at.info("starting")):(this.Ya=Tl,this.stopRecording())}}no(t){var e,s,r;this.ro&&(this.Ya!==Ls&&this.Ya!==Fr&&(this.Ya=Nl),$!=null&&(e=$.__PosthogExtensions__)!=null&&(e=e.rrweb)!=null&&e.record&&(s=$.__PosthogExtensions__)!=null&&s.initSessionRecording?this.so(t):(r=$.__PosthogExtensions__)==null||r.loadExternalDependency==null||r.loadExternalDependency(this._instance,this.ao,(i=>{if(i)return at.error("could not load recorder",i);this.so(t)})))}stopRecording(){var t,e;(t=this.Xa)==null||t.call(this),this.Xa=void 0,(e=this.Ja)==null||e.stop()}oo(){var t,e;(t=this.Xa)==null||t.call(this),this.Xa=void 0,(e=this.Ja)==null||e.discard()}lo(){var t,e;(t=this.Mr)==null||t.unregister(Ho),(e=this.Mr)==null||e.unregister(lu)}uo(t,e){if(D(t))return null;var s,r=he(t)?t:parseFloat(t);return typeof(s=r)!="number"||!Number.isFinite(s)||0>s||s>1?(at.warn(e+" must be between 0 and 1. Ignoring invalid value:",t),null):r}ho(t){if(this.Mr){var e,s,r=this.Mr,i=()=>{var n,o=t.sessionRecording===!1?void 0:t.sessionRecording,a=this.uo((n=this.Ne.session_recording)==null?void 0:n.sampleRate,"session_recording.sampleRate"),l=this.uo(o?.sampleRate,"remote config sampleRate"),u=a??l;D(u)&&this.lo();var c=o?.minimumDurationMilliseconds;r.register({[Vt]:w({cache_timestamp:Date.now(),enabled:!!o},o,{networkPayloadCapture:w({capturePerformance:t.capturePerformance},o?.networkPayloadCapture),canvasRecording:{enabled:o?.recordCanvas,fps:o?.canvasFps,quality:o?.canvasQuality},sampleRate:u,minimumDurationMilliseconds:x(c)?null:c,endpoint:o?.endpoint,triggerMatchType:o?.triggerMatchType,masking:o?.masking,urlTriggers:o?.urlTriggers,version:o?.version,triggerGroups:o?.triggerGroups})})};i(),(e=this.Xa)==null||e.call(this),this.Xa=(s=this._instance.sessionManager)==null?void 0:s.onSessionId(i)}}onRemoteConfig(t){var e=t.ok?t.config:void 0;return e&&"sessionRecording"in e?e.sessionRecording===!1?(this.ho(e),void this.oo()):(this.ho(e),void this.startIfEnabledOrStop()):(this.Ya===Ls&&(this.Ya=Fr,at.warn("config refresh failed, recording will not start until page reload")),void this.startIfEnabledOrStop())}log(t,e){var s;e===void 0&&(e="log"),(s=this.Ja)!=null&&s.log?this.Ja.log(t,e):at.warn("log called before recorder was ready")}get ao(){var t,e,s=(t=this._instance)==null||(t=t.persistence)==null?void 0:t.get_property(Vt);return(s==null||(e=s.scriptConfig)==null?void 0:e.script)||"lazy-recorder"}do(){var t,e=this._instance.get_property(Vt);if(!e)return!1;try{t=typeof e=="object"?e:JSON.parse(e)}catch(s){return at.warn("persisted remote config for session recording is invalid and will be ignored",s),!1}return!D(t.cache_timestamp)&&36e5>=Date.now()-t.cache_timestamp}so(t){var e,s,r;if(!this.eo){if((e=$.__PosthogExtensions__)==null||!e.initSessionRecording)return at.warn("Called on script loaded before session recording is available. This can be caused by adblockers."),void this._instance.register_for_session({[mu]:!0});var i;if(this.Ja||(this.Ja=(i=$.__PosthogExtensions__)==null?void 0:i.initSessionRecording(this._instance,this.io),this.Ja._forceAllowLocalhostNetworkCapture=this._forceAllowLocalhostNetworkCapture),!this.do())return this.Ya===Fr||this.Ya===Ls?void 0:(this.Ya=Ls,at.info("persisted remote config is stale, requesting fresh config before starting"),void new Uu(this._instance).load());this.Ya=Nl,(s=(r=this.Ja).setDocumentWasEverVisible)==null||s.call(r,this.io),this.Ja.start(t)}}onRRwebEmit(t){var e;(e=this.Ja)==null||e.onRRwebEmit==null||e.onRRwebEmit(t)}overrideLinkedFlag(){var t,e;this.Ja||(e=this.Mr)==null||e.register({[uu]:!0}),(t=this.Ja)==null||t.overrideLinkedFlag()}overrideSampling(){var t,e;this.Ja||(e=this.Mr)==null||e.register({[cu]:!0}),(t=this.Ja)==null||t.overrideSampling()}overrideTrigger(t){var e,s;this.Ja||(s=this.Mr)==null||s.register({[t==="url"?du:hu]:!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 s;return!((s=this.Ja)==null||!s.tryAddCustomEvent(t,e))}}},bf={autocapture:class{constructor(t){this.vo=!1,this.co=null,this.fo=!1,this.po=!1,this.instance=t,this.rageclicks=new Al(t.config.rageclick),this.mo=null}initialize(){this.startIfEnabled()}get Ne(){var t,e,s=te(this.instance.config.autocapture)?this.instance.config.autocapture:{};return s.url_allowlist=(t=s.url_allowlist)==null?void 0:t.map((r=>new RegExp(r))),s.url_ignorelist=(e=s.url_ignorelist)==null?void 0:e.map((r=>new RegExp(r))),s}yo(){if(this.isBrowserSupported()){if(v&&C){var t=s=>{s=s||v?.event;try{this.bo(s)}catch(r){yn.error("Failed to capture event",r)}};if(ie(C,"submit",t,{capture:!0}),ie(C,"change",t,{capture:!0}),ie(C,"click",t,{capture:!0}),this.Ne.capture_copied_text){var e=s=>{s=s||v?.event;try{this.bo(s,_n)}catch(r){yn.error("Failed to capture copy/cut event",r)}};ie(C,"copy",e,{capture:!0}),ie(C,"cut",e,{capture:!0})}}}else yn.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 s=e.autocapture_opt_out;Ke(s)&&(this.instance.persistence&&this.instance.persistence.register({[jn]:s}),this.co=s),this.startIfEnabled()}else this.startIfEnabled()}setElementSelectors(t){this.mo=t}getElementSelectors(t){var e,s=[];return(e=this.mo)==null||e.forEach((r=>{var i=C?.querySelectorAll(r);i?.forEach((n=>{t===n&&s.push(r)}))})),s}get isEnabled(){var t,e,s=(t=this.instance.persistence)==null?void 0:t.props[jn],r=this.co,i=this.instance.Qi()&&!this.fo;if($e(r)&&!Ke(s)&&!i)return!1;var n=(e=this.co)!==null&&e!==void 0?e:!!s;return!!this.instance.config.autocapture&&!n}bo(t,e){if(e===void 0&&(e="$autocapture"),this.isEnabled){var s,r=on(t);bu(r)&&(r=r.parentNode||null),e==="$autocapture"&&t.type==="click"&&t instanceof MouseEvent&&this.instance.config.rageclick&&(s=this.rageclicks)!=null&&s.isRageClick(t.clientX,t.clientY,t.timeStamp||new Date().getTime())&&ol(r,this.instance.config.rageclick)&&this.bo(t,"$rageclick");var i=e===_n;if(r&&(function(d,h,p,f,g,m){var _;if(!v||Go(d)||p!=null&&p.url_allowlist&&!rl(p.url_allowlist,m)||p!=null&&p.url_ignorelist&&rl(p.url_ignorelist,m))return!1;if(p!=null&&p.dom_event_allowlist){var E=p.dom_event_allowlist;if(E&&!E.some((S=>h.type===S)))return!1}var b=Cu(d,f),I=b.parentIsUsefulElement,F=b.targetElementList;if(!(function(S,A){var R=A?.element_allowlist;if(x(R))return!0;var N,T=function(J){if(R.some((z=>J.tagName.toLowerCase()===z)))return{v:!0}};for(var O of S)if(N=T(O))return N.v;return!1})(F,p)||!so(F,p?.css_selector_allowlist)||so(F,(_=p?.css_selector_ignorelist)!==null&&_!==void 0?_:vp))return!1;try{var P=v.getComputedStyle(d);if(P&&P.getPropertyValue("cursor")==="pointer"&&h.type==="click")return!0}catch{}var B=d.tagName.toLowerCase();switch(B){case"html":return!1;case"form":return(g||["submit"]).indexOf(h.type)>=0;case"input":case"select":case"textarea":return(g||["change","click"]).indexOf(h.type)>=0;default:return I?(g||["click"]).indexOf(h.type)>=0:(g||["click"]).indexOf(h.type)>=0&&(Vo.indexOf(B)>-1||d.getAttribute("contenteditable")==="true")}})(r,t,this.Ne,i,i?["copy","cut"]:void 0,this.instance)){var n=uf(r,{e:t,maskAllElementAttributes:this.instance.config.mask_all_element_attributes,maskAllText:this.instance.config.mask_all_text,elementAttributeIgnoreList:this.Ne.element_attribute_ignorelist,elementsChainAsString:this.po,disableCaptureUrlHashes:this.instance.config.disable_capture_url_hashes}),o=n.props;if(n.explicitNoCapture)return!1;var a=this.getElementSelectors(r);if(a&&a.length>0&&(o.$element_selectors=a),e===_n){var l,u=xu(v==null||(l=v.getSelection())==null?void 0:l.toString()),c=t.type||"clipboard";if(!u)return!1;o.$selected_content=u,o.$copy_type=c}return this.instance.capture(e,o),!0}}}isBrowserSupported(){return Se(C?.querySelectorAll)}},historyAutocapture:class{constructor(t){var e;this._instance=t,this._o=(v==null||(e=v.location)==null?void 0:e.pathname)||""}initialize(){this.startIfEnabled()}get isEnabled(){return this._instance.config.capture_pageview==="history_change"}startIfEnabled(){this.isEnabled&&(k.info("History API monitoring enabled, starting..."),this.monitorHistoryChanges())}stop(){this.wo&&this.wo(),this.wo=void 0,k.info("History API monitoring stopped")}monitorHistoryChanges(){v&&v.history&&(this.ko("pushState"),this.ko("replaceState"),this.xo())}ko(t){var e;if(v&&((e=v.history[t])==null||!e.__posthog_wrapped__)){var s=this;(function(r,i,n){try{if(!(i in r))return $l;var o={next:r[i]},a=n((function(){for(var l=arguments.length,u=new Array(l),c=0;l>c;c++)u[c]=arguments[c];return o.next.apply(this,u)}));return Se(a)&&(a.prototype=a.prototype||{},Object.defineProperties(a,{__posthog_wrapped__:{enumerable:!1,value:!0},__posthog_layer__:{enumerable:!1,value:o}})),r[i]=a,()=>{if(r[i]!==a)for(var l=r[i];Se(l)&&l.__posthog_layer__;){var u=l.__posthog_layer__;if(u.next===a)return void(u.next=o.next);l=u.next}else r[i]=o.next}}catch{return $l}})(v.history,t,(r=>function(i,n,o){r.call(this,i,n,o),s.So(t)}))}}So(t){try{var e,s=v==null||(e=v.location)==null?void 0:e.pathname;if(!s)return;s!==this._o&&this.isEnabled&&this._instance.capture(os,{navigation_type:t}),this._o=s}catch(r){k.error("Error capturing "+t+" pageview",r)}}xo(){if(!this.wo){var t=()=>{this.So("popstate")};ie(v,"popstate",t),this.wo=()=>{v&&v.removeEventListener("popstate",t)}}}},heatmaps:class{get Ne(){return this.instance.config}constructor(t){var e;this.Co=!1,this.vo=!1,this.Mo=null,this.instance=t,this.Co=!((e=this.instance.persistence)==null||!e.props[Un]),this.rageclicks=new Al(t.config.rageclick)}initialize(){this.startIfEnabled()}get flushIntervalMilliseconds(){var t=5e3;return te(this.Ne.capture_heatmaps)&&this.Ne.capture_heatmaps.flush_interval_milliseconds&&(t=this.Ne.capture_heatmaps.flush_interval_milliseconds),t}get isEnabled(){return D(this.Ne.capture_heatmaps)?D(this.Ne.enable_heatmaps)?this.Co:this.Ne.enable_heatmaps:this.Ne.capture_heatmaps!==!1}startIfEnabled(){if(this.isEnabled){if(this.vo)return;hf.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 s=!!e.heatmaps;this.instance.persistence&&this.instance.persistence.register({[Un]:s}),this.Co=s,this.startIfEnabled()}}}getAndClearBuffer(){var t=this.R;return this.R=void 0,t}Io(t){bn(t.originalEvent)&&this.ke(t.originalEvent,"deadclick")}Ie(){this.Mo&&clearInterval(this.Mo),this.Mo=C?.visibilityState==="visible"?setInterval(this.cr.bind(this),this.flushIntervalMilliseconds):null}To(){v&&C&&(this.Po=this.cr.bind(this),ie(v,ni,this.Po),this.Ro=t=>this.ke(t||v?.event),ie(C,"click",this.Ro,{capture:!0}),this.Ao=t=>this.Fo(t||v?.event),ie(C,"mousemove",this.Ao,{capture:!0}),this.Lo=new pl(this.instance,xp,this.Io.bind(this)),this.Lo.startIfEnabledOrStop(),this.Oo=this.Ie.bind(this),ie(C,ii,this.Oo),this.vo=!0)}Eo(){var t;v&&C&&(this.Po&&v.removeEventListener(ni,this.Po),this.Ro&&C.removeEventListener("click",this.Ro,{capture:!0}),this.Ao&&C.removeEventListener("mousemove",this.Ao,{capture:!0}),this.Oo&&C.removeEventListener(ii,this.Oo),clearTimeout(this.Do),(t=this.Lo)==null||t.stop(),this.vo=!1)}$o(t,e){var s=this.instance.scrollManager.scrollY(),r=this.instance.scrollManager.scrollX(),i=this.instance.scrollManager.scrollElement(),n=(function(o,a,l){for(var u=o;u&&Ft(u)&&!Me(u,"body");){if(u===l)return!1;var c=void 0;try{var d,h,p;c=(d=(h=(p=u.ownerDocument)==null?void 0:p.defaultView)!==null&&h!==void 0?h:v)==null?void 0:d.getComputedStyle(u).position}catch{return!1}if(M(a,c))return!0;u=ku(u)}return!1})(on(t),["fixed","sticky"],i);return{x:t.clientX+(n?0:r),y:t.clientY+(n?0:s),target_fixed:n,type:e}}ke(t,e){var s;if(e===void 0&&(e="click"),!sl(t.target)&&bn(t)){var r=this.$o(t,e);(s=this.rageclicks)!=null&&s.isRageClick(t.clientX,t.clientY,new Date().getTime())&&ol(on(t),this.instance.config.rageclick)&&this.Vt(w({},r,{type:"rageclick"})),this.Vt(r)}}Fo(t){!sl(t.target)&&bn(t)&&(clearTimeout(this.Do),this.Do=setTimeout((()=>{this.Vt(this.$o(t,"mousemove"))}),500))}Vt(t){if(v){var e=this.Ne.disable_capture_url_hashes?Ct(v.location.href):v.location.href,s=this.Ne.custom_personal_data_properties,r=this.Ne.mask_personal_data_properties?[..._s,...s||[]]:[],i=ir(e,r,nr);this.R=this.R||{},this.R[i]||(this.R[i]=[]),this.R[i].push(t)}}cr(){this.R&&!mt(this.R)&&this.instance.capture("$$heatmap",{$heatmap_data:this.getAndClearBuffer()})}},deadClicksAutocapture:pl,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",w({$current_url:this.R.url},this.R.metrics.reduce(((s,r)=>w({},s,{["$web_vitals_"+r.name+"_event"]:w({},r),["$web_vitals_"+r.name+"_value"]:r.value})),{}))),this.R={navigationKey:void 0,url:void 0,metrics:[],firstMetricTimestamp:void 0})},this.jo=s=>{var r;if(this.R=this.R||{navigationKey:void 0,url:void 0,metrics:[],firstMetricTimestamp:void 0},D(s?.name)||D(s?.value))Lt.error("Invalid metric received",s);else{var i=typeof s.navigationURL=="string"?s.navigationURL:void 0,n=this.Bo(i);if(!x(n)){var o=he(s.navigationId)||typeof s.navigationId=="string"?"navigation:"+s.navigationId:"url:"+n;if(!this.Ho||this.Ho>s.value){this.R.navigationKey!==o&&(this.No(),this.qo=setTimeout(this.No,this.flushToCaptureTimeoutMs)),x(this.R.navigationKey)&&(this.R.navigationKey=o,this.R.url=n),this.R.firstMetricTimestamp=x(this.R.firstMetricTimestamp)?Date.now():this.R.firstMetricTimestamp,s.attribution&&s.attribution.interactionTargetElement&&(s.attribution.interactionTargetElement=void 0);var a=(r=this._instance.sessionManager)==null?void 0:r.checkAndGetSessionAndWindowId(!0),l=w({},s,i?{navigationURL:n}:{},{$current_url:n,timestamp:Date.now()});x(a)||(l.$session_id=a.sessionId,l.$window_id=a.windowId),this.R.metrics.push(l),this.R.metrics.length===this.allowedMetrics.length&&this.No()}else Lt.error("Ignoring metric with value >= "+this.Ho,s)}}},this.Uo=()=>{if(!this.vo){var s,r,i,n,o=$.__PosthogExtensions__,a=o?.postHogWebVitalsCallbacksByFlavor,l=a?.[this.zo]||(this.zo==="web-vitals"&&x(a)?o?.postHogWebVitalsCallbacks:void 0);if(x(l)||(s=l.onLCP,r=l.onCLS,i=l.onFCP,n=l.onINP),s&&r&&i&&n){var u={reportSoftNavs:this.useSoftNavs};this.allowedMetrics.indexOf("LCP")>-1&&s(this.jo.bind(this),u),this.allowedMetrics.indexOf("CLS")>-1&&r(this.jo.bind(this),u),this.allowedMetrics.indexOf("FCP")>-1&&i(this.jo.bind(this),u),this.allowedMetrics.indexOf("INP")>-1&&n(this.jo.bind(this),u),this.vo=!0}else Lt.error("web vitals callbacks not loaded - not starting")}},this._instance=t,this.Co=!((e=this._instance.persistence)==null||!e.props[qn]),this.startIfEnabled()}get Wo(){return this._instance.config.capture_performance}get allowedMetrics(){var t,e,s=te(this.Wo)?(t=this.Wo)==null?void 0:t.web_vitals_allowed_metrics:void 0;return D(s)?((e=this._instance.persistence)==null?void 0:e.props[Vn])||["CLS","FCP","INP","LCP"]:s}get flushToCaptureTimeoutMs(){return(te(this.Wo)?this.Wo.web_vitals_delayed_flush_ms:void 0)||5e3}get useAttribution(){var t=te(this.Wo)?this.Wo.web_vitals_attribution:void 0;return t!=null&&t}get useSoftNavs(){var t=te(this.Wo)?this.Wo.__preview_web_vitals_soft_navs:void 0;return t!=null&&t}get Ho(){var t=te(this.Wo)&&he(this.Wo.__web_vitals_max_value)?this.Wo.__web_vitals_max_value:Rl;return t>0&&6e4>=t?Rl:t}get isEnabled(){var t=re?.protocol;if(t!=="http:"&&t!=="https:")return Lt.info("Web Vitals are disabled on non-http/https protocols"),!1;var e=te(this.Wo)?this.Wo.web_vitals:Ke(this.Wo)?this.Wo:void 0;return Ke(e)?e:this.Co}startIfEnabled(){this.isEnabled&&!this.vo&&(Lt.info("enabled, starting..."),this.ai(this.Uo))}onRemoteConfig(t){if(t.ok){var e=t.config;if("capturePerformance"in e){var s=te(e.capturePerformance)&&!!e.capturePerformance.web_vitals,r=te(e.capturePerformance)?e.capturePerformance.web_vitals_allowed_metrics:void 0;this._instance.persistence&&(this._instance.persistence.register({[qn]:s}),this._instance.persistence.register({[Vn]:r})),this.Co=s,this.startIfEnabled()}}}get zo(){return this.useSoftNavs?this.useAttribution?"web-vitals-with-attribution-soft-navs":"web-vitals-soft-navs":this.useAttribution?"web-vitals-with-attribution":"web-vitals"}ai(t){var e=$.__PosthogExtensions__,s=this.zo,r=e?.postHogWebVitalsCallbacksByFlavor;r!=null&&r[s]||s==="web-vitals"&&x(r)&&e!=null&&e.postHogWebVitalsCallbacks?t():e==null||e.loadExternalDependency==null||e.loadExternalDependency(this._instance,s,(i=>{i?Lt.error("failed to load script",i):t()}))}Bo(t){var e=t||v?.location.href;if(e){var s=this._instance.config.disable_capture_url_hashes?Ct(e):e,r=this._instance.config.custom_personal_data_properties,i=this._instance.config.mask_personal_data_properties?[..._s,...r||[]]:[];return ir(s,i,nr)}Lt.error("Could not determine current URL")}}},Ef={exceptionObserver:class{constructor(t){var e;this.Uo=()=>{var s;if(v&&this.isEnabled&&(s=$.__PosthogExtensions__)!=null&&s.errorWrappingFunctions){var r=$.__PosthogExtensions__.errorWrappingFunctions.wrapOnError,i=$.__PosthogExtensions__.errorWrappingFunctions.wrapUnhandledRejection,n=$.__PosthogExtensions__.errorWrappingFunctions.wrapConsoleError;try{!this.Vo&&this.Ne.capture_unhandled_errors&&(this.Vo=r(this.captureException.bind(this))),!this.Zo&&this.Ne.capture_unhandled_rejections&&(this.Zo=i(this.captureException.bind(this))),!this.Go&&this.Ne.capture_console_errors&&(this.Go=n(this.captureException.bind(this)))}catch(o){Ms.error("failed to start",o),this.Qo()}}},this._instance=t,this.Ko=!((e=this._instance.persistence)==null||!e.props[Hn]),this.Jo=new yh(w({},(function(s){var r,i,n,o;return s===void 0&&(s={}),{refillRate:(r=(i=s.exceptionRateLimiterRefillRate)!==null&&i!==void 0?i:s.__exceptionRateLimiterRefillRate)!==null&&r!==void 0?r:1,bucketSize:(n=(o=s.exceptionRateLimiterBucketSize)!==null&&o!==void 0?o:s.__exceptionRateLimiterBucketSize)!==null&&n!==void 0?n:10}})(this._instance.config.error_tracking),{refillInterval:1e4,rt:Ms})),this.Ne=this.Yo(),this.startIfEnabledOrStop()}Yo(){var t=this._instance.config.capture_exceptions,e={capture_unhandled_errors:!1,capture_unhandled_rejections:!1,capture_console_errors:!1};return te(t)?e=w({},e,t):(x(t)?this.Ko:t)&&(e=w({},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?(Ms.info("enabled"),this.Qo(),this.ai(this.Uo)):this.Qo()}ai(t){var e,s;(e=$.__PosthogExtensions__)!=null&&e.errorWrappingFunctions?t():(s=$.__PosthogExtensions__)==null||s.loadExternalDependency==null||s.loadExternalDependency(this._instance,"exception-autocapture",(r=>{if(r)return Ms.error("failed to load script",r);t()}))}Qo(){var t,e,s;(t=this.Vo)==null||t.call(this),this.Vo=void 0,(e=this.Zo)==null||e.call(this),this.Zo=void 0,(s=this.Go)==null||s.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({[Hn]:this.Ko}),this.Ne=this.Yo(),this.startIfEnabledOrStop())}}onConfigChange(){this.Ne=this.Yo()}captureException(t){var e,s,r,i=(e=t==null||(s=t.$exception_list)==null||(s=s[0])==null?void 0:s.type)!==null&&e!==void 0?e:"Exception";this.Jo.consumeRateLimit(i)?Ms.info("Skipping exception capture because of client rate limiting.",{exception:i}):(r=this._instance.exceptions)==null||r.sendExceptionEvent(t)}},exceptions:class{constructor(t){var e,s;this.Xo=[],this.tl=new Lh([new zh,new Qh,new Vh,new qh,new Zh,new Yh,new Kh,new Xh],(function(r){for(var i=arguments.length,n=new Array(i>1?i-1:0),o=1;i>o;o++)n[o-1]=arguments[o];return function(a,l){l===void 0&&(l=0);for(var u=[],c=a.split(` -`),d=l;c.length>d;d++){var h=c[d];if(1024>=h.length){var p=Xa.test(h)?h.replace(Xa,"$1"):h;if(!p.match(/\S*Error: /)){for(var f of n){var g=f(p,r);if(g){u.push(g);break}}if(u.length>=50)break}}}return(function(m){if(!m.length)return[];var _=Array.from(m);return _.reverse(),_.slice(0,50).map((E=>{return w({},E,{filename:E.filename||(b=_,b[b.length-1]||{}).filename,function:E.function||ms});var b}))})(u)}})("web:javascript",jh,Wh)),this._instance=t,this.Xo=(e=(s=this._instance.persistence)==null?void 0:s.get_property(Wn))!==null&&e!==void 0?e:[],this.el=Qr(this.il()),this.rl=new tp(this.el)}onConfigChange(){this.el=Qr(this.il()),this.rl.setConfig(this.el)}onRemoteConfig(t){var e,s,r;if(t.ok){var i=t.config;if("errorTracking"in i){var n=(e=(s=i.errorTracking)==null?void 0:s.suppressionRules)!==null&&e!==void 0?e:[],o=(r=i.errorTracking)==null?void 0:r.captureExtensionExceptions;this.Xo=n,this._instance.persistence&&this._instance.persistence.register({[Wn]:this.Xo,[zn]:o})}}}get nl(){var t,e=!!this._instance.get_property(zn),s=this._instance.config.error_tracking.captureExtensionExceptions;return(t=s??e)!==null&&t!==void 0&&t}buildProperties(t,e){return this.tl.buildFromUnknown(t,{syntheticException:e?.syntheticException,mechanism:{handled:e?.handled}})}addExceptionStep(t,e){if(this.el.enabled)try{if(!W(t)||t.trim().length===0)return void Xe.warn("Ignoring exception step because message must be a non-empty string");var s=(function(n){if(!n)return{sanitizedProperties:{},droppedKeys:[]};var o=[];return{sanitizedProperties:Object.keys(n).reduce(((a,l)=>ep.has(l)?(o.push(l),a):(a[l]=n[l],a)),{}),droppedKeys:o}})(this.sl(e)),r=s.sanitizedProperties,i=s.droppedKeys;i.length>0&&Xe.warn("Ignoring reserved exception step fields",{droppedKeys:i}),this.rl.add(w({[Zr]:t,[Xr]:new Date().toISOString()},r))}catch(n){Xe.error("Failed to add exception step. Ignoring breadcrumb.",n)}}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 Xe.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 Xe.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 Xe.info("Skipping exception capture because it was thrown by the PostHog SDK")}var s=this.el.enabled&&D(t.$exception_steps)?this.dl(t):t,r=typeof(n=globalThis._posthogReleaseId)=="string"&&n.length>0?n:void 0;r&&(s.$release_id=r);try{var i=this._instance.capture("$exception",s,{_noTruncate:!0,_batchKey:"exceptionEvent",Wn:!0});return i&&this.rl.clear(),i}catch(o){return Xe.error("Failed to capture exception event. Dropping this exception.",o),void this.rl.clear()}}catch(o){return void Xe.error("Failed to process exception event. Ignoring this exception.",o)}var n}dl(t){try{var e=this.rl.getAttachable();return e.length===0?t:w({},t,{$exception_steps:e})}catch(s){return Xe.error("Failed to read buffered exception steps. Capturing exception without steps.",s),t}}ll(t){this.el.enabled&&this.rl.add({[Zr]:t,[Xr]:new Date().toISOString()})}sl(t){return te(t)?w({},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(((s,r)=>{var i=r.type,n=r.value;return W(i)&&i.length>0&&s.$exception_types.push(i),W(n)&&n.length>0&&s.$exception_values.push(n),s}),{$exception_types:[],$exception_values:[]});return this.Xo.some((s=>{var r=s.values.map((i=>{var n=td[i.operator],o=e[i.key];if(!n||!o)return!1;var a=L(i.value)?i.value:[i.value];return a.length>0&&n(a,o)}));return s.type==="OR"?r.some(Boolean):r.every(Boolean)}))}catch(s){return Xe.warn("Failed to evaluate suppression rules. Capturing the exception.",s),!1}}ul(t){return t.flatMap((e=>{var s,r;return(s=(r=e.stacktrace)==null?void 0:r.frames)!==null&&s!==void 0?s:[]})).some((e=>e.filename&&e.filename.startsWith("chrome-extension://")))}hl(t){if(t.length>0){var e,s,r,i,n=(e=(s=t[0].stacktrace)==null?void 0:s.frames)!==null&&e!==void 0?e:[],o=n[n.length-1];return(r=o==null||(i=o.filename)==null?void 0:i.includes("posthog.com/static"))!==null&&r!==void 0&&r}return!1}al(t){return!D(t)&&L(t)}}},Sf=w({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 s,r;if(this.Mr&&this.Mr.register({[Uo]:!!e.productTours}),!En(this._instance))return!this.vl&&D((s=this.Mr)==null?void 0:s.props[Ws])||Pr.info("product tours disabled; stopping and clearing cached tours"),(r=this.vl)==null||r.stop(),this.vl=null,void this.clearCache();this.loadIfEnabled()}}}loadIfEnabled(){!this.vl&&En(this._instance)&&this.ai((()=>this.fl()))}ai(t){var e,s;(e=$.__PosthogExtensions__)!=null&&e.generateProductTours?t():(s=$.__PosthogExtensions__)==null||s.loadExternalDependency==null||s.loadExternalDependency(this._instance,"product-tours",(r=>{r?Pr.error("Could not load product tours script",r):t()}))}fl(){var t;!this.vl&&(t=$.__PosthogExtensions__)!=null&&t.generateProductTours&&(this.vl=$.__PosthogExtensions__.generateProductTours(this._instance,!0))}getProductTours(t,e){if(e===void 0&&(e=!1),!L(this.cl)||e){var s=this.Mr;if(s){var r=s.props[Ws];if(L(r)&&!e)return this.cl=r,void t(r,{isLoaded:!0})}this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/product_tours/?token="+this._instance.config.token),method:"GET",timestampMode:"query",callback:i=>{if(En(this._instance)){var n=i.statusCode;if(n!==200||!i.json){var o="Product Tours API could not be loaded, status: "+n;return n===0?i.error||Pr.warn(o):Pr.error(o),void t([],{isLoaded:!1,error:o})}var a=L(i.json.product_tours)?i.json.product_tours:[];this.cl=a,s&&s.register({[Ws]:a}),t(a,{isLoaded:!0})}else t([],{isLoaded:!0})}})}else t(this.cl,{isLoaded:!0})}getActiveProductTours(t){D(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(Ws)}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)}}},$i),xf={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 s=this.globalsForEvent(e);this.gl.push(s),this.gl.length>1e3&&(this.gl=this.gl.slice(10))}}get siteAppLoaders(){var t;return(t=$._POSTHOG_REMOTE_CONFIG)==null||(t=t[this._instance.config.token])==null?void 0:t.siteApps}initialize(){if(this.isEnabled){var t=this._instance._addCaptureHook(this.ml.bind(this));this.yl=()=>{t(),this.gl=[],this.yl=void 0}}}globalsForEvent(t){var e,s,r,i,n,o,a;if(!t)throw new Error("Event payload is required");var l={},u=this._instance.get_property("$groups")||[],c=this._instance.get_property("$stored_group_properties")||{};for(var d of Object.entries(c)){var h=d[0];l[h]={id:u[h],type:h,properties:d[1]}}var p=t.$set_once,f=t.$set;return{event:w({},Ic(t,pf),{properties:w({},t.properties,f?{$set:w({},(e=(s=t.properties)==null?void 0:s.$set)!==null&&e!==void 0?e:{},f)}:{},p?{$set_once:w({},(r=(i=t.properties)==null?void 0:i.$set_once)!==null&&r!==void 0?r:{},p)}:{}),elements_chain:(n=(o=t.properties)==null?void 0:o.$elements_chain)!==null&&n!==void 0?n:"",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,s=(e=t.tagName)==null?void 0:e.toLowerCase();return s==="style"&&this._instance.config.prepare_external_dependency_stylesheet?this._instance.config.prepare_external_dependency_stylesheet(t)||(Ze.error("prepare_external_dependency_stylesheet returned null"),null):s==="script"&&this._instance.config.prepare_external_dependency_script?this._instance.config.prepare_external_dependency_script(t)||(Ze.error("prepare_external_dependency_script returned null"),null):t}_l(){var t,e,s,r,i,n,o,a;if(!this._instance.config.prepare_external_dependency_stylesheet&&!this._instance.config.prepare_external_dependency_script)return()=>{};var l=C?.defaultView,u=l==null||(t=l.Node)==null?void 0:t.prototype;if(!l||!u)return()=>{};if(this.pl++,this.wl)return this.kl();var c=[],d=this,h=new WeakSet,p=(m,_,E)=>{if(m!=null&&m[_]){var b=m[_];m[_]=E(b),c.push((()=>{m[_]=b}))}},f=m=>{if(h.has(m))return m;var _=d.bl(m);return _&&h.add(_),_},g=m=>m.map((_=>typeof _=="string"?_:f(_))).filter((_=>!$e(_)));return p(u,"appendChild",(m=>function(_){var E=f(_);return E?m.call(this,E):_})),p(u,"insertBefore",(m=>function(_,E){var b=f(_);return b?m.call(this,b,E):_})),p(u,"replaceChild",(m=>function(_,E){var b=f(_);return b?m.call(this,b,E):E})),[(e=l.Element)==null?void 0:e.prototype,(s=l.Document)==null?void 0:s.prototype,(r=l.DocumentFragment)==null?void 0:r.prototype].forEach((m=>{p(m,"append",(_=>function(){for(var E=arguments.length,b=new Array(E),I=0;E>I;I++)b[I]=arguments[I];return _.apply(this,g(b))})),p(m,"prepend",(_=>function(){for(var E=arguments.length,b=new Array(E),I=0;E>I;I++)b[I]=arguments[I];return _.apply(this,g(b))}))})),[(i=l.Element)==null?void 0:i.prototype,(n=l.CharacterData)==null?void 0:n.prototype,(o=l.DocumentType)==null?void 0:o.prototype].forEach((m=>{p(m,"before",(_=>function(){for(var E=arguments.length,b=new Array(E),I=0;E>I;I++)b[I]=arguments[I];return _.apply(this,g(b))})),p(m,"after",(_=>function(){for(var E=arguments.length,b=new Array(E),I=0;E>I;I++)b[I]=arguments[I];return _.apply(this,g(b))})),p(m,"replaceWith",(_=>function(){for(var E=arguments.length,b=new Array(E),I=0;E>I;I++)b[I]=arguments[I];var F=g(b);return b.length&&!F.length?void 0:_.apply(this,F)}))})),p((a=l.Element)==null?void 0:a.prototype,"insertAdjacentElement",(m=>function(_,E){var b=f(E);return b?m.call(this,_,b):null})),this.wl=()=>{c.forEach((m=>m())),this.wl=void 0},this.kl()}kl(){var t=!1;return()=>{var e;t||(t=!0,this.pl--,this.pl===0&&((e=this.wl)==null||e.call(this)))}}xl(t,e){e===void 0&&(e=!0);var s=this._l();try{var r=t(s);return e&&s(),r}catch(i){throw s(),i}}setupSiteApp(t){var e=this.apps[t.id],s=()=>{var o;!e.errored&&this.gl.length&&(Ze.info("Processing "+this.gl.length+" events for site app with id "+t.id),this.gl.forEach((a=>this.xl((()=>e.processEvent==null?void 0:e.processEvent(a))))),e.processedBuffer=!0),Object.values(this.apps).every((a=>a.processedBuffer||a.errored))&&((o=this.yl)==null||o.call(this))},r=!1,i=o=>{e.errored=!o,e.loaded=!0,Ze.info("Site app with id "+t.id+" "+(o?"loaded":"errored")),r&&s()};try{var n=this.xl((o=>t.init({posthog:this._instance,callback(a){o(),i(a)}})),!1).processEvent;n&&(e.processEvent=n),r=!0}catch(o){Ze.error(Ml+t.id,o),i(!1)}if(r&&e.loaded)try{s()}catch(o){Ze.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 s of t)this.setupSiteApp(s)}Cl(t){var e=this;if(Object.keys(this.apps).length!==0){var s=this.globalsForEvent(t),r=function(n){try{e.xl((()=>n.processEvent==null?void 0:n.processEvent(s)))}catch(o){Ze.error("Error while processing event "+t.event+" for site app "+n.id,o)}};for(var i of Object.values(this.apps))r(i)}}onRemoteConfig(t){var e,s,r,i=this;if((e=this.siteAppLoaders)!=null&&e.length)return this.isEnabled?(this.Sl(),void this._instance.on("eventCaptured",(l=>this.Cl(l)))):void Ze.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.');if((s=this.yl)==null||s.call(this),t.ok){var n=t.config;if((r=n.siteApps)!=null&&r.length)if(this.isEnabled){var o=function(){var l,u=a.id,c=a.url;$["__$$ph_site_app_"+u]=i._instance,(l=$.__PosthogExtensions__)==null||l.loadSiteApp==null||l.loadSiteApp(i._instance,c,(d=>{if(d)return Ze.error(Ml+u,d)}))};for(var a of n.siteApps)o()}else Ze.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.')}}}},kf={tracingHeaders:class{constructor(t){this.Ml=void 0,this.Tl=void 0,this.El=void 0,this.Uo=()=>{var e,s,r=this.Il();r?(x(this.Ml)&&(this.Ml=(e=$.__PosthogExtensions__)==null||(e=e.tracingHeadersPatchFns)==null?void 0:e._patchXHR(r,(()=>this._instance.get_distinct_id()),this._instance.sessionManager)),x(this.Tl)&&(this.Tl=(s=$.__PosthogExtensions__)==null||(s=s.tracingHeadersPatchFns)==null?void 0:s._patchFetch(r,(()=>this._instance.get_distinct_id()),this._instance.sessionManager))):this.Qo()},this._instance=t}initialize(){this.startIfEnabledOrStop()}ai(t){var e,s;(e=$.__PosthogExtensions__)!=null&&e.tracingHeadersPatchFns?t():(s=$.__PosthogExtensions__)==null||s.loadExternalDependency==null||s.loadExternalDependency(this._instance,"tracing-headers",(r=>{if(r)return df.error("failed to load script",r);t()}))}Pl(){var t,e;return(t=(e=this._instance.config.tracing_headers)!==null&&e!==void 0?e:this._instance.config.addTracingHeaders)!==null&&t!==void 0?t:this._instance.config.__add_tracing_headers}Il(){var t=this.Pl();return L(t)?(L(this.El)?this.El.splice(0,this.El.length,...t):this.El=[...t],t.length>0?this.El:void 0):(L(this.El)&&this.El.splice(0),this.El=t||void 0,this.El)}Qo(){var t,e;(t=this.Ml)==null||t.call(this),(e=this.Tl)==null||e.call(this),this.Ml=void 0,this.Tl=void 0}startIfEnabledOrStop(){this.Il()?this.ai(this.Uo):this.Qo()}}},If=w({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(D(e))return q.warn("Flags not loaded yet. Not loading surveys.");var s=L(e);this.Rl=s?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=[],s=0;slocalStorage.removeItem(i)))}catch{}}loadIfEnabled(){if(!this._surveyManager)if(this.Al)q.info("Already initializing surveys, skipping...");else if(this.Ne.disable_surveys)q.info(Ll);else if(this.Ne.cookieless_mode&&this._instance.consent.isOptedOut())q.info("Not loading surveys in cookieless mode without consent.");else{var t=$?.__PosthogExtensions__;if(t){if(!x(this.Rl)||this.Ne.advanced_enable_surveys){var e=this.Rl||this.Ne.advanced_enable_surveys;this.Al=!0;try{var s=t.generateSurveys;if(s)return void this.Dl(s,e);var r=t.loadExternalDependency;if(!r)return void this.$l(Wo);r(this._instance,"surveys",(i=>{i||!t.generateSurveys?this.$l("Could not load surveys script",i):this.Dl(t.generateSurveys,e)}))}catch(i){throw this.$l("Error initializing surveys",i),i}finally{this.Al=!1}}}else q.error("PostHog Extensions not found.")}}Dl(t,e){this._surveyManager=t(this._instance,e),this._surveyEventReceiver=new mf(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(Ll),t([]);var s,r=this._instance.get_property(Kn);if(r&&!e)return t(r,{isLoaded:!0}),void(this.ql()&&this.getSurveys((()=>{}),!0));typeof Promise<"u"&&this.Ll?this.Ll.then((i=>t(i.surveys,i.context))):(typeof Promise<"u"&&(this.Ll=new Promise((i=>{s=i}))),this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/surveys/?token="+this.Ne.token),method:"GET",timestampMode:"query",timeout:this.Ne.surveys_request_timeout_ms,callback:i=>{var n;this.Ll=null;var o=i.statusCode;if(o!==200||!i.json){var a="Surveys API could not be loaded, status: "+o;o!==0?q.error(a):i.error||q.warn(a),this.Ol=Date.now();var l={isLoaded:!1,error:a};return t([],l),void(s==null||s({surveys:[],context:l}))}this.Ol=null;var u,c=i.json.surveys||[],d=c.filter((p=>(function(f){return!(!f.start_date||f.end_date)})(p)&&(rd(p)||(function(f){var g;return!((g=f.conditions)==null||(g=g.actions)==null||(g=g.values)==null||!g.length)})(p))));d.length>0&&((u=this._surveyEventReceiver)==null||u.register(d)),(n=this._instance.persistence)==null||n.register({[Kn]:c,[ti]:Date.now()});var h={isLoaded:!0};t(c,h),s?.({surveys:c,context:h})}}))}ql(){return this.jl()&&!this.Ll&&!this.Bl()}jl(){var t=this._instance.get_property(ti);return he(t)&&Date.now()-t>3e5}Bl(){return he(this.Ol)&&3e5>Date.now()-this.Ol}markSurveyAsSeen(t,e){var s,r={id:t,current_iteration:(s=e?.iteration)!==null&&s!==void 0?s:null};nd(r);try{localStorage.setItem("lastSeenSurveyDate",new Date().toISOString())}catch{}}Nl(t){for(var e of this.Fl)try{if(!t.isLoaded)return e([],t);this.getSurveys(e)}catch(s){q.error("Error in survey callback",s)}}getActiveMatchingSurveys(t,e){if(e===void 0&&(e=!1),!D(this._surveyManager))return this._surveyManager.getActiveMatchingSurveys(t,e);q.warn("init was not called")}Hl(t){var e=null;return this.getSurveys((s=>{var r;e=(r=s.find((i=>i.id===t)))!==null&&r!==void 0?r:null})),e}Ul(t){if(D(this._surveyManager))return{eligible:!1,reason:Ar};var e=typeof t=="string"?this.Hl(t):t;return e?this._surveyManager.checkSurveyEligibility(e):{eligible:!1,reason:"Survey not found"}}zl(t){if(D(this._surveyManager))return{eligible:!1,reason:Ar};var e=typeof t=="string"?this.Hl(t):t;return e?this._surveyManager.checkSurveyRenderability(e):{eligible:!1,reason:"Survey not found"}}canRenderSurvey(t){if(D(this._surveyManager))return q.warn("init was not called"),{visible:!1,disabledReason:Ar};var e=this.zl(t);return{visible:e.eligible,disabledReason:e.reason}}canRenderSurveyAsync(t,e){return D(this._surveyManager)?(q.warn("init was not called"),Promise.resolve({visible:!1,disabledReason:Ar})):new Promise((s=>{this.getSurveys((r=>{var i,n=(i=r.find((a=>a.id===t)))!==null&&i!==void 0?i:null;if(n){var o=this.zl(n);s({visible:o.eligible,disabledReason:o.reason})}else s({visible:!1,disabledReason:"Survey not found"})}),e)}))}renderSurvey(t,e,s){var r;if(D(this._surveyManager))q.warn("init was not called");else{var i=typeof t=="string"?this.Hl(t):t;if(i!=null&&i.id)if(Zp.includes(i.type)){var n=C?.querySelector(e);if(n)return(r=i.appearance)!=null&&r.surveyPopupDelaySeconds?(q.info("Rendering survey "+i.id+" with delay of "+i.appearance.surveyPopupDelaySeconds+" seconds"),void setTimeout((()=>{var o,a;q.info("Rendering survey "+i.id+" with delay of "+((o=i.appearance)==null?void 0:o.surveyPopupDelaySeconds)+" seconds"),(a=this._surveyManager)==null||a.renderSurvey(i,n,s),q.info("Survey "+i.id+" rendered")}),1e3*i.appearance.surveyPopupDelaySeconds)):void this._surveyManager.renderSurvey(i,n,s);q.warn("Survey element not found")}else q.warn("Surveys of type "+i.type+" cannot be rendered in the app");else q.warn("Survey not found")}}displaySurvey(t,e){var s;if(D(this._surveyManager))q.warn("init was not called");else{var r=this.Hl(t);if(r){var i=r;if((s=r.appearance)!=null&&s.surveyPopupDelaySeconds&&e.ignoreDelay&&(i=w({},r,{appearance:w({},r.appearance,{surveyPopupDelaySeconds:0})})),e.displayType!==io.Popover&&e.initialResponses&&q.warn("initialResponses is only supported for popover surveys. prefill will not be applied."),e.ignoreConditions===!1){var n=this.Ul(r);if(!n.eligible)return void q.warn("Survey is not eligible to be displayed: ",n.reason)}e.displayType!==io.Inline?this._surveyManager.handlePopoverSurvey(i,e):this.renderSurvey(i,e.selector,e.properties)}else q.warn("Survey not found")}}cancelPendingSurvey(t){D(this._surveyManager)?q.warn("init was not called"):this._surveyManager.cancelSurvey(t)}handlePageUnload(){var t;(t=this._surveyManager)==null||t.handlePageUnload==null||t.handlePageUnload()}}},$i),Cf={toolbar:class{constructor(t){this.instance=t}Wl(t){$.ph_toolbar_state=t}Vl(){var t;return(t=$.ph_toolbar_state)!==null&&t!==void 0?t:0}initialize(){return this.maybeLoadToolbar()}maybeLoadToolbar(t,e,s){if(t===void 0&&(t=void 0),e===void 0&&(e=void 0),s===void 0&&(s=void 0),to(this.instance.config)||!v||!C)return!1;t=t??v.location,s=s??v.history;try{if(!e){try{v.localStorage.setItem("test","test"),v.localStorage.removeItem("test")}catch{return!1}e=v?.localStorage}var r,i=vf||ci(t.hash,"__posthog")||ci(t.hash,"state"),n=i?el((()=>JSON.parse(atob(decodeURIComponent(i)))))||el((()=>JSON.parse(decodeURIComponent(i)))):null;return n&&n.action==="ph_authorize"?((r=n).source="url",r&&Object.keys(r).length>0&&(n.desiredHash?t.hash=n.desiredHash:s?s.replaceState(s.state,"",t.pathname+t.search):t.hash="")):((r=JSON.parse(e.getItem(Ol)||"{}")).source="localstorage",delete r.userIntent),!(!r.token||this.instance.config.token!==r.token||(this.loadToolbar(r),0))}catch{return!1}}Zl(t){var e=$.ph_load_toolbar||$.ph_load_editor;!D(e)&&Se(e)?e(t,this.instance):Dl.warn("No toolbar load function found")}loadToolbar(t){var e=!(C==null||!C.getElementById(wu));if(!v||e)return!1;var s=this.instance.requestRouter.region==="custom"&&this.instance.config.advanced_disable_toolbar_metrics,r=w({token:this.instance.config.token},t,{apiURL:this.instance.requestRouter.endpointFor("ui")},s?{instrument:!1}:{});if(v.localStorage.setItem(Ol,JSON.stringify(w({},r,{source:void 0}))),this.Vl()===2)this.Zl(r);else if(this.Vl()===0){var i;this.Wl(1),(i=$.__PosthogExtensions__)==null||i.loadExternalDependency==null||i.loadExternalDependency(this.instance,"toolbar",(n=>{if(n)return Dl.error("[Toolbar] Failed to load",n),void this.Wl(0);this.Wl(2),this.Zl(r)})),ie(v,"turbolinks:load",(()=>{this.Wl(0),this.loadToolbar(r)}))}return!0}Gl(t){return this.loadToolbar(t)}maybeLoadEditor(t,e,s){return t===void 0&&(t=void 0),e===void 0&&(e=void 0),s===void 0&&(s=void 0),this.maybeLoadToolbar(t,e,s)}}},Ff=w({experiments:ye},$i),Pf={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;D(e)||(Ke(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||to(this._instance.config)||this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut())){var t=$?.__PosthogExtensions__;if(t&&!x(this.Ql)&&this.Ql)if(this.Jl&&this.Jl.token){this.Kl=!0;try{var e=t.initConversations;if(e)return this.tu(e),void(this.Kl=!1);var s=t.loadExternalDependency;if(!s)return void this.eu(Wo);s(this._instance,"conversations",(r=>{r||!t.initConversations?this.eu("Could not load conversations script",r):this.tu(t.initConversations),this.Kl=!1}))}catch(r){this.eu("Error initializing conversations",r),this.Kl=!1}}else Ue.error("Conversations enabled but missing token in remote config.")}}tu(t){if(this.Jl)try{this._conversationsManager=t(this.Jl,this._instance),this.Yl=!1,Ue.info("Conversations loaded successfully")}catch(e){this.eu("Error completing conversations initialization",e)}else Ue.error("Cannot complete initialization: remote config is null")}eu(t,e){Ue.error(t,e),this._conversationsManager=null,this.Kl=!1,this.Yl=!0}show(){this._conversationsManager?this._conversationsManager.show():Ue.warn("Conversations not loaded yet.")}hide(){this._conversationsManager&&this._conversationsManager.hide()}isAvailable(){return this.Ql===!0&&!$e(this._conversationsManager)}getUnavailableReason(){return this.isAvailable()?null:this._instance.config.disable_conversations?"disabled_by_config":to(this._instance.config)?"disabled_for_toolbar":this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut()?"consent_opted_out":this.Xl===!1?"remote_config_failed":x(this.Ql)?this.Xl?"disabled_in_project":"remote_config_pending":this.Ql?D(this.Jl)||!this.Jl.token?"missing_token":$!=null&&$.__PosthogExtensions__?this.Kl?"initializing":this.Yl?"load_failed":"not_loaded":"extensions_unavailable":"disabled_in_project"}isVisible(){var t,e;return(t=(e=this._conversationsManager)==null?void 0:e.isVisible())!==null&&t!==void 0&&t}sendMessage(t,e,s){var r=this;return X((function*(){return r._conversationsManager?r._conversationsManager.sendMessage(t,e,s):(Ue.warn(Dt),null)}))()}getMessages(t,e){var s=this;return X((function*(){return s._conversationsManager?s._conversationsManager.getMessages(t,e):(Ue.warn(Dt),null)}))()}markAsRead(t){var e=this;return X((function*(){return e._conversationsManager?e._conversationsManager.markAsRead(t):(Ue.warn(Dt),null)}))()}getTickets(t){var e=this;return X((function*(){return e._conversationsManager?e._conversationsManager.getTickets(t):(Ue.warn(Dt),null)}))()}requestRestoreLink(t){var e=this;return X((function*(){return e._conversationsManager?e._conversationsManager.requestRestoreLink(t):(Ue.warn(Dt),null)}))()}restoreFromToken(t){var e=this;return X((function*(){return e._conversationsManager?e._conversationsManager.restoreFromToken(t):(Ue.warn(Dt),null)}))()}restoreFromUrlToken(){var t=this;return X((function*(){return t._conversationsManager?t._conversationsManager.restoreFromUrlToken():(Ue.warn(Dt),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()}}},Af={logs:class{constructor(t){var e,s=this;this.iu=!1,this.ru=!1,this.rt=se("[logs]"),this.nu=w({},this.rt,{error(){for(var r=arguments.length,i=new Array(r),n=0;r>n;n++)i[n]=arguments[n];i.some(Vl)||s.rt.error(...i)}}),this.tr=[],this.su=[],this.Sa=0,this.au=()=>{var r,i;this.Sa=0,(r=this.ou)==null||r.onReconnect(),(i=this.lu)==null||i.onReconnect()},this._instance=t,this._instance&&(e=this._instance.config.logs)!=null&&e.captureConsoleLogs&&(this.iu=!0),v&&ie(v,"online",this.au)}uu(t,e,s,r){var i,n=(function(o,a){var l,u,c,d,h,p,f,g=(l=o?.flushIntervalMs)!==null&&l!==void 0?l:3e3,m=(u=o?.maxBufferSize)!==null&&u!==void 0?u:100,_=a!=null&&a.consoleCapture?void 0:(c=o?.maxLogsPerInterval)!==null&&c!==void 0?c:1e3,E=x(_)?Math.max(m,2048):Math.max(m,_),b=o?.resourceAttributes;return{serviceName:(d=(h=b?.["service.name"])!==null&&h!==void 0?h:o?.serviceName)!==null&&d!==void 0?d:a?.serviceNameDefault,serviceVersion:(p=b?.["service.version"])!==null&&p!==void 0?p:o?.serviceVersion,environment:(f=b?.["deployment.environment"])!==null&&f!==void 0?f:o?.environment,resourceAttributes:b,beforeSend:o?.beforeSend,flushIntervalMs:g,maxBufferSize:m,maxQueueSize:E,maxBatchRecordsPerPost:100,rateCapWindowMs:g,maxLogsPerInterval:_,backgroundFlushBudgetMs:0,terminationFlushBudgetMs:0}})((i=this._instance)==null||(i=i.config)==null?void 0:i.logs,s);return[new Th(this.hu(t,e),n,this.nu,(()=>this.du()),(o=>o()),void 0,r),n]}vu(){var t,e=(t=this._instance)==null||(t=t.config)==null?void 0:t.logs;if(!this.ou||this.cu!==e){var s;(s=this.ou)==null||s.reset(),this.cu=e;var r=this.uu((()=>this.tr),(i=>{this.tr=i}));this.ou=r[0],this.fu=r[1]}return this.ou}pu(){var t,e=(t=this._instance)==null||(t=t.config)==null?void 0:t.logs;if(!this.lu||this.gu!==e){var s;(s=this.lu)==null||s.reset(),this.gu=e;var r=this.uu((()=>this.su),(i=>{this.su=i}),{serviceNameDefault:"posthog-browser-logs",consoleCapture:!0},ql);this.lu=r[0],this.mu=r[1]}return this.lu}initialize(){this.loadIfEnabled()}onRemoteConfig(t){var e;if(t.ok){var s=(e=t.config.logs)==null?void 0:e.captureConsoleLogs;!D(s)&&s&&(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){Vl(t)||this.rt.error("PostHog logs flush failed:",t)}loadIfEnabled(){if(this.iu&&!this.ru){var t=$?.__PosthogExtensions__;if(t){var e=t.loadExternalDependency;e?e(this._instance,"logs",(s=>{var r;s||(r=t.logs)==null||!r.initializeLogs?this.rt.error("Could not load logs script",s):(t.logs.initializeLogs(this._instance),this.ru=!0)})):this.rt.error(Wo)}else this.rt.error("PostHog Extensions not found.")}}hu(t,e){var s=this._instance;return{get isDisabled(){return!1},get optedOut(){return!s.is_capturing()},getPersistedProperty:r=>r===ut.LogsQueue?t():void 0,setPersistedProperty(r,i){var n;r===ut.LogsQueue&&e((n=i)!==null&&n!==void 0?n:[])},Ot:r=>this.Ot(r),getLibraryId:()=>Y.LIB_NAME,getLibraryVersion:()=>Y.LIB_VERSION}}Ot(t){return new Promise((e=>{if(Ru(this.Sa,3))e({kind:"fatal",error:xn(void 0,"logs endpoint is unreachable, dropping batch")});else{var s=!1,r=n=>{s||(s=!0,clearTimeout(i),e(n))},i=setTimeout((()=>{this.rt.warn("Logs request timed out before receiving a response"),r({kind:"retry-later",error:xn(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:n=>{var o=n.statusCode;if(this.ku(o),o>=200&&300>o)r({kind:"ok"});else if(o===413)r({kind:"too-large"});else if(o!==0&&o!==429&&500>o)r({kind:"fatal",error:new Error("logs request failed with status "+o)});else{var a;o===0?(n.error||this.rt.warn("Logs request failed before receiving an HTTP response"),r({kind:"retry-later",error:xn(n.error,"logs request failed before receiving an HTTP response")})):r({kind:"retry-later",error:(a=n.error)!==null&&a!==void 0?a:new Error("logs request failed with status "+o)})}}})}}))}ku(t){(t!==0||this._instance.__loaded)&&(this.Sa=Tu(t,this.Sa,3,(()=>this.rt.warn("Log requests are failing before receiving an HTTP response; this can happen due to network issues, CORS, browser blocking, or ad blockers. Stopped sending logs; will try again when connectivity changes."))))}bu(t){this.tr.length>0&&this.xu(t,this.tr,this.fu,Y.LIB_NAME,(e=>{this.tr=e})),this.su.length>0&&this.xu(t,this.su,this.mu,ql,(e=>{this.su=e}))}xu(t,e,s,r,i){if(e.length!==0){var n=e.map((a=>a.record));i([]);var o=ru(n,su(s,Y.LIB_NAME,Y.LIB_VERSION),r,Y.LIB_VERSION);this._instance._send_request({method:"POST",url:this.wu(),data:o,compression:"best-available",batchKey:"logs",transport:t})}}wu(){return this._instance.requestRouter.endpointFor("api","/i/v1/logs")+"?token="+encodeURIComponent(this._instance.config.token)}du(){var t,e={};if(e.distinctId=this._instance.get_distinct_id(),this._instance.sessionManager){var s=this._instance.sessionManager.checkAndGetSessionAndWindowId(!0),r=s.windowId,i=s.sessionStartTimestamp,n=s.lastActivityTimestamp;e.sessionId=s.sessionId,e.windowId=r,D(i)||(e.sessionStartTimestamp=i),D(n)||(e.lastActivityTimestamp=n)}if($!=null&&(t=$.location)!=null&&t.href&&(e.currentUrl=this._instance.config.disable_capture_url_hashes?Ct($.location.href):$.location.href),this._instance.featureFlags){var o=this._instance.featureFlags.getFlags();o&&o.length>0&&(e.activeFeatureFlags=o)}return e}}},$f={metrics:class{constructor(t){this.rt=se("[metrics]"),this._instance=t}initialize(){}vu(){var t,e,s=(t=this._instance)==null||(t=t.config)==null?void 0:t.metrics;return this.ou&&this.cu===s||((e=this.ou)==null||e.reset(),this.cu=s,this.ou=new Nh(this.hu(),(function(r){var i,n,o,a,l,u=r?.resourceAttributes;return{serviceName:(i=u?.["service.name"])!==null&&i!==void 0?i:r?.serviceName,serviceVersion:(n=u?.["service.version"])!==null&&n!==void 0?n:r?.serviceVersion,environment:(o=u?.["deployment.environment"])!==null&&o!==void 0?o:r?.environment,resourceAttributes:u,beforeSend:r?.beforeSend,flushIntervalMs:(a=r?.flushIntervalMs)!==null&&a!==void 0?a:1e4,maxSeriesPerFlush:(l=r?.maxSeriesPerFlush)!==null&&l!==void 0?l:1e3}})(s),this.rt)),this.ou}count(t,e,s){e===void 0&&(e=1),this.vu().count(t,e,s)}gauge(t,e,s){this.vu().gauge(t,e,s)}histogram(t,e,s){this.vu().histogram(t,e,s)}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((s=>this.rt.error("PostHog metrics flush failed:",s)))}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:s=>e.Jt(s),getLibraryId:()=>Y.LIB_NAME,getLibraryVersion:()=>Y.LIB_VERSION}}Jt(t,e){return new Promise((s=>{var r=!1,i=o=>{r||(r=!0,clearTimeout(n),s(o))},n=setTimeout((()=>i({kind:"retry-later",error:new Error("metrics request timed out")})),9e4);this._instance._send_request(w({method:"POST",url:this.Su(),data:t,compression:"best-available",batchKey:"metrics"},e&&{transport:e},{fireCallbackOnDrop:!0,callback(o){var a=o.statusCode;if(a>=200&&300>a)i({kind:"ok"});else if(a===413)i({kind:"too-large"});else if(a!==0&&a!==429&&500>a)i({kind:"fatal",error:new Error("metrics request failed with status "+a)});else{var l;i({kind:"retry-later",error:(l=o.error)!==null&&l!==void 0?l:new Error("metrics request failed with status "+a)})}}}))}))}Su(){return this._instance.requestRouter.endpointFor("api","/i/v1/metrics")+"?token="+encodeURIComponent(this._instance.config.token)}}},Rf=w({},$i,wf,bf,Ef,Sf,xf,If,kf,Cf,Ff,Pf,Af,$f);Te.__defaultExtensionClasses=w({},Rf);var cd=(function(){Y.SDK_DIST_CHANNEL="npm";var t=Ys[as]=new Te;return(function(){function e(){e.done||(e.done=!0,ad=!1,Z(Ys,(function(s){s._dom_loaded()})))}C!=null&&C.addEventListener?C.readyState==="complete"?e():ie(C,"DOMContentLoaded",e,{capture:!1}):v&&k.error("Browser doesn't support `document.addEventListener` so PostHog couldn't be initialized")})(),t})();const ud="CodeFile",dd="GeneratedCode",Tf={CustomAction:"A",CustomWidget:"W",CustomFunction:"F",CustomClass:"C",CodeFile:"C"};function kt(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function po(t){return String(t||"").trim().replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function Nf(t={},e=0){const s=po(t.artifactType||t.type||ud),r=po(t.artifactName||t.name||t.fileName||`${dd}-${e+1}`);return`${s||"artifact"}-${r||e+1}`}function hd(t={},e=0){const s=kt(t),r=s.artifactType||s.type||ud,i=s.artifactName||s.name||dd;let n=s.fileName||i;return n.endsWith(".dart")||(n+=".dart"),{id:po(s.id)||Nf({...s,artifactType:r,artifactName:i,fileName:n},e),artifactType:r,artifactName:i,fileName:n,deployPath:s.deployPath||"",description:s.description||"",code:s.code||s.content||"",dependencies:pd(s.dependencies),imports:Array.isArray(s.imports)?s.imports:[],publicApi:Array.isArray(s.publicApi)?s.publicApi:[],relationships:fd(s.relationships),deployStatus:s.deployStatus||"pending",review:s.review||null,metadata:kt(s.metadata),codeType:s.codeType||Tf[r]||"O"}}function pd(t){return t?Array.isArray(t)?t.map(e=>{if(typeof e=="string")return{name:e,version:null,inferred:!1};const s=kt(e),r=s.name||s.package;return r?{name:r,version:s.version||null,versionRequired:!!(s.versionRequired||s.required),inferred:!!s.inferred,...s.reason?{reason:s.reason}:{}}:null}).filter(Boolean):Object.entries(kt(t)).map(([e,s])=>({name:e,version:s||null,inferred:!1})):[]}function fd(t){return t?(Array.isArray(t)?t:[t]).map(e=>{const s=kt(e);return!s.from&&!s.to?null:{from:s.from||null,to:s.to||null,type:s.type||"uses",description:s.description||""}}).filter(Boolean):[]}function fo(t){if(typeof t!="string")return null;const e=t.trim();if(!e)return null;try{return JSON.parse(e)}catch{const s=e.match(/```(?:json)?\s*([\s\S]*?)```/i);if(!s)return null;try{return JSON.parse(s[1].trim())}catch{return null}}}function or(t,e={}){const s=[],r=typeof t=="string"?fo(t):t,n=kt(r||{});!r&&typeof t=="string"&&s.push("Structured bundle parse failed; using legacy single-artifact fallback.");const o=Array.isArray(n.artifacts)?n.artifacts:[{artifactType:n.artifactType||e.artifactType,artifactName:n.artifactName||e.artifactName,fileName:n.fileName||e.fileName,description:n.description,code:n.code||e.code||(typeof t=="string"?t:""),dependencies:n.dependencies||e.dependencies,relationships:n.relationships||e.relationships}];o.forEach((d,h)=>{!d?.artifactType&&!d?.type&&s.push(`Artifact ${h+1} has no artifactType; it will deploy as a standalone code file under lib/custom_code/ root.`)});const a=o.map((d,h)=>hd(d,h)),l=new Map(o.map((d,h)=>[kt(d).id,a[h]?.id]).filter(([d,h])=>d&&h)),u=d=>l.get(d)||d,c=fd(n.relationships||e.relationships).map(d=>({...d,from:d.from?u(d.from):d.from,to:d.to?u(d.to):d.to}));return{schemaVersion:n.schemaVersion||e.schemaVersion||null,id:n.id||e.id||"bundle-current",title:n.title||n.name||e.title||"Generated artifact bundle",description:n.description||e.description||"",artifacts:a,dependencies:pd(n.dependencies||e.dependencies),relationships:c,deployOrder:Array.isArray(n.deployOrder)?n.deployOrder.map(u):a.map(d=>d.id),warnings:[...s,...Array.isArray(n.warnings)?n.warnings:[]],metadata:kt(n.metadata)}}function fi(t){return or(t).artifacts[0]||hd()}function yt(t){if(typeof t!="string")return t??"";const e=t.trim();if(!e)return"";try{return JSON.parse(e)}catch{return t}}function ws(t){return JSON.stringify(t,null,2)}function Mf(t){return ws({task:"architect",userRequest:String(t??"")})}function Lf(t){const e=yt(t);return e&&typeof e=="object"&&typeof e.task=="string"?ws(e):ws({task:"generate_bundle",bundleSpec:e})}function Of(t){return ws({task:"review_bundle",generatedBundle:yt(t),outputRequirements:{bundleReview:["status","score","summary","manualActions","findings"],scoreRange:[0,100],eachArtifact:["id","review.status","review.findings"],manualActions:{definition:"Setup the developer must perform by hand in the FlutterFlow editor that FlutterFlow will NOT do for them.",exclude:["creating the Custom Action, Widget or Code File itself - deploying the code creates it","declaring parameters or return values FlutterFlow derives from the function signature","anything that resolves as a side effect of using the action or widget in the editor","generic advice such as testing, reviewing or rebuilding the app"],preferEmpty:"Return an empty array when nothing qualifies - an empty list is the expected result for most bundles."}}})}function Zo(t,e=null){const s={stage:t};return e!=null&&(s.bundle=yt(e)),s}function Df({bundleSpec:t,artifactBundle:e,bundleReview:s,artifactId:r,userFeedback:i}){return ws({task:"regenerate_artifact",artifactId:r,bundleSpec:yt(t),artifactBundle:yt(e),bundleReview:yt(s),userFeedback:String(i)})}function gd({bundleSpec:t,artifactBundle:e,bundleReview:s,userFeedback:r}){return ws({task:"regenerate_bundle",bundleSpec:yt(t),artifactBundle:yt(e),bundleReview:yt(s),userFeedback:String(r??"")})}const Gl={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"},Bf=["sanitizationResult","modelArmor","modelArmorResult","data","result","error"];function Le(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function jf(t){return Le(t)?typeof t.filterMatchState=="string"||typeof t.invocationResult=="string"||Array.isArray(t.matchedFilters)||Le(t.filterSummary)||Le(t.filterResults):!1}function md(t,e=0){if(!Le(t)||e>3)return null;if(jf(t))return t;for(const s of Bf){const r=t[s];if(Le(r)){const i=md(r,e+1);if(i)return i}}return null}function gi(t){return Array.isArray(t)?t.some(gi):Le(t)?t.matched===!0||t.matchState==="MATCH_FOUND"?!0:Object.values(t).some(gi):!1}function go(t){return Array.isArray(t)?t.some(go):Le(t)?typeof t.executionState=="string"&&t.executionState!=="EXECUTION_SUCCESS"?!0:Object.values(t).some(go):!1}function vd(t){return{csamFilterFilterResult:"csam",maliciousUriFilterResult:"malicious_uris",piAndJailbreakFilterResult:"pi_and_jailbreak",raiFilterResult:"rai",sdpFilterResult:"sdp",virusScanFilterResult:"virus_scan"}[t]||t}function Uf(t,e){if(Le(t))for(const[s,r]of Object.entries(t)){if(!Le(r))continue;const i=Le(r.categories)?r.categories:{},n=Object.entries(i).filter(([,o])=>Le(o)&&o.matched===!0).map(([o])=>o);n.length>0?n.forEach(o=>e.add(o)):r.matched===!0&&e.add(vd(s))}}function Hf(t,e){if(!t)return;const s=Array.isArray(t)?t.flatMap(r=>Le(r)?Object.entries(r):[]):Object.entries(t);for(const[r,i]of s){if(!gi(i))continue;const n=vd(r),o=i?.raiFilterResult?.raiFilterTypeResults||(n==="rai"?i?.raiFilterTypeResults:null),a=Le(o)?Object.entries(o).filter(([,l])=>gi(l)).map(([l])=>l):[];a.length>0?a.forEach(l=>e.add(l)):e.add(n)}}function Wf(t){return Gl[t]?Gl[t]:String(t).replace(/([a-z])([A-Z])/g,"$1 $2").replace(/_/g," ").toLowerCase()}function Kl(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 zf(t){const e=md(t);if(!e)return null;const s=new Set(Array.isArray(e.matchedFilters)?e.matchedFilters:[]);Uf(e.filterSummary,s),Hf(e.filterResults,s);const r=e.blocked===!0||e.filterMatchState==="MATCH_FOUND"||s.size>0,i=e.invocationResult||null,n=go(e.filterSummary||e.filterResults);return!r&&!n&&!["PARTIAL","FAILURE"].includes(i)?null:{kind:r?"blocked":"unavailable",invocationResult:i,matchedFilters:[...s]}}function qf(t,e){const s=zf(t);if(!s)return null;const r=[...new Set(s.matchedFilters.map(Wf))],i=s.kind==="blocked",n=new Error(i?`Safety screening blocked this pipeline step for ${Kl(r)}.`:"Safety screening could not be completed. Please try again.");return n.name="ModelArmorError",n.code=i?"MODEL_ARMOR_BLOCKED":"MODEL_ARMOR_UNAVAILABLE",n.isModelArmor=!0,n.pipelineStep=e,n.userTitle=i?"Request blocked for safety":"Safety check unavailable",n.userMessage=i?`The safety check detected ${Kl(r)}. Edit your request to remove or rephrase the flagged content, then run the pipeline again.`:"The safety service did not finish all of its checks. Please wait a moment and run the pipeline again.",n.retryExplanation=i?"Trying another model would not change this safety decision.":"A fallback model was not attempted because safety screening must complete first.",n.matchedFilters=s.matchedFilters,n}function Vf(t){return String(t||"").replace(/\/\*[\s\S]*?\*\//g,"").replace(/\/\/[^\n]*/g,"")}function Jl(t){const e=/^(import|export|part|library|class|enum|extension|typedef|mixin|abstract|const|final|var|late)\b/,s=[];for(const r of Vf(t).split(` -`)){if(!/^[A-Za-z_$]/.test(r)||e.test(r))continue;const i=r.match(/^[\w$<>,?\s[\]]+?\s([a-zA-Z_$][\w$]*)\s*\(/);i&&s.push(i[1])}return s}function Xo(t,e){const s=t.replace(/\.dart$/,"");if(e==="W")return s.replace(/(^|_)(\w)/g,(r,i,n)=>n.toUpperCase());if(e==="A"){const r=s.replace(/(^|_)(\w)/g,(i,n,o)=>o.toUpperCase());return r.charAt(0).toLowerCase()+r.slice(1)}return e==="F"?"CustomFunctions":e==="C"?t.endsWith(".dart")?t:`${t}.dart`:s}async function Yl(t){const e=new TextEncoder().encode(String(t||"")),s=await globalThis.crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(s),r=>r.toString(16).padStart(2,"0")).join("")}async function Gf(t,e=new Map){const s={},r=new Set;for(const[o,a]of t.entries()){if(a.type==="D"||a.type==="O")continue;const l=Xo(o,a.type),u={old_identifier_name:l,new_identifier_name:l,type:a.type,is_deleted:!1,current_checksum:await Yl(a.content)},c=e.get(a.path);if(c!==void 0&&(u.original_checksum=await Yl(c)),s[o]=u,a.type==="F"){const d=Jl(a.content);(d.length>0?d:[a.functionName].filter(Boolean)).forEach(p=>r.add(p))}}const i=new Set(Jl(e.get("lib/flutter_flow/custom_functions.dart")||"")),n={functions_to_rename:[],functions_to_delete:[],functions_to_add:Array.from(r).filter(o=>!i.has(o))};return{fileMapContents:JSON.stringify(s),functionsMapContents:JSON.stringify(n)}}const Kf=new Set(["CustomWidget","CustomAction","CustomFunction","CustomClass","CodeFile"]),Zl={CustomWidget:"custom_code/widgets/",CustomAction:"custom_code/actions/",CustomFunction:"flutter_flow/custom_functions.dart",CustomClass:"custom_code/",CodeFile:"custom_code/"},Jf=new Set(["void","dynamic","String","int","double","num","bool","Color","DateTime","DateTimeRange","LatLng","FFPlace","FFUploadedFile","DocumentReference","List"]),Yf=["Struct","Record"],Zf=[{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=>kn(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=>kn(t).some(e=>{const s=/^\s*final\s+(?:double|int|String|bool|Color|num)\s+(\w+)\s*;/gm;let r;for(;(r=s.exec(e))!==null;){const i=r[1];if(!(new RegExp(`this\\.${i}\\s*=(?!=)`).test(e)||new RegExp(`[:,]\\s*${i}\\s*=(?!=)`).test(e)))return!0}return!1}),pos:`class W extends StatefulWidget { +(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const n of document.querySelectorAll('link[rel="modulepreload"]'))r(n);new MutationObserver(n=>{for(const i of n)if(i.type==="childList")for(const o of i.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&r(o)}).observe(document,{childList:!0,subtree:!0});function s(n){const i={};return n.integrity&&(i.integrity=n.integrity),n.referrerPolicy&&(i.referrerPolicy=n.referrerPolicy),n.crossOrigin==="use-credentials"?i.credentials="include":n.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function r(n){if(n.ep)return;n.ep=!0;const i=s(n);fetch(n.href,i)}})();var v=typeof window<"u"?window:void 0,we=typeof globalThis<"u"?globalThis:v,ke=we?.navigator,C=we?.document,re=we?.location,Lo=we?.fetch,Ri=we!=null&&we.XMLHttpRequest&&"withCredentials"in new we.XMLHttpRequest?we.XMLHttpRequest:void 0,La=we?.AbortController,ch=we?.CompressionStream,Pe=ke?.userAgent;function Ic(){return!(!v||v.navigator.onLine===!1)}var Fs=typeof globalThis<"u"?globalThis:v;Fs&&typeof self>"u"&&(Fs.self=Fs),Fs&&typeof File>"u"&&(Fs.File=function(){});var $=v??{},Y={DEBUG:!1,LIB_VERSION:"0.5.0",LIB_NAME:"browser-common"};function Oa(t,e,s,r,n,i,o){try{var a=t[i](o),l=a.value}catch(u){return void s(u)}a.done?e(l):Promise.resolve(l).then(r,n)}function X(t){return function(){var e=this,s=arguments;return new Promise((function(r,n){var i=t.apply(e,s);function o(l){Oa(i,r,n,o,a,"next",l)}function a(l){Oa(i,r,n,o,a,"throw",l)}o(void 0)}))}}function w(){return w=Object.assign?Object.assign.bind():function(t){for(var e=1;arguments.length>e;e++){var s=arguments[e];for(var r in s)({}).hasOwnProperty.call(s,r)&&(t[r]=s[r])}return t},w.apply(null,arguments)}function Cc(t,e){if(t==null)return{};var s={};for(var r in t)if({}.hasOwnProperty.call(t,r)){if(e.indexOf(r)!==-1)continue;s[r]=t[r]}return s}var Da=t=>{if(typeof t!="string")return t;try{return JSON.parse(t)}catch{return t}};function Ba(t){return typeof t=="string"||t}function ja(t){return typeof t=="string"?t:void 0}var Ps,uh=["$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})({}),Ua=(function(t){return t.GZipJS="gzip-js",t.Base64="base64",t})({}),dh=["$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"],hh=["token"],Fc="NativeGzipValidationError",Ti=t=>t.length>=2&&t[0]===31&&t[1]===139,Ha=(t,e)=>t===Ua.GZipJS||e===Ua.GZipJS||e==="gzip",Wa=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=Fc,e},ph=(function(){var t=X((function*(e,s){18>e.size&&wr("too-short");var r=new Uint8Array(yield e.slice(0,10).arrayBuffer());Ti(r)&&r[2]===8||wr("invalid-header");var n=new DataView(yield e.slice(e.size-8).arrayBuffer());n.getUint32(0,!0)!==(o=>{for(var a=(()=>{if(Ps)return Ps;Ps=[];for(var c=0;256>c;c++){for(var d=c,h=0;8>h;h++)d=1&d?3988292384^d>>>1:d>>>1;Ps[c]=d>>>0}return Ps})(),l=4294967295,u=0;o.length>u;u++)l=a[255&(l^o[u])]^l>>>8;return(4294967295^l)>>>0})(s)&&wr("invalid-crc");var i=s.length>>>0;n.getUint32(4,!0)!==i&&wr("invalid-size")}));return function(e,s){return t.apply(this,arguments)}})();function Ni(){return Ni=X((function*(t,e,s){e===void 0&&(e=!0);try{var r=new TextEncoder().encode(t),n=new globalThis.CompressionStream("gzip"),i=n.writable.getWriter(),o=i.write(r).then((()=>i.close())).catch((function(){var u=X((function*(c){try{yield i.abort(c)}catch{}throw c}));return function(c){return u.apply(this,arguments)}})()),a=new Response(n.readable).blob(),l=(yield Promise.all([a,o]))[0];return yield ph(l,r),l}catch(u){if(s!=null&&s.rethrow)throw u;return e&&console.error("Failed to gzip compress data",u),null}})),Ni.apply(this,arguments)}var fh=["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"],za=function(t,e){if(e===void 0&&(e=[]),!t)return!1;var s=t.toLowerCase();return fh.concat(e).some((r=>{var n=r.toLowerCase();return s.indexOf(n)!==-1}))};function M(t,e){return t.indexOf(e)!==-1}var An=function(t){return t.trim()},Mi=function(t){return t.replace(/^\$/,"")};function Pc(t){var e,s=[];return(e=JSON.stringify(t,(function(r,n){if(typeof n=="bigint")return n.toString();if(typeof n!="function"&&typeof n!="symbol"){if(n instanceof Error)return{name:n.name,message:n.message,stack:n.stack};if(n&&typeof n=="object"){for(;s.length>0&&s[s.length-1]!==this;)s.pop();if(s.includes(n))return"[Circular]";s.push(n)}return n}})))!==null&&e!==void 0?e:"null"}var Ac=Object.prototype,$c=Ac.hasOwnProperty,$n=Ac.toString,L=Array.isArray||function(t){return $n.call(t)==="[object Array]"},Se=t=>typeof t=="function",te=t=>t===Object(t)&&!L(t),mt=t=>{if(te(t)){for(var e in t)if($c.call(t,e))return!1;return!0}return!1},x=t=>t===void 0,W=t=>$n.call(t)=="[object String]",Li=t=>W(t)&&t.trim().length===0,$e=t=>t===null,D=t=>x(t)||$e(t),he=t=>$n.call(t)=="[object Number]"&&t==t,lt=t=>he(t)&&t>0,Ke=t=>$n.call(t)==="[object Boolean]",gh=t=>t instanceof FormData,mh=t=>M(dh,t),vh=t=>M(hh,t);function Rc(t){return t===null||typeof t!="object"}function Vr(t,e){return{}.toString.call(t)==="[object "+e+"]"}function Oo(t){return typeof Event<"u"&&Tc(t,Event)}function Tc(t,e){try{return t instanceof e}catch{return!1}}var _h=[!0,"true",1,"1","yes"],Xn=t=>M(_h,t),yh=[!1,"false",0,"0","no"];function rt(t,e,s,r,n){return e>s&&(r.warn("min cannot be greater than max."),e=s),he(t)?t>s?(r.warn(" cannot be greater than max: "+s+". Using max value instead."),s):e>t?(r.warn(" cannot be less than min: "+e+". Using min value instead."),e):t:(r.warn(" must be a number. using max or fallback. max: "+s+", fallback: "+n),rt(n||s,e,s,r))}class wh{constructor(e){this.tt={},this.et=e.et,this.it=rt(e.bucketSize,0,100,e.rt),this.nt=rt(e.refillRate,0,this.it,e.rt),this.st=rt(e.refillInterval,0,864e5,e.rt)}ot(e,s){var r=Math.floor((s-e.lastAccess)/this.st);r>0&&(e.tokens=Math.min(e.tokens+r*this.nt,this.it),e.lastAccess=e.lastAccess+r*this.st)}consumeRateLimit(e){var s,r=Date.now(),n=String(e),i=this.tt[n];return i?this.ot(i,r):this.tt[n]=i={tokens:this.it,lastAccess:r},i.tokens===0||(i.tokens--,i.tokens===0&&((s=this.et)==null||s.call(this,e)),i.tokens===0)}stop(){this.tt={}}}var Oe="Mobile",Gr="iOS",vt="Android",fs="Tablet",Nc=vt+" "+fs,Mc="iPad",Lc="Apple",Oc=Lc+" Watch",Vs="Safari",gs="BlackBerry",Dc="Samsung",Bc=Dc+"Browser",jc=Dc+" Internet",Gt="Chrome",bh=Gt+" OS",Uc=Gt+" "+Gr,Do="Internet Explorer",Hc=Do+" "+Oe,Bo="Opera",Eh=Bo+" Mini",jo="Edge",Wc="Microsoft "+jo,ds="Firefox",zc=ds+" "+Gr,tr="Nintendo",sr="PlayStation",hs="Xbox",qc=vt+" "+Oe,Vc=Oe+" "+Vs,Bs="Windows",Oi=Bs+" Phone",qa="Nokia",Di="Ouya",Gc="Generic",Sh=Gc+" "+Oe.toLowerCase(),Kc=Gc+" "+fs.toLowerCase(),Bi="Konqueror",Jc="Oculus Browser",Kr="Vivaldi",Yc="Yandex",Jr="Whale",ji="DuckDuckGo",Zc="Pale Moon",Yr="Waterfox",Gs="Brave",Xc="Google Search App",le="(\\d+(\\.\\d+)?)",Qn=new RegExp("Version/"+le),xh=new RegExp(hs,"i"),kh=new RegExp(sr+" \\w+","i"),Ih=new RegExp(tr+" \\w+","i"),Uo=new RegExp(gs+"|PlayBook|BB10","i"),Ch={"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"},Qc=function(t,e,s,r){e=e||"";var n=(function(i){return i!=null&&i.brave?Gs:null})(s);return n||(r!=null&&r.detectGoogleSearchApp&&M(t,"GSA/")?Xc:M(t," OPR/")&&M(t,"Mini")?Eh:M(t," OPR/")?Bo:Uo.test(t)?gs:M(t,"IE"+Oe)||M(t,"WPDesktop")?Hc:M(t,"OculusBrowser")?Jc:M(t,Bc)?jc:M(t,jo)||M(t,"Edg/")?Wc:M(t,Kr+"/")?Kr:M(t,"YaBrowser/")?Yc:M(t,Jr+"/")?Jr:M(t,ji+"/")||M(t,"Ddg/")?ji:M(t,"FBIOS")?"Facebook "+Oe:M(t,"UCWEB")||M(t,"UCBrowser")?"UC Browser":M(t,"CriOS")?Uc:M(t,"CrMo")||M(t,Gt)?Gt:M(t,vt)&&M(t,Vs)?qc:M(t,"FxiOS")?zc:M(t.toLowerCase(),Bi.toLowerCase())?Bi:M(t,Gs+"/")?Gs:((i,o)=>o&&M(o,Lc)||(function(a){return M(a,Vs)&&!M(a,Gt)&&!M(a,vt)})(i))(t,e)?M(t,Oe)?Vc:Vs:M(t,"PaleMoon/")?Zc:M(t,Yr+"/")?Yr:M(t,ds)?ds:M(t,"MSIE")||M(t,"Trident/")?Do:M(t,"Gecko")?ds:"")},Fh={[Hc]:[new RegExp("rv:"+le)],[Wc]:[new RegExp(jo+"?\\/"+le)],[Gt]:[new RegExp("("+Gt+"|CrMo)\\/"+le)],[Uc]:[new RegExp("CriOS\\/"+le)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+le)],[Vs]:[Qn],[Vc]:[Qn],[Bo]:[new RegExp("(Opera|OPR)\\/"+le)],[ds]:[new RegExp(ds+"\\/"+le)],[zc]:[new RegExp("FxiOS\\/"+le)],[Bi]:[new RegExp("Konqueror[:/]?"+le,"i")],[gs]:[new RegExp(gs+" "+le),Qn],[qc]:[new RegExp("android\\s"+le,"i")],[jc]:[new RegExp(Bc+"\\/"+le)],[Jc]:[new RegExp("OculusBrowser\\/"+le)],[Kr]:[new RegExp(Kr+"\\/"+le)],[Yc]:[new RegExp("YaBrowser\\/"+le)],[Jr]:[new RegExp(Jr+"\\/"+le)],[Gs]:[new RegExp(Gs+"\\/"+le)],[ji]:[new RegExp("(DuckDuckGo|Ddg)\\/"+le)],[Zc]:[new RegExp("PaleMoon\\/"+le)],[Yr]:[new RegExp(Yr+"\\/"+le)],[Xc]:[new RegExp("GSA\\/"+le)],[Do]:[new RegExp("(rv:|MSIE )"+le)],Mozilla:[new RegExp("rv:"+le)]},Ph=function(t,e,s,r){var n=Qc(t,e,s,r),i=Fh[n];if(x(i))return null;for(var o=0;i.length>o;o++){var a=t.match(i[o]);if(a)return parseFloat(a[a.length-2])}return null},Va=[[new RegExp(hs+"; "+hs+" (.*?)[);]","i"),t=>[hs,t&&t[1]||""]],[new RegExp(tr,"i"),[tr,""]],[new RegExp(sr,"i"),[sr,""]],[Uo,[gs,""]],[new RegExp(Bs,"i"),(t,e)=>{if(/Phone/.test(e)||/WPDesktop/.test(e))return[Oi,""];if(new RegExp(Oe).test(e)&&!/IEMobile\b/.test(e))return[Bs+" "+Oe,""];var s=/Windows NT ([0-9.]+)/i.exec(e);if(s&&s[1]){var r=Ch[s[1]]||"";return/arm/i.test(e)&&(r="RT"),[Bs,r]}return[Bs,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,t=>t&&t[3]?[Gr,[t[3],t[4],t[5]||"0"].join(".")]:[Gr,""]],[/(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i,t=>{var e="";return t&&t.length>=3&&(e=x(t[2])?t[3]:t[2]),["watchOS",e]}],[new RegExp("("+vt+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+vt+")","i"),t=>t&&t[2]?[vt,[t[2],t[3],t[4]||"0"].join(".")]:[vt,""]],[/Mac OS X (\d+)[_.](\d+)[_.]?(\d+)?/i,t=>{var e=["Mac OS X",""];return t&&t[1]&&(e[1]=[t[1],t[2],t[3]||"0"].join(".")),e}],[/Mac/i,["Mac OS X",""]],[/CrOS/,[bh,""]],[/Linux|debian/i,["Linux",""]]],Ga=function(t){return Ih.test(t)?tr:kh.test(t)?sr:xh.test(t)?hs:new RegExp(Di,"i").test(t)?Di:new RegExp("("+Oi+"|WPDesktop)","i").test(t)?Oi:/iPad/.test(t)?Mc:/iPod/.test(t)?"iPod Touch":/iPhone/.test(t)?"iPhone":/(watch)(?: ?os[,/]|\d,\d\/)[\d.]+/i.test(t)?Oc:Uo.test(t)?gs:/(kobo)\s(ereader|touch)/i.test(t)?"Kobo":new RegExp(qa,"i").test(t)?qa:/(kf[a-z]{2}wi|aeo[c-r]{2})( bui|\))/i.test(t)||/(kf[a-z]+)( bui|\)).+silk\//i.test(t)?"Kindle Fire":/(Android|ZTE)/i.test(t)?new RegExp(Oe).test(t)&&!/(9138B|TB782B|Nexus [97]|pixel c|HUAWEISHT|BTV|noble nook|smart ultra 6)/i.test(t)||/pixel[\daxl ]{1,6}/i.test(t)&&!/pixel c/i.test(t)||/(huaweimed-al00|tah-|APA|SM-G92|i980|zte|U304AA)/i.test(t)||/lmy47v/i.test(t)&&!/QTAQZ3/i.test(t)?vt:Nc:new RegExp("(pda|"+Oe+")","i").test(t)?Sh:new RegExp(fs,"i").test(t)&&!new RegExp(fs+" pc","i").test(t)?Kc:""},Ah=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Ka(t,e){return typeof(s=t)=="string"&&Ah.test(s)?t:e();var s}function Ct(t){return t&&t.split("#")[0]}function Ho(t,e){var s=setTimeout(t,e);return s?.unref&&s?.unref(),s}function Ja(t,e,s){return eu.apply(this,arguments)}function eu(){return(eu=X((function*(t,e,s){var r;try{return yield Promise.race([t,new Promise(((n,i)=>{r=Ho((()=>{try{s?.(),n()}catch(o){i(o)}}),e)}))])}finally{clearTimeout(r)}}))).apply(this,arguments)}var $h=t=>t instanceof Error,tu={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}},Rh=tu.info;function su(t){if(Ke(t))return{boolValue:t};if(typeof t=="number")return Number.isFinite(t)?Number.isInteger(t)?{intValue:t}:{doubleValue:t}:{stringValue:String(t)};if(typeof t=="string")return{stringValue:t};if(L(t))return{arrayValue:{values:t.map((e=>su(e)))}};try{return{stringValue:JSON.stringify(t)}}catch{return{stringValue:String(t)}}}function Zr(t){var e=[];for(var s in t){var r=t[s];$e(r)||x(r)||e.push({key:s,value:su(r)})}return e}function Th(t,e){var s=tu[t.level||"info"]||Rh,r=s.text,n=s.number,i=String(Date.now())+"000000",o={};e.distinctId&&(o.posthogDistinctId=e.distinctId),e.sessionId&&(o.sessionId=e.sessionId),e.windowId&&(o["window.id"]=e.windowId),D(e.sessionStartTimestamp)||(o.sessionStartTimestamp=String(e.sessionStartTimestamp)),D(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=w({},o,t.attributes||{}),l={timeUnixNano:i,observedTimeUnixNano:i,severityNumber:n,severityText:r,body:{stringValue:t.body},attributes:Zr(a)};return t.trace_id&&(l.traceId=t.trace_id),t.span_id&&(l.spanId=t.span_id),x(t.trace_flags)||(l.flags=t.trace_flags),l}function ru(t,e,s){return w({},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":s})}function nu(t,e,s,r){return{resourceLogs:[{resource:{attributes:Zr(e)},scopeLogs:[{scope:{name:s,version:r},logRecords:t}]}]}}let Nh=class{constructor(t,e,s,r,n,i,o){var a;i===void 0&&(i=()=>Promise.resolve()),this._instance=t,this.Ne=e,this.rt=s,this.ut=r,this.ht=n,this.dt=i,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 s={record:Th(e,this.ut())};this.ht((()=>this.At(s)))}}else this.rt.info("Log was rejected in beforeSend function")}}Pt(t){var e=this.Ne.beforeSend;if(!e)return t;var s=L(e)?e:[e],r=t;for(var n of s)try{var i=n(r);if(!i)return this.rt.info("Log was rejected in beforeSend function"),null;r=i}catch(o){return this.rt.error("Error in beforeSend function for log:",o),null}return r}Rt(){if(this.Tt===void 0)return!0;var t=Date.now(),e=t-this.bt;return this.Mt>e&&e>=0||(this.bt=t,this._t=0,this.wt=!1),this.Tt>this._t?(this._t++,!0):(this.wt||(this.rt.warn("captureLog dropping logs: exceeded "+this.Tt+" logs per "+this.Mt+"ms"),this.wt=!0),!1)}flush(){var t=this;return X((function*(){if(!t._instance.isDisabled)return t.ct||(t.ct=t.Ft().finally((()=>{t.ct=null}))),t.ct}))()}Ft(){var t=this;return X((function*(){var e;t.Et();var s=(e=t._instance.getPersistedProperty(ut.LogsQueue))!==null&&e!==void 0?e:[];if(s.length!==0)for(var r=s.length,n=0;s.length>0&&r>n;){var i,o;t.ft=0;var a=Math.min(s.length,t.Ct),l=s.slice(0,a),u=nu(l.map((d=>d.record)),t.Lt(),(i=t.vt)!==null&&i!==void 0?i: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),s=(o=t._instance.getPersistedProperty(ut.LogsQueue))!==null&&o!==void 0?o:[],n+=l.length,c.kind==="fatal"))throw c.error}}))()}Dt(t){var e=this;return X((function*(){var s,r=Math.max(0,t-e.ft),n=(s=e._instance.getPersistedProperty(ut.LogsQueue))!==null&&s!==void 0?s:[];e._instance.setPersistedProperty(ut.LogsQueue,n.slice(r)),yield e.dt()}))()}Lt(){return ru(this.Ne,this._instance.getLibraryId(),this._instance.getLibraryVersion())}At(t){var e;if(!this._instance.optedOut){var s=(e=this._instance.getPersistedProperty(ut.LogsQueue))!==null&&e!==void 0?e:[];this.xt>s.length||(s.shift(),this.ft++,this.rt.info("Logs queue is full, dropping oldest record.")),s.push(t),this._instance.setPersistedProperty(ut.LogsQueue,s),this.kt>s.length?this.$t():this.It()}}$t(t){t===void 0&&(t=this.St),this.Nt||(this.Nt=Ho((()=>{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 X((function*(){e.Et();var s=e.flush().catch((()=>{}));t!==void 0?yield Ja(s,t):yield s}))()}flushWithTimeout(t){var e=this;return X((function*(){var s=e.flush();yield Ja(s,t,(()=>{s.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 ei=[0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4];function Ya(t){return String(t)+"000000"}function Za(t,e,s,r){var n="";return r&&(n=Object.keys(r).sort().map((i=>JSON.stringify(i)+":"+JSON.stringify(r[i]))).join(",")),t+"\0"+e+"\0"+(s??"")+"\0"+n}let Mh=class{constructor(t,e,s){this._instance=t,this.Ne=e,this.rt=s,this.Bt=new Map,this.ct=null,this.Ht=!1,this.Ut=new Map,this.zt=new Set,this.Wt=0}count(t,e,s){e===void 0&&(e=1),this.Vt({name:t,type:"count",value:e,unit:s?.unit,attributes:s?.attributes})}gauge(t,e,s){this.Vt({name:t,type:"gauge",value:e,unit:s?.unit,attributes:s?.attributes})}histogram(t,e,s){this.Vt({name:t,type:"histogram",value:e,unit:s?.unit,attributes:s?.attributes})}flush(){var t=this,e=this.ct,s=(function(){var n=X((function*(){e&&(yield e.catch((()=>{}))),yield t.Zt()}));return function(){return n.apply(this,arguments)}})(),r=s().finally((()=>{this.ct===r&&(this.ct=null)}));return this.ct=r,r}drainWindow(){if(this.Bt.size===0)return null;var t=this.Bt;return this.Bt=new Map,this.Ht=!1,this.Ut=new Map,this.zt=new Set,this.Gt(t)}reset(){this.Wt++,this.Et(),this.Bt=new Map,this.ct=null,this.Ht=!1,this.Ut=new Map,this.zt=new Set}Vt(t){if(!this._instance.isDisabled&&!this._instance.optedOut){var e=this.Pt(t);if(e!==null)if(e.name&&typeof e.name=="string")if(typeof e.value=="number"&&Number.isFinite(e.value))if(e.type==="count"&&0>e.value)this.rt.warn("Dropping count '"+e.name+"': counters are monotonic, value must be >= 0");else{var s,r;try{s=e.attributes?w({},e.attributes):void 0,r=Za(e.type,e.name,e.unit,s)}catch(o){return void this.rt.warn("Dropping metric '"+e.name+"': attributes could not be serialized",o)}var n=this.Bt.get(r);if(!n){if(!this.Qt())return;n={name:e.name,type:e.type,unit:e.unit,attributes:s,windowStartMs:Date.now()},this.Bt.set(r,n)}var i=this.Ut.get(e.name);i===void 0?this.Ut.set(e.name,e.type):i===e.type||this.zt.has(e.name)||(this.zt.add(e.name),this.rt.warn("Metric name '"+e.name+"' is already used as a "+i+"; recording it as a "+e.type+" too will blend both series in charts. Use a distinct name.")),this.Kt(n,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 s;switch(t.type){case"count":t.total=((s=t.total)!==null&&s!==void 0?s: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(ei.length+1).fill(0)});var r=t.hist;r.count+=1,r.sum+=e,r.min=Math.min(r.min,e),r.max=Math.max(r.max,e),r.bucketCounts[(function(n,i){for(var o=0;i.length>o;o++)if(i[o]>=n)return o;return i.length})(e,ei)]+=1}}Pt(t){var e=this.Ne.beforeSend;if(!e)return t;var s=L(e)?e:[e],r=t;for(var n of s)try{var i=n(r);if(!i)return this.rt.info("Metric was rejected in beforeSend function"),null;r=i}catch(o){return this.rt.error("Error in beforeSend function for metric:",o),null}return r}$t(){this.Nt||(this.Nt=Ho((()=>{this.Nt=void 0,this.flush().catch((t=>{this.rt.error("Metrics flush failed:",t)}))}),this.Ne.flushIntervalMs))}Et(){this.Nt&&(clearTimeout(this.Nt),this.Nt=void 0)}Zt(){var t=this;return X((function*(){if(t.Bt.size!==0){var e=t.Bt;t.Bt=new Map,t.Ht=!1,t.Ut=new Map,t.zt=new Set;var s=t.Wt,r=yield t._instance.Jt(t.Gt(e));if(s===t.Wt)switch(r.kind){case"ok":return;case"retry-later":return t.Yt(e),void t.$t();case"too-large":return void t.rt.warn("Metrics batch exceeded the server size limit and was dropped");case"fatal":return void t.rt.error("Failed to send metrics batch:",r.error)}}}))()}Gt(t){return e=this.Xt(t),s=(function(i,o,a){return w({},i.resourceAttributes,{"service.name":i.serviceName||"unknown_service"},i.environment&&{"deployment.environment":i.environment},i.serviceVersion&&{"service.version":i.serviceVersion},{"telemetry.sdk.name":o,"telemetry.sdk.version":a})})(this.Ne,this._instance.getLibraryId(),this._instance.getLibraryVersion()),r=this._instance.getLibraryId(),n=this._instance.getLibraryVersion(),{resourceMetrics:[{resource:{attributes:Zr(s)},scopeMetrics:[{scope:{name:r,version:n},metrics:e}]}]};var e,s,r,n}Xt(t){var e=Ya(Date.now()),s=new Map;for(var r of t.values()){var n,i=Za(r.type,r.name,r.unit,void 0),o=s.get(i);o||(o=w({name:r.name},r.unit&&{unit:r.unit}),r.type==="count"?o.sum={aggregationTemporality:1,isMonotonic:!0,dataPoints:[]}:r.type==="gauge"?o.gauge={dataPoints:[]}:o.histogram={aggregationTemporality:1,dataPoints:[]},s.set(i,o));var a=Zr((n=r.attributes)!==null&&n!==void 0?n:{}),l=Ya(r.windowStartMs);if(r.type==="count"){var u,c={attributes:a,startTimeUnixNano:l,timeUnixNano:e,asDouble:(u=r.total)!==null&&u!==void 0?u:0};o.sum.dataPoints.push(c)}else if(r.type==="gauge"){var d,h={attributes:a,timeUnixNano:e,asDouble:(d=r.last)!==null&&d!==void 0?d:0};o.gauge.dataPoints.push(h)}else r.hist&&o.histogram.dataPoints.push({attributes:a,startTimeUnixNano:l,timeUnixNano:e,count:r.hist.count,sum:r.hist.sum,min:r.hist.min,max:r.hist.max,bucketCounts:r.hist.bucketCounts,explicitBounds:ei})}return Array.from(s.values())}Yt(t){var e,s;for(var r of t){var n=r[0],i=r[1],o=this.Bt.get(n);if(o)switch(o.windowStartMs=Math.min(o.windowStartMs,i.windowStartMs),o.type){case"count":o.total=((e=o.total)!==null&&e!==void 0?e:0)+((s=i.total)!==null&&s!==void 0?s:0);break;case"gauge":break;case"histogram":if(i.hist)if(o.hist){o.hist.count+=i.hist.count,o.hist.sum+=i.hist.sum,o.hist.min=Math.min(o.hist.min,i.hist.min),o.hist.max=Math.max(o.hist.max,i.hist.max);for(var a=0;o.hist.bucketCounts.length>a;a++)o.hist.bucketCounts[a]+=i.hist.bucketCounts[a]}else o.hist=i.hist}else this.Qt()&&this.Bt.set(n,i)}}};var br,Xa,ti;function Lh(t){var e=globalThis._posthogChunkIds;if(e){var s=Object.keys(e);return ti&&s.length===Xa||(Xa=s.length,ti=s.reduce(((r,n)=>{br||(br={});var i=br[n];if(i)r[i[0]]=i[1];else for(var o=t(n),a=o.length-1;a>=0;a--){var l=o[a],u=l?.filename,c=e[n];if(u&&c){r[u]=c,br[n]=[u,c];break}}return r}),{})),ti}}class Oh{constructor(e,s,r){r===void 0&&(r=[]),this.coercers=e,this.stackParser=s,this.modifiers=r}buildFromUnknown(e,s){s===void 0&&(s={});var r=s&&s.mechanism||{handled:!0,type:"generic"},n=this.buildCoercingContext(r,s,0).apply(e),i=this.buildParsingContext(s),o=this.parseStacktrace(n,i);return{$exception_list:this.convertToExceptionList(o,r),$exception_level:"error"}}modifyFrames(e){var s=this;return X((function*(){for(var r of e)r.stacktrace&&r.stacktrace.frames&&L(r.stacktrace.frames)&&(r.stacktrace.frames=yield s.applyModifiers(r.stacktrace.frames));return e}))()}coerceFallback(e){var s;return{type:"Error",value:"Unknown error",stack:(s=e.syntheticException)==null?void 0:s.stack,synthetic:!0}}parseStacktrace(e,s){var r,n;return e.cause!=null&&(r=this.parseStacktrace(e.cause,s)),e.stack!=""&&e.stack!=null&&(n=this.applyChunkIds(this.stackParser(e.stack,e.synthetic?s.skipFirstLines:0),s.chunkIdMap)),w({},e,{cause:r,stack:n})}applyChunkIds(e,s){return e.map((r=>(r.filename&&s&&(r.chunk_id=s[r.filename]),r)))}applyCoercers(e,s){for(var r of this.coercers)if(r.match(e))return r.coerce(e,s);return this.coerceFallback(s)}applyModifiers(e){var s=this;return X((function*(){var r=e;for(var n of s.modifiers)r=yield n(r);return r}))()}convertToExceptionList(e,s){var r,n,i,o={type:e.type,value:e.value,mechanism:{type:(r=s.type)!==null&&r!==void 0?r:"generic",handled:(n=s.handled)===null||n===void 0||n,synthetic:(i=e.synthetic)!==null&&i!==void 0&&i}};e.stack&&(o.stacktrace={type:"raw",frames:e.stack});var a=[o];return e.cause!=null&&a.push(...this.convertToExceptionList(e.cause,w({},s,{handled:!0}))),a}buildParsingContext(e){var s;return{chunkIdMap:Lh(this.stackParser),skipFirstLines:(s=e.skipFirstLines)!==null&&s!==void 0?s:1}}buildCoercingContext(e,s,r){r===void 0&&(r=0);var n=(i,o)=>{if(4>=o){var a=this.buildCoercingContext(e,s,o);return this.applyCoercers(i,a)}};return w({},s,{syntheticException:r==0?s.syntheticException:void 0,mechanism:e,apply:i=>n(i,r),next:i=>n(i,r+1)})}}var ms="?";function Ui(t,e,s,r,n){var i={platform:t,filename:e,function:s===""?ms:s,in_app:!0};return x(r)||(i.lineno=r),x(n)||(i.colno=n),i}var iu=(t,e)=>{var s=t.indexOf("safari-extension")!==-1,r=t.indexOf("safari-web-extension")!==-1;return s||r?[t.indexOf("@")!==-1?t.split("@")[0]:ms,s?"safari-extension:"+e:"safari-web-extension:"+e]:[t,e]},Dh=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,Bh=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,jh=/\((\S*)(?::(\d+))(?::(\d+))\)/,Uh=(t,e)=>{var s=Dh.exec(t);if(s)return Ui(e,s[1],ms,+s[2],+s[3]);var r=Bh.exec(t);if(r){if(r[2]&&r[2].indexOf("eval")===0){var n=jh.exec(r[2]);n&&(r[2]=n[1],r[3]=n[2],r[4]=n[3])}var i=iu(r[1]||ms,r[2]);return Ui(e,i[1],i[0],r[3]?+r[3]:void 0,r[4]?+r[4]:void 0)}},Hh=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,Wh=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,zh=(t,e)=>{var s=Hh.exec(t);if(s){if(s[3]&&s[3].indexOf(" > eval")>-1){var r=Wh.exec(s[3]);r&&(s[1]=s[1]||"eval",s[3]=r[1],s[4]=r[2],s[5]="")}var n=s[3],i=s[1]||ms,o=iu(i,n);return Ui(e,n=o[1],i=o[0],s[4]?+s[4]:void 0,s[5]?+s[5]:void 0)}},Qa=/\(error: (.*)\)/;class qh{match(e){return this.isDOMException(e)||this.isDOMError(e)}coerce(e,s){var r=W(e.stack);return{type:this.getType(e),value:this.getValue(e),stack:r?e.stack:void 0,cause:e.cause?s.next(e.cause):void 0,synthetic:!1}}getType(e){return this.isDOMError(e)?"DOMError":"DOMException"}getValue(e){var s=e.name||(this.isDOMError(e)?"DOMError":"DOMException");return e.message?s+": "+e.message:s}isDOMException(e){return Vr(e,"DOMException")}isDOMError(e){return Vr(e,"DOMError")}}class Vh{match(e){return(function(s){switch({}.toString.call(s)){case"[object Error]":case"[object Exception]":case"[object DOMException]":case"[object DOMError]":case"[object WebAssembly.Exception]":return!0;default:return Tc(s,Error)}})(e)}coerce(e,s){return{type:this.getType(e),value:this.getMessage(e,s),stack:this.getStack(e),cause:e.cause?s.next(e.cause):void 0,synthetic:!1}}getType(e){return e.name||e.constructor.name}getMessage(e,s){var r=e.message;return String(r.error&&typeof r.error.message=="string"?r.error.message:r)}getStack(e){return e.stacktrace||e.stack||void 0}}class Gh{constructor(){}match(e){return!!Vr(e,"ErrorEvent")&&(e.error!=null||this.fe(e))}coerce(e,s){var r;if(e.error!=null)return s.apply(e.error);var n=s.apply(e.message);return w({},n,{stack:(r=this.pe(e))!==null&&r!==void 0?r:n.stack,synthetic:!0})}fe(e){return W(e.message)&&e.message.length>0}pe(e){var s=e;if(W(s.filename)&&s.filename.length>0){var r,n,i=(r=s.lineno)!==null&&r!==void 0?r:0,o=(n=s.colno)!==null&&n!==void 0?n:0;return`Error + at `+s.filename+":"+i+":"+o}}}var Kh=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;class Jh{match(e){return typeof e=="string"}coerce(e,s){var r,n=this.getInfos(e),i=n[0],o=n[1];return{type:i??"Error",value:o??e,stack:(r=s.syntheticException)==null?void 0:r.stack,synthetic:!0}}getInfos(e){var s="Error",r=e,n=e.match(Kh);return n&&(s=n[1],r=n[2]),[s,r]}}var Yh=["fatal","error","warning","log","info","debug"];function ou(t,e){e===void 0&&(e=40);var s=Object.keys(t);if(s.sort(),!s.length)return"[object has no keys]";for(var r=s.length;r>0;r--){var n=s.slice(0,r).join(", ");if(e>=n.length)return r===s.length?n:n.length>e?n.slice(0,e)+"...":n}return""}class Zh{match(e){return typeof e=="object"&&e!==null}coerce(e,s){var r,n,i=this.getErrorPropertyFromObject(e);return i?s.apply(i):{type:this.getType(e),value:this.getValue(e),stack:(r=this.getStack(e))!==null&&r!==void 0?r:(n=s.syntheticException)==null?void 0:n.stack,level:this.isSeverityLevel(e.level)?e.level:"error",synthetic:!0}}getType(e){return Oo(e)?e.constructor.name:"Error"}getValue(e){if("name"in e&&typeof e.name=="string"){var s="'"+e.name+"' captured as exception";return"message"in e&&typeof e.message=="string"&&(s+=" with message: '"+e.message+"'"),s}if("message"in e&&typeof e.message=="string")return e.message;var r=this.getObjectClassName(e);return(r&&r!=="Object"?"'"+r+"'":"Object")+" captured as exception with keys: "+ou(e)}isSeverityLevel(e){return W(e)&&!Li(e)&&Yh.indexOf(e)>=0}getStack(e){try{return W(e.stacktrace)&&e.stacktrace.length>0?e.stacktrace:W(e.stack)&&e.stack.length>0?e.stack:void 0}catch{return}}getErrorPropertyFromObject(e){for(var s in e)if({}.hasOwnProperty.call(e,s)){var r=e[s];if($h(r))return r}}getObjectClassName(e){try{var s=Object.getPrototypeOf(e);return s?s.constructor.name:void 0}catch{return}}}class Xh{match(e){return Oo(e)}coerce(e,s){var r,n=e.constructor.name;return{type:n,value:n+" captured as exception with keys: "+ou(e),stack:(r=s.syntheticException)==null?void 0:r.stack,synthetic:!0}}}class Qh{match(e){return Rc(e)}coerce(e,s){var r;return{type:"Error",value:"Primitive value captured as exception: "+String(e),stack:(r=s.syntheticException)==null?void 0:r.stack,synthetic:!0}}}class ep{match(e){return Vr(e,"PromiseRejectionEvent")||this.isCustomEventWrappingRejection(e)}isCustomEventWrappingRejection(e){if(!Oo(e))return!1;try{var s=e.detail;return s!=null&&typeof s=="object"&&"reason"in s}catch{return!1}}coerce(e,s){var r,n=this.getUnhandledRejectionReason(e);return Rc(n)?{type:"UnhandledRejection",value:"Non-Error promise rejection captured with value: "+String(n),stack:(r=s.syntheticException)==null?void 0:r.stack,synthetic:!0}:s.apply(n)}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 Xr="$message",Qr="$timestamp",tp=new Set([Xr,Qr]),si={enabled:!0,max_bytes:32768};function en(t){var e;return t?{enabled:(e=t.enabled)!==null&&e!==void 0?e:si.enabled,max_bytes:rp(t.max_bytes,si.max_bytes)}:w({},si)}class sp{constructor(e){this.Ke=[],this.Je=0,this.Ne=en(e)}setConfig(e){this.Ne=en(e),this.Xe()}add(e){var s=(function(n){var i;try{i=Pc(n)}catch{return}try{var o=JSON.parse(i);if(!te(o))return;var a=o,l=a[Xr],u=a[Qr];return!W(l)||l.trim().length===0||!W(u)&&!he(u)?void 0:{step:a,json:i}}catch{return}})(e);if(s){var r=(function(n){if(typeof TextEncoder<"u")return new TextEncoder().encode(n).length;for(var i=encodeURIComponent(n),o=0,a=0;i.length>a;a++)i[a]==="%"?(o+=1,a+=2):o+=1;return o})(s.json);r>this.Ne.max_bytes||(this.Ke.push({step:s.step,bytes:r}),this.Je+=r,this.Xe())}}getAttachable(){return this.Ke.map((e=>e.step))}clear(){this.Ke=[],this.Je=0}size(){return this.Ke.length}Xe(){for(;this.Je>this.Ne.max_bytes&&this.Ke.length>0;){var e=this.Ke.shift();e&&(this.Je-=e.bytes)}}}function rp(t,e){if(!he(t)||t===1/0||t===-1/0)return e;var s=Math.floor(t);return 0>s?e:s}var au=function(t,e){var s=(e===void 0?{}:e).debugEnabled,r={k(n){if(v&&(Y.DEBUG||v.POSTHOG_DEBUG||s)&&!x(v.console)&&v.console){for(var i=("__rrweb_original__"in v.console[n])?v.console[n].__rrweb_original__:v.console[n],o=arguments.length,a=new Array(o>1?o-1:0),l=1;o>l;l++)a[l-1]=arguments[l];i(t,...a)}},debug(){for(var n=arguments.length,i=new Array(n),o=0;n>o;o++)i[o]=arguments[o];r.k("debug",...i)},info(){for(var n=arguments.length,i=new Array(n),o=0;n>o;o++)i[o]=arguments[o];r.k("log",...i)},warn(){for(var n=arguments.length,i=new Array(n),o=0;n>o;o++)i[o]=arguments[o];r.k("warn",...i)},error(){for(var n=arguments.length,i=new Array(n),o=0;n>o;o++)i[o]=arguments[o];r.k("error",...i)},critical(){for(var n=arguments.length,i=new Array(n),o=0;n>o;o++)i[o]=arguments[o];console.error(t,...i)},uninitializedWarning(n){r.error("You must initialize PostHog before calling "+n)},createLogger:(n,i)=>au(t+" "+n,i)};return r},k=au("[PostHog.js]"),se=k.createLogger,np=se("[ExternalScriptsLoader]"),ri=(t,e,s)=>{if(t.config.disable_external_dependency_loading)return np.warn(e+" was requested but loading of external scripts is disabled."),s("Loading of external scripts is disabled");var r=C?.querySelectorAll("script");if(r){for(var n,i=function(){if(r[o].src===e){var l=r[o];return l.__posthog_loading_callback_fired?{v:s()}:(l.addEventListener("load",(u=>{l.__posthog_loading_callback_fired=!0,s(void 0,u)})),l.onerror=u=>s(u),{v:void 0})}},o=0;r.length>o;o++)if(n=i())return n.v}var a=()=>{if(!C)return s("document not found");var l=C.createElement("script");if(l.type="text/javascript",l.crossOrigin="anonymous",l.src=e,l.onload=d=>{l.__posthog_loading_callback_fired=!0,s(void 0,d)},l.onerror=d=>s(d),t.config.prepare_external_dependency_script&&(l=t.config.prepare_external_dependency_script(l)),!l)return s("prepare_external_dependency_script returned null");if(t.config.external_scripts_inject_target==="head")C.head.appendChild(l);else{var u,c=C.querySelectorAll("body > script");c.length>0?(u=c[0].parentNode)==null||u.insertBefore(l,c[0]):C.body.appendChild(l)}};C!=null&&C.body?a():C?.addEventListener("DOMContentLoaded",a)};$.__PosthogExtensions__=$.__PosthogExtensions__||{},$.__PosthogExtensions__.loadExternalDependency=(t,e,s)=>{if(e!=="remote-config"){var r;if(t.config.strict_script_versioning)r=t.requestRouter.endpointFor("assets","/static/"+t.version+"/"+e+".js");else{var n="/static/"+e+".js?v="+t.version;if(e==="toolbar"){var i=3e5;n=n+"&t="+Math.floor(Date.now()/i)*i}r=t.requestRouter.endpointFor("assets",n)}ri(t,r,s)}else{var o=t.requestRouter.endpointFor("assets","/array/"+t.config.token+"/config.js");ri(t,o,s)}},$.__PosthogExtensions__.loadSiteApp=(t,e,s)=>{var r=t.requestRouter.endpointFor("api",e);ri(t,r,s)};Y.DEBUG=!1,Y.LIB_VERSION="1.415.7",Y.LIB_NAME="web";var lu="$people_distinct_id",rr="$device_id",ni="$device_model",js="__alias",Us="__timers",Hi="$autocapture_disabled_server_side",Wi="$heatmaps_enabled_server_side",zi="$exception_capture_enabled_server_side",qi="$error_tracking_suppression_rules",Vi="$error_tracking_capture_extension_exceptions",Gi="$web_vitals_enabled_server_side",Wo="$dead_clicks_enabled_server_side",zo="$product_tours_enabled_server_side",Ki="$web_vitals_allowed_metrics",Vt="$session_recording_remote_config",cu="$replay_sample_rate",uu="$replay_override_sampling",du="$replay_override_linked_flag",hu="$replay_override_url_trigger",pu="$replay_override_event_trigger",cs="$sesid",qo="$session_is_sampled",Bt="$enabled_feature_flags",Hs="$active_feature_flags",Tr="$early_access_features",Ji="$feature_flag_details",Ws="$feature_flag_payloads",Nr="$feature_flag_request_id",tn="$minimal_flag_called_events",et="$override_feature_flags",jt="$override_feature_flag_payloads",ct="$stored_person_properties",Ut="$stored_group_properties",Yi="$surveys",sn="$surveys_loaded_at",Zi="$surveys_activated",Mr="$surveys_activated_session",Lr="$surveys_activated_timestamps",zs="ph_product_tours",Wt="$flag_call_reported",qs="$flag_call_reported_session_id",Or="$feature_flag_errors",Ks="$feature_flag_evaluated_at",He="$user_state",Xi="$client_session_props",Qi="$capture_rate_limit",eo="$initial_campaign_params",to="$initial_referrer_info",rn="$initial_person_info",nn="$epp",Er="$posthog_cookieless",fu="$cookieless_mode",gu="$sdk_debug_extensions_init_method",mu="$sdk_debug_extensions_init_time_ms",vu="$sdk_debug_recording_script_not_loaded",Vo="PostHog loadExternalDependency extension not found.",Ht="on_reject",ht="always",ts="anonymous",Tt="identified",so="identified_only",on="visibilitychange",an="beforeunload",os="$pageview",ii="$pageleave",oi="$identify",el="$groupidentify";function Sr(t,e){L(t)&&t.forEach(e)}function Z(t,e){if(!D(t))if(L(t))t.forEach(e);else if(gh(t))t.forEach(((r,n)=>e(r,n)));else for(var s in t)$c.call(t,s)&&e(t[s],s)}var ee=function(t){for(var e=arguments.length,s=new Array(e>1?e-1:0),r=1;e>r;r++)s[r-1]=arguments[r];for(var n of s)for(var i in n)n[i]!==void 0&&(t[i]=n[i]);return t};function Dr(t){for(var e=Object.keys(t),s=e.length,r=new Array(s);s--;)r[s]=[e[s],t[e[s]]];return r}var tl=function(t){try{return t()}catch{return}},ip=function(t){return function(){try{for(var e=arguments.length,s=new Array(e),r=0;e>r;r++)s[r]=arguments[r];return t.apply(this,s)}catch(n){k.critical("Implementation error. Please turn on debug mode and open a ticket on https://app.posthog.com/home#panel=support%3Asupport%3A."),k.critical(n)}}},Go=function(t){var e={};return Z(t,(function(s,r){(W(s)&&s.length>0||he(s))&&(e[r]=s)})),e},op=["herokuapp.com","vercel.app","netlify.app"];function ap(t){var e=t?.hostname;if(!W(e))return!1;var s=e.split(".").slice(-2).join(".");for(var r of op)if(s===r)return!1;return!0}function ne(t,e,s,r){var n=r??{},i=n.capture,o=n.passive;t?.addEventListener(e,s,{capture:i!==void 0&&i,passive:o===void 0||o})}function ro(t){return t.name==="ph_toolbar_internal"}var _u=t=>{if(C){try{for(var e=t+"=",s=C.cookie.split(";").filter((i=>i.length)),r=0;s.length>r;r++){for(var n=s[r];n.charAt(0)==" ";)n=n.substring(1,n.length);if(n.indexOf(e)===0)return decodeURIComponent(n.substring(e.length,n.length))}}catch{}return null}};Math.trunc||(Math.trunc=function(t){return 0>t?Math.ceil(t):Math.floor(t)}),Number.isInteger||(Number.isInteger=function(t){return he(t)&&isFinite(t)&&Math.floor(t)===t});class ln{constructor(e){if(this.bytes=e,e.length!==16)throw new TypeError("not 128-bit length")}static fromFieldsV7(e,s,r,n){if(!Number.isInteger(e)||!Number.isInteger(s)||!Number.isInteger(r)||!Number.isInteger(n)||0>e||0>s||0>r||0>n||e>0xffffffffffff||s>4095||r>1073741823||n>4294967295)throw new RangeError("invalid field value");var i=new Uint8Array(16);return i[0]=e/Math.pow(2,40),i[1]=e/Math.pow(2,32),i[2]=e/Math.pow(2,24),i[3]=e/Math.pow(2,16),i[4]=e/256,i[5]=e,i[6]=112|s>>>8,i[7]=s,i[8]=128|r>>>24,i[9]=r>>>16,i[10]=r>>>8,i[11]=r,i[12]=n>>>24,i[13]=n>>>16,i[14]=n>>>8,i[15]=n,new ln(i)}toString(){for(var e="",s=0;this.bytes.length>s;s++)e=e+(this.bytes[s]>>>4).toString(16)+(15&this.bytes[s]).toString(16),s!==3&&s!==5&&s!==7&&s!==9||(e+="-");if(e.length!==36)throw new Error("Invalid UUIDv7 was generated");return e}clone(){return new ln(this.bytes.slice(0))}equals(e){return this.compareTo(e)===0}compareTo(e){for(var s=0;16>s;s++){var r=this.bytes[s]-e.bytes[s];if(r!==0)return Math.sign(r)}return 0}}class lp{generate(){var e=this.generateOrAbort();if(!x(e))return e;this.S=0;var s=this.generateOrAbort();if(x(s))throw new Error("Could not generate UUID after timestamp reset");return s}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 ln.fromFieldsV7(this.S,Math.trunc(this.I/Math.pow(2,30)),this.I&Math.pow(2,30)-1,this.A.nextUint32())}C(){this.I=1024*this.A.nextUint32()+(1023&this.A.nextUint32())}constructor(){this.S=0,this.I=0,this.A=new cp}}var sl,yu=t=>{if(typeof UUIDV7_DENY_WEAK_RNG<"u"&&UUIDV7_DENY_WEAK_RNG)throw new Error("no cryptographically strong RNG available");for(var e=0;t.length>e;e++)t[e]=65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random());return t};v&&!x(v.crypto)&&crypto.getRandomValues&&(yu=t=>crypto.getRandomValues(t));class cp{nextUint32(){return this.R.length>this.O||(yu(this.R),this.O=0),this.R[this.O++]}constructor(){this.R=new Uint32Array(8),this.O=1/0}}var dt=()=>up().toString(),up=()=>(sl||(sl=new lp)).generate(),As="",dp=/[a-z0-9][a-z0-9-]+\.[a-z]{2,}$/i,pt={N:()=>!!C,j(t){k.error("cookieStore error: "+t)},P:_u,H(t){var e;try{e=JSON.parse(pt.P(t))||{}}catch{}return e},F(t,e,s,r,n){if(!C)return!1;try{var i="",o="",a=(function(c,d){if(d){var h=(function(f,g){if(g===void 0&&(g=C),As)return As;if(!g||["localhost","127.0.0.1"].includes(f))return"";for(var m=f.split("."),_=Math.min(m.length,8),b="dmn_chk_"+dt();!As&&_--;){var E=m.slice(_).join("."),I=b+"=1;domain=."+E+";path=/";g.cookie=I+";max-age=3",g.cookie.includes(b)&&(g.cookie=I+";max-age=0",As=E)}return As})(c);if(!h){var p=(f=>{var g=f.match(dp);return g?g[0]:""})(c);p!==h&&k.info("Warning: cookie subdomain discovery mismatch",p,h),h=p}return h?"; domain=."+h:""}return""})(C.location.hostname,r);if(s){var l=new Date;l.setTime(l.getTime()+864e5*s),i="; expires="+l.toUTCString()}n&&(o="; secure");var u=t+"="+encodeURIComponent(JSON.stringify(e))+i+"; SameSite=Lax; path=/"+a+o;return u.length>3686.4&&k.warn("cookieStore warning: large cookie, len="+u.length),C.cookie=u,!0}catch{return!1}},q(t,e){if(C!=null&&C.cookie)try{pt.F(t,"",-1,e)}catch{return}}},ai=null,Q={N(){if(!$e(ai))return ai;var t=!0;if(x(v))t=!1;else try{var e="__mplssupport__";Q.F(e,"xyz"),Q.P(e)!=='"xyz"'&&(t=!1),Q.q(e)}catch{t=!1}return t||k.error("localStorage unsupported; falling back to cookie store"),ai=t,t},j(t){k.error("localStorage error: "+t)},P(t){try{return v?.localStorage.getItem(t)}catch(e){Q.j(e)}return null},H(t){try{return JSON.parse(Q.P(t))||{}}catch{}return null},F(t,e){try{return v?.localStorage.setItem(t,JSON.stringify(e)),!0}catch(s){Q.j(s)}return!1},q(t){try{v?.localStorage.removeItem(t)}catch(e){Q.j(e)}}},hp=[rr,"distinct_id",cs,qo,nn,rn,He],xr={},pp={N:()=>!0,j(t){k.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]}},Nt=null,ce={N(){if(!$e(Nt))return Nt;if(Nt=!0,x(v))Nt=!1;else try{var t="__support__";ce.F(t,"xyz"),ce.P(t)!=='"xyz"'&&(Nt=!1),ce.q(t)}catch{Nt=!1}return Nt},j(t){k.error("sessionStorage error: ",t)},P(t){try{return v?.sessionStorage.getItem(t)}catch(e){ce.j(e)}return null},H(t){try{return JSON.parse(ce.P(t))||null}catch{}return null},F(t,e){try{return v?.sessionStorage.setItem(t,JSON.stringify(e)),!0}catch(s){ce.j(s)}return!1},q(t){try{v?.sessionStorage.removeItem(t)}catch(e){ce.j(e)}}};class fp{constructor(e){this._instance=e}get Ne(){return this._instance.config}get consent(){return this.ti()?0:this.ei}isOptedOut(){return this.Ne.cookieless_mode===ht||this.isRejected()||this.consent===-1&&this.Ne.cookieless_mode===Ht}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,s=e.token,r=e.opt_out_capturing_cookie_prefix;return e.consent_persistence_name||(r?r+s:"__ph_opt_in_out_"+s)}get ei(){var e=this.ii.P(this.ri);return Xn(e)?1:M(yh,e)?0:-1}get ii(){var e=this.Ne.opt_out_capturing_persistence_type,s=e==="localStorage"?Q:pt;if(!this.ni||this.ni!==s){this.ni=s;var r=e==="localStorage"?pt:Q;r.P(this.ri)&&(this.ni.P(this.ri)||this.optInOut(Xn(r.P(this.ri))),r.q(this.ri,this.Ne.cross_subdomain_cookie))}return this.ni}ti(){return!!this.Ne.respect_dnt&&[ke?.doNotTrack,ke?.msDoNotTrack,$.doNotTrack].some((e=>Xn(e)))}}function wu(t,e){var s,r=t==null||(s=t.config)==null?void 0:s.get_current_url;if(!Se(r))return e;try{var n=r(e);return W(n)&&n?n:e}catch(i){return k.error("Error in get_current_url, falling back to window.location.href",i),e}}var bu="__POSTHOG_TOOLBAR__",gp=1,mp=3,vp=11;function rl(t){return t instanceof Element&&(t.id===bu||!(t.closest==null||!t.closest(".toolbar-global-fade-container")))}function Ft(t){return!!t&&t.nodeType===gp}function Me(t,e){return!!t&&!!t.tagName&&t.tagName.toLowerCase()===e.toLowerCase()}function Eu(t){return!!t&&t.nodeType===mp}function Su(t){return!!t&&t.nodeType===vp&&Ft(t.host)}var xu=1e3;function Ko(t){return t?An(t).split(/\s+/):[]}function nl(t,e){var s=(function(r){var n,i=v==null||(n=v.location)==null?void 0:n.href;return x(i)?void 0:wu(r,i)})(e);return!!(s&&t&&t.some((r=>s.match(r))))}function cn(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 Ko(e)}function ku(t){return D(t)?null:An(t).split(/(\s+)/).filter((e=>Js(e))).join("").replace(/[\r\n]/g," ").replace(/[ ]+/g," ").substring(0,255)}function nr(t){var e="";return io(t)&&!Pu(t)&&t.childNodes&&t.childNodes.length&&Z(t.childNodes,(function(s){var r;Eu(s)&&s.textContent&&(e+=(r=ku(s.textContent))!==null&&r!==void 0?r:"")})),An(e)}function li(t){var e;return x(t.target)?t.srcElement||null:(e=t.target)!=null&&e.shadowRoot?t.composedPath()[0]||null:t.target||null}var Jo=["a","button","form","input","select","textarea","label"];function no(t,e){if(x(e))return!0;var s,r=function(i){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}})(i,o))))return{v:!0}};for(var n of t)if(s=r(n))return s.v;return!1}function Iu(t){var e=t.parentNode;return!(!e||!Ft(e))&&e}var _p=[".ph-no-autocapture","[data-ph-no-autocapture]"],Cu=["next","previous","prev",">","<"],yp=[...Cu,"+","-","−","–"],il=(t,e)=>/[a-z0-9]/i.test(e)?t.includes(e):t===e,ol=[".ph-no-rageclick",".ph-no-capture"],wp=["","text","search","email","password","url","tel","number"];function al(t,e){if(!v||Yo(t))return!1;var s,r,n,i,o;if(Ke(e)?(s=!!e&&ol,r=void 0,n=!1):(s=(i=e?.css_selector_ignorelist)!==null&&i!==void 0?i:ol,r=e?.content_ignorelist,n=(o=e?.ignore_text_selection)!==null&&o!==void 0&&o),s===!1||n&&(function(l){return!(!l||!Ft(l))&&(!!Me(l,"textarea")||(Me(l,"input")?M(wp,(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=Fu(t,!1).targetElementList;return!(function(l,u){if(l===!1||x(l))return!1;var c;if(l===!0)c=Cu;else{if(!L(l))return!1;if(l.length>10)return k.error("[PostHog] content_ignorelist array cannot exceed 10 items. Use css_selector_ignorelist for more complex matching."),!1;c=l.map((d=>d.toLowerCase()))}return u.some((d=>{var h=d.safeText,p=d.ariaLabel;return c.some((f=>il(h,f)||il(p,f)))}))})(r,a.map((l=>{var u;return{safeText:nr(l).toLowerCase(),ariaLabel:((u=l.getAttribute("aria-label"))==null?void 0:u.toLowerCase().trim())||""}})))&&!no(a,s)}var Yo=t=>!t||Me(t,"html")||!Ft(t),Fu=(t,e)=>{if(!v||Yo(t))return{parentIsUsefulElement:!1,targetElementList:[]};for(var s=!1,r=[t],n=t;n.parentNode&&!Me(n,"body");)if(Su(n.parentNode))r.push(n.parentNode.host),n=n.parentNode.host;else{var i=Iu(n);if(!i)break;if(e||Jo.indexOf(i.tagName.toLowerCase())>-1)s=!0;else try{var o=v.getComputedStyle(i);o&&o.getPropertyValue("cursor")==="pointer"&&(s=!0)}catch{}r.push(i),n=i}return{parentIsUsefulElement:s,targetElementList:r}};function io(t){for(var e=new Set,s=0,r=t;r.parentNode&&!Me(r,"body");r=r.parentNode){if(s++>=xu||e.has(r))return!1;e.add(r);var n=cn(r);if(M(n,"ph-sensitive")||M(n,"ph-no-capture"))return!1}if(M(cn(t),"ph-include"))return!0;var i=t.type||"";if(W(i))switch(i.toLowerCase()){case"hidden":case"password":return!1}var o=t.name||t.id||"";return!W(o)||!/^cc|cardnum|ccnum|creditcard|csc|cvc|cvv|exp|pass|pwd|routing|seccode|securitycode|securitynum|socialsec|socsec|ssn/i.test(o.replace(/[^a-zA-Z0-9]/g,""))}function Pu(t){return!!(Me(t,"input")&&!["button","checkbox","submit","reset"].includes(t.type)||Me(t,"select")||Me(t,"textarea")||t.getAttribute("contenteditable")==="true")}var ll=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}))$"),cl=/(^|[^0-9A-Za-z_])([0-9][0-9 -]*[0-9])(?=$|[^0-9A-Za-z_])/g,bp=[16,15,14,13],Ep=new RegExp("^(\\d{3}-?\\d{2}-?\\d{4})$"),ul=new RegExp("(^|[^0-9])((?!000|666)[0-9]{3}-?(?!00)[0-9]{2}-?(?!0000)[0-9]{4})(?=$|([^0-9]))","g"),dl=/[0-9A-Za-z_]/;function Sp(t){for(var e=0,s=!1,r=t.length-1;r>=0;r--){var n=t.charCodeAt(r)-48;s&&(n*=2)>9&&(n-=9),e+=n,s=!s}return e%10==0}function Js(t,e){if(e===void 0&&(e=!0),D(t))return!1;if(W(t)){t=An(t);var s=e?ll.test((t||"").replace(/[- ]/g,"")):(function(n){var i;for(cl.lastIndex=0;i=cl.exec(n);){var o=i[2];if(o)for(var a=o.replace(/[- ]/g,""),l=0;a.length>l;l++)for(var u of bp){var c=l+u;if(a.length>=c){var d=a.slice(l,c);if(ll.test(d)&&Sp(d))return!0}}}return!1})(t);if(s)return!1;var r=e?Ep.test(t):(function(n){var i;for(ul.lastIndex=0;i=ul.exec(n);){var o=i[1],a=i[3];if(!(o&&a&&dl.test(o)&&dl.test(a)))return!0}return!1})(t);if(r)return!1}return!0}function hl(t){var e=nr(t);return Js(e=(e+" "+Au(t)).trim())?e:""}function Au(t){var e="";return t&&t.childNodes&&t.childNodes.length&&Z(t.childNodes,(function(s){var r;if(s&&((r=s.tagName)==null?void 0:r.toLowerCase())==="span")try{var n=nr(s);e=(e+" "+n).trim(),s.childNodes&&s.childNodes.length&&(e=(e+" "+Au(s)).trim())}catch(i){k.error("[AutoCapture]",i)}})),e}function pl(t){return t.replace(/"|\\"/g,'\\"')}function xp(t){var e=t.attr__class;if(e)return L(e)?e:Ko(e)}var kr=se("[Dead Clicks]"),kp=()=>!0,Ip=t=>{var e,s=!((e=t.instance.persistence)==null||!e.get_property(Wo)),r=t.instance.config.capture_dead_clicks;return Ke(r)?r:!!te(r)||s};class fl{get lazyLoadedDeadClicksAutocapture(){return this.si}constructor(e,s,r){this.instance=e,this.isEnabled=s,this.onCapture=r,this.startIfEnabledOrStop()}onRemoteConfig(e){if(e.ok){var s=e.config;"captureDeadClicks"in s&&(this.instance.persistence&&this.instance.persistence.register({[Wo]:s.captureDeadClicks}),this.startIfEnabledOrStop())}}startIfEnabledOrStop(){this.isEnabled(this)?this.ai((()=>{this.oi()})):this.stop()}ai(e){var s,r;(s=$.__PosthogExtensions__)!=null&&s.initDeadClicksAutocapture?e():(r=$.__PosthogExtensions__)==null||r.loadExternalDependency==null||r.loadExternalDependency(this.instance,"dead-clicks-autocapture",(n=>{n?kr.error("failed to load script",n):e()}))}oi(){var e;if(C){if(!this.si&&(e=$.__PosthogExtensions__)!=null&&e.initDeadClicksAutocapture){var s=te(this.instance.config.capture_dead_clicks)?w({},this.instance.config.capture_dead_clicks):{};s.__onCapture=this.onCapture,this.onCapture&&(s.capture_dead_swipes=!1),this.si=$.__PosthogExtensions__.initDeadClicksAutocapture(this.instance,s),this.si.start(C),kr.info("starting...")}}else kr.error("`document` not found. Cannot start.")}stop(){this.si&&(this.si.stop(),this.si=void 0,kr.info("stopping..."))}}var ci=se("[SegmentIntegration]"),$u="posthog-js";function Ru(t,e){var s=e===void 0?{}:e,r=s.organization,n=s.projectId,i=s.prefix,o=s.severityAllowList,a=o===void 0?["error"]:o,l=s.sendExceptionsToPostHog,u=l===void 0||l;return c=>{var d,h,p,f,g;if(a!=="*"&&!a.includes(c.level)||!t.__loaded)return c;c.tags||(c.tags={});var m=t.requestRouter.endpointFor("ui","/project/"+t.config.token+"/person/"+t.get_distinct_id());c.tags["PostHog Person URL"]=m,t.sessionRecordingStarted()&&(c.tags["PostHog Recording URL"]=t.get_session_replay_url({withTimestamp:!0}));var _,b=((d=c.exception)==null?void 0:d.values)||[],E=b.map((F=>w({},F,{stacktrace:F.stacktrace?w({},F.stacktrace,{type:"raw",frames:(F.stacktrace.frames||[]).map((P=>w({},P,{platform:"web:javascript"})))}):void 0}))),I={$exception_message:((h=b[0])==null?void 0:h.value)||c.message,$exception_type:(p=b[0])==null?void 0:p.type,$exception_level:c.level,$exception_list:E,$sentry_event_id:c.event_id,$sentry_exception:c.exception,$sentry_exception_message:((f=b[0])==null?void 0:f.value)||c.message,$sentry_exception_type:(g=b[0])==null?void 0:g.type,$sentry_tags:c.tags};return r&&n&&(I.$sentry_url=(i||"https://sentry.io/organizations/")+r+"/issues/?project="+n+"&query="+c.event_id),u&&((_=t.exceptions)==null||_.sendExceptionEvent(I)),c}}class Cp{constructor(e,s,r,n,i,o){this.name=$u,this.setupOnce=function(a){a(Ru(e,{organization:s,projectId:r,prefix:n,severityAllowList:i,sendExceptionsToPostHog:o==null||o}))}}}class gl{constructor(e){this.li=(s,r,n)=>{n&&(n.noSessionId||n.activityTimeout||n.sessionPastMaximumLength||n.crossTabAdoption)&&(k.info("[PageViewManager] Session rotated, clearing pageview state",{sessionId:s,changeReason:n}),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,s){var r,n=this.vi(e,s);return this.ui={pathname:(r=v?.location.pathname)!==null&&r!==void 0?r:"",pageViewId:s,timestamp:e},this._instance.scrollManager.resetContext(),n}doPageLeave(e){var s;return this.vi(e,(s=this.ui)==null?void 0:s.pageViewId)}doEvent(){var e;return{$pageview_id:(e=this.ui)==null?void 0:e.pageViewId}}vi(e,s){var r=this.ui;if(!r)return{$pageview_id:s};var n={$pageview_id:s,$prev_pageview_id:r.pageViewId},i=this._instance.scrollManager.getContext();if(i&&!this._instance.config.disable_scroll_properties){var o=i.maxScrollHeight,a=i.lastScrollY,l=i.maxScrollY,u=i.maxContentHeight,c=i.lastContentY,d=i.maxContentY;if(!(x(o)||x(a)||x(l)||x(u)||x(c)||x(d))){o=Math.ceil(o),a=Math.ceil(a),l=Math.ceil(l),u=Math.ceil(u),c=Math.ceil(c),d=Math.ceil(d);var h=o>1?rt(a/o,0,1,k):1,p=o>1?rt(l/o,0,1,k):1,f=u>1?rt(c/u,0,1,k):1,g=u>1?rt(d/u,0,1,k):1;n=ee(n,{$prev_pageview_last_scroll:a,$prev_pageview_last_scroll_percentage:h,$prev_pageview_max_scroll:l,$prev_pageview_max_scroll_percentage:p,$prev_pageview_last_content:c,$prev_pageview_last_content_percentage:f,$prev_pageview_max_content:d,$prev_pageview_max_content_percentage:g})}}return r.pathname&&(n.$prev_pageview_pathname=r.pathname),r.timestamp&&(n.$prev_pageview_duration=(e.getTime()-r.timestamp.getTime())/1e3),n}}var ui=["flags","surveys"],Fp={[lu]:{exposure:"hidden"},[js]:{exposure:"hidden"},__cmpns:{exposure:"hidden"},[Us]:{exposure:"hidden"},[Hi]:{exposure:"event"},[Wi]:{exposure:"hidden"},[zi]:{exposure:"event"},[qi]:{exposure:"hidden"},[Vi]:{exposure:"event"},[Gi]:{exposure:"event"},[Wo]:{exposure:"event"},[zo]:{exposure:"hidden"},[Ki]:{exposure:"event"},[Vt]:{exposure:"hidden"},$session_recording_enabled_server_side:{exposure:"hidden"},[cs]:{exposure:"hidden"},[qo]:{exposure:"event"},[cu]:{exposure:"event",shouldSkipFromEventProperties:t=>$e(t)},$session_past_minimum_duration:{exposure:"event"},$session_recording_url_trigger_activated_session:{exposure:"event"},$session_recording_event_trigger_activated_session:{exposure:"event"},$debug_first_full_snapshot_timestamp:{exposure:"event"},$sess_rec_flush_size:{exposure:"hidden"},[Bt]:{exposure:"hidden",storageGroup:"flags"},[Hs]:{exposure:"hidden",storageGroup:"flags"},[Tr]:{exposure:"hidden"},[Ji]:{exposure:"hidden",storageGroup:"flags"},[Ws]:{exposure:"hidden",storageGroup:"flags"},[Nr]:{exposure:"hidden",storageGroup:"flags",volatile:!0},[tn]:{exposure:"hidden",storageGroup:"flags"},[et]:{exposure:"hidden"},[jt]:{exposure:"hidden"},[ct]:{exposure:"hidden"},[Ut]:{exposure:"hidden"},[Yi]:{exposure:"hidden",storageGroup:"surveys"},[sn]:{exposure:"hidden",storageGroup:"surveys",volatile:!0},[Zi]:{exposure:"event"},[Mr]:{exposure:"hidden"},[Lr]:{exposure:"hidden"},[zs]:{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"},[Wt]:{exposure:"hidden"},[qs]:{exposure:"hidden"},[Or]:{exposure:"hidden"},[Ks]:{exposure:"hidden",storageGroup:"flags",volatile:!0},[He]:{exposure:"hidden"},[Xi]:{exposure:"hidden"},[Qi]:{exposure:"hidden"},[eo]:{exposure:"hidden"},[to]:{exposure:"hidden"},[rn]:{exposure:"hidden"},[nn]:{exposure:"hidden"},[uu]:{exposure:"event"},[du]:{exposure:"event"},[hu]:{exposure:"event"},[pu]:{exposure:"event"},[gu]:{exposure:"event"},[mu]:{exposure:"event"},[vu]:{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"}},Pp=[["$posthog_sr_group_event_trigger_",{exposure:"hidden"}],["$posthog_sr_group_url_trigger_",{exposure:"hidden"}],["$posthog_sr_group_sampling_",{exposure:"hidden"}]],Mt=t=>{var e=Fp[t];if(e)return e;for(var s of Pp){var r=s[1];if(t.indexOf(s[0])===0)return r}},us=(t,e)=>{try{return JSON.stringify(t,((s,r)=>typeof r=="bigint"?r.toString():r),e)}catch{return Pc(t)}},un=t=>{var e=C?.createElement("a");return x(e)?null:(e.href=t,e)},vs=function(t,e){for(var s,r=((t.split("#")[0]||"").split(/\?(.*)/)[1]||"").replace(/^\?+/g,"").split("&"),n=0;r.length>n;n++){var i=r[n].split("=");if(i[0]===e){s=i;break}}if(!L(s)||2>s.length)return"";var o=s[1];try{o=decodeURIComponent(o)}catch{k.error("Skipping decoding for malformed query param: "+o)}return o.replace(/\+/g," ")},ir=function(t,e,s){if(!t||!e||!e.length)return t;for(var r=t.split("#"),n=r[1],i=(r[0]||"").split("?"),o=i[1],a=i[0],l=(o||"").split("&"),u=[],c=0;l.length>c;c++){var d=l[c].split("=");L(d)&&(e.includes(d[0])?u.push(d[0]+"="+s):u.push(l[c]))}var h=a;return o!=null&&(h+="?"+u.join("&")),n!=null&&(h+="#"+n),h},dn=function(t,e){var s=t.match(new RegExp(e+"=([^&]*)"));return s?s[1]:null},Tu=(t,e)=>t>=e&&Ic(),Nu=(t,e,s,r)=>{if(t===0){if(Ic()){var n=e+1;return n===s&&r(),n}return e}return 0},Ir="https?://(.*)",_s=["gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","irclid","_kx"],Ap=["utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid",..._s],or="",$p=["li_fat_id"];function Mu(t,e,s){if(!C)return{};var r,n=e?[..._s,...s||[]]:[],i=Lu(ir(C.URL,n,or),t),o=(r={},Z($p,(function(a){var l=_u(a);r[a]=l||null})),r);return ee(o,i)}function Lu(t,e){var s=Ap.concat(e||[]),r={};return Z(s,(function(n){var i=vs(t,n);r[n]=i||null})),r}function Ou(t){var e=(function(i){return i?i.search(Ir+"google.([^/?]*)")===0?"google":i.search(Ir+"bing.com")===0?"bing":i.search(Ir+"yahoo.com")===0?"yahoo":i.search(Ir+"duckduckgo.com")===0?"duckduckgo":null:null})(t),s=e!="yahoo"?"q":"p",r={};if(!$e(e)){r.$search_engine=e;var n=C?vs(C.referrer,s):"";n.length&&(r.ph_keyword=n)}return r}function ml(){return navigator.language||navigator.userLanguage}var hn="$direct";function Du(){return C?.referrer||hn}function Bu(t,e,s){s===void 0&&(s=!1);var r=t?[..._s,...e||[]]:[],n=s?Ct(re?.href):re?.href,i=n?.substring(0,1e3);return{r:Du().substring(0,1e3),u:i?ir(i,r,or):void 0}}function ju(t,e){var s;e===void 0&&(e=!1);var r=t.r,n=t.u,i=e?Ct(n):n,o={$referrer:r,$referring_domain:r==null?void 0:r==hn?hn:(s=un(r))==null?void 0:s.host};if(i){o.$current_url=i;var a=un(i);o.$host=a?.host,o.$pathname=a?.pathname;var l=Lu(i);ee(o,l)}if(r){var u=Ou(r);ee(o,u)}return o}function Uu(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return}}function Rp(){try{return new Date().getTimezoneOffset()}catch{return}}var Tp={flags:Ks,surveys:sn},Np=["cookie","localstorage","localstorage+cookie","sessionstorage","memory"],ss="main";class di{constructor(e,s,r){if(r===void 0&&(r=!0),this.ci={},this.fi=!1,this.pi=!1,this.Ne=e,this.gi=r,this.props={},this.mi=void 0,this.yi=(i=>{var o="";return i.token&&(o=i.token.replace(/\+/g,"PL").replace(/\//g,"SL").replace(/=/g,"EQ")),i.persistence_name?"ph_"+i.persistence_name:"ph_"+o+"_posthog"})(e),this.ii=this.bi(e),this.pi=this.wi(e),this.load(),e.debug&&k.info("Persistence loaded",e.persistence,w({},this.props)),this.update_config(e,e,s),this.save(),v){var n=()=>this.flush();ne(v,"beforeunload",n,{capture:!1}),ne(v,"pagehide",n,{capture:!1})}}ki(){var e,s=(e=this.Ne)==null?void 0:e.persistence_save_debounce_ms;return he(s)&&s>0?s:0}isDisabled(){return!!this.xi}bi(e){Np.indexOf(e.persistence.toLowerCase())===-1&&(k.critical("Unknown persistence type "+e.persistence+"; falling back to localStorage+cookie"),e.persistence="localStorage+cookie");var s,r=(function(o,a){o===void 0&&(o=[]),a===void 0&&(a=!1);var l=[...hp,...o];return w({},Q,{H(u){try{var c={};try{c=pt.H(u)||{}}catch{}var d,h=JSON.parse(Q.P(u)||"{}");if(a){var p={};for(var f in c){var g=c[f];$e(g)||g===""||(p[f]=g)}d=ee(h,p)}else d=ee(c,h);return Q.F(u,d),d}catch{}return null},F(u,c,d,h,p,f){var g=Q.F(u,c,void 0,void 0,f);try{var m={};l.forEach((_=>{c[_]&&(m[_]=c[_])})),Object.keys(m).length&&pt.F(u,m,d,h,p,f)}catch(_){Q.j(_)}return g},q(u,c){try{v?.localStorage.removeItem(u),pt.q(u,c)}catch(d){Q.j(d)}}})})(e.cookie_persisted_properties||[],e.__preview_cookie_wins_on_conflict||!1),n=!1,i=e.persistence.toLowerCase();return i==="localstorage"&&Q.N()?(s=Q,n=!0):i==="localstorage+cookie"&&r.N()?(s=r,n=!0):i==="sessionstorage"&&ce.N()?s=ce:i==="memory"?s=pp:i==="cookie"?s=pt:r.N()?(s=r,n=!0):s=pt,this.fi=n,s}Si(e){return this.yi+"__"+e}wi(e){return this.fi&&!!e.split_storage}properties(){var e={};return Z(this.props,((s,r)=>{var n=Mt(r);if(!n||n.exposure==="event"){if(n!=null&&n.shouldSkipFromEventProperties!=null&&n.shouldSkipFromEventProperties(s))return;e[r]=s}})),e}load(){if(!this.xi){var e=this.ii.H(this.yi);e&&(this.props=ee({},e)),this.pi&&this.Ci()}}Ci(){for(var e of ui){var s=Q.H(this.Si(e));if(s&&!mt(s)){var r=this.Mi(e);r.persisted=!0,this.Ti(e)||(r.fingerprint=this.Ei(s,e)),this.Ii(e,s)||ee(this.props,s)}}}Ti(e){return Object.keys(this.props).some((s=>{var r;return((r=Mt(s))==null?void 0:r.storageGroup)===e}))}Ii(e,s){var r=Tp[e];if(!r)return!1;var n=s[r],i=this.props[r];return he(n)&&he(i)&&i>n}refreshKey(e){var s;if(!this.xi){var r=this.pi?(s=Mt(e))==null?void 0:s.storageGroup:void 0,n=r?Q.H(this.Si(r)):this.ii.H(this.yi);if(n&&e in n)this.Pi(e,n[e]);else{if(r){var i=this.ii.H(this.yi);if(i&&e in i)return void this.Pi(e,i[e])}this.Ri(e)}}}save(){if(!this.xi){var e=this.ki();e>0?x(this.Ai)&&(this.Ai=setTimeout((()=>{this.Ai=void 0,this.Fi()}),e)):this.Fi()}}flush(){x(this.Ai)||(clearTimeout(this.Ai),this.Ai=void 0,this.Fi())}Fi(){this.xi||(this.pi?this.Li():this.Oi(this.ii,this.yi,this.props,ss))}Li(){var e=this.Di(),s=e.main,r=e.groups;for(var n of(this.Oi(this.ii,this.yi,s,ss),ui)){var i,o=r[n];(!mt(o)||(i=this.ci[n])!=null&&i.persisted)&&this.Oi(Q,this.Si(n),o,n)}}Di(){var e={},s={flags:{},surveys:{}};return Z(this.props,((r,n)=>{var i,o=(i=Mt(n))==null?void 0:i.storageGroup;o?s[o][n]=r:e[n]=r})),{main:e,groups:s}}Ei(e,s){if(s===ss)return JSON.stringify(e)+"|"+this.$i+"|"+this.Ni+"|"+this.qi;var r={};return Z(e,((n,i)=>{var o;r[i]=(o=Mt(i))!=null&&o.volatile?"__volatile__":n})),JSON.stringify(r)}Oi(e,s,r,n){var i=this.Mi(n);if(n===ss||i.dirty||x(i.fingerprint)){var o;try{if((o=this.Ei(r,n))===i.fingerprint)return void(i.dirty=!1)}catch{o=void 0}e.F(s,r,this.$i,this.Ni,this.qi,this.Ne.debug)?(i.dirty=!1,n!==ss&&(i.persisted=!0),x(o)||(i.fingerprint=o)):this.Ne.debug&&k.warn('failed to persist storage entry "'+s+'"; will retry on next save')}}remove(e){var s=(e===void 0?{}:e).keepGroupEntries,r=s!==void 0&&s;if(x(this.Ai)||(clearTimeout(this.Ai),this.Ai=void 0),this.ii.q(this.yi,!1),this.ii.q(this.yi,!0),!r&&this.gi)for(var n of ui)Q.q(this.Si(n));r?delete this.ci[ss]:this.ci={}}clear(){this.remove(),this.props={}}register_once(e,s,r){if(te(e)){x(s)&&(s="None"),this.$i=x(r)?this.ji:r;var n=!1;if(Z(e,((i,o)=>{this.props.hasOwnProperty(o)&&this.props[o]!==s||(this.Pi(o,i),n=!0)})),n)return this.save(),!0}return!1}register(e,s){if(te(e)){this.$i=x(s)?this.ji:s;var r=!1;if(Z(e,((n,i)=>{e.hasOwnProperty(i)&&(this.props[i]!==n||te(n)||L(n))&&(this.Pi(i,n),r=!0)})),r)return this.save(),!0}return!1}unregister(e){var s=typeof e=="string"?[e]:e,r=!1;for(var n of s)n in this.props&&(this.Ri(n),r=!0);r&&this.save()}update_campaign_params(){var e=C?.URL;if(e!==this.mi){var s=Mu(this.Ne.custom_campaign_params,this.Ne.mask_personal_data_properties,this.Ne.custom_personal_data_properties);mt(Go(s))||this.register(s),this.mi=e}}update_search_keyword(){var e;this.register((e=C?.referrer)?Ou(e):{})}update_referrer_info(){var e;this.register_once({$referrer:Du(),$referring_domain:C!=null&&C.referrer&&((e=un(C.referrer))==null?void 0:e.host)||hn},void 0)}set_initial_person_info(){this.props[eo]||this.props[to]||this.register_once({[rn]:Bu(this.Ne.mask_personal_data_properties,this.Ne.custom_personal_data_properties,this.Ne.disable_capture_url_hashes)},void 0)}get_initial_props(){var e={};Z([to,eo],(n=>{var i=this.props[n];i&&Z(i,(function(o,a){e["$initial_"+Mi(a)]=o}))}));var s=this.props[rn];if(s){var r=(function(n,i){i===void 0&&(i=!1);var o=ju(n,i),a={};return Z(o,(function(l,u){a["$initial_"+Mi(u)]=l})),a})(s,this.Ne.disable_capture_url_hashes);ee(e,r)}return e}safe_merge(e){return Z(this.props,(function(s,r){r in e||(e[r]=s)})),e}update_config(e,s,r){this.ji=this.$i=e.cookie_expiration,this.set_disabled(e.disable_persistence||!!r),this.set_cross_subdomain(e.cross_subdomain_cookie),this.set_secure(e.secure_cookie);var n=e.persistence!==s.persistence||!((l,u)=>{if(l.length!==u.length)return!1;var c=[...l].sort(),d=[...u].sort();return c.every(((h,p)=>h===d[p]))})(e.cookie_persisted_properties||[],s.cookie_persisted_properties||[]),i=n?this.bi(e):this.ii,o=this.wi(e);if(n||o!==this.pi){var a=this.props;this.clear(),this.ii=i,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,s){var r=this.props[Us]||{};r[e]=s,this.Pi(Us,r),this.save()}remove_event_timer(e){var s=this.props[Us]||{},r=s[e];return x(r)||(delete s[e],this.Pi(Us,s),this.save()),r}get_property(e){return this.props[e]}set_property(e,s){this.Pi(e,s),this.save()}Pi(e,s){var r;this.props[e]=s,(r=Mt(e))!=null&&r.volatile||this.Bi(e)}Ri(e){delete this.props[e],this.Bi(e)}Bi(e){var s,r=(s=Mt(e))==null?void 0:s.storageGroup;r&&(this.Mi(r).dirty=!0)}Mi(e){return this.ci[e]||(this.ci[e]={})}}function Cr(t){var e=!0;return{dispose(){if(e){e=!1;var s=t();s&&Se(s.then)&&s.then(void 0,(()=>{}))}}}}var xe={GZipJS:"gzip-js",Base64:"base64"},$s={Activation:"events",Cancellation:"cancelEvents"},hi={Popover:"popover",API:"api",Widget:"widget"},ft={SHOWN:"survey shown",DISMISSED:"survey dismissed",SENT:"survey sent"},pi={SURVEY_ID:"$survey_id",SURVEY_ITERATION:"$survey_iteration",SURVEY_LAST_SEEN_DATE:"$survey_last_seen_date"},oo={Popover:"popover",Inline:"inline"},Mp={SHOWN:"product tour shown"},vl={TOUR_LAST_SEEN_DATE:"$product_tour_last_seen_date",TOUR_TYPE:"$product_tour_type"},_l=se("[RateLimiter]");class Lp{constructor(e){this.serverLimits={},this.lastEventRateLimited=!1,this.checkForLimiting=s=>{var r=s.text;if(r&&r.length)try{(JSON.parse(r).quota_limited||[]).forEach((n=>{_l.info((n||"events")+" is quota limited."),this.serverLimits[n]=new Date().getTime()+6e4}))}catch(n){return void _l.warn('could not rate limit - continuing. Error: "'+n?.message+'"',{text:r})}},this.instance=e,this.lastEventRateLimited=this.clientRateLimitContext(!0).isRateLimited}get captureEventsPerSecond(){var e;return((e=this.instance.config.rate_limiting)==null?void 0:e.events_per_second)||10}get captureEventsBurstLimit(){var e;return Math.max(((e=this.instance.config.rate_limiting)==null?void 0:e.events_burst_limit)||10*this.captureEventsPerSecond,this.captureEventsPerSecond)}clientRateLimitContext(e){var s,r,n;e===void 0&&(e=!1);var i=this.captureEventsBurstLimit,o=this.captureEventsPerSecond,a=new Date().getTime(),l=(s=(r=this.instance.persistence)==null?void 0:r.get_property(Qi))!==null&&s!==void 0?s:{tokens:i,last:a};l.tokens+=(a-l.last)/1e3*o,l.last=a,l.tokens>i&&(l.tokens=i);var u=1>l.tokens;if(u||e||(l.tokens=Math.max(0,l.tokens-1)),u&&!e){var c=(he(l.dropped)?l.dropped:0)+1;l.dropped=c,!this.lastEventRateLimited&&this.Hi(c)&&(l.dropped=0)}return this.lastEventRateLimited=u,(n=this.instance.persistence)==null||n.set_property(Qi,l),{isRateLimited:u,remainingTokens:l.tokens}}Ui(e){var s=this.instance.config.property_denylist;return!L(s)||!s.includes(e)}zi(){var e;if(this.Ui("$current_url")&&this.Ui("$pathname")&&re!=null&&re.pathname)return""+((e=re.origin)!==null&&e!==void 0?e:"")+re.pathname}Hi(e){var s,r,n=this.captureEventsBurstLimit,i=this.captureEventsPerSecond,o=this.zi(),a=this.Ui("$session_id")?(s=(r=this.instance).get_session_id)==null?void 0:s.call(r):void 0,l=[e+" event(s) dropped since the last warning",o?"triggered on "+o:void 0,a?"session "+a:void 0].filter(Boolean).join(", ");return!!this.instance.capture("$$client_ingestion_warning",{$$client_ingestion_warning_message:"posthog-js client rate limited: "+l+". Config is set to "+i+" events per second and "+n+" events burst limit."},{skip_client_rate_limiting:!0})}isServerRateLimited(e){var s=this.serverLimits[e||"events"]||!1;return s!==!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 xt.info("Using preloaded remote config",this.remoteConfig),this.Zi(this.remoteConfig),void this.Gi();if(this._instance.Qi())return void xt.warn("Remote config is disabled. Falling back to local config.");this.Wi((e=>{if(!e)return xt.info("No config found after loading remote JS config. Falling back to JSON."),void this.Vi((s=>{this.Zi(s.json,s),this.Gi()}));this.Zi(e),this.Gi()}))}catch(e){xt.error("Error loading remote config",e),this.Zi()}}stop(){this.Ki&&(clearInterval(this.Ki),this.Ki=void 0)}refresh(){!this._instance.Qi()&&C&&C.visibilityState!=="hidden"&&this._instance.reloadFeatureFlags()}Gi(){var e;if(!this.Ki){var s=(e=this._instance.config.remote_config_refresh_interval_ms)!==null&&e!==void 0?e:3e5;s!==0&&(this.Ki=setInterval((()=>{this.refresh()}),s))}}Zi(e,s){!e&&s&&(s.statusCode===0?s.error||xt.warn("Failed to fetch remote config from PostHog."):xt.error("Failed to fetch remote config from PostHog."));try{this._instance.Zi(e?{ok:!0,config:e}:{ok:!1})}catch(n){xt.error("Error applying remote config",n)}if(e?.hasFeatureFlags!==!1&&!this._instance.config.advanced_disable_feature_flags_on_first_load)try{var r;(r=this._instance.featureFlags)==null||r.ensureFlagsLoaded()}catch(n){xt.error("Error loading feature flags",n)}}}var qe=Uint8Array,Ae=Uint16Array,ys=Uint32Array,Zo=new qe([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),Xo=new qe([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),yl=new qe([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Wu=function(t,e){for(var s=new Ae(31),r=0;31>r;++r)s[r]=e+=1<r;++r)for(var i=s[r];s[r+1]>i;++i)n[i]=i-s[r]<<5|r;return[s,n]},zu=Wu(Zo,2),ao=zu[1];zu[0][28]=258,ao[258]=28;for(var wl=Wu(Xo,0)[1],qu=new Ae(32768),ie=0;32768>ie;++ie){var rs=(43690&ie)>>>1|(21845&ie)<<1;qu[ie]=((65280&(rs=(61680&(rs=(52428&rs)>>>2|(13107&rs)<<2))>>>4|(3855&rs)<<4))>>>8|(255&rs)<<8)>>>1}var Ys=function(t,e,s){for(var r=t.length,n=0,i=new Ae(e);r>n;++n)++i[t[n]-1];var o,a=new Ae(e);for(n=0;e>n;++n)a[n]=a[n-1]+i[n-1]<<1;for(o=new Ae(r),n=0;r>n;++n)o[n]=qu[a[t[n]-1]++]>>>15-t[n];return o},Jt=new qe(288);for(ie=0;144>ie;++ie)Jt[ie]=8;for(ie=144;256>ie;++ie)Jt[ie]=9;for(ie=256;280>ie;++ie)Jt[ie]=7;for(ie=280;288>ie;++ie)Jt[ie]=8;var pn=new qe(32);for(ie=0;32>ie;++ie)pn[ie]=5;var Op=Ys(Jt,9),Dp=Ys(pn,5),Vu=function(t){return(t/8>>0)+(7&t&&1)},Gu=function(t,e,s){(s==null||s>t.length)&&(s=t.length);var r=new(t instanceof Ae?Ae:t instanceof ys?ys:qe)(s-e);return r.set(t.subarray(e,s)),r},ot=function(t,e,s){var r=e/8>>0;t[r]|=s<<=7&e,t[r+1]|=s>>>8},Rs=function(t,e,s){var r=e/8>>0;t[r]|=s<<=7&e,t[r+1]|=s>>>8,t[r+2]|=s>>>16},fi=function(t,e){for(var s=[],r=0;t.length>r;++r)t[r]&&s.push({s:r,f:t[r]});var n=s.length,i=s.slice();if(!n)return[new qe(0),0];if(n==1){var o=new qe(s[0].s+1);return o[s[0].s]=1,[o,1]}s.sort((function(F,P){return F.f-P.f})),s.push({s:-1,f:25001});var a=s[0],l=s[1],u=0,c=1,d=2;for(s[0]={s:-1,f:a.f+l.f,l:a,r:l};c!=n-1;)a=s[s[d].f>s[u].f?u++:d++],l=s[u!=c&&s[d].f>s[u].f?u++:d++],s[c++]={s:-1,f:a.f+l.f,l:a,r:l};var h=i[0].s;for(r=1;n>r;++r)i[r].s>h&&(h=i[r].s);var p=new Ae(h+1),f=lo(s[c-1],p,0);if(f>e){r=0;var g=0,m=f-e,_=1<r;++r){var b=i[r].s;if(e>=p[b])break;g+=_-(1<>>=m;g>0;){var E=i[r].s;e>p[E]?g-=1<=0&&g;--r){var I=i[r].s;p[I]==e&&(--p[I],++g)}f=e}return[new qe(p),f]},lo=function(t,e,s){return t.s==-1?Math.max(lo(t.l,e,s+1),lo(t.r,e,s+1)):e[t.s]=s},bl=function(t){for(var e=t.length;e&&!t[--e];);for(var s=new Ae(++e),r=0,n=t[0],i=1,o=function(l){s[r++]=l},a=1;e>=a;++a)if(t[a]==n&&a!=e)++i;else{if(!n&&i>2){for(;i>138;i-=138)o(32754);i>2&&(o(i>10?i-11<<5|28690:i-3<<5|12305),i=0)}else if(i>3){for(o(n),--i;i>6;i-=6)o(8304);i>2&&(o(i-3<<5|8208),i=0)}for(;i--;)o(n);i=1,n=t[a]}return[s.subarray(0,r),e]},Ts=function(t,e){for(var s=0,r=0;e.length>r;++r)s+=t[r]*e[r];return s},co=function(t,e,s){var r=s.length,n=Vu(e+2);t[n]=255&r,t[n+1]=r>>>8,t[n+2]=255^t[n],t[n+3]=255^t[n+1];for(var i=0;r>i;++i)t[n+i+4]=s[i];return 8*(n+4+r)},El=function(t,e,s,r,n,i,o,a,l,u,c){ot(e,c++,s),++n[256];for(var d=fi(n,15),h=d[0],p=d[1],f=fi(i,15),g=f[0],m=f[1],_=bl(h),b=_[0],E=_[1],I=bl(g),F=I[0],P=I[1],B=new Ae(19),S=0;b.length>S;++S)B[31&b[S]]++;for(S=0;F.length>S;++S)B[31&F[S]]++;for(var A=fi(B,7),R=A[0],N=A[1],T=19;T>4&&!R[yl[T-1]];--T);var O,J,z,H,oe=u+5<<3,pe=Ts(n,Jt)+Ts(i,pn)+o,Ie=Ts(n,h)+Ts(i,g)+o+14+3*T+Ts(B,R)+(2*B[16]+3*B[17]+7*B[18]);if(pe>=oe&&Ie>=oe)return co(e,c,t.subarray(l,l+u));if(ot(e,c,1+(pe>Ie)),c+=2,pe>Ie){O=Ys(h,p),J=h,z=Ys(g,m),H=g;var _e=Ys(R,N);for(ot(e,c,E-257),ot(e,c+5,P-1),ot(e,c+10,T-4),c+=14,S=0;T>S;++S)ot(e,c+3*S,R[yl[S]]);c+=3*T;for(var Ce=[b,F],Re=0;2>Re;++Re){var ae=Ce[Re];for(S=0;ae.length>S;++S)ot(e,c,_e[me=31&ae[S]]),c+=R[me],me>15&&(ot(e,c,ae[S]>>>5&127),c+=ae[S]>>>12)}}else O=Op,J=Jt,z=Dp,H=pn;for(S=0;a>S;++S)if(r[S]>255){var me;Rs(e,c,O[257+(me=r[S]>>>18&31)]),c+=J[me+257],me>7&&(ot(e,c,r[S]>>>23&31),c+=Zo[me]);var ge=31&r[S];Rs(e,c,z[ge]),c+=H[ge],ge>3&&(Rs(e,c,r[S]>>>5&8191),c+=Xo[ge])}else Rs(e,c,O[r[S]]),c+=J[r[S]];return Rs(e,c,O[256]),c+J[256]},Bp=new ys([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),jp=(function(){for(var t=new ys(256),e=0;256>e;++e){for(var s=e,r=9;--r;)s=(1&s&&3988292384)^s>>>1;t[e]=s}return t})(),gi=function(t,e,s){for(;s;++e)t[e]=s,s>>>=8};function Up(t,e){e===void 0&&(e={});var s=(function(){var d=4294967295;return{p(h){for(var p=d,f=0;h.length>f;++f)p=jp[255&p^h[f]]^p>>>8;d=p},d(){return 4294967295^d}}})(),r=t.length;s.p(t);var n,i,o,a,l,u=(a=10+((n=e).filename&&n.filename.length+1||0),l=8,(function(d,h,p,f,g,m){var _=d.length,b=new qe(f+_+5*(1+Math.floor(_/7e3))+g),E=b.subarray(f,b.length-g),I=0;if(!h||8>_)for(var F=0;_>=F;F+=65535){var P=F+65535;_>P?I=co(E,I,d.subarray(F,P)):(E[F]=!0,I=co(E,I,d.subarray(F,_)))}else{for(var B=Bp[h-1],S=B>>>13,A=8191&B,R=(1<F;++F){var me=z(F),ge=32767&F,Ye=T[me];if(N[ge]=Ye,T[me]=ge,F>=Re){var Rt=_-F;if((Ie>7e3||Ce>24576)&&Rt>423){I=El(d,E,0,H,oe,pe,_e,Ce,ae,F-ae,I),Ce=Ie=_e=0,ae=F;for(var de=0;286>de;++de)oe[de]=0;for(de=0;30>de;++de)pe[de]=0}var Ve=2,St=0,Is=A,Be=ge-Ye&32767;if(Rt>2&&me==z(F-Be))for(var Fe=Math.min(S,Rt)-1,vr=Math.min(32767,F),_r=Math.min(258,Rt);vr>=Be&&--Is&&ge!=Ye;){if(d[F+Ve]==d[F+Ve-Be]){for(var je=0;_r>je&&d[F+je]==d[F+je-Be];++je);if(je>Ve){if(Ve=je,St=Be,je>Fe)break;var yr=Math.min(Be,je-2),Qt=0;for(de=0;yr>de;++de){var es=F-Be+de+32768&32767,Cs=es-N[es]+32768&32767;Cs>Qt&&(Qt=Cs,Ye=es)}}}Be+=(ge=Ye)-(Ye=N[ge])+32768&32767}if(St){H[Ce++]=268435456|ao[Ve]<<18|wl[St];var Na=31&ao[Ve],Ma=31&wl[St];_e+=Zo[Na]+Xo[Ma],++oe[257+Na],++pe[Ma],Re=F+Ve,++Ie}else H[Ce++]=d[F],++oe[d[F]]}}I=El(d,E,!0,H,oe,pe,_e,Ce,ae,F-ae,I)}return Gu(b,0,f+Vu(I)+g)})(i=t,(o=e).level==null?6:o.level,o.mem==null?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(i.length)))):12+o.mem,a,l)),c=u.length;return(function(d,h){var p=h.filename;if(d[0]=31,d[1]=139,d[2]=8,d[8]=2>h.level?4:h.level==9?2:0,d[9]=3,h.mtime!=0&&gi(d,4,Math.floor(new Date(h.mtime||Date.now())/1e3)),p){d[3]=8;for(var f=0;p.length>=f;++f)d[f+10]=p.charCodeAt(f)}})(u,e),gi(u,c-8,s.d()),gi(u,c-4,r),u}var Hp=!!Ri||!!Lo,Ku="text/plain",Br=!1,Ju=(t,e)=>{var s=t.split("#"),r=s[1],n=s[0].split("?"),i=n[0],o=n[1];if(!o)return t;var a=o.split("&").filter((l=>l.split("=")[0]!==e)).join("&");return i+(a?"?"+a:"")+(r?"#"+r:"")},Rn=function(t,e,s){var r;s===void 0&&(s=!0);var n=t.split("?"),i=n[0],o=n[1],a=w({},e),l=(r=o?.split("&").map((c=>{var d,h=c.split("="),p=h[0],f=s&&(d=a[p])!==null&&d!==void 0?d:h[1];return delete a[p],p+"="+f})))!==null&&r!==void 0?r:[],u=(function(c,d){var h,p;d===void 0&&(d="&");var f=[];return Z(c,(function(g,m){x(g)||x(m)||m==="undefined"||(h=encodeURIComponent((_=>_ instanceof File)(g)?g.name:g.toString()),p=encodeURIComponent(m),f[f.length]=p+"="+h)})),f.join(d)})(a);return u&&l.push(u),l.length>0?i+"?"+l.join("&"):i},mi=t=>{if(t.Ji)return t.Ji;var e=t.data,s=t.compression;if(e){if(s===xe.GZipJS){var r=Up((function(a,l){var u=a.length;if(typeof TextEncoder<"u")return new TextEncoder().encode(a);for(var c=new qe(a.length+(a.length>>>1)),d=0,h=function(m){c[d++]=m},p=0;u>p;++p){if(d+5>c.length){var f=new qe(d+8+(u-p<<1));f.set(c),c=f}var g=a.charCodeAt(p);128>g?h(g):2048>g?(h(192|g>>>6),h(128|63&g)):g>55295&&57344>g?(h(240|(g=65536+(1047552&g)|1023&a.charCodeAt(++p))>>>18),h(128|g>>>12&63),h(128|g>>>6&63),h(128|63&g)):(h(224|g>>>12),h(128|g>>>6&63),h(128|63&g))}return Gu(c,0,d)})(us(e)),{mtime:0});return{contentType:Ku,body:r.buffer.slice(r.byteOffset,r.byteOffset+r.byteLength),estimatedSize:r.byteLength}}if(s===xe.Base64){var n=(function(a){return a&&btoa(encodeURIComponent(a).replace(/%([0-9A-F]{2})/g,((l,u)=>String.fromCharCode(parseInt(u,16)))))})(us(e)),i=(a=>"data="+encodeURIComponent(typeof a=="string"?a:us(a)))(n);return{contentType:"application/x-www-form-urlencoded",body:i,estimatedSize:new Blob([i]).size}}var o=us(e);return{contentType:"application/json",body:o,estimatedSize:new Blob([o]).size}}},Yu=t=>{var e,s,r=()=>t.transport==="sendBeacon"?{url:Rn(t.url,{compression:xe.Base64}),encodedBody:mi(w({},t,{compression:xe.Base64,Ji:void 0}))}:{url:Ju(t.url,"compression"),encodedBody:mi(w({},t,{compression:void 0,Ji:void 0}))};try{e=mi(t)}catch(n){if(Ha(t.compression,vs(t.url,"compression")))return k.error("Failed to gzip request body, sending uncompressed payload",n),r();throw n}return e&&Ha(t.compression,vs(t.url,"compression"))&&!((s=e.body)instanceof ArrayBuffer?Ti(new Uint8Array(s)):ArrayBuffer.isView(s)&&Ti(new Uint8Array(s.buffer,s.byteOffset,s.byteLength)))?(Br=!0,r()):{url:t.url,encodedBody:e}},Zu=t=>{try{return Yu(t)}catch(e){return k.error(e),void(t.callback==null||t.callback({statusCode:0,error:e}))}},Wp=(function(){var t=X((function*(e){var s=us(e.data),r=yield(function(i,o,a){return Ni.apply(this,arguments)})(s,Y.DEBUG,{rethrow:!0});if(!r)return e;var n=yield r.arrayBuffer();return w({},e,{Ji:{contentType:Ku,body:n,estimatedSize:n.byteLength}})}));return function(e){return t.apply(this,arguments)}})(),zp=/Failed to fetch|NetworkError|Load failed/i,Xu=t=>t?.name==="TypeError"&&zp.test(t?.message||""),Qu=t=>{var e=Zu(t);if(e){var s=e.url,r=e.encodedBody,n=r??{},i=n.contentType,o=n.body,a=n.estimatedSize,l=new Headers;Z(t.headers,(function(f,g){l.append(g,f)})),i&&l.append("Content-Type",i);var u=null,c=!1;if(La){var d=new La;u={signal:d.signal,timeout:setTimeout((()=>{var f,g;c=!0,d.abort((f=t.timeout,(g=new Error("PostHog request timed out"+(f?" after "+f+"ms":""))).name="AbortError",g))}),t.timeout)}}var h=f=>{c&&f?.name==="AbortError"||Xu(f)?k.warn(f):k.error(f),t.callback==null||t.callback({statusCode:0,error:f})};try{var p;Lo(s,w({method:t?.method||"GET",headers:l,keepalive:t.method==="POST"&&!t.Yi&&52428.8>(a||0),body:o,signal:(p=u)==null?void 0:p.signal},t.fetchOptions)).then((f=>f.text().then((g=>{var m={statusCode:f.status,text:g};if(f.status===200)try{m.json=JSON.parse(g)}catch(_){k.error(_)}t.callback==null||t.callback(m)})))).catch(h).finally((()=>u?clearTimeout(u.timeout):null))}catch(f){u&&clearTimeout(u.timeout),h(f)}}},uo=t=>{try{var e,s=Yu(t),r=s.url,n=s.encodedBody,i=n??{},o=i.body,a=i.estimatedSize;if(!o)return;var l=o instanceof Blob?o:new Blob([o],{type:i.contentType});if(ke.sendBeacon(r,l))return;var u=L(t.data)?t.data:(e=t.data)==null?void 0:e.batch;if(L(u)&&u.length>1&&(a??0)>16384){var c=Math.ceil(u.length/2),d=h=>L(t.data)?h:w({},t.data,{batch:h});return uo(w({},t,{data:d(u.slice(0,c))})),void uo(w({},t,{data:d(u.slice(c))}))}k.warn("Beacon of ~"+(a??0)+" bytes was rejected by the browser, falling back to fetch"),Qu(w({},t,{Yi:!0}))}catch(h){k.warn("Beacon send failed",h)}},Sl=(t,e,s,r)=>{var n=r==="query"?e==="POST"?"sent_at":"_":void 0;return Rn(s===xe.GZipJS?Ju(t,"compression"):t,w({},n?{[n]:Date.now().toString()}:{},s===xe.GZipJS?{}:{compression:s}))},jr=[];Lo&&jr.push({transport:"fetch",method:Qu}),Ri&&jr.push({transport:"XHR",method(t){var e=Zu(t);if(e){var s=new Ri,r=e.encodedBody;s.open(t.method||"GET",e.url,!0);var n=r??{},i=n.contentType,o=n.body;Z(t.headers,(function(a,l){s.setRequestHeader(l,a)})),i&&s.setRequestHeader("Content-Type",i),t.timeout&&(s.timeout=t.timeout),s.onreadystatechange=()=>{if(s.readyState===4){var a={statusCode:s.status,text:s.responseText};if(s.status===200)try{a.json=JSON.parse(s.responseText)}catch{}t.callback==null||t.callback(a)}},s.send(o)}}}),ke!=null&&ke.sendBeacon&&jr.push({transport:"sendBeacon",method:uo});var ho=3e3;class qp{constructor(e,s){this.Xi=!0,this.tr=[],this.er=rt(s?.flush_interval_ms||ho,250,5e3,k.createLogger("flush interval"),ho),this.ir=e}enqueue(e){this.tr.push(e),this.rr||this.nr()}unload(){this.sr();var e=this.tr.length>0?this.ar():{},s=Object.values(e);[...s.filter((r=>r.url.indexOf("/e")===0)),...s.filter((r=>r.url.indexOf("/e")!==0))].map((r=>{this.lr(w({},r,{transport:"sendBeacon"}))}))}enable(){this.Xi=!1,this.nr()}nr(){var e=this;this.Xi||(this.rr=setTimeout((()=>{if(this.sr(),this.tr.length>0){var s=this.ar(),r=function(){var i=s[n],o=new Date().getTime();i.data&&L(i.data)&&Z(i.data,(a=>{a.offset=Math.abs(a.timestamp-o),delete a.timestamp})),e.lr(i)};for(var n in s)r()}}),this.er))}lr(e){try{this.ir(e)}catch(s){k.error(s)}}sr(){clearTimeout(this.rr),this.rr=void 0}ar(){var e={};return Z(this.tr,(s=>{var r,n=s,i=(n?n.batchKey:null)||n.url;x(e[i])&&(e[i]=w({},n,{data:[]})),(r=e[i].data)==null||r.push(n.data)})),this.tr=[],e}}var Vp=["retriesPerformedSoFar"];class Gp{constructor(e){this.ur=!1,this.hr=3e3,this.tr=[],this._instance=e,this.tr=[],this.dr=!0,!x(v)&&"onLine"in v.navigator&&(this.dr=v.navigator.onLine,this.vr=()=>{this.dr=!0,this.cr()},this.pr=()=>{this.dr=!1},ne(v,"online",this.vr),ne(v,"offline",this.pr))}get length(){return this.tr.length}retriableRequest(e){var s=e.retriesPerformedSoFar,r=Cc(e,Vp);lt(s)&&(r.url=Rn(r.url,{retry_count:s})),this._instance._send_request(w({},r,{callback:n=>{if(n.statusCode!==200&&(400>n.statusCode||n.statusCode>=500)){if((n.statusCode===0?3:10)>(s??0))return void this.At(w({retriesPerformedSoFar:s},r));n.statusCode===0&&k.warn("Request failed before receiving an HTTP response; this can happen due to network issues, CORS, browser blocking, or ad blockers. Stopped retrying after "+(s??0)+" retries.")}r.callback==null||r.callback(n)}}))}At(e){var s=e.retriesPerformedSoFar||0;e.retriesPerformedSoFar=s+1;var r=(function(o){var a=3e3*Math.pow(2,o),l=a/2,u=Math.min(18e5,a),c=Math.random()-.5;return Math.ceil(u+c*(u-l))})(s),n=Date.now()+r;this.tr.push({retryAt:n,requestOptions:e});var i="Enqueued failed request for retry in "+r;navigator.onLine||(i+=" (Browser is offline)"),k.warn(i),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(),s=[],r=this.tr.filter((i=>e>i.retryAt||(s.push(i),!1)));if(this.tr=s,r.length>0)for(var n of r)this.retriableRequest(n.requestOptions)}unload(){for(var e of(this.mr&&(clearTimeout(this.mr),this.mr=void 0),this.ur=!1,x(v)||(this.vr&&(v.removeEventListener("online",this.vr),this.vr=void 0),this.pr&&(v.removeEventListener("offline",this.pr),this.pr=void 0)),this.tr)){var s=e.requestOptions;try{this._instance._send_request(w({},s,{transport:"sendBeacon"}))}catch(r){k.error(r)}}this.tr=[]}}class Kp{constructor(e){this.yr=()=>{var s,r,n,i;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,(s=this.br.maxScrollY)!==null&&s!==void 0?s:0),this.br.maxScrollHeight=Math.max(l,(r=this.br.maxScrollHeight)!==null&&r!==void 0?r:0),this.br.lastContentY=u,this.br.maxContentY=Math.max(u,(n=this.br.maxContentY)!==null&&n!==void 0?n:0),this.br.maxContentHeight=Math.max(c,(i=this.br.maxContentHeight)!==null&&i!==void 0?i: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(){ne(v,"scroll",this.yr,{capture:!0}),ne(v,"scrollend",this.yr,{capture:!0}),ne(v,"resize",this.yr)}scrollElement(){if(!this._r)return v?.document.documentElement;var e=L(this._r)?this._r:[this._r];for(var s of e){var r=v?.document.querySelector(s);if(r)return r}}wr(e){var s=e==="y"?"scrollTop":"scrollLeft";if(this._r){var r=this.scrollElement();return r&&r[s]||0}return v?e==="y"?v.scrollY||v.pageYOffset||v.document.documentElement.scrollTop||0:v.scrollX||v.pageXOffset||v.document.documentElement.scrollLeft||0:0}scrollY(){return this.wr("y")}scrollX(){return this.wr("x")}}var Jp=t=>Bu(t?.config.mask_personal_data_properties,t?.config.custom_personal_data_properties,t?.config.disable_capture_url_hashes);class xl{constructor(e,s,r,n){this.kr=i=>{var o=this.Sr();if(!o||o.sessionId!==i){var a={sessionId:i,props:this.Cr(this._instance)};this.Mr.register({[Xi]:a})}},this._instance=e,this.Tr=s,this.Mr=r,this.Cr=n||Jp,this.Tr.onSessionId(this.kr)}Sr(){return this.Mr.props[Xi]}getSetOnceProps(){var e,s=(e=this.Sr())==null?void 0:e.props;return s?"r"in s?ju(s,this._instance.config.disable_capture_url_hashes):{$referring_domain:s.referringDomain,$pathname:s.initialPathName,utm_source:s.utm_source,utm_campaign:s.utm_campaign,utm_medium:s.utm_medium,utm_content:s.utm_content,utm_term:s.utm_term}:{}}getSessionProps(){var e={};return Z(Go(this.getSetOnceProps()),((s,r)=>{r==="$current_url"&&(r="url"),e["$session_entry_"+Mi(r)]=s})),e}}class Qo{on(e,s){return this.Er[e]||(this.Er[e]=[]),this.Er[e].push(s),()=>{this.Er[e]=this.Er[e].filter((r=>r!==s))}}emit(e,s){for(var r of this.Er[e]||[])r(s);for(var n of this.Er["*"]||[])n(e,s)}constructor(){this.Er={}}}var Ns=se("[SessionId]");class kl{on(e,s){return this.Ir.on(e,s)}constructor(e,s,r){var n;if(this.Pr=null,this.Rr=[],this.Ar=void 0,this.Fr=!1,this.Ir=new Qo,this.Lr=(u,c)=>!(!lt(u)||!lt(c))&&Math.abs(u-c)>this.sessionTimeoutMs,!e.persistence)throw new Error("SessionIdManager requires a PostHogPersistence instance");if(e.config.cookieless_mode===ht)throw new Error('SessionIdManager cannot be used with cookieless_mode="always"');this.Ne=e.config,this.Mr=e.persistence,this.Or=void 0,this.Dr=void 0,this._sessionStartTimestamp=null,this._sessionActivityTimestamp=null,this.$r=s||dt,this.Nr=r||dt;var i=this.Ne.persistence_name||this.Ne.token;if(this._sessionTimeoutMs=1e3*rt(this.Ne.session_idle_timeout_seconds||1800,60,36e3,Ns.createLogger("session_idle_timeout_seconds"),1800),e.register({$configured_session_timeout_ms:this._sessionTimeoutMs}),this.qr(),this.jr="ph_"+i+"_window_id",this.Br="ph_"+i+"_primary_window_exists",this.Hr()){var o=ce.H(this.jr),a=ce.H(this.Br);o&&!a?this.Or=o:ce.q(this.jr),ce.F(this.Br,!0)}if((n=this.Ne.bootstrap)!=null&&n.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){Ns.error("Invalid sessionID in bootstrap",u)}this.zr()}get sessionTimeoutMs(){return this._sessionTimeoutMs}onSessionId(e){return x(this.Rr)&&(this.Rr=[]),this.Rr.push(e),this.Dr&&e(this.Dr,this.Or),()=>{this.Rr=this.Rr.filter((s=>s!==e))}}Hr(){return this.Ne.persistence!=="memory"&&!this.Mr.xi&&ce.N()}Wr(e){e!==this.Or&&(this.Or=e,this.Hr()&&ce.F(this.jr,e))}Vr(){return this.Or?this.Or:this.Hr()?ce.H(this.jr):null}Zr(e){var s=this.Pr;return!$e(s)&&!$e(e)&&5e3>Math.abs(e-s)}Ur(e,s,r){var n=s!==this._sessionActivityTimestamp,i=!(e!==this.Dr||r!==this._sessionStartTimestamp);this._sessionStartTimestamp=r,this._sessionActivityTimestamp=s,this.Dr=e,i&&!n||i&&this.Zr(s)||(this.Pr=s,this.Mr.register({[cs]:[s,e,r]}))}Gr(){var e,s=(e=this.Ne)==null?void 0:e.persistence_save_debounce_ms;return lt(s)&&s>0}Qr(){this.Gr()?this.Mr.refreshKey(cs):(this.Mr.flush(),this.Mr.load())}Kr(){var e;if(!$e(this._sessionActivityTimestamp)&&this._sessionActivityTimestamp!==this.Pr){this.Qr();var s=this.Jr();s[1]===this.Dr&&s[2]===this._sessionStartTimestamp&&(this.Pr=this._sessionActivityTimestamp,this.Mr.register({[cs]:[this._sessionActivityTimestamp,(e=this.Dr)!==null&&e!==void 0?e:null,this._sessionStartTimestamp]}),this.Mr.flush())}}Yr(){var e=this.Jr()[0],s=lt(e)?e:0,r=lt(this._sessionActivityTimestamp)?this._sessionActivityTimestamp:0;return Math.max(s,r)}Xr(e){return this.Qr(),this.Lr(e,this.Yr())}Jr(){var e=this.Mr.props[cs];return L(e)&&e.length===2&&e.push(e[0]),e||[0,null,0]}resetSessionId(){this.Pr=null,clearTimeout(this.tn),this.tn=void 0,this.Ur(null,null,null)}destroy(){this.Fr=!0,this.Kr(),clearTimeout(this.tn),this.tn=void 0,this.Ar&&v&&(v.removeEventListener(an,this.Ar,{capture:!1}),this.Ar=void 0),this.Rr=[]}zr(){this.Ar=()=>{this.Kr(),this.Hr()&&ce.q(this.Br)},ne(v,an,this.Ar,{capture:!1})}checkAndGetSessionAndWindowId(e,s){if(e===void 0&&(e=!1),s===void 0&&(s=null),this.Ne.cookieless_mode===ht)throw new Error('checkAndGetSessionAndWindowId should not be called with cookieless_mode="always"');var r=s||new Date().getTime(),n=this.Jr(),i=n[1],o=n[2],a=this.Yr(),l=this.Vr(),u=lt(o)&&Math.abs(r-o)>864e5,c=!1,d=!1,h=!i,p=i,f=!h&&!e&&this.Lr(r,a);if(f){(f=this.Xr(r))||Ns.info("cross-tab refresh kept the session alive",{sessionId:i});var g=this.Jr();i=g[1],o=g[2]}h||f||u?(i=this.$r(),l=this.Nr(),Ns.info("new session ID generated",{sessionId:i,windowId:l,changeReason:{noSessionId:h,activityTimeout:f,sessionPastMaximumLength:u}}),o=r,c=!0):(l||(l=this.Nr(),c=!0),(d=i!==p)&&(Ns.info("adopted cross-tab session id",{sessionId:i,windowId:l}),c=!0));var m=lt(a)&&e&&!u?a:r,_=lt(o)?o:new Date().getTime();this.Wr(l),this.Ur(i,m,_),e||this.qr();var b={noSessionId:h,activityTimeout:f,sessionPastMaximumLength:u,crossTabAdoption:d};return c&&this.Rr.forEach((E=>E(i,l,b))),{sessionId:i,windowId:l,sessionStartTimestamp:_,changeReason:c?b:void 0,lastActivityTimestamp:a}}qr(){this.Fr||(clearTimeout(this.tn),this.tn=setTimeout((()=>{if(!this.Fr)if(this.Xr(new Date().getTime())){var e=this.Dr;this.resetSessionId(),this.Ir.emit("forcedIdleReset",{idleSessionId:e})}else this.qr()}),1.1*this.sessionTimeoutMs))}}var ed=function(t,e){if(!t)return!1;var s=t.userAgent;if(s&&za(s,e))return!0;try{var r=t?.userAgentData;if(r!=null&&r.brands&&r.brands.some((n=>za(n?.brand,e))))return!0}catch{}return!!t.webdriver};function td(){return(td=X((function*(){var t=ke?.userAgentData;if(t!=null&&t.getHighEntropyValues)try{var e=yield t.getHighEntropyValues(["model"]),s=e?.model;return W(s)&&s.length>0?s:void 0}catch(r){return void k.info("Unable to resolve $device_model from userAgentData.getHighEntropyValues",r)}}))).apply(this,arguments)}var fn=function(t,e){if(!(function(s){try{new RegExp(s)}catch{return!1}return!0})(e))return!1;try{return new RegExp(e).test(t)}catch{return!1}};function vi(t,e,s){return us({distinct_id:t,userPropertiesToSet:e,userPropertiesToSetOnce:s})}var sd={exact:(t,e)=>e.some((s=>t.some((r=>s===r)))),is_not:(t,e)=>e.every((s=>t.every((r=>s!==r)))),regex:(t,e)=>e.some((s=>t.some((r=>fn(s,r))))),not_regex:(t,e)=>e.every((s=>t.every((r=>!fn(s,r))))),icontains:(t,e)=>e.map(Fr).some((s=>t.map(Fr).some((r=>s.includes(r))))),not_icontains:(t,e)=>e.map(Fr).every((s=>t.map(Fr).every((r=>!s.includes(r))))),gt:(t,e)=>e.some((s=>{var r=parseFloat(s);return!isNaN(r)&&t.some((n=>r>parseFloat(n)))})),lt:(t,e)=>e.some((s=>{var r=parseFloat(s);return!isNaN(r)&&t.some((n=>rt.toLowerCase();function rd(t,e){return!t||Object.entries(t).every((s=>{var r=s[1],n=e?.[s[0]];if(x(n)||$e(n))return!1;var i=[String(n)],o=sd[r.operator];return!!o&&o(r.values,i)}))}var po="custom",Il="i.posthog.com",Yp=/^\/static\//;class Zp{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,s=(e=this.instance.config.ui_host)==null?void 0:e.replace(/\/$/,"");return s||(s=this.apiHost.replace("."+Il,".posthog.com")),s==="https://app.posthog.com"?"https://us.posthog.com":s}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":po),this.en[this.apiHost]}rn(e){if(Yp.test(e)){var s=this.instance.config.asset_host;if(typeof s=="string")return s.trim().replace(/\/$/,"")||void 0}}endpointFor(e,s){if(s===void 0&&(s=""),s&&(s=s[0]==="/"?s:"/"+s),e==="ui")return this.uiHost+s;if(e==="flags")return this.flagsApiHost+s;if(e==="assets"){var r=this.rn(s);if(r)return""+r+s}if(this.region===po)return this.apiHost+s;var n=Il+s;switch(e){case"assets":return"https://"+this.region+"-assets."+n;case"api":return"https://"+this.region+"."+n}}}function nd(t){var e;return!((e=t.conditions)==null||(e=e.events)==null||(e=e.values)==null||!e.length)}var q=se("[Surveys]"),id="seenSurvey_",od=t=>{try{var e=(s=>((r,n)=>""+id+(function(i){return i.current_iteration&&i.current_iteration>0?i.id+"_"+i.current_iteration:i.id})(n))(0,s))(t);if(localStorage.getItem(e))return;localStorage.setItem(e,"true")}catch(s){q.error("Failed to persist survey seen state",s)}},Xp=[hi.Popover,hi.Widget,hi.API],Qp={ignoreConditions:!1,ignoreDelay:!1,displayType:oo.Popover},ef=se("[PostHog ExternalIntegrations]"),tf={intercom:"intercom-integration",crispChat:"crisp-chat-integration"};class sf{constructor(e){this._instance=e}ai(e,s){var r;(r=$.__PosthogExtensions__)==null||r.loadExternalDependency==null||r.loadExternalDependency(this._instance,e,(n=>{if(n)return ef.error("failed to load script",n);s()}))}startIfEnabledOrStop(){var e=this,s=function(){var i,o,a,l=r[0],u=r[1];!u||(i=$.__PosthogExtensions__)!=null&&(i=i.integrations)!=null&&i[l]||e.ai(tf[l],(()=>{var c;(c=$.__PosthogExtensions__)==null||(c=c.integrations)==null||(c=c[l])==null||c.start(e._instance)})),!u&&(o=$.__PosthogExtensions__)!=null&&(o=o.integrations)!=null&&o[l]&&((a=$.__PosthogExtensions__)==null||(a=a.integrations)==null||(a=a[l])==null||a.stop())};for(var r of Object.entries((n=this._instance.config.integrations)!==null&&n!==void 0?n:{})){var n;s()}}}class rf{constructor(e,s){this.rt=e,this.nn=s,this.sn=new Map,this.an=!1}add(e){var s=this;return X((function*(){if(s.an)throw new Error("Cannot add an extension to a disposed ExtensionRuntime");if(s.sn.has(e.name))throw new Error('Browser extension "'+e.name+'" is already registered');s.sn.set(e.name,e);try{var r=e.setup(s.nn);r&&(yield r)}catch(i){var n=s.sn.get(e.name)===e;n&&s.sn.delete(e.name),s.rt.error('Failed to set up browser extension "'+e.name+'"',i),n&&s.ln(e)}}))()}dispose(){if(!this.an){this.an=!0;var e=Array.from(this.sn.values()).reverse();for(var s of(this.sn.clear(),e))this.ln(s)}}ln(e){try{var s=e.dispose==null?void 0:e.dispose();s&&Se(s.then)&&s.then(void 0,(r=>{this.rt.error('Failed to dispose browser extension "'+e.name+'"',r)}))}catch(r){this.rt.error('Failed to dispose browser extension "'+e.name+'"',r)}}}class nf{constructor(e){this._instance=e}initialize(){}get(e){var s=this._instance.persistence;if(typeof e=="string")return s?.get_property(e);var r={};for(var n of e){var i=s?.get_property(n);x(i)||(r[n]=i)}return r}set(e,s){var r;(r=this._instance.persistence)==null||r.register(typeof e=="string"?{[e]:s}:e)}remove(e){var s;(s=this._instance.persistence)==null||s.unregister(e)}}var Cl="extensionsRemoteConfig";class of{constructor(e){this.an=!1,this.instance=e,this.rt=k,this.un=e.hn,this.kv=new nf(e),this.onEvent=s=>Cr(this.instance.on("eventCaptured",(r=>{try{s({event:r.event,properties:r.properties})}catch(n){this.rt.error("Browser extension event listener failed",n)}}))),this.onRemoteConfig=s=>{if(this.an)return Cr((()=>{}));var r=i=>{try{s(i)}catch(o){this.rt.error("Browser extension remote config listener failed",o)}},n=this.instance.dn.on(Cl,r);return this.un&&r(this.un),Cr(n)},this.vn=new rf(k.createLogger("[BrowserExtensions]"),this)}get logger(){return this.rt}get distinctId(){return this.instance.get_distinct_id()}get anonymousId(){var e;return(e=this.instance.get_property(rr))!==null&&e!==void 0?e:this.distinctId}get deviceId(){var e=this.instance.get_property(rr);return typeof e=="string"?e:void 0}get library(){return{name:Y.LIB_NAME,version:Y.LIB_VERSION}}get initialPersonProperties(){var e,s;return(e=(s=this.instance.persistence)==null?void 0:s.get_initial_props())!==null&&e!==void 0?e:{}}get groups(){return this.instance.getGroups()}get session(){try{var e,s,r,n,i=(e=this.instance.sessionManager)==null?void 0:e.checkAndGetSessionAndWindowId(!0);return{sessionId:(s=i?.sessionId)!==null&&s!==void 0?s:"",windowId:(r=i?.windowId)!==null&&r!==void 0?r:"",sessionStartTimestamp:(n=i?.sessionStartTimestamp)!==null&&n!==void 0?n:0}}catch{return{sessionId:"",windowId:"",sessionStartTimestamp:0}}}get projectToken(){return this.instance.config.token}add(e){return this.vn.add(e)}capture(e,s,r){var n=this;return X((function*(){r?n.instance.capture(e,s,{timestamp:r.timestamp,uuid:r.uuid,$set:r.set,$set_once:r.setOnce}):n.instance.capture(e,s)}))()}registerDynamicEventProperties(e){return Cr(this.instance.cn(e))}handleRemoteConfig(e){this.an||(this.un=e,this.instance.dn.emit(Cl,e))}sendRequest(e,s){var r=this;return X((function*(){var n;s===void 0&&(s={});var i=r.instance.requestRouter.endpointFor((n=s.target)!==null&&n!==void 0?n:"api",e),o={method:s.method,url:s.query?Rn(i,s.query):i,data:s.body,headers:s.headers,timeout:s.timeoutMs,fireCallbackOnDrop:!0,transport:s.transport,compression:s.compression,timestampMode:s.sentAt};return s.transport==="sendBeacon"?(r.instance._send_request(o),{statusCode:202}):new Promise((a=>{o.callback=a,r.instance._send_request(o)}))}))()}dispose(){this.an||(this.an=!0,this.vn.dispose())}}var Zs={},_i=0,gn=()=>{},Fl='Consent opt in/out is not valid with cookieless_mode="always" and will be ignored',Ms="Surveys module not available",Pl="sanitize_properties is deprecated. Use before_send instead",ad="Invalid value for property_denylist config: ",af=["token","distinct_id",fu],as="posthog",ld=!Hp&&Pe?.indexOf("MSIE")===-1&&Pe?.indexOf("Mozilla")===-1,yi=t=>{var e;return w({api_host:"https://us.i.posthog.com",flags_api_host:null,ui_host:null,asset_host:null,token:"",autocapture:!0,cross_subdomain_cookie:ap(C?.location),persistence:"localStorage+cookie",persistence_name:"",cookie_persisted_properties:[],loaded:gn,save_campaign_params:!0,custom_campaign_params:[],custom_blocked_useragents:[],save_referrer:!0,capture_pageleave:"if_capture_pageview",defaults:t??"unset",__preview_deferred_init_extensions:!1,__preview_external_dependency_versioned_paths:!1,__preview_cookie_wins_on_conflict:!1,debug:re&&W(re?.search)&&re.search.indexOf("__posthog_debug=true")!==-1||!1,cookie_expiration:365,upgrade:!1,disable_session_recording:!1,disable_persistence:!1,disable_web_experiments:!0,disable_surveys:!1,disable_surveys_automatic_display:!1,disable_conversations:!1,disable_product_tours:!1,disableDeviceModel:!1,disable_external_dependency_loading:!1,strict_script_versioning:!1,enable_recording_console_log:void 0,secure_cookie:(v==null||(e=v.location)==null?void 0:e.protocol)==="https:",ip:!1,opt_out_capturing_by_default:!1,opt_out_persistence_by_default:!1,opt_out_useragent_filter:!1,opt_out_capturing_persistence_type:"localStorage",consent_persistence_name:null,opt_out_capturing_cookie_prefix:null,opt_in_site_apps:!1,property_denylist:[],respect_dnt:!1,sanitize_properties:null,request_headers:{},request_batching:!0,properties_string_max_length:65535,mask_all_element_attributes:!1,mask_all_text:!1,mask_personal_data_properties:!1,custom_personal_data_properties:[],advanced_disable_flags:!1,advanced_disable_decide:!1,advanced_disable_feature_flags:!1,advanced_disable_feature_flags_on_first_load:!1,advanced_only_evaluate_survey_feature_flags:!1,advanced_feature_flags_dedup_per_session:!1,advanced_enable_surveys:!1,advanced_disable_toolbar_metrics:!1,feature_flag_request_timeout_ms:3e3,surveys_request_timeout_ms:1e4,on_request_error(s){k.error("Bad HTTP status: "+s.statusCode+" "+s.text)},get_device_id:s=>s,capture_performance:void 0,name:"posthog",bootstrap:{},disable_compression:!1,session_idle_timeout_seconds:1800,person_profiles:so,before_send:void 0,get_current_url:void 0,request_queue_config:{flush_interval_ms:ho},error_tracking:{},_onCapture:gn},(s=>({rageclick:s&&s>="2026-05-30"?{content_ignorelist:yp,ignore_text_selection:!0}:!s||"2025-11-30">s||{content_ignorelist:!0},capture_pageview:!s||"2025-05-24">s||"history_change",session_recording:s&&s>="2026-06-25"?{strictMinimumDuration:!0,canvasCapture:{resolutionScale:.6},streamNetworkBody:!0}:s&&s>="2026-05-30"?{strictMinimumDuration:!0,canvasCapture:{resolutionScale:.6}}:s&&s>="2025-11-30"?{strictMinimumDuration:!0}:{},external_scripts_inject_target:s&&s>="2026-01-30"?"head":"body",internal_or_test_user_hostname:s&&s>="2026-01-30"?/^(localhost|127\.0\.0\.1)$/:void 0,persistence_save_debounce_ms:s&&s>="2026-05-30"?250:0,split_storage:!(!s||"2026-05-30">s),detect_google_search_app:!(!s||"2026-05-30">s),disable_capture_url_hashes:!(!s||"2026-06-25">s)}))(t))},lf=[["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"]],Al=t=>{var e={};for(var s of lf){var r=s[0],n=s[1];x(t[r])||(e[n]=t[r])}var i=ee({},e,t),o=t.__preview_external_dependency_versioned_paths;return x(o)||(x(t.strict_script_versioning)&&(i.strict_script_versioning=!!o),W(o)&&x(t.asset_host)&&(i.asset_host=o)),L(t.property_blacklist)&&(x(t.property_denylist)?i.property_denylist=t.property_blacklist:L(t.property_denylist)?i.property_denylist=[...t.property_blacklist,...t.property_denylist]:k.error(ad+t.property_denylist)),i};class cf{constructor(){this.__forceAllowLocalhost=!1}get fn(){return this.__forceAllowLocalhost}set fn(e){k.error("WebPerformanceObserver is deprecated and has no impact on network capture. Use `_forceAllowLocalhostNetworkCapture` on `posthog.sessionRecording`"),this.__forceAllowLocalhost=e}}class Te{pn(e,s){if(e){var r=this.sn.indexOf(e);r!==-1&&this.sn.splice(r,1)}return this.sn.push(s),s.initialize==null||s.initialize(),s}gn(){return this.config.cookieless_mode===ht||this.config.cookieless_mode===Ht&&this.consent.isRejected()}get decideEndpointWasHit(){var e,s;return(e=(s=this.featureFlags)==null?void 0:s.hasLoadedFlags)!==null&&e!==void 0&&e}get flagsEndpointWasHit(){var e,s;return(e=(s=this.featureFlags)==null?void 0:s.hasLoadedFlags)!==null&&e!==void 0&&e}constructor(){var e;this.webPerformance=new cf,this.mn=!1,this.version=Y.LIB_VERSION,this.yn=new Set,this.bn="",this.dn=new Qo,this.sn=[],this._n=[],this._calculate_event_properties=this.calculateEventProperties.bind(this),this.config=yi(),this.SentryIntegration=Cp,this.sentryIntegration=r=>(function(n,i){var o=Ru(n,i);return{name:$u,processEvent:a=>o(a)}})(this,r),this.__request_queue=[],this.__loaded=!1,this.analyticsDefaultEndpoint="/e/",this.wn=!1,this.kn=null,this.xn=null,this.Sn=null,this.scrollManager=new Kp(this),this.pageViewManager=new gl(this),this.rateLimiter=new Lp(this),this.requestRouter=new Zp(this),this.consent=new fp(this),this.externalIntegrations=new sf(this);var s=(e=Te.__defaultExtensionClasses)!==null&&e!==void 0?e:{};this.featureFlags=s.featureFlags&&new s.featureFlags(this),this.toolbar=s.toolbar&&new s.toolbar(this),this.surveys=s.surveys&&new s.surveys(this),this.conversations=s.conversations&&new s.conversations(this),this.logs=s.logs&&new s.logs(this),this.metrics=s.metrics&&new s.metrics(this),this.experiments=s.experiments&&new s.experiments(this),this.exceptions=s.exceptions&&new s.exceptions(this),this.people={set:(r,n,i)=>{var o=W(r)?{[r]:n}:r;this.setPersonProperties(o),i?.({})},set_once:(r,n,i)=>{var o=W(r)?{[r]:n}:r;this.setPersonProperties(void 0,o),i?.({})}},this.on("eventCaptured",(r=>k.info('send "'+r?.event+'"',r)))}init(e,s,r){if(r&&r!==as){var n,i=(n=Zs[r])!==null&&n!==void 0?n:new Te;return i._init(e,s,r),Zs[r]=i,Zs[as][r]=i,i}return this._init(e,s,r)}_init(e,s,r){var n,i;s===void 0&&(s={});var o,a=W(e)?e.trim():"";if(!a)return k.critical("PostHog was initialized without a token. This likely indicates a misconfiguration. Please check the first argument passed to posthog.init()"),this;if(this.__loaded)return a!==((o=this.config)==null?void 0:o.token)?console.warn("[PostHog.js]","You have already initialized PostHog with a different project token! Re-initializing is a no-op, so events will keep going to the project this instance was initialized with. To capture into a second project, load PostHog once, then initialize a named instance after the SDK has loaded, e.g. posthog.init('"+a+"', { ... }, 'project2')"):console.warn("[PostHog.js]","You have already initialized PostHog! Re-initializing is a no-op"),this;this.__loaded=!0,this.config=yi(s.defaults),s.debug=this.Cn(s.debug),this.Mn=s,this.Tn=[],s.person_profiles?this.xn=s.person_profiles:s.process_person&&(this.xn=s.process_person);var l=yi(s.defaults),u=Al(s),c=ee({},l,u,{name:r,token:a});te(l.rageclick)&&te(u.rageclick)&&(c.rageclick=ee({},l.rageclick,u.rageclick)),te(l.session_recording)&&te(u.session_recording)&&(c.session_recording=ee({},l.session_recording,u.session_recording)),this.set_config(c),this.config.on_xhr_error&&k.error("on_xhr_error is deprecated. Use on_request_error instead"),this.compression=s.disable_compression?void 0:xe.GZipJS;var d=this.En();if(this.persistence=new di(this.config,d),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new di(w({},this.config,{persistence:"sessionStorage"}),d,!1),this.bn="ph_"+(this.config.persistence_name||this.config.token)+"_session_registered_properties",this.config.persistence!=="memory"&&!d&&ce.N()){var h=ce.H(this.bn);L(h)&&h.forEach((P=>{W(P)&&this.yn.add(P)}))}else ce.q(this.bn);var p=w({},this.persistence.props),f=w({},this.sessionPersistence.props);this.register({$initialization_time:new Date().toISOString()}),this.In=new qp((P=>this.Pn(P)),this.config.request_queue_config),this.Rn=new Gp(this),this.__request_queue=[];var g=this.gn();if(g||(this.sessionManager=new kl(this),this.sessionPropsManager=new xl(this,this.sessionManager,this.persistence),this.sessionManager.onSessionId(((P,B,S)=>{(S!=null&&S.activityTimeout||S!=null&&S.sessionPastMaximumLength||S!=null&&S.crossTabAdoption)&&this.An()}))),this.Fn(),this.config.__preview_deferred_init_extensions?(k.info("Deferring extension initialization to improve startup performance"),setTimeout((()=>{this.Ln(g)}),0)):(k.info("Initializing extensions synchronously"),this.Ln(g)),Y.DEBUG=Y.DEBUG||this.config.debug,Y.DEBUG&&k.info("Starting in debug mode",{this:this,config:s,thisC:w({},this.config),p,s:f}),!this.config.identity_distinct_id||(n=s.bootstrap)!=null&&n.distinctID||(s.bootstrap=w({},s.bootstrap,{distinctID:this.config.identity_distinct_id,isIdentifiedID:!0})),((i=s.bootstrap)==null?void 0:i.distinctID)!==void 0){var m=s.bootstrap.distinctID,_=this.get_distinct_id(),b=this.persistence.get_property(He);if(s.bootstrap.isIdentifiedID&&_!=null&&_!==m&&b===ts)this.identify(m);else if(s.bootstrap.isIdentifiedID&&_!=null&&_!==m&&b===Tt)k.warn("Bootstrap distinctID differs from an already-identified user. The existing identity is preserved. Call reset() before reinitializing if you intend to switch users.");else{var E=this.config.get_device_id(dt()),I=s.bootstrap.isIdentifiedID?E:m;this.persistence.set_property(He,s.bootstrap.isIdentifiedID?Tt:ts),this.register({distinct_id:m,$device_id:I})}}if(g)this.register_once({distinct_id:Er,$device_id:null},"");else if(!this.get_distinct_id()){var F=this.config.get_device_id(dt());this.register_once({distinct_id:F,$device_id:F},""),this.persistence.set_property(He,ts)}return ne(v,"onpagehide"in self?"pagehide":"unload",this._handle_unload.bind(this),{passive:!1}),s.segment?(function(P,B){var S=P.config.segment;if(!S)return B();(function(A,R){var N=A.config.segment;if(!N)return R();var T=J=>{var z=()=>J.anonymousId()||dt();A.config.get_device_id=z,J.id()&&(A.register({distinct_id:J.id(),$device_id:z()}),A.persistence.set_property(He,Tt)),R()},O=N.user();"then"in O&&Se(O.then)?O.then(T):T(O)})(P,(()=>{S.register((A=>{typeof Promise<"u"&&Promise.resolve||ci.warn("This browser does not have Promise support, and can not use the segment integration");var R=(N,T)=>{if(!T)return N;N.event.userId||N.event.anonymousId===A.get_distinct_id()||(ci.info("No userId set, resetting PostHog"),A.reset()),N.event.userId&&N.event.userId!==A.get_distinct_id()&&(ci.info("UserId set, identifying with PostHog"),A.identify(N.event.userId));var O=A.calculateEventProperties(T,N.event.properties);return N.event.properties=Object.assign({},O,N.event.properties),N};return{name:"PostHog JS",type:"enrichment",version:"1.0.0",isLoaded:()=>!0,load:()=>Promise.resolve(),track:N=>R(N,N.event.event),page:N=>R(N,os),identify:N=>R(N,oi),screen:N=>R(N,"$screen")}})(P)).then((()=>{B()}))}))})(this,(()=>this.On())):this.On(),Se(this.config._onCapture)&&this.config._onCapture!==gn&&(k.warn("onCapture is deprecated. Please use `before_send` instead"),this.on("eventCaptured",(P=>this.config._onCapture(P.event,P)))),this.config.ip&&k.warn('The `ip` config option has NO EFFECT AT ALL and has been deprecated. Use a custom transformation or "Discard IP data" project setting instead. See https://posthog.com/tutorials/web-redact-properties#hiding-customer-ip-address for more information.'),this.config.disableDeviceModel||(function(){return td.apply(this,arguments)})().then((P=>{P&&this.register({[ni]:P})})).catch(gn),this}Fn(){var e,s,r,n,i,o,a=(e=(s=this.config.__extensionClasses)==null?void 0:s.featureFlags)!==null&&e!==void 0?e:(r=Te.__defaultExtensionClasses)==null?void 0:r.featureFlags;a&&(this.featureFlags&&this.featureFlags instanceof a||((n=this.Dn)==null||n.call(this),this.Dn=void 0,this.featureFlags=new a(this)),Se(this.featureFlags.onReloading)&&Se(this.featureFlags.setup)?this.Dn||(this.Dn=this.featureFlags.onReloading((()=>{this.dn.emit("featureFlagsReloading",!0)})),this.$n().add(this.featureFlags)):(i=(o=this.featureFlags).initialize)==null||i.call(o))}Ln(e){var s,r,n,i,o,a,l,u=performance.now(),c=w({},Te.__defaultExtensionClasses,this.config.__extensionClasses),d=[];c.exceptions&&this.sn.push(this.exceptions=(s=this.exceptions)!==null&&s!==void 0?s:new c.exceptions(this)),c.historyAutocapture&&this.sn.push(this.historyAutocapture=new c.historyAutocapture(this)),c.tracingHeaders&&this.sn.push(this.tracingHeaders=new c.tracingHeaders(this)),c.siteApps&&this.sn.push(this.siteApps=new c.siteApps(this)),c.sessionRecording&&!e&&this.sn.push(this.sessionRecording=new c.sessionRecording(this)),this.config.disable_scroll_properties||d.push((()=>{this.scrollManager.startMeasuringScrollPosition()})),c.autocapture&&this.sn.push(this.autocapture=new c.autocapture(this)),c.surveys&&this.sn.push(this.surveys=(r=this.surveys)!==null&&r!==void 0?r:new c.surveys(this)),c.logs&&this.sn.push(this.logs=(n=this.logs)!==null&&n!==void 0?n:new c.logs(this)),c.metrics&&this.sn.push(this.metrics=(i=this.metrics)!==null&&i!==void 0?i: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,Ip)),c.toolbar&&this.sn.push(this.toolbar=(a=this.toolbar)!==null&&a!==void 0?a:new c.toolbar(this)),c.experiments&&this.sn.push(this.experiments=(l=this.experiments)!==null&&l!==void 0?l:new c.experiments(this)),this.sn.forEach((h=>{h.initialize&&d.push((()=>{h.initialize==null||h.initialize()}))})),d.push((()=>{if(this.Nn){var h=this.Nn;this.Nn=void 0,this.sn.forEach((p=>p.onRemoteConfig==null?void 0:p.onRemoteConfig(h)))}})),this.qn(d,u)}qn(e,s){for(;e.length>0;){if(this.config.__preview_deferred_init_extensions&&performance.now()-s>=30&&e.length>0)return void setTimeout((()=>{this.qn(e,s)}),0);var r=e.shift();if(r)try{r()}catch(i){k.error("Error initializing extension:",i)}}var n=Math.round(performance.now()-s);this.register_for_session({[gu]:this.config.__preview_deferred_init_extensions?"deferred":"synchronous",[mu]:n}),this.config.__preview_deferred_init_extensions&&k.info("PostHog extensions initialized ("+n+"ms)")}Zi(e){var s;if(!C||!C.body)return k.info("document not ready yet, trying again in 500 milliseconds..."),void setTimeout((()=>{this.Zi(e)}),500);if(this.config.__preview_deferred_init_extensions&&(this.Nn=e),this.hn=e,this.compression=void 0,e.ok){var r,n=e.config;n.supportedCompression&&!this.config.disable_compression&&(this.compression=M(n.supportedCompression,xe.GZipJS)?xe.GZipJS:M(n.supportedCompression,xe.Base64)?xe.Base64:void 0),(r=n.analytics)!=null&&r.endpoint&&(this.analyticsDefaultEndpoint=n.analytics.endpoint)}this.set_config({person_profiles:this.xn?this.xn:so}),(s=this.jn)==null||s.handleRemoteConfig(e),this.sn.forEach((i=>i.onRemoteConfig==null?void 0:i.onRemoteConfig(e)))}On(){try{this.config.loaded(this)}catch(r){k.critical("`loaded` function failed",r)}if(this.Bn(),this.config.internal_or_test_user_hostname&&re!=null&&re.hostname){var e=re.hostname,s=this.config.internal_or_test_user_hostname;(typeof s=="string"?e===s:s.test(e))&&this.setInternalOrTestUser()}this.config.capture_pageview&&setTimeout((()=>{(this.consent.isOptedIn()||this.gn())&&this.Hn()}),1),this.Un=new Hu(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,s,r,n,i;(e=this.surveys)==null||e.handlePageUnload==null||e.handlePageUnload(),(s=this.metrics)==null||s.flush("sendBeacon"),this.config.request_batching?(this.zn()&&this.capture(ii),(r=this.logs)==null||r.flushLogs("sendBeacon"),(n=this.In)==null||n.unload(),(i=this.Rn)==null||i.unload()):this.zn()&&this.capture(ii,null,{transport:"sendBeacon"})}_send_request(e){this.__loaded?ld?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=w({},this.config.request_headers,e.headers),e.compression=e.compression==="best-available"?this.compression:e.compression,(x(this.config.disable_beacon)?this.config.__preview_disable_beacon:this.config.disable_beacon)&&(e.disableTransport=["sendBeacon"]),e.fetchOptions=e.fetchOptions||this.config.fetch_options,(s=>{var r,n,i,o=w({},s);o.timeout=o.timeout||6e4;var a,l,u,c,d,h=(r=o.transport)!==null&&r!==void 0?r:"fetch";h==="sendBeacon"&&x(o.compression)&&o.data&&(o.compression=xe.Base64),o.method==="POST"&&o.data&&(o.timestampMode==="capture-body"?o.data={api_key:(l=(d=(c=L(a=o.data)?a:[a])[0])==null||(u=d.properties)==null?void 0:u.token)!==null&&l!==void 0?l:d?.token,batch:c,sent_at:new Date().toISOString()}:o.timestampMode==="body"&&(o.data=(function(m,_){return _===void 0&&(_=new Date().toISOString()),L(m)?m.map((b=>w({},b,{sent_at:_}))):w({},m,{sent_at:_})})(o.data))),o.url=Sl(o.url,o.method,o.compression,o.timestampMode);var p=jr.filter((m=>!o.disableTransport||!m.transport||!o.disableTransport.includes(m.transport))),f=(n=(i=(function(m,_){for(var b=0;m.length>b;b++)if(m[b].transport===h)return m[b]})(p))==null?void 0:i.method)!==null&&n!==void 0?n:p[0].method;if(!f)throw new Error("No available transport method");var g=m=>{try{f(m)}catch(_){Xu(_)?k.warn(_):k.error(_),o.callback==null||o.callback({statusCode:0,error:_})}};h!=="sendBeacon"&&o.data&&o.compression===xe.GZipJS&&ch&&typeof Promise<"u"&&!Br?Wp(o).then((m=>{g(m)})).catch((m=>{if(Wa(m))return Br=!0,void g(w({},o,{compression:void 0,url:Sl(s.url,s.method,void 0,s.timestampMode)}));(_=>{if(!_||typeof _!="object")return!1;var b="name"in _?String(_.name):"";return Wa(_)||b===Fc})(m)&&(Br=!0),g(o)})):f(o)})(w({},e,{callback:s=>{var r,n;this.rateLimiter.checkForLimiting(s),400>s.statusCode||(r=(n=this.config).on_request_error)==null||r.call(n,s),e.callback==null||e.callback(s)}}))):e.fireCallbackOnDrop&&(e.callback==null||e.callback({statusCode:0}))}Pn(e){this.Rn?this.Rn.retriableRequest(e):this._send_request(e)}_execute_array(e){_i++;try{var s,r=[],n=[],i=[];Sr(e,(a=>{if(a)if(L(s=a[0]))i.push(a);else if(Se(a))try{a.call(this)}catch(l){k.error("Error executing queued PostHog call",a,l)}else L(a)&&s==="alias"?r.push(a):L(a)&&s.indexOf("capture")!==-1&&Se(this[s])?i.push(a):n.push(a)}));var o=function(a,l){Sr(a,(function(u){try{if(L(u[0])){var c=l;Z(u,(function(d){c=c[d[0]].apply(c,d.slice(1))}))}else l[u[0]].apply(l,u.slice(1))}catch(d){k.error("Error executing queued PostHog call",u,d)}}))};o(r,this),o(n,this),o(i,this)}finally{_i--}}push(e){if(_i>0&&L(e)&&W(e[0])){var s=Te.prototype[e[0]];Se(s)&&s.apply(this,e.slice(1))}else this._execute_array([e])}capture(e,s,r){var n,i,o,a,l;if(this.__loaded&&this.persistence&&this.sessionPersistence&&this.In){if(this.is_capturing())if(!x(e)&&W(e)){var u=!this.config.opt_out_useragent_filter&&this._is_bot();if(!u||this.config.__preview_capture_bot_pageviews){var c=r!=null&&r.skip_client_rate_limiting?void 0:this.rateLimiter.clientRateLimitContext();if(c==null||!c.isRateLimited){s!=null&&s.$current_url&&!W(s?.$current_url)&&(k.error("Invalid `$current_url` property provided to `posthog.capture`. Input must be a string. Ignoring provided value."),s==null||delete s.$current_url),e!=="$exception"||r!=null&&r.Wn||k.warn("Using `posthog.capture('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureException(error)` instead, which attaches required metadata automatically."),this.sessionPersistence.update_search_keyword(),this.config.save_campaign_params&&this.sessionPersistence.update_campaign_params(),this.config.save_referrer&&this.sessionPersistence.update_referrer_info(),(this.config.save_campaign_params||this.config.save_referrer)&&this.persistence.set_initial_person_info();var d=new Date,h=r?.timestamp||d,p=Ka(r?.uuid,dt),f={uuid:p,event:e,properties:this.calculateEventProperties(e,s||{},h,p)};e===os&&this.config.__preview_capture_bot_pageviews&&u&&(f.event="$bot_pageview",f.properties.$browser_type="bot"),c&&(f.properties.$lib_rate_limit_remaining_tokens=c.remainingTokens);var g=e==="$feature_flag_called"&&f.properties.$feature_flag_has_experiment===!1&&this.get_property(tn)===!0;r?.$set&&!g&&(f.$set=r?.$set);var m=r?.$unset;m&&(f.$unset=m);var _,b,E,I=g?void 0:this.Vn(r?.$set_once,e!==el,e===oi);if(I&&(f.$set_once=I),r!=null&&r._noTruncate||(i=this.config.properties_string_max_length,o=f,a=T=>W(T)?T.slice(0,i):T,l=new Set,f=(function T(O,J){if(O!==Object(O))return a?a(O):O;if(!l.has(O)){var z;if(l.add(O),L(O))z=[],Sr(O,(oe=>{z.push(T(oe))}));else{var H={};Z(O,((oe,pe)=>{l.has(oe)||(H[pe]=T(oe))})),z=H}return z}})(o)),f.timestamp=h,x(r?.timestamp)||(f.properties.$event_time_override_provided=!0,f.properties.$event_time_override_system_time=d),g&&(f.properties=(function(T,O){O===void 0&&(O=[]);var J={},z=H=>{T[H]!==void 0&&(J[H]=T[H])};return uh.forEach(z),O.forEach(z),J})(f.properties,af)),e===ft.DISMISSED||e===ft.SENT){var F=s?.[pi.SURVEY_ID],P=s?.[pi.SURVEY_ITERATION];od({id:F,current_iteration:P}),f.$set=w({},f.$set,{[(_={id:F,current_iteration:P},b=e===ft.SENT?"responded":"dismissed",E="$survey_"+b+"/"+_.id,_.current_iteration&&_.current_iteration>0&&(E="$survey_"+b+"/"+_.id+"/"+_.current_iteration),E)]:!0})}else e===ft.SHOWN&&(f.$set=w({},f.$set,{[pi.SURVEY_LAST_SEEN_DATE]:new Date().toISOString()}));if(e===Mp.SHOWN){var B=s?.[vl.TOUR_TYPE];B&&(f.$set=w({},f.$set,{[vl.TOUR_LAST_SEEN_DATE+"/"+B]:new Date().toISOString()}))}var S=w({},f.properties.$set,f.$set);if(mt(S)||this.setPersonPropertiesForFlags(S),!D(this.config.before_send)){var A=this.Pt(f);if(!A)return;(f=A).uuid=Ka(f.uuid,dt)}this.dn.emit("eventCaptured",f);var R=(n=r?._url)!==null&&n!==void 0?n:this.requestRouter.endpointFor("api",this.analyticsDefaultEndpoint),N={method:"POST",url:R,data:f,compression:"best-available",timestampMode:r?._batchKey==="recordings"||/\/s\/(?:\?|$)/.test(R)?"body":"capture-body",batchKey:r?._batchKey,transport:r?.transport};return!this.config.request_batching||r&&(r==null||!r._batchKey)||r!=null&&r.send_instantly?this.Pn(N):this.In.enqueue(N),f}k.critical("This capture call is ignored due to client rate limiting.")}}else k.error("No event name provided to posthog.capture")}else k.uninitializedWarning("posthog.capture")}_addCaptureHook(e){return this.on("eventCaptured",(s=>e(s.event,s)))}$n(){var e;return(e=this.jn)!==null&&e!==void 0?e:this.jn=new of(this)}cn(e){this._n.push(e);var s=!0;return()=>{if(s){s=!1;var r=this._n.indexOf(e);r!==-1&&this._n.splice(r,1)}}}calculateEventProperties(e,s,r,n,i){if(r=r||new Date,!this.persistence||!this.sessionPersistence)return s;var o=i?void 0:this.persistence.remove_event_timer(e),a=w({},s);if(a.token=this.config.token,a.$config_defaults=this.config.defaults,this.gn()&&(a[fu]=!0),e==="$snapshot"){var l=w({},this.persistence.properties(),this.sessionPersistence.properties());return a.distinct_id=l.distinct_id,(!W(a.distinct_id)&&!he(a.distinct_id)||Li(a.distinct_id))&&k.error("Invalid distinct_id for replay event. This indicates a bug in your implementation"),a}var u,c=(function(F,P,B,S){var A,R,N,T;if(S===void 0&&(S=!1),!Pe)return{};var O,J=F?[..._s,...P||[]]:[],z=(function(_r){for(var je=0;Va.length>je;je++){var yr=Va[je],Qt=yr[1],es=yr[0].exec(_r),Cs=es&&(Se(Qt)?Qt(es,_r):Qt);if(Cs)return Cs}return["",""]})(Pe),H=z[0],oe=z[1],pe=(O=typeof navigator<"u"?navigator:void 0)!=null&&O.brave?{brave:!0}:{},Ie={};x(B)||(Ie.detectGoogleSearchApp=B);var _e={},Ce=(A=navigator)==null||(A=A.userAgentData)==null?void 0:A.platform,Re=(R=navigator)==null?void 0:R.maxTouchPoints,ae=v==null||(N=v.screen)==null?void 0:N.width,me=v==null||(T=v.screen)==null?void 0:T.height,ge=v?.devicePixelRatio;x(Ce)||(_e.userAgentDataPlatform=Ce),x(Re)||(_e.maxTouchPoints=Re),x(ae)||(_e.screenWidth=ae),x(me)||(_e.screenHeight=me),x(ge)||(_e.devicePixelRatio=ge);var Ye,Rt,de,Ve,St,Is,Be,Fe,vr=ee(Go({$os:H,$os_version:oe,$browser:Qc(Pe,navigator.vendor,pe,Ie),$device:Ga(Pe),$device_type:(Rt=Pe,de=_e,Fe=Ga(Rt),Fe===Mc||Fe===Nc||Fe==="Kobo"||Fe==="Kindle Fire"||Fe===Kc?fs:Fe===tr||Fe===hs||Fe===sr||Fe===Di?"Console":Fe===Oc?"Wearable":Fe?Oe:de?.userAgentDataPlatform==="Android"&&((Ve=de?.maxTouchPoints)!==null&&Ve!==void 0?Ve:0)>0?600>Math.min((St=de?.screenWidth)!==null&&St!==void 0?St:0,(Is=de?.screenHeight)!==null&&Is!==void 0?Is:0)/((Be=de?.devicePixelRatio)!==null&&Be!==void 0?Be:1)?Oe:fs:"Desktop"),$timezone:Uu(),$timezone_offset:Rp()}),{$current_url:ir(S?Ct(re?.href):re?.href,J,or),$host:re?.host,$pathname:re?.pathname,$raw_user_agent:Pe.length>1e3?Pe.substring(0,997)+"...":Pe,$browser_version:Ph(Pe,navigator.vendor,pe,Ie),$browser_language:ml(),$browser_language_prefix:(Ye=ml(),typeof Ye=="string"?Ye.split("-")[0]:void 0),$screen_height:v?.screen.height,$screen_width:v?.screen.width,$viewport_height:v?.innerHeight,$viewport_width:v?.innerWidth,$lib:Y.LIB_NAME,$lib_version:Y.LIB_VERSION,$insert_id:Math.random().toString(36).substring(2,10)+Math.random().toString(36).substring(2,10),$time:Date.now()/1e3});return Y.SDK_DIST_CHANNEL&&(vr.$sdk_dist_channel=Y.SDK_DIST_CHANNEL),vr})(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(i,r.getTime()),h=d.windowId;a.$session_id=d.sessionId,a.$window_id=h}this.sessionPropsManager&&ee(a,this.sessionPropsManager.getSessionProps());try{var p;this.sessionRecording&&ee(a,this.sessionRecording.sdkDebugProperties),a.$sdk_debug_retry_queue_size=(p=this.Rn)==null?void 0:p.length}catch(F){a.$sdk_debug_error_capturing_properties=String(F)}if(this.requestRouter.region===po&&(a.$lib_custom_api_host=this.config.api_host),u=e!==os||i?e!==ii||i?this.pageViewManager.doEvent():this.pageViewManager.doPageLeave(r):this.pageViewManager.doPageView(r,n),a=ee(a,u),e===os&&C&&(a.title=C.title),!x(o)){var f=r.getTime()-o;a.$duration=parseFloat((f/1e3).toFixed(3))}Pe&&this.config.opt_out_useragent_filter&&(a.$browser_type=this._is_bot()?"bot":"browser");var g=this.persistence.properties(),m=this.sessionPersistence.properties();Z(["$referrer","$referring_domain"],(F=>{F in g&&delete m[F]}));var _={};if(this._n.length>0)for(var b of this._n.slice())try{ee(_,b())}catch(F){k.error("Failed to produce browser extension event properties",F)}(a=ee({},c,g,m,w({},_,a))).$is_identified=this._isIdentified(),L(this.config.property_denylist)?Z(this.config.property_denylist,(function(F){delete a[F]})):k.error(ad+this.config.property_denylist+" or property_blacklist config: "+this.config.property_blacklist);var E=this.config.sanitize_properties;E&&(k.error(Pl),a=E(a,e));var I=this.Zn();return a.$process_person_profile=I,I&&!i&&this.Gn("_calculate_event_properties"),a}Vn(e,s,r){var n;if(s===void 0&&(s=!0),r===void 0&&(r=!1),!this.persistence||!this.Zn()||this.mn&&!r)return e;var i=this.persistence.get_initial_props(),o=(n=this.sessionPropsManager)==null?void 0:n.getSetOnceProps(),a=ee({},i,o||{},e||{}),l=this.config.sanitize_properties;return l&&(k.error(Pl),a=l(a,"$set_once")),s&&(this.mn=!0),mt(a)?void 0:a}register(e,s){var r;(r=this.persistence)==null||r.register(e,s)}register_once(e,s,r){var n;(n=this.persistence)==null||n.register_once(e,s,r)}register_for_session(e){var s;(s=this.sessionPersistence)==null||s.register(e),Object.keys(e).forEach((r=>this.yn.add(r))),this.Qn()}unregister(e){var s;(s=this.persistence)==null||s.unregister(e)}unregister_for_session(e){var s;(s=this.sessionPersistence)==null||s.unregister(e),this.yn.delete(e),this.Qn()}Kn(e,s){this.register({[e]:s})}An(){this.yn.forEach((e=>{var s;(s=this.sessionPersistence)==null||s.unregister(e)})),this.yn.clear(),this.Qn()}Qn(){var e;if(this.bn)if(this.config.persistence==="memory"||(e=this.sessionPersistence)!=null&&e.xi||!ce.N())ce.q(this.bn);else{var s=[];this.yn.forEach((r=>s.push(r))),s.length>0?ce.F(this.bn,s):ce.q(this.bn)}}getFeatureFlag(e,s){var r;return(r=this.featureFlags)==null?void 0:r.getFeatureFlag(e,s)}getFeatureFlagPayload(e){var s;return(s=this.featureFlags)==null?void 0:s.getFeatureFlagPayload(e)}getFeatureFlagResult(e,s){var r;return(r=this.featureFlags)==null?void 0:r.getFeatureFlagResult(e,s)}getAllFeatureFlags(){var e,s;return(e=(s=this.featureFlags)==null?void 0:s.getAllFeatureFlags())!==null&&e!==void 0?e:[]}isFeatureEnabled(e,s){var r,n;return(r=(n=this.featureFlags)==null?void 0:n.isFeatureEnabled(e,s))!==null&&r!==void 0?r:s?.defaultValue}reloadFeatureFlags(){var e;(e=this.featureFlags)==null||e.reloadFeatureFlags()}updateFlags(e,s,r){var n;(n=this.featureFlags)==null||n.updateFlags(e,s,r)}updateEarlyAccessFeatureEnrollment(e,s,r){var n;(n=this.featureFlags)==null||n.updateEarlyAccessFeatureEnrollment(e,s,r)}getEarlyAccessFeatures(e,s,r){var n;return s===void 0&&(s=!1),(n=this.featureFlags)==null?void 0:n.getEarlyAccessFeatures(e,s,r)}on(e,s){return this.dn.on(e,s)}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:Ms}),()=>{})}onSessionId(e){var s,r;return(s=(r=this.sessionManager)==null?void 0:r.onSessionId(e))!==null&&s!==void 0?s:()=>{}}getSurveys(e,s){s===void 0&&(s=!1),this.surveys?this.surveys.getSurveys(e,s):e([],{isLoaded:!1,error:Ms})}getActiveMatchingSurveys(e,s){s===void 0&&(s=!1),this.surveys?this.surveys.getActiveMatchingSurveys(e,s):e([],{isLoaded:!1,error:Ms})}renderSurvey(e,s){var r;(r=this.surveys)==null||r.renderSurvey(e,s)}displaySurvey(e,s){var r;s===void 0&&(s=Qp),(r=this.surveys)==null||r.displaySurvey(e,s)}cancelPendingSurvey(e){var s;(s=this.surveys)==null||s.cancelPendingSurvey(e)}canRenderSurvey(e){var s,r;return(s=(r=this.surveys)==null?void 0:r.canRenderSurvey(e))!==null&&s!==void 0?s:{visible:!1,disabledReason:Ms}}canRenderSurveyAsync(e,s){var r,n;return s===void 0&&(s=!1),(r=(n=this.surveys)==null?void 0:n.canRenderSurveyAsync(e,s))!==null&&r!==void 0?r:Promise.resolve({visible:!1,disabledReason:Ms})}Jn(e){return!e||Li(e)?(k.critical("Unique user id has not been set in posthog.identify"),!1):e===Er?(k.critical('The string "'+e+'" was set in posthog.identify which indicates an error. This ID is only used as a sentinel value.'),!1):!["distinct_id","distinctid"].includes(e.toLowerCase())&&!["undefined","null"].includes(e.toLowerCase())||(k.critical('The string "'+e+'" was set in posthog.identify which indicates an error. This ID should be unique to the user and not a hardcoded string.'),!1)}identify(e,s,r){if(!this.__loaded||!this.persistence)return k.uninitializedWarning("posthog.identify");if(he(e)&&(e=e.toString(),k.warn("The first argument to posthog.identify was a number, but it should be a string. It has been converted to a string.")),this.Jn(e)&&this.Gn("posthog.identify")){var n=this.get_distinct_id();this.register({$user_id:e}),this.get_property(rr)||this.register_once({$had_persisted_distinct_id:!0,$device_id:n},""),e!==n&&e!==this.get_property(js)&&(this.unregister(js),this.register({distinct_id:e}));var i,o=(this.persistence.get_property(He)||ts)===ts,a=e!==n,l=!a&&o;if(a&&o)this.persistence.set_property(He,Tt),this.setPersonPropertiesForFlags({$set:s||{},$set_once:r||{}},!1),this.capture(oi,{distinct_id:e,$anon_distinct_id:n},{$set:s||{},$set_once:r||{}}),this.Sn=vi(e,s,r),(i=this.featureFlags)==null||i.setAnonymousDistinctId(n);else if(l){this.persistence.set_property(He,Tt);var u=s||{},c=r||{};this.setPersonPropertiesForFlags({$set:u,$set_once:c},!1),this.capture("$set",{$set:u,$set_once:c}),this.Sn=vi(e,s,r)}else(s||r)&&this.setPersonProperties(s,r);a?(this.reloadFeatureFlags(),this.featureFlags?this.featureFlags.resetFlagCallReported():this.unregister(Wt)):l&&(s||r)&&this.reloadFeatureFlags()}}setPersonProperties(e,s){if((e||s)&&this.Gn("posthog.setPersonProperties")){var r=vi(this.get_distinct_id(),e,s);this.Sn!==r?(this.setPersonPropertiesForFlags({$set:e||{},$set_once:s||{}},!0),this.capture("$set",{$set:e||{},$set_once:s||{}}),this.Sn=r):k.info("A duplicate setPersonProperties call was made with the same properties. It has been ignored.")}}unsetPersonProperties(e){var s,r=(L(e)?e:[e]).filter((n=>W(n)&&n.length>0));r.length!==0&&this.Gn("posthog.unsetPersonProperties")&&((s=this.featureFlags)==null||s.unsetPersonPropertiesForFlags(r,!0),this.capture("$set",{$unset:r}),this.Sn=null)}group(e,s,r){if(e&&s){var n=this.getGroups(),i=n[e]!==s;if(i&&this.resetGroupPropertiesForFlags(e),this.register({$groups:w({},n,{[e]:s})}),i||r){var o={$group_type:e,$group_key:s};r&&(o.$group_set=r),this.capture(el,o)}r&&this.setGroupPropertiesForFlags({[e]:r}),i&&!r&&this.reloadFeatureFlags()}else k.error("posthog.group requires a group type and group key")}resetGroups(){this.register({$groups:{}}),this.resetGroupPropertiesForFlags(),this.reloadFeatureFlags()}setPersonPropertiesForFlags(e,s){var r;s===void 0&&(s=!0),(r=this.featureFlags)==null||r.setPersonPropertiesForFlags(e,s)}resetPersonPropertiesForFlags(e){var s;e===void 0&&(e=!0),(s=this.featureFlags)==null||s.resetPersonPropertiesForFlags(e)}setGroupPropertiesForFlags(e,s){var r;s===void 0&&(s=!0),this.Gn("posthog.setGroupPropertiesForFlags")&&((r=this.featureFlags)==null||r.setGroupPropertiesForFlags(e,s))}resetGroupPropertiesForFlags(e){var s;(s=this.featureFlags)==null||s.resetGroupPropertiesForFlags(e)}reset(e){this.Yn(e)}Yn(e,s){var r,n,i,o,a,l,u,c,d,h;if(s===void 0&&(s=!1),k.info("reset"),!this.__loaded)return k.uninitializedWarning("posthog.reset");var p,f=this.get_property(rr),g=this.get_property(ni),m=this.get_property(Vt),_=this.is_capturing();if(this.consent.reset(),s||!_||this.is_capturing()||console.warn("[PostHog.js]","reset() cleared the stored consent, and capturing is now off because of `opt_out_capturing_by_default`. Call opt_in_capturing() again, and prefer calling reset() before opting in rather than after."),(r=this.persistence)==null||r.clear(),(n=this.sessionPersistence)==null||n.clear(),this.yn.clear(),this.Qn(),x(m)||(p=this.persistence)==null||p.register({[Vt]:m}),(i=this.surveys)==null||i.reset(),(o=this.Un)==null||o.stop(),(a=this.featureFlags)==null||a.reset(),(l=this.conversations)==null||l.reset(),(u=this.logs)==null||u.reset(),(c=this.metrics)==null||c.reset(),(d=this.persistence)==null||d.set_property(He,ts),(h=this.sessionManager)==null||h.resetSessionId(),this.Sn=null,this.config.cookieless_mode===ht)this.register_once({distinct_id:Er,$device_id:null},"");else{var b=this.config.get_device_id(dt());this.register_once({distinct_id:b,$device_id:e?b:f},""),e||x(g)||this.register({[ni]: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 s=this;return X((function*(){var r,n,i,o,a,l,u;if(s.__loaded){(r=s.Un)==null||r.stop(),(n=s.jn)==null||n.dispose(),(i=s.sessionRecording)==null||i.dispose(),(o=s.logs)==null||o.flushLogs("sendBeacon"),(a=s.metrics)==null||a.flush("sendBeacon"),(l=s.In)==null||l.unload(),(u=s.Rn)==null||u.unload();try{var c;(c=s.featureFlags)==null||c.destroy()}catch(d){k.error("Error while destroying feature flags",d)}}else k.uninitializedWarning("posthog.shutdown")}))()}setIdentity(e,s){var r;this.config.identity_distinct_id=e,this.config.identity_hash=s,this.alias(e),(r=this.conversations)==null||r.Xn()}clearIdentity(){var e;delete this.config.identity_distinct_id,delete this.config.identity_hash,(e=this.conversations)==null||e.ts()}get_distinct_id(){return this.get_property("distinct_id")}getGroups(){return this.get_property("$groups")||{}}get_session_id(){var e,s;return(e=(s=this.sessionManager)==null?void 0:s.checkAndGetSessionAndWindowId(!0).sessionId)!==null&&e!==void 0?e:""}get_session_replay_url(e){if(!this.sessionManager)return"";var s=this.sessionManager.checkAndGetSessionAndWindowId(!0),r=s.sessionStartTimestamp,n=this.requestRouter.endpointFor("ui","/project/"+this.config.token+"/replay/"+s.sessionId);if(e!=null&&e.withTimestamp&&r){var i,o=(i=e.timestampLookBack)!==null&&i!==void 0?i:10;if(!r)return n;n+="?t="+Math.max(Math.floor((new Date().getTime()-r)/1e3)-o,0)}return n}alias(e,s){return e===this.get_property(lu)?(k.critical("Attempting to create alias for existing People user - aborting."),-2):this.Gn("posthog.alias")?(x(s)&&(s=this.get_distinct_id()),e!==s?(this.Kn(js,e),this.capture("$create_alias",{alias:e,distinct_id:s})):(k.warn("alias matches current distinct_id - skipping api call."),this.identify(e),-1)):void 0}set_config(e){var s=w({},this.config);if(te(e)){var r,n,i,o,a,l,u,c,d,h,p,f;ee(this.config,Al(e));var g=this.En();(r=this.persistence)==null||r.update_config(this.config,s,g),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new di(w({},this.config,{persistence:"sessionStorage"}),g,!1);var m=this.Cn(this.config.debug);Ke(m)&&(this.config.debug=m),Ke(this.config.debug)&&(this.config.debug?(Y.DEBUG=!0,Q.N()&&Q.F("ph_debug",!0),k.info("set_config",{config:e,oldConfig:s,newConfig:w({},this.config)})):(Y.DEBUG=!1,Q.N()&&Q.q("ph_debug"))),(n=this.featureFlags)==null||n.updateConfig==null||n.updateConfig(this.config,this.Qi()),(i=this.exceptionObserver)==null||i.onConfigChange(),(o=this.exceptions)==null||o.onConfigChange(),(a=this.sessionRecording)==null||a.startIfEnabledOrStop(),(l=this.tracingHeaders)==null||l.startIfEnabledOrStop(),(u=this.autocapture)==null||u.startIfEnabled(),(c=this.heatmaps)==null||c.startIfEnabled(),(d=this.exceptionObserver)==null||d.startIfEnabledOrStop(),(h=this.deadClicksAutocapture)==null||h.startIfEnabledOrStop(),(p=this.surveys)==null||p.loadIfEnabled(),this.es(),(f=this.externalIntegrations)==null||f.startIfEnabledOrStop()}}_overrideSDKInfo(e,s){Y.LIB_NAME=e,Y.LIB_VERSION=s}startSessionRecording(e){var s,r,n,i,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)&&((s=this.sessionManager)==null||s.checkAndGetSessionAndWindowId(),l.sampling&&((r=this.sessionRecording)==null||r.overrideSampling()),l.linked_flag&&((n=this.sessionRecording)==null||n.overrideLinkedFlag()),l.url_trigger&&((i=this.sessionRecording)==null||i.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,s){if(this.exceptions){var r=new Error("PostHog syntheticException"),n=this.exceptions.buildProperties(e,{handled:!0,syntheticException:r});return this.exceptions.sendExceptionEvent(w({},n,s))}}addExceptionStep(e,s){var r;(r=this.exceptions)==null||r.addExceptionStep(e,s)}captureLog(e){var s;(s=this.logs)==null||s.captureLog(e)}get logger(){var e,s;return(e=(s=this.logs)==null?void 0:s.logger)!==null&&e!==void 0?e:Te.rs}startExceptionAutocapture(e){this.set_config({capture_exceptions:e==null||e})}stopExceptionAutocapture(){this.set_config({capture_exceptions:!1})}loadToolbar(e){var s,r;return(s=(r=this.toolbar)==null?void 0:r.loadToolbar(e))!==null&&s!==void 0&&s}get_property(e){var s;return(s=this.persistence)==null?void 0:s.props[e]}getSessionProperty(e){var s;return(s=this.sessionPersistence)==null?void 0:s.props[e]}toString(){var e,s=(e=this.config.name)!==null&&e!==void 0?e:as;return s!==as&&(s=as+"."+s),s}_isIdentified(){var e,s;return((e=this.persistence)==null?void 0:e.get_property(He))===Tt||((s=this.sessionPersistence)==null?void 0:s.get_property(He))===Tt}Zn(){var e,s;return!(this.config.person_profiles==="never"||this.config.person_profiles===so&&!this._isIdentified()&&mt(this.getGroups())&&((e=this.persistence)==null||(e=e.props)==null||!e[js])&&((s=this.persistence)==null||(s=s.props)==null||!s[nn]))}zn(){return this.config.capture_pageleave===!0||this.config.capture_pageleave==="if_capture_pageview"&&(this.config.capture_pageview===!0||this.config.capture_pageview==="history_change")}createPersonProfile(){this.Zn()||this.Gn("posthog.createPersonProfile")&&this.setPersonProperties({},{})}setInternalOrTestUser(){this.Gn("posthog.setInternalOrTestUser")&&this.setPersonProperties({$internal_or_test_user:!0})}Gn(e){return this.config.person_profiles==="never"?(k.error(e+' was called, but process_person is set to "never". This call will be ignored.'),!1):(this.Kn(nn,!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!==Ht)}es(){var e,s,r,n,i=this.En();return((e=this.persistence)==null?void 0:e.xi)!==i&&((r=this.persistence)==null||r.set_disabled(i)),((s=this.sessionPersistence)==null?void 0:s.xi)!==i&&((n=this.sessionPersistence)==null||n.set_disabled(i)),i&&(this.yn.clear(),this.Qn()),i}opt_in_capturing(e){var s;if(this.config.cookieless_mode!==ht){if(this.gn()){var r,n,i,o,a;this.Yn(!0,!0),(r=this.sessionManager)==null||r.destroy(),(n=this.pageViewManager)==null||n.destroy(),this.sessionManager=new kl(this),this.pageViewManager=new gl(this),this.persistence&&(this.sessionPropsManager=new xl(this,this.sessionManager,this.persistence));var l,u=(i=(o=this.config.__extensionClasses)==null?void 0:o.sessionRecording)!==null&&i!==void 0?i:(a=Te.__defaultExtensionClasses)==null?void 0:a.sessionRecording;u&&(this.sessionRecording=this.pn(this.sessionRecording,new u(this)),this.hn&&((l=this.sessionRecording)==null||l.onRemoteConfig==null||l.onRemoteConfig(this.hn)))}var c,d;this.consent.optInOut(!0),this.es(),this.Bn(),(s=this.sessionRecording)==null||s.startIfEnabledOrStop(),this.config.cookieless_mode==Ht&&((c=this.surveys)==null||c.loadIfEnabled()),(x(e?.captureEventName)||e!=null&&e.captureEventName)&&this.capture((d=e?.captureEventName)!==null&&d!==void 0?d:"$opt_in",e?.captureProperties,{send_instantly:!0}),this.config.capture_pageview&&this.Hn()}else k.warn(Fl)}opt_out_capturing(){var e,s,r;this.config.cookieless_mode!==ht?(this.config.cookieless_mode===Ht&&this.consent.isOptedIn()&&this.Yn(!0,!0),this.consent.optInOut(!1),this.es(),this.config.cookieless_mode===Ht&&(this.register({distinct_id:Er,$device_id:null}),(e=this.sessionRecording)==null||e.stopRecording(),this.sessionRecording=void 0,(s=this.sessionManager)==null||s.destroy(),(r=this.pageViewManager)==null||r.destroy(),this.sessionManager=void 0,this.sessionPropsManager=void 0,this.config.capture_pageview&&this.Hn(),this.Bn())):k.warn(Fl)}has_opted_in_capturing(){return this.consent.isOptedIn()}has_opted_out_capturing(){return this.consent.isOptedOut()}get_explicit_consent_status(){var e=this.consent.consent;return e===1?"granted":e===0?"denied":"pending"}is_capturing(){return this.config.cookieless_mode===ht||(this.config.cookieless_mode===Ht?this.consent.isRejected()||this.consent.isOptedIn():!this.has_opted_out_capturing())}clear_opt_in_out_capturing(){this.consent.reset(),this.es()}_is_bot(){return ke?ed(ke,this.config.custom_blocked_useragents):void 0}Hn(){C&&(C.visibilityState==="visible"?this.wn||(this.wn=!0,this.capture(os,{title:C.title},{send_instantly:!0}),this.kn&&(C.removeEventListener(on,this.kn),this.kn=null)):this.kn||(this.kn=this.Hn.bind(this),ne(C,on,this.kn)))}debug(e){e===!1?(v?.console.log("You've disabled debug mode."),this.set_config({debug:!1})):(v?.console.log("You're now in debug mode. All calls to PostHog will be logged in your console.\nYou can disable this with `posthog.debug(false)`."),this.set_config({debug:!0}))}Qi(){var e=this.Mn||{};return"advanced_disable_flags"in e?!!e.advanced_disable_flags:this.config.advanced_disable_flags!==!1?!!this.config.advanced_disable_flags:this.config.advanced_disable_decide===!0?(k.warn("Config field 'advanced_disable_decide' is deprecated. Please use 'advanced_disable_flags' instead. The old field will be removed in a future major version."),!0):(function(s,r,n,i,o){var a=r in s&&!D(s[r]),l=n in s&&!D(s[n]);return a?s[r]:!!l&&(o&&o.warn("Config field '"+n+"' is deprecated. Please use '"+r+"' instead. The old field will be removed in a future major version."),s[n])})(e,"advanced_disable_flags","advanced_disable_decide",0,k)}Pt(e){var s;if(D(this.config.before_send))return e;var r=Object.keys((s=e.properties)!==null&&s!==void 0?s:{}).filter(vh),n=L(this.config.before_send)?this.config.before_send:[this.config.before_send],i=e;for(var o of n){if(i=o(i),D(i)){var a="Event '"+e.event+"' was rejected in beforeSend function";return mh(e.event)?k.warn(a+". This can cause unexpected behavior."):k.info(a),null}i.properties&&!mt(i.properties)||k.warn("Event '"+e.event+"' has no properties after beforeSend function, this is likely an error.")}for(var l of r)if(i.properties&&D(i.properties[l]))return k.warn("Event '"+e.event+"' had its '"+l+"' property removed in a beforeSend function. This property is required for ingestion, so the event will be dropped."),null;return i}getPageViewId(){var e;return(e=this.pageViewManager.ui)==null?void 0:e.pageViewId}captureTraceFeedback(e,s){this.capture("$ai_feedback",{$ai_trace_id:String(e),$ai_feedback_text:s})}captureTraceMetric(e,s,r){this.capture("$ai_metric",{$ai_trace_id:String(e),$ai_metric_name:s,$ai_metric_value:String(r)})}Cn(e){var s=Ke(e)&&!e,r=Q.N()&&Q.P("ph_debug")==="true";return!s&&(!!r||e)}}Te.__defaultExtensionClasses={},Te.rs=(()=>{var t=()=>{};return{trace:t,debug:t,info:t,warn:t,error:t,fatal:t}})(),(function(t,e){for(var s=0;e.length>s;s++)t.prototype[e[s]]=ip(t.prototype[e[s]])})(Te,["identify"]);class $l{constructor(e){this.disabled=e===!1;var s=te(e)?e:{};this.thresholdPx=s.threshold_px||30,this.timeoutMs=s.timeout_ms||1e3,this.clickCount=s.click_count||3,this.clicks=[]}isRageClick(e,s,r){if(this.disabled)return!1;var n=this.clicks[this.clicks.length-1];if(n&&Math.abs(e-n.x)+Math.abs(s-n.y)r-n.timestamp){if(this.clicks.push({x:e,y:s,timestamp:r}),this.clicks.length===this.clickCount)return!0}else this.clicks=[{x:e,y:s,timestamp:r}];return!1}}var wi="$copy_autocapture",bi=se("[AutoCapture]");function Ei(t,e){return e.length>t?e.slice(0,t)+"...":e}function uf(t){if(t.previousElementSibling)return t.previousElementSibling;var e=t;do e=e.previousSibling;while(e&&!Ft(e));return e}function df(t,e){var s,r,n=e.e,i=e.maskAllElementAttributes,o=e.maskAllText,a=e.elementAttributeIgnoreList,l=e.elementsChainAsString,u=e.disableCaptureUrlHashes;if(!Ft(t))return{props:{}};for(var c=[t],d=new Set([t]),h=t;h.parentNode&&!Me(h,"body")&&xu>c.length;)if(Su(h.parentNode)){var p=h.parentNode.host;if(d.has(p))break;d.add(p),c.push(p),h=p}else{if(!Ft(h.parentNode)||d.has(h.parentNode))break;d.add(h.parentNode),c.push(h.parentNode),h=h.parentNode}var f,g,m=[],_={},b=!1,E=!1;if(Z(c,(S=>{var A=io(S);if(Me(S,"a")){var R=S.getAttribute("href");b=!!(A&&R&&Js(R))&&(u?Ct(R):R)}M(cn(S),"ph-no-capture")&&(E=!0),m.push((function(T,O,J,z,H){H===void 0&&(H=!1);var oe=T.tagName.toLowerCase(),pe={tag_name:oe};Jo.indexOf(oe)>-1&&!J&&(pe.$el_text=oe.toLowerCase()==="a"||oe.toLowerCase()==="button"?Ei(1024,hl(T)):Ei(1024,nr(T)));var Ie=cn(T);Ie.length>0&&(pe.classes=Ie.filter((function(ae){return ae!==""}))),Z(T.attributes,(function(ae){var me;if((!Pu(T)||["name","id","class","aria-label"].indexOf(ae.name)!==-1)&&(z==null||!z.includes(ae.name))&&!O&&Js(ae.value)&&(!W(me=ae.name)||me.substring(0,10)!=="_ngcontent"&&me.substring(0,7)!=="_nghost")){var ge=ae.value;ae.name==="class"&&(ge=Ko(ge).join(" ")),pe["attr__"+ae.name]=Ei(1024,ae.name==="href"&&H?Ct(ge):ge)}}));for(var _e=1,Ce=1,Re=T;Re=uf(Re);)_e++,Re.tagName===T.tagName&&Ce++;return pe.nth_child=_e,pe.nth_of_type=Ce,pe})(S,i,o,a,u));var N=(function(T){if(!io(T))return{};var O={};return Z(T.attributes,(function(J){if(J.name&&J.name.indexOf("data-ph-capture-attribute")===0){var z=J.name.replace("data-ph-capture-attribute-",""),H=J.value;z&&H&&Js(H)&&(O[z]=H)}})),O})(S);ee(_,N)})),E)return{props:{},explicitNoCapture:E};if(o||(m[0].$el_text=Me(t,"a")||Me(t,"button")?hl(t):nr(t)),b){var I,F;m[0].attr__href=b;var P=(I=un(b))==null?void 0:I.host,B=v==null||(F=v.location)==null?void 0:F.host;P&&B&&P!==B&&(f=b)}return{props:ee({$event_type:n.type,$ce_version:1},l?{}:{$elements:m},{$elements_chain:(g=m,(function(S){return S.map((A=>{var R,N,T="";if(A.tag_name&&(T+=A.tag_name),A.attr_class)for(var O of(A.attr_class.sort(),A.attr_class))T+="."+O.replace(/"/g,"");var J=w({},A.text?{text:A.text}:{},{"nth-child":(R=A.nth_child)!==null&&R!==void 0?R:0,"nth-of-type":(N=A.nth_of_type)!==null&&N!==void 0?N:0},A.href?{href:A.href}:{},A.attr_id?{attr_id:A.attr_id}:{},A.attributes),z={};return Dr(J).sort(((H,oe)=>H[0].localeCompare(oe[0]))).forEach((H=>{var oe=H[1];return z[pl(H[0].toString())]=pl(oe.toString())})),(T+=":")+Dr(z).map((H=>H[0]+'="'+H[1]+'"')).join("")})).join(";")})((function(S){return S.map((A=>{var R,N,T={text:(R=A.$el_text)==null?void 0:R.slice(0,400),tag_name:A.tag_name,href:(N=A.attr__href)==null?void 0:N.slice(0,2048),attr_class:xp(A),attr_id:A.attr__id,nth_child:A.nth_child,nth_of_type:A.nth_of_type,attributes:{}};return Dr(A).filter((O=>O[0].indexOf("attr__")===0)).forEach((O=>T.attributes[O[0]]=O[1])),T}))})(g)))},(s=m[0])!=null&&s.$el_text?{$el_text:(r=m[0])==null?void 0:r.$el_text}:{},f&&n.type==="click"?{$external_click_url:f}:{},_)}}var Ls=se("[ExceptionAutocapture]"),Rl=()=>{},hf=se("[TracingHeaders]"),Lt=se("[Web Vitals]"),Tl=9e5,Nl="disabled",Ml="lazy_loading",Os="awaiting_config",Pr="missing_config";se("[SessionRecording]"),se("[SessionRecording]");var fo="[SessionRecording]",at=se(fo),pf=se("[Heatmaps]");function Si(t){return te(t)&&"clientX"in t&&"clientY"in t&&he(t.clientX)&&he(t.clientY)}var Ar=se("[Product Tours]"),xi=t=>{var e;return!t.config.disable_product_tours&&!((e=t.persistence)==null||!e.get_property(zo))},ff=["$set_once","$set"],Ze=se("[SiteApps]"),Ll="Error while initializing PostHog app with config id ";function ns(t,e,s){if(D(t))return!1;switch(s){case"exact":return t===e;case"contains":var r=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/_/g,".").replace(/%/g,".*");return new RegExp(r,"i").test(t);case"regex":try{return new RegExp(e).test(t)}catch{return!1}default:return!1}}class gf{constructor(e){this.ns=new Qo,this.ss=(s,r)=>this.os(s,r)&&this.ls(s,r)&&this.us(s,r)&&this.hs(s,r),this.os=(s,r)=>r==null||!r.event||s?.event===r?.event,this._instance=e,this.ds=new Set,this.vs=new Set}init(){var e,s;x((e=this._instance)==null?void 0:e._addCaptureHook)||(s=this._instance)==null||s._addCaptureHook(((r,n)=>{this.on(r,n)}))}register(e){var s,r;if(!x((s=this._instance)==null?void 0:s._addCaptureHook)&&(e.forEach((o=>{var a,l;(a=this.vs)==null||a.add(o),(l=o.steps)==null||l.forEach((u=>{var c;(c=this.ds)==null||c.add(u?.event||"")}))})),(r=this._instance)!=null&&r.autocapture)){var n,i=new Set;e.forEach((o=>{var a;(a=o.steps)==null||a.forEach((l=>{l!=null&&l.selector&&i.add(l?.selector)}))})),(n=this._instance)==null||n.autocapture.setElementSelectors(i)}}on(e,s){var r;s!=null&&e.length!=0&&(this.ds.has(e)||this.ds.has(s.event))&&this.vs&&((r=this.vs)==null?void 0:r.size)>0&&this.vs.forEach((n=>{this.cs(s,n)&&this.ns.emit("actionCaptured",n.name)}))}fs(e){this.onAction("actionCaptured",(s=>e(s)))}cs(e,s){if(s?.steps==null)return!1;for(var r of s.steps)if(this.ss(e,r))return!0;return!1}onAction(e,s){return this.ns.on(e,s)}ls(e,s){if(s!=null&&s.url){var r,n=e==null||(r=e.properties)==null?void 0:r.$current_url;if(!n||typeof n!="string"||!ns(n,s.url,s.url_matching||"contains"))return!1}return!0}us(e,s){return!!this.ps(e,s)&&!!this.gs(e,s)&&!!this.ys(e,s)}ps(e,s){var r;if(s==null||!s.href)return!0;var n=this.bs(e);if(n.length>0)return n.some((a=>ns(a.href,s.href,s.href_matching||"exact")));var i,o=(e==null||(r=e.properties)==null?void 0:r.$elements_chain)||"";return!!o&&ns((i=o.match(/(?::|")href="(.*?)"/))?i[1]:"",s.href,s.href_matching||"exact")}gs(e,s){var r;if(s==null||!s.text)return!0;var n=this.bs(e);if(n.length>0)return n.some((u=>ns(u.text,s.text,s.text_matching||"exact")||ns(u.$el_text,s.text,s.text_matching||"exact")));var i,o,a,l=(e==null||(r=e.properties)==null?void 0:r.$elements_chain)||"";return!!l&&(i=(function(u){for(var c,d=[],h=/(?::|")text="(.*?)"/g;!D(c=h.exec(u));)d.includes(c[1])||d.push(c[1]);return d})(l),o=s.text,a=s.text_matching||"exact",i.some((u=>ns(u,o,a))))}ys(e,s){var r,n;if(s==null||!s.selector)return!0;var i=e==null||(r=e.properties)==null?void 0:r.$element_selectors;if(i!=null&&i.includes(s.selector))return!0;var o=(e==null||(n=e.properties)==null?void 0:n.$elements_chain)||"";if(s.selector_regex&&o)try{return new RegExp(s.selector_regex).test(o)}catch{return!1}return!1}bs(e){var s;return(e==null||(s=e.properties)==null?void 0:s.$elements)==null?[]:e?.properties.$elements}hs(e,s){return s==null||!s.properties||s.properties.length===0||rd(s.properties.reduce(((r,n)=>{var i=L(n.value)?n.value.map(String):n.value!=null?[String(n.value)]:[];return r[n.key]={values:i,operator:n.operator||"exact"},r}),{}),e?.properties)}}class mf{constructor(e){var s;this._s=[],this._instance=e,this.ws=new Map,this.ks=new Map,this.xs=new Map,(s=this._instance)==null||s.onSessionId==null||s.onSessionId((r=>this.Ss(r)))}Cs(e){return!1}Ms(){return null}Ts(e){}Es(){}Is(e,s){return!!e&&rd(e.propertyFilters,s?.properties)}Ps(e,s){var r=new Map;return e.forEach((n=>{var i;(i=n.conditions)==null||(i=i[s])==null||(i=i.values)==null||i.forEach((o=>{if(o!=null&&o.name){var a=r.get(o.name)||[];a.push(n.id),r.set(o.name,a)}}))})),r}Rs(e,s,r){var n=(r===$s.Activation?this.ws:this.ks).get(e),i=[];return this.As((o=>{i=o.filter((a=>n?.includes(a.id)))})),i.filter((o=>{var a,l=(a=o.conditions)==null||(a=a[r])==null||(a=a.values)==null?void 0:a.find((u=>u.name===e));return this.Is(l,s)}))}register(e){var s;x((s=this._instance)==null?void 0:s._addCaptureHook)||(this.Fs(e),this.Ls(e))}Ls(e){var s=e.filter((r=>{var n,i;return((n=r.conditions)==null?void 0:n.actions)&&((i=r.conditions)==null||(i=i.actions)==null||(i=i.values)==null?void 0:i.length)>0}));s.length!==0&&(this.Os==null&&(this.Os=new gf(this._instance),this.Os.init(),this.Os.fs((r=>{this.onAction(r)}))),s.forEach((r=>{var n,i,o,a,l;r.conditions&&(n=r.conditions)!=null&&n.actions&&(i=r.conditions)!=null&&(i=i.actions)!=null&&i.values&&((o=r.conditions)==null||(o=o.actions)==null||(o=o.values)==null?void 0:o.length)>0&&((a=this.Os)==null||a.register(r.conditions.actions.values),(l=r.conditions)==null||(l=l.actions)==null||(l=l.values)==null||l.forEach((u=>{if(u&&u.name){var c=this.xs.get(u.name);c&&c.push(r.id),this.xs.set(u.name,c||[r.id])}})))})))}Fs(e){var s,r=e.filter((i=>{var o,a;return((o=i.conditions)==null?void 0:o.events)&&((a=i.conditions)==null||(a=a.events)==null||(a=a.values)==null?void 0:a.length)>0})),n=e.filter((i=>{var o,a;return((o=i.conditions)==null?void 0:o.cancelEvents)&&((a=i.conditions)==null||(a=a.cancelEvents)==null||(a=a.values)==null?void 0:a.length)>0}));r.length===0&&n.length===0||((s=this._instance)==null||s._addCaptureHook(((i,o)=>{this.onEvent(i,o)})),this.ws=this.Ps(e,$s.Activation),this.ks=this.Ps(e,$s.Cancellation))}onEvent(e,s){var r,n,i=this.Ds(),o=(s==null||(r=s.properties)==null?void 0:r.$survey_id)||(s==null||(n=s.properties)==null?void 0:n.$product_tour_id);if(o&&this.getActivatedIds().includes(o)){var a=this.$s(e,o);if(a==="consume")return i.info("event consumed activated item, removing it",{event:e,itemId:o}),void this.Ns([o]);if(a==="persist")return i.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,s,$s.Cancellation);l.length>0&&(i.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)){i.info("event name matched",{event:e,eventPayload:s,items:this.ws.get(e)});var u=this.Rs(e,s,$s.Activation);this.Hs(u.map((c=>c.id)))}}onAction(e){this.xs.has(e)&&this.Hs(this.xs.get(e)||[])}Hs(e){var s;if(e.length!==0){var r=!((s=this._instance)==null||s.get_session_id==null||!s.get_session_id()),n=[];for(var i of e)r&&this.Cs(i)?this.qs(i)&&this.Us(i):n.push(i);n.length>0&&(this._s=[...new Set([...this._s,...n])]),this.Ds().info("updating activated items",{activatedItems:this.getActivatedIds()})}}qs(e){this._s=this._s.filter((r=>r!==e));var s=this.zs();return!s.includes(e)&&(this.Ws([...s,e]),this.Vs(),!0)}Ns(e){var s=new Set(e);this._s=this._s.filter((i=>!s.has(i)));var r=this.Zs(),n=r.filter((i=>!s.has(i)));n.length!==r.length&&(this.Ws(n),n.length===0&&this.Gs()),this.js(e)}Qs(){var e,s=this.Ms();if(!s)return{};var r=(e=this._instance)==null||(e=e.persistence)==null?void 0:e.props[s];return r&&typeof r=="object"?r:{}}Us(e){if(this.Ms()){var s=this.Qs();this.Ts(w({},s,{[e]:Date.now()}))}}js(e){if(this.Ms()){var s=this.Qs(),r={},n=!1;for(var i of Object.entries(s)){var o=i[0],a=i[1];e.includes(o)?n=!0:r[o]=a}n&&(mt(r)?this.Es():this.Ts(r))}}Ks(){this.Ms()&&this.Es()}getActivationTimestamp(e){if(this.zs().includes(e)){var s=this.Qs()[e];return he(s)?s:void 0}}Zs(){var e,s=this.Js();return((e=this._instance)==null||(e=e.persistence)==null?void 0:e.props[s])||[]}zs(){var e,s,r=this.Zs();if(r.length===0)return[];var n=(e=this._instance)==null||(e=e.persistence)==null?void 0:e.props[this.Ys()],i=(s=this._instance)==null||s.get_session_id==null?void 0:s.get_session_id();return i&&n===i?r:[]}Vs(){var e,s=(e=this._instance)==null||e.get_session_id==null?void 0:e.get_session_id();s&&this.Xs(s)}Gs(){this.ta()}Ss(e){var s,r=(s=this._instance)==null||(s=s.persistence)==null?void 0:s.props[this.Ys()];if(r&&r!==e){var n=this.Zs(),i=this.Qs();n.length>0&&(this.Ws([]),n.filter((o=>he(i[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 vf extends mf{constructor(e){super(e)}Js(){return Zi}Ys(){return Mr}Ms(){return Lr}Ts(e){var s;(s=this._instance)==null||(s=s.persistence)==null||s.register({[Lr]:e})}Es(){var e;(e=this._instance)==null||(e=e.persistence)==null||e.unregister(Lr)}Cs(e){var s,r;this.As((i=>{r=i.find((o=>o.id===e))}));var n=(s=r)==null||(s=s.appearance)==null?void 0:s.surveyPopupDelaySeconds;return he(n)&&n>0}ra(){return ft.SHOWN}As(e){var s;(s=this._instance)==null||s.getSurveys(e)}Bs(e){var s;(s=this._instance)==null||s.cancelPendingSurvey(e)}Ds(){return q}Ws(e){var s;(s=this._instance)==null||(s=s.persistence)==null||s.register({[Zi]:e})}Xs(e){var s;(s=this._instance)==null||(s=s.persistence)==null||s.register({[Mr]:e})}ta(){var e;(e=this._instance)==null||(e=e.persistence)==null||e.unregister(Mr)}ea(){return!1}$s(e,s){var r;this.As((i=>{r=i.find((o=>o.id===s))}));var n=!r||(function(i){var o;return nd(i)&&!((o=i.conditions)==null||(o=o.events)==null||!o.repeatedActivation)||i.schedule==="always"})(r);return n?e===ft.SHOWN?"consume":"ignore":e===ft.SHOWN?"persist":e===ft.DISMISSED||e===ft.SENT?"consume":"ignore"}getSurveys(){return this.getActivatedIds()}getEventToSurveys(){return this.getEventToItemsMap()}}var $r="SDK is not enabled or survey functionality is not yet loaded",Ol="Disabled. Not loading surveys.",_f=v!=null&&v.location?dn(v.location.hash,"__posthog")||dn(location.hash,"state"):null,Dl="_postHogToolbarParams",Bl=se("[Toolbar]"),jl=se("[FeatureFlags]");class yf{constructor(e,s){s===void 0&&(s=!1),this.na=!1,this.update(e,s)}update(e,s){this.sa=((r,n)=>{var i,o,a,l;return{bootstrap:{featureFlags:(i=r.bootstrap)==null?void 0:i.featureFlags,featureFlagPayloads:(o=r.bootstrap)==null?void 0:o.featureFlagPayloads},remoteRequestsDisabled:n,featureFlagsDisabled:!!r.advanced_disable_feature_flags,onlyEvaluateSurveyFeatureFlags:!!r.advanced_only_evaluate_survey_feature_flags,deduplicateCallsPerSession:!!r.advanced_feature_flags_dedup_per_session,cacheTtlMs:r.feature_flag_cache_ttl_ms,requestTimeoutMs:r.feature_flag_request_timeout_ms,compression:r.disable_compression?"none":"base64",evaluationContexts:(a=(l=r.evaluation_contexts)!==null&&l!==void 0?l:r.evaluation_environments)!==null&&a!==void 0?a:[],flagKeys:L(r.flag_keys)?r.flag_keys:void 0}})(e,s),!e.evaluation_environments||e.evaluation_contexts||this.na||(jl.warn("evaluation_environments is deprecated. Use evaluation_contexts instead. evaluation_environments will be removed in a future version."),this.na=!0),x(e.flag_keys)||L(e.flag_keys)||jl.error("Invalid flag_keys found:",e.flag_keys,"Expected array of non-empty strings")}get(){return this.sa}}var Ul=se("[FeatureFlags]"),Ot=se("[FeatureFlags]",{debugEnabled:!0}),ki=`" failed. Feature flags didn't load in time.`,Hl="connection_error",Wl=t=>{for(var e={},s=0;t.length>s;s++)e[t[s]]=!0;return e},zl=t=>{var e={};for(var s of Dr(t||{})){var r=s[1];r&&(e[s[0]]=r)}return e},Xe=se("[Error tracking]"),ql="Refusing to render web experiment since the viewer is a likely bot",wf={icontains:(t,e)=>e.toLowerCase().indexOf(t.toLowerCase())>-1,not_icontains:(t,e)=>e.toLowerCase().indexOf(t.toLowerCase())===-1,regex:(t,e)=>fn(e,t),not_regex:(t,e)=>!fn(e,t),exact:(t,e)=>e===t,is_not:(t,e)=>e!==t};class ye{get Ne(){return this._instance.config}constructor(e){var s=this;this.getWebExperimentsAndEvaluateDisplayLogic=function(r){r===void 0&&(r=!1),s.getWebExperiments((n=>{ye.aa("retrieved web experiments from the server"),s.oa=new Map,n.forEach((i=>{if(i.feature_flag_key){var o;s.oa&&(ye.aa("setting flag key ",i.feature_flag_key," to web experiment ",i),(o=s.oa)==null||o.set(i.feature_flag_key,i));var a=s._instance.getFeatureFlag(i.feature_flag_key);W(a)&&i.variants[a]&&s.la(i.name,a,i.variants[a].transforms)}else if(i.variants)for(var l in i.variants){var u=i.variants[l];ye.ua(u,s._instance)&&s.la(i.name,l,u.transforms)}}))}),r)},this._instance=e,this._instance.onFeatureFlags((r=>{this.onFeatureFlags(r)}))}initialize(){}onFeatureFlags(e){if(this._is_bot())ye.aa(ql);else if(!this.Ne.disable_web_experiments){if(D(this.oa))return this.oa=new Map,this.loadIfEnabled(),void this.previewWebExperiment();ye.aa("applying feature flags",e),e.forEach((s=>{var r;if(this.oa&&(r=this.oa)!=null&&r.has(s)){var n,i=this._instance.getFeatureFlag(s),o=(n=this.oa)==null?void 0:n.get(s);i&&o!=null&&o.variants[i]&&this.la(o.name,i,o.variants[i].transforms)}}))}}previewWebExperiment(){var e=ye.getWindowLocation();if(e!=null&&e.search){var s=vs(e?.search,"__experiment_id"),r=vs(e?.search,"__experiment_variant");s&&r&&(ye.aa("previewing web experiments "+s+" && "+r),this.getWebExperiments((n=>{this.ha(parseInt(s),r,n)}),!1,!0))}}loadIfEnabled(){this.Ne.disable_web_experiments||this.getWebExperimentsAndEvaluateDisplayLogic()}getWebExperiments(e,s,r){if(this.Ne.disable_web_experiments&&!r)return e([]);var n=this._instance.get_property("$web_experiments");if(n&&!s)return e(n);this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/web_experiments/?token="+this.Ne.token),method:"GET",timestampMode:"query",callback:i=>e(i.statusCode===200&&i.json&&i.json.experiments||[])})}ha(e,s,r){var n=r.filter((i=>i.id===e));n&&n.length>0&&(ye.aa("Previewing web experiment ["+n[0].name+"] with variant ["+s+"]"),this.la(n[0].name,s,n[0].variants[s].transforms))}static ua(e,s){return!D(e.conditions)&&ye.da(e,s)&&ye.va(e)}static da(e,s){var r;if(D(e.conditions)||D((r=e.conditions)==null?void 0:r.url))return!0;var n=ye.getWindowLocation();if(n){var i,o,a,l=wu(s,n.href);return(i=e.conditions)==null||!i.url||wf[(o=(a=e.conditions)==null?void 0:a.urlMatchType)!==null&&o!==void 0?o:"icontains"](e.conditions.url,l)}return!1}static getWindowLocation(){return v?.location}static va(e){var s;if(D(e.conditions)||D((s=e.conditions)==null?void 0:s.utm))return!0;var r=Mu();if(r.utm_source){var n,i,o,a,l,u,c,d,h=(n=e.conditions)==null||(n=n.utm)==null||!n.utm_campaign||((i=e.conditions)==null||(i=i.utm)==null?void 0:i.utm_campaign)==r.utm_campaign,p=(o=e.conditions)==null||(o=o.utm)==null||!o.utm_source||((a=e.conditions)==null||(a=a.utm)==null?void 0:a.utm_source)==r.utm_source,f=(l=e.conditions)==null||(l=l.utm)==null||!l.utm_medium||((u=e.conditions)==null||(u=u.utm)==null?void 0:u.utm_medium)==r.utm_medium,g=(c=e.conditions)==null||(c=c.utm)==null||!c.utm_term||((d=e.conditions)==null||(d=d.utm)==null?void 0:d.utm_term)==r.utm_term;return h&&f&&g&&p}return!1}static aa(e){for(var s=arguments.length,r=new Array(s>1?s-1:0),n=1;s>n;n++)r[n-1]=arguments[n];k.info("[WebExperiments] "+e,r)}la(e,s,r){this._is_bot()?ye.aa(ql):s!=="control"?r.forEach((n=>{if(n.selector){var i;ye.aa("applying transform of variant "+s+" for experiment "+e+" ",n);var o=(i=document)==null?void 0:i.querySelectorAll(n.selector);o?.forEach((a=>{var l=a;n.html&&(l.innerHTML=n.html),n.css&&l.setAttribute("style",n.css)}))}})):ye.aa("Control variants leave the page unmodified.")}_is_bot(){return ke&&this._instance?ed(ke,this.Ne.custom_blocked_useragents):void 0}}var Ue=se("[Conversations]"),Dt="Conversations not available yet.",Vl="console",cd="__posthogHandledLogsRequestError",Ii=(t,e)=>{var s=t instanceof Error?t:new Error(e);return s[cd]=!0,s},Gl=t=>!!t&&typeof t=="object"&&t[cd]===!0,Tn={featureFlags:class{constructor(t){this.name="featureFlags",this.ca=!1,this.featureFlagEventHandlers=[],this.rt=Ul,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 yf(t.config,t.Qi()),this.Ta=this.Ea)}updateConfig(t,e){var s;(s=this.Ea)==null||s.update(t,e)}setup(t){return this.Ia=t,this.rt=t.logger.createLogger("[FeatureFlags]"),s=()=>{this.Ia===t&&(this.Ia=void 0,this.nn=t,this.Pa(t))},(e=t.kv.initialize())!=null&&e.then?e.then(s):s();var e,s}Pa(t){if(this.nn===t)return v&&ne(v,"online",this.Ca),this.Ra=t.registerDynamicEventProperties((()=>this.Aa()?this.fa:this.pa)),this.Fa(),this.initialize()}destroy(){v?.removeEventListener("online",this.Ca)}dispose(){var t;this.ba++,this.wa=!1,this.Ia=void 0,this.nn&&(this.La(),(t=this.Ra)==null||t.dispose(),this.Ra=void 0,this.ga=[],v?.removeEventListener("online",this.Ca),this.nn=void 0)}get Ne(){return this.Ta.get()}Oa(t){var e;return(e=this.nn)==null?void 0:e.kv.get(t)}F(t){this.Da((()=>{var e;return(e=this.nn)==null?void 0:e.kv.set(t)}))}q(t){this.Da((()=>{var e;return(e=this.nn)==null?void 0:e.kv.remove(t)}))}Da(t){try{t()}catch(e){this.rt.error("Failed to update feature flag persistence",e)}}Fa(){var t={};for(var e of[Hs,Ws,Nr,et]){var s=this.Oa(e);x(s)||(t[e]=s)}this.fa=t;var r=w({},t),n=this.Oa(Bt);if(n)for(var i of Object.entries(n))r["$feature/"+i[0]]=i[1];this.pa=r}Aa(){var t=this.Ne.cacheTtlMs;if(!t||0>=t)return!1;var e=this.Oa(Ks);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 s=e&&typeof e=="string"&&e.trim().length>0;return s||this.rt.error("Invalid evaluation context found:",e,"Expected non-empty string"),s})):[]}qa(){var t=this.Ne.flagKeys;if(!x(t))return t.filter((e=>{var s=e&&typeof e=="string"&&e.trim().length>0;return s||this.rt.error("Invalid flag key found:",e,"Expected non-empty string"),s}))}initialize(){var t,e,s=this.Ne,r=(t=(e=s.bootstrap)==null?void 0:e.featureFlags)!==null&&t!==void 0?t:{};if(Object.keys(r).length){var n,i,o=(n=(i=s.bootstrap)==null?void 0:i.featureFlagPayloads)!==null&&n!==void 0?n:{},a=Object.keys(r).filter((u=>!!r[u])).reduce(((u,c)=>(u[c]=r[c]||!1,u)),{}),l=Object.keys(o).filter((u=>a[u])).reduce(((u,c)=>(o[c]&&(u[c]=o[c]),u)),{});return this.ja({featureFlags:a,featureFlagPayloads:l})}}updateFlags(t,e,s){var r,n,i=s!=null&&s.merge&&(r=this.Oa(Bt))!==null&&r!==void 0?r:{},o=s!=null&&s.merge&&(n=this.Oa(Ws))!==null&&n!==void 0?n:{},a=w({},i,t),l=w({},o,e),u={};for(var c of Object.entries(a)){var d=c[0],h=c[1];u[d]={key:d,enabled:Ba(h),variant:ja(h),reason:void 0,metadata:x(l?.[d])?void 0:{id:0,version:void 0,description:void 0,payload:l[d]}}}this.ja({flags:u})}get hasLoadedFlags(){return this.ma}getFlags(){return Object.keys(this.getFlagVariants())}getFlagsWithDetails(){var t=this.Oa(Ji),e=this.Oa(et),s=this.Oa(jt);if(!s&&!e)return t||{};var r=ee({},t||{}),n=[...new Set([...Object.keys(s||{}),...Object.keys(e||{})])];for(var i of n){var o,a,l=r[i],u=e?.[i],c=x(u)?(o=l?.enabled)!==null&&o!==void 0&&o:!!u,d=x(u)?l?.variant:typeof u=="string"?u:void 0,h=s?.[i],p=w({},l,{enabled:c,variant:c?d??l?.variant:void 0});c!==l?.enabled&&(p.original_enabled=l?.enabled),d!==l?.variant&&(p.original_variant=l?.variant),h&&(p.metadata=w({},l?.metadata,{payload:h,original_payload:l==null||(a=l.metadata)==null?void 0:a.payload})),r[i]=p}return this.ca||(this.rt.warn(" Overriding feature flag details!",{flagDetails:t,overriddenPayloads:s,finalDetails:r}),this.ca=!0),r}getAllFeatureFlags(){var t=this.getFlagVariants(),e=this.getFlagPayloads();return Object.keys(t).map((s=>{var r=t[s];return{key:s,enabled:Ba(r),variant:ja(r),payload:Da(e[s])}}))}getFlagVariants(){var t=this.Oa(Bt),e=this.Oa(et);if(!e)return t||{};for(var s=ee({},t||{}),r=Object.keys(e),n=0;r.length>n;n++)s[r[n]]=e[r[n]];return this.ca||(this.rt.warn(" Overriding feature flags!",{enabledFlags:t,overriddenFlags:e,finalFlags:s}),this.ca=!0),s}getFlagPayloads(){var t=this.Oa(Ws),e=this.Oa(jt);if(!e)return t||{};for(var s=ee({},t||{}),r=Object.keys(e),n=0;r.length>n;n++)s[r[n]]=e[r[n]];return this.ca||(this.rt.warn(" Overriding feature flag payloads!",{flagPayloads:t,overriddenPayloads:e,finalPayloads:s}),this.ca=!0),s}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(Wt)}Ha(t){this.La();var e=this.nn;if(e&&!this.Ne.remoteRequestsDisabled&&!this.Ma())if(this.ya)this.wa=!0;else{var s={token:e.projectToken,distinct_id:e.distinctId,groups:e.groups,$anon_distinct_id:this.$anon_distinct_id,person_properties:w({},e.initialPersonProperties,this.Oa(ct)||{},{$lib:e.library.name,$lib_version:e.library.version}),group_properties:this.Oa(Ut),timezone:Uu()};x(e.deviceId)||(s.$device_id=e.deviceId),(t!=null&&t.disableFlags||this.Ne.featureFlagsDisabled)&&(s.disable_flags=!0);var r=this.Na();r.length&&(s.evaluation_contexts=r);var n=this.qa();x(n)||(s.flag_keys=n);var i=this.Ne.onlyEvaluateSurveyFeatureFlags,o="/flags/?v=2"+(i?"&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({[Or]:[Hl]}),this.rt.error("Feature flag request failed",c)),l()};try{e.sendRequest(o,{target:"flags",method:"POST",body:s,compression:this.Ne.compression==="base64"?xe.Base64:void 0,sentAt:"body",timeoutMs:this.Ne.requestTimeoutMs}).then((c=>{var d,h,p=(d=c.json)!==null&&d!==void 0?d:{},f=c.statusCode!==200;if(this.ya=!1,a===this.ba){if(this.Ua(c.statusCode),f||this.wa||(this.$anon_distinct_id=void 0),!s.disable_flags||this.wa){this.ka=!f;var g=[];c.error?g.push(c.error instanceof Error&&c.error.name==="AbortError"?"timeout":c.error instanceof Error?Hl:"unknown_error"):c.statusCode!==200&&g.push("api_error_"+c.statusCode),p.errorsWhileComputingFlags&&g.push("errors_while_computing_flags");var m=!((h=p.quotaLimited)==null||!h.includes("feature_flags"));m&&g.push("quota_limited"),this.F({[Or]: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."):s.disable_flags||this.ja(p,f,{partialResponse:i}),l()}}else l()})).catch(u)}catch(c){u(c)}}}Ma(){return Tu(this.Sa,3)}Ua(t){this.Sa=Nu(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 s;if(e===void 0&&(e={}),!e.fresh||this.ka)if(this.ma||this.getFlags()&&this.getFlags().length>0){if(!this.$a()){var r=this.getFeatureFlagResult(t,e);return(s=r?.variant)!==null&&s!==void 0?s:r?.enabled}}else this.rt.warn('getFeatureFlag for key "'+t+ki)}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 s,r=this.getFlagVariants(),n=t in r,i=r[t],o=this.getFlagPayloads()[t],a=String(i),l=this.Oa(Nr)||void 0,u=this.Oa(Ks)||void 0,c=this.Oa(Wt)||{};if(this.Ne.deduplicateCallsPerSession){var d,h=(d=this.nn)==null?void 0:d.session.sessionId,p=this.Oa(qs);h&&h!==p&&(c={},s=h)}if(e.send_event||!("send_event"in e))if(t in c&&c[t].includes(a))s&&this.F({[Wt]:c,[qs]:s});else{var f,g,m,_,b,E,I,F,P,B;L(c[t])?c[t].push(a):c[t]=[a],this.F(w({[Wt]:c},s?{[qs]:s}:{}));var S=this.getFeatureFlagDetails(t),A=[...(f=this.Oa(Or))!==null&&f!==void 0?f:[]];x(i)&&A.push("flag_missing");var R={$feature_flag:t,$feature_flag_response:i,$feature_flag_payload:o||null,$feature_flag_request_id:l,$feature_flag_evaluated_at:u,$feature_flag_bootstrapped_response:((g=this.Ne.bootstrap)==null||(g=g.featureFlags)==null?void 0:g[t])||null,$feature_flag_bootstrapped_payload:((m=this.Ne.bootstrap)==null||(m=m.featureFlagPayloads)==null?void 0:m[t])||null,$used_bootstrap_value:!this.ka};x(S==null||(_=S.metadata)==null?void 0:_.has_experiment)||(R.$feature_flag_has_experiment=S.metadata.has_experiment),x(S==null||(b=S.metadata)==null?void 0:b.version)||(R.$feature_flag_version=S.metadata.version);var N,T=(E=S==null||(I=S.reason)==null?void 0:I.description)!==null&&E!==void 0?E:S==null||(F=S.reason)==null?void 0:F.code;T&&(R.$feature_flag_reason=T),S!=null&&(P=S.metadata)!=null&&P.id&&(R.$feature_flag_id=S.metadata.id),x(S?.original_variant)&&x(S?.original_enabled)||(R.$feature_flag_original_response=x(S.original_variant)?S.original_enabled:S.original_variant),S!=null&&(B=S.metadata)!=null&&B.original_payload&&(R.$feature_flag_original_payload=S==null||(N=S.metadata)==null?void 0:N.original_payload),A.length&&(R.$feature_flag_error=A.join(",")),this.za(R)}else s&&this.F({[Wt]:c,[qs]:s});if(n)return{key:t,enabled:!!i,variant:typeof i=="string"?i:void 0,payload:Da(o)}}}else this.rt.warn('getFeatureFlagResult for key "'+t+ki)}za(t){try{var e;(e=this.nn)==null||e.capture("$feature_flag_called",t).catch((s=>{this.rt.error("Failed to capture feature flag call",s)}))}catch(s){this.rt.error("Failed to capture feature flag call",s)}}getRemoteConfigPayload(t,e){this.Wa(t,e)}Wa(t,e){var s=this;return X((function*(){var r=s.nn;if(r){var n={distinct_id:r.distinctId,token:r.projectToken,person_properties:{$lib:r.library.name,$lib_version:r.library.version}},i=s.Na();i.length&&(n.evaluation_contexts=i);var o,a=s.qa();x(a)||(n.flag_keys=a);try{var l,u=(l=(yield r.sendRequest("/flags/?v=2",{target:"flags",method:"POST",body:n,compression:s.Ne.compression==="base64"?xe.Base64:void 0,sentAt:"body",timeoutMs:s.Ne.requestTimeoutMs})).json)==null?void 0:l.featureFlagPayloads;o=u?.[t]||void 0}catch(c){return void s.rt.error("Remote config feature flag request failed",c)}try{e(o)}catch(c){s.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+ki),e.defaultValue;var s=this.getFeatureFlag(t,e);return x(s)?e.defaultValue:!!s}addFeatureFlagsHandler(t){this.featureFlagEventHandlers.push(t)}removeFeatureFlagsHandler(t){this.featureFlagEventHandlers=this.featureFlagEventHandlers.filter((e=>e!==t))}receivedFeatureFlags(t,e,s){this.ja(t,e,s)}ja(t,e,s){if(this.nn){this.ma=!0;var r=(function(n,i,o,a,l,u){i===void 0&&(i={}),o===void 0&&(o={}),a===void 0&&(a={}),u===void 0&&(u=Ul);var c=((P,B)=>{var S=P.flags;return S?w({},P,{featureFlags:Object.fromEntries(Object.keys(S).map((A=>{var R;return[A,(R=S[A].variant)!==null&&R!==void 0?R:S[A].enabled]}))),featureFlagPayloads:Object.fromEntries(Object.keys(S).filter((A=>S[A].enabled)).filter((A=>{var R;return(R=S[A].metadata)==null?void 0:R.payload})).map((A=>{var R;return[A,(R=S[A].metadata)==null?void 0:R.payload]})))}):(P.featureFlags&&B.warn("Using an older version of the feature flags endpoint. Please upgrade your PostHog server to the latest version"),P)})(n,u),d=c.flags,h=c.featureFlags,p=c.featureFlagPayloads;if(h){var f=n.requestId,g=n.evaluatedAt;if(L(h)){u.warn("v1 of the feature flags endpoint is deprecated. Please use the latest version.");var m={};if(h)for(var _=0;h.length>_;_++)m[h[_]]=!0;return{[Hs]:h,[Bt]:m,[tn]:!1}}var b=h,E=p,I=d;if(l!=null&&l.partialResponse)b=w({},i,b),E=w({},o,E),I=w({},a,I);else if(n.errorsWhileComputingFlags)if(d){var F=new Set(Object.keys(d).filter((P=>{var B;return!((B=d[P])!=null&&B.failed)})));b=w({},i,Object.fromEntries(Object.entries(b).filter((P=>F.has(P[0]))))),E=w({},o,Object.fromEntries(Object.entries(E||{}).filter((P=>F.has(P[0]))))),I=w({},a,Object.fromEntries(Object.entries(I||{}).filter((P=>F.has(P[0])))))}else b=w({},i,b),E=w({},o,E),I=w({},a,I);return w({[Hs]:Object.keys(zl(b)),[Bt]:b||{},[Ws]:E||{},[Ji]:I||{},[tn]:n.minimalFlagCalledEvents===!0},f?{[Nr]:f}:{},g?{[Ks]:g}:{})}})(t,this.getFlagVariants(),this.getFlagPayloads(),this.getFlagsWithDetails(),s,this.rt);r&&this.F(r),e||(this.xa=!1),this.Va(e)}}override(t,e){e===void 0&&(e=!1),this.rt.warn("override is deprecated. Please use overrideFeatureFlags instead."),this.overrideFeatureFlags({flags:t,suppressWarning:e})}overrideFeatureFlags(t){this.Za(t)}Za(t){if(this.nn){if(t===!1)return this.q([et,jt]),this.Va(),void Ot.info("All overrides cleared");if(L(t))return this.F({[et]:Wl(t)}),this.Va(),void Ot.info("Flag overrides set",{flags:t});if(t&&typeof t=="object"&&("flags"in t||"payloads"in t)){var e,s=t;this.ca=!!((e=s.suppressWarning)!==null&&e!==void 0&&e);var r={},n=s.flags,i=s.payloads;return n&&(r[et]=L(n)?Wl(n):n),i&&(r[jt]=i),Object.keys(r).length&&this.F(r),n===!1&&i===!1?this.q([et,jt]):n===!1?this.q(et):i===!1&&this.q(jt),this.Va(),n===!1?Ot.info("Flag overrides cleared"):n&&Ot.info("Flag overrides set",{flags:n}),void(i===!1?Ot.info("Payload overrides cleared"):i&&Ot.info("Payload overrides set",{payloads:i}))}if(t&&typeof t=="object")return this.F({[et]:t}),this.Va(),void Ot.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(),s=e.flags,r=e.flagVariants;try{t(s,r)}catch(n){this.rt.error("Error while running feature flags callback",n)}}return()=>this.removeFeatureFlagsHandler(t)}updateEarlyAccessFeatureEnrollment(t,e,s){var r=(this.Oa(Tr)||[]).find((l=>l.flagKey===t)),n={["$feature_enrollment/"+t]:e},i={$feature_flag:t,$feature_enrollment:e,$set:n};r&&(i.$early_access_feature_name=r.name),s&&(i.$feature_enrollment_stage=s);var o=w({},this.getFlagVariants(),{[t]:e});this.F({[Hs]:Object.keys(zl(o)),[Bt]:o,[ct]:w({},this.Oa(ct)||{},n)}),this.Va();try{var a;(a=this.nn)==null||a.capture("$feature_enrollment_update",i).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,s){e===void 0&&(e=!1);var r=this.Oa(Tr);!r||e?this.Qa(t,s):t(r)}Qa(t,e){var s=this;return X((function*(){var r=s.nn;if(r){var n,i=e?"&"+e.map((a=>"stage="+a)).join("&"):"";try{var o=yield r.sendRequest("/api/early_access_features/?token="+r.projectToken+i,{target:"api",method:"GET",sentAt:"query"});if(!o.json)return;s.F({[Tr]:n=o.json.earlyAccessFeatures})}catch(a){return void s.rt.error("Early access feature request failed",a)}try{t(n)}catch(a){s.rt.error("Early access feature callback failed",a)}}}))()}Ga(){var t=this.getFlags(),e=this.getFlagVariants();return{flags:t.filter((s=>e[s])),flagVariants:Object.keys(e).filter((s=>e[s])).reduce(((s,r)=>(s[r]=e[r],s)),{})}}Va(t){this.Fa();var e=this.Ga(),s=e.flags,r=e.flagVariants;this.featureFlagEventHandlers.forEach((n=>{try{n(s,r,{errorsLoading:t})}catch(i){this.rt.error("Error while running feature flags callback",i)}}))}setPersonPropertiesForFlags(t,e){e===void 0&&(e=!0),this.Ka(t,e)}Ka(t,e){e===void 0&&(e=!0);var s=this.Oa(ct)||{},r=t?.$set||(t!=null&&t.$set_once?{}:t),n=t?.$set_once,i={};if(n)for(var o in n)({}).hasOwnProperty.call(n,o)&&(o in s||(i[o]=n[o]));this.F({[ct]:w({},s,i,r)}),e&&this.reloadFeatureFlags()}unsetPersonPropertiesForFlags(t,e){e===void 0&&(e=!0);var s=w({},this.Oa(ct)||{});t.forEach((r=>{delete s[r]})),this.F({[ct]:s}),e&&this.reloadFeatureFlags()}resetPersonPropertiesForFlags(t){t===void 0&&(t=!0),this.q(ct),t&&this.reloadFeatureFlags()}setGroupPropertiesForFlags(t,e){e===void 0&&(e=!0);var s=this.Oa(Ut)||{},r=w({},s);for(var n of Object.keys(t))r[n]=w({},s[n],t[n]);this.F({[Ut]:r}),e&&this.reloadFeatureFlags()}resetGroupPropertiesForFlags(t){if(t){var e=this.Oa(Ut)||{};this.F({[Ut]:w({},e,{[t]:{}})})}else this.q(Ut)}reset(){this.ba++,this.wa=!1,this.Fa(),this.ma=!1,this._a=!1,this.ka=!1,this.$anon_distinct_id=void 0,this.La(),this.ca=!1,this.Sa=0}}},bf={sessionRecording:class{get Ne(){return this._instance.config}get Mr(){return this._instance.persistence}get started(){var t;return!((t=this.Ja)==null||!t.isStarted)}get status(){var t,e;return this.Ya===Os||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=Nl,this.Xa=void 0,this.eo=!1,this.io=(()=>{var e;if(C==null||!C.visibilityState||C.visibilityState==="visible")return!0;var s=v==null||(e=v.performance)==null||e.getEntriesByType==null?void 0:e.getEntriesByType("visibility-state");return!(s!=null&&s.length)||s.some((r=>r.name==="visible"))})(),this.Ie=()=>{var e;C?.visibilityState==="visible"&&(this.io=!0,(e=this.Ja)==null||e.setDocumentWasEverVisible==null||e.setDocumentWasEverVisible(!0))},this._instance=t,!this._instance.sessionManager)throw at.error("started without valid sessionManager"),new Error(fo+" started without valid sessionManager. This is a bug.");if(this.Ne.cookieless_mode===ht)throw new Error(fo+' cannot be used with cookieless_mode="always"');C!=null&&C.addEventListener&&ne(C,"visibilitychange",this.Ie)}initialize(){this.startIfEnabledOrStop()}dispose(){this.eo=!0,C==null||C.removeEventListener==null||C.removeEventListener("visibilitychange",this.Ie),this.stopRecording()}get ro(){var t,e=!((t=this._instance.get_property(Vt))==null||!t.enabled),s=!this.Ne.disable_session_recording,r=this.Ne.disable_session_recording||this._instance.consent.isOptedOut();return v&&e&&s&&!r}startIfEnabledOrStop(t){var e;if(!(this.eo||this.ro&&(e=this.Ja)!=null&&e.isStarted)){var s=!x(Object.assign)&&!x(Array.from);this.ro&&s?(this.no(t),at.info("starting")):(this.Ya=Nl,this.stopRecording())}}no(t){var e,s,r;this.ro&&(this.Ya!==Os&&this.Ya!==Pr&&(this.Ya=Ml),$!=null&&(e=$.__PosthogExtensions__)!=null&&(e=e.rrweb)!=null&&e.record&&(s=$.__PosthogExtensions__)!=null&&s.initSessionRecording?this.so(t):(r=$.__PosthogExtensions__)==null||r.loadExternalDependency==null||r.loadExternalDependency(this._instance,this.ao,(n=>{if(n)return at.error("could not load recorder",n);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(qo),(e=this.Mr)==null||e.unregister(cu)}uo(t,e){if(D(t))return null;var s,r=he(t)?t:parseFloat(t);return typeof(s=r)!="number"||!Number.isFinite(s)||0>s||s>1?(at.warn(e+" must be between 0 and 1. Ignoring invalid value:",t),null):r}ho(t){if(this.Mr){var e,s,r=this.Mr,n=()=>{var i,o=t.sessionRecording===!1?void 0:t.sessionRecording,a=this.uo((i=this.Ne.session_recording)==null?void 0:i.sampleRate,"session_recording.sampleRate"),l=this.uo(o?.sampleRate,"remote config sampleRate"),u=a??l;D(u)&&this.lo();var c=o?.minimumDurationMilliseconds;r.register({[Vt]:w({cache_timestamp:Date.now(),enabled:!!o},o,{networkPayloadCapture:w({capturePerformance:t.capturePerformance},o?.networkPayloadCapture),canvasRecording:{enabled:o?.recordCanvas,fps:o?.canvasFps,quality:o?.canvasQuality},sampleRate:u,minimumDurationMilliseconds:x(c)?null:c,endpoint:o?.endpoint,triggerMatchType:o?.triggerMatchType,masking:o?.masking,urlTriggers:o?.urlTriggers,version:o?.version,triggerGroups:o?.triggerGroups})})};n(),(e=this.Xa)==null||e.call(this),this.Xa=(s=this._instance.sessionManager)==null?void 0:s.onSessionId(n)}}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===Os&&(this.Ya=Pr,at.warn("config refresh failed, recording will not start until page reload")),void this.startIfEnabledOrStop())}log(t,e){var s;e===void 0&&(e="log"),(s=this.Ja)!=null&&s.log?this.Ja.log(t,e):at.warn("log called before recorder was ready")}get ao(){var t,e,s=(t=this._instance)==null||(t=t.persistence)==null?void 0:t.get_property(Vt);return(s==null||(e=s.scriptConfig)==null?void 0:e.script)||"lazy-recorder"}do(){var t,e=this._instance.get_property(Vt);if(!e)return!1;try{t=typeof e=="object"?e:JSON.parse(e)}catch(s){return at.warn("persisted remote config for session recording is invalid and will be ignored",s),!1}return!D(t.cache_timestamp)&&36e5>=Date.now()-t.cache_timestamp}so(t){var e,s,r;if(!this.eo){if((e=$.__PosthogExtensions__)==null||!e.initSessionRecording)return at.warn("Called on script loaded before session recording is available. This can be caused by adblockers."),void this._instance.register_for_session({[vu]:!0});var n;if(this.Ja||(this.Ja=(n=$.__PosthogExtensions__)==null?void 0:n.initSessionRecording(this._instance,this.io),this.Ja._forceAllowLocalhostNetworkCapture=this._forceAllowLocalhostNetworkCapture),!this.do())return this.Ya===Pr||this.Ya===Os?void 0:(this.Ya=Os,at.info("persisted remote config is stale, requesting fresh config before starting"),void new Hu(this._instance).load());this.Ya=Ml,(s=(r=this.Ja).setDocumentWasEverVisible)==null||s.call(r,this.io),this.Ja.start(t)}}onRRwebEmit(t){var e;(e=this.Ja)==null||e.onRRwebEmit==null||e.onRRwebEmit(t)}overrideLinkedFlag(){var t,e;this.Ja||(e=this.Mr)==null||e.register({[du]:!0}),(t=this.Ja)==null||t.overrideLinkedFlag()}overrideSampling(){var t,e;this.Ja||(e=this.Mr)==null||e.register({[uu]:!0}),(t=this.Ja)==null||t.overrideSampling()}overrideTrigger(t){var e,s;this.Ja||(s=this.Mr)==null||s.register({[t==="url"?hu:pu]:!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 s;return!((s=this.Ja)==null||!s.tryAddCustomEvent(t,e))}}},Ef={autocapture:class{constructor(t){this.vo=!1,this.co=null,this.fo=!1,this.po=!1,this.instance=t,this.rageclicks=new $l(t.config.rageclick),this.mo=null}initialize(){this.startIfEnabled()}get Ne(){var t,e,s=te(this.instance.config.autocapture)?this.instance.config.autocapture:{};return s.url_allowlist=(t=s.url_allowlist)==null?void 0:t.map((r=>new RegExp(r))),s.url_ignorelist=(e=s.url_ignorelist)==null?void 0:e.map((r=>new RegExp(r))),s}yo(){if(this.isBrowserSupported()){if(v&&C){var t=s=>{s=s||v?.event;try{this.bo(s)}catch(r){bi.error("Failed to capture event",r)}};if(ne(C,"submit",t,{capture:!0}),ne(C,"change",t,{capture:!0}),ne(C,"click",t,{capture:!0}),this.Ne.capture_copied_text){var e=s=>{s=s||v?.event;try{this.bo(s,wi)}catch(r){bi.error("Failed to capture copy/cut event",r)}};ne(C,"copy",e,{capture:!0}),ne(C,"cut",e,{capture:!0})}}}else bi.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 s=e.autocapture_opt_out;Ke(s)&&(this.instance.persistence&&this.instance.persistence.register({[Hi]:s}),this.co=s),this.startIfEnabled()}else this.startIfEnabled()}setElementSelectors(t){this.mo=t}getElementSelectors(t){var e,s=[];return(e=this.mo)==null||e.forEach((r=>{var n=C?.querySelectorAll(r);n?.forEach((i=>{t===i&&s.push(r)}))})),s}get isEnabled(){var t,e,s=(t=this.instance.persistence)==null?void 0:t.props[Hi],r=this.co,n=this.instance.Qi()&&!this.fo;if($e(r)&&!Ke(s)&&!n)return!1;var i=(e=this.co)!==null&&e!==void 0?e:!!s;return!!this.instance.config.autocapture&&!i}bo(t,e){if(e===void 0&&(e="$autocapture"),this.isEnabled){var s,r=li(t);Eu(r)&&(r=r.parentNode||null),e==="$autocapture"&&t.type==="click"&&t instanceof MouseEvent&&this.instance.config.rageclick&&(s=this.rageclicks)!=null&&s.isRageClick(t.clientX,t.clientY,t.timeStamp||new Date().getTime())&&al(r,this.instance.config.rageclick)&&this.bo(t,"$rageclick");var n=e===wi;if(r&&(function(d,h,p,f,g,m){var _;if(!v||Yo(d)||p!=null&&p.url_allowlist&&!nl(p.url_allowlist,m)||p!=null&&p.url_ignorelist&&nl(p.url_ignorelist,m))return!1;if(p!=null&&p.dom_event_allowlist){var b=p.dom_event_allowlist;if(b&&!b.some((S=>h.type===S)))return!1}var E=Fu(d,f),I=E.parentIsUsefulElement,F=E.targetElementList;if(!(function(S,A){var R=A?.element_allowlist;if(x(R))return!0;var N,T=function(J){if(R.some((z=>J.tagName.toLowerCase()===z)))return{v:!0}};for(var O of S)if(N=T(O))return N.v;return!1})(F,p)||!no(F,p?.css_selector_allowlist)||no(F,(_=p?.css_selector_ignorelist)!==null&&_!==void 0?_:_p))return!1;try{var P=v.getComputedStyle(d);if(P&&P.getPropertyValue("cursor")==="pointer"&&h.type==="click")return!0}catch{}var B=d.tagName.toLowerCase();switch(B){case"html":return!1;case"form":return(g||["submit"]).indexOf(h.type)>=0;case"input":case"select":case"textarea":return(g||["change","click"]).indexOf(h.type)>=0;default:return I?(g||["click"]).indexOf(h.type)>=0:(g||["click"]).indexOf(h.type)>=0&&(Jo.indexOf(B)>-1||d.getAttribute("contenteditable")==="true")}})(r,t,this.Ne,n,n?["copy","cut"]:void 0,this.instance)){var i=df(r,{e:t,maskAllElementAttributes:this.instance.config.mask_all_element_attributes,maskAllText:this.instance.config.mask_all_text,elementAttributeIgnoreList:this.Ne.element_attribute_ignorelist,elementsChainAsString:this.po,disableCaptureUrlHashes:this.instance.config.disable_capture_url_hashes}),o=i.props;if(i.explicitNoCapture)return!1;var a=this.getElementSelectors(r);if(a&&a.length>0&&(o.$element_selectors=a),e===wi){var l,u=ku(v==null||(l=v.getSelection())==null?void 0:l.toString()),c=t.type||"clipboard";if(!u)return!1;o.$selected_content=u,o.$copy_type=c}return this.instance.capture(e,o),!0}}}isBrowserSupported(){return Se(C?.querySelectorAll)}},historyAutocapture:class{constructor(t){var e;this._instance=t,this._o=(v==null||(e=v.location)==null?void 0:e.pathname)||""}initialize(){this.startIfEnabled()}get isEnabled(){return this._instance.config.capture_pageview==="history_change"}startIfEnabled(){this.isEnabled&&(k.info("History API monitoring enabled, starting..."),this.monitorHistoryChanges())}stop(){this.wo&&this.wo(),this.wo=void 0,k.info("History API monitoring stopped")}monitorHistoryChanges(){v&&v.history&&(this.ko("pushState"),this.ko("replaceState"),this.xo())}ko(t){var e;if(v&&((e=v.history[t])==null||!e.__posthog_wrapped__)){var s=this;(function(r,n,i){try{if(!(n in r))return Rl;var o={next:r[n]},a=i((function(){for(var l=arguments.length,u=new Array(l),c=0;l>c;c++)u[c]=arguments[c];return o.next.apply(this,u)}));return Se(a)&&(a.prototype=a.prototype||{},Object.defineProperties(a,{__posthog_wrapped__:{enumerable:!1,value:!0},__posthog_layer__:{enumerable:!1,value:o}})),r[n]=a,()=>{if(r[n]!==a)for(var l=r[n];Se(l)&&l.__posthog_layer__;){var u=l.__posthog_layer__;if(u.next===a)return void(u.next=o.next);l=u.next}else r[n]=o.next}}catch{return Rl}})(v.history,t,(r=>function(n,i,o){r.call(this,n,i,o),s.So(t)}))}}So(t){try{var e,s=v==null||(e=v.location)==null?void 0:e.pathname;if(!s)return;s!==this._o&&this.isEnabled&&this._instance.capture(os,{navigation_type:t}),this._o=s}catch(r){k.error("Error capturing "+t+" pageview",r)}}xo(){if(!this.wo){var t=()=>{this.So("popstate")};ne(v,"popstate",t),this.wo=()=>{v&&v.removeEventListener("popstate",t)}}}},heatmaps:class{get Ne(){return this.instance.config}constructor(t){var e;this.Co=!1,this.vo=!1,this.Mo=null,this.instance=t,this.Co=!((e=this.instance.persistence)==null||!e.props[Wi]),this.rageclicks=new $l(t.config.rageclick)}initialize(){this.startIfEnabled()}get flushIntervalMilliseconds(){var t=5e3;return te(this.Ne.capture_heatmaps)&&this.Ne.capture_heatmaps.flush_interval_milliseconds&&(t=this.Ne.capture_heatmaps.flush_interval_milliseconds),t}get isEnabled(){return D(this.Ne.capture_heatmaps)?D(this.Ne.enable_heatmaps)?this.Co:this.Ne.enable_heatmaps:this.Ne.capture_heatmaps!==!1}startIfEnabled(){if(this.isEnabled){if(this.vo)return;pf.info("starting..."),this.To(),this.Ie()}else{var t;clearInterval((t=this.Mo)!==null&&t!==void 0?t:void 0),this.Eo(),this.getAndClearBuffer()}}onRemoteConfig(t){if(t.ok){var e=t.config;if("heatmaps"in e){var s=!!e.heatmaps;this.instance.persistence&&this.instance.persistence.register({[Wi]:s}),this.Co=s,this.startIfEnabled()}}}getAndClearBuffer(){var t=this.R;return this.R=void 0,t}Io(t){Si(t.originalEvent)&&this.ke(t.originalEvent,"deadclick")}Ie(){this.Mo&&clearInterval(this.Mo),this.Mo=C?.visibilityState==="visible"?setInterval(this.cr.bind(this),this.flushIntervalMilliseconds):null}To(){v&&C&&(this.Po=this.cr.bind(this),ne(v,an,this.Po),this.Ro=t=>this.ke(t||v?.event),ne(C,"click",this.Ro,{capture:!0}),this.Ao=t=>this.Fo(t||v?.event),ne(C,"mousemove",this.Ao,{capture:!0}),this.Lo=new fl(this.instance,kp,this.Io.bind(this)),this.Lo.startIfEnabledOrStop(),this.Oo=this.Ie.bind(this),ne(C,on,this.Oo),this.vo=!0)}Eo(){var t;v&&C&&(this.Po&&v.removeEventListener(an,this.Po),this.Ro&&C.removeEventListener("click",this.Ro,{capture:!0}),this.Ao&&C.removeEventListener("mousemove",this.Ao,{capture:!0}),this.Oo&&C.removeEventListener(on,this.Oo),clearTimeout(this.Do),(t=this.Lo)==null||t.stop(),this.vo=!1)}$o(t,e){var s=this.instance.scrollManager.scrollY(),r=this.instance.scrollManager.scrollX(),n=this.instance.scrollManager.scrollElement(),i=(function(o,a,l){for(var u=o;u&&Ft(u)&&!Me(u,"body");){if(u===l)return!1;var c=void 0;try{var d,h,p;c=(d=(h=(p=u.ownerDocument)==null?void 0:p.defaultView)!==null&&h!==void 0?h:v)==null?void 0:d.getComputedStyle(u).position}catch{return!1}if(M(a,c))return!0;u=Iu(u)}return!1})(li(t),["fixed","sticky"],n);return{x:t.clientX+(i?0:r),y:t.clientY+(i?0:s),target_fixed:i,type:e}}ke(t,e){var s;if(e===void 0&&(e="click"),!rl(t.target)&&Si(t)){var r=this.$o(t,e);(s=this.rageclicks)!=null&&s.isRageClick(t.clientX,t.clientY,new Date().getTime())&&al(li(t),this.instance.config.rageclick)&&this.Vt(w({},r,{type:"rageclick"})),this.Vt(r)}}Fo(t){!rl(t.target)&&Si(t)&&(clearTimeout(this.Do),this.Do=setTimeout((()=>{this.Vt(this.$o(t,"mousemove"))}),500))}Vt(t){if(v){var e=this.Ne.disable_capture_url_hashes?Ct(v.location.href):v.location.href,s=this.Ne.custom_personal_data_properties,r=this.Ne.mask_personal_data_properties?[..._s,...s||[]]:[],n=ir(e,r,or);this.R=this.R||{},this.R[n]||(this.R[n]=[]),this.R[n].push(t)}}cr(){this.R&&!mt(this.R)&&this.instance.capture("$$heatmap",{$heatmap_data:this.getAndClearBuffer()})}},deadClicksAutocapture:fl,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",w({$current_url:this.R.url},this.R.metrics.reduce(((s,r)=>w({},s,{["$web_vitals_"+r.name+"_event"]:w({},r),["$web_vitals_"+r.name+"_value"]:r.value})),{}))),this.R={navigationKey:void 0,url:void 0,metrics:[],firstMetricTimestamp:void 0})},this.jo=s=>{var r;if(this.R=this.R||{navigationKey:void 0,url:void 0,metrics:[],firstMetricTimestamp:void 0},D(s?.name)||D(s?.value))Lt.error("Invalid metric received",s);else{var n=typeof s.navigationURL=="string"?s.navigationURL:void 0,i=this.Bo(n);if(!x(i)){var o=he(s.navigationId)||typeof s.navigationId=="string"?"navigation:"+s.navigationId:"url:"+i;if(!this.Ho||this.Ho>s.value){this.R.navigationKey!==o&&(this.No(),this.qo=setTimeout(this.No,this.flushToCaptureTimeoutMs)),x(this.R.navigationKey)&&(this.R.navigationKey=o,this.R.url=i),this.R.firstMetricTimestamp=x(this.R.firstMetricTimestamp)?Date.now():this.R.firstMetricTimestamp,s.attribution&&s.attribution.interactionTargetElement&&(s.attribution.interactionTargetElement=void 0);var a=(r=this._instance.sessionManager)==null?void 0:r.checkAndGetSessionAndWindowId(!0),l=w({},s,n?{navigationURL:i}:{},{$current_url:i,timestamp:Date.now()});x(a)||(l.$session_id=a.sessionId,l.$window_id=a.windowId),this.R.metrics.push(l),this.R.metrics.length===this.allowedMetrics.length&&this.No()}else Lt.error("Ignoring metric with value >= "+this.Ho,s)}}},this.Uo=()=>{if(!this.vo){var s,r,n,i,o=$.__PosthogExtensions__,a=o?.postHogWebVitalsCallbacksByFlavor,l=a?.[this.zo]||(this.zo==="web-vitals"&&x(a)?o?.postHogWebVitalsCallbacks:void 0);if(x(l)||(s=l.onLCP,r=l.onCLS,n=l.onFCP,i=l.onINP),s&&r&&n&&i){var u={reportSoftNavs:this.useSoftNavs};this.allowedMetrics.indexOf("LCP")>-1&&s(this.jo.bind(this),u),this.allowedMetrics.indexOf("CLS")>-1&&r(this.jo.bind(this),u),this.allowedMetrics.indexOf("FCP")>-1&&n(this.jo.bind(this),u),this.allowedMetrics.indexOf("INP")>-1&&i(this.jo.bind(this),u),this.vo=!0}else Lt.error("web vitals callbacks not loaded - not starting")}},this._instance=t,this.Co=!((e=this._instance.persistence)==null||!e.props[Gi]),this.startIfEnabled()}get Wo(){return this._instance.config.capture_performance}get allowedMetrics(){var t,e,s=te(this.Wo)?(t=this.Wo)==null?void 0:t.web_vitals_allowed_metrics:void 0;return D(s)?((e=this._instance.persistence)==null?void 0:e.props[Ki])||["CLS","FCP","INP","LCP"]:s}get flushToCaptureTimeoutMs(){return(te(this.Wo)?this.Wo.web_vitals_delayed_flush_ms:void 0)||5e3}get useAttribution(){var t=te(this.Wo)?this.Wo.web_vitals_attribution:void 0;return t!=null&&t}get useSoftNavs(){var t=te(this.Wo)?this.Wo.__preview_web_vitals_soft_navs:void 0;return t!=null&&t}get Ho(){var t=te(this.Wo)&&he(this.Wo.__web_vitals_max_value)?this.Wo.__web_vitals_max_value:Tl;return t>0&&6e4>=t?Tl:t}get isEnabled(){var t=re?.protocol;if(t!=="http:"&&t!=="https:")return Lt.info("Web Vitals are disabled on non-http/https protocols"),!1;var e=te(this.Wo)?this.Wo.web_vitals:Ke(this.Wo)?this.Wo:void 0;return Ke(e)?e:this.Co}startIfEnabled(){this.isEnabled&&!this.vo&&(Lt.info("enabled, starting..."),this.ai(this.Uo))}onRemoteConfig(t){if(t.ok){var e=t.config;if("capturePerformance"in e){var s=te(e.capturePerformance)&&!!e.capturePerformance.web_vitals,r=te(e.capturePerformance)?e.capturePerformance.web_vitals_allowed_metrics:void 0;this._instance.persistence&&(this._instance.persistence.register({[Gi]:s}),this._instance.persistence.register({[Ki]:r})),this.Co=s,this.startIfEnabled()}}}get zo(){return this.useSoftNavs?this.useAttribution?"web-vitals-with-attribution-soft-navs":"web-vitals-soft-navs":this.useAttribution?"web-vitals-with-attribution":"web-vitals"}ai(t){var e=$.__PosthogExtensions__,s=this.zo,r=e?.postHogWebVitalsCallbacksByFlavor;r!=null&&r[s]||s==="web-vitals"&&x(r)&&e!=null&&e.postHogWebVitalsCallbacks?t():e==null||e.loadExternalDependency==null||e.loadExternalDependency(this._instance,s,(n=>{n?Lt.error("failed to load script",n):t()}))}Bo(t){var e=t||v?.location.href;if(e){var s=this._instance.config.disable_capture_url_hashes?Ct(e):e,r=this._instance.config.custom_personal_data_properties,n=this._instance.config.mask_personal_data_properties?[..._s,...r||[]]:[];return ir(s,n,or)}Lt.error("Could not determine current URL")}}},Sf={exceptionObserver:class{constructor(t){var e;this.Uo=()=>{var s;if(v&&this.isEnabled&&(s=$.__PosthogExtensions__)!=null&&s.errorWrappingFunctions){var r=$.__PosthogExtensions__.errorWrappingFunctions.wrapOnError,n=$.__PosthogExtensions__.errorWrappingFunctions.wrapUnhandledRejection,i=$.__PosthogExtensions__.errorWrappingFunctions.wrapConsoleError;try{!this.Vo&&this.Ne.capture_unhandled_errors&&(this.Vo=r(this.captureException.bind(this))),!this.Zo&&this.Ne.capture_unhandled_rejections&&(this.Zo=n(this.captureException.bind(this))),!this.Go&&this.Ne.capture_console_errors&&(this.Go=i(this.captureException.bind(this)))}catch(o){Ls.error("failed to start",o),this.Qo()}}},this._instance=t,this.Ko=!((e=this._instance.persistence)==null||!e.props[zi]),this.Jo=new wh(w({},(function(s){var r,n,i,o;return s===void 0&&(s={}),{refillRate:(r=(n=s.exceptionRateLimiterRefillRate)!==null&&n!==void 0?n:s.__exceptionRateLimiterRefillRate)!==null&&r!==void 0?r:1,bucketSize:(i=(o=s.exceptionRateLimiterBucketSize)!==null&&o!==void 0?o:s.__exceptionRateLimiterBucketSize)!==null&&i!==void 0?i:10}})(this._instance.config.error_tracking),{refillInterval:1e4,rt:Ls})),this.Ne=this.Yo(),this.startIfEnabledOrStop()}Yo(){var t=this._instance.config.capture_exceptions,e={capture_unhandled_errors:!1,capture_unhandled_rejections:!1,capture_console_errors:!1};return te(t)?e=w({},e,t):(x(t)?this.Ko:t)&&(e=w({},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?(Ls.info("enabled"),this.Qo(),this.ai(this.Uo)):this.Qo()}ai(t){var e,s;(e=$.__PosthogExtensions__)!=null&&e.errorWrappingFunctions?t():(s=$.__PosthogExtensions__)==null||s.loadExternalDependency==null||s.loadExternalDependency(this._instance,"exception-autocapture",(r=>{if(r)return Ls.error("failed to load script",r);t()}))}Qo(){var t,e,s;(t=this.Vo)==null||t.call(this),this.Vo=void 0,(e=this.Zo)==null||e.call(this),this.Zo=void 0,(s=this.Go)==null||s.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({[zi]:this.Ko}),this.Ne=this.Yo(),this.startIfEnabledOrStop())}}onConfigChange(){this.Ne=this.Yo()}captureException(t){var e,s,r,n=(e=t==null||(s=t.$exception_list)==null||(s=s[0])==null?void 0:s.type)!==null&&e!==void 0?e:"Exception";this.Jo.consumeRateLimit(n)?Ls.info("Skipping exception capture because of client rate limiting.",{exception:n}):(r=this._instance.exceptions)==null||r.sendExceptionEvent(t)}},exceptions:class{constructor(t){var e,s;this.Xo=[],this.tl=new Oh([new qh,new ep,new Gh,new Vh,new Xh,new Zh,new Jh,new Qh],(function(r){for(var n=arguments.length,i=new Array(n>1?n-1:0),o=1;n>o;o++)i[o-1]=arguments[o];return function(a,l){l===void 0&&(l=0);for(var u=[],c=a.split(` +`),d=l;c.length>d;d++){var h=c[d];if(1024>=h.length){var p=Qa.test(h)?h.replace(Qa,"$1"):h;if(!p.match(/\S*Error: /)){for(var f of i){var g=f(p,r);if(g){u.push(g);break}}if(u.length>=50)break}}}return(function(m){if(!m.length)return[];var _=Array.from(m);return _.reverse(),_.slice(0,50).map((b=>{return w({},b,{filename:b.filename||(E=_,E[E.length-1]||{}).filename,function:b.function||ms});var E}))})(u)}})("web:javascript",Uh,zh)),this._instance=t,this.Xo=(e=(s=this._instance.persistence)==null?void 0:s.get_property(qi))!==null&&e!==void 0?e:[],this.el=en(this.il()),this.rl=new sp(this.el)}onConfigChange(){this.el=en(this.il()),this.rl.setConfig(this.el)}onRemoteConfig(t){var e,s,r;if(t.ok){var n=t.config;if("errorTracking"in n){var i=(e=(s=n.errorTracking)==null?void 0:s.suppressionRules)!==null&&e!==void 0?e:[],o=(r=n.errorTracking)==null?void 0:r.captureExtensionExceptions;this.Xo=i,this._instance.persistence&&this._instance.persistence.register({[qi]:this.Xo,[Vi]:o})}}}get nl(){var t,e=!!this._instance.get_property(Vi),s=this._instance.config.error_tracking.captureExtensionExceptions;return(t=s??e)!==null&&t!==void 0&&t}buildProperties(t,e){return this.tl.buildFromUnknown(t,{syntheticException:e?.syntheticException,mechanism:{handled:e?.handled}})}addExceptionStep(t,e){if(this.el.enabled)try{if(!W(t)||t.trim().length===0)return void Xe.warn("Ignoring exception step because message must be a non-empty string");var s=(function(i){if(!i)return{sanitizedProperties:{},droppedKeys:[]};var o=[];return{sanitizedProperties:Object.keys(i).reduce(((a,l)=>tp.has(l)?(o.push(l),a):(a[l]=i[l],a)),{}),droppedKeys:o}})(this.sl(e)),r=s.sanitizedProperties,n=s.droppedKeys;n.length>0&&Xe.warn("Ignoring reserved exception step fields",{droppedKeys:n}),this.rl.add(w({[Xr]:t,[Qr]:new Date().toISOString()},r))}catch(i){Xe.error("Failed to add exception step. Ignoring breadcrumb.",i)}}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 Xe.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 Xe.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 Xe.info("Skipping exception capture because it was thrown by the PostHog SDK")}var s=this.el.enabled&&D(t.$exception_steps)?this.dl(t):t,r=typeof(i=globalThis._posthogReleaseId)=="string"&&i.length>0?i:void 0;r&&(s.$release_id=r);try{var n=this._instance.capture("$exception",s,{_noTruncate:!0,_batchKey:"exceptionEvent",Wn:!0});return n&&this.rl.clear(),n}catch(o){return Xe.error("Failed to capture exception event. Dropping this exception.",o),void this.rl.clear()}}catch(o){return void Xe.error("Failed to process exception event. Ignoring this exception.",o)}var i}dl(t){try{var e=this.rl.getAttachable();return e.length===0?t:w({},t,{$exception_steps:e})}catch(s){return Xe.error("Failed to read buffered exception steps. Capturing exception without steps.",s),t}}ll(t){this.el.enabled&&this.rl.add({[Xr]:t,[Qr]:new Date().toISOString()})}sl(t){return te(t)?w({},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(((s,r)=>{var n=r.type,i=r.value;return W(n)&&n.length>0&&s.$exception_types.push(n),W(i)&&i.length>0&&s.$exception_values.push(i),s}),{$exception_types:[],$exception_values:[]});return this.Xo.some((s=>{var r=s.values.map((n=>{var i=sd[n.operator],o=e[n.key];if(!i||!o)return!1;var a=L(n.value)?n.value:[n.value];return a.length>0&&i(a,o)}));return s.type==="OR"?r.some(Boolean):r.every(Boolean)}))}catch(s){return Xe.warn("Failed to evaluate suppression rules. Capturing the exception.",s),!1}}ul(t){return t.flatMap((e=>{var s,r;return(s=(r=e.stacktrace)==null?void 0:r.frames)!==null&&s!==void 0?s:[]})).some((e=>e.filename&&e.filename.startsWith("chrome-extension://")))}hl(t){if(t.length>0){var e,s,r,n,i=(e=(s=t[0].stacktrace)==null?void 0:s.frames)!==null&&e!==void 0?e:[],o=i[i.length-1];return(r=o==null||(n=o.filename)==null?void 0:n.includes("posthog.com/static"))!==null&&r!==void 0&&r}return!1}al(t){return!D(t)&&L(t)}}},xf=w({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 s,r;if(this.Mr&&this.Mr.register({[zo]:!!e.productTours}),!xi(this._instance))return!this.vl&&D((s=this.Mr)==null?void 0:s.props[zs])||Ar.info("product tours disabled; stopping and clearing cached tours"),(r=this.vl)==null||r.stop(),this.vl=null,void this.clearCache();this.loadIfEnabled()}}}loadIfEnabled(){!this.vl&&xi(this._instance)&&this.ai((()=>this.fl()))}ai(t){var e,s;(e=$.__PosthogExtensions__)!=null&&e.generateProductTours?t():(s=$.__PosthogExtensions__)==null||s.loadExternalDependency==null||s.loadExternalDependency(this._instance,"product-tours",(r=>{r?Ar.error("Could not load product tours script",r):t()}))}fl(){var t;!this.vl&&(t=$.__PosthogExtensions__)!=null&&t.generateProductTours&&(this.vl=$.__PosthogExtensions__.generateProductTours(this._instance,!0))}getProductTours(t,e){if(e===void 0&&(e=!1),!L(this.cl)||e){var s=this.Mr;if(s){var r=s.props[zs];if(L(r)&&!e)return this.cl=r,void t(r,{isLoaded:!0})}this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/product_tours/?token="+this._instance.config.token),method:"GET",timestampMode:"query",callback:n=>{if(xi(this._instance)){var i=n.statusCode;if(i!==200||!n.json){var o="Product Tours API could not be loaded, status: "+i;return i===0?n.error||Ar.warn(o):Ar.error(o),void t([],{isLoaded:!1,error:o})}var a=L(n.json.product_tours)?n.json.product_tours:[];this.cl=a,s&&s.register({[zs]:a}),t(a,{isLoaded:!0})}else t([],{isLoaded:!0})}})}else t(this.cl,{isLoaded:!0})}getActiveProductTours(t){D(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(zs)}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)}}},Tn),kf={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 s=this.globalsForEvent(e);this.gl.push(s),this.gl.length>1e3&&(this.gl=this.gl.slice(10))}}get siteAppLoaders(){var t;return(t=$._POSTHOG_REMOTE_CONFIG)==null||(t=t[this._instance.config.token])==null?void 0:t.siteApps}initialize(){if(this.isEnabled){var t=this._instance._addCaptureHook(this.ml.bind(this));this.yl=()=>{t(),this.gl=[],this.yl=void 0}}}globalsForEvent(t){var e,s,r,n,i,o,a;if(!t)throw new Error("Event payload is required");var l={},u=this._instance.get_property("$groups")||[],c=this._instance.get_property("$stored_group_properties")||{};for(var d of Object.entries(c)){var h=d[0];l[h]={id:u[h],type:h,properties:d[1]}}var p=t.$set_once,f=t.$set;return{event:w({},Cc(t,ff),{properties:w({},t.properties,f?{$set:w({},(e=(s=t.properties)==null?void 0:s.$set)!==null&&e!==void 0?e:{},f)}:{},p?{$set_once:w({},(r=(n=t.properties)==null?void 0:n.$set_once)!==null&&r!==void 0?r:{},p)}:{}),elements_chain:(i=(o=t.properties)==null?void 0:o.$elements_chain)!==null&&i!==void 0?i:"",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,s=(e=t.tagName)==null?void 0:e.toLowerCase();return s==="style"&&this._instance.config.prepare_external_dependency_stylesheet?this._instance.config.prepare_external_dependency_stylesheet(t)||(Ze.error("prepare_external_dependency_stylesheet returned null"),null):s==="script"&&this._instance.config.prepare_external_dependency_script?this._instance.config.prepare_external_dependency_script(t)||(Ze.error("prepare_external_dependency_script returned null"),null):t}_l(){var t,e,s,r,n,i,o,a;if(!this._instance.config.prepare_external_dependency_stylesheet&&!this._instance.config.prepare_external_dependency_script)return()=>{};var l=C?.defaultView,u=l==null||(t=l.Node)==null?void 0:t.prototype;if(!l||!u)return()=>{};if(this.pl++,this.wl)return this.kl();var c=[],d=this,h=new WeakSet,p=(m,_,b)=>{if(m!=null&&m[_]){var E=m[_];m[_]=b(E),c.push((()=>{m[_]=E}))}},f=m=>{if(h.has(m))return m;var _=d.bl(m);return _&&h.add(_),_},g=m=>m.map((_=>typeof _=="string"?_:f(_))).filter((_=>!$e(_)));return p(u,"appendChild",(m=>function(_){var b=f(_);return b?m.call(this,b):_})),p(u,"insertBefore",(m=>function(_,b){var E=f(_);return E?m.call(this,E,b):_})),p(u,"replaceChild",(m=>function(_,b){var E=f(_);return E?m.call(this,E,b):b})),[(e=l.Element)==null?void 0:e.prototype,(s=l.Document)==null?void 0:s.prototype,(r=l.DocumentFragment)==null?void 0:r.prototype].forEach((m=>{p(m,"append",(_=>function(){for(var b=arguments.length,E=new Array(b),I=0;b>I;I++)E[I]=arguments[I];return _.apply(this,g(E))})),p(m,"prepend",(_=>function(){for(var b=arguments.length,E=new Array(b),I=0;b>I;I++)E[I]=arguments[I];return _.apply(this,g(E))}))})),[(n=l.Element)==null?void 0:n.prototype,(i=l.CharacterData)==null?void 0:i.prototype,(o=l.DocumentType)==null?void 0:o.prototype].forEach((m=>{p(m,"before",(_=>function(){for(var b=arguments.length,E=new Array(b),I=0;b>I;I++)E[I]=arguments[I];return _.apply(this,g(E))})),p(m,"after",(_=>function(){for(var b=arguments.length,E=new Array(b),I=0;b>I;I++)E[I]=arguments[I];return _.apply(this,g(E))})),p(m,"replaceWith",(_=>function(){for(var b=arguments.length,E=new Array(b),I=0;b>I;I++)E[I]=arguments[I];var F=g(E);return E.length&&!F.length?void 0:_.apply(this,F)}))})),p((a=l.Element)==null?void 0:a.prototype,"insertAdjacentElement",(m=>function(_,b){var E=f(b);return E?m.call(this,_,E):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 s=this._l();try{var r=t(s);return e&&s(),r}catch(n){throw s(),n}}setupSiteApp(t){var e=this.apps[t.id],s=()=>{var o;!e.errored&&this.gl.length&&(Ze.info("Processing "+this.gl.length+" events for site app with id "+t.id),this.gl.forEach((a=>this.xl((()=>e.processEvent==null?void 0:e.processEvent(a))))),e.processedBuffer=!0),Object.values(this.apps).every((a=>a.processedBuffer||a.errored))&&((o=this.yl)==null||o.call(this))},r=!1,n=o=>{e.errored=!o,e.loaded=!0,Ze.info("Site app with id "+t.id+" "+(o?"loaded":"errored")),r&&s()};try{var i=this.xl((o=>t.init({posthog:this._instance,callback(a){o(),n(a)}})),!1).processEvent;i&&(e.processEvent=i),r=!0}catch(o){Ze.error(Ll+t.id,o),n(!1)}if(r&&e.loaded)try{s()}catch(o){Ze.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 s of t)this.setupSiteApp(s)}Cl(t){var e=this;if(Object.keys(this.apps).length!==0){var s=this.globalsForEvent(t),r=function(i){try{e.xl((()=>i.processEvent==null?void 0:i.processEvent(s)))}catch(o){Ze.error("Error while processing event "+t.event+" for site app "+i.id,o)}};for(var n of Object.values(this.apps))r(n)}}onRemoteConfig(t){var e,s,r,n=this;if((e=this.siteAppLoaders)!=null&&e.length)return this.isEnabled?(this.Sl(),void this._instance.on("eventCaptured",(l=>this.Cl(l)))):void Ze.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.');if((s=this.yl)==null||s.call(this),t.ok){var i=t.config;if((r=i.siteApps)!=null&&r.length)if(this.isEnabled){var o=function(){var l,u=a.id,c=a.url;$["__$$ph_site_app_"+u]=n._instance,(l=$.__PosthogExtensions__)==null||l.loadSiteApp==null||l.loadSiteApp(n._instance,c,(d=>{if(d)return Ze.error(Ll+u,d)}))};for(var a of i.siteApps)o()}else Ze.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.')}}}},If={tracingHeaders:class{constructor(t){this.Ml=void 0,this.Tl=void 0,this.El=void 0,this.Uo=()=>{var e,s,r=this.Il();r?(x(this.Ml)&&(this.Ml=(e=$.__PosthogExtensions__)==null||(e=e.tracingHeadersPatchFns)==null?void 0:e._patchXHR(r,(()=>this._instance.get_distinct_id()),this._instance.sessionManager)),x(this.Tl)&&(this.Tl=(s=$.__PosthogExtensions__)==null||(s=s.tracingHeadersPatchFns)==null?void 0:s._patchFetch(r,(()=>this._instance.get_distinct_id()),this._instance.sessionManager))):this.Qo()},this._instance=t}initialize(){this.startIfEnabledOrStop()}ai(t){var e,s;(e=$.__PosthogExtensions__)!=null&&e.tracingHeadersPatchFns?t():(s=$.__PosthogExtensions__)==null||s.loadExternalDependency==null||s.loadExternalDependency(this._instance,"tracing-headers",(r=>{if(r)return hf.error("failed to load script",r);t()}))}Pl(){var t,e;return(t=(e=this._instance.config.tracing_headers)!==null&&e!==void 0?e:this._instance.config.addTracingHeaders)!==null&&t!==void 0?t:this._instance.config.__add_tracing_headers}Il(){var t=this.Pl();return L(t)?(L(this.El)?this.El.splice(0,this.El.length,...t):this.El=[...t],t.length>0?this.El:void 0):(L(this.El)&&this.El.splice(0),this.El=t||void 0,this.El)}Qo(){var t,e;(t=this.Ml)==null||t.call(this),(e=this.Tl)==null||e.call(this),this.Ml=void 0,this.Tl=void 0}startIfEnabledOrStop(){this.Il()?this.ai(this.Uo):this.Qo()}}},Cf=w({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(D(e))return q.warn("Flags not loaded yet. Not loading surveys.");var s=L(e);this.Rl=s?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=[],s=0;slocalStorage.removeItem(n)))}catch{}}loadIfEnabled(){if(!this._surveyManager)if(this.Al)q.info("Already initializing surveys, skipping...");else if(this.Ne.disable_surveys)q.info(Ol);else if(this.Ne.cookieless_mode&&this._instance.consent.isOptedOut())q.info("Not loading surveys in cookieless mode without consent.");else{var t=$?.__PosthogExtensions__;if(t){if(!x(this.Rl)||this.Ne.advanced_enable_surveys){var e=this.Rl||this.Ne.advanced_enable_surveys;this.Al=!0;try{var s=t.generateSurveys;if(s)return void this.Dl(s,e);var r=t.loadExternalDependency;if(!r)return void this.$l(Vo);r(this._instance,"surveys",(n=>{n||!t.generateSurveys?this.$l("Could not load surveys script",n):this.Dl(t.generateSurveys,e)}))}catch(n){throw this.$l("Error initializing surveys",n),n}finally{this.Al=!1}}}else q.error("PostHog Extensions not found.")}}Dl(t,e){this._surveyManager=t(this._instance,e),this._surveyEventReceiver=new vf(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(Ol),t([]);var s,r=this._instance.get_property(Yi);if(r&&!e)return t(r,{isLoaded:!0}),void(this.ql()&&this.getSurveys((()=>{}),!0));typeof Promise<"u"&&this.Ll?this.Ll.then((n=>t(n.surveys,n.context))):(typeof Promise<"u"&&(this.Ll=new Promise((n=>{s=n}))),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:n=>{var i;this.Ll=null;var o=n.statusCode;if(o!==200||!n.json){var a="Surveys API could not be loaded, status: "+o;o!==0?q.error(a):n.error||q.warn(a),this.Ol=Date.now();var l={isLoaded:!1,error:a};return t([],l),void(s==null||s({surveys:[],context:l}))}this.Ol=null;var u,c=n.json.surveys||[],d=c.filter((p=>(function(f){return!(!f.start_date||f.end_date)})(p)&&(nd(p)||(function(f){var g;return!((g=f.conditions)==null||(g=g.actions)==null||(g=g.values)==null||!g.length)})(p))));d.length>0&&((u=this._surveyEventReceiver)==null||u.register(d)),(i=this._instance.persistence)==null||i.register({[Yi]:c,[sn]:Date.now()});var h={isLoaded:!0};t(c,h),s?.({surveys:c,context:h})}}))}ql(){return this.jl()&&!this.Ll&&!this.Bl()}jl(){var t=this._instance.get_property(sn);return he(t)&&Date.now()-t>3e5}Bl(){return he(this.Ol)&&3e5>Date.now()-this.Ol}markSurveyAsSeen(t,e){var s,r={id:t,current_iteration:(s=e?.iteration)!==null&&s!==void 0?s:null};od(r);try{localStorage.setItem("lastSeenSurveyDate",new Date().toISOString())}catch{}}Nl(t){for(var e of this.Fl)try{if(!t.isLoaded)return e([],t);this.getSurveys(e)}catch(s){q.error("Error in survey callback",s)}}getActiveMatchingSurveys(t,e){if(e===void 0&&(e=!1),!D(this._surveyManager))return this._surveyManager.getActiveMatchingSurveys(t,e);q.warn("init was not called")}Hl(t){var e=null;return this.getSurveys((s=>{var r;e=(r=s.find((n=>n.id===t)))!==null&&r!==void 0?r:null})),e}Ul(t){if(D(this._surveyManager))return{eligible:!1,reason:$r};var e=typeof t=="string"?this.Hl(t):t;return e?this._surveyManager.checkSurveyEligibility(e):{eligible:!1,reason:"Survey not found"}}zl(t){if(D(this._surveyManager))return{eligible:!1,reason:$r};var e=typeof t=="string"?this.Hl(t):t;return e?this._surveyManager.checkSurveyRenderability(e):{eligible:!1,reason:"Survey not found"}}canRenderSurvey(t){if(D(this._surveyManager))return q.warn("init was not called"),{visible:!1,disabledReason:$r};var e=this.zl(t);return{visible:e.eligible,disabledReason:e.reason}}canRenderSurveyAsync(t,e){return D(this._surveyManager)?(q.warn("init was not called"),Promise.resolve({visible:!1,disabledReason:$r})):new Promise((s=>{this.getSurveys((r=>{var n,i=(n=r.find((a=>a.id===t)))!==null&&n!==void 0?n:null;if(i){var o=this.zl(i);s({visible:o.eligible,disabledReason:o.reason})}else s({visible:!1,disabledReason:"Survey not found"})}),e)}))}renderSurvey(t,e,s){var r;if(D(this._surveyManager))q.warn("init was not called");else{var n=typeof t=="string"?this.Hl(t):t;if(n!=null&&n.id)if(Xp.includes(n.type)){var i=C?.querySelector(e);if(i)return(r=n.appearance)!=null&&r.surveyPopupDelaySeconds?(q.info("Rendering survey "+n.id+" with delay of "+n.appearance.surveyPopupDelaySeconds+" seconds"),void setTimeout((()=>{var o,a;q.info("Rendering survey "+n.id+" with delay of "+((o=n.appearance)==null?void 0:o.surveyPopupDelaySeconds)+" seconds"),(a=this._surveyManager)==null||a.renderSurvey(n,i,s),q.info("Survey "+n.id+" rendered")}),1e3*n.appearance.surveyPopupDelaySeconds)):void this._surveyManager.renderSurvey(n,i,s);q.warn("Survey element not found")}else q.warn("Surveys of type "+n.type+" cannot be rendered in the app");else q.warn("Survey not found")}}displaySurvey(t,e){var s;if(D(this._surveyManager))q.warn("init was not called");else{var r=this.Hl(t);if(r){var n=r;if((s=r.appearance)!=null&&s.surveyPopupDelaySeconds&&e.ignoreDelay&&(n=w({},r,{appearance:w({},r.appearance,{surveyPopupDelaySeconds:0})})),e.displayType!==oo.Popover&&e.initialResponses&&q.warn("initialResponses is only supported for popover surveys. prefill will not be applied."),e.ignoreConditions===!1){var i=this.Ul(r);if(!i.eligible)return void q.warn("Survey is not eligible to be displayed: ",i.reason)}e.displayType!==oo.Inline?this._surveyManager.handlePopoverSurvey(n,e):this.renderSurvey(n,e.selector,e.properties)}else q.warn("Survey not found")}}cancelPendingSurvey(t){D(this._surveyManager)?q.warn("init was not called"):this._surveyManager.cancelSurvey(t)}handlePageUnload(){var t;(t=this._surveyManager)==null||t.handlePageUnload==null||t.handlePageUnload()}}},Tn),Ff={toolbar:class{constructor(t){this.instance=t}Wl(t){$.ph_toolbar_state=t}Vl(){var t;return(t=$.ph_toolbar_state)!==null&&t!==void 0?t:0}initialize(){return this.maybeLoadToolbar()}maybeLoadToolbar(t,e,s){if(t===void 0&&(t=void 0),e===void 0&&(e=void 0),s===void 0&&(s=void 0),ro(this.instance.config)||!v||!C)return!1;t=t??v.location,s=s??v.history;try{if(!e){try{v.localStorage.setItem("test","test"),v.localStorage.removeItem("test")}catch{return!1}e=v?.localStorage}var r,n=_f||dn(t.hash,"__posthog")||dn(t.hash,"state"),i=n?tl((()=>JSON.parse(atob(decodeURIComponent(n)))))||tl((()=>JSON.parse(decodeURIComponent(n)))):null;return i&&i.action==="ph_authorize"?((r=i).source="url",r&&Object.keys(r).length>0&&(i.desiredHash?t.hash=i.desiredHash:s?s.replaceState(s.state,"",t.pathname+t.search):t.hash="")):((r=JSON.parse(e.getItem(Dl)||"{}")).source="localstorage",delete r.userIntent),!(!r.token||this.instance.config.token!==r.token||(this.loadToolbar(r),0))}catch{return!1}}Zl(t){var e=$.ph_load_toolbar||$.ph_load_editor;!D(e)&&Se(e)?e(t,this.instance):Bl.warn("No toolbar load function found")}loadToolbar(t){var e=!(C==null||!C.getElementById(bu));if(!v||e)return!1;var s=this.instance.requestRouter.region==="custom"&&this.instance.config.advanced_disable_toolbar_metrics,r=w({token:this.instance.config.token},t,{apiURL:this.instance.requestRouter.endpointFor("ui")},s?{instrument:!1}:{});if(v.localStorage.setItem(Dl,JSON.stringify(w({},r,{source:void 0}))),this.Vl()===2)this.Zl(r);else if(this.Vl()===0){var n;this.Wl(1),(n=$.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this.instance,"toolbar",(i=>{if(i)return Bl.error("[Toolbar] Failed to load",i),void this.Wl(0);this.Wl(2),this.Zl(r)})),ne(v,"turbolinks:load",(()=>{this.Wl(0),this.loadToolbar(r)}))}return!0}Gl(t){return this.loadToolbar(t)}maybeLoadEditor(t,e,s){return t===void 0&&(t=void 0),e===void 0&&(e=void 0),s===void 0&&(s=void 0),this.maybeLoadToolbar(t,e,s)}}},Pf=w({experiments:ye},Tn),Af={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;D(e)||(Ke(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||ro(this._instance.config)||this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut())){var t=$?.__PosthogExtensions__;if(t&&!x(this.Ql)&&this.Ql)if(this.Jl&&this.Jl.token){this.Kl=!0;try{var e=t.initConversations;if(e)return this.tu(e),void(this.Kl=!1);var s=t.loadExternalDependency;if(!s)return void this.eu(Vo);s(this._instance,"conversations",(r=>{r||!t.initConversations?this.eu("Could not load conversations script",r):this.tu(t.initConversations),this.Kl=!1}))}catch(r){this.eu("Error initializing conversations",r),this.Kl=!1}}else Ue.error("Conversations enabled but missing token in remote config.")}}tu(t){if(this.Jl)try{this._conversationsManager=t(this.Jl,this._instance),this.Yl=!1,Ue.info("Conversations loaded successfully")}catch(e){this.eu("Error completing conversations initialization",e)}else Ue.error("Cannot complete initialization: remote config is null")}eu(t,e){Ue.error(t,e),this._conversationsManager=null,this.Kl=!1,this.Yl=!0}show(){this._conversationsManager?this._conversationsManager.show():Ue.warn("Conversations not loaded yet.")}hide(){this._conversationsManager&&this._conversationsManager.hide()}isAvailable(){return this.Ql===!0&&!$e(this._conversationsManager)}getUnavailableReason(){return this.isAvailable()?null:this._instance.config.disable_conversations?"disabled_by_config":ro(this._instance.config)?"disabled_for_toolbar":this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut()?"consent_opted_out":this.Xl===!1?"remote_config_failed":x(this.Ql)?this.Xl?"disabled_in_project":"remote_config_pending":this.Ql?D(this.Jl)||!this.Jl.token?"missing_token":$!=null&&$.__PosthogExtensions__?this.Kl?"initializing":this.Yl?"load_failed":"not_loaded":"extensions_unavailable":"disabled_in_project"}isVisible(){var t,e;return(t=(e=this._conversationsManager)==null?void 0:e.isVisible())!==null&&t!==void 0&&t}sendMessage(t,e,s){var r=this;return X((function*(){return r._conversationsManager?r._conversationsManager.sendMessage(t,e,s):(Ue.warn(Dt),null)}))()}getMessages(t,e){var s=this;return X((function*(){return s._conversationsManager?s._conversationsManager.getMessages(t,e):(Ue.warn(Dt),null)}))()}markAsRead(t){var e=this;return X((function*(){return e._conversationsManager?e._conversationsManager.markAsRead(t):(Ue.warn(Dt),null)}))()}getTickets(t){var e=this;return X((function*(){return e._conversationsManager?e._conversationsManager.getTickets(t):(Ue.warn(Dt),null)}))()}requestRestoreLink(t){var e=this;return X((function*(){return e._conversationsManager?e._conversationsManager.requestRestoreLink(t):(Ue.warn(Dt),null)}))()}restoreFromToken(t){var e=this;return X((function*(){return e._conversationsManager?e._conversationsManager.restoreFromToken(t):(Ue.warn(Dt),null)}))()}restoreFromUrlToken(){var t=this;return X((function*(){return t._conversationsManager?t._conversationsManager.restoreFromUrlToken():(Ue.warn(Dt),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()}}},$f={logs:class{constructor(t){var e,s=this;this.iu=!1,this.ru=!1,this.rt=se("[logs]"),this.nu=w({},this.rt,{error(){for(var r=arguments.length,n=new Array(r),i=0;r>i;i++)n[i]=arguments[i];n.some(Gl)||s.rt.error(...n)}}),this.tr=[],this.su=[],this.Sa=0,this.au=()=>{var r,n;this.Sa=0,(r=this.ou)==null||r.onReconnect(),(n=this.lu)==null||n.onReconnect()},this._instance=t,this._instance&&(e=this._instance.config.logs)!=null&&e.captureConsoleLogs&&(this.iu=!0),v&&ne(v,"online",this.au)}uu(t,e,s,r){var n,i=(function(o,a){var l,u,c,d,h,p,f,g=(l=o?.flushIntervalMs)!==null&&l!==void 0?l:3e3,m=(u=o?.maxBufferSize)!==null&&u!==void 0?u:100,_=a!=null&&a.consoleCapture?void 0:(c=o?.maxLogsPerInterval)!==null&&c!==void 0?c:1e3,b=x(_)?Math.max(m,2048):Math.max(m,_),E=o?.resourceAttributes;return{serviceName:(d=(h=E?.["service.name"])!==null&&h!==void 0?h:o?.serviceName)!==null&&d!==void 0?d:a?.serviceNameDefault,serviceVersion:(p=E?.["service.version"])!==null&&p!==void 0?p:o?.serviceVersion,environment:(f=E?.["deployment.environment"])!==null&&f!==void 0?f:o?.environment,resourceAttributes:E,beforeSend:o?.beforeSend,flushIntervalMs:g,maxBufferSize:m,maxQueueSize:b,maxBatchRecordsPerPost:100,rateCapWindowMs:g,maxLogsPerInterval:_,backgroundFlushBudgetMs:0,terminationFlushBudgetMs:0}})((n=this._instance)==null||(n=n.config)==null?void 0:n.logs,s);return[new Nh(this.hu(t,e),i,this.nu,(()=>this.du()),(o=>o()),void 0,r),i]}vu(){var t,e=(t=this._instance)==null||(t=t.config)==null?void 0:t.logs;if(!this.ou||this.cu!==e){var s;(s=this.ou)==null||s.reset(),this.cu=e;var r=this.uu((()=>this.tr),(n=>{this.tr=n}));this.ou=r[0],this.fu=r[1]}return this.ou}pu(){var t,e=(t=this._instance)==null||(t=t.config)==null?void 0:t.logs;if(!this.lu||this.gu!==e){var s;(s=this.lu)==null||s.reset(),this.gu=e;var r=this.uu((()=>this.su),(n=>{this.su=n}),{serviceNameDefault:"posthog-browser-logs",consoleCapture:!0},Vl);this.lu=r[0],this.mu=r[1]}return this.lu}initialize(){this.loadIfEnabled()}onRemoteConfig(t){var e;if(t.ok){var s=(e=t.config.logs)==null?void 0:e.captureConsoleLogs;!D(s)&&s&&(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){Gl(t)||this.rt.error("PostHog logs flush failed:",t)}loadIfEnabled(){if(this.iu&&!this.ru){var t=$?.__PosthogExtensions__;if(t){var e=t.loadExternalDependency;e?e(this._instance,"logs",(s=>{var r;s||(r=t.logs)==null||!r.initializeLogs?this.rt.error("Could not load logs script",s):(t.logs.initializeLogs(this._instance),this.ru=!0)})):this.rt.error(Vo)}else this.rt.error("PostHog Extensions not found.")}}hu(t,e){var s=this._instance;return{get isDisabled(){return!1},get optedOut(){return!s.is_capturing()},getPersistedProperty:r=>r===ut.LogsQueue?t():void 0,setPersistedProperty(r,n){var i;r===ut.LogsQueue&&e((i=n)!==null&&i!==void 0?i:[])},Ot:r=>this.Ot(r),getLibraryId:()=>Y.LIB_NAME,getLibraryVersion:()=>Y.LIB_VERSION}}Ot(t){return new Promise((e=>{if(Tu(this.Sa,3))e({kind:"fatal",error:Ii(void 0,"logs endpoint is unreachable, dropping batch")});else{var s=!1,r=i=>{s||(s=!0,clearTimeout(n),e(i))},n=setTimeout((()=>{this.rt.warn("Logs request timed out before receiving a response"),r({kind:"retry-later",error:Ii(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:i=>{var o=i.statusCode;if(this.ku(o),o>=200&&300>o)r({kind:"ok"});else if(o===413)r({kind:"too-large"});else if(o!==0&&o!==429&&500>o)r({kind:"fatal",error:new Error("logs request failed with status "+o)});else{var a;o===0?(i.error||this.rt.warn("Logs request failed before receiving an HTTP response"),r({kind:"retry-later",error:Ii(i.error,"logs request failed before receiving an HTTP response")})):r({kind:"retry-later",error:(a=i.error)!==null&&a!==void 0?a:new Error("logs request failed with status "+o)})}}})}}))}ku(t){(t!==0||this._instance.__loaded)&&(this.Sa=Nu(t,this.Sa,3,(()=>this.rt.warn("Log requests are failing before receiving an HTTP response; this can happen due to network issues, CORS, browser blocking, or ad blockers. Stopped sending logs; will try again when connectivity changes."))))}bu(t){this.tr.length>0&&this.xu(t,this.tr,this.fu,Y.LIB_NAME,(e=>{this.tr=e})),this.su.length>0&&this.xu(t,this.su,this.mu,Vl,(e=>{this.su=e}))}xu(t,e,s,r,n){if(e.length!==0){var i=e.map((a=>a.record));n([]);var o=nu(i,ru(s,Y.LIB_NAME,Y.LIB_VERSION),r,Y.LIB_VERSION);this._instance._send_request({method:"POST",url:this.wu(),data:o,compression:"best-available",batchKey:"logs",transport:t})}}wu(){return this._instance.requestRouter.endpointFor("api","/i/v1/logs")+"?token="+encodeURIComponent(this._instance.config.token)}du(){var t,e={};if(e.distinctId=this._instance.get_distinct_id(),this._instance.sessionManager){var s=this._instance.sessionManager.checkAndGetSessionAndWindowId(!0),r=s.windowId,n=s.sessionStartTimestamp,i=s.lastActivityTimestamp;e.sessionId=s.sessionId,e.windowId=r,D(n)||(e.sessionStartTimestamp=n),D(i)||(e.lastActivityTimestamp=i)}if($!=null&&(t=$.location)!=null&&t.href&&(e.currentUrl=this._instance.config.disable_capture_url_hashes?Ct($.location.href):$.location.href),this._instance.featureFlags){var o=this._instance.featureFlags.getFlags();o&&o.length>0&&(e.activeFeatureFlags=o)}return e}}},Rf={metrics:class{constructor(t){this.rt=se("[metrics]"),this._instance=t}initialize(){}vu(){var t,e,s=(t=this._instance)==null||(t=t.config)==null?void 0:t.metrics;return this.ou&&this.cu===s||((e=this.ou)==null||e.reset(),this.cu=s,this.ou=new Mh(this.hu(),(function(r){var n,i,o,a,l,u=r?.resourceAttributes;return{serviceName:(n=u?.["service.name"])!==null&&n!==void 0?n:r?.serviceName,serviceVersion:(i=u?.["service.version"])!==null&&i!==void 0?i:r?.serviceVersion,environment:(o=u?.["deployment.environment"])!==null&&o!==void 0?o:r?.environment,resourceAttributes:u,beforeSend:r?.beforeSend,flushIntervalMs:(a=r?.flushIntervalMs)!==null&&a!==void 0?a:1e4,maxSeriesPerFlush:(l=r?.maxSeriesPerFlush)!==null&&l!==void 0?l:1e3}})(s),this.rt)),this.ou}count(t,e,s){e===void 0&&(e=1),this.vu().count(t,e,s)}gauge(t,e,s){this.vu().gauge(t,e,s)}histogram(t,e,s){this.vu().histogram(t,e,s)}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((s=>this.rt.error("PostHog metrics flush failed:",s)))}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:s=>e.Jt(s),getLibraryId:()=>Y.LIB_NAME,getLibraryVersion:()=>Y.LIB_VERSION}}Jt(t,e){return new Promise((s=>{var r=!1,n=o=>{r||(r=!0,clearTimeout(i),s(o))},i=setTimeout((()=>n({kind:"retry-later",error:new Error("metrics request timed out")})),9e4);this._instance._send_request(w({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)n({kind:"ok"});else if(a===413)n({kind:"too-large"});else if(a!==0&&a!==429&&500>a)n({kind:"fatal",error:new Error("metrics request failed with status "+a)});else{var l;n({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)}}},Tf=w({},Tn,bf,Ef,Sf,xf,kf,Cf,If,Ff,Pf,Af,$f,Rf);Te.__defaultExtensionClasses=w({},Tf);var ud=(function(){Y.SDK_DIST_CHANNEL="npm";var t=Zs[as]=new Te;return(function(){function e(){e.done||(e.done=!0,ld=!1,Z(Zs,(function(s){s._dom_loaded()})))}C!=null&&C.addEventListener?C.readyState==="complete"?e():ne(C,"DOMContentLoaded",e,{capture:!1}):v&&k.error("Browser doesn't support `document.addEventListener` so PostHog couldn't be initialized")})(),t})();const dd="CodeFile",hd="GeneratedCode",Nf={CustomAction:"A",CustomWidget:"W",CustomFunction:"F",CustomClass:"C",CodeFile:"C"};function kt(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function go(t){return String(t||"").trim().replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function Mf(t={},e=0){const s=go(t.artifactType||t.type||dd),r=go(t.artifactName||t.name||t.fileName||`${hd}-${e+1}`);return`${s||"artifact"}-${r||e+1}`}function pd(t={},e=0){const s=kt(t),r=s.artifactType||s.type||dd,n=s.artifactName||s.name||hd;let i=s.fileName||n;return i.endsWith(".dart")||(i+=".dart"),{id:go(s.id)||Mf({...s,artifactType:r,artifactName:n,fileName:i},e),artifactType:r,artifactName:n,fileName:i,deployPath:s.deployPath||"",description:s.description||"",code:s.code||s.content||"",dependencies:fd(s.dependencies),imports:Array.isArray(s.imports)?s.imports:[],publicApi:Array.isArray(s.publicApi)?s.publicApi:[],relationships:gd(s.relationships),deployStatus:s.deployStatus||"pending",review:s.review||null,metadata:kt(s.metadata),codeType:s.codeType||Nf[r]||"O"}}function fd(t){return t?Array.isArray(t)?t.map(e=>{if(typeof e=="string")return{name:e,version:null,inferred:!1};const s=kt(e),r=s.name||s.package;return r?{name:r,version:s.version||null,versionRequired:!!(s.versionRequired||s.required),inferred:!!s.inferred,...s.reason?{reason:s.reason}:{}}:null}).filter(Boolean):Object.entries(kt(t)).map(([e,s])=>({name:e,version:s||null,inferred:!1})):[]}function gd(t){return t?(Array.isArray(t)?t:[t]).map(e=>{const s=kt(e);return!s.from&&!s.to?null:{from:s.from||null,to:s.to||null,type:s.type||"uses",description:s.description||""}}).filter(Boolean):[]}function mo(t){if(typeof t!="string")return null;const e=t.trim();if(!e)return null;try{return JSON.parse(e)}catch{const s=e.match(/```(?:json)?\s*([\s\S]*?)```/i);if(!s)return null;try{return JSON.parse(s[1].trim())}catch{return null}}}function ar(t,e={}){const s=[],r=typeof t=="string"?mo(t):t,i=kt(r||{});!r&&typeof t=="string"&&s.push("Structured bundle parse failed; using legacy single-artifact fallback.");const o=Array.isArray(i.artifacts)?i.artifacts:[{artifactType:i.artifactType||e.artifactType,artifactName:i.artifactName||e.artifactName,fileName:i.fileName||e.fileName,description:i.description,code:i.code||e.code||(typeof t=="string"?t:""),dependencies:i.dependencies||e.dependencies,relationships:i.relationships||e.relationships}];o.forEach((d,h)=>{!d?.artifactType&&!d?.type&&s.push(`Artifact ${h+1} has no artifactType; it will deploy as a standalone code file under lib/custom_code/ root.`)});const a=o.map((d,h)=>pd(d,h)),l=new Map(o.map((d,h)=>[kt(d).id,a[h]?.id]).filter(([d,h])=>d&&h)),u=d=>l.get(d)||d,c=gd(i.relationships||e.relationships).map(d=>({...d,from:d.from?u(d.from):d.from,to:d.to?u(d.to):d.to}));return{schemaVersion:i.schemaVersion||e.schemaVersion||null,id:i.id||e.id||"bundle-current",title:i.title||i.name||e.title||"Generated artifact bundle",description:i.description||e.description||"",artifacts:a,dependencies:fd(i.dependencies||e.dependencies),relationships:c,deployOrder:Array.isArray(i.deployOrder)?i.deployOrder.map(u):a.map(d=>d.id),warnings:[...s,...Array.isArray(i.warnings)?i.warnings:[]],metadata:kt(i.metadata)}}function mn(t){return ar(t).artifacts[0]||pd()}function yt(t){if(typeof t!="string")return t??"";const e=t.trim();if(!e)return"";try{return JSON.parse(e)}catch{return t}}function ws(t){return JSON.stringify(t,null,2)}function Lf(t){return ws({task:"architect",userRequest:String(t??"")})}function Of(t){const e=yt(t);return e&&typeof e=="object"&&typeof e.task=="string"?ws(e):ws({task:"generate_bundle",bundleSpec:e})}function Df(t){return ws({task:"review_bundle",generatedBundle:yt(t),outputRequirements:{bundleReview:["status","score","summary","manualActions","findings"],scoreRange:[0,100],eachArtifact:["id","review.status","review.findings"],manualActions:{definition:"Setup the developer must perform by hand in the FlutterFlow editor that FlutterFlow will NOT do for them.",exclude:["creating the Custom Action, Widget or Code File itself - deploying the code creates it","declaring parameters or return values FlutterFlow derives from the function signature","anything that resolves as a side effect of using the action or widget in the editor","generic advice such as testing, reviewing or rebuilding the app"],preferEmpty:"Return an empty array when nothing qualifies - an empty list is the expected result for most bundles."}}})}function ea(t,e=null){const s={stage:t};return e!=null&&(s.bundle=yt(e)),s}function Bf({bundleSpec:t,artifactBundle:e,bundleReview:s,artifactId:r,userFeedback:n}){return ws({task:"regenerate_artifact",artifactId:r,bundleSpec:yt(t),artifactBundle:yt(e),bundleReview:yt(s),userFeedback:String(n)})}function md({bundleSpec:t,artifactBundle:e,bundleReview:s,userFeedback:r}){return ws({task:"regenerate_bundle",bundleSpec:yt(t),artifactBundle:yt(e),bundleReview:yt(s),userFeedback:String(r??"")})}const Kl={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"},jf=["sanitizationResult","modelArmor","modelArmorResult","data","result","error"];function Le(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function Uf(t){return Le(t)?typeof t.filterMatchState=="string"||typeof t.invocationResult=="string"||Array.isArray(t.matchedFilters)||Le(t.filterSummary)||Le(t.filterResults):!1}function vd(t,e=0){if(!Le(t)||e>3)return null;if(Uf(t))return t;for(const s of jf){const r=t[s];if(Le(r)){const n=vd(r,e+1);if(n)return n}}return null}function vn(t){return Array.isArray(t)?t.some(vn):Le(t)?t.matched===!0||t.matchState==="MATCH_FOUND"?!0:Object.values(t).some(vn):!1}function vo(t){return Array.isArray(t)?t.some(vo):Le(t)?typeof t.executionState=="string"&&t.executionState!=="EXECUTION_SUCCESS"?!0:Object.values(t).some(vo):!1}function _d(t){return{csamFilterFilterResult:"csam",maliciousUriFilterResult:"malicious_uris",piAndJailbreakFilterResult:"pi_and_jailbreak",raiFilterResult:"rai",sdpFilterResult:"sdp",virusScanFilterResult:"virus_scan"}[t]||t}function Hf(t,e){if(Le(t))for(const[s,r]of Object.entries(t)){if(!Le(r))continue;const n=Le(r.categories)?r.categories:{},i=Object.entries(n).filter(([,o])=>Le(o)&&o.matched===!0).map(([o])=>o);i.length>0?i.forEach(o=>e.add(o)):r.matched===!0&&e.add(_d(s))}}function Wf(t,e){if(!t)return;const s=Array.isArray(t)?t.flatMap(r=>Le(r)?Object.entries(r):[]):Object.entries(t);for(const[r,n]of s){if(!vn(n))continue;const i=_d(r),o=n?.raiFilterResult?.raiFilterTypeResults||(i==="rai"?n?.raiFilterTypeResults:null),a=Le(o)?Object.entries(o).filter(([,l])=>vn(l)).map(([l])=>l):[];a.length>0?a.forEach(l=>e.add(l)):e.add(i)}}function zf(t){return Kl[t]?Kl[t]:String(t).replace(/([a-z])([A-Z])/g,"$1 $2").replace(/_/g," ").toLowerCase()}function Jl(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 qf(t){const e=vd(t);if(!e)return null;const s=new Set(Array.isArray(e.matchedFilters)?e.matchedFilters:[]);Hf(e.filterSummary,s),Wf(e.filterResults,s);const r=e.blocked===!0||e.filterMatchState==="MATCH_FOUND"||s.size>0,n=e.invocationResult||null,i=vo(e.filterSummary||e.filterResults);return!r&&!i&&!["PARTIAL","FAILURE"].includes(n)?null:{kind:r?"blocked":"unavailable",invocationResult:n,matchedFilters:[...s]}}function Vf(t,e){const s=qf(t);if(!s)return null;const r=[...new Set(s.matchedFilters.map(zf))],n=s.kind==="blocked",i=new Error(n?`Safety screening blocked this pipeline step for ${Jl(r)}.`:"Safety screening could not be completed. Please try again.");return i.name="ModelArmorError",i.code=n?"MODEL_ARMOR_BLOCKED":"MODEL_ARMOR_UNAVAILABLE",i.isModelArmor=!0,i.pipelineStep=e,i.userTitle=n?"Request blocked for safety":"Safety check unavailable",i.userMessage=n?`The safety check detected ${Jl(r)}. Edit your request to remove or rephrase the flagged content, then run the pipeline again.`:"The safety service did not finish all of its checks. Please wait a moment and run the pipeline again.",i.retryExplanation=n?"Trying another model would not change this safety decision.":"A fallback model was not attempted because safety screening must complete first.",i.matchedFilters=s.matchedFilters,i}function Gf(t){return String(t||"").replace(/\/\*[\s\S]*?\*\//g,"").replace(/\/\/[^\n]*/g,"")}function Yl(t){const e=/^(import|export|part|library|class|enum|extension|typedef|mixin|abstract|const|final|var|late)\b/,s=[];for(const r of Gf(t).split(` +`)){if(!/^[A-Za-z_$]/.test(r)||e.test(r))continue;const n=r.match(/^[\w$<>,?\s[\]]+?\s([a-zA-Z_$][\w$]*)\s*\(/);n&&s.push(n[1])}return s}function ta(t,e){const s=t.replace(/\.dart$/,"");if(e==="W")return s.replace(/(^|_)(\w)/g,(r,n,i)=>i.toUpperCase());if(e==="A"){const r=s.replace(/(^|_)(\w)/g,(n,i,o)=>o.toUpperCase());return r.charAt(0).toLowerCase()+r.slice(1)}return e==="F"?"CustomFunctions":e==="C"?t.endsWith(".dart")?t:`${t}.dart`:s}async function Zl(t){const e=new TextEncoder().encode(String(t||"")),s=await globalThis.crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(s),r=>r.toString(16).padStart(2,"0")).join("")}async function Kf(t,e=new Map){const s={},r=new Set;for(const[o,a]of t.entries()){if(a.type==="D"||a.type==="O")continue;const l=ta(o,a.type),u={old_identifier_name:l,new_identifier_name:l,type:a.type,is_deleted:!1,current_checksum:await Zl(a.content)},c=e.get(a.path);if(c!==void 0&&(u.original_checksum=await Zl(c)),s[o]=u,a.type==="F"){const d=Yl(a.content);(d.length>0?d:[a.functionName].filter(Boolean)).forEach(p=>r.add(p))}}const n=new Set(Yl(e.get("lib/flutter_flow/custom_functions.dart")||"")),i={functions_to_rename:[],functions_to_delete:[],functions_to_add:Array.from(r).filter(o=>!n.has(o))};return{fileMapContents:JSON.stringify(s),functionsMapContents:JSON.stringify(i)}}const Jf=new Set(["CustomWidget","CustomAction","CustomFunction","CustomClass","CodeFile"]),Xl={CustomWidget:"custom_code/widgets/",CustomAction:"custom_code/actions/",CustomFunction:"flutter_flow/custom_functions.dart",CustomClass:"custom_code/",CodeFile:"custom_code/"},Yf=new Set(["void","dynamic","String","int","double","num","bool","Color","DateTime","DateTimeRange","LatLng","FFPlace","FFUploadedFile","DocumentReference","List"]),Zf=["Struct","Record"],Xf=[{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=>Ci(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=>Ci(t).some(e=>{const s=/^\s*final\s+(?:double|int|String|bool|Color|num)\s+(\w+)\s*;/gm;let r;for(;(r=s.exec(e))!==null;){const n=r[1];if(!(new RegExp(`this\\.${n}\\s*=(?!=)`).test(e)||new RegExp(`[:,]\\s*${n}\\s*=(?!=)`).test(e)))return!0}return!1}),pos:`class W extends StatefulWidget { const W({required this.value}); final double value; }`,neg:`class _P { @@ -14,7 +14,7 @@ class W extends StatefulWidget { final double value; }`},{id:"asset-without-anchor",severity:"warning",message:'CustomWidget calls Image.asset with a path arriving as a String parameter. An asset reaches the build only when a FlutterFlow widget NODE references it - a filename passed as a parameter does not count, so the image renders as a broken-image icon on device. "Download Unused Project Assets" does not fix it (FlutterFlow issues 522, 2271, 3799). Keep something in the UI referencing the file, or load it over the network instead.',detect:t=>/Image\.asset\s*\(/.test(t)&&/final\s+String\??\s+\w*[Pp]ath\b/.test(t),pos:`class W extends StatefulWidget { final String? imagePath; } var x = Image.asset(widget.imagePath);`,neg:`class W extends StatefulWidget { final String? imagePath; } -var x = Image.network(widget.imagePath);`},{id:"unsupported-param-type",severity:"error",message:"CustomWidget exposes a Flutter data type FlutterFlow cannot express as a Define Parameter: TextStyle, BoxShadow, FontWeight, FontStyle, TextDirection, TextAlign, EdgeInsets, Offset, Alignment/AlignmentGeometry, Border, BorderRadius, BoxDecoration, BoxConstraints, BorderSide, Gradient, or ThemeData. FlutterFlow's supported data types (docs.flutterflow.io/resources/data-representation/data-types) are only int, double, bool, string, Color, Image, DateTime, Json, LatLng, and the FF objects, so this parameter cannot be configured in the editor and the widget will not place or compile. Expose primitives instead (color, fontSize as double?, fontWeight via a custom enum, doubles for spacing).",detect:t=>kn(t).some(e=>/final\s+(TextStyle|BoxShadow|FontWeight|FontStyle|TextDirection|TextAlign|EdgeInsets|Offset|Alignment(?:Geometry)?|Border(?:Radius|Side)?|BoxDecoration|BoxConstraints|Gradient|LinearGradient|RadialGradient|ThemeData)\??\s+\w+\s*;/.test(e)),pos:`class W extends StatefulWidget { +var x = Image.network(widget.imagePath);`},{id:"unsupported-param-type",severity:"error",message:"CustomWidget exposes a Flutter data type FlutterFlow cannot express as a Define Parameter: TextStyle, BoxShadow, FontWeight, FontStyle, TextDirection, TextAlign, EdgeInsets, Offset, Alignment/AlignmentGeometry, Border, BorderRadius, BoxDecoration, BoxConstraints, BorderSide, Gradient, or ThemeData. FlutterFlow's supported data types (docs.flutterflow.io/resources/data-representation/data-types) are only int, double, bool, string, Color, Image, DateTime, Json, LatLng, and the FF objects, so this parameter cannot be configured in the editor and the widget will not place or compile. Expose primitives instead (color, fontSize as double?, fontWeight via a custom enum, doubles for spacing).",detect:t=>Ci(t).some(e=>/final\s+(TextStyle|BoxShadow|FontWeight|FontStyle|TextDirection|TextAlign|EdgeInsets|Offset|Alignment(?:Geometry)?|Border(?:Radius|Side)?|BoxDecoration|BoxConstraints|Gradient|LinearGradient|RadialGradient|ThemeData)\??\s+\w+\s*;/.test(e)),pos:`class W extends StatefulWidget { const W({this.textStyle}); final TextStyle? textStyle; @override _S createState() => _S(); @@ -24,37 +24,37 @@ class _S extends State { @override Widget build(BuildContext c) => const Size final double? width; @override _S createState() => _S(); } -class _S extends State { @override Widget build(BuildContext c) => Padding(padding: const EdgeInsets.all(8), child: const SizedBox()); }`}];function Qe(t,e,s){return{artifactId:t.id,artifactName:t.artifactName,artifactType:t.artifactType,severity:e,message:s}}function ar(t){let e="",s=0;for(;s"&&(s--,s===0))return{inner:t.slice(e+1,r),end:r+1};return null}function Qf(t,e){const s=new RegExp(`class\\s+${e}\\b[^{]*\\{`).exec(t);if(!s)return null;let r=0;for(let i=s.index+s[0].length-1;ieg(t).usable);function sg(t=""){const e=ar(t);return tg.filter(s=>s.detect(e)).map(({id:s,severity:r,message:i})=>({id:s,severity:r,message:i}))}function rg(t){const e=[],s=t.matchAll(/\bFuture\b/g);for(const r of s){let i=r.index+6,n=null;const o=i;for(;io;if(t[i]==="<"){const u=Xf(t,i);if(!u||(n=u.inner.replace(/\s+/g," ").trim(),i=u.end,!/\s/.test(t[i]||"")))continue;for(;iXl(o.functionName)===r);if(i)return i;const n=o=>!o.functionName.startsWith("_");return s.find(n)||s[0]}function Ri(t=""){return Array.from(ar(t).matchAll(/\b(?:class|enum)\s+([A-Za-z_]\w*)/g),e=>e[1])}function ig(t="",e=""){return Qo(t,e)?.returnType||null}function Ql(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 ng(t,e){const s=Ri(e);if(s.length===0)return null;const i=String(t||"").split("/").pop().replace(/\.dart$/,"");if(s.some(l=>Ql(l)===i)||s.length>1)return null;const[o]=s,a=`${Ql(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 ea(t){return String(t||"").replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,"")}function og(t,e,s=""){const r=Qo(e,s)?.functionName;if(!r)return null;const i=String(t||"").split("/").pop(),n=Xo(i,"A");if(n===r)return null;const o=`${ea(r)}.dart`;return`File name "${i}" does not match Action "${r}". FlutterFlow derives the action from the file name, so it looks for "${n}" and reports Action "${n}" declaration not found. Rename the file to "${o}" - FlutterFlow puts an underscore before every capital - or rename the function to "${n}".`}function ag(t="",e=""){return Qo(t,e)!==null}function lg(t,e=new Set){return(t?.match(/[A-Za-z_]\w*/g)||[]).filter(r=>Jf.has(r)?!1:!Yf.some(n=>r.endsWith(n))||e.has(r))}function cg(t,{functionName:e="",declaredTypes:s=new Set}={}){const r=ig(t,e),i=lg(r,s);if(i.length===0)return null;const[n]=i;let o;return s.has(n)?o=`uses Code File type "${n}", which FlutterFlow cannot process as an Action Return Value`:r===n?o="is not a FlutterFlow Action Return Value":o=`uses type "${n}", which is not a FlutterFlow Action Return Value`,`CustomAction return type "${r}" ${o}. Return JSON (Future) or an existing FlutterFlow Data Type (*Struct) instead.`}function ug(t,e={}){const s=[],r=t.fileName||"",i=t.code||"";if(Kf.has(t.artifactType)||s.push(Qe(t,"error",`Unsupported artifact type "${t.artifactType}".`)),r.endsWith(".dart")||s.push(Qe(t,"error","FlutterFlow custom code artifacts must use .dart files.")),!i.trim())return s.push(Qe(t,"warning","Generated artifact has no Dart code yet.")),s;if(t.artifactType==="CustomWidget"){/class\s+\w+\s+extends\s+(StatelessWidget|StatefulWidget)/.test(i)||s.push(Qe(t,"warning","CustomWidget code should declare a widget class extending StatelessWidget or StatefulWidget."));for(const n of sg(i))s.push(Qe(t,n.severity,n.message))}if(t.artifactType==="CustomAction"&&!ag(i,t.artifactName)&&s.push(Qe(t,"warning","CustomAction code should expose an async Future function callable from FlutterFlow.")),t.artifactType==="CustomAction"){const n=e.declaredTypes||new Set(Ri(i)),o=cg(i,{functionName:t.artifactName,declaredTypes:n});o&&s.push(Qe(t,"error",o));const a=og(r,i,t.artifactName);a&&s.push(Qe(t,"error",a))}if(t.artifactType==="CustomFunction"&&/class\s+\w+\s+extends\s+(StatelessWidget|StatefulWidget)/.test(i)&&s.push(Qe(t,"warning","CustomFunction should be a callable function, not a widget class.")),t.artifactType==="CustomClass"||t.artifactType==="CodeFile"){const n=ng(r,i);n&&s.push(Qe(t,"info",n))}return s}function dg(t){const e=Array.isArray(t?.artifacts)?t.artifacts:[],s=new Set(e.flatMap(n=>Ri(n.code||""))),r=e.flatMap(n=>ug(n,{declaredTypes:s})),i=e.map(n=>({artifactId:n.id,fileName:n.fileName,pathHint:Zl[n.artifactType]||Zl.CodeFile}));return{valid:r.every(n=>n.severity!=="error"),findings:r,deployHints:i}}const ec="// DO NOT REMOVE OR MODIFY THE CODE ABOVE!";function tc(t){return(/^\s*import\s+['"]([^'"]+)['"]/.exec(t)||[])[1]||null}function hg(t=""){const e=t.indexOf(ec);return e===-1?t:t.slice(e+ec.length).replace(/^\s*\n/,"")}const pg=/^\s*import\s+['"][^'"]+['"]\s*;\s*(?:\/\/.*)?$/;function fg(t="",e=""){const s=hg(t),r=new Set((e.match(/^\s*import .*$/gm)||[]).map(tc).filter(Boolean)),i=s.split(` -`).filter(n=>{const o=tc(n);return o===null||!r.has(o)?!0:!pg.test(n)}).join(` -`).replace(/^\s*\/\/ Automatic FlutterFlow imports\s*$/m,"").replace(/^\s*\n+/,"");return e+i}const gg=new Set(["flutter","flutter_test","flutter_driver","flutter_localizations"]);function _d(t){let e="",s=0;for(;s{const r=s.name||s.package;if(!r||r==="flutter")return e;const i=s.versionRequired||s.required;return e[r]=i&&s.version||"",e},{})}function wg(t){const e=new Map,s=new Map,r=[];for(const i of t)e.has(i.fileName)?r.push(`Duplicate deploy file name "${i.fileName}" for artifacts "${e.get(i.fileName)}" and "${i.artifactId}".`):e.set(i.fileName,i.artifactId),s.has(i.path)?r.push(`Duplicate deploy path "${i.path}" for artifacts "${s.get(i.path)}" and "${i.artifactId}".`):s.set(i.path,i.artifactId);return r}function bg(t,e={}){const s=Array.isArray(t?.artifacts)?t.artifacts:[],i=(e.selectedArtifactIds||t?.deployOrder||s.map(p=>p.id)).map(p=>s.find(f=>f.id===p)).filter(Boolean),n=[...t?.warnings||[]];let o=[];i.forEach(p=>{const f=yg(p),g=p.fixedCode||p.code||"",m=p.codeType||vg[p.artifactType]||Ne.OTHER;g.trim()||n.push(`${p.artifactName||p.id} has no generated code.`),o.push({artifactId:p.id,artifactName:p.artifactName,artifactType:p.artifactType,fileName:f,content:g,type:m,path:p.deployPath||_g(f,m),deployPath:p.deployPath||"",deployMode:"customCodeSync"})});const a="lib/flutter_flow/custom_functions.dart",l=o.map((p,f)=>({entry:p,index:f})).filter(({entry:p})=>p.type===Ne.FUNCTION&&p.path===a);if(l.length>1){const p=l[0],f={...p.entry,artifactId:l.map(({entry:m})=>m.artifactId).join("+"),artifactName:p.entry.artifactName,content:l.map(({entry:m})=>`// ${m.artifactId} +class _S extends State { @override Widget build(BuildContext c) => Padding(padding: const EdgeInsets.all(8), child: const SizedBox()); }`}];function Qe(t,e,s){return{artifactId:t.id,artifactName:t.artifactName,artifactType:t.artifactType,severity:e,message:s}}function lr(t){let e="",s=0;for(;s"&&(s--,s===0))return{inner:t.slice(e+1,r),end:r+1};return null}function eg(t,e){const s=new RegExp(`class\\s+${e}\\b[^{]*\\{`).exec(t);if(!s)return null;let r=0;for(let n=s.index+s[0].length-1;ntg(t).usable);function rg(t=""){const e=lr(t);return sg.filter(s=>s.detect(e)).map(({id:s,severity:r,message:n})=>({id:s,severity:r,message:n}))}function ng(t){const e=[],s=t.matchAll(/\bFuture\b/g);for(const r of s){let n=r.index+6,i=null;const o=n;for(;no;if(t[n]==="<"){const u=Qf(t,n);if(!u||(i=u.inner.replace(/\s+/g," ").trim(),n=u.end,!/\s/.test(t[n]||"")))continue;for(;nQl(o.functionName)===r);if(n)return n;const i=o=>!o.functionName.startsWith("_");return s.find(i)||s[0]}function Nn(t=""){return Array.from(lr(t).matchAll(/\b(?:class|enum)\s+([A-Za-z_]\w*)/g),e=>e[1])}function ig(t="",e=""){return sa(t,e)?.returnType||null}function ec(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 og(t,e){const s=Nn(e);if(s.length===0)return null;const n=String(t||"").split("/").pop().replace(/\.dart$/,"");if(s.some(l=>ec(l)===n)||s.length>1)return null;const[o]=s,a=`${ec(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 ra(t){return String(t||"").replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,"")}function ag(t,e,s=""){const r=sa(e,s)?.functionName;if(!r)return null;const n=String(t||"").split("/").pop(),i=ta(n,"A");if(i===r)return null;const o=`${ra(r)}.dart`;return`File name "${n}" does not match Action "${r}". FlutterFlow derives the action from the file name, so it looks for "${i}" and reports Action "${i}" declaration not found. Rename the file to "${o}" - FlutterFlow puts an underscore before every capital - or rename the function to "${i}".`}function lg(t="",e=""){return sa(t,e)!==null}function cg(t,e=new Set){return(t?.match(/[A-Za-z_]\w*/g)||[]).filter(r=>Yf.has(r)?!1:!Zf.some(i=>r.endsWith(i))||e.has(r))}function ug(t,{functionName:e="",declaredTypes:s=new Set}={}){const r=ig(t,e),n=cg(r,s);if(n.length===0)return null;const[i]=n;let o;return s.has(i)?o=`uses Code File type "${i}", which FlutterFlow cannot process as an Action Return Value`:r===i?o="is not a FlutterFlow Action Return Value":o=`uses type "${i}", which is not a FlutterFlow Action Return Value`,`CustomAction return type "${r}" ${o}. Return JSON (Future) or an existing FlutterFlow Data Type (*Struct) instead.`}function dg(t,e={}){const s=[],r=t.fileName||"",n=t.code||"";if(Jf.has(t.artifactType)||s.push(Qe(t,"error",`Unsupported artifact type "${t.artifactType}".`)),r.endsWith(".dart")||s.push(Qe(t,"error","FlutterFlow custom code artifacts must use .dart files.")),!n.trim())return s.push(Qe(t,"warning","Generated artifact has no Dart code yet.")),s;if(t.artifactType==="CustomWidget"){/class\s+\w+\s+extends\s+(StatelessWidget|StatefulWidget)/.test(n)||s.push(Qe(t,"warning","CustomWidget code should declare a widget class extending StatelessWidget or StatefulWidget."));for(const i of rg(n))s.push(Qe(t,i.severity,i.message))}if(t.artifactType==="CustomAction"&&!lg(n,t.artifactName)&&s.push(Qe(t,"warning","CustomAction code should expose an async Future function callable from FlutterFlow.")),t.artifactType==="CustomAction"){const i=e.declaredTypes||new Set(Nn(n)),o=ug(n,{functionName:t.artifactName,declaredTypes:i});o&&s.push(Qe(t,"error",o));const a=ag(r,n,t.artifactName);a&&s.push(Qe(t,"error",a))}if(t.artifactType==="CustomFunction"&&/class\s+\w+\s+extends\s+(StatelessWidget|StatefulWidget)/.test(n)&&s.push(Qe(t,"warning","CustomFunction should be a callable function, not a widget class.")),t.artifactType==="CustomClass"||t.artifactType==="CodeFile"){const i=og(r,n);i&&s.push(Qe(t,"info",i))}return s}function hg(t){const e=Array.isArray(t?.artifacts)?t.artifacts:[],s=new Set(e.flatMap(i=>Nn(i.code||""))),r=e.flatMap(i=>dg(i,{declaredTypes:s})),n=e.map(i=>({artifactId:i.id,fileName:i.fileName,pathHint:Xl[i.artifactType]||Xl.CodeFile}));return{valid:r.every(i=>i.severity!=="error"),findings:r,deployHints:n}}const tc="// DO NOT REMOVE OR MODIFY THE CODE ABOVE!";function sc(t){return(/^\s*import\s+['"]([^'"]+)['"]/.exec(t)||[])[1]||null}function pg(t=""){const e=t.indexOf(tc);return e===-1?t:t.slice(e+tc.length).replace(/^\s*\n/,"")}const fg=/^\s*import\s+['"][^'"]+['"]\s*;\s*(?:\/\/.*)?$/;function gg(t="",e=""){const s=pg(t),r=new Set((e.match(/^\s*import .*$/gm)||[]).map(sc).filter(Boolean)),n=s.split(` +`).filter(i=>{const o=sc(i);return o===null||!r.has(o)?!0:!fg.test(i)}).join(` +`).replace(/^\s*\/\/ Automatic FlutterFlow imports\s*$/m,"").replace(/^\s*\n+/,"");return e+n}const mg=new Set(["flutter","flutter_test","flutter_driver","flutter_localizations"]);function yd(t){let e="",s=0;for(;s{const r=s.name||s.package;if(!r||r==="flutter")return e;const n=s.versionRequired||s.required;return e[r]=n&&s.version||"",e},{})}function bg(t){const e=new Map,s=new Map,r=[];for(const n of t)e.has(n.fileName)?r.push(`Duplicate deploy file name "${n.fileName}" for artifacts "${e.get(n.fileName)}" and "${n.artifactId}".`):e.set(n.fileName,n.artifactId),s.has(n.path)?r.push(`Duplicate deploy path "${n.path}" for artifacts "${s.get(n.path)}" and "${n.artifactId}".`):s.set(n.path,n.artifactId);return r}function Eg(t,e={}){const s=Array.isArray(t?.artifacts)?t.artifacts:[],n=(e.selectedArtifactIds||t?.deployOrder||s.map(p=>p.id)).map(p=>s.find(f=>f.id===p)).filter(Boolean),i=[...t?.warnings||[]];let o=[];n.forEach(p=>{const f=wg(p),g=p.fixedCode||p.code||"",m=p.codeType||_g[p.artifactType]||Ne.OTHER;g.trim()||i.push(`${p.artifactName||p.id} has no generated code.`),o.push({artifactId:p.id,artifactName:p.artifactName,artifactType:p.artifactType,fileName:f,content:g,type:m,path:p.deployPath||yg(f,m),deployPath:p.deployPath||"",deployMode:"customCodeSync"})});const a="lib/flutter_flow/custom_functions.dart",l=o.map((p,f)=>({entry:p,index:f})).filter(({entry:p})=>p.type===Ne.FUNCTION&&p.path===a);if(l.length>1){const p=l[0],f={...p.entry,artifactId:l.map(({entry:m})=>m.artifactId).join("+"),artifactName:p.entry.artifactName,content:l.map(({entry:m})=>`// ${m.artifactId} ${m.content}`).join(` -`)},g=new Set(l.slice(1).map(({index:m})=>m));o=o.filter((m,_)=>!g.has(_)),o[p.index]=f}const u={...sc(t?.dependencies),...i.reduce((p,f)=>({...p,...sc(f.dependencies)}),{})},c={};i.forEach(p=>{ta(p.code||"").forEach(f=>{f in u||(c[f]="")})});const d={...c,...u},h=wg(o);return{bundleId:t?.id||"bundle-current",title:t?.title||"Generated artifact bundle",fileEntries:o,dependencies:d,relationships:t?.relationships||[],warnings:n,errors:h}}function Eg(t){return String(t||"").match(/\bclass\s+([A-Z][A-Za-z0-9_]*)\b/)?.[1]}function Sg(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 xg(t,e){const r=[Sg(t),Eg(e.content),e.artifactName].find(i=>/^[A-Z][A-Za-z0-9_]*$/.test(String(i||"")));if(!r)throw new Error(`Cannot derive a FlutterFlow custom class name for ${t}.`);return r}function kg(t,e=new Map){const s=[];for(const[r,i]of t.entries())i.type!=="C"||e.has(i.path)||s.push({artifactId:i.artifactId||r,className:xg(r,i),content:i.content,fileName:r,path:i.path});return s}function Ig(t,e){const s=new Set(e.map(r=>r.path));return new Map(Array.from(t.entries()).filter(([,r])=>!s.has(r.path)))}const rc={pass:0,warning:1,fail:2},Cg=["manualActions"];function De(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function gt(...t){for(const e of t){if(typeof e=="string"&&e.trim())return e.trim();if(Array.isArray(e)&&e.length>0){const s=e.filter(r=>typeof r=="string").join(` -`);if(s)return s}}return""}function tt(t){return t==null?[]:Array.isArray(t)?t:[t]}function Fg(t){const e=De(t).value??t;if(e==null||typeof e=="string"&&e.trim()==="")return null;const s=Number(e);if(Number.isFinite(s))return s;const r=String(t||"").match(/\bscore\b[^\d]{0,12}(\d{1,3})(?:\s*\/\s*100)?/i);return r?Number(r[1]):null}function We(t){return String(t||"").trim().replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function sa(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 mo(...t){return t.filter(Boolean).reduce((e,s)=>rc[s]>rc[e]?s:e,"pass")}function yd(t,e="warning",s="review"){if(typeof t=="string")return{severity:e,message:t,suggestion:"",source:s};const r=De(t),i=gt(r.message,r.title,r.issue,r.description,r.summary);return i?{severity:sa(r.severity||r.status||r.level)||e,message:i,suggestion:gt(r.suggestion,r.fix,r.recommendation,r.action),source:r.source||s}:null}function vo(t,e="review"){const s=De(t);return[["findings","warning"],["issues","warning"],["criticalIssues","fail"],["errors","fail"],["warnings","warning"],["recommendations","warning"],["requiredFixes","fail"],["suggestions","warning"]].flatMap(([i,n])=>tt(s[i]).map(o=>yd(o,n,e)).filter(Boolean))}function Pg(t,e,s=null){if(typeof t=="string")return{id:`${s||"bundle"}-manual-${e+1}`,title:t,detail:"",location:"",timing:"unspecified",artifactId:s,source:"Code Review"};const r=De(t),i=gt(r.title,r.action,r.step,r.message,r.name,r.description);return i?{id:r.id||`${s||"bundle"}-manual-${e+1}`,title:i,detail:gt(r.detail,r.instructions,r.description),location:gt(r.location,r.flutterFlowPath,r.path),timing:gt(r.timing,r.phase)||"unspecified",artifactId:s,source:gt(r.source)||"Code Review"}:null}function _o(t,e=null){const s=De(t);return Cg.flatMap(r=>tt(s[r])).map((r,i)=>Pg(r,i,e)).filter(Boolean)}function Ag(t){let e=typeof t=="string"?fo(t):t;if(!e&&typeof t=="string")return{rawText:t,root:{}};const s=De(e);typeof s.content=="string"&&(e=fo(s.content)||e);const r=De(e),i=De(r.reviewResult||r.codeReview||r.result);return{rawText:"",root:Object.keys(i).length?i:r}}function $g(t,e){const s=[e.id,e.fileName,e.artifactName].map(We);return t.find(r=>{const i=De(r);return[i.id,i.fileName,i.artifactName,i.name].map(We).some(n=>n&&s.includes(n))})||null}function Rg(t,e){return tt(t?.metadata?.compatibility?.deployHints).find(i=>We(i?.artifactId)===We(e.id)||We(i?.fileName)===We(e.fileName))?.pathHint||""}function Tg(t,e){return tt(t?.relationships).filter(s=>We(s?.from)===We(e.id)||We(s?.to)===We(e.id))}function Ng(t,e){return tt(t?.metadata?.compatibility?.findings).filter(s=>!s?.artifactId||We(s.artifactId)===We(e.id)).map(s=>yd(s,"warning","Compatibility check")).filter(Boolean)}function Mg(t,e,s,r){const i=$g(e,s),n=De(i?.review||i||s.review),o=Object.keys(n).length>0,a=[...vo(n),...Ng(t,s)],l=_o(n,s.id),u=sa(n.status||n.verdict||n.outcome||n.result),c=a.length?mo(...a.map(h=>h.severity)):null,d=mo(u,c,o?null:"warning");return{...s,index:r,status:d,statusReason:o?gt(n.summary,n.overview,n.assessment,n.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 n.fixedSource=="string"&&n.fixedSource.trim()?n.fixedSource.trim():null,pathHint:Rg(t,s),relationships:Tg(t,s)}}function Lg({status:t,score:e,artifactPresentations:s,manualSteps:r}){const i=s.length;if(i===0&&r.length===0)return e==null?"Code review returned no overall summary and no score.":`Reviewed bundle with score ${e}/100.`;const n=s.reduce((a,l)=>(a[l.status]+=1,a),{pass:0,warning:0,fail:0}),o=[];return t&&o.push(`Overall verdict: ${t}.`),i&&o.push(`${i} artifact${i===1?"":"s"}: ${n.pass} pass, ${n.warning} warn, ${n.fail} fail.`),r.length&&o.push(`Do before deploy: ${r.map(a=>a.title).join("; ")}.`),e==null&&o.push("No numeric score (0-100) was returned."),o.join(" ")}function Og({bundle:t,reviewResult:e}){const s=De(t),r=tt(s.artifacts),{root:i,rawText:n}=Ag(e),o=[i.bundleReview,i.overallReview,i.overall,i.bundleSummary,i.summaryReview,i.review].map(De).find(b=>Object.keys(b).length)||{},a=tt(i.artifacts||i.files||i.reviews),l=r.map((b,I)=>Mg(s,a,b,I)),u=vo(i),d=[...vo(o),...u],h=[..._o(o),..._o(i),...l.flatMap(b=>b.manualSteps)].filter((b,I,F)=>F.findIndex(P=>P.title===b.title&&P.artifactId===b.artifactId)===I),p=sa(o.status||o.verdict||o.overallStatus||i.status||i.verdict||i.overallStatus||i.outcome),f=mo(p,...d.map(b=>b.severity),...l.map(b=>b.status)),g=o.score??i.score??i.overallScore??n,m=Fg(g),_=gt(o.headline,o.summary,o.executiveSummary,o.overview,o.assessment,o.conclusion,i.overallSummary,i.headline,i.summary,i.executiveSummary,i.overview,i.assessment,i.conclusion,n)||Lg({status:f,score:m,artifactPresentations:l,manualSteps:h}),E=l.reduce((b,I)=>(b[I.status]+=1,b),{pass:0,warning:0,fail:0});return{title:s.title||"Generated artifact bundle",description:s.description||"",status:f,score:m,summary:_,findings:d,manualSteps:h,artifacts:l,counts:E,reviewCoverage:{reviewed:l.filter(b=>b.reviewComplete).length,total:l.length},deployOrder:tt(s.deployOrder),relationships:tt(s.relationships),warnings:tt(s.warnings),compatibility:De(s.metadata?.compatibility)}}const Dg=/^\uFEFF/;function Os(t){let e=0,s=t.length;for(;ee&&!t[s-1].trim();)s--;return t.slice(e,s).join(` -`)}function Bg(t){const e=String(t??"").replace(Dg,"");if(!e.trim())return"";const s=e.split(` -`),r=c=>{const d=c.trim();return/^`{3,}[A-Za-z0-9+#_.-]*$/.test(d)?c.length-c.trimStart().length:-1};let i=0,n=-1;const o=[];{let c=0;for(let d=0;d=0&&(i++,n<0&&(n=d),o.push(c+h)),c+=s[d].length+1}}if(i===0)return Os(s);{const c=yo(e);if(!c.error&&o.every(h=>nc(h,c.commentAndStringRanges)))return Os(s)}if(i===1){const c=Os(s.slice(0,n)),d=Os(s.slice(n+1));return d.length>=c.length?d:c}const a=[];let l=null;for(let c=0;cm));o=o.filter((m,_)=>!g.has(_)),o[p.index]=f}const u={...rc(t?.dependencies),...n.reduce((p,f)=>({...p,...rc(f.dependencies)}),{})},c={};n.forEach(p=>{na(p.code||"").forEach(f=>{f in u||(c[f]="")})});const d={...c,...u},h=bg(o);return{bundleId:t?.id||"bundle-current",title:t?.title||"Generated artifact bundle",fileEntries:o,dependencies:d,relationships:t?.relationships||[],warnings:i,errors:h}}function Sg(t){return String(t||"").match(/\bclass\s+([A-Z][A-Za-z0-9_]*)\b/)?.[1]}function xg(t){return String(t||"").split("/").pop().replace(/\.dart$/,"").split(/[^A-Za-z0-9]+/).filter(Boolean).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join("")}function kg(t,e){const r=[xg(t),Sg(e.content),e.artifactName].find(n=>/^[A-Z][A-Za-z0-9_]*$/.test(String(n||"")));if(!r)throw new Error(`Cannot derive a FlutterFlow custom class name for ${t}.`);return r}function Ig(t,e=new Map){const s=[];for(const[r,n]of t.entries())n.type!=="C"||e.has(n.path)||s.push({artifactId:n.artifactId||r,className:kg(r,n),content:n.content,fileName:r,path:n.path});return s}function Cg(t,e){const s=new Set(e.map(r=>r.path));return new Map(Array.from(t.entries()).filter(([,r])=>!s.has(r.path)))}const nc={pass:0,warning:1,fail:2},Fg=["manualActions"];function De(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function gt(...t){for(const e of t){if(typeof e=="string"&&e.trim())return e.trim();if(Array.isArray(e)&&e.length>0){const s=e.filter(r=>typeof r=="string").join(` +`);if(s)return s}}return""}function tt(t){return t==null?[]:Array.isArray(t)?t:[t]}function Pg(t){const e=De(t).value??t;if(e==null||typeof e=="string"&&e.trim()==="")return null;const s=Number(e);if(Number.isFinite(s))return s;const r=String(t||"").match(/\bscore\b[^\d]{0,12}(\d{1,3})(?:\s*\/\s*100)?/i);return r?Number(r[1]):null}function We(t){return String(t||"").trim().replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function ia(t){const e=String(t||"").toLowerCase();return/(fail|error|critical|block|reject|invalid)/.test(e)?"fail":/(warn|attention|manual|partial|incomplete|concern)/.test(e)?"warning":/(pass|success|ready|approve|valid|clean|info|notice)/.test(e)?"pass":null}function _o(...t){return t.filter(Boolean).reduce((e,s)=>nc[s]>nc[e]?s:e,"pass")}function wd(t,e="warning",s="review"){if(typeof t=="string")return{severity:e,message:t,suggestion:"",source:s};const r=De(t),n=gt(r.message,r.title,r.issue,r.description,r.summary);return n?{severity:ia(r.severity||r.status||r.level)||e,message:n,suggestion:gt(r.suggestion,r.fix,r.recommendation,r.action),source:r.source||s}:null}function yo(t,e="review"){const s=De(t);return[["findings","warning"],["issues","warning"],["criticalIssues","fail"],["errors","fail"],["warnings","warning"],["recommendations","warning"],["requiredFixes","fail"],["suggestions","warning"]].flatMap(([n,i])=>tt(s[n]).map(o=>wd(o,i,e)).filter(Boolean))}function Ag(t,e,s=null){if(typeof t=="string")return{id:`${s||"bundle"}-manual-${e+1}`,title:t,detail:"",location:"",timing:"unspecified",artifactId:s,source:"Code Review"};const r=De(t),n=gt(r.title,r.action,r.step,r.message,r.name,r.description);return n?{id:r.id||`${s||"bundle"}-manual-${e+1}`,title:n,detail:gt(r.detail,r.instructions,r.description),location:gt(r.location,r.flutterFlowPath,r.path),timing:gt(r.timing,r.phase)||"unspecified",artifactId:s,source:gt(r.source)||"Code Review"}:null}function wo(t,e=null){const s=De(t);return Fg.flatMap(r=>tt(s[r])).map((r,n)=>Ag(r,n,e)).filter(Boolean)}function $g(t){let e=typeof t=="string"?mo(t):t;if(!e&&typeof t=="string")return{rawText:t,root:{}};const s=De(e);typeof s.content=="string"&&(e=mo(s.content)||e);const r=De(e),n=De(r.reviewResult||r.codeReview||r.result);return{rawText:"",root:Object.keys(n).length?n:r}}function Rg(t,e){const s=[e.id,e.fileName,e.artifactName].map(We);return t.find(r=>{const n=De(r);return[n.id,n.fileName,n.artifactName,n.name].map(We).some(i=>i&&s.includes(i))})||null}function Tg(t,e){return tt(t?.metadata?.compatibility?.deployHints).find(n=>We(n?.artifactId)===We(e.id)||We(n?.fileName)===We(e.fileName))?.pathHint||""}function Ng(t,e){return tt(t?.relationships).filter(s=>We(s?.from)===We(e.id)||We(s?.to)===We(e.id))}function Mg(t,e){return tt(t?.metadata?.compatibility?.findings).filter(s=>!s?.artifactId||We(s.artifactId)===We(e.id)).map(s=>wd(s,"warning","Compatibility check")).filter(Boolean)}function Lg(t,e,s,r){const n=Rg(e,s),i=De(n?.review||n||s.review),o=Object.keys(i).length>0,a=[...yo(i),...Mg(t,s)],l=wo(i,s.id),u=ia(i.status||i.verdict||i.outcome||i.result),c=a.length?_o(...a.map(h=>h.severity)):null,d=_o(u,c,o?null:"warning");return{...s,index:r,status:d,statusReason:o?gt(i.summary,i.overview,i.assessment,i.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 i.fixedSource=="string"&&i.fixedSource.trim()?i.fixedSource.trim():null,pathHint:Tg(t,s),relationships:Ng(t,s)}}function Og({status:t,score:e,artifactPresentations:s,manualSteps:r}){const n=s.length;if(n===0&&r.length===0)return e==null?"Code review returned no overall summary and no score.":`Reviewed bundle with score ${e}/100.`;const i=s.reduce((a,l)=>(a[l.status]+=1,a),{pass:0,warning:0,fail:0}),o=[];return t&&o.push(`Overall verdict: ${t}.`),n&&o.push(`${n} artifact${n===1?"":"s"}: ${i.pass} pass, ${i.warning} warn, ${i.fail} fail.`),r.length&&o.push(`Do before deploy: ${r.map(a=>a.title).join("; ")}.`),e==null&&o.push("No numeric score (0-100) was returned."),o.join(" ")}function Dg({bundle:t,reviewResult:e}){const s=De(t),r=tt(s.artifacts),{root:n,rawText:i}=$g(e),o=[n.bundleReview,n.overallReview,n.overall,n.bundleSummary,n.summaryReview,n.review].map(De).find(E=>Object.keys(E).length)||{},a=tt(n.artifacts||n.files||n.reviews),l=r.map((E,I)=>Lg(s,a,E,I)),u=yo(n),d=[...yo(o),...u],h=[...wo(o),...wo(n),...l.flatMap(E=>E.manualSteps)].filter((E,I,F)=>F.findIndex(P=>P.title===E.title&&P.artifactId===E.artifactId)===I),p=ia(o.status||o.verdict||o.overallStatus||n.status||n.verdict||n.overallStatus||n.outcome),f=_o(p,...d.map(E=>E.severity),...l.map(E=>E.status)),g=o.score??n.score??n.overallScore??i,m=Pg(g),_=gt(o.headline,o.summary,o.executiveSummary,o.overview,o.assessment,o.conclusion,n.overallSummary,n.headline,n.summary,n.executiveSummary,n.overview,n.assessment,n.conclusion,i)||Og({status:f,score:m,artifactPresentations:l,manualSteps:h}),b=l.reduce((E,I)=>(E[I.status]+=1,E),{pass:0,warning:0,fail:0});return{title:s.title||"Generated artifact bundle",description:s.description||"",status:f,score:m,summary:_,findings:d,manualSteps:h,artifacts:l,counts:b,reviewCoverage:{reviewed:l.filter(E=>E.reviewComplete).length,total:l.length},deployOrder:tt(s.deployOrder),relationships:tt(s.relationships),warnings:tt(s.warnings),compatibility:De(s.metadata?.compatibility)}}const Bg=/^\uFEFF/;function Ds(t){let e=0,s=t.length;for(;ee&&!t[s-1].trim();)s--;return t.slice(e,s).join(` +`)}function jg(t){const e=String(t??"").replace(Bg,"");if(!e.trim())return"";const s=e.split(` +`),r=c=>{const d=c.trim();return/^`{3,}[A-Za-z0-9+#_.-]*$/.test(d)?c.length-c.trimStart().length:-1};let n=0,i=-1;const o=[];{let c=0;for(let d=0;d=0&&(n++,i<0&&(i=d),o.push(c+h)),c+=s[d].length+1}}if(n===0)return Ds(s);{const c=bo(e);if(!c.error&&o.every(h=>oc(h,c.commentAndStringRanges)))return Ds(s)}if(n===1){const c=Ds(s.slice(0,i)),d=Ds(s.slice(i+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(` +${d}`,{commentAndStringRanges:g}=bo(f),m=p.length+1+h;if(oc(m,g)){l.push(d);continue}a.push(Ds(l)),l=null}const u=a.filter(c=>c.length>0);return u.length===0?"":u.join(` -`)}function jg(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 wd(t){const e=jg(t);return Array.from(e.matchAll(/class\s+([A-Z]\w*)\s+extends\s+[A-Za-z_]\w*Widget\b/g),s=>s[1])}function bd(t){return`${ea(t)}.dart`}function Ug(t){return Xo(t,"W")}const ic={"(":")","[":"]","{":"}"},Hg={")":"(","]":"[","}":"{"},Wg=/[A-Za-z0-9_]/;function yo(t){const e=[{kind:"code",opener:null,openedLine:0}],s=[];let r=1,i=0;const n=(c,d)=>{(c===` +`)}function Ug(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 bd(t){const e=Ug(t);return Array.from(e.matchAll(/class\s+([A-Z]\w*)\s+extends\s+[A-Za-z_]\w*Widget\b/g),s=>s[1])}function Ed(t){return`${ra(t)}.dart`}function Hg(t){return ta(t,"W")}const ic={"(":")","[":"]","{":"}"},Wg={")":"(","]":"[","}":"{"},zg=/[A-Za-z0-9_]/;function bo(t){const e=[{kind:"code",opener:null,openedLine:0}],s=[];let r=1,n=0;const i=(c,d)=>{(c===` `||c==="\r"&&d!==` -`)&&r++};let o=null;const a=()=>{for(const c of e)(c.kind==="string"||c.kind==="block-comment"||c.kind==="line-comment")&&s.push({start:c.startIndex,end:t.length})};for(;i0?t[i-1]:"",f=i>1?t[i-2]:"",g=(p==="r"||p==="R")&&!Wg.test(f);e.push({kind:"string",quote:c,triple:h,raw:g,startIndex:i,openedLine:r}),i+=h?3:1;continue}if(ic[c]){e.push({kind:"code",opener:c,openedLine:r}),i++;continue}if(Hg[c]){if(d.interpolation&&c==="}"){e.pop(),i++;continue}if(d.opener&&ic[d.opener]===c){e.pop(),i++;continue}return d.opener?(a(),{error:o??`line ${r}: "${c}" closes nothing - "${d.opener}" opened on line ${d.openedLine} is still open`,commentAndStringRanges:s}):(a(),{error:o??`line ${r}: unexpected "${c}" with no matching opener`,commentAndStringRanges:s})}n(c,t[i+1]),i++}a();let l=e.length-1;for(;l>0&&e[l].kind==="line-comment";)l--;let u=o;if(!u){const c=e[l];if(!(c.kind==="code"&&!c.opener&&!c.interpolation))if(c.kind==="string")u=`unclosed ${c.triple?"triple-quoted ":""}string starting on line ${c.openedLine} was never closed`;else if(c.kind==="block-comment")u=`unterminated /* comment starting on line ${c.openedLine}`;else if(c.interpolation){const d=e.findLast(p=>p.opener);u=`unclosed "\${" expression${d?` opened on line ${d.openedLine}`:""} was never closed`}else u=`"${c.opener}" opened on line ${c.openedLine} is never closed`}return{error:u,commentAndStringRanges:s}}function zg(t){return yo(String(t??"")).error}function nc(t,e){return e.some(({start:s,end:r})=>t>=s&&ttypeof s=="string"?s:s?.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 qg=/^dependencies\s*:\s*(?:#.*)?$/,Vg=/^(?:"([^"]+)"|'([^']+)'|([A-Za-z_][A-Za-z0-9_-]*))\s*:/;function ra(t){const e=t.match(Vg);return e?e[1]??e[2]??e[3]:null}function Ti(t){const e=t.trim();return e===""||e.startsWith("#")}function pr(t){const e=t.match(/^(\s*)/);return e?e[1].length:0}function ia(t,e){const s=t.findIndex(n=>e.test(n));if(s===-1)return null;let r=s,i=null;for(let n=s+1;n=0.0.0"}`}function Jg(t,e={}){const s=String(t||""),r=Object.entries(e).filter(([u])=>u&&u!=="flutter");if(r.length===0)return{yaml:s,added:[],alreadyPresent:[]};const i=s.split(` -`),n=new Set(Sd(s)),o=[],a=[];for(const[u,c]of r)n.has(u)?a.push(u):(o.push([u,c]),n.add(u));if(o.length===0)return{yaml:s,added:[],alreadyPresent:a};const l=na(i);if(l){const u=o.map(([c,d])=>oc(l.childIndent,c,d));i.splice(l.endIndex,0,...u)}else i.length>0&&i[i.length-1].trim()!==""&&i.push(""),i.push("dependencies:"),o.forEach(([u,c])=>{i.push(oc(" ",u,c))});return{yaml:i.join(` -`),added:o.map(([u])=>u),alreadyPresent:a}}function Yg(t,e={}){const s=String(t||""),r=Object.entries(e).filter(([l])=>l&&l!=="flutter");if(r.length===0)return{yaml:s,overridden:[],skipped:[]};const i=s.split(` -`),n=Ni(s),o=[],a=[];for(const[l,u]of r){const c=n.get(l);if(!c||!c.isScalar||!String(u||"").trim()){a.push(l);continue}const d=" ".repeat(pr(i[c.lineIndex]));i[c.lineIndex]=`${d}${l}: ${kd(String(u).trim())}${c.comment}`,o.push({name:l,from:c.constraint,to:u})}return{yaml:i.join(` -`),overridden:o,skipped:a}}function Id(t){const e=String(t||""),s=[];return e.trim()?(/^name:\s*\S+/m.test(e)||s.push("pubspec.yaml missing name field"),na(e.split(` -`))||s.push("pubspec.yaml missing dependencies section"),Sd(e).includes("flutter")||s.push("pubspec.yaml missing Flutter SDK dependency"),{valid:s.length===0,errors:s}):(s.push("pubspec.yaml is empty"),{valid:!1,errors:s})}const Zg=">=3.0.0 <4.0.0",Xg=new Set(["flutter","flutter_test","flutter_driver","flutter_localizations","integration_test"]);function Cd(t){const e=String(t||"").trim(),s=e[0];return s!=="'"&&s!=='"'||e[e.length-1]!==s?e:e.slice(1,-1).replaceAll(`${s}${s}`,s)}function Qg(t=""){const e=mg(t).filter(s=>!s.startsWith("dart:")&&!s.startsWith("package:"));return{selfContained:e.length===0,unresolvableImports:e}}function ac(t,e,s){const r=[];for(const[i,n]of t){if(Xg.has(i)&&!n.isScalar){s.add(i);continue}if(!n.isScalar){r.push(i);continue}e[i]=Cd(n.constraint)}return r}function em(t){const e=new Set,s={},r={},i=ac(Ni(t),s,e);i.push(...ac(Gg(t,"dependency_overrides"),r,e));const n=new Set([...Object.keys(s),...e]),{sdk:o}=xd(t);return{sdkConstraint:Cd(o)||Zg,dependencies:s,overrides:r,sdkPackages:[...e].sort(),availablePackages:n,unrepresentable:i}}function tm(t,e,s){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 ${s.join(", ")}, which your project's pubspec.yaml does not declare with a version constraint, so it could not be compiled before the deploy.`}function sm(t,e){const{sdkConstraint:s,dependencies:r,overrides:i,sdkPackages:n,availablePackages:o,unrepresentable:a}=em(e),l={sdkConstraint:s,dependencies:r,overrides:i,sdkPackages:n},u=[],c=[];for(const d of t){const{className:h,content:p}=d;if(a.length>0){c.push({className:h,reason:`${h} was not compiled before deploying: your project declares ${a.join(", ")} from a source that cannot be reproduced outside the project, so package resolution could not be matched exactly.`});continue}const{unresolvableImports:f}=Qg(p),g=ta(p).filter(m=>!o.has(m));if(f.length>0||g.length>0){c.push({className:h,reason:tm(h,f,g)});continue}u.push({fileName:`${ea(h)}.dart`,content:p})}return{manifest:l,sources:u,skipped:c}}function lc(t,e){const s=`${t}${e}`.split(` -`),r=s.pop()??"",i=[];for(const n of s){const o=Fd(n);o&&i.push(o)}return{events:i,buffer:r}}function rm(t){const e=Fd(t);return e?[e]:[]}function Fd(t){const e=t.trim();if(!e)return null;try{const s=JSON.parse(e);return s&&typeof s=="object"&&!Array.isArray(s)?s:null}catch{return null}}async function im(t,e={}){const{onPhase:s,onLog:r}=e;let i=null,n="";const o=a=>{if(a.event==="phase"){a.message&&s&&s(a.message);return}if(a.event==="log"){a.message&&r&&r(a.message);return}i=a};if(t.body?.getReader){const a=t.body.getReader(),l=new TextDecoder;for(;;){const{done:u,value:c}=await a.read();if(u)break;const d=lc(n,l.decode(c,{stream:!0}));n=d.buffer,d.events.forEach(o)}}else{const a=lc("",await t.text());n=a.buffer,a.events.forEach(o)}return rm(n).forEach(o),i?{...i,success:i.success===!0||i.success===void 0&&t.ok}:{success:!1,error:t.ok?"The FlutterFlow deploy runner closed the connection before it finished.":`FlutterFlow custom class provisioning failed (HTTP ${t.status}).`}}const nm=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;function wt(t){const e=String(t||"").trim().match(nm);return e?{major:Number(e[1]),minor:Number(e[2]),patch:Number(e[3]),prerelease:e[4]?e[4].split("."):[]}:null}function om(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 s=0;s0)}function lm(t){const e=wt(t);return e?e.major>0?`${e.major+1}.0.0`:`0.${e.minor+1}.0`:null}function aa(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 wt(o)?{min:o,minInclusive:!0,max:lm(o),maxInclusive:!1}:null}if(wt(e))return{min:e,minInclusive:!0,max:e,maxInclusive:!0};const s={min:null,minInclusive:!1,max:null,maxInclusive:!1},r=/(>=|<=|>|<)\s*([0-9][0-9A-Za-z.+-]*)/g;let i=!1,n;for(;(n=r.exec(e))!==null;){const[,o,a]=n;if(!wt(a))return null;i=!0,o===">="||o===">"?(s.min=a,s.minInclusive=o===">="):(s.max=a,s.maxInclusive=o==="<=")}return i?s:null}function cc(t,e){const s=aa(t);if(!s||!wt(e))return!1;if(s.min!==null){const r=mi(e,s.min);if(r<0||r===0&&!s.minInclusive)return!1}if(s.max!==null){const r=mi(e,s.max);if(r>0||r===0&&!s.maxInclusive)return!1}return!0}function cm(t,e){const s=aa(t);if(!s||!wt(e))return!1;if(s.max===null)return!0;const r=mi(s.max,e);return r>0?!0:r===0&&s.maxInclusive}function ns(t){const e=aa(t);return e?e.min:null}const um="https://pub.dev/api/packages/",dm=8e3;function hm(t,e={}){const{dartSdkFloor:s=null,flutterSdkFloor:r=null}=e,i=Array.isArray(t?.versions)?t.versions:[];let n=null;for(const o of i){const a=o?.version;if(!a||o.retracted||am(a))continue;const l=o.pubspec?.environment||{};s&&l.sdk&&!cc(l.sdk,s)||r&&l.flutter&&!cc(l.flutter,r)||(!n||mi(a,n)>0)&&(n=a)}return n?{version:n,constraint:`^${n}`}:null}async function pm(t,e={}){const{dartSdkFloor:s=null,flutterSdkFloor:r=null,fetchImpl:i=fetch}=e;let n;try{const a=await i(`${um}${encodeURIComponent(t)}`,{signal:AbortSignal.timeout(dm)});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}"`};n=await a.json()}catch(a){return{name:t,constraint:null,version:null,error:`could not reach pub.dev for "${t}" (${a.message})`}}const o=hm(n,{dartSdkFloor:s,flutterSdkFloor:r});return o?{name:t,...o,error:null}:{name:t,constraint:null,version:null,error:s?`no published "${t}" release supports Dart ${s}`:`no published "${t}" release could be read`}}async function fm(t,e={}){const s=await Promise.all(t.map(r=>pm(r,e)));return new Map(s.map(({name:r,...i})=>[r,i]))}async function gm(t,e={},s={}){const{resolveVersions:r=fm}=s,i=Object.entries(e).filter(([c])=>c&&c!=="flutter"),n=xd(t),o={dartSdkFloor:ns(n.sdk),flutterSdkFloor:ns(n.flutter)},a={additions:{},overrides:{},kept:[],warnings:[],sdk:o};if(i.length===0)return a;const l=Ni(t),u=[];for(const[c,d]of i){const h=l.get(c);if(!h){u.push(c);continue}const p=ns(d);if(!p){a.kept.push({name:c,constraint:h.constraint});continue}if(!h.isScalar){a.warnings.push(`"${c}" is declared in your project from a git, path, or SDK source, but the generated code needs at least ${p}. Left as-is — update it yourself if the build fails.`),a.kept.push({name:c,constraint:h.constraint});continue}if(cm(h.constraint,p)){a.kept.push({name:c,constraint:h.constraint});continue}a.overrides[c]=`^${p}`,a.warnings.push(`"${c}" was pinned to ${h.constraint} in your project, which cannot resolve the ${p} the generated code needs. Raising it to ^${p} — this changes a dependency the rest of your app also uses.`)}if(u.length>0){const c=await r(u,o);for(const d of u){const h=c.get(d);if(h?.constraint){a.additions[d]=h.constraint;continue}const p=e[d]||"";if(ns(p)){a.additions[d]=`^${ns(p)}`,a.warnings.push(`Could not confirm "${d}" version on pub.dev (${h?.error||"lookup failed"}). Using ^${ns(p)} from the AI's recommendation — verify this is current.`);continue}a.additions[d]=">=0.0.0",a.warnings.push(`Could not determine a version for "${d}" (${h?.error||"lookup failed"}) and the AI supplied none. Added with a wide-open >=0.0.0 constraint — pin a concrete version in FlutterFlow before deploying.`)}}return a}const mm={"&":"&","<":"<",">":">",'"':""","'":"'"};function bt(t){return String(t??"").replace(/[&<>"']/g,e=>mm[e])}function j(t){return t?bt(t).replace(/\n/g,"
"):""}function It(t){return bt(t).replace(/\r?\n/g," ")}function vm(t,e={}){const s=t?.pipelineStep;if(s!=null&&e[s]!=null)return e[s];const r=t?.message||"";return r.includes("Code Generator")?2:r.includes("Code Review")?3:1}function _m(t){const e={"Integration Audit Report":"📋","Critical Issues":"❌",Warnings:"⚠️",Recommendations:"✅","Overall Score":"📊"};for(const[s,r]of Object.entries(e))if(t.toLowerCase().includes(s.toLowerCase()))return r;return"📄"}function ym(t){const e={critical:"❌",warning:"⚠️",recommendation:"✅",score:"📊",issue:"🔍",fix:"🔧"};for(const[s,r]of Object.entries(e))if(t.toLowerCase().includes(s.toLowerCase()))return r;return"📝"}function wm(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 bs(t){if(!t)return"";if(typeof t!="string")return String(t);const e=/```(?:\w+)?\n?([\s\S]*?)```/,s=t.match(e);return s?s[1].trim():t.trim()}function uc(t){return t=bt(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 Pd(t,e="dart",s=globalThis.hljs){if(!t)return"";const r=bs(t);try{return s.highlight(r,{language:e}).value}catch(i){console.warn("Syntax highlighting failed:",i);try{return s.highlight(r,{language:"json"}).value}catch{return bt(r)}}}function Mi(t,e={}){const{highlighter:s=globalThis.hljs}=e;let r='
';const i=String(t??"").split(` -`);let n=!1,o="";for(const a of i){if(a.startsWith("```")){if(n){const l=wm(o),u=Pd(o.trim(),l,s);r+=`
+`)&&r++};let o=null;const a=()=>{for(const c of e)(c.kind==="string"||c.kind==="block-comment"||c.kind==="line-comment")&&s.push({start:c.startIndex,end:t.length})};for(;n0?t[n-1]:"",f=n>1?t[n-2]:"",g=(p==="r"||p==="R")&&!zg.test(f);e.push({kind:"string",quote:c,triple:h,raw:g,startIndex:n,openedLine:r}),n+=h?3:1;continue}if(ic[c]){e.push({kind:"code",opener:c,openedLine:r}),n++;continue}if(Wg[c]){if(d.interpolation&&c==="}"){e.pop(),n++;continue}if(d.opener&&ic[d.opener]===c){e.pop(),n++;continue}return d.opener?(a(),{error:o??`line ${r}: "${c}" closes nothing - "${d.opener}" opened on line ${d.openedLine} is still open`,commentAndStringRanges:s}):(a(),{error:o??`line ${r}: unexpected "${c}" with no matching opener`,commentAndStringRanges:s})}i(c,t[n+1]),n++}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:s}}function qg(t){return bo(String(t??"")).error}function oc(t,e){return e.some(({start:s,end:r})=>t>=s&&ttypeof s=="string"?s:s?.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 Vg=/^dependencies\s*:\s*(?:#.*)?$/,Gg=/^(?:"([^"]+)"|'([^']+)'|([A-Za-z_][A-Za-z0-9_-]*))\s*:/;function Mn(t){const e=t.match(Gg);return e?e[1]??e[2]??e[3]:null}function fr(t){const e=t.trim();return e===""||e.startsWith("#")}function ks(t){const e=t.match(/^(\s*)/);return e?e[1].length:0}function oa(t,e){const s=t.findIndex(i=>e.test(i));if(s===-1)return null;let r=s,n=null;for(let i=s+1;i=0.0.0"}`}function Yg(t,e={}){const s=String(t||""),r=Object.entries(e).filter(([u])=>u&&u!=="flutter");if(r.length===0)return{yaml:s,added:[],alreadyPresent:[]};const n=s.split(` +`),i=new Set(kd(s)),o=[],a=[];for(const[u,c]of r)i.has(u)?a.push(u):(o.push([u,c]),i.add(u));if(o.length===0)return{yaml:s,added:[],alreadyPresent:a};const l=aa(n);if(l){const u=o.map(([c,d])=>ac(l.childIndent,c,d));n.splice(l.endIndex,0,...u)}else n.length>0&&n[n.length-1].trim()!==""&&n.push(""),n.push("dependencies:"),o.forEach(([u,c])=>{n.push(ac(" ",u,c))});return{yaml:n.join(` +`),added:o.map(([u])=>u),alreadyPresent:a}}function Zg(t,e={}){const s=String(t||""),r=Object.entries(e).filter(([l])=>l&&l!=="flutter");if(r.length===0)return{yaml:s,overridden:[],skipped:[]};const n=s.split(` +`),i=On(s),o=[],a=[];for(const[l,u]of r){const c=i.get(l);if(!c||!c.isScalar||!String(u||"").trim()){a.push(l);continue}const d=" ".repeat(ks(n[c.lineIndex]));n[c.lineIndex]=`${d}${l}: ${Cd(String(u).trim())}${c.comment}`,o.push({name:l,from:c.constraint,to:u})}return{yaml:n.join(` +`),overridden:o,skipped:a}}function Fd(t){const e=String(t||""),s=[];return e.trim()?(/^name:\s*\S+/m.test(e)||s.push("pubspec.yaml missing name field"),aa(e.split(` +`))||s.push("pubspec.yaml missing dependencies section"),kd(e).includes("flutter")||s.push("pubspec.yaml missing Flutter SDK dependency"),{valid:s.length===0,errors:s}):(s.push("pubspec.yaml is empty"),{valid:!1,errors:s})}const Xg=">=3.0.0 <4.0.0";function Eo(t){const e=String(t||"").trim(),s=e[0];return s!=="'"&&s!=='"'||e[e.length-1]!==s?e:e.slice(1,-1).replaceAll(`${s}${s}`,s)}function Qg(t=""){const e=vg(t).filter(s=>!s.startsWith("dart:")&&!s.startsWith("package:"));return{selfContained:e.length===0,unresolvableImports:e}}function lc(t,e,s){const r=[];for(const[n,i]of t){if(i.isScalar){e[n]=Eo(i.constraint);continue}if(i.sourceKey==="sdk"){s.add(n);continue}if(i.sourceKey==="version"){e[n]=Eo(i.sourceValue);continue}r.push(n)}return r}function em(t){const e=new Set,s={},r={},n=lc(On(t),s,e);n.push(...lc(Kg(t,"dependency_overrides"),r,e));const i=new Set([...Object.keys(s),...e]),{sdk:o}=Id(t);return{sdkConstraint:Eo(o)||Xg,dependencies:s,overrides:r,sdkPackages:[...e].sort(),availablePackages:i,unrepresentable:n}}function tm(t,e,s){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 ${s.join(", ")}, which your project's pubspec.yaml does not declare with a version constraint, so it could not be compiled before the deploy.`}function sm(t,e){const{sdkConstraint:s,dependencies:r,overrides:n,sdkPackages:i,availablePackages:o,unrepresentable:a}=em(e),l={sdkConstraint:s,dependencies:r,overrides:n,sdkPackages:i},u=[],c=[];for(const d of t){const{className:h,content:p}=d,f=na(p),g=f.filter(b=>a.includes(b));if(g.length>0){c.push({className:h,reason:`${h} was not compiled before deploying: it imports ${g.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:m}=Qg(p),_=f.filter(b=>!o.has(b));if(m.length>0||_.length>0){c.push({className:h,reason:tm(h,m,_)});continue}u.push({fileName:`${ra(h)}.dart`,content:p})}return{manifest:l,sources:u,skipped:c}}function cc(t,e){const s=`${t}${e}`.split(` +`),r=s.pop()??"",n=[];for(const i of s){const o=Pd(i);o&&n.push(o)}return{events:n,buffer:r}}function rm(t){const e=Pd(t);return e?[e]:[]}function Pd(t){const e=t.trim();if(!e)return null;try{const s=JSON.parse(e);return s&&typeof s=="object"&&!Array.isArray(s)?s:null}catch{return null}}async function nm(t,e={}){const{onPhase:s,onLog:r}=e;let n=null,i="";const o=a=>{if(a.event==="phase"){a.message&&s&&s(a.message);return}if(a.event==="log"){a.message&&r&&r(a.message);return}n=a};if(t.body?.getReader){const a=t.body.getReader(),l=new TextDecoder;for(;;){const{done:u,value:c}=await a.read();if(u)break;const d=cc(i,l.decode(c,{stream:!0}));i=d.buffer,d.events.forEach(o)}}else{const a=cc("",await t.text());i=a.buffer,a.events.forEach(o)}return rm(i).forEach(o),n?{...n,success:n.success===!0||n.success===void 0&&t.ok}:{success:!1,error:t.ok?"The FlutterFlow deploy runner closed the connection before it finished.":`FlutterFlow custom class provisioning failed (HTTP ${t.status}).`}}const im=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;function wt(t){const e=String(t||"").trim().match(im);return e?{major:Number(e[1]),minor:Number(e[2]),patch:Number(e[3]),prerelease:e[4]?e[4].split("."):[]}:null}function om(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 s=0;s0)}function lm(t){const e=wt(t);return e?e.major>0?`${e.major+1}.0.0`:`0.${e.minor+1}.0`:null}function la(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 wt(o)?{min:o,minInclusive:!0,max:lm(o),maxInclusive:!1}:null}if(wt(e))return{min:e,minInclusive:!0,max:e,maxInclusive:!0};const s={min:null,minInclusive:!1,max:null,maxInclusive:!1},r=/(>=|<=|>|<)\s*([0-9][0-9A-Za-z.+-]*)/g;let n=!1,i;for(;(i=r.exec(e))!==null;){const[,o,a]=i;if(!wt(a))return null;n=!0,o===">="||o===">"?(s.min=a,s.minInclusive=o===">="):(s.max=a,s.maxInclusive=o==="<=")}return n?s:null}function uc(t,e){const s=la(t);if(!s||!wt(e))return!1;if(s.min!==null){const r=_n(e,s.min);if(r<0||r===0&&!s.minInclusive)return!1}if(s.max!==null){const r=_n(e,s.max);if(r>0||r===0&&!s.maxInclusive)return!1}return!0}function cm(t,e){const s=la(t);if(!s||!wt(e))return!1;if(s.max===null)return!0;const r=_n(s.max,e);return r>0?!0:r===0&&s.maxInclusive}function is(t){const e=la(t);return e?e.min:null}const um="https://pub.dev/api/packages/",dm=8e3;function hm(t,e={}){const{dartSdkFloor:s=null,flutterSdkFloor:r=null}=e,n=Array.isArray(t?.versions)?t.versions:[];let i=null;for(const o of n){const a=o?.version;if(!a||o.retracted||am(a))continue;const l=o.pubspec?.environment||{};s&&l.sdk&&!uc(l.sdk,s)||r&&l.flutter&&!uc(l.flutter,r)||(!i||_n(a,i)>0)&&(i=a)}return i?{version:i,constraint:`^${i}`}:null}async function pm(t,e={}){const{dartSdkFloor:s=null,flutterSdkFloor:r=null,fetchImpl:n=fetch}=e;let i;try{const a=await n(`${um}${encodeURIComponent(t)}`,{signal:AbortSignal.timeout(dm)});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}"`};i=await a.json()}catch(a){return{name:t,constraint:null,version:null,error:`could not reach pub.dev for "${t}" (${a.message})`}}const o=hm(i,{dartSdkFloor:s,flutterSdkFloor:r});return o?{name:t,...o,error:null}:{name:t,constraint:null,version:null,error:s?`no published "${t}" release supports Dart ${s}`:`no published "${t}" release could be read`}}async function fm(t,e={}){const s=await Promise.all(t.map(r=>pm(r,e)));return new Map(s.map(({name:r,...n})=>[r,n]))}async function gm(t,e={},s={}){const{resolveVersions:r=fm}=s,n=Object.entries(e).filter(([c])=>c&&c!=="flutter"),i=Id(t),o={dartSdkFloor:is(i.sdk),flutterSdkFloor:is(i.flutter)},a={additions:{},overrides:{},kept:[],warnings:[],sdk:o};if(n.length===0)return a;const l=On(t),u=[];for(const[c,d]of n){const h=l.get(c);if(!h){u.push(c);continue}const p=is(d);if(!p){a.kept.push({name:c,constraint:h.constraint});continue}if(!h.isScalar){a.warnings.push(`"${c}" is declared in your project from a git, path, or SDK source, but the generated code needs at least ${p}. Left as-is — update it yourself if the build fails.`),a.kept.push({name:c,constraint:h.constraint});continue}if(cm(h.constraint,p)){a.kept.push({name:c,constraint:h.constraint});continue}a.overrides[c]=`^${p}`,a.warnings.push(`"${c}" was pinned to ${h.constraint} in your project, which cannot resolve the ${p} the generated code needs. Raising it to ^${p} — this changes a dependency the rest of your app also uses.`)}if(u.length>0){const c=await r(u,o);for(const d of u){const h=c.get(d);if(h?.constraint){a.additions[d]=h.constraint;continue}const p=e[d]||"";if(is(p)){a.additions[d]=`^${is(p)}`,a.warnings.push(`Could not confirm "${d}" version on pub.dev (${h?.error||"lookup failed"}). Using ^${is(p)} from the AI's recommendation — verify this is current.`);continue}a.additions[d]=">=0.0.0",a.warnings.push(`Could not determine a version for "${d}" (${h?.error||"lookup failed"}) and the AI supplied none. Added with a wide-open >=0.0.0 constraint — pin a concrete version in FlutterFlow before deploying.`)}}return a}const mm={"&":"&","<":"<",">":">",'"':""","'":"'"};function bt(t){return String(t??"").replace(/[&<>"']/g,e=>mm[e])}function j(t){return t?bt(t).replace(/\n/g,"
"):""}function It(t){return bt(t).replace(/\r?\n/g," ")}function vm(t,e={}){const s=t?.pipelineStep;if(s!=null&&e[s]!=null)return e[s];const r=t?.message||"";return r.includes("Code Generator")?2:r.includes("Code Review")?3:1}function _m(t){const e={"Integration Audit Report":"📋","Critical Issues":"❌",Warnings:"⚠️",Recommendations:"✅","Overall Score":"📊"};for(const[s,r]of Object.entries(e))if(t.toLowerCase().includes(s.toLowerCase()))return r;return"📄"}function ym(t){const e={critical:"❌",warning:"⚠️",recommendation:"✅",score:"📊",issue:"🔍",fix:"🔧"};for(const[s,r]of Object.entries(e))if(t.toLowerCase().includes(s.toLowerCase()))return r;return"📝"}function wm(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 bs(t){if(!t)return"";if(typeof t!="string")return String(t);const e=/```(?:\w+)?\n?([\s\S]*?)```/,s=t.match(e);return s?s[1].trim():t.trim()}function dc(t){return t=bt(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 Ad(t,e="dart",s=globalThis.hljs){if(!t)return"";const r=bs(t);try{return s.highlight(r,{language:e}).value}catch(n){console.warn("Syntax highlighting failed:",n);try{return s.highlight(r,{language:"json"}).value}catch{return bt(r)}}}function Dn(t,e={}){const{highlighter:s=globalThis.hljs}=e;let r='
';const n=String(t??"").split(` +`);let i=!1,o="";for(const a of n){if(a.startsWith("```")){if(i){const l=wm(o),u=Ad(o.trim(),l,s);r+=`
${u}
-
`,o="",n=!1}else n=!0;continue}if(n){o+=a+` +
`,o="",i=!1}else i=!0;continue}if(i){o+=a+` `;continue}if(a.startsWith("# ")){const l=a.substring(2).trim();r+=`

${_m(l)} @@ -67,8 +67,8 @@ ${d}`,{commentAndStringRanges:g}=yo(f),m=p.length+1+h;if(nc(m,g)){l.push(d);cont

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

${uc(a)}

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

${dc(a)}

`)}return r+="",`
@@ -76,14 +76,14 @@ ${d}`,{commentAndStringRanges:g}=yo(f),m=p.length+1+h;if(nc(m,g)){l.push(d);cont
${r}
- `}const bm="https://ccc-ffai-runner-y5cyj3473a-uw.a.run.app/deployCustomClasses",Em="phc_KoqpBJCIiWMW5I6HKBM092DVXZbMmE4KkPHqI518pF3",Sm="https://us.i.posthog.com";cd.init(Em,{api_host:Sm,person_profiles:"identified_only"});function zt(t,e={}){try{cd.capture(t,e)}catch(s){console.error("PostHog tracking failed",s)}}const Je="https://4tgke4.buildship.run",Ad={professional:"price_1T2ldCKszA2slvDXatdeCpbI",power:"price_1T2le9KszA2slvDXR4mPvw7M"},vi="ccc_auth_session",dc=new WeakSet;let G={email:null,sessionToken:null,isVerified:!1};function Es(t={}){return{tier:"free",status:"none",periodEnd:null,isLoading:!1,isResolved:!1,error:null,...t}}let fe=Es({isResolved:!0});const xm=`${Je}/service/runpipeline`,km="bs_user_id",Im="bs_identity_token",Cm=`${Je}/authUserCheck`;let Ge={userId:null,token:null,status:null,resolved:!1};const _i={free:2,professional:50,power:2e3},yi="ccc_subscription",hc=3,Fm=new Set(["active","trialing","paid"]),lr="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"],Pm={"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 qt(t){return Pm[t]||t}const Am=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 $d(t){return Am.has(t)}const wo=4,In=8*1024*1024,$m="https://4tgke4.buildship.run/service/runpipeline-image";let Pt=[];function Rm(t){return new Promise(e=>{const s=new FileReader;s.onload=()=>e(s.result),s.onerror=()=>e(null),s.readAsDataURL(t)})}async function Tm(t){const e=new FormData;return e.append("file",t),(await fetch($m,{method:"POST",body:e})).json()}function Nm(t){if(Array.isArray(t)){const e=t[0];if(e&&typeof e=="object")for(const s of Object.keys(e)){if(s==="item"||s==="index")continue;const r=e[s];if(r&&typeof r=="object"){if(typeof r.file=="string")return r.file;if(typeof r.url=="string")return r.url}if(typeof r=="string")return r}return""}return typeof t=="string"?t:t&&typeof t=="object"&&(t.url||t.fileUrl||t.file_url||t.downloadUrl||t.imageUrl||t.image_url||t.file)||""}async function Mm(t){const e=Array.from(t.target.files||[]);if(!e.length)return;const s=e.filter(l=>l.size>In);s.length&&ue(`Skipped ${s.length} image(s) over the ${(In/1024/1024).toFixed(0)} MB limit.`,"warning");const r=e.filter(l=>l.size<=In);if(!r.length){t.target.value="";return}const i=wo-Pt.length,o=r.slice(0,i).map(async l=>{const u=await Rm(l);if(!u)return null;let c="";try{c=Nm(await Tm(l))}catch{c=""}return{dataUrl:u,name:l.name,url:c}}),a=(await Promise.all(o)).filter(Boolean);t.target.value="",!(a.length&&!$d(document.getElementById("code-generator-model")?.value))&&(Pt.push(...a),r.length>i&&ue(`You can attach up to ${wo} images.`,"info"),la())}function Lm(t){Pt.splice(t,1),la()}function la(){const t=document.getElementById("prompt-image-thumbnails"),e=document.getElementById("prompt-image-btn-label");t&&(t.innerHTML="",Pt.forEach((s,r)=>{const i=document.createElement("div");i.className="prompt-img-thumb",i.innerHTML=`Prompt image`,t.appendChild(i)}),e&&(e.textContent=Pt.length>=wo?"Image limit reached":"Add images"))}function Rd(){const t=document.getElementById("prompt-image-upload");if(!t)return;const e=document.getElementById("code-generator-model"),s=$d(e?.value);t.classList.toggle("hidden",!s),!s&&Pt.length&&(Pt=[],la())}const Kt="ccc_usage",Td="google/gemini-3.7-flash",Nd="google/gemini-3.7-flash",Cn="google/gemini-3.7-flash",pc={professional:11,power:49},bo={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 Om(){const t=new AbortController,e=setTimeout(()=>t.abort(),5e3);try{const s=await fetch("https://open.er-api.com/v6/latest/AUD",{signal:t.signal});if(!s.ok)return;const r=await s.json();if(r.result!=="success"||!r.rates)return;const i=r.rates,n={AUD:1},o=new Set([...Object.keys(Ur),...Object.values(Eo),...Object.values(bo)]);for(const a of o)a!=="AUD"&&(typeof i[a]=="number"&&i[a]>0?n[a]=i[a]:Ur[a]&&(n[a]=Ur[a]));Hr=n}catch{}finally{clearTimeout(e)}}const Eo={"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 Md(){try{const n=Intl.DateTimeFormat().resolvedOptions().timeZone;if(n&&Eo[n])return Eo[n]}catch{}const e=(navigator.language||"en-US").replace("-","_"),s=bo[e];if(s)return s;const r=e.split("_")[0],i=bo[r];return i||"USD"}function fc(t,e){const s=Hr[e]??Hr.USD,r=t*s,i=Math.round(r*100)/100;try{return new Intl.NumberFormat("en-US",{style:"currency",currency:e,minimumFractionDigits:0,maximumFractionDigits:i>=100||i%1===0?0:2}).format(i)}catch{return new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",minimumFractionDigits:0,maximumFractionDigits:2}).format(t*Hr.USD)}}const st="ccc_api_key_",_t="ccc_session_api_key_",nt="ccc_encryption_key",cr="ccc_encryption_key_scope",Dm="ccc_keystore",wi="keys",ur="ccc_encryption_key_version";let So=null,bi=null,dr=!1,Ei=!1,gc=!1;class Si extends Error{constructor(){super("Secure browser key storage is unavailable."),this.name="CredentialStorageUnavailableError"}}function mc(){if(gc)return;gc=!0;const t="Secure browser key storage is unavailable. Existing credentials were left untouched; new credentials will be available only in this tab session.";console.warn(t),document.body&&ue(t,"warning")}function Ld(){return localStorage.getItem(ur)||""}function xo(){return crypto.randomUUID?.()||Dd(crypto.getRandomValues(new Uint8Array(16)))}function Bm(){const t=Ld();if(t)return t;const e=xo();return localStorage.setItem(ur,e),e}function Ss(){So=null,bi=null,dr=!1,Ei=!1}window.addEventListener("storage",t=>{t.key===ur&&Ss()});function jm(){return new Promise((t,e)=>{const s=indexedDB.open(Dm,1);s.onupgradeneeded=()=>{const r=s.result;r.objectStoreNames.contains(wi)||r.createObjectStore(wi)},s.onsuccess=()=>t(s.result),s.onerror=()=>e(s.error)})}async function ca(t,e){const s=await jm();return new Promise((r,i)=>{const n=s.transaction(wi,t);let o;try{o=e(n.objectStore(wi))}catch(l){s.close(),i(l);return}let a;o.onsuccess=()=>{a=o.result},o.onerror=()=>i(o.error),n.oncomplete=()=>{s.close(),r(a)},n.onerror=()=>{s.close(),i(n.error||new Error("Encryption key transaction failed."))},n.onabort=()=>{s.close(),i(n.error||new Error("Encryption key transaction aborted."))}})}function Um(t){return t instanceof CryptoKey&&t.algorithm?.name==="AES-GCM"&&t.extractable===!1&&t.usages.includes("encrypt")&&t.usages.includes("decrypt")}async function Hm(){const t=await ca("readonly",e=>e.get(nt));return Um(t)?t:null}async function Od(t){await ca("readwrite",e=>e.put(t,nt))}async function Wm(){Ss();try{await ca("readwrite",t=>t.delete(nt))}catch(t){console.warn("Could not delete the stored encryption key:",t)}}async function zm(){const t=sessionStorage.getItem(nt);if(!t)return null;const e=await crypto.subtle.importKey("jwk",JSON.parse(t),{name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);return await Od(e),sessionStorage.removeItem(nt),sessionStorage.removeItem(cr),localStorage.removeItem(st+"salt"),e}async function vc(t){const e=sessionStorage.getItem(nt);if(e)return Ei=sessionStorage.getItem(cr)!=="session",crypto.subtle.importKey("jwk",JSON.parse(e),{name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);if(!t)throw new Si;const s=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!0,["encrypt","decrypt"]),r=await crypto.subtle.exportKey("jwk",s);return sessionStorage.setItem(nt,JSON.stringify(r)),sessionStorage.setItem(cr,"session"),Ei=!1,crypto.subtle.importKey("jwk",r,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}async function qm(t){if(sessionStorage.getItem(cr)==="session"&&sessionStorage.getItem(nt))return mc(),dr=!0,vc(t);try{const e=await Hm();if(e)return e;const s=await zm();if(s)return s;const r=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);return await Od(r),r}catch(e){return console.warn("IndexedDB encryption-key storage failed:",e),mc(),dr=!0,vc(t)}}async function ua(t={}){const{allowSessionFallbackCreation:e=!0}=t,s=Bm();bi!==s&&Ss();const r=So||qm(e);So=r,bi=s;try{return await r}catch(i){throw Ss(),i}}async function Vm(t){const e=await ua(),s=bi,r=new TextEncoder,i=crypto.getRandomValues(new Uint8Array(12)),n=await crypto.subtle.encrypt({name:"AES-GCM",iv:i},e,r.encode(t)),o=new Uint8Array(i.length+n.byteLength);return o.set(i),o.set(new Uint8Array(n),i.length),{ciphertext:Dd(o),keyVersion:s,sessionFallback:dr}}async function Gm(t,e={}){const{isSessionCredential:s=!1}=e;try{const r=await ua({allowSessionFallbackCreation:!1});if(dr&&!s&&!Ei)throw new Si;const i=Km(t),n=i.slice(0,12),o=i.slice(12),a=await crypto.subtle.decrypt({name:"AES-GCM",iv:n},r,o);return new TextDecoder().decode(a)}catch(r){if(r instanceof Si)throw r;return console.error("Decryption failed:",r),null}}function Dd(t){const e=new Uint8Array(t);let s="";for(let r=0;r0}let hr="",xi="",Zs=null,yc=0;async function da(){sessionStorage.getItem(nt)&&await ua(),hr=await Ee("flutterflow"),xi=await Ee("flutterflow_project_id"),Qm(),Xt()}function ha(){document.getElementById("api-keys-modal").classList.add("open"),fa(),hr&&Hd(hr)}function Bd(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("api-keys-modal");e&&e.classList.remove("open");const s=document.getElementById("walkthrough-modal");s&&(pa(),s.classList.add("open"))}let Et=1;function jd(){const t=document.querySelector(".wt-steps");return t?Array.from(t.querySelectorAll(".wt-step-card")):[]}function Li(){const t=jd();t.length&&t.forEach((e,s)=>{const r=s+1;if(r===Et){e.classList.remove("opacity-60","bg-gray-50","border-gray-200"),e.classList.add("bg-blue-50","border-blue-200");const i=e.querySelector("div:first-child");i&&(i.classList.remove("bg-gray-400"),i.classList.add("bg-blue-500"),i.innerHTML=r)}else if(r0&&Et<=t&&(Et++,Li())}function Ym(){const t=document.getElementById("walkthrough-modal");t&&(Et=1,Li(),t.classList.add("open"))}function Zm(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("walkthrough-modal");e&&e.classList.remove("open");const s=document.getElementById("walkthrough-dont-show");s&&s.checked&&localStorage.setItem("hasSeenWalkthrough","true")}function Ud(){if(G.isVerified&&Yt()&&fe.tier!=="free")return;if(!localStorage.getItem("hasSeenWalkthrough")){const e=document.getElementById("walkthrough-modal");e&&(Et=1,Li(),e.classList.add("open"))}}async function fa(){const t=document.getElementById("flutterflow-api-key-input");hr?(t.value="",t.placeholder="Key saved (enter new to replace)"):t.placeholder="Enter your FlutterFlow API key",Xm()}function Xm(){wc("flutterflow","flutterflow-key-status"),wc("flutterflow_project_id","flutterflow-project-status")}function wc(t,e){const s=document.getElementById(e);if(!s)return;const r=s.querySelector(".key-status-dot"),i=s.querySelector("span");ls(t)?(r.className="key-status-dot configured",i.className="text-green-600",i.textContent="User key configured"):(r.className="key-status-dot missing",i.className="text-gray-500",i.textContent="Not configured")}function Xt(){const t=y.step2Result&&y.step2Result.length>0,e=document.getElementById("btn-deploy-to-ff"),s=document.getElementById("btn-run-pipeline");s&&s.classList.remove("hidden"),e&&e.classList.toggle("hidden",!t)}function Qm(){const t=document.getElementById("api-keys-status");if(!t)return;const e=t.querySelectorAll(".key-status-dot"),s=["flutterflow"];e.forEach((r,i)=>{const n=s[i];n==="flutterflow"?ls("flutterflow")&&ls("flutterflow_project_id")?(r.className="key-status-dot configured",r.title="FlutterFlow (Fully configured)"):ls("flutterflow")||ls("flutterflow_project_id")?(r.className="key-status-dot env",r.title="FlutterFlow (Partially configured)"):(r.className="key-status-dot missing",r.title="FlutterFlow (Not configured)"):ls(n)?(r.className="key-status-dot configured",r.title=n.charAt(0).toUpperCase()+n.slice(1)+" (User key)"):(r.className="key-status-dot missing",r.title=n.charAt(0).toUpperCase()+n.slice(1)+" (Not configured)")}),Xt()}async function ev(){const t=document.getElementById("flutterflow-api-key-input"),e=document.getElementById("flutterflow-projects-select");t.value.trim()&&await _c("flutterflow",t.value);const s=e?.value.trim()||"";if(s){if(!Oi(s)){ue("The selected FlutterFlow project has an unexpected ID format.","error"),e.focus();return}await _c("flutterflow_project_id",s)}await da(),fa();const r=document.querySelector("#api-keys-modal .bg-blue-500"),i=r.textContent;r.textContent="Saved!",r.classList.remove("bg-blue-500","hover:bg-blue-600"),r.classList.add("bg-green-500"),setTimeout(()=>{r.textContent=i,r.classList.remove("bg-green-500"),r.classList.add("bg-blue-500","hover:bg-blue-600"),Bd()},1e3)}async function tv(){if(!confirm("Are you sure you want to clear all stored API keys?"))return;localStorage.setItem(ur,xo()),Ss(),localStorage.removeItem(st+"flutterflow"),localStorage.removeItem(st+"flutterflow_project_id"),sessionStorage.removeItem(_t+"flutterflow"),sessionStorage.removeItem(_t+"flutterflow_project_id"),sessionStorage.removeItem(nt),sessionStorage.removeItem(cr),localStorage.removeItem(st+"salt"),await Wm(),localStorage.setItem(ur,xo()),localStorage.removeItem(st+"flutterflow"),localStorage.removeItem(st+"flutterflow_project_id"),sessionStorage.removeItem(_t+"flutterflow"),sessionStorage.removeItem(_t+"flutterflow_project_id"),await da();const t=document.getElementById("flutterflow-projects-select");t&&(t.innerHTML=''),fa()}function Oi(t){return!t||t.trim().length<5||t.includes(" ")?!1:/^[a-zA-Z0-9-]+$/.test(t)}function sv(t,e){const s=document.getElementById(t);s&&(s.value?e?s.style.borderColor="#22c55e":s.style.borderColor="#ef4444":s.style.borderColor="")}function rv(){const t=document.getElementById("flutterflow-api-key-input");t&&(t.addEventListener("input",e=>{const s=e.target.value.trim().length>0;sv("flutterflow-api-key-input",s)}),t.addEventListener("blur",iv(async e=>{const s=e.target.value.trim();s&&await Hd(s)},500)))}function iv(t,e){let s;return function(...i){const n=()=>{clearTimeout(s),t(...i)};clearTimeout(s),s=setTimeout(n,e)}}async function Hd(t){const e=document.getElementById("flutterflow-projects-select"),s=document.getElementById("flutterflow-projects-error");if(!e){console.error("Projects dropdown element not found");return}e.innerHTML='',s&&s.classList.add("hidden");try{const i=await new gr(t,"").listProjects();if(!i||i.length===0){e.innerHTML='';return}e.innerHTML='',i.forEach(n=>{const o=document.createElement("option");o.value=n.id||n.projectId||"",o.textContent=n.name||n.projectName||`Project ${n.id}`,e.appendChild(o)}),xi&&(e.value=xi)}catch(r){console.error("Failed to fetch projects:",r),e.innerHTML='',s&&(s.textContent=`Failed to load projects: ${r.message}`,s.classList.remove("hidden"))}}function nv(t){const e=document.getElementById(t),r=e.nextElementSibling.querySelector("svg");e.type==="password"?(e.type="text",r.innerHTML=` + `}const bm="https://ccc-ffai-runner-y5cyj3473a-uw.a.run.app/deployCustomClasses",Em="phc_KoqpBJCIiWMW5I6HKBM092DVXZbMmE4KkPHqI518pF3",Sm="https://us.i.posthog.com";ud.init(Em,{api_host:Sm,person_profiles:"identified_only"});function zt(t,e={}){try{ud.capture(t,e)}catch(s){console.error("PostHog tracking failed",s)}}const Je="https://4tgke4.buildship.run",$d={professional:"price_1T2ldCKszA2slvDXatdeCpbI",power:"price_1T2le9KszA2slvDXR4mPvw7M"},yn="ccc_auth_session",hc=new WeakSet;let G={email:null,sessionToken:null,isVerified:!1};function Es(t={}){return{tier:"free",status:"none",periodEnd:null,isLoading:!1,isResolved:!1,error:null,...t}}let fe=Es({isResolved:!0});const xm=`${Je}/service/runpipeline`,km="bs_user_id",Im="bs_identity_token",Cm=`${Je}/authUserCheck`;let Ge={userId:null,token:null,status:null,resolved:!1};const wn={free:2,professional:50,power:2e3},bn="ccc_subscription",pc=3,Fm=new Set(["active","trialing","paid"]),cr="google/gemini-3.7-flash",Ur=["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"],Pm={"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 qt(t){return Pm[t]||t}const Am=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 Rd(t){return Am.has(t)}const So=4,Fi=8*1024*1024,$m="https://4tgke4.buildship.run/service/runpipeline-image";let Pt=[];function Rm(t){return new Promise(e=>{const s=new FileReader;s.onload=()=>e(s.result),s.onerror=()=>e(null),s.readAsDataURL(t)})}async function Tm(t){const e=new FormData;return e.append("file",t),(await fetch($m,{method:"POST",body:e})).json()}function Nm(t){if(Array.isArray(t)){const e=t[0];if(e&&typeof e=="object")for(const s of Object.keys(e)){if(s==="item"||s==="index")continue;const r=e[s];if(r&&typeof r=="object"){if(typeof r.file=="string")return r.file;if(typeof r.url=="string")return r.url}if(typeof r=="string")return r}return""}return typeof t=="string"?t:t&&typeof t=="object"&&(t.url||t.fileUrl||t.file_url||t.downloadUrl||t.imageUrl||t.image_url||t.file)||""}async function Mm(t){const e=Array.from(t.target.files||[]);if(!e.length)return;const s=e.filter(l=>l.size>Fi);s.length&&ue(`Skipped ${s.length} image(s) over the ${(Fi/1024/1024).toFixed(0)} MB limit.`,"warning");const r=e.filter(l=>l.size<=Fi);if(!r.length){t.target.value="";return}const n=So-Pt.length,o=r.slice(0,n).map(async l=>{const u=await Rm(l);if(!u)return null;let c="";try{c=Nm(await Tm(l))}catch{c=""}return{dataUrl:u,name:l.name,url:c}}),a=(await Promise.all(o)).filter(Boolean);t.target.value="",!(a.length&&!Rd(document.getElementById("code-generator-model")?.value))&&(Pt.push(...a),r.length>n&&ue(`You can attach up to ${So} images.`,"info"),ca())}function Lm(t){Pt.splice(t,1),ca()}function ca(){const t=document.getElementById("prompt-image-thumbnails"),e=document.getElementById("prompt-image-btn-label");t&&(t.innerHTML="",Pt.forEach((s,r)=>{const n=document.createElement("div");n.className="prompt-img-thumb",n.innerHTML=`Prompt image`,t.appendChild(n)}),e&&(e.textContent=Pt.length>=So?"Image limit reached":"Add images"))}function Td(){const t=document.getElementById("prompt-image-upload");if(!t)return;const e=document.getElementById("code-generator-model"),s=Rd(e?.value);t.classList.toggle("hidden",!s),!s&&Pt.length&&(Pt=[],ca())}const Kt="ccc_usage",Nd="google/gemini-3.7-flash",Md="google/gemini-3.7-flash",Pi="google/gemini-3.7-flash",fc={professional:11,power:49},xo={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"},Hr={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 Wr={...Hr};async function Om(){const t=new AbortController,e=setTimeout(()=>t.abort(),5e3);try{const s=await fetch("https://open.er-api.com/v6/latest/AUD",{signal:t.signal});if(!s.ok)return;const r=await s.json();if(r.result!=="success"||!r.rates)return;const n=r.rates,i={AUD:1},o=new Set([...Object.keys(Hr),...Object.values(ko),...Object.values(xo)]);for(const a of o)a!=="AUD"&&(typeof n[a]=="number"&&n[a]>0?i[a]=n[a]:Hr[a]&&(i[a]=Hr[a]));Wr=i}catch{}finally{clearTimeout(e)}}const ko={"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 Ld(){try{const i=Intl.DateTimeFormat().resolvedOptions().timeZone;if(i&&ko[i])return ko[i]}catch{}const e=(navigator.language||"en-US").replace("-","_"),s=xo[e];if(s)return s;const r=e.split("_")[0],n=xo[r];return n||"USD"}function gc(t,e){const s=Wr[e]??Wr.USD,r=t*s,n=Math.round(r*100)/100;try{return new Intl.NumberFormat("en-US",{style:"currency",currency:e,minimumFractionDigits:0,maximumFractionDigits:n>=100||n%1===0?0:2}).format(n)}catch{return new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",minimumFractionDigits:0,maximumFractionDigits:2}).format(t*Wr.USD)}}const st="ccc_api_key_",_t="ccc_session_api_key_",it="ccc_encryption_key",ur="ccc_encryption_key_scope",Dm="ccc_keystore",En="keys",dr="ccc_encryption_key_version";let Io=null,Sn=null,hr=!1,xn=!1,mc=!1;class kn extends Error{constructor(){super("Secure browser key storage is unavailable."),this.name="CredentialStorageUnavailableError"}}function vc(){if(mc)return;mc=!0;const t="Secure browser key storage is unavailable. Existing credentials were left untouched; new credentials will be available only in this tab session.";console.warn(t),document.body&&ue(t,"warning")}function Od(){return localStorage.getItem(dr)||""}function Co(){return crypto.randomUUID?.()||Bd(crypto.getRandomValues(new Uint8Array(16)))}function Bm(){const t=Od();if(t)return t;const e=Co();return localStorage.setItem(dr,e),e}function Ss(){Io=null,Sn=null,hr=!1,xn=!1}window.addEventListener("storage",t=>{t.key===dr&&Ss()});function jm(){return new Promise((t,e)=>{const s=indexedDB.open(Dm,1);s.onupgradeneeded=()=>{const r=s.result;r.objectStoreNames.contains(En)||r.createObjectStore(En)},s.onsuccess=()=>t(s.result),s.onerror=()=>e(s.error)})}async function ua(t,e){const s=await jm();return new Promise((r,n)=>{const i=s.transaction(En,t);let o;try{o=e(i.objectStore(En))}catch(l){s.close(),n(l);return}let a;o.onsuccess=()=>{a=o.result},o.onerror=()=>n(o.error),i.oncomplete=()=>{s.close(),r(a)},i.onerror=()=>{s.close(),n(i.error||new Error("Encryption key transaction failed."))},i.onabort=()=>{s.close(),n(i.error||new Error("Encryption key transaction aborted."))}})}function Um(t){return t instanceof CryptoKey&&t.algorithm?.name==="AES-GCM"&&t.extractable===!1&&t.usages.includes("encrypt")&&t.usages.includes("decrypt")}async function Hm(){const t=await ua("readonly",e=>e.get(it));return Um(t)?t:null}async function Dd(t){await ua("readwrite",e=>e.put(t,it))}async function Wm(){Ss();try{await ua("readwrite",t=>t.delete(it))}catch(t){console.warn("Could not delete the stored encryption key:",t)}}async function zm(){const t=sessionStorage.getItem(it);if(!t)return null;const e=await crypto.subtle.importKey("jwk",JSON.parse(t),{name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);return await Dd(e),sessionStorage.removeItem(it),sessionStorage.removeItem(ur),localStorage.removeItem(st+"salt"),e}async function _c(t){const e=sessionStorage.getItem(it);if(e)return xn=sessionStorage.getItem(ur)!=="session",crypto.subtle.importKey("jwk",JSON.parse(e),{name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);if(!t)throw new kn;const s=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!0,["encrypt","decrypt"]),r=await crypto.subtle.exportKey("jwk",s);return sessionStorage.setItem(it,JSON.stringify(r)),sessionStorage.setItem(ur,"session"),xn=!1,crypto.subtle.importKey("jwk",r,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}async function qm(t){if(sessionStorage.getItem(ur)==="session"&&sessionStorage.getItem(it))return vc(),hr=!0,_c(t);try{const e=await Hm();if(e)return e;const s=await zm();if(s)return s;const r=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);return await Dd(r),r}catch(e){return console.warn("IndexedDB encryption-key storage failed:",e),vc(),hr=!0,_c(t)}}async function da(t={}){const{allowSessionFallbackCreation:e=!0}=t,s=Bm();Sn!==s&&Ss();const r=Io||qm(e);Io=r,Sn=s;try{return await r}catch(n){throw Ss(),n}}async function Vm(t){const e=await da(),s=Sn,r=new TextEncoder,n=crypto.getRandomValues(new Uint8Array(12)),i=await crypto.subtle.encrypt({name:"AES-GCM",iv:n},e,r.encode(t)),o=new Uint8Array(n.length+i.byteLength);return o.set(n),o.set(new Uint8Array(i),n.length),{ciphertext:Bd(o),keyVersion:s,sessionFallback:hr}}async function Gm(t,e={}){const{isSessionCredential:s=!1}=e;try{const r=await da({allowSessionFallbackCreation:!1});if(hr&&!s&&!xn)throw new kn;const n=Km(t),i=n.slice(0,12),o=n.slice(12),a=await crypto.subtle.decrypt({name:"AES-GCM",iv:i},r,o);return new TextDecoder().decode(a)}catch(r){if(r instanceof kn)throw r;return console.error("Decryption failed:",r),null}}function Bd(t){const e=new Uint8Array(t);let s="";for(let r=0;r0}let pr="",In="",Xs=null,wc=0;async function ha(){sessionStorage.getItem(it)&&await da(),pr=await Ee("flutterflow"),In=await Ee("flutterflow_project_id"),Qm(),Xt()}function pa(){document.getElementById("api-keys-modal").classList.add("open"),ga(),pr&&Wd(pr)}function jd(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("api-keys-modal");e&&e.classList.remove("open");const s=document.getElementById("walkthrough-modal");s&&(fa(),s.classList.add("open"))}let Et=1;function Ud(){const t=document.querySelector(".wt-steps");return t?Array.from(t.querySelectorAll(".wt-step-card")):[]}function Bn(){const t=Ud();t.length&&t.forEach((e,s)=>{const r=s+1;if(r===Et){e.classList.remove("opacity-60","bg-gray-50","border-gray-200"),e.classList.add("bg-blue-50","border-blue-200");const n=e.querySelector("div:first-child");n&&(n.classList.remove("bg-gray-400"),n.classList.add("bg-blue-500"),n.innerHTML=r)}else if(r0&&Et<=t&&(Et++,Bn())}function Ym(){const t=document.getElementById("walkthrough-modal");t&&(Et=1,Bn(),t.classList.add("open"))}function Zm(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("walkthrough-modal");e&&e.classList.remove("open");const s=document.getElementById("walkthrough-dont-show");s&&s.checked&&localStorage.setItem("hasSeenWalkthrough","true")}function Hd(){if(G.isVerified&&Yt()&&fe.tier!=="free")return;if(!localStorage.getItem("hasSeenWalkthrough")){const e=document.getElementById("walkthrough-modal");e&&(Et=1,Bn(),e.classList.add("open"))}}async function ga(){const t=document.getElementById("flutterflow-api-key-input");pr?(t.value="",t.placeholder="Key saved (enter new to replace)"):t.placeholder="Enter your FlutterFlow API key",Xm()}function Xm(){bc("flutterflow","flutterflow-key-status"),bc("flutterflow_project_id","flutterflow-project-status")}function bc(t,e){const s=document.getElementById(e);if(!s)return;const r=s.querySelector(".key-status-dot"),n=s.querySelector("span");ls(t)?(r.className="key-status-dot configured",n.className="text-green-600",n.textContent="User key configured"):(r.className="key-status-dot missing",n.className="text-gray-500",n.textContent="Not configured")}function Xt(){const t=y.step2Result&&y.step2Result.length>0,e=document.getElementById("btn-deploy-to-ff"),s=document.getElementById("btn-run-pipeline");s&&s.classList.remove("hidden"),e&&e.classList.toggle("hidden",!t)}function Qm(){const t=document.getElementById("api-keys-status");if(!t)return;const e=t.querySelectorAll(".key-status-dot"),s=["flutterflow"];e.forEach((r,n)=>{const i=s[n];i==="flutterflow"?ls("flutterflow")&&ls("flutterflow_project_id")?(r.className="key-status-dot configured",r.title="FlutterFlow (Fully configured)"):ls("flutterflow")||ls("flutterflow_project_id")?(r.className="key-status-dot env",r.title="FlutterFlow (Partially configured)"):(r.className="key-status-dot missing",r.title="FlutterFlow (Not configured)"):ls(i)?(r.className="key-status-dot configured",r.title=i.charAt(0).toUpperCase()+i.slice(1)+" (User key)"):(r.className="key-status-dot missing",r.title=i.charAt(0).toUpperCase()+i.slice(1)+" (Not configured)")}),Xt()}async function ev(){const t=document.getElementById("flutterflow-api-key-input"),e=document.getElementById("flutterflow-projects-select");t.value.trim()&&await yc("flutterflow",t.value);const s=e?.value.trim()||"";if(s){if(!jn(s)){ue("The selected FlutterFlow project has an unexpected ID format.","error"),e.focus();return}await yc("flutterflow_project_id",s)}await ha(),ga();const r=document.querySelector("#api-keys-modal .bg-blue-500"),n=r.textContent;r.textContent="Saved!",r.classList.remove("bg-blue-500","hover:bg-blue-600"),r.classList.add("bg-green-500"),setTimeout(()=>{r.textContent=n,r.classList.remove("bg-green-500"),r.classList.add("bg-blue-500","hover:bg-blue-600"),jd()},1e3)}async function tv(){if(!confirm("Are you sure you want to clear all stored API keys?"))return;localStorage.setItem(dr,Co()),Ss(),localStorage.removeItem(st+"flutterflow"),localStorage.removeItem(st+"flutterflow_project_id"),sessionStorage.removeItem(_t+"flutterflow"),sessionStorage.removeItem(_t+"flutterflow_project_id"),sessionStorage.removeItem(it),sessionStorage.removeItem(ur),localStorage.removeItem(st+"salt"),await Wm(),localStorage.setItem(dr,Co()),localStorage.removeItem(st+"flutterflow"),localStorage.removeItem(st+"flutterflow_project_id"),sessionStorage.removeItem(_t+"flutterflow"),sessionStorage.removeItem(_t+"flutterflow_project_id"),await ha();const t=document.getElementById("flutterflow-projects-select");t&&(t.innerHTML=''),ga()}function jn(t){return!t||t.trim().length<5||t.includes(" ")?!1:/^[a-zA-Z0-9-]+$/.test(t)}function sv(t,e){const s=document.getElementById(t);s&&(s.value?e?s.style.borderColor="#22c55e":s.style.borderColor="#ef4444":s.style.borderColor="")}function rv(){const t=document.getElementById("flutterflow-api-key-input");t&&(t.addEventListener("input",e=>{const s=e.target.value.trim().length>0;sv("flutterflow-api-key-input",s)}),t.addEventListener("blur",nv(async e=>{const s=e.target.value.trim();s&&await Wd(s)},500)))}function nv(t,e){let s;return function(...n){const i=()=>{clearTimeout(s),t(...n)};clearTimeout(s),s=setTimeout(i,e)}}async function Wd(t){const e=document.getElementById("flutterflow-projects-select"),s=document.getElementById("flutterflow-projects-error");if(!e){console.error("Projects dropdown element not found");return}e.innerHTML='',s&&s.classList.add("hidden");try{const n=await new mr(t,"").listProjects();if(!n||n.length===0){e.innerHTML='';return}e.innerHTML='',n.forEach(i=>{const o=document.createElement("option");o.value=i.id||i.projectId||"",o.textContent=i.name||i.projectName||`Project ${i.id}`,e.appendChild(o)}),In&&(e.value=In)}catch(r){console.error("Failed to fetch projects:",r),e.innerHTML='',s&&(s.textContent=`Failed to load projects: ${r.message}`,s.classList.remove("hidden"))}}function iv(t){const e=document.getElementById(t),r=e.nextElementSibling.querySelector("svg");e.type==="password"?(e.type="text",r.innerHTML=` `):(e.type="password",r.innerHTML=` - `)}let y={step1Result:null,step2Result:null,step3Result:null,bundleSpec:null,artifactBundle:null,bundleReview:null,selectedArtifactId:null,resultsViewMode:"summary",currentStep:0,isRunning:!1};function ov(){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 av(){y.bundleSpec=or(y.step1Result,{artifactType:"CustomWidget",artifactName:"GeneratedWidget"})}function Di(){const t=fi(y.bundleSpec);y.artifactBundle=or(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=dg(y.artifactBundle);y.artifactBundle={...y.artifactBundle,warnings:[...y.artifactBundle.warnings,...e.findings.map(s=>s.message)],metadata:{...y.artifactBundle.metadata,compatibility:e}},y.selectedArtifactId=fi(y.artifactBundle).id}function Bi(){const t=or(y.step3Result,{id:y.artifactBundle?.id,title:y.artifactBundle?.title}),e=new Map(t.artifacts.map(r=>[r.id,r.review])),s=new Map(t.artifacts.filter(r=>{const i=r.review;return i&&typeof i.fixedSource=="string"&&i.fixedSource.trim()}).map(r=>[r.id,r.review.fixedSource.trim()]));y.bundleReview=or({id:y.artifactBundle?.id,title:y.artifactBundle?.title,artifacts:y.artifactBundle?.artifacts?.map(r=>{const i=s.get(r.id)||null;return{...r,review:e.get(r.id)||r.review||y.step3Result||null,...i?{fixedCode:i}:{}}})||[],relationships:y.artifactBundle?.relationships,warnings:y.artifactBundle?.warnings})}function Wd(){const t=ga();return{artifactType:t.artifactType||"CustomWidget",artifactName:t.artifactName||"GeneratedWidget",fileName:t.fileName||""}}function ga(){const t=y.artifactBundle||y.bundleSpec||null;return(Array.isArray(t?.artifacts)?t.artifacts:[]).find(s=>s.id===y.selectedArtifactId)||fi(t)}function ma(){return ga().code||y.step2Result||""}async function lv(){try{await da()}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 cv(t,e){const s=e?.trim()?` (${e.trim().slice(0,200)})`:"";return t===401?`Your FlutterFlow API key was rejected (401 Unauthorized)${s}. Re-enter a current key under API Keys settings, then try again.`:`Listing FlutterFlow projects was denied (403)${s}. 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 gr{constructor(e,s,r="main",i=Wr.production){this.apiKey=e,this.baseUrl=i,this._projectId=s,this._branchName=r,this._endpoint=i}get projectId(){return this._projectId}get branchName(){return this._branchName==="main"?"":this._branchName}async exportProjectZip(){console.log(`Exporting code from FlutterFlow project: ${this.projectId}, branch: ${this.branchName||"main"}`);const e=[{project:{path:`projects/${this.projectId}`},...this.branchName?{branch_name:this.branchName}:{},export_as_module:!1,include_assets_map:!1,format:!1,export_as_debug:!1},{project_id:this.projectId,branch_name:this.branchName,include_assets:!1,export_as_module:!1}];let s=null;for(const r of e)try{const i=await fetch(`${this.baseUrl}exportCode`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify(r)});if(!i.ok){const a=await i.text();s=new Error(`Export failed: ${i.status} - ${a}`);continue}const n=await i.json(),o=n?.value?.project_zip||n?.project_zip;if(!o){s=new Error("Export response did not include project source.");continue}return o}catch(i){s=i}throw s||new Error("Export failed for an unknown reason.")}async fetchProjectSource(){const e=await this.exportProjectZip(),s=await JSZip.loadAsync(e,{base64:!0}),r=Object.keys(s.files).filter(a=>!s.files[a].dir&&(a==="pubspec.yaml"||a.endsWith("/pubspec.yaml"))).sort((a,l)=>a.split("/").length-l.split("/").length)[0];if(!r)throw new Error("Export did not contain a pubspec.yaml.");const i=r.slice(0,r.length-12),n=new Map,o=Object.keys(s.files).filter(a=>{if(s.files[a].dir||!a.startsWith(i))return!1;const l=a.slice(i.length);return l==="lib/flutter_flow/custom_functions.dart"||l.startsWith("lib/custom_code/")&&l.endsWith(".dart")});return await Promise.all(o.map(async a=>{n.set(a.slice(i.length),await s.files[a].async("string"))})),{pubspecYaml:await s.files[r].async("string"),files:n}}async pushCodeWithRetry(e,s=3){const r=[Wr.production,Wr.staging],i=Math.max(0,r.indexOf(this._endpoint));for(let n=0;nsetTimeout(d,1e3*(n+1)));continue}return l}catch(l){console.warn(`Push to ${a} failed: ${l.message}, trying next...`),await new Promise(u=>setTimeout(u,1e3*(n+1)))}}throw new Error("All API endpoints failed after retries")}async pushCode(e){return this.pushCodeWithRetry(e)}parseProjectsResponse(e){if(e?.success&&typeof e.value=="string")try{const r=JSON.parse(e.value);if(r&&Array.isArray(r.entries))return r.entries.map(i=>({id:i.id,name:i.project?.name||i.id}))}catch(r){console.error("Failed to parse stringified project value:",r)}const s=e?.projects||e?.items||e?.entries||(Array.isArray(e)?e:[]);return Array.isArray(s)?s:[]}async listProjects(){console.log("Listing projects for API key");const e=[`${this.baseUrl}listProjects`,"https://api.flutterflow.io/v2/l/listProjects"];let s=0,r="";for(const i of e){const n=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify({project_type:"ALL",deserialize_response:!0})});if(n.ok)return i!==e[0]&&console.log(`listProjects answered on legacy path ${i}`),this.parseProjectsResponse(await n.json());if(s=n.status,r=await n.text(),console.warn(`listProjects via ${i} returned ${s}: ${r}`),n.status===401||n.status===403)throw new Error(cv(n.status,r));if(n.status!==404)throw new Error(`List projects failed: ${n.status} - ${r}`)}throw new Error(`List projects failed: ${s} - ${r}`)}}async function va(t){const e=t.clone();let s;try{s=await t.json()}catch{const n=await e.text();if(!t.ok)return{success:!1,responseCode:t.status,errorMessage:n||`HTTP ${t.status}`,errorMap:new Map};throw new Error(`Invalid JSON response: ${n}`)}if(!t.ok){let i=s.message||`HTTP ${t.status}`,n=new Map;if(s.errors)n=new Map(Object.entries(s.errors));else if(!s.message&&typeof s=="object"){const o=Object.keys(s).filter(a=>a.endsWith(".dart")&&Array.isArray(s[a]));o.length>0&&(n=new Map(Object.entries(s)),i=o.flatMap(l=>s[l].map(u=>`${l}: ${u.errorMessage}`)).join(` -`)||`HTTP ${t.status}`)}return{success:!1,responseCode:t.status,errorMessage:i,errorMap:n}}let r={};if(s.value)try{r=typeof s.value=="string"?JSON.parse(s.value):s.value}catch(i){console.warn("Ignoring malformed push response value:",i)}return{success:!0,responseCode:t.status,errorMap:new Map(Object.entries(r))}}function _a(t,e){return{401:"Authentication failed. Please check your FlutterFlow API key.",403:"Access denied. You may not have permission to modify this project.",404:"Project not found. Please check your Project ID.",409:"Conflict detected. The project may have been modified elsewhere.",422:"Validation failed: Invalid request format",429:"Rate limit exceeded. Please try again in a few minutes.",500:"FlutterFlow server error. Please try again later.",503:"FlutterFlow service temporarily unavailable."}[t]||`FlutterFlow API error: ${`HTTP ${t}`}`}const U={ACTION:"A",WIDGET:"W",FUNCTION:"F",CODE_FILE:"C",DEPENDENCIES:"D",OTHER:"O"},zd=/class\s+\w+\s+extends\s+(?:StatelessWidget|StatefulWidget)\b/,qd=/extends\s+State<\w+>/;function uv(t,e=""){if(t==="pubspec.yaml")return U.DEPENDENCIES;if(!t.endsWith(".dart")||t.endsWith("index.dart"))return U.OTHER;if(t==="custom_functions.dart")return U.FUNCTION;if(e){const s=zd.test(e),r=qd.test(e);if(s||r)return U.WIDGET;if(/^\s*Future(?:<[^>]+>)?\s+\w+\s*\(/m.test(e))return U.ACTION;if(e.match(/^\s*(String|int|double|bool|List|Map|dynamic|void)\s+\w+\s*\(/m))return U.FUNCTION}return U.CODE_FILE}function Vd(t,e){switch(e){case U.ACTION:return`lib/custom_code/actions/${t}`;case U.WIDGET:return`lib/custom_code/widgets/${t}`;case U.FUNCTION:return"lib/flutter_flow/custom_functions.dart";case U.CODE_FILE:return`lib/custom_code/${t}`;case U.DEPENDENCIES:return"pubspec.yaml";case U.OTHER:return`lib/custom_code/${t}`;default:return t}}async function ya(t,e=new Map){return Gf(t,e)}const ko=new Map;function Gd(t){return`${t.baseUrl}|${t.projectId}|${t.branchName}`}function ji(t){ko.delete(Gd(t))}async function wa(t,e,s,r,i=""){const n=kg(e,s);if(n.length===0)return{remoteFiles:s,syncFileMap:e,unverified:[]};const o=sm(n,i),a={...o.manifest,sources:o.sources},l=o.skipped.map(d=>d.reason);l.forEach(d=>console.warn(`[custom class deploy] ${d}`)),console.log(`Provisioning ${n.length} new FlutterFlow custom code file(s) before sync.`),be.set("provision");const u=await fetch(bm,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:t.apiKey,projectId:t.projectId,baseUrl:t.baseUrl,commitMessage:r,customClasses:n,verification:a,stream:!0})}),c=await im(u,{onPhase:d=>be.setSubstatus(d),onLog:d=>console.log(`[custom class deploy] ${d}`)});if(!c.success){const d=c.details?` ${c.details}`:"";throw new Error(`${c.error||"FlutterFlow custom class provisioning failed."}${d}`)}return ji(t),c.verificationSkipped&&(console.warn(`[custom class deploy] ${c.verificationSkipped}`),l.push(c.verificationSkipped)),{remoteFiles:s,syncFileMap:Ig(e,n),unverified:l}}async function ba(t,e={}){const s=Gd(t);let r=ko.get(s);if(r===void 0){try{r=await t.fetchProjectSource()}catch(l){throw new Error(`Could not read your project's pubspec.yaml (${l.message}). Deploy was stopped so your existing package dependencies aren't overwritten. Check your FlutterFlow API key and project, then try again.`)}const a=Id(r.pubspecYaml);if(!a.valid)throw new Error(`Your project's pubspec.yaml could not be read reliably (${a.errors.join("; ")}). Deploy was stopped so your existing package dependencies aren't overwritten.`);ko.set(s,r)}const i=await gm(r.pubspecYaml,e),n=Yg(r.pubspecYaml,i.overrides),o=Jg(n.yaml,i.additions);return i.warnings.forEach(a=>console.warn(`[pubspec] ${a}`)),o.added.length>0&&console.log("Adding dependencies:",o.added.map(a=>`${a}: ${i.additions[a]||"any"}`).join(", "),i.sdk.dartSdkFloor?`(resolved for Dart ${i.sdk.dartSdkFloor})`:""),i.kept.forEach(({name:a,constraint:l})=>console.log(`Keeping your existing ${a}: ${l||"(non-version source)"}`)),{...o,overridden:n.overridden,warnings:i.warnings,remoteFiles:r.files}}function dv(t){const e=[],s=[];t.content.length>5e4&&s.push("Code file is large (>50KB). This may take longer to commit."),t.content.length>1e5&&e.push("Code file is too large (>100KB). Consider splitting into smaller components.");const r=t.content.split(` -`).length;r>500&&s.push(`Code has ${r} lines. Consider breaking it into smaller widgets.`),t.content.includes("setState")&&t.codeType===U.ACTION&&s.push("Using setState in a Custom Action may not work as expected. Consider using a Custom Widget."),t.content.includes("dynamic")&&!t.content.includes("?")&&s.push('Code uses "dynamic" types. Consider adding explicit types for better null safety.'),t.content.match(/Color\(0xFF[0-9A-Fa-f]{6}\)/)&&s.push("Code contains hardcoded colors. Consider using FlutterFlowTheme.of(context) for theme consistency.");const i=t.content.match(/print\s*\(/g);i&&i.length>3&&s.push(`Code contains ${i.length} print statements. Consider removing debug prints before committing.`);const n=zg(t.content);if(n&&e.push(`FlutterFlow cannot format this code - ${n}. Fix or regenerate before committing.`),t.codeType===U.WIDGET){const o=wd(t.content),a=Ug(t.fileName);if(o.length===0)e.push("No public widget class found (must extend StatelessWidget or StatefulWidget).");else if(!o.includes(a)){const l=`${bd(o[0])}`;e.push(`Widget class name "${o[0]}" does not match the file name "${t.fileName}". FlutterFlow derives the widget from the file name, so it will report "No widget ${a} found". Rename the file to "${l}" or the class to match before committing.`)}}return{canProceed:e.length===0,issues:e,warnings:s}}function Kd(t,e={}){const{artifactType:s="CustomWidget",artifactName:r="GeneratedCode",fileName:i}=e,n=Bg(t);let o=i||r;if(s==="CustomFunction")o="custom_functions.dart";else if(s==="CustomWidget"){const u=wd(n)[0],c=u?bd(u):null;c&&o!==c?(console.warn(`Commit file name "${o}" does not match declared widget class "${u}"; renaming to "${c}" so FlutterFlow can find the widget.`),o=c):o.endsWith(".dart")||(o+=".dart")}else o.endsWith(".dart")||(o+=".dart");let a=U.CODE_FILE;switch(s){case"CustomAction":a=U.ACTION;break;case"CustomWidget":a=U.WIDGET;break;case"CustomFunction":a=U.FUNCTION;break;case"CustomClass":case"CodeFile":a=U.CODE_FILE;break}let l="";return a===U.WIDGET?l=`// Automatic FlutterFlow imports + `)}let y={step1Result:null,step2Result:null,step3Result:null,bundleSpec:null,artifactBundle:null,bundleReview:null,selectedArtifactId:null,resultsViewMode:"summary",currentStep:0,isRunning:!1};function ov(){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 av(){y.bundleSpec=ar(y.step1Result,{artifactType:"CustomWidget",artifactName:"GeneratedWidget"})}function Un(){const t=mn(y.bundleSpec);y.artifactBundle=ar(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=hg(y.artifactBundle);y.artifactBundle={...y.artifactBundle,warnings:[...y.artifactBundle.warnings,...e.findings.map(s=>s.message)],metadata:{...y.artifactBundle.metadata,compatibility:e}},y.selectedArtifactId=mn(y.artifactBundle).id}function Hn(){const t=ar(y.step3Result,{id:y.artifactBundle?.id,title:y.artifactBundle?.title}),e=new Map(t.artifacts.map(r=>[r.id,r.review])),s=new Map(t.artifacts.filter(r=>{const n=r.review;return n&&typeof n.fixedSource=="string"&&n.fixedSource.trim()}).map(r=>[r.id,r.review.fixedSource.trim()]));y.bundleReview=ar({id:y.artifactBundle?.id,title:y.artifactBundle?.title,artifacts:y.artifactBundle?.artifacts?.map(r=>{const n=s.get(r.id)||null;return{...r,review:e.get(r.id)||r.review||y.step3Result||null,...n?{fixedCode:n}:{}}})||[],relationships:y.artifactBundle?.relationships,warnings:y.artifactBundle?.warnings})}function zd(){const t=ma();return{artifactType:t.artifactType||"CustomWidget",artifactName:t.artifactName||"GeneratedWidget",fileName:t.fileName||""}}function ma(){const t=y.artifactBundle||y.bundleSpec||null;return(Array.isArray(t?.artifacts)?t.artifacts:[]).find(s=>s.id===y.selectedArtifactId)||mn(t)}function va(){return ma().code||y.step2Result||""}async function lv(){try{await ha()}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 cv(t,e){const s=e?.trim()?` (${e.trim().slice(0,200)})`:"";return t===401?`Your FlutterFlow API key was rejected (401 Unauthorized)${s}. Re-enter a current key under API Keys settings, then try again.`:`Listing FlutterFlow projects was denied (403)${s}. 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 mr{constructor(e,s,r="main",n=zr.production){this.apiKey=e,this.baseUrl=n,this._projectId=s,this._branchName=r,this._endpoint=n}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 s=null;for(const r of e)try{const n=await fetch(`${this.baseUrl}exportCode`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify(r)});if(!n.ok){const a=await n.text();s=new Error(`Export failed: ${n.status} - ${a}`);continue}const i=await n.json(),o=i?.value?.project_zip||i?.project_zip;if(!o){s=new Error("Export response did not include project source.");continue}return o}catch(n){s=n}throw s||new Error("Export failed for an unknown reason.")}async fetchProjectSource(){const e=await this.exportProjectZip(),s=await JSZip.loadAsync(e,{base64:!0}),r=Object.keys(s.files).filter(a=>!s.files[a].dir&&(a==="pubspec.yaml"||a.endsWith("/pubspec.yaml"))).sort((a,l)=>a.split("/").length-l.split("/").length)[0];if(!r)throw new Error("Export did not contain a pubspec.yaml.");const n=r.slice(0,r.length-12),i=new Map,o=Object.keys(s.files).filter(a=>{if(s.files[a].dir||!a.startsWith(n))return!1;const l=a.slice(n.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=>{i.set(a.slice(n.length),await s.files[a].async("string"))})),{pubspecYaml:await s.files[r].async("string"),files:i}}async pushCodeWithRetry(e,s=3){const r=[zr.production,zr.staging],n=Math.max(0,r.indexOf(this._endpoint));for(let i=0;isetTimeout(d,1e3*(i+1)));continue}return l}catch(l){console.warn(`Push to ${a} failed: ${l.message}, trying next...`),await new Promise(u=>setTimeout(u,1e3*(i+1)))}}throw new Error("All API endpoints failed after retries")}async pushCode(e){return this.pushCodeWithRetry(e)}parseProjectsResponse(e){if(e?.success&&typeof e.value=="string")try{const r=JSON.parse(e.value);if(r&&Array.isArray(r.entries))return r.entries.map(n=>({id:n.id,name:n.project?.name||n.id}))}catch(r){console.error("Failed to parse stringified project value:",r)}const s=e?.projects||e?.items||e?.entries||(Array.isArray(e)?e:[]);return Array.isArray(s)?s:[]}async listProjects(){console.log("Listing projects for API key");const e=[`${this.baseUrl}listProjects`,"https://api.flutterflow.io/v2/l/listProjects"];let s=0,r="";for(const n of e){const i=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify({project_type:"ALL",deserialize_response:!0})});if(i.ok)return n!==e[0]&&console.log(`listProjects answered on legacy path ${n}`),this.parseProjectsResponse(await i.json());if(s=i.status,r=await i.text(),console.warn(`listProjects via ${n} returned ${s}: ${r}`),i.status===401||i.status===403)throw new Error(cv(i.status,r));if(i.status!==404)throw new Error(`List projects failed: ${i.status} - ${r}`)}throw new Error(`List projects failed: ${s} - ${r}`)}}async function _a(t){const e=t.clone();let s;try{s=await t.json()}catch{const i=await e.text();if(!t.ok)return{success:!1,responseCode:t.status,errorMessage:i||`HTTP ${t.status}`,errorMap:new Map};throw new Error(`Invalid JSON response: ${i}`)}if(!t.ok){let n=s.message||`HTTP ${t.status}`,i=new Map;if(s.errors)i=new Map(Object.entries(s.errors));else if(!s.message&&typeof s=="object"){const o=Object.keys(s).filter(a=>a.endsWith(".dart")&&Array.isArray(s[a]));o.length>0&&(i=new Map(Object.entries(s)),n=o.flatMap(l=>s[l].map(u=>`${l}: ${u.errorMessage}`)).join(` +`)||`HTTP ${t.status}`)}return{success:!1,responseCode:t.status,errorMessage:n,errorMap:i}}let r={};if(s.value)try{r=typeof s.value=="string"?JSON.parse(s.value):s.value}catch(n){console.warn("Ignoring malformed push response value:",n)}return{success:!0,responseCode:t.status,errorMap:new Map(Object.entries(r))}}function ya(t,e){return{401:"Authentication failed. Please check your FlutterFlow API key.",403:"Access denied. You may not have permission to modify this project.",404:"Project not found. Please check your Project ID.",409:"Conflict detected. The project may have been modified elsewhere.",422:"Validation failed: Invalid request format",429:"Rate limit exceeded. Please try again in a few minutes.",500:"FlutterFlow server error. Please try again later.",503:"FlutterFlow service temporarily unavailable."}[t]||`FlutterFlow API error: ${`HTTP ${t}`}`}const U={ACTION:"A",WIDGET:"W",FUNCTION:"F",CODE_FILE:"C",DEPENDENCIES:"D",OTHER:"O"},qd=/class\s+\w+\s+extends\s+(?:StatelessWidget|StatefulWidget)\b/,Vd=/extends\s+State<\w+>/;function uv(t,e=""){if(t==="pubspec.yaml")return U.DEPENDENCIES;if(!t.endsWith(".dart")||t.endsWith("index.dart"))return U.OTHER;if(t==="custom_functions.dart")return U.FUNCTION;if(e){const s=qd.test(e),r=Vd.test(e);if(s||r)return U.WIDGET;if(/^\s*Future(?:<[^>]+>)?\s+\w+\s*\(/m.test(e))return U.ACTION;if(e.match(/^\s*(String|int|double|bool|List|Map|dynamic|void)\s+\w+\s*\(/m))return U.FUNCTION}return U.CODE_FILE}function Gd(t,e){switch(e){case U.ACTION:return`lib/custom_code/actions/${t}`;case U.WIDGET:return`lib/custom_code/widgets/${t}`;case U.FUNCTION:return"lib/flutter_flow/custom_functions.dart";case U.CODE_FILE:return`lib/custom_code/${t}`;case U.DEPENDENCIES:return"pubspec.yaml";case U.OTHER:return`lib/custom_code/${t}`;default:return t}}async function wa(t,e=new Map){return Kf(t,e)}const Fo=new Map;function Kd(t){return`${t.baseUrl}|${t.projectId}|${t.branchName}`}function Wn(t){Fo.delete(Kd(t))}async function ba(t,e,s,r,n=""){const i=Ig(e,s);if(i.length===0)return{remoteFiles:s,syncFileMap:e,unverified:[]};const o=sm(i,n),a={...o.manifest,sources:o.sources},l=o.skipped.map(d=>d.reason);l.forEach(d=>console.warn(`[custom class deploy] ${d}`)),console.log(`Provisioning ${i.length} new FlutterFlow custom code file(s) before sync.`),be.set("provision");const u=await fetch(bm,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:t.apiKey,projectId:t.projectId,baseUrl:t.baseUrl,commitMessage:r,customClasses:i,verification:a,stream:!0})}),c=await nm(u,{onPhase:d=>be.setSubstatus(d),onLog:d=>console.log(`[custom class deploy] ${d}`)});if(!c.success){const d=c.details?` ${c.details}`:"";throw new Error(`${c.error||"FlutterFlow custom class provisioning failed."}${d}`)}return Wn(t),c.verificationSkipped&&(console.warn(`[custom class deploy] ${c.verificationSkipped}`),l.push(c.verificationSkipped)),{remoteFiles:s,syncFileMap:Cg(e,i),unverified:l}}async function Ea(t,e={}){const s=Kd(t);let r=Fo.get(s);if(r===void 0){try{r=await t.fetchProjectSource()}catch(l){throw new Error(`Could not read your project's pubspec.yaml (${l.message}). Deploy was stopped so your existing package dependencies aren't overwritten. Check your FlutterFlow API key and project, then try again.`)}const a=Fd(r.pubspecYaml);if(!a.valid)throw new Error(`Your project's pubspec.yaml could not be read reliably (${a.errors.join("; ")}). Deploy was stopped so your existing package dependencies aren't overwritten.`);Fo.set(s,r)}const n=await gm(r.pubspecYaml,e),i=Zg(r.pubspecYaml,n.overrides),o=Yg(i.yaml,n.additions);return n.warnings.forEach(a=>console.warn(`[pubspec] ${a}`)),o.added.length>0&&console.log("Adding dependencies:",o.added.map(a=>`${a}: ${n.additions[a]||"any"}`).join(", "),n.sdk.dartSdkFloor?`(resolved for Dart ${n.sdk.dartSdkFloor})`:""),n.kept.forEach(({name:a,constraint:l})=>console.log(`Keeping your existing ${a}: ${l||"(non-version source)"}`)),{...o,overridden:i.overridden,warnings:n.warnings,remoteFiles:r.files}}function dv(t){const e=[],s=[];t.content.length>5e4&&s.push("Code file is large (>50KB). This may take longer to commit."),t.content.length>1e5&&e.push("Code file is too large (>100KB). Consider splitting into smaller components.");const r=t.content.split(` +`).length;r>500&&s.push(`Code has ${r} lines. Consider breaking it into smaller widgets.`),t.content.includes("setState")&&t.codeType===U.ACTION&&s.push("Using setState in a Custom Action may not work as expected. Consider using a Custom Widget."),t.content.includes("dynamic")&&!t.content.includes("?")&&s.push('Code uses "dynamic" types. Consider adding explicit types for better null safety.'),t.content.match(/Color\(0xFF[0-9A-Fa-f]{6}\)/)&&s.push("Code contains hardcoded colors. Consider using FlutterFlowTheme.of(context) for theme consistency.");const n=t.content.match(/print\s*\(/g);n&&n.length>3&&s.push(`Code contains ${n.length} print statements. Consider removing debug prints before committing.`);const i=qg(t.content);if(i&&e.push(`FlutterFlow cannot format this code - ${i}. Fix or regenerate before committing.`),t.codeType===U.WIDGET){const o=bd(t.content),a=Hg(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=`${Ed(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:s}}function Jd(t,e={}){const{artifactType:s="CustomWidget",artifactName:r="GeneratedCode",fileName:n}=e,i=jg(t);let o=n||r;if(s==="CustomFunction")o="custom_functions.dart";else if(s==="CustomWidget"){const u=bd(i)[0],c=u?Ed(u):null;c&&o!==c?(console.warn(`Commit file name "${o}" does not match declared widget class "${u}"; renaming to "${c}" so FlutterFlow can find the widget.`),o=c):o.endsWith(".dart")||(o+=".dart")}else o.endsWith(".dart")||(o+=".dart");let a=U.CODE_FILE;switch(s){case"CustomAction":a=U.ACTION;break;case"CustomWidget":a=U.WIDGET;break;case"CustomFunction":a=U.FUNCTION;break;case"CustomClass":case"CodeFile":a=U.CODE_FILE;break}let l="";return a===U.WIDGET?l=`// Automatic FlutterFlow imports import '/flutter_flow/flutter_flow_theme.dart'; import '/flutter_flow/flutter_flow_util.dart'; import 'package:flutter/material.dart'; @@ -109,15 +109,15 @@ import '/flutter_flow/lat_lng.dart'; import '/flutter_flow/place.dart'; import '/flutter_flow/uploaded_file.dart'; -`),{content:fg(n,l),fileName:o,codeType:a,artifactType:s,artifactName:r}}function hv(t){const e={};for(const s of ta(t))e[s]="";return e}function pv(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 fv(t,e,s,r=new Set,i=""){const n=[],o=zd.test(e),a=qd.test(e);return s===U.WIDGET&&!o&&!a&&n.push("No widget class definition found (must extend StatelessWidget or StatefulWidget)"),{valid:n.length===0,errors:n}}function Ui(t){const e=[],s=[];if(!t||t.size===0)return e.push("No files to commit"),{valid:!1,errors:e,warnings:s};const r=new Set(Array.from(t.values()).flatMap(i=>Ri(i.content||"")));for(const[i,n]of t.entries()){if((!n.content||n.content.trim().length===0)&&e.push(`File ${i} is empty`),n.content&&n.content.length>1e5&&s.push(`File ${i} is very large (>100KB)`),i.endsWith(".dart")){const o=fv(i,n.content,n.type,r,n.artifactName);o.valid||e.push(...o.errors.map(a=>`${i}: ${a}`))}if(i==="pubspec.yaml"){const o=Id(n.content);o.valid||e.push(...o.errors)}}return{valid:e.length===0,errors:e,warnings:s}}const V={IDLE:"IDLE",PREPARING:"PREPARING",VALIDATING:"VALIDATING",PUSHING:"PUSHING",SUCCESS:"SUCCESS",ERROR:"ERROR"},K={currentState:V.IDLE,startTime:null,endTime:null,error:null,result:null,filesProcessed:0,totalFiles:0,reset(){this.currentState=V.IDLE,this.startTime=null,this.endTime=null,this.error=null,this.result=null,this.filesProcessed=0,this.totalFiles=0},setState(t){if(!Object.values(V).includes(t)){console.error(`Invalid commit state: ${t}`);return}this.currentState=t,t===V.PREPARING&&(this.startTime=Date.now()),(t===V.SUCCESS||t===V.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(V.ERROR)},setSuccess(t){this.result=t,this.setState(V.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===V.PREPARING||this.currentState===V.VALIDATING||this.currentState===V.PUSHING}};async function gv(t,e,s={}){let{codeType:r="W"}=s;const{pubspecDeps:i={},artifactName:n=e}=s;r==="CustomWidget"&&(r=U.WIDGET),r==="CustomAction"&&(r=U.ACTION),r==="CustomFunction"&&(r=U.FUNCTION),r==="CustomClass"&&(r=U.CODE_FILE),r==="CodeFile"&&(r=U.CODE_FILE),K.reset(),K.setState(V.PREPARING);try{const o=await Ee("flutterflow"),a=await Ee("flutterflow_project_id");if(!o||!a)throw new Error("FlutterFlow credentials not configured. Please set your API key and Project ID in the API Keys settings.");if(!Oi(a))throw new Error("Invalid FlutterFlow Project ID format.");const l=fr(),u=new gr(o,a,"main",l);K.setState(V.VALIDATING);const c=new Map,d=r||uv(e,t),h=Vd(e,d);c.set(e,{artifactName:n,content:t,type:d,path:h}),K.setProgress(0,c.size);const p=Ui(c);if(!p.valid)throw new Error(`Validation failed: +`),{content:gg(i,l),fileName:o,codeType:a,artifactType:s,artifactName:r}}function hv(t){const e={};for(const s of na(t))e[s]="";return e}function pv(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 fv(t,e,s,r=new Set,n=""){const i=[],o=qd.test(e),a=Vd.test(e);return s===U.WIDGET&&!o&&!a&&i.push("No widget class definition found (must extend StatelessWidget or StatefulWidget)"),{valid:i.length===0,errors:i}}function zn(t){const e=[],s=[];if(!t||t.size===0)return e.push("No files to commit"),{valid:!1,errors:e,warnings:s};const r=new Set(Array.from(t.values()).flatMap(n=>Nn(n.content||"")));for(const[n,i]of t.entries()){if((!i.content||i.content.trim().length===0)&&e.push(`File ${n} is empty`),i.content&&i.content.length>1e5&&s.push(`File ${n} is very large (>100KB)`),n.endsWith(".dart")){const o=fv(n,i.content,i.type,r,i.artifactName);o.valid||e.push(...o.errors.map(a=>`${n}: ${a}`))}if(n==="pubspec.yaml"){const o=Fd(i.content);o.valid||e.push(...o.errors)}}return{valid:e.length===0,errors:e,warnings:s}}const V={IDLE:"IDLE",PREPARING:"PREPARING",VALIDATING:"VALIDATING",PUSHING:"PUSHING",SUCCESS:"SUCCESS",ERROR:"ERROR"},K={currentState:V.IDLE,startTime:null,endTime:null,error:null,result:null,filesProcessed:0,totalFiles:0,reset(){this.currentState=V.IDLE,this.startTime=null,this.endTime=null,this.error=null,this.result=null,this.filesProcessed=0,this.totalFiles=0},setState(t){if(!Object.values(V).includes(t)){console.error(`Invalid commit state: ${t}`);return}this.currentState=t,t===V.PREPARING&&(this.startTime=Date.now()),(t===V.SUCCESS||t===V.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(V.ERROR)},setSuccess(t){this.result=t,this.setState(V.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===V.PREPARING||this.currentState===V.VALIDATING||this.currentState===V.PUSHING}};async function gv(t,e,s={}){let{codeType:r="W"}=s;const{pubspecDeps:n={},artifactName:i=e}=s;r==="CustomWidget"&&(r=U.WIDGET),r==="CustomAction"&&(r=U.ACTION),r==="CustomFunction"&&(r=U.FUNCTION),r==="CustomClass"&&(r=U.CODE_FILE),r==="CodeFile"&&(r=U.CODE_FILE),K.reset(),K.setState(V.PREPARING);try{const o=await Ee("flutterflow"),a=await Ee("flutterflow_project_id");if(!o||!a)throw new Error("FlutterFlow credentials not configured. Please set your API key and Project ID in the API Keys settings.");if(!jn(a))throw new Error("Invalid FlutterFlow Project ID format.");const l=gr(),u=new mr(o,a,"main",l);K.setState(V.VALIDATING);const c=new Map,d=r||uv(e,t),h=Gd(e,d);c.set(e,{artifactName:i,content:t,type:d,path:h}),K.setProgress(0,c.size);const p=zn(c);if(!p.valid)throw new Error(`Validation failed: ${p.errors.join(` -`)}`);const f=await ba(u,i),g=f.yaml,m=await wa(u,c,f.remoteFiles,`Provision ${n} custom class`,g),_=await ya(m.syncFileMap,m.remoteFiles),E=new Map(m.syncFileMap);E.set("pubspec.yaml",{content:g,type:"D",path:"pubspec.yaml"}),be.set("package");const b=await Ea(E),I={project_id:a,zipped_custom_code:b,uid:`web_${Date.now()}`,branch_name:u.branchName,serialized_yaml:g,file_map:_.fileMapContents,functions_map:_.functionsMapContents};K.setState(V.PUSHING),K.setProgress(1,c.size),ji(u),be.set("push");const F=await u.pushCode(I),P=await va(F);if(P.success)K.setSuccess({fileCount:c.size,projectId:a,warnings:P.errorMap&&P.errorMap.size>0?Array.from(P.errorMap.entries()):[]});else{const B=P.errorMessage||_a(P.responseCode);throw new Error(B)}return{success:!0,message:`Successfully committed ${e} to FlutterFlow project ${a}`,addedDependencies:f.added,unverified:m.unverified,warnings:P.errorMap?Array.from(P.errorMap.entries()):[]}}catch(o){return console.error("Commit failed:",o),K.setError(o),{success:!1,error:o.message,state:K.currentState}}}async function Ea(t){const e=new JSZip;for(const[s,r]of t.entries())e.file(s,r.content);return e.generateAsync({type:"base64",compression:"DEFLATE",compressionOptions:{level:6}})}async function mv(t,e={}){const{artifactType:s,artifactName:r,fileName:i,pipelineResult:n}=e;console.log(`Starting commit for ${r} (${s})`);try{K.setState(V.PREPARING);const o=Kd(t,{artifactType:s,artifactName:r,fileName:i}),a=hv(o.content);console.log("Detected dependencies:",a),K.setState(V.VALIDATING);const l=await Ee("flutterflow"),u=Zs||await Ee("flutterflow_project_id");if(!l)throw new Error("FlutterFlow API Key not configured. Please add it in API Keys settings.");if(!u)throw new Error("FlutterFlow Project ID not configured. Please add it in API Keys settings.");if(!Oi(u))throw new Error("Invalid FlutterFlow Project ID format.");const c=new Map;c.set(o.fileName,{artifactName:r,content:o.content,type:o.codeType,path:Vd(o.fileName,o.codeType),functionName:o.codeType===U.FUNCTION?r:void 0}),K.setProgress(0,c.size);const d=Ui(c);if(!d.valid)throw new Error(`File validation failed: +`)}`);const f=await Ea(u,n),g=f.yaml,m=await ba(u,c,f.remoteFiles,`Provision ${i} custom class`,g),_=await wa(m.syncFileMap,m.remoteFiles),b=new Map(m.syncFileMap);b.set("pubspec.yaml",{content:g,type:"D",path:"pubspec.yaml"}),be.set("package");const E=await Sa(b),I={project_id:a,zipped_custom_code:E,uid:`web_${Date.now()}`,branch_name:u.branchName,serialized_yaml:g,file_map:_.fileMapContents,functions_map:_.functionsMapContents};K.setState(V.PUSHING),K.setProgress(1,c.size),Wn(u),be.set("push");const F=await u.pushCode(I),P=await _a(F);if(P.success)K.setSuccess({fileCount:c.size,projectId:a,warnings:P.errorMap&&P.errorMap.size>0?Array.from(P.errorMap.entries()):[]});else{const B=P.errorMessage||ya(P.responseCode);throw new Error(B)}return{success:!0,message:`Successfully committed ${e} to FlutterFlow project ${a}`,addedDependencies:f.added,unverified:m.unverified,warnings:P.errorMap?Array.from(P.errorMap.entries()):[]}}catch(o){return console.error("Commit failed:",o),K.setError(o),{success:!1,error:o.message,state:K.currentState}}}async function Sa(t){const e=new JSZip;for(const[s,r]of t.entries())e.file(s,r.content);return e.generateAsync({type:"base64",compression:"DEFLATE",compressionOptions:{level:6}})}async function mv(t,e={}){const{artifactType:s,artifactName:r,fileName:n,pipelineResult:i}=e;console.log(`Starting commit for ${r} (${s})`);try{K.setState(V.PREPARING);const o=Jd(t,{artifactType:s,artifactName:r,fileName:n}),a=hv(o.content);console.log("Detected dependencies:",a),K.setState(V.VALIDATING);const l=await Ee("flutterflow"),u=Xs||await Ee("flutterflow_project_id");if(!l)throw new Error("FlutterFlow API Key not configured. Please add it in API Keys settings.");if(!u)throw new Error("FlutterFlow Project ID not configured. Please add it in API Keys settings.");if(!jn(u))throw new Error("Invalid FlutterFlow Project ID format.");const c=new Map;c.set(o.fileName,{artifactName:r,content:o.content,type:o.codeType,path:Gd(o.fileName,o.codeType),functionName:o.codeType===U.FUNCTION?r:void 0}),K.setProgress(0,c.size);const d=zn(c);if(!d.valid)throw new Error(`File validation failed: ${d.errors.join(` -`)}`);d.warnings.length>0&&console.warn("Validation warnings:",d.warnings),K.setState(V.PUSHING);const h=fr(),p=new gr(l,u,"main",h),f=await ba(p,a),g=f.yaml,m=await wa(p,c,f.remoteFiles,`Provision ${r} custom class`,g),_=await ya(m.syncFileMap,m.remoteFiles),E=new Map(m.syncFileMap);E.set("pubspec.yaml",{content:g,type:U.DEPENDENCIES,path:"pubspec.yaml"}),be.set("package");const b=await Ea(E),I={project_id:u,zipped_custom_code:b,uid:`web_${Date.now()}`,branch_name:p.branchName,serialized_yaml:g,file_map:_.fileMapContents,functions_map:_.functionsMapContents};K.setProgress(1,c.size),ji(p),be.set("push");const F=await p.pushCode(I),P=await va(F);if(P.success){const B={...pv(o,n),projectId:u};return K.setSuccess({...B,fileCount:c.size,warnings:P.errorMap?Array.from(P.errorMap.entries()):[]}),{success:!0,message:`Successfully committed ${o.fileName} to FlutterFlow`,metadata:B,addedDependencies:f.added,unverified:m.unverified,warnings:P.errorMap?Array.from(P.errorMap.entries()):[],elapsedTime:K.getElapsedTime()}}else{const B=P.errorMessage||_a(P.responseCode),S=new Error(B);throw S.errorMap=P.errorMap,S}}catch(o){console.error("Commit execution failed:",o),K.setError(o);let a=new Map;if(o.errorMap)a=o.errorMap;else if(o.message&&o.message.includes("{"))try{const l=o.message.match(/\{[\s\S]*\}/);if(l){const u=JSON.parse(l[0]);a=new Map(Object.entries(u))}}catch(l){console.warn("Failed to parse error map from commit response:",l)}return{success:!1,error:o.message,errorMap:a,state:K.currentState,elapsedTime:K.getElapsedTime()}}}async function vv(t,e={}){const{pipelineResult:s}=e;try{if(K.setState(V.PREPARING),t.errors?.length>0)throw new Error(`Bundle validation failed: +`)}`);d.warnings.length>0&&console.warn("Validation warnings:",d.warnings),K.setState(V.PUSHING);const h=gr(),p=new mr(l,u,"main",h),f=await Ea(p,a),g=f.yaml,m=await ba(p,c,f.remoteFiles,`Provision ${r} custom class`,g),_=await wa(m.syncFileMap,m.remoteFiles),b=new Map(m.syncFileMap);b.set("pubspec.yaml",{content:g,type:U.DEPENDENCIES,path:"pubspec.yaml"}),be.set("package");const E=await Sa(b),I={project_id:u,zipped_custom_code:E,uid:`web_${Date.now()}`,branch_name:p.branchName,serialized_yaml:g,file_map:_.fileMapContents,functions_map:_.functionsMapContents};K.setProgress(1,c.size),Wn(p),be.set("push");const F=await p.pushCode(I),P=await _a(F);if(P.success){const B={...pv(o,i),projectId:u};return K.setSuccess({...B,fileCount:c.size,warnings:P.errorMap?Array.from(P.errorMap.entries()):[]}),{success:!0,message:`Successfully committed ${o.fileName} to FlutterFlow`,metadata:B,addedDependencies:f.added,unverified:m.unverified,warnings:P.errorMap?Array.from(P.errorMap.entries()):[],elapsedTime:K.getElapsedTime()}}else{const B=P.errorMessage||ya(P.responseCode),S=new Error(B);throw S.errorMap=P.errorMap,S}}catch(o){console.error("Commit execution failed:",o),K.setError(o);let a=new Map;if(o.errorMap)a=o.errorMap;else if(o.message&&o.message.includes("{"))try{const l=o.message.match(/\{[\s\S]*\}/);if(l){const u=JSON.parse(l[0]);a=new Map(Object.entries(u))}}catch(l){console.warn("Failed to parse error map from commit response:",l)}return{success:!1,error:o.message,errorMap:a,state:K.currentState,elapsedTime:K.getElapsedTime()}}}async function vv(t,e={}){const{pipelineResult:s}=e;try{if(K.setState(V.PREPARING),t.errors?.length>0)throw new Error(`Bundle validation failed: ${t.errors.join(` -`)}`);const r=new Map(t.fileEntries.map(I=>[I.fileName,{artifactId:I.artifactId,artifactName:I.artifactName,content:I.content,type:I.type,path:I.path,functionName:I.type===U.FUNCTION?I.artifactName:void 0}]));K.setProgress(0,r.size);const i=Ui(r);if(!i.valid)throw new Error(`File validation failed: -${i.errors.join(` -`)}`);K.setState(V.VALIDATING);const n=await Ee("flutterflow"),o=Zs||await Ee("flutterflow_project_id");if(!n)throw new Error("FlutterFlow API Key not configured. Please add it in API Keys settings.");if(!o)throw new Error("FlutterFlow Project ID not configured. Please add it in API Keys settings.");if(!Oi(o))throw new Error("Invalid FlutterFlow Project ID format.");K.setState(V.PUSHING);const a=fr(),l=new gr(n,o,"main",a),u=await ba(l,t.dependencies),c=u.yaml,d=await wa(l,r,u.remoteFiles,`Provision ${t.title} custom classes`,c),h=await ya(d.syncFileMap,d.remoteFiles),p=new Map(d.syncFileMap);p.set("pubspec.yaml",{content:c,type:U.DEPENDENCIES,path:"pubspec.yaml"}),be.set("package");const f=await Ea(p),g={project_id:o,zipped_custom_code:f,uid:`web_${Date.now()}`,branch_name:l.branchName,serialized_yaml:c,file_map:h.fileMapContents,functions_map:h.functionsMapContents};K.setProgress(1,r.size),ji(l),be.set("push");const m=await l.pushCode(g),_=await va(m);if(_.success){const I={...s,artifactType:"Bundle",artifactName:t.title,fileName:`${t.fileEntries.length} artifacts`,codeSize:t.fileEntries.reduce((F,P)=>F+P.content.length,0),projectId:o};return K.setSuccess({...I,fileCount:r.size,warnings:_.errorMap?Array.from(_.errorMap.entries()):[]}),{success:!0,message:`Successfully committed ${t.fileEntries.length} artifacts to FlutterFlow`,metadata:I,addedDependencies:u.added,unverified:d.unverified,warnings:_.errorMap?Array.from(_.errorMap.entries()):[],elapsedTime:K.getElapsedTime()}}const E=_.errorMessage||_a(_.responseCode),b=new Error(E);throw b.errorMap=_.errorMap,b}catch(r){return console.error("Bundle commit execution failed:",r),K.setError(r),{success:!1,error:r.message,errorMap:r.errorMap||new Map,state:K.currentState,elapsedTime:K.getElapsedTime()}}}async function _v(t,e=[]){const s=Zo("architect");try{return await ki("architect",Td,Mf(t),s,e)}catch(r){throw r.isModelArmor?r:new Error(`Prompt Architect failed: ${r.message}`)}}async function Hi(t,e,s=[]){const r=Lf(t),i=Zo("generator",y.bundleSpec);try{return await ki("generator",e,r,i,s)}catch(n){if(n.isModelArmor)throw n;if(e!==Cn){console.warn(`Code Generator failed with ${e}, retrying with fallback model:`,n.message);try{return await ki("generator",Cn,r,i,s)}catch(o){throw o.isModelArmor?o:new Error(`Code Generator failed: primary (${e}): ${n.message} | fallback (${Cn}): ${o.message}`)}}throw new Error(`Code Generator failed: ${n.message}`)}}async function Wi(t,e=null){const s={...Zo("review",y.artifactBundle||y.bundleSpec),architect_output:e};try{return await ki("review",Nd,Of(t),s)}catch(r){throw r.isModelArmor?r:new Error(`Code Review failed: ${r.message}`)}}function Sa(t,e){return t.isModelArmor?`${t.userTitle}: ${t.userMessage}`:`${e}: ${t.message}`}function Io(t,e){const s=document.getElementById(`step${t}-item`),r=document.getElementById(`step${t}-status`);!s||!r||(s.classList.remove("active","completed","error"),r.classList.remove("running","completed","error"),e==="active"?(s.classList.add("active"),r.classList.add("running"),r.innerHTML=` +`)}`);const r=new Map(t.fileEntries.map(I=>[I.fileName,{artifactId:I.artifactId,artifactName:I.artifactName,content:I.content,type:I.type,path:I.path,functionName:I.type===U.FUNCTION?I.artifactName:void 0}]));K.setProgress(0,r.size);const n=zn(r);if(!n.valid)throw new Error(`File validation failed: +${n.errors.join(` +`)}`);K.setState(V.VALIDATING);const i=await Ee("flutterflow"),o=Xs||await Ee("flutterflow_project_id");if(!i)throw new Error("FlutterFlow API Key not configured. Please add it in API Keys settings.");if(!o)throw new Error("FlutterFlow Project ID not configured. Please add it in API Keys settings.");if(!jn(o))throw new Error("Invalid FlutterFlow Project ID format.");K.setState(V.PUSHING);const a=gr(),l=new mr(i,o,"main",a),u=await Ea(l,t.dependencies),c=u.yaml,d=await ba(l,r,u.remoteFiles,`Provision ${t.title} custom classes`,c),h=await wa(d.syncFileMap,d.remoteFiles),p=new Map(d.syncFileMap);p.set("pubspec.yaml",{content:c,type:U.DEPENDENCIES,path:"pubspec.yaml"}),be.set("package");const f=await Sa(p),g={project_id:o,zipped_custom_code:f,uid:`web_${Date.now()}`,branch_name:l.branchName,serialized_yaml:c,file_map:h.fileMapContents,functions_map:h.functionsMapContents};K.setProgress(1,r.size),Wn(l),be.set("push");const m=await l.pushCode(g),_=await _a(m);if(_.success){const I={...s,artifactType:"Bundle",artifactName:t.title,fileName:`${t.fileEntries.length} artifacts`,codeSize:t.fileEntries.reduce((F,P)=>F+P.content.length,0),projectId:o};return K.setSuccess({...I,fileCount:r.size,warnings:_.errorMap?Array.from(_.errorMap.entries()):[]}),{success:!0,message:`Successfully committed ${t.fileEntries.length} artifacts to FlutterFlow`,metadata:I,addedDependencies:u.added,unverified:d.unverified,warnings:_.errorMap?Array.from(_.errorMap.entries()):[],elapsedTime:K.getElapsedTime()}}const b=_.errorMessage||ya(_.responseCode),E=new Error(b);throw E.errorMap=_.errorMap,E}catch(r){return console.error("Bundle commit execution failed:",r),K.setError(r),{success:!1,error:r.message,errorMap:r.errorMap||new Map,state:K.currentState,elapsedTime:K.getElapsedTime()}}}async function _v(t,e=[]){const s=ea("architect");try{return await Cn("architect",Nd,Lf(t),s,e)}catch(r){throw r.isModelArmor?r:new Error(`Prompt Architect failed: ${r.message}`)}}async function qn(t,e,s=[]){const r=Of(t),n=ea("generator",y.bundleSpec);try{return await Cn("generator",e,r,n,s)}catch(i){if(i.isModelArmor)throw i;if(e!==Pi){console.warn(`Code Generator failed with ${e}, retrying with fallback model:`,i.message);try{return await Cn("generator",Pi,r,n,s)}catch(o){throw o.isModelArmor?o:new Error(`Code Generator failed: primary (${e}): ${i.message} | fallback (${Pi}): ${o.message}`)}}throw new Error(`Code Generator failed: ${i.message}`)}}async function Vn(t,e=null){const s={...ea("review",y.artifactBundle||y.bundleSpec),architect_output:e};try{return await Cn("review",Md,Df(t),s)}catch(r){throw r.isModelArmor?r:new Error(`Code Review failed: ${r.message}`)}}function xa(t,e){return t.isModelArmor?`${t.userTitle}: ${t.userMessage}`:`${e}: ${t.message}`}function Po(t,e){const s=document.getElementById(`step${t}-item`),r=document.getElementById(`step${t}-status`);!s||!r||(s.classList.remove("active","completed","error"),r.classList.remove("running","completed","error"),e==="active"?(s.classList.add("active"),r.classList.add("running"),r.innerHTML=` `):e==="completed"?(s.classList.add("completed"),r.classList.add("completed"),r.innerHTML=` @@ -125,19 +125,19 @@ ${i.errors.join(` `):r.innerHTML=` - `)}function ve(t,e){const s=document.getElementById(`step${t}-loading`),r=document.getElementById(`step${t}-result`);e?(s.classList.remove("hidden"),r.classList.add("hidden"),Io(t,"active")):(s.classList.add("hidden"),r.classList.remove("hidden"),Io(t,"completed"))}function yv(t){const e=document.getElementById(`${t}-content`),s=document.getElementById(`${t}-chevron`);e.classList.contains("open")?(e.classList.remove("open"),s&&(s.style.transform="rotate(0deg)")):(e.classList.add("open"),s&&(s.style.transform="rotate(180deg)"))}function wv(t){ze(parseInt(t.replace("step","")))}function ze(t){for(let o=1;o<=3;o++){const a=document.getElementById(`step${o}-item`);a&&a.classList.remove("active")}const e=document.getElementById(`step${t}-item`);e&&e.classList.add("active"),Zt();const s=document.getElementById("ready-state");s&&s.classList.add("hidden");for(let o=1;o<=3;o++){const a=document.getElementById(`step${o}-content`);a&&a.classList.add("hidden")}const r=document.getElementById(`step${t}-content`);r&&r.classList.remove("hidden");const i=document.getElementById("stage-title"),n={1:"Prompt Architect",2:"Code Generator",3:"Code Review"};i&&(i.textContent=n[t]||"Active Workflow Stage")}function bv(t){const e=document.getElementById(t);if(!e)return;const s=e.dataset.raw||e.textContent;navigator.clipboard.writeText(s).then(()=>{zt("Code Copied",{elementId:t});const i=e.closest(".code-container")?.querySelector(".copy-btn");i&&(i.classList.add("copied"),i.innerHTML=' Copied!',setTimeout(()=>{i.classList.remove("copied"),i.innerHTML=' Copy'},2e3))}).catch(r=>{console.warn("Failed to copy to clipboard:",r)})}function Co(t){const e=Po(t);console.log(`Step 1 (Prompt Architect): ${qt(Td)}`),console.log(e!==t?`Step 2 (Code Generator): ${qt(t)} → ${qt(e)} (Free Tier fallback)`:`Step 2 (Code Generator): ${qt(t)}`),console.log(`Step 3 (Code Review): ${qt(Nd)}`)}async function Ev(){if(console.log("runRefinement called"),y.isRunning)return;const t=document.getElementById("code-generator-model").value;y.isRunning=!0,xa("standardRegenerate",y.step2Result,y.step1Result);const e=document.querySelectorAll(".btn-refine-action");e.forEach(s=>{s.disabled=!0,s.innerHTML=` + `)}function ve(t,e){const s=document.getElementById(`step${t}-loading`),r=document.getElementById(`step${t}-result`);e?(s.classList.remove("hidden"),r.classList.add("hidden"),Po(t,"active")):(s.classList.add("hidden"),r.classList.remove("hidden"),Po(t,"completed"))}function yv(t){const e=document.getElementById(`${t}-content`),s=document.getElementById(`${t}-chevron`);e.classList.contains("open")?(e.classList.remove("open"),s&&(s.style.transform="rotate(0deg)")):(e.classList.add("open"),s&&(s.style.transform="rotate(180deg)"))}function wv(t){ze(parseInt(t.replace("step","")))}function ze(t){for(let o=1;o<=3;o++){const a=document.getElementById(`step${o}-item`);a&&a.classList.remove("active")}const e=document.getElementById(`step${t}-item`);e&&e.classList.add("active"),Zt();const s=document.getElementById("ready-state");s&&s.classList.add("hidden");for(let o=1;o<=3;o++){const a=document.getElementById(`step${o}-content`);a&&a.classList.add("hidden")}const r=document.getElementById(`step${t}-content`);r&&r.classList.remove("hidden");const n=document.getElementById("stage-title"),i={1:"Prompt Architect",2:"Code Generator",3:"Code Review"};n&&(n.textContent=i[t]||"Active Workflow Stage")}function bv(t){const e=document.getElementById(t);if(!e)return;const s=e.dataset.raw||e.textContent;navigator.clipboard.writeText(s).then(()=>{zt("Code Copied",{elementId:t});const n=e.closest(".code-container")?.querySelector(".copy-btn");n&&(n.classList.add("copied"),n.innerHTML=' Copied!',setTimeout(()=>{n.classList.remove("copied"),n.innerHTML=' Copy'},2e3))}).catch(r=>{console.warn("Failed to copy to clipboard:",r)})}function Ao(t){const e=Ro(t);console.log(`Step 1 (Prompt Architect): ${qt(Nd)}`),console.log(e!==t?`Step 2 (Code Generator): ${qt(t)} → ${qt(e)} (Free Tier fallback)`:`Step 2 (Code Generator): ${qt(t)}`),console.log(`Step 3 (Code Review): ${qt(Md)}`)}async function Ev(){if(console.log("runRefinement called"),y.isRunning)return;const t=document.getElementById("code-generator-model").value;y.isRunning=!0,ka("standardRegenerate",y.step2Result,y.step1Result);const e=document.querySelectorAll(".btn-refine-action");e.forEach(s=>{s.disabled=!0,s.innerHTML=` - Refining...`});try{const s=ga(),r=Df({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,artifactId:s.id,userFeedback:"Fix the issues listed in the audit report."});Vi(),it(2),ze(2),ve(2,!0),y.step2Result=await Hi(r,t),Di();const i=document.getElementById("step2-output"),n=bs(y.step2Result);i.textContent=n,i.dataset.raw=n,ve(2,!1),ze(3),it(3),ve(3,!0),y.step3Result=await Wi(y.step2Result,y.step1Result),Bi();const o=document.getElementById("step3-output");o.textContent=y.step3Result,ve(3,!1),$t();const a=Mi(y.step3Result);Gi(n,a)}catch(s){console.error("Refinement failed:",s),$t(),ue(Sa(s,"Refinement failed"),"error")}finally{y.isRunning=!1,e.forEach(s=>{s.disabled=!1,s.textContent="Refine & Regenerate"}),Xt()}}async function xa(t,e,s){const r=`${Je}/connectFeedback`,i={type:t,code:e,input:s};try{const n=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)});if(!n.ok){const a=await n.text();return console.error(`callEndpoint failed: ${n.status} ${n.statusText}`,a),{success:!1,status:n.status,error:a}}const o=await n.json();return console.log("Telemetry success:",o),o}catch(n){return console.error("callEndpoint failed:",n),{success:!1,error:n.message}}}function Sv(){const t=document.getElementById("ff-error-paste-input");t&&(t.value="")}async function xv(){const t=document.getElementById("ff-error-paste-input"),e=t?.value?.trim();if(!e){t?.focus(),t?.classList.add("ring-2","ring-red-400","border-red-300"),setTimeout(()=>t?.classList.remove("ring-2","ring-red-400","border-red-300"),2e3);return}if(!y.step2Result){ue("No generated code found. Please run the full pipeline first.","warning");return}if(y.isRunning)return;const s=document.getElementById("code-generator-model").value;y.isRunning=!0,xa("flutterflowError",y.step2Result,e);const r=document.getElementById("btn-fix-from-errors");r&&(r.disabled=!0,r.innerHTML=` + Refining...`});try{const s=ma(),r=Bf({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,artifactId:s.id,userFeedback:"Fix the issues listed in the audit report."});Jn(),nt(2),ze(2),ve(2,!0),y.step2Result=await qn(r,t),Un();const n=document.getElementById("step2-output"),i=bs(y.step2Result);n.textContent=i,n.dataset.raw=i,ve(2,!1),ze(3),nt(3),ve(3,!0),y.step3Result=await Vn(y.step2Result,y.step1Result),Hn();const o=document.getElementById("step3-output");o.textContent=y.step3Result,ve(3,!1),$t();const a=Dn(y.step3Result);Yn(i,a)}catch(s){console.error("Refinement failed:",s),$t(),ue(xa(s,"Refinement failed"),"error")}finally{y.isRunning=!1,e.forEach(s=>{s.disabled=!1,s.textContent="Refine & Regenerate"}),Xt()}}async function ka(t,e,s){const r=`${Je}/connectFeedback`,n={type:t,code:e,input:s};try{const i=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!i.ok){const a=await i.text();return console.error(`callEndpoint failed: ${i.status} ${i.statusText}`,a),{success:!1,status:i.status,error:a}}const o=await i.json();return console.log("Telemetry success:",o),o}catch(i){return console.error("callEndpoint failed:",i),{success:!1,error:i.message}}}function Sv(){const t=document.getElementById("ff-error-paste-input");t&&(t.value="")}async function xv(){const t=document.getElementById("ff-error-paste-input"),e=t?.value?.trim();if(!e){t?.focus(),t?.classList.add("ring-2","ring-red-400","border-red-300"),setTimeout(()=>t?.classList.remove("ring-2","ring-red-400","border-red-300"),2e3);return}if(!y.step2Result){ue("No generated code found. Please run the full pipeline first.","warning");return}if(y.isRunning)return;const s=document.getElementById("code-generator-model").value;y.isRunning=!0,ka("flutterflowError",y.step2Result,e);const r=document.getElementById("btn-fix-from-errors");r&&(r.disabled=!0,r.innerHTML=` - Fixing…`);try{const i=gd({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,userFeedback:e});ah(),Vi(),it(2),ze(2),ve(2,!0),y.step2Result=await Hi(i,s),Di();const n=document.getElementById("step2-output"),o=bs(y.step2Result);n.textContent=o,n.dataset.raw=o,ve(2,!1),ze(3),it(3),ve(3,!0),y.step3Result=await Wi(y.step2Result,y.step1Result),Bi();const a=document.getElementById("step3-output");a.textContent=y.step3Result,ve(3,!1),$t();const l=Mi(y.step3Result);Gi(o,l),t&&(t.value="")}catch(i){console.error("Fix from errors failed:",i),$t(),ue(Sa(i,"Failed to fix errors"),"error")}finally{y.isRunning=!1,r&&(r.disabled=!1,r.textContent="Fix Errors & Regenerate"),Xt()}}async function Fo(){if(console.log("runThinkingPipeline called"),y.isRunning)return;localStorage.setItem("hasSeenWalkthrough","true");const t=document.getElementById("pipeline-input").value,e=document.getElementById("code-generator-model").value;if(!t.trim()){ue("Please describe your FlutterFlow widget first.","warning");return}if(!await zv())return;await Dv();const s=Po(e);zt("Pipeline Started",{selectedModel:e,effectiveModel:s,inputLength:t.length});const r=document.getElementById("btn-run-pipeline");y.isRunning=!0,ov(),r.disabled=!0,r.innerHTML=` + Fixing…`);try{const n=md({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,userFeedback:e});lh(),Jn(),nt(2),ze(2),ve(2,!0),y.step2Result=await qn(n,s),Un();const i=document.getElementById("step2-output"),o=bs(y.step2Result);i.textContent=o,i.dataset.raw=o,ve(2,!1),ze(3),nt(3),ve(3,!0),y.step3Result=await Vn(y.step2Result,y.step1Result),Hn();const a=document.getElementById("step3-output");a.textContent=y.step3Result,ve(3,!1),$t();const l=Dn(y.step3Result);Yn(o,l),t&&(t.value="")}catch(n){console.error("Fix from errors failed:",n),$t(),ue(xa(n,"Failed to fix errors"),"error")}finally{y.isRunning=!1,r&&(r.disabled=!1,r.textContent="Fix Errors & Regenerate"),Xt()}}async function $o(){if(console.log("runThinkingPipeline called"),y.isRunning)return;localStorage.setItem("hasSeenWalkthrough","true");const t=document.getElementById("pipeline-input").value,e=document.getElementById("code-generator-model").value;if(!t.trim()){ue("Please describe your FlutterFlow widget first.","warning");return}if(!await zv())return;await Dv();const s=Ro(e);zt("Pipeline Started",{selectedModel:e,effectiveModel:s,inputLength:t.length});const r=document.getElementById("btn-run-pipeline");y.isRunning=!0,ov(),r.disabled=!0,r.innerHTML=` - Running...`,Co(s);try{Zt();const i=document.getElementById("ready-state");i&&i.classList.add("hidden");const n=document.getElementById("paywall-exhausted");n&&n.classList.add("hidden"),Vi(),ze(1),it(1),ve(1,!0);const o=Pt.filter(p=>p.url).map(p=>({url:p.url}));y.step1Result=await _v(t,o),av(),zt("Prompt Architect Completed");const a=document.getElementById("step1-output"),l=bs(y.step1Result);a.textContent=l,a.dataset.raw=l,ve(1,!1),ze(2),it(2),ve(2,!0),y.step2Result=await Hi(y.step1Result,s,o),Di(),zt("Code Generator Completed");const u=document.getElementById("step2-output"),c=bs(y.step2Result);u.textContent=c,u.dataset.raw=c,ve(2,!1),ze(3),it(3),ve(3,!0),y.step3Result=await Wi(y.step2Result,y.step1Result),Bi(),zt("Code Review Completed");const d=document.getElementById("step3-output");d.textContent=y.step3Result,ve(3,!1),$t();const h=Mi(y.step3Result);Gi(c,h)}catch(i){if(console.error("Pipeline failed:",i),$t(),i.isUsageLimit){const{count:c}=zi();Aa(c,Pa(),{openModal:!0});return}zt("Pipeline Failed",{error:i.message,effectiveModel:Po(document.getElementById("code-generator-model").value)});const o=vm(i,{architect:1,generator:2,review:3});ze(o);const a=document.getElementById(`step${o}-result`),l=document.getElementById(`step${o}-loading`),u=document.getElementById(`step${o}-output`);if(l&&l.classList.add("hidden"),a&&a.classList.remove("hidden"),u)if(i.isModelArmor)u.innerHTML=``;else{let c=i.message;i.message.includes("image input")?c=`This model doesn't support image input. Please use ${qt(lr)} for image-based requests or remove image references from your prompt.`:(i.message.includes("Load failed")||i.message.includes("CORS"))&&(c="API connection failed. This might be due to CORS restrictions or network issues. Please check your API key and try again."),u.innerHTML=`
+ Running...`,Ao(s);try{Zt();const n=document.getElementById("ready-state");n&&n.classList.add("hidden");const i=document.getElementById("paywall-exhausted");i&&i.classList.add("hidden"),Jn(),ze(1),nt(1),ve(1,!0);const o=Pt.filter(p=>p.url).map(p=>({url:p.url}));y.step1Result=await _v(t,o),av(),zt("Prompt Architect Completed");const a=document.getElementById("step1-output"),l=bs(y.step1Result);a.textContent=l,a.dataset.raw=l,ve(1,!1),ze(2),nt(2),ve(2,!0),y.step2Result=await qn(y.step1Result,s,o),Un(),zt("Code Generator Completed");const u=document.getElementById("step2-output"),c=bs(y.step2Result);u.textContent=c,u.dataset.raw=c,ve(2,!1),ze(3),nt(3),ve(3,!0),y.step3Result=await Vn(y.step2Result,y.step1Result),Hn(),zt("Code Review Completed");const d=document.getElementById("step3-output");d.textContent=y.step3Result,ve(3,!1),$t();const h=Dn(y.step3Result);Yn(c,h)}catch(n){if(console.error("Pipeline failed:",n),$t(),n.isUsageLimit){const{count:c}=Gn();$a(c,Aa(),{openModal:!0});return}zt("Pipeline Failed",{error:n.message,effectiveModel:Ro(document.getElementById("code-generator-model").value)});const o=vm(n,{architect:1,generator:2,review:3});ze(o);const a=document.getElementById(`step${o}-result`),l=document.getElementById(`step${o}-loading`),u=document.getElementById(`step${o}-output`);if(l&&l.classList.add("hidden"),a&&a.classList.remove("hidden"),u)if(n.isModelArmor)u.innerHTML=``;else{let c=n.message;n.message.includes("image input")?c=`This model doesn't support image input. Please use ${qt(cr)} for image-based requests or remove image references from your prompt.`:(n.message.includes("Load failed")||n.message.includes("CORS"))&&(c="API connection failed. This might be due to CORS restrictions or network issues. Please check your API key and try again."),u.innerHTML=`

Connection Error

${j(c)}

@@ -145,10 +145,10 @@ ${i.errors.join(`

Try using a different model

Ensure network allows API calls

-
`}Io(o,"error")}finally{y.isRunning=!1,r.disabled=!1,r.innerHTML=` +
`}Po(o,"error")}finally{y.isRunning=!1,r.disabled=!1,r.innerHTML=` - Run Pipeline`,Xt()}}function kv(){const t=document.getElementById("code-generator-model").value,e=[lr,"anthropic/claude-opus-5","openai/gpt-5.6-sol"].filter(r=>r!==t),s=prompt(`Retry with different model? + Run Pipeline`,Xt()}}function kv(){const t=document.getElementById("code-generator-model").value,e=[cr,"anthropic/claude-opus-5","openai/gpt-5.6-sol"].filter(r=>r!==t),s=prompt(`Retry with different model? Current: ${t} @@ -156,15 +156,15 @@ Options: 1. ${e[0]} 2. ${e[1]} -Enter 1 or 2:`);s==="1"?(document.getElementById("code-generator-model").value=e[0],Fo()):s==="2"&&(document.getElementById("code-generator-model").value=e[1],Fo())}async function Iv(){const t=ma();if(!t){ue("No code to commit. Please run the pipeline first.","warning");return}const e=await Ee("flutterflow"),s=await Ee("flutterflow_project_id");if(!e||!s){ue("FlutterFlow credentials not configured. Add your API Key and Project ID in settings.","warning"),ha();return}if(y.artifactBundle?.artifacts?.length>1){await Cv();return}const{artifactType:r,artifactName:i,fileName:n}=Wd(),o=Kd(t,{artifactType:r,artifactName:i,fileName:n}),a=dv(o);if(!a.canProceed){ue(`Pre-commit checks failed: ${a.issues.join("; ")}`,"error");return}eh(o,a,null,null)}async function Cv(){const t=await Ee("flutterflow"),e=await Ee("flutterflow_project_id");if(!t||!e){ue("FlutterFlow credentials not configured. Add your API Key and Project ID in settings.","warning"),ha();return}const s=bg(y.artifactBundle);if(s.errors.length>0){ue(`Bundle validation failed: ${s.errors.join("; ")}`,"error");return}const r=new Map(s.fileEntries.map(a=>[a.fileName,{content:a.content,type:a.type,path:a.path}])),i=Ui(r),n={canProceed:i.valid&&s.errors.length===0,issues:[...s.errors,...i.errors],warnings:[...s.warnings,...i.warnings]};if(!n.canProceed){ue(`Bundle validation failed: ${n.issues.join("; ")}`,"error");return}const o={content:s.fileEntries.map(a=>`// ${a.fileName} +Enter 1 or 2:`);s==="1"?(document.getElementById("code-generator-model").value=e[0],$o()):s==="2"&&(document.getElementById("code-generator-model").value=e[1],$o())}async function Iv(){const t=va();if(!t){ue("No code to commit. Please run the pipeline first.","warning");return}const e=await Ee("flutterflow"),s=await Ee("flutterflow_project_id");if(!e||!s){ue("FlutterFlow credentials not configured. Add your API Key and Project ID in settings.","warning"),pa();return}if(y.artifactBundle?.artifacts?.length>1){await Cv();return}const{artifactType:r,artifactName:n,fileName:i}=zd(),o=Jd(t,{artifactType:r,artifactName:n,fileName:i}),a=dv(o);if(!a.canProceed){ue(`Pre-commit checks failed: ${a.issues.join("; ")}`,"error");return}th(o,a,null,null)}async function Cv(){const t=await Ee("flutterflow"),e=await Ee("flutterflow_project_id");if(!t||!e){ue("FlutterFlow credentials not configured. Add your API Key and Project ID in settings.","warning"),pa();return}const s=Eg(y.artifactBundle);if(s.errors.length>0){ue(`Bundle validation failed: ${s.errors.join("; ")}`,"error");return}const r=new Map(s.fileEntries.map(a=>[a.fileName,{content:a.content,type:a.type,path:a.path}])),n=zn(r),i={canProceed:n.valid&&s.errors.length===0,issues:[...s.errors,...n.errors],warnings:[...s.warnings,...n.warnings]};if(!i.canProceed){ue(`Bundle validation failed: ${i.issues.join("; ")}`,"error");return}const o={content:s.fileEntries.map(a=>`// ${a.fileName} ${a.content}`).join(` -`),fileName:`${s.fileEntries.length} files`,codeType:"bundle",artifactType:"Bundle",artifactName:s.title};eh(o,n,s.dependencies,s)}function Fv(t){let e=t.errorMap||new Map;!(e instanceof Map)&&typeof e=="object"&&(e=new Map(Object.entries(e)));let s=`
+`),fileName:`${s.fileEntries.length} files`,codeType:"bundle",artifactType:"Bundle",artifactName:s.title};th(o,i,s.dependencies,s)}function Fv(t){let e=t.errorMap||new Map;!(e instanceof Map)&&typeof e=="object"&&(e=new Map(Object.entries(e)));let s=`

FlutterFlow Commit Failed

${j(t.error)}

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

Errors:

-
    `;for(const[i,n]of e.entries()){const o=Ed(n);s+=`
  • - ${j(i)}: ${j(o)} +
      `;for(const[n,i]of e.entries()){const o=Sd(i);s+=`
    • + ${j(n)}: ${j(o)}
    • `}s+="
"}s+="
",s+=`
`;const r=document.getElementById("step3-output");r&&(r.innerHTML=s,document.getElementById("btn-regenerate-from-error")?.addEventListener("click",()=>{Pv(t.error,e)}))}async function Pv(t,e){if(y.isRunning)return;const s=document.getElementById("code-generator-model").value;y.isRunning=!0;const r=document.getElementById("btn-regenerate-from-error");r&&(r.disabled=!0,r.innerHTML=` - Fixing...`);try{let i=`The previous code had the following errors when committing to FlutterFlow: + Fixing...`);try{let n=`The previous code had the following errors when committing to FlutterFlow: -`;if(e&&e.size>0)for(const[c,d]of e.entries()){const h=Ed(d);i+=`File: ${c} +`;if(e&&e.size>0)for(const[c,d]of e.entries()){const h=Sd(d);n+=`File: ${c} Error: ${h} -`}else i+=`${t} -`;const n=gd({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,userFeedback:i});Vi(),it(2),ze(2),ve(2,!0),y.step2Result=await Hi(n,s),Di();const o=document.getElementById("step2-output"),a=bs(y.step2Result);o.textContent=a,o.dataset.raw=a,ve(2,!1),ze(3),it(3),ve(3,!0),y.step3Result=await Wi(y.step2Result,y.step1Result),Bi();const l=document.getElementById("step3-output");l.textContent=y.step3Result,ve(3,!1),$t();const u=Mi(y.step3Result);Gi(a,u)}catch(i){console.error("Regeneration failed:",i),$t(),ue(Sa(i,"Regeneration failed"),"error")}finally{y.isRunning=!1,r&&(r.disabled=!1,r.textContent="Fix Errors & Regenerate"),Xt()}}async function Av(){const t=document.getElementById("ff-status-dot"),e=document.getElementById("ff-status-text");if(!t||!e)return;const s=await Ee("flutterflow"),r=await Ee("flutterflow_project_id");s&&r?(t.className="w-2 h-2 rounded-full bg-green-500",e.textContent="FlutterFlow credentials configured",e.className="text-green-600"):s||r?(t.className="w-2 h-2 rounded-full bg-yellow-500",e.textContent="FlutterFlow credentials incomplete",e.className="text-yellow-600"):(t.className="w-2 h-2 rounded-full bg-red-500",e.textContent="FlutterFlow credentials not configured",e.className="text-red-600")}async function $v(t){try{const e=await fetch(`${Je}/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 Rv(t){try{const s=await(await fetch(`${Je}/auth/verify-magic-link`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:t})})).json();if(s.error||!s.email||!s.sessionToken)throw new Error(s.error||"Invalid or expired link");return s}catch(e){throw console.error("verifyMagicLink failed:",{message:e.message,stack:e.stack}),e}}async function Tv(t){try{const e=await fetch(`${Je}/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:`${Je}/auth/refresh-session`,status:e.status}),null;const s=await e.json();return s.error||!s.email||!s.sessionToken?(console.warn("refreshSession: validation failed",{error:s.error,hasEmail:!!s.email,hasToken:!!s.sessionToken}),null):s}catch(e){return console.error("refreshSession: fetch failed",{url:`${Je}/auth/refresh-session`,message:e.message,stack:e.stack}),null}}function bc(t,e){const s=Jd(),r=(G.email||s.email)!==t;G.email=t,G.sessionToken=e,G.isVerified=!0,fe=Es({isLoading:!0}),localStorage.setItem(vi,JSON.stringify({email:t,sessionToken:e})),r&&$a()}function ka(){G.email=null,G.sessionToken=null,G.isVerified=!1,fe=Es({isResolved:!0}),localStorage.removeItem(vi),localStorage.removeItem(yi)}function Jd(){try{const t=localStorage.getItem(vi);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(vi),{email:null,sessionToken:null}}}async function Nv(){const e=new URLSearchParams(window.location.search).get("token");if(e){window.history.replaceState({},"",window.location.pathname);try{const{email:s,sessionToken:r}=await Rv(e);bc(s,r)}catch(s){ue(s.message||"Sign-in link invalid or expired.","error")}}else{const{email:s,sessionToken:r}=Jd();if(s&&r){const i=await Tv(r);i?bc(i.email,i.sessionToken):ka()}}Ca()}function Ia(){const t=document.getElementById("signin-modal");t&&t.classList.add("open")}function Mv(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("signin-modal");e&&e.classList.remove("open")}async function Lv(){const t=document.getElementById("signin-email-input"),e=document.getElementById("signin-submit-btn"),s=document.getElementById("signin-message"),r=t?.value?.trim();if(!r||!/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/.test(r)||r.length>254){s&&(s.textContent="Please enter a valid email address.");return}e&&(e.disabled=!0,e.textContent="Sending…"),s&&(s.textContent="");try{await $v(r),t&&(t.value=""),s&&(s.textContent=`Check your email — we sent a link to ${r}`),e&&(e.textContent="Sent!")}catch(n){console.error("handleMagicLinkRequest: sendMagicLink failed",{email:r,err:n}),s&&(s.textContent="Something went wrong. Please try again."),e&&(e.disabled=!1,e.textContent="Send Link")}}function Ov(){ka(),$a(),Ca(),qi()}function Ca(){const t=G.isVerified&&!!G.email,e=document.getElementById("auth-signedout"),s=document.getElementById("auth-signedin"),r=document.getElementById("auth-guest-usage");e&&e.classList.toggle("hidden",t),s&&s.classList.toggle("hidden",!t),r&&r.classList.toggle("hidden",t);const i=document.getElementById("auth-user-email");i&&(i.textContent=G.email||""),zr(),qi()}async function Yd(){try{if(typeof FingerprintJS>"u"){console.warn("resolveIdentity: FingerprintJS not loaded, skipping");return}const e=await(await FingerprintJS.load()).get(),s=e.visitorId,r=await fetch(Cm,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({fingerprint:e.visitorId,cookie_id:s})});if(!r.ok)throw new Error(`Identity check HTTP ${r.status}`);const i=await r.json();if(Ge.userId=i.user_id,Ge.token=i.identity_token||null,Ge.status=i.status,Ge.resolved=!0,sessionStorage.setItem(km,i.user_id),Ge.token&&sessionStorage.setItem(Im,Ge.token),i.usage_count!==void 0){const n=At(),a=(i.usage_month||n)===n?i.usage_count:0;localStorage.setItem(Kt,JSON.stringify({count:a,month:n})),Xs()}console.log(`Identity resolved: ${i.status} (${i.user_id.slice(0,8)}...) usage: ${i.usage_count??"n/a"}`)}catch(t){console.error("resolveIdentity failed:",t)}}let Fn=null;function Dv(t=5e3){return Ge.resolved?Promise.resolve():(Fn||(Fn=Yd().catch(e=>{console.warn("ensureIdentityReady: identity resolution failed",e)})),Promise.race([Fn,new Promise(e=>setTimeout(e,t))]))}function Zd(){const t=At();try{const e=localStorage.getItem(Kt);return e?JSON.parse(e):{count:0,month:t}}catch(e){return console.warn("getUsageData: failed to parse usage storage",{key:Kt,month:t,err:e}),localStorage.removeItem(Kt),{count:0,month:t}}}function At(){const t=new Date;return`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,"0")}`}function zi(){const t=Zd();return t.month!==At()?{count:0,month:At()}:t}function Bv(){const e={count:zi().count+1,month:At()};return localStorage.setItem(Kt,JSON.stringify(e)),e}function Fa(){return!!fe.isLoading}function Yt(){return!!fe.isResolved}function jv(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(_i,e)?e:null}function Uv(t){return t&&Object.entries(Ad).find(([,e])=>e===t)?.[0]||null}function $r(...t){return t.find(e=>e!=null&&e!=="")}function Hv(...t){return t.find(e=>e&&typeof e=="object")||{}}function Wv(t){const e=t.data&&typeof t.data=="object"?t.data:t,s=Hv(e.subscription,e.stripeSubscription,e.currentSubscription,e.customer?.subscriptions?.data?.[0],e.subscriptions?.data?.[0],e.subscriptions?.[0]),r=e.metadata||s.metadata||e.customer?.metadata||{},i=$r(e.priceId,e.price_id,e.stripePriceId,e.stripe_price_id,s.priceId,s.price_id,s.plan?.id,s.price?.id,s.items?.data?.[0]?.price?.id,s.items?.[0]?.price?.id,s.lines?.data?.[0]?.price?.id),n=$r(e.status,e.subscriptionStatus,e.subscription_status,s.status,"none"),o=jv($r(e.tier,e.plan,e.planId,e.plan_id,e.subscriptionTier,e.subscription_tier,e.product,e.productName,s.tier,s.plan,r.tier,r.plan)),a=Fm.has(String(n).toLowerCase()),l=e.active===!0||e.isSubscribed===!0||e.subscribed===!0||e.hasSubscription===!0,u=o||Uv(i)||(a||l?"professional":"free");return Es({tier:u,status:n,periodEnd:$r(e.periodEnd,e.currentPeriodEnd,e.current_period_end,s.current_period_end,s.periodEnd,null),isResolved:!0})}function Pa(){return _i[fe.tier]??_i.free}async function zv(){if(G.isVerified&&(!Yt()||Fa())&&(await Xd({force:!0}),qi()),G.isVerified&&!Yt())return ue("Could not verify your subscription. Please refresh or try Manage billing.","error"),!1;const{count:t}=zi(),e=Pa();if(t>=e)return Aa(t,e,{openModal:!0}),!1;const s=Math.floor(e*.8);if(t>=s){const r=e-t;ue(`${r} run${r===1?"":"s"} remaining this month.`,"warning")}return!0}function Pn(){const t=document.getElementById("paywall-exhausted");t&&t.classList.add("hidden")}function Aa(t,e,s={}){const r=document.getElementById("walkthrough-modal");r&&r.classList.remove("open");const i=document.getElementById("ready-state");i&&i.classList.add("hidden");const n=document.getElementById("preview-frame-container");n&&(n.style.display="none");const o=document.getElementById("main-stage-container");o&&o.classList.add("visible");const a=document.getElementById("results-view");a&&a.classList.remove("visible"),document.body.classList.remove("results-fullscreen","results-with-sidebar");const l=document.getElementById("pipeline-progress");l&&l.classList.remove("visible");const u=document.getElementById("paywall-exhausted");if(!u){ue(`You've used all ${e} runs for this month. Upgrade to continue.`,"error"),Ii();return}const c=document.getElementById("paywall-exhausted-text");if(c){const h=fe.tier;h==="free"?c.textContent=`You've used all ${e} free generations this month. Upgrade to Pro for 50 generations/month and access to all AI models.`:c.textContent=`You've used all ${e} generations this month on your ${h} plan. Your limit resets next month.`}const d=document.getElementById("paywall-signin-btn");d&&d.classList.toggle("hidden",G.isVerified),u.classList.remove("hidden"),s.openModal&&Ii()}function Po(t){return fe.tier==="free"&&jr.includes(t)?lr:t}function qv(){const t=document.getElementById("code-options-content"),e=document.getElementById("code-generator-model");if(!t||!e)return;const s=fe.tier,i=!(G.isVerified&&!Yt())&&s==="free";Array.from(e.options).forEach(o=>{const a=qt(o.value),l=jr.includes(o.value);o.textContent=l&&i?`${a} (PRO)`:a,o.disabled=!1}),i&&jr.includes(e.value)&&(e.value=lr),e.disabled=!1,dc.has(e)||(e.addEventListener("change",()=>{Yt()&&fe.tier==="free"&&jr.includes(e.value)&&(e.value=lr,Ii()),Co(e.value),Rd()}),dc.add(e));let n=document.getElementById("model-selector-free-notice");i?(n||(n=document.createElement("p"),n.id="model-selector-free-notice",n.className="text-xs text-gray-400 mt-1",t.appendChild(n)),n.innerHTML='Free plan — Gemini only. '):n&&n.remove(),Co(e.value)}function Xs(){const t=document.getElementById("usage-counter");if(!t)return;if(G.isVerified&&Fa()){t.textContent="Checking plan…",t.className="text-xs text-gray-500",zr(),Pn();return}if(G.isVerified&&!Yt()){t.textContent="Plan check failed",t.className="text-xs text-red-600 font-medium",zr(),Pn();return}const{count:e}=zi(),s=Pa();t.textContent=`${e} / ${s} runs this month`;const r=s>0?e/s:0;t.className=r>=1?"text-xs text-red-600 font-medium":r>=.8?"text-xs text-yellow-600 font-medium":"text-xs text-gray-500",zr(),e>=s&&!y.isRunning?Aa(e,s):Pn()}function zr(){const t=document.getElementById("guest-usage-text");if(!t)return;const e=Zd(),s=e.month===At()?e.count??0:0,r=_i.free;t.textContent=`${s} / ${r} generations used`}async function Xd(t={}){const e=t.force===!0;if(!G.isVerified||!G.sessionToken){fe=Es({isResolved:!0});return}fe={...fe,isLoading:!0,error:null};const s=localStorage.getItem(yi);if(!e&&s)try{const{data:r,email:i,ts:n,version:o}=JSON.parse(s);if(o===hc&&i===G.email&&Date.now()-n<300*1e3){fe={...r,isLoading:!1,isResolved:r.isResolved!==!1};return}}catch(r){console.warn("Failed to parse subscription cache:",r,"| raw value:",s)}try{const i=await(await fetch(`${Je}/stripe/get-subscription`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:G.sessionToken,user_id:Ge.userId})})).json();if(i.error){if(["unauthorized","invalid session","expired session"].some(o=>String(i.error).toLowerCase().includes(o))){ka(),Ca();return}fe=Es({isResolved:!1,error:i.error});return}fe=Wv(i),localStorage.setItem(yi,JSON.stringify({version:hc,data:fe,email:G.email,ts:Date.now()}))}catch(r){console.error("fetchSubscription failed:",r),fe={...fe,isLoading:!1,isResolved:!1,error:r.message}}}function $a(){localStorage.removeItem(yi)}async function Vv(t){if(!G.isVerified||!G.sessionToken){Qd(),Ia();return}if(!Ad[t]){ue("Invalid plan selected.","error");return}const e=document.getElementById(`checkout-btn-${t}`);e&&(e.disabled=!0,e.textContent="Redirecting…");try{const r=await(await fetch(`${Je}/stripe/create-checkout-session-intl`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tierId:t,sessionToken:G.sessionToken,currency:Md()})})).json();if(r.error||!r.url)throw new Error(r.error||"Failed to create checkout session");const{url:i}=r;window.location.href=i}catch(s){console.error("startCheckout failed:",s),e&&(e.disabled=!1,e.textContent="Subscribe"),ue("Could not start checkout. Please try again.","error")}}async function Gv(){if(!G.isVerified||!G.sessionToken){Ia();return}const t=document.getElementById("manage-billing-btn");t&&(t.disabled=!0,t.textContent="Loading…");try{const s=await(await fetch(`${Je}/stripe/create-portal-session`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:G.sessionToken})})).json();if(s.error||!s.url)throw new Error(s.error||"Failed to open billing portal");const{url:r}=s;window.location.href=r}catch(e){console.error("openCustomerPortal failed:",e),t&&(t.disabled=!1,t.textContent="Manage billing"),ue("Could not open billing portal. Please try again.","error")}}async function ki(t,e,s,r={},i=[]){const o=new AbortController,a=setTimeout(()=>o.abort(),12e4);try{const l=await fetch(xm,{method:"POST",headers:{"Content-Type":"application/json",...Ge.token?{Authorization:`Bearer ${Ge.token}`}:{}},signal:o.signal,body:JSON.stringify({user_id:Ge.userId,step:t,model:e,prompt:s,images:i,context:r})}),u=await l.text();let c={};try{c=u?JSON.parse(u):{}}catch{c={}}if(l.status===429){c.serverCount!==void 0&&(localStorage.setItem(Kt,JSON.stringify({count:c.serverCount,month:At()})),Xs());const p=new Error(c.message||"Monthly usage limit reached. Upgrade to continue.");throw p.isUsageLimit=!0,p}const d=qf(c,t);if(d)throw d;if(console.log(`[BuildShip] ${t} response keys:`,Object.keys(c),"content type:",typeof c.content),!l.ok)throw new Error(`${c.message||c.error||"BuildShip pipeline error"} (HTTP ${l.status})`);if(t==="generator")if(c.usage_status==="success"&&Number.isFinite(c.usage_count)){const p=At();(c.usage_month||p)===p&&(localStorage.setItem(Kt,JSON.stringify({count:c.usage_count,month:p})),Xs())}else Bv(),Xs();let h=c.output||c.content;if(!h){const p=u?` (body: ${u.slice(0,120)})`:"";throw new Error(`BuildShip returned no output for step "${t}"${p}`)}return Array.isArray(h)&&(h=h.map(p=>typeof p=="string"?p:p.text||"").join("")),typeof h!="string"&&(h=JSON.stringify(h)),h}catch(l){throw l.name==="AbortError"?new Error(`BuildShip ${t} timed out after ${12e4/1e3}s`):l instanceof TypeError?new Error(`BuildShip unreachable: ${l.message}`):l}finally{clearTimeout(a)}}function Kv(){const e=new URLSearchParams(window.location.search).get("checkout");e==="success"?(window.history.replaceState({},"",window.location.pathname),$a(),ue("Subscription active! Welcome aboard.","success")):e==="cancel"&&(window.history.replaceState({},"",window.location.pathname),ue("Checkout cancelled.","info"))}function qi(){const t=G.isVerified&&!!G.email,e=fe.tier,s=t&&Fa(),r=!t||Yt(),i=document.getElementById("subscription-tier-badge");if(i){const a={free:"Free",professional:"Professional",power:"Power Developer"},l={free:"bg-gray-100 text-gray-600",professional:"bg-indigo-100 text-indigo-700",power:"bg-purple-100 text-purple-700",unresolved:"bg-red-50 text-red-600"};i.textContent=s?"Checking…":r?a[e]||"Free":"Plan unavailable",i.className=`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${r?l[e]||l.free:l.unresolved}`}const n=document.getElementById("upgrade-prompt");n&&n.classList.toggle("hidden",!t||s||!r||e!=="free");const o=document.getElementById("manage-billing-btn");o&&o.classList.toggle("hidden",!t||s||r&&e==="free"),Jv(r?e:null),qv(),Rd(),Xs()}function Jv(t){const e=["bg-gray-100","text-gray-500","cursor-default"];Object.entries({professional:{btnId:"checkout-btn-professional",defaultText:"Subscribe"},power:{btnId:"checkout-btn-power",defaultText:"Subscribe"}}).forEach(([i,{btnId:n,defaultText:o}])=>{const a=document.getElementById(n);a&&(i===t?(a.disabled=!0,a.textContent="Current plan",a.classList.add(...e)):(a.disabled=!1,a.textContent=o,a.classList.remove(...e)))});const r=document.getElementById("free-tier-current");r&&r.classList.toggle("hidden",t!=="free")}function Ao(){const t=Md(),e=document.getElementById("pro-price"),s=document.getElementById("power-price"),r=document.getElementById("pro-price-note"),i=document.getElementById("power-price-note");e&&(e.textContent=fc(pc.professional,t)),s&&(s.textContent=fc(pc.power,t));const n="billed monthly";r&&(r.textContent=n),i&&(i.textContent=n)}function Ii(){Ao();const t=document.getElementById("pricing-modal");t&&t.classList.add("open"),Om().then(()=>Ao())}function Qd(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("pricing-modal");e&&e.classList.remove("open")}function ue(t,e="info"){const s={success:"bg-green-600 text-white",error:"bg-red-600 text-white",warning:"bg-amber-500 text-white",info:"bg-gray-800 text-white"},r=document.createElement("div");r.className=`fixed bottom-6 left-1/2 -translate-x-1/2 px-5 py-3 rounded-lg text-sm font-medium shadow-lg z-50 transition-opacity duration-300 ${s[e]||s.info}`,r.textContent=t,document.body.appendChild(r),setTimeout(()=>{r.style.opacity="0",setTimeout(()=>r.remove(),300)},3500)}document.addEventListener("DOMContentLoaded",async()=>{hljs.configure({tabReplace:" ",classPrefix:"hljs-"}),Yv(),await Nv(),Kv(),await Xd(),qi(),Ao(),await lv(),rv();const t=document.getElementById("flutterflow-endpoint-select");if(t){const s=fr();t.value=s}Ud(),Yd();const e=document.getElementById("pipeline-input");e&&(e.addEventListener("input",()=>{Et===2&&e.value.trim().length>0&&(pa(),Li())}),e.addEventListener("blur",()=>{const s=document.getElementById("walkthrough-modal");Et===2&&s&&s.classList.add("open")}),e.addEventListener("keydown",s=>{if(s.key==="Tab"){const r=document.getElementById("walkthrough-modal");Et===2&&r&&setTimeout(()=>{r.classList.add("open")},100)}})),window.addEventListener("commitStateChange",s=>{const{state:r}=s.detail;r===V.PREPARING||r===V.VALIDATING||r===V.PUSHING?(be.phaseId||sh(),Sc(r)):(r===V.SUCCESS||r===V.ERROR)&&(Sc(r),setTimeout(Ci,1e3))})});function Yv(){const t=document.getElementById("preview-frame-container");t&&(t.style.display="")}function Zv(){const t=document.getElementById("welcome-video-player");t&&(t.addEventListener("click",Zt),document.addEventListener("keydown",Zt))}function Zt(){const t=document.getElementById("preview-frame-container"),e=document.getElementById("main-stage-container"),s=document.getElementById("ready-state");t&&(t.style.display="none"),e&&e.classList.add("visible"),s&&s.classList.remove("hidden");const r=document.getElementById("welcome-video-player");r&&r.removeEventListener("click",Zt),document.removeEventListener("keydown",Zt),Ud()}let Qs=null;async function Xv(){const t=document.getElementById("confirm-project-select");if(!t)return;const e=++yc,s=()=>e===yc,r=await Ee("flutterflow"),i=await Ee("flutterflow_project_id");if(s()){if(!r){t.innerHTML='',t.disabled=!0;return}t.disabled=!1,t.innerHTML='';try{const o=await new gr(r,"").listProjects();if(!s())return;if(!o||o.length===0){t.innerHTML='';return}t.innerHTML='',o.forEach(a=>{const l=document.createElement("option");l.value=a.id||a.projectId||"",l.textContent=a.name||a.projectName||`Project ${a.id}`,t.appendChild(l)}),i&&(t.value=i)}catch(n){if(!s())return;console.error("Failed to load projects for deploy:",n),t.innerHTML=''}}}function Qv(){return document.getElementById("confirm-project-select")?.value?.trim()||null}function eh(t,e,s,r=null){Qs={codeInfo:t,checks:e,deps:s,bundlePlan:r},document.getElementById("confirm-file-name").textContent=t.fileName,document.getElementById("confirm-artifact-type").textContent=t.artifactType,document.getElementById("confirm-file-size").textContent=`${(t.content.length/1024).toFixed(1)} KB`,document.getElementById("confirm-line-count").textContent=r?`${r.fileEntries.length} files`:t.content.split(` -`).length,Xv();const i=document.getElementById("confirm-deps-list"),n=document.getElementById("confirm-deps-section");s&&Object.keys(s).length>0?(i.innerHTML=Object.entries(s).map(([u,c])=>{const d=c?`at least ${bt(c)}`:"version resolved from your project";return`
  • • ${bt(u)}: ${d}
  • `}).join(""),n.classList.remove("hidden")):n.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=>`
  • • ${bt(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&&l.classList.add("open")}function th(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("commit-confirm-modal");e&&e.classList.remove("open"),Qs=null}function e_(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("commit-success-modal");e&&e.classList.remove("open");const s=["success-message","success-project-id","success-file-name","success-artifact-type","success-time","success-size"];for(const n of s){const o=document.getElementById(n);o&&(o.textContent="")}const r=document.getElementById("success-warnings-section");r&&r.classList.add("hidden");const i=document.getElementById("success-warnings-list");i&&(i.innerHTML="")}function $o(t){const e=(g,m)=>{const _=document.getElementById(g);_&&(_.textContent=m||"")},s=t.metadata?.fileName||"",r=t.metadata?.projectId||"",i=t.metadata?.artifactType||"",n=t.elapsedTime?`${(t.elapsedTime/1e3).toFixed(1)}s`:"",o=t.metadata?.codeSize?`${(t.metadata.codeSize/1024).toFixed(1)} KB`:"";e("success-message",t.message||"Code committed successfully!"),e("success-project-id",r),e("success-file-name",s),e("success-artifact-type",i),e("success-time",n),e("success-size",o);const a=t.addedDependencies||[],l=document.getElementById("success-deps-row");l&&l.classList.toggle("hidden",a.length===0),e("success-deps",a.join(", "));const u=document.getElementById("success-open-ff-link");u&&r&&(u.href=`https://app.flutterflow.io/project/${r}`);const c=document.getElementById("success-warnings-section"),d=document.getElementById("success-warnings-list"),h=t.unverified||[],p=t.warnings||[];(p.length>0||h.length>0)&&c&&d&&(d.innerHTML=[...h.map(g=>`
  • Not verified before deploying: ${j(String(g))}
  • `),...p.map(([g,m])=>`
  • ${j(g)}: ${j(String(m))}
  • `)].join(""),c.classList.remove("hidden"));const f=document.getElementById("commit-success-modal");f&&f.classList.add("open")}function Ro(t){Ci(),Fv(t)}function t_(){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 Ec={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}},s_=[{after:0,text:"Starting a FlutterFlow build runner..."},{after:12,text:"Preparing the FlutterFlow AI workspace..."},{after:35,text:"Uploading your custom classes..."},{after:60,text:"FlutterFlow is applying the changes..."},{after:100,text:"Still working — this can take a couple of minutes..."}],be={sequence:[],phaseId:null,phaseStartedAt:null,timer:null,substatus:null,liveSubstatus:!1,start({withProvisioning:t=!1}={}){this.sequence=["prepare","validate","project"],t&&this.sequence.push("provision"),this.sequence.push("package","push","done");const e=document.getElementById("commit-progress-overlay");e&&e.classList.add("open"),this.set("prepare")},set(t,e=null){if(!(!Ec[t]||t===this.phaseId)){if(!this.sequence.includes(t)){const s=this.sequence.indexOf("package");this.sequence.splice(s===-1?this.sequence.length:s,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=Ec[this.phaseId];if(!t)return;const e=(Date.now()-this.phaseStartedAt)/1e3,s=t.start+(t.end-t.start)*(1-Math.exp(-e/25));if(this.phaseId==="provision"&&!this.liveSubstatus){const o=s_.filter(a=>e>=a.after).pop();o&&(this.substatus=o.text)}const r=this.sequence.indexOf(this.phaseId),n=[`Step ${r===-1?1:r+1} of ${this.sequence.length}`];e>=5&&n.push(r_(e)),rh(this.phaseId==="done"?100:s,t.message,n.join(" · "),this.substatus)},stop(){this.timer&&clearInterval(this.timer),this.timer=null,this.phaseId=null;const t=document.getElementById("commit-progress-overlay");t&&t.classList.remove("open")}};function r_(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 sh(t){be.start(t)}function Ci(){be.stop()}function rh(t,e,s,r=null){const i=document.getElementById("commit-progress-bar"),n=document.getElementById("progress-message"),o=document.getElementById("progress-detail"),a=document.getElementById("progress-substatus");i&&(i.style.width=`${Math.round(t*10)/10}%`),n&&(n.textContent=e),o&&(o.textContent=s),a&&(a.textContent=r||"",a.classList.toggle("hidden",!r))}function Sc(t){const e={[V.PREPARING]:"prepare",[V.VALIDATING]:"validate",[V.PUSHING]:"project",[V.SUCCESS]:"done"};if(t===V.ERROR){be.timer&&clearInterval(be.timer),be.timer=null,rh(100,"Failed","Error occurred");return}const s=e[t];s&&be.set(s)}function i_(t){return t.bundlePlan?t.bundlePlan.fileEntries.some(e=>e.type===U.CODE_FILE):t.codeInfo?.codeType===U.CODE_FILE}async function n_(){if(!Qs){console.error("No pending commit data");return}const t=Qs;if(Qs=null,Zs=Qv(),th(),sh({withProvisioning:i_(t)}),t.bundlePlan){const o=await vv(t.bundlePlan,{pipelineResult:{step1Result:y.step1Result,selectedModel:document.getElementById("code-generator-model")?.value}});Zs=null,Ci(),o.success?$o(o):Ro(o);return}const{codeInfo:e}=t,{artifactType:s,artifactName:r,fileName:i}=Wd(),n=await mv(e.content,{artifactType:s,artifactName:r,fileName:i,pipelineResult:{step1Result:y.step1Result,selectedModel:document.getElementById("code-generator-model")?.value}});Zs=null,Ci(),n.success?$o(n):Ro(n)}window.runThinkingPipeline=Fo;window.toggleStep=wv;window.toggleSection=yv;window.selectWorkflowStep=ze;window.copyCode=bv;window.retryWithDifferentModel=kv;window.openApiKeysModal=ha;window.closeApiKeysModal=Bd;window.closeWalkthroughModal=Zm;window.openWalkthroughModal=Ym;window.advanceWalkthrough=pa;window.commitToFlutterFlow=gv;function o_(){const t=document.getElementById("pipeline-input");t&&t.focus()}function a_(){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=o_;window.openModelSelector=a_;window.handlePromptImageSelect=Mm;window.removePromptImage=Lm;window.saveApiKeys=ev;window.clearAllApiKeys=tv;window.toggleKeyVisibility=nv;window.handleWelcomeVideoEnd=Zv;window.dismissWelcomeVideo=Zt;window.initiateCommitToFlutterFlow=Iv;window.updateFlutterFlowCredentialStatus=Av;window.closeCommitConfirmModal=th;window.closeCommitSuccessModal=e_;window.showCommitSuccessModal=$o;window.showCommitFailureModal=Ro;window.toggleCodePreview=t_;window.confirmCommitToFlutterFlow=n_;window.runRefinement=Ev;window.regenerateFromPastedErrors=xv;window.clearErrorInput=Sv;window.setFlutterFlowEndpoint=Jm;window.getFlutterFlowEndpoint=fr;window.commitProgress=be;window.openSignInModal=Ia;window.closeSignInModal=Mv;window.handleMagicLinkRequest=Lv;window.handleSignOut=Ov;window.startCheckout=Vv;window.openCustomerPortal=Gv;window.openPricingModal=Ii;window.closePricingModal=Qd;let ps=null,ih=null;const xc=120;function Vi(){const t=document.getElementById("pipeline-progress"),e=document.getElementById("results-view"),s=document.getElementById("ready-state");s&&s.classList.add("hidden"),e&&e.classList.remove("visible"),document.body.classList.remove("results-fullscreen","results-with-sidebar"),t&&t.classList.add("visible"),ih=Date.now();for(let r=1;r<=3;r++){const i=document.getElementById(`pdot-${r}`);i&&(i.className="progress-dot")}it(1),l_()}function it(t){const e={1:"Analyzing your prompt...",2:"Generating Dart code...",3:"Running code audit..."},s={1:"Step 1 of 3 — Prompt Architect",2:"Step 2 of 3 — Code Generator",3:"Step 3 of 3 — Code Review"},r=document.getElementById("progress-title-text"),i=document.getElementById("progress-substep-text");r&&(r.textContent=e[t]||e[1]),i&&(i.textContent=s[t]||s[1]);for(let n=1;n<=3;n++){const o=document.getElementById(`pdot-${n}`);o&&(n{const t=(Date.now()-ih)/1e3,e=document.getElementById("progress-elapsed"),s=document.getElementById("pipeline-progress-fill");e&&(e.textContent=`${Math.floor(t)}s`);const r=t/xc*100,i=Math.min(95,r*(1-Math.exp(-t/(xc*.6)))*1.2);s&&(s.style.width=`${i}%`)},250)}function $t(){ps&&(clearInterval(ps),ps=null);const t=document.getElementById("pipeline-progress-fill");t&&(t.style.width="100%");for(let e=1;e<=3;e++){const s=document.getElementById(`pdot-${e}`);s&&(s.className="progress-dot completed")}setTimeout(()=>{const e=document.getElementById("pipeline-progress");e&&e.classList.remove("visible"),t&&(t.style.width="0%")},400)}function xs(t,e=""){const s={pass:'',warning:'',fail:'',info:''};return``}function nh(t){return{pass:"Passed review",warning:"Needs attention",fail:"Blocking issues"}[t]||"Needs attention"}function c_(){return Og({bundle:y.artifactBundle,reviewResult:y.step3Result})}function u_(t){return` +`}else n+=`${t} +`;const i=md({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,userFeedback:n});Jn(),nt(2),ze(2),ve(2,!0),y.step2Result=await qn(i,s),Un();const o=document.getElementById("step2-output"),a=bs(y.step2Result);o.textContent=a,o.dataset.raw=a,ve(2,!1),ze(3),nt(3),ve(3,!0),y.step3Result=await Vn(y.step2Result,y.step1Result),Hn();const l=document.getElementById("step3-output");l.textContent=y.step3Result,ve(3,!1),$t();const u=Dn(y.step3Result);Yn(a,u)}catch(n){console.error("Regeneration failed:",n),$t(),ue(xa(n,"Regeneration failed"),"error")}finally{y.isRunning=!1,r&&(r.disabled=!1,r.textContent="Fix Errors & Regenerate"),Xt()}}async function Av(){const t=document.getElementById("ff-status-dot"),e=document.getElementById("ff-status-text");if(!t||!e)return;const s=await Ee("flutterflow"),r=await Ee("flutterflow_project_id");s&&r?(t.className="w-2 h-2 rounded-full bg-green-500",e.textContent="FlutterFlow credentials configured",e.className="text-green-600"):s||r?(t.className="w-2 h-2 rounded-full bg-yellow-500",e.textContent="FlutterFlow credentials incomplete",e.className="text-yellow-600"):(t.className="w-2 h-2 rounded-full bg-red-500",e.textContent="FlutterFlow credentials not configured",e.className="text-red-600")}async function $v(t){try{const e=await fetch(`${Je}/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 Rv(t){try{const s=await(await fetch(`${Je}/auth/verify-magic-link`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:t})})).json();if(s.error||!s.email||!s.sessionToken)throw new Error(s.error||"Invalid or expired link");return s}catch(e){throw console.error("verifyMagicLink failed:",{message:e.message,stack:e.stack}),e}}async function Tv(t){try{const e=await fetch(`${Je}/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:`${Je}/auth/refresh-session`,status:e.status}),null;const s=await e.json();return s.error||!s.email||!s.sessionToken?(console.warn("refreshSession: validation failed",{error:s.error,hasEmail:!!s.email,hasToken:!!s.sessionToken}),null):s}catch(e){return console.error("refreshSession: fetch failed",{url:`${Je}/auth/refresh-session`,message:e.message,stack:e.stack}),null}}function Ec(t,e){const s=Yd(),r=(G.email||s.email)!==t;G.email=t,G.sessionToken=e,G.isVerified=!0,fe=Es({isLoading:!0}),localStorage.setItem(yn,JSON.stringify({email:t,sessionToken:e})),r&&Ra()}function Ia(){G.email=null,G.sessionToken=null,G.isVerified=!1,fe=Es({isResolved:!0}),localStorage.removeItem(yn),localStorage.removeItem(bn)}function Yd(){try{const t=localStorage.getItem(yn);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(yn),{email:null,sessionToken:null}}}async function Nv(){const e=new URLSearchParams(window.location.search).get("token");if(e){window.history.replaceState({},"",window.location.pathname);try{const{email:s,sessionToken:r}=await Rv(e);Ec(s,r)}catch(s){ue(s.message||"Sign-in link invalid or expired.","error")}}else{const{email:s,sessionToken:r}=Yd();if(s&&r){const n=await Tv(r);n?Ec(n.email,n.sessionToken):Ia()}}Fa()}function Ca(){const t=document.getElementById("signin-modal");t&&t.classList.add("open")}function Mv(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("signin-modal");e&&e.classList.remove("open")}async function Lv(){const t=document.getElementById("signin-email-input"),e=document.getElementById("signin-submit-btn"),s=document.getElementById("signin-message"),r=t?.value?.trim();if(!r||!/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/.test(r)||r.length>254){s&&(s.textContent="Please enter a valid email address.");return}e&&(e.disabled=!0,e.textContent="Sending…"),s&&(s.textContent="");try{await $v(r),t&&(t.value=""),s&&(s.textContent=`Check your email — we sent a link to ${r}`),e&&(e.textContent="Sent!")}catch(i){console.error("handleMagicLinkRequest: sendMagicLink failed",{email:r,err:i}),s&&(s.textContent="Something went wrong. Please try again."),e&&(e.disabled=!1,e.textContent="Send Link")}}function Ov(){Ia(),Ra(),Fa(),Kn()}function Fa(){const t=G.isVerified&&!!G.email,e=document.getElementById("auth-signedout"),s=document.getElementById("auth-signedin"),r=document.getElementById("auth-guest-usage");e&&e.classList.toggle("hidden",t),s&&s.classList.toggle("hidden",!t),r&&r.classList.toggle("hidden",t);const n=document.getElementById("auth-user-email");n&&(n.textContent=G.email||""),qr(),Kn()}async function Zd(){try{if(typeof FingerprintJS>"u"){console.warn("resolveIdentity: FingerprintJS not loaded, skipping");return}const e=await(await FingerprintJS.load()).get(),s=e.visitorId,r=await fetch(Cm,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({fingerprint:e.visitorId,cookie_id:s})});if(!r.ok)throw new Error(`Identity check HTTP ${r.status}`);const n=await r.json();if(Ge.userId=n.user_id,Ge.token=n.identity_token||null,Ge.status=n.status,Ge.resolved=!0,sessionStorage.setItem(km,n.user_id),Ge.token&&sessionStorage.setItem(Im,Ge.token),n.usage_count!==void 0){const i=At(),a=(n.usage_month||i)===i?n.usage_count:0;localStorage.setItem(Kt,JSON.stringify({count:a,month:i})),Qs()}console.log(`Identity resolved: ${n.status} (${n.user_id.slice(0,8)}...) usage: ${n.usage_count??"n/a"}`)}catch(t){console.error("resolveIdentity failed:",t)}}let Ai=null;function Dv(t=5e3){return Ge.resolved?Promise.resolve():(Ai||(Ai=Zd().catch(e=>{console.warn("ensureIdentityReady: identity resolution failed",e)})),Promise.race([Ai,new Promise(e=>setTimeout(e,t))]))}function Xd(){const t=At();try{const e=localStorage.getItem(Kt);return e?JSON.parse(e):{count:0,month:t}}catch(e){return console.warn("getUsageData: failed to parse usage storage",{key:Kt,month:t,err:e}),localStorage.removeItem(Kt),{count:0,month:t}}}function At(){const t=new Date;return`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,"0")}`}function Gn(){const t=Xd();return t.month!==At()?{count:0,month:At()}:t}function Bv(){const e={count:Gn().count+1,month:At()};return localStorage.setItem(Kt,JSON.stringify(e)),e}function Pa(){return!!fe.isLoading}function Yt(){return!!fe.isResolved}function jv(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(wn,e)?e:null}function Uv(t){return t&&Object.entries($d).find(([,e])=>e===t)?.[0]||null}function Rr(...t){return t.find(e=>e!=null&&e!=="")}function Hv(...t){return t.find(e=>e&&typeof e=="object")||{}}function Wv(t){const e=t.data&&typeof t.data=="object"?t.data:t,s=Hv(e.subscription,e.stripeSubscription,e.currentSubscription,e.customer?.subscriptions?.data?.[0],e.subscriptions?.data?.[0],e.subscriptions?.[0]),r=e.metadata||s.metadata||e.customer?.metadata||{},n=Rr(e.priceId,e.price_id,e.stripePriceId,e.stripe_price_id,s.priceId,s.price_id,s.plan?.id,s.price?.id,s.items?.data?.[0]?.price?.id,s.items?.[0]?.price?.id,s.lines?.data?.[0]?.price?.id),i=Rr(e.status,e.subscriptionStatus,e.subscription_status,s.status,"none"),o=jv(Rr(e.tier,e.plan,e.planId,e.plan_id,e.subscriptionTier,e.subscription_tier,e.product,e.productName,s.tier,s.plan,r.tier,r.plan)),a=Fm.has(String(i).toLowerCase()),l=e.active===!0||e.isSubscribed===!0||e.subscribed===!0||e.hasSubscription===!0,u=o||Uv(n)||(a||l?"professional":"free");return Es({tier:u,status:i,periodEnd:Rr(e.periodEnd,e.currentPeriodEnd,e.current_period_end,s.current_period_end,s.periodEnd,null),isResolved:!0})}function Aa(){return wn[fe.tier]??wn.free}async function zv(){if(G.isVerified&&(!Yt()||Pa())&&(await Qd({force:!0}),Kn()),G.isVerified&&!Yt())return ue("Could not verify your subscription. Please refresh or try Manage billing.","error"),!1;const{count:t}=Gn(),e=Aa();if(t>=e)return $a(t,e,{openModal:!0}),!1;const s=Math.floor(e*.8);if(t>=s){const r=e-t;ue(`${r} run${r===1?"":"s"} remaining this month.`,"warning")}return!0}function $i(){const t=document.getElementById("paywall-exhausted");t&&t.classList.add("hidden")}function $a(t,e,s={}){const r=document.getElementById("walkthrough-modal");r&&r.classList.remove("open");const n=document.getElementById("ready-state");n&&n.classList.add("hidden");const i=document.getElementById("preview-frame-container");i&&(i.style.display="none");const o=document.getElementById("main-stage-container");o&&o.classList.add("visible");const a=document.getElementById("results-view");a&&a.classList.remove("visible"),document.body.classList.remove("results-fullscreen","results-with-sidebar");const l=document.getElementById("pipeline-progress");l&&l.classList.remove("visible");const u=document.getElementById("paywall-exhausted");if(!u){ue(`You've used all ${e} runs for this month. Upgrade to continue.`,"error"),Fn();return}const c=document.getElementById("paywall-exhausted-text");if(c){const h=fe.tier;h==="free"?c.textContent=`You've used all ${e} free generations this month. Upgrade to Pro for 50 generations/month and access to all AI models.`:c.textContent=`You've used all ${e} generations this month on your ${h} plan. Your limit resets next month.`}const d=document.getElementById("paywall-signin-btn");d&&d.classList.toggle("hidden",G.isVerified),u.classList.remove("hidden"),s.openModal&&Fn()}function Ro(t){return fe.tier==="free"&&Ur.includes(t)?cr:t}function qv(){const t=document.getElementById("code-options-content"),e=document.getElementById("code-generator-model");if(!t||!e)return;const s=fe.tier,n=!(G.isVerified&&!Yt())&&s==="free";Array.from(e.options).forEach(o=>{const a=qt(o.value),l=Ur.includes(o.value);o.textContent=l&&n?`${a} (PRO)`:a,o.disabled=!1}),n&&Ur.includes(e.value)&&(e.value=cr),e.disabled=!1,hc.has(e)||(e.addEventListener("change",()=>{Yt()&&fe.tier==="free"&&Ur.includes(e.value)&&(e.value=cr,Fn()),Ao(e.value),Td()}),hc.add(e));let i=document.getElementById("model-selector-free-notice");n?(i||(i=document.createElement("p"),i.id="model-selector-free-notice",i.className="text-xs text-gray-400 mt-1",t.appendChild(i)),i.innerHTML='Free plan — Gemini only. '):i&&i.remove(),Ao(e.value)}function Qs(){const t=document.getElementById("usage-counter");if(!t)return;if(G.isVerified&&Pa()){t.textContent="Checking plan…",t.className="text-xs text-gray-500",qr(),$i();return}if(G.isVerified&&!Yt()){t.textContent="Plan check failed",t.className="text-xs text-red-600 font-medium",qr(),$i();return}const{count:e}=Gn(),s=Aa();t.textContent=`${e} / ${s} runs this month`;const r=s>0?e/s:0;t.className=r>=1?"text-xs text-red-600 font-medium":r>=.8?"text-xs text-yellow-600 font-medium":"text-xs text-gray-500",qr(),e>=s&&!y.isRunning?$a(e,s):$i()}function qr(){const t=document.getElementById("guest-usage-text");if(!t)return;const e=Xd(),s=e.month===At()?e.count??0:0,r=wn.free;t.textContent=`${s} / ${r} generations used`}async function Qd(t={}){const e=t.force===!0;if(!G.isVerified||!G.sessionToken){fe=Es({isResolved:!0});return}fe={...fe,isLoading:!0,error:null};const s=localStorage.getItem(bn);if(!e&&s)try{const{data:r,email:n,ts:i,version:o}=JSON.parse(s);if(o===pc&&n===G.email&&Date.now()-i<300*1e3){fe={...r,isLoading:!1,isResolved:r.isResolved!==!1};return}}catch(r){console.warn("Failed to parse subscription cache:",r,"| raw value:",s)}try{const n=await(await fetch(`${Je}/stripe/get-subscription`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:G.sessionToken,user_id:Ge.userId})})).json();if(n.error){if(["unauthorized","invalid session","expired session"].some(o=>String(n.error).toLowerCase().includes(o))){Ia(),Fa();return}fe=Es({isResolved:!1,error:n.error});return}fe=Wv(n),localStorage.setItem(bn,JSON.stringify({version:pc,data:fe,email:G.email,ts:Date.now()}))}catch(r){console.error("fetchSubscription failed:",r),fe={...fe,isLoading:!1,isResolved:!1,error:r.message}}}function Ra(){localStorage.removeItem(bn)}async function Vv(t){if(!G.isVerified||!G.sessionToken){eh(),Ca();return}if(!$d[t]){ue("Invalid plan selected.","error");return}const e=document.getElementById(`checkout-btn-${t}`);e&&(e.disabled=!0,e.textContent="Redirecting…");try{const r=await(await fetch(`${Je}/stripe/create-checkout-session-intl`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tierId:t,sessionToken:G.sessionToken,currency:Ld()})})).json();if(r.error||!r.url)throw new Error(r.error||"Failed to create checkout session");const{url:n}=r;window.location.href=n}catch(s){console.error("startCheckout failed:",s),e&&(e.disabled=!1,e.textContent="Subscribe"),ue("Could not start checkout. Please try again.","error")}}async function Gv(){if(!G.isVerified||!G.sessionToken){Ca();return}const t=document.getElementById("manage-billing-btn");t&&(t.disabled=!0,t.textContent="Loading…");try{const s=await(await fetch(`${Je}/stripe/create-portal-session`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:G.sessionToken})})).json();if(s.error||!s.url)throw new Error(s.error||"Failed to open billing portal");const{url:r}=s;window.location.href=r}catch(e){console.error("openCustomerPortal failed:",e),t&&(t.disabled=!1,t.textContent="Manage billing"),ue("Could not open billing portal. Please try again.","error")}}async function Cn(t,e,s,r={},n=[]){const o=new AbortController,a=setTimeout(()=>o.abort(),12e4);try{const l=await fetch(xm,{method:"POST",headers:{"Content-Type":"application/json",...Ge.token?{Authorization:`Bearer ${Ge.token}`}:{}},signal:o.signal,body:JSON.stringify({user_id:Ge.userId,step:t,model:e,prompt:s,images:n,context:r})}),u=await l.text();let c={};try{c=u?JSON.parse(u):{}}catch{c={}}if(l.status===429){c.serverCount!==void 0&&(localStorage.setItem(Kt,JSON.stringify({count:c.serverCount,month:At()})),Qs());const p=new Error(c.message||"Monthly usage limit reached. Upgrade to continue.");throw p.isUsageLimit=!0,p}const d=Vf(c,t);if(d)throw d;if(console.log(`[BuildShip] ${t} response keys:`,Object.keys(c),"content type:",typeof c.content),!l.ok)throw new Error(`${c.message||c.error||"BuildShip pipeline error"} (HTTP ${l.status})`);if(t==="generator")if(c.usage_status==="success"&&Number.isFinite(c.usage_count)){const p=At();(c.usage_month||p)===p&&(localStorage.setItem(Kt,JSON.stringify({count:c.usage_count,month:p})),Qs())}else Bv(),Qs();let h=c.output||c.content;if(!h){const p=u?` (body: ${u.slice(0,120)})`:"";throw new Error(`BuildShip returned no output for step "${t}"${p}`)}return Array.isArray(h)&&(h=h.map(p=>typeof p=="string"?p:p.text||"").join("")),typeof h!="string"&&(h=JSON.stringify(h)),h}catch(l){throw l.name==="AbortError"?new Error(`BuildShip ${t} timed out after ${12e4/1e3}s`):l instanceof TypeError?new Error(`BuildShip unreachable: ${l.message}`):l}finally{clearTimeout(a)}}function Kv(){const e=new URLSearchParams(window.location.search).get("checkout");e==="success"?(window.history.replaceState({},"",window.location.pathname),Ra(),ue("Subscription active! Welcome aboard.","success")):e==="cancel"&&(window.history.replaceState({},"",window.location.pathname),ue("Checkout cancelled.","info"))}function Kn(){const t=G.isVerified&&!!G.email,e=fe.tier,s=t&&Pa(),r=!t||Yt(),n=document.getElementById("subscription-tier-badge");if(n){const a={free:"Free",professional:"Professional",power:"Power Developer"},l={free:"bg-gray-100 text-gray-600",professional:"bg-indigo-100 text-indigo-700",power:"bg-purple-100 text-purple-700",unresolved:"bg-red-50 text-red-600"};n.textContent=s?"Checking…":r?a[e]||"Free":"Plan unavailable",n.className=`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${r?l[e]||l.free:l.unresolved}`}const i=document.getElementById("upgrade-prompt");i&&i.classList.toggle("hidden",!t||s||!r||e!=="free");const o=document.getElementById("manage-billing-btn");o&&o.classList.toggle("hidden",!t||s||r&&e==="free"),Jv(r?e:null),qv(),Td(),Qs()}function Jv(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(([n,{btnId:i,defaultText:o}])=>{const a=document.getElementById(i);a&&(n===t?(a.disabled=!0,a.textContent="Current plan",a.classList.add(...e)):(a.disabled=!1,a.textContent=o,a.classList.remove(...e)))});const r=document.getElementById("free-tier-current");r&&r.classList.toggle("hidden",t!=="free")}function To(){const t=Ld(),e=document.getElementById("pro-price"),s=document.getElementById("power-price"),r=document.getElementById("pro-price-note"),n=document.getElementById("power-price-note");e&&(e.textContent=gc(fc.professional,t)),s&&(s.textContent=gc(fc.power,t));const i="billed monthly";r&&(r.textContent=i),n&&(n.textContent=i)}function Fn(){To();const t=document.getElementById("pricing-modal");t&&t.classList.add("open"),Om().then(()=>To())}function eh(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("pricing-modal");e&&e.classList.remove("open")}function ue(t,e="info"){const s={success:"bg-green-600 text-white",error:"bg-red-600 text-white",warning:"bg-amber-500 text-white",info:"bg-gray-800 text-white"},r=document.createElement("div");r.className=`fixed bottom-6 left-1/2 -translate-x-1/2 px-5 py-3 rounded-lg text-sm font-medium shadow-lg z-50 transition-opacity duration-300 ${s[e]||s.info}`,r.textContent=t,document.body.appendChild(r),setTimeout(()=>{r.style.opacity="0",setTimeout(()=>r.remove(),300)},3500)}document.addEventListener("DOMContentLoaded",async()=>{hljs.configure({tabReplace:" ",classPrefix:"hljs-"}),Yv(),await Nv(),Kv(),await Qd(),Kn(),To(),await lv(),rv();const t=document.getElementById("flutterflow-endpoint-select");if(t){const s=gr();t.value=s}Hd(),Zd();const e=document.getElementById("pipeline-input");e&&(e.addEventListener("input",()=>{Et===2&&e.value.trim().length>0&&(fa(),Bn())}),e.addEventListener("blur",()=>{const s=document.getElementById("walkthrough-modal");Et===2&&s&&s.classList.add("open")}),e.addEventListener("keydown",s=>{if(s.key==="Tab"){const r=document.getElementById("walkthrough-modal");Et===2&&r&&setTimeout(()=>{r.classList.add("open")},100)}})),window.addEventListener("commitStateChange",s=>{const{state:r}=s.detail;r===V.PREPARING||r===V.VALIDATING||r===V.PUSHING?(be.phaseId||rh(),xc(r)):(r===V.SUCCESS||r===V.ERROR)&&(xc(r),setTimeout(Pn,1e3))})});function Yv(){const t=document.getElementById("preview-frame-container");t&&(t.style.display="")}function Zv(){const t=document.getElementById("welcome-video-player");t&&(t.addEventListener("click",Zt),document.addEventListener("keydown",Zt))}function Zt(){const t=document.getElementById("preview-frame-container"),e=document.getElementById("main-stage-container"),s=document.getElementById("ready-state");t&&(t.style.display="none"),e&&e.classList.add("visible"),s&&s.classList.remove("hidden");const r=document.getElementById("welcome-video-player");r&&r.removeEventListener("click",Zt),document.removeEventListener("keydown",Zt),Hd()}let er=null;async function Xv(){const t=document.getElementById("confirm-project-select");if(!t)return;const e=++wc,s=()=>e===wc,r=await Ee("flutterflow"),n=await Ee("flutterflow_project_id");if(s()){if(!r){t.innerHTML='',t.disabled=!0;return}t.disabled=!1,t.innerHTML='';try{const o=await new mr(r,"").listProjects();if(!s())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)}),n&&(t.value=n)}catch(i){if(!s())return;console.error("Failed to load projects for deploy:",i),t.innerHTML=''}}}function Qv(){return document.getElementById("confirm-project-select")?.value?.trim()||null}function th(t,e,s,r=null){er={codeInfo:t,checks:e,deps:s,bundlePlan:r},document.getElementById("confirm-file-name").textContent=t.fileName,document.getElementById("confirm-artifact-type").textContent=t.artifactType,document.getElementById("confirm-file-size").textContent=`${(t.content.length/1024).toFixed(1)} KB`,document.getElementById("confirm-line-count").textContent=r?`${r.fileEntries.length} files`:t.content.split(` +`).length,Xv();const n=document.getElementById("confirm-deps-list"),i=document.getElementById("confirm-deps-section");s&&Object.keys(s).length>0?(n.innerHTML=Object.entries(s).map(([u,c])=>{const d=c?`at least ${bt(c)}`:"version resolved from your project";return`
  • • ${bt(u)}: ${d}
  • `}).join(""),i.classList.remove("hidden")):i.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=>`
  • • ${bt(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&&l.classList.add("open")}function sh(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("commit-confirm-modal");e&&e.classList.remove("open"),er=null}function e_(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("commit-success-modal");e&&e.classList.remove("open");const s=["success-message","success-project-id","success-file-name","success-artifact-type","success-time","success-size"];for(const i of s){const o=document.getElementById(i);o&&(o.textContent="")}const r=document.getElementById("success-warnings-section");r&&r.classList.add("hidden");const n=document.getElementById("success-warnings-list");n&&(n.innerHTML="")}function No(t){const e=(g,m)=>{const _=document.getElementById(g);_&&(_.textContent=m||"")},s=t.metadata?.fileName||"",r=t.metadata?.projectId||"",n=t.metadata?.artifactType||"",i=t.elapsedTime?`${(t.elapsedTime/1e3).toFixed(1)}s`:"",o=t.metadata?.codeSize?`${(t.metadata.codeSize/1024).toFixed(1)} KB`:"";e("success-message",t.message||"Code committed successfully!"),e("success-project-id",r),e("success-file-name",s),e("success-artifact-type",n),e("success-time",i),e("success-size",o);const a=t.addedDependencies||[],l=document.getElementById("success-deps-row");l&&l.classList.toggle("hidden",a.length===0),e("success-deps",a.join(", "));const u=document.getElementById("success-open-ff-link");u&&r&&(u.href=`https://app.flutterflow.io/project/${r}`);const c=document.getElementById("success-warnings-section"),d=document.getElementById("success-warnings-list"),h=t.unverified||[],p=t.warnings||[];(p.length>0||h.length>0)&&c&&d&&(d.innerHTML=[...h.map(g=>`
  • Not verified before deploying: ${j(String(g))}
  • `),...p.map(([g,m])=>`
  • ${j(g)}: ${j(String(m))}
  • `)].join(""),c.classList.remove("hidden"));const f=document.getElementById("commit-success-modal");f&&f.classList.add("open")}function Mo(t){Pn(),Fv(t)}function t_(){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 Sc={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}},s_=[{after:0,text:"Starting a FlutterFlow build runner..."},{after:12,text:"Preparing the FlutterFlow AI workspace..."},{after:35,text:"Uploading your custom classes..."},{after:60,text:"FlutterFlow is applying the changes..."},{after:100,text:"Still working — this can take a couple of minutes..."}],be={sequence:[],phaseId:null,phaseStartedAt:null,timer:null,substatus:null,liveSubstatus:!1,start({withProvisioning:t=!1}={}){this.sequence=["prepare","validate","project"],t&&this.sequence.push("provision"),this.sequence.push("package","push","done");const e=document.getElementById("commit-progress-overlay");e&&e.classList.add("open"),this.set("prepare")},set(t,e=null){if(!(!Sc[t]||t===this.phaseId)){if(!this.sequence.includes(t)){const s=this.sequence.indexOf("package");this.sequence.splice(s===-1?this.sequence.length:s,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=Sc[this.phaseId];if(!t)return;const e=(Date.now()-this.phaseStartedAt)/1e3,s=t.start+(t.end-t.start)*(1-Math.exp(-e/25));if(this.phaseId==="provision"&&!this.liveSubstatus){const o=s_.filter(a=>e>=a.after).pop();o&&(this.substatus=o.text)}const r=this.sequence.indexOf(this.phaseId),i=[`Step ${r===-1?1:r+1} of ${this.sequence.length}`];e>=5&&i.push(r_(e)),nh(this.phaseId==="done"?100:s,t.message,i.join(" · "),this.substatus)},stop(){this.timer&&clearInterval(this.timer),this.timer=null,this.phaseId=null;const t=document.getElementById("commit-progress-overlay");t&&t.classList.remove("open")}};function r_(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 rh(t){be.start(t)}function Pn(){be.stop()}function nh(t,e,s,r=null){const n=document.getElementById("commit-progress-bar"),i=document.getElementById("progress-message"),o=document.getElementById("progress-detail"),a=document.getElementById("progress-substatus");n&&(n.style.width=`${Math.round(t*10)/10}%`),i&&(i.textContent=e),o&&(o.textContent=s),a&&(a.textContent=r||"",a.classList.toggle("hidden",!r))}function xc(t){const e={[V.PREPARING]:"prepare",[V.VALIDATING]:"validate",[V.PUSHING]:"project",[V.SUCCESS]:"done"};if(t===V.ERROR){be.timer&&clearInterval(be.timer),be.timer=null,nh(100,"Failed","Error occurred");return}const s=e[t];s&&be.set(s)}function n_(t){return t.bundlePlan?t.bundlePlan.fileEntries.some(e=>e.type===U.CODE_FILE):t.codeInfo?.codeType===U.CODE_FILE}async function i_(){if(!er){console.error("No pending commit data");return}const t=er;if(er=null,Xs=Qv(),sh(),rh({withProvisioning:n_(t)}),t.bundlePlan){const o=await vv(t.bundlePlan,{pipelineResult:{step1Result:y.step1Result,selectedModel:document.getElementById("code-generator-model")?.value}});Xs=null,Pn(),o.success?No(o):Mo(o);return}const{codeInfo:e}=t,{artifactType:s,artifactName:r,fileName:n}=zd(),i=await mv(e.content,{artifactType:s,artifactName:r,fileName:n,pipelineResult:{step1Result:y.step1Result,selectedModel:document.getElementById("code-generator-model")?.value}});Xs=null,Pn(),i.success?No(i):Mo(i)}window.runThinkingPipeline=$o;window.toggleStep=wv;window.toggleSection=yv;window.selectWorkflowStep=ze;window.copyCode=bv;window.retryWithDifferentModel=kv;window.openApiKeysModal=pa;window.closeApiKeysModal=jd;window.closeWalkthroughModal=Zm;window.openWalkthroughModal=Ym;window.advanceWalkthrough=fa;window.commitToFlutterFlow=gv;function o_(){const t=document.getElementById("pipeline-input");t&&t.focus()}function a_(){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=o_;window.openModelSelector=a_;window.handlePromptImageSelect=Mm;window.removePromptImage=Lm;window.saveApiKeys=ev;window.clearAllApiKeys=tv;window.toggleKeyVisibility=iv;window.handleWelcomeVideoEnd=Zv;window.dismissWelcomeVideo=Zt;window.initiateCommitToFlutterFlow=Iv;window.updateFlutterFlowCredentialStatus=Av;window.closeCommitConfirmModal=sh;window.closeCommitSuccessModal=e_;window.showCommitSuccessModal=No;window.showCommitFailureModal=Mo;window.toggleCodePreview=t_;window.confirmCommitToFlutterFlow=i_;window.runRefinement=Ev;window.regenerateFromPastedErrors=xv;window.clearErrorInput=Sv;window.setFlutterFlowEndpoint=Jm;window.getFlutterFlowEndpoint=gr;window.commitProgress=be;window.openSignInModal=Ca;window.closeSignInModal=Mv;window.handleMagicLinkRequest=Lv;window.handleSignOut=Ov;window.startCheckout=Vv;window.openCustomerPortal=Gv;window.openPricingModal=Fn;window.closePricingModal=eh;let ps=null,ih=null;const kc=120;function Jn(){const t=document.getElementById("pipeline-progress"),e=document.getElementById("results-view"),s=document.getElementById("ready-state");s&&s.classList.add("hidden"),e&&e.classList.remove("visible"),document.body.classList.remove("results-fullscreen","results-with-sidebar"),t&&t.classList.add("visible"),ih=Date.now();for(let r=1;r<=3;r++){const n=document.getElementById(`pdot-${r}`);n&&(n.className="progress-dot")}nt(1),l_()}function nt(t){const e={1:"Analyzing your prompt...",2:"Generating Dart code...",3:"Running code audit..."},s={1:"Step 1 of 3 — Prompt Architect",2:"Step 2 of 3 — Code Generator",3:"Step 3 of 3 — Code Review"},r=document.getElementById("progress-title-text"),n=document.getElementById("progress-substep-text");r&&(r.textContent=e[t]||e[1]),n&&(n.textContent=s[t]||s[1]);for(let i=1;i<=3;i++){const o=document.getElementById(`pdot-${i}`);o&&(i{const t=(Date.now()-ih)/1e3,e=document.getElementById("progress-elapsed"),s=document.getElementById("pipeline-progress-fill");e&&(e.textContent=`${Math.floor(t)}s`);const r=t/kc*100,n=Math.min(95,r*(1-Math.exp(-t/(kc*.6)))*1.2);s&&(s.style.width=`${n}%`)},250)}function $t(){ps&&(clearInterval(ps),ps=null);const t=document.getElementById("pipeline-progress-fill");t&&(t.style.width="100%");for(let e=1;e<=3;e++){const s=document.getElementById(`pdot-${e}`);s&&(s.className="progress-dot completed")}setTimeout(()=>{const e=document.getElementById("pipeline-progress");e&&e.classList.remove("visible"),t&&(t.style.width="0%")},400)}function xs(t,e=""){const s={pass:'',warning:'',fail:'',info:''};return``}function oh(t){return{pass:"Passed review",warning:"Needs attention",fail:"Blocking issues"}[t]||"Needs attention"}function c_(){return Dg({bundle:y.artifactBundle,reviewResult:y.step3Result})}function u_(t){return`
    ${xs(t.severity)}
    @@ -197,7 +197,7 @@ Error: ${h} ${t.detail&&t.detail!==t.title?`

    ${j(t.detail)}

    `:""}
    - `}function h_(t){const e=document.getElementById("results-summary-detail"),s=document.getElementById("results-title");if(!e)return;s&&(s.textContent=t.title);const r=t.score,i=r==null?"neutral":r>=80?"pass":r>=60?"warning":"fail",n=r==null?"":r>=80?"Strong":r>=60?"Needs work":"High risk",o=t.findings.length?` + `}function h_(t){const e=document.getElementById("results-summary-detail"),s=document.getElementById("results-title");if(!e)return;s&&(s.textContent=t.title);const r=t.score,n=r==null?"neutral":r>=80?"pass":r>=60?"warning":"fail",i=r==null?"":r>=80?"Strong":r>=60?"Needs work":"High risk",o=t.findings.length?`
      ${t.findings.map(l=>`
    • @@ -230,11 +230,11 @@ Error: ${h} ${a}
    -
    - `}function p_(t){const e=t.artifacts.find(l=>l.id===y.selectedArtifactId)||t.artifacts[0];if(!e)return"";const s={pass:{icon:"pass",message:"No file-specific issues were found."},warning:{icon:"warning",message:"This file needs attention, but Code Review did not return a specific finding."},fail:{icon:"fail",message:"This file is blocked, but Code Review did not return a specific finding."}}[e.status],r=e.findings.length?e.findings.map(u_).join(""):`
    ${xs(s.icon)} ${j(s.message)}
    `,i=e.dependencies?.length?e.dependencies.map(l=>` + `}function p_(t){const e=t.artifacts.find(l=>l.id===y.selectedArtifactId)||t.artifacts[0];if(!e)return"";const s={pass:{icon:"pass",message:"No file-specific issues were found."},warning:{icon:"warning",message:"This file needs attention, but Code Review did not return a specific finding."},fail:{icon:"fail",message:"This file is blocked, but Code Review did not return a specific finding."}}[e.status],r=e.findings.length?e.findings.map(u_).join(""):`
    ${xs(s.icon)} ${j(s.message)}
    `,n=e.dependencies?.length?e.dependencies.map(l=>`
  • ${j(l.name)}${l.version?` ${j(l.version)}`:""}${l.reason?`

    ${j(l.reason)}

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

    ${j(l.description)}

    `:""}
  • `).join(""):'
  • No relationships for this file
  • ';return`
    - ${xs(e.status)} ${j(nh(e.status))} + ${xs(e.status)} ${j(oh(e.status))}

    ${j(e.artifactName)}

    ${e.description?`

    ${j(e.description)}

    `:""}
    @@ -280,7 +280,7 @@ Error: ${h}

    Dependencies

    -
      ${i}
    +
      ${n}

    Deployment

    @@ -297,24 +297,24 @@ Error: ${h}

    Imports

    -
    ${n}
    +
    ${i}

    Relationships

      ${a}
    - `}function f_(t){const e=document.getElementById("bundle-strip"),s=document.getElementById("results-summary-tab"),r=document.getElementById("artifact-tabs"),i=document.getElementById("results-file-count");if(s&&s.classList.toggle("active",y.resultsViewMode==="summary"),!t.artifacts.length){i&&(i.textContent="0 files"),e&&e.classList.remove("visible"),r&&(r.innerHTML="");return}if(i){const n=t.artifacts.length;i.textContent=`${n} ${n===1?"file":"files"}`}r&&(r.innerHTML=t.artifacts.map(n=>` + `}function f_(t){const e=document.getElementById("bundle-strip"),s=document.getElementById("results-summary-tab"),r=document.getElementById("artifact-tabs"),n=document.getElementById("results-file-count");if(s&&s.classList.toggle("active",y.resultsViewMode==="summary"),!t.artifacts.length){n&&(n.textContent="0 files"),e&&e.classList.remove("visible"),r&&(r.innerHTML="");return}if(n){const i=t.artifacts.length;n.textContent=`${i} ${i===1?"file":"files"}`}r&&(r.innerHTML=t.artifacts.map(i=>` - `).join(""),r.onclick=n=>{const o=n.target.closest(".artifact-tab");o?.dataset?.artifactId&&oh(o.dataset.artifactId)}),e&&e.classList.add("visible")}function Ra(){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"),s=document.getElementById("results-audit-output"),r=document.getElementById("results-summary-detail"),i=document.getElementById("artifact-results-split"),n=c_(),o=ma();if(h_(n),f_(n),e&&(e.textContent=""),e){const a=Pd(o);e.innerHTML=a}s&&(s.innerHTML=p_(n)),r&&r.classList.toggle("hidden",y.resultsViewMode!=="summary"),i&&i.classList.toggle("hidden",y.resultsViewMode!=="file"),t&&t.classList.add("visible")}function Gi(t,e){y.selectedArtifactId||(y.selectedArtifactId=fi(y.artifactBundle).id),y.resultsViewMode="summary",document.body.classList.add("results-fullscreen");const s=document.getElementById("step3-output");s&&(s.textContent=""),Ra(),Xt();const r=document.getElementById("btn-feedback-up"),i=document.getElementById("btn-feedback-down");r&&(r.className="feedback-btn"),i&&(i.className="feedback-btn")}function oh(t){y.selectedArtifactId=t,y.resultsViewMode="file",Ra()}function g_(){y.resultsViewMode="summary",Ra()}function m_(){const t=document.getElementById("btn-copy-results"),e=ma();navigator.clipboard.writeText(e).then(()=>{if(t){t.classList.add("copied");const s=t.querySelector("span");if(s){const r=s.textContent;s.textContent="Copied!",setTimeout(()=>{t.classList.remove("copied"),s.textContent=r},2e3)}}})}function v_(t){const e=document.getElementById("btn-feedback-up"),s=document.getElementById("btn-feedback-down");t==="up"?(e.classList.toggle("active-up"),s.classList.remove("active-down")):(s.classList.toggle("active-down"),e.classList.remove("active-up"));const r=t==="up"?"thumbsUp":"thumbsDown";xa(r,y.step2Result,y.step1Result),zt("Generation Feedback",{feedback:r})}function __(){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 ah(){const t=document.getElementById("error-input-panel");t&&(t.classList.add("hidden"),t.style.display="none")}window.copyResultsCode=m_;window.selectArtifact=oh;window.selectResultsSummary=g_;window.submitResultsFeedback=v_;window.showErrorInputPanel=__;window.hideErrorInputPanel=ah; + `).join(""),r.onclick=i=>{const o=i.target.closest(".artifact-tab");o?.dataset?.artifactId&&ah(o.dataset.artifactId)}),e&&e.classList.add("visible")}function Ta(){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"),s=document.getElementById("results-audit-output"),r=document.getElementById("results-summary-detail"),n=document.getElementById("artifact-results-split"),i=c_(),o=va();if(h_(i),f_(i),e&&(e.textContent=""),e){const a=Ad(o);e.innerHTML=a}s&&(s.innerHTML=p_(i)),r&&r.classList.toggle("hidden",y.resultsViewMode!=="summary"),n&&n.classList.toggle("hidden",y.resultsViewMode!=="file"),t&&t.classList.add("visible")}function Yn(t,e){y.selectedArtifactId||(y.selectedArtifactId=mn(y.artifactBundle).id),y.resultsViewMode="summary",document.body.classList.add("results-fullscreen");const s=document.getElementById("step3-output");s&&(s.textContent=""),Ta(),Xt();const r=document.getElementById("btn-feedback-up"),n=document.getElementById("btn-feedback-down");r&&(r.className="feedback-btn"),n&&(n.className="feedback-btn")}function ah(t){y.selectedArtifactId=t,y.resultsViewMode="file",Ta()}function g_(){y.resultsViewMode="summary",Ta()}function m_(){const t=document.getElementById("btn-copy-results"),e=va();navigator.clipboard.writeText(e).then(()=>{if(t){t.classList.add("copied");const s=t.querySelector("span");if(s){const r=s.textContent;s.textContent="Copied!",setTimeout(()=>{t.classList.remove("copied"),s.textContent=r},2e3)}}})}function v_(t){const e=document.getElementById("btn-feedback-up"),s=document.getElementById("btn-feedback-down");t==="up"?(e.classList.toggle("active-up"),s.classList.remove("active-down")):(s.classList.toggle("active-down"),e.classList.remove("active-up"));const r=t==="up"?"thumbsUp":"thumbsDown";ka(r,y.step2Result,y.step1Result),zt("Generation Feedback",{feedback:r})}function __(){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 lh(){const t=document.getElementById("error-input-panel");t&&(t.classList.add("hidden"),t.style.display="none")}window.copyResultsCode=m_;window.selectArtifact=ah;window.selectResultsSummary=g_;window.submitResultsFeedback=v_;window.showErrorInputPanel=__;window.hideErrorInputPanel=lh; diff --git a/dist/index.html b/dist/index.html index 726893a..21d5260 100644 --- a/dist/index.html +++ b/dist/index.html @@ -2420,7 +2420,7 @@ .pm-cards { padding: 0 16px; } } - +
    diff --git a/src/customCodeVerification.js b/src/customCodeVerification.js index baa3fa0..82e0f72 100644 --- a/src/customCodeVerification.js +++ b/src/customCodeVerification.js @@ -14,16 +14,16 @@ import { identifierToFlutterFlowFileStem } from "./flutterFlowArtifactValidation // only guards a malformed manifest. const FALLBACK_SDK_CONSTRAINT = ">=3.0.0 <4.0.0"; -// Packages the Flutter SDK supplies, declared as `sdk: flutter` rather than -// with a pub version. This mirrors the allowlist the deploy runner enforces, -// so anything named here can be reproduced in the scratch package. -const SDK_DEPENDENCIES = new Set([ - "flutter", - "flutter_test", - "flutter_driver", - "flutter_localizations", - "integration_test", -]); +// Which packages the Flutter SDK supplies is read from the project's own +// pubspec, never from a list kept here. A block-form entry whose first own-key +// is `sdk:` is an SDK package by definition, so the classification cannot fall +// behind the SDK: when Flutter ships a new package, a project declaring it +// classifies correctly with no change to this file. +// +// The list this replaced could not do that. It omitted `flutter_web_plugins`, +// which turned every project declaring it - every project with web support and +// a plugin - into one whose dependencies could not be reproduced, and refused +// the whole deploy for a package most of its classes never imported. // Why the verification manifest is sent as structured data rather than as // pubspec.yaml text: the deploy runner writes the manifest to disk and runs @@ -71,17 +71,28 @@ export function classifyCustomClassImports(code = "") { function collect(declared, into, sdkPackages) { const unrepresentable = []; for (const [name, info] of declared) { - if (SDK_DEPENDENCIES.has(name) && !info.isScalar) { + if (info.isScalar) { + into[name] = unquoteConstraint(info.constraint); + continue; + } + + // A block-form entry's first own-key says where the package comes from. + // `sdk:` is the Flutter SDK, which the runner reproduces from the name + // alone as `name: {sdk: flutter}`. A nested `version:` is simply a + // constraint written on its own line. + if (info.sourceKey === "sdk") { sdkPackages.add(name); continue; } - if (!info.isScalar) { - // `git:`, `path:`, a nested `hosted:` block - none can be reproduced - // outside the project, and none can be expressed in the manifest. - unrepresentable.push(name); + if (info.sourceKey === "version") { + into[name] = unquoteConstraint(info.sourceValue); continue; } - into[name] = unquoteConstraint(info.constraint); + + // `git:`, `path:`, a nested `hosted:` block - none can be reproduced + // outside the project, and none can be expressed in a manifest that + // carries names and constraints only. + unrepresentable.push(name); } return unrepresentable; } @@ -156,11 +167,18 @@ function skipReason(className, unresolvableImports, missingPackages) { * FlutterFlow. Classes that depend on the generated app are reported in * `skipped` so the deploy can say plainly what it did not verify. * - * When the project declares a dependency that cannot be reproduced outside it - * (a `git:` or `path:` source), nothing is verified: the scratch package would - * resolve packages differently from the project, and a check against different - * versions is worse than no check, because it reports a result that does not - * describe the code that actually ships. + * A dependency that cannot be reproduced outside the project - a `git:` or + * `path:` source - stops only a class that imports it. For that class the + * scratch package would resolve different code from the project, and a check + * against the wrong versions reports a result that does not describe what + * ships, so it is left out of `sources` and named in `skipped`. A class that + * does not import it resolves everything it uses to the same versions the + * project will, so it is verified normally. + * + * That scoping is the point. Deciding it once for the whole project meant a + * single `git:` entry - or a package the SDK supplied but a hand-kept name list + * had not heard of - left every class in the deploy uncompiled, including the + * ones that never touched it. * * @param {Array<{className: string, content: string}>} classes - Classes to deploy * @param {string} projectPubspecYaml - The project's merged pubspec.yaml @@ -183,16 +201,25 @@ export function planCustomCodeVerification(classes, projectPubspecYaml) { for (const entry of classes) { const { className, content } = entry; - if (unrepresentable.length > 0) { + const importedPackages = extractPackageImports(content); + + // Scoped to this class's own imports. A dependency the project declares + // from a source the manifest cannot express is only a problem for a class + // that actually imports it. + const unresolvablePackages = importedPackages.filter((name) => + unrepresentable.includes(name), + ); + + if (unresolvablePackages.length > 0) { skipped.push({ className, - reason: `${className} was not compiled before deploying: your project declares ${unrepresentable.join(", ")} from a source that cannot be reproduced outside the project, so package resolution could not be matched exactly.`, + reason: `${className} was not compiled before deploying: it imports ${unresolvablePackages.join(", ")}, which your project declares from a source that cannot be reproduced outside it, so package resolution could not be matched exactly.`, }); continue; } const { unresolvableImports } = classifyCustomClassImports(content); - const missingPackages = extractPackageImports(content).filter( + const missingPackages = importedPackages.filter( (name) => !availablePackages.has(name), ); diff --git a/src/customCodeVerification.test.js b/src/customCodeVerification.test.js index 6a481d5..02e3d4b 100644 --- a/src/customCodeVerification.test.js +++ b/src/customCodeVerification.test.js @@ -119,17 +119,126 @@ test("a dependency from a git or path source is reported unrepresentable", () => assert.deepEqual(manifest.unrepresentable, ["private_thing"]); }); -test("nothing is verified when package resolution cannot be matched exactly", () => { +test("a git dependency does not stop a class that never imports it", () => { const plan = planCustomCodeVerification( [{ className: "BackgroundDownloaderService", content: SELF_CONTAINED }], PROJECT_PUBSPEC, ); - // Compiling against different versions than the project resolves would report - // a result that does not describe the code that ships. - assert.deepEqual(plan.sources, []); + // The project declares `private_thing` from git, which cannot be reproduced + // outside it - but this class does not import it, so the scratch package + // resolves everything it does use to the versions the project will, and the + // check still describes the code that ships. Deciding this once for the whole + // project left every class uncompiled over a dependency it never touched. + assert.deepEqual(plan.sources, [ + { + fileName: "background_downloader_service.dart", + content: SELF_CONTAINED, + }, + ]); + assert.deepEqual(plan.skipped, []); +}); + +test("a class that imports the unreproducible dependency is skipped, and named as the reason", () => { + const importsPrivateThing = `import 'package:private_thing/private_thing.dart'; + +class UsesPrivateThing {} +`; + + const plan = planCustomCodeVerification( + [ + { className: "UsesPrivateThing", content: importsPrivateThing }, + { className: "BackgroundDownloaderService", content: SELF_CONTAINED }, + ], + PROJECT_PUBSPEC, + ); + + assert.deepEqual( + plan.sources.map((entry) => entry.fileName), + ["background_downloader_service.dart"], + ); assert.equal(plan.skipped.length, 1); - assert.match(plan.skipped[0].reason, /private_thing/); + assert.equal(plan.skipped[0].className, "UsesPrivateThing"); + // The reason names this class's own import, not the project's whole + // dependency set, so it says what to do about this class. + assert.match(plan.skipped[0].reason, /it imports private_thing/); +}); + +test("an SDK package no list has heard of is reproduced from its pubspec source", () => { + // The regression: flutter_web_plugins is a genuine Flutter SDK package that + // the hand-kept list omitted, so every project declaring it - which is every + // web-enabled project with a plugin - read as unreproducible and the deploy + // was refused for a package most of its classes never imported. + 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.equal(manifest.sdkPackages.includes("flutter_web_plugins"), true); + 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 class importing a package the project declares as an SDK package is not missing it", () => { + const pubspec = `name: my_app + +environment: + sdk: '>=3.0.0 <4.0.0' + +dependencies: + flutter: + sdk: flutter + flutter_web_plugins: + sdk: flutter +`; + 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("a block-form entry written as a bare version is read as a constraint", () => { + const pubspec = `name: my_app + +environment: + sdk: '>=3.0.0 <4.0.0' + +dependencies: + flutter: + sdk: flutter + intl: + version: ^0.20.3 +`; + + const manifest = buildAnalysisManifest(pubspec); + + assert.equal(manifest.dependencies.intl, "^0.20.3"); + assert.deepEqual(manifest.unrepresentable, []); + assert.deepEqual(manifest.sdkPackages, ["flutter"]); }); test("plans a real compile for a class whose imports all resolve", () => { diff --git a/src/pubspecSync.js b/src/pubspecSync.js index e824edd..1cdbbb9 100644 --- a/src/pubspecSync.js +++ b/src/pubspecSync.js @@ -103,6 +103,43 @@ function splitValueAndComment(rest) { }; } +/** + * Reads the first key of a block-form dependency's own mapping. + * + * A block-form entry says where a package comes from on a following, more + * deeply indented line: `sdk:`, `git:`, `path:`, a nested `hosted:`, or a + * `version:` written on its own line. That key is the only thing that + * distinguishes a package the Flutter SDK supplies from one the analysis + * manifest cannot reproduce, so it is read here rather than guessed from the + * package's name. A name list cannot work: 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. + * + * @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 + * @param {number} parentIndent - Indent of the dependency entry itself + * @returns {{key: string, value: string}|null} First own-key, or null if the + * entry has no mapping below it + */ +function readSourceDirective(lines, entryIndex, endIndex, parentIndent) { + for (let i = entryIndex + 1; i < endIndex; i += 1) { + const line = lines[i]; + if (isBlankOrComment(line)) continue; + // 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 to read. + if (indentOf(line) <= parentIndent) return null; + const trimmed = line.trim(); + const key = parseDependencyName(trimmed); + if (!key) continue; + const { value } = splitValueAndComment( + trimmed.slice(trimmed.indexOf(":") + 1), + ); + return { key, value }; + } + return null; +} + /** * Reads every package declared under `dependencies:` with its constraint. * @@ -111,7 +148,7 @@ function splitValueAndComment(rest) { * it is reported with `isScalar: false`. * * @param {string} yamlContent - Raw pubspec.yaml content - * @returns {Map} + * @returns {Map} */ export function parseExistingDependencies(yamlContent) { const lines = String(yamlContent || "").split("\n"); @@ -123,7 +160,8 @@ export function parseExistingDependencies(yamlContent) { const line = lines[i]; if (isBlankOrComment(line)) continue; // Only direct children are dependency names; deeper lines describe a - // dependency's own keys (sdk:, git:, version:, ...). + // dependency's own keys (sdk:, git:, version:, ...), which + // readSourceDirective reads separately below. if (indentOf(line) !== block.childIndent.length) continue; const trimmed = line.trim(); const name = parseDependencyName(trimmed); @@ -132,11 +170,21 @@ export function parseExistingDependencies(yamlContent) { const { value, comment } = splitValueAndComment( trimmed.slice(trimmed.indexOf(":") + 1), ); + const isScalar = value !== ""; + // 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); + declared.set(name, { constraint: value, comment, lineIndex: i, - isScalar: value !== "", + isScalar, + sourceKey: directive ? directive.key : null, + sourceValue: directive ? directive.value : null, }); } return declared; @@ -158,7 +206,7 @@ export function parseExistingDependencies(yamlContent) { * * @param {string} yamlContent - Raw pubspec.yaml content * @param {string} blockName - Top-level key, e.g. "dependency_overrides" - * @returns {Map} + * @returns {Map} */ export function parseDependencyBlock(yamlContent, blockName) { const lines = String(yamlContent || "").split("\n"); @@ -180,11 +228,21 @@ export function parseDependencyBlock(yamlContent, blockName) { const { value, comment } = splitValueAndComment( trimmed.slice(trimmed.indexOf(":") + 1), ); + const isScalar = value !== ""; + // 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); + declared.set(name, { constraint: value, comment, lineIndex: i, - isScalar: value !== "", + isScalar, + sourceKey: directive ? directive.key : null, + sourceValue: directive ? directive.value : null, }); } return declared; diff --git a/src/pubspecSync.test.js b/src/pubspecSync.test.js index d3b54cc..0499a77 100644 --- a/src/pubspecSync.test.js +++ b/src/pubspecSync.test.js @@ -2,6 +2,8 @@ import assert from "node:assert/strict"; import test from "node:test"; import { mergeDependenciesIntoYaml, + parseDependencyBlock, + parseExistingDependencies, parseExistingDependencyNames, validateProjectPubspec, } from "./pubspecSync.js"; @@ -173,3 +175,71 @@ test("accepts a real project pubspec and rejects a synthesized stub", () => { assert.equal(validateProjectPubspec("").valid, false); }); + +test("reads where a block-form dependency comes from", () => { + const declared = parseExistingDependencies(PROJECT_PUBSPEC); + + // The first own-key is what says whether a package can be reproduced outside + // the project, so it is read rather than inferred from the package's name. + assert.equal(declared.get("flutter").sourceKey, "sdk"); + assert.equal(declared.get("flutter").sourceValue, "flutter"); + assert.equal(declared.get("cloud_firestore").sourceKey, null); + assert.equal(declared.get("cloud_firestore").isScalar, true); +}); + +test("does not read a following sibling dependency's key as the previous entry's source", () => { + const pubspec = `dependencies: + flutter: + sdk: flutter + alpha: + beta: ^2.0.0 +`; + const declared = parseExistingDependencies(pubspec); + + // `alpha` is block form with no mapping under it. Scanning past the entry + // would reach `beta` and attribute its constraint to `alpha`. + assert.equal(declared.get("alpha").isScalar, false); + assert.equal(declared.get("alpha").sourceKey, null); + assert.equal(declared.get("beta").constraint, "^2.0.0"); +}); + +test("a nested version block is read as a constraint, not as a source", () => { + const pubspec = `dependencies: + intl: + version: ^0.20.3 +`; + const declared = parseExistingDependencies(pubspec); + + assert.equal(declared.get("intl").sourceKey, "version"); + assert.equal(declared.get("intl").sourceValue, "^0.20.3"); +}); + +test("a git source keeps only its first key, whatever the nested shape", () => { + const pubspec = `dependencies: + private_thing: + git: + url: https://example.invalid/private.git + ref: main + hosted_thing: + hosted: + name: hosted_thing + url: https://example.invalid + version: ^1.0.0 +`; + const declared = parseExistingDependencies(pubspec); + + assert.equal(declared.get("private_thing").sourceKey, "git"); + assert.equal(declared.get("hosted_thing").sourceKey, "hosted"); +}); + +test("reads a source from dependency_overrides too", () => { + const overrides = parseDependencyBlock( + `dependency_overrides: + flutter_web_plugins: + sdk: flutter +`, + "dependency_overrides", + ); + + assert.equal(overrides.get("flutter_web_plugins").sourceKey, "sdk"); +}); From b28b814a50297d43f1c8b840972a54b5285efcb2 Mon Sep 17 00:00:00 2001 From: Stuart Date: Tue, 22 Sep 2026 15:32:24 +1000 Subject: [PATCH 02/13] ci: gate main with required CI checks and branch protection (STU-345) --- .github/workflows/ci.yml | 52 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 .github/workflows/ci.yml diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..0dcad9b --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,52 @@ +name: CI + +on: + push: + branches: [main] + pull_request: + +jobs: + build-and-test: + runs-on: ubuntu-latest + + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Set up Node.js + uses: actions/setup-node@v4 + with: + node-version-file: '.nvmrc' + cache: 'npm' + + - name: Set up PHP + uses: shivammathur/setup-php@v2 + with: + php-version: '8.3' + + - name: Install dependencies + run: npm ci + + - name: Run tests + run: npm test + + - name: Build production bundle + run: npm run build + + - name: Run deploy guard + run: npm run test:deploy-guard + + - name: Run proxy allowlist tests + run: npm run test:proxies + + - name: Scan production bundle for API key/endpoint leaks + run: | + set -e + echo "Scanning dist/ for leaked provider API endpoints and API key assignments..." + if grep -R --include='*.js' --include='*.html' --include='*.css' -E \ + 'api\.groq\.com|apiKey[[:space:]]*[:=][[:space:]]*["'\'''][^"'\''']+["'\''']' \ + dist/; then + echo "FAIL: Potential provider API key/endpoint leak detected in dist/" + exit 1 + fi + echo "No API key/endpoint leaks found." From f479a9a3b72cfd17954a98a8ecdfb52dba8b8f8d Mon Sep 17 00:00:00 2001 From: Stuart Date: Tue, 22 Sep 2026 15:41:17 +1000 Subject: [PATCH 03/13] fix(ci): avoid shell quoting errors in bundle leak scan --- .github/workflows/ci.yml | 13 ++-------- scripts/scan_bundle_for_leaks.py | 44 ++++++++++++++++++++++++++++++++ 2 files changed, 46 insertions(+), 11 deletions(-) create mode 100755 scripts/scan_bundle_for_leaks.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 0dcad9b..2004d4d 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -6,7 +6,7 @@ on: pull_request: jobs: - build-and-test: + ci: runs-on: ubuntu-latest steps: @@ -40,13 +40,4 @@ jobs: run: npm run test:proxies - name: Scan production bundle for API key/endpoint leaks - run: | - set -e - echo "Scanning dist/ for leaked provider API endpoints and API key assignments..." - if grep -R --include='*.js' --include='*.html' --include='*.css' -E \ - 'api\.groq\.com|apiKey[[:space:]]*[:=][[:space:]]*["'\'''][^"'\''']+["'\''']' \ - dist/; then - echo "FAIL: Potential provider API key/endpoint leak detected in dist/" - exit 1 - fi - echo "No API key/endpoint leaks found." + run: python3 scripts/scan_bundle_for_leaks.py diff --git a/scripts/scan_bundle_for_leaks.py b/scripts/scan_bundle_for_leaks.py new file mode 100755 index 0000000..700615b --- /dev/null +++ b/scripts/scan_bundle_for_leaks.py @@ -0,0 +1,44 @@ +#!/usr/bin/env python3 +import os +import re +import sys + +DIST_DIR = "dist" +PATTERNS = { + "api.groq.com endpoint": re.compile(r"api\.groq\.com"), + "apiKey assignment": re.compile(r"apiKey\s*[:=]\s*['\"][^'\"]+['\"]", re.IGNORECASE), +} + +def main() -> int: + if not os.path.isdir(DIST_DIR): + print(f"{DIST_DIR}/ directory not found; skipping scan.") + return 0 + + leaks = [] + for root, _dirs, files in os.walk(DIST_DIR): + for name in files: + if name.endswith(".map"): + continue + path = os.path.join(root, name) + try: + with open(path, "r", encoding="utf-8", errors="replace") as f: + content = f.read() + except OSError as e: + print(f"WARN: could not read {path}: {e}", file=sys.stderr) + continue + for label, pattern in PATTERNS.items(): + for match in pattern.finditer(content): + snippet = content[max(0, match.start()-20):match.end()+20].replace("\n", " ") + leaks.append((path, label, snippet)) + + if leaks: + print("FAIL: Potential provider API key/endpoint leak detected in dist/", file=sys.stderr) + for path, label, snippet in leaks: + print(f" {path} [{label}]: {snippet}", file=sys.stderr) + return 1 + + print("No API key/endpoint leaks found.") + return 0 + +if __name__ == "__main__": + sys.exit(main()) From bf50a2dbf805740dc7796420d899b2466a900ec7 Mon Sep 17 00:00:00 2001 From: Stuart Date: Tue, 22 Sep 2026 15:53:14 +1000 Subject: [PATCH 04/13] feat(auth): provider-aware plus-alias guard for magic-link sign-in - Add shared authMagicLink helpers with provider allowlist. - Show a non-blocking hint for plus-tagged known-provider addresses. - Pass email through to /auth/send-magic-link and render server codes inline. - Preserve recovery path for existing accounts on plus-tagged addresses. - Add unit tests and fixture matching the backend contract. --- app.js | 24 ++++++++--- src/authMagicLink.js | 43 ++++++++++++++++++++ src/authMagicLink.test.js | 74 ++++++++++++++++++++++++++++++++++ src/authMagicLinkFixtures.json | 13 ++++++ 4 files changed, 148 insertions(+), 6 deletions(-) create mode 100644 src/authMagicLink.js create mode 100644 src/authMagicLink.test.js create mode 100644 src/authMagicLinkFixtures.json diff --git a/app.js b/app.js index ac24de8..4f99ce4 100644 --- a/app.js +++ b/app.js @@ -32,6 +32,12 @@ import { } from "./src/flutterFlowCodeSanitizer.js"; import { formatFlutterFlowFileError } from "./src/flutterFlowFileErrors.js"; import { extractPackageImports } from "./src/dartPackageImports.js"; +import { + explainPlusAliasRule, + getMagicLinkResultMessage, + isKnownProviderPlusAlias, + trimEmail, +} from "./src/authMagicLink.js"; import { planCustomCodeVerification } from "./src/customCodeVerification.js"; import { readProvisionResponse } from "./src/provisionStream.js"; import { buildFlutterFlowSyncMetadata } from "./src/flutterFlowSyncMetadata.js"; @@ -4272,7 +4278,7 @@ async function handleMagicLinkRequest() { const input = document.getElementById('signin-email-input') const btn = document.getElementById('signin-submit-btn') const msg = document.getElementById('signin-message') - const email = input?.value?.trim() + const email = trimEmail(input?.value) const emailRegex = /^[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])?)*$/ if (!email || !emailRegex.test(email) || email.length > 254) { @@ -4281,13 +4287,19 @@ async function handleMagicLinkRequest() { } if (btn) { btn.disabled = true; btn.textContent = 'Sending…' } - if (msg) msg.textContent = '' + + // Explain the rule for known providers, but do not block submission here. + // Existing accounts on plus-tagged addresses are still allowed to recover + // because the server performs the authoritative check. + const plusAliasHint = explainPlusAliasRule(email) + if (msg && plusAliasHint) msg.textContent = plusAliasHint try { - await sendMagicLink(email) - if (input) input.value = '' - if (msg) msg.textContent = `Check your email — we sent a link to ${email}` - if (btn) btn.textContent = 'Sent!' + const data = await sendMagicLink(email) + if (input && data?.code !== 'PLUS_ALIAS_REJECTED') input.value = '' + if (msg) msg.textContent = getMagicLinkResultMessage(data, email) + if (btn) btn.textContent = data?.code === 'PLUS_ALIAS_REJECTED' ? 'Send Link' : 'Sent!' + if (btn && data?.code === 'PLUS_ALIAS_REJECTED') btn.disabled = false } catch (err) { console.error('handleMagicLinkRequest: sendMagicLink failed', { email, err }) if (msg) msg.textContent = 'Something went wrong. Please try again.' diff --git a/src/authMagicLink.js b/src/authMagicLink.js new file mode 100644 index 0000000..84bcc89 --- /dev/null +++ b/src/authMagicLink.js @@ -0,0 +1,43 @@ +const ALLOWLISTED_DOMAINS = new Set([ + 'gmail.com', + 'googlemail.com', + 'outlook.com', + 'hotmail.com', + 'live.com', + 'msn.com' +]); + +export const MAGIC_LINK_SUCCESS_CODE = 'MAGIC_LINK_SENT'; +export const PLUS_ALIAS_REJECTED_CODE = 'PLUS_ALIAS_REJECTED'; + +export function trimEmail(raw) { + return typeof raw === 'string' ? raw.trim() : ''; +} + +export function isKnownProviderPlusAlias(rawEmail) { + const email = trimEmail(rawEmail); + const at = email.lastIndexOf('@'); + if (at <= 0 || at === email.length - 1) return false; + const local = email.slice(0, at); + const domain = email.slice(at + 1).toLowerCase(); + if (!ALLOWLISTED_DOMAINS.has(domain)) return false; + return local.includes('+'); +} + +export function explainPlusAliasRule(rawEmail) { + if (!isKnownProviderPlusAlias(rawEmail)) return null; + const email = trimEmail(rawEmail); + const at = email.lastIndexOf('@'); + const domain = email.slice(at + 1).toLowerCase(); + return `Please enter your primary email address. Plus aliases (such as ${email}) are not allowed for ${domain} accounts.`; +} + +export function getMagicLinkResultMessage(data, email) { + if (data?.code === PLUS_ALIAS_REJECTED_CODE) { + return data.message || explainPlusAliasRule(email) || 'Please enter your primary email address.'; + } + if (data?.code === MAGIC_LINK_SUCCESS_CODE || !data?.code) { + return `Check your email — we sent a link to ${trimEmail(email)}`; + } + return data.message || 'Something went wrong. Please try again.'; +} diff --git a/src/authMagicLink.test.js b/src/authMagicLink.test.js new file mode 100644 index 0000000..95f3c85 --- /dev/null +++ b/src/authMagicLink.test.js @@ -0,0 +1,74 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { + explainPlusAliasRule, + getMagicLinkResultMessage, + isKnownProviderPlusAlias, + trimEmail, +} from "./authMagicLink.js"; + +test("detects plus aliases on allowlisted providers (case-insensitive)", () => { + assert.ok(isKnownProviderPlusAlias("user+tag@gmail.com")); + assert.ok(isKnownProviderPlusAlias("user+tag@GMAIL.COM")); + assert.ok(isKnownProviderPlusAlias("u+alias@googlemail.com")); + assert.ok(isKnownProviderPlusAlias("me+stuff@outlook.com")); + assert.ok(isKnownProviderPlusAlias("me+stuff@hotmail.com")); + assert.ok(isKnownProviderPlusAlias("me+stuff@live.com")); + assert.ok(isKnownProviderPlusAlias("me+stuff@msn.com")); +}); + +test("does not flag untagged allowlisted addresses", () => { + assert.equal(isKnownProviderPlusAlias("user@gmail.com"), false); + assert.equal(isKnownProviderPlusAlias("user@outlook.com"), false); + assert.equal(isKnownProviderPlusAlias("user@googlemail.com"), false); +}); + +test("does not flag plus aliases on custom or unrelated domains", () => { + assert.equal(isKnownProviderPlusAlias("user+tag@example.com"), false); + assert.equal(isKnownProviderPlusAlias("user+tag@company.io"), false); + assert.equal(isKnownProviderPlusAlias("user+tag@subdomain.gmail.com"), false); +}); + +test("trims whitespace before checking", () => { + assert.ok(isKnownProviderPlusAlias(" user+tag@gmail.com ")); + assert.equal(trimEmail(" user@example.com "), "user@example.com"); +}); + +test("explainPlusAliasRule returns an actionable message for blocked aliases", () => { + const msg = explainPlusAliasRule("user+tag@gmail.com"); + assert.ok(msg.includes("primary email address")); + assert.ok(msg.includes("gmail.com")); + assert.ok(msg.includes("user+tag@gmail.com")); +}); + +test("explainPlusAliasRule returns null for non-blocked addresses", () => { + assert.equal(explainPlusAliasRule("user@gmail.com"), null); + assert.equal(explainPlusAliasRule("user+tag@example.com"), null); +}); + +test("getMagicLinkResultMessage maps server codes to inline messages", () => { + assert.equal( + getMagicLinkResultMessage({ code: "MAGIC_LINK_SENT" }, "user@gmail.com"), + "Check your email — we sent a link to user@gmail.com" + ); + + const rejection = { code: "PLUS_ALIAS_REJECTED", message: "Use primary email." }; + assert.equal( + getMagicLinkResultMessage(rejection, "user+tag@gmail.com"), + "Use primary email." + ); + + assert.ok( + getMagicLinkResultMessage( + { code: "PLUS_ALIAS_REJECTED" }, + "user+tag@gmail.com" + ).includes("primary email address") + ); +}); + +test("getMagicLinkResultMessage treats legacy success responses as sent", () => { + assert.equal( + getMagicLinkResultMessage({ message: "Check your email" }, "user@gmail.com"), + "Check your email — we sent a link to user@gmail.com" + ); +}); diff --git a/src/authMagicLinkFixtures.json b/src/authMagicLinkFixtures.json new file mode 100644 index 0000000..b0fa8ea --- /dev/null +++ b/src/authMagicLinkFixtures.json @@ -0,0 +1,13 @@ +{ + "allowlistedDomains": [ + "gmail.com", + "googlemail.com", + "outlook.com", + "hotmail.com", + "live.com", + "msn.com" + ], + "successCode": "MAGIC_LINK_SENT", + "validationCode": "PLUS_ALIAS_REJECTED", + "messageTemplate": "Please enter your primary email address. Plus aliases (such as {email}) are not allowed for {domain} accounts." +} From 50a5c861184b487ceef6c2bdc017137d54425a23 Mon Sep 17 00:00:00 2001 From: Stuart Date: Tue, 22 Sep 2026 17:20:49 +1000 Subject: [PATCH 05/13] fix: classify a block-form dependency by any nested source key, not just the first (cherry picked from commit d5a3c922469ccb5da7bf43e6b378c9d913115a2f) --- .../{index-D4d_RpDK.js => index-DheZmoMN.js} | 134 +++++++++--------- dist/index.html | 2 +- src/customCodeVerification.js | 13 +- src/customCodeVerification.test.js | 26 ++++ src/pubspecSync.js | 56 +++++--- src/pubspecSync.test.js | 58 +++++++- 6 files changed, 195 insertions(+), 94 deletions(-) rename dist/assets/{index-D4d_RpDK.js => index-DheZmoMN.js} (66%) diff --git a/dist/assets/index-D4d_RpDK.js b/dist/assets/index-DheZmoMN.js similarity index 66% rename from dist/assets/index-D4d_RpDK.js rename to dist/assets/index-DheZmoMN.js index efa7947..7722dbb 100644 --- a/dist/assets/index-D4d_RpDK.js +++ b/dist/assets/index-DheZmoMN.js @@ -1,8 +1,8 @@ -(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const n of document.querySelectorAll('link[rel="modulepreload"]'))r(n);new MutationObserver(n=>{for(const i of n)if(i.type==="childList")for(const o of i.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&r(o)}).observe(document,{childList:!0,subtree:!0});function s(n){const i={};return n.integrity&&(i.integrity=n.integrity),n.referrerPolicy&&(i.referrerPolicy=n.referrerPolicy),n.crossOrigin==="use-credentials"?i.credentials="include":n.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function r(n){if(n.ep)return;n.ep=!0;const i=s(n);fetch(n.href,i)}})();var v=typeof window<"u"?window:void 0,we=typeof globalThis<"u"?globalThis:v,ke=we?.navigator,C=we?.document,re=we?.location,Lo=we?.fetch,Ri=we!=null&&we.XMLHttpRequest&&"withCredentials"in new we.XMLHttpRequest?we.XMLHttpRequest:void 0,La=we?.AbortController,ch=we?.CompressionStream,Pe=ke?.userAgent;function Ic(){return!(!v||v.navigator.onLine===!1)}var Fs=typeof globalThis<"u"?globalThis:v;Fs&&typeof self>"u"&&(Fs.self=Fs),Fs&&typeof File>"u"&&(Fs.File=function(){});var $=v??{},Y={DEBUG:!1,LIB_VERSION:"0.5.0",LIB_NAME:"browser-common"};function Oa(t,e,s,r,n,i,o){try{var a=t[i](o),l=a.value}catch(u){return void s(u)}a.done?e(l):Promise.resolve(l).then(r,n)}function X(t){return function(){var e=this,s=arguments;return new Promise((function(r,n){var i=t.apply(e,s);function o(l){Oa(i,r,n,o,a,"next",l)}function a(l){Oa(i,r,n,o,a,"throw",l)}o(void 0)}))}}function w(){return w=Object.assign?Object.assign.bind():function(t){for(var e=1;arguments.length>e;e++){var s=arguments[e];for(var r in s)({}).hasOwnProperty.call(s,r)&&(t[r]=s[r])}return t},w.apply(null,arguments)}function Cc(t,e){if(t==null)return{};var s={};for(var r in t)if({}.hasOwnProperty.call(t,r)){if(e.indexOf(r)!==-1)continue;s[r]=t[r]}return s}var Da=t=>{if(typeof t!="string")return t;try{return JSON.parse(t)}catch{return t}};function Ba(t){return typeof t=="string"||t}function ja(t){return typeof t=="string"?t:void 0}var Ps,uh=["$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})({}),Ua=(function(t){return t.GZipJS="gzip-js",t.Base64="base64",t})({}),dh=["$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"],hh=["token"],Fc="NativeGzipValidationError",Ti=t=>t.length>=2&&t[0]===31&&t[1]===139,Ha=(t,e)=>t===Ua.GZipJS||e===Ua.GZipJS||e==="gzip",Wa=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=Fc,e},ph=(function(){var t=X((function*(e,s){18>e.size&&wr("too-short");var r=new Uint8Array(yield e.slice(0,10).arrayBuffer());Ti(r)&&r[2]===8||wr("invalid-header");var n=new DataView(yield e.slice(e.size-8).arrayBuffer());n.getUint32(0,!0)!==(o=>{for(var a=(()=>{if(Ps)return Ps;Ps=[];for(var c=0;256>c;c++){for(var d=c,h=0;8>h;h++)d=1&d?3988292384^d>>>1:d>>>1;Ps[c]=d>>>0}return Ps})(),l=4294967295,u=0;o.length>u;u++)l=a[255&(l^o[u])]^l>>>8;return(4294967295^l)>>>0})(s)&&wr("invalid-crc");var i=s.length>>>0;n.getUint32(4,!0)!==i&&wr("invalid-size")}));return function(e,s){return t.apply(this,arguments)}})();function Ni(){return Ni=X((function*(t,e,s){e===void 0&&(e=!0);try{var r=new TextEncoder().encode(t),n=new globalThis.CompressionStream("gzip"),i=n.writable.getWriter(),o=i.write(r).then((()=>i.close())).catch((function(){var u=X((function*(c){try{yield i.abort(c)}catch{}throw c}));return function(c){return u.apply(this,arguments)}})()),a=new Response(n.readable).blob(),l=(yield Promise.all([a,o]))[0];return yield ph(l,r),l}catch(u){if(s!=null&&s.rethrow)throw u;return e&&console.error("Failed to gzip compress data",u),null}})),Ni.apply(this,arguments)}var fh=["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"],za=function(t,e){if(e===void 0&&(e=[]),!t)return!1;var s=t.toLowerCase();return fh.concat(e).some((r=>{var n=r.toLowerCase();return s.indexOf(n)!==-1}))};function M(t,e){return t.indexOf(e)!==-1}var An=function(t){return t.trim()},Mi=function(t){return t.replace(/^\$/,"")};function Pc(t){var e,s=[];return(e=JSON.stringify(t,(function(r,n){if(typeof n=="bigint")return n.toString();if(typeof n!="function"&&typeof n!="symbol"){if(n instanceof Error)return{name:n.name,message:n.message,stack:n.stack};if(n&&typeof n=="object"){for(;s.length>0&&s[s.length-1]!==this;)s.pop();if(s.includes(n))return"[Circular]";s.push(n)}return n}})))!==null&&e!==void 0?e:"null"}var Ac=Object.prototype,$c=Ac.hasOwnProperty,$n=Ac.toString,L=Array.isArray||function(t){return $n.call(t)==="[object Array]"},Se=t=>typeof t=="function",te=t=>t===Object(t)&&!L(t),mt=t=>{if(te(t)){for(var e in t)if($c.call(t,e))return!1;return!0}return!1},x=t=>t===void 0,W=t=>$n.call(t)=="[object String]",Li=t=>W(t)&&t.trim().length===0,$e=t=>t===null,D=t=>x(t)||$e(t),he=t=>$n.call(t)=="[object Number]"&&t==t,lt=t=>he(t)&&t>0,Ke=t=>$n.call(t)==="[object Boolean]",gh=t=>t instanceof FormData,mh=t=>M(dh,t),vh=t=>M(hh,t);function Rc(t){return t===null||typeof t!="object"}function Vr(t,e){return{}.toString.call(t)==="[object "+e+"]"}function Oo(t){return typeof Event<"u"&&Tc(t,Event)}function Tc(t,e){try{return t instanceof e}catch{return!1}}var _h=[!0,"true",1,"1","yes"],Xn=t=>M(_h,t),yh=[!1,"false",0,"0","no"];function rt(t,e,s,r,n){return e>s&&(r.warn("min cannot be greater than max."),e=s),he(t)?t>s?(r.warn(" cannot be greater than max: "+s+". Using max value instead."),s):e>t?(r.warn(" cannot be less than min: "+e+". Using min value instead."),e):t:(r.warn(" must be a number. using max or fallback. max: "+s+", fallback: "+n),rt(n||s,e,s,r))}class wh{constructor(e){this.tt={},this.et=e.et,this.it=rt(e.bucketSize,0,100,e.rt),this.nt=rt(e.refillRate,0,this.it,e.rt),this.st=rt(e.refillInterval,0,864e5,e.rt)}ot(e,s){var r=Math.floor((s-e.lastAccess)/this.st);r>0&&(e.tokens=Math.min(e.tokens+r*this.nt,this.it),e.lastAccess=e.lastAccess+r*this.st)}consumeRateLimit(e){var s,r=Date.now(),n=String(e),i=this.tt[n];return i?this.ot(i,r):this.tt[n]=i={tokens:this.it,lastAccess:r},i.tokens===0||(i.tokens--,i.tokens===0&&((s=this.et)==null||s.call(this,e)),i.tokens===0)}stop(){this.tt={}}}var Oe="Mobile",Gr="iOS",vt="Android",fs="Tablet",Nc=vt+" "+fs,Mc="iPad",Lc="Apple",Oc=Lc+" Watch",Vs="Safari",gs="BlackBerry",Dc="Samsung",Bc=Dc+"Browser",jc=Dc+" Internet",Gt="Chrome",bh=Gt+" OS",Uc=Gt+" "+Gr,Do="Internet Explorer",Hc=Do+" "+Oe,Bo="Opera",Eh=Bo+" Mini",jo="Edge",Wc="Microsoft "+jo,ds="Firefox",zc=ds+" "+Gr,tr="Nintendo",sr="PlayStation",hs="Xbox",qc=vt+" "+Oe,Vc=Oe+" "+Vs,Bs="Windows",Oi=Bs+" Phone",qa="Nokia",Di="Ouya",Gc="Generic",Sh=Gc+" "+Oe.toLowerCase(),Kc=Gc+" "+fs.toLowerCase(),Bi="Konqueror",Jc="Oculus Browser",Kr="Vivaldi",Yc="Yandex",Jr="Whale",ji="DuckDuckGo",Zc="Pale Moon",Yr="Waterfox",Gs="Brave",Xc="Google Search App",le="(\\d+(\\.\\d+)?)",Qn=new RegExp("Version/"+le),xh=new RegExp(hs,"i"),kh=new RegExp(sr+" \\w+","i"),Ih=new RegExp(tr+" \\w+","i"),Uo=new RegExp(gs+"|PlayBook|BB10","i"),Ch={"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"},Qc=function(t,e,s,r){e=e||"";var n=(function(i){return i!=null&&i.brave?Gs:null})(s);return n||(r!=null&&r.detectGoogleSearchApp&&M(t,"GSA/")?Xc:M(t," OPR/")&&M(t,"Mini")?Eh:M(t," OPR/")?Bo:Uo.test(t)?gs:M(t,"IE"+Oe)||M(t,"WPDesktop")?Hc:M(t,"OculusBrowser")?Jc:M(t,Bc)?jc:M(t,jo)||M(t,"Edg/")?Wc:M(t,Kr+"/")?Kr:M(t,"YaBrowser/")?Yc:M(t,Jr+"/")?Jr:M(t,ji+"/")||M(t,"Ddg/")?ji:M(t,"FBIOS")?"Facebook "+Oe:M(t,"UCWEB")||M(t,"UCBrowser")?"UC Browser":M(t,"CriOS")?Uc:M(t,"CrMo")||M(t,Gt)?Gt:M(t,vt)&&M(t,Vs)?qc:M(t,"FxiOS")?zc:M(t.toLowerCase(),Bi.toLowerCase())?Bi:M(t,Gs+"/")?Gs:((i,o)=>o&&M(o,Lc)||(function(a){return M(a,Vs)&&!M(a,Gt)&&!M(a,vt)})(i))(t,e)?M(t,Oe)?Vc:Vs:M(t,"PaleMoon/")?Zc:M(t,Yr+"/")?Yr:M(t,ds)?ds:M(t,"MSIE")||M(t,"Trident/")?Do:M(t,"Gecko")?ds:"")},Fh={[Hc]:[new RegExp("rv:"+le)],[Wc]:[new RegExp(jo+"?\\/"+le)],[Gt]:[new RegExp("("+Gt+"|CrMo)\\/"+le)],[Uc]:[new RegExp("CriOS\\/"+le)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+le)],[Vs]:[Qn],[Vc]:[Qn],[Bo]:[new RegExp("(Opera|OPR)\\/"+le)],[ds]:[new RegExp(ds+"\\/"+le)],[zc]:[new RegExp("FxiOS\\/"+le)],[Bi]:[new RegExp("Konqueror[:/]?"+le,"i")],[gs]:[new RegExp(gs+" "+le),Qn],[qc]:[new RegExp("android\\s"+le,"i")],[jc]:[new RegExp(Bc+"\\/"+le)],[Jc]:[new RegExp("OculusBrowser\\/"+le)],[Kr]:[new RegExp(Kr+"\\/"+le)],[Yc]:[new RegExp("YaBrowser\\/"+le)],[Jr]:[new RegExp(Jr+"\\/"+le)],[Gs]:[new RegExp(Gs+"\\/"+le)],[ji]:[new RegExp("(DuckDuckGo|Ddg)\\/"+le)],[Zc]:[new RegExp("PaleMoon\\/"+le)],[Yr]:[new RegExp(Yr+"\\/"+le)],[Xc]:[new RegExp("GSA\\/"+le)],[Do]:[new RegExp("(rv:|MSIE )"+le)],Mozilla:[new RegExp("rv:"+le)]},Ph=function(t,e,s,r){var n=Qc(t,e,s,r),i=Fh[n];if(x(i))return null;for(var o=0;i.length>o;o++){var a=t.match(i[o]);if(a)return parseFloat(a[a.length-2])}return null},Va=[[new RegExp(hs+"; "+hs+" (.*?)[);]","i"),t=>[hs,t&&t[1]||""]],[new RegExp(tr,"i"),[tr,""]],[new RegExp(sr,"i"),[sr,""]],[Uo,[gs,""]],[new RegExp(Bs,"i"),(t,e)=>{if(/Phone/.test(e)||/WPDesktop/.test(e))return[Oi,""];if(new RegExp(Oe).test(e)&&!/IEMobile\b/.test(e))return[Bs+" "+Oe,""];var s=/Windows NT ([0-9.]+)/i.exec(e);if(s&&s[1]){var r=Ch[s[1]]||"";return/arm/i.test(e)&&(r="RT"),[Bs,r]}return[Bs,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,t=>t&&t[3]?[Gr,[t[3],t[4],t[5]||"0"].join(".")]:[Gr,""]],[/(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i,t=>{var e="";return t&&t.length>=3&&(e=x(t[2])?t[3]:t[2]),["watchOS",e]}],[new RegExp("("+vt+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+vt+")","i"),t=>t&&t[2]?[vt,[t[2],t[3],t[4]||"0"].join(".")]:[vt,""]],[/Mac OS X (\d+)[_.](\d+)[_.]?(\d+)?/i,t=>{var e=["Mac OS X",""];return t&&t[1]&&(e[1]=[t[1],t[2],t[3]||"0"].join(".")),e}],[/Mac/i,["Mac OS X",""]],[/CrOS/,[bh,""]],[/Linux|debian/i,["Linux",""]]],Ga=function(t){return Ih.test(t)?tr:kh.test(t)?sr:xh.test(t)?hs:new RegExp(Di,"i").test(t)?Di:new RegExp("("+Oi+"|WPDesktop)","i").test(t)?Oi:/iPad/.test(t)?Mc:/iPod/.test(t)?"iPod Touch":/iPhone/.test(t)?"iPhone":/(watch)(?: ?os[,/]|\d,\d\/)[\d.]+/i.test(t)?Oc:Uo.test(t)?gs:/(kobo)\s(ereader|touch)/i.test(t)?"Kobo":new RegExp(qa,"i").test(t)?qa:/(kf[a-z]{2}wi|aeo[c-r]{2})( bui|\))/i.test(t)||/(kf[a-z]+)( bui|\)).+silk\//i.test(t)?"Kindle Fire":/(Android|ZTE)/i.test(t)?new RegExp(Oe).test(t)&&!/(9138B|TB782B|Nexus [97]|pixel c|HUAWEISHT|BTV|noble nook|smart ultra 6)/i.test(t)||/pixel[\daxl ]{1,6}/i.test(t)&&!/pixel c/i.test(t)||/(huaweimed-al00|tah-|APA|SM-G92|i980|zte|U304AA)/i.test(t)||/lmy47v/i.test(t)&&!/QTAQZ3/i.test(t)?vt:Nc:new RegExp("(pda|"+Oe+")","i").test(t)?Sh:new RegExp(fs,"i").test(t)&&!new RegExp(fs+" pc","i").test(t)?Kc:""},Ah=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Ka(t,e){return typeof(s=t)=="string"&&Ah.test(s)?t:e();var s}function Ct(t){return t&&t.split("#")[0]}function Ho(t,e){var s=setTimeout(t,e);return s?.unref&&s?.unref(),s}function Ja(t,e,s){return eu.apply(this,arguments)}function eu(){return(eu=X((function*(t,e,s){var r;try{return yield Promise.race([t,new Promise(((n,i)=>{r=Ho((()=>{try{s?.(),n()}catch(o){i(o)}}),e)}))])}finally{clearTimeout(r)}}))).apply(this,arguments)}var $h=t=>t instanceof Error,tu={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}},Rh=tu.info;function su(t){if(Ke(t))return{boolValue:t};if(typeof t=="number")return Number.isFinite(t)?Number.isInteger(t)?{intValue:t}:{doubleValue:t}:{stringValue:String(t)};if(typeof t=="string")return{stringValue:t};if(L(t))return{arrayValue:{values:t.map((e=>su(e)))}};try{return{stringValue:JSON.stringify(t)}}catch{return{stringValue:String(t)}}}function Zr(t){var e=[];for(var s in t){var r=t[s];$e(r)||x(r)||e.push({key:s,value:su(r)})}return e}function Th(t,e){var s=tu[t.level||"info"]||Rh,r=s.text,n=s.number,i=String(Date.now())+"000000",o={};e.distinctId&&(o.posthogDistinctId=e.distinctId),e.sessionId&&(o.sessionId=e.sessionId),e.windowId&&(o["window.id"]=e.windowId),D(e.sessionStartTimestamp)||(o.sessionStartTimestamp=String(e.sessionStartTimestamp)),D(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=w({},o,t.attributes||{}),l={timeUnixNano:i,observedTimeUnixNano:i,severityNumber:n,severityText:r,body:{stringValue:t.body},attributes:Zr(a)};return t.trace_id&&(l.traceId=t.trace_id),t.span_id&&(l.spanId=t.span_id),x(t.trace_flags)||(l.flags=t.trace_flags),l}function ru(t,e,s){return w({},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":s})}function nu(t,e,s,r){return{resourceLogs:[{resource:{attributes:Zr(e)},scopeLogs:[{scope:{name:s,version:r},logRecords:t}]}]}}let Nh=class{constructor(t,e,s,r,n,i,o){var a;i===void 0&&(i=()=>Promise.resolve()),this._instance=t,this.Ne=e,this.rt=s,this.ut=r,this.ht=n,this.dt=i,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 s={record:Th(e,this.ut())};this.ht((()=>this.At(s)))}}else this.rt.info("Log was rejected in beforeSend function")}}Pt(t){var e=this.Ne.beforeSend;if(!e)return t;var s=L(e)?e:[e],r=t;for(var n of s)try{var i=n(r);if(!i)return this.rt.info("Log was rejected in beforeSend function"),null;r=i}catch(o){return this.rt.error("Error in beforeSend function for log:",o),null}return r}Rt(){if(this.Tt===void 0)return!0;var t=Date.now(),e=t-this.bt;return this.Mt>e&&e>=0||(this.bt=t,this._t=0,this.wt=!1),this.Tt>this._t?(this._t++,!0):(this.wt||(this.rt.warn("captureLog dropping logs: exceeded "+this.Tt+" logs per "+this.Mt+"ms"),this.wt=!0),!1)}flush(){var t=this;return X((function*(){if(!t._instance.isDisabled)return t.ct||(t.ct=t.Ft().finally((()=>{t.ct=null}))),t.ct}))()}Ft(){var t=this;return X((function*(){var e;t.Et();var s=(e=t._instance.getPersistedProperty(ut.LogsQueue))!==null&&e!==void 0?e:[];if(s.length!==0)for(var r=s.length,n=0;s.length>0&&r>n;){var i,o;t.ft=0;var a=Math.min(s.length,t.Ct),l=s.slice(0,a),u=nu(l.map((d=>d.record)),t.Lt(),(i=t.vt)!==null&&i!==void 0?i: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),s=(o=t._instance.getPersistedProperty(ut.LogsQueue))!==null&&o!==void 0?o:[],n+=l.length,c.kind==="fatal"))throw c.error}}))()}Dt(t){var e=this;return X((function*(){var s,r=Math.max(0,t-e.ft),n=(s=e._instance.getPersistedProperty(ut.LogsQueue))!==null&&s!==void 0?s:[];e._instance.setPersistedProperty(ut.LogsQueue,n.slice(r)),yield e.dt()}))()}Lt(){return ru(this.Ne,this._instance.getLibraryId(),this._instance.getLibraryVersion())}At(t){var e;if(!this._instance.optedOut){var s=(e=this._instance.getPersistedProperty(ut.LogsQueue))!==null&&e!==void 0?e:[];this.xt>s.length||(s.shift(),this.ft++,this.rt.info("Logs queue is full, dropping oldest record.")),s.push(t),this._instance.setPersistedProperty(ut.LogsQueue,s),this.kt>s.length?this.$t():this.It()}}$t(t){t===void 0&&(t=this.St),this.Nt||(this.Nt=Ho((()=>{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 X((function*(){e.Et();var s=e.flush().catch((()=>{}));t!==void 0?yield Ja(s,t):yield s}))()}flushWithTimeout(t){var e=this;return X((function*(){var s=e.flush();yield Ja(s,t,(()=>{s.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 ei=[0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4];function Ya(t){return String(t)+"000000"}function Za(t,e,s,r){var n="";return r&&(n=Object.keys(r).sort().map((i=>JSON.stringify(i)+":"+JSON.stringify(r[i]))).join(",")),t+"\0"+e+"\0"+(s??"")+"\0"+n}let Mh=class{constructor(t,e,s){this._instance=t,this.Ne=e,this.rt=s,this.Bt=new Map,this.ct=null,this.Ht=!1,this.Ut=new Map,this.zt=new Set,this.Wt=0}count(t,e,s){e===void 0&&(e=1),this.Vt({name:t,type:"count",value:e,unit:s?.unit,attributes:s?.attributes})}gauge(t,e,s){this.Vt({name:t,type:"gauge",value:e,unit:s?.unit,attributes:s?.attributes})}histogram(t,e,s){this.Vt({name:t,type:"histogram",value:e,unit:s?.unit,attributes:s?.attributes})}flush(){var t=this,e=this.ct,s=(function(){var n=X((function*(){e&&(yield e.catch((()=>{}))),yield t.Zt()}));return function(){return n.apply(this,arguments)}})(),r=s().finally((()=>{this.ct===r&&(this.ct=null)}));return this.ct=r,r}drainWindow(){if(this.Bt.size===0)return null;var t=this.Bt;return this.Bt=new Map,this.Ht=!1,this.Ut=new Map,this.zt=new Set,this.Gt(t)}reset(){this.Wt++,this.Et(),this.Bt=new Map,this.ct=null,this.Ht=!1,this.Ut=new Map,this.zt=new Set}Vt(t){if(!this._instance.isDisabled&&!this._instance.optedOut){var e=this.Pt(t);if(e!==null)if(e.name&&typeof e.name=="string")if(typeof e.value=="number"&&Number.isFinite(e.value))if(e.type==="count"&&0>e.value)this.rt.warn("Dropping count '"+e.name+"': counters are monotonic, value must be >= 0");else{var s,r;try{s=e.attributes?w({},e.attributes):void 0,r=Za(e.type,e.name,e.unit,s)}catch(o){return void this.rt.warn("Dropping metric '"+e.name+"': attributes could not be serialized",o)}var n=this.Bt.get(r);if(!n){if(!this.Qt())return;n={name:e.name,type:e.type,unit:e.unit,attributes:s,windowStartMs:Date.now()},this.Bt.set(r,n)}var i=this.Ut.get(e.name);i===void 0?this.Ut.set(e.name,e.type):i===e.type||this.zt.has(e.name)||(this.zt.add(e.name),this.rt.warn("Metric name '"+e.name+"' is already used as a "+i+"; recording it as a "+e.type+" too will blend both series in charts. Use a distinct name.")),this.Kt(n,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 s;switch(t.type){case"count":t.total=((s=t.total)!==null&&s!==void 0?s: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(ei.length+1).fill(0)});var r=t.hist;r.count+=1,r.sum+=e,r.min=Math.min(r.min,e),r.max=Math.max(r.max,e),r.bucketCounts[(function(n,i){for(var o=0;i.length>o;o++)if(i[o]>=n)return o;return i.length})(e,ei)]+=1}}Pt(t){var e=this.Ne.beforeSend;if(!e)return t;var s=L(e)?e:[e],r=t;for(var n of s)try{var i=n(r);if(!i)return this.rt.info("Metric was rejected in beforeSend function"),null;r=i}catch(o){return this.rt.error("Error in beforeSend function for metric:",o),null}return r}$t(){this.Nt||(this.Nt=Ho((()=>{this.Nt=void 0,this.flush().catch((t=>{this.rt.error("Metrics flush failed:",t)}))}),this.Ne.flushIntervalMs))}Et(){this.Nt&&(clearTimeout(this.Nt),this.Nt=void 0)}Zt(){var t=this;return X((function*(){if(t.Bt.size!==0){var e=t.Bt;t.Bt=new Map,t.Ht=!1,t.Ut=new Map,t.zt=new Set;var s=t.Wt,r=yield t._instance.Jt(t.Gt(e));if(s===t.Wt)switch(r.kind){case"ok":return;case"retry-later":return t.Yt(e),void t.$t();case"too-large":return void t.rt.warn("Metrics batch exceeded the server size limit and was dropped");case"fatal":return void t.rt.error("Failed to send metrics batch:",r.error)}}}))()}Gt(t){return e=this.Xt(t),s=(function(i,o,a){return w({},i.resourceAttributes,{"service.name":i.serviceName||"unknown_service"},i.environment&&{"deployment.environment":i.environment},i.serviceVersion&&{"service.version":i.serviceVersion},{"telemetry.sdk.name":o,"telemetry.sdk.version":a})})(this.Ne,this._instance.getLibraryId(),this._instance.getLibraryVersion()),r=this._instance.getLibraryId(),n=this._instance.getLibraryVersion(),{resourceMetrics:[{resource:{attributes:Zr(s)},scopeMetrics:[{scope:{name:r,version:n},metrics:e}]}]};var e,s,r,n}Xt(t){var e=Ya(Date.now()),s=new Map;for(var r of t.values()){var n,i=Za(r.type,r.name,r.unit,void 0),o=s.get(i);o||(o=w({name:r.name},r.unit&&{unit:r.unit}),r.type==="count"?o.sum={aggregationTemporality:1,isMonotonic:!0,dataPoints:[]}:r.type==="gauge"?o.gauge={dataPoints:[]}:o.histogram={aggregationTemporality:1,dataPoints:[]},s.set(i,o));var a=Zr((n=r.attributes)!==null&&n!==void 0?n:{}),l=Ya(r.windowStartMs);if(r.type==="count"){var u,c={attributes:a,startTimeUnixNano:l,timeUnixNano:e,asDouble:(u=r.total)!==null&&u!==void 0?u:0};o.sum.dataPoints.push(c)}else if(r.type==="gauge"){var d,h={attributes:a,timeUnixNano:e,asDouble:(d=r.last)!==null&&d!==void 0?d:0};o.gauge.dataPoints.push(h)}else r.hist&&o.histogram.dataPoints.push({attributes:a,startTimeUnixNano:l,timeUnixNano:e,count:r.hist.count,sum:r.hist.sum,min:r.hist.min,max:r.hist.max,bucketCounts:r.hist.bucketCounts,explicitBounds:ei})}return Array.from(s.values())}Yt(t){var e,s;for(var r of t){var n=r[0],i=r[1],o=this.Bt.get(n);if(o)switch(o.windowStartMs=Math.min(o.windowStartMs,i.windowStartMs),o.type){case"count":o.total=((e=o.total)!==null&&e!==void 0?e:0)+((s=i.total)!==null&&s!==void 0?s:0);break;case"gauge":break;case"histogram":if(i.hist)if(o.hist){o.hist.count+=i.hist.count,o.hist.sum+=i.hist.sum,o.hist.min=Math.min(o.hist.min,i.hist.min),o.hist.max=Math.max(o.hist.max,i.hist.max);for(var a=0;o.hist.bucketCounts.length>a;a++)o.hist.bucketCounts[a]+=i.hist.bucketCounts[a]}else o.hist=i.hist}else this.Qt()&&this.Bt.set(n,i)}}};var br,Xa,ti;function Lh(t){var e=globalThis._posthogChunkIds;if(e){var s=Object.keys(e);return ti&&s.length===Xa||(Xa=s.length,ti=s.reduce(((r,n)=>{br||(br={});var i=br[n];if(i)r[i[0]]=i[1];else for(var o=t(n),a=o.length-1;a>=0;a--){var l=o[a],u=l?.filename,c=e[n];if(u&&c){r[u]=c,br[n]=[u,c];break}}return r}),{})),ti}}class Oh{constructor(e,s,r){r===void 0&&(r=[]),this.coercers=e,this.stackParser=s,this.modifiers=r}buildFromUnknown(e,s){s===void 0&&(s={});var r=s&&s.mechanism||{handled:!0,type:"generic"},n=this.buildCoercingContext(r,s,0).apply(e),i=this.buildParsingContext(s),o=this.parseStacktrace(n,i);return{$exception_list:this.convertToExceptionList(o,r),$exception_level:"error"}}modifyFrames(e){var s=this;return X((function*(){for(var r of e)r.stacktrace&&r.stacktrace.frames&&L(r.stacktrace.frames)&&(r.stacktrace.frames=yield s.applyModifiers(r.stacktrace.frames));return e}))()}coerceFallback(e){var s;return{type:"Error",value:"Unknown error",stack:(s=e.syntheticException)==null?void 0:s.stack,synthetic:!0}}parseStacktrace(e,s){var r,n;return e.cause!=null&&(r=this.parseStacktrace(e.cause,s)),e.stack!=""&&e.stack!=null&&(n=this.applyChunkIds(this.stackParser(e.stack,e.synthetic?s.skipFirstLines:0),s.chunkIdMap)),w({},e,{cause:r,stack:n})}applyChunkIds(e,s){return e.map((r=>(r.filename&&s&&(r.chunk_id=s[r.filename]),r)))}applyCoercers(e,s){for(var r of this.coercers)if(r.match(e))return r.coerce(e,s);return this.coerceFallback(s)}applyModifiers(e){var s=this;return X((function*(){var r=e;for(var n of s.modifiers)r=yield n(r);return r}))()}convertToExceptionList(e,s){var r,n,i,o={type:e.type,value:e.value,mechanism:{type:(r=s.type)!==null&&r!==void 0?r:"generic",handled:(n=s.handled)===null||n===void 0||n,synthetic:(i=e.synthetic)!==null&&i!==void 0&&i}};e.stack&&(o.stacktrace={type:"raw",frames:e.stack});var a=[o];return e.cause!=null&&a.push(...this.convertToExceptionList(e.cause,w({},s,{handled:!0}))),a}buildParsingContext(e){var s;return{chunkIdMap:Lh(this.stackParser),skipFirstLines:(s=e.skipFirstLines)!==null&&s!==void 0?s:1}}buildCoercingContext(e,s,r){r===void 0&&(r=0);var n=(i,o)=>{if(4>=o){var a=this.buildCoercingContext(e,s,o);return this.applyCoercers(i,a)}};return w({},s,{syntheticException:r==0?s.syntheticException:void 0,mechanism:e,apply:i=>n(i,r),next:i=>n(i,r+1)})}}var ms="?";function Ui(t,e,s,r,n){var i={platform:t,filename:e,function:s===""?ms:s,in_app:!0};return x(r)||(i.lineno=r),x(n)||(i.colno=n),i}var iu=(t,e)=>{var s=t.indexOf("safari-extension")!==-1,r=t.indexOf("safari-web-extension")!==-1;return s||r?[t.indexOf("@")!==-1?t.split("@")[0]:ms,s?"safari-extension:"+e:"safari-web-extension:"+e]:[t,e]},Dh=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,Bh=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,jh=/\((\S*)(?::(\d+))(?::(\d+))\)/,Uh=(t,e)=>{var s=Dh.exec(t);if(s)return Ui(e,s[1],ms,+s[2],+s[3]);var r=Bh.exec(t);if(r){if(r[2]&&r[2].indexOf("eval")===0){var n=jh.exec(r[2]);n&&(r[2]=n[1],r[3]=n[2],r[4]=n[3])}var i=iu(r[1]||ms,r[2]);return Ui(e,i[1],i[0],r[3]?+r[3]:void 0,r[4]?+r[4]:void 0)}},Hh=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,Wh=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,zh=(t,e)=>{var s=Hh.exec(t);if(s){if(s[3]&&s[3].indexOf(" > eval")>-1){var r=Wh.exec(s[3]);r&&(s[1]=s[1]||"eval",s[3]=r[1],s[4]=r[2],s[5]="")}var n=s[3],i=s[1]||ms,o=iu(i,n);return Ui(e,n=o[1],i=o[0],s[4]?+s[4]:void 0,s[5]?+s[5]:void 0)}},Qa=/\(error: (.*)\)/;class qh{match(e){return this.isDOMException(e)||this.isDOMError(e)}coerce(e,s){var r=W(e.stack);return{type:this.getType(e),value:this.getValue(e),stack:r?e.stack:void 0,cause:e.cause?s.next(e.cause):void 0,synthetic:!1}}getType(e){return this.isDOMError(e)?"DOMError":"DOMException"}getValue(e){var s=e.name||(this.isDOMError(e)?"DOMError":"DOMException");return e.message?s+": "+e.message:s}isDOMException(e){return Vr(e,"DOMException")}isDOMError(e){return Vr(e,"DOMError")}}class Vh{match(e){return(function(s){switch({}.toString.call(s)){case"[object Error]":case"[object Exception]":case"[object DOMException]":case"[object DOMError]":case"[object WebAssembly.Exception]":return!0;default:return Tc(s,Error)}})(e)}coerce(e,s){return{type:this.getType(e),value:this.getMessage(e,s),stack:this.getStack(e),cause:e.cause?s.next(e.cause):void 0,synthetic:!1}}getType(e){return e.name||e.constructor.name}getMessage(e,s){var r=e.message;return String(r.error&&typeof r.error.message=="string"?r.error.message:r)}getStack(e){return e.stacktrace||e.stack||void 0}}class Gh{constructor(){}match(e){return!!Vr(e,"ErrorEvent")&&(e.error!=null||this.fe(e))}coerce(e,s){var r;if(e.error!=null)return s.apply(e.error);var n=s.apply(e.message);return w({},n,{stack:(r=this.pe(e))!==null&&r!==void 0?r:n.stack,synthetic:!0})}fe(e){return W(e.message)&&e.message.length>0}pe(e){var s=e;if(W(s.filename)&&s.filename.length>0){var r,n,i=(r=s.lineno)!==null&&r!==void 0?r:0,o=(n=s.colno)!==null&&n!==void 0?n:0;return`Error - at `+s.filename+":"+i+":"+o}}}var Kh=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;class Jh{match(e){return typeof e=="string"}coerce(e,s){var r,n=this.getInfos(e),i=n[0],o=n[1];return{type:i??"Error",value:o??e,stack:(r=s.syntheticException)==null?void 0:r.stack,synthetic:!0}}getInfos(e){var s="Error",r=e,n=e.match(Kh);return n&&(s=n[1],r=n[2]),[s,r]}}var Yh=["fatal","error","warning","log","info","debug"];function ou(t,e){e===void 0&&(e=40);var s=Object.keys(t);if(s.sort(),!s.length)return"[object has no keys]";for(var r=s.length;r>0;r--){var n=s.slice(0,r).join(", ");if(e>=n.length)return r===s.length?n:n.length>e?n.slice(0,e)+"...":n}return""}class Zh{match(e){return typeof e=="object"&&e!==null}coerce(e,s){var r,n,i=this.getErrorPropertyFromObject(e);return i?s.apply(i):{type:this.getType(e),value:this.getValue(e),stack:(r=this.getStack(e))!==null&&r!==void 0?r:(n=s.syntheticException)==null?void 0:n.stack,level:this.isSeverityLevel(e.level)?e.level:"error",synthetic:!0}}getType(e){return Oo(e)?e.constructor.name:"Error"}getValue(e){if("name"in e&&typeof e.name=="string"){var s="'"+e.name+"' captured as exception";return"message"in e&&typeof e.message=="string"&&(s+=" with message: '"+e.message+"'"),s}if("message"in e&&typeof e.message=="string")return e.message;var r=this.getObjectClassName(e);return(r&&r!=="Object"?"'"+r+"'":"Object")+" captured as exception with keys: "+ou(e)}isSeverityLevel(e){return W(e)&&!Li(e)&&Yh.indexOf(e)>=0}getStack(e){try{return W(e.stacktrace)&&e.stacktrace.length>0?e.stacktrace:W(e.stack)&&e.stack.length>0?e.stack:void 0}catch{return}}getErrorPropertyFromObject(e){for(var s in e)if({}.hasOwnProperty.call(e,s)){var r=e[s];if($h(r))return r}}getObjectClassName(e){try{var s=Object.getPrototypeOf(e);return s?s.constructor.name:void 0}catch{return}}}class Xh{match(e){return Oo(e)}coerce(e,s){var r,n=e.constructor.name;return{type:n,value:n+" captured as exception with keys: "+ou(e),stack:(r=s.syntheticException)==null?void 0:r.stack,synthetic:!0}}}class Qh{match(e){return Rc(e)}coerce(e,s){var r;return{type:"Error",value:"Primitive value captured as exception: "+String(e),stack:(r=s.syntheticException)==null?void 0:r.stack,synthetic:!0}}}class ep{match(e){return Vr(e,"PromiseRejectionEvent")||this.isCustomEventWrappingRejection(e)}isCustomEventWrappingRejection(e){if(!Oo(e))return!1;try{var s=e.detail;return s!=null&&typeof s=="object"&&"reason"in s}catch{return!1}}coerce(e,s){var r,n=this.getUnhandledRejectionReason(e);return Rc(n)?{type:"UnhandledRejection",value:"Non-Error promise rejection captured with value: "+String(n),stack:(r=s.syntheticException)==null?void 0:r.stack,synthetic:!0}:s.apply(n)}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 Xr="$message",Qr="$timestamp",tp=new Set([Xr,Qr]),si={enabled:!0,max_bytes:32768};function en(t){var e;return t?{enabled:(e=t.enabled)!==null&&e!==void 0?e:si.enabled,max_bytes:rp(t.max_bytes,si.max_bytes)}:w({},si)}class sp{constructor(e){this.Ke=[],this.Je=0,this.Ne=en(e)}setConfig(e){this.Ne=en(e),this.Xe()}add(e){var s=(function(n){var i;try{i=Pc(n)}catch{return}try{var o=JSON.parse(i);if(!te(o))return;var a=o,l=a[Xr],u=a[Qr];return!W(l)||l.trim().length===0||!W(u)&&!he(u)?void 0:{step:a,json:i}}catch{return}})(e);if(s){var r=(function(n){if(typeof TextEncoder<"u")return new TextEncoder().encode(n).length;for(var i=encodeURIComponent(n),o=0,a=0;i.length>a;a++)i[a]==="%"?(o+=1,a+=2):o+=1;return o})(s.json);r>this.Ne.max_bytes||(this.Ke.push({step:s.step,bytes:r}),this.Je+=r,this.Xe())}}getAttachable(){return this.Ke.map((e=>e.step))}clear(){this.Ke=[],this.Je=0}size(){return this.Ke.length}Xe(){for(;this.Je>this.Ne.max_bytes&&this.Ke.length>0;){var e=this.Ke.shift();e&&(this.Je-=e.bytes)}}}function rp(t,e){if(!he(t)||t===1/0||t===-1/0)return e;var s=Math.floor(t);return 0>s?e:s}var au=function(t,e){var s=(e===void 0?{}:e).debugEnabled,r={k(n){if(v&&(Y.DEBUG||v.POSTHOG_DEBUG||s)&&!x(v.console)&&v.console){for(var i=("__rrweb_original__"in v.console[n])?v.console[n].__rrweb_original__:v.console[n],o=arguments.length,a=new Array(o>1?o-1:0),l=1;o>l;l++)a[l-1]=arguments[l];i(t,...a)}},debug(){for(var n=arguments.length,i=new Array(n),o=0;n>o;o++)i[o]=arguments[o];r.k("debug",...i)},info(){for(var n=arguments.length,i=new Array(n),o=0;n>o;o++)i[o]=arguments[o];r.k("log",...i)},warn(){for(var n=arguments.length,i=new Array(n),o=0;n>o;o++)i[o]=arguments[o];r.k("warn",...i)},error(){for(var n=arguments.length,i=new Array(n),o=0;n>o;o++)i[o]=arguments[o];r.k("error",...i)},critical(){for(var n=arguments.length,i=new Array(n),o=0;n>o;o++)i[o]=arguments[o];console.error(t,...i)},uninitializedWarning(n){r.error("You must initialize PostHog before calling "+n)},createLogger:(n,i)=>au(t+" "+n,i)};return r},k=au("[PostHog.js]"),se=k.createLogger,np=se("[ExternalScriptsLoader]"),ri=(t,e,s)=>{if(t.config.disable_external_dependency_loading)return np.warn(e+" was requested but loading of external scripts is disabled."),s("Loading of external scripts is disabled");var r=C?.querySelectorAll("script");if(r){for(var n,i=function(){if(r[o].src===e){var l=r[o];return l.__posthog_loading_callback_fired?{v:s()}:(l.addEventListener("load",(u=>{l.__posthog_loading_callback_fired=!0,s(void 0,u)})),l.onerror=u=>s(u),{v:void 0})}},o=0;r.length>o;o++)if(n=i())return n.v}var a=()=>{if(!C)return s("document not found");var l=C.createElement("script");if(l.type="text/javascript",l.crossOrigin="anonymous",l.src=e,l.onload=d=>{l.__posthog_loading_callback_fired=!0,s(void 0,d)},l.onerror=d=>s(d),t.config.prepare_external_dependency_script&&(l=t.config.prepare_external_dependency_script(l)),!l)return s("prepare_external_dependency_script returned null");if(t.config.external_scripts_inject_target==="head")C.head.appendChild(l);else{var u,c=C.querySelectorAll("body > script");c.length>0?(u=c[0].parentNode)==null||u.insertBefore(l,c[0]):C.body.appendChild(l)}};C!=null&&C.body?a():C?.addEventListener("DOMContentLoaded",a)};$.__PosthogExtensions__=$.__PosthogExtensions__||{},$.__PosthogExtensions__.loadExternalDependency=(t,e,s)=>{if(e!=="remote-config"){var r;if(t.config.strict_script_versioning)r=t.requestRouter.endpointFor("assets","/static/"+t.version+"/"+e+".js");else{var n="/static/"+e+".js?v="+t.version;if(e==="toolbar"){var i=3e5;n=n+"&t="+Math.floor(Date.now()/i)*i}r=t.requestRouter.endpointFor("assets",n)}ri(t,r,s)}else{var o=t.requestRouter.endpointFor("assets","/array/"+t.config.token+"/config.js");ri(t,o,s)}},$.__PosthogExtensions__.loadSiteApp=(t,e,s)=>{var r=t.requestRouter.endpointFor("api",e);ri(t,r,s)};Y.DEBUG=!1,Y.LIB_VERSION="1.415.7",Y.LIB_NAME="web";var lu="$people_distinct_id",rr="$device_id",ni="$device_model",js="__alias",Us="__timers",Hi="$autocapture_disabled_server_side",Wi="$heatmaps_enabled_server_side",zi="$exception_capture_enabled_server_side",qi="$error_tracking_suppression_rules",Vi="$error_tracking_capture_extension_exceptions",Gi="$web_vitals_enabled_server_side",Wo="$dead_clicks_enabled_server_side",zo="$product_tours_enabled_server_side",Ki="$web_vitals_allowed_metrics",Vt="$session_recording_remote_config",cu="$replay_sample_rate",uu="$replay_override_sampling",du="$replay_override_linked_flag",hu="$replay_override_url_trigger",pu="$replay_override_event_trigger",cs="$sesid",qo="$session_is_sampled",Bt="$enabled_feature_flags",Hs="$active_feature_flags",Tr="$early_access_features",Ji="$feature_flag_details",Ws="$feature_flag_payloads",Nr="$feature_flag_request_id",tn="$minimal_flag_called_events",et="$override_feature_flags",jt="$override_feature_flag_payloads",ct="$stored_person_properties",Ut="$stored_group_properties",Yi="$surveys",sn="$surveys_loaded_at",Zi="$surveys_activated",Mr="$surveys_activated_session",Lr="$surveys_activated_timestamps",zs="ph_product_tours",Wt="$flag_call_reported",qs="$flag_call_reported_session_id",Or="$feature_flag_errors",Ks="$feature_flag_evaluated_at",He="$user_state",Xi="$client_session_props",Qi="$capture_rate_limit",eo="$initial_campaign_params",to="$initial_referrer_info",rn="$initial_person_info",nn="$epp",Er="$posthog_cookieless",fu="$cookieless_mode",gu="$sdk_debug_extensions_init_method",mu="$sdk_debug_extensions_init_time_ms",vu="$sdk_debug_recording_script_not_loaded",Vo="PostHog loadExternalDependency extension not found.",Ht="on_reject",ht="always",ts="anonymous",Tt="identified",so="identified_only",on="visibilitychange",an="beforeunload",os="$pageview",ii="$pageleave",oi="$identify",el="$groupidentify";function Sr(t,e){L(t)&&t.forEach(e)}function Z(t,e){if(!D(t))if(L(t))t.forEach(e);else if(gh(t))t.forEach(((r,n)=>e(r,n)));else for(var s in t)$c.call(t,s)&&e(t[s],s)}var ee=function(t){for(var e=arguments.length,s=new Array(e>1?e-1:0),r=1;e>r;r++)s[r-1]=arguments[r];for(var n of s)for(var i in n)n[i]!==void 0&&(t[i]=n[i]);return t};function Dr(t){for(var e=Object.keys(t),s=e.length,r=new Array(s);s--;)r[s]=[e[s],t[e[s]]];return r}var tl=function(t){try{return t()}catch{return}},ip=function(t){return function(){try{for(var e=arguments.length,s=new Array(e),r=0;e>r;r++)s[r]=arguments[r];return t.apply(this,s)}catch(n){k.critical("Implementation error. Please turn on debug mode and open a ticket on https://app.posthog.com/home#panel=support%3Asupport%3A."),k.critical(n)}}},Go=function(t){var e={};return Z(t,(function(s,r){(W(s)&&s.length>0||he(s))&&(e[r]=s)})),e},op=["herokuapp.com","vercel.app","netlify.app"];function ap(t){var e=t?.hostname;if(!W(e))return!1;var s=e.split(".").slice(-2).join(".");for(var r of op)if(s===r)return!1;return!0}function ne(t,e,s,r){var n=r??{},i=n.capture,o=n.passive;t?.addEventListener(e,s,{capture:i!==void 0&&i,passive:o===void 0||o})}function ro(t){return t.name==="ph_toolbar_internal"}var _u=t=>{if(C){try{for(var e=t+"=",s=C.cookie.split(";").filter((i=>i.length)),r=0;s.length>r;r++){for(var n=s[r];n.charAt(0)==" ";)n=n.substring(1,n.length);if(n.indexOf(e)===0)return decodeURIComponent(n.substring(e.length,n.length))}}catch{}return null}};Math.trunc||(Math.trunc=function(t){return 0>t?Math.ceil(t):Math.floor(t)}),Number.isInteger||(Number.isInteger=function(t){return he(t)&&isFinite(t)&&Math.floor(t)===t});class ln{constructor(e){if(this.bytes=e,e.length!==16)throw new TypeError("not 128-bit length")}static fromFieldsV7(e,s,r,n){if(!Number.isInteger(e)||!Number.isInteger(s)||!Number.isInteger(r)||!Number.isInteger(n)||0>e||0>s||0>r||0>n||e>0xffffffffffff||s>4095||r>1073741823||n>4294967295)throw new RangeError("invalid field value");var i=new Uint8Array(16);return i[0]=e/Math.pow(2,40),i[1]=e/Math.pow(2,32),i[2]=e/Math.pow(2,24),i[3]=e/Math.pow(2,16),i[4]=e/256,i[5]=e,i[6]=112|s>>>8,i[7]=s,i[8]=128|r>>>24,i[9]=r>>>16,i[10]=r>>>8,i[11]=r,i[12]=n>>>24,i[13]=n>>>16,i[14]=n>>>8,i[15]=n,new ln(i)}toString(){for(var e="",s=0;this.bytes.length>s;s++)e=e+(this.bytes[s]>>>4).toString(16)+(15&this.bytes[s]).toString(16),s!==3&&s!==5&&s!==7&&s!==9||(e+="-");if(e.length!==36)throw new Error("Invalid UUIDv7 was generated");return e}clone(){return new ln(this.bytes.slice(0))}equals(e){return this.compareTo(e)===0}compareTo(e){for(var s=0;16>s;s++){var r=this.bytes[s]-e.bytes[s];if(r!==0)return Math.sign(r)}return 0}}class lp{generate(){var e=this.generateOrAbort();if(!x(e))return e;this.S=0;var s=this.generateOrAbort();if(x(s))throw new Error("Could not generate UUID after timestamp reset");return s}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 ln.fromFieldsV7(this.S,Math.trunc(this.I/Math.pow(2,30)),this.I&Math.pow(2,30)-1,this.A.nextUint32())}C(){this.I=1024*this.A.nextUint32()+(1023&this.A.nextUint32())}constructor(){this.S=0,this.I=0,this.A=new cp}}var sl,yu=t=>{if(typeof UUIDV7_DENY_WEAK_RNG<"u"&&UUIDV7_DENY_WEAK_RNG)throw new Error("no cryptographically strong RNG available");for(var e=0;t.length>e;e++)t[e]=65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random());return t};v&&!x(v.crypto)&&crypto.getRandomValues&&(yu=t=>crypto.getRandomValues(t));class cp{nextUint32(){return this.R.length>this.O||(yu(this.R),this.O=0),this.R[this.O++]}constructor(){this.R=new Uint32Array(8),this.O=1/0}}var dt=()=>up().toString(),up=()=>(sl||(sl=new lp)).generate(),As="",dp=/[a-z0-9][a-z0-9-]+\.[a-z]{2,}$/i,pt={N:()=>!!C,j(t){k.error("cookieStore error: "+t)},P:_u,H(t){var e;try{e=JSON.parse(pt.P(t))||{}}catch{}return e},F(t,e,s,r,n){if(!C)return!1;try{var i="",o="",a=(function(c,d){if(d){var h=(function(f,g){if(g===void 0&&(g=C),As)return As;if(!g||["localhost","127.0.0.1"].includes(f))return"";for(var m=f.split("."),_=Math.min(m.length,8),b="dmn_chk_"+dt();!As&&_--;){var E=m.slice(_).join("."),I=b+"=1;domain=."+E+";path=/";g.cookie=I+";max-age=3",g.cookie.includes(b)&&(g.cookie=I+";max-age=0",As=E)}return As})(c);if(!h){var p=(f=>{var g=f.match(dp);return g?g[0]:""})(c);p!==h&&k.info("Warning: cookie subdomain discovery mismatch",p,h),h=p}return h?"; domain=."+h:""}return""})(C.location.hostname,r);if(s){var l=new Date;l.setTime(l.getTime()+864e5*s),i="; expires="+l.toUTCString()}n&&(o="; secure");var u=t+"="+encodeURIComponent(JSON.stringify(e))+i+"; SameSite=Lax; path=/"+a+o;return u.length>3686.4&&k.warn("cookieStore warning: large cookie, len="+u.length),C.cookie=u,!0}catch{return!1}},q(t,e){if(C!=null&&C.cookie)try{pt.F(t,"",-1,e)}catch{return}}},ai=null,Q={N(){if(!$e(ai))return ai;var t=!0;if(x(v))t=!1;else try{var e="__mplssupport__";Q.F(e,"xyz"),Q.P(e)!=='"xyz"'&&(t=!1),Q.q(e)}catch{t=!1}return t||k.error("localStorage unsupported; falling back to cookie store"),ai=t,t},j(t){k.error("localStorage error: "+t)},P(t){try{return v?.localStorage.getItem(t)}catch(e){Q.j(e)}return null},H(t){try{return JSON.parse(Q.P(t))||{}}catch{}return null},F(t,e){try{return v?.localStorage.setItem(t,JSON.stringify(e)),!0}catch(s){Q.j(s)}return!1},q(t){try{v?.localStorage.removeItem(t)}catch(e){Q.j(e)}}},hp=[rr,"distinct_id",cs,qo,nn,rn,He],xr={},pp={N:()=>!0,j(t){k.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]}},Nt=null,ce={N(){if(!$e(Nt))return Nt;if(Nt=!0,x(v))Nt=!1;else try{var t="__support__";ce.F(t,"xyz"),ce.P(t)!=='"xyz"'&&(Nt=!1),ce.q(t)}catch{Nt=!1}return Nt},j(t){k.error("sessionStorage error: ",t)},P(t){try{return v?.sessionStorage.getItem(t)}catch(e){ce.j(e)}return null},H(t){try{return JSON.parse(ce.P(t))||null}catch{}return null},F(t,e){try{return v?.sessionStorage.setItem(t,JSON.stringify(e)),!0}catch(s){ce.j(s)}return!1},q(t){try{v?.sessionStorage.removeItem(t)}catch(e){ce.j(e)}}};class fp{constructor(e){this._instance=e}get Ne(){return this._instance.config}get consent(){return this.ti()?0:this.ei}isOptedOut(){return this.Ne.cookieless_mode===ht||this.isRejected()||this.consent===-1&&this.Ne.cookieless_mode===Ht}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,s=e.token,r=e.opt_out_capturing_cookie_prefix;return e.consent_persistence_name||(r?r+s:"__ph_opt_in_out_"+s)}get ei(){var e=this.ii.P(this.ri);return Xn(e)?1:M(yh,e)?0:-1}get ii(){var e=this.Ne.opt_out_capturing_persistence_type,s=e==="localStorage"?Q:pt;if(!this.ni||this.ni!==s){this.ni=s;var r=e==="localStorage"?pt:Q;r.P(this.ri)&&(this.ni.P(this.ri)||this.optInOut(Xn(r.P(this.ri))),r.q(this.ri,this.Ne.cross_subdomain_cookie))}return this.ni}ti(){return!!this.Ne.respect_dnt&&[ke?.doNotTrack,ke?.msDoNotTrack,$.doNotTrack].some((e=>Xn(e)))}}function wu(t,e){var s,r=t==null||(s=t.config)==null?void 0:s.get_current_url;if(!Se(r))return e;try{var n=r(e);return W(n)&&n?n:e}catch(i){return k.error("Error in get_current_url, falling back to window.location.href",i),e}}var bu="__POSTHOG_TOOLBAR__",gp=1,mp=3,vp=11;function rl(t){return t instanceof Element&&(t.id===bu||!(t.closest==null||!t.closest(".toolbar-global-fade-container")))}function Ft(t){return!!t&&t.nodeType===gp}function Me(t,e){return!!t&&!!t.tagName&&t.tagName.toLowerCase()===e.toLowerCase()}function Eu(t){return!!t&&t.nodeType===mp}function Su(t){return!!t&&t.nodeType===vp&&Ft(t.host)}var xu=1e3;function Ko(t){return t?An(t).split(/\s+/):[]}function nl(t,e){var s=(function(r){var n,i=v==null||(n=v.location)==null?void 0:n.href;return x(i)?void 0:wu(r,i)})(e);return!!(s&&t&&t.some((r=>s.match(r))))}function cn(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 Ko(e)}function ku(t){return D(t)?null:An(t).split(/(\s+)/).filter((e=>Js(e))).join("").replace(/[\r\n]/g," ").replace(/[ ]+/g," ").substring(0,255)}function nr(t){var e="";return io(t)&&!Pu(t)&&t.childNodes&&t.childNodes.length&&Z(t.childNodes,(function(s){var r;Eu(s)&&s.textContent&&(e+=(r=ku(s.textContent))!==null&&r!==void 0?r:"")})),An(e)}function li(t){var e;return x(t.target)?t.srcElement||null:(e=t.target)!=null&&e.shadowRoot?t.composedPath()[0]||null:t.target||null}var Jo=["a","button","form","input","select","textarea","label"];function no(t,e){if(x(e))return!0;var s,r=function(i){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}})(i,o))))return{v:!0}};for(var n of t)if(s=r(n))return s.v;return!1}function Iu(t){var e=t.parentNode;return!(!e||!Ft(e))&&e}var _p=[".ph-no-autocapture","[data-ph-no-autocapture]"],Cu=["next","previous","prev",">","<"],yp=[...Cu,"+","-","−","–"],il=(t,e)=>/[a-z0-9]/i.test(e)?t.includes(e):t===e,ol=[".ph-no-rageclick",".ph-no-capture"],wp=["","text","search","email","password","url","tel","number"];function al(t,e){if(!v||Yo(t))return!1;var s,r,n,i,o;if(Ke(e)?(s=!!e&&ol,r=void 0,n=!1):(s=(i=e?.css_selector_ignorelist)!==null&&i!==void 0?i:ol,r=e?.content_ignorelist,n=(o=e?.ignore_text_selection)!==null&&o!==void 0&&o),s===!1||n&&(function(l){return!(!l||!Ft(l))&&(!!Me(l,"textarea")||(Me(l,"input")?M(wp,(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=Fu(t,!1).targetElementList;return!(function(l,u){if(l===!1||x(l))return!1;var c;if(l===!0)c=Cu;else{if(!L(l))return!1;if(l.length>10)return k.error("[PostHog] content_ignorelist array cannot exceed 10 items. Use css_selector_ignorelist for more complex matching."),!1;c=l.map((d=>d.toLowerCase()))}return u.some((d=>{var h=d.safeText,p=d.ariaLabel;return c.some((f=>il(h,f)||il(p,f)))}))})(r,a.map((l=>{var u;return{safeText:nr(l).toLowerCase(),ariaLabel:((u=l.getAttribute("aria-label"))==null?void 0:u.toLowerCase().trim())||""}})))&&!no(a,s)}var Yo=t=>!t||Me(t,"html")||!Ft(t),Fu=(t,e)=>{if(!v||Yo(t))return{parentIsUsefulElement:!1,targetElementList:[]};for(var s=!1,r=[t],n=t;n.parentNode&&!Me(n,"body");)if(Su(n.parentNode))r.push(n.parentNode.host),n=n.parentNode.host;else{var i=Iu(n);if(!i)break;if(e||Jo.indexOf(i.tagName.toLowerCase())>-1)s=!0;else try{var o=v.getComputedStyle(i);o&&o.getPropertyValue("cursor")==="pointer"&&(s=!0)}catch{}r.push(i),n=i}return{parentIsUsefulElement:s,targetElementList:r}};function io(t){for(var e=new Set,s=0,r=t;r.parentNode&&!Me(r,"body");r=r.parentNode){if(s++>=xu||e.has(r))return!1;e.add(r);var n=cn(r);if(M(n,"ph-sensitive")||M(n,"ph-no-capture"))return!1}if(M(cn(t),"ph-include"))return!0;var i=t.type||"";if(W(i))switch(i.toLowerCase()){case"hidden":case"password":return!1}var o=t.name||t.id||"";return!W(o)||!/^cc|cardnum|ccnum|creditcard|csc|cvc|cvv|exp|pass|pwd|routing|seccode|securitycode|securitynum|socialsec|socsec|ssn/i.test(o.replace(/[^a-zA-Z0-9]/g,""))}function Pu(t){return!!(Me(t,"input")&&!["button","checkbox","submit","reset"].includes(t.type)||Me(t,"select")||Me(t,"textarea")||t.getAttribute("contenteditable")==="true")}var ll=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}))$"),cl=/(^|[^0-9A-Za-z_])([0-9][0-9 -]*[0-9])(?=$|[^0-9A-Za-z_])/g,bp=[16,15,14,13],Ep=new RegExp("^(\\d{3}-?\\d{2}-?\\d{4})$"),ul=new RegExp("(^|[^0-9])((?!000|666)[0-9]{3}-?(?!00)[0-9]{2}-?(?!0000)[0-9]{4})(?=$|([^0-9]))","g"),dl=/[0-9A-Za-z_]/;function Sp(t){for(var e=0,s=!1,r=t.length-1;r>=0;r--){var n=t.charCodeAt(r)-48;s&&(n*=2)>9&&(n-=9),e+=n,s=!s}return e%10==0}function Js(t,e){if(e===void 0&&(e=!0),D(t))return!1;if(W(t)){t=An(t);var s=e?ll.test((t||"").replace(/[- ]/g,"")):(function(n){var i;for(cl.lastIndex=0;i=cl.exec(n);){var o=i[2];if(o)for(var a=o.replace(/[- ]/g,""),l=0;a.length>l;l++)for(var u of bp){var c=l+u;if(a.length>=c){var d=a.slice(l,c);if(ll.test(d)&&Sp(d))return!0}}}return!1})(t);if(s)return!1;var r=e?Ep.test(t):(function(n){var i;for(ul.lastIndex=0;i=ul.exec(n);){var o=i[1],a=i[3];if(!(o&&a&&dl.test(o)&&dl.test(a)))return!0}return!1})(t);if(r)return!1}return!0}function hl(t){var e=nr(t);return Js(e=(e+" "+Au(t)).trim())?e:""}function Au(t){var e="";return t&&t.childNodes&&t.childNodes.length&&Z(t.childNodes,(function(s){var r;if(s&&((r=s.tagName)==null?void 0:r.toLowerCase())==="span")try{var n=nr(s);e=(e+" "+n).trim(),s.childNodes&&s.childNodes.length&&(e=(e+" "+Au(s)).trim())}catch(i){k.error("[AutoCapture]",i)}})),e}function pl(t){return t.replace(/"|\\"/g,'\\"')}function xp(t){var e=t.attr__class;if(e)return L(e)?e:Ko(e)}var kr=se("[Dead Clicks]"),kp=()=>!0,Ip=t=>{var e,s=!((e=t.instance.persistence)==null||!e.get_property(Wo)),r=t.instance.config.capture_dead_clicks;return Ke(r)?r:!!te(r)||s};class fl{get lazyLoadedDeadClicksAutocapture(){return this.si}constructor(e,s,r){this.instance=e,this.isEnabled=s,this.onCapture=r,this.startIfEnabledOrStop()}onRemoteConfig(e){if(e.ok){var s=e.config;"captureDeadClicks"in s&&(this.instance.persistence&&this.instance.persistence.register({[Wo]:s.captureDeadClicks}),this.startIfEnabledOrStop())}}startIfEnabledOrStop(){this.isEnabled(this)?this.ai((()=>{this.oi()})):this.stop()}ai(e){var s,r;(s=$.__PosthogExtensions__)!=null&&s.initDeadClicksAutocapture?e():(r=$.__PosthogExtensions__)==null||r.loadExternalDependency==null||r.loadExternalDependency(this.instance,"dead-clicks-autocapture",(n=>{n?kr.error("failed to load script",n):e()}))}oi(){var e;if(C){if(!this.si&&(e=$.__PosthogExtensions__)!=null&&e.initDeadClicksAutocapture){var s=te(this.instance.config.capture_dead_clicks)?w({},this.instance.config.capture_dead_clicks):{};s.__onCapture=this.onCapture,this.onCapture&&(s.capture_dead_swipes=!1),this.si=$.__PosthogExtensions__.initDeadClicksAutocapture(this.instance,s),this.si.start(C),kr.info("starting...")}}else kr.error("`document` not found. Cannot start.")}stop(){this.si&&(this.si.stop(),this.si=void 0,kr.info("stopping..."))}}var ci=se("[SegmentIntegration]"),$u="posthog-js";function Ru(t,e){var s=e===void 0?{}:e,r=s.organization,n=s.projectId,i=s.prefix,o=s.severityAllowList,a=o===void 0?["error"]:o,l=s.sendExceptionsToPostHog,u=l===void 0||l;return c=>{var d,h,p,f,g;if(a!=="*"&&!a.includes(c.level)||!t.__loaded)return c;c.tags||(c.tags={});var m=t.requestRouter.endpointFor("ui","/project/"+t.config.token+"/person/"+t.get_distinct_id());c.tags["PostHog Person URL"]=m,t.sessionRecordingStarted()&&(c.tags["PostHog Recording URL"]=t.get_session_replay_url({withTimestamp:!0}));var _,b=((d=c.exception)==null?void 0:d.values)||[],E=b.map((F=>w({},F,{stacktrace:F.stacktrace?w({},F.stacktrace,{type:"raw",frames:(F.stacktrace.frames||[]).map((P=>w({},P,{platform:"web:javascript"})))}):void 0}))),I={$exception_message:((h=b[0])==null?void 0:h.value)||c.message,$exception_type:(p=b[0])==null?void 0:p.type,$exception_level:c.level,$exception_list:E,$sentry_event_id:c.event_id,$sentry_exception:c.exception,$sentry_exception_message:((f=b[0])==null?void 0:f.value)||c.message,$sentry_exception_type:(g=b[0])==null?void 0:g.type,$sentry_tags:c.tags};return r&&n&&(I.$sentry_url=(i||"https://sentry.io/organizations/")+r+"/issues/?project="+n+"&query="+c.event_id),u&&((_=t.exceptions)==null||_.sendExceptionEvent(I)),c}}class Cp{constructor(e,s,r,n,i,o){this.name=$u,this.setupOnce=function(a){a(Ru(e,{organization:s,projectId:r,prefix:n,severityAllowList:i,sendExceptionsToPostHog:o==null||o}))}}}class gl{constructor(e){this.li=(s,r,n)=>{n&&(n.noSessionId||n.activityTimeout||n.sessionPastMaximumLength||n.crossTabAdoption)&&(k.info("[PageViewManager] Session rotated, clearing pageview state",{sessionId:s,changeReason:n}),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,s){var r,n=this.vi(e,s);return this.ui={pathname:(r=v?.location.pathname)!==null&&r!==void 0?r:"",pageViewId:s,timestamp:e},this._instance.scrollManager.resetContext(),n}doPageLeave(e){var s;return this.vi(e,(s=this.ui)==null?void 0:s.pageViewId)}doEvent(){var e;return{$pageview_id:(e=this.ui)==null?void 0:e.pageViewId}}vi(e,s){var r=this.ui;if(!r)return{$pageview_id:s};var n={$pageview_id:s,$prev_pageview_id:r.pageViewId},i=this._instance.scrollManager.getContext();if(i&&!this._instance.config.disable_scroll_properties){var o=i.maxScrollHeight,a=i.lastScrollY,l=i.maxScrollY,u=i.maxContentHeight,c=i.lastContentY,d=i.maxContentY;if(!(x(o)||x(a)||x(l)||x(u)||x(c)||x(d))){o=Math.ceil(o),a=Math.ceil(a),l=Math.ceil(l),u=Math.ceil(u),c=Math.ceil(c),d=Math.ceil(d);var h=o>1?rt(a/o,0,1,k):1,p=o>1?rt(l/o,0,1,k):1,f=u>1?rt(c/u,0,1,k):1,g=u>1?rt(d/u,0,1,k):1;n=ee(n,{$prev_pageview_last_scroll:a,$prev_pageview_last_scroll_percentage:h,$prev_pageview_max_scroll:l,$prev_pageview_max_scroll_percentage:p,$prev_pageview_last_content:c,$prev_pageview_last_content_percentage:f,$prev_pageview_max_content:d,$prev_pageview_max_content_percentage:g})}}return r.pathname&&(n.$prev_pageview_pathname=r.pathname),r.timestamp&&(n.$prev_pageview_duration=(e.getTime()-r.timestamp.getTime())/1e3),n}}var ui=["flags","surveys"],Fp={[lu]:{exposure:"hidden"},[js]:{exposure:"hidden"},__cmpns:{exposure:"hidden"},[Us]:{exposure:"hidden"},[Hi]:{exposure:"event"},[Wi]:{exposure:"hidden"},[zi]:{exposure:"event"},[qi]:{exposure:"hidden"},[Vi]:{exposure:"event"},[Gi]:{exposure:"event"},[Wo]:{exposure:"event"},[zo]:{exposure:"hidden"},[Ki]:{exposure:"event"},[Vt]:{exposure:"hidden"},$session_recording_enabled_server_side:{exposure:"hidden"},[cs]:{exposure:"hidden"},[qo]:{exposure:"event"},[cu]:{exposure:"event",shouldSkipFromEventProperties:t=>$e(t)},$session_past_minimum_duration:{exposure:"event"},$session_recording_url_trigger_activated_session:{exposure:"event"},$session_recording_event_trigger_activated_session:{exposure:"event"},$debug_first_full_snapshot_timestamp:{exposure:"event"},$sess_rec_flush_size:{exposure:"hidden"},[Bt]:{exposure:"hidden",storageGroup:"flags"},[Hs]:{exposure:"hidden",storageGroup:"flags"},[Tr]:{exposure:"hidden"},[Ji]:{exposure:"hidden",storageGroup:"flags"},[Ws]:{exposure:"hidden",storageGroup:"flags"},[Nr]:{exposure:"hidden",storageGroup:"flags",volatile:!0},[tn]:{exposure:"hidden",storageGroup:"flags"},[et]:{exposure:"hidden"},[jt]:{exposure:"hidden"},[ct]:{exposure:"hidden"},[Ut]:{exposure:"hidden"},[Yi]:{exposure:"hidden",storageGroup:"surveys"},[sn]:{exposure:"hidden",storageGroup:"surveys",volatile:!0},[Zi]:{exposure:"event"},[Mr]:{exposure:"hidden"},[Lr]:{exposure:"hidden"},[zs]:{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"},[Wt]:{exposure:"hidden"},[qs]:{exposure:"hidden"},[Or]:{exposure:"hidden"},[Ks]:{exposure:"hidden",storageGroup:"flags",volatile:!0},[He]:{exposure:"hidden"},[Xi]:{exposure:"hidden"},[Qi]:{exposure:"hidden"},[eo]:{exposure:"hidden"},[to]:{exposure:"hidden"},[rn]:{exposure:"hidden"},[nn]:{exposure:"hidden"},[uu]:{exposure:"event"},[du]:{exposure:"event"},[hu]:{exposure:"event"},[pu]:{exposure:"event"},[gu]:{exposure:"event"},[mu]:{exposure:"event"},[vu]:{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"}},Pp=[["$posthog_sr_group_event_trigger_",{exposure:"hidden"}],["$posthog_sr_group_url_trigger_",{exposure:"hidden"}],["$posthog_sr_group_sampling_",{exposure:"hidden"}]],Mt=t=>{var e=Fp[t];if(e)return e;for(var s of Pp){var r=s[1];if(t.indexOf(s[0])===0)return r}},us=(t,e)=>{try{return JSON.stringify(t,((s,r)=>typeof r=="bigint"?r.toString():r),e)}catch{return Pc(t)}},un=t=>{var e=C?.createElement("a");return x(e)?null:(e.href=t,e)},vs=function(t,e){for(var s,r=((t.split("#")[0]||"").split(/\?(.*)/)[1]||"").replace(/^\?+/g,"").split("&"),n=0;r.length>n;n++){var i=r[n].split("=");if(i[0]===e){s=i;break}}if(!L(s)||2>s.length)return"";var o=s[1];try{o=decodeURIComponent(o)}catch{k.error("Skipping decoding for malformed query param: "+o)}return o.replace(/\+/g," ")},ir=function(t,e,s){if(!t||!e||!e.length)return t;for(var r=t.split("#"),n=r[1],i=(r[0]||"").split("?"),o=i[1],a=i[0],l=(o||"").split("&"),u=[],c=0;l.length>c;c++){var d=l[c].split("=");L(d)&&(e.includes(d[0])?u.push(d[0]+"="+s):u.push(l[c]))}var h=a;return o!=null&&(h+="?"+u.join("&")),n!=null&&(h+="#"+n),h},dn=function(t,e){var s=t.match(new RegExp(e+"=([^&]*)"));return s?s[1]:null},Tu=(t,e)=>t>=e&&Ic(),Nu=(t,e,s,r)=>{if(t===0){if(Ic()){var n=e+1;return n===s&&r(),n}return e}return 0},Ir="https?://(.*)",_s=["gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","irclid","_kx"],Ap=["utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid",..._s],or="",$p=["li_fat_id"];function Mu(t,e,s){if(!C)return{};var r,n=e?[..._s,...s||[]]:[],i=Lu(ir(C.URL,n,or),t),o=(r={},Z($p,(function(a){var l=_u(a);r[a]=l||null})),r);return ee(o,i)}function Lu(t,e){var s=Ap.concat(e||[]),r={};return Z(s,(function(n){var i=vs(t,n);r[n]=i||null})),r}function Ou(t){var e=(function(i){return i?i.search(Ir+"google.([^/?]*)")===0?"google":i.search(Ir+"bing.com")===0?"bing":i.search(Ir+"yahoo.com")===0?"yahoo":i.search(Ir+"duckduckgo.com")===0?"duckduckgo":null:null})(t),s=e!="yahoo"?"q":"p",r={};if(!$e(e)){r.$search_engine=e;var n=C?vs(C.referrer,s):"";n.length&&(r.ph_keyword=n)}return r}function ml(){return navigator.language||navigator.userLanguage}var hn="$direct";function Du(){return C?.referrer||hn}function Bu(t,e,s){s===void 0&&(s=!1);var r=t?[..._s,...e||[]]:[],n=s?Ct(re?.href):re?.href,i=n?.substring(0,1e3);return{r:Du().substring(0,1e3),u:i?ir(i,r,or):void 0}}function ju(t,e){var s;e===void 0&&(e=!1);var r=t.r,n=t.u,i=e?Ct(n):n,o={$referrer:r,$referring_domain:r==null?void 0:r==hn?hn:(s=un(r))==null?void 0:s.host};if(i){o.$current_url=i;var a=un(i);o.$host=a?.host,o.$pathname=a?.pathname;var l=Lu(i);ee(o,l)}if(r){var u=Ou(r);ee(o,u)}return o}function Uu(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return}}function Rp(){try{return new Date().getTimezoneOffset()}catch{return}}var Tp={flags:Ks,surveys:sn},Np=["cookie","localstorage","localstorage+cookie","sessionstorage","memory"],ss="main";class di{constructor(e,s,r){if(r===void 0&&(r=!0),this.ci={},this.fi=!1,this.pi=!1,this.Ne=e,this.gi=r,this.props={},this.mi=void 0,this.yi=(i=>{var o="";return i.token&&(o=i.token.replace(/\+/g,"PL").replace(/\//g,"SL").replace(/=/g,"EQ")),i.persistence_name?"ph_"+i.persistence_name:"ph_"+o+"_posthog"})(e),this.ii=this.bi(e),this.pi=this.wi(e),this.load(),e.debug&&k.info("Persistence loaded",e.persistence,w({},this.props)),this.update_config(e,e,s),this.save(),v){var n=()=>this.flush();ne(v,"beforeunload",n,{capture:!1}),ne(v,"pagehide",n,{capture:!1})}}ki(){var e,s=(e=this.Ne)==null?void 0:e.persistence_save_debounce_ms;return he(s)&&s>0?s:0}isDisabled(){return!!this.xi}bi(e){Np.indexOf(e.persistence.toLowerCase())===-1&&(k.critical("Unknown persistence type "+e.persistence+"; falling back to localStorage+cookie"),e.persistence="localStorage+cookie");var s,r=(function(o,a){o===void 0&&(o=[]),a===void 0&&(a=!1);var l=[...hp,...o];return w({},Q,{H(u){try{var c={};try{c=pt.H(u)||{}}catch{}var d,h=JSON.parse(Q.P(u)||"{}");if(a){var p={};for(var f in c){var g=c[f];$e(g)||g===""||(p[f]=g)}d=ee(h,p)}else d=ee(c,h);return Q.F(u,d),d}catch{}return null},F(u,c,d,h,p,f){var g=Q.F(u,c,void 0,void 0,f);try{var m={};l.forEach((_=>{c[_]&&(m[_]=c[_])})),Object.keys(m).length&&pt.F(u,m,d,h,p,f)}catch(_){Q.j(_)}return g},q(u,c){try{v?.localStorage.removeItem(u),pt.q(u,c)}catch(d){Q.j(d)}}})})(e.cookie_persisted_properties||[],e.__preview_cookie_wins_on_conflict||!1),n=!1,i=e.persistence.toLowerCase();return i==="localstorage"&&Q.N()?(s=Q,n=!0):i==="localstorage+cookie"&&r.N()?(s=r,n=!0):i==="sessionstorage"&&ce.N()?s=ce:i==="memory"?s=pp:i==="cookie"?s=pt:r.N()?(s=r,n=!0):s=pt,this.fi=n,s}Si(e){return this.yi+"__"+e}wi(e){return this.fi&&!!e.split_storage}properties(){var e={};return Z(this.props,((s,r)=>{var n=Mt(r);if(!n||n.exposure==="event"){if(n!=null&&n.shouldSkipFromEventProperties!=null&&n.shouldSkipFromEventProperties(s))return;e[r]=s}})),e}load(){if(!this.xi){var e=this.ii.H(this.yi);e&&(this.props=ee({},e)),this.pi&&this.Ci()}}Ci(){for(var e of ui){var s=Q.H(this.Si(e));if(s&&!mt(s)){var r=this.Mi(e);r.persisted=!0,this.Ti(e)||(r.fingerprint=this.Ei(s,e)),this.Ii(e,s)||ee(this.props,s)}}}Ti(e){return Object.keys(this.props).some((s=>{var r;return((r=Mt(s))==null?void 0:r.storageGroup)===e}))}Ii(e,s){var r=Tp[e];if(!r)return!1;var n=s[r],i=this.props[r];return he(n)&&he(i)&&i>n}refreshKey(e){var s;if(!this.xi){var r=this.pi?(s=Mt(e))==null?void 0:s.storageGroup:void 0,n=r?Q.H(this.Si(r)):this.ii.H(this.yi);if(n&&e in n)this.Pi(e,n[e]);else{if(r){var i=this.ii.H(this.yi);if(i&&e in i)return void this.Pi(e,i[e])}this.Ri(e)}}}save(){if(!this.xi){var e=this.ki();e>0?x(this.Ai)&&(this.Ai=setTimeout((()=>{this.Ai=void 0,this.Fi()}),e)):this.Fi()}}flush(){x(this.Ai)||(clearTimeout(this.Ai),this.Ai=void 0,this.Fi())}Fi(){this.xi||(this.pi?this.Li():this.Oi(this.ii,this.yi,this.props,ss))}Li(){var e=this.Di(),s=e.main,r=e.groups;for(var n of(this.Oi(this.ii,this.yi,s,ss),ui)){var i,o=r[n];(!mt(o)||(i=this.ci[n])!=null&&i.persisted)&&this.Oi(Q,this.Si(n),o,n)}}Di(){var e={},s={flags:{},surveys:{}};return Z(this.props,((r,n)=>{var i,o=(i=Mt(n))==null?void 0:i.storageGroup;o?s[o][n]=r:e[n]=r})),{main:e,groups:s}}Ei(e,s){if(s===ss)return JSON.stringify(e)+"|"+this.$i+"|"+this.Ni+"|"+this.qi;var r={};return Z(e,((n,i)=>{var o;r[i]=(o=Mt(i))!=null&&o.volatile?"__volatile__":n})),JSON.stringify(r)}Oi(e,s,r,n){var i=this.Mi(n);if(n===ss||i.dirty||x(i.fingerprint)){var o;try{if((o=this.Ei(r,n))===i.fingerprint)return void(i.dirty=!1)}catch{o=void 0}e.F(s,r,this.$i,this.Ni,this.qi,this.Ne.debug)?(i.dirty=!1,n!==ss&&(i.persisted=!0),x(o)||(i.fingerprint=o)):this.Ne.debug&&k.warn('failed to persist storage entry "'+s+'"; will retry on next save')}}remove(e){var s=(e===void 0?{}:e).keepGroupEntries,r=s!==void 0&&s;if(x(this.Ai)||(clearTimeout(this.Ai),this.Ai=void 0),this.ii.q(this.yi,!1),this.ii.q(this.yi,!0),!r&&this.gi)for(var n of ui)Q.q(this.Si(n));r?delete this.ci[ss]:this.ci={}}clear(){this.remove(),this.props={}}register_once(e,s,r){if(te(e)){x(s)&&(s="None"),this.$i=x(r)?this.ji:r;var n=!1;if(Z(e,((i,o)=>{this.props.hasOwnProperty(o)&&this.props[o]!==s||(this.Pi(o,i),n=!0)})),n)return this.save(),!0}return!1}register(e,s){if(te(e)){this.$i=x(s)?this.ji:s;var r=!1;if(Z(e,((n,i)=>{e.hasOwnProperty(i)&&(this.props[i]!==n||te(n)||L(n))&&(this.Pi(i,n),r=!0)})),r)return this.save(),!0}return!1}unregister(e){var s=typeof e=="string"?[e]:e,r=!1;for(var n of s)n in this.props&&(this.Ri(n),r=!0);r&&this.save()}update_campaign_params(){var e=C?.URL;if(e!==this.mi){var s=Mu(this.Ne.custom_campaign_params,this.Ne.mask_personal_data_properties,this.Ne.custom_personal_data_properties);mt(Go(s))||this.register(s),this.mi=e}}update_search_keyword(){var e;this.register((e=C?.referrer)?Ou(e):{})}update_referrer_info(){var e;this.register_once({$referrer:Du(),$referring_domain:C!=null&&C.referrer&&((e=un(C.referrer))==null?void 0:e.host)||hn},void 0)}set_initial_person_info(){this.props[eo]||this.props[to]||this.register_once({[rn]:Bu(this.Ne.mask_personal_data_properties,this.Ne.custom_personal_data_properties,this.Ne.disable_capture_url_hashes)},void 0)}get_initial_props(){var e={};Z([to,eo],(n=>{var i=this.props[n];i&&Z(i,(function(o,a){e["$initial_"+Mi(a)]=o}))}));var s=this.props[rn];if(s){var r=(function(n,i){i===void 0&&(i=!1);var o=ju(n,i),a={};return Z(o,(function(l,u){a["$initial_"+Mi(u)]=l})),a})(s,this.Ne.disable_capture_url_hashes);ee(e,r)}return e}safe_merge(e){return Z(this.props,(function(s,r){r in e||(e[r]=s)})),e}update_config(e,s,r){this.ji=this.$i=e.cookie_expiration,this.set_disabled(e.disable_persistence||!!r),this.set_cross_subdomain(e.cross_subdomain_cookie),this.set_secure(e.secure_cookie);var n=e.persistence!==s.persistence||!((l,u)=>{if(l.length!==u.length)return!1;var c=[...l].sort(),d=[...u].sort();return c.every(((h,p)=>h===d[p]))})(e.cookie_persisted_properties||[],s.cookie_persisted_properties||[]),i=n?this.bi(e):this.ii,o=this.wi(e);if(n||o!==this.pi){var a=this.props;this.clear(),this.ii=i,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,s){var r=this.props[Us]||{};r[e]=s,this.Pi(Us,r),this.save()}remove_event_timer(e){var s=this.props[Us]||{},r=s[e];return x(r)||(delete s[e],this.Pi(Us,s),this.save()),r}get_property(e){return this.props[e]}set_property(e,s){this.Pi(e,s),this.save()}Pi(e,s){var r;this.props[e]=s,(r=Mt(e))!=null&&r.volatile||this.Bi(e)}Ri(e){delete this.props[e],this.Bi(e)}Bi(e){var s,r=(s=Mt(e))==null?void 0:s.storageGroup;r&&(this.Mi(r).dirty=!0)}Mi(e){return this.ci[e]||(this.ci[e]={})}}function Cr(t){var e=!0;return{dispose(){if(e){e=!1;var s=t();s&&Se(s.then)&&s.then(void 0,(()=>{}))}}}}var xe={GZipJS:"gzip-js",Base64:"base64"},$s={Activation:"events",Cancellation:"cancelEvents"},hi={Popover:"popover",API:"api",Widget:"widget"},ft={SHOWN:"survey shown",DISMISSED:"survey dismissed",SENT:"survey sent"},pi={SURVEY_ID:"$survey_id",SURVEY_ITERATION:"$survey_iteration",SURVEY_LAST_SEEN_DATE:"$survey_last_seen_date"},oo={Popover:"popover",Inline:"inline"},Mp={SHOWN:"product tour shown"},vl={TOUR_LAST_SEEN_DATE:"$product_tour_last_seen_date",TOUR_TYPE:"$product_tour_type"},_l=se("[RateLimiter]");class Lp{constructor(e){this.serverLimits={},this.lastEventRateLimited=!1,this.checkForLimiting=s=>{var r=s.text;if(r&&r.length)try{(JSON.parse(r).quota_limited||[]).forEach((n=>{_l.info((n||"events")+" is quota limited."),this.serverLimits[n]=new Date().getTime()+6e4}))}catch(n){return void _l.warn('could not rate limit - continuing. Error: "'+n?.message+'"',{text:r})}},this.instance=e,this.lastEventRateLimited=this.clientRateLimitContext(!0).isRateLimited}get captureEventsPerSecond(){var e;return((e=this.instance.config.rate_limiting)==null?void 0:e.events_per_second)||10}get captureEventsBurstLimit(){var e;return Math.max(((e=this.instance.config.rate_limiting)==null?void 0:e.events_burst_limit)||10*this.captureEventsPerSecond,this.captureEventsPerSecond)}clientRateLimitContext(e){var s,r,n;e===void 0&&(e=!1);var i=this.captureEventsBurstLimit,o=this.captureEventsPerSecond,a=new Date().getTime(),l=(s=(r=this.instance.persistence)==null?void 0:r.get_property(Qi))!==null&&s!==void 0?s:{tokens:i,last:a};l.tokens+=(a-l.last)/1e3*o,l.last=a,l.tokens>i&&(l.tokens=i);var u=1>l.tokens;if(u||e||(l.tokens=Math.max(0,l.tokens-1)),u&&!e){var c=(he(l.dropped)?l.dropped:0)+1;l.dropped=c,!this.lastEventRateLimited&&this.Hi(c)&&(l.dropped=0)}return this.lastEventRateLimited=u,(n=this.instance.persistence)==null||n.set_property(Qi,l),{isRateLimited:u,remainingTokens:l.tokens}}Ui(e){var s=this.instance.config.property_denylist;return!L(s)||!s.includes(e)}zi(){var e;if(this.Ui("$current_url")&&this.Ui("$pathname")&&re!=null&&re.pathname)return""+((e=re.origin)!==null&&e!==void 0?e:"")+re.pathname}Hi(e){var s,r,n=this.captureEventsBurstLimit,i=this.captureEventsPerSecond,o=this.zi(),a=this.Ui("$session_id")?(s=(r=this.instance).get_session_id)==null?void 0:s.call(r):void 0,l=[e+" event(s) dropped since the last warning",o?"triggered on "+o:void 0,a?"session "+a:void 0].filter(Boolean).join(", ");return!!this.instance.capture("$$client_ingestion_warning",{$$client_ingestion_warning_message:"posthog-js client rate limited: "+l+". Config is set to "+i+" events per second and "+n+" events burst limit."},{skip_client_rate_limiting:!0})}isServerRateLimited(e){var s=this.serverLimits[e||"events"]||!1;return s!==!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 xt.info("Using preloaded remote config",this.remoteConfig),this.Zi(this.remoteConfig),void this.Gi();if(this._instance.Qi())return void xt.warn("Remote config is disabled. Falling back to local config.");this.Wi((e=>{if(!e)return xt.info("No config found after loading remote JS config. Falling back to JSON."),void this.Vi((s=>{this.Zi(s.json,s),this.Gi()}));this.Zi(e),this.Gi()}))}catch(e){xt.error("Error loading remote config",e),this.Zi()}}stop(){this.Ki&&(clearInterval(this.Ki),this.Ki=void 0)}refresh(){!this._instance.Qi()&&C&&C.visibilityState!=="hidden"&&this._instance.reloadFeatureFlags()}Gi(){var e;if(!this.Ki){var s=(e=this._instance.config.remote_config_refresh_interval_ms)!==null&&e!==void 0?e:3e5;s!==0&&(this.Ki=setInterval((()=>{this.refresh()}),s))}}Zi(e,s){!e&&s&&(s.statusCode===0?s.error||xt.warn("Failed to fetch remote config from PostHog."):xt.error("Failed to fetch remote config from PostHog."));try{this._instance.Zi(e?{ok:!0,config:e}:{ok:!1})}catch(n){xt.error("Error applying remote config",n)}if(e?.hasFeatureFlags!==!1&&!this._instance.config.advanced_disable_feature_flags_on_first_load)try{var r;(r=this._instance.featureFlags)==null||r.ensureFlagsLoaded()}catch(n){xt.error("Error loading feature flags",n)}}}var qe=Uint8Array,Ae=Uint16Array,ys=Uint32Array,Zo=new qe([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),Xo=new qe([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),yl=new qe([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Wu=function(t,e){for(var s=new Ae(31),r=0;31>r;++r)s[r]=e+=1<r;++r)for(var i=s[r];s[r+1]>i;++i)n[i]=i-s[r]<<5|r;return[s,n]},zu=Wu(Zo,2),ao=zu[1];zu[0][28]=258,ao[258]=28;for(var wl=Wu(Xo,0)[1],qu=new Ae(32768),ie=0;32768>ie;++ie){var rs=(43690&ie)>>>1|(21845&ie)<<1;qu[ie]=((65280&(rs=(61680&(rs=(52428&rs)>>>2|(13107&rs)<<2))>>>4|(3855&rs)<<4))>>>8|(255&rs)<<8)>>>1}var Ys=function(t,e,s){for(var r=t.length,n=0,i=new Ae(e);r>n;++n)++i[t[n]-1];var o,a=new Ae(e);for(n=0;e>n;++n)a[n]=a[n-1]+i[n-1]<<1;for(o=new Ae(r),n=0;r>n;++n)o[n]=qu[a[t[n]-1]++]>>>15-t[n];return o},Jt=new qe(288);for(ie=0;144>ie;++ie)Jt[ie]=8;for(ie=144;256>ie;++ie)Jt[ie]=9;for(ie=256;280>ie;++ie)Jt[ie]=7;for(ie=280;288>ie;++ie)Jt[ie]=8;var pn=new qe(32);for(ie=0;32>ie;++ie)pn[ie]=5;var Op=Ys(Jt,9),Dp=Ys(pn,5),Vu=function(t){return(t/8>>0)+(7&t&&1)},Gu=function(t,e,s){(s==null||s>t.length)&&(s=t.length);var r=new(t instanceof Ae?Ae:t instanceof ys?ys:qe)(s-e);return r.set(t.subarray(e,s)),r},ot=function(t,e,s){var r=e/8>>0;t[r]|=s<<=7&e,t[r+1]|=s>>>8},Rs=function(t,e,s){var r=e/8>>0;t[r]|=s<<=7&e,t[r+1]|=s>>>8,t[r+2]|=s>>>16},fi=function(t,e){for(var s=[],r=0;t.length>r;++r)t[r]&&s.push({s:r,f:t[r]});var n=s.length,i=s.slice();if(!n)return[new qe(0),0];if(n==1){var o=new qe(s[0].s+1);return o[s[0].s]=1,[o,1]}s.sort((function(F,P){return F.f-P.f})),s.push({s:-1,f:25001});var a=s[0],l=s[1],u=0,c=1,d=2;for(s[0]={s:-1,f:a.f+l.f,l:a,r:l};c!=n-1;)a=s[s[d].f>s[u].f?u++:d++],l=s[u!=c&&s[d].f>s[u].f?u++:d++],s[c++]={s:-1,f:a.f+l.f,l:a,r:l};var h=i[0].s;for(r=1;n>r;++r)i[r].s>h&&(h=i[r].s);var p=new Ae(h+1),f=lo(s[c-1],p,0);if(f>e){r=0;var g=0,m=f-e,_=1<r;++r){var b=i[r].s;if(e>=p[b])break;g+=_-(1<>>=m;g>0;){var E=i[r].s;e>p[E]?g-=1<=0&&g;--r){var I=i[r].s;p[I]==e&&(--p[I],++g)}f=e}return[new qe(p),f]},lo=function(t,e,s){return t.s==-1?Math.max(lo(t.l,e,s+1),lo(t.r,e,s+1)):e[t.s]=s},bl=function(t){for(var e=t.length;e&&!t[--e];);for(var s=new Ae(++e),r=0,n=t[0],i=1,o=function(l){s[r++]=l},a=1;e>=a;++a)if(t[a]==n&&a!=e)++i;else{if(!n&&i>2){for(;i>138;i-=138)o(32754);i>2&&(o(i>10?i-11<<5|28690:i-3<<5|12305),i=0)}else if(i>3){for(o(n),--i;i>6;i-=6)o(8304);i>2&&(o(i-3<<5|8208),i=0)}for(;i--;)o(n);i=1,n=t[a]}return[s.subarray(0,r),e]},Ts=function(t,e){for(var s=0,r=0;e.length>r;++r)s+=t[r]*e[r];return s},co=function(t,e,s){var r=s.length,n=Vu(e+2);t[n]=255&r,t[n+1]=r>>>8,t[n+2]=255^t[n],t[n+3]=255^t[n+1];for(var i=0;r>i;++i)t[n+i+4]=s[i];return 8*(n+4+r)},El=function(t,e,s,r,n,i,o,a,l,u,c){ot(e,c++,s),++n[256];for(var d=fi(n,15),h=d[0],p=d[1],f=fi(i,15),g=f[0],m=f[1],_=bl(h),b=_[0],E=_[1],I=bl(g),F=I[0],P=I[1],B=new Ae(19),S=0;b.length>S;++S)B[31&b[S]]++;for(S=0;F.length>S;++S)B[31&F[S]]++;for(var A=fi(B,7),R=A[0],N=A[1],T=19;T>4&&!R[yl[T-1]];--T);var O,J,z,H,oe=u+5<<3,pe=Ts(n,Jt)+Ts(i,pn)+o,Ie=Ts(n,h)+Ts(i,g)+o+14+3*T+Ts(B,R)+(2*B[16]+3*B[17]+7*B[18]);if(pe>=oe&&Ie>=oe)return co(e,c,t.subarray(l,l+u));if(ot(e,c,1+(pe>Ie)),c+=2,pe>Ie){O=Ys(h,p),J=h,z=Ys(g,m),H=g;var _e=Ys(R,N);for(ot(e,c,E-257),ot(e,c+5,P-1),ot(e,c+10,T-4),c+=14,S=0;T>S;++S)ot(e,c+3*S,R[yl[S]]);c+=3*T;for(var Ce=[b,F],Re=0;2>Re;++Re){var ae=Ce[Re];for(S=0;ae.length>S;++S)ot(e,c,_e[me=31&ae[S]]),c+=R[me],me>15&&(ot(e,c,ae[S]>>>5&127),c+=ae[S]>>>12)}}else O=Op,J=Jt,z=Dp,H=pn;for(S=0;a>S;++S)if(r[S]>255){var me;Rs(e,c,O[257+(me=r[S]>>>18&31)]),c+=J[me+257],me>7&&(ot(e,c,r[S]>>>23&31),c+=Zo[me]);var ge=31&r[S];Rs(e,c,z[ge]),c+=H[ge],ge>3&&(Rs(e,c,r[S]>>>5&8191),c+=Xo[ge])}else Rs(e,c,O[r[S]]),c+=J[r[S]];return Rs(e,c,O[256]),c+J[256]},Bp=new ys([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),jp=(function(){for(var t=new ys(256),e=0;256>e;++e){for(var s=e,r=9;--r;)s=(1&s&&3988292384)^s>>>1;t[e]=s}return t})(),gi=function(t,e,s){for(;s;++e)t[e]=s,s>>>=8};function Up(t,e){e===void 0&&(e={});var s=(function(){var d=4294967295;return{p(h){for(var p=d,f=0;h.length>f;++f)p=jp[255&p^h[f]]^p>>>8;d=p},d(){return 4294967295^d}}})(),r=t.length;s.p(t);var n,i,o,a,l,u=(a=10+((n=e).filename&&n.filename.length+1||0),l=8,(function(d,h,p,f,g,m){var _=d.length,b=new qe(f+_+5*(1+Math.floor(_/7e3))+g),E=b.subarray(f,b.length-g),I=0;if(!h||8>_)for(var F=0;_>=F;F+=65535){var P=F+65535;_>P?I=co(E,I,d.subarray(F,P)):(E[F]=!0,I=co(E,I,d.subarray(F,_)))}else{for(var B=Bp[h-1],S=B>>>13,A=8191&B,R=(1<F;++F){var me=z(F),ge=32767&F,Ye=T[me];if(N[ge]=Ye,T[me]=ge,F>=Re){var Rt=_-F;if((Ie>7e3||Ce>24576)&&Rt>423){I=El(d,E,0,H,oe,pe,_e,Ce,ae,F-ae,I),Ce=Ie=_e=0,ae=F;for(var de=0;286>de;++de)oe[de]=0;for(de=0;30>de;++de)pe[de]=0}var Ve=2,St=0,Is=A,Be=ge-Ye&32767;if(Rt>2&&me==z(F-Be))for(var Fe=Math.min(S,Rt)-1,vr=Math.min(32767,F),_r=Math.min(258,Rt);vr>=Be&&--Is&&ge!=Ye;){if(d[F+Ve]==d[F+Ve-Be]){for(var je=0;_r>je&&d[F+je]==d[F+je-Be];++je);if(je>Ve){if(Ve=je,St=Be,je>Fe)break;var yr=Math.min(Be,je-2),Qt=0;for(de=0;yr>de;++de){var es=F-Be+de+32768&32767,Cs=es-N[es]+32768&32767;Cs>Qt&&(Qt=Cs,Ye=es)}}}Be+=(ge=Ye)-(Ye=N[ge])+32768&32767}if(St){H[Ce++]=268435456|ao[Ve]<<18|wl[St];var Na=31&ao[Ve],Ma=31&wl[St];_e+=Zo[Na]+Xo[Ma],++oe[257+Na],++pe[Ma],Re=F+Ve,++Ie}else H[Ce++]=d[F],++oe[d[F]]}}I=El(d,E,!0,H,oe,pe,_e,Ce,ae,F-ae,I)}return Gu(b,0,f+Vu(I)+g)})(i=t,(o=e).level==null?6:o.level,o.mem==null?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(i.length)))):12+o.mem,a,l)),c=u.length;return(function(d,h){var p=h.filename;if(d[0]=31,d[1]=139,d[2]=8,d[8]=2>h.level?4:h.level==9?2:0,d[9]=3,h.mtime!=0&&gi(d,4,Math.floor(new Date(h.mtime||Date.now())/1e3)),p){d[3]=8;for(var f=0;p.length>=f;++f)d[f+10]=p.charCodeAt(f)}})(u,e),gi(u,c-8,s.d()),gi(u,c-4,r),u}var Hp=!!Ri||!!Lo,Ku="text/plain",Br=!1,Ju=(t,e)=>{var s=t.split("#"),r=s[1],n=s[0].split("?"),i=n[0],o=n[1];if(!o)return t;var a=o.split("&").filter((l=>l.split("=")[0]!==e)).join("&");return i+(a?"?"+a:"")+(r?"#"+r:"")},Rn=function(t,e,s){var r;s===void 0&&(s=!0);var n=t.split("?"),i=n[0],o=n[1],a=w({},e),l=(r=o?.split("&").map((c=>{var d,h=c.split("="),p=h[0],f=s&&(d=a[p])!==null&&d!==void 0?d:h[1];return delete a[p],p+"="+f})))!==null&&r!==void 0?r:[],u=(function(c,d){var h,p;d===void 0&&(d="&");var f=[];return Z(c,(function(g,m){x(g)||x(m)||m==="undefined"||(h=encodeURIComponent((_=>_ instanceof File)(g)?g.name:g.toString()),p=encodeURIComponent(m),f[f.length]=p+"="+h)})),f.join(d)})(a);return u&&l.push(u),l.length>0?i+"?"+l.join("&"):i},mi=t=>{if(t.Ji)return t.Ji;var e=t.data,s=t.compression;if(e){if(s===xe.GZipJS){var r=Up((function(a,l){var u=a.length;if(typeof TextEncoder<"u")return new TextEncoder().encode(a);for(var c=new qe(a.length+(a.length>>>1)),d=0,h=function(m){c[d++]=m},p=0;u>p;++p){if(d+5>c.length){var f=new qe(d+8+(u-p<<1));f.set(c),c=f}var g=a.charCodeAt(p);128>g?h(g):2048>g?(h(192|g>>>6),h(128|63&g)):g>55295&&57344>g?(h(240|(g=65536+(1047552&g)|1023&a.charCodeAt(++p))>>>18),h(128|g>>>12&63),h(128|g>>>6&63),h(128|63&g)):(h(224|g>>>12),h(128|g>>>6&63),h(128|63&g))}return Gu(c,0,d)})(us(e)),{mtime:0});return{contentType:Ku,body:r.buffer.slice(r.byteOffset,r.byteOffset+r.byteLength),estimatedSize:r.byteLength}}if(s===xe.Base64){var n=(function(a){return a&&btoa(encodeURIComponent(a).replace(/%([0-9A-F]{2})/g,((l,u)=>String.fromCharCode(parseInt(u,16)))))})(us(e)),i=(a=>"data="+encodeURIComponent(typeof a=="string"?a:us(a)))(n);return{contentType:"application/x-www-form-urlencoded",body:i,estimatedSize:new Blob([i]).size}}var o=us(e);return{contentType:"application/json",body:o,estimatedSize:new Blob([o]).size}}},Yu=t=>{var e,s,r=()=>t.transport==="sendBeacon"?{url:Rn(t.url,{compression:xe.Base64}),encodedBody:mi(w({},t,{compression:xe.Base64,Ji:void 0}))}:{url:Ju(t.url,"compression"),encodedBody:mi(w({},t,{compression:void 0,Ji:void 0}))};try{e=mi(t)}catch(n){if(Ha(t.compression,vs(t.url,"compression")))return k.error("Failed to gzip request body, sending uncompressed payload",n),r();throw n}return e&&Ha(t.compression,vs(t.url,"compression"))&&!((s=e.body)instanceof ArrayBuffer?Ti(new Uint8Array(s)):ArrayBuffer.isView(s)&&Ti(new Uint8Array(s.buffer,s.byteOffset,s.byteLength)))?(Br=!0,r()):{url:t.url,encodedBody:e}},Zu=t=>{try{return Yu(t)}catch(e){return k.error(e),void(t.callback==null||t.callback({statusCode:0,error:e}))}},Wp=(function(){var t=X((function*(e){var s=us(e.data),r=yield(function(i,o,a){return Ni.apply(this,arguments)})(s,Y.DEBUG,{rethrow:!0});if(!r)return e;var n=yield r.arrayBuffer();return w({},e,{Ji:{contentType:Ku,body:n,estimatedSize:n.byteLength}})}));return function(e){return t.apply(this,arguments)}})(),zp=/Failed to fetch|NetworkError|Load failed/i,Xu=t=>t?.name==="TypeError"&&zp.test(t?.message||""),Qu=t=>{var e=Zu(t);if(e){var s=e.url,r=e.encodedBody,n=r??{},i=n.contentType,o=n.body,a=n.estimatedSize,l=new Headers;Z(t.headers,(function(f,g){l.append(g,f)})),i&&l.append("Content-Type",i);var u=null,c=!1;if(La){var d=new La;u={signal:d.signal,timeout:setTimeout((()=>{var f,g;c=!0,d.abort((f=t.timeout,(g=new Error("PostHog request timed out"+(f?" after "+f+"ms":""))).name="AbortError",g))}),t.timeout)}}var h=f=>{c&&f?.name==="AbortError"||Xu(f)?k.warn(f):k.error(f),t.callback==null||t.callback({statusCode:0,error:f})};try{var p;Lo(s,w({method:t?.method||"GET",headers:l,keepalive:t.method==="POST"&&!t.Yi&&52428.8>(a||0),body:o,signal:(p=u)==null?void 0:p.signal},t.fetchOptions)).then((f=>f.text().then((g=>{var m={statusCode:f.status,text:g};if(f.status===200)try{m.json=JSON.parse(g)}catch(_){k.error(_)}t.callback==null||t.callback(m)})))).catch(h).finally((()=>u?clearTimeout(u.timeout):null))}catch(f){u&&clearTimeout(u.timeout),h(f)}}},uo=t=>{try{var e,s=Yu(t),r=s.url,n=s.encodedBody,i=n??{},o=i.body,a=i.estimatedSize;if(!o)return;var l=o instanceof Blob?o:new Blob([o],{type:i.contentType});if(ke.sendBeacon(r,l))return;var u=L(t.data)?t.data:(e=t.data)==null?void 0:e.batch;if(L(u)&&u.length>1&&(a??0)>16384){var c=Math.ceil(u.length/2),d=h=>L(t.data)?h:w({},t.data,{batch:h});return uo(w({},t,{data:d(u.slice(0,c))})),void uo(w({},t,{data:d(u.slice(c))}))}k.warn("Beacon of ~"+(a??0)+" bytes was rejected by the browser, falling back to fetch"),Qu(w({},t,{Yi:!0}))}catch(h){k.warn("Beacon send failed",h)}},Sl=(t,e,s,r)=>{var n=r==="query"?e==="POST"?"sent_at":"_":void 0;return Rn(s===xe.GZipJS?Ju(t,"compression"):t,w({},n?{[n]:Date.now().toString()}:{},s===xe.GZipJS?{}:{compression:s}))},jr=[];Lo&&jr.push({transport:"fetch",method:Qu}),Ri&&jr.push({transport:"XHR",method(t){var e=Zu(t);if(e){var s=new Ri,r=e.encodedBody;s.open(t.method||"GET",e.url,!0);var n=r??{},i=n.contentType,o=n.body;Z(t.headers,(function(a,l){s.setRequestHeader(l,a)})),i&&s.setRequestHeader("Content-Type",i),t.timeout&&(s.timeout=t.timeout),s.onreadystatechange=()=>{if(s.readyState===4){var a={statusCode:s.status,text:s.responseText};if(s.status===200)try{a.json=JSON.parse(s.responseText)}catch{}t.callback==null||t.callback(a)}},s.send(o)}}}),ke!=null&&ke.sendBeacon&&jr.push({transport:"sendBeacon",method:uo});var ho=3e3;class qp{constructor(e,s){this.Xi=!0,this.tr=[],this.er=rt(s?.flush_interval_ms||ho,250,5e3,k.createLogger("flush interval"),ho),this.ir=e}enqueue(e){this.tr.push(e),this.rr||this.nr()}unload(){this.sr();var e=this.tr.length>0?this.ar():{},s=Object.values(e);[...s.filter((r=>r.url.indexOf("/e")===0)),...s.filter((r=>r.url.indexOf("/e")!==0))].map((r=>{this.lr(w({},r,{transport:"sendBeacon"}))}))}enable(){this.Xi=!1,this.nr()}nr(){var e=this;this.Xi||(this.rr=setTimeout((()=>{if(this.sr(),this.tr.length>0){var s=this.ar(),r=function(){var i=s[n],o=new Date().getTime();i.data&&L(i.data)&&Z(i.data,(a=>{a.offset=Math.abs(a.timestamp-o),delete a.timestamp})),e.lr(i)};for(var n in s)r()}}),this.er))}lr(e){try{this.ir(e)}catch(s){k.error(s)}}sr(){clearTimeout(this.rr),this.rr=void 0}ar(){var e={};return Z(this.tr,(s=>{var r,n=s,i=(n?n.batchKey:null)||n.url;x(e[i])&&(e[i]=w({},n,{data:[]})),(r=e[i].data)==null||r.push(n.data)})),this.tr=[],e}}var Vp=["retriesPerformedSoFar"];class Gp{constructor(e){this.ur=!1,this.hr=3e3,this.tr=[],this._instance=e,this.tr=[],this.dr=!0,!x(v)&&"onLine"in v.navigator&&(this.dr=v.navigator.onLine,this.vr=()=>{this.dr=!0,this.cr()},this.pr=()=>{this.dr=!1},ne(v,"online",this.vr),ne(v,"offline",this.pr))}get length(){return this.tr.length}retriableRequest(e){var s=e.retriesPerformedSoFar,r=Cc(e,Vp);lt(s)&&(r.url=Rn(r.url,{retry_count:s})),this._instance._send_request(w({},r,{callback:n=>{if(n.statusCode!==200&&(400>n.statusCode||n.statusCode>=500)){if((n.statusCode===0?3:10)>(s??0))return void this.At(w({retriesPerformedSoFar:s},r));n.statusCode===0&&k.warn("Request failed before receiving an HTTP response; this can happen due to network issues, CORS, browser blocking, or ad blockers. Stopped retrying after "+(s??0)+" retries.")}r.callback==null||r.callback(n)}}))}At(e){var s=e.retriesPerformedSoFar||0;e.retriesPerformedSoFar=s+1;var r=(function(o){var a=3e3*Math.pow(2,o),l=a/2,u=Math.min(18e5,a),c=Math.random()-.5;return Math.ceil(u+c*(u-l))})(s),n=Date.now()+r;this.tr.push({retryAt:n,requestOptions:e});var i="Enqueued failed request for retry in "+r;navigator.onLine||(i+=" (Browser is offline)"),k.warn(i),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(),s=[],r=this.tr.filter((i=>e>i.retryAt||(s.push(i),!1)));if(this.tr=s,r.length>0)for(var n of r)this.retriableRequest(n.requestOptions)}unload(){for(var e of(this.mr&&(clearTimeout(this.mr),this.mr=void 0),this.ur=!1,x(v)||(this.vr&&(v.removeEventListener("online",this.vr),this.vr=void 0),this.pr&&(v.removeEventListener("offline",this.pr),this.pr=void 0)),this.tr)){var s=e.requestOptions;try{this._instance._send_request(w({},s,{transport:"sendBeacon"}))}catch(r){k.error(r)}}this.tr=[]}}class Kp{constructor(e){this.yr=()=>{var s,r,n,i;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,(s=this.br.maxScrollY)!==null&&s!==void 0?s:0),this.br.maxScrollHeight=Math.max(l,(r=this.br.maxScrollHeight)!==null&&r!==void 0?r:0),this.br.lastContentY=u,this.br.maxContentY=Math.max(u,(n=this.br.maxContentY)!==null&&n!==void 0?n:0),this.br.maxContentHeight=Math.max(c,(i=this.br.maxContentHeight)!==null&&i!==void 0?i: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(){ne(v,"scroll",this.yr,{capture:!0}),ne(v,"scrollend",this.yr,{capture:!0}),ne(v,"resize",this.yr)}scrollElement(){if(!this._r)return v?.document.documentElement;var e=L(this._r)?this._r:[this._r];for(var s of e){var r=v?.document.querySelector(s);if(r)return r}}wr(e){var s=e==="y"?"scrollTop":"scrollLeft";if(this._r){var r=this.scrollElement();return r&&r[s]||0}return v?e==="y"?v.scrollY||v.pageYOffset||v.document.documentElement.scrollTop||0:v.scrollX||v.pageXOffset||v.document.documentElement.scrollLeft||0:0}scrollY(){return this.wr("y")}scrollX(){return this.wr("x")}}var Jp=t=>Bu(t?.config.mask_personal_data_properties,t?.config.custom_personal_data_properties,t?.config.disable_capture_url_hashes);class xl{constructor(e,s,r,n){this.kr=i=>{var o=this.Sr();if(!o||o.sessionId!==i){var a={sessionId:i,props:this.Cr(this._instance)};this.Mr.register({[Xi]:a})}},this._instance=e,this.Tr=s,this.Mr=r,this.Cr=n||Jp,this.Tr.onSessionId(this.kr)}Sr(){return this.Mr.props[Xi]}getSetOnceProps(){var e,s=(e=this.Sr())==null?void 0:e.props;return s?"r"in s?ju(s,this._instance.config.disable_capture_url_hashes):{$referring_domain:s.referringDomain,$pathname:s.initialPathName,utm_source:s.utm_source,utm_campaign:s.utm_campaign,utm_medium:s.utm_medium,utm_content:s.utm_content,utm_term:s.utm_term}:{}}getSessionProps(){var e={};return Z(Go(this.getSetOnceProps()),((s,r)=>{r==="$current_url"&&(r="url"),e["$session_entry_"+Mi(r)]=s})),e}}class Qo{on(e,s){return this.Er[e]||(this.Er[e]=[]),this.Er[e].push(s),()=>{this.Er[e]=this.Er[e].filter((r=>r!==s))}}emit(e,s){for(var r of this.Er[e]||[])r(s);for(var n of this.Er["*"]||[])n(e,s)}constructor(){this.Er={}}}var Ns=se("[SessionId]");class kl{on(e,s){return this.Ir.on(e,s)}constructor(e,s,r){var n;if(this.Pr=null,this.Rr=[],this.Ar=void 0,this.Fr=!1,this.Ir=new Qo,this.Lr=(u,c)=>!(!lt(u)||!lt(c))&&Math.abs(u-c)>this.sessionTimeoutMs,!e.persistence)throw new Error("SessionIdManager requires a PostHogPersistence instance");if(e.config.cookieless_mode===ht)throw new Error('SessionIdManager cannot be used with cookieless_mode="always"');this.Ne=e.config,this.Mr=e.persistence,this.Or=void 0,this.Dr=void 0,this._sessionStartTimestamp=null,this._sessionActivityTimestamp=null,this.$r=s||dt,this.Nr=r||dt;var i=this.Ne.persistence_name||this.Ne.token;if(this._sessionTimeoutMs=1e3*rt(this.Ne.session_idle_timeout_seconds||1800,60,36e3,Ns.createLogger("session_idle_timeout_seconds"),1800),e.register({$configured_session_timeout_ms:this._sessionTimeoutMs}),this.qr(),this.jr="ph_"+i+"_window_id",this.Br="ph_"+i+"_primary_window_exists",this.Hr()){var o=ce.H(this.jr),a=ce.H(this.Br);o&&!a?this.Or=o:ce.q(this.jr),ce.F(this.Br,!0)}if((n=this.Ne.bootstrap)!=null&&n.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){Ns.error("Invalid sessionID in bootstrap",u)}this.zr()}get sessionTimeoutMs(){return this._sessionTimeoutMs}onSessionId(e){return x(this.Rr)&&(this.Rr=[]),this.Rr.push(e),this.Dr&&e(this.Dr,this.Or),()=>{this.Rr=this.Rr.filter((s=>s!==e))}}Hr(){return this.Ne.persistence!=="memory"&&!this.Mr.xi&&ce.N()}Wr(e){e!==this.Or&&(this.Or=e,this.Hr()&&ce.F(this.jr,e))}Vr(){return this.Or?this.Or:this.Hr()?ce.H(this.jr):null}Zr(e){var s=this.Pr;return!$e(s)&&!$e(e)&&5e3>Math.abs(e-s)}Ur(e,s,r){var n=s!==this._sessionActivityTimestamp,i=!(e!==this.Dr||r!==this._sessionStartTimestamp);this._sessionStartTimestamp=r,this._sessionActivityTimestamp=s,this.Dr=e,i&&!n||i&&this.Zr(s)||(this.Pr=s,this.Mr.register({[cs]:[s,e,r]}))}Gr(){var e,s=(e=this.Ne)==null?void 0:e.persistence_save_debounce_ms;return lt(s)&&s>0}Qr(){this.Gr()?this.Mr.refreshKey(cs):(this.Mr.flush(),this.Mr.load())}Kr(){var e;if(!$e(this._sessionActivityTimestamp)&&this._sessionActivityTimestamp!==this.Pr){this.Qr();var s=this.Jr();s[1]===this.Dr&&s[2]===this._sessionStartTimestamp&&(this.Pr=this._sessionActivityTimestamp,this.Mr.register({[cs]:[this._sessionActivityTimestamp,(e=this.Dr)!==null&&e!==void 0?e:null,this._sessionStartTimestamp]}),this.Mr.flush())}}Yr(){var e=this.Jr()[0],s=lt(e)?e:0,r=lt(this._sessionActivityTimestamp)?this._sessionActivityTimestamp:0;return Math.max(s,r)}Xr(e){return this.Qr(),this.Lr(e,this.Yr())}Jr(){var e=this.Mr.props[cs];return L(e)&&e.length===2&&e.push(e[0]),e||[0,null,0]}resetSessionId(){this.Pr=null,clearTimeout(this.tn),this.tn=void 0,this.Ur(null,null,null)}destroy(){this.Fr=!0,this.Kr(),clearTimeout(this.tn),this.tn=void 0,this.Ar&&v&&(v.removeEventListener(an,this.Ar,{capture:!1}),this.Ar=void 0),this.Rr=[]}zr(){this.Ar=()=>{this.Kr(),this.Hr()&&ce.q(this.Br)},ne(v,an,this.Ar,{capture:!1})}checkAndGetSessionAndWindowId(e,s){if(e===void 0&&(e=!1),s===void 0&&(s=null),this.Ne.cookieless_mode===ht)throw new Error('checkAndGetSessionAndWindowId should not be called with cookieless_mode="always"');var r=s||new Date().getTime(),n=this.Jr(),i=n[1],o=n[2],a=this.Yr(),l=this.Vr(),u=lt(o)&&Math.abs(r-o)>864e5,c=!1,d=!1,h=!i,p=i,f=!h&&!e&&this.Lr(r,a);if(f){(f=this.Xr(r))||Ns.info("cross-tab refresh kept the session alive",{sessionId:i});var g=this.Jr();i=g[1],o=g[2]}h||f||u?(i=this.$r(),l=this.Nr(),Ns.info("new session ID generated",{sessionId:i,windowId:l,changeReason:{noSessionId:h,activityTimeout:f,sessionPastMaximumLength:u}}),o=r,c=!0):(l||(l=this.Nr(),c=!0),(d=i!==p)&&(Ns.info("adopted cross-tab session id",{sessionId:i,windowId:l}),c=!0));var m=lt(a)&&e&&!u?a:r,_=lt(o)?o:new Date().getTime();this.Wr(l),this.Ur(i,m,_),e||this.qr();var b={noSessionId:h,activityTimeout:f,sessionPastMaximumLength:u,crossTabAdoption:d};return c&&this.Rr.forEach((E=>E(i,l,b))),{sessionId:i,windowId:l,sessionStartTimestamp:_,changeReason:c?b:void 0,lastActivityTimestamp:a}}qr(){this.Fr||(clearTimeout(this.tn),this.tn=setTimeout((()=>{if(!this.Fr)if(this.Xr(new Date().getTime())){var e=this.Dr;this.resetSessionId(),this.Ir.emit("forcedIdleReset",{idleSessionId:e})}else this.qr()}),1.1*this.sessionTimeoutMs))}}var ed=function(t,e){if(!t)return!1;var s=t.userAgent;if(s&&za(s,e))return!0;try{var r=t?.userAgentData;if(r!=null&&r.brands&&r.brands.some((n=>za(n?.brand,e))))return!0}catch{}return!!t.webdriver};function td(){return(td=X((function*(){var t=ke?.userAgentData;if(t!=null&&t.getHighEntropyValues)try{var e=yield t.getHighEntropyValues(["model"]),s=e?.model;return W(s)&&s.length>0?s:void 0}catch(r){return void k.info("Unable to resolve $device_model from userAgentData.getHighEntropyValues",r)}}))).apply(this,arguments)}var fn=function(t,e){if(!(function(s){try{new RegExp(s)}catch{return!1}return!0})(e))return!1;try{return new RegExp(e).test(t)}catch{return!1}};function vi(t,e,s){return us({distinct_id:t,userPropertiesToSet:e,userPropertiesToSetOnce:s})}var sd={exact:(t,e)=>e.some((s=>t.some((r=>s===r)))),is_not:(t,e)=>e.every((s=>t.every((r=>s!==r)))),regex:(t,e)=>e.some((s=>t.some((r=>fn(s,r))))),not_regex:(t,e)=>e.every((s=>t.every((r=>!fn(s,r))))),icontains:(t,e)=>e.map(Fr).some((s=>t.map(Fr).some((r=>s.includes(r))))),not_icontains:(t,e)=>e.map(Fr).every((s=>t.map(Fr).every((r=>!s.includes(r))))),gt:(t,e)=>e.some((s=>{var r=parseFloat(s);return!isNaN(r)&&t.some((n=>r>parseFloat(n)))})),lt:(t,e)=>e.some((s=>{var r=parseFloat(s);return!isNaN(r)&&t.some((n=>rt.toLowerCase();function rd(t,e){return!t||Object.entries(t).every((s=>{var r=s[1],n=e?.[s[0]];if(x(n)||$e(n))return!1;var i=[String(n)],o=sd[r.operator];return!!o&&o(r.values,i)}))}var po="custom",Il="i.posthog.com",Yp=/^\/static\//;class Zp{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,s=(e=this.instance.config.ui_host)==null?void 0:e.replace(/\/$/,"");return s||(s=this.apiHost.replace("."+Il,".posthog.com")),s==="https://app.posthog.com"?"https://us.posthog.com":s}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":po),this.en[this.apiHost]}rn(e){if(Yp.test(e)){var s=this.instance.config.asset_host;if(typeof s=="string")return s.trim().replace(/\/$/,"")||void 0}}endpointFor(e,s){if(s===void 0&&(s=""),s&&(s=s[0]==="/"?s:"/"+s),e==="ui")return this.uiHost+s;if(e==="flags")return this.flagsApiHost+s;if(e==="assets"){var r=this.rn(s);if(r)return""+r+s}if(this.region===po)return this.apiHost+s;var n=Il+s;switch(e){case"assets":return"https://"+this.region+"-assets."+n;case"api":return"https://"+this.region+"."+n}}}function nd(t){var e;return!((e=t.conditions)==null||(e=e.events)==null||(e=e.values)==null||!e.length)}var q=se("[Surveys]"),id="seenSurvey_",od=t=>{try{var e=(s=>((r,n)=>""+id+(function(i){return i.current_iteration&&i.current_iteration>0?i.id+"_"+i.current_iteration:i.id})(n))(0,s))(t);if(localStorage.getItem(e))return;localStorage.setItem(e,"true")}catch(s){q.error("Failed to persist survey seen state",s)}},Xp=[hi.Popover,hi.Widget,hi.API],Qp={ignoreConditions:!1,ignoreDelay:!1,displayType:oo.Popover},ef=se("[PostHog ExternalIntegrations]"),tf={intercom:"intercom-integration",crispChat:"crisp-chat-integration"};class sf{constructor(e){this._instance=e}ai(e,s){var r;(r=$.__PosthogExtensions__)==null||r.loadExternalDependency==null||r.loadExternalDependency(this._instance,e,(n=>{if(n)return ef.error("failed to load script",n);s()}))}startIfEnabledOrStop(){var e=this,s=function(){var i,o,a,l=r[0],u=r[1];!u||(i=$.__PosthogExtensions__)!=null&&(i=i.integrations)!=null&&i[l]||e.ai(tf[l],(()=>{var c;(c=$.__PosthogExtensions__)==null||(c=c.integrations)==null||(c=c[l])==null||c.start(e._instance)})),!u&&(o=$.__PosthogExtensions__)!=null&&(o=o.integrations)!=null&&o[l]&&((a=$.__PosthogExtensions__)==null||(a=a.integrations)==null||(a=a[l])==null||a.stop())};for(var r of Object.entries((n=this._instance.config.integrations)!==null&&n!==void 0?n:{})){var n;s()}}}class rf{constructor(e,s){this.rt=e,this.nn=s,this.sn=new Map,this.an=!1}add(e){var s=this;return X((function*(){if(s.an)throw new Error("Cannot add an extension to a disposed ExtensionRuntime");if(s.sn.has(e.name))throw new Error('Browser extension "'+e.name+'" is already registered');s.sn.set(e.name,e);try{var r=e.setup(s.nn);r&&(yield r)}catch(i){var n=s.sn.get(e.name)===e;n&&s.sn.delete(e.name),s.rt.error('Failed to set up browser extension "'+e.name+'"',i),n&&s.ln(e)}}))()}dispose(){if(!this.an){this.an=!0;var e=Array.from(this.sn.values()).reverse();for(var s of(this.sn.clear(),e))this.ln(s)}}ln(e){try{var s=e.dispose==null?void 0:e.dispose();s&&Se(s.then)&&s.then(void 0,(r=>{this.rt.error('Failed to dispose browser extension "'+e.name+'"',r)}))}catch(r){this.rt.error('Failed to dispose browser extension "'+e.name+'"',r)}}}class nf{constructor(e){this._instance=e}initialize(){}get(e){var s=this._instance.persistence;if(typeof e=="string")return s?.get_property(e);var r={};for(var n of e){var i=s?.get_property(n);x(i)||(r[n]=i)}return r}set(e,s){var r;(r=this._instance.persistence)==null||r.register(typeof e=="string"?{[e]:s}:e)}remove(e){var s;(s=this._instance.persistence)==null||s.unregister(e)}}var Cl="extensionsRemoteConfig";class of{constructor(e){this.an=!1,this.instance=e,this.rt=k,this.un=e.hn,this.kv=new nf(e),this.onEvent=s=>Cr(this.instance.on("eventCaptured",(r=>{try{s({event:r.event,properties:r.properties})}catch(n){this.rt.error("Browser extension event listener failed",n)}}))),this.onRemoteConfig=s=>{if(this.an)return Cr((()=>{}));var r=i=>{try{s(i)}catch(o){this.rt.error("Browser extension remote config listener failed",o)}},n=this.instance.dn.on(Cl,r);return this.un&&r(this.un),Cr(n)},this.vn=new rf(k.createLogger("[BrowserExtensions]"),this)}get logger(){return this.rt}get distinctId(){return this.instance.get_distinct_id()}get anonymousId(){var e;return(e=this.instance.get_property(rr))!==null&&e!==void 0?e:this.distinctId}get deviceId(){var e=this.instance.get_property(rr);return typeof e=="string"?e:void 0}get library(){return{name:Y.LIB_NAME,version:Y.LIB_VERSION}}get initialPersonProperties(){var e,s;return(e=(s=this.instance.persistence)==null?void 0:s.get_initial_props())!==null&&e!==void 0?e:{}}get groups(){return this.instance.getGroups()}get session(){try{var e,s,r,n,i=(e=this.instance.sessionManager)==null?void 0:e.checkAndGetSessionAndWindowId(!0);return{sessionId:(s=i?.sessionId)!==null&&s!==void 0?s:"",windowId:(r=i?.windowId)!==null&&r!==void 0?r:"",sessionStartTimestamp:(n=i?.sessionStartTimestamp)!==null&&n!==void 0?n:0}}catch{return{sessionId:"",windowId:"",sessionStartTimestamp:0}}}get projectToken(){return this.instance.config.token}add(e){return this.vn.add(e)}capture(e,s,r){var n=this;return X((function*(){r?n.instance.capture(e,s,{timestamp:r.timestamp,uuid:r.uuid,$set:r.set,$set_once:r.setOnce}):n.instance.capture(e,s)}))()}registerDynamicEventProperties(e){return Cr(this.instance.cn(e))}handleRemoteConfig(e){this.an||(this.un=e,this.instance.dn.emit(Cl,e))}sendRequest(e,s){var r=this;return X((function*(){var n;s===void 0&&(s={});var i=r.instance.requestRouter.endpointFor((n=s.target)!==null&&n!==void 0?n:"api",e),o={method:s.method,url:s.query?Rn(i,s.query):i,data:s.body,headers:s.headers,timeout:s.timeoutMs,fireCallbackOnDrop:!0,transport:s.transport,compression:s.compression,timestampMode:s.sentAt};return s.transport==="sendBeacon"?(r.instance._send_request(o),{statusCode:202}):new Promise((a=>{o.callback=a,r.instance._send_request(o)}))}))()}dispose(){this.an||(this.an=!0,this.vn.dispose())}}var Zs={},_i=0,gn=()=>{},Fl='Consent opt in/out is not valid with cookieless_mode="always" and will be ignored',Ms="Surveys module not available",Pl="sanitize_properties is deprecated. Use before_send instead",ad="Invalid value for property_denylist config: ",af=["token","distinct_id",fu],as="posthog",ld=!Hp&&Pe?.indexOf("MSIE")===-1&&Pe?.indexOf("Mozilla")===-1,yi=t=>{var e;return w({api_host:"https://us.i.posthog.com",flags_api_host:null,ui_host:null,asset_host:null,token:"",autocapture:!0,cross_subdomain_cookie:ap(C?.location),persistence:"localStorage+cookie",persistence_name:"",cookie_persisted_properties:[],loaded:gn,save_campaign_params:!0,custom_campaign_params:[],custom_blocked_useragents:[],save_referrer:!0,capture_pageleave:"if_capture_pageview",defaults:t??"unset",__preview_deferred_init_extensions:!1,__preview_external_dependency_versioned_paths:!1,__preview_cookie_wins_on_conflict:!1,debug:re&&W(re?.search)&&re.search.indexOf("__posthog_debug=true")!==-1||!1,cookie_expiration:365,upgrade:!1,disable_session_recording:!1,disable_persistence:!1,disable_web_experiments:!0,disable_surveys:!1,disable_surveys_automatic_display:!1,disable_conversations:!1,disable_product_tours:!1,disableDeviceModel:!1,disable_external_dependency_loading:!1,strict_script_versioning:!1,enable_recording_console_log:void 0,secure_cookie:(v==null||(e=v.location)==null?void 0:e.protocol)==="https:",ip:!1,opt_out_capturing_by_default:!1,opt_out_persistence_by_default:!1,opt_out_useragent_filter:!1,opt_out_capturing_persistence_type:"localStorage",consent_persistence_name:null,opt_out_capturing_cookie_prefix:null,opt_in_site_apps:!1,property_denylist:[],respect_dnt:!1,sanitize_properties:null,request_headers:{},request_batching:!0,properties_string_max_length:65535,mask_all_element_attributes:!1,mask_all_text:!1,mask_personal_data_properties:!1,custom_personal_data_properties:[],advanced_disable_flags:!1,advanced_disable_decide:!1,advanced_disable_feature_flags:!1,advanced_disable_feature_flags_on_first_load:!1,advanced_only_evaluate_survey_feature_flags:!1,advanced_feature_flags_dedup_per_session:!1,advanced_enable_surveys:!1,advanced_disable_toolbar_metrics:!1,feature_flag_request_timeout_ms:3e3,surveys_request_timeout_ms:1e4,on_request_error(s){k.error("Bad HTTP status: "+s.statusCode+" "+s.text)},get_device_id:s=>s,capture_performance:void 0,name:"posthog",bootstrap:{},disable_compression:!1,session_idle_timeout_seconds:1800,person_profiles:so,before_send:void 0,get_current_url:void 0,request_queue_config:{flush_interval_ms:ho},error_tracking:{},_onCapture:gn},(s=>({rageclick:s&&s>="2026-05-30"?{content_ignorelist:yp,ignore_text_selection:!0}:!s||"2025-11-30">s||{content_ignorelist:!0},capture_pageview:!s||"2025-05-24">s||"history_change",session_recording:s&&s>="2026-06-25"?{strictMinimumDuration:!0,canvasCapture:{resolutionScale:.6},streamNetworkBody:!0}:s&&s>="2026-05-30"?{strictMinimumDuration:!0,canvasCapture:{resolutionScale:.6}}:s&&s>="2025-11-30"?{strictMinimumDuration:!0}:{},external_scripts_inject_target:s&&s>="2026-01-30"?"head":"body",internal_or_test_user_hostname:s&&s>="2026-01-30"?/^(localhost|127\.0\.0\.1)$/:void 0,persistence_save_debounce_ms:s&&s>="2026-05-30"?250:0,split_storage:!(!s||"2026-05-30">s),detect_google_search_app:!(!s||"2026-05-30">s),disable_capture_url_hashes:!(!s||"2026-06-25">s)}))(t))},lf=[["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"]],Al=t=>{var e={};for(var s of lf){var r=s[0],n=s[1];x(t[r])||(e[n]=t[r])}var i=ee({},e,t),o=t.__preview_external_dependency_versioned_paths;return x(o)||(x(t.strict_script_versioning)&&(i.strict_script_versioning=!!o),W(o)&&x(t.asset_host)&&(i.asset_host=o)),L(t.property_blacklist)&&(x(t.property_denylist)?i.property_denylist=t.property_blacklist:L(t.property_denylist)?i.property_denylist=[...t.property_blacklist,...t.property_denylist]:k.error(ad+t.property_denylist)),i};class cf{constructor(){this.__forceAllowLocalhost=!1}get fn(){return this.__forceAllowLocalhost}set fn(e){k.error("WebPerformanceObserver is deprecated and has no impact on network capture. Use `_forceAllowLocalhostNetworkCapture` on `posthog.sessionRecording`"),this.__forceAllowLocalhost=e}}class Te{pn(e,s){if(e){var r=this.sn.indexOf(e);r!==-1&&this.sn.splice(r,1)}return this.sn.push(s),s.initialize==null||s.initialize(),s}gn(){return this.config.cookieless_mode===ht||this.config.cookieless_mode===Ht&&this.consent.isRejected()}get decideEndpointWasHit(){var e,s;return(e=(s=this.featureFlags)==null?void 0:s.hasLoadedFlags)!==null&&e!==void 0&&e}get flagsEndpointWasHit(){var e,s;return(e=(s=this.featureFlags)==null?void 0:s.hasLoadedFlags)!==null&&e!==void 0&&e}constructor(){var e;this.webPerformance=new cf,this.mn=!1,this.version=Y.LIB_VERSION,this.yn=new Set,this.bn="",this.dn=new Qo,this.sn=[],this._n=[],this._calculate_event_properties=this.calculateEventProperties.bind(this),this.config=yi(),this.SentryIntegration=Cp,this.sentryIntegration=r=>(function(n,i){var o=Ru(n,i);return{name:$u,processEvent:a=>o(a)}})(this,r),this.__request_queue=[],this.__loaded=!1,this.analyticsDefaultEndpoint="/e/",this.wn=!1,this.kn=null,this.xn=null,this.Sn=null,this.scrollManager=new Kp(this),this.pageViewManager=new gl(this),this.rateLimiter=new Lp(this),this.requestRouter=new Zp(this),this.consent=new fp(this),this.externalIntegrations=new sf(this);var s=(e=Te.__defaultExtensionClasses)!==null&&e!==void 0?e:{};this.featureFlags=s.featureFlags&&new s.featureFlags(this),this.toolbar=s.toolbar&&new s.toolbar(this),this.surveys=s.surveys&&new s.surveys(this),this.conversations=s.conversations&&new s.conversations(this),this.logs=s.logs&&new s.logs(this),this.metrics=s.metrics&&new s.metrics(this),this.experiments=s.experiments&&new s.experiments(this),this.exceptions=s.exceptions&&new s.exceptions(this),this.people={set:(r,n,i)=>{var o=W(r)?{[r]:n}:r;this.setPersonProperties(o),i?.({})},set_once:(r,n,i)=>{var o=W(r)?{[r]:n}:r;this.setPersonProperties(void 0,o),i?.({})}},this.on("eventCaptured",(r=>k.info('send "'+r?.event+'"',r)))}init(e,s,r){if(r&&r!==as){var n,i=(n=Zs[r])!==null&&n!==void 0?n:new Te;return i._init(e,s,r),Zs[r]=i,Zs[as][r]=i,i}return this._init(e,s,r)}_init(e,s,r){var n,i;s===void 0&&(s={});var o,a=W(e)?e.trim():"";if(!a)return k.critical("PostHog was initialized without a token. This likely indicates a misconfiguration. Please check the first argument passed to posthog.init()"),this;if(this.__loaded)return a!==((o=this.config)==null?void 0:o.token)?console.warn("[PostHog.js]","You have already initialized PostHog with a different project token! Re-initializing is a no-op, so events will keep going to the project this instance was initialized with. To capture into a second project, load PostHog once, then initialize a named instance after the SDK has loaded, e.g. posthog.init('"+a+"', { ... }, 'project2')"):console.warn("[PostHog.js]","You have already initialized PostHog! Re-initializing is a no-op"),this;this.__loaded=!0,this.config=yi(s.defaults),s.debug=this.Cn(s.debug),this.Mn=s,this.Tn=[],s.person_profiles?this.xn=s.person_profiles:s.process_person&&(this.xn=s.process_person);var l=yi(s.defaults),u=Al(s),c=ee({},l,u,{name:r,token:a});te(l.rageclick)&&te(u.rageclick)&&(c.rageclick=ee({},l.rageclick,u.rageclick)),te(l.session_recording)&&te(u.session_recording)&&(c.session_recording=ee({},l.session_recording,u.session_recording)),this.set_config(c),this.config.on_xhr_error&&k.error("on_xhr_error is deprecated. Use on_request_error instead"),this.compression=s.disable_compression?void 0:xe.GZipJS;var d=this.En();if(this.persistence=new di(this.config,d),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new di(w({},this.config,{persistence:"sessionStorage"}),d,!1),this.bn="ph_"+(this.config.persistence_name||this.config.token)+"_session_registered_properties",this.config.persistence!=="memory"&&!d&&ce.N()){var h=ce.H(this.bn);L(h)&&h.forEach((P=>{W(P)&&this.yn.add(P)}))}else ce.q(this.bn);var p=w({},this.persistence.props),f=w({},this.sessionPersistence.props);this.register({$initialization_time:new Date().toISOString()}),this.In=new qp((P=>this.Pn(P)),this.config.request_queue_config),this.Rn=new Gp(this),this.__request_queue=[];var g=this.gn();if(g||(this.sessionManager=new kl(this),this.sessionPropsManager=new xl(this,this.sessionManager,this.persistence),this.sessionManager.onSessionId(((P,B,S)=>{(S!=null&&S.activityTimeout||S!=null&&S.sessionPastMaximumLength||S!=null&&S.crossTabAdoption)&&this.An()}))),this.Fn(),this.config.__preview_deferred_init_extensions?(k.info("Deferring extension initialization to improve startup performance"),setTimeout((()=>{this.Ln(g)}),0)):(k.info("Initializing extensions synchronously"),this.Ln(g)),Y.DEBUG=Y.DEBUG||this.config.debug,Y.DEBUG&&k.info("Starting in debug mode",{this:this,config:s,thisC:w({},this.config),p,s:f}),!this.config.identity_distinct_id||(n=s.bootstrap)!=null&&n.distinctID||(s.bootstrap=w({},s.bootstrap,{distinctID:this.config.identity_distinct_id,isIdentifiedID:!0})),((i=s.bootstrap)==null?void 0:i.distinctID)!==void 0){var m=s.bootstrap.distinctID,_=this.get_distinct_id(),b=this.persistence.get_property(He);if(s.bootstrap.isIdentifiedID&&_!=null&&_!==m&&b===ts)this.identify(m);else if(s.bootstrap.isIdentifiedID&&_!=null&&_!==m&&b===Tt)k.warn("Bootstrap distinctID differs from an already-identified user. The existing identity is preserved. Call reset() before reinitializing if you intend to switch users.");else{var E=this.config.get_device_id(dt()),I=s.bootstrap.isIdentifiedID?E:m;this.persistence.set_property(He,s.bootstrap.isIdentifiedID?Tt:ts),this.register({distinct_id:m,$device_id:I})}}if(g)this.register_once({distinct_id:Er,$device_id:null},"");else if(!this.get_distinct_id()){var F=this.config.get_device_id(dt());this.register_once({distinct_id:F,$device_id:F},""),this.persistence.set_property(He,ts)}return ne(v,"onpagehide"in self?"pagehide":"unload",this._handle_unload.bind(this),{passive:!1}),s.segment?(function(P,B){var S=P.config.segment;if(!S)return B();(function(A,R){var N=A.config.segment;if(!N)return R();var T=J=>{var z=()=>J.anonymousId()||dt();A.config.get_device_id=z,J.id()&&(A.register({distinct_id:J.id(),$device_id:z()}),A.persistence.set_property(He,Tt)),R()},O=N.user();"then"in O&&Se(O.then)?O.then(T):T(O)})(P,(()=>{S.register((A=>{typeof Promise<"u"&&Promise.resolve||ci.warn("This browser does not have Promise support, and can not use the segment integration");var R=(N,T)=>{if(!T)return N;N.event.userId||N.event.anonymousId===A.get_distinct_id()||(ci.info("No userId set, resetting PostHog"),A.reset()),N.event.userId&&N.event.userId!==A.get_distinct_id()&&(ci.info("UserId set, identifying with PostHog"),A.identify(N.event.userId));var O=A.calculateEventProperties(T,N.event.properties);return N.event.properties=Object.assign({},O,N.event.properties),N};return{name:"PostHog JS",type:"enrichment",version:"1.0.0",isLoaded:()=>!0,load:()=>Promise.resolve(),track:N=>R(N,N.event.event),page:N=>R(N,os),identify:N=>R(N,oi),screen:N=>R(N,"$screen")}})(P)).then((()=>{B()}))}))})(this,(()=>this.On())):this.On(),Se(this.config._onCapture)&&this.config._onCapture!==gn&&(k.warn("onCapture is deprecated. Please use `before_send` instead"),this.on("eventCaptured",(P=>this.config._onCapture(P.event,P)))),this.config.ip&&k.warn('The `ip` config option has NO EFFECT AT ALL and has been deprecated. Use a custom transformation or "Discard IP data" project setting instead. See https://posthog.com/tutorials/web-redact-properties#hiding-customer-ip-address for more information.'),this.config.disableDeviceModel||(function(){return td.apply(this,arguments)})().then((P=>{P&&this.register({[ni]:P})})).catch(gn),this}Fn(){var e,s,r,n,i,o,a=(e=(s=this.config.__extensionClasses)==null?void 0:s.featureFlags)!==null&&e!==void 0?e:(r=Te.__defaultExtensionClasses)==null?void 0:r.featureFlags;a&&(this.featureFlags&&this.featureFlags instanceof a||((n=this.Dn)==null||n.call(this),this.Dn=void 0,this.featureFlags=new a(this)),Se(this.featureFlags.onReloading)&&Se(this.featureFlags.setup)?this.Dn||(this.Dn=this.featureFlags.onReloading((()=>{this.dn.emit("featureFlagsReloading",!0)})),this.$n().add(this.featureFlags)):(i=(o=this.featureFlags).initialize)==null||i.call(o))}Ln(e){var s,r,n,i,o,a,l,u=performance.now(),c=w({},Te.__defaultExtensionClasses,this.config.__extensionClasses),d=[];c.exceptions&&this.sn.push(this.exceptions=(s=this.exceptions)!==null&&s!==void 0?s:new c.exceptions(this)),c.historyAutocapture&&this.sn.push(this.historyAutocapture=new c.historyAutocapture(this)),c.tracingHeaders&&this.sn.push(this.tracingHeaders=new c.tracingHeaders(this)),c.siteApps&&this.sn.push(this.siteApps=new c.siteApps(this)),c.sessionRecording&&!e&&this.sn.push(this.sessionRecording=new c.sessionRecording(this)),this.config.disable_scroll_properties||d.push((()=>{this.scrollManager.startMeasuringScrollPosition()})),c.autocapture&&this.sn.push(this.autocapture=new c.autocapture(this)),c.surveys&&this.sn.push(this.surveys=(r=this.surveys)!==null&&r!==void 0?r:new c.surveys(this)),c.logs&&this.sn.push(this.logs=(n=this.logs)!==null&&n!==void 0?n:new c.logs(this)),c.metrics&&this.sn.push(this.metrics=(i=this.metrics)!==null&&i!==void 0?i: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,Ip)),c.toolbar&&this.sn.push(this.toolbar=(a=this.toolbar)!==null&&a!==void 0?a:new c.toolbar(this)),c.experiments&&this.sn.push(this.experiments=(l=this.experiments)!==null&&l!==void 0?l:new c.experiments(this)),this.sn.forEach((h=>{h.initialize&&d.push((()=>{h.initialize==null||h.initialize()}))})),d.push((()=>{if(this.Nn){var h=this.Nn;this.Nn=void 0,this.sn.forEach((p=>p.onRemoteConfig==null?void 0:p.onRemoteConfig(h)))}})),this.qn(d,u)}qn(e,s){for(;e.length>0;){if(this.config.__preview_deferred_init_extensions&&performance.now()-s>=30&&e.length>0)return void setTimeout((()=>{this.qn(e,s)}),0);var r=e.shift();if(r)try{r()}catch(i){k.error("Error initializing extension:",i)}}var n=Math.round(performance.now()-s);this.register_for_session({[gu]:this.config.__preview_deferred_init_extensions?"deferred":"synchronous",[mu]:n}),this.config.__preview_deferred_init_extensions&&k.info("PostHog extensions initialized ("+n+"ms)")}Zi(e){var s;if(!C||!C.body)return k.info("document not ready yet, trying again in 500 milliseconds..."),void setTimeout((()=>{this.Zi(e)}),500);if(this.config.__preview_deferred_init_extensions&&(this.Nn=e),this.hn=e,this.compression=void 0,e.ok){var r,n=e.config;n.supportedCompression&&!this.config.disable_compression&&(this.compression=M(n.supportedCompression,xe.GZipJS)?xe.GZipJS:M(n.supportedCompression,xe.Base64)?xe.Base64:void 0),(r=n.analytics)!=null&&r.endpoint&&(this.analyticsDefaultEndpoint=n.analytics.endpoint)}this.set_config({person_profiles:this.xn?this.xn:so}),(s=this.jn)==null||s.handleRemoteConfig(e),this.sn.forEach((i=>i.onRemoteConfig==null?void 0:i.onRemoteConfig(e)))}On(){try{this.config.loaded(this)}catch(r){k.critical("`loaded` function failed",r)}if(this.Bn(),this.config.internal_or_test_user_hostname&&re!=null&&re.hostname){var e=re.hostname,s=this.config.internal_or_test_user_hostname;(typeof s=="string"?e===s:s.test(e))&&this.setInternalOrTestUser()}this.config.capture_pageview&&setTimeout((()=>{(this.consent.isOptedIn()||this.gn())&&this.Hn()}),1),this.Un=new Hu(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,s,r,n,i;(e=this.surveys)==null||e.handlePageUnload==null||e.handlePageUnload(),(s=this.metrics)==null||s.flush("sendBeacon"),this.config.request_batching?(this.zn()&&this.capture(ii),(r=this.logs)==null||r.flushLogs("sendBeacon"),(n=this.In)==null||n.unload(),(i=this.Rn)==null||i.unload()):this.zn()&&this.capture(ii,null,{transport:"sendBeacon"})}_send_request(e){this.__loaded?ld?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=w({},this.config.request_headers,e.headers),e.compression=e.compression==="best-available"?this.compression:e.compression,(x(this.config.disable_beacon)?this.config.__preview_disable_beacon:this.config.disable_beacon)&&(e.disableTransport=["sendBeacon"]),e.fetchOptions=e.fetchOptions||this.config.fetch_options,(s=>{var r,n,i,o=w({},s);o.timeout=o.timeout||6e4;var a,l,u,c,d,h=(r=o.transport)!==null&&r!==void 0?r:"fetch";h==="sendBeacon"&&x(o.compression)&&o.data&&(o.compression=xe.Base64),o.method==="POST"&&o.data&&(o.timestampMode==="capture-body"?o.data={api_key:(l=(d=(c=L(a=o.data)?a:[a])[0])==null||(u=d.properties)==null?void 0:u.token)!==null&&l!==void 0?l:d?.token,batch:c,sent_at:new Date().toISOString()}:o.timestampMode==="body"&&(o.data=(function(m,_){return _===void 0&&(_=new Date().toISOString()),L(m)?m.map((b=>w({},b,{sent_at:_}))):w({},m,{sent_at:_})})(o.data))),o.url=Sl(o.url,o.method,o.compression,o.timestampMode);var p=jr.filter((m=>!o.disableTransport||!m.transport||!o.disableTransport.includes(m.transport))),f=(n=(i=(function(m,_){for(var b=0;m.length>b;b++)if(m[b].transport===h)return m[b]})(p))==null?void 0:i.method)!==null&&n!==void 0?n:p[0].method;if(!f)throw new Error("No available transport method");var g=m=>{try{f(m)}catch(_){Xu(_)?k.warn(_):k.error(_),o.callback==null||o.callback({statusCode:0,error:_})}};h!=="sendBeacon"&&o.data&&o.compression===xe.GZipJS&&ch&&typeof Promise<"u"&&!Br?Wp(o).then((m=>{g(m)})).catch((m=>{if(Wa(m))return Br=!0,void g(w({},o,{compression:void 0,url:Sl(s.url,s.method,void 0,s.timestampMode)}));(_=>{if(!_||typeof _!="object")return!1;var b="name"in _?String(_.name):"";return Wa(_)||b===Fc})(m)&&(Br=!0),g(o)})):f(o)})(w({},e,{callback:s=>{var r,n;this.rateLimiter.checkForLimiting(s),400>s.statusCode||(r=(n=this.config).on_request_error)==null||r.call(n,s),e.callback==null||e.callback(s)}}))):e.fireCallbackOnDrop&&(e.callback==null||e.callback({statusCode:0}))}Pn(e){this.Rn?this.Rn.retriableRequest(e):this._send_request(e)}_execute_array(e){_i++;try{var s,r=[],n=[],i=[];Sr(e,(a=>{if(a)if(L(s=a[0]))i.push(a);else if(Se(a))try{a.call(this)}catch(l){k.error("Error executing queued PostHog call",a,l)}else L(a)&&s==="alias"?r.push(a):L(a)&&s.indexOf("capture")!==-1&&Se(this[s])?i.push(a):n.push(a)}));var o=function(a,l){Sr(a,(function(u){try{if(L(u[0])){var c=l;Z(u,(function(d){c=c[d[0]].apply(c,d.slice(1))}))}else l[u[0]].apply(l,u.slice(1))}catch(d){k.error("Error executing queued PostHog call",u,d)}}))};o(r,this),o(n,this),o(i,this)}finally{_i--}}push(e){if(_i>0&&L(e)&&W(e[0])){var s=Te.prototype[e[0]];Se(s)&&s.apply(this,e.slice(1))}else this._execute_array([e])}capture(e,s,r){var n,i,o,a,l;if(this.__loaded&&this.persistence&&this.sessionPersistence&&this.In){if(this.is_capturing())if(!x(e)&&W(e)){var u=!this.config.opt_out_useragent_filter&&this._is_bot();if(!u||this.config.__preview_capture_bot_pageviews){var c=r!=null&&r.skip_client_rate_limiting?void 0:this.rateLimiter.clientRateLimitContext();if(c==null||!c.isRateLimited){s!=null&&s.$current_url&&!W(s?.$current_url)&&(k.error("Invalid `$current_url` property provided to `posthog.capture`. Input must be a string. Ignoring provided value."),s==null||delete s.$current_url),e!=="$exception"||r!=null&&r.Wn||k.warn("Using `posthog.capture('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureException(error)` instead, which attaches required metadata automatically."),this.sessionPersistence.update_search_keyword(),this.config.save_campaign_params&&this.sessionPersistence.update_campaign_params(),this.config.save_referrer&&this.sessionPersistence.update_referrer_info(),(this.config.save_campaign_params||this.config.save_referrer)&&this.persistence.set_initial_person_info();var d=new Date,h=r?.timestamp||d,p=Ka(r?.uuid,dt),f={uuid:p,event:e,properties:this.calculateEventProperties(e,s||{},h,p)};e===os&&this.config.__preview_capture_bot_pageviews&&u&&(f.event="$bot_pageview",f.properties.$browser_type="bot"),c&&(f.properties.$lib_rate_limit_remaining_tokens=c.remainingTokens);var g=e==="$feature_flag_called"&&f.properties.$feature_flag_has_experiment===!1&&this.get_property(tn)===!0;r?.$set&&!g&&(f.$set=r?.$set);var m=r?.$unset;m&&(f.$unset=m);var _,b,E,I=g?void 0:this.Vn(r?.$set_once,e!==el,e===oi);if(I&&(f.$set_once=I),r!=null&&r._noTruncate||(i=this.config.properties_string_max_length,o=f,a=T=>W(T)?T.slice(0,i):T,l=new Set,f=(function T(O,J){if(O!==Object(O))return a?a(O):O;if(!l.has(O)){var z;if(l.add(O),L(O))z=[],Sr(O,(oe=>{z.push(T(oe))}));else{var H={};Z(O,((oe,pe)=>{l.has(oe)||(H[pe]=T(oe))})),z=H}return z}})(o)),f.timestamp=h,x(r?.timestamp)||(f.properties.$event_time_override_provided=!0,f.properties.$event_time_override_system_time=d),g&&(f.properties=(function(T,O){O===void 0&&(O=[]);var J={},z=H=>{T[H]!==void 0&&(J[H]=T[H])};return uh.forEach(z),O.forEach(z),J})(f.properties,af)),e===ft.DISMISSED||e===ft.SENT){var F=s?.[pi.SURVEY_ID],P=s?.[pi.SURVEY_ITERATION];od({id:F,current_iteration:P}),f.$set=w({},f.$set,{[(_={id:F,current_iteration:P},b=e===ft.SENT?"responded":"dismissed",E="$survey_"+b+"/"+_.id,_.current_iteration&&_.current_iteration>0&&(E="$survey_"+b+"/"+_.id+"/"+_.current_iteration),E)]:!0})}else e===ft.SHOWN&&(f.$set=w({},f.$set,{[pi.SURVEY_LAST_SEEN_DATE]:new Date().toISOString()}));if(e===Mp.SHOWN){var B=s?.[vl.TOUR_TYPE];B&&(f.$set=w({},f.$set,{[vl.TOUR_LAST_SEEN_DATE+"/"+B]:new Date().toISOString()}))}var S=w({},f.properties.$set,f.$set);if(mt(S)||this.setPersonPropertiesForFlags(S),!D(this.config.before_send)){var A=this.Pt(f);if(!A)return;(f=A).uuid=Ka(f.uuid,dt)}this.dn.emit("eventCaptured",f);var R=(n=r?._url)!==null&&n!==void 0?n:this.requestRouter.endpointFor("api",this.analyticsDefaultEndpoint),N={method:"POST",url:R,data:f,compression:"best-available",timestampMode:r?._batchKey==="recordings"||/\/s\/(?:\?|$)/.test(R)?"body":"capture-body",batchKey:r?._batchKey,transport:r?.transport};return!this.config.request_batching||r&&(r==null||!r._batchKey)||r!=null&&r.send_instantly?this.Pn(N):this.In.enqueue(N),f}k.critical("This capture call is ignored due to client rate limiting.")}}else k.error("No event name provided to posthog.capture")}else k.uninitializedWarning("posthog.capture")}_addCaptureHook(e){return this.on("eventCaptured",(s=>e(s.event,s)))}$n(){var e;return(e=this.jn)!==null&&e!==void 0?e:this.jn=new of(this)}cn(e){this._n.push(e);var s=!0;return()=>{if(s){s=!1;var r=this._n.indexOf(e);r!==-1&&this._n.splice(r,1)}}}calculateEventProperties(e,s,r,n,i){if(r=r||new Date,!this.persistence||!this.sessionPersistence)return s;var o=i?void 0:this.persistence.remove_event_timer(e),a=w({},s);if(a.token=this.config.token,a.$config_defaults=this.config.defaults,this.gn()&&(a[fu]=!0),e==="$snapshot"){var l=w({},this.persistence.properties(),this.sessionPersistence.properties());return a.distinct_id=l.distinct_id,(!W(a.distinct_id)&&!he(a.distinct_id)||Li(a.distinct_id))&&k.error("Invalid distinct_id for replay event. This indicates a bug in your implementation"),a}var u,c=(function(F,P,B,S){var A,R,N,T;if(S===void 0&&(S=!1),!Pe)return{};var O,J=F?[..._s,...P||[]]:[],z=(function(_r){for(var je=0;Va.length>je;je++){var yr=Va[je],Qt=yr[1],es=yr[0].exec(_r),Cs=es&&(Se(Qt)?Qt(es,_r):Qt);if(Cs)return Cs}return["",""]})(Pe),H=z[0],oe=z[1],pe=(O=typeof navigator<"u"?navigator:void 0)!=null&&O.brave?{brave:!0}:{},Ie={};x(B)||(Ie.detectGoogleSearchApp=B);var _e={},Ce=(A=navigator)==null||(A=A.userAgentData)==null?void 0:A.platform,Re=(R=navigator)==null?void 0:R.maxTouchPoints,ae=v==null||(N=v.screen)==null?void 0:N.width,me=v==null||(T=v.screen)==null?void 0:T.height,ge=v?.devicePixelRatio;x(Ce)||(_e.userAgentDataPlatform=Ce),x(Re)||(_e.maxTouchPoints=Re),x(ae)||(_e.screenWidth=ae),x(me)||(_e.screenHeight=me),x(ge)||(_e.devicePixelRatio=ge);var Ye,Rt,de,Ve,St,Is,Be,Fe,vr=ee(Go({$os:H,$os_version:oe,$browser:Qc(Pe,navigator.vendor,pe,Ie),$device:Ga(Pe),$device_type:(Rt=Pe,de=_e,Fe=Ga(Rt),Fe===Mc||Fe===Nc||Fe==="Kobo"||Fe==="Kindle Fire"||Fe===Kc?fs:Fe===tr||Fe===hs||Fe===sr||Fe===Di?"Console":Fe===Oc?"Wearable":Fe?Oe:de?.userAgentDataPlatform==="Android"&&((Ve=de?.maxTouchPoints)!==null&&Ve!==void 0?Ve:0)>0?600>Math.min((St=de?.screenWidth)!==null&&St!==void 0?St:0,(Is=de?.screenHeight)!==null&&Is!==void 0?Is:0)/((Be=de?.devicePixelRatio)!==null&&Be!==void 0?Be:1)?Oe:fs:"Desktop"),$timezone:Uu(),$timezone_offset:Rp()}),{$current_url:ir(S?Ct(re?.href):re?.href,J,or),$host:re?.host,$pathname:re?.pathname,$raw_user_agent:Pe.length>1e3?Pe.substring(0,997)+"...":Pe,$browser_version:Ph(Pe,navigator.vendor,pe,Ie),$browser_language:ml(),$browser_language_prefix:(Ye=ml(),typeof Ye=="string"?Ye.split("-")[0]:void 0),$screen_height:v?.screen.height,$screen_width:v?.screen.width,$viewport_height:v?.innerHeight,$viewport_width:v?.innerWidth,$lib:Y.LIB_NAME,$lib_version:Y.LIB_VERSION,$insert_id:Math.random().toString(36).substring(2,10)+Math.random().toString(36).substring(2,10),$time:Date.now()/1e3});return Y.SDK_DIST_CHANNEL&&(vr.$sdk_dist_channel=Y.SDK_DIST_CHANNEL),vr})(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(i,r.getTime()),h=d.windowId;a.$session_id=d.sessionId,a.$window_id=h}this.sessionPropsManager&&ee(a,this.sessionPropsManager.getSessionProps());try{var p;this.sessionRecording&&ee(a,this.sessionRecording.sdkDebugProperties),a.$sdk_debug_retry_queue_size=(p=this.Rn)==null?void 0:p.length}catch(F){a.$sdk_debug_error_capturing_properties=String(F)}if(this.requestRouter.region===po&&(a.$lib_custom_api_host=this.config.api_host),u=e!==os||i?e!==ii||i?this.pageViewManager.doEvent():this.pageViewManager.doPageLeave(r):this.pageViewManager.doPageView(r,n),a=ee(a,u),e===os&&C&&(a.title=C.title),!x(o)){var f=r.getTime()-o;a.$duration=parseFloat((f/1e3).toFixed(3))}Pe&&this.config.opt_out_useragent_filter&&(a.$browser_type=this._is_bot()?"bot":"browser");var g=this.persistence.properties(),m=this.sessionPersistence.properties();Z(["$referrer","$referring_domain"],(F=>{F in g&&delete m[F]}));var _={};if(this._n.length>0)for(var b of this._n.slice())try{ee(_,b())}catch(F){k.error("Failed to produce browser extension event properties",F)}(a=ee({},c,g,m,w({},_,a))).$is_identified=this._isIdentified(),L(this.config.property_denylist)?Z(this.config.property_denylist,(function(F){delete a[F]})):k.error(ad+this.config.property_denylist+" or property_blacklist config: "+this.config.property_blacklist);var E=this.config.sanitize_properties;E&&(k.error(Pl),a=E(a,e));var I=this.Zn();return a.$process_person_profile=I,I&&!i&&this.Gn("_calculate_event_properties"),a}Vn(e,s,r){var n;if(s===void 0&&(s=!0),r===void 0&&(r=!1),!this.persistence||!this.Zn()||this.mn&&!r)return e;var i=this.persistence.get_initial_props(),o=(n=this.sessionPropsManager)==null?void 0:n.getSetOnceProps(),a=ee({},i,o||{},e||{}),l=this.config.sanitize_properties;return l&&(k.error(Pl),a=l(a,"$set_once")),s&&(this.mn=!0),mt(a)?void 0:a}register(e,s){var r;(r=this.persistence)==null||r.register(e,s)}register_once(e,s,r){var n;(n=this.persistence)==null||n.register_once(e,s,r)}register_for_session(e){var s;(s=this.sessionPersistence)==null||s.register(e),Object.keys(e).forEach((r=>this.yn.add(r))),this.Qn()}unregister(e){var s;(s=this.persistence)==null||s.unregister(e)}unregister_for_session(e){var s;(s=this.sessionPersistence)==null||s.unregister(e),this.yn.delete(e),this.Qn()}Kn(e,s){this.register({[e]:s})}An(){this.yn.forEach((e=>{var s;(s=this.sessionPersistence)==null||s.unregister(e)})),this.yn.clear(),this.Qn()}Qn(){var e;if(this.bn)if(this.config.persistence==="memory"||(e=this.sessionPersistence)!=null&&e.xi||!ce.N())ce.q(this.bn);else{var s=[];this.yn.forEach((r=>s.push(r))),s.length>0?ce.F(this.bn,s):ce.q(this.bn)}}getFeatureFlag(e,s){var r;return(r=this.featureFlags)==null?void 0:r.getFeatureFlag(e,s)}getFeatureFlagPayload(e){var s;return(s=this.featureFlags)==null?void 0:s.getFeatureFlagPayload(e)}getFeatureFlagResult(e,s){var r;return(r=this.featureFlags)==null?void 0:r.getFeatureFlagResult(e,s)}getAllFeatureFlags(){var e,s;return(e=(s=this.featureFlags)==null?void 0:s.getAllFeatureFlags())!==null&&e!==void 0?e:[]}isFeatureEnabled(e,s){var r,n;return(r=(n=this.featureFlags)==null?void 0:n.isFeatureEnabled(e,s))!==null&&r!==void 0?r:s?.defaultValue}reloadFeatureFlags(){var e;(e=this.featureFlags)==null||e.reloadFeatureFlags()}updateFlags(e,s,r){var n;(n=this.featureFlags)==null||n.updateFlags(e,s,r)}updateEarlyAccessFeatureEnrollment(e,s,r){var n;(n=this.featureFlags)==null||n.updateEarlyAccessFeatureEnrollment(e,s,r)}getEarlyAccessFeatures(e,s,r){var n;return s===void 0&&(s=!1),(n=this.featureFlags)==null?void 0:n.getEarlyAccessFeatures(e,s,r)}on(e,s){return this.dn.on(e,s)}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:Ms}),()=>{})}onSessionId(e){var s,r;return(s=(r=this.sessionManager)==null?void 0:r.onSessionId(e))!==null&&s!==void 0?s:()=>{}}getSurveys(e,s){s===void 0&&(s=!1),this.surveys?this.surveys.getSurveys(e,s):e([],{isLoaded:!1,error:Ms})}getActiveMatchingSurveys(e,s){s===void 0&&(s=!1),this.surveys?this.surveys.getActiveMatchingSurveys(e,s):e([],{isLoaded:!1,error:Ms})}renderSurvey(e,s){var r;(r=this.surveys)==null||r.renderSurvey(e,s)}displaySurvey(e,s){var r;s===void 0&&(s=Qp),(r=this.surveys)==null||r.displaySurvey(e,s)}cancelPendingSurvey(e){var s;(s=this.surveys)==null||s.cancelPendingSurvey(e)}canRenderSurvey(e){var s,r;return(s=(r=this.surveys)==null?void 0:r.canRenderSurvey(e))!==null&&s!==void 0?s:{visible:!1,disabledReason:Ms}}canRenderSurveyAsync(e,s){var r,n;return s===void 0&&(s=!1),(r=(n=this.surveys)==null?void 0:n.canRenderSurveyAsync(e,s))!==null&&r!==void 0?r:Promise.resolve({visible:!1,disabledReason:Ms})}Jn(e){return!e||Li(e)?(k.critical("Unique user id has not been set in posthog.identify"),!1):e===Er?(k.critical('The string "'+e+'" was set in posthog.identify which indicates an error. This ID is only used as a sentinel value.'),!1):!["distinct_id","distinctid"].includes(e.toLowerCase())&&!["undefined","null"].includes(e.toLowerCase())||(k.critical('The string "'+e+'" was set in posthog.identify which indicates an error. This ID should be unique to the user and not a hardcoded string.'),!1)}identify(e,s,r){if(!this.__loaded||!this.persistence)return k.uninitializedWarning("posthog.identify");if(he(e)&&(e=e.toString(),k.warn("The first argument to posthog.identify was a number, but it should be a string. It has been converted to a string.")),this.Jn(e)&&this.Gn("posthog.identify")){var n=this.get_distinct_id();this.register({$user_id:e}),this.get_property(rr)||this.register_once({$had_persisted_distinct_id:!0,$device_id:n},""),e!==n&&e!==this.get_property(js)&&(this.unregister(js),this.register({distinct_id:e}));var i,o=(this.persistence.get_property(He)||ts)===ts,a=e!==n,l=!a&&o;if(a&&o)this.persistence.set_property(He,Tt),this.setPersonPropertiesForFlags({$set:s||{},$set_once:r||{}},!1),this.capture(oi,{distinct_id:e,$anon_distinct_id:n},{$set:s||{},$set_once:r||{}}),this.Sn=vi(e,s,r),(i=this.featureFlags)==null||i.setAnonymousDistinctId(n);else if(l){this.persistence.set_property(He,Tt);var u=s||{},c=r||{};this.setPersonPropertiesForFlags({$set:u,$set_once:c},!1),this.capture("$set",{$set:u,$set_once:c}),this.Sn=vi(e,s,r)}else(s||r)&&this.setPersonProperties(s,r);a?(this.reloadFeatureFlags(),this.featureFlags?this.featureFlags.resetFlagCallReported():this.unregister(Wt)):l&&(s||r)&&this.reloadFeatureFlags()}}setPersonProperties(e,s){if((e||s)&&this.Gn("posthog.setPersonProperties")){var r=vi(this.get_distinct_id(),e,s);this.Sn!==r?(this.setPersonPropertiesForFlags({$set:e||{},$set_once:s||{}},!0),this.capture("$set",{$set:e||{},$set_once:s||{}}),this.Sn=r):k.info("A duplicate setPersonProperties call was made with the same properties. It has been ignored.")}}unsetPersonProperties(e){var s,r=(L(e)?e:[e]).filter((n=>W(n)&&n.length>0));r.length!==0&&this.Gn("posthog.unsetPersonProperties")&&((s=this.featureFlags)==null||s.unsetPersonPropertiesForFlags(r,!0),this.capture("$set",{$unset:r}),this.Sn=null)}group(e,s,r){if(e&&s){var n=this.getGroups(),i=n[e]!==s;if(i&&this.resetGroupPropertiesForFlags(e),this.register({$groups:w({},n,{[e]:s})}),i||r){var o={$group_type:e,$group_key:s};r&&(o.$group_set=r),this.capture(el,o)}r&&this.setGroupPropertiesForFlags({[e]:r}),i&&!r&&this.reloadFeatureFlags()}else k.error("posthog.group requires a group type and group key")}resetGroups(){this.register({$groups:{}}),this.resetGroupPropertiesForFlags(),this.reloadFeatureFlags()}setPersonPropertiesForFlags(e,s){var r;s===void 0&&(s=!0),(r=this.featureFlags)==null||r.setPersonPropertiesForFlags(e,s)}resetPersonPropertiesForFlags(e){var s;e===void 0&&(e=!0),(s=this.featureFlags)==null||s.resetPersonPropertiesForFlags(e)}setGroupPropertiesForFlags(e,s){var r;s===void 0&&(s=!0),this.Gn("posthog.setGroupPropertiesForFlags")&&((r=this.featureFlags)==null||r.setGroupPropertiesForFlags(e,s))}resetGroupPropertiesForFlags(e){var s;(s=this.featureFlags)==null||s.resetGroupPropertiesForFlags(e)}reset(e){this.Yn(e)}Yn(e,s){var r,n,i,o,a,l,u,c,d,h;if(s===void 0&&(s=!1),k.info("reset"),!this.__loaded)return k.uninitializedWarning("posthog.reset");var p,f=this.get_property(rr),g=this.get_property(ni),m=this.get_property(Vt),_=this.is_capturing();if(this.consent.reset(),s||!_||this.is_capturing()||console.warn("[PostHog.js]","reset() cleared the stored consent, and capturing is now off because of `opt_out_capturing_by_default`. Call opt_in_capturing() again, and prefer calling reset() before opting in rather than after."),(r=this.persistence)==null||r.clear(),(n=this.sessionPersistence)==null||n.clear(),this.yn.clear(),this.Qn(),x(m)||(p=this.persistence)==null||p.register({[Vt]:m}),(i=this.surveys)==null||i.reset(),(o=this.Un)==null||o.stop(),(a=this.featureFlags)==null||a.reset(),(l=this.conversations)==null||l.reset(),(u=this.logs)==null||u.reset(),(c=this.metrics)==null||c.reset(),(d=this.persistence)==null||d.set_property(He,ts),(h=this.sessionManager)==null||h.resetSessionId(),this.Sn=null,this.config.cookieless_mode===ht)this.register_once({distinct_id:Er,$device_id:null},"");else{var b=this.config.get_device_id(dt());this.register_once({distinct_id:b,$device_id:e?b:f},""),e||x(g)||this.register({[ni]: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 s=this;return X((function*(){var r,n,i,o,a,l,u;if(s.__loaded){(r=s.Un)==null||r.stop(),(n=s.jn)==null||n.dispose(),(i=s.sessionRecording)==null||i.dispose(),(o=s.logs)==null||o.flushLogs("sendBeacon"),(a=s.metrics)==null||a.flush("sendBeacon"),(l=s.In)==null||l.unload(),(u=s.Rn)==null||u.unload();try{var c;(c=s.featureFlags)==null||c.destroy()}catch(d){k.error("Error while destroying feature flags",d)}}else k.uninitializedWarning("posthog.shutdown")}))()}setIdentity(e,s){var r;this.config.identity_distinct_id=e,this.config.identity_hash=s,this.alias(e),(r=this.conversations)==null||r.Xn()}clearIdentity(){var e;delete this.config.identity_distinct_id,delete this.config.identity_hash,(e=this.conversations)==null||e.ts()}get_distinct_id(){return this.get_property("distinct_id")}getGroups(){return this.get_property("$groups")||{}}get_session_id(){var e,s;return(e=(s=this.sessionManager)==null?void 0:s.checkAndGetSessionAndWindowId(!0).sessionId)!==null&&e!==void 0?e:""}get_session_replay_url(e){if(!this.sessionManager)return"";var s=this.sessionManager.checkAndGetSessionAndWindowId(!0),r=s.sessionStartTimestamp,n=this.requestRouter.endpointFor("ui","/project/"+this.config.token+"/replay/"+s.sessionId);if(e!=null&&e.withTimestamp&&r){var i,o=(i=e.timestampLookBack)!==null&&i!==void 0?i:10;if(!r)return n;n+="?t="+Math.max(Math.floor((new Date().getTime()-r)/1e3)-o,0)}return n}alias(e,s){return e===this.get_property(lu)?(k.critical("Attempting to create alias for existing People user - aborting."),-2):this.Gn("posthog.alias")?(x(s)&&(s=this.get_distinct_id()),e!==s?(this.Kn(js,e),this.capture("$create_alias",{alias:e,distinct_id:s})):(k.warn("alias matches current distinct_id - skipping api call."),this.identify(e),-1)):void 0}set_config(e){var s=w({},this.config);if(te(e)){var r,n,i,o,a,l,u,c,d,h,p,f;ee(this.config,Al(e));var g=this.En();(r=this.persistence)==null||r.update_config(this.config,s,g),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new di(w({},this.config,{persistence:"sessionStorage"}),g,!1);var m=this.Cn(this.config.debug);Ke(m)&&(this.config.debug=m),Ke(this.config.debug)&&(this.config.debug?(Y.DEBUG=!0,Q.N()&&Q.F("ph_debug",!0),k.info("set_config",{config:e,oldConfig:s,newConfig:w({},this.config)})):(Y.DEBUG=!1,Q.N()&&Q.q("ph_debug"))),(n=this.featureFlags)==null||n.updateConfig==null||n.updateConfig(this.config,this.Qi()),(i=this.exceptionObserver)==null||i.onConfigChange(),(o=this.exceptions)==null||o.onConfigChange(),(a=this.sessionRecording)==null||a.startIfEnabledOrStop(),(l=this.tracingHeaders)==null||l.startIfEnabledOrStop(),(u=this.autocapture)==null||u.startIfEnabled(),(c=this.heatmaps)==null||c.startIfEnabled(),(d=this.exceptionObserver)==null||d.startIfEnabledOrStop(),(h=this.deadClicksAutocapture)==null||h.startIfEnabledOrStop(),(p=this.surveys)==null||p.loadIfEnabled(),this.es(),(f=this.externalIntegrations)==null||f.startIfEnabledOrStop()}}_overrideSDKInfo(e,s){Y.LIB_NAME=e,Y.LIB_VERSION=s}startSessionRecording(e){var s,r,n,i,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)&&((s=this.sessionManager)==null||s.checkAndGetSessionAndWindowId(),l.sampling&&((r=this.sessionRecording)==null||r.overrideSampling()),l.linked_flag&&((n=this.sessionRecording)==null||n.overrideLinkedFlag()),l.url_trigger&&((i=this.sessionRecording)==null||i.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,s){if(this.exceptions){var r=new Error("PostHog syntheticException"),n=this.exceptions.buildProperties(e,{handled:!0,syntheticException:r});return this.exceptions.sendExceptionEvent(w({},n,s))}}addExceptionStep(e,s){var r;(r=this.exceptions)==null||r.addExceptionStep(e,s)}captureLog(e){var s;(s=this.logs)==null||s.captureLog(e)}get logger(){var e,s;return(e=(s=this.logs)==null?void 0:s.logger)!==null&&e!==void 0?e:Te.rs}startExceptionAutocapture(e){this.set_config({capture_exceptions:e==null||e})}stopExceptionAutocapture(){this.set_config({capture_exceptions:!1})}loadToolbar(e){var s,r;return(s=(r=this.toolbar)==null?void 0:r.loadToolbar(e))!==null&&s!==void 0&&s}get_property(e){var s;return(s=this.persistence)==null?void 0:s.props[e]}getSessionProperty(e){var s;return(s=this.sessionPersistence)==null?void 0:s.props[e]}toString(){var e,s=(e=this.config.name)!==null&&e!==void 0?e:as;return s!==as&&(s=as+"."+s),s}_isIdentified(){var e,s;return((e=this.persistence)==null?void 0:e.get_property(He))===Tt||((s=this.sessionPersistence)==null?void 0:s.get_property(He))===Tt}Zn(){var e,s;return!(this.config.person_profiles==="never"||this.config.person_profiles===so&&!this._isIdentified()&&mt(this.getGroups())&&((e=this.persistence)==null||(e=e.props)==null||!e[js])&&((s=this.persistence)==null||(s=s.props)==null||!s[nn]))}zn(){return this.config.capture_pageleave===!0||this.config.capture_pageleave==="if_capture_pageview"&&(this.config.capture_pageview===!0||this.config.capture_pageview==="history_change")}createPersonProfile(){this.Zn()||this.Gn("posthog.createPersonProfile")&&this.setPersonProperties({},{})}setInternalOrTestUser(){this.Gn("posthog.setInternalOrTestUser")&&this.setPersonProperties({$internal_or_test_user:!0})}Gn(e){return this.config.person_profiles==="never"?(k.error(e+' was called, but process_person is set to "never". This call will be ignored.'),!1):(this.Kn(nn,!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!==Ht)}es(){var e,s,r,n,i=this.En();return((e=this.persistence)==null?void 0:e.xi)!==i&&((r=this.persistence)==null||r.set_disabled(i)),((s=this.sessionPersistence)==null?void 0:s.xi)!==i&&((n=this.sessionPersistence)==null||n.set_disabled(i)),i&&(this.yn.clear(),this.Qn()),i}opt_in_capturing(e){var s;if(this.config.cookieless_mode!==ht){if(this.gn()){var r,n,i,o,a;this.Yn(!0,!0),(r=this.sessionManager)==null||r.destroy(),(n=this.pageViewManager)==null||n.destroy(),this.sessionManager=new kl(this),this.pageViewManager=new gl(this),this.persistence&&(this.sessionPropsManager=new xl(this,this.sessionManager,this.persistence));var l,u=(i=(o=this.config.__extensionClasses)==null?void 0:o.sessionRecording)!==null&&i!==void 0?i:(a=Te.__defaultExtensionClasses)==null?void 0:a.sessionRecording;u&&(this.sessionRecording=this.pn(this.sessionRecording,new u(this)),this.hn&&((l=this.sessionRecording)==null||l.onRemoteConfig==null||l.onRemoteConfig(this.hn)))}var c,d;this.consent.optInOut(!0),this.es(),this.Bn(),(s=this.sessionRecording)==null||s.startIfEnabledOrStop(),this.config.cookieless_mode==Ht&&((c=this.surveys)==null||c.loadIfEnabled()),(x(e?.captureEventName)||e!=null&&e.captureEventName)&&this.capture((d=e?.captureEventName)!==null&&d!==void 0?d:"$opt_in",e?.captureProperties,{send_instantly:!0}),this.config.capture_pageview&&this.Hn()}else k.warn(Fl)}opt_out_capturing(){var e,s,r;this.config.cookieless_mode!==ht?(this.config.cookieless_mode===Ht&&this.consent.isOptedIn()&&this.Yn(!0,!0),this.consent.optInOut(!1),this.es(),this.config.cookieless_mode===Ht&&(this.register({distinct_id:Er,$device_id:null}),(e=this.sessionRecording)==null||e.stopRecording(),this.sessionRecording=void 0,(s=this.sessionManager)==null||s.destroy(),(r=this.pageViewManager)==null||r.destroy(),this.sessionManager=void 0,this.sessionPropsManager=void 0,this.config.capture_pageview&&this.Hn(),this.Bn())):k.warn(Fl)}has_opted_in_capturing(){return this.consent.isOptedIn()}has_opted_out_capturing(){return this.consent.isOptedOut()}get_explicit_consent_status(){var e=this.consent.consent;return e===1?"granted":e===0?"denied":"pending"}is_capturing(){return this.config.cookieless_mode===ht||(this.config.cookieless_mode===Ht?this.consent.isRejected()||this.consent.isOptedIn():!this.has_opted_out_capturing())}clear_opt_in_out_capturing(){this.consent.reset(),this.es()}_is_bot(){return ke?ed(ke,this.config.custom_blocked_useragents):void 0}Hn(){C&&(C.visibilityState==="visible"?this.wn||(this.wn=!0,this.capture(os,{title:C.title},{send_instantly:!0}),this.kn&&(C.removeEventListener(on,this.kn),this.kn=null)):this.kn||(this.kn=this.Hn.bind(this),ne(C,on,this.kn)))}debug(e){e===!1?(v?.console.log("You've disabled debug mode."),this.set_config({debug:!1})):(v?.console.log("You're now in debug mode. All calls to PostHog will be logged in your console.\nYou can disable this with `posthog.debug(false)`."),this.set_config({debug:!0}))}Qi(){var e=this.Mn||{};return"advanced_disable_flags"in e?!!e.advanced_disable_flags:this.config.advanced_disable_flags!==!1?!!this.config.advanced_disable_flags:this.config.advanced_disable_decide===!0?(k.warn("Config field 'advanced_disable_decide' is deprecated. Please use 'advanced_disable_flags' instead. The old field will be removed in a future major version."),!0):(function(s,r,n,i,o){var a=r in s&&!D(s[r]),l=n in s&&!D(s[n]);return a?s[r]:!!l&&(o&&o.warn("Config field '"+n+"' is deprecated. Please use '"+r+"' instead. The old field will be removed in a future major version."),s[n])})(e,"advanced_disable_flags","advanced_disable_decide",0,k)}Pt(e){var s;if(D(this.config.before_send))return e;var r=Object.keys((s=e.properties)!==null&&s!==void 0?s:{}).filter(vh),n=L(this.config.before_send)?this.config.before_send:[this.config.before_send],i=e;for(var o of n){if(i=o(i),D(i)){var a="Event '"+e.event+"' was rejected in beforeSend function";return mh(e.event)?k.warn(a+". This can cause unexpected behavior."):k.info(a),null}i.properties&&!mt(i.properties)||k.warn("Event '"+e.event+"' has no properties after beforeSend function, this is likely an error.")}for(var l of r)if(i.properties&&D(i.properties[l]))return k.warn("Event '"+e.event+"' had its '"+l+"' property removed in a beforeSend function. This property is required for ingestion, so the event will be dropped."),null;return i}getPageViewId(){var e;return(e=this.pageViewManager.ui)==null?void 0:e.pageViewId}captureTraceFeedback(e,s){this.capture("$ai_feedback",{$ai_trace_id:String(e),$ai_feedback_text:s})}captureTraceMetric(e,s,r){this.capture("$ai_metric",{$ai_trace_id:String(e),$ai_metric_name:s,$ai_metric_value:String(r)})}Cn(e){var s=Ke(e)&&!e,r=Q.N()&&Q.P("ph_debug")==="true";return!s&&(!!r||e)}}Te.__defaultExtensionClasses={},Te.rs=(()=>{var t=()=>{};return{trace:t,debug:t,info:t,warn:t,error:t,fatal:t}})(),(function(t,e){for(var s=0;e.length>s;s++)t.prototype[e[s]]=ip(t.prototype[e[s]])})(Te,["identify"]);class $l{constructor(e){this.disabled=e===!1;var s=te(e)?e:{};this.thresholdPx=s.threshold_px||30,this.timeoutMs=s.timeout_ms||1e3,this.clickCount=s.click_count||3,this.clicks=[]}isRageClick(e,s,r){if(this.disabled)return!1;var n=this.clicks[this.clicks.length-1];if(n&&Math.abs(e-n.x)+Math.abs(s-n.y)r-n.timestamp){if(this.clicks.push({x:e,y:s,timestamp:r}),this.clicks.length===this.clickCount)return!0}else this.clicks=[{x:e,y:s,timestamp:r}];return!1}}var wi="$copy_autocapture",bi=se("[AutoCapture]");function Ei(t,e){return e.length>t?e.slice(0,t)+"...":e}function uf(t){if(t.previousElementSibling)return t.previousElementSibling;var e=t;do e=e.previousSibling;while(e&&!Ft(e));return e}function df(t,e){var s,r,n=e.e,i=e.maskAllElementAttributes,o=e.maskAllText,a=e.elementAttributeIgnoreList,l=e.elementsChainAsString,u=e.disableCaptureUrlHashes;if(!Ft(t))return{props:{}};for(var c=[t],d=new Set([t]),h=t;h.parentNode&&!Me(h,"body")&&xu>c.length;)if(Su(h.parentNode)){var p=h.parentNode.host;if(d.has(p))break;d.add(p),c.push(p),h=p}else{if(!Ft(h.parentNode)||d.has(h.parentNode))break;d.add(h.parentNode),c.push(h.parentNode),h=h.parentNode}var f,g,m=[],_={},b=!1,E=!1;if(Z(c,(S=>{var A=io(S);if(Me(S,"a")){var R=S.getAttribute("href");b=!!(A&&R&&Js(R))&&(u?Ct(R):R)}M(cn(S),"ph-no-capture")&&(E=!0),m.push((function(T,O,J,z,H){H===void 0&&(H=!1);var oe=T.tagName.toLowerCase(),pe={tag_name:oe};Jo.indexOf(oe)>-1&&!J&&(pe.$el_text=oe.toLowerCase()==="a"||oe.toLowerCase()==="button"?Ei(1024,hl(T)):Ei(1024,nr(T)));var Ie=cn(T);Ie.length>0&&(pe.classes=Ie.filter((function(ae){return ae!==""}))),Z(T.attributes,(function(ae){var me;if((!Pu(T)||["name","id","class","aria-label"].indexOf(ae.name)!==-1)&&(z==null||!z.includes(ae.name))&&!O&&Js(ae.value)&&(!W(me=ae.name)||me.substring(0,10)!=="_ngcontent"&&me.substring(0,7)!=="_nghost")){var ge=ae.value;ae.name==="class"&&(ge=Ko(ge).join(" ")),pe["attr__"+ae.name]=Ei(1024,ae.name==="href"&&H?Ct(ge):ge)}}));for(var _e=1,Ce=1,Re=T;Re=uf(Re);)_e++,Re.tagName===T.tagName&&Ce++;return pe.nth_child=_e,pe.nth_of_type=Ce,pe})(S,i,o,a,u));var N=(function(T){if(!io(T))return{};var O={};return Z(T.attributes,(function(J){if(J.name&&J.name.indexOf("data-ph-capture-attribute")===0){var z=J.name.replace("data-ph-capture-attribute-",""),H=J.value;z&&H&&Js(H)&&(O[z]=H)}})),O})(S);ee(_,N)})),E)return{props:{},explicitNoCapture:E};if(o||(m[0].$el_text=Me(t,"a")||Me(t,"button")?hl(t):nr(t)),b){var I,F;m[0].attr__href=b;var P=(I=un(b))==null?void 0:I.host,B=v==null||(F=v.location)==null?void 0:F.host;P&&B&&P!==B&&(f=b)}return{props:ee({$event_type:n.type,$ce_version:1},l?{}:{$elements:m},{$elements_chain:(g=m,(function(S){return S.map((A=>{var R,N,T="";if(A.tag_name&&(T+=A.tag_name),A.attr_class)for(var O of(A.attr_class.sort(),A.attr_class))T+="."+O.replace(/"/g,"");var J=w({},A.text?{text:A.text}:{},{"nth-child":(R=A.nth_child)!==null&&R!==void 0?R:0,"nth-of-type":(N=A.nth_of_type)!==null&&N!==void 0?N:0},A.href?{href:A.href}:{},A.attr_id?{attr_id:A.attr_id}:{},A.attributes),z={};return Dr(J).sort(((H,oe)=>H[0].localeCompare(oe[0]))).forEach((H=>{var oe=H[1];return z[pl(H[0].toString())]=pl(oe.toString())})),(T+=":")+Dr(z).map((H=>H[0]+'="'+H[1]+'"')).join("")})).join(";")})((function(S){return S.map((A=>{var R,N,T={text:(R=A.$el_text)==null?void 0:R.slice(0,400),tag_name:A.tag_name,href:(N=A.attr__href)==null?void 0:N.slice(0,2048),attr_class:xp(A),attr_id:A.attr__id,nth_child:A.nth_child,nth_of_type:A.nth_of_type,attributes:{}};return Dr(A).filter((O=>O[0].indexOf("attr__")===0)).forEach((O=>T.attributes[O[0]]=O[1])),T}))})(g)))},(s=m[0])!=null&&s.$el_text?{$el_text:(r=m[0])==null?void 0:r.$el_text}:{},f&&n.type==="click"?{$external_click_url:f}:{},_)}}var Ls=se("[ExceptionAutocapture]"),Rl=()=>{},hf=se("[TracingHeaders]"),Lt=se("[Web Vitals]"),Tl=9e5,Nl="disabled",Ml="lazy_loading",Os="awaiting_config",Pr="missing_config";se("[SessionRecording]"),se("[SessionRecording]");var fo="[SessionRecording]",at=se(fo),pf=se("[Heatmaps]");function Si(t){return te(t)&&"clientX"in t&&"clientY"in t&&he(t.clientX)&&he(t.clientY)}var Ar=se("[Product Tours]"),xi=t=>{var e;return!t.config.disable_product_tours&&!((e=t.persistence)==null||!e.get_property(zo))},ff=["$set_once","$set"],Ze=se("[SiteApps]"),Ll="Error while initializing PostHog app with config id ";function ns(t,e,s){if(D(t))return!1;switch(s){case"exact":return t===e;case"contains":var r=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/_/g,".").replace(/%/g,".*");return new RegExp(r,"i").test(t);case"regex":try{return new RegExp(e).test(t)}catch{return!1}default:return!1}}class gf{constructor(e){this.ns=new Qo,this.ss=(s,r)=>this.os(s,r)&&this.ls(s,r)&&this.us(s,r)&&this.hs(s,r),this.os=(s,r)=>r==null||!r.event||s?.event===r?.event,this._instance=e,this.ds=new Set,this.vs=new Set}init(){var e,s;x((e=this._instance)==null?void 0:e._addCaptureHook)||(s=this._instance)==null||s._addCaptureHook(((r,n)=>{this.on(r,n)}))}register(e){var s,r;if(!x((s=this._instance)==null?void 0:s._addCaptureHook)&&(e.forEach((o=>{var a,l;(a=this.vs)==null||a.add(o),(l=o.steps)==null||l.forEach((u=>{var c;(c=this.ds)==null||c.add(u?.event||"")}))})),(r=this._instance)!=null&&r.autocapture)){var n,i=new Set;e.forEach((o=>{var a;(a=o.steps)==null||a.forEach((l=>{l!=null&&l.selector&&i.add(l?.selector)}))})),(n=this._instance)==null||n.autocapture.setElementSelectors(i)}}on(e,s){var r;s!=null&&e.length!=0&&(this.ds.has(e)||this.ds.has(s.event))&&this.vs&&((r=this.vs)==null?void 0:r.size)>0&&this.vs.forEach((n=>{this.cs(s,n)&&this.ns.emit("actionCaptured",n.name)}))}fs(e){this.onAction("actionCaptured",(s=>e(s)))}cs(e,s){if(s?.steps==null)return!1;for(var r of s.steps)if(this.ss(e,r))return!0;return!1}onAction(e,s){return this.ns.on(e,s)}ls(e,s){if(s!=null&&s.url){var r,n=e==null||(r=e.properties)==null?void 0:r.$current_url;if(!n||typeof n!="string"||!ns(n,s.url,s.url_matching||"contains"))return!1}return!0}us(e,s){return!!this.ps(e,s)&&!!this.gs(e,s)&&!!this.ys(e,s)}ps(e,s){var r;if(s==null||!s.href)return!0;var n=this.bs(e);if(n.length>0)return n.some((a=>ns(a.href,s.href,s.href_matching||"exact")));var i,o=(e==null||(r=e.properties)==null?void 0:r.$elements_chain)||"";return!!o&&ns((i=o.match(/(?::|")href="(.*?)"/))?i[1]:"",s.href,s.href_matching||"exact")}gs(e,s){var r;if(s==null||!s.text)return!0;var n=this.bs(e);if(n.length>0)return n.some((u=>ns(u.text,s.text,s.text_matching||"exact")||ns(u.$el_text,s.text,s.text_matching||"exact")));var i,o,a,l=(e==null||(r=e.properties)==null?void 0:r.$elements_chain)||"";return!!l&&(i=(function(u){for(var c,d=[],h=/(?::|")text="(.*?)"/g;!D(c=h.exec(u));)d.includes(c[1])||d.push(c[1]);return d})(l),o=s.text,a=s.text_matching||"exact",i.some((u=>ns(u,o,a))))}ys(e,s){var r,n;if(s==null||!s.selector)return!0;var i=e==null||(r=e.properties)==null?void 0:r.$element_selectors;if(i!=null&&i.includes(s.selector))return!0;var o=(e==null||(n=e.properties)==null?void 0:n.$elements_chain)||"";if(s.selector_regex&&o)try{return new RegExp(s.selector_regex).test(o)}catch{return!1}return!1}bs(e){var s;return(e==null||(s=e.properties)==null?void 0:s.$elements)==null?[]:e?.properties.$elements}hs(e,s){return s==null||!s.properties||s.properties.length===0||rd(s.properties.reduce(((r,n)=>{var i=L(n.value)?n.value.map(String):n.value!=null?[String(n.value)]:[];return r[n.key]={values:i,operator:n.operator||"exact"},r}),{}),e?.properties)}}class mf{constructor(e){var s;this._s=[],this._instance=e,this.ws=new Map,this.ks=new Map,this.xs=new Map,(s=this._instance)==null||s.onSessionId==null||s.onSessionId((r=>this.Ss(r)))}Cs(e){return!1}Ms(){return null}Ts(e){}Es(){}Is(e,s){return!!e&&rd(e.propertyFilters,s?.properties)}Ps(e,s){var r=new Map;return e.forEach((n=>{var i;(i=n.conditions)==null||(i=i[s])==null||(i=i.values)==null||i.forEach((o=>{if(o!=null&&o.name){var a=r.get(o.name)||[];a.push(n.id),r.set(o.name,a)}}))})),r}Rs(e,s,r){var n=(r===$s.Activation?this.ws:this.ks).get(e),i=[];return this.As((o=>{i=o.filter((a=>n?.includes(a.id)))})),i.filter((o=>{var a,l=(a=o.conditions)==null||(a=a[r])==null||(a=a.values)==null?void 0:a.find((u=>u.name===e));return this.Is(l,s)}))}register(e){var s;x((s=this._instance)==null?void 0:s._addCaptureHook)||(this.Fs(e),this.Ls(e))}Ls(e){var s=e.filter((r=>{var n,i;return((n=r.conditions)==null?void 0:n.actions)&&((i=r.conditions)==null||(i=i.actions)==null||(i=i.values)==null?void 0:i.length)>0}));s.length!==0&&(this.Os==null&&(this.Os=new gf(this._instance),this.Os.init(),this.Os.fs((r=>{this.onAction(r)}))),s.forEach((r=>{var n,i,o,a,l;r.conditions&&(n=r.conditions)!=null&&n.actions&&(i=r.conditions)!=null&&(i=i.actions)!=null&&i.values&&((o=r.conditions)==null||(o=o.actions)==null||(o=o.values)==null?void 0:o.length)>0&&((a=this.Os)==null||a.register(r.conditions.actions.values),(l=r.conditions)==null||(l=l.actions)==null||(l=l.values)==null||l.forEach((u=>{if(u&&u.name){var c=this.xs.get(u.name);c&&c.push(r.id),this.xs.set(u.name,c||[r.id])}})))})))}Fs(e){var s,r=e.filter((i=>{var o,a;return((o=i.conditions)==null?void 0:o.events)&&((a=i.conditions)==null||(a=a.events)==null||(a=a.values)==null?void 0:a.length)>0})),n=e.filter((i=>{var o,a;return((o=i.conditions)==null?void 0:o.cancelEvents)&&((a=i.conditions)==null||(a=a.cancelEvents)==null||(a=a.values)==null?void 0:a.length)>0}));r.length===0&&n.length===0||((s=this._instance)==null||s._addCaptureHook(((i,o)=>{this.onEvent(i,o)})),this.ws=this.Ps(e,$s.Activation),this.ks=this.Ps(e,$s.Cancellation))}onEvent(e,s){var r,n,i=this.Ds(),o=(s==null||(r=s.properties)==null?void 0:r.$survey_id)||(s==null||(n=s.properties)==null?void 0:n.$product_tour_id);if(o&&this.getActivatedIds().includes(o)){var a=this.$s(e,o);if(a==="consume")return i.info("event consumed activated item, removing it",{event:e,itemId:o}),void this.Ns([o]);if(a==="persist")return i.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,s,$s.Cancellation);l.length>0&&(i.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)){i.info("event name matched",{event:e,eventPayload:s,items:this.ws.get(e)});var u=this.Rs(e,s,$s.Activation);this.Hs(u.map((c=>c.id)))}}onAction(e){this.xs.has(e)&&this.Hs(this.xs.get(e)||[])}Hs(e){var s;if(e.length!==0){var r=!((s=this._instance)==null||s.get_session_id==null||!s.get_session_id()),n=[];for(var i of e)r&&this.Cs(i)?this.qs(i)&&this.Us(i):n.push(i);n.length>0&&(this._s=[...new Set([...this._s,...n])]),this.Ds().info("updating activated items",{activatedItems:this.getActivatedIds()})}}qs(e){this._s=this._s.filter((r=>r!==e));var s=this.zs();return!s.includes(e)&&(this.Ws([...s,e]),this.Vs(),!0)}Ns(e){var s=new Set(e);this._s=this._s.filter((i=>!s.has(i)));var r=this.Zs(),n=r.filter((i=>!s.has(i)));n.length!==r.length&&(this.Ws(n),n.length===0&&this.Gs()),this.js(e)}Qs(){var e,s=this.Ms();if(!s)return{};var r=(e=this._instance)==null||(e=e.persistence)==null?void 0:e.props[s];return r&&typeof r=="object"?r:{}}Us(e){if(this.Ms()){var s=this.Qs();this.Ts(w({},s,{[e]:Date.now()}))}}js(e){if(this.Ms()){var s=this.Qs(),r={},n=!1;for(var i of Object.entries(s)){var o=i[0],a=i[1];e.includes(o)?n=!0:r[o]=a}n&&(mt(r)?this.Es():this.Ts(r))}}Ks(){this.Ms()&&this.Es()}getActivationTimestamp(e){if(this.zs().includes(e)){var s=this.Qs()[e];return he(s)?s:void 0}}Zs(){var e,s=this.Js();return((e=this._instance)==null||(e=e.persistence)==null?void 0:e.props[s])||[]}zs(){var e,s,r=this.Zs();if(r.length===0)return[];var n=(e=this._instance)==null||(e=e.persistence)==null?void 0:e.props[this.Ys()],i=(s=this._instance)==null||s.get_session_id==null?void 0:s.get_session_id();return i&&n===i?r:[]}Vs(){var e,s=(e=this._instance)==null||e.get_session_id==null?void 0:e.get_session_id();s&&this.Xs(s)}Gs(){this.ta()}Ss(e){var s,r=(s=this._instance)==null||(s=s.persistence)==null?void 0:s.props[this.Ys()];if(r&&r!==e){var n=this.Zs(),i=this.Qs();n.length>0&&(this.Ws([]),n.filter((o=>he(i[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 vf extends mf{constructor(e){super(e)}Js(){return Zi}Ys(){return Mr}Ms(){return Lr}Ts(e){var s;(s=this._instance)==null||(s=s.persistence)==null||s.register({[Lr]:e})}Es(){var e;(e=this._instance)==null||(e=e.persistence)==null||e.unregister(Lr)}Cs(e){var s,r;this.As((i=>{r=i.find((o=>o.id===e))}));var n=(s=r)==null||(s=s.appearance)==null?void 0:s.surveyPopupDelaySeconds;return he(n)&&n>0}ra(){return ft.SHOWN}As(e){var s;(s=this._instance)==null||s.getSurveys(e)}Bs(e){var s;(s=this._instance)==null||s.cancelPendingSurvey(e)}Ds(){return q}Ws(e){var s;(s=this._instance)==null||(s=s.persistence)==null||s.register({[Zi]:e})}Xs(e){var s;(s=this._instance)==null||(s=s.persistence)==null||s.register({[Mr]:e})}ta(){var e;(e=this._instance)==null||(e=e.persistence)==null||e.unregister(Mr)}ea(){return!1}$s(e,s){var r;this.As((i=>{r=i.find((o=>o.id===s))}));var n=!r||(function(i){var o;return nd(i)&&!((o=i.conditions)==null||(o=o.events)==null||!o.repeatedActivation)||i.schedule==="always"})(r);return n?e===ft.SHOWN?"consume":"ignore":e===ft.SHOWN?"persist":e===ft.DISMISSED||e===ft.SENT?"consume":"ignore"}getSurveys(){return this.getActivatedIds()}getEventToSurveys(){return this.getEventToItemsMap()}}var $r="SDK is not enabled or survey functionality is not yet loaded",Ol="Disabled. Not loading surveys.",_f=v!=null&&v.location?dn(v.location.hash,"__posthog")||dn(location.hash,"state"):null,Dl="_postHogToolbarParams",Bl=se("[Toolbar]"),jl=se("[FeatureFlags]");class yf{constructor(e,s){s===void 0&&(s=!1),this.na=!1,this.update(e,s)}update(e,s){this.sa=((r,n)=>{var i,o,a,l;return{bootstrap:{featureFlags:(i=r.bootstrap)==null?void 0:i.featureFlags,featureFlagPayloads:(o=r.bootstrap)==null?void 0:o.featureFlagPayloads},remoteRequestsDisabled:n,featureFlagsDisabled:!!r.advanced_disable_feature_flags,onlyEvaluateSurveyFeatureFlags:!!r.advanced_only_evaluate_survey_feature_flags,deduplicateCallsPerSession:!!r.advanced_feature_flags_dedup_per_session,cacheTtlMs:r.feature_flag_cache_ttl_ms,requestTimeoutMs:r.feature_flag_request_timeout_ms,compression:r.disable_compression?"none":"base64",evaluationContexts:(a=(l=r.evaluation_contexts)!==null&&l!==void 0?l:r.evaluation_environments)!==null&&a!==void 0?a:[],flagKeys:L(r.flag_keys)?r.flag_keys:void 0}})(e,s),!e.evaluation_environments||e.evaluation_contexts||this.na||(jl.warn("evaluation_environments is deprecated. Use evaluation_contexts instead. evaluation_environments will be removed in a future version."),this.na=!0),x(e.flag_keys)||L(e.flag_keys)||jl.error("Invalid flag_keys found:",e.flag_keys,"Expected array of non-empty strings")}get(){return this.sa}}var Ul=se("[FeatureFlags]"),Ot=se("[FeatureFlags]",{debugEnabled:!0}),ki=`" failed. Feature flags didn't load in time.`,Hl="connection_error",Wl=t=>{for(var e={},s=0;t.length>s;s++)e[t[s]]=!0;return e},zl=t=>{var e={};for(var s of Dr(t||{})){var r=s[1];r&&(e[s[0]]=r)}return e},Xe=se("[Error tracking]"),ql="Refusing to render web experiment since the viewer is a likely bot",wf={icontains:(t,e)=>e.toLowerCase().indexOf(t.toLowerCase())>-1,not_icontains:(t,e)=>e.toLowerCase().indexOf(t.toLowerCase())===-1,regex:(t,e)=>fn(e,t),not_regex:(t,e)=>!fn(e,t),exact:(t,e)=>e===t,is_not:(t,e)=>e!==t};class ye{get Ne(){return this._instance.config}constructor(e){var s=this;this.getWebExperimentsAndEvaluateDisplayLogic=function(r){r===void 0&&(r=!1),s.getWebExperiments((n=>{ye.aa("retrieved web experiments from the server"),s.oa=new Map,n.forEach((i=>{if(i.feature_flag_key){var o;s.oa&&(ye.aa("setting flag key ",i.feature_flag_key," to web experiment ",i),(o=s.oa)==null||o.set(i.feature_flag_key,i));var a=s._instance.getFeatureFlag(i.feature_flag_key);W(a)&&i.variants[a]&&s.la(i.name,a,i.variants[a].transforms)}else if(i.variants)for(var l in i.variants){var u=i.variants[l];ye.ua(u,s._instance)&&s.la(i.name,l,u.transforms)}}))}),r)},this._instance=e,this._instance.onFeatureFlags((r=>{this.onFeatureFlags(r)}))}initialize(){}onFeatureFlags(e){if(this._is_bot())ye.aa(ql);else if(!this.Ne.disable_web_experiments){if(D(this.oa))return this.oa=new Map,this.loadIfEnabled(),void this.previewWebExperiment();ye.aa("applying feature flags",e),e.forEach((s=>{var r;if(this.oa&&(r=this.oa)!=null&&r.has(s)){var n,i=this._instance.getFeatureFlag(s),o=(n=this.oa)==null?void 0:n.get(s);i&&o!=null&&o.variants[i]&&this.la(o.name,i,o.variants[i].transforms)}}))}}previewWebExperiment(){var e=ye.getWindowLocation();if(e!=null&&e.search){var s=vs(e?.search,"__experiment_id"),r=vs(e?.search,"__experiment_variant");s&&r&&(ye.aa("previewing web experiments "+s+" && "+r),this.getWebExperiments((n=>{this.ha(parseInt(s),r,n)}),!1,!0))}}loadIfEnabled(){this.Ne.disable_web_experiments||this.getWebExperimentsAndEvaluateDisplayLogic()}getWebExperiments(e,s,r){if(this.Ne.disable_web_experiments&&!r)return e([]);var n=this._instance.get_property("$web_experiments");if(n&&!s)return e(n);this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/web_experiments/?token="+this.Ne.token),method:"GET",timestampMode:"query",callback:i=>e(i.statusCode===200&&i.json&&i.json.experiments||[])})}ha(e,s,r){var n=r.filter((i=>i.id===e));n&&n.length>0&&(ye.aa("Previewing web experiment ["+n[0].name+"] with variant ["+s+"]"),this.la(n[0].name,s,n[0].variants[s].transforms))}static ua(e,s){return!D(e.conditions)&&ye.da(e,s)&&ye.va(e)}static da(e,s){var r;if(D(e.conditions)||D((r=e.conditions)==null?void 0:r.url))return!0;var n=ye.getWindowLocation();if(n){var i,o,a,l=wu(s,n.href);return(i=e.conditions)==null||!i.url||wf[(o=(a=e.conditions)==null?void 0:a.urlMatchType)!==null&&o!==void 0?o:"icontains"](e.conditions.url,l)}return!1}static getWindowLocation(){return v?.location}static va(e){var s;if(D(e.conditions)||D((s=e.conditions)==null?void 0:s.utm))return!0;var r=Mu();if(r.utm_source){var n,i,o,a,l,u,c,d,h=(n=e.conditions)==null||(n=n.utm)==null||!n.utm_campaign||((i=e.conditions)==null||(i=i.utm)==null?void 0:i.utm_campaign)==r.utm_campaign,p=(o=e.conditions)==null||(o=o.utm)==null||!o.utm_source||((a=e.conditions)==null||(a=a.utm)==null?void 0:a.utm_source)==r.utm_source,f=(l=e.conditions)==null||(l=l.utm)==null||!l.utm_medium||((u=e.conditions)==null||(u=u.utm)==null?void 0:u.utm_medium)==r.utm_medium,g=(c=e.conditions)==null||(c=c.utm)==null||!c.utm_term||((d=e.conditions)==null||(d=d.utm)==null?void 0:d.utm_term)==r.utm_term;return h&&f&&g&&p}return!1}static aa(e){for(var s=arguments.length,r=new Array(s>1?s-1:0),n=1;s>n;n++)r[n-1]=arguments[n];k.info("[WebExperiments] "+e,r)}la(e,s,r){this._is_bot()?ye.aa(ql):s!=="control"?r.forEach((n=>{if(n.selector){var i;ye.aa("applying transform of variant "+s+" for experiment "+e+" ",n);var o=(i=document)==null?void 0:i.querySelectorAll(n.selector);o?.forEach((a=>{var l=a;n.html&&(l.innerHTML=n.html),n.css&&l.setAttribute("style",n.css)}))}})):ye.aa("Control variants leave the page unmodified.")}_is_bot(){return ke&&this._instance?ed(ke,this.Ne.custom_blocked_useragents):void 0}}var Ue=se("[Conversations]"),Dt="Conversations not available yet.",Vl="console",cd="__posthogHandledLogsRequestError",Ii=(t,e)=>{var s=t instanceof Error?t:new Error(e);return s[cd]=!0,s},Gl=t=>!!t&&typeof t=="object"&&t[cd]===!0,Tn={featureFlags:class{constructor(t){this.name="featureFlags",this.ca=!1,this.featureFlagEventHandlers=[],this.rt=Ul,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 yf(t.config,t.Qi()),this.Ta=this.Ea)}updateConfig(t,e){var s;(s=this.Ea)==null||s.update(t,e)}setup(t){return this.Ia=t,this.rt=t.logger.createLogger("[FeatureFlags]"),s=()=>{this.Ia===t&&(this.Ia=void 0,this.nn=t,this.Pa(t))},(e=t.kv.initialize())!=null&&e.then?e.then(s):s();var e,s}Pa(t){if(this.nn===t)return v&&ne(v,"online",this.Ca),this.Ra=t.registerDynamicEventProperties((()=>this.Aa()?this.fa:this.pa)),this.Fa(),this.initialize()}destroy(){v?.removeEventListener("online",this.Ca)}dispose(){var t;this.ba++,this.wa=!1,this.Ia=void 0,this.nn&&(this.La(),(t=this.Ra)==null||t.dispose(),this.Ra=void 0,this.ga=[],v?.removeEventListener("online",this.Ca),this.nn=void 0)}get Ne(){return this.Ta.get()}Oa(t){var e;return(e=this.nn)==null?void 0:e.kv.get(t)}F(t){this.Da((()=>{var e;return(e=this.nn)==null?void 0:e.kv.set(t)}))}q(t){this.Da((()=>{var e;return(e=this.nn)==null?void 0:e.kv.remove(t)}))}Da(t){try{t()}catch(e){this.rt.error("Failed to update feature flag persistence",e)}}Fa(){var t={};for(var e of[Hs,Ws,Nr,et]){var s=this.Oa(e);x(s)||(t[e]=s)}this.fa=t;var r=w({},t),n=this.Oa(Bt);if(n)for(var i of Object.entries(n))r["$feature/"+i[0]]=i[1];this.pa=r}Aa(){var t=this.Ne.cacheTtlMs;if(!t||0>=t)return!1;var e=this.Oa(Ks);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 s=e&&typeof e=="string"&&e.trim().length>0;return s||this.rt.error("Invalid evaluation context found:",e,"Expected non-empty string"),s})):[]}qa(){var t=this.Ne.flagKeys;if(!x(t))return t.filter((e=>{var s=e&&typeof e=="string"&&e.trim().length>0;return s||this.rt.error("Invalid flag key found:",e,"Expected non-empty string"),s}))}initialize(){var t,e,s=this.Ne,r=(t=(e=s.bootstrap)==null?void 0:e.featureFlags)!==null&&t!==void 0?t:{};if(Object.keys(r).length){var n,i,o=(n=(i=s.bootstrap)==null?void 0:i.featureFlagPayloads)!==null&&n!==void 0?n:{},a=Object.keys(r).filter((u=>!!r[u])).reduce(((u,c)=>(u[c]=r[c]||!1,u)),{}),l=Object.keys(o).filter((u=>a[u])).reduce(((u,c)=>(o[c]&&(u[c]=o[c]),u)),{});return this.ja({featureFlags:a,featureFlagPayloads:l})}}updateFlags(t,e,s){var r,n,i=s!=null&&s.merge&&(r=this.Oa(Bt))!==null&&r!==void 0?r:{},o=s!=null&&s.merge&&(n=this.Oa(Ws))!==null&&n!==void 0?n:{},a=w({},i,t),l=w({},o,e),u={};for(var c of Object.entries(a)){var d=c[0],h=c[1];u[d]={key:d,enabled:Ba(h),variant:ja(h),reason:void 0,metadata:x(l?.[d])?void 0:{id:0,version:void 0,description:void 0,payload:l[d]}}}this.ja({flags:u})}get hasLoadedFlags(){return this.ma}getFlags(){return Object.keys(this.getFlagVariants())}getFlagsWithDetails(){var t=this.Oa(Ji),e=this.Oa(et),s=this.Oa(jt);if(!s&&!e)return t||{};var r=ee({},t||{}),n=[...new Set([...Object.keys(s||{}),...Object.keys(e||{})])];for(var i of n){var o,a,l=r[i],u=e?.[i],c=x(u)?(o=l?.enabled)!==null&&o!==void 0&&o:!!u,d=x(u)?l?.variant:typeof u=="string"?u:void 0,h=s?.[i],p=w({},l,{enabled:c,variant:c?d??l?.variant:void 0});c!==l?.enabled&&(p.original_enabled=l?.enabled),d!==l?.variant&&(p.original_variant=l?.variant),h&&(p.metadata=w({},l?.metadata,{payload:h,original_payload:l==null||(a=l.metadata)==null?void 0:a.payload})),r[i]=p}return this.ca||(this.rt.warn(" Overriding feature flag details!",{flagDetails:t,overriddenPayloads:s,finalDetails:r}),this.ca=!0),r}getAllFeatureFlags(){var t=this.getFlagVariants(),e=this.getFlagPayloads();return Object.keys(t).map((s=>{var r=t[s];return{key:s,enabled:Ba(r),variant:ja(r),payload:Da(e[s])}}))}getFlagVariants(){var t=this.Oa(Bt),e=this.Oa(et);if(!e)return t||{};for(var s=ee({},t||{}),r=Object.keys(e),n=0;r.length>n;n++)s[r[n]]=e[r[n]];return this.ca||(this.rt.warn(" Overriding feature flags!",{enabledFlags:t,overriddenFlags:e,finalFlags:s}),this.ca=!0),s}getFlagPayloads(){var t=this.Oa(Ws),e=this.Oa(jt);if(!e)return t||{};for(var s=ee({},t||{}),r=Object.keys(e),n=0;r.length>n;n++)s[r[n]]=e[r[n]];return this.ca||(this.rt.warn(" Overriding feature flag payloads!",{flagPayloads:t,overriddenPayloads:e,finalPayloads:s}),this.ca=!0),s}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(Wt)}Ha(t){this.La();var e=this.nn;if(e&&!this.Ne.remoteRequestsDisabled&&!this.Ma())if(this.ya)this.wa=!0;else{var s={token:e.projectToken,distinct_id:e.distinctId,groups:e.groups,$anon_distinct_id:this.$anon_distinct_id,person_properties:w({},e.initialPersonProperties,this.Oa(ct)||{},{$lib:e.library.name,$lib_version:e.library.version}),group_properties:this.Oa(Ut),timezone:Uu()};x(e.deviceId)||(s.$device_id=e.deviceId),(t!=null&&t.disableFlags||this.Ne.featureFlagsDisabled)&&(s.disable_flags=!0);var r=this.Na();r.length&&(s.evaluation_contexts=r);var n=this.qa();x(n)||(s.flag_keys=n);var i=this.Ne.onlyEvaluateSurveyFeatureFlags,o="/flags/?v=2"+(i?"&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({[Or]:[Hl]}),this.rt.error("Feature flag request failed",c)),l()};try{e.sendRequest(o,{target:"flags",method:"POST",body:s,compression:this.Ne.compression==="base64"?xe.Base64:void 0,sentAt:"body",timeoutMs:this.Ne.requestTimeoutMs}).then((c=>{var d,h,p=(d=c.json)!==null&&d!==void 0?d:{},f=c.statusCode!==200;if(this.ya=!1,a===this.ba){if(this.Ua(c.statusCode),f||this.wa||(this.$anon_distinct_id=void 0),!s.disable_flags||this.wa){this.ka=!f;var g=[];c.error?g.push(c.error instanceof Error&&c.error.name==="AbortError"?"timeout":c.error instanceof Error?Hl:"unknown_error"):c.statusCode!==200&&g.push("api_error_"+c.statusCode),p.errorsWhileComputingFlags&&g.push("errors_while_computing_flags");var m=!((h=p.quotaLimited)==null||!h.includes("feature_flags"));m&&g.push("quota_limited"),this.F({[Or]: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."):s.disable_flags||this.ja(p,f,{partialResponse:i}),l()}}else l()})).catch(u)}catch(c){u(c)}}}Ma(){return Tu(this.Sa,3)}Ua(t){this.Sa=Nu(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 s;if(e===void 0&&(e={}),!e.fresh||this.ka)if(this.ma||this.getFlags()&&this.getFlags().length>0){if(!this.$a()){var r=this.getFeatureFlagResult(t,e);return(s=r?.variant)!==null&&s!==void 0?s:r?.enabled}}else this.rt.warn('getFeatureFlag for key "'+t+ki)}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 s,r=this.getFlagVariants(),n=t in r,i=r[t],o=this.getFlagPayloads()[t],a=String(i),l=this.Oa(Nr)||void 0,u=this.Oa(Ks)||void 0,c=this.Oa(Wt)||{};if(this.Ne.deduplicateCallsPerSession){var d,h=(d=this.nn)==null?void 0:d.session.sessionId,p=this.Oa(qs);h&&h!==p&&(c={},s=h)}if(e.send_event||!("send_event"in e))if(t in c&&c[t].includes(a))s&&this.F({[Wt]:c,[qs]:s});else{var f,g,m,_,b,E,I,F,P,B;L(c[t])?c[t].push(a):c[t]=[a],this.F(w({[Wt]:c},s?{[qs]:s}:{}));var S=this.getFeatureFlagDetails(t),A=[...(f=this.Oa(Or))!==null&&f!==void 0?f:[]];x(i)&&A.push("flag_missing");var R={$feature_flag:t,$feature_flag_response:i,$feature_flag_payload:o||null,$feature_flag_request_id:l,$feature_flag_evaluated_at:u,$feature_flag_bootstrapped_response:((g=this.Ne.bootstrap)==null||(g=g.featureFlags)==null?void 0:g[t])||null,$feature_flag_bootstrapped_payload:((m=this.Ne.bootstrap)==null||(m=m.featureFlagPayloads)==null?void 0:m[t])||null,$used_bootstrap_value:!this.ka};x(S==null||(_=S.metadata)==null?void 0:_.has_experiment)||(R.$feature_flag_has_experiment=S.metadata.has_experiment),x(S==null||(b=S.metadata)==null?void 0:b.version)||(R.$feature_flag_version=S.metadata.version);var N,T=(E=S==null||(I=S.reason)==null?void 0:I.description)!==null&&E!==void 0?E:S==null||(F=S.reason)==null?void 0:F.code;T&&(R.$feature_flag_reason=T),S!=null&&(P=S.metadata)!=null&&P.id&&(R.$feature_flag_id=S.metadata.id),x(S?.original_variant)&&x(S?.original_enabled)||(R.$feature_flag_original_response=x(S.original_variant)?S.original_enabled:S.original_variant),S!=null&&(B=S.metadata)!=null&&B.original_payload&&(R.$feature_flag_original_payload=S==null||(N=S.metadata)==null?void 0:N.original_payload),A.length&&(R.$feature_flag_error=A.join(",")),this.za(R)}else s&&this.F({[Wt]:c,[qs]:s});if(n)return{key:t,enabled:!!i,variant:typeof i=="string"?i:void 0,payload:Da(o)}}}else this.rt.warn('getFeatureFlagResult for key "'+t+ki)}za(t){try{var e;(e=this.nn)==null||e.capture("$feature_flag_called",t).catch((s=>{this.rt.error("Failed to capture feature flag call",s)}))}catch(s){this.rt.error("Failed to capture feature flag call",s)}}getRemoteConfigPayload(t,e){this.Wa(t,e)}Wa(t,e){var s=this;return X((function*(){var r=s.nn;if(r){var n={distinct_id:r.distinctId,token:r.projectToken,person_properties:{$lib:r.library.name,$lib_version:r.library.version}},i=s.Na();i.length&&(n.evaluation_contexts=i);var o,a=s.qa();x(a)||(n.flag_keys=a);try{var l,u=(l=(yield r.sendRequest("/flags/?v=2",{target:"flags",method:"POST",body:n,compression:s.Ne.compression==="base64"?xe.Base64:void 0,sentAt:"body",timeoutMs:s.Ne.requestTimeoutMs})).json)==null?void 0:l.featureFlagPayloads;o=u?.[t]||void 0}catch(c){return void s.rt.error("Remote config feature flag request failed",c)}try{e(o)}catch(c){s.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+ki),e.defaultValue;var s=this.getFeatureFlag(t,e);return x(s)?e.defaultValue:!!s}addFeatureFlagsHandler(t){this.featureFlagEventHandlers.push(t)}removeFeatureFlagsHandler(t){this.featureFlagEventHandlers=this.featureFlagEventHandlers.filter((e=>e!==t))}receivedFeatureFlags(t,e,s){this.ja(t,e,s)}ja(t,e,s){if(this.nn){this.ma=!0;var r=(function(n,i,o,a,l,u){i===void 0&&(i={}),o===void 0&&(o={}),a===void 0&&(a={}),u===void 0&&(u=Ul);var c=((P,B)=>{var S=P.flags;return S?w({},P,{featureFlags:Object.fromEntries(Object.keys(S).map((A=>{var R;return[A,(R=S[A].variant)!==null&&R!==void 0?R:S[A].enabled]}))),featureFlagPayloads:Object.fromEntries(Object.keys(S).filter((A=>S[A].enabled)).filter((A=>{var R;return(R=S[A].metadata)==null?void 0:R.payload})).map((A=>{var R;return[A,(R=S[A].metadata)==null?void 0:R.payload]})))}):(P.featureFlags&&B.warn("Using an older version of the feature flags endpoint. Please upgrade your PostHog server to the latest version"),P)})(n,u),d=c.flags,h=c.featureFlags,p=c.featureFlagPayloads;if(h){var f=n.requestId,g=n.evaluatedAt;if(L(h)){u.warn("v1 of the feature flags endpoint is deprecated. Please use the latest version.");var m={};if(h)for(var _=0;h.length>_;_++)m[h[_]]=!0;return{[Hs]:h,[Bt]:m,[tn]:!1}}var b=h,E=p,I=d;if(l!=null&&l.partialResponse)b=w({},i,b),E=w({},o,E),I=w({},a,I);else if(n.errorsWhileComputingFlags)if(d){var F=new Set(Object.keys(d).filter((P=>{var B;return!((B=d[P])!=null&&B.failed)})));b=w({},i,Object.fromEntries(Object.entries(b).filter((P=>F.has(P[0]))))),E=w({},o,Object.fromEntries(Object.entries(E||{}).filter((P=>F.has(P[0]))))),I=w({},a,Object.fromEntries(Object.entries(I||{}).filter((P=>F.has(P[0])))))}else b=w({},i,b),E=w({},o,E),I=w({},a,I);return w({[Hs]:Object.keys(zl(b)),[Bt]:b||{},[Ws]:E||{},[Ji]:I||{},[tn]:n.minimalFlagCalledEvents===!0},f?{[Nr]:f}:{},g?{[Ks]:g}:{})}})(t,this.getFlagVariants(),this.getFlagPayloads(),this.getFlagsWithDetails(),s,this.rt);r&&this.F(r),e||(this.xa=!1),this.Va(e)}}override(t,e){e===void 0&&(e=!1),this.rt.warn("override is deprecated. Please use overrideFeatureFlags instead."),this.overrideFeatureFlags({flags:t,suppressWarning:e})}overrideFeatureFlags(t){this.Za(t)}Za(t){if(this.nn){if(t===!1)return this.q([et,jt]),this.Va(),void Ot.info("All overrides cleared");if(L(t))return this.F({[et]:Wl(t)}),this.Va(),void Ot.info("Flag overrides set",{flags:t});if(t&&typeof t=="object"&&("flags"in t||"payloads"in t)){var e,s=t;this.ca=!!((e=s.suppressWarning)!==null&&e!==void 0&&e);var r={},n=s.flags,i=s.payloads;return n&&(r[et]=L(n)?Wl(n):n),i&&(r[jt]=i),Object.keys(r).length&&this.F(r),n===!1&&i===!1?this.q([et,jt]):n===!1?this.q(et):i===!1&&this.q(jt),this.Va(),n===!1?Ot.info("Flag overrides cleared"):n&&Ot.info("Flag overrides set",{flags:n}),void(i===!1?Ot.info("Payload overrides cleared"):i&&Ot.info("Payload overrides set",{payloads:i}))}if(t&&typeof t=="object")return this.F({[et]:t}),this.Va(),void Ot.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(),s=e.flags,r=e.flagVariants;try{t(s,r)}catch(n){this.rt.error("Error while running feature flags callback",n)}}return()=>this.removeFeatureFlagsHandler(t)}updateEarlyAccessFeatureEnrollment(t,e,s){var r=(this.Oa(Tr)||[]).find((l=>l.flagKey===t)),n={["$feature_enrollment/"+t]:e},i={$feature_flag:t,$feature_enrollment:e,$set:n};r&&(i.$early_access_feature_name=r.name),s&&(i.$feature_enrollment_stage=s);var o=w({},this.getFlagVariants(),{[t]:e});this.F({[Hs]:Object.keys(zl(o)),[Bt]:o,[ct]:w({},this.Oa(ct)||{},n)}),this.Va();try{var a;(a=this.nn)==null||a.capture("$feature_enrollment_update",i).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,s){e===void 0&&(e=!1);var r=this.Oa(Tr);!r||e?this.Qa(t,s):t(r)}Qa(t,e){var s=this;return X((function*(){var r=s.nn;if(r){var n,i=e?"&"+e.map((a=>"stage="+a)).join("&"):"";try{var o=yield r.sendRequest("/api/early_access_features/?token="+r.projectToken+i,{target:"api",method:"GET",sentAt:"query"});if(!o.json)return;s.F({[Tr]:n=o.json.earlyAccessFeatures})}catch(a){return void s.rt.error("Early access feature request failed",a)}try{t(n)}catch(a){s.rt.error("Early access feature callback failed",a)}}}))()}Ga(){var t=this.getFlags(),e=this.getFlagVariants();return{flags:t.filter((s=>e[s])),flagVariants:Object.keys(e).filter((s=>e[s])).reduce(((s,r)=>(s[r]=e[r],s)),{})}}Va(t){this.Fa();var e=this.Ga(),s=e.flags,r=e.flagVariants;this.featureFlagEventHandlers.forEach((n=>{try{n(s,r,{errorsLoading:t})}catch(i){this.rt.error("Error while running feature flags callback",i)}}))}setPersonPropertiesForFlags(t,e){e===void 0&&(e=!0),this.Ka(t,e)}Ka(t,e){e===void 0&&(e=!0);var s=this.Oa(ct)||{},r=t?.$set||(t!=null&&t.$set_once?{}:t),n=t?.$set_once,i={};if(n)for(var o in n)({}).hasOwnProperty.call(n,o)&&(o in s||(i[o]=n[o]));this.F({[ct]:w({},s,i,r)}),e&&this.reloadFeatureFlags()}unsetPersonPropertiesForFlags(t,e){e===void 0&&(e=!0);var s=w({},this.Oa(ct)||{});t.forEach((r=>{delete s[r]})),this.F({[ct]:s}),e&&this.reloadFeatureFlags()}resetPersonPropertiesForFlags(t){t===void 0&&(t=!0),this.q(ct),t&&this.reloadFeatureFlags()}setGroupPropertiesForFlags(t,e){e===void 0&&(e=!0);var s=this.Oa(Ut)||{},r=w({},s);for(var n of Object.keys(t))r[n]=w({},s[n],t[n]);this.F({[Ut]:r}),e&&this.reloadFeatureFlags()}resetGroupPropertiesForFlags(t){if(t){var e=this.Oa(Ut)||{};this.F({[Ut]:w({},e,{[t]:{}})})}else this.q(Ut)}reset(){this.ba++,this.wa=!1,this.Fa(),this.ma=!1,this._a=!1,this.ka=!1,this.$anon_distinct_id=void 0,this.La(),this.ca=!1,this.Sa=0}}},bf={sessionRecording:class{get Ne(){return this._instance.config}get Mr(){return this._instance.persistence}get started(){var t;return!((t=this.Ja)==null||!t.isStarted)}get status(){var t,e;return this.Ya===Os||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=Nl,this.Xa=void 0,this.eo=!1,this.io=(()=>{var e;if(C==null||!C.visibilityState||C.visibilityState==="visible")return!0;var s=v==null||(e=v.performance)==null||e.getEntriesByType==null?void 0:e.getEntriesByType("visibility-state");return!(s!=null&&s.length)||s.some((r=>r.name==="visible"))})(),this.Ie=()=>{var e;C?.visibilityState==="visible"&&(this.io=!0,(e=this.Ja)==null||e.setDocumentWasEverVisible==null||e.setDocumentWasEverVisible(!0))},this._instance=t,!this._instance.sessionManager)throw at.error("started without valid sessionManager"),new Error(fo+" started without valid sessionManager. This is a bug.");if(this.Ne.cookieless_mode===ht)throw new Error(fo+' cannot be used with cookieless_mode="always"');C!=null&&C.addEventListener&&ne(C,"visibilitychange",this.Ie)}initialize(){this.startIfEnabledOrStop()}dispose(){this.eo=!0,C==null||C.removeEventListener==null||C.removeEventListener("visibilitychange",this.Ie),this.stopRecording()}get ro(){var t,e=!((t=this._instance.get_property(Vt))==null||!t.enabled),s=!this.Ne.disable_session_recording,r=this.Ne.disable_session_recording||this._instance.consent.isOptedOut();return v&&e&&s&&!r}startIfEnabledOrStop(t){var e;if(!(this.eo||this.ro&&(e=this.Ja)!=null&&e.isStarted)){var s=!x(Object.assign)&&!x(Array.from);this.ro&&s?(this.no(t),at.info("starting")):(this.Ya=Nl,this.stopRecording())}}no(t){var e,s,r;this.ro&&(this.Ya!==Os&&this.Ya!==Pr&&(this.Ya=Ml),$!=null&&(e=$.__PosthogExtensions__)!=null&&(e=e.rrweb)!=null&&e.record&&(s=$.__PosthogExtensions__)!=null&&s.initSessionRecording?this.so(t):(r=$.__PosthogExtensions__)==null||r.loadExternalDependency==null||r.loadExternalDependency(this._instance,this.ao,(n=>{if(n)return at.error("could not load recorder",n);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(qo),(e=this.Mr)==null||e.unregister(cu)}uo(t,e){if(D(t))return null;var s,r=he(t)?t:parseFloat(t);return typeof(s=r)!="number"||!Number.isFinite(s)||0>s||s>1?(at.warn(e+" must be between 0 and 1. Ignoring invalid value:",t),null):r}ho(t){if(this.Mr){var e,s,r=this.Mr,n=()=>{var i,o=t.sessionRecording===!1?void 0:t.sessionRecording,a=this.uo((i=this.Ne.session_recording)==null?void 0:i.sampleRate,"session_recording.sampleRate"),l=this.uo(o?.sampleRate,"remote config sampleRate"),u=a??l;D(u)&&this.lo();var c=o?.minimumDurationMilliseconds;r.register({[Vt]:w({cache_timestamp:Date.now(),enabled:!!o},o,{networkPayloadCapture:w({capturePerformance:t.capturePerformance},o?.networkPayloadCapture),canvasRecording:{enabled:o?.recordCanvas,fps:o?.canvasFps,quality:o?.canvasQuality},sampleRate:u,minimumDurationMilliseconds:x(c)?null:c,endpoint:o?.endpoint,triggerMatchType:o?.triggerMatchType,masking:o?.masking,urlTriggers:o?.urlTriggers,version:o?.version,triggerGroups:o?.triggerGroups})})};n(),(e=this.Xa)==null||e.call(this),this.Xa=(s=this._instance.sessionManager)==null?void 0:s.onSessionId(n)}}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===Os&&(this.Ya=Pr,at.warn("config refresh failed, recording will not start until page reload")),void this.startIfEnabledOrStop())}log(t,e){var s;e===void 0&&(e="log"),(s=this.Ja)!=null&&s.log?this.Ja.log(t,e):at.warn("log called before recorder was ready")}get ao(){var t,e,s=(t=this._instance)==null||(t=t.persistence)==null?void 0:t.get_property(Vt);return(s==null||(e=s.scriptConfig)==null?void 0:e.script)||"lazy-recorder"}do(){var t,e=this._instance.get_property(Vt);if(!e)return!1;try{t=typeof e=="object"?e:JSON.parse(e)}catch(s){return at.warn("persisted remote config for session recording is invalid and will be ignored",s),!1}return!D(t.cache_timestamp)&&36e5>=Date.now()-t.cache_timestamp}so(t){var e,s,r;if(!this.eo){if((e=$.__PosthogExtensions__)==null||!e.initSessionRecording)return at.warn("Called on script loaded before session recording is available. This can be caused by adblockers."),void this._instance.register_for_session({[vu]:!0});var n;if(this.Ja||(this.Ja=(n=$.__PosthogExtensions__)==null?void 0:n.initSessionRecording(this._instance,this.io),this.Ja._forceAllowLocalhostNetworkCapture=this._forceAllowLocalhostNetworkCapture),!this.do())return this.Ya===Pr||this.Ya===Os?void 0:(this.Ya=Os,at.info("persisted remote config is stale, requesting fresh config before starting"),void new Hu(this._instance).load());this.Ya=Ml,(s=(r=this.Ja).setDocumentWasEverVisible)==null||s.call(r,this.io),this.Ja.start(t)}}onRRwebEmit(t){var e;(e=this.Ja)==null||e.onRRwebEmit==null||e.onRRwebEmit(t)}overrideLinkedFlag(){var t,e;this.Ja||(e=this.Mr)==null||e.register({[du]:!0}),(t=this.Ja)==null||t.overrideLinkedFlag()}overrideSampling(){var t,e;this.Ja||(e=this.Mr)==null||e.register({[uu]:!0}),(t=this.Ja)==null||t.overrideSampling()}overrideTrigger(t){var e,s;this.Ja||(s=this.Mr)==null||s.register({[t==="url"?hu:pu]:!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 s;return!((s=this.Ja)==null||!s.tryAddCustomEvent(t,e))}}},Ef={autocapture:class{constructor(t){this.vo=!1,this.co=null,this.fo=!1,this.po=!1,this.instance=t,this.rageclicks=new $l(t.config.rageclick),this.mo=null}initialize(){this.startIfEnabled()}get Ne(){var t,e,s=te(this.instance.config.autocapture)?this.instance.config.autocapture:{};return s.url_allowlist=(t=s.url_allowlist)==null?void 0:t.map((r=>new RegExp(r))),s.url_ignorelist=(e=s.url_ignorelist)==null?void 0:e.map((r=>new RegExp(r))),s}yo(){if(this.isBrowserSupported()){if(v&&C){var t=s=>{s=s||v?.event;try{this.bo(s)}catch(r){bi.error("Failed to capture event",r)}};if(ne(C,"submit",t,{capture:!0}),ne(C,"change",t,{capture:!0}),ne(C,"click",t,{capture:!0}),this.Ne.capture_copied_text){var e=s=>{s=s||v?.event;try{this.bo(s,wi)}catch(r){bi.error("Failed to capture copy/cut event",r)}};ne(C,"copy",e,{capture:!0}),ne(C,"cut",e,{capture:!0})}}}else bi.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 s=e.autocapture_opt_out;Ke(s)&&(this.instance.persistence&&this.instance.persistence.register({[Hi]:s}),this.co=s),this.startIfEnabled()}else this.startIfEnabled()}setElementSelectors(t){this.mo=t}getElementSelectors(t){var e,s=[];return(e=this.mo)==null||e.forEach((r=>{var n=C?.querySelectorAll(r);n?.forEach((i=>{t===i&&s.push(r)}))})),s}get isEnabled(){var t,e,s=(t=this.instance.persistence)==null?void 0:t.props[Hi],r=this.co,n=this.instance.Qi()&&!this.fo;if($e(r)&&!Ke(s)&&!n)return!1;var i=(e=this.co)!==null&&e!==void 0?e:!!s;return!!this.instance.config.autocapture&&!i}bo(t,e){if(e===void 0&&(e="$autocapture"),this.isEnabled){var s,r=li(t);Eu(r)&&(r=r.parentNode||null),e==="$autocapture"&&t.type==="click"&&t instanceof MouseEvent&&this.instance.config.rageclick&&(s=this.rageclicks)!=null&&s.isRageClick(t.clientX,t.clientY,t.timeStamp||new Date().getTime())&&al(r,this.instance.config.rageclick)&&this.bo(t,"$rageclick");var n=e===wi;if(r&&(function(d,h,p,f,g,m){var _;if(!v||Yo(d)||p!=null&&p.url_allowlist&&!nl(p.url_allowlist,m)||p!=null&&p.url_ignorelist&&nl(p.url_ignorelist,m))return!1;if(p!=null&&p.dom_event_allowlist){var b=p.dom_event_allowlist;if(b&&!b.some((S=>h.type===S)))return!1}var E=Fu(d,f),I=E.parentIsUsefulElement,F=E.targetElementList;if(!(function(S,A){var R=A?.element_allowlist;if(x(R))return!0;var N,T=function(J){if(R.some((z=>J.tagName.toLowerCase()===z)))return{v:!0}};for(var O of S)if(N=T(O))return N.v;return!1})(F,p)||!no(F,p?.css_selector_allowlist)||no(F,(_=p?.css_selector_ignorelist)!==null&&_!==void 0?_:_p))return!1;try{var P=v.getComputedStyle(d);if(P&&P.getPropertyValue("cursor")==="pointer"&&h.type==="click")return!0}catch{}var B=d.tagName.toLowerCase();switch(B){case"html":return!1;case"form":return(g||["submit"]).indexOf(h.type)>=0;case"input":case"select":case"textarea":return(g||["change","click"]).indexOf(h.type)>=0;default:return I?(g||["click"]).indexOf(h.type)>=0:(g||["click"]).indexOf(h.type)>=0&&(Jo.indexOf(B)>-1||d.getAttribute("contenteditable")==="true")}})(r,t,this.Ne,n,n?["copy","cut"]:void 0,this.instance)){var i=df(r,{e:t,maskAllElementAttributes:this.instance.config.mask_all_element_attributes,maskAllText:this.instance.config.mask_all_text,elementAttributeIgnoreList:this.Ne.element_attribute_ignorelist,elementsChainAsString:this.po,disableCaptureUrlHashes:this.instance.config.disable_capture_url_hashes}),o=i.props;if(i.explicitNoCapture)return!1;var a=this.getElementSelectors(r);if(a&&a.length>0&&(o.$element_selectors=a),e===wi){var l,u=ku(v==null||(l=v.getSelection())==null?void 0:l.toString()),c=t.type||"clipboard";if(!u)return!1;o.$selected_content=u,o.$copy_type=c}return this.instance.capture(e,o),!0}}}isBrowserSupported(){return Se(C?.querySelectorAll)}},historyAutocapture:class{constructor(t){var e;this._instance=t,this._o=(v==null||(e=v.location)==null?void 0:e.pathname)||""}initialize(){this.startIfEnabled()}get isEnabled(){return this._instance.config.capture_pageview==="history_change"}startIfEnabled(){this.isEnabled&&(k.info("History API monitoring enabled, starting..."),this.monitorHistoryChanges())}stop(){this.wo&&this.wo(),this.wo=void 0,k.info("History API monitoring stopped")}monitorHistoryChanges(){v&&v.history&&(this.ko("pushState"),this.ko("replaceState"),this.xo())}ko(t){var e;if(v&&((e=v.history[t])==null||!e.__posthog_wrapped__)){var s=this;(function(r,n,i){try{if(!(n in r))return Rl;var o={next:r[n]},a=i((function(){for(var l=arguments.length,u=new Array(l),c=0;l>c;c++)u[c]=arguments[c];return o.next.apply(this,u)}));return Se(a)&&(a.prototype=a.prototype||{},Object.defineProperties(a,{__posthog_wrapped__:{enumerable:!1,value:!0},__posthog_layer__:{enumerable:!1,value:o}})),r[n]=a,()=>{if(r[n]!==a)for(var l=r[n];Se(l)&&l.__posthog_layer__;){var u=l.__posthog_layer__;if(u.next===a)return void(u.next=o.next);l=u.next}else r[n]=o.next}}catch{return Rl}})(v.history,t,(r=>function(n,i,o){r.call(this,n,i,o),s.So(t)}))}}So(t){try{var e,s=v==null||(e=v.location)==null?void 0:e.pathname;if(!s)return;s!==this._o&&this.isEnabled&&this._instance.capture(os,{navigation_type:t}),this._o=s}catch(r){k.error("Error capturing "+t+" pageview",r)}}xo(){if(!this.wo){var t=()=>{this.So("popstate")};ne(v,"popstate",t),this.wo=()=>{v&&v.removeEventListener("popstate",t)}}}},heatmaps:class{get Ne(){return this.instance.config}constructor(t){var e;this.Co=!1,this.vo=!1,this.Mo=null,this.instance=t,this.Co=!((e=this.instance.persistence)==null||!e.props[Wi]),this.rageclicks=new $l(t.config.rageclick)}initialize(){this.startIfEnabled()}get flushIntervalMilliseconds(){var t=5e3;return te(this.Ne.capture_heatmaps)&&this.Ne.capture_heatmaps.flush_interval_milliseconds&&(t=this.Ne.capture_heatmaps.flush_interval_milliseconds),t}get isEnabled(){return D(this.Ne.capture_heatmaps)?D(this.Ne.enable_heatmaps)?this.Co:this.Ne.enable_heatmaps:this.Ne.capture_heatmaps!==!1}startIfEnabled(){if(this.isEnabled){if(this.vo)return;pf.info("starting..."),this.To(),this.Ie()}else{var t;clearInterval((t=this.Mo)!==null&&t!==void 0?t:void 0),this.Eo(),this.getAndClearBuffer()}}onRemoteConfig(t){if(t.ok){var e=t.config;if("heatmaps"in e){var s=!!e.heatmaps;this.instance.persistence&&this.instance.persistence.register({[Wi]:s}),this.Co=s,this.startIfEnabled()}}}getAndClearBuffer(){var t=this.R;return this.R=void 0,t}Io(t){Si(t.originalEvent)&&this.ke(t.originalEvent,"deadclick")}Ie(){this.Mo&&clearInterval(this.Mo),this.Mo=C?.visibilityState==="visible"?setInterval(this.cr.bind(this),this.flushIntervalMilliseconds):null}To(){v&&C&&(this.Po=this.cr.bind(this),ne(v,an,this.Po),this.Ro=t=>this.ke(t||v?.event),ne(C,"click",this.Ro,{capture:!0}),this.Ao=t=>this.Fo(t||v?.event),ne(C,"mousemove",this.Ao,{capture:!0}),this.Lo=new fl(this.instance,kp,this.Io.bind(this)),this.Lo.startIfEnabledOrStop(),this.Oo=this.Ie.bind(this),ne(C,on,this.Oo),this.vo=!0)}Eo(){var t;v&&C&&(this.Po&&v.removeEventListener(an,this.Po),this.Ro&&C.removeEventListener("click",this.Ro,{capture:!0}),this.Ao&&C.removeEventListener("mousemove",this.Ao,{capture:!0}),this.Oo&&C.removeEventListener(on,this.Oo),clearTimeout(this.Do),(t=this.Lo)==null||t.stop(),this.vo=!1)}$o(t,e){var s=this.instance.scrollManager.scrollY(),r=this.instance.scrollManager.scrollX(),n=this.instance.scrollManager.scrollElement(),i=(function(o,a,l){for(var u=o;u&&Ft(u)&&!Me(u,"body");){if(u===l)return!1;var c=void 0;try{var d,h,p;c=(d=(h=(p=u.ownerDocument)==null?void 0:p.defaultView)!==null&&h!==void 0?h:v)==null?void 0:d.getComputedStyle(u).position}catch{return!1}if(M(a,c))return!0;u=Iu(u)}return!1})(li(t),["fixed","sticky"],n);return{x:t.clientX+(i?0:r),y:t.clientY+(i?0:s),target_fixed:i,type:e}}ke(t,e){var s;if(e===void 0&&(e="click"),!rl(t.target)&&Si(t)){var r=this.$o(t,e);(s=this.rageclicks)!=null&&s.isRageClick(t.clientX,t.clientY,new Date().getTime())&&al(li(t),this.instance.config.rageclick)&&this.Vt(w({},r,{type:"rageclick"})),this.Vt(r)}}Fo(t){!rl(t.target)&&Si(t)&&(clearTimeout(this.Do),this.Do=setTimeout((()=>{this.Vt(this.$o(t,"mousemove"))}),500))}Vt(t){if(v){var e=this.Ne.disable_capture_url_hashes?Ct(v.location.href):v.location.href,s=this.Ne.custom_personal_data_properties,r=this.Ne.mask_personal_data_properties?[..._s,...s||[]]:[],n=ir(e,r,or);this.R=this.R||{},this.R[n]||(this.R[n]=[]),this.R[n].push(t)}}cr(){this.R&&!mt(this.R)&&this.instance.capture("$$heatmap",{$heatmap_data:this.getAndClearBuffer()})}},deadClicksAutocapture:fl,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",w({$current_url:this.R.url},this.R.metrics.reduce(((s,r)=>w({},s,{["$web_vitals_"+r.name+"_event"]:w({},r),["$web_vitals_"+r.name+"_value"]:r.value})),{}))),this.R={navigationKey:void 0,url:void 0,metrics:[],firstMetricTimestamp:void 0})},this.jo=s=>{var r;if(this.R=this.R||{navigationKey:void 0,url:void 0,metrics:[],firstMetricTimestamp:void 0},D(s?.name)||D(s?.value))Lt.error("Invalid metric received",s);else{var n=typeof s.navigationURL=="string"?s.navigationURL:void 0,i=this.Bo(n);if(!x(i)){var o=he(s.navigationId)||typeof s.navigationId=="string"?"navigation:"+s.navigationId:"url:"+i;if(!this.Ho||this.Ho>s.value){this.R.navigationKey!==o&&(this.No(),this.qo=setTimeout(this.No,this.flushToCaptureTimeoutMs)),x(this.R.navigationKey)&&(this.R.navigationKey=o,this.R.url=i),this.R.firstMetricTimestamp=x(this.R.firstMetricTimestamp)?Date.now():this.R.firstMetricTimestamp,s.attribution&&s.attribution.interactionTargetElement&&(s.attribution.interactionTargetElement=void 0);var a=(r=this._instance.sessionManager)==null?void 0:r.checkAndGetSessionAndWindowId(!0),l=w({},s,n?{navigationURL:i}:{},{$current_url:i,timestamp:Date.now()});x(a)||(l.$session_id=a.sessionId,l.$window_id=a.windowId),this.R.metrics.push(l),this.R.metrics.length===this.allowedMetrics.length&&this.No()}else Lt.error("Ignoring metric with value >= "+this.Ho,s)}}},this.Uo=()=>{if(!this.vo){var s,r,n,i,o=$.__PosthogExtensions__,a=o?.postHogWebVitalsCallbacksByFlavor,l=a?.[this.zo]||(this.zo==="web-vitals"&&x(a)?o?.postHogWebVitalsCallbacks:void 0);if(x(l)||(s=l.onLCP,r=l.onCLS,n=l.onFCP,i=l.onINP),s&&r&&n&&i){var u={reportSoftNavs:this.useSoftNavs};this.allowedMetrics.indexOf("LCP")>-1&&s(this.jo.bind(this),u),this.allowedMetrics.indexOf("CLS")>-1&&r(this.jo.bind(this),u),this.allowedMetrics.indexOf("FCP")>-1&&n(this.jo.bind(this),u),this.allowedMetrics.indexOf("INP")>-1&&i(this.jo.bind(this),u),this.vo=!0}else Lt.error("web vitals callbacks not loaded - not starting")}},this._instance=t,this.Co=!((e=this._instance.persistence)==null||!e.props[Gi]),this.startIfEnabled()}get Wo(){return this._instance.config.capture_performance}get allowedMetrics(){var t,e,s=te(this.Wo)?(t=this.Wo)==null?void 0:t.web_vitals_allowed_metrics:void 0;return D(s)?((e=this._instance.persistence)==null?void 0:e.props[Ki])||["CLS","FCP","INP","LCP"]:s}get flushToCaptureTimeoutMs(){return(te(this.Wo)?this.Wo.web_vitals_delayed_flush_ms:void 0)||5e3}get useAttribution(){var t=te(this.Wo)?this.Wo.web_vitals_attribution:void 0;return t!=null&&t}get useSoftNavs(){var t=te(this.Wo)?this.Wo.__preview_web_vitals_soft_navs:void 0;return t!=null&&t}get Ho(){var t=te(this.Wo)&&he(this.Wo.__web_vitals_max_value)?this.Wo.__web_vitals_max_value:Tl;return t>0&&6e4>=t?Tl:t}get isEnabled(){var t=re?.protocol;if(t!=="http:"&&t!=="https:")return Lt.info("Web Vitals are disabled on non-http/https protocols"),!1;var e=te(this.Wo)?this.Wo.web_vitals:Ke(this.Wo)?this.Wo:void 0;return Ke(e)?e:this.Co}startIfEnabled(){this.isEnabled&&!this.vo&&(Lt.info("enabled, starting..."),this.ai(this.Uo))}onRemoteConfig(t){if(t.ok){var e=t.config;if("capturePerformance"in e){var s=te(e.capturePerformance)&&!!e.capturePerformance.web_vitals,r=te(e.capturePerformance)?e.capturePerformance.web_vitals_allowed_metrics:void 0;this._instance.persistence&&(this._instance.persistence.register({[Gi]:s}),this._instance.persistence.register({[Ki]:r})),this.Co=s,this.startIfEnabled()}}}get zo(){return this.useSoftNavs?this.useAttribution?"web-vitals-with-attribution-soft-navs":"web-vitals-soft-navs":this.useAttribution?"web-vitals-with-attribution":"web-vitals"}ai(t){var e=$.__PosthogExtensions__,s=this.zo,r=e?.postHogWebVitalsCallbacksByFlavor;r!=null&&r[s]||s==="web-vitals"&&x(r)&&e!=null&&e.postHogWebVitalsCallbacks?t():e==null||e.loadExternalDependency==null||e.loadExternalDependency(this._instance,s,(n=>{n?Lt.error("failed to load script",n):t()}))}Bo(t){var e=t||v?.location.href;if(e){var s=this._instance.config.disable_capture_url_hashes?Ct(e):e,r=this._instance.config.custom_personal_data_properties,n=this._instance.config.mask_personal_data_properties?[..._s,...r||[]]:[];return ir(s,n,or)}Lt.error("Could not determine current URL")}}},Sf={exceptionObserver:class{constructor(t){var e;this.Uo=()=>{var s;if(v&&this.isEnabled&&(s=$.__PosthogExtensions__)!=null&&s.errorWrappingFunctions){var r=$.__PosthogExtensions__.errorWrappingFunctions.wrapOnError,n=$.__PosthogExtensions__.errorWrappingFunctions.wrapUnhandledRejection,i=$.__PosthogExtensions__.errorWrappingFunctions.wrapConsoleError;try{!this.Vo&&this.Ne.capture_unhandled_errors&&(this.Vo=r(this.captureException.bind(this))),!this.Zo&&this.Ne.capture_unhandled_rejections&&(this.Zo=n(this.captureException.bind(this))),!this.Go&&this.Ne.capture_console_errors&&(this.Go=i(this.captureException.bind(this)))}catch(o){Ls.error("failed to start",o),this.Qo()}}},this._instance=t,this.Ko=!((e=this._instance.persistence)==null||!e.props[zi]),this.Jo=new wh(w({},(function(s){var r,n,i,o;return s===void 0&&(s={}),{refillRate:(r=(n=s.exceptionRateLimiterRefillRate)!==null&&n!==void 0?n:s.__exceptionRateLimiterRefillRate)!==null&&r!==void 0?r:1,bucketSize:(i=(o=s.exceptionRateLimiterBucketSize)!==null&&o!==void 0?o:s.__exceptionRateLimiterBucketSize)!==null&&i!==void 0?i:10}})(this._instance.config.error_tracking),{refillInterval:1e4,rt:Ls})),this.Ne=this.Yo(),this.startIfEnabledOrStop()}Yo(){var t=this._instance.config.capture_exceptions,e={capture_unhandled_errors:!1,capture_unhandled_rejections:!1,capture_console_errors:!1};return te(t)?e=w({},e,t):(x(t)?this.Ko:t)&&(e=w({},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?(Ls.info("enabled"),this.Qo(),this.ai(this.Uo)):this.Qo()}ai(t){var e,s;(e=$.__PosthogExtensions__)!=null&&e.errorWrappingFunctions?t():(s=$.__PosthogExtensions__)==null||s.loadExternalDependency==null||s.loadExternalDependency(this._instance,"exception-autocapture",(r=>{if(r)return Ls.error("failed to load script",r);t()}))}Qo(){var t,e,s;(t=this.Vo)==null||t.call(this),this.Vo=void 0,(e=this.Zo)==null||e.call(this),this.Zo=void 0,(s=this.Go)==null||s.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({[zi]:this.Ko}),this.Ne=this.Yo(),this.startIfEnabledOrStop())}}onConfigChange(){this.Ne=this.Yo()}captureException(t){var e,s,r,n=(e=t==null||(s=t.$exception_list)==null||(s=s[0])==null?void 0:s.type)!==null&&e!==void 0?e:"Exception";this.Jo.consumeRateLimit(n)?Ls.info("Skipping exception capture because of client rate limiting.",{exception:n}):(r=this._instance.exceptions)==null||r.sendExceptionEvent(t)}},exceptions:class{constructor(t){var e,s;this.Xo=[],this.tl=new Oh([new qh,new ep,new Gh,new Vh,new Xh,new Zh,new Jh,new Qh],(function(r){for(var n=arguments.length,i=new Array(n>1?n-1:0),o=1;n>o;o++)i[o-1]=arguments[o];return function(a,l){l===void 0&&(l=0);for(var u=[],c=a.split(` -`),d=l;c.length>d;d++){var h=c[d];if(1024>=h.length){var p=Qa.test(h)?h.replace(Qa,"$1"):h;if(!p.match(/\S*Error: /)){for(var f of i){var g=f(p,r);if(g){u.push(g);break}}if(u.length>=50)break}}}return(function(m){if(!m.length)return[];var _=Array.from(m);return _.reverse(),_.slice(0,50).map((b=>{return w({},b,{filename:b.filename||(E=_,E[E.length-1]||{}).filename,function:b.function||ms});var E}))})(u)}})("web:javascript",Uh,zh)),this._instance=t,this.Xo=(e=(s=this._instance.persistence)==null?void 0:s.get_property(qi))!==null&&e!==void 0?e:[],this.el=en(this.il()),this.rl=new sp(this.el)}onConfigChange(){this.el=en(this.il()),this.rl.setConfig(this.el)}onRemoteConfig(t){var e,s,r;if(t.ok){var n=t.config;if("errorTracking"in n){var i=(e=(s=n.errorTracking)==null?void 0:s.suppressionRules)!==null&&e!==void 0?e:[],o=(r=n.errorTracking)==null?void 0:r.captureExtensionExceptions;this.Xo=i,this._instance.persistence&&this._instance.persistence.register({[qi]:this.Xo,[Vi]:o})}}}get nl(){var t,e=!!this._instance.get_property(Vi),s=this._instance.config.error_tracking.captureExtensionExceptions;return(t=s??e)!==null&&t!==void 0&&t}buildProperties(t,e){return this.tl.buildFromUnknown(t,{syntheticException:e?.syntheticException,mechanism:{handled:e?.handled}})}addExceptionStep(t,e){if(this.el.enabled)try{if(!W(t)||t.trim().length===0)return void Xe.warn("Ignoring exception step because message must be a non-empty string");var s=(function(i){if(!i)return{sanitizedProperties:{},droppedKeys:[]};var o=[];return{sanitizedProperties:Object.keys(i).reduce(((a,l)=>tp.has(l)?(o.push(l),a):(a[l]=i[l],a)),{}),droppedKeys:o}})(this.sl(e)),r=s.sanitizedProperties,n=s.droppedKeys;n.length>0&&Xe.warn("Ignoring reserved exception step fields",{droppedKeys:n}),this.rl.add(w({[Xr]:t,[Qr]:new Date().toISOString()},r))}catch(i){Xe.error("Failed to add exception step. Ignoring breadcrumb.",i)}}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 Xe.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 Xe.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 Xe.info("Skipping exception capture because it was thrown by the PostHog SDK")}var s=this.el.enabled&&D(t.$exception_steps)?this.dl(t):t,r=typeof(i=globalThis._posthogReleaseId)=="string"&&i.length>0?i:void 0;r&&(s.$release_id=r);try{var n=this._instance.capture("$exception",s,{_noTruncate:!0,_batchKey:"exceptionEvent",Wn:!0});return n&&this.rl.clear(),n}catch(o){return Xe.error("Failed to capture exception event. Dropping this exception.",o),void this.rl.clear()}}catch(o){return void Xe.error("Failed to process exception event. Ignoring this exception.",o)}var i}dl(t){try{var e=this.rl.getAttachable();return e.length===0?t:w({},t,{$exception_steps:e})}catch(s){return Xe.error("Failed to read buffered exception steps. Capturing exception without steps.",s),t}}ll(t){this.el.enabled&&this.rl.add({[Xr]:t,[Qr]:new Date().toISOString()})}sl(t){return te(t)?w({},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(((s,r)=>{var n=r.type,i=r.value;return W(n)&&n.length>0&&s.$exception_types.push(n),W(i)&&i.length>0&&s.$exception_values.push(i),s}),{$exception_types:[],$exception_values:[]});return this.Xo.some((s=>{var r=s.values.map((n=>{var i=sd[n.operator],o=e[n.key];if(!i||!o)return!1;var a=L(n.value)?n.value:[n.value];return a.length>0&&i(a,o)}));return s.type==="OR"?r.some(Boolean):r.every(Boolean)}))}catch(s){return Xe.warn("Failed to evaluate suppression rules. Capturing the exception.",s),!1}}ul(t){return t.flatMap((e=>{var s,r;return(s=(r=e.stacktrace)==null?void 0:r.frames)!==null&&s!==void 0?s:[]})).some((e=>e.filename&&e.filename.startsWith("chrome-extension://")))}hl(t){if(t.length>0){var e,s,r,n,i=(e=(s=t[0].stacktrace)==null?void 0:s.frames)!==null&&e!==void 0?e:[],o=i[i.length-1];return(r=o==null||(n=o.filename)==null?void 0:n.includes("posthog.com/static"))!==null&&r!==void 0&&r}return!1}al(t){return!D(t)&&L(t)}}},xf=w({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 s,r;if(this.Mr&&this.Mr.register({[zo]:!!e.productTours}),!xi(this._instance))return!this.vl&&D((s=this.Mr)==null?void 0:s.props[zs])||Ar.info("product tours disabled; stopping and clearing cached tours"),(r=this.vl)==null||r.stop(),this.vl=null,void this.clearCache();this.loadIfEnabled()}}}loadIfEnabled(){!this.vl&&xi(this._instance)&&this.ai((()=>this.fl()))}ai(t){var e,s;(e=$.__PosthogExtensions__)!=null&&e.generateProductTours?t():(s=$.__PosthogExtensions__)==null||s.loadExternalDependency==null||s.loadExternalDependency(this._instance,"product-tours",(r=>{r?Ar.error("Could not load product tours script",r):t()}))}fl(){var t;!this.vl&&(t=$.__PosthogExtensions__)!=null&&t.generateProductTours&&(this.vl=$.__PosthogExtensions__.generateProductTours(this._instance,!0))}getProductTours(t,e){if(e===void 0&&(e=!1),!L(this.cl)||e){var s=this.Mr;if(s){var r=s.props[zs];if(L(r)&&!e)return this.cl=r,void t(r,{isLoaded:!0})}this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/product_tours/?token="+this._instance.config.token),method:"GET",timestampMode:"query",callback:n=>{if(xi(this._instance)){var i=n.statusCode;if(i!==200||!n.json){var o="Product Tours API could not be loaded, status: "+i;return i===0?n.error||Ar.warn(o):Ar.error(o),void t([],{isLoaded:!1,error:o})}var a=L(n.json.product_tours)?n.json.product_tours:[];this.cl=a,s&&s.register({[zs]:a}),t(a,{isLoaded:!0})}else t([],{isLoaded:!0})}})}else t(this.cl,{isLoaded:!0})}getActiveProductTours(t){D(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(zs)}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)}}},Tn),kf={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 s=this.globalsForEvent(e);this.gl.push(s),this.gl.length>1e3&&(this.gl=this.gl.slice(10))}}get siteAppLoaders(){var t;return(t=$._POSTHOG_REMOTE_CONFIG)==null||(t=t[this._instance.config.token])==null?void 0:t.siteApps}initialize(){if(this.isEnabled){var t=this._instance._addCaptureHook(this.ml.bind(this));this.yl=()=>{t(),this.gl=[],this.yl=void 0}}}globalsForEvent(t){var e,s,r,n,i,o,a;if(!t)throw new Error("Event payload is required");var l={},u=this._instance.get_property("$groups")||[],c=this._instance.get_property("$stored_group_properties")||{};for(var d of Object.entries(c)){var h=d[0];l[h]={id:u[h],type:h,properties:d[1]}}var p=t.$set_once,f=t.$set;return{event:w({},Cc(t,ff),{properties:w({},t.properties,f?{$set:w({},(e=(s=t.properties)==null?void 0:s.$set)!==null&&e!==void 0?e:{},f)}:{},p?{$set_once:w({},(r=(n=t.properties)==null?void 0:n.$set_once)!==null&&r!==void 0?r:{},p)}:{}),elements_chain:(i=(o=t.properties)==null?void 0:o.$elements_chain)!==null&&i!==void 0?i:"",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,s=(e=t.tagName)==null?void 0:e.toLowerCase();return s==="style"&&this._instance.config.prepare_external_dependency_stylesheet?this._instance.config.prepare_external_dependency_stylesheet(t)||(Ze.error("prepare_external_dependency_stylesheet returned null"),null):s==="script"&&this._instance.config.prepare_external_dependency_script?this._instance.config.prepare_external_dependency_script(t)||(Ze.error("prepare_external_dependency_script returned null"),null):t}_l(){var t,e,s,r,n,i,o,a;if(!this._instance.config.prepare_external_dependency_stylesheet&&!this._instance.config.prepare_external_dependency_script)return()=>{};var l=C?.defaultView,u=l==null||(t=l.Node)==null?void 0:t.prototype;if(!l||!u)return()=>{};if(this.pl++,this.wl)return this.kl();var c=[],d=this,h=new WeakSet,p=(m,_,b)=>{if(m!=null&&m[_]){var E=m[_];m[_]=b(E),c.push((()=>{m[_]=E}))}},f=m=>{if(h.has(m))return m;var _=d.bl(m);return _&&h.add(_),_},g=m=>m.map((_=>typeof _=="string"?_:f(_))).filter((_=>!$e(_)));return p(u,"appendChild",(m=>function(_){var b=f(_);return b?m.call(this,b):_})),p(u,"insertBefore",(m=>function(_,b){var E=f(_);return E?m.call(this,E,b):_})),p(u,"replaceChild",(m=>function(_,b){var E=f(_);return E?m.call(this,E,b):b})),[(e=l.Element)==null?void 0:e.prototype,(s=l.Document)==null?void 0:s.prototype,(r=l.DocumentFragment)==null?void 0:r.prototype].forEach((m=>{p(m,"append",(_=>function(){for(var b=arguments.length,E=new Array(b),I=0;b>I;I++)E[I]=arguments[I];return _.apply(this,g(E))})),p(m,"prepend",(_=>function(){for(var b=arguments.length,E=new Array(b),I=0;b>I;I++)E[I]=arguments[I];return _.apply(this,g(E))}))})),[(n=l.Element)==null?void 0:n.prototype,(i=l.CharacterData)==null?void 0:i.prototype,(o=l.DocumentType)==null?void 0:o.prototype].forEach((m=>{p(m,"before",(_=>function(){for(var b=arguments.length,E=new Array(b),I=0;b>I;I++)E[I]=arguments[I];return _.apply(this,g(E))})),p(m,"after",(_=>function(){for(var b=arguments.length,E=new Array(b),I=0;b>I;I++)E[I]=arguments[I];return _.apply(this,g(E))})),p(m,"replaceWith",(_=>function(){for(var b=arguments.length,E=new Array(b),I=0;b>I;I++)E[I]=arguments[I];var F=g(E);return E.length&&!F.length?void 0:_.apply(this,F)}))})),p((a=l.Element)==null?void 0:a.prototype,"insertAdjacentElement",(m=>function(_,b){var E=f(b);return E?m.call(this,_,E):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 s=this._l();try{var r=t(s);return e&&s(),r}catch(n){throw s(),n}}setupSiteApp(t){var e=this.apps[t.id],s=()=>{var o;!e.errored&&this.gl.length&&(Ze.info("Processing "+this.gl.length+" events for site app with id "+t.id),this.gl.forEach((a=>this.xl((()=>e.processEvent==null?void 0:e.processEvent(a))))),e.processedBuffer=!0),Object.values(this.apps).every((a=>a.processedBuffer||a.errored))&&((o=this.yl)==null||o.call(this))},r=!1,n=o=>{e.errored=!o,e.loaded=!0,Ze.info("Site app with id "+t.id+" "+(o?"loaded":"errored")),r&&s()};try{var i=this.xl((o=>t.init({posthog:this._instance,callback(a){o(),n(a)}})),!1).processEvent;i&&(e.processEvent=i),r=!0}catch(o){Ze.error(Ll+t.id,o),n(!1)}if(r&&e.loaded)try{s()}catch(o){Ze.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 s of t)this.setupSiteApp(s)}Cl(t){var e=this;if(Object.keys(this.apps).length!==0){var s=this.globalsForEvent(t),r=function(i){try{e.xl((()=>i.processEvent==null?void 0:i.processEvent(s)))}catch(o){Ze.error("Error while processing event "+t.event+" for site app "+i.id,o)}};for(var n of Object.values(this.apps))r(n)}}onRemoteConfig(t){var e,s,r,n=this;if((e=this.siteAppLoaders)!=null&&e.length)return this.isEnabled?(this.Sl(),void this._instance.on("eventCaptured",(l=>this.Cl(l)))):void Ze.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.');if((s=this.yl)==null||s.call(this),t.ok){var i=t.config;if((r=i.siteApps)!=null&&r.length)if(this.isEnabled){var o=function(){var l,u=a.id,c=a.url;$["__$$ph_site_app_"+u]=n._instance,(l=$.__PosthogExtensions__)==null||l.loadSiteApp==null||l.loadSiteApp(n._instance,c,(d=>{if(d)return Ze.error(Ll+u,d)}))};for(var a of i.siteApps)o()}else Ze.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.')}}}},If={tracingHeaders:class{constructor(t){this.Ml=void 0,this.Tl=void 0,this.El=void 0,this.Uo=()=>{var e,s,r=this.Il();r?(x(this.Ml)&&(this.Ml=(e=$.__PosthogExtensions__)==null||(e=e.tracingHeadersPatchFns)==null?void 0:e._patchXHR(r,(()=>this._instance.get_distinct_id()),this._instance.sessionManager)),x(this.Tl)&&(this.Tl=(s=$.__PosthogExtensions__)==null||(s=s.tracingHeadersPatchFns)==null?void 0:s._patchFetch(r,(()=>this._instance.get_distinct_id()),this._instance.sessionManager))):this.Qo()},this._instance=t}initialize(){this.startIfEnabledOrStop()}ai(t){var e,s;(e=$.__PosthogExtensions__)!=null&&e.tracingHeadersPatchFns?t():(s=$.__PosthogExtensions__)==null||s.loadExternalDependency==null||s.loadExternalDependency(this._instance,"tracing-headers",(r=>{if(r)return hf.error("failed to load script",r);t()}))}Pl(){var t,e;return(t=(e=this._instance.config.tracing_headers)!==null&&e!==void 0?e:this._instance.config.addTracingHeaders)!==null&&t!==void 0?t:this._instance.config.__add_tracing_headers}Il(){var t=this.Pl();return L(t)?(L(this.El)?this.El.splice(0,this.El.length,...t):this.El=[...t],t.length>0?this.El:void 0):(L(this.El)&&this.El.splice(0),this.El=t||void 0,this.El)}Qo(){var t,e;(t=this.Ml)==null||t.call(this),(e=this.Tl)==null||e.call(this),this.Ml=void 0,this.Tl=void 0}startIfEnabledOrStop(){this.Il()?this.ai(this.Uo):this.Qo()}}},Cf=w({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(D(e))return q.warn("Flags not loaded yet. Not loading surveys.");var s=L(e);this.Rl=s?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=[],s=0;slocalStorage.removeItem(n)))}catch{}}loadIfEnabled(){if(!this._surveyManager)if(this.Al)q.info("Already initializing surveys, skipping...");else if(this.Ne.disable_surveys)q.info(Ol);else if(this.Ne.cookieless_mode&&this._instance.consent.isOptedOut())q.info("Not loading surveys in cookieless mode without consent.");else{var t=$?.__PosthogExtensions__;if(t){if(!x(this.Rl)||this.Ne.advanced_enable_surveys){var e=this.Rl||this.Ne.advanced_enable_surveys;this.Al=!0;try{var s=t.generateSurveys;if(s)return void this.Dl(s,e);var r=t.loadExternalDependency;if(!r)return void this.$l(Vo);r(this._instance,"surveys",(n=>{n||!t.generateSurveys?this.$l("Could not load surveys script",n):this.Dl(t.generateSurveys,e)}))}catch(n){throw this.$l("Error initializing surveys",n),n}finally{this.Al=!1}}}else q.error("PostHog Extensions not found.")}}Dl(t,e){this._surveyManager=t(this._instance,e),this._surveyEventReceiver=new vf(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(Ol),t([]);var s,r=this._instance.get_property(Yi);if(r&&!e)return t(r,{isLoaded:!0}),void(this.ql()&&this.getSurveys((()=>{}),!0));typeof Promise<"u"&&this.Ll?this.Ll.then((n=>t(n.surveys,n.context))):(typeof Promise<"u"&&(this.Ll=new Promise((n=>{s=n}))),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:n=>{var i;this.Ll=null;var o=n.statusCode;if(o!==200||!n.json){var a="Surveys API could not be loaded, status: "+o;o!==0?q.error(a):n.error||q.warn(a),this.Ol=Date.now();var l={isLoaded:!1,error:a};return t([],l),void(s==null||s({surveys:[],context:l}))}this.Ol=null;var u,c=n.json.surveys||[],d=c.filter((p=>(function(f){return!(!f.start_date||f.end_date)})(p)&&(nd(p)||(function(f){var g;return!((g=f.conditions)==null||(g=g.actions)==null||(g=g.values)==null||!g.length)})(p))));d.length>0&&((u=this._surveyEventReceiver)==null||u.register(d)),(i=this._instance.persistence)==null||i.register({[Yi]:c,[sn]:Date.now()});var h={isLoaded:!0};t(c,h),s?.({surveys:c,context:h})}}))}ql(){return this.jl()&&!this.Ll&&!this.Bl()}jl(){var t=this._instance.get_property(sn);return he(t)&&Date.now()-t>3e5}Bl(){return he(this.Ol)&&3e5>Date.now()-this.Ol}markSurveyAsSeen(t,e){var s,r={id:t,current_iteration:(s=e?.iteration)!==null&&s!==void 0?s:null};od(r);try{localStorage.setItem("lastSeenSurveyDate",new Date().toISOString())}catch{}}Nl(t){for(var e of this.Fl)try{if(!t.isLoaded)return e([],t);this.getSurveys(e)}catch(s){q.error("Error in survey callback",s)}}getActiveMatchingSurveys(t,e){if(e===void 0&&(e=!1),!D(this._surveyManager))return this._surveyManager.getActiveMatchingSurveys(t,e);q.warn("init was not called")}Hl(t){var e=null;return this.getSurveys((s=>{var r;e=(r=s.find((n=>n.id===t)))!==null&&r!==void 0?r:null})),e}Ul(t){if(D(this._surveyManager))return{eligible:!1,reason:$r};var e=typeof t=="string"?this.Hl(t):t;return e?this._surveyManager.checkSurveyEligibility(e):{eligible:!1,reason:"Survey not found"}}zl(t){if(D(this._surveyManager))return{eligible:!1,reason:$r};var e=typeof t=="string"?this.Hl(t):t;return e?this._surveyManager.checkSurveyRenderability(e):{eligible:!1,reason:"Survey not found"}}canRenderSurvey(t){if(D(this._surveyManager))return q.warn("init was not called"),{visible:!1,disabledReason:$r};var e=this.zl(t);return{visible:e.eligible,disabledReason:e.reason}}canRenderSurveyAsync(t,e){return D(this._surveyManager)?(q.warn("init was not called"),Promise.resolve({visible:!1,disabledReason:$r})):new Promise((s=>{this.getSurveys((r=>{var n,i=(n=r.find((a=>a.id===t)))!==null&&n!==void 0?n:null;if(i){var o=this.zl(i);s({visible:o.eligible,disabledReason:o.reason})}else s({visible:!1,disabledReason:"Survey not found"})}),e)}))}renderSurvey(t,e,s){var r;if(D(this._surveyManager))q.warn("init was not called");else{var n=typeof t=="string"?this.Hl(t):t;if(n!=null&&n.id)if(Xp.includes(n.type)){var i=C?.querySelector(e);if(i)return(r=n.appearance)!=null&&r.surveyPopupDelaySeconds?(q.info("Rendering survey "+n.id+" with delay of "+n.appearance.surveyPopupDelaySeconds+" seconds"),void setTimeout((()=>{var o,a;q.info("Rendering survey "+n.id+" with delay of "+((o=n.appearance)==null?void 0:o.surveyPopupDelaySeconds)+" seconds"),(a=this._surveyManager)==null||a.renderSurvey(n,i,s),q.info("Survey "+n.id+" rendered")}),1e3*n.appearance.surveyPopupDelaySeconds)):void this._surveyManager.renderSurvey(n,i,s);q.warn("Survey element not found")}else q.warn("Surveys of type "+n.type+" cannot be rendered in the app");else q.warn("Survey not found")}}displaySurvey(t,e){var s;if(D(this._surveyManager))q.warn("init was not called");else{var r=this.Hl(t);if(r){var n=r;if((s=r.appearance)!=null&&s.surveyPopupDelaySeconds&&e.ignoreDelay&&(n=w({},r,{appearance:w({},r.appearance,{surveyPopupDelaySeconds:0})})),e.displayType!==oo.Popover&&e.initialResponses&&q.warn("initialResponses is only supported for popover surveys. prefill will not be applied."),e.ignoreConditions===!1){var i=this.Ul(r);if(!i.eligible)return void q.warn("Survey is not eligible to be displayed: ",i.reason)}e.displayType!==oo.Inline?this._surveyManager.handlePopoverSurvey(n,e):this.renderSurvey(n,e.selector,e.properties)}else q.warn("Survey not found")}}cancelPendingSurvey(t){D(this._surveyManager)?q.warn("init was not called"):this._surveyManager.cancelSurvey(t)}handlePageUnload(){var t;(t=this._surveyManager)==null||t.handlePageUnload==null||t.handlePageUnload()}}},Tn),Ff={toolbar:class{constructor(t){this.instance=t}Wl(t){$.ph_toolbar_state=t}Vl(){var t;return(t=$.ph_toolbar_state)!==null&&t!==void 0?t:0}initialize(){return this.maybeLoadToolbar()}maybeLoadToolbar(t,e,s){if(t===void 0&&(t=void 0),e===void 0&&(e=void 0),s===void 0&&(s=void 0),ro(this.instance.config)||!v||!C)return!1;t=t??v.location,s=s??v.history;try{if(!e){try{v.localStorage.setItem("test","test"),v.localStorage.removeItem("test")}catch{return!1}e=v?.localStorage}var r,n=_f||dn(t.hash,"__posthog")||dn(t.hash,"state"),i=n?tl((()=>JSON.parse(atob(decodeURIComponent(n)))))||tl((()=>JSON.parse(decodeURIComponent(n)))):null;return i&&i.action==="ph_authorize"?((r=i).source="url",r&&Object.keys(r).length>0&&(i.desiredHash?t.hash=i.desiredHash:s?s.replaceState(s.state,"",t.pathname+t.search):t.hash="")):((r=JSON.parse(e.getItem(Dl)||"{}")).source="localstorage",delete r.userIntent),!(!r.token||this.instance.config.token!==r.token||(this.loadToolbar(r),0))}catch{return!1}}Zl(t){var e=$.ph_load_toolbar||$.ph_load_editor;!D(e)&&Se(e)?e(t,this.instance):Bl.warn("No toolbar load function found")}loadToolbar(t){var e=!(C==null||!C.getElementById(bu));if(!v||e)return!1;var s=this.instance.requestRouter.region==="custom"&&this.instance.config.advanced_disable_toolbar_metrics,r=w({token:this.instance.config.token},t,{apiURL:this.instance.requestRouter.endpointFor("ui")},s?{instrument:!1}:{});if(v.localStorage.setItem(Dl,JSON.stringify(w({},r,{source:void 0}))),this.Vl()===2)this.Zl(r);else if(this.Vl()===0){var n;this.Wl(1),(n=$.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this.instance,"toolbar",(i=>{if(i)return Bl.error("[Toolbar] Failed to load",i),void this.Wl(0);this.Wl(2),this.Zl(r)})),ne(v,"turbolinks:load",(()=>{this.Wl(0),this.loadToolbar(r)}))}return!0}Gl(t){return this.loadToolbar(t)}maybeLoadEditor(t,e,s){return t===void 0&&(t=void 0),e===void 0&&(e=void 0),s===void 0&&(s=void 0),this.maybeLoadToolbar(t,e,s)}}},Pf=w({experiments:ye},Tn),Af={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;D(e)||(Ke(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||ro(this._instance.config)||this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut())){var t=$?.__PosthogExtensions__;if(t&&!x(this.Ql)&&this.Ql)if(this.Jl&&this.Jl.token){this.Kl=!0;try{var e=t.initConversations;if(e)return this.tu(e),void(this.Kl=!1);var s=t.loadExternalDependency;if(!s)return void this.eu(Vo);s(this._instance,"conversations",(r=>{r||!t.initConversations?this.eu("Could not load conversations script",r):this.tu(t.initConversations),this.Kl=!1}))}catch(r){this.eu("Error initializing conversations",r),this.Kl=!1}}else Ue.error("Conversations enabled but missing token in remote config.")}}tu(t){if(this.Jl)try{this._conversationsManager=t(this.Jl,this._instance),this.Yl=!1,Ue.info("Conversations loaded successfully")}catch(e){this.eu("Error completing conversations initialization",e)}else Ue.error("Cannot complete initialization: remote config is null")}eu(t,e){Ue.error(t,e),this._conversationsManager=null,this.Kl=!1,this.Yl=!0}show(){this._conversationsManager?this._conversationsManager.show():Ue.warn("Conversations not loaded yet.")}hide(){this._conversationsManager&&this._conversationsManager.hide()}isAvailable(){return this.Ql===!0&&!$e(this._conversationsManager)}getUnavailableReason(){return this.isAvailable()?null:this._instance.config.disable_conversations?"disabled_by_config":ro(this._instance.config)?"disabled_for_toolbar":this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut()?"consent_opted_out":this.Xl===!1?"remote_config_failed":x(this.Ql)?this.Xl?"disabled_in_project":"remote_config_pending":this.Ql?D(this.Jl)||!this.Jl.token?"missing_token":$!=null&&$.__PosthogExtensions__?this.Kl?"initializing":this.Yl?"load_failed":"not_loaded":"extensions_unavailable":"disabled_in_project"}isVisible(){var t,e;return(t=(e=this._conversationsManager)==null?void 0:e.isVisible())!==null&&t!==void 0&&t}sendMessage(t,e,s){var r=this;return X((function*(){return r._conversationsManager?r._conversationsManager.sendMessage(t,e,s):(Ue.warn(Dt),null)}))()}getMessages(t,e){var s=this;return X((function*(){return s._conversationsManager?s._conversationsManager.getMessages(t,e):(Ue.warn(Dt),null)}))()}markAsRead(t){var e=this;return X((function*(){return e._conversationsManager?e._conversationsManager.markAsRead(t):(Ue.warn(Dt),null)}))()}getTickets(t){var e=this;return X((function*(){return e._conversationsManager?e._conversationsManager.getTickets(t):(Ue.warn(Dt),null)}))()}requestRestoreLink(t){var e=this;return X((function*(){return e._conversationsManager?e._conversationsManager.requestRestoreLink(t):(Ue.warn(Dt),null)}))()}restoreFromToken(t){var e=this;return X((function*(){return e._conversationsManager?e._conversationsManager.restoreFromToken(t):(Ue.warn(Dt),null)}))()}restoreFromUrlToken(){var t=this;return X((function*(){return t._conversationsManager?t._conversationsManager.restoreFromUrlToken():(Ue.warn(Dt),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()}}},$f={logs:class{constructor(t){var e,s=this;this.iu=!1,this.ru=!1,this.rt=se("[logs]"),this.nu=w({},this.rt,{error(){for(var r=arguments.length,n=new Array(r),i=0;r>i;i++)n[i]=arguments[i];n.some(Gl)||s.rt.error(...n)}}),this.tr=[],this.su=[],this.Sa=0,this.au=()=>{var r,n;this.Sa=0,(r=this.ou)==null||r.onReconnect(),(n=this.lu)==null||n.onReconnect()},this._instance=t,this._instance&&(e=this._instance.config.logs)!=null&&e.captureConsoleLogs&&(this.iu=!0),v&&ne(v,"online",this.au)}uu(t,e,s,r){var n,i=(function(o,a){var l,u,c,d,h,p,f,g=(l=o?.flushIntervalMs)!==null&&l!==void 0?l:3e3,m=(u=o?.maxBufferSize)!==null&&u!==void 0?u:100,_=a!=null&&a.consoleCapture?void 0:(c=o?.maxLogsPerInterval)!==null&&c!==void 0?c:1e3,b=x(_)?Math.max(m,2048):Math.max(m,_),E=o?.resourceAttributes;return{serviceName:(d=(h=E?.["service.name"])!==null&&h!==void 0?h:o?.serviceName)!==null&&d!==void 0?d:a?.serviceNameDefault,serviceVersion:(p=E?.["service.version"])!==null&&p!==void 0?p:o?.serviceVersion,environment:(f=E?.["deployment.environment"])!==null&&f!==void 0?f:o?.environment,resourceAttributes:E,beforeSend:o?.beforeSend,flushIntervalMs:g,maxBufferSize:m,maxQueueSize:b,maxBatchRecordsPerPost:100,rateCapWindowMs:g,maxLogsPerInterval:_,backgroundFlushBudgetMs:0,terminationFlushBudgetMs:0}})((n=this._instance)==null||(n=n.config)==null?void 0:n.logs,s);return[new Nh(this.hu(t,e),i,this.nu,(()=>this.du()),(o=>o()),void 0,r),i]}vu(){var t,e=(t=this._instance)==null||(t=t.config)==null?void 0:t.logs;if(!this.ou||this.cu!==e){var s;(s=this.ou)==null||s.reset(),this.cu=e;var r=this.uu((()=>this.tr),(n=>{this.tr=n}));this.ou=r[0],this.fu=r[1]}return this.ou}pu(){var t,e=(t=this._instance)==null||(t=t.config)==null?void 0:t.logs;if(!this.lu||this.gu!==e){var s;(s=this.lu)==null||s.reset(),this.gu=e;var r=this.uu((()=>this.su),(n=>{this.su=n}),{serviceNameDefault:"posthog-browser-logs",consoleCapture:!0},Vl);this.lu=r[0],this.mu=r[1]}return this.lu}initialize(){this.loadIfEnabled()}onRemoteConfig(t){var e;if(t.ok){var s=(e=t.config.logs)==null?void 0:e.captureConsoleLogs;!D(s)&&s&&(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){Gl(t)||this.rt.error("PostHog logs flush failed:",t)}loadIfEnabled(){if(this.iu&&!this.ru){var t=$?.__PosthogExtensions__;if(t){var e=t.loadExternalDependency;e?e(this._instance,"logs",(s=>{var r;s||(r=t.logs)==null||!r.initializeLogs?this.rt.error("Could not load logs script",s):(t.logs.initializeLogs(this._instance),this.ru=!0)})):this.rt.error(Vo)}else this.rt.error("PostHog Extensions not found.")}}hu(t,e){var s=this._instance;return{get isDisabled(){return!1},get optedOut(){return!s.is_capturing()},getPersistedProperty:r=>r===ut.LogsQueue?t():void 0,setPersistedProperty(r,n){var i;r===ut.LogsQueue&&e((i=n)!==null&&i!==void 0?i:[])},Ot:r=>this.Ot(r),getLibraryId:()=>Y.LIB_NAME,getLibraryVersion:()=>Y.LIB_VERSION}}Ot(t){return new Promise((e=>{if(Tu(this.Sa,3))e({kind:"fatal",error:Ii(void 0,"logs endpoint is unreachable, dropping batch")});else{var s=!1,r=i=>{s||(s=!0,clearTimeout(n),e(i))},n=setTimeout((()=>{this.rt.warn("Logs request timed out before receiving a response"),r({kind:"retry-later",error:Ii(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:i=>{var o=i.statusCode;if(this.ku(o),o>=200&&300>o)r({kind:"ok"});else if(o===413)r({kind:"too-large"});else if(o!==0&&o!==429&&500>o)r({kind:"fatal",error:new Error("logs request failed with status "+o)});else{var a;o===0?(i.error||this.rt.warn("Logs request failed before receiving an HTTP response"),r({kind:"retry-later",error:Ii(i.error,"logs request failed before receiving an HTTP response")})):r({kind:"retry-later",error:(a=i.error)!==null&&a!==void 0?a:new Error("logs request failed with status "+o)})}}})}}))}ku(t){(t!==0||this._instance.__loaded)&&(this.Sa=Nu(t,this.Sa,3,(()=>this.rt.warn("Log requests are failing before receiving an HTTP response; this can happen due to network issues, CORS, browser blocking, or ad blockers. Stopped sending logs; will try again when connectivity changes."))))}bu(t){this.tr.length>0&&this.xu(t,this.tr,this.fu,Y.LIB_NAME,(e=>{this.tr=e})),this.su.length>0&&this.xu(t,this.su,this.mu,Vl,(e=>{this.su=e}))}xu(t,e,s,r,n){if(e.length!==0){var i=e.map((a=>a.record));n([]);var o=nu(i,ru(s,Y.LIB_NAME,Y.LIB_VERSION),r,Y.LIB_VERSION);this._instance._send_request({method:"POST",url:this.wu(),data:o,compression:"best-available",batchKey:"logs",transport:t})}}wu(){return this._instance.requestRouter.endpointFor("api","/i/v1/logs")+"?token="+encodeURIComponent(this._instance.config.token)}du(){var t,e={};if(e.distinctId=this._instance.get_distinct_id(),this._instance.sessionManager){var s=this._instance.sessionManager.checkAndGetSessionAndWindowId(!0),r=s.windowId,n=s.sessionStartTimestamp,i=s.lastActivityTimestamp;e.sessionId=s.sessionId,e.windowId=r,D(n)||(e.sessionStartTimestamp=n),D(i)||(e.lastActivityTimestamp=i)}if($!=null&&(t=$.location)!=null&&t.href&&(e.currentUrl=this._instance.config.disable_capture_url_hashes?Ct($.location.href):$.location.href),this._instance.featureFlags){var o=this._instance.featureFlags.getFlags();o&&o.length>0&&(e.activeFeatureFlags=o)}return e}}},Rf={metrics:class{constructor(t){this.rt=se("[metrics]"),this._instance=t}initialize(){}vu(){var t,e,s=(t=this._instance)==null||(t=t.config)==null?void 0:t.metrics;return this.ou&&this.cu===s||((e=this.ou)==null||e.reset(),this.cu=s,this.ou=new Mh(this.hu(),(function(r){var n,i,o,a,l,u=r?.resourceAttributes;return{serviceName:(n=u?.["service.name"])!==null&&n!==void 0?n:r?.serviceName,serviceVersion:(i=u?.["service.version"])!==null&&i!==void 0?i:r?.serviceVersion,environment:(o=u?.["deployment.environment"])!==null&&o!==void 0?o:r?.environment,resourceAttributes:u,beforeSend:r?.beforeSend,flushIntervalMs:(a=r?.flushIntervalMs)!==null&&a!==void 0?a:1e4,maxSeriesPerFlush:(l=r?.maxSeriesPerFlush)!==null&&l!==void 0?l:1e3}})(s),this.rt)),this.ou}count(t,e,s){e===void 0&&(e=1),this.vu().count(t,e,s)}gauge(t,e,s){this.vu().gauge(t,e,s)}histogram(t,e,s){this.vu().histogram(t,e,s)}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((s=>this.rt.error("PostHog metrics flush failed:",s)))}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:s=>e.Jt(s),getLibraryId:()=>Y.LIB_NAME,getLibraryVersion:()=>Y.LIB_VERSION}}Jt(t,e){return new Promise((s=>{var r=!1,n=o=>{r||(r=!0,clearTimeout(i),s(o))},i=setTimeout((()=>n({kind:"retry-later",error:new Error("metrics request timed out")})),9e4);this._instance._send_request(w({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)n({kind:"ok"});else if(a===413)n({kind:"too-large"});else if(a!==0&&a!==429&&500>a)n({kind:"fatal",error:new Error("metrics request failed with status "+a)});else{var l;n({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)}}},Tf=w({},Tn,bf,Ef,Sf,xf,kf,Cf,If,Ff,Pf,Af,$f,Rf);Te.__defaultExtensionClasses=w({},Tf);var ud=(function(){Y.SDK_DIST_CHANNEL="npm";var t=Zs[as]=new Te;return(function(){function e(){e.done||(e.done=!0,ld=!1,Z(Zs,(function(s){s._dom_loaded()})))}C!=null&&C.addEventListener?C.readyState==="complete"?e():ne(C,"DOMContentLoaded",e,{capture:!1}):v&&k.error("Browser doesn't support `document.addEventListener` so PostHog couldn't be initialized")})(),t})();const dd="CodeFile",hd="GeneratedCode",Nf={CustomAction:"A",CustomWidget:"W",CustomFunction:"F",CustomClass:"C",CodeFile:"C"};function kt(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function go(t){return String(t||"").trim().replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function Mf(t={},e=0){const s=go(t.artifactType||t.type||dd),r=go(t.artifactName||t.name||t.fileName||`${hd}-${e+1}`);return`${s||"artifact"}-${r||e+1}`}function pd(t={},e=0){const s=kt(t),r=s.artifactType||s.type||dd,n=s.artifactName||s.name||hd;let i=s.fileName||n;return i.endsWith(".dart")||(i+=".dart"),{id:go(s.id)||Mf({...s,artifactType:r,artifactName:n,fileName:i},e),artifactType:r,artifactName:n,fileName:i,deployPath:s.deployPath||"",description:s.description||"",code:s.code||s.content||"",dependencies:fd(s.dependencies),imports:Array.isArray(s.imports)?s.imports:[],publicApi:Array.isArray(s.publicApi)?s.publicApi:[],relationships:gd(s.relationships),deployStatus:s.deployStatus||"pending",review:s.review||null,metadata:kt(s.metadata),codeType:s.codeType||Nf[r]||"O"}}function fd(t){return t?Array.isArray(t)?t.map(e=>{if(typeof e=="string")return{name:e,version:null,inferred:!1};const s=kt(e),r=s.name||s.package;return r?{name:r,version:s.version||null,versionRequired:!!(s.versionRequired||s.required),inferred:!!s.inferred,...s.reason?{reason:s.reason}:{}}:null}).filter(Boolean):Object.entries(kt(t)).map(([e,s])=>({name:e,version:s||null,inferred:!1})):[]}function gd(t){return t?(Array.isArray(t)?t:[t]).map(e=>{const s=kt(e);return!s.from&&!s.to?null:{from:s.from||null,to:s.to||null,type:s.type||"uses",description:s.description||""}}).filter(Boolean):[]}function mo(t){if(typeof t!="string")return null;const e=t.trim();if(!e)return null;try{return JSON.parse(e)}catch{const s=e.match(/```(?:json)?\s*([\s\S]*?)```/i);if(!s)return null;try{return JSON.parse(s[1].trim())}catch{return null}}}function ar(t,e={}){const s=[],r=typeof t=="string"?mo(t):t,i=kt(r||{});!r&&typeof t=="string"&&s.push("Structured bundle parse failed; using legacy single-artifact fallback.");const o=Array.isArray(i.artifacts)?i.artifacts:[{artifactType:i.artifactType||e.artifactType,artifactName:i.artifactName||e.artifactName,fileName:i.fileName||e.fileName,description:i.description,code:i.code||e.code||(typeof t=="string"?t:""),dependencies:i.dependencies||e.dependencies,relationships:i.relationships||e.relationships}];o.forEach((d,h)=>{!d?.artifactType&&!d?.type&&s.push(`Artifact ${h+1} has no artifactType; it will deploy as a standalone code file under lib/custom_code/ root.`)});const a=o.map((d,h)=>pd(d,h)),l=new Map(o.map((d,h)=>[kt(d).id,a[h]?.id]).filter(([d,h])=>d&&h)),u=d=>l.get(d)||d,c=gd(i.relationships||e.relationships).map(d=>({...d,from:d.from?u(d.from):d.from,to:d.to?u(d.to):d.to}));return{schemaVersion:i.schemaVersion||e.schemaVersion||null,id:i.id||e.id||"bundle-current",title:i.title||i.name||e.title||"Generated artifact bundle",description:i.description||e.description||"",artifacts:a,dependencies:fd(i.dependencies||e.dependencies),relationships:c,deployOrder:Array.isArray(i.deployOrder)?i.deployOrder.map(u):a.map(d=>d.id),warnings:[...s,...Array.isArray(i.warnings)?i.warnings:[]],metadata:kt(i.metadata)}}function mn(t){return ar(t).artifacts[0]||pd()}function yt(t){if(typeof t!="string")return t??"";const e=t.trim();if(!e)return"";try{return JSON.parse(e)}catch{return t}}function ws(t){return JSON.stringify(t,null,2)}function Lf(t){return ws({task:"architect",userRequest:String(t??"")})}function Of(t){const e=yt(t);return e&&typeof e=="object"&&typeof e.task=="string"?ws(e):ws({task:"generate_bundle",bundleSpec:e})}function Df(t){return ws({task:"review_bundle",generatedBundle:yt(t),outputRequirements:{bundleReview:["status","score","summary","manualActions","findings"],scoreRange:[0,100],eachArtifact:["id","review.status","review.findings"],manualActions:{definition:"Setup the developer must perform by hand in the FlutterFlow editor that FlutterFlow will NOT do for them.",exclude:["creating the Custom Action, Widget or Code File itself - deploying the code creates it","declaring parameters or return values FlutterFlow derives from the function signature","anything that resolves as a side effect of using the action or widget in the editor","generic advice such as testing, reviewing or rebuilding the app"],preferEmpty:"Return an empty array when nothing qualifies - an empty list is the expected result for most bundles."}}})}function ea(t,e=null){const s={stage:t};return e!=null&&(s.bundle=yt(e)),s}function Bf({bundleSpec:t,artifactBundle:e,bundleReview:s,artifactId:r,userFeedback:n}){return ws({task:"regenerate_artifact",artifactId:r,bundleSpec:yt(t),artifactBundle:yt(e),bundleReview:yt(s),userFeedback:String(n)})}function md({bundleSpec:t,artifactBundle:e,bundleReview:s,userFeedback:r}){return ws({task:"regenerate_bundle",bundleSpec:yt(t),artifactBundle:yt(e),bundleReview:yt(s),userFeedback:String(r??"")})}const Kl={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"},jf=["sanitizationResult","modelArmor","modelArmorResult","data","result","error"];function Le(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function Uf(t){return Le(t)?typeof t.filterMatchState=="string"||typeof t.invocationResult=="string"||Array.isArray(t.matchedFilters)||Le(t.filterSummary)||Le(t.filterResults):!1}function vd(t,e=0){if(!Le(t)||e>3)return null;if(Uf(t))return t;for(const s of jf){const r=t[s];if(Le(r)){const n=vd(r,e+1);if(n)return n}}return null}function vn(t){return Array.isArray(t)?t.some(vn):Le(t)?t.matched===!0||t.matchState==="MATCH_FOUND"?!0:Object.values(t).some(vn):!1}function vo(t){return Array.isArray(t)?t.some(vo):Le(t)?typeof t.executionState=="string"&&t.executionState!=="EXECUTION_SUCCESS"?!0:Object.values(t).some(vo):!1}function _d(t){return{csamFilterFilterResult:"csam",maliciousUriFilterResult:"malicious_uris",piAndJailbreakFilterResult:"pi_and_jailbreak",raiFilterResult:"rai",sdpFilterResult:"sdp",virusScanFilterResult:"virus_scan"}[t]||t}function Hf(t,e){if(Le(t))for(const[s,r]of Object.entries(t)){if(!Le(r))continue;const n=Le(r.categories)?r.categories:{},i=Object.entries(n).filter(([,o])=>Le(o)&&o.matched===!0).map(([o])=>o);i.length>0?i.forEach(o=>e.add(o)):r.matched===!0&&e.add(_d(s))}}function Wf(t,e){if(!t)return;const s=Array.isArray(t)?t.flatMap(r=>Le(r)?Object.entries(r):[]):Object.entries(t);for(const[r,n]of s){if(!vn(n))continue;const i=_d(r),o=n?.raiFilterResult?.raiFilterTypeResults||(i==="rai"?n?.raiFilterTypeResults:null),a=Le(o)?Object.entries(o).filter(([,l])=>vn(l)).map(([l])=>l):[];a.length>0?a.forEach(l=>e.add(l)):e.add(i)}}function zf(t){return Kl[t]?Kl[t]:String(t).replace(/([a-z])([A-Z])/g,"$1 $2").replace(/_/g," ").toLowerCase()}function Jl(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 qf(t){const e=vd(t);if(!e)return null;const s=new Set(Array.isArray(e.matchedFilters)?e.matchedFilters:[]);Hf(e.filterSummary,s),Wf(e.filterResults,s);const r=e.blocked===!0||e.filterMatchState==="MATCH_FOUND"||s.size>0,n=e.invocationResult||null,i=vo(e.filterSummary||e.filterResults);return!r&&!i&&!["PARTIAL","FAILURE"].includes(n)?null:{kind:r?"blocked":"unavailable",invocationResult:n,matchedFilters:[...s]}}function Vf(t,e){const s=qf(t);if(!s)return null;const r=[...new Set(s.matchedFilters.map(zf))],n=s.kind==="blocked",i=new Error(n?`Safety screening blocked this pipeline step for ${Jl(r)}.`:"Safety screening could not be completed. Please try again.");return i.name="ModelArmorError",i.code=n?"MODEL_ARMOR_BLOCKED":"MODEL_ARMOR_UNAVAILABLE",i.isModelArmor=!0,i.pipelineStep=e,i.userTitle=n?"Request blocked for safety":"Safety check unavailable",i.userMessage=n?`The safety check detected ${Jl(r)}. Edit your request to remove or rephrase the flagged content, then run the pipeline again.`:"The safety service did not finish all of its checks. Please wait a moment and run the pipeline again.",i.retryExplanation=n?"Trying another model would not change this safety decision.":"A fallback model was not attempted because safety screening must complete first.",i.matchedFilters=s.matchedFilters,i}function Gf(t){return String(t||"").replace(/\/\*[\s\S]*?\*\//g,"").replace(/\/\/[^\n]*/g,"")}function Yl(t){const e=/^(import|export|part|library|class|enum|extension|typedef|mixin|abstract|const|final|var|late)\b/,s=[];for(const r of Gf(t).split(` -`)){if(!/^[A-Za-z_$]/.test(r)||e.test(r))continue;const n=r.match(/^[\w$<>,?\s[\]]+?\s([a-zA-Z_$][\w$]*)\s*\(/);n&&s.push(n[1])}return s}function ta(t,e){const s=t.replace(/\.dart$/,"");if(e==="W")return s.replace(/(^|_)(\w)/g,(r,n,i)=>i.toUpperCase());if(e==="A"){const r=s.replace(/(^|_)(\w)/g,(n,i,o)=>o.toUpperCase());return r.charAt(0).toLowerCase()+r.slice(1)}return e==="F"?"CustomFunctions":e==="C"?t.endsWith(".dart")?t:`${t}.dart`:s}async function Zl(t){const e=new TextEncoder().encode(String(t||"")),s=await globalThis.crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(s),r=>r.toString(16).padStart(2,"0")).join("")}async function Kf(t,e=new Map){const s={},r=new Set;for(const[o,a]of t.entries()){if(a.type==="D"||a.type==="O")continue;const l=ta(o,a.type),u={old_identifier_name:l,new_identifier_name:l,type:a.type,is_deleted:!1,current_checksum:await Zl(a.content)},c=e.get(a.path);if(c!==void 0&&(u.original_checksum=await Zl(c)),s[o]=u,a.type==="F"){const d=Yl(a.content);(d.length>0?d:[a.functionName].filter(Boolean)).forEach(p=>r.add(p))}}const n=new Set(Yl(e.get("lib/flutter_flow/custom_functions.dart")||"")),i={functions_to_rename:[],functions_to_delete:[],functions_to_add:Array.from(r).filter(o=>!n.has(o))};return{fileMapContents:JSON.stringify(s),functionsMapContents:JSON.stringify(i)}}const Jf=new Set(["CustomWidget","CustomAction","CustomFunction","CustomClass","CodeFile"]),Xl={CustomWidget:"custom_code/widgets/",CustomAction:"custom_code/actions/",CustomFunction:"flutter_flow/custom_functions.dart",CustomClass:"custom_code/",CodeFile:"custom_code/"},Yf=new Set(["void","dynamic","String","int","double","num","bool","Color","DateTime","DateTimeRange","LatLng","FFPlace","FFUploadedFile","DocumentReference","List"]),Zf=["Struct","Record"],Xf=[{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=>Ci(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=>Ci(t).some(e=>{const s=/^\s*final\s+(?:double|int|String|bool|Color|num)\s+(\w+)\s*;/gm;let r;for(;(r=s.exec(e))!==null;){const n=r[1];if(!(new RegExp(`this\\.${n}\\s*=(?!=)`).test(e)||new RegExp(`[:,]\\s*${n}\\s*=(?!=)`).test(e)))return!0}return!1}),pos:`class W extends StatefulWidget { +(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const n of document.querySelectorAll('link[rel="modulepreload"]'))r(n);new MutationObserver(n=>{for(const i of n)if(i.type==="childList")for(const o of i.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&r(o)}).observe(document,{childList:!0,subtree:!0});function s(n){const i={};return n.integrity&&(i.integrity=n.integrity),n.referrerPolicy&&(i.referrerPolicy=n.referrerPolicy),n.crossOrigin==="use-credentials"?i.credentials="include":n.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function r(n){if(n.ep)return;n.ep=!0;const i=s(n);fetch(n.href,i)}})();var v=typeof window<"u"?window:void 0,we=typeof globalThis<"u"?globalThis:v,ke=we?.navigator,C=we?.document,re=we?.location,Mo=we?.fetch,$i=we!=null&&we.XMLHttpRequest&&"withCredentials"in new we.XMLHttpRequest?we.XMLHttpRequest:void 0,Ma=we?.AbortController,ah=we?.CompressionStream,Pe=ke?.userAgent;function kc(){return!(!v||v.navigator.onLine===!1)}var Cs=typeof globalThis<"u"?globalThis:v;Cs&&typeof self>"u"&&(Cs.self=Cs),Cs&&typeof File>"u"&&(Cs.File=function(){});var $=v??{},Y={DEBUG:!1,LIB_VERSION:"0.5.0",LIB_NAME:"browser-common"};function La(t,e,s,r,n,i,o){try{var a=t[i](o),l=a.value}catch(u){return void s(u)}a.done?e(l):Promise.resolve(l).then(r,n)}function X(t){return function(){var e=this,s=arguments;return new Promise((function(r,n){var i=t.apply(e,s);function o(l){La(i,r,n,o,a,"next",l)}function a(l){La(i,r,n,o,a,"throw",l)}o(void 0)}))}}function w(){return w=Object.assign?Object.assign.bind():function(t){for(var e=1;arguments.length>e;e++){var s=arguments[e];for(var r in s)({}).hasOwnProperty.call(s,r)&&(t[r]=s[r])}return t},w.apply(null,arguments)}function Ic(t,e){if(t==null)return{};var s={};for(var r in t)if({}.hasOwnProperty.call(t,r)){if(e.indexOf(r)!==-1)continue;s[r]=t[r]}return s}var Oa=t=>{if(typeof t!="string")return t;try{return JSON.parse(t)}catch{return t}};function Da(t){return typeof t=="string"||t}function Ba(t){return typeof t=="string"?t:void 0}var Fs,lh=["$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})({}),ja=(function(t){return t.GZipJS="gzip-js",t.Base64="base64",t})({}),ch=["$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"],uh=["token"],Cc="NativeGzipValidationError",Ri=t=>t.length>=2&&t[0]===31&&t[1]===139,Ua=(t,e)=>t===ja.GZipJS||e===ja.GZipJS||e==="gzip",Ha=t=>!(!t||typeof t!="object")&&("name"in t?String(t.name):"")==="NotReadableError",yr=t=>{var e=new Error("Native gzip produced invalid output: "+t);throw e.name=Cc,e},dh=(function(){var t=X((function*(e,s){18>e.size&&yr("too-short");var r=new Uint8Array(yield e.slice(0,10).arrayBuffer());Ri(r)&&r[2]===8||yr("invalid-header");var n=new DataView(yield e.slice(e.size-8).arrayBuffer());n.getUint32(0,!0)!==(o=>{for(var a=(()=>{if(Fs)return Fs;Fs=[];for(var c=0;256>c;c++){for(var d=c,h=0;8>h;h++)d=1&d?3988292384^d>>>1:d>>>1;Fs[c]=d>>>0}return Fs})(),l=4294967295,u=0;o.length>u;u++)l=a[255&(l^o[u])]^l>>>8;return(4294967295^l)>>>0})(s)&&yr("invalid-crc");var i=s.length>>>0;n.getUint32(4,!0)!==i&&yr("invalid-size")}));return function(e,s){return t.apply(this,arguments)}})();function Ti(){return Ti=X((function*(t,e,s){e===void 0&&(e=!0);try{var r=new TextEncoder().encode(t),n=new globalThis.CompressionStream("gzip"),i=n.writable.getWriter(),o=i.write(r).then((()=>i.close())).catch((function(){var u=X((function*(c){try{yield i.abort(c)}catch{}throw c}));return function(c){return u.apply(this,arguments)}})()),a=new Response(n.readable).blob(),l=(yield Promise.all([a,o]))[0];return yield dh(l,r),l}catch(u){if(s!=null&&s.rethrow)throw u;return e&&console.error("Failed to gzip compress data",u),null}})),Ti.apply(this,arguments)}var hh=["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"],Wa=function(t,e){if(e===void 0&&(e=[]),!t)return!1;var s=t.toLowerCase();return hh.concat(e).some((r=>{var n=r.toLowerCase();return s.indexOf(n)!==-1}))};function M(t,e){return t.indexOf(e)!==-1}var Pn=function(t){return t.trim()},Ni=function(t){return t.replace(/^\$/,"")};function Fc(t){var e,s=[];return(e=JSON.stringify(t,(function(r,n){if(typeof n=="bigint")return n.toString();if(typeof n!="function"&&typeof n!="symbol"){if(n instanceof Error)return{name:n.name,message:n.message,stack:n.stack};if(n&&typeof n=="object"){for(;s.length>0&&s[s.length-1]!==this;)s.pop();if(s.includes(n))return"[Circular]";s.push(n)}return n}})))!==null&&e!==void 0?e:"null"}var Pc=Object.prototype,Ac=Pc.hasOwnProperty,An=Pc.toString,L=Array.isArray||function(t){return An.call(t)==="[object Array]"},Se=t=>typeof t=="function",te=t=>t===Object(t)&&!L(t),mt=t=>{if(te(t)){for(var e in t)if(Ac.call(t,e))return!1;return!0}return!1},x=t=>t===void 0,W=t=>An.call(t)=="[object String]",Mi=t=>W(t)&&t.trim().length===0,$e=t=>t===null,D=t=>x(t)||$e(t),he=t=>An.call(t)=="[object Number]"&&t==t,lt=t=>he(t)&&t>0,Ke=t=>An.call(t)==="[object Boolean]",ph=t=>t instanceof FormData,fh=t=>M(ch,t),gh=t=>M(uh,t);function $c(t){return t===null||typeof t!="object"}function qr(t,e){return{}.toString.call(t)==="[object "+e+"]"}function Lo(t){return typeof Event<"u"&&Rc(t,Event)}function Rc(t,e){try{return t instanceof e}catch{return!1}}var mh=[!0,"true",1,"1","yes"],Zn=t=>M(mh,t),vh=[!1,"false",0,"0","no"];function rt(t,e,s,r,n){return e>s&&(r.warn("min cannot be greater than max."),e=s),he(t)?t>s?(r.warn(" cannot be greater than max: "+s+". Using max value instead."),s):e>t?(r.warn(" cannot be less than min: "+e+". Using min value instead."),e):t:(r.warn(" must be a number. using max or fallback. max: "+s+", fallback: "+n),rt(n||s,e,s,r))}class _h{constructor(e){this.tt={},this.et=e.et,this.it=rt(e.bucketSize,0,100,e.rt),this.nt=rt(e.refillRate,0,this.it,e.rt),this.st=rt(e.refillInterval,0,864e5,e.rt)}ot(e,s){var r=Math.floor((s-e.lastAccess)/this.st);r>0&&(e.tokens=Math.min(e.tokens+r*this.nt,this.it),e.lastAccess=e.lastAccess+r*this.st)}consumeRateLimit(e){var s,r=Date.now(),n=String(e),i=this.tt[n];return i?this.ot(i,r):this.tt[n]=i={tokens:this.it,lastAccess:r},i.tokens===0||(i.tokens--,i.tokens===0&&((s=this.et)==null||s.call(this,e)),i.tokens===0)}stop(){this.tt={}}}var Oe="Mobile",Vr="iOS",vt="Android",ps="Tablet",Tc=vt+" "+ps,Nc="iPad",Mc="Apple",Lc=Mc+" Watch",qs="Safari",fs="BlackBerry",Oc="Samsung",Dc=Oc+"Browser",Bc=Oc+" Internet",Vt="Chrome",yh=Vt+" OS",jc=Vt+" "+Vr,Oo="Internet Explorer",Uc=Oo+" "+Oe,Do="Opera",wh=Do+" Mini",Bo="Edge",Hc="Microsoft "+Bo,us="Firefox",Wc=us+" "+Vr,er="Nintendo",tr="PlayStation",ds="Xbox",zc=vt+" "+Oe,qc=Oe+" "+qs,Ds="Windows",Li=Ds+" Phone",za="Nokia",Oi="Ouya",Vc="Generic",bh=Vc+" "+Oe.toLowerCase(),Gc=Vc+" "+ps.toLowerCase(),Di="Konqueror",Kc="Oculus Browser",Gr="Vivaldi",Jc="Yandex",Kr="Whale",Bi="DuckDuckGo",Yc="Pale Moon",Jr="Waterfox",Vs="Brave",Zc="Google Search App",le="(\\d+(\\.\\d+)?)",Xn=new RegExp("Version/"+le),Eh=new RegExp(ds,"i"),Sh=new RegExp(tr+" \\w+","i"),xh=new RegExp(er+" \\w+","i"),jo=new RegExp(fs+"|PlayBook|BB10","i"),kh={"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"},Xc=function(t,e,s,r){e=e||"";var n=(function(i){return i!=null&&i.brave?Vs:null})(s);return n||(r!=null&&r.detectGoogleSearchApp&&M(t,"GSA/")?Zc:M(t," OPR/")&&M(t,"Mini")?wh:M(t," OPR/")?Do:jo.test(t)?fs:M(t,"IE"+Oe)||M(t,"WPDesktop")?Uc:M(t,"OculusBrowser")?Kc:M(t,Dc)?Bc:M(t,Bo)||M(t,"Edg/")?Hc:M(t,Gr+"/")?Gr:M(t,"YaBrowser/")?Jc:M(t,Kr+"/")?Kr:M(t,Bi+"/")||M(t,"Ddg/")?Bi:M(t,"FBIOS")?"Facebook "+Oe:M(t,"UCWEB")||M(t,"UCBrowser")?"UC Browser":M(t,"CriOS")?jc:M(t,"CrMo")||M(t,Vt)?Vt:M(t,vt)&&M(t,qs)?zc:M(t,"FxiOS")?Wc:M(t.toLowerCase(),Di.toLowerCase())?Di:M(t,Vs+"/")?Vs:((i,o)=>o&&M(o,Mc)||(function(a){return M(a,qs)&&!M(a,Vt)&&!M(a,vt)})(i))(t,e)?M(t,Oe)?qc:qs:M(t,"PaleMoon/")?Yc:M(t,Jr+"/")?Jr:M(t,us)?us:M(t,"MSIE")||M(t,"Trident/")?Oo:M(t,"Gecko")?us:"")},Ih={[Uc]:[new RegExp("rv:"+le)],[Hc]:[new RegExp(Bo+"?\\/"+le)],[Vt]:[new RegExp("("+Vt+"|CrMo)\\/"+le)],[jc]:[new RegExp("CriOS\\/"+le)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+le)],[qs]:[Xn],[qc]:[Xn],[Do]:[new RegExp("(Opera|OPR)\\/"+le)],[us]:[new RegExp(us+"\\/"+le)],[Wc]:[new RegExp("FxiOS\\/"+le)],[Di]:[new RegExp("Konqueror[:/]?"+le,"i")],[fs]:[new RegExp(fs+" "+le),Xn],[zc]:[new RegExp("android\\s"+le,"i")],[Bc]:[new RegExp(Dc+"\\/"+le)],[Kc]:[new RegExp("OculusBrowser\\/"+le)],[Gr]:[new RegExp(Gr+"\\/"+le)],[Jc]:[new RegExp("YaBrowser\\/"+le)],[Kr]:[new RegExp(Kr+"\\/"+le)],[Vs]:[new RegExp(Vs+"\\/"+le)],[Bi]:[new RegExp("(DuckDuckGo|Ddg)\\/"+le)],[Yc]:[new RegExp("PaleMoon\\/"+le)],[Jr]:[new RegExp(Jr+"\\/"+le)],[Zc]:[new RegExp("GSA\\/"+le)],[Oo]:[new RegExp("(rv:|MSIE )"+le)],Mozilla:[new RegExp("rv:"+le)]},Ch=function(t,e,s,r){var n=Xc(t,e,s,r),i=Ih[n];if(x(i))return null;for(var o=0;i.length>o;o++){var a=t.match(i[o]);if(a)return parseFloat(a[a.length-2])}return null},qa=[[new RegExp(ds+"; "+ds+" (.*?)[);]","i"),t=>[ds,t&&t[1]||""]],[new RegExp(er,"i"),[er,""]],[new RegExp(tr,"i"),[tr,""]],[jo,[fs,""]],[new RegExp(Ds,"i"),(t,e)=>{if(/Phone/.test(e)||/WPDesktop/.test(e))return[Li,""];if(new RegExp(Oe).test(e)&&!/IEMobile\b/.test(e))return[Ds+" "+Oe,""];var s=/Windows NT ([0-9.]+)/i.exec(e);if(s&&s[1]){var r=kh[s[1]]||"";return/arm/i.test(e)&&(r="RT"),[Ds,r]}return[Ds,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,t=>t&&t[3]?[Vr,[t[3],t[4],t[5]||"0"].join(".")]:[Vr,""]],[/(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i,t=>{var e="";return t&&t.length>=3&&(e=x(t[2])?t[3]:t[2]),["watchOS",e]}],[new RegExp("("+vt+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+vt+")","i"),t=>t&&t[2]?[vt,[t[2],t[3],t[4]||"0"].join(".")]:[vt,""]],[/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/,[yh,""]],[/Linux|debian/i,["Linux",""]]],Va=function(t){return xh.test(t)?er:Sh.test(t)?tr:Eh.test(t)?ds:new RegExp(Oi,"i").test(t)?Oi:new RegExp("("+Li+"|WPDesktop)","i").test(t)?Li:/iPad/.test(t)?Nc:/iPod/.test(t)?"iPod Touch":/iPhone/.test(t)?"iPhone":/(watch)(?: ?os[,/]|\d,\d\/)[\d.]+/i.test(t)?Lc:jo.test(t)?fs:/(kobo)\s(ereader|touch)/i.test(t)?"Kobo":new RegExp(za,"i").test(t)?za:/(kf[a-z]{2}wi|aeo[c-r]{2})( bui|\))/i.test(t)||/(kf[a-z]+)( bui|\)).+silk\//i.test(t)?"Kindle Fire":/(Android|ZTE)/i.test(t)?new RegExp(Oe).test(t)&&!/(9138B|TB782B|Nexus [97]|pixel c|HUAWEISHT|BTV|noble nook|smart ultra 6)/i.test(t)||/pixel[\daxl ]{1,6}/i.test(t)&&!/pixel c/i.test(t)||/(huaweimed-al00|tah-|APA|SM-G92|i980|zte|U304AA)/i.test(t)||/lmy47v/i.test(t)&&!/QTAQZ3/i.test(t)?vt:Tc:new RegExp("(pda|"+Oe+")","i").test(t)?bh:new RegExp(ps,"i").test(t)&&!new RegExp(ps+" pc","i").test(t)?Gc:""},Fh=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Ga(t,e){return typeof(s=t)=="string"&&Fh.test(s)?t:e();var s}function Ct(t){return t&&t.split("#")[0]}function Uo(t,e){var s=setTimeout(t,e);return s?.unref&&s?.unref(),s}function Ka(t,e,s){return Qc.apply(this,arguments)}function Qc(){return(Qc=X((function*(t,e,s){var r;try{return yield Promise.race([t,new Promise(((n,i)=>{r=Uo((()=>{try{s?.(),n()}catch(o){i(o)}}),e)}))])}finally{clearTimeout(r)}}))).apply(this,arguments)}var Ph=t=>t instanceof Error,eu={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}},Ah=eu.info;function tu(t){if(Ke(t))return{boolValue:t};if(typeof t=="number")return Number.isFinite(t)?Number.isInteger(t)?{intValue:t}:{doubleValue:t}:{stringValue:String(t)};if(typeof t=="string")return{stringValue:t};if(L(t))return{arrayValue:{values:t.map((e=>tu(e)))}};try{return{stringValue:JSON.stringify(t)}}catch{return{stringValue:String(t)}}}function Yr(t){var e=[];for(var s in t){var r=t[s];$e(r)||x(r)||e.push({key:s,value:tu(r)})}return e}function $h(t,e){var s=eu[t.level||"info"]||Ah,r=s.text,n=s.number,i=String(Date.now())+"000000",o={};e.distinctId&&(o.posthogDistinctId=e.distinctId),e.sessionId&&(o.sessionId=e.sessionId),e.windowId&&(o["window.id"]=e.windowId),D(e.sessionStartTimestamp)||(o.sessionStartTimestamp=String(e.sessionStartTimestamp)),D(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=w({},o,t.attributes||{}),l={timeUnixNano:i,observedTimeUnixNano:i,severityNumber:n,severityText:r,body:{stringValue:t.body},attributes:Yr(a)};return t.trace_id&&(l.traceId=t.trace_id),t.span_id&&(l.spanId=t.span_id),x(t.trace_flags)||(l.flags=t.trace_flags),l}function su(t,e,s){return w({},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":s})}function ru(t,e,s,r){return{resourceLogs:[{resource:{attributes:Yr(e)},scopeLogs:[{scope:{name:s,version:r},logRecords:t}]}]}}let Rh=class{constructor(t,e,s,r,n,i,o){var a;i===void 0&&(i=()=>Promise.resolve()),this._instance=t,this.Ne=e,this.rt=s,this.ut=r,this.ht=n,this.dt=i,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 s={record:$h(e,this.ut())};this.ht((()=>this.At(s)))}}else this.rt.info("Log was rejected in beforeSend function")}}Pt(t){var e=this.Ne.beforeSend;if(!e)return t;var s=L(e)?e:[e],r=t;for(var n of s)try{var i=n(r);if(!i)return this.rt.info("Log was rejected in beforeSend function"),null;r=i}catch(o){return this.rt.error("Error in beforeSend function for log:",o),null}return r}Rt(){if(this.Tt===void 0)return!0;var t=Date.now(),e=t-this.bt;return this.Mt>e&&e>=0||(this.bt=t,this._t=0,this.wt=!1),this.Tt>this._t?(this._t++,!0):(this.wt||(this.rt.warn("captureLog dropping logs: exceeded "+this.Tt+" logs per "+this.Mt+"ms"),this.wt=!0),!1)}flush(){var t=this;return X((function*(){if(!t._instance.isDisabled)return t.ct||(t.ct=t.Ft().finally((()=>{t.ct=null}))),t.ct}))()}Ft(){var t=this;return X((function*(){var e;t.Et();var s=(e=t._instance.getPersistedProperty(ut.LogsQueue))!==null&&e!==void 0?e:[];if(s.length!==0)for(var r=s.length,n=0;s.length>0&&r>n;){var i,o;t.ft=0;var a=Math.min(s.length,t.Ct),l=s.slice(0,a),u=ru(l.map((d=>d.record)),t.Lt(),(i=t.vt)!==null&&i!==void 0?i: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),s=(o=t._instance.getPersistedProperty(ut.LogsQueue))!==null&&o!==void 0?o:[],n+=l.length,c.kind==="fatal"))throw c.error}}))()}Dt(t){var e=this;return X((function*(){var s,r=Math.max(0,t-e.ft),n=(s=e._instance.getPersistedProperty(ut.LogsQueue))!==null&&s!==void 0?s:[];e._instance.setPersistedProperty(ut.LogsQueue,n.slice(r)),yield e.dt()}))()}Lt(){return su(this.Ne,this._instance.getLibraryId(),this._instance.getLibraryVersion())}At(t){var e;if(!this._instance.optedOut){var s=(e=this._instance.getPersistedProperty(ut.LogsQueue))!==null&&e!==void 0?e:[];this.xt>s.length||(s.shift(),this.ft++,this.rt.info("Logs queue is full, dropping oldest record.")),s.push(t),this._instance.setPersistedProperty(ut.LogsQueue,s),this.kt>s.length?this.$t():this.It()}}$t(t){t===void 0&&(t=this.St),this.Nt||(this.Nt=Uo((()=>{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 X((function*(){e.Et();var s=e.flush().catch((()=>{}));t!==void 0?yield Ka(s,t):yield s}))()}flushWithTimeout(t){var e=this;return X((function*(){var s=e.flush();yield Ka(s,t,(()=>{s.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 Qn=[0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4];function Ja(t){return String(t)+"000000"}function Ya(t,e,s,r){var n="";return r&&(n=Object.keys(r).sort().map((i=>JSON.stringify(i)+":"+JSON.stringify(r[i]))).join(",")),t+"\0"+e+"\0"+(s??"")+"\0"+n}let Th=class{constructor(t,e,s){this._instance=t,this.Ne=e,this.rt=s,this.Bt=new Map,this.ct=null,this.Ht=!1,this.Ut=new Map,this.zt=new Set,this.Wt=0}count(t,e,s){e===void 0&&(e=1),this.Vt({name:t,type:"count",value:e,unit:s?.unit,attributes:s?.attributes})}gauge(t,e,s){this.Vt({name:t,type:"gauge",value:e,unit:s?.unit,attributes:s?.attributes})}histogram(t,e,s){this.Vt({name:t,type:"histogram",value:e,unit:s?.unit,attributes:s?.attributes})}flush(){var t=this,e=this.ct,s=(function(){var n=X((function*(){e&&(yield e.catch((()=>{}))),yield t.Zt()}));return function(){return n.apply(this,arguments)}})(),r=s().finally((()=>{this.ct===r&&(this.ct=null)}));return this.ct=r,r}drainWindow(){if(this.Bt.size===0)return null;var t=this.Bt;return this.Bt=new Map,this.Ht=!1,this.Ut=new Map,this.zt=new Set,this.Gt(t)}reset(){this.Wt++,this.Et(),this.Bt=new Map,this.ct=null,this.Ht=!1,this.Ut=new Map,this.zt=new Set}Vt(t){if(!this._instance.isDisabled&&!this._instance.optedOut){var e=this.Pt(t);if(e!==null)if(e.name&&typeof e.name=="string")if(typeof e.value=="number"&&Number.isFinite(e.value))if(e.type==="count"&&0>e.value)this.rt.warn("Dropping count '"+e.name+"': counters are monotonic, value must be >= 0");else{var s,r;try{s=e.attributes?w({},e.attributes):void 0,r=Ya(e.type,e.name,e.unit,s)}catch(o){return void this.rt.warn("Dropping metric '"+e.name+"': attributes could not be serialized",o)}var n=this.Bt.get(r);if(!n){if(!this.Qt())return;n={name:e.name,type:e.type,unit:e.unit,attributes:s,windowStartMs:Date.now()},this.Bt.set(r,n)}var i=this.Ut.get(e.name);i===void 0?this.Ut.set(e.name,e.type):i===e.type||this.zt.has(e.name)||(this.zt.add(e.name),this.rt.warn("Metric name '"+e.name+"' is already used as a "+i+"; recording it as a "+e.type+" too will blend both series in charts. Use a distinct name.")),this.Kt(n,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 s;switch(t.type){case"count":t.total=((s=t.total)!==null&&s!==void 0?s: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(Qn.length+1).fill(0)});var r=t.hist;r.count+=1,r.sum+=e,r.min=Math.min(r.min,e),r.max=Math.max(r.max,e),r.bucketCounts[(function(n,i){for(var o=0;i.length>o;o++)if(i[o]>=n)return o;return i.length})(e,Qn)]+=1}}Pt(t){var e=this.Ne.beforeSend;if(!e)return t;var s=L(e)?e:[e],r=t;for(var n of s)try{var i=n(r);if(!i)return this.rt.info("Metric was rejected in beforeSend function"),null;r=i}catch(o){return this.rt.error("Error in beforeSend function for metric:",o),null}return r}$t(){this.Nt||(this.Nt=Uo((()=>{this.Nt=void 0,this.flush().catch((t=>{this.rt.error("Metrics flush failed:",t)}))}),this.Ne.flushIntervalMs))}Et(){this.Nt&&(clearTimeout(this.Nt),this.Nt=void 0)}Zt(){var t=this;return X((function*(){if(t.Bt.size!==0){var e=t.Bt;t.Bt=new Map,t.Ht=!1,t.Ut=new Map,t.zt=new Set;var s=t.Wt,r=yield t._instance.Jt(t.Gt(e));if(s===t.Wt)switch(r.kind){case"ok":return;case"retry-later":return t.Yt(e),void t.$t();case"too-large":return void t.rt.warn("Metrics batch exceeded the server size limit and was dropped");case"fatal":return void t.rt.error("Failed to send metrics batch:",r.error)}}}))()}Gt(t){return e=this.Xt(t),s=(function(i,o,a){return w({},i.resourceAttributes,{"service.name":i.serviceName||"unknown_service"},i.environment&&{"deployment.environment":i.environment},i.serviceVersion&&{"service.version":i.serviceVersion},{"telemetry.sdk.name":o,"telemetry.sdk.version":a})})(this.Ne,this._instance.getLibraryId(),this._instance.getLibraryVersion()),r=this._instance.getLibraryId(),n=this._instance.getLibraryVersion(),{resourceMetrics:[{resource:{attributes:Yr(s)},scopeMetrics:[{scope:{name:r,version:n},metrics:e}]}]};var e,s,r,n}Xt(t){var e=Ja(Date.now()),s=new Map;for(var r of t.values()){var n,i=Ya(r.type,r.name,r.unit,void 0),o=s.get(i);o||(o=w({name:r.name},r.unit&&{unit:r.unit}),r.type==="count"?o.sum={aggregationTemporality:1,isMonotonic:!0,dataPoints:[]}:r.type==="gauge"?o.gauge={dataPoints:[]}:o.histogram={aggregationTemporality:1,dataPoints:[]},s.set(i,o));var a=Yr((n=r.attributes)!==null&&n!==void 0?n:{}),l=Ja(r.windowStartMs);if(r.type==="count"){var u,c={attributes:a,startTimeUnixNano:l,timeUnixNano:e,asDouble:(u=r.total)!==null&&u!==void 0?u:0};o.sum.dataPoints.push(c)}else if(r.type==="gauge"){var d,h={attributes:a,timeUnixNano:e,asDouble:(d=r.last)!==null&&d!==void 0?d:0};o.gauge.dataPoints.push(h)}else r.hist&&o.histogram.dataPoints.push({attributes:a,startTimeUnixNano:l,timeUnixNano:e,count:r.hist.count,sum:r.hist.sum,min:r.hist.min,max:r.hist.max,bucketCounts:r.hist.bucketCounts,explicitBounds:Qn})}return Array.from(s.values())}Yt(t){var e,s;for(var r of t){var n=r[0],i=r[1],o=this.Bt.get(n);if(o)switch(o.windowStartMs=Math.min(o.windowStartMs,i.windowStartMs),o.type){case"count":o.total=((e=o.total)!==null&&e!==void 0?e:0)+((s=i.total)!==null&&s!==void 0?s:0);break;case"gauge":break;case"histogram":if(i.hist)if(o.hist){o.hist.count+=i.hist.count,o.hist.sum+=i.hist.sum,o.hist.min=Math.min(o.hist.min,i.hist.min),o.hist.max=Math.max(o.hist.max,i.hist.max);for(var a=0;o.hist.bucketCounts.length>a;a++)o.hist.bucketCounts[a]+=i.hist.bucketCounts[a]}else o.hist=i.hist}else this.Qt()&&this.Bt.set(n,i)}}};var wr,Za,ei;function Nh(t){var e=globalThis._posthogChunkIds;if(e){var s=Object.keys(e);return ei&&s.length===Za||(Za=s.length,ei=s.reduce(((r,n)=>{wr||(wr={});var i=wr[n];if(i)r[i[0]]=i[1];else for(var o=t(n),a=o.length-1;a>=0;a--){var l=o[a],u=l?.filename,c=e[n];if(u&&c){r[u]=c,wr[n]=[u,c];break}}return r}),{})),ei}}class Mh{constructor(e,s,r){r===void 0&&(r=[]),this.coercers=e,this.stackParser=s,this.modifiers=r}buildFromUnknown(e,s){s===void 0&&(s={});var r=s&&s.mechanism||{handled:!0,type:"generic"},n=this.buildCoercingContext(r,s,0).apply(e),i=this.buildParsingContext(s),o=this.parseStacktrace(n,i);return{$exception_list:this.convertToExceptionList(o,r),$exception_level:"error"}}modifyFrames(e){var s=this;return X((function*(){for(var r of e)r.stacktrace&&r.stacktrace.frames&&L(r.stacktrace.frames)&&(r.stacktrace.frames=yield s.applyModifiers(r.stacktrace.frames));return e}))()}coerceFallback(e){var s;return{type:"Error",value:"Unknown error",stack:(s=e.syntheticException)==null?void 0:s.stack,synthetic:!0}}parseStacktrace(e,s){var r,n;return e.cause!=null&&(r=this.parseStacktrace(e.cause,s)),e.stack!=""&&e.stack!=null&&(n=this.applyChunkIds(this.stackParser(e.stack,e.synthetic?s.skipFirstLines:0),s.chunkIdMap)),w({},e,{cause:r,stack:n})}applyChunkIds(e,s){return e.map((r=>(r.filename&&s&&(r.chunk_id=s[r.filename]),r)))}applyCoercers(e,s){for(var r of this.coercers)if(r.match(e))return r.coerce(e,s);return this.coerceFallback(s)}applyModifiers(e){var s=this;return X((function*(){var r=e;for(var n of s.modifiers)r=yield n(r);return r}))()}convertToExceptionList(e,s){var r,n,i,o={type:e.type,value:e.value,mechanism:{type:(r=s.type)!==null&&r!==void 0?r:"generic",handled:(n=s.handled)===null||n===void 0||n,synthetic:(i=e.synthetic)!==null&&i!==void 0&&i}};e.stack&&(o.stacktrace={type:"raw",frames:e.stack});var a=[o];return e.cause!=null&&a.push(...this.convertToExceptionList(e.cause,w({},s,{handled:!0}))),a}buildParsingContext(e){var s;return{chunkIdMap:Nh(this.stackParser),skipFirstLines:(s=e.skipFirstLines)!==null&&s!==void 0?s:1}}buildCoercingContext(e,s,r){r===void 0&&(r=0);var n=(i,o)=>{if(4>=o){var a=this.buildCoercingContext(e,s,o);return this.applyCoercers(i,a)}};return w({},s,{syntheticException:r==0?s.syntheticException:void 0,mechanism:e,apply:i=>n(i,r),next:i=>n(i,r+1)})}}var gs="?";function ji(t,e,s,r,n){var i={platform:t,filename:e,function:s===""?gs:s,in_app:!0};return x(r)||(i.lineno=r),x(n)||(i.colno=n),i}var nu=(t,e)=>{var s=t.indexOf("safari-extension")!==-1,r=t.indexOf("safari-web-extension")!==-1;return s||r?[t.indexOf("@")!==-1?t.split("@")[0]:gs,s?"safari-extension:"+e:"safari-web-extension:"+e]:[t,e]},Lh=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,Oh=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,Dh=/\((\S*)(?::(\d+))(?::(\d+))\)/,Bh=(t,e)=>{var s=Lh.exec(t);if(s)return ji(e,s[1],gs,+s[2],+s[3]);var r=Oh.exec(t);if(r){if(r[2]&&r[2].indexOf("eval")===0){var n=Dh.exec(r[2]);n&&(r[2]=n[1],r[3]=n[2],r[4]=n[3])}var i=nu(r[1]||gs,r[2]);return ji(e,i[1],i[0],r[3]?+r[3]:void 0,r[4]?+r[4]:void 0)}},jh=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,Uh=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,Hh=(t,e)=>{var s=jh.exec(t);if(s){if(s[3]&&s[3].indexOf(" > eval")>-1){var r=Uh.exec(s[3]);r&&(s[1]=s[1]||"eval",s[3]=r[1],s[4]=r[2],s[5]="")}var n=s[3],i=s[1]||gs,o=nu(i,n);return ji(e,n=o[1],i=o[0],s[4]?+s[4]:void 0,s[5]?+s[5]:void 0)}},Xa=/\(error: (.*)\)/;class Wh{match(e){return this.isDOMException(e)||this.isDOMError(e)}coerce(e,s){var r=W(e.stack);return{type:this.getType(e),value:this.getValue(e),stack:r?e.stack:void 0,cause:e.cause?s.next(e.cause):void 0,synthetic:!1}}getType(e){return this.isDOMError(e)?"DOMError":"DOMException"}getValue(e){var s=e.name||(this.isDOMError(e)?"DOMError":"DOMException");return e.message?s+": "+e.message:s}isDOMException(e){return qr(e,"DOMException")}isDOMError(e){return qr(e,"DOMError")}}class zh{match(e){return(function(s){switch({}.toString.call(s)){case"[object Error]":case"[object Exception]":case"[object DOMException]":case"[object DOMError]":case"[object WebAssembly.Exception]":return!0;default:return Rc(s,Error)}})(e)}coerce(e,s){return{type:this.getType(e),value:this.getMessage(e,s),stack:this.getStack(e),cause:e.cause?s.next(e.cause):void 0,synthetic:!1}}getType(e){return e.name||e.constructor.name}getMessage(e,s){var r=e.message;return String(r.error&&typeof r.error.message=="string"?r.error.message:r)}getStack(e){return e.stacktrace||e.stack||void 0}}class qh{constructor(){}match(e){return!!qr(e,"ErrorEvent")&&(e.error!=null||this.fe(e))}coerce(e,s){var r;if(e.error!=null)return s.apply(e.error);var n=s.apply(e.message);return w({},n,{stack:(r=this.pe(e))!==null&&r!==void 0?r:n.stack,synthetic:!0})}fe(e){return W(e.message)&&e.message.length>0}pe(e){var s=e;if(W(s.filename)&&s.filename.length>0){var r,n,i=(r=s.lineno)!==null&&r!==void 0?r:0,o=(n=s.colno)!==null&&n!==void 0?n:0;return`Error + at `+s.filename+":"+i+":"+o}}}var Vh=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;class Gh{match(e){return typeof e=="string"}coerce(e,s){var r,n=this.getInfos(e),i=n[0],o=n[1];return{type:i??"Error",value:o??e,stack:(r=s.syntheticException)==null?void 0:r.stack,synthetic:!0}}getInfos(e){var s="Error",r=e,n=e.match(Vh);return n&&(s=n[1],r=n[2]),[s,r]}}var Kh=["fatal","error","warning","log","info","debug"];function iu(t,e){e===void 0&&(e=40);var s=Object.keys(t);if(s.sort(),!s.length)return"[object has no keys]";for(var r=s.length;r>0;r--){var n=s.slice(0,r).join(", ");if(e>=n.length)return r===s.length?n:n.length>e?n.slice(0,e)+"...":n}return""}class Jh{match(e){return typeof e=="object"&&e!==null}coerce(e,s){var r,n,i=this.getErrorPropertyFromObject(e);return i?s.apply(i):{type:this.getType(e),value:this.getValue(e),stack:(r=this.getStack(e))!==null&&r!==void 0?r:(n=s.syntheticException)==null?void 0:n.stack,level:this.isSeverityLevel(e.level)?e.level:"error",synthetic:!0}}getType(e){return Lo(e)?e.constructor.name:"Error"}getValue(e){if("name"in e&&typeof e.name=="string"){var s="'"+e.name+"' captured as exception";return"message"in e&&typeof e.message=="string"&&(s+=" with message: '"+e.message+"'"),s}if("message"in e&&typeof e.message=="string")return e.message;var r=this.getObjectClassName(e);return(r&&r!=="Object"?"'"+r+"'":"Object")+" captured as exception with keys: "+iu(e)}isSeverityLevel(e){return W(e)&&!Mi(e)&&Kh.indexOf(e)>=0}getStack(e){try{return W(e.stacktrace)&&e.stacktrace.length>0?e.stacktrace:W(e.stack)&&e.stack.length>0?e.stack:void 0}catch{return}}getErrorPropertyFromObject(e){for(var s in e)if({}.hasOwnProperty.call(e,s)){var r=e[s];if(Ph(r))return r}}getObjectClassName(e){try{var s=Object.getPrototypeOf(e);return s?s.constructor.name:void 0}catch{return}}}class Yh{match(e){return Lo(e)}coerce(e,s){var r,n=e.constructor.name;return{type:n,value:n+" captured as exception with keys: "+iu(e),stack:(r=s.syntheticException)==null?void 0:r.stack,synthetic:!0}}}class Zh{match(e){return $c(e)}coerce(e,s){var r;return{type:"Error",value:"Primitive value captured as exception: "+String(e),stack:(r=s.syntheticException)==null?void 0:r.stack,synthetic:!0}}}class Xh{match(e){return qr(e,"PromiseRejectionEvent")||this.isCustomEventWrappingRejection(e)}isCustomEventWrappingRejection(e){if(!Lo(e))return!1;try{var s=e.detail;return s!=null&&typeof s=="object"&&"reason"in s}catch{return!1}}coerce(e,s){var r,n=this.getUnhandledRejectionReason(e);return $c(n)?{type:"UnhandledRejection",value:"Non-Error promise rejection captured with value: "+String(n),stack:(r=s.syntheticException)==null?void 0:r.stack,synthetic:!0}:s.apply(n)}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 Zr="$message",Xr="$timestamp",Qh=new Set([Zr,Xr]),ti={enabled:!0,max_bytes:32768};function Qr(t){var e;return t?{enabled:(e=t.enabled)!==null&&e!==void 0?e:ti.enabled,max_bytes:tp(t.max_bytes,ti.max_bytes)}:w({},ti)}class ep{constructor(e){this.Ke=[],this.Je=0,this.Ne=Qr(e)}setConfig(e){this.Ne=Qr(e),this.Xe()}add(e){var s=(function(n){var i;try{i=Fc(n)}catch{return}try{var o=JSON.parse(i);if(!te(o))return;var a=o,l=a[Zr],u=a[Xr];return!W(l)||l.trim().length===0||!W(u)&&!he(u)?void 0:{step:a,json:i}}catch{return}})(e);if(s){var r=(function(n){if(typeof TextEncoder<"u")return new TextEncoder().encode(n).length;for(var i=encodeURIComponent(n),o=0,a=0;i.length>a;a++)i[a]==="%"?(o+=1,a+=2):o+=1;return o})(s.json);r>this.Ne.max_bytes||(this.Ke.push({step:s.step,bytes:r}),this.Je+=r,this.Xe())}}getAttachable(){return this.Ke.map((e=>e.step))}clear(){this.Ke=[],this.Je=0}size(){return this.Ke.length}Xe(){for(;this.Je>this.Ne.max_bytes&&this.Ke.length>0;){var e=this.Ke.shift();e&&(this.Je-=e.bytes)}}}function tp(t,e){if(!he(t)||t===1/0||t===-1/0)return e;var s=Math.floor(t);return 0>s?e:s}var ou=function(t,e){var s=(e===void 0?{}:e).debugEnabled,r={k(n){if(v&&(Y.DEBUG||v.POSTHOG_DEBUG||s)&&!x(v.console)&&v.console){for(var i=("__rrweb_original__"in v.console[n])?v.console[n].__rrweb_original__:v.console[n],o=arguments.length,a=new Array(o>1?o-1:0),l=1;o>l;l++)a[l-1]=arguments[l];i(t,...a)}},debug(){for(var n=arguments.length,i=new Array(n),o=0;n>o;o++)i[o]=arguments[o];r.k("debug",...i)},info(){for(var n=arguments.length,i=new Array(n),o=0;n>o;o++)i[o]=arguments[o];r.k("log",...i)},warn(){for(var n=arguments.length,i=new Array(n),o=0;n>o;o++)i[o]=arguments[o];r.k("warn",...i)},error(){for(var n=arguments.length,i=new Array(n),o=0;n>o;o++)i[o]=arguments[o];r.k("error",...i)},critical(){for(var n=arguments.length,i=new Array(n),o=0;n>o;o++)i[o]=arguments[o];console.error(t,...i)},uninitializedWarning(n){r.error("You must initialize PostHog before calling "+n)},createLogger:(n,i)=>ou(t+" "+n,i)};return r},k=ou("[PostHog.js]"),se=k.createLogger,sp=se("[ExternalScriptsLoader]"),si=(t,e,s)=>{if(t.config.disable_external_dependency_loading)return sp.warn(e+" was requested but loading of external scripts is disabled."),s("Loading of external scripts is disabled");var r=C?.querySelectorAll("script");if(r){for(var n,i=function(){if(r[o].src===e){var l=r[o];return l.__posthog_loading_callback_fired?{v:s()}:(l.addEventListener("load",(u=>{l.__posthog_loading_callback_fired=!0,s(void 0,u)})),l.onerror=u=>s(u),{v:void 0})}},o=0;r.length>o;o++)if(n=i())return n.v}var a=()=>{if(!C)return s("document not found");var l=C.createElement("script");if(l.type="text/javascript",l.crossOrigin="anonymous",l.src=e,l.onload=d=>{l.__posthog_loading_callback_fired=!0,s(void 0,d)},l.onerror=d=>s(d),t.config.prepare_external_dependency_script&&(l=t.config.prepare_external_dependency_script(l)),!l)return s("prepare_external_dependency_script returned null");if(t.config.external_scripts_inject_target==="head")C.head.appendChild(l);else{var u,c=C.querySelectorAll("body > script");c.length>0?(u=c[0].parentNode)==null||u.insertBefore(l,c[0]):C.body.appendChild(l)}};C!=null&&C.body?a():C?.addEventListener("DOMContentLoaded",a)};$.__PosthogExtensions__=$.__PosthogExtensions__||{},$.__PosthogExtensions__.loadExternalDependency=(t,e,s)=>{if(e!=="remote-config"){var r;if(t.config.strict_script_versioning)r=t.requestRouter.endpointFor("assets","/static/"+t.version+"/"+e+".js");else{var n="/static/"+e+".js?v="+t.version;if(e==="toolbar"){var i=3e5;n=n+"&t="+Math.floor(Date.now()/i)*i}r=t.requestRouter.endpointFor("assets",n)}si(t,r,s)}else{var o=t.requestRouter.endpointFor("assets","/array/"+t.config.token+"/config.js");si(t,o,s)}},$.__PosthogExtensions__.loadSiteApp=(t,e,s)=>{var r=t.requestRouter.endpointFor("api",e);si(t,r,s)};Y.DEBUG=!1,Y.LIB_VERSION="1.415.7",Y.LIB_NAME="web";var au="$people_distinct_id",sr="$device_id",ri="$device_model",Bs="__alias",js="__timers",Ui="$autocapture_disabled_server_side",Hi="$heatmaps_enabled_server_side",Wi="$exception_capture_enabled_server_side",zi="$error_tracking_suppression_rules",qi="$error_tracking_capture_extension_exceptions",Vi="$web_vitals_enabled_server_side",Ho="$dead_clicks_enabled_server_side",Wo="$product_tours_enabled_server_side",Gi="$web_vitals_allowed_metrics",qt="$session_recording_remote_config",lu="$replay_sample_rate",cu="$replay_override_sampling",uu="$replay_override_linked_flag",du="$replay_override_url_trigger",hu="$replay_override_event_trigger",ls="$sesid",zo="$session_is_sampled",Bt="$enabled_feature_flags",Us="$active_feature_flags",Rr="$early_access_features",Ki="$feature_flag_details",Hs="$feature_flag_payloads",Tr="$feature_flag_request_id",en="$minimal_flag_called_events",et="$override_feature_flags",jt="$override_feature_flag_payloads",ct="$stored_person_properties",Ut="$stored_group_properties",Ji="$surveys",tn="$surveys_loaded_at",Yi="$surveys_activated",Nr="$surveys_activated_session",Mr="$surveys_activated_timestamps",Ws="ph_product_tours",Wt="$flag_call_reported",zs="$flag_call_reported_session_id",Lr="$feature_flag_errors",Gs="$feature_flag_evaluated_at",He="$user_state",Zi="$client_session_props",Xi="$capture_rate_limit",Qi="$initial_campaign_params",eo="$initial_referrer_info",sn="$initial_person_info",rn="$epp",br="$posthog_cookieless",pu="$cookieless_mode",fu="$sdk_debug_extensions_init_method",gu="$sdk_debug_extensions_init_time_ms",mu="$sdk_debug_recording_script_not_loaded",qo="PostHog loadExternalDependency extension not found.",Ht="on_reject",ht="always",es="anonymous",Tt="identified",to="identified_only",nn="visibilitychange",on="beforeunload",is="$pageview",ni="$pageleave",ii="$identify",Qa="$groupidentify";function Er(t,e){L(t)&&t.forEach(e)}function Z(t,e){if(!D(t))if(L(t))t.forEach(e);else if(ph(t))t.forEach(((r,n)=>e(r,n)));else for(var s in t)Ac.call(t,s)&&e(t[s],s)}var ee=function(t){for(var e=arguments.length,s=new Array(e>1?e-1:0),r=1;e>r;r++)s[r-1]=arguments[r];for(var n of s)for(var i in n)n[i]!==void 0&&(t[i]=n[i]);return t};function Or(t){for(var e=Object.keys(t),s=e.length,r=new Array(s);s--;)r[s]=[e[s],t[e[s]]];return r}var el=function(t){try{return t()}catch{return}},rp=function(t){return function(){try{for(var e=arguments.length,s=new Array(e),r=0;e>r;r++)s[r]=arguments[r];return t.apply(this,s)}catch(n){k.critical("Implementation error. Please turn on debug mode and open a ticket on https://app.posthog.com/home#panel=support%3Asupport%3A."),k.critical(n)}}},Vo=function(t){var e={};return Z(t,(function(s,r){(W(s)&&s.length>0||he(s))&&(e[r]=s)})),e},np=["herokuapp.com","vercel.app","netlify.app"];function ip(t){var e=t?.hostname;if(!W(e))return!1;var s=e.split(".").slice(-2).join(".");for(var r of np)if(s===r)return!1;return!0}function ne(t,e,s,r){var n=r??{},i=n.capture,o=n.passive;t?.addEventListener(e,s,{capture:i!==void 0&&i,passive:o===void 0||o})}function so(t){return t.name==="ph_toolbar_internal"}var vu=t=>{if(C){try{for(var e=t+"=",s=C.cookie.split(";").filter((i=>i.length)),r=0;s.length>r;r++){for(var n=s[r];n.charAt(0)==" ";)n=n.substring(1,n.length);if(n.indexOf(e)===0)return decodeURIComponent(n.substring(e.length,n.length))}}catch{}return null}};Math.trunc||(Math.trunc=function(t){return 0>t?Math.ceil(t):Math.floor(t)}),Number.isInteger||(Number.isInteger=function(t){return he(t)&&isFinite(t)&&Math.floor(t)===t});class an{constructor(e){if(this.bytes=e,e.length!==16)throw new TypeError("not 128-bit length")}static fromFieldsV7(e,s,r,n){if(!Number.isInteger(e)||!Number.isInteger(s)||!Number.isInteger(r)||!Number.isInteger(n)||0>e||0>s||0>r||0>n||e>0xffffffffffff||s>4095||r>1073741823||n>4294967295)throw new RangeError("invalid field value");var i=new Uint8Array(16);return i[0]=e/Math.pow(2,40),i[1]=e/Math.pow(2,32),i[2]=e/Math.pow(2,24),i[3]=e/Math.pow(2,16),i[4]=e/256,i[5]=e,i[6]=112|s>>>8,i[7]=s,i[8]=128|r>>>24,i[9]=r>>>16,i[10]=r>>>8,i[11]=r,i[12]=n>>>24,i[13]=n>>>16,i[14]=n>>>8,i[15]=n,new an(i)}toString(){for(var e="",s=0;this.bytes.length>s;s++)e=e+(this.bytes[s]>>>4).toString(16)+(15&this.bytes[s]).toString(16),s!==3&&s!==5&&s!==7&&s!==9||(e+="-");if(e.length!==36)throw new Error("Invalid UUIDv7 was generated");return e}clone(){return new an(this.bytes.slice(0))}equals(e){return this.compareTo(e)===0}compareTo(e){for(var s=0;16>s;s++){var r=this.bytes[s]-e.bytes[s];if(r!==0)return Math.sign(r)}return 0}}class op{generate(){var e=this.generateOrAbort();if(!x(e))return e;this.S=0;var s=this.generateOrAbort();if(x(s))throw new Error("Could not generate UUID after timestamp reset");return s}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 an.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 ap}}var tl,_u=t=>{if(typeof UUIDV7_DENY_WEAK_RNG<"u"&&UUIDV7_DENY_WEAK_RNG)throw new Error("no cryptographically strong RNG available");for(var e=0;t.length>e;e++)t[e]=65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random());return t};v&&!x(v.crypto)&&crypto.getRandomValues&&(_u=t=>crypto.getRandomValues(t));class ap{nextUint32(){return this.R.length>this.O||(_u(this.R),this.O=0),this.R[this.O++]}constructor(){this.R=new Uint32Array(8),this.O=1/0}}var dt=()=>lp().toString(),lp=()=>(tl||(tl=new op)).generate(),Ps="",cp=/[a-z0-9][a-z0-9-]+\.[a-z]{2,}$/i,pt={N:()=>!!C,j(t){k.error("cookieStore error: "+t)},P:vu,H(t){var e;try{e=JSON.parse(pt.P(t))||{}}catch{}return e},F(t,e,s,r,n){if(!C)return!1;try{var i="",o="",a=(function(c,d){if(d){var h=(function(f,g){if(g===void 0&&(g=C),Ps)return Ps;if(!g||["localhost","127.0.0.1"].includes(f))return"";for(var m=f.split("."),_=Math.min(m.length,8),b="dmn_chk_"+dt();!Ps&&_--;){var E=m.slice(_).join("."),I=b+"=1;domain=."+E+";path=/";g.cookie=I+";max-age=3",g.cookie.includes(b)&&(g.cookie=I+";max-age=0",Ps=E)}return Ps})(c);if(!h){var p=(f=>{var g=f.match(cp);return g?g[0]:""})(c);p!==h&&k.info("Warning: cookie subdomain discovery mismatch",p,h),h=p}return h?"; domain=."+h:""}return""})(C.location.hostname,r);if(s){var l=new Date;l.setTime(l.getTime()+864e5*s),i="; expires="+l.toUTCString()}n&&(o="; secure");var u=t+"="+encodeURIComponent(JSON.stringify(e))+i+"; SameSite=Lax; path=/"+a+o;return u.length>3686.4&&k.warn("cookieStore warning: large cookie, len="+u.length),C.cookie=u,!0}catch{return!1}},q(t,e){if(C!=null&&C.cookie)try{pt.F(t,"",-1,e)}catch{return}}},oi=null,Q={N(){if(!$e(oi))return oi;var t=!0;if(x(v))t=!1;else try{var e="__mplssupport__";Q.F(e,"xyz"),Q.P(e)!=='"xyz"'&&(t=!1),Q.q(e)}catch{t=!1}return t||k.error("localStorage unsupported; falling back to cookie store"),oi=t,t},j(t){k.error("localStorage error: "+t)},P(t){try{return v?.localStorage.getItem(t)}catch(e){Q.j(e)}return null},H(t){try{return JSON.parse(Q.P(t))||{}}catch{}return null},F(t,e){try{return v?.localStorage.setItem(t,JSON.stringify(e)),!0}catch(s){Q.j(s)}return!1},q(t){try{v?.localStorage.removeItem(t)}catch(e){Q.j(e)}}},up=[sr,"distinct_id",ls,zo,rn,sn,He],Sr={},dp={N:()=>!0,j(t){k.error("memoryStorage error: "+t)},P:t=>Sr[t]||null,H:t=>Sr[t]||null,F:(t,e)=>(Sr[t]=e,!0),q(t){delete Sr[t]}},Nt=null,ce={N(){if(!$e(Nt))return Nt;if(Nt=!0,x(v))Nt=!1;else try{var t="__support__";ce.F(t,"xyz"),ce.P(t)!=='"xyz"'&&(Nt=!1),ce.q(t)}catch{Nt=!1}return Nt},j(t){k.error("sessionStorage error: ",t)},P(t){try{return v?.sessionStorage.getItem(t)}catch(e){ce.j(e)}return null},H(t){try{return JSON.parse(ce.P(t))||null}catch{}return null},F(t,e){try{return v?.sessionStorage.setItem(t,JSON.stringify(e)),!0}catch(s){ce.j(s)}return!1},q(t){try{v?.sessionStorage.removeItem(t)}catch(e){ce.j(e)}}};class hp{constructor(e){this._instance=e}get Ne(){return this._instance.config}get consent(){return this.ti()?0:this.ei}isOptedOut(){return this.Ne.cookieless_mode===ht||this.isRejected()||this.consent===-1&&this.Ne.cookieless_mode===Ht}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,s=e.token,r=e.opt_out_capturing_cookie_prefix;return e.consent_persistence_name||(r?r+s:"__ph_opt_in_out_"+s)}get ei(){var e=this.ii.P(this.ri);return Zn(e)?1:M(vh,e)?0:-1}get ii(){var e=this.Ne.opt_out_capturing_persistence_type,s=e==="localStorage"?Q:pt;if(!this.ni||this.ni!==s){this.ni=s;var r=e==="localStorage"?pt:Q;r.P(this.ri)&&(this.ni.P(this.ri)||this.optInOut(Zn(r.P(this.ri))),r.q(this.ri,this.Ne.cross_subdomain_cookie))}return this.ni}ti(){return!!this.Ne.respect_dnt&&[ke?.doNotTrack,ke?.msDoNotTrack,$.doNotTrack].some((e=>Zn(e)))}}function yu(t,e){var s,r=t==null||(s=t.config)==null?void 0:s.get_current_url;if(!Se(r))return e;try{var n=r(e);return W(n)&&n?n:e}catch(i){return k.error("Error in get_current_url, falling back to window.location.href",i),e}}var wu="__POSTHOG_TOOLBAR__",pp=1,fp=3,gp=11;function sl(t){return t instanceof Element&&(t.id===wu||!(t.closest==null||!t.closest(".toolbar-global-fade-container")))}function Ft(t){return!!t&&t.nodeType===pp}function Me(t,e){return!!t&&!!t.tagName&&t.tagName.toLowerCase()===e.toLowerCase()}function bu(t){return!!t&&t.nodeType===fp}function Eu(t){return!!t&&t.nodeType===gp&&Ft(t.host)}var Su=1e3;function Go(t){return t?Pn(t).split(/\s+/):[]}function rl(t,e){var s=(function(r){var n,i=v==null||(n=v.location)==null?void 0:n.href;return x(i)?void 0:yu(r,i)})(e);return!!(s&&t&&t.some((r=>s.match(r))))}function ln(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 Go(e)}function xu(t){return D(t)?null:Pn(t).split(/(\s+)/).filter((e=>Ks(e))).join("").replace(/[\r\n]/g," ").replace(/[ ]+/g," ").substring(0,255)}function rr(t){var e="";return no(t)&&!Fu(t)&&t.childNodes&&t.childNodes.length&&Z(t.childNodes,(function(s){var r;bu(s)&&s.textContent&&(e+=(r=xu(s.textContent))!==null&&r!==void 0?r:"")})),Pn(e)}function ai(t){var e;return x(t.target)?t.srcElement||null:(e=t.target)!=null&&e.shadowRoot?t.composedPath()[0]||null:t.target||null}var Ko=["a","button","form","input","select","textarea","label"];function ro(t,e){if(x(e))return!0;var s,r=function(i){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}})(i,o))))return{v:!0}};for(var n of t)if(s=r(n))return s.v;return!1}function ku(t){var e=t.parentNode;return!(!e||!Ft(e))&&e}var mp=[".ph-no-autocapture","[data-ph-no-autocapture]"],Iu=["next","previous","prev",">","<"],vp=[...Iu,"+","-","−","–"],nl=(t,e)=>/[a-z0-9]/i.test(e)?t.includes(e):t===e,il=[".ph-no-rageclick",".ph-no-capture"],_p=["","text","search","email","password","url","tel","number"];function ol(t,e){if(!v||Jo(t))return!1;var s,r,n,i,o;if(Ke(e)?(s=!!e&&il,r=void 0,n=!1):(s=(i=e?.css_selector_ignorelist)!==null&&i!==void 0?i:il,r=e?.content_ignorelist,n=(o=e?.ignore_text_selection)!==null&&o!==void 0&&o),s===!1||n&&(function(l){return!(!l||!Ft(l))&&(!!Me(l,"textarea")||(Me(l,"input")?M(_p,(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=Cu(t,!1).targetElementList;return!(function(l,u){if(l===!1||x(l))return!1;var c;if(l===!0)c=Iu;else{if(!L(l))return!1;if(l.length>10)return k.error("[PostHog] content_ignorelist array cannot exceed 10 items. Use css_selector_ignorelist for more complex matching."),!1;c=l.map((d=>d.toLowerCase()))}return u.some((d=>{var h=d.safeText,p=d.ariaLabel;return c.some((f=>nl(h,f)||nl(p,f)))}))})(r,a.map((l=>{var u;return{safeText:rr(l).toLowerCase(),ariaLabel:((u=l.getAttribute("aria-label"))==null?void 0:u.toLowerCase().trim())||""}})))&&!ro(a,s)}var Jo=t=>!t||Me(t,"html")||!Ft(t),Cu=(t,e)=>{if(!v||Jo(t))return{parentIsUsefulElement:!1,targetElementList:[]};for(var s=!1,r=[t],n=t;n.parentNode&&!Me(n,"body");)if(Eu(n.parentNode))r.push(n.parentNode.host),n=n.parentNode.host;else{var i=ku(n);if(!i)break;if(e||Ko.indexOf(i.tagName.toLowerCase())>-1)s=!0;else try{var o=v.getComputedStyle(i);o&&o.getPropertyValue("cursor")==="pointer"&&(s=!0)}catch{}r.push(i),n=i}return{parentIsUsefulElement:s,targetElementList:r}};function no(t){for(var e=new Set,s=0,r=t;r.parentNode&&!Me(r,"body");r=r.parentNode){if(s++>=Su||e.has(r))return!1;e.add(r);var n=ln(r);if(M(n,"ph-sensitive")||M(n,"ph-no-capture"))return!1}if(M(ln(t),"ph-include"))return!0;var i=t.type||"";if(W(i))switch(i.toLowerCase()){case"hidden":case"password":return!1}var o=t.name||t.id||"";return!W(o)||!/^cc|cardnum|ccnum|creditcard|csc|cvc|cvv|exp|pass|pwd|routing|seccode|securitycode|securitynum|socialsec|socsec|ssn/i.test(o.replace(/[^a-zA-Z0-9]/g,""))}function Fu(t){return!!(Me(t,"input")&&!["button","checkbox","submit","reset"].includes(t.type)||Me(t,"select")||Me(t,"textarea")||t.getAttribute("contenteditable")==="true")}var al=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}))$"),ll=/(^|[^0-9A-Za-z_])([0-9][0-9 -]*[0-9])(?=$|[^0-9A-Za-z_])/g,yp=[16,15,14,13],wp=new RegExp("^(\\d{3}-?\\d{2}-?\\d{4})$"),cl=new RegExp("(^|[^0-9])((?!000|666)[0-9]{3}-?(?!00)[0-9]{2}-?(?!0000)[0-9]{4})(?=$|([^0-9]))","g"),ul=/[0-9A-Za-z_]/;function bp(t){for(var e=0,s=!1,r=t.length-1;r>=0;r--){var n=t.charCodeAt(r)-48;s&&(n*=2)>9&&(n-=9),e+=n,s=!s}return e%10==0}function Ks(t,e){if(e===void 0&&(e=!0),D(t))return!1;if(W(t)){t=Pn(t);var s=e?al.test((t||"").replace(/[- ]/g,"")):(function(n){var i;for(ll.lastIndex=0;i=ll.exec(n);){var o=i[2];if(o)for(var a=o.replace(/[- ]/g,""),l=0;a.length>l;l++)for(var u of yp){var c=l+u;if(a.length>=c){var d=a.slice(l,c);if(al.test(d)&&bp(d))return!0}}}return!1})(t);if(s)return!1;var r=e?wp.test(t):(function(n){var i;for(cl.lastIndex=0;i=cl.exec(n);){var o=i[1],a=i[3];if(!(o&&a&&ul.test(o)&&ul.test(a)))return!0}return!1})(t);if(r)return!1}return!0}function dl(t){var e=rr(t);return Ks(e=(e+" "+Pu(t)).trim())?e:""}function Pu(t){var e="";return t&&t.childNodes&&t.childNodes.length&&Z(t.childNodes,(function(s){var r;if(s&&((r=s.tagName)==null?void 0:r.toLowerCase())==="span")try{var n=rr(s);e=(e+" "+n).trim(),s.childNodes&&s.childNodes.length&&(e=(e+" "+Pu(s)).trim())}catch(i){k.error("[AutoCapture]",i)}})),e}function hl(t){return t.replace(/"|\\"/g,'\\"')}function Ep(t){var e=t.attr__class;if(e)return L(e)?e:Go(e)}var xr=se("[Dead Clicks]"),Sp=()=>!0,xp=t=>{var e,s=!((e=t.instance.persistence)==null||!e.get_property(Ho)),r=t.instance.config.capture_dead_clicks;return Ke(r)?r:!!te(r)||s};class pl{get lazyLoadedDeadClicksAutocapture(){return this.si}constructor(e,s,r){this.instance=e,this.isEnabled=s,this.onCapture=r,this.startIfEnabledOrStop()}onRemoteConfig(e){if(e.ok){var s=e.config;"captureDeadClicks"in s&&(this.instance.persistence&&this.instance.persistence.register({[Ho]:s.captureDeadClicks}),this.startIfEnabledOrStop())}}startIfEnabledOrStop(){this.isEnabled(this)?this.ai((()=>{this.oi()})):this.stop()}ai(e){var s,r;(s=$.__PosthogExtensions__)!=null&&s.initDeadClicksAutocapture?e():(r=$.__PosthogExtensions__)==null||r.loadExternalDependency==null||r.loadExternalDependency(this.instance,"dead-clicks-autocapture",(n=>{n?xr.error("failed to load script",n):e()}))}oi(){var e;if(C){if(!this.si&&(e=$.__PosthogExtensions__)!=null&&e.initDeadClicksAutocapture){var s=te(this.instance.config.capture_dead_clicks)?w({},this.instance.config.capture_dead_clicks):{};s.__onCapture=this.onCapture,this.onCapture&&(s.capture_dead_swipes=!1),this.si=$.__PosthogExtensions__.initDeadClicksAutocapture(this.instance,s),this.si.start(C),xr.info("starting...")}}else xr.error("`document` not found. Cannot start.")}stop(){this.si&&(this.si.stop(),this.si=void 0,xr.info("stopping..."))}}var li=se("[SegmentIntegration]"),Au="posthog-js";function $u(t,e){var s=e===void 0?{}:e,r=s.organization,n=s.projectId,i=s.prefix,o=s.severityAllowList,a=o===void 0?["error"]:o,l=s.sendExceptionsToPostHog,u=l===void 0||l;return c=>{var d,h,p,f,g;if(a!=="*"&&!a.includes(c.level)||!t.__loaded)return c;c.tags||(c.tags={});var m=t.requestRouter.endpointFor("ui","/project/"+t.config.token+"/person/"+t.get_distinct_id());c.tags["PostHog Person URL"]=m,t.sessionRecordingStarted()&&(c.tags["PostHog Recording URL"]=t.get_session_replay_url({withTimestamp:!0}));var _,b=((d=c.exception)==null?void 0:d.values)||[],E=b.map((F=>w({},F,{stacktrace:F.stacktrace?w({},F.stacktrace,{type:"raw",frames:(F.stacktrace.frames||[]).map((P=>w({},P,{platform:"web:javascript"})))}):void 0}))),I={$exception_message:((h=b[0])==null?void 0:h.value)||c.message,$exception_type:(p=b[0])==null?void 0:p.type,$exception_level:c.level,$exception_list:E,$sentry_event_id:c.event_id,$sentry_exception:c.exception,$sentry_exception_message:((f=b[0])==null?void 0:f.value)||c.message,$sentry_exception_type:(g=b[0])==null?void 0:g.type,$sentry_tags:c.tags};return r&&n&&(I.$sentry_url=(i||"https://sentry.io/organizations/")+r+"/issues/?project="+n+"&query="+c.event_id),u&&((_=t.exceptions)==null||_.sendExceptionEvent(I)),c}}class kp{constructor(e,s,r,n,i,o){this.name=Au,this.setupOnce=function(a){a($u(e,{organization:s,projectId:r,prefix:n,severityAllowList:i,sendExceptionsToPostHog:o==null||o}))}}}class fl{constructor(e){this.li=(s,r,n)=>{n&&(n.noSessionId||n.activityTimeout||n.sessionPastMaximumLength||n.crossTabAdoption)&&(k.info("[PageViewManager] Session rotated, clearing pageview state",{sessionId:s,changeReason:n}),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,s){var r,n=this.vi(e,s);return this.ui={pathname:(r=v?.location.pathname)!==null&&r!==void 0?r:"",pageViewId:s,timestamp:e},this._instance.scrollManager.resetContext(),n}doPageLeave(e){var s;return this.vi(e,(s=this.ui)==null?void 0:s.pageViewId)}doEvent(){var e;return{$pageview_id:(e=this.ui)==null?void 0:e.pageViewId}}vi(e,s){var r=this.ui;if(!r)return{$pageview_id:s};var n={$pageview_id:s,$prev_pageview_id:r.pageViewId},i=this._instance.scrollManager.getContext();if(i&&!this._instance.config.disable_scroll_properties){var o=i.maxScrollHeight,a=i.lastScrollY,l=i.maxScrollY,u=i.maxContentHeight,c=i.lastContentY,d=i.maxContentY;if(!(x(o)||x(a)||x(l)||x(u)||x(c)||x(d))){o=Math.ceil(o),a=Math.ceil(a),l=Math.ceil(l),u=Math.ceil(u),c=Math.ceil(c),d=Math.ceil(d);var h=o>1?rt(a/o,0,1,k):1,p=o>1?rt(l/o,0,1,k):1,f=u>1?rt(c/u,0,1,k):1,g=u>1?rt(d/u,0,1,k):1;n=ee(n,{$prev_pageview_last_scroll:a,$prev_pageview_last_scroll_percentage:h,$prev_pageview_max_scroll:l,$prev_pageview_max_scroll_percentage:p,$prev_pageview_last_content:c,$prev_pageview_last_content_percentage:f,$prev_pageview_max_content:d,$prev_pageview_max_content_percentage:g})}}return r.pathname&&(n.$prev_pageview_pathname=r.pathname),r.timestamp&&(n.$prev_pageview_duration=(e.getTime()-r.timestamp.getTime())/1e3),n}}var ci=["flags","surveys"],Ip={[au]:{exposure:"hidden"},[Bs]:{exposure:"hidden"},__cmpns:{exposure:"hidden"},[js]:{exposure:"hidden"},[Ui]:{exposure:"event"},[Hi]:{exposure:"hidden"},[Wi]:{exposure:"event"},[zi]:{exposure:"hidden"},[qi]:{exposure:"event"},[Vi]:{exposure:"event"},[Ho]:{exposure:"event"},[Wo]:{exposure:"hidden"},[Gi]:{exposure:"event"},[qt]:{exposure:"hidden"},$session_recording_enabled_server_side:{exposure:"hidden"},[ls]:{exposure:"hidden"},[zo]:{exposure:"event"},[lu]:{exposure:"event",shouldSkipFromEventProperties:t=>$e(t)},$session_past_minimum_duration:{exposure:"event"},$session_recording_url_trigger_activated_session:{exposure:"event"},$session_recording_event_trigger_activated_session:{exposure:"event"},$debug_first_full_snapshot_timestamp:{exposure:"event"},$sess_rec_flush_size:{exposure:"hidden"},[Bt]:{exposure:"hidden",storageGroup:"flags"},[Us]:{exposure:"hidden",storageGroup:"flags"},[Rr]:{exposure:"hidden"},[Ki]:{exposure:"hidden",storageGroup:"flags"},[Hs]:{exposure:"hidden",storageGroup:"flags"},[Tr]:{exposure:"hidden",storageGroup:"flags",volatile:!0},[en]:{exposure:"hidden",storageGroup:"flags"},[et]:{exposure:"hidden"},[jt]:{exposure:"hidden"},[ct]:{exposure:"hidden"},[Ut]:{exposure:"hidden"},[Ji]:{exposure:"hidden",storageGroup:"surveys"},[tn]:{exposure:"hidden",storageGroup:"surveys",volatile:!0},[Yi]:{exposure:"event"},[Nr]:{exposure:"hidden"},[Mr]:{exposure:"hidden"},[Ws]:{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"},[Wt]:{exposure:"hidden"},[zs]:{exposure:"hidden"},[Lr]:{exposure:"hidden"},[Gs]:{exposure:"hidden",storageGroup:"flags",volatile:!0},[He]:{exposure:"hidden"},[Zi]:{exposure:"hidden"},[Xi]:{exposure:"hidden"},[Qi]:{exposure:"hidden"},[eo]:{exposure:"hidden"},[sn]:{exposure:"hidden"},[rn]:{exposure:"hidden"},[cu]:{exposure:"event"},[uu]:{exposure:"event"},[du]:{exposure:"event"},[hu]:{exposure:"event"},[fu]:{exposure:"event"},[gu]:{exposure:"event"},[mu]:{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"}},Cp=[["$posthog_sr_group_event_trigger_",{exposure:"hidden"}],["$posthog_sr_group_url_trigger_",{exposure:"hidden"}],["$posthog_sr_group_sampling_",{exposure:"hidden"}]],Mt=t=>{var e=Ip[t];if(e)return e;for(var s of Cp){var r=s[1];if(t.indexOf(s[0])===0)return r}},cs=(t,e)=>{try{return JSON.stringify(t,((s,r)=>typeof r=="bigint"?r.toString():r),e)}catch{return Fc(t)}},cn=t=>{var e=C?.createElement("a");return x(e)?null:(e.href=t,e)},ms=function(t,e){for(var s,r=((t.split("#")[0]||"").split(/\?(.*)/)[1]||"").replace(/^\?+/g,"").split("&"),n=0;r.length>n;n++){var i=r[n].split("=");if(i[0]===e){s=i;break}}if(!L(s)||2>s.length)return"";var o=s[1];try{o=decodeURIComponent(o)}catch{k.error("Skipping decoding for malformed query param: "+o)}return o.replace(/\+/g," ")},nr=function(t,e,s){if(!t||!e||!e.length)return t;for(var r=t.split("#"),n=r[1],i=(r[0]||"").split("?"),o=i[1],a=i[0],l=(o||"").split("&"),u=[],c=0;l.length>c;c++){var d=l[c].split("=");L(d)&&(e.includes(d[0])?u.push(d[0]+"="+s):u.push(l[c]))}var h=a;return o!=null&&(h+="?"+u.join("&")),n!=null&&(h+="#"+n),h},un=function(t,e){var s=t.match(new RegExp(e+"=([^&]*)"));return s?s[1]:null},Ru=(t,e)=>t>=e&&kc(),Tu=(t,e,s,r)=>{if(t===0){if(kc()){var n=e+1;return n===s&&r(),n}return e}return 0},kr="https?://(.*)",vs=["gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","irclid","_kx"],Fp=["utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid",...vs],ir="",Pp=["li_fat_id"];function Nu(t,e,s){if(!C)return{};var r,n=e?[...vs,...s||[]]:[],i=Mu(nr(C.URL,n,ir),t),o=(r={},Z(Pp,(function(a){var l=vu(a);r[a]=l||null})),r);return ee(o,i)}function Mu(t,e){var s=Fp.concat(e||[]),r={};return Z(s,(function(n){var i=ms(t,n);r[n]=i||null})),r}function Lu(t){var e=(function(i){return i?i.search(kr+"google.([^/?]*)")===0?"google":i.search(kr+"bing.com")===0?"bing":i.search(kr+"yahoo.com")===0?"yahoo":i.search(kr+"duckduckgo.com")===0?"duckduckgo":null:null})(t),s=e!="yahoo"?"q":"p",r={};if(!$e(e)){r.$search_engine=e;var n=C?ms(C.referrer,s):"";n.length&&(r.ph_keyword=n)}return r}function gl(){return navigator.language||navigator.userLanguage}var dn="$direct";function Ou(){return C?.referrer||dn}function Du(t,e,s){s===void 0&&(s=!1);var r=t?[...vs,...e||[]]:[],n=s?Ct(re?.href):re?.href,i=n?.substring(0,1e3);return{r:Ou().substring(0,1e3),u:i?nr(i,r,ir):void 0}}function Bu(t,e){var s;e===void 0&&(e=!1);var r=t.r,n=t.u,i=e?Ct(n):n,o={$referrer:r,$referring_domain:r==null?void 0:r==dn?dn:(s=cn(r))==null?void 0:s.host};if(i){o.$current_url=i;var a=cn(i);o.$host=a?.host,o.$pathname=a?.pathname;var l=Mu(i);ee(o,l)}if(r){var u=Lu(r);ee(o,u)}return o}function ju(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return}}function Ap(){try{return new Date().getTimezoneOffset()}catch{return}}var $p={flags:Gs,surveys:tn},Rp=["cookie","localstorage","localstorage+cookie","sessionstorage","memory"],ts="main";class ui{constructor(e,s,r){if(r===void 0&&(r=!0),this.ci={},this.fi=!1,this.pi=!1,this.Ne=e,this.gi=r,this.props={},this.mi=void 0,this.yi=(i=>{var o="";return i.token&&(o=i.token.replace(/\+/g,"PL").replace(/\//g,"SL").replace(/=/g,"EQ")),i.persistence_name?"ph_"+i.persistence_name:"ph_"+o+"_posthog"})(e),this.ii=this.bi(e),this.pi=this.wi(e),this.load(),e.debug&&k.info("Persistence loaded",e.persistence,w({},this.props)),this.update_config(e,e,s),this.save(),v){var n=()=>this.flush();ne(v,"beforeunload",n,{capture:!1}),ne(v,"pagehide",n,{capture:!1})}}ki(){var e,s=(e=this.Ne)==null?void 0:e.persistence_save_debounce_ms;return he(s)&&s>0?s:0}isDisabled(){return!!this.xi}bi(e){Rp.indexOf(e.persistence.toLowerCase())===-1&&(k.critical("Unknown persistence type "+e.persistence+"; falling back to localStorage+cookie"),e.persistence="localStorage+cookie");var s,r=(function(o,a){o===void 0&&(o=[]),a===void 0&&(a=!1);var l=[...up,...o];return w({},Q,{H(u){try{var c={};try{c=pt.H(u)||{}}catch{}var d,h=JSON.parse(Q.P(u)||"{}");if(a){var p={};for(var f in c){var g=c[f];$e(g)||g===""||(p[f]=g)}d=ee(h,p)}else d=ee(c,h);return Q.F(u,d),d}catch{}return null},F(u,c,d,h,p,f){var g=Q.F(u,c,void 0,void 0,f);try{var m={};l.forEach((_=>{c[_]&&(m[_]=c[_])})),Object.keys(m).length&&pt.F(u,m,d,h,p,f)}catch(_){Q.j(_)}return g},q(u,c){try{v?.localStorage.removeItem(u),pt.q(u,c)}catch(d){Q.j(d)}}})})(e.cookie_persisted_properties||[],e.__preview_cookie_wins_on_conflict||!1),n=!1,i=e.persistence.toLowerCase();return i==="localstorage"&&Q.N()?(s=Q,n=!0):i==="localstorage+cookie"&&r.N()?(s=r,n=!0):i==="sessionstorage"&&ce.N()?s=ce:i==="memory"?s=dp:i==="cookie"?s=pt:r.N()?(s=r,n=!0):s=pt,this.fi=n,s}Si(e){return this.yi+"__"+e}wi(e){return this.fi&&!!e.split_storage}properties(){var e={};return Z(this.props,((s,r)=>{var n=Mt(r);if(!n||n.exposure==="event"){if(n!=null&&n.shouldSkipFromEventProperties!=null&&n.shouldSkipFromEventProperties(s))return;e[r]=s}})),e}load(){if(!this.xi){var e=this.ii.H(this.yi);e&&(this.props=ee({},e)),this.pi&&this.Ci()}}Ci(){for(var e of ci){var s=Q.H(this.Si(e));if(s&&!mt(s)){var r=this.Mi(e);r.persisted=!0,this.Ti(e)||(r.fingerprint=this.Ei(s,e)),this.Ii(e,s)||ee(this.props,s)}}}Ti(e){return Object.keys(this.props).some((s=>{var r;return((r=Mt(s))==null?void 0:r.storageGroup)===e}))}Ii(e,s){var r=$p[e];if(!r)return!1;var n=s[r],i=this.props[r];return he(n)&&he(i)&&i>n}refreshKey(e){var s;if(!this.xi){var r=this.pi?(s=Mt(e))==null?void 0:s.storageGroup:void 0,n=r?Q.H(this.Si(r)):this.ii.H(this.yi);if(n&&e in n)this.Pi(e,n[e]);else{if(r){var i=this.ii.H(this.yi);if(i&&e in i)return void this.Pi(e,i[e])}this.Ri(e)}}}save(){if(!this.xi){var e=this.ki();e>0?x(this.Ai)&&(this.Ai=setTimeout((()=>{this.Ai=void 0,this.Fi()}),e)):this.Fi()}}flush(){x(this.Ai)||(clearTimeout(this.Ai),this.Ai=void 0,this.Fi())}Fi(){this.xi||(this.pi?this.Li():this.Oi(this.ii,this.yi,this.props,ts))}Li(){var e=this.Di(),s=e.main,r=e.groups;for(var n of(this.Oi(this.ii,this.yi,s,ts),ci)){var i,o=r[n];(!mt(o)||(i=this.ci[n])!=null&&i.persisted)&&this.Oi(Q,this.Si(n),o,n)}}Di(){var e={},s={flags:{},surveys:{}};return Z(this.props,((r,n)=>{var i,o=(i=Mt(n))==null?void 0:i.storageGroup;o?s[o][n]=r:e[n]=r})),{main:e,groups:s}}Ei(e,s){if(s===ts)return JSON.stringify(e)+"|"+this.$i+"|"+this.Ni+"|"+this.qi;var r={};return Z(e,((n,i)=>{var o;r[i]=(o=Mt(i))!=null&&o.volatile?"__volatile__":n})),JSON.stringify(r)}Oi(e,s,r,n){var i=this.Mi(n);if(n===ts||i.dirty||x(i.fingerprint)){var o;try{if((o=this.Ei(r,n))===i.fingerprint)return void(i.dirty=!1)}catch{o=void 0}e.F(s,r,this.$i,this.Ni,this.qi,this.Ne.debug)?(i.dirty=!1,n!==ts&&(i.persisted=!0),x(o)||(i.fingerprint=o)):this.Ne.debug&&k.warn('failed to persist storage entry "'+s+'"; will retry on next save')}}remove(e){var s=(e===void 0?{}:e).keepGroupEntries,r=s!==void 0&&s;if(x(this.Ai)||(clearTimeout(this.Ai),this.Ai=void 0),this.ii.q(this.yi,!1),this.ii.q(this.yi,!0),!r&&this.gi)for(var n of ci)Q.q(this.Si(n));r?delete this.ci[ts]:this.ci={}}clear(){this.remove(),this.props={}}register_once(e,s,r){if(te(e)){x(s)&&(s="None"),this.$i=x(r)?this.ji:r;var n=!1;if(Z(e,((i,o)=>{this.props.hasOwnProperty(o)&&this.props[o]!==s||(this.Pi(o,i),n=!0)})),n)return this.save(),!0}return!1}register(e,s){if(te(e)){this.$i=x(s)?this.ji:s;var r=!1;if(Z(e,((n,i)=>{e.hasOwnProperty(i)&&(this.props[i]!==n||te(n)||L(n))&&(this.Pi(i,n),r=!0)})),r)return this.save(),!0}return!1}unregister(e){var s=typeof e=="string"?[e]:e,r=!1;for(var n of s)n in this.props&&(this.Ri(n),r=!0);r&&this.save()}update_campaign_params(){var e=C?.URL;if(e!==this.mi){var s=Nu(this.Ne.custom_campaign_params,this.Ne.mask_personal_data_properties,this.Ne.custom_personal_data_properties);mt(Vo(s))||this.register(s),this.mi=e}}update_search_keyword(){var e;this.register((e=C?.referrer)?Lu(e):{})}update_referrer_info(){var e;this.register_once({$referrer:Ou(),$referring_domain:C!=null&&C.referrer&&((e=cn(C.referrer))==null?void 0:e.host)||dn},void 0)}set_initial_person_info(){this.props[Qi]||this.props[eo]||this.register_once({[sn]:Du(this.Ne.mask_personal_data_properties,this.Ne.custom_personal_data_properties,this.Ne.disable_capture_url_hashes)},void 0)}get_initial_props(){var e={};Z([eo,Qi],(n=>{var i=this.props[n];i&&Z(i,(function(o,a){e["$initial_"+Ni(a)]=o}))}));var s=this.props[sn];if(s){var r=(function(n,i){i===void 0&&(i=!1);var o=Bu(n,i),a={};return Z(o,(function(l,u){a["$initial_"+Ni(u)]=l})),a})(s,this.Ne.disable_capture_url_hashes);ee(e,r)}return e}safe_merge(e){return Z(this.props,(function(s,r){r in e||(e[r]=s)})),e}update_config(e,s,r){this.ji=this.$i=e.cookie_expiration,this.set_disabled(e.disable_persistence||!!r),this.set_cross_subdomain(e.cross_subdomain_cookie),this.set_secure(e.secure_cookie);var n=e.persistence!==s.persistence||!((l,u)=>{if(l.length!==u.length)return!1;var c=[...l].sort(),d=[...u].sort();return c.every(((h,p)=>h===d[p]))})(e.cookie_persisted_properties||[],s.cookie_persisted_properties||[]),i=n?this.bi(e):this.ii,o=this.wi(e);if(n||o!==this.pi){var a=this.props;this.clear(),this.ii=i,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,s){var r=this.props[js]||{};r[e]=s,this.Pi(js,r),this.save()}remove_event_timer(e){var s=this.props[js]||{},r=s[e];return x(r)||(delete s[e],this.Pi(js,s),this.save()),r}get_property(e){return this.props[e]}set_property(e,s){this.Pi(e,s),this.save()}Pi(e,s){var r;this.props[e]=s,(r=Mt(e))!=null&&r.volatile||this.Bi(e)}Ri(e){delete this.props[e],this.Bi(e)}Bi(e){var s,r=(s=Mt(e))==null?void 0:s.storageGroup;r&&(this.Mi(r).dirty=!0)}Mi(e){return this.ci[e]||(this.ci[e]={})}}function Ir(t){var e=!0;return{dispose(){if(e){e=!1;var s=t();s&&Se(s.then)&&s.then(void 0,(()=>{}))}}}}var xe={GZipJS:"gzip-js",Base64:"base64"},As={Activation:"events",Cancellation:"cancelEvents"},di={Popover:"popover",API:"api",Widget:"widget"},ft={SHOWN:"survey shown",DISMISSED:"survey dismissed",SENT:"survey sent"},hi={SURVEY_ID:"$survey_id",SURVEY_ITERATION:"$survey_iteration",SURVEY_LAST_SEEN_DATE:"$survey_last_seen_date"},io={Popover:"popover",Inline:"inline"},Tp={SHOWN:"product tour shown"},ml={TOUR_LAST_SEEN_DATE:"$product_tour_last_seen_date",TOUR_TYPE:"$product_tour_type"},vl=se("[RateLimiter]");class Np{constructor(e){this.serverLimits={},this.lastEventRateLimited=!1,this.checkForLimiting=s=>{var r=s.text;if(r&&r.length)try{(JSON.parse(r).quota_limited||[]).forEach((n=>{vl.info((n||"events")+" is quota limited."),this.serverLimits[n]=new Date().getTime()+6e4}))}catch(n){return void vl.warn('could not rate limit - continuing. Error: "'+n?.message+'"',{text:r})}},this.instance=e,this.lastEventRateLimited=this.clientRateLimitContext(!0).isRateLimited}get captureEventsPerSecond(){var e;return((e=this.instance.config.rate_limiting)==null?void 0:e.events_per_second)||10}get captureEventsBurstLimit(){var e;return Math.max(((e=this.instance.config.rate_limiting)==null?void 0:e.events_burst_limit)||10*this.captureEventsPerSecond,this.captureEventsPerSecond)}clientRateLimitContext(e){var s,r,n;e===void 0&&(e=!1);var i=this.captureEventsBurstLimit,o=this.captureEventsPerSecond,a=new Date().getTime(),l=(s=(r=this.instance.persistence)==null?void 0:r.get_property(Xi))!==null&&s!==void 0?s:{tokens:i,last:a};l.tokens+=(a-l.last)/1e3*o,l.last=a,l.tokens>i&&(l.tokens=i);var u=1>l.tokens;if(u||e||(l.tokens=Math.max(0,l.tokens-1)),u&&!e){var c=(he(l.dropped)?l.dropped:0)+1;l.dropped=c,!this.lastEventRateLimited&&this.Hi(c)&&(l.dropped=0)}return this.lastEventRateLimited=u,(n=this.instance.persistence)==null||n.set_property(Xi,l),{isRateLimited:u,remainingTokens:l.tokens}}Ui(e){var s=this.instance.config.property_denylist;return!L(s)||!s.includes(e)}zi(){var e;if(this.Ui("$current_url")&&this.Ui("$pathname")&&re!=null&&re.pathname)return""+((e=re.origin)!==null&&e!==void 0?e:"")+re.pathname}Hi(e){var s,r,n=this.captureEventsBurstLimit,i=this.captureEventsPerSecond,o=this.zi(),a=this.Ui("$session_id")?(s=(r=this.instance).get_session_id)==null?void 0:s.call(r):void 0,l=[e+" event(s) dropped since the last warning",o?"triggered on "+o:void 0,a?"session "+a:void 0].filter(Boolean).join(", ");return!!this.instance.capture("$$client_ingestion_warning",{$$client_ingestion_warning_message:"posthog-js client rate limited: "+l+". Config is set to "+i+" events per second and "+n+" events burst limit."},{skip_client_rate_limiting:!0})}isServerRateLimited(e){var s=this.serverLimits[e||"events"]||!1;return s!==!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 xt.info("Using preloaded remote config",this.remoteConfig),this.Zi(this.remoteConfig),void this.Gi();if(this._instance.Qi())return void xt.warn("Remote config is disabled. Falling back to local config.");this.Wi((e=>{if(!e)return xt.info("No config found after loading remote JS config. Falling back to JSON."),void this.Vi((s=>{this.Zi(s.json,s),this.Gi()}));this.Zi(e),this.Gi()}))}catch(e){xt.error("Error loading remote config",e),this.Zi()}}stop(){this.Ki&&(clearInterval(this.Ki),this.Ki=void 0)}refresh(){!this._instance.Qi()&&C&&C.visibilityState!=="hidden"&&this._instance.reloadFeatureFlags()}Gi(){var e;if(!this.Ki){var s=(e=this._instance.config.remote_config_refresh_interval_ms)!==null&&e!==void 0?e:3e5;s!==0&&(this.Ki=setInterval((()=>{this.refresh()}),s))}}Zi(e,s){!e&&s&&(s.statusCode===0?s.error||xt.warn("Failed to fetch remote config from PostHog."):xt.error("Failed to fetch remote config from PostHog."));try{this._instance.Zi(e?{ok:!0,config:e}:{ok:!1})}catch(n){xt.error("Error applying remote config",n)}if(e?.hasFeatureFlags!==!1&&!this._instance.config.advanced_disable_feature_flags_on_first_load)try{var r;(r=this._instance.featureFlags)==null||r.ensureFlagsLoaded()}catch(n){xt.error("Error loading feature flags",n)}}}var qe=Uint8Array,Ae=Uint16Array,_s=Uint32Array,Yo=new qe([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),Zo=new qe([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),_l=new qe([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Hu=function(t,e){for(var s=new Ae(31),r=0;31>r;++r)s[r]=e+=1<r;++r)for(var i=s[r];s[r+1]>i;++i)n[i]=i-s[r]<<5|r;return[s,n]},Wu=Hu(Yo,2),oo=Wu[1];Wu[0][28]=258,oo[258]=28;for(var yl=Hu(Zo,0)[1],zu=new Ae(32768),ie=0;32768>ie;++ie){var ss=(43690&ie)>>>1|(21845&ie)<<1;zu[ie]=((65280&(ss=(61680&(ss=(52428&ss)>>>2|(13107&ss)<<2))>>>4|(3855&ss)<<4))>>>8|(255&ss)<<8)>>>1}var Js=function(t,e,s){for(var r=t.length,n=0,i=new Ae(e);r>n;++n)++i[t[n]-1];var o,a=new Ae(e);for(n=0;e>n;++n)a[n]=a[n-1]+i[n-1]<<1;for(o=new Ae(r),n=0;r>n;++n)o[n]=zu[a[t[n]-1]++]>>>15-t[n];return o},Kt=new qe(288);for(ie=0;144>ie;++ie)Kt[ie]=8;for(ie=144;256>ie;++ie)Kt[ie]=9;for(ie=256;280>ie;++ie)Kt[ie]=7;for(ie=280;288>ie;++ie)Kt[ie]=8;var hn=new qe(32);for(ie=0;32>ie;++ie)hn[ie]=5;var Mp=Js(Kt,9),Lp=Js(hn,5),qu=function(t){return(t/8>>0)+(7&t&&1)},Vu=function(t,e,s){(s==null||s>t.length)&&(s=t.length);var r=new(t instanceof Ae?Ae:t instanceof _s?_s:qe)(s-e);return r.set(t.subarray(e,s)),r},ot=function(t,e,s){var r=e/8>>0;t[r]|=s<<=7&e,t[r+1]|=s>>>8},$s=function(t,e,s){var r=e/8>>0;t[r]|=s<<=7&e,t[r+1]|=s>>>8,t[r+2]|=s>>>16},pi=function(t,e){for(var s=[],r=0;t.length>r;++r)t[r]&&s.push({s:r,f:t[r]});var n=s.length,i=s.slice();if(!n)return[new qe(0),0];if(n==1){var o=new qe(s[0].s+1);return o[s[0].s]=1,[o,1]}s.sort((function(F,P){return F.f-P.f})),s.push({s:-1,f:25001});var a=s[0],l=s[1],u=0,c=1,d=2;for(s[0]={s:-1,f:a.f+l.f,l:a,r:l};c!=n-1;)a=s[s[d].f>s[u].f?u++:d++],l=s[u!=c&&s[d].f>s[u].f?u++:d++],s[c++]={s:-1,f:a.f+l.f,l:a,r:l};var h=i[0].s;for(r=1;n>r;++r)i[r].s>h&&(h=i[r].s);var p=new Ae(h+1),f=ao(s[c-1],p,0);if(f>e){r=0;var g=0,m=f-e,_=1<r;++r){var b=i[r].s;if(e>=p[b])break;g+=_-(1<>>=m;g>0;){var E=i[r].s;e>p[E]?g-=1<=0&&g;--r){var I=i[r].s;p[I]==e&&(--p[I],++g)}f=e}return[new qe(p),f]},ao=function(t,e,s){return t.s==-1?Math.max(ao(t.l,e,s+1),ao(t.r,e,s+1)):e[t.s]=s},wl=function(t){for(var e=t.length;e&&!t[--e];);for(var s=new Ae(++e),r=0,n=t[0],i=1,o=function(l){s[r++]=l},a=1;e>=a;++a)if(t[a]==n&&a!=e)++i;else{if(!n&&i>2){for(;i>138;i-=138)o(32754);i>2&&(o(i>10?i-11<<5|28690:i-3<<5|12305),i=0)}else if(i>3){for(o(n),--i;i>6;i-=6)o(8304);i>2&&(o(i-3<<5|8208),i=0)}for(;i--;)o(n);i=1,n=t[a]}return[s.subarray(0,r),e]},Rs=function(t,e){for(var s=0,r=0;e.length>r;++r)s+=t[r]*e[r];return s},lo=function(t,e,s){var r=s.length,n=qu(e+2);t[n]=255&r,t[n+1]=r>>>8,t[n+2]=255^t[n],t[n+3]=255^t[n+1];for(var i=0;r>i;++i)t[n+i+4]=s[i];return 8*(n+4+r)},bl=function(t,e,s,r,n,i,o,a,l,u,c){ot(e,c++,s),++n[256];for(var d=pi(n,15),h=d[0],p=d[1],f=pi(i,15),g=f[0],m=f[1],_=wl(h),b=_[0],E=_[1],I=wl(g),F=I[0],P=I[1],B=new Ae(19),S=0;b.length>S;++S)B[31&b[S]]++;for(S=0;F.length>S;++S)B[31&F[S]]++;for(var A=pi(B,7),R=A[0],N=A[1],T=19;T>4&&!R[_l[T-1]];--T);var O,J,z,H,oe=u+5<<3,pe=Rs(n,Kt)+Rs(i,hn)+o,Ie=Rs(n,h)+Rs(i,g)+o+14+3*T+Rs(B,R)+(2*B[16]+3*B[17]+7*B[18]);if(pe>=oe&&Ie>=oe)return lo(e,c,t.subarray(l,l+u));if(ot(e,c,1+(pe>Ie)),c+=2,pe>Ie){O=Js(h,p),J=h,z=Js(g,m),H=g;var _e=Js(R,N);for(ot(e,c,E-257),ot(e,c+5,P-1),ot(e,c+10,T-4),c+=14,S=0;T>S;++S)ot(e,c+3*S,R[_l[S]]);c+=3*T;for(var Ce=[b,F],Re=0;2>Re;++Re){var ae=Ce[Re];for(S=0;ae.length>S;++S)ot(e,c,_e[me=31&ae[S]]),c+=R[me],me>15&&(ot(e,c,ae[S]>>>5&127),c+=ae[S]>>>12)}}else O=Mp,J=Kt,z=Lp,H=hn;for(S=0;a>S;++S)if(r[S]>255){var me;$s(e,c,O[257+(me=r[S]>>>18&31)]),c+=J[me+257],me>7&&(ot(e,c,r[S]>>>23&31),c+=Yo[me]);var ge=31&r[S];$s(e,c,z[ge]),c+=H[ge],ge>3&&($s(e,c,r[S]>>>5&8191),c+=Zo[ge])}else $s(e,c,O[r[S]]),c+=J[r[S]];return $s(e,c,O[256]),c+J[256]},Op=new _s([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),Dp=(function(){for(var t=new _s(256),e=0;256>e;++e){for(var s=e,r=9;--r;)s=(1&s&&3988292384)^s>>>1;t[e]=s}return t})(),fi=function(t,e,s){for(;s;++e)t[e]=s,s>>>=8};function Bp(t,e){e===void 0&&(e={});var s=(function(){var d=4294967295;return{p(h){for(var p=d,f=0;h.length>f;++f)p=Dp[255&p^h[f]]^p>>>8;d=p},d(){return 4294967295^d}}})(),r=t.length;s.p(t);var n,i,o,a,l,u=(a=10+((n=e).filename&&n.filename.length+1||0),l=8,(function(d,h,p,f,g,m){var _=d.length,b=new qe(f+_+5*(1+Math.floor(_/7e3))+g),E=b.subarray(f,b.length-g),I=0;if(!h||8>_)for(var F=0;_>=F;F+=65535){var P=F+65535;_>P?I=lo(E,I,d.subarray(F,P)):(E[F]=!0,I=lo(E,I,d.subarray(F,_)))}else{for(var B=Op[h-1],S=B>>>13,A=8191&B,R=(1<F;++F){var me=z(F),ge=32767&F,Ye=T[me];if(N[ge]=Ye,T[me]=ge,F>=Re){var Rt=_-F;if((Ie>7e3||Ce>24576)&&Rt>423){I=bl(d,E,0,H,oe,pe,_e,Ce,ae,F-ae,I),Ce=Ie=_e=0,ae=F;for(var de=0;286>de;++de)oe[de]=0;for(de=0;30>de;++de)pe[de]=0}var Ve=2,St=0,ks=A,Be=ge-Ye&32767;if(Rt>2&&me==z(F-Be))for(var Fe=Math.min(S,Rt)-1,mr=Math.min(32767,F),vr=Math.min(258,Rt);mr>=Be&&--ks&&ge!=Ye;){if(d[F+Ve]==d[F+Ve-Be]){for(var je=0;vr>je&&d[F+je]==d[F+je-Be];++je);if(je>Ve){if(Ve=je,St=Be,je>Fe)break;var _r=Math.min(Be,je-2),Xt=0;for(de=0;_r>de;++de){var Qt=F-Be+de+32768&32767,Is=Qt-N[Qt]+32768&32767;Is>Xt&&(Xt=Is,Ye=Qt)}}}Be+=(ge=Ye)-(Ye=N[ge])+32768&32767}if(St){H[Ce++]=268435456|oo[Ve]<<18|yl[St];var Ta=31&oo[Ve],Na=31&yl[St];_e+=Yo[Ta]+Zo[Na],++oe[257+Ta],++pe[Na],Re=F+Ve,++Ie}else H[Ce++]=d[F],++oe[d[F]]}}I=bl(d,E,!0,H,oe,pe,_e,Ce,ae,F-ae,I)}return Vu(b,0,f+qu(I)+g)})(i=t,(o=e).level==null?6:o.level,o.mem==null?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(i.length)))):12+o.mem,a,l)),c=u.length;return(function(d,h){var p=h.filename;if(d[0]=31,d[1]=139,d[2]=8,d[8]=2>h.level?4:h.level==9?2:0,d[9]=3,h.mtime!=0&&fi(d,4,Math.floor(new Date(h.mtime||Date.now())/1e3)),p){d[3]=8;for(var f=0;p.length>=f;++f)d[f+10]=p.charCodeAt(f)}})(u,e),fi(u,c-8,s.d()),fi(u,c-4,r),u}var jp=!!$i||!!Mo,Gu="text/plain",Dr=!1,Ku=(t,e)=>{var s=t.split("#"),r=s[1],n=s[0].split("?"),i=n[0],o=n[1];if(!o)return t;var a=o.split("&").filter((l=>l.split("=")[0]!==e)).join("&");return i+(a?"?"+a:"")+(r?"#"+r:"")},$n=function(t,e,s){var r;s===void 0&&(s=!0);var n=t.split("?"),i=n[0],o=n[1],a=w({},e),l=(r=o?.split("&").map((c=>{var d,h=c.split("="),p=h[0],f=s&&(d=a[p])!==null&&d!==void 0?d:h[1];return delete a[p],p+"="+f})))!==null&&r!==void 0?r:[],u=(function(c,d){var h,p;d===void 0&&(d="&");var f=[];return Z(c,(function(g,m){x(g)||x(m)||m==="undefined"||(h=encodeURIComponent((_=>_ instanceof File)(g)?g.name:g.toString()),p=encodeURIComponent(m),f[f.length]=p+"="+h)})),f.join(d)})(a);return u&&l.push(u),l.length>0?i+"?"+l.join("&"):i},gi=t=>{if(t.Ji)return t.Ji;var e=t.data,s=t.compression;if(e){if(s===xe.GZipJS){var r=Bp((function(a,l){var u=a.length;if(typeof TextEncoder<"u")return new TextEncoder().encode(a);for(var c=new qe(a.length+(a.length>>>1)),d=0,h=function(m){c[d++]=m},p=0;u>p;++p){if(d+5>c.length){var f=new qe(d+8+(u-p<<1));f.set(c),c=f}var g=a.charCodeAt(p);128>g?h(g):2048>g?(h(192|g>>>6),h(128|63&g)):g>55295&&57344>g?(h(240|(g=65536+(1047552&g)|1023&a.charCodeAt(++p))>>>18),h(128|g>>>12&63),h(128|g>>>6&63),h(128|63&g)):(h(224|g>>>12),h(128|g>>>6&63),h(128|63&g))}return Vu(c,0,d)})(cs(e)),{mtime:0});return{contentType:Gu,body:r.buffer.slice(r.byteOffset,r.byteOffset+r.byteLength),estimatedSize:r.byteLength}}if(s===xe.Base64){var n=(function(a){return a&&btoa(encodeURIComponent(a).replace(/%([0-9A-F]{2})/g,((l,u)=>String.fromCharCode(parseInt(u,16)))))})(cs(e)),i=(a=>"data="+encodeURIComponent(typeof a=="string"?a:cs(a)))(n);return{contentType:"application/x-www-form-urlencoded",body:i,estimatedSize:new Blob([i]).size}}var o=cs(e);return{contentType:"application/json",body:o,estimatedSize:new Blob([o]).size}}},Ju=t=>{var e,s,r=()=>t.transport==="sendBeacon"?{url:$n(t.url,{compression:xe.Base64}),encodedBody:gi(w({},t,{compression:xe.Base64,Ji:void 0}))}:{url:Ku(t.url,"compression"),encodedBody:gi(w({},t,{compression:void 0,Ji:void 0}))};try{e=gi(t)}catch(n){if(Ua(t.compression,ms(t.url,"compression")))return k.error("Failed to gzip request body, sending uncompressed payload",n),r();throw n}return e&&Ua(t.compression,ms(t.url,"compression"))&&!((s=e.body)instanceof ArrayBuffer?Ri(new Uint8Array(s)):ArrayBuffer.isView(s)&&Ri(new Uint8Array(s.buffer,s.byteOffset,s.byteLength)))?(Dr=!0,r()):{url:t.url,encodedBody:e}},Yu=t=>{try{return Ju(t)}catch(e){return k.error(e),void(t.callback==null||t.callback({statusCode:0,error:e}))}},Up=(function(){var t=X((function*(e){var s=cs(e.data),r=yield(function(i,o,a){return Ti.apply(this,arguments)})(s,Y.DEBUG,{rethrow:!0});if(!r)return e;var n=yield r.arrayBuffer();return w({},e,{Ji:{contentType:Gu,body:n,estimatedSize:n.byteLength}})}));return function(e){return t.apply(this,arguments)}})(),Hp=/Failed to fetch|NetworkError|Load failed/i,Zu=t=>t?.name==="TypeError"&&Hp.test(t?.message||""),Xu=t=>{var e=Yu(t);if(e){var s=e.url,r=e.encodedBody,n=r??{},i=n.contentType,o=n.body,a=n.estimatedSize,l=new Headers;Z(t.headers,(function(f,g){l.append(g,f)})),i&&l.append("Content-Type",i);var u=null,c=!1;if(Ma){var d=new Ma;u={signal:d.signal,timeout:setTimeout((()=>{var f,g;c=!0,d.abort((f=t.timeout,(g=new Error("PostHog request timed out"+(f?" after "+f+"ms":""))).name="AbortError",g))}),t.timeout)}}var h=f=>{c&&f?.name==="AbortError"||Zu(f)?k.warn(f):k.error(f),t.callback==null||t.callback({statusCode:0,error:f})};try{var p;Mo(s,w({method:t?.method||"GET",headers:l,keepalive:t.method==="POST"&&!t.Yi&&52428.8>(a||0),body:o,signal:(p=u)==null?void 0:p.signal},t.fetchOptions)).then((f=>f.text().then((g=>{var m={statusCode:f.status,text:g};if(f.status===200)try{m.json=JSON.parse(g)}catch(_){k.error(_)}t.callback==null||t.callback(m)})))).catch(h).finally((()=>u?clearTimeout(u.timeout):null))}catch(f){u&&clearTimeout(u.timeout),h(f)}}},co=t=>{try{var e,s=Ju(t),r=s.url,n=s.encodedBody,i=n??{},o=i.body,a=i.estimatedSize;if(!o)return;var l=o instanceof Blob?o:new Blob([o],{type:i.contentType});if(ke.sendBeacon(r,l))return;var u=L(t.data)?t.data:(e=t.data)==null?void 0:e.batch;if(L(u)&&u.length>1&&(a??0)>16384){var c=Math.ceil(u.length/2),d=h=>L(t.data)?h:w({},t.data,{batch:h});return co(w({},t,{data:d(u.slice(0,c))})),void co(w({},t,{data:d(u.slice(c))}))}k.warn("Beacon of ~"+(a??0)+" bytes was rejected by the browser, falling back to fetch"),Xu(w({},t,{Yi:!0}))}catch(h){k.warn("Beacon send failed",h)}},El=(t,e,s,r)=>{var n=r==="query"?e==="POST"?"sent_at":"_":void 0;return $n(s===xe.GZipJS?Ku(t,"compression"):t,w({},n?{[n]:Date.now().toString()}:{},s===xe.GZipJS?{}:{compression:s}))},Br=[];Mo&&Br.push({transport:"fetch",method:Xu}),$i&&Br.push({transport:"XHR",method(t){var e=Yu(t);if(e){var s=new $i,r=e.encodedBody;s.open(t.method||"GET",e.url,!0);var n=r??{},i=n.contentType,o=n.body;Z(t.headers,(function(a,l){s.setRequestHeader(l,a)})),i&&s.setRequestHeader("Content-Type",i),t.timeout&&(s.timeout=t.timeout),s.onreadystatechange=()=>{if(s.readyState===4){var a={statusCode:s.status,text:s.responseText};if(s.status===200)try{a.json=JSON.parse(s.responseText)}catch{}t.callback==null||t.callback(a)}},s.send(o)}}}),ke!=null&&ke.sendBeacon&&Br.push({transport:"sendBeacon",method:co});var uo=3e3;class Wp{constructor(e,s){this.Xi=!0,this.tr=[],this.er=rt(s?.flush_interval_ms||uo,250,5e3,k.createLogger("flush interval"),uo),this.ir=e}enqueue(e){this.tr.push(e),this.rr||this.nr()}unload(){this.sr();var e=this.tr.length>0?this.ar():{},s=Object.values(e);[...s.filter((r=>r.url.indexOf("/e")===0)),...s.filter((r=>r.url.indexOf("/e")!==0))].map((r=>{this.lr(w({},r,{transport:"sendBeacon"}))}))}enable(){this.Xi=!1,this.nr()}nr(){var e=this;this.Xi||(this.rr=setTimeout((()=>{if(this.sr(),this.tr.length>0){var s=this.ar(),r=function(){var i=s[n],o=new Date().getTime();i.data&&L(i.data)&&Z(i.data,(a=>{a.offset=Math.abs(a.timestamp-o),delete a.timestamp})),e.lr(i)};for(var n in s)r()}}),this.er))}lr(e){try{this.ir(e)}catch(s){k.error(s)}}sr(){clearTimeout(this.rr),this.rr=void 0}ar(){var e={};return Z(this.tr,(s=>{var r,n=s,i=(n?n.batchKey:null)||n.url;x(e[i])&&(e[i]=w({},n,{data:[]})),(r=e[i].data)==null||r.push(n.data)})),this.tr=[],e}}var zp=["retriesPerformedSoFar"];class qp{constructor(e){this.ur=!1,this.hr=3e3,this.tr=[],this._instance=e,this.tr=[],this.dr=!0,!x(v)&&"onLine"in v.navigator&&(this.dr=v.navigator.onLine,this.vr=()=>{this.dr=!0,this.cr()},this.pr=()=>{this.dr=!1},ne(v,"online",this.vr),ne(v,"offline",this.pr))}get length(){return this.tr.length}retriableRequest(e){var s=e.retriesPerformedSoFar,r=Ic(e,zp);lt(s)&&(r.url=$n(r.url,{retry_count:s})),this._instance._send_request(w({},r,{callback:n=>{if(n.statusCode!==200&&(400>n.statusCode||n.statusCode>=500)){if((n.statusCode===0?3:10)>(s??0))return void this.At(w({retriesPerformedSoFar:s},r));n.statusCode===0&&k.warn("Request failed before receiving an HTTP response; this can happen due to network issues, CORS, browser blocking, or ad blockers. Stopped retrying after "+(s??0)+" retries.")}r.callback==null||r.callback(n)}}))}At(e){var s=e.retriesPerformedSoFar||0;e.retriesPerformedSoFar=s+1;var r=(function(o){var a=3e3*Math.pow(2,o),l=a/2,u=Math.min(18e5,a),c=Math.random()-.5;return Math.ceil(u+c*(u-l))})(s),n=Date.now()+r;this.tr.push({retryAt:n,requestOptions:e});var i="Enqueued failed request for retry in "+r;navigator.onLine||(i+=" (Browser is offline)"),k.warn(i),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(),s=[],r=this.tr.filter((i=>e>i.retryAt||(s.push(i),!1)));if(this.tr=s,r.length>0)for(var n of r)this.retriableRequest(n.requestOptions)}unload(){for(var e of(this.mr&&(clearTimeout(this.mr),this.mr=void 0),this.ur=!1,x(v)||(this.vr&&(v.removeEventListener("online",this.vr),this.vr=void 0),this.pr&&(v.removeEventListener("offline",this.pr),this.pr=void 0)),this.tr)){var s=e.requestOptions;try{this._instance._send_request(w({},s,{transport:"sendBeacon"}))}catch(r){k.error(r)}}this.tr=[]}}class Vp{constructor(e){this.yr=()=>{var s,r,n,i;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,(s=this.br.maxScrollY)!==null&&s!==void 0?s:0),this.br.maxScrollHeight=Math.max(l,(r=this.br.maxScrollHeight)!==null&&r!==void 0?r:0),this.br.lastContentY=u,this.br.maxContentY=Math.max(u,(n=this.br.maxContentY)!==null&&n!==void 0?n:0),this.br.maxContentHeight=Math.max(c,(i=this.br.maxContentHeight)!==null&&i!==void 0?i: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(){ne(v,"scroll",this.yr,{capture:!0}),ne(v,"scrollend",this.yr,{capture:!0}),ne(v,"resize",this.yr)}scrollElement(){if(!this._r)return v?.document.documentElement;var e=L(this._r)?this._r:[this._r];for(var s of e){var r=v?.document.querySelector(s);if(r)return r}}wr(e){var s=e==="y"?"scrollTop":"scrollLeft";if(this._r){var r=this.scrollElement();return r&&r[s]||0}return v?e==="y"?v.scrollY||v.pageYOffset||v.document.documentElement.scrollTop||0:v.scrollX||v.pageXOffset||v.document.documentElement.scrollLeft||0:0}scrollY(){return this.wr("y")}scrollX(){return this.wr("x")}}var Gp=t=>Du(t?.config.mask_personal_data_properties,t?.config.custom_personal_data_properties,t?.config.disable_capture_url_hashes);class Sl{constructor(e,s,r,n){this.kr=i=>{var o=this.Sr();if(!o||o.sessionId!==i){var a={sessionId:i,props:this.Cr(this._instance)};this.Mr.register({[Zi]:a})}},this._instance=e,this.Tr=s,this.Mr=r,this.Cr=n||Gp,this.Tr.onSessionId(this.kr)}Sr(){return this.Mr.props[Zi]}getSetOnceProps(){var e,s=(e=this.Sr())==null?void 0:e.props;return s?"r"in s?Bu(s,this._instance.config.disable_capture_url_hashes):{$referring_domain:s.referringDomain,$pathname:s.initialPathName,utm_source:s.utm_source,utm_campaign:s.utm_campaign,utm_medium:s.utm_medium,utm_content:s.utm_content,utm_term:s.utm_term}:{}}getSessionProps(){var e={};return Z(Vo(this.getSetOnceProps()),((s,r)=>{r==="$current_url"&&(r="url"),e["$session_entry_"+Ni(r)]=s})),e}}class Xo{on(e,s){return this.Er[e]||(this.Er[e]=[]),this.Er[e].push(s),()=>{this.Er[e]=this.Er[e].filter((r=>r!==s))}}emit(e,s){for(var r of this.Er[e]||[])r(s);for(var n of this.Er["*"]||[])n(e,s)}constructor(){this.Er={}}}var Ts=se("[SessionId]");class xl{on(e,s){return this.Ir.on(e,s)}constructor(e,s,r){var n;if(this.Pr=null,this.Rr=[],this.Ar=void 0,this.Fr=!1,this.Ir=new Xo,this.Lr=(u,c)=>!(!lt(u)||!lt(c))&&Math.abs(u-c)>this.sessionTimeoutMs,!e.persistence)throw new Error("SessionIdManager requires a PostHogPersistence instance");if(e.config.cookieless_mode===ht)throw new Error('SessionIdManager cannot be used with cookieless_mode="always"');this.Ne=e.config,this.Mr=e.persistence,this.Or=void 0,this.Dr=void 0,this._sessionStartTimestamp=null,this._sessionActivityTimestamp=null,this.$r=s||dt,this.Nr=r||dt;var i=this.Ne.persistence_name||this.Ne.token;if(this._sessionTimeoutMs=1e3*rt(this.Ne.session_idle_timeout_seconds||1800,60,36e3,Ts.createLogger("session_idle_timeout_seconds"),1800),e.register({$configured_session_timeout_ms:this._sessionTimeoutMs}),this.qr(),this.jr="ph_"+i+"_window_id",this.Br="ph_"+i+"_primary_window_exists",this.Hr()){var o=ce.H(this.jr),a=ce.H(this.Br);o&&!a?this.Or=o:ce.q(this.jr),ce.F(this.Br,!0)}if((n=this.Ne.bootstrap)!=null&&n.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){Ts.error("Invalid sessionID in bootstrap",u)}this.zr()}get sessionTimeoutMs(){return this._sessionTimeoutMs}onSessionId(e){return x(this.Rr)&&(this.Rr=[]),this.Rr.push(e),this.Dr&&e(this.Dr,this.Or),()=>{this.Rr=this.Rr.filter((s=>s!==e))}}Hr(){return this.Ne.persistence!=="memory"&&!this.Mr.xi&&ce.N()}Wr(e){e!==this.Or&&(this.Or=e,this.Hr()&&ce.F(this.jr,e))}Vr(){return this.Or?this.Or:this.Hr()?ce.H(this.jr):null}Zr(e){var s=this.Pr;return!$e(s)&&!$e(e)&&5e3>Math.abs(e-s)}Ur(e,s,r){var n=s!==this._sessionActivityTimestamp,i=!(e!==this.Dr||r!==this._sessionStartTimestamp);this._sessionStartTimestamp=r,this._sessionActivityTimestamp=s,this.Dr=e,i&&!n||i&&this.Zr(s)||(this.Pr=s,this.Mr.register({[ls]:[s,e,r]}))}Gr(){var e,s=(e=this.Ne)==null?void 0:e.persistence_save_debounce_ms;return lt(s)&&s>0}Qr(){this.Gr()?this.Mr.refreshKey(ls):(this.Mr.flush(),this.Mr.load())}Kr(){var e;if(!$e(this._sessionActivityTimestamp)&&this._sessionActivityTimestamp!==this.Pr){this.Qr();var s=this.Jr();s[1]===this.Dr&&s[2]===this._sessionStartTimestamp&&(this.Pr=this._sessionActivityTimestamp,this.Mr.register({[ls]:[this._sessionActivityTimestamp,(e=this.Dr)!==null&&e!==void 0?e:null,this._sessionStartTimestamp]}),this.Mr.flush())}}Yr(){var e=this.Jr()[0],s=lt(e)?e:0,r=lt(this._sessionActivityTimestamp)?this._sessionActivityTimestamp:0;return Math.max(s,r)}Xr(e){return this.Qr(),this.Lr(e,this.Yr())}Jr(){var e=this.Mr.props[ls];return L(e)&&e.length===2&&e.push(e[0]),e||[0,null,0]}resetSessionId(){this.Pr=null,clearTimeout(this.tn),this.tn=void 0,this.Ur(null,null,null)}destroy(){this.Fr=!0,this.Kr(),clearTimeout(this.tn),this.tn=void 0,this.Ar&&v&&(v.removeEventListener(on,this.Ar,{capture:!1}),this.Ar=void 0),this.Rr=[]}zr(){this.Ar=()=>{this.Kr(),this.Hr()&&ce.q(this.Br)},ne(v,on,this.Ar,{capture:!1})}checkAndGetSessionAndWindowId(e,s){if(e===void 0&&(e=!1),s===void 0&&(s=null),this.Ne.cookieless_mode===ht)throw new Error('checkAndGetSessionAndWindowId should not be called with cookieless_mode="always"');var r=s||new Date().getTime(),n=this.Jr(),i=n[1],o=n[2],a=this.Yr(),l=this.Vr(),u=lt(o)&&Math.abs(r-o)>864e5,c=!1,d=!1,h=!i,p=i,f=!h&&!e&&this.Lr(r,a);if(f){(f=this.Xr(r))||Ts.info("cross-tab refresh kept the session alive",{sessionId:i});var g=this.Jr();i=g[1],o=g[2]}h||f||u?(i=this.$r(),l=this.Nr(),Ts.info("new session ID generated",{sessionId:i,windowId:l,changeReason:{noSessionId:h,activityTimeout:f,sessionPastMaximumLength:u}}),o=r,c=!0):(l||(l=this.Nr(),c=!0),(d=i!==p)&&(Ts.info("adopted cross-tab session id",{sessionId:i,windowId:l}),c=!0));var m=lt(a)&&e&&!u?a:r,_=lt(o)?o:new Date().getTime();this.Wr(l),this.Ur(i,m,_),e||this.qr();var b={noSessionId:h,activityTimeout:f,sessionPastMaximumLength:u,crossTabAdoption:d};return c&&this.Rr.forEach((E=>E(i,l,b))),{sessionId:i,windowId:l,sessionStartTimestamp:_,changeReason:c?b:void 0,lastActivityTimestamp:a}}qr(){this.Fr||(clearTimeout(this.tn),this.tn=setTimeout((()=>{if(!this.Fr)if(this.Xr(new Date().getTime())){var e=this.Dr;this.resetSessionId(),this.Ir.emit("forcedIdleReset",{idleSessionId:e})}else this.qr()}),1.1*this.sessionTimeoutMs))}}var Qu=function(t,e){if(!t)return!1;var s=t.userAgent;if(s&&Wa(s,e))return!0;try{var r=t?.userAgentData;if(r!=null&&r.brands&&r.brands.some((n=>Wa(n?.brand,e))))return!0}catch{}return!!t.webdriver};function ed(){return(ed=X((function*(){var t=ke?.userAgentData;if(t!=null&&t.getHighEntropyValues)try{var e=yield t.getHighEntropyValues(["model"]),s=e?.model;return W(s)&&s.length>0?s:void 0}catch(r){return void k.info("Unable to resolve $device_model from userAgentData.getHighEntropyValues",r)}}))).apply(this,arguments)}var pn=function(t,e){if(!(function(s){try{new RegExp(s)}catch{return!1}return!0})(e))return!1;try{return new RegExp(e).test(t)}catch{return!1}};function mi(t,e,s){return cs({distinct_id:t,userPropertiesToSet:e,userPropertiesToSetOnce:s})}var td={exact:(t,e)=>e.some((s=>t.some((r=>s===r)))),is_not:(t,e)=>e.every((s=>t.every((r=>s!==r)))),regex:(t,e)=>e.some((s=>t.some((r=>pn(s,r))))),not_regex:(t,e)=>e.every((s=>t.every((r=>!pn(s,r))))),icontains:(t,e)=>e.map(Cr).some((s=>t.map(Cr).some((r=>s.includes(r))))),not_icontains:(t,e)=>e.map(Cr).every((s=>t.map(Cr).every((r=>!s.includes(r))))),gt:(t,e)=>e.some((s=>{var r=parseFloat(s);return!isNaN(r)&&t.some((n=>r>parseFloat(n)))})),lt:(t,e)=>e.some((s=>{var r=parseFloat(s);return!isNaN(r)&&t.some((n=>rt.toLowerCase();function sd(t,e){return!t||Object.entries(t).every((s=>{var r=s[1],n=e?.[s[0]];if(x(n)||$e(n))return!1;var i=[String(n)],o=td[r.operator];return!!o&&o(r.values,i)}))}var ho="custom",kl="i.posthog.com",Kp=/^\/static\//;class Jp{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,s=(e=this.instance.config.ui_host)==null?void 0:e.replace(/\/$/,"");return s||(s=this.apiHost.replace("."+kl,".posthog.com")),s==="https://app.posthog.com"?"https://us.posthog.com":s}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":ho),this.en[this.apiHost]}rn(e){if(Kp.test(e)){var s=this.instance.config.asset_host;if(typeof s=="string")return s.trim().replace(/\/$/,"")||void 0}}endpointFor(e,s){if(s===void 0&&(s=""),s&&(s=s[0]==="/"?s:"/"+s),e==="ui")return this.uiHost+s;if(e==="flags")return this.flagsApiHost+s;if(e==="assets"){var r=this.rn(s);if(r)return""+r+s}if(this.region===ho)return this.apiHost+s;var n=kl+s;switch(e){case"assets":return"https://"+this.region+"-assets."+n;case"api":return"https://"+this.region+"."+n}}}function rd(t){var e;return!((e=t.conditions)==null||(e=e.events)==null||(e=e.values)==null||!e.length)}var q=se("[Surveys]"),nd="seenSurvey_",id=t=>{try{var e=(s=>((r,n)=>""+nd+(function(i){return i.current_iteration&&i.current_iteration>0?i.id+"_"+i.current_iteration:i.id})(n))(0,s))(t);if(localStorage.getItem(e))return;localStorage.setItem(e,"true")}catch(s){q.error("Failed to persist survey seen state",s)}},Yp=[di.Popover,di.Widget,di.API],Zp={ignoreConditions:!1,ignoreDelay:!1,displayType:io.Popover},Xp=se("[PostHog ExternalIntegrations]"),Qp={intercom:"intercom-integration",crispChat:"crisp-chat-integration"};class ef{constructor(e){this._instance=e}ai(e,s){var r;(r=$.__PosthogExtensions__)==null||r.loadExternalDependency==null||r.loadExternalDependency(this._instance,e,(n=>{if(n)return Xp.error("failed to load script",n);s()}))}startIfEnabledOrStop(){var e=this,s=function(){var i,o,a,l=r[0],u=r[1];!u||(i=$.__PosthogExtensions__)!=null&&(i=i.integrations)!=null&&i[l]||e.ai(Qp[l],(()=>{var c;(c=$.__PosthogExtensions__)==null||(c=c.integrations)==null||(c=c[l])==null||c.start(e._instance)})),!u&&(o=$.__PosthogExtensions__)!=null&&(o=o.integrations)!=null&&o[l]&&((a=$.__PosthogExtensions__)==null||(a=a.integrations)==null||(a=a[l])==null||a.stop())};for(var r of Object.entries((n=this._instance.config.integrations)!==null&&n!==void 0?n:{})){var n;s()}}}class tf{constructor(e,s){this.rt=e,this.nn=s,this.sn=new Map,this.an=!1}add(e){var s=this;return X((function*(){if(s.an)throw new Error("Cannot add an extension to a disposed ExtensionRuntime");if(s.sn.has(e.name))throw new Error('Browser extension "'+e.name+'" is already registered');s.sn.set(e.name,e);try{var r=e.setup(s.nn);r&&(yield r)}catch(i){var n=s.sn.get(e.name)===e;n&&s.sn.delete(e.name),s.rt.error('Failed to set up browser extension "'+e.name+'"',i),n&&s.ln(e)}}))()}dispose(){if(!this.an){this.an=!0;var e=Array.from(this.sn.values()).reverse();for(var s of(this.sn.clear(),e))this.ln(s)}}ln(e){try{var s=e.dispose==null?void 0:e.dispose();s&&Se(s.then)&&s.then(void 0,(r=>{this.rt.error('Failed to dispose browser extension "'+e.name+'"',r)}))}catch(r){this.rt.error('Failed to dispose browser extension "'+e.name+'"',r)}}}class sf{constructor(e){this._instance=e}initialize(){}get(e){var s=this._instance.persistence;if(typeof e=="string")return s?.get_property(e);var r={};for(var n of e){var i=s?.get_property(n);x(i)||(r[n]=i)}return r}set(e,s){var r;(r=this._instance.persistence)==null||r.register(typeof e=="string"?{[e]:s}:e)}remove(e){var s;(s=this._instance.persistence)==null||s.unregister(e)}}var Il="extensionsRemoteConfig";class rf{constructor(e){this.an=!1,this.instance=e,this.rt=k,this.un=e.hn,this.kv=new sf(e),this.onEvent=s=>Ir(this.instance.on("eventCaptured",(r=>{try{s({event:r.event,properties:r.properties})}catch(n){this.rt.error("Browser extension event listener failed",n)}}))),this.onRemoteConfig=s=>{if(this.an)return Ir((()=>{}));var r=i=>{try{s(i)}catch(o){this.rt.error("Browser extension remote config listener failed",o)}},n=this.instance.dn.on(Il,r);return this.un&&r(this.un),Ir(n)},this.vn=new tf(k.createLogger("[BrowserExtensions]"),this)}get logger(){return this.rt}get distinctId(){return this.instance.get_distinct_id()}get anonymousId(){var e;return(e=this.instance.get_property(sr))!==null&&e!==void 0?e:this.distinctId}get deviceId(){var e=this.instance.get_property(sr);return typeof e=="string"?e:void 0}get library(){return{name:Y.LIB_NAME,version:Y.LIB_VERSION}}get initialPersonProperties(){var e,s;return(e=(s=this.instance.persistence)==null?void 0:s.get_initial_props())!==null&&e!==void 0?e:{}}get groups(){return this.instance.getGroups()}get session(){try{var e,s,r,n,i=(e=this.instance.sessionManager)==null?void 0:e.checkAndGetSessionAndWindowId(!0);return{sessionId:(s=i?.sessionId)!==null&&s!==void 0?s:"",windowId:(r=i?.windowId)!==null&&r!==void 0?r:"",sessionStartTimestamp:(n=i?.sessionStartTimestamp)!==null&&n!==void 0?n:0}}catch{return{sessionId:"",windowId:"",sessionStartTimestamp:0}}}get projectToken(){return this.instance.config.token}add(e){return this.vn.add(e)}capture(e,s,r){var n=this;return X((function*(){r?n.instance.capture(e,s,{timestamp:r.timestamp,uuid:r.uuid,$set:r.set,$set_once:r.setOnce}):n.instance.capture(e,s)}))()}registerDynamicEventProperties(e){return Ir(this.instance.cn(e))}handleRemoteConfig(e){this.an||(this.un=e,this.instance.dn.emit(Il,e))}sendRequest(e,s){var r=this;return X((function*(){var n;s===void 0&&(s={});var i=r.instance.requestRouter.endpointFor((n=s.target)!==null&&n!==void 0?n:"api",e),o={method:s.method,url:s.query?$n(i,s.query):i,data:s.body,headers:s.headers,timeout:s.timeoutMs,fireCallbackOnDrop:!0,transport:s.transport,compression:s.compression,timestampMode:s.sentAt};return s.transport==="sendBeacon"?(r.instance._send_request(o),{statusCode:202}):new Promise((a=>{o.callback=a,r.instance._send_request(o)}))}))()}dispose(){this.an||(this.an=!0,this.vn.dispose())}}var Ys={},vi=0,fn=()=>{},Cl='Consent opt in/out is not valid with cookieless_mode="always" and will be ignored',Ns="Surveys module not available",Fl="sanitize_properties is deprecated. Use before_send instead",od="Invalid value for property_denylist config: ",nf=["token","distinct_id",pu],os="posthog",ad=!jp&&Pe?.indexOf("MSIE")===-1&&Pe?.indexOf("Mozilla")===-1,_i=t=>{var e;return w({api_host:"https://us.i.posthog.com",flags_api_host:null,ui_host:null,asset_host:null,token:"",autocapture:!0,cross_subdomain_cookie:ip(C?.location),persistence:"localStorage+cookie",persistence_name:"",cookie_persisted_properties:[],loaded:fn,save_campaign_params:!0,custom_campaign_params:[],custom_blocked_useragents:[],save_referrer:!0,capture_pageleave:"if_capture_pageview",defaults:t??"unset",__preview_deferred_init_extensions:!1,__preview_external_dependency_versioned_paths:!1,__preview_cookie_wins_on_conflict:!1,debug:re&&W(re?.search)&&re.search.indexOf("__posthog_debug=true")!==-1||!1,cookie_expiration:365,upgrade:!1,disable_session_recording:!1,disable_persistence:!1,disable_web_experiments:!0,disable_surveys:!1,disable_surveys_automatic_display:!1,disable_conversations:!1,disable_product_tours:!1,disableDeviceModel:!1,disable_external_dependency_loading:!1,strict_script_versioning:!1,enable_recording_console_log:void 0,secure_cookie:(v==null||(e=v.location)==null?void 0:e.protocol)==="https:",ip:!1,opt_out_capturing_by_default:!1,opt_out_persistence_by_default:!1,opt_out_useragent_filter:!1,opt_out_capturing_persistence_type:"localStorage",consent_persistence_name:null,opt_out_capturing_cookie_prefix:null,opt_in_site_apps:!1,property_denylist:[],respect_dnt:!1,sanitize_properties:null,request_headers:{},request_batching:!0,properties_string_max_length:65535,mask_all_element_attributes:!1,mask_all_text:!1,mask_personal_data_properties:!1,custom_personal_data_properties:[],advanced_disable_flags:!1,advanced_disable_decide:!1,advanced_disable_feature_flags:!1,advanced_disable_feature_flags_on_first_load:!1,advanced_only_evaluate_survey_feature_flags:!1,advanced_feature_flags_dedup_per_session:!1,advanced_enable_surveys:!1,advanced_disable_toolbar_metrics:!1,feature_flag_request_timeout_ms:3e3,surveys_request_timeout_ms:1e4,on_request_error(s){k.error("Bad HTTP status: "+s.statusCode+" "+s.text)},get_device_id:s=>s,capture_performance:void 0,name:"posthog",bootstrap:{},disable_compression:!1,session_idle_timeout_seconds:1800,person_profiles:to,before_send:void 0,get_current_url:void 0,request_queue_config:{flush_interval_ms:uo},error_tracking:{},_onCapture:fn},(s=>({rageclick:s&&s>="2026-05-30"?{content_ignorelist:vp,ignore_text_selection:!0}:!s||"2025-11-30">s||{content_ignorelist:!0},capture_pageview:!s||"2025-05-24">s||"history_change",session_recording:s&&s>="2026-06-25"?{strictMinimumDuration:!0,canvasCapture:{resolutionScale:.6},streamNetworkBody:!0}:s&&s>="2026-05-30"?{strictMinimumDuration:!0,canvasCapture:{resolutionScale:.6}}:s&&s>="2025-11-30"?{strictMinimumDuration:!0}:{},external_scripts_inject_target:s&&s>="2026-01-30"?"head":"body",internal_or_test_user_hostname:s&&s>="2026-01-30"?/^(localhost|127\.0\.0\.1)$/:void 0,persistence_save_debounce_ms:s&&s>="2026-05-30"?250:0,split_storage:!(!s||"2026-05-30">s),detect_google_search_app:!(!s||"2026-05-30">s),disable_capture_url_hashes:!(!s||"2026-06-25">s)}))(t))},of=[["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"]],Pl=t=>{var e={};for(var s of of){var r=s[0],n=s[1];x(t[r])||(e[n]=t[r])}var i=ee({},e,t),o=t.__preview_external_dependency_versioned_paths;return x(o)||(x(t.strict_script_versioning)&&(i.strict_script_versioning=!!o),W(o)&&x(t.asset_host)&&(i.asset_host=o)),L(t.property_blacklist)&&(x(t.property_denylist)?i.property_denylist=t.property_blacklist:L(t.property_denylist)?i.property_denylist=[...t.property_blacklist,...t.property_denylist]:k.error(od+t.property_denylist)),i};class af{constructor(){this.__forceAllowLocalhost=!1}get fn(){return this.__forceAllowLocalhost}set fn(e){k.error("WebPerformanceObserver is deprecated and has no impact on network capture. Use `_forceAllowLocalhostNetworkCapture` on `posthog.sessionRecording`"),this.__forceAllowLocalhost=e}}class Te{pn(e,s){if(e){var r=this.sn.indexOf(e);r!==-1&&this.sn.splice(r,1)}return this.sn.push(s),s.initialize==null||s.initialize(),s}gn(){return this.config.cookieless_mode===ht||this.config.cookieless_mode===Ht&&this.consent.isRejected()}get decideEndpointWasHit(){var e,s;return(e=(s=this.featureFlags)==null?void 0:s.hasLoadedFlags)!==null&&e!==void 0&&e}get flagsEndpointWasHit(){var e,s;return(e=(s=this.featureFlags)==null?void 0:s.hasLoadedFlags)!==null&&e!==void 0&&e}constructor(){var e;this.webPerformance=new af,this.mn=!1,this.version=Y.LIB_VERSION,this.yn=new Set,this.bn="",this.dn=new Xo,this.sn=[],this._n=[],this._calculate_event_properties=this.calculateEventProperties.bind(this),this.config=_i(),this.SentryIntegration=kp,this.sentryIntegration=r=>(function(n,i){var o=$u(n,i);return{name:Au,processEvent:a=>o(a)}})(this,r),this.__request_queue=[],this.__loaded=!1,this.analyticsDefaultEndpoint="/e/",this.wn=!1,this.kn=null,this.xn=null,this.Sn=null,this.scrollManager=new Vp(this),this.pageViewManager=new fl(this),this.rateLimiter=new Np(this),this.requestRouter=new Jp(this),this.consent=new hp(this),this.externalIntegrations=new ef(this);var s=(e=Te.__defaultExtensionClasses)!==null&&e!==void 0?e:{};this.featureFlags=s.featureFlags&&new s.featureFlags(this),this.toolbar=s.toolbar&&new s.toolbar(this),this.surveys=s.surveys&&new s.surveys(this),this.conversations=s.conversations&&new s.conversations(this),this.logs=s.logs&&new s.logs(this),this.metrics=s.metrics&&new s.metrics(this),this.experiments=s.experiments&&new s.experiments(this),this.exceptions=s.exceptions&&new s.exceptions(this),this.people={set:(r,n,i)=>{var o=W(r)?{[r]:n}:r;this.setPersonProperties(o),i?.({})},set_once:(r,n,i)=>{var o=W(r)?{[r]:n}:r;this.setPersonProperties(void 0,o),i?.({})}},this.on("eventCaptured",(r=>k.info('send "'+r?.event+'"',r)))}init(e,s,r){if(r&&r!==os){var n,i=(n=Ys[r])!==null&&n!==void 0?n:new Te;return i._init(e,s,r),Ys[r]=i,Ys[os][r]=i,i}return this._init(e,s,r)}_init(e,s,r){var n,i;s===void 0&&(s={});var o,a=W(e)?e.trim():"";if(!a)return k.critical("PostHog was initialized without a token. This likely indicates a misconfiguration. Please check the first argument passed to posthog.init()"),this;if(this.__loaded)return a!==((o=this.config)==null?void 0:o.token)?console.warn("[PostHog.js]","You have already initialized PostHog with a different project token! Re-initializing is a no-op, so events will keep going to the project this instance was initialized with. To capture into a second project, load PostHog once, then initialize a named instance after the SDK has loaded, e.g. posthog.init('"+a+"', { ... }, 'project2')"):console.warn("[PostHog.js]","You have already initialized PostHog! Re-initializing is a no-op"),this;this.__loaded=!0,this.config=_i(s.defaults),s.debug=this.Cn(s.debug),this.Mn=s,this.Tn=[],s.person_profiles?this.xn=s.person_profiles:s.process_person&&(this.xn=s.process_person);var l=_i(s.defaults),u=Pl(s),c=ee({},l,u,{name:r,token:a});te(l.rageclick)&&te(u.rageclick)&&(c.rageclick=ee({},l.rageclick,u.rageclick)),te(l.session_recording)&&te(u.session_recording)&&(c.session_recording=ee({},l.session_recording,u.session_recording)),this.set_config(c),this.config.on_xhr_error&&k.error("on_xhr_error is deprecated. Use on_request_error instead"),this.compression=s.disable_compression?void 0:xe.GZipJS;var d=this.En();if(this.persistence=new ui(this.config,d),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new ui(w({},this.config,{persistence:"sessionStorage"}),d,!1),this.bn="ph_"+(this.config.persistence_name||this.config.token)+"_session_registered_properties",this.config.persistence!=="memory"&&!d&&ce.N()){var h=ce.H(this.bn);L(h)&&h.forEach((P=>{W(P)&&this.yn.add(P)}))}else ce.q(this.bn);var p=w({},this.persistence.props),f=w({},this.sessionPersistence.props);this.register({$initialization_time:new Date().toISOString()}),this.In=new Wp((P=>this.Pn(P)),this.config.request_queue_config),this.Rn=new qp(this),this.__request_queue=[];var g=this.gn();if(g||(this.sessionManager=new xl(this),this.sessionPropsManager=new Sl(this,this.sessionManager,this.persistence),this.sessionManager.onSessionId(((P,B,S)=>{(S!=null&&S.activityTimeout||S!=null&&S.sessionPastMaximumLength||S!=null&&S.crossTabAdoption)&&this.An()}))),this.Fn(),this.config.__preview_deferred_init_extensions?(k.info("Deferring extension initialization to improve startup performance"),setTimeout((()=>{this.Ln(g)}),0)):(k.info("Initializing extensions synchronously"),this.Ln(g)),Y.DEBUG=Y.DEBUG||this.config.debug,Y.DEBUG&&k.info("Starting in debug mode",{this:this,config:s,thisC:w({},this.config),p,s:f}),!this.config.identity_distinct_id||(n=s.bootstrap)!=null&&n.distinctID||(s.bootstrap=w({},s.bootstrap,{distinctID:this.config.identity_distinct_id,isIdentifiedID:!0})),((i=s.bootstrap)==null?void 0:i.distinctID)!==void 0){var m=s.bootstrap.distinctID,_=this.get_distinct_id(),b=this.persistence.get_property(He);if(s.bootstrap.isIdentifiedID&&_!=null&&_!==m&&b===es)this.identify(m);else if(s.bootstrap.isIdentifiedID&&_!=null&&_!==m&&b===Tt)k.warn("Bootstrap distinctID differs from an already-identified user. The existing identity is preserved. Call reset() before reinitializing if you intend to switch users.");else{var E=this.config.get_device_id(dt()),I=s.bootstrap.isIdentifiedID?E:m;this.persistence.set_property(He,s.bootstrap.isIdentifiedID?Tt:es),this.register({distinct_id:m,$device_id:I})}}if(g)this.register_once({distinct_id:br,$device_id:null},"");else if(!this.get_distinct_id()){var F=this.config.get_device_id(dt());this.register_once({distinct_id:F,$device_id:F},""),this.persistence.set_property(He,es)}return ne(v,"onpagehide"in self?"pagehide":"unload",this._handle_unload.bind(this),{passive:!1}),s.segment?(function(P,B){var S=P.config.segment;if(!S)return B();(function(A,R){var N=A.config.segment;if(!N)return R();var T=J=>{var z=()=>J.anonymousId()||dt();A.config.get_device_id=z,J.id()&&(A.register({distinct_id:J.id(),$device_id:z()}),A.persistence.set_property(He,Tt)),R()},O=N.user();"then"in O&&Se(O.then)?O.then(T):T(O)})(P,(()=>{S.register((A=>{typeof Promise<"u"&&Promise.resolve||li.warn("This browser does not have Promise support, and can not use the segment integration");var R=(N,T)=>{if(!T)return N;N.event.userId||N.event.anonymousId===A.get_distinct_id()||(li.info("No userId set, resetting PostHog"),A.reset()),N.event.userId&&N.event.userId!==A.get_distinct_id()&&(li.info("UserId set, identifying with PostHog"),A.identify(N.event.userId));var O=A.calculateEventProperties(T,N.event.properties);return N.event.properties=Object.assign({},O,N.event.properties),N};return{name:"PostHog JS",type:"enrichment",version:"1.0.0",isLoaded:()=>!0,load:()=>Promise.resolve(),track:N=>R(N,N.event.event),page:N=>R(N,is),identify:N=>R(N,ii),screen:N=>R(N,"$screen")}})(P)).then((()=>{B()}))}))})(this,(()=>this.On())):this.On(),Se(this.config._onCapture)&&this.config._onCapture!==fn&&(k.warn("onCapture is deprecated. Please use `before_send` instead"),this.on("eventCaptured",(P=>this.config._onCapture(P.event,P)))),this.config.ip&&k.warn('The `ip` config option has NO EFFECT AT ALL and has been deprecated. Use a custom transformation or "Discard IP data" project setting instead. See https://posthog.com/tutorials/web-redact-properties#hiding-customer-ip-address for more information.'),this.config.disableDeviceModel||(function(){return ed.apply(this,arguments)})().then((P=>{P&&this.register({[ri]:P})})).catch(fn),this}Fn(){var e,s,r,n,i,o,a=(e=(s=this.config.__extensionClasses)==null?void 0:s.featureFlags)!==null&&e!==void 0?e:(r=Te.__defaultExtensionClasses)==null?void 0:r.featureFlags;a&&(this.featureFlags&&this.featureFlags instanceof a||((n=this.Dn)==null||n.call(this),this.Dn=void 0,this.featureFlags=new a(this)),Se(this.featureFlags.onReloading)&&Se(this.featureFlags.setup)?this.Dn||(this.Dn=this.featureFlags.onReloading((()=>{this.dn.emit("featureFlagsReloading",!0)})),this.$n().add(this.featureFlags)):(i=(o=this.featureFlags).initialize)==null||i.call(o))}Ln(e){var s,r,n,i,o,a,l,u=performance.now(),c=w({},Te.__defaultExtensionClasses,this.config.__extensionClasses),d=[];c.exceptions&&this.sn.push(this.exceptions=(s=this.exceptions)!==null&&s!==void 0?s:new c.exceptions(this)),c.historyAutocapture&&this.sn.push(this.historyAutocapture=new c.historyAutocapture(this)),c.tracingHeaders&&this.sn.push(this.tracingHeaders=new c.tracingHeaders(this)),c.siteApps&&this.sn.push(this.siteApps=new c.siteApps(this)),c.sessionRecording&&!e&&this.sn.push(this.sessionRecording=new c.sessionRecording(this)),this.config.disable_scroll_properties||d.push((()=>{this.scrollManager.startMeasuringScrollPosition()})),c.autocapture&&this.sn.push(this.autocapture=new c.autocapture(this)),c.surveys&&this.sn.push(this.surveys=(r=this.surveys)!==null&&r!==void 0?r:new c.surveys(this)),c.logs&&this.sn.push(this.logs=(n=this.logs)!==null&&n!==void 0?n:new c.logs(this)),c.metrics&&this.sn.push(this.metrics=(i=this.metrics)!==null&&i!==void 0?i: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,xp)),c.toolbar&&this.sn.push(this.toolbar=(a=this.toolbar)!==null&&a!==void 0?a:new c.toolbar(this)),c.experiments&&this.sn.push(this.experiments=(l=this.experiments)!==null&&l!==void 0?l:new c.experiments(this)),this.sn.forEach((h=>{h.initialize&&d.push((()=>{h.initialize==null||h.initialize()}))})),d.push((()=>{if(this.Nn){var h=this.Nn;this.Nn=void 0,this.sn.forEach((p=>p.onRemoteConfig==null?void 0:p.onRemoteConfig(h)))}})),this.qn(d,u)}qn(e,s){for(;e.length>0;){if(this.config.__preview_deferred_init_extensions&&performance.now()-s>=30&&e.length>0)return void setTimeout((()=>{this.qn(e,s)}),0);var r=e.shift();if(r)try{r()}catch(i){k.error("Error initializing extension:",i)}}var n=Math.round(performance.now()-s);this.register_for_session({[fu]:this.config.__preview_deferred_init_extensions?"deferred":"synchronous",[gu]:n}),this.config.__preview_deferred_init_extensions&&k.info("PostHog extensions initialized ("+n+"ms)")}Zi(e){var s;if(!C||!C.body)return k.info("document not ready yet, trying again in 500 milliseconds..."),void setTimeout((()=>{this.Zi(e)}),500);if(this.config.__preview_deferred_init_extensions&&(this.Nn=e),this.hn=e,this.compression=void 0,e.ok){var r,n=e.config;n.supportedCompression&&!this.config.disable_compression&&(this.compression=M(n.supportedCompression,xe.GZipJS)?xe.GZipJS:M(n.supportedCompression,xe.Base64)?xe.Base64:void 0),(r=n.analytics)!=null&&r.endpoint&&(this.analyticsDefaultEndpoint=n.analytics.endpoint)}this.set_config({person_profiles:this.xn?this.xn:to}),(s=this.jn)==null||s.handleRemoteConfig(e),this.sn.forEach((i=>i.onRemoteConfig==null?void 0:i.onRemoteConfig(e)))}On(){try{this.config.loaded(this)}catch(r){k.critical("`loaded` function failed",r)}if(this.Bn(),this.config.internal_or_test_user_hostname&&re!=null&&re.hostname){var e=re.hostname,s=this.config.internal_or_test_user_hostname;(typeof s=="string"?e===s:s.test(e))&&this.setInternalOrTestUser()}this.config.capture_pageview&&setTimeout((()=>{(this.consent.isOptedIn()||this.gn())&&this.Hn()}),1),this.Un=new Uu(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()&&Er(this.__request_queue,(e=>this.Pn(e))),this.__request_queue=[],this.Bn()}_handle_unload(){var e,s,r,n,i;(e=this.surveys)==null||e.handlePageUnload==null||e.handlePageUnload(),(s=this.metrics)==null||s.flush("sendBeacon"),this.config.request_batching?(this.zn()&&this.capture(ni),(r=this.logs)==null||r.flushLogs("sendBeacon"),(n=this.In)==null||n.unload(),(i=this.Rn)==null||i.unload()):this.zn()&&this.capture(ni,null,{transport:"sendBeacon"})}_send_request(e){this.__loaded?ad?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=w({},this.config.request_headers,e.headers),e.compression=e.compression==="best-available"?this.compression:e.compression,(x(this.config.disable_beacon)?this.config.__preview_disable_beacon:this.config.disable_beacon)&&(e.disableTransport=["sendBeacon"]),e.fetchOptions=e.fetchOptions||this.config.fetch_options,(s=>{var r,n,i,o=w({},s);o.timeout=o.timeout||6e4;var a,l,u,c,d,h=(r=o.transport)!==null&&r!==void 0?r:"fetch";h==="sendBeacon"&&x(o.compression)&&o.data&&(o.compression=xe.Base64),o.method==="POST"&&o.data&&(o.timestampMode==="capture-body"?o.data={api_key:(l=(d=(c=L(a=o.data)?a:[a])[0])==null||(u=d.properties)==null?void 0:u.token)!==null&&l!==void 0?l:d?.token,batch:c,sent_at:new Date().toISOString()}:o.timestampMode==="body"&&(o.data=(function(m,_){return _===void 0&&(_=new Date().toISOString()),L(m)?m.map((b=>w({},b,{sent_at:_}))):w({},m,{sent_at:_})})(o.data))),o.url=El(o.url,o.method,o.compression,o.timestampMode);var p=Br.filter((m=>!o.disableTransport||!m.transport||!o.disableTransport.includes(m.transport))),f=(n=(i=(function(m,_){for(var b=0;m.length>b;b++)if(m[b].transport===h)return m[b]})(p))==null?void 0:i.method)!==null&&n!==void 0?n:p[0].method;if(!f)throw new Error("No available transport method");var g=m=>{try{f(m)}catch(_){Zu(_)?k.warn(_):k.error(_),o.callback==null||o.callback({statusCode:0,error:_})}};h!=="sendBeacon"&&o.data&&o.compression===xe.GZipJS&&ah&&typeof Promise<"u"&&!Dr?Up(o).then((m=>{g(m)})).catch((m=>{if(Ha(m))return Dr=!0,void g(w({},o,{compression:void 0,url:El(s.url,s.method,void 0,s.timestampMode)}));(_=>{if(!_||typeof _!="object")return!1;var b="name"in _?String(_.name):"";return Ha(_)||b===Cc})(m)&&(Dr=!0),g(o)})):f(o)})(w({},e,{callback:s=>{var r,n;this.rateLimiter.checkForLimiting(s),400>s.statusCode||(r=(n=this.config).on_request_error)==null||r.call(n,s),e.callback==null||e.callback(s)}}))):e.fireCallbackOnDrop&&(e.callback==null||e.callback({statusCode:0}))}Pn(e){this.Rn?this.Rn.retriableRequest(e):this._send_request(e)}_execute_array(e){vi++;try{var s,r=[],n=[],i=[];Er(e,(a=>{if(a)if(L(s=a[0]))i.push(a);else if(Se(a))try{a.call(this)}catch(l){k.error("Error executing queued PostHog call",a,l)}else L(a)&&s==="alias"?r.push(a):L(a)&&s.indexOf("capture")!==-1&&Se(this[s])?i.push(a):n.push(a)}));var o=function(a,l){Er(a,(function(u){try{if(L(u[0])){var c=l;Z(u,(function(d){c=c[d[0]].apply(c,d.slice(1))}))}else l[u[0]].apply(l,u.slice(1))}catch(d){k.error("Error executing queued PostHog call",u,d)}}))};o(r,this),o(n,this),o(i,this)}finally{vi--}}push(e){if(vi>0&&L(e)&&W(e[0])){var s=Te.prototype[e[0]];Se(s)&&s.apply(this,e.slice(1))}else this._execute_array([e])}capture(e,s,r){var n,i,o,a,l;if(this.__loaded&&this.persistence&&this.sessionPersistence&&this.In){if(this.is_capturing())if(!x(e)&&W(e)){var u=!this.config.opt_out_useragent_filter&&this._is_bot();if(!u||this.config.__preview_capture_bot_pageviews){var c=r!=null&&r.skip_client_rate_limiting?void 0:this.rateLimiter.clientRateLimitContext();if(c==null||!c.isRateLimited){s!=null&&s.$current_url&&!W(s?.$current_url)&&(k.error("Invalid `$current_url` property provided to `posthog.capture`. Input must be a string. Ignoring provided value."),s==null||delete s.$current_url),e!=="$exception"||r!=null&&r.Wn||k.warn("Using `posthog.capture('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureException(error)` instead, which attaches required metadata automatically."),this.sessionPersistence.update_search_keyword(),this.config.save_campaign_params&&this.sessionPersistence.update_campaign_params(),this.config.save_referrer&&this.sessionPersistence.update_referrer_info(),(this.config.save_campaign_params||this.config.save_referrer)&&this.persistence.set_initial_person_info();var d=new Date,h=r?.timestamp||d,p=Ga(r?.uuid,dt),f={uuid:p,event:e,properties:this.calculateEventProperties(e,s||{},h,p)};e===is&&this.config.__preview_capture_bot_pageviews&&u&&(f.event="$bot_pageview",f.properties.$browser_type="bot"),c&&(f.properties.$lib_rate_limit_remaining_tokens=c.remainingTokens);var g=e==="$feature_flag_called"&&f.properties.$feature_flag_has_experiment===!1&&this.get_property(en)===!0;r?.$set&&!g&&(f.$set=r?.$set);var m=r?.$unset;m&&(f.$unset=m);var _,b,E,I=g?void 0:this.Vn(r?.$set_once,e!==Qa,e===ii);if(I&&(f.$set_once=I),r!=null&&r._noTruncate||(i=this.config.properties_string_max_length,o=f,a=T=>W(T)?T.slice(0,i):T,l=new Set,f=(function T(O,J){if(O!==Object(O))return a?a(O):O;if(!l.has(O)){var z;if(l.add(O),L(O))z=[],Er(O,(oe=>{z.push(T(oe))}));else{var H={};Z(O,((oe,pe)=>{l.has(oe)||(H[pe]=T(oe))})),z=H}return z}})(o)),f.timestamp=h,x(r?.timestamp)||(f.properties.$event_time_override_provided=!0,f.properties.$event_time_override_system_time=d),g&&(f.properties=(function(T,O){O===void 0&&(O=[]);var J={},z=H=>{T[H]!==void 0&&(J[H]=T[H])};return lh.forEach(z),O.forEach(z),J})(f.properties,nf)),e===ft.DISMISSED||e===ft.SENT){var F=s?.[hi.SURVEY_ID],P=s?.[hi.SURVEY_ITERATION];id({id:F,current_iteration:P}),f.$set=w({},f.$set,{[(_={id:F,current_iteration:P},b=e===ft.SENT?"responded":"dismissed",E="$survey_"+b+"/"+_.id,_.current_iteration&&_.current_iteration>0&&(E="$survey_"+b+"/"+_.id+"/"+_.current_iteration),E)]:!0})}else e===ft.SHOWN&&(f.$set=w({},f.$set,{[hi.SURVEY_LAST_SEEN_DATE]:new Date().toISOString()}));if(e===Tp.SHOWN){var B=s?.[ml.TOUR_TYPE];B&&(f.$set=w({},f.$set,{[ml.TOUR_LAST_SEEN_DATE+"/"+B]:new Date().toISOString()}))}var S=w({},f.properties.$set,f.$set);if(mt(S)||this.setPersonPropertiesForFlags(S),!D(this.config.before_send)){var A=this.Pt(f);if(!A)return;(f=A).uuid=Ga(f.uuid,dt)}this.dn.emit("eventCaptured",f);var R=(n=r?._url)!==null&&n!==void 0?n:this.requestRouter.endpointFor("api",this.analyticsDefaultEndpoint),N={method:"POST",url:R,data:f,compression:"best-available",timestampMode:r?._batchKey==="recordings"||/\/s\/(?:\?|$)/.test(R)?"body":"capture-body",batchKey:r?._batchKey,transport:r?.transport};return!this.config.request_batching||r&&(r==null||!r._batchKey)||r!=null&&r.send_instantly?this.Pn(N):this.In.enqueue(N),f}k.critical("This capture call is ignored due to client rate limiting.")}}else k.error("No event name provided to posthog.capture")}else k.uninitializedWarning("posthog.capture")}_addCaptureHook(e){return this.on("eventCaptured",(s=>e(s.event,s)))}$n(){var e;return(e=this.jn)!==null&&e!==void 0?e:this.jn=new rf(this)}cn(e){this._n.push(e);var s=!0;return()=>{if(s){s=!1;var r=this._n.indexOf(e);r!==-1&&this._n.splice(r,1)}}}calculateEventProperties(e,s,r,n,i){if(r=r||new Date,!this.persistence||!this.sessionPersistence)return s;var o=i?void 0:this.persistence.remove_event_timer(e),a=w({},s);if(a.token=this.config.token,a.$config_defaults=this.config.defaults,this.gn()&&(a[pu]=!0),e==="$snapshot"){var l=w({},this.persistence.properties(),this.sessionPersistence.properties());return a.distinct_id=l.distinct_id,(!W(a.distinct_id)&&!he(a.distinct_id)||Mi(a.distinct_id))&&k.error("Invalid distinct_id for replay event. This indicates a bug in your implementation"),a}var u,c=(function(F,P,B,S){var A,R,N,T;if(S===void 0&&(S=!1),!Pe)return{};var O,J=F?[...vs,...P||[]]:[],z=(function(vr){for(var je=0;qa.length>je;je++){var _r=qa[je],Xt=_r[1],Qt=_r[0].exec(vr),Is=Qt&&(Se(Xt)?Xt(Qt,vr):Xt);if(Is)return Is}return["",""]})(Pe),H=z[0],oe=z[1],pe=(O=typeof navigator<"u"?navigator:void 0)!=null&&O.brave?{brave:!0}:{},Ie={};x(B)||(Ie.detectGoogleSearchApp=B);var _e={},Ce=(A=navigator)==null||(A=A.userAgentData)==null?void 0:A.platform,Re=(R=navigator)==null?void 0:R.maxTouchPoints,ae=v==null||(N=v.screen)==null?void 0:N.width,me=v==null||(T=v.screen)==null?void 0:T.height,ge=v?.devicePixelRatio;x(Ce)||(_e.userAgentDataPlatform=Ce),x(Re)||(_e.maxTouchPoints=Re),x(ae)||(_e.screenWidth=ae),x(me)||(_e.screenHeight=me),x(ge)||(_e.devicePixelRatio=ge);var Ye,Rt,de,Ve,St,ks,Be,Fe,mr=ee(Vo({$os:H,$os_version:oe,$browser:Xc(Pe,navigator.vendor,pe,Ie),$device:Va(Pe),$device_type:(Rt=Pe,de=_e,Fe=Va(Rt),Fe===Nc||Fe===Tc||Fe==="Kobo"||Fe==="Kindle Fire"||Fe===Gc?ps:Fe===er||Fe===ds||Fe===tr||Fe===Oi?"Console":Fe===Lc?"Wearable":Fe?Oe:de?.userAgentDataPlatform==="Android"&&((Ve=de?.maxTouchPoints)!==null&&Ve!==void 0?Ve:0)>0?600>Math.min((St=de?.screenWidth)!==null&&St!==void 0?St:0,(ks=de?.screenHeight)!==null&&ks!==void 0?ks:0)/((Be=de?.devicePixelRatio)!==null&&Be!==void 0?Be:1)?Oe:ps:"Desktop"),$timezone:ju(),$timezone_offset:Ap()}),{$current_url:nr(S?Ct(re?.href):re?.href,J,ir),$host:re?.host,$pathname:re?.pathname,$raw_user_agent:Pe.length>1e3?Pe.substring(0,997)+"...":Pe,$browser_version:Ch(Pe,navigator.vendor,pe,Ie),$browser_language:gl(),$browser_language_prefix:(Ye=gl(),typeof Ye=="string"?Ye.split("-")[0]:void 0),$screen_height:v?.screen.height,$screen_width:v?.screen.width,$viewport_height:v?.innerHeight,$viewport_width:v?.innerWidth,$lib:Y.LIB_NAME,$lib_version:Y.LIB_VERSION,$insert_id:Math.random().toString(36).substring(2,10)+Math.random().toString(36).substring(2,10),$time:Date.now()/1e3});return Y.SDK_DIST_CHANNEL&&(mr.$sdk_dist_channel=Y.SDK_DIST_CHANNEL),mr})(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(i,r.getTime()),h=d.windowId;a.$session_id=d.sessionId,a.$window_id=h}this.sessionPropsManager&&ee(a,this.sessionPropsManager.getSessionProps());try{var p;this.sessionRecording&&ee(a,this.sessionRecording.sdkDebugProperties),a.$sdk_debug_retry_queue_size=(p=this.Rn)==null?void 0:p.length}catch(F){a.$sdk_debug_error_capturing_properties=String(F)}if(this.requestRouter.region===ho&&(a.$lib_custom_api_host=this.config.api_host),u=e!==is||i?e!==ni||i?this.pageViewManager.doEvent():this.pageViewManager.doPageLeave(r):this.pageViewManager.doPageView(r,n),a=ee(a,u),e===is&&C&&(a.title=C.title),!x(o)){var f=r.getTime()-o;a.$duration=parseFloat((f/1e3).toFixed(3))}Pe&&this.config.opt_out_useragent_filter&&(a.$browser_type=this._is_bot()?"bot":"browser");var g=this.persistence.properties(),m=this.sessionPersistence.properties();Z(["$referrer","$referring_domain"],(F=>{F in g&&delete m[F]}));var _={};if(this._n.length>0)for(var b of this._n.slice())try{ee(_,b())}catch(F){k.error("Failed to produce browser extension event properties",F)}(a=ee({},c,g,m,w({},_,a))).$is_identified=this._isIdentified(),L(this.config.property_denylist)?Z(this.config.property_denylist,(function(F){delete a[F]})):k.error(od+this.config.property_denylist+" or property_blacklist config: "+this.config.property_blacklist);var E=this.config.sanitize_properties;E&&(k.error(Fl),a=E(a,e));var I=this.Zn();return a.$process_person_profile=I,I&&!i&&this.Gn("_calculate_event_properties"),a}Vn(e,s,r){var n;if(s===void 0&&(s=!0),r===void 0&&(r=!1),!this.persistence||!this.Zn()||this.mn&&!r)return e;var i=this.persistence.get_initial_props(),o=(n=this.sessionPropsManager)==null?void 0:n.getSetOnceProps(),a=ee({},i,o||{},e||{}),l=this.config.sanitize_properties;return l&&(k.error(Fl),a=l(a,"$set_once")),s&&(this.mn=!0),mt(a)?void 0:a}register(e,s){var r;(r=this.persistence)==null||r.register(e,s)}register_once(e,s,r){var n;(n=this.persistence)==null||n.register_once(e,s,r)}register_for_session(e){var s;(s=this.sessionPersistence)==null||s.register(e),Object.keys(e).forEach((r=>this.yn.add(r))),this.Qn()}unregister(e){var s;(s=this.persistence)==null||s.unregister(e)}unregister_for_session(e){var s;(s=this.sessionPersistence)==null||s.unregister(e),this.yn.delete(e),this.Qn()}Kn(e,s){this.register({[e]:s})}An(){this.yn.forEach((e=>{var s;(s=this.sessionPersistence)==null||s.unregister(e)})),this.yn.clear(),this.Qn()}Qn(){var e;if(this.bn)if(this.config.persistence==="memory"||(e=this.sessionPersistence)!=null&&e.xi||!ce.N())ce.q(this.bn);else{var s=[];this.yn.forEach((r=>s.push(r))),s.length>0?ce.F(this.bn,s):ce.q(this.bn)}}getFeatureFlag(e,s){var r;return(r=this.featureFlags)==null?void 0:r.getFeatureFlag(e,s)}getFeatureFlagPayload(e){var s;return(s=this.featureFlags)==null?void 0:s.getFeatureFlagPayload(e)}getFeatureFlagResult(e,s){var r;return(r=this.featureFlags)==null?void 0:r.getFeatureFlagResult(e,s)}getAllFeatureFlags(){var e,s;return(e=(s=this.featureFlags)==null?void 0:s.getAllFeatureFlags())!==null&&e!==void 0?e:[]}isFeatureEnabled(e,s){var r,n;return(r=(n=this.featureFlags)==null?void 0:n.isFeatureEnabled(e,s))!==null&&r!==void 0?r:s?.defaultValue}reloadFeatureFlags(){var e;(e=this.featureFlags)==null||e.reloadFeatureFlags()}updateFlags(e,s,r){var n;(n=this.featureFlags)==null||n.updateFlags(e,s,r)}updateEarlyAccessFeatureEnrollment(e,s,r){var n;(n=this.featureFlags)==null||n.updateEarlyAccessFeatureEnrollment(e,s,r)}getEarlyAccessFeatures(e,s,r){var n;return s===void 0&&(s=!1),(n=this.featureFlags)==null?void 0:n.getEarlyAccessFeatures(e,s,r)}on(e,s){return this.dn.on(e,s)}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:Ns}),()=>{})}onSessionId(e){var s,r;return(s=(r=this.sessionManager)==null?void 0:r.onSessionId(e))!==null&&s!==void 0?s:()=>{}}getSurveys(e,s){s===void 0&&(s=!1),this.surveys?this.surveys.getSurveys(e,s):e([],{isLoaded:!1,error:Ns})}getActiveMatchingSurveys(e,s){s===void 0&&(s=!1),this.surveys?this.surveys.getActiveMatchingSurveys(e,s):e([],{isLoaded:!1,error:Ns})}renderSurvey(e,s){var r;(r=this.surveys)==null||r.renderSurvey(e,s)}displaySurvey(e,s){var r;s===void 0&&(s=Zp),(r=this.surveys)==null||r.displaySurvey(e,s)}cancelPendingSurvey(e){var s;(s=this.surveys)==null||s.cancelPendingSurvey(e)}canRenderSurvey(e){var s,r;return(s=(r=this.surveys)==null?void 0:r.canRenderSurvey(e))!==null&&s!==void 0?s:{visible:!1,disabledReason:Ns}}canRenderSurveyAsync(e,s){var r,n;return s===void 0&&(s=!1),(r=(n=this.surveys)==null?void 0:n.canRenderSurveyAsync(e,s))!==null&&r!==void 0?r:Promise.resolve({visible:!1,disabledReason:Ns})}Jn(e){return!e||Mi(e)?(k.critical("Unique user id has not been set in posthog.identify"),!1):e===br?(k.critical('The string "'+e+'" was set in posthog.identify which indicates an error. This ID is only used as a sentinel value.'),!1):!["distinct_id","distinctid"].includes(e.toLowerCase())&&!["undefined","null"].includes(e.toLowerCase())||(k.critical('The string "'+e+'" was set in posthog.identify which indicates an error. This ID should be unique to the user and not a hardcoded string.'),!1)}identify(e,s,r){if(!this.__loaded||!this.persistence)return k.uninitializedWarning("posthog.identify");if(he(e)&&(e=e.toString(),k.warn("The first argument to posthog.identify was a number, but it should be a string. It has been converted to a string.")),this.Jn(e)&&this.Gn("posthog.identify")){var n=this.get_distinct_id();this.register({$user_id:e}),this.get_property(sr)||this.register_once({$had_persisted_distinct_id:!0,$device_id:n},""),e!==n&&e!==this.get_property(Bs)&&(this.unregister(Bs),this.register({distinct_id:e}));var i,o=(this.persistence.get_property(He)||es)===es,a=e!==n,l=!a&&o;if(a&&o)this.persistence.set_property(He,Tt),this.setPersonPropertiesForFlags({$set:s||{},$set_once:r||{}},!1),this.capture(ii,{distinct_id:e,$anon_distinct_id:n},{$set:s||{},$set_once:r||{}}),this.Sn=mi(e,s,r),(i=this.featureFlags)==null||i.setAnonymousDistinctId(n);else if(l){this.persistence.set_property(He,Tt);var u=s||{},c=r||{};this.setPersonPropertiesForFlags({$set:u,$set_once:c},!1),this.capture("$set",{$set:u,$set_once:c}),this.Sn=mi(e,s,r)}else(s||r)&&this.setPersonProperties(s,r);a?(this.reloadFeatureFlags(),this.featureFlags?this.featureFlags.resetFlagCallReported():this.unregister(Wt)):l&&(s||r)&&this.reloadFeatureFlags()}}setPersonProperties(e,s){if((e||s)&&this.Gn("posthog.setPersonProperties")){var r=mi(this.get_distinct_id(),e,s);this.Sn!==r?(this.setPersonPropertiesForFlags({$set:e||{},$set_once:s||{}},!0),this.capture("$set",{$set:e||{},$set_once:s||{}}),this.Sn=r):k.info("A duplicate setPersonProperties call was made with the same properties. It has been ignored.")}}unsetPersonProperties(e){var s,r=(L(e)?e:[e]).filter((n=>W(n)&&n.length>0));r.length!==0&&this.Gn("posthog.unsetPersonProperties")&&((s=this.featureFlags)==null||s.unsetPersonPropertiesForFlags(r,!0),this.capture("$set",{$unset:r}),this.Sn=null)}group(e,s,r){if(e&&s){var n=this.getGroups(),i=n[e]!==s;if(i&&this.resetGroupPropertiesForFlags(e),this.register({$groups:w({},n,{[e]:s})}),i||r){var o={$group_type:e,$group_key:s};r&&(o.$group_set=r),this.capture(Qa,o)}r&&this.setGroupPropertiesForFlags({[e]:r}),i&&!r&&this.reloadFeatureFlags()}else k.error("posthog.group requires a group type and group key")}resetGroups(){this.register({$groups:{}}),this.resetGroupPropertiesForFlags(),this.reloadFeatureFlags()}setPersonPropertiesForFlags(e,s){var r;s===void 0&&(s=!0),(r=this.featureFlags)==null||r.setPersonPropertiesForFlags(e,s)}resetPersonPropertiesForFlags(e){var s;e===void 0&&(e=!0),(s=this.featureFlags)==null||s.resetPersonPropertiesForFlags(e)}setGroupPropertiesForFlags(e,s){var r;s===void 0&&(s=!0),this.Gn("posthog.setGroupPropertiesForFlags")&&((r=this.featureFlags)==null||r.setGroupPropertiesForFlags(e,s))}resetGroupPropertiesForFlags(e){var s;(s=this.featureFlags)==null||s.resetGroupPropertiesForFlags(e)}reset(e){this.Yn(e)}Yn(e,s){var r,n,i,o,a,l,u,c,d,h;if(s===void 0&&(s=!1),k.info("reset"),!this.__loaded)return k.uninitializedWarning("posthog.reset");var p,f=this.get_property(sr),g=this.get_property(ri),m=this.get_property(qt),_=this.is_capturing();if(this.consent.reset(),s||!_||this.is_capturing()||console.warn("[PostHog.js]","reset() cleared the stored consent, and capturing is now off because of `opt_out_capturing_by_default`. Call opt_in_capturing() again, and prefer calling reset() before opting in rather than after."),(r=this.persistence)==null||r.clear(),(n=this.sessionPersistence)==null||n.clear(),this.yn.clear(),this.Qn(),x(m)||(p=this.persistence)==null||p.register({[qt]:m}),(i=this.surveys)==null||i.reset(),(o=this.Un)==null||o.stop(),(a=this.featureFlags)==null||a.reset(),(l=this.conversations)==null||l.reset(),(u=this.logs)==null||u.reset(),(c=this.metrics)==null||c.reset(),(d=this.persistence)==null||d.set_property(He,es),(h=this.sessionManager)==null||h.resetSessionId(),this.Sn=null,this.config.cookieless_mode===ht)this.register_once({distinct_id:br,$device_id:null},"");else{var b=this.config.get_device_id(dt());this.register_once({distinct_id:b,$device_id:e?b:f},""),e||x(g)||this.register({[ri]: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 s=this;return X((function*(){var r,n,i,o,a,l,u;if(s.__loaded){(r=s.Un)==null||r.stop(),(n=s.jn)==null||n.dispose(),(i=s.sessionRecording)==null||i.dispose(),(o=s.logs)==null||o.flushLogs("sendBeacon"),(a=s.metrics)==null||a.flush("sendBeacon"),(l=s.In)==null||l.unload(),(u=s.Rn)==null||u.unload();try{var c;(c=s.featureFlags)==null||c.destroy()}catch(d){k.error("Error while destroying feature flags",d)}}else k.uninitializedWarning("posthog.shutdown")}))()}setIdentity(e,s){var r;this.config.identity_distinct_id=e,this.config.identity_hash=s,this.alias(e),(r=this.conversations)==null||r.Xn()}clearIdentity(){var e;delete this.config.identity_distinct_id,delete this.config.identity_hash,(e=this.conversations)==null||e.ts()}get_distinct_id(){return this.get_property("distinct_id")}getGroups(){return this.get_property("$groups")||{}}get_session_id(){var e,s;return(e=(s=this.sessionManager)==null?void 0:s.checkAndGetSessionAndWindowId(!0).sessionId)!==null&&e!==void 0?e:""}get_session_replay_url(e){if(!this.sessionManager)return"";var s=this.sessionManager.checkAndGetSessionAndWindowId(!0),r=s.sessionStartTimestamp,n=this.requestRouter.endpointFor("ui","/project/"+this.config.token+"/replay/"+s.sessionId);if(e!=null&&e.withTimestamp&&r){var i,o=(i=e.timestampLookBack)!==null&&i!==void 0?i:10;if(!r)return n;n+="?t="+Math.max(Math.floor((new Date().getTime()-r)/1e3)-o,0)}return n}alias(e,s){return e===this.get_property(au)?(k.critical("Attempting to create alias for existing People user - aborting."),-2):this.Gn("posthog.alias")?(x(s)&&(s=this.get_distinct_id()),e!==s?(this.Kn(Bs,e),this.capture("$create_alias",{alias:e,distinct_id:s})):(k.warn("alias matches current distinct_id - skipping api call."),this.identify(e),-1)):void 0}set_config(e){var s=w({},this.config);if(te(e)){var r,n,i,o,a,l,u,c,d,h,p,f;ee(this.config,Pl(e));var g=this.En();(r=this.persistence)==null||r.update_config(this.config,s,g),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new ui(w({},this.config,{persistence:"sessionStorage"}),g,!1);var m=this.Cn(this.config.debug);Ke(m)&&(this.config.debug=m),Ke(this.config.debug)&&(this.config.debug?(Y.DEBUG=!0,Q.N()&&Q.F("ph_debug",!0),k.info("set_config",{config:e,oldConfig:s,newConfig:w({},this.config)})):(Y.DEBUG=!1,Q.N()&&Q.q("ph_debug"))),(n=this.featureFlags)==null||n.updateConfig==null||n.updateConfig(this.config,this.Qi()),(i=this.exceptionObserver)==null||i.onConfigChange(),(o=this.exceptions)==null||o.onConfigChange(),(a=this.sessionRecording)==null||a.startIfEnabledOrStop(),(l=this.tracingHeaders)==null||l.startIfEnabledOrStop(),(u=this.autocapture)==null||u.startIfEnabled(),(c=this.heatmaps)==null||c.startIfEnabled(),(d=this.exceptionObserver)==null||d.startIfEnabledOrStop(),(h=this.deadClicksAutocapture)==null||h.startIfEnabledOrStop(),(p=this.surveys)==null||p.loadIfEnabled(),this.es(),(f=this.externalIntegrations)==null||f.startIfEnabledOrStop()}}_overrideSDKInfo(e,s){Y.LIB_NAME=e,Y.LIB_VERSION=s}startSessionRecording(e){var s,r,n,i,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)&&((s=this.sessionManager)==null||s.checkAndGetSessionAndWindowId(),l.sampling&&((r=this.sessionRecording)==null||r.overrideSampling()),l.linked_flag&&((n=this.sessionRecording)==null||n.overrideLinkedFlag()),l.url_trigger&&((i=this.sessionRecording)==null||i.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,s){if(this.exceptions){var r=new Error("PostHog syntheticException"),n=this.exceptions.buildProperties(e,{handled:!0,syntheticException:r});return this.exceptions.sendExceptionEvent(w({},n,s))}}addExceptionStep(e,s){var r;(r=this.exceptions)==null||r.addExceptionStep(e,s)}captureLog(e){var s;(s=this.logs)==null||s.captureLog(e)}get logger(){var e,s;return(e=(s=this.logs)==null?void 0:s.logger)!==null&&e!==void 0?e:Te.rs}startExceptionAutocapture(e){this.set_config({capture_exceptions:e==null||e})}stopExceptionAutocapture(){this.set_config({capture_exceptions:!1})}loadToolbar(e){var s,r;return(s=(r=this.toolbar)==null?void 0:r.loadToolbar(e))!==null&&s!==void 0&&s}get_property(e){var s;return(s=this.persistence)==null?void 0:s.props[e]}getSessionProperty(e){var s;return(s=this.sessionPersistence)==null?void 0:s.props[e]}toString(){var e,s=(e=this.config.name)!==null&&e!==void 0?e:os;return s!==os&&(s=os+"."+s),s}_isIdentified(){var e,s;return((e=this.persistence)==null?void 0:e.get_property(He))===Tt||((s=this.sessionPersistence)==null?void 0:s.get_property(He))===Tt}Zn(){var e,s;return!(this.config.person_profiles==="never"||this.config.person_profiles===to&&!this._isIdentified()&&mt(this.getGroups())&&((e=this.persistence)==null||(e=e.props)==null||!e[Bs])&&((s=this.persistence)==null||(s=s.props)==null||!s[rn]))}zn(){return this.config.capture_pageleave===!0||this.config.capture_pageleave==="if_capture_pageview"&&(this.config.capture_pageview===!0||this.config.capture_pageview==="history_change")}createPersonProfile(){this.Zn()||this.Gn("posthog.createPersonProfile")&&this.setPersonProperties({},{})}setInternalOrTestUser(){this.Gn("posthog.setInternalOrTestUser")&&this.setPersonProperties({$internal_or_test_user:!0})}Gn(e){return this.config.person_profiles==="never"?(k.error(e+' was called, but process_person is set to "never". This call will be ignored.'),!1):(this.Kn(rn,!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!==Ht)}es(){var e,s,r,n,i=this.En();return((e=this.persistence)==null?void 0:e.xi)!==i&&((r=this.persistence)==null||r.set_disabled(i)),((s=this.sessionPersistence)==null?void 0:s.xi)!==i&&((n=this.sessionPersistence)==null||n.set_disabled(i)),i&&(this.yn.clear(),this.Qn()),i}opt_in_capturing(e){var s;if(this.config.cookieless_mode!==ht){if(this.gn()){var r,n,i,o,a;this.Yn(!0,!0),(r=this.sessionManager)==null||r.destroy(),(n=this.pageViewManager)==null||n.destroy(),this.sessionManager=new xl(this),this.pageViewManager=new fl(this),this.persistence&&(this.sessionPropsManager=new Sl(this,this.sessionManager,this.persistence));var l,u=(i=(o=this.config.__extensionClasses)==null?void 0:o.sessionRecording)!==null&&i!==void 0?i:(a=Te.__defaultExtensionClasses)==null?void 0:a.sessionRecording;u&&(this.sessionRecording=this.pn(this.sessionRecording,new u(this)),this.hn&&((l=this.sessionRecording)==null||l.onRemoteConfig==null||l.onRemoteConfig(this.hn)))}var c,d;this.consent.optInOut(!0),this.es(),this.Bn(),(s=this.sessionRecording)==null||s.startIfEnabledOrStop(),this.config.cookieless_mode==Ht&&((c=this.surveys)==null||c.loadIfEnabled()),(x(e?.captureEventName)||e!=null&&e.captureEventName)&&this.capture((d=e?.captureEventName)!==null&&d!==void 0?d:"$opt_in",e?.captureProperties,{send_instantly:!0}),this.config.capture_pageview&&this.Hn()}else k.warn(Cl)}opt_out_capturing(){var e,s,r;this.config.cookieless_mode!==ht?(this.config.cookieless_mode===Ht&&this.consent.isOptedIn()&&this.Yn(!0,!0),this.consent.optInOut(!1),this.es(),this.config.cookieless_mode===Ht&&(this.register({distinct_id:br,$device_id:null}),(e=this.sessionRecording)==null||e.stopRecording(),this.sessionRecording=void 0,(s=this.sessionManager)==null||s.destroy(),(r=this.pageViewManager)==null||r.destroy(),this.sessionManager=void 0,this.sessionPropsManager=void 0,this.config.capture_pageview&&this.Hn(),this.Bn())):k.warn(Cl)}has_opted_in_capturing(){return this.consent.isOptedIn()}has_opted_out_capturing(){return this.consent.isOptedOut()}get_explicit_consent_status(){var e=this.consent.consent;return e===1?"granted":e===0?"denied":"pending"}is_capturing(){return this.config.cookieless_mode===ht||(this.config.cookieless_mode===Ht?this.consent.isRejected()||this.consent.isOptedIn():!this.has_opted_out_capturing())}clear_opt_in_out_capturing(){this.consent.reset(),this.es()}_is_bot(){return ke?Qu(ke,this.config.custom_blocked_useragents):void 0}Hn(){C&&(C.visibilityState==="visible"?this.wn||(this.wn=!0,this.capture(is,{title:C.title},{send_instantly:!0}),this.kn&&(C.removeEventListener(nn,this.kn),this.kn=null)):this.kn||(this.kn=this.Hn.bind(this),ne(C,nn,this.kn)))}debug(e){e===!1?(v?.console.log("You've disabled debug mode."),this.set_config({debug:!1})):(v?.console.log("You're now in debug mode. All calls to PostHog will be logged in your console.\nYou can disable this with `posthog.debug(false)`."),this.set_config({debug:!0}))}Qi(){var e=this.Mn||{};return"advanced_disable_flags"in e?!!e.advanced_disable_flags:this.config.advanced_disable_flags!==!1?!!this.config.advanced_disable_flags:this.config.advanced_disable_decide===!0?(k.warn("Config field 'advanced_disable_decide' is deprecated. Please use 'advanced_disable_flags' instead. The old field will be removed in a future major version."),!0):(function(s,r,n,i,o){var a=r in s&&!D(s[r]),l=n in s&&!D(s[n]);return a?s[r]:!!l&&(o&&o.warn("Config field '"+n+"' is deprecated. Please use '"+r+"' instead. The old field will be removed in a future major version."),s[n])})(e,"advanced_disable_flags","advanced_disable_decide",0,k)}Pt(e){var s;if(D(this.config.before_send))return e;var r=Object.keys((s=e.properties)!==null&&s!==void 0?s:{}).filter(gh),n=L(this.config.before_send)?this.config.before_send:[this.config.before_send],i=e;for(var o of n){if(i=o(i),D(i)){var a="Event '"+e.event+"' was rejected in beforeSend function";return fh(e.event)?k.warn(a+". This can cause unexpected behavior."):k.info(a),null}i.properties&&!mt(i.properties)||k.warn("Event '"+e.event+"' has no properties after beforeSend function, this is likely an error.")}for(var l of r)if(i.properties&&D(i.properties[l]))return k.warn("Event '"+e.event+"' had its '"+l+"' property removed in a beforeSend function. This property is required for ingestion, so the event will be dropped."),null;return i}getPageViewId(){var e;return(e=this.pageViewManager.ui)==null?void 0:e.pageViewId}captureTraceFeedback(e,s){this.capture("$ai_feedback",{$ai_trace_id:String(e),$ai_feedback_text:s})}captureTraceMetric(e,s,r){this.capture("$ai_metric",{$ai_trace_id:String(e),$ai_metric_name:s,$ai_metric_value:String(r)})}Cn(e){var s=Ke(e)&&!e,r=Q.N()&&Q.P("ph_debug")==="true";return!s&&(!!r||e)}}Te.__defaultExtensionClasses={},Te.rs=(()=>{var t=()=>{};return{trace:t,debug:t,info:t,warn:t,error:t,fatal:t}})(),(function(t,e){for(var s=0;e.length>s;s++)t.prototype[e[s]]=rp(t.prototype[e[s]])})(Te,["identify"]);class Al{constructor(e){this.disabled=e===!1;var s=te(e)?e:{};this.thresholdPx=s.threshold_px||30,this.timeoutMs=s.timeout_ms||1e3,this.clickCount=s.click_count||3,this.clicks=[]}isRageClick(e,s,r){if(this.disabled)return!1;var n=this.clicks[this.clicks.length-1];if(n&&Math.abs(e-n.x)+Math.abs(s-n.y)r-n.timestamp){if(this.clicks.push({x:e,y:s,timestamp:r}),this.clicks.length===this.clickCount)return!0}else this.clicks=[{x:e,y:s,timestamp:r}];return!1}}var yi="$copy_autocapture",wi=se("[AutoCapture]");function bi(t,e){return e.length>t?e.slice(0,t)+"...":e}function lf(t){if(t.previousElementSibling)return t.previousElementSibling;var e=t;do e=e.previousSibling;while(e&&!Ft(e));return e}function cf(t,e){var s,r,n=e.e,i=e.maskAllElementAttributes,o=e.maskAllText,a=e.elementAttributeIgnoreList,l=e.elementsChainAsString,u=e.disableCaptureUrlHashes;if(!Ft(t))return{props:{}};for(var c=[t],d=new Set([t]),h=t;h.parentNode&&!Me(h,"body")&&Su>c.length;)if(Eu(h.parentNode)){var p=h.parentNode.host;if(d.has(p))break;d.add(p),c.push(p),h=p}else{if(!Ft(h.parentNode)||d.has(h.parentNode))break;d.add(h.parentNode),c.push(h.parentNode),h=h.parentNode}var f,g,m=[],_={},b=!1,E=!1;if(Z(c,(S=>{var A=no(S);if(Me(S,"a")){var R=S.getAttribute("href");b=!!(A&&R&&Ks(R))&&(u?Ct(R):R)}M(ln(S),"ph-no-capture")&&(E=!0),m.push((function(T,O,J,z,H){H===void 0&&(H=!1);var oe=T.tagName.toLowerCase(),pe={tag_name:oe};Ko.indexOf(oe)>-1&&!J&&(pe.$el_text=oe.toLowerCase()==="a"||oe.toLowerCase()==="button"?bi(1024,dl(T)):bi(1024,rr(T)));var Ie=ln(T);Ie.length>0&&(pe.classes=Ie.filter((function(ae){return ae!==""}))),Z(T.attributes,(function(ae){var me;if((!Fu(T)||["name","id","class","aria-label"].indexOf(ae.name)!==-1)&&(z==null||!z.includes(ae.name))&&!O&&Ks(ae.value)&&(!W(me=ae.name)||me.substring(0,10)!=="_ngcontent"&&me.substring(0,7)!=="_nghost")){var ge=ae.value;ae.name==="class"&&(ge=Go(ge).join(" ")),pe["attr__"+ae.name]=bi(1024,ae.name==="href"&&H?Ct(ge):ge)}}));for(var _e=1,Ce=1,Re=T;Re=lf(Re);)_e++,Re.tagName===T.tagName&&Ce++;return pe.nth_child=_e,pe.nth_of_type=Ce,pe})(S,i,o,a,u));var N=(function(T){if(!no(T))return{};var O={};return Z(T.attributes,(function(J){if(J.name&&J.name.indexOf("data-ph-capture-attribute")===0){var z=J.name.replace("data-ph-capture-attribute-",""),H=J.value;z&&H&&Ks(H)&&(O[z]=H)}})),O})(S);ee(_,N)})),E)return{props:{},explicitNoCapture:E};if(o||(m[0].$el_text=Me(t,"a")||Me(t,"button")?dl(t):rr(t)),b){var I,F;m[0].attr__href=b;var P=(I=cn(b))==null?void 0:I.host,B=v==null||(F=v.location)==null?void 0:F.host;P&&B&&P!==B&&(f=b)}return{props:ee({$event_type:n.type,$ce_version:1},l?{}:{$elements:m},{$elements_chain:(g=m,(function(S){return S.map((A=>{var R,N,T="";if(A.tag_name&&(T+=A.tag_name),A.attr_class)for(var O of(A.attr_class.sort(),A.attr_class))T+="."+O.replace(/"/g,"");var J=w({},A.text?{text:A.text}:{},{"nth-child":(R=A.nth_child)!==null&&R!==void 0?R:0,"nth-of-type":(N=A.nth_of_type)!==null&&N!==void 0?N:0},A.href?{href:A.href}:{},A.attr_id?{attr_id:A.attr_id}:{},A.attributes),z={};return Or(J).sort(((H,oe)=>H[0].localeCompare(oe[0]))).forEach((H=>{var oe=H[1];return z[hl(H[0].toString())]=hl(oe.toString())})),(T+=":")+Or(z).map((H=>H[0]+'="'+H[1]+'"')).join("")})).join(";")})((function(S){return S.map((A=>{var R,N,T={text:(R=A.$el_text)==null?void 0:R.slice(0,400),tag_name:A.tag_name,href:(N=A.attr__href)==null?void 0:N.slice(0,2048),attr_class:Ep(A),attr_id:A.attr__id,nth_child:A.nth_child,nth_of_type:A.nth_of_type,attributes:{}};return Or(A).filter((O=>O[0].indexOf("attr__")===0)).forEach((O=>T.attributes[O[0]]=O[1])),T}))})(g)))},(s=m[0])!=null&&s.$el_text?{$el_text:(r=m[0])==null?void 0:r.$el_text}:{},f&&n.type==="click"?{$external_click_url:f}:{},_)}}var Ms=se("[ExceptionAutocapture]"),$l=()=>{},uf=se("[TracingHeaders]"),Lt=se("[Web Vitals]"),Rl=9e5,Tl="disabled",Nl="lazy_loading",Ls="awaiting_config",Fr="missing_config";se("[SessionRecording]"),se("[SessionRecording]");var po="[SessionRecording]",at=se(po),df=se("[Heatmaps]");function Ei(t){return te(t)&&"clientX"in t&&"clientY"in t&&he(t.clientX)&&he(t.clientY)}var Pr=se("[Product Tours]"),Si=t=>{var e;return!t.config.disable_product_tours&&!((e=t.persistence)==null||!e.get_property(Wo))},hf=["$set_once","$set"],Ze=se("[SiteApps]"),Ml="Error while initializing PostHog app with config id ";function rs(t,e,s){if(D(t))return!1;switch(s){case"exact":return t===e;case"contains":var r=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/_/g,".").replace(/%/g,".*");return new RegExp(r,"i").test(t);case"regex":try{return new RegExp(e).test(t)}catch{return!1}default:return!1}}class pf{constructor(e){this.ns=new Xo,this.ss=(s,r)=>this.os(s,r)&&this.ls(s,r)&&this.us(s,r)&&this.hs(s,r),this.os=(s,r)=>r==null||!r.event||s?.event===r?.event,this._instance=e,this.ds=new Set,this.vs=new Set}init(){var e,s;x((e=this._instance)==null?void 0:e._addCaptureHook)||(s=this._instance)==null||s._addCaptureHook(((r,n)=>{this.on(r,n)}))}register(e){var s,r;if(!x((s=this._instance)==null?void 0:s._addCaptureHook)&&(e.forEach((o=>{var a,l;(a=this.vs)==null||a.add(o),(l=o.steps)==null||l.forEach((u=>{var c;(c=this.ds)==null||c.add(u?.event||"")}))})),(r=this._instance)!=null&&r.autocapture)){var n,i=new Set;e.forEach((o=>{var a;(a=o.steps)==null||a.forEach((l=>{l!=null&&l.selector&&i.add(l?.selector)}))})),(n=this._instance)==null||n.autocapture.setElementSelectors(i)}}on(e,s){var r;s!=null&&e.length!=0&&(this.ds.has(e)||this.ds.has(s.event))&&this.vs&&((r=this.vs)==null?void 0:r.size)>0&&this.vs.forEach((n=>{this.cs(s,n)&&this.ns.emit("actionCaptured",n.name)}))}fs(e){this.onAction("actionCaptured",(s=>e(s)))}cs(e,s){if(s?.steps==null)return!1;for(var r of s.steps)if(this.ss(e,r))return!0;return!1}onAction(e,s){return this.ns.on(e,s)}ls(e,s){if(s!=null&&s.url){var r,n=e==null||(r=e.properties)==null?void 0:r.$current_url;if(!n||typeof n!="string"||!rs(n,s.url,s.url_matching||"contains"))return!1}return!0}us(e,s){return!!this.ps(e,s)&&!!this.gs(e,s)&&!!this.ys(e,s)}ps(e,s){var r;if(s==null||!s.href)return!0;var n=this.bs(e);if(n.length>0)return n.some((a=>rs(a.href,s.href,s.href_matching||"exact")));var i,o=(e==null||(r=e.properties)==null?void 0:r.$elements_chain)||"";return!!o&&rs((i=o.match(/(?::|")href="(.*?)"/))?i[1]:"",s.href,s.href_matching||"exact")}gs(e,s){var r;if(s==null||!s.text)return!0;var n=this.bs(e);if(n.length>0)return n.some((u=>rs(u.text,s.text,s.text_matching||"exact")||rs(u.$el_text,s.text,s.text_matching||"exact")));var i,o,a,l=(e==null||(r=e.properties)==null?void 0:r.$elements_chain)||"";return!!l&&(i=(function(u){for(var c,d=[],h=/(?::|")text="(.*?)"/g;!D(c=h.exec(u));)d.includes(c[1])||d.push(c[1]);return d})(l),o=s.text,a=s.text_matching||"exact",i.some((u=>rs(u,o,a))))}ys(e,s){var r,n;if(s==null||!s.selector)return!0;var i=e==null||(r=e.properties)==null?void 0:r.$element_selectors;if(i!=null&&i.includes(s.selector))return!0;var o=(e==null||(n=e.properties)==null?void 0:n.$elements_chain)||"";if(s.selector_regex&&o)try{return new RegExp(s.selector_regex).test(o)}catch{return!1}return!1}bs(e){var s;return(e==null||(s=e.properties)==null?void 0:s.$elements)==null?[]:e?.properties.$elements}hs(e,s){return s==null||!s.properties||s.properties.length===0||sd(s.properties.reduce(((r,n)=>{var i=L(n.value)?n.value.map(String):n.value!=null?[String(n.value)]:[];return r[n.key]={values:i,operator:n.operator||"exact"},r}),{}),e?.properties)}}class ff{constructor(e){var s;this._s=[],this._instance=e,this.ws=new Map,this.ks=new Map,this.xs=new Map,(s=this._instance)==null||s.onSessionId==null||s.onSessionId((r=>this.Ss(r)))}Cs(e){return!1}Ms(){return null}Ts(e){}Es(){}Is(e,s){return!!e&&sd(e.propertyFilters,s?.properties)}Ps(e,s){var r=new Map;return e.forEach((n=>{var i;(i=n.conditions)==null||(i=i[s])==null||(i=i.values)==null||i.forEach((o=>{if(o!=null&&o.name){var a=r.get(o.name)||[];a.push(n.id),r.set(o.name,a)}}))})),r}Rs(e,s,r){var n=(r===As.Activation?this.ws:this.ks).get(e),i=[];return this.As((o=>{i=o.filter((a=>n?.includes(a.id)))})),i.filter((o=>{var a,l=(a=o.conditions)==null||(a=a[r])==null||(a=a.values)==null?void 0:a.find((u=>u.name===e));return this.Is(l,s)}))}register(e){var s;x((s=this._instance)==null?void 0:s._addCaptureHook)||(this.Fs(e),this.Ls(e))}Ls(e){var s=e.filter((r=>{var n,i;return((n=r.conditions)==null?void 0:n.actions)&&((i=r.conditions)==null||(i=i.actions)==null||(i=i.values)==null?void 0:i.length)>0}));s.length!==0&&(this.Os==null&&(this.Os=new pf(this._instance),this.Os.init(),this.Os.fs((r=>{this.onAction(r)}))),s.forEach((r=>{var n,i,o,a,l;r.conditions&&(n=r.conditions)!=null&&n.actions&&(i=r.conditions)!=null&&(i=i.actions)!=null&&i.values&&((o=r.conditions)==null||(o=o.actions)==null||(o=o.values)==null?void 0:o.length)>0&&((a=this.Os)==null||a.register(r.conditions.actions.values),(l=r.conditions)==null||(l=l.actions)==null||(l=l.values)==null||l.forEach((u=>{if(u&&u.name){var c=this.xs.get(u.name);c&&c.push(r.id),this.xs.set(u.name,c||[r.id])}})))})))}Fs(e){var s,r=e.filter((i=>{var o,a;return((o=i.conditions)==null?void 0:o.events)&&((a=i.conditions)==null||(a=a.events)==null||(a=a.values)==null?void 0:a.length)>0})),n=e.filter((i=>{var o,a;return((o=i.conditions)==null?void 0:o.cancelEvents)&&((a=i.conditions)==null||(a=a.cancelEvents)==null||(a=a.values)==null?void 0:a.length)>0}));r.length===0&&n.length===0||((s=this._instance)==null||s._addCaptureHook(((i,o)=>{this.onEvent(i,o)})),this.ws=this.Ps(e,As.Activation),this.ks=this.Ps(e,As.Cancellation))}onEvent(e,s){var r,n,i=this.Ds(),o=(s==null||(r=s.properties)==null?void 0:r.$survey_id)||(s==null||(n=s.properties)==null?void 0:n.$product_tour_id);if(o&&this.getActivatedIds().includes(o)){var a=this.$s(e,o);if(a==="consume")return i.info("event consumed activated item, removing it",{event:e,itemId:o}),void this.Ns([o]);if(a==="persist")return i.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,s,As.Cancellation);l.length>0&&(i.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)){i.info("event name matched",{event:e,eventPayload:s,items:this.ws.get(e)});var u=this.Rs(e,s,As.Activation);this.Hs(u.map((c=>c.id)))}}onAction(e){this.xs.has(e)&&this.Hs(this.xs.get(e)||[])}Hs(e){var s;if(e.length!==0){var r=!((s=this._instance)==null||s.get_session_id==null||!s.get_session_id()),n=[];for(var i of e)r&&this.Cs(i)?this.qs(i)&&this.Us(i):n.push(i);n.length>0&&(this._s=[...new Set([...this._s,...n])]),this.Ds().info("updating activated items",{activatedItems:this.getActivatedIds()})}}qs(e){this._s=this._s.filter((r=>r!==e));var s=this.zs();return!s.includes(e)&&(this.Ws([...s,e]),this.Vs(),!0)}Ns(e){var s=new Set(e);this._s=this._s.filter((i=>!s.has(i)));var r=this.Zs(),n=r.filter((i=>!s.has(i)));n.length!==r.length&&(this.Ws(n),n.length===0&&this.Gs()),this.js(e)}Qs(){var e,s=this.Ms();if(!s)return{};var r=(e=this._instance)==null||(e=e.persistence)==null?void 0:e.props[s];return r&&typeof r=="object"?r:{}}Us(e){if(this.Ms()){var s=this.Qs();this.Ts(w({},s,{[e]:Date.now()}))}}js(e){if(this.Ms()){var s=this.Qs(),r={},n=!1;for(var i of Object.entries(s)){var o=i[0],a=i[1];e.includes(o)?n=!0:r[o]=a}n&&(mt(r)?this.Es():this.Ts(r))}}Ks(){this.Ms()&&this.Es()}getActivationTimestamp(e){if(this.zs().includes(e)){var s=this.Qs()[e];return he(s)?s:void 0}}Zs(){var e,s=this.Js();return((e=this._instance)==null||(e=e.persistence)==null?void 0:e.props[s])||[]}zs(){var e,s,r=this.Zs();if(r.length===0)return[];var n=(e=this._instance)==null||(e=e.persistence)==null?void 0:e.props[this.Ys()],i=(s=this._instance)==null||s.get_session_id==null?void 0:s.get_session_id();return i&&n===i?r:[]}Vs(){var e,s=(e=this._instance)==null||e.get_session_id==null?void 0:e.get_session_id();s&&this.Xs(s)}Gs(){this.ta()}Ss(e){var s,r=(s=this._instance)==null||(s=s.persistence)==null?void 0:s.props[this.Ys()];if(r&&r!==e){var n=this.Zs(),i=this.Qs();n.length>0&&(this.Ws([]),n.filter((o=>he(i[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 gf extends ff{constructor(e){super(e)}Js(){return Yi}Ys(){return Nr}Ms(){return Mr}Ts(e){var s;(s=this._instance)==null||(s=s.persistence)==null||s.register({[Mr]:e})}Es(){var e;(e=this._instance)==null||(e=e.persistence)==null||e.unregister(Mr)}Cs(e){var s,r;this.As((i=>{r=i.find((o=>o.id===e))}));var n=(s=r)==null||(s=s.appearance)==null?void 0:s.surveyPopupDelaySeconds;return he(n)&&n>0}ra(){return ft.SHOWN}As(e){var s;(s=this._instance)==null||s.getSurveys(e)}Bs(e){var s;(s=this._instance)==null||s.cancelPendingSurvey(e)}Ds(){return q}Ws(e){var s;(s=this._instance)==null||(s=s.persistence)==null||s.register({[Yi]:e})}Xs(e){var s;(s=this._instance)==null||(s=s.persistence)==null||s.register({[Nr]:e})}ta(){var e;(e=this._instance)==null||(e=e.persistence)==null||e.unregister(Nr)}ea(){return!1}$s(e,s){var r;this.As((i=>{r=i.find((o=>o.id===s))}));var n=!r||(function(i){var o;return rd(i)&&!((o=i.conditions)==null||(o=o.events)==null||!o.repeatedActivation)||i.schedule==="always"})(r);return n?e===ft.SHOWN?"consume":"ignore":e===ft.SHOWN?"persist":e===ft.DISMISSED||e===ft.SENT?"consume":"ignore"}getSurveys(){return this.getActivatedIds()}getEventToSurveys(){return this.getEventToItemsMap()}}var Ar="SDK is not enabled or survey functionality is not yet loaded",Ll="Disabled. Not loading surveys.",mf=v!=null&&v.location?un(v.location.hash,"__posthog")||un(location.hash,"state"):null,Ol="_postHogToolbarParams",Dl=se("[Toolbar]"),Bl=se("[FeatureFlags]");class vf{constructor(e,s){s===void 0&&(s=!1),this.na=!1,this.update(e,s)}update(e,s){this.sa=((r,n)=>{var i,o,a,l;return{bootstrap:{featureFlags:(i=r.bootstrap)==null?void 0:i.featureFlags,featureFlagPayloads:(o=r.bootstrap)==null?void 0:o.featureFlagPayloads},remoteRequestsDisabled:n,featureFlagsDisabled:!!r.advanced_disable_feature_flags,onlyEvaluateSurveyFeatureFlags:!!r.advanced_only_evaluate_survey_feature_flags,deduplicateCallsPerSession:!!r.advanced_feature_flags_dedup_per_session,cacheTtlMs:r.feature_flag_cache_ttl_ms,requestTimeoutMs:r.feature_flag_request_timeout_ms,compression:r.disable_compression?"none":"base64",evaluationContexts:(a=(l=r.evaluation_contexts)!==null&&l!==void 0?l:r.evaluation_environments)!==null&&a!==void 0?a:[],flagKeys:L(r.flag_keys)?r.flag_keys:void 0}})(e,s),!e.evaluation_environments||e.evaluation_contexts||this.na||(Bl.warn("evaluation_environments is deprecated. Use evaluation_contexts instead. evaluation_environments will be removed in a future version."),this.na=!0),x(e.flag_keys)||L(e.flag_keys)||Bl.error("Invalid flag_keys found:",e.flag_keys,"Expected array of non-empty strings")}get(){return this.sa}}var jl=se("[FeatureFlags]"),Ot=se("[FeatureFlags]",{debugEnabled:!0}),xi=`" failed. Feature flags didn't load in time.`,Ul="connection_error",Hl=t=>{for(var e={},s=0;t.length>s;s++)e[t[s]]=!0;return e},Wl=t=>{var e={};for(var s of Or(t||{})){var r=s[1];r&&(e[s[0]]=r)}return e},Xe=se("[Error tracking]"),zl="Refusing to render web experiment since the viewer is a likely bot",_f={icontains:(t,e)=>e.toLowerCase().indexOf(t.toLowerCase())>-1,not_icontains:(t,e)=>e.toLowerCase().indexOf(t.toLowerCase())===-1,regex:(t,e)=>pn(e,t),not_regex:(t,e)=>!pn(e,t),exact:(t,e)=>e===t,is_not:(t,e)=>e!==t};class ye{get Ne(){return this._instance.config}constructor(e){var s=this;this.getWebExperimentsAndEvaluateDisplayLogic=function(r){r===void 0&&(r=!1),s.getWebExperiments((n=>{ye.aa("retrieved web experiments from the server"),s.oa=new Map,n.forEach((i=>{if(i.feature_flag_key){var o;s.oa&&(ye.aa("setting flag key ",i.feature_flag_key," to web experiment ",i),(o=s.oa)==null||o.set(i.feature_flag_key,i));var a=s._instance.getFeatureFlag(i.feature_flag_key);W(a)&&i.variants[a]&&s.la(i.name,a,i.variants[a].transforms)}else if(i.variants)for(var l in i.variants){var u=i.variants[l];ye.ua(u,s._instance)&&s.la(i.name,l,u.transforms)}}))}),r)},this._instance=e,this._instance.onFeatureFlags((r=>{this.onFeatureFlags(r)}))}initialize(){}onFeatureFlags(e){if(this._is_bot())ye.aa(zl);else if(!this.Ne.disable_web_experiments){if(D(this.oa))return this.oa=new Map,this.loadIfEnabled(),void this.previewWebExperiment();ye.aa("applying feature flags",e),e.forEach((s=>{var r;if(this.oa&&(r=this.oa)!=null&&r.has(s)){var n,i=this._instance.getFeatureFlag(s),o=(n=this.oa)==null?void 0:n.get(s);i&&o!=null&&o.variants[i]&&this.la(o.name,i,o.variants[i].transforms)}}))}}previewWebExperiment(){var e=ye.getWindowLocation();if(e!=null&&e.search){var s=ms(e?.search,"__experiment_id"),r=ms(e?.search,"__experiment_variant");s&&r&&(ye.aa("previewing web experiments "+s+" && "+r),this.getWebExperiments((n=>{this.ha(parseInt(s),r,n)}),!1,!0))}}loadIfEnabled(){this.Ne.disable_web_experiments||this.getWebExperimentsAndEvaluateDisplayLogic()}getWebExperiments(e,s,r){if(this.Ne.disable_web_experiments&&!r)return e([]);var n=this._instance.get_property("$web_experiments");if(n&&!s)return e(n);this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/web_experiments/?token="+this.Ne.token),method:"GET",timestampMode:"query",callback:i=>e(i.statusCode===200&&i.json&&i.json.experiments||[])})}ha(e,s,r){var n=r.filter((i=>i.id===e));n&&n.length>0&&(ye.aa("Previewing web experiment ["+n[0].name+"] with variant ["+s+"]"),this.la(n[0].name,s,n[0].variants[s].transforms))}static ua(e,s){return!D(e.conditions)&&ye.da(e,s)&&ye.va(e)}static da(e,s){var r;if(D(e.conditions)||D((r=e.conditions)==null?void 0:r.url))return!0;var n=ye.getWindowLocation();if(n){var i,o,a,l=yu(s,n.href);return(i=e.conditions)==null||!i.url||_f[(o=(a=e.conditions)==null?void 0:a.urlMatchType)!==null&&o!==void 0?o:"icontains"](e.conditions.url,l)}return!1}static getWindowLocation(){return v?.location}static va(e){var s;if(D(e.conditions)||D((s=e.conditions)==null?void 0:s.utm))return!0;var r=Nu();if(r.utm_source){var n,i,o,a,l,u,c,d,h=(n=e.conditions)==null||(n=n.utm)==null||!n.utm_campaign||((i=e.conditions)==null||(i=i.utm)==null?void 0:i.utm_campaign)==r.utm_campaign,p=(o=e.conditions)==null||(o=o.utm)==null||!o.utm_source||((a=e.conditions)==null||(a=a.utm)==null?void 0:a.utm_source)==r.utm_source,f=(l=e.conditions)==null||(l=l.utm)==null||!l.utm_medium||((u=e.conditions)==null||(u=u.utm)==null?void 0:u.utm_medium)==r.utm_medium,g=(c=e.conditions)==null||(c=c.utm)==null||!c.utm_term||((d=e.conditions)==null||(d=d.utm)==null?void 0:d.utm_term)==r.utm_term;return h&&f&&g&&p}return!1}static aa(e){for(var s=arguments.length,r=new Array(s>1?s-1:0),n=1;s>n;n++)r[n-1]=arguments[n];k.info("[WebExperiments] "+e,r)}la(e,s,r){this._is_bot()?ye.aa(zl):s!=="control"?r.forEach((n=>{if(n.selector){var i;ye.aa("applying transform of variant "+s+" for experiment "+e+" ",n);var o=(i=document)==null?void 0:i.querySelectorAll(n.selector);o?.forEach((a=>{var l=a;n.html&&(l.innerHTML=n.html),n.css&&l.setAttribute("style",n.css)}))}})):ye.aa("Control variants leave the page unmodified.")}_is_bot(){return ke&&this._instance?Qu(ke,this.Ne.custom_blocked_useragents):void 0}}var Ue=se("[Conversations]"),Dt="Conversations not available yet.",ql="console",ld="__posthogHandledLogsRequestError",ki=(t,e)=>{var s=t instanceof Error?t:new Error(e);return s[ld]=!0,s},Vl=t=>!!t&&typeof t=="object"&&t[ld]===!0,Rn={featureFlags:class{constructor(t){this.name="featureFlags",this.ca=!1,this.featureFlagEventHandlers=[],this.rt=jl,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 vf(t.config,t.Qi()),this.Ta=this.Ea)}updateConfig(t,e){var s;(s=this.Ea)==null||s.update(t,e)}setup(t){return this.Ia=t,this.rt=t.logger.createLogger("[FeatureFlags]"),s=()=>{this.Ia===t&&(this.Ia=void 0,this.nn=t,this.Pa(t))},(e=t.kv.initialize())!=null&&e.then?e.then(s):s();var e,s}Pa(t){if(this.nn===t)return v&&ne(v,"online",this.Ca),this.Ra=t.registerDynamicEventProperties((()=>this.Aa()?this.fa:this.pa)),this.Fa(),this.initialize()}destroy(){v?.removeEventListener("online",this.Ca)}dispose(){var t;this.ba++,this.wa=!1,this.Ia=void 0,this.nn&&(this.La(),(t=this.Ra)==null||t.dispose(),this.Ra=void 0,this.ga=[],v?.removeEventListener("online",this.Ca),this.nn=void 0)}get Ne(){return this.Ta.get()}Oa(t){var e;return(e=this.nn)==null?void 0:e.kv.get(t)}F(t){this.Da((()=>{var e;return(e=this.nn)==null?void 0:e.kv.set(t)}))}q(t){this.Da((()=>{var e;return(e=this.nn)==null?void 0:e.kv.remove(t)}))}Da(t){try{t()}catch(e){this.rt.error("Failed to update feature flag persistence",e)}}Fa(){var t={};for(var e of[Us,Hs,Tr,et]){var s=this.Oa(e);x(s)||(t[e]=s)}this.fa=t;var r=w({},t),n=this.Oa(Bt);if(n)for(var i of Object.entries(n))r["$feature/"+i[0]]=i[1];this.pa=r}Aa(){var t=this.Ne.cacheTtlMs;if(!t||0>=t)return!1;var e=this.Oa(Gs);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 s=e&&typeof e=="string"&&e.trim().length>0;return s||this.rt.error("Invalid evaluation context found:",e,"Expected non-empty string"),s})):[]}qa(){var t=this.Ne.flagKeys;if(!x(t))return t.filter((e=>{var s=e&&typeof e=="string"&&e.trim().length>0;return s||this.rt.error("Invalid flag key found:",e,"Expected non-empty string"),s}))}initialize(){var t,e,s=this.Ne,r=(t=(e=s.bootstrap)==null?void 0:e.featureFlags)!==null&&t!==void 0?t:{};if(Object.keys(r).length){var n,i,o=(n=(i=s.bootstrap)==null?void 0:i.featureFlagPayloads)!==null&&n!==void 0?n:{},a=Object.keys(r).filter((u=>!!r[u])).reduce(((u,c)=>(u[c]=r[c]||!1,u)),{}),l=Object.keys(o).filter((u=>a[u])).reduce(((u,c)=>(o[c]&&(u[c]=o[c]),u)),{});return this.ja({featureFlags:a,featureFlagPayloads:l})}}updateFlags(t,e,s){var r,n,i=s!=null&&s.merge&&(r=this.Oa(Bt))!==null&&r!==void 0?r:{},o=s!=null&&s.merge&&(n=this.Oa(Hs))!==null&&n!==void 0?n:{},a=w({},i,t),l=w({},o,e),u={};for(var c of Object.entries(a)){var d=c[0],h=c[1];u[d]={key:d,enabled:Da(h),variant:Ba(h),reason:void 0,metadata:x(l?.[d])?void 0:{id:0,version:void 0,description:void 0,payload:l[d]}}}this.ja({flags:u})}get hasLoadedFlags(){return this.ma}getFlags(){return Object.keys(this.getFlagVariants())}getFlagsWithDetails(){var t=this.Oa(Ki),e=this.Oa(et),s=this.Oa(jt);if(!s&&!e)return t||{};var r=ee({},t||{}),n=[...new Set([...Object.keys(s||{}),...Object.keys(e||{})])];for(var i of n){var o,a,l=r[i],u=e?.[i],c=x(u)?(o=l?.enabled)!==null&&o!==void 0&&o:!!u,d=x(u)?l?.variant:typeof u=="string"?u:void 0,h=s?.[i],p=w({},l,{enabled:c,variant:c?d??l?.variant:void 0});c!==l?.enabled&&(p.original_enabled=l?.enabled),d!==l?.variant&&(p.original_variant=l?.variant),h&&(p.metadata=w({},l?.metadata,{payload:h,original_payload:l==null||(a=l.metadata)==null?void 0:a.payload})),r[i]=p}return this.ca||(this.rt.warn(" Overriding feature flag details!",{flagDetails:t,overriddenPayloads:s,finalDetails:r}),this.ca=!0),r}getAllFeatureFlags(){var t=this.getFlagVariants(),e=this.getFlagPayloads();return Object.keys(t).map((s=>{var r=t[s];return{key:s,enabled:Da(r),variant:Ba(r),payload:Oa(e[s])}}))}getFlagVariants(){var t=this.Oa(Bt),e=this.Oa(et);if(!e)return t||{};for(var s=ee({},t||{}),r=Object.keys(e),n=0;r.length>n;n++)s[r[n]]=e[r[n]];return this.ca||(this.rt.warn(" Overriding feature flags!",{enabledFlags:t,overriddenFlags:e,finalFlags:s}),this.ca=!0),s}getFlagPayloads(){var t=this.Oa(Hs),e=this.Oa(jt);if(!e)return t||{};for(var s=ee({},t||{}),r=Object.keys(e),n=0;r.length>n;n++)s[r[n]]=e[r[n]];return this.ca||(this.rt.warn(" Overriding feature flag payloads!",{flagPayloads:t,overriddenPayloads:e,finalPayloads:s}),this.ca=!0),s}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(Wt)}Ha(t){this.La();var e=this.nn;if(e&&!this.Ne.remoteRequestsDisabled&&!this.Ma())if(this.ya)this.wa=!0;else{var s={token:e.projectToken,distinct_id:e.distinctId,groups:e.groups,$anon_distinct_id:this.$anon_distinct_id,person_properties:w({},e.initialPersonProperties,this.Oa(ct)||{},{$lib:e.library.name,$lib_version:e.library.version}),group_properties:this.Oa(Ut),timezone:ju()};x(e.deviceId)||(s.$device_id=e.deviceId),(t!=null&&t.disableFlags||this.Ne.featureFlagsDisabled)&&(s.disable_flags=!0);var r=this.Na();r.length&&(s.evaluation_contexts=r);var n=this.qa();x(n)||(s.flag_keys=n);var i=this.Ne.onlyEvaluateSurveyFeatureFlags,o="/flags/?v=2"+(i?"&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({[Lr]:[Ul]}),this.rt.error("Feature flag request failed",c)),l()};try{e.sendRequest(o,{target:"flags",method:"POST",body:s,compression:this.Ne.compression==="base64"?xe.Base64:void 0,sentAt:"body",timeoutMs:this.Ne.requestTimeoutMs}).then((c=>{var d,h,p=(d=c.json)!==null&&d!==void 0?d:{},f=c.statusCode!==200;if(this.ya=!1,a===this.ba){if(this.Ua(c.statusCode),f||this.wa||(this.$anon_distinct_id=void 0),!s.disable_flags||this.wa){this.ka=!f;var g=[];c.error?g.push(c.error instanceof Error&&c.error.name==="AbortError"?"timeout":c.error instanceof Error?Ul:"unknown_error"):c.statusCode!==200&&g.push("api_error_"+c.statusCode),p.errorsWhileComputingFlags&&g.push("errors_while_computing_flags");var m=!((h=p.quotaLimited)==null||!h.includes("feature_flags"));m&&g.push("quota_limited"),this.F({[Lr]: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."):s.disable_flags||this.ja(p,f,{partialResponse:i}),l()}}else l()})).catch(u)}catch(c){u(c)}}}Ma(){return Ru(this.Sa,3)}Ua(t){this.Sa=Tu(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 s;if(e===void 0&&(e={}),!e.fresh||this.ka)if(this.ma||this.getFlags()&&this.getFlags().length>0){if(!this.$a()){var r=this.getFeatureFlagResult(t,e);return(s=r?.variant)!==null&&s!==void 0?s:r?.enabled}}else this.rt.warn('getFeatureFlag for key "'+t+xi)}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 s,r=this.getFlagVariants(),n=t in r,i=r[t],o=this.getFlagPayloads()[t],a=String(i),l=this.Oa(Tr)||void 0,u=this.Oa(Gs)||void 0,c=this.Oa(Wt)||{};if(this.Ne.deduplicateCallsPerSession){var d,h=(d=this.nn)==null?void 0:d.session.sessionId,p=this.Oa(zs);h&&h!==p&&(c={},s=h)}if(e.send_event||!("send_event"in e))if(t in c&&c[t].includes(a))s&&this.F({[Wt]:c,[zs]:s});else{var f,g,m,_,b,E,I,F,P,B;L(c[t])?c[t].push(a):c[t]=[a],this.F(w({[Wt]:c},s?{[zs]:s}:{}));var S=this.getFeatureFlagDetails(t),A=[...(f=this.Oa(Lr))!==null&&f!==void 0?f:[]];x(i)&&A.push("flag_missing");var R={$feature_flag:t,$feature_flag_response:i,$feature_flag_payload:o||null,$feature_flag_request_id:l,$feature_flag_evaluated_at:u,$feature_flag_bootstrapped_response:((g=this.Ne.bootstrap)==null||(g=g.featureFlags)==null?void 0:g[t])||null,$feature_flag_bootstrapped_payload:((m=this.Ne.bootstrap)==null||(m=m.featureFlagPayloads)==null?void 0:m[t])||null,$used_bootstrap_value:!this.ka};x(S==null||(_=S.metadata)==null?void 0:_.has_experiment)||(R.$feature_flag_has_experiment=S.metadata.has_experiment),x(S==null||(b=S.metadata)==null?void 0:b.version)||(R.$feature_flag_version=S.metadata.version);var N,T=(E=S==null||(I=S.reason)==null?void 0:I.description)!==null&&E!==void 0?E:S==null||(F=S.reason)==null?void 0:F.code;T&&(R.$feature_flag_reason=T),S!=null&&(P=S.metadata)!=null&&P.id&&(R.$feature_flag_id=S.metadata.id),x(S?.original_variant)&&x(S?.original_enabled)||(R.$feature_flag_original_response=x(S.original_variant)?S.original_enabled:S.original_variant),S!=null&&(B=S.metadata)!=null&&B.original_payload&&(R.$feature_flag_original_payload=S==null||(N=S.metadata)==null?void 0:N.original_payload),A.length&&(R.$feature_flag_error=A.join(",")),this.za(R)}else s&&this.F({[Wt]:c,[zs]:s});if(n)return{key:t,enabled:!!i,variant:typeof i=="string"?i:void 0,payload:Oa(o)}}}else this.rt.warn('getFeatureFlagResult for key "'+t+xi)}za(t){try{var e;(e=this.nn)==null||e.capture("$feature_flag_called",t).catch((s=>{this.rt.error("Failed to capture feature flag call",s)}))}catch(s){this.rt.error("Failed to capture feature flag call",s)}}getRemoteConfigPayload(t,e){this.Wa(t,e)}Wa(t,e){var s=this;return X((function*(){var r=s.nn;if(r){var n={distinct_id:r.distinctId,token:r.projectToken,person_properties:{$lib:r.library.name,$lib_version:r.library.version}},i=s.Na();i.length&&(n.evaluation_contexts=i);var o,a=s.qa();x(a)||(n.flag_keys=a);try{var l,u=(l=(yield r.sendRequest("/flags/?v=2",{target:"flags",method:"POST",body:n,compression:s.Ne.compression==="base64"?xe.Base64:void 0,sentAt:"body",timeoutMs:s.Ne.requestTimeoutMs})).json)==null?void 0:l.featureFlagPayloads;o=u?.[t]||void 0}catch(c){return void s.rt.error("Remote config feature flag request failed",c)}try{e(o)}catch(c){s.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+xi),e.defaultValue;var s=this.getFeatureFlag(t,e);return x(s)?e.defaultValue:!!s}addFeatureFlagsHandler(t){this.featureFlagEventHandlers.push(t)}removeFeatureFlagsHandler(t){this.featureFlagEventHandlers=this.featureFlagEventHandlers.filter((e=>e!==t))}receivedFeatureFlags(t,e,s){this.ja(t,e,s)}ja(t,e,s){if(this.nn){this.ma=!0;var r=(function(n,i,o,a,l,u){i===void 0&&(i={}),o===void 0&&(o={}),a===void 0&&(a={}),u===void 0&&(u=jl);var c=((P,B)=>{var S=P.flags;return S?w({},P,{featureFlags:Object.fromEntries(Object.keys(S).map((A=>{var R;return[A,(R=S[A].variant)!==null&&R!==void 0?R:S[A].enabled]}))),featureFlagPayloads:Object.fromEntries(Object.keys(S).filter((A=>S[A].enabled)).filter((A=>{var R;return(R=S[A].metadata)==null?void 0:R.payload})).map((A=>{var R;return[A,(R=S[A].metadata)==null?void 0:R.payload]})))}):(P.featureFlags&&B.warn("Using an older version of the feature flags endpoint. Please upgrade your PostHog server to the latest version"),P)})(n,u),d=c.flags,h=c.featureFlags,p=c.featureFlagPayloads;if(h){var f=n.requestId,g=n.evaluatedAt;if(L(h)){u.warn("v1 of the feature flags endpoint is deprecated. Please use the latest version.");var m={};if(h)for(var _=0;h.length>_;_++)m[h[_]]=!0;return{[Us]:h,[Bt]:m,[en]:!1}}var b=h,E=p,I=d;if(l!=null&&l.partialResponse)b=w({},i,b),E=w({},o,E),I=w({},a,I);else if(n.errorsWhileComputingFlags)if(d){var F=new Set(Object.keys(d).filter((P=>{var B;return!((B=d[P])!=null&&B.failed)})));b=w({},i,Object.fromEntries(Object.entries(b).filter((P=>F.has(P[0]))))),E=w({},o,Object.fromEntries(Object.entries(E||{}).filter((P=>F.has(P[0]))))),I=w({},a,Object.fromEntries(Object.entries(I||{}).filter((P=>F.has(P[0])))))}else b=w({},i,b),E=w({},o,E),I=w({},a,I);return w({[Us]:Object.keys(Wl(b)),[Bt]:b||{},[Hs]:E||{},[Ki]:I||{},[en]:n.minimalFlagCalledEvents===!0},f?{[Tr]:f}:{},g?{[Gs]:g}:{})}})(t,this.getFlagVariants(),this.getFlagPayloads(),this.getFlagsWithDetails(),s,this.rt);r&&this.F(r),e||(this.xa=!1),this.Va(e)}}override(t,e){e===void 0&&(e=!1),this.rt.warn("override is deprecated. Please use overrideFeatureFlags instead."),this.overrideFeatureFlags({flags:t,suppressWarning:e})}overrideFeatureFlags(t){this.Za(t)}Za(t){if(this.nn){if(t===!1)return this.q([et,jt]),this.Va(),void Ot.info("All overrides cleared");if(L(t))return this.F({[et]:Hl(t)}),this.Va(),void Ot.info("Flag overrides set",{flags:t});if(t&&typeof t=="object"&&("flags"in t||"payloads"in t)){var e,s=t;this.ca=!!((e=s.suppressWarning)!==null&&e!==void 0&&e);var r={},n=s.flags,i=s.payloads;return n&&(r[et]=L(n)?Hl(n):n),i&&(r[jt]=i),Object.keys(r).length&&this.F(r),n===!1&&i===!1?this.q([et,jt]):n===!1?this.q(et):i===!1&&this.q(jt),this.Va(),n===!1?Ot.info("Flag overrides cleared"):n&&Ot.info("Flag overrides set",{flags:n}),void(i===!1?Ot.info("Payload overrides cleared"):i&&Ot.info("Payload overrides set",{payloads:i}))}if(t&&typeof t=="object")return this.F({[et]:t}),this.Va(),void Ot.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(),s=e.flags,r=e.flagVariants;try{t(s,r)}catch(n){this.rt.error("Error while running feature flags callback",n)}}return()=>this.removeFeatureFlagsHandler(t)}updateEarlyAccessFeatureEnrollment(t,e,s){var r=(this.Oa(Rr)||[]).find((l=>l.flagKey===t)),n={["$feature_enrollment/"+t]:e},i={$feature_flag:t,$feature_enrollment:e,$set:n};r&&(i.$early_access_feature_name=r.name),s&&(i.$feature_enrollment_stage=s);var o=w({},this.getFlagVariants(),{[t]:e});this.F({[Us]:Object.keys(Wl(o)),[Bt]:o,[ct]:w({},this.Oa(ct)||{},n)}),this.Va();try{var a;(a=this.nn)==null||a.capture("$feature_enrollment_update",i).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,s){e===void 0&&(e=!1);var r=this.Oa(Rr);!r||e?this.Qa(t,s):t(r)}Qa(t,e){var s=this;return X((function*(){var r=s.nn;if(r){var n,i=e?"&"+e.map((a=>"stage="+a)).join("&"):"";try{var o=yield r.sendRequest("/api/early_access_features/?token="+r.projectToken+i,{target:"api",method:"GET",sentAt:"query"});if(!o.json)return;s.F({[Rr]:n=o.json.earlyAccessFeatures})}catch(a){return void s.rt.error("Early access feature request failed",a)}try{t(n)}catch(a){s.rt.error("Early access feature callback failed",a)}}}))()}Ga(){var t=this.getFlags(),e=this.getFlagVariants();return{flags:t.filter((s=>e[s])),flagVariants:Object.keys(e).filter((s=>e[s])).reduce(((s,r)=>(s[r]=e[r],s)),{})}}Va(t){this.Fa();var e=this.Ga(),s=e.flags,r=e.flagVariants;this.featureFlagEventHandlers.forEach((n=>{try{n(s,r,{errorsLoading:t})}catch(i){this.rt.error("Error while running feature flags callback",i)}}))}setPersonPropertiesForFlags(t,e){e===void 0&&(e=!0),this.Ka(t,e)}Ka(t,e){e===void 0&&(e=!0);var s=this.Oa(ct)||{},r=t?.$set||(t!=null&&t.$set_once?{}:t),n=t?.$set_once,i={};if(n)for(var o in n)({}).hasOwnProperty.call(n,o)&&(o in s||(i[o]=n[o]));this.F({[ct]:w({},s,i,r)}),e&&this.reloadFeatureFlags()}unsetPersonPropertiesForFlags(t,e){e===void 0&&(e=!0);var s=w({},this.Oa(ct)||{});t.forEach((r=>{delete s[r]})),this.F({[ct]:s}),e&&this.reloadFeatureFlags()}resetPersonPropertiesForFlags(t){t===void 0&&(t=!0),this.q(ct),t&&this.reloadFeatureFlags()}setGroupPropertiesForFlags(t,e){e===void 0&&(e=!0);var s=this.Oa(Ut)||{},r=w({},s);for(var n of Object.keys(t))r[n]=w({},s[n],t[n]);this.F({[Ut]:r}),e&&this.reloadFeatureFlags()}resetGroupPropertiesForFlags(t){if(t){var e=this.Oa(Ut)||{};this.F({[Ut]:w({},e,{[t]:{}})})}else this.q(Ut)}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}}},yf={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===Ls||this.Ya===Fr?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=Tl,this.Xa=void 0,this.eo=!1,this.io=(()=>{var e;if(C==null||!C.visibilityState||C.visibilityState==="visible")return!0;var s=v==null||(e=v.performance)==null||e.getEntriesByType==null?void 0:e.getEntriesByType("visibility-state");return!(s!=null&&s.length)||s.some((r=>r.name==="visible"))})(),this.Ie=()=>{var e;C?.visibilityState==="visible"&&(this.io=!0,(e=this.Ja)==null||e.setDocumentWasEverVisible==null||e.setDocumentWasEverVisible(!0))},this._instance=t,!this._instance.sessionManager)throw at.error("started without valid sessionManager"),new Error(po+" started without valid sessionManager. This is a bug.");if(this.Ne.cookieless_mode===ht)throw new Error(po+' cannot be used with cookieless_mode="always"');C!=null&&C.addEventListener&&ne(C,"visibilitychange",this.Ie)}initialize(){this.startIfEnabledOrStop()}dispose(){this.eo=!0,C==null||C.removeEventListener==null||C.removeEventListener("visibilitychange",this.Ie),this.stopRecording()}get ro(){var t,e=!((t=this._instance.get_property(qt))==null||!t.enabled),s=!this.Ne.disable_session_recording,r=this.Ne.disable_session_recording||this._instance.consent.isOptedOut();return v&&e&&s&&!r}startIfEnabledOrStop(t){var e;if(!(this.eo||this.ro&&(e=this.Ja)!=null&&e.isStarted)){var s=!x(Object.assign)&&!x(Array.from);this.ro&&s?(this.no(t),at.info("starting")):(this.Ya=Tl,this.stopRecording())}}no(t){var e,s,r;this.ro&&(this.Ya!==Ls&&this.Ya!==Fr&&(this.Ya=Nl),$!=null&&(e=$.__PosthogExtensions__)!=null&&(e=e.rrweb)!=null&&e.record&&(s=$.__PosthogExtensions__)!=null&&s.initSessionRecording?this.so(t):(r=$.__PosthogExtensions__)==null||r.loadExternalDependency==null||r.loadExternalDependency(this._instance,this.ao,(n=>{if(n)return at.error("could not load recorder",n);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(zo),(e=this.Mr)==null||e.unregister(lu)}uo(t,e){if(D(t))return null;var s,r=he(t)?t:parseFloat(t);return typeof(s=r)!="number"||!Number.isFinite(s)||0>s||s>1?(at.warn(e+" must be between 0 and 1. Ignoring invalid value:",t),null):r}ho(t){if(this.Mr){var e,s,r=this.Mr,n=()=>{var i,o=t.sessionRecording===!1?void 0:t.sessionRecording,a=this.uo((i=this.Ne.session_recording)==null?void 0:i.sampleRate,"session_recording.sampleRate"),l=this.uo(o?.sampleRate,"remote config sampleRate"),u=a??l;D(u)&&this.lo();var c=o?.minimumDurationMilliseconds;r.register({[qt]:w({cache_timestamp:Date.now(),enabled:!!o},o,{networkPayloadCapture:w({capturePerformance:t.capturePerformance},o?.networkPayloadCapture),canvasRecording:{enabled:o?.recordCanvas,fps:o?.canvasFps,quality:o?.canvasQuality},sampleRate:u,minimumDurationMilliseconds:x(c)?null:c,endpoint:o?.endpoint,triggerMatchType:o?.triggerMatchType,masking:o?.masking,urlTriggers:o?.urlTriggers,version:o?.version,triggerGroups:o?.triggerGroups})})};n(),(e=this.Xa)==null||e.call(this),this.Xa=(s=this._instance.sessionManager)==null?void 0:s.onSessionId(n)}}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===Ls&&(this.Ya=Fr,at.warn("config refresh failed, recording will not start until page reload")),void this.startIfEnabledOrStop())}log(t,e){var s;e===void 0&&(e="log"),(s=this.Ja)!=null&&s.log?this.Ja.log(t,e):at.warn("log called before recorder was ready")}get ao(){var t,e,s=(t=this._instance)==null||(t=t.persistence)==null?void 0:t.get_property(qt);return(s==null||(e=s.scriptConfig)==null?void 0:e.script)||"lazy-recorder"}do(){var t,e=this._instance.get_property(qt);if(!e)return!1;try{t=typeof e=="object"?e:JSON.parse(e)}catch(s){return at.warn("persisted remote config for session recording is invalid and will be ignored",s),!1}return!D(t.cache_timestamp)&&36e5>=Date.now()-t.cache_timestamp}so(t){var e,s,r;if(!this.eo){if((e=$.__PosthogExtensions__)==null||!e.initSessionRecording)return at.warn("Called on script loaded before session recording is available. This can be caused by adblockers."),void this._instance.register_for_session({[mu]:!0});var n;if(this.Ja||(this.Ja=(n=$.__PosthogExtensions__)==null?void 0:n.initSessionRecording(this._instance,this.io),this.Ja._forceAllowLocalhostNetworkCapture=this._forceAllowLocalhostNetworkCapture),!this.do())return this.Ya===Fr||this.Ya===Ls?void 0:(this.Ya=Ls,at.info("persisted remote config is stale, requesting fresh config before starting"),void new Uu(this._instance).load());this.Ya=Nl,(s=(r=this.Ja).setDocumentWasEverVisible)==null||s.call(r,this.io),this.Ja.start(t)}}onRRwebEmit(t){var e;(e=this.Ja)==null||e.onRRwebEmit==null||e.onRRwebEmit(t)}overrideLinkedFlag(){var t,e;this.Ja||(e=this.Mr)==null||e.register({[uu]:!0}),(t=this.Ja)==null||t.overrideLinkedFlag()}overrideSampling(){var t,e;this.Ja||(e=this.Mr)==null||e.register({[cu]:!0}),(t=this.Ja)==null||t.overrideSampling()}overrideTrigger(t){var e,s;this.Ja||(s=this.Mr)==null||s.register({[t==="url"?du:hu]:!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 s;return!((s=this.Ja)==null||!s.tryAddCustomEvent(t,e))}}},wf={autocapture:class{constructor(t){this.vo=!1,this.co=null,this.fo=!1,this.po=!1,this.instance=t,this.rageclicks=new Al(t.config.rageclick),this.mo=null}initialize(){this.startIfEnabled()}get Ne(){var t,e,s=te(this.instance.config.autocapture)?this.instance.config.autocapture:{};return s.url_allowlist=(t=s.url_allowlist)==null?void 0:t.map((r=>new RegExp(r))),s.url_ignorelist=(e=s.url_ignorelist)==null?void 0:e.map((r=>new RegExp(r))),s}yo(){if(this.isBrowserSupported()){if(v&&C){var t=s=>{s=s||v?.event;try{this.bo(s)}catch(r){wi.error("Failed to capture event",r)}};if(ne(C,"submit",t,{capture:!0}),ne(C,"change",t,{capture:!0}),ne(C,"click",t,{capture:!0}),this.Ne.capture_copied_text){var e=s=>{s=s||v?.event;try{this.bo(s,yi)}catch(r){wi.error("Failed to capture copy/cut event",r)}};ne(C,"copy",e,{capture:!0}),ne(C,"cut",e,{capture:!0})}}}else wi.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 s=e.autocapture_opt_out;Ke(s)&&(this.instance.persistence&&this.instance.persistence.register({[Ui]:s}),this.co=s),this.startIfEnabled()}else this.startIfEnabled()}setElementSelectors(t){this.mo=t}getElementSelectors(t){var e,s=[];return(e=this.mo)==null||e.forEach((r=>{var n=C?.querySelectorAll(r);n?.forEach((i=>{t===i&&s.push(r)}))})),s}get isEnabled(){var t,e,s=(t=this.instance.persistence)==null?void 0:t.props[Ui],r=this.co,n=this.instance.Qi()&&!this.fo;if($e(r)&&!Ke(s)&&!n)return!1;var i=(e=this.co)!==null&&e!==void 0?e:!!s;return!!this.instance.config.autocapture&&!i}bo(t,e){if(e===void 0&&(e="$autocapture"),this.isEnabled){var s,r=ai(t);bu(r)&&(r=r.parentNode||null),e==="$autocapture"&&t.type==="click"&&t instanceof MouseEvent&&this.instance.config.rageclick&&(s=this.rageclicks)!=null&&s.isRageClick(t.clientX,t.clientY,t.timeStamp||new Date().getTime())&&ol(r,this.instance.config.rageclick)&&this.bo(t,"$rageclick");var n=e===yi;if(r&&(function(d,h,p,f,g,m){var _;if(!v||Jo(d)||p!=null&&p.url_allowlist&&!rl(p.url_allowlist,m)||p!=null&&p.url_ignorelist&&rl(p.url_ignorelist,m))return!1;if(p!=null&&p.dom_event_allowlist){var b=p.dom_event_allowlist;if(b&&!b.some((S=>h.type===S)))return!1}var E=Cu(d,f),I=E.parentIsUsefulElement,F=E.targetElementList;if(!(function(S,A){var R=A?.element_allowlist;if(x(R))return!0;var N,T=function(J){if(R.some((z=>J.tagName.toLowerCase()===z)))return{v:!0}};for(var O of S)if(N=T(O))return N.v;return!1})(F,p)||!ro(F,p?.css_selector_allowlist)||ro(F,(_=p?.css_selector_ignorelist)!==null&&_!==void 0?_:mp))return!1;try{var P=v.getComputedStyle(d);if(P&&P.getPropertyValue("cursor")==="pointer"&&h.type==="click")return!0}catch{}var B=d.tagName.toLowerCase();switch(B){case"html":return!1;case"form":return(g||["submit"]).indexOf(h.type)>=0;case"input":case"select":case"textarea":return(g||["change","click"]).indexOf(h.type)>=0;default:return I?(g||["click"]).indexOf(h.type)>=0:(g||["click"]).indexOf(h.type)>=0&&(Ko.indexOf(B)>-1||d.getAttribute("contenteditable")==="true")}})(r,t,this.Ne,n,n?["copy","cut"]:void 0,this.instance)){var i=cf(r,{e:t,maskAllElementAttributes:this.instance.config.mask_all_element_attributes,maskAllText:this.instance.config.mask_all_text,elementAttributeIgnoreList:this.Ne.element_attribute_ignorelist,elementsChainAsString:this.po,disableCaptureUrlHashes:this.instance.config.disable_capture_url_hashes}),o=i.props;if(i.explicitNoCapture)return!1;var a=this.getElementSelectors(r);if(a&&a.length>0&&(o.$element_selectors=a),e===yi){var l,u=xu(v==null||(l=v.getSelection())==null?void 0:l.toString()),c=t.type||"clipboard";if(!u)return!1;o.$selected_content=u,o.$copy_type=c}return this.instance.capture(e,o),!0}}}isBrowserSupported(){return Se(C?.querySelectorAll)}},historyAutocapture:class{constructor(t){var e;this._instance=t,this._o=(v==null||(e=v.location)==null?void 0:e.pathname)||""}initialize(){this.startIfEnabled()}get isEnabled(){return this._instance.config.capture_pageview==="history_change"}startIfEnabled(){this.isEnabled&&(k.info("History API monitoring enabled, starting..."),this.monitorHistoryChanges())}stop(){this.wo&&this.wo(),this.wo=void 0,k.info("History API monitoring stopped")}monitorHistoryChanges(){v&&v.history&&(this.ko("pushState"),this.ko("replaceState"),this.xo())}ko(t){var e;if(v&&((e=v.history[t])==null||!e.__posthog_wrapped__)){var s=this;(function(r,n,i){try{if(!(n in r))return $l;var o={next:r[n]},a=i((function(){for(var l=arguments.length,u=new Array(l),c=0;l>c;c++)u[c]=arguments[c];return o.next.apply(this,u)}));return Se(a)&&(a.prototype=a.prototype||{},Object.defineProperties(a,{__posthog_wrapped__:{enumerable:!1,value:!0},__posthog_layer__:{enumerable:!1,value:o}})),r[n]=a,()=>{if(r[n]!==a)for(var l=r[n];Se(l)&&l.__posthog_layer__;){var u=l.__posthog_layer__;if(u.next===a)return void(u.next=o.next);l=u.next}else r[n]=o.next}}catch{return $l}})(v.history,t,(r=>function(n,i,o){r.call(this,n,i,o),s.So(t)}))}}So(t){try{var e,s=v==null||(e=v.location)==null?void 0:e.pathname;if(!s)return;s!==this._o&&this.isEnabled&&this._instance.capture(is,{navigation_type:t}),this._o=s}catch(r){k.error("Error capturing "+t+" pageview",r)}}xo(){if(!this.wo){var t=()=>{this.So("popstate")};ne(v,"popstate",t),this.wo=()=>{v&&v.removeEventListener("popstate",t)}}}},heatmaps:class{get Ne(){return this.instance.config}constructor(t){var e;this.Co=!1,this.vo=!1,this.Mo=null,this.instance=t,this.Co=!((e=this.instance.persistence)==null||!e.props[Hi]),this.rageclicks=new Al(t.config.rageclick)}initialize(){this.startIfEnabled()}get flushIntervalMilliseconds(){var t=5e3;return te(this.Ne.capture_heatmaps)&&this.Ne.capture_heatmaps.flush_interval_milliseconds&&(t=this.Ne.capture_heatmaps.flush_interval_milliseconds),t}get isEnabled(){return D(this.Ne.capture_heatmaps)?D(this.Ne.enable_heatmaps)?this.Co:this.Ne.enable_heatmaps:this.Ne.capture_heatmaps!==!1}startIfEnabled(){if(this.isEnabled){if(this.vo)return;df.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 s=!!e.heatmaps;this.instance.persistence&&this.instance.persistence.register({[Hi]:s}),this.Co=s,this.startIfEnabled()}}}getAndClearBuffer(){var t=this.R;return this.R=void 0,t}Io(t){Ei(t.originalEvent)&&this.ke(t.originalEvent,"deadclick")}Ie(){this.Mo&&clearInterval(this.Mo),this.Mo=C?.visibilityState==="visible"?setInterval(this.cr.bind(this),this.flushIntervalMilliseconds):null}To(){v&&C&&(this.Po=this.cr.bind(this),ne(v,on,this.Po),this.Ro=t=>this.ke(t||v?.event),ne(C,"click",this.Ro,{capture:!0}),this.Ao=t=>this.Fo(t||v?.event),ne(C,"mousemove",this.Ao,{capture:!0}),this.Lo=new pl(this.instance,Sp,this.Io.bind(this)),this.Lo.startIfEnabledOrStop(),this.Oo=this.Ie.bind(this),ne(C,nn,this.Oo),this.vo=!0)}Eo(){var t;v&&C&&(this.Po&&v.removeEventListener(on,this.Po),this.Ro&&C.removeEventListener("click",this.Ro,{capture:!0}),this.Ao&&C.removeEventListener("mousemove",this.Ao,{capture:!0}),this.Oo&&C.removeEventListener(nn,this.Oo),clearTimeout(this.Do),(t=this.Lo)==null||t.stop(),this.vo=!1)}$o(t,e){var s=this.instance.scrollManager.scrollY(),r=this.instance.scrollManager.scrollX(),n=this.instance.scrollManager.scrollElement(),i=(function(o,a,l){for(var u=o;u&&Ft(u)&&!Me(u,"body");){if(u===l)return!1;var c=void 0;try{var d,h,p;c=(d=(h=(p=u.ownerDocument)==null?void 0:p.defaultView)!==null&&h!==void 0?h:v)==null?void 0:d.getComputedStyle(u).position}catch{return!1}if(M(a,c))return!0;u=ku(u)}return!1})(ai(t),["fixed","sticky"],n);return{x:t.clientX+(i?0:r),y:t.clientY+(i?0:s),target_fixed:i,type:e}}ke(t,e){var s;if(e===void 0&&(e="click"),!sl(t.target)&&Ei(t)){var r=this.$o(t,e);(s=this.rageclicks)!=null&&s.isRageClick(t.clientX,t.clientY,new Date().getTime())&&ol(ai(t),this.instance.config.rageclick)&&this.Vt(w({},r,{type:"rageclick"})),this.Vt(r)}}Fo(t){!sl(t.target)&&Ei(t)&&(clearTimeout(this.Do),this.Do=setTimeout((()=>{this.Vt(this.$o(t,"mousemove"))}),500))}Vt(t){if(v){var e=this.Ne.disable_capture_url_hashes?Ct(v.location.href):v.location.href,s=this.Ne.custom_personal_data_properties,r=this.Ne.mask_personal_data_properties?[...vs,...s||[]]:[],n=nr(e,r,ir);this.R=this.R||{},this.R[n]||(this.R[n]=[]),this.R[n].push(t)}}cr(){this.R&&!mt(this.R)&&this.instance.capture("$$heatmap",{$heatmap_data:this.getAndClearBuffer()})}},deadClicksAutocapture:pl,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",w({$current_url:this.R.url},this.R.metrics.reduce(((s,r)=>w({},s,{["$web_vitals_"+r.name+"_event"]:w({},r),["$web_vitals_"+r.name+"_value"]:r.value})),{}))),this.R={navigationKey:void 0,url:void 0,metrics:[],firstMetricTimestamp:void 0})},this.jo=s=>{var r;if(this.R=this.R||{navigationKey:void 0,url:void 0,metrics:[],firstMetricTimestamp:void 0},D(s?.name)||D(s?.value))Lt.error("Invalid metric received",s);else{var n=typeof s.navigationURL=="string"?s.navigationURL:void 0,i=this.Bo(n);if(!x(i)){var o=he(s.navigationId)||typeof s.navigationId=="string"?"navigation:"+s.navigationId:"url:"+i;if(!this.Ho||this.Ho>s.value){this.R.navigationKey!==o&&(this.No(),this.qo=setTimeout(this.No,this.flushToCaptureTimeoutMs)),x(this.R.navigationKey)&&(this.R.navigationKey=o,this.R.url=i),this.R.firstMetricTimestamp=x(this.R.firstMetricTimestamp)?Date.now():this.R.firstMetricTimestamp,s.attribution&&s.attribution.interactionTargetElement&&(s.attribution.interactionTargetElement=void 0);var a=(r=this._instance.sessionManager)==null?void 0:r.checkAndGetSessionAndWindowId(!0),l=w({},s,n?{navigationURL:i}:{},{$current_url:i,timestamp:Date.now()});x(a)||(l.$session_id=a.sessionId,l.$window_id=a.windowId),this.R.metrics.push(l),this.R.metrics.length===this.allowedMetrics.length&&this.No()}else Lt.error("Ignoring metric with value >= "+this.Ho,s)}}},this.Uo=()=>{if(!this.vo){var s,r,n,i,o=$.__PosthogExtensions__,a=o?.postHogWebVitalsCallbacksByFlavor,l=a?.[this.zo]||(this.zo==="web-vitals"&&x(a)?o?.postHogWebVitalsCallbacks:void 0);if(x(l)||(s=l.onLCP,r=l.onCLS,n=l.onFCP,i=l.onINP),s&&r&&n&&i){var u={reportSoftNavs:this.useSoftNavs};this.allowedMetrics.indexOf("LCP")>-1&&s(this.jo.bind(this),u),this.allowedMetrics.indexOf("CLS")>-1&&r(this.jo.bind(this),u),this.allowedMetrics.indexOf("FCP")>-1&&n(this.jo.bind(this),u),this.allowedMetrics.indexOf("INP")>-1&&i(this.jo.bind(this),u),this.vo=!0}else Lt.error("web vitals callbacks not loaded - not starting")}},this._instance=t,this.Co=!((e=this._instance.persistence)==null||!e.props[Vi]),this.startIfEnabled()}get Wo(){return this._instance.config.capture_performance}get allowedMetrics(){var t,e,s=te(this.Wo)?(t=this.Wo)==null?void 0:t.web_vitals_allowed_metrics:void 0;return D(s)?((e=this._instance.persistence)==null?void 0:e.props[Gi])||["CLS","FCP","INP","LCP"]:s}get flushToCaptureTimeoutMs(){return(te(this.Wo)?this.Wo.web_vitals_delayed_flush_ms:void 0)||5e3}get useAttribution(){var t=te(this.Wo)?this.Wo.web_vitals_attribution:void 0;return t!=null&&t}get useSoftNavs(){var t=te(this.Wo)?this.Wo.__preview_web_vitals_soft_navs:void 0;return t!=null&&t}get Ho(){var t=te(this.Wo)&&he(this.Wo.__web_vitals_max_value)?this.Wo.__web_vitals_max_value:Rl;return t>0&&6e4>=t?Rl:t}get isEnabled(){var t=re?.protocol;if(t!=="http:"&&t!=="https:")return Lt.info("Web Vitals are disabled on non-http/https protocols"),!1;var e=te(this.Wo)?this.Wo.web_vitals:Ke(this.Wo)?this.Wo:void 0;return Ke(e)?e:this.Co}startIfEnabled(){this.isEnabled&&!this.vo&&(Lt.info("enabled, starting..."),this.ai(this.Uo))}onRemoteConfig(t){if(t.ok){var e=t.config;if("capturePerformance"in e){var s=te(e.capturePerformance)&&!!e.capturePerformance.web_vitals,r=te(e.capturePerformance)?e.capturePerformance.web_vitals_allowed_metrics:void 0;this._instance.persistence&&(this._instance.persistence.register({[Vi]:s}),this._instance.persistence.register({[Gi]:r})),this.Co=s,this.startIfEnabled()}}}get zo(){return this.useSoftNavs?this.useAttribution?"web-vitals-with-attribution-soft-navs":"web-vitals-soft-navs":this.useAttribution?"web-vitals-with-attribution":"web-vitals"}ai(t){var e=$.__PosthogExtensions__,s=this.zo,r=e?.postHogWebVitalsCallbacksByFlavor;r!=null&&r[s]||s==="web-vitals"&&x(r)&&e!=null&&e.postHogWebVitalsCallbacks?t():e==null||e.loadExternalDependency==null||e.loadExternalDependency(this._instance,s,(n=>{n?Lt.error("failed to load script",n):t()}))}Bo(t){var e=t||v?.location.href;if(e){var s=this._instance.config.disable_capture_url_hashes?Ct(e):e,r=this._instance.config.custom_personal_data_properties,n=this._instance.config.mask_personal_data_properties?[...vs,...r||[]]:[];return nr(s,n,ir)}Lt.error("Could not determine current URL")}}},bf={exceptionObserver:class{constructor(t){var e;this.Uo=()=>{var s;if(v&&this.isEnabled&&(s=$.__PosthogExtensions__)!=null&&s.errorWrappingFunctions){var r=$.__PosthogExtensions__.errorWrappingFunctions.wrapOnError,n=$.__PosthogExtensions__.errorWrappingFunctions.wrapUnhandledRejection,i=$.__PosthogExtensions__.errorWrappingFunctions.wrapConsoleError;try{!this.Vo&&this.Ne.capture_unhandled_errors&&(this.Vo=r(this.captureException.bind(this))),!this.Zo&&this.Ne.capture_unhandled_rejections&&(this.Zo=n(this.captureException.bind(this))),!this.Go&&this.Ne.capture_console_errors&&(this.Go=i(this.captureException.bind(this)))}catch(o){Ms.error("failed to start",o),this.Qo()}}},this._instance=t,this.Ko=!((e=this._instance.persistence)==null||!e.props[Wi]),this.Jo=new _h(w({},(function(s){var r,n,i,o;return s===void 0&&(s={}),{refillRate:(r=(n=s.exceptionRateLimiterRefillRate)!==null&&n!==void 0?n:s.__exceptionRateLimiterRefillRate)!==null&&r!==void 0?r:1,bucketSize:(i=(o=s.exceptionRateLimiterBucketSize)!==null&&o!==void 0?o:s.__exceptionRateLimiterBucketSize)!==null&&i!==void 0?i:10}})(this._instance.config.error_tracking),{refillInterval:1e4,rt:Ms})),this.Ne=this.Yo(),this.startIfEnabledOrStop()}Yo(){var t=this._instance.config.capture_exceptions,e={capture_unhandled_errors:!1,capture_unhandled_rejections:!1,capture_console_errors:!1};return te(t)?e=w({},e,t):(x(t)?this.Ko:t)&&(e=w({},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?(Ms.info("enabled"),this.Qo(),this.ai(this.Uo)):this.Qo()}ai(t){var e,s;(e=$.__PosthogExtensions__)!=null&&e.errorWrappingFunctions?t():(s=$.__PosthogExtensions__)==null||s.loadExternalDependency==null||s.loadExternalDependency(this._instance,"exception-autocapture",(r=>{if(r)return Ms.error("failed to load script",r);t()}))}Qo(){var t,e,s;(t=this.Vo)==null||t.call(this),this.Vo=void 0,(e=this.Zo)==null||e.call(this),this.Zo=void 0,(s=this.Go)==null||s.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({[Wi]:this.Ko}),this.Ne=this.Yo(),this.startIfEnabledOrStop())}}onConfigChange(){this.Ne=this.Yo()}captureException(t){var e,s,r,n=(e=t==null||(s=t.$exception_list)==null||(s=s[0])==null?void 0:s.type)!==null&&e!==void 0?e:"Exception";this.Jo.consumeRateLimit(n)?Ms.info("Skipping exception capture because of client rate limiting.",{exception:n}):(r=this._instance.exceptions)==null||r.sendExceptionEvent(t)}},exceptions:class{constructor(t){var e,s;this.Xo=[],this.tl=new Mh([new Wh,new Xh,new qh,new zh,new Yh,new Jh,new Gh,new Zh],(function(r){for(var n=arguments.length,i=new Array(n>1?n-1:0),o=1;n>o;o++)i[o-1]=arguments[o];return function(a,l){l===void 0&&(l=0);for(var u=[],c=a.split(` +`),d=l;c.length>d;d++){var h=c[d];if(1024>=h.length){var p=Xa.test(h)?h.replace(Xa,"$1"):h;if(!p.match(/\S*Error: /)){for(var f of i){var g=f(p,r);if(g){u.push(g);break}}if(u.length>=50)break}}}return(function(m){if(!m.length)return[];var _=Array.from(m);return _.reverse(),_.slice(0,50).map((b=>{return w({},b,{filename:b.filename||(E=_,E[E.length-1]||{}).filename,function:b.function||gs});var E}))})(u)}})("web:javascript",Bh,Hh)),this._instance=t,this.Xo=(e=(s=this._instance.persistence)==null?void 0:s.get_property(zi))!==null&&e!==void 0?e:[],this.el=Qr(this.il()),this.rl=new ep(this.el)}onConfigChange(){this.el=Qr(this.il()),this.rl.setConfig(this.el)}onRemoteConfig(t){var e,s,r;if(t.ok){var n=t.config;if("errorTracking"in n){var i=(e=(s=n.errorTracking)==null?void 0:s.suppressionRules)!==null&&e!==void 0?e:[],o=(r=n.errorTracking)==null?void 0:r.captureExtensionExceptions;this.Xo=i,this._instance.persistence&&this._instance.persistence.register({[zi]:this.Xo,[qi]:o})}}}get nl(){var t,e=!!this._instance.get_property(qi),s=this._instance.config.error_tracking.captureExtensionExceptions;return(t=s??e)!==null&&t!==void 0&&t}buildProperties(t,e){return this.tl.buildFromUnknown(t,{syntheticException:e?.syntheticException,mechanism:{handled:e?.handled}})}addExceptionStep(t,e){if(this.el.enabled)try{if(!W(t)||t.trim().length===0)return void Xe.warn("Ignoring exception step because message must be a non-empty string");var s=(function(i){if(!i)return{sanitizedProperties:{},droppedKeys:[]};var o=[];return{sanitizedProperties:Object.keys(i).reduce(((a,l)=>Qh.has(l)?(o.push(l),a):(a[l]=i[l],a)),{}),droppedKeys:o}})(this.sl(e)),r=s.sanitizedProperties,n=s.droppedKeys;n.length>0&&Xe.warn("Ignoring reserved exception step fields",{droppedKeys:n}),this.rl.add(w({[Zr]:t,[Xr]:new Date().toISOString()},r))}catch(i){Xe.error("Failed to add exception step. Ignoring breadcrumb.",i)}}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 Xe.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 Xe.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 Xe.info("Skipping exception capture because it was thrown by the PostHog SDK")}var s=this.el.enabled&&D(t.$exception_steps)?this.dl(t):t,r=typeof(i=globalThis._posthogReleaseId)=="string"&&i.length>0?i:void 0;r&&(s.$release_id=r);try{var n=this._instance.capture("$exception",s,{_noTruncate:!0,_batchKey:"exceptionEvent",Wn:!0});return n&&this.rl.clear(),n}catch(o){return Xe.error("Failed to capture exception event. Dropping this exception.",o),void this.rl.clear()}}catch(o){return void Xe.error("Failed to process exception event. Ignoring this exception.",o)}var i}dl(t){try{var e=this.rl.getAttachable();return e.length===0?t:w({},t,{$exception_steps:e})}catch(s){return Xe.error("Failed to read buffered exception steps. Capturing exception without steps.",s),t}}ll(t){this.el.enabled&&this.rl.add({[Zr]:t,[Xr]:new Date().toISOString()})}sl(t){return te(t)?w({},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(((s,r)=>{var n=r.type,i=r.value;return W(n)&&n.length>0&&s.$exception_types.push(n),W(i)&&i.length>0&&s.$exception_values.push(i),s}),{$exception_types:[],$exception_values:[]});return this.Xo.some((s=>{var r=s.values.map((n=>{var i=td[n.operator],o=e[n.key];if(!i||!o)return!1;var a=L(n.value)?n.value:[n.value];return a.length>0&&i(a,o)}));return s.type==="OR"?r.some(Boolean):r.every(Boolean)}))}catch(s){return Xe.warn("Failed to evaluate suppression rules. Capturing the exception.",s),!1}}ul(t){return t.flatMap((e=>{var s,r;return(s=(r=e.stacktrace)==null?void 0:r.frames)!==null&&s!==void 0?s:[]})).some((e=>e.filename&&e.filename.startsWith("chrome-extension://")))}hl(t){if(t.length>0){var e,s,r,n,i=(e=(s=t[0].stacktrace)==null?void 0:s.frames)!==null&&e!==void 0?e:[],o=i[i.length-1];return(r=o==null||(n=o.filename)==null?void 0:n.includes("posthog.com/static"))!==null&&r!==void 0&&r}return!1}al(t){return!D(t)&&L(t)}}},Ef=w({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 s,r;if(this.Mr&&this.Mr.register({[Wo]:!!e.productTours}),!Si(this._instance))return!this.vl&&D((s=this.Mr)==null?void 0:s.props[Ws])||Pr.info("product tours disabled; stopping and clearing cached tours"),(r=this.vl)==null||r.stop(),this.vl=null,void this.clearCache();this.loadIfEnabled()}}}loadIfEnabled(){!this.vl&&Si(this._instance)&&this.ai((()=>this.fl()))}ai(t){var e,s;(e=$.__PosthogExtensions__)!=null&&e.generateProductTours?t():(s=$.__PosthogExtensions__)==null||s.loadExternalDependency==null||s.loadExternalDependency(this._instance,"product-tours",(r=>{r?Pr.error("Could not load product tours script",r):t()}))}fl(){var t;!this.vl&&(t=$.__PosthogExtensions__)!=null&&t.generateProductTours&&(this.vl=$.__PosthogExtensions__.generateProductTours(this._instance,!0))}getProductTours(t,e){if(e===void 0&&(e=!1),!L(this.cl)||e){var s=this.Mr;if(s){var r=s.props[Ws];if(L(r)&&!e)return this.cl=r,void t(r,{isLoaded:!0})}this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/product_tours/?token="+this._instance.config.token),method:"GET",timestampMode:"query",callback:n=>{if(Si(this._instance)){var i=n.statusCode;if(i!==200||!n.json){var o="Product Tours API could not be loaded, status: "+i;return i===0?n.error||Pr.warn(o):Pr.error(o),void t([],{isLoaded:!1,error:o})}var a=L(n.json.product_tours)?n.json.product_tours:[];this.cl=a,s&&s.register({[Ws]:a}),t(a,{isLoaded:!0})}else t([],{isLoaded:!0})}})}else t(this.cl,{isLoaded:!0})}getActiveProductTours(t){D(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(Ws)}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)}}},Rn),Sf={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 s=this.globalsForEvent(e);this.gl.push(s),this.gl.length>1e3&&(this.gl=this.gl.slice(10))}}get siteAppLoaders(){var t;return(t=$._POSTHOG_REMOTE_CONFIG)==null||(t=t[this._instance.config.token])==null?void 0:t.siteApps}initialize(){if(this.isEnabled){var t=this._instance._addCaptureHook(this.ml.bind(this));this.yl=()=>{t(),this.gl=[],this.yl=void 0}}}globalsForEvent(t){var e,s,r,n,i,o,a;if(!t)throw new Error("Event payload is required");var l={},u=this._instance.get_property("$groups")||[],c=this._instance.get_property("$stored_group_properties")||{};for(var d of Object.entries(c)){var h=d[0];l[h]={id:u[h],type:h,properties:d[1]}}var p=t.$set_once,f=t.$set;return{event:w({},Ic(t,hf),{properties:w({},t.properties,f?{$set:w({},(e=(s=t.properties)==null?void 0:s.$set)!==null&&e!==void 0?e:{},f)}:{},p?{$set_once:w({},(r=(n=t.properties)==null?void 0:n.$set_once)!==null&&r!==void 0?r:{},p)}:{}),elements_chain:(i=(o=t.properties)==null?void 0:o.$elements_chain)!==null&&i!==void 0?i:"",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,s=(e=t.tagName)==null?void 0:e.toLowerCase();return s==="style"&&this._instance.config.prepare_external_dependency_stylesheet?this._instance.config.prepare_external_dependency_stylesheet(t)||(Ze.error("prepare_external_dependency_stylesheet returned null"),null):s==="script"&&this._instance.config.prepare_external_dependency_script?this._instance.config.prepare_external_dependency_script(t)||(Ze.error("prepare_external_dependency_script returned null"),null):t}_l(){var t,e,s,r,n,i,o,a;if(!this._instance.config.prepare_external_dependency_stylesheet&&!this._instance.config.prepare_external_dependency_script)return()=>{};var l=C?.defaultView,u=l==null||(t=l.Node)==null?void 0:t.prototype;if(!l||!u)return()=>{};if(this.pl++,this.wl)return this.kl();var c=[],d=this,h=new WeakSet,p=(m,_,b)=>{if(m!=null&&m[_]){var E=m[_];m[_]=b(E),c.push((()=>{m[_]=E}))}},f=m=>{if(h.has(m))return m;var _=d.bl(m);return _&&h.add(_),_},g=m=>m.map((_=>typeof _=="string"?_:f(_))).filter((_=>!$e(_)));return p(u,"appendChild",(m=>function(_){var b=f(_);return b?m.call(this,b):_})),p(u,"insertBefore",(m=>function(_,b){var E=f(_);return E?m.call(this,E,b):_})),p(u,"replaceChild",(m=>function(_,b){var E=f(_);return E?m.call(this,E,b):b})),[(e=l.Element)==null?void 0:e.prototype,(s=l.Document)==null?void 0:s.prototype,(r=l.DocumentFragment)==null?void 0:r.prototype].forEach((m=>{p(m,"append",(_=>function(){for(var b=arguments.length,E=new Array(b),I=0;b>I;I++)E[I]=arguments[I];return _.apply(this,g(E))})),p(m,"prepend",(_=>function(){for(var b=arguments.length,E=new Array(b),I=0;b>I;I++)E[I]=arguments[I];return _.apply(this,g(E))}))})),[(n=l.Element)==null?void 0:n.prototype,(i=l.CharacterData)==null?void 0:i.prototype,(o=l.DocumentType)==null?void 0:o.prototype].forEach((m=>{p(m,"before",(_=>function(){for(var b=arguments.length,E=new Array(b),I=0;b>I;I++)E[I]=arguments[I];return _.apply(this,g(E))})),p(m,"after",(_=>function(){for(var b=arguments.length,E=new Array(b),I=0;b>I;I++)E[I]=arguments[I];return _.apply(this,g(E))})),p(m,"replaceWith",(_=>function(){for(var b=arguments.length,E=new Array(b),I=0;b>I;I++)E[I]=arguments[I];var F=g(E);return E.length&&!F.length?void 0:_.apply(this,F)}))})),p((a=l.Element)==null?void 0:a.prototype,"insertAdjacentElement",(m=>function(_,b){var E=f(b);return E?m.call(this,_,E):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 s=this._l();try{var r=t(s);return e&&s(),r}catch(n){throw s(),n}}setupSiteApp(t){var e=this.apps[t.id],s=()=>{var o;!e.errored&&this.gl.length&&(Ze.info("Processing "+this.gl.length+" events for site app with id "+t.id),this.gl.forEach((a=>this.xl((()=>e.processEvent==null?void 0:e.processEvent(a))))),e.processedBuffer=!0),Object.values(this.apps).every((a=>a.processedBuffer||a.errored))&&((o=this.yl)==null||o.call(this))},r=!1,n=o=>{e.errored=!o,e.loaded=!0,Ze.info("Site app with id "+t.id+" "+(o?"loaded":"errored")),r&&s()};try{var i=this.xl((o=>t.init({posthog:this._instance,callback(a){o(),n(a)}})),!1).processEvent;i&&(e.processEvent=i),r=!0}catch(o){Ze.error(Ml+t.id,o),n(!1)}if(r&&e.loaded)try{s()}catch(o){Ze.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 s of t)this.setupSiteApp(s)}Cl(t){var e=this;if(Object.keys(this.apps).length!==0){var s=this.globalsForEvent(t),r=function(i){try{e.xl((()=>i.processEvent==null?void 0:i.processEvent(s)))}catch(o){Ze.error("Error while processing event "+t.event+" for site app "+i.id,o)}};for(var n of Object.values(this.apps))r(n)}}onRemoteConfig(t){var e,s,r,n=this;if((e=this.siteAppLoaders)!=null&&e.length)return this.isEnabled?(this.Sl(),void this._instance.on("eventCaptured",(l=>this.Cl(l)))):void Ze.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.');if((s=this.yl)==null||s.call(this),t.ok){var i=t.config;if((r=i.siteApps)!=null&&r.length)if(this.isEnabled){var o=function(){var l,u=a.id,c=a.url;$["__$$ph_site_app_"+u]=n._instance,(l=$.__PosthogExtensions__)==null||l.loadSiteApp==null||l.loadSiteApp(n._instance,c,(d=>{if(d)return Ze.error(Ml+u,d)}))};for(var a of i.siteApps)o()}else Ze.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.')}}}},xf={tracingHeaders:class{constructor(t){this.Ml=void 0,this.Tl=void 0,this.El=void 0,this.Uo=()=>{var e,s,r=this.Il();r?(x(this.Ml)&&(this.Ml=(e=$.__PosthogExtensions__)==null||(e=e.tracingHeadersPatchFns)==null?void 0:e._patchXHR(r,(()=>this._instance.get_distinct_id()),this._instance.sessionManager)),x(this.Tl)&&(this.Tl=(s=$.__PosthogExtensions__)==null||(s=s.tracingHeadersPatchFns)==null?void 0:s._patchFetch(r,(()=>this._instance.get_distinct_id()),this._instance.sessionManager))):this.Qo()},this._instance=t}initialize(){this.startIfEnabledOrStop()}ai(t){var e,s;(e=$.__PosthogExtensions__)!=null&&e.tracingHeadersPatchFns?t():(s=$.__PosthogExtensions__)==null||s.loadExternalDependency==null||s.loadExternalDependency(this._instance,"tracing-headers",(r=>{if(r)return uf.error("failed to load script",r);t()}))}Pl(){var t,e;return(t=(e=this._instance.config.tracing_headers)!==null&&e!==void 0?e:this._instance.config.addTracingHeaders)!==null&&t!==void 0?t:this._instance.config.__add_tracing_headers}Il(){var t=this.Pl();return L(t)?(L(this.El)?this.El.splice(0,this.El.length,...t):this.El=[...t],t.length>0?this.El:void 0):(L(this.El)&&this.El.splice(0),this.El=t||void 0,this.El)}Qo(){var t,e;(t=this.Ml)==null||t.call(this),(e=this.Tl)==null||e.call(this),this.Ml=void 0,this.Tl=void 0}startIfEnabledOrStop(){this.Il()?this.ai(this.Uo):this.Qo()}}},kf=w({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(D(e))return q.warn("Flags not loaded yet. Not loading surveys.");var s=L(e);this.Rl=s?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=[],s=0;slocalStorage.removeItem(n)))}catch{}}loadIfEnabled(){if(!this._surveyManager)if(this.Al)q.info("Already initializing surveys, skipping...");else if(this.Ne.disable_surveys)q.info(Ll);else if(this.Ne.cookieless_mode&&this._instance.consent.isOptedOut())q.info("Not loading surveys in cookieless mode without consent.");else{var t=$?.__PosthogExtensions__;if(t){if(!x(this.Rl)||this.Ne.advanced_enable_surveys){var e=this.Rl||this.Ne.advanced_enable_surveys;this.Al=!0;try{var s=t.generateSurveys;if(s)return void this.Dl(s,e);var r=t.loadExternalDependency;if(!r)return void this.$l(qo);r(this._instance,"surveys",(n=>{n||!t.generateSurveys?this.$l("Could not load surveys script",n):this.Dl(t.generateSurveys,e)}))}catch(n){throw this.$l("Error initializing surveys",n),n}finally{this.Al=!1}}}else q.error("PostHog Extensions not found.")}}Dl(t,e){this._surveyManager=t(this._instance,e),this._surveyEventReceiver=new gf(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(Ll),t([]);var s,r=this._instance.get_property(Ji);if(r&&!e)return t(r,{isLoaded:!0}),void(this.ql()&&this.getSurveys((()=>{}),!0));typeof Promise<"u"&&this.Ll?this.Ll.then((n=>t(n.surveys,n.context))):(typeof Promise<"u"&&(this.Ll=new Promise((n=>{s=n}))),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:n=>{var i;this.Ll=null;var o=n.statusCode;if(o!==200||!n.json){var a="Surveys API could not be loaded, status: "+o;o!==0?q.error(a):n.error||q.warn(a),this.Ol=Date.now();var l={isLoaded:!1,error:a};return t([],l),void(s==null||s({surveys:[],context:l}))}this.Ol=null;var u,c=n.json.surveys||[],d=c.filter((p=>(function(f){return!(!f.start_date||f.end_date)})(p)&&(rd(p)||(function(f){var g;return!((g=f.conditions)==null||(g=g.actions)==null||(g=g.values)==null||!g.length)})(p))));d.length>0&&((u=this._surveyEventReceiver)==null||u.register(d)),(i=this._instance.persistence)==null||i.register({[Ji]:c,[tn]:Date.now()});var h={isLoaded:!0};t(c,h),s?.({surveys:c,context:h})}}))}ql(){return this.jl()&&!this.Ll&&!this.Bl()}jl(){var t=this._instance.get_property(tn);return he(t)&&Date.now()-t>3e5}Bl(){return he(this.Ol)&&3e5>Date.now()-this.Ol}markSurveyAsSeen(t,e){var s,r={id:t,current_iteration:(s=e?.iteration)!==null&&s!==void 0?s:null};id(r);try{localStorage.setItem("lastSeenSurveyDate",new Date().toISOString())}catch{}}Nl(t){for(var e of this.Fl)try{if(!t.isLoaded)return e([],t);this.getSurveys(e)}catch(s){q.error("Error in survey callback",s)}}getActiveMatchingSurveys(t,e){if(e===void 0&&(e=!1),!D(this._surveyManager))return this._surveyManager.getActiveMatchingSurveys(t,e);q.warn("init was not called")}Hl(t){var e=null;return this.getSurveys((s=>{var r;e=(r=s.find((n=>n.id===t)))!==null&&r!==void 0?r:null})),e}Ul(t){if(D(this._surveyManager))return{eligible:!1,reason:Ar};var e=typeof t=="string"?this.Hl(t):t;return e?this._surveyManager.checkSurveyEligibility(e):{eligible:!1,reason:"Survey not found"}}zl(t){if(D(this._surveyManager))return{eligible:!1,reason:Ar};var e=typeof t=="string"?this.Hl(t):t;return e?this._surveyManager.checkSurveyRenderability(e):{eligible:!1,reason:"Survey not found"}}canRenderSurvey(t){if(D(this._surveyManager))return q.warn("init was not called"),{visible:!1,disabledReason:Ar};var e=this.zl(t);return{visible:e.eligible,disabledReason:e.reason}}canRenderSurveyAsync(t,e){return D(this._surveyManager)?(q.warn("init was not called"),Promise.resolve({visible:!1,disabledReason:Ar})):new Promise((s=>{this.getSurveys((r=>{var n,i=(n=r.find((a=>a.id===t)))!==null&&n!==void 0?n:null;if(i){var o=this.zl(i);s({visible:o.eligible,disabledReason:o.reason})}else s({visible:!1,disabledReason:"Survey not found"})}),e)}))}renderSurvey(t,e,s){var r;if(D(this._surveyManager))q.warn("init was not called");else{var n=typeof t=="string"?this.Hl(t):t;if(n!=null&&n.id)if(Yp.includes(n.type)){var i=C?.querySelector(e);if(i)return(r=n.appearance)!=null&&r.surveyPopupDelaySeconds?(q.info("Rendering survey "+n.id+" with delay of "+n.appearance.surveyPopupDelaySeconds+" seconds"),void setTimeout((()=>{var o,a;q.info("Rendering survey "+n.id+" with delay of "+((o=n.appearance)==null?void 0:o.surveyPopupDelaySeconds)+" seconds"),(a=this._surveyManager)==null||a.renderSurvey(n,i,s),q.info("Survey "+n.id+" rendered")}),1e3*n.appearance.surveyPopupDelaySeconds)):void this._surveyManager.renderSurvey(n,i,s);q.warn("Survey element not found")}else q.warn("Surveys of type "+n.type+" cannot be rendered in the app");else q.warn("Survey not found")}}displaySurvey(t,e){var s;if(D(this._surveyManager))q.warn("init was not called");else{var r=this.Hl(t);if(r){var n=r;if((s=r.appearance)!=null&&s.surveyPopupDelaySeconds&&e.ignoreDelay&&(n=w({},r,{appearance:w({},r.appearance,{surveyPopupDelaySeconds:0})})),e.displayType!==io.Popover&&e.initialResponses&&q.warn("initialResponses is only supported for popover surveys. prefill will not be applied."),e.ignoreConditions===!1){var i=this.Ul(r);if(!i.eligible)return void q.warn("Survey is not eligible to be displayed: ",i.reason)}e.displayType!==io.Inline?this._surveyManager.handlePopoverSurvey(n,e):this.renderSurvey(n,e.selector,e.properties)}else q.warn("Survey not found")}}cancelPendingSurvey(t){D(this._surveyManager)?q.warn("init was not called"):this._surveyManager.cancelSurvey(t)}handlePageUnload(){var t;(t=this._surveyManager)==null||t.handlePageUnload==null||t.handlePageUnload()}}},Rn),If={toolbar:class{constructor(t){this.instance=t}Wl(t){$.ph_toolbar_state=t}Vl(){var t;return(t=$.ph_toolbar_state)!==null&&t!==void 0?t:0}initialize(){return this.maybeLoadToolbar()}maybeLoadToolbar(t,e,s){if(t===void 0&&(t=void 0),e===void 0&&(e=void 0),s===void 0&&(s=void 0),so(this.instance.config)||!v||!C)return!1;t=t??v.location,s=s??v.history;try{if(!e){try{v.localStorage.setItem("test","test"),v.localStorage.removeItem("test")}catch{return!1}e=v?.localStorage}var r,n=mf||un(t.hash,"__posthog")||un(t.hash,"state"),i=n?el((()=>JSON.parse(atob(decodeURIComponent(n)))))||el((()=>JSON.parse(decodeURIComponent(n)))):null;return i&&i.action==="ph_authorize"?((r=i).source="url",r&&Object.keys(r).length>0&&(i.desiredHash?t.hash=i.desiredHash:s?s.replaceState(s.state,"",t.pathname+t.search):t.hash="")):((r=JSON.parse(e.getItem(Ol)||"{}")).source="localstorage",delete r.userIntent),!(!r.token||this.instance.config.token!==r.token||(this.loadToolbar(r),0))}catch{return!1}}Zl(t){var e=$.ph_load_toolbar||$.ph_load_editor;!D(e)&&Se(e)?e(t,this.instance):Dl.warn("No toolbar load function found")}loadToolbar(t){var e=!(C==null||!C.getElementById(wu));if(!v||e)return!1;var s=this.instance.requestRouter.region==="custom"&&this.instance.config.advanced_disable_toolbar_metrics,r=w({token:this.instance.config.token},t,{apiURL:this.instance.requestRouter.endpointFor("ui")},s?{instrument:!1}:{});if(v.localStorage.setItem(Ol,JSON.stringify(w({},r,{source:void 0}))),this.Vl()===2)this.Zl(r);else if(this.Vl()===0){var n;this.Wl(1),(n=$.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this.instance,"toolbar",(i=>{if(i)return Dl.error("[Toolbar] Failed to load",i),void this.Wl(0);this.Wl(2),this.Zl(r)})),ne(v,"turbolinks:load",(()=>{this.Wl(0),this.loadToolbar(r)}))}return!0}Gl(t){return this.loadToolbar(t)}maybeLoadEditor(t,e,s){return t===void 0&&(t=void 0),e===void 0&&(e=void 0),s===void 0&&(s=void 0),this.maybeLoadToolbar(t,e,s)}}},Cf=w({experiments:ye},Rn),Ff={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;D(e)||(Ke(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||so(this._instance.config)||this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut())){var t=$?.__PosthogExtensions__;if(t&&!x(this.Ql)&&this.Ql)if(this.Jl&&this.Jl.token){this.Kl=!0;try{var e=t.initConversations;if(e)return this.tu(e),void(this.Kl=!1);var s=t.loadExternalDependency;if(!s)return void this.eu(qo);s(this._instance,"conversations",(r=>{r||!t.initConversations?this.eu("Could not load conversations script",r):this.tu(t.initConversations),this.Kl=!1}))}catch(r){this.eu("Error initializing conversations",r),this.Kl=!1}}else Ue.error("Conversations enabled but missing token in remote config.")}}tu(t){if(this.Jl)try{this._conversationsManager=t(this.Jl,this._instance),this.Yl=!1,Ue.info("Conversations loaded successfully")}catch(e){this.eu("Error completing conversations initialization",e)}else Ue.error("Cannot complete initialization: remote config is null")}eu(t,e){Ue.error(t,e),this._conversationsManager=null,this.Kl=!1,this.Yl=!0}show(){this._conversationsManager?this._conversationsManager.show():Ue.warn("Conversations not loaded yet.")}hide(){this._conversationsManager&&this._conversationsManager.hide()}isAvailable(){return this.Ql===!0&&!$e(this._conversationsManager)}getUnavailableReason(){return this.isAvailable()?null:this._instance.config.disable_conversations?"disabled_by_config":so(this._instance.config)?"disabled_for_toolbar":this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut()?"consent_opted_out":this.Xl===!1?"remote_config_failed":x(this.Ql)?this.Xl?"disabled_in_project":"remote_config_pending":this.Ql?D(this.Jl)||!this.Jl.token?"missing_token":$!=null&&$.__PosthogExtensions__?this.Kl?"initializing":this.Yl?"load_failed":"not_loaded":"extensions_unavailable":"disabled_in_project"}isVisible(){var t,e;return(t=(e=this._conversationsManager)==null?void 0:e.isVisible())!==null&&t!==void 0&&t}sendMessage(t,e,s){var r=this;return X((function*(){return r._conversationsManager?r._conversationsManager.sendMessage(t,e,s):(Ue.warn(Dt),null)}))()}getMessages(t,e){var s=this;return X((function*(){return s._conversationsManager?s._conversationsManager.getMessages(t,e):(Ue.warn(Dt),null)}))()}markAsRead(t){var e=this;return X((function*(){return e._conversationsManager?e._conversationsManager.markAsRead(t):(Ue.warn(Dt),null)}))()}getTickets(t){var e=this;return X((function*(){return e._conversationsManager?e._conversationsManager.getTickets(t):(Ue.warn(Dt),null)}))()}requestRestoreLink(t){var e=this;return X((function*(){return e._conversationsManager?e._conversationsManager.requestRestoreLink(t):(Ue.warn(Dt),null)}))()}restoreFromToken(t){var e=this;return X((function*(){return e._conversationsManager?e._conversationsManager.restoreFromToken(t):(Ue.warn(Dt),null)}))()}restoreFromUrlToken(){var t=this;return X((function*(){return t._conversationsManager?t._conversationsManager.restoreFromUrlToken():(Ue.warn(Dt),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()}}},Pf={logs:class{constructor(t){var e,s=this;this.iu=!1,this.ru=!1,this.rt=se("[logs]"),this.nu=w({},this.rt,{error(){for(var r=arguments.length,n=new Array(r),i=0;r>i;i++)n[i]=arguments[i];n.some(Vl)||s.rt.error(...n)}}),this.tr=[],this.su=[],this.Sa=0,this.au=()=>{var r,n;this.Sa=0,(r=this.ou)==null||r.onReconnect(),(n=this.lu)==null||n.onReconnect()},this._instance=t,this._instance&&(e=this._instance.config.logs)!=null&&e.captureConsoleLogs&&(this.iu=!0),v&&ne(v,"online",this.au)}uu(t,e,s,r){var n,i=(function(o,a){var l,u,c,d,h,p,f,g=(l=o?.flushIntervalMs)!==null&&l!==void 0?l:3e3,m=(u=o?.maxBufferSize)!==null&&u!==void 0?u:100,_=a!=null&&a.consoleCapture?void 0:(c=o?.maxLogsPerInterval)!==null&&c!==void 0?c:1e3,b=x(_)?Math.max(m,2048):Math.max(m,_),E=o?.resourceAttributes;return{serviceName:(d=(h=E?.["service.name"])!==null&&h!==void 0?h:o?.serviceName)!==null&&d!==void 0?d:a?.serviceNameDefault,serviceVersion:(p=E?.["service.version"])!==null&&p!==void 0?p:o?.serviceVersion,environment:(f=E?.["deployment.environment"])!==null&&f!==void 0?f:o?.environment,resourceAttributes:E,beforeSend:o?.beforeSend,flushIntervalMs:g,maxBufferSize:m,maxQueueSize:b,maxBatchRecordsPerPost:100,rateCapWindowMs:g,maxLogsPerInterval:_,backgroundFlushBudgetMs:0,terminationFlushBudgetMs:0}})((n=this._instance)==null||(n=n.config)==null?void 0:n.logs,s);return[new Rh(this.hu(t,e),i,this.nu,(()=>this.du()),(o=>o()),void 0,r),i]}vu(){var t,e=(t=this._instance)==null||(t=t.config)==null?void 0:t.logs;if(!this.ou||this.cu!==e){var s;(s=this.ou)==null||s.reset(),this.cu=e;var r=this.uu((()=>this.tr),(n=>{this.tr=n}));this.ou=r[0],this.fu=r[1]}return this.ou}pu(){var t,e=(t=this._instance)==null||(t=t.config)==null?void 0:t.logs;if(!this.lu||this.gu!==e){var s;(s=this.lu)==null||s.reset(),this.gu=e;var r=this.uu((()=>this.su),(n=>{this.su=n}),{serviceNameDefault:"posthog-browser-logs",consoleCapture:!0},ql);this.lu=r[0],this.mu=r[1]}return this.lu}initialize(){this.loadIfEnabled()}onRemoteConfig(t){var e;if(t.ok){var s=(e=t.config.logs)==null?void 0:e.captureConsoleLogs;!D(s)&&s&&(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){Vl(t)||this.rt.error("PostHog logs flush failed:",t)}loadIfEnabled(){if(this.iu&&!this.ru){var t=$?.__PosthogExtensions__;if(t){var e=t.loadExternalDependency;e?e(this._instance,"logs",(s=>{var r;s||(r=t.logs)==null||!r.initializeLogs?this.rt.error("Could not load logs script",s):(t.logs.initializeLogs(this._instance),this.ru=!0)})):this.rt.error(qo)}else this.rt.error("PostHog Extensions not found.")}}hu(t,e){var s=this._instance;return{get isDisabled(){return!1},get optedOut(){return!s.is_capturing()},getPersistedProperty:r=>r===ut.LogsQueue?t():void 0,setPersistedProperty(r,n){var i;r===ut.LogsQueue&&e((i=n)!==null&&i!==void 0?i:[])},Ot:r=>this.Ot(r),getLibraryId:()=>Y.LIB_NAME,getLibraryVersion:()=>Y.LIB_VERSION}}Ot(t){return new Promise((e=>{if(Ru(this.Sa,3))e({kind:"fatal",error:ki(void 0,"logs endpoint is unreachable, dropping batch")});else{var s=!1,r=i=>{s||(s=!0,clearTimeout(n),e(i))},n=setTimeout((()=>{this.rt.warn("Logs request timed out before receiving a response"),r({kind:"retry-later",error:ki(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:i=>{var o=i.statusCode;if(this.ku(o),o>=200&&300>o)r({kind:"ok"});else if(o===413)r({kind:"too-large"});else if(o!==0&&o!==429&&500>o)r({kind:"fatal",error:new Error("logs request failed with status "+o)});else{var a;o===0?(i.error||this.rt.warn("Logs request failed before receiving an HTTP response"),r({kind:"retry-later",error:ki(i.error,"logs request failed before receiving an HTTP response")})):r({kind:"retry-later",error:(a=i.error)!==null&&a!==void 0?a:new Error("logs request failed with status "+o)})}}})}}))}ku(t){(t!==0||this._instance.__loaded)&&(this.Sa=Tu(t,this.Sa,3,(()=>this.rt.warn("Log requests are failing before receiving an HTTP response; this can happen due to network issues, CORS, browser blocking, or ad blockers. Stopped sending logs; will try again when connectivity changes."))))}bu(t){this.tr.length>0&&this.xu(t,this.tr,this.fu,Y.LIB_NAME,(e=>{this.tr=e})),this.su.length>0&&this.xu(t,this.su,this.mu,ql,(e=>{this.su=e}))}xu(t,e,s,r,n){if(e.length!==0){var i=e.map((a=>a.record));n([]);var o=ru(i,su(s,Y.LIB_NAME,Y.LIB_VERSION),r,Y.LIB_VERSION);this._instance._send_request({method:"POST",url:this.wu(),data:o,compression:"best-available",batchKey:"logs",transport:t})}}wu(){return this._instance.requestRouter.endpointFor("api","/i/v1/logs")+"?token="+encodeURIComponent(this._instance.config.token)}du(){var t,e={};if(e.distinctId=this._instance.get_distinct_id(),this._instance.sessionManager){var s=this._instance.sessionManager.checkAndGetSessionAndWindowId(!0),r=s.windowId,n=s.sessionStartTimestamp,i=s.lastActivityTimestamp;e.sessionId=s.sessionId,e.windowId=r,D(n)||(e.sessionStartTimestamp=n),D(i)||(e.lastActivityTimestamp=i)}if($!=null&&(t=$.location)!=null&&t.href&&(e.currentUrl=this._instance.config.disable_capture_url_hashes?Ct($.location.href):$.location.href),this._instance.featureFlags){var o=this._instance.featureFlags.getFlags();o&&o.length>0&&(e.activeFeatureFlags=o)}return e}}},Af={metrics:class{constructor(t){this.rt=se("[metrics]"),this._instance=t}initialize(){}vu(){var t,e,s=(t=this._instance)==null||(t=t.config)==null?void 0:t.metrics;return this.ou&&this.cu===s||((e=this.ou)==null||e.reset(),this.cu=s,this.ou=new Th(this.hu(),(function(r){var n,i,o,a,l,u=r?.resourceAttributes;return{serviceName:(n=u?.["service.name"])!==null&&n!==void 0?n:r?.serviceName,serviceVersion:(i=u?.["service.version"])!==null&&i!==void 0?i:r?.serviceVersion,environment:(o=u?.["deployment.environment"])!==null&&o!==void 0?o:r?.environment,resourceAttributes:u,beforeSend:r?.beforeSend,flushIntervalMs:(a=r?.flushIntervalMs)!==null&&a!==void 0?a:1e4,maxSeriesPerFlush:(l=r?.maxSeriesPerFlush)!==null&&l!==void 0?l:1e3}})(s),this.rt)),this.ou}count(t,e,s){e===void 0&&(e=1),this.vu().count(t,e,s)}gauge(t,e,s){this.vu().gauge(t,e,s)}histogram(t,e,s){this.vu().histogram(t,e,s)}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((s=>this.rt.error("PostHog metrics flush failed:",s)))}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:s=>e.Jt(s),getLibraryId:()=>Y.LIB_NAME,getLibraryVersion:()=>Y.LIB_VERSION}}Jt(t,e){return new Promise((s=>{var r=!1,n=o=>{r||(r=!0,clearTimeout(i),s(o))},i=setTimeout((()=>n({kind:"retry-later",error:new Error("metrics request timed out")})),9e4);this._instance._send_request(w({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)n({kind:"ok"});else if(a===413)n({kind:"too-large"});else if(a!==0&&a!==429&&500>a)n({kind:"fatal",error:new Error("metrics request failed with status "+a)});else{var l;n({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)}}},$f=w({},Rn,yf,wf,bf,Ef,Sf,kf,xf,If,Cf,Ff,Pf,Af);Te.__defaultExtensionClasses=w({},$f);(function(){Y.SDK_DIST_CHANNEL="npm";var t=Ys[os]=new Te;return(function(){function e(){e.done||(e.done=!0,ad=!1,Z(Ys,(function(s){s._dom_loaded()})))}C!=null&&C.addEventListener?C.readyState==="complete"?e():ne(C,"DOMContentLoaded",e,{capture:!1}):v&&k.error("Browser doesn't support `document.addEventListener` so PostHog couldn't be initialized")})(),t})();const cd="CodeFile",ud="GeneratedCode",Rf={CustomAction:"A",CustomWidget:"W",CustomFunction:"F",CustomClass:"C",CodeFile:"C"};function kt(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function fo(t){return String(t||"").trim().replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function Tf(t={},e=0){const s=fo(t.artifactType||t.type||cd),r=fo(t.artifactName||t.name||t.fileName||`${ud}-${e+1}`);return`${s||"artifact"}-${r||e+1}`}function dd(t={},e=0){const s=kt(t),r=s.artifactType||s.type||cd,n=s.artifactName||s.name||ud;let i=s.fileName||n;return i.endsWith(".dart")||(i+=".dart"),{id:fo(s.id)||Tf({...s,artifactType:r,artifactName:n,fileName:i},e),artifactType:r,artifactName:n,fileName:i,deployPath:s.deployPath||"",description:s.description||"",code:s.code||s.content||"",dependencies:hd(s.dependencies),imports:Array.isArray(s.imports)?s.imports:[],publicApi:Array.isArray(s.publicApi)?s.publicApi:[],relationships:pd(s.relationships),deployStatus:s.deployStatus||"pending",review:s.review||null,metadata:kt(s.metadata),codeType:s.codeType||Rf[r]||"O"}}function hd(t){return t?Array.isArray(t)?t.map(e=>{if(typeof e=="string")return{name:e,version:null,inferred:!1};const s=kt(e),r=s.name||s.package;return r?{name:r,version:s.version||null,versionRequired:!!(s.versionRequired||s.required),inferred:!!s.inferred,...s.reason?{reason:s.reason}:{}}:null}).filter(Boolean):Object.entries(kt(t)).map(([e,s])=>({name:e,version:s||null,inferred:!1})):[]}function pd(t){return t?(Array.isArray(t)?t:[t]).map(e=>{const s=kt(e);return!s.from&&!s.to?null:{from:s.from||null,to:s.to||null,type:s.type||"uses",description:s.description||""}}).filter(Boolean):[]}function go(t){if(typeof t!="string")return null;const e=t.trim();if(!e)return null;try{return JSON.parse(e)}catch{const s=e.match(/```(?:json)?\s*([\s\S]*?)```/i);if(!s)return null;try{return JSON.parse(s[1].trim())}catch{return null}}}function or(t,e={}){const s=[],r=typeof t=="string"?go(t):t,i=kt(r||{});!r&&typeof t=="string"&&s.push("Structured bundle parse failed; using legacy single-artifact fallback.");const o=Array.isArray(i.artifacts)?i.artifacts:[{artifactType:i.artifactType||e.artifactType,artifactName:i.artifactName||e.artifactName,fileName:i.fileName||e.fileName,description:i.description,code:i.code||e.code||(typeof t=="string"?t:""),dependencies:i.dependencies||e.dependencies,relationships:i.relationships||e.relationships}];o.forEach((d,h)=>{!d?.artifactType&&!d?.type&&s.push(`Artifact ${h+1} has no artifactType; it will deploy as a standalone code file under lib/custom_code/ root.`)});const a=o.map((d,h)=>dd(d,h)),l=new Map(o.map((d,h)=>[kt(d).id,a[h]?.id]).filter(([d,h])=>d&&h)),u=d=>l.get(d)||d,c=pd(i.relationships||e.relationships).map(d=>({...d,from:d.from?u(d.from):d.from,to:d.to?u(d.to):d.to}));return{schemaVersion:i.schemaVersion||e.schemaVersion||null,id:i.id||e.id||"bundle-current",title:i.title||i.name||e.title||"Generated artifact bundle",description:i.description||e.description||"",artifacts:a,dependencies:hd(i.dependencies||e.dependencies),relationships:c,deployOrder:Array.isArray(i.deployOrder)?i.deployOrder.map(u):a.map(d=>d.id),warnings:[...s,...Array.isArray(i.warnings)?i.warnings:[]],metadata:kt(i.metadata)}}function gn(t){return or(t).artifacts[0]||dd()}function yt(t){if(typeof t!="string")return t??"";const e=t.trim();if(!e)return"";try{return JSON.parse(e)}catch{return t}}function ys(t){return JSON.stringify(t,null,2)}function Nf(t){return ys({task:"architect",userRequest:String(t??"")})}function Mf(t){const e=yt(t);return e&&typeof e=="object"&&typeof e.task=="string"?ys(e):ys({task:"generate_bundle",bundleSpec:e})}function Lf(t){return ys({task:"review_bundle",generatedBundle:yt(t),outputRequirements:{bundleReview:["status","score","summary","manualActions","findings"],scoreRange:[0,100],eachArtifact:["id","review.status","review.findings"],manualActions:{definition:"Setup the developer must perform by hand in the FlutterFlow editor that FlutterFlow will NOT do for them.",exclude:["creating the Custom Action, Widget or Code File itself - deploying the code creates it","declaring parameters or return values FlutterFlow derives from the function signature","anything that resolves as a side effect of using the action or widget in the editor","generic advice such as testing, reviewing or rebuilding the app"],preferEmpty:"Return an empty array when nothing qualifies - an empty list is the expected result for most bundles."}}})}function Qo(t,e=null){const s={stage:t};return e!=null&&(s.bundle=yt(e)),s}function Of({bundleSpec:t,artifactBundle:e,bundleReview:s,artifactId:r,userFeedback:n}){return ys({task:"regenerate_artifact",artifactId:r,bundleSpec:yt(t),artifactBundle:yt(e),bundleReview:yt(s),userFeedback:String(n)})}function fd({bundleSpec:t,artifactBundle:e,bundleReview:s,userFeedback:r}){return ys({task:"regenerate_bundle",bundleSpec:yt(t),artifactBundle:yt(e),bundleReview:yt(s),userFeedback:String(r??"")})}const Gl={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"},Df=["sanitizationResult","modelArmor","modelArmorResult","data","result","error"];function Le(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function Bf(t){return Le(t)?typeof t.filterMatchState=="string"||typeof t.invocationResult=="string"||Array.isArray(t.matchedFilters)||Le(t.filterSummary)||Le(t.filterResults):!1}function gd(t,e=0){if(!Le(t)||e>3)return null;if(Bf(t))return t;for(const s of Df){const r=t[s];if(Le(r)){const n=gd(r,e+1);if(n)return n}}return null}function mn(t){return Array.isArray(t)?t.some(mn):Le(t)?t.matched===!0||t.matchState==="MATCH_FOUND"?!0:Object.values(t).some(mn):!1}function mo(t){return Array.isArray(t)?t.some(mo):Le(t)?typeof t.executionState=="string"&&t.executionState!=="EXECUTION_SUCCESS"?!0:Object.values(t).some(mo):!1}function md(t){return{csamFilterFilterResult:"csam",maliciousUriFilterResult:"malicious_uris",piAndJailbreakFilterResult:"pi_and_jailbreak",raiFilterResult:"rai",sdpFilterResult:"sdp",virusScanFilterResult:"virus_scan"}[t]||t}function jf(t,e){if(Le(t))for(const[s,r]of Object.entries(t)){if(!Le(r))continue;const n=Le(r.categories)?r.categories:{},i=Object.entries(n).filter(([,o])=>Le(o)&&o.matched===!0).map(([o])=>o);i.length>0?i.forEach(o=>e.add(o)):r.matched===!0&&e.add(md(s))}}function Uf(t,e){if(!t)return;const s=Array.isArray(t)?t.flatMap(r=>Le(r)?Object.entries(r):[]):Object.entries(t);for(const[r,n]of s){if(!mn(n))continue;const i=md(r),o=n?.raiFilterResult?.raiFilterTypeResults||(i==="rai"?n?.raiFilterTypeResults:null),a=Le(o)?Object.entries(o).filter(([,l])=>mn(l)).map(([l])=>l):[];a.length>0?a.forEach(l=>e.add(l)):e.add(i)}}function Hf(t){return Gl[t]?Gl[t]:String(t).replace(/([a-z])([A-Z])/g,"$1 $2").replace(/_/g," ").toLowerCase()}function Kl(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 Wf(t){const e=gd(t);if(!e)return null;const s=new Set(Array.isArray(e.matchedFilters)?e.matchedFilters:[]);jf(e.filterSummary,s),Uf(e.filterResults,s);const r=e.blocked===!0||e.filterMatchState==="MATCH_FOUND"||s.size>0,n=e.invocationResult||null,i=mo(e.filterSummary||e.filterResults);return!r&&!i&&!["PARTIAL","FAILURE"].includes(n)?null:{kind:r?"blocked":"unavailable",invocationResult:n,matchedFilters:[...s]}}function zf(t,e){const s=Wf(t);if(!s)return null;const r=[...new Set(s.matchedFilters.map(Hf))],n=s.kind==="blocked",i=new Error(n?`Safety screening blocked this pipeline step for ${Kl(r)}.`:"Safety screening could not be completed. Please try again.");return i.name="ModelArmorError",i.code=n?"MODEL_ARMOR_BLOCKED":"MODEL_ARMOR_UNAVAILABLE",i.isModelArmor=!0,i.pipelineStep=e,i.userTitle=n?"Request blocked for safety":"Safety check unavailable",i.userMessage=n?`The safety check detected ${Kl(r)}. Edit your request to remove or rephrase the flagged content, then run the pipeline again.`:"The safety service did not finish all of its checks. Please wait a moment and run the pipeline again.",i.retryExplanation=n?"Trying another model would not change this safety decision.":"A fallback model was not attempted because safety screening must complete first.",i.matchedFilters=s.matchedFilters,i}function qf(t){return String(t||"").replace(/\/\*[\s\S]*?\*\//g,"").replace(/\/\/[^\n]*/g,"")}function Jl(t){const e=/^(import|export|part|library|class|enum|extension|typedef|mixin|abstract|const|final|var|late)\b/,s=[];for(const r of qf(t).split(` +`)){if(!/^[A-Za-z_$]/.test(r)||e.test(r))continue;const n=r.match(/^[\w$<>,?\s[\]]+?\s([a-zA-Z_$][\w$]*)\s*\(/);n&&s.push(n[1])}return s}function ea(t,e){const s=t.replace(/\.dart$/,"");if(e==="W")return s.replace(/(^|_)(\w)/g,(r,n,i)=>i.toUpperCase());if(e==="A"){const r=s.replace(/(^|_)(\w)/g,(n,i,o)=>o.toUpperCase());return r.charAt(0).toLowerCase()+r.slice(1)}return e==="F"?"CustomFunctions":e==="C"?t.endsWith(".dart")?t:`${t}.dart`:s}async function Yl(t){const e=new TextEncoder().encode(String(t||"")),s=await globalThis.crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(s),r=>r.toString(16).padStart(2,"0")).join("")}async function Vf(t,e=new Map){const s={},r=new Set;for(const[o,a]of t.entries()){if(a.type==="D"||a.type==="O")continue;const l=ea(o,a.type),u={old_identifier_name:l,new_identifier_name:l,type:a.type,is_deleted:!1,current_checksum:await Yl(a.content)},c=e.get(a.path);if(c!==void 0&&(u.original_checksum=await Yl(c)),s[o]=u,a.type==="F"){const d=Jl(a.content);(d.length>0?d:[a.functionName].filter(Boolean)).forEach(p=>r.add(p))}}const n=new Set(Jl(e.get("lib/flutter_flow/custom_functions.dart")||"")),i={functions_to_rename:[],functions_to_delete:[],functions_to_add:Array.from(r).filter(o=>!n.has(o))};return{fileMapContents:JSON.stringify(s),functionsMapContents:JSON.stringify(i)}}const Gf=new Set(["CustomWidget","CustomAction","CustomFunction","CustomClass","CodeFile"]),Zl={CustomWidget:"custom_code/widgets/",CustomAction:"custom_code/actions/",CustomFunction:"flutter_flow/custom_functions.dart",CustomClass:"custom_code/",CodeFile:"custom_code/"},Kf=new Set(["void","dynamic","String","int","double","num","bool","Color","DateTime","DateTimeRange","LatLng","FFPlace","FFUploadedFile","DocumentReference","List"]),Jf=["Struct","Record"],Yf=[{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=>Ii(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=>Ii(t).some(e=>{const s=/^\s*final\s+(?:double|int|String|bool|Color|num)\s+(\w+)\s*;/gm;let r;for(;(r=s.exec(e))!==null;){const n=r[1];if(!(new RegExp(`this\\.${n}\\s*=(?!=)`).test(e)||new RegExp(`[:,]\\s*${n}\\s*=(?!=)`).test(e)))return!0}return!1}),pos:`class W extends StatefulWidget { const W({required this.value}); final double value; }`,neg:`class _P { @@ -14,7 +14,7 @@ class W extends StatefulWidget { final double value; }`},{id:"asset-without-anchor",severity:"warning",message:'CustomWidget calls Image.asset with a path arriving as a String parameter. An asset reaches the build only when a FlutterFlow widget NODE references it - a filename passed as a parameter does not count, so the image renders as a broken-image icon on device. "Download Unused Project Assets" does not fix it (FlutterFlow issues 522, 2271, 3799). Keep something in the UI referencing the file, or load it over the network instead.',detect:t=>/Image\.asset\s*\(/.test(t)&&/final\s+String\??\s+\w*[Pp]ath\b/.test(t),pos:`class W extends StatefulWidget { final String? imagePath; } var x = Image.asset(widget.imagePath);`,neg:`class W extends StatefulWidget { final String? imagePath; } -var x = Image.network(widget.imagePath);`},{id:"unsupported-param-type",severity:"error",message:"CustomWidget exposes a Flutter data type FlutterFlow cannot express as a Define Parameter: TextStyle, BoxShadow, FontWeight, FontStyle, TextDirection, TextAlign, EdgeInsets, Offset, Alignment/AlignmentGeometry, Border, BorderRadius, BoxDecoration, BoxConstraints, BorderSide, Gradient, or ThemeData. FlutterFlow's supported data types (docs.flutterflow.io/resources/data-representation/data-types) are only int, double, bool, string, Color, Image, DateTime, Json, LatLng, and the FF objects, so this parameter cannot be configured in the editor and the widget will not place or compile. Expose primitives instead (color, fontSize as double?, fontWeight via a custom enum, doubles for spacing).",detect:t=>Ci(t).some(e=>/final\s+(TextStyle|BoxShadow|FontWeight|FontStyle|TextDirection|TextAlign|EdgeInsets|Offset|Alignment(?:Geometry)?|Border(?:Radius|Side)?|BoxDecoration|BoxConstraints|Gradient|LinearGradient|RadialGradient|ThemeData)\??\s+\w+\s*;/.test(e)),pos:`class W extends StatefulWidget { +var x = Image.network(widget.imagePath);`},{id:"unsupported-param-type",severity:"error",message:"CustomWidget exposes a Flutter data type FlutterFlow cannot express as a Define Parameter: TextStyle, BoxShadow, FontWeight, FontStyle, TextDirection, TextAlign, EdgeInsets, Offset, Alignment/AlignmentGeometry, Border, BorderRadius, BoxDecoration, BoxConstraints, BorderSide, Gradient, or ThemeData. FlutterFlow's supported data types (docs.flutterflow.io/resources/data-representation/data-types) are only int, double, bool, string, Color, Image, DateTime, Json, LatLng, and the FF objects, so this parameter cannot be configured in the editor and the widget will not place or compile. Expose primitives instead (color, fontSize as double?, fontWeight via a custom enum, doubles for spacing).",detect:t=>Ii(t).some(e=>/final\s+(TextStyle|BoxShadow|FontWeight|FontStyle|TextDirection|TextAlign|EdgeInsets|Offset|Alignment(?:Geometry)?|Border(?:Radius|Side)?|BoxDecoration|BoxConstraints|Gradient|LinearGradient|RadialGradient|ThemeData)\??\s+\w+\s*;/.test(e)),pos:`class W extends StatefulWidget { const W({this.textStyle}); final TextStyle? textStyle; @override _S createState() => _S(); @@ -24,51 +24,51 @@ class _S extends State { @override Widget build(BuildContext c) => const Size final double? width; @override _S createState() => _S(); } -class _S extends State { @override Widget build(BuildContext c) => Padding(padding: const EdgeInsets.all(8), child: const SizedBox()); }`}];function Qe(t,e,s){return{artifactId:t.id,artifactName:t.artifactName,artifactType:t.artifactType,severity:e,message:s}}function lr(t){let e="",s=0;for(;s"&&(s--,s===0))return{inner:t.slice(e+1,r),end:r+1};return null}function eg(t,e){const s=new RegExp(`class\\s+${e}\\b[^{]*\\{`).exec(t);if(!s)return null;let r=0;for(let n=s.index+s[0].length-1;ntg(t).usable);function rg(t=""){const e=lr(t);return sg.filter(s=>s.detect(e)).map(({id:s,severity:r,message:n})=>({id:s,severity:r,message:n}))}function ng(t){const e=[],s=t.matchAll(/\bFuture\b/g);for(const r of s){let n=r.index+6,i=null;const o=n;for(;no;if(t[n]==="<"){const u=Qf(t,n);if(!u||(i=u.inner.replace(/\s+/g," ").trim(),n=u.end,!/\s/.test(t[n]||"")))continue;for(;nQl(o.functionName)===r);if(n)return n;const i=o=>!o.functionName.startsWith("_");return s.find(i)||s[0]}function Nn(t=""){return Array.from(lr(t).matchAll(/\b(?:class|enum)\s+([A-Za-z_]\w*)/g),e=>e[1])}function ig(t="",e=""){return sa(t,e)?.returnType||null}function ec(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 og(t,e){const s=Nn(e);if(s.length===0)return null;const n=String(t||"").split("/").pop().replace(/\.dart$/,"");if(s.some(l=>ec(l)===n)||s.length>1)return null;const[o]=s,a=`${ec(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 ra(t){return String(t||"").replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,"")}function ag(t,e,s=""){const r=sa(e,s)?.functionName;if(!r)return null;const n=String(t||"").split("/").pop(),i=ta(n,"A");if(i===r)return null;const o=`${ra(r)}.dart`;return`File name "${n}" does not match Action "${r}". FlutterFlow derives the action from the file name, so it looks for "${i}" and reports Action "${i}" declaration not found. Rename the file to "${o}" - FlutterFlow puts an underscore before every capital - or rename the function to "${i}".`}function lg(t="",e=""){return sa(t,e)!==null}function cg(t,e=new Set){return(t?.match(/[A-Za-z_]\w*/g)||[]).filter(r=>Yf.has(r)?!1:!Zf.some(i=>r.endsWith(i))||e.has(r))}function ug(t,{functionName:e="",declaredTypes:s=new Set}={}){const r=ig(t,e),n=cg(r,s);if(n.length===0)return null;const[i]=n;let o;return s.has(i)?o=`uses Code File type "${i}", which FlutterFlow cannot process as an Action Return Value`:r===i?o="is not a FlutterFlow Action Return Value":o=`uses type "${i}", which is not a FlutterFlow Action Return Value`,`CustomAction return type "${r}" ${o}. Return JSON (Future) or an existing FlutterFlow Data Type (*Struct) instead.`}function dg(t,e={}){const s=[],r=t.fileName||"",n=t.code||"";if(Jf.has(t.artifactType)||s.push(Qe(t,"error",`Unsupported artifact type "${t.artifactType}".`)),r.endsWith(".dart")||s.push(Qe(t,"error","FlutterFlow custom code artifacts must use .dart files.")),!n.trim())return s.push(Qe(t,"warning","Generated artifact has no Dart code yet.")),s;if(t.artifactType==="CustomWidget"){/class\s+\w+\s+extends\s+(StatelessWidget|StatefulWidget)/.test(n)||s.push(Qe(t,"warning","CustomWidget code should declare a widget class extending StatelessWidget or StatefulWidget."));for(const i of rg(n))s.push(Qe(t,i.severity,i.message))}if(t.artifactType==="CustomAction"&&!lg(n,t.artifactName)&&s.push(Qe(t,"warning","CustomAction code should expose an async Future function callable from FlutterFlow.")),t.artifactType==="CustomAction"){const i=e.declaredTypes||new Set(Nn(n)),o=ug(n,{functionName:t.artifactName,declaredTypes:i});o&&s.push(Qe(t,"error",o));const a=ag(r,n,t.artifactName);a&&s.push(Qe(t,"error",a))}if(t.artifactType==="CustomFunction"&&/class\s+\w+\s+extends\s+(StatelessWidget|StatefulWidget)/.test(n)&&s.push(Qe(t,"warning","CustomFunction should be a callable function, not a widget class.")),t.artifactType==="CustomClass"||t.artifactType==="CodeFile"){const i=og(r,n);i&&s.push(Qe(t,"info",i))}return s}function hg(t){const e=Array.isArray(t?.artifacts)?t.artifacts:[],s=new Set(e.flatMap(i=>Nn(i.code||""))),r=e.flatMap(i=>dg(i,{declaredTypes:s})),n=e.map(i=>({artifactId:i.id,fileName:i.fileName,pathHint:Xl[i.artifactType]||Xl.CodeFile}));return{valid:r.every(i=>i.severity!=="error"),findings:r,deployHints:n}}const tc="// DO NOT REMOVE OR MODIFY THE CODE ABOVE!";function sc(t){return(/^\s*import\s+['"]([^'"]+)['"]/.exec(t)||[])[1]||null}function pg(t=""){const e=t.indexOf(tc);return e===-1?t:t.slice(e+tc.length).replace(/^\s*\n/,"")}const fg=/^\s*import\s+['"][^'"]+['"]\s*;\s*(?:\/\/.*)?$/;function gg(t="",e=""){const s=pg(t),r=new Set((e.match(/^\s*import .*$/gm)||[]).map(sc).filter(Boolean)),n=s.split(` -`).filter(i=>{const o=sc(i);return o===null||!r.has(o)?!0:!fg.test(i)}).join(` -`).replace(/^\s*\/\/ Automatic FlutterFlow imports\s*$/m,"").replace(/^\s*\n+/,"");return e+n}const mg=new Set(["flutter","flutter_test","flutter_driver","flutter_localizations"]);function yd(t){let e="",s=0;for(;s{const r=s.name||s.package;if(!r||r==="flutter")return e;const n=s.versionRequired||s.required;return e[r]=n&&s.version||"",e},{})}function bg(t){const e=new Map,s=new Map,r=[];for(const n of t)e.has(n.fileName)?r.push(`Duplicate deploy file name "${n.fileName}" for artifacts "${e.get(n.fileName)}" and "${n.artifactId}".`):e.set(n.fileName,n.artifactId),s.has(n.path)?r.push(`Duplicate deploy path "${n.path}" for artifacts "${s.get(n.path)}" and "${n.artifactId}".`):s.set(n.path,n.artifactId);return r}function Eg(t,e={}){const s=Array.isArray(t?.artifacts)?t.artifacts:[],n=(e.selectedArtifactIds||t?.deployOrder||s.map(p=>p.id)).map(p=>s.find(f=>f.id===p)).filter(Boolean),i=[...t?.warnings||[]];let o=[];n.forEach(p=>{const f=wg(p),g=p.fixedCode||p.code||"",m=p.codeType||_g[p.artifactType]||Ne.OTHER;g.trim()||i.push(`${p.artifactName||p.id} has no generated code.`),o.push({artifactId:p.id,artifactName:p.artifactName,artifactType:p.artifactType,fileName:f,content:g,type:m,path:p.deployPath||yg(f,m),deployPath:p.deployPath||"",deployMode:"customCodeSync"})});const a="lib/flutter_flow/custom_functions.dart",l=o.map((p,f)=>({entry:p,index:f})).filter(({entry:p})=>p.type===Ne.FUNCTION&&p.path===a);if(l.length>1){const p=l[0],f={...p.entry,artifactId:l.map(({entry:m})=>m.artifactId).join("+"),artifactName:p.entry.artifactName,content:l.map(({entry:m})=>`// ${m.artifactId} +class _S extends State { @override Widget build(BuildContext c) => Padding(padding: const EdgeInsets.all(8), child: const SizedBox()); }`}];function Qe(t,e,s){return{artifactId:t.id,artifactName:t.artifactName,artifactType:t.artifactType,severity:e,message:s}}function ar(t){let e="",s=0;for(;s"&&(s--,s===0))return{inner:t.slice(e+1,r),end:r+1};return null}function Xf(t,e){const s=new RegExp(`class\\s+${e}\\b[^{]*\\{`).exec(t);if(!s)return null;let r=0;for(let n=s.index+s[0].length-1;nQf(t).usable);function tg(t=""){const e=ar(t);return eg.filter(s=>s.detect(e)).map(({id:s,severity:r,message:n})=>({id:s,severity:r,message:n}))}function sg(t){const e=[],s=t.matchAll(/\bFuture\b/g);for(const r of s){let n=r.index+6,i=null;const o=n;for(;no;if(t[n]==="<"){const u=Zf(t,n);if(!u||(i=u.inner.replace(/\s+/g," ").trim(),n=u.end,!/\s/.test(t[n]||"")))continue;for(;nXl(o.functionName)===r);if(n)return n;const i=o=>!o.functionName.startsWith("_");return s.find(i)||s[0]}function Tn(t=""){return Array.from(ar(t).matchAll(/\b(?:class|enum)\s+([A-Za-z_]\w*)/g),e=>e[1])}function rg(t="",e=""){return ta(t,e)?.returnType||null}function Ql(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 ng(t,e){const s=Tn(e);if(s.length===0)return null;const n=String(t||"").split("/").pop().replace(/\.dart$/,"");if(s.some(l=>Ql(l)===n)||s.length>1)return null;const[o]=s,a=`${Ql(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 sa(t){return String(t||"").replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,"")}function ig(t,e,s=""){const r=ta(e,s)?.functionName;if(!r)return null;const n=String(t||"").split("/").pop(),i=ea(n,"A");if(i===r)return null;const o=`${sa(r)}.dart`;return`File name "${n}" does not match Action "${r}". FlutterFlow derives the action from the file name, so it looks for "${i}" and reports Action "${i}" declaration not found. Rename the file to "${o}" - FlutterFlow puts an underscore before every capital - or rename the function to "${i}".`}function og(t="",e=""){return ta(t,e)!==null}function ag(t,e=new Set){return(t?.match(/[A-Za-z_]\w*/g)||[]).filter(r=>Kf.has(r)?!1:!Jf.some(i=>r.endsWith(i))||e.has(r))}function lg(t,{functionName:e="",declaredTypes:s=new Set}={}){const r=rg(t,e),n=ag(r,s);if(n.length===0)return null;const[i]=n;let o;return s.has(i)?o=`uses Code File type "${i}", which FlutterFlow cannot process as an Action Return Value`:r===i?o="is not a FlutterFlow Action Return Value":o=`uses type "${i}", which is not a FlutterFlow Action Return Value`,`CustomAction return type "${r}" ${o}. Return JSON (Future) or an existing FlutterFlow Data Type (*Struct) instead.`}function cg(t,e={}){const s=[],r=t.fileName||"",n=t.code||"";if(Gf.has(t.artifactType)||s.push(Qe(t,"error",`Unsupported artifact type "${t.artifactType}".`)),r.endsWith(".dart")||s.push(Qe(t,"error","FlutterFlow custom code artifacts must use .dart files.")),!n.trim())return s.push(Qe(t,"warning","Generated artifact has no Dart code yet.")),s;if(t.artifactType==="CustomWidget"){/class\s+\w+\s+extends\s+(StatelessWidget|StatefulWidget)/.test(n)||s.push(Qe(t,"warning","CustomWidget code should declare a widget class extending StatelessWidget or StatefulWidget."));for(const i of tg(n))s.push(Qe(t,i.severity,i.message))}if(t.artifactType==="CustomAction"&&!og(n,t.artifactName)&&s.push(Qe(t,"warning","CustomAction code should expose an async Future function callable from FlutterFlow.")),t.artifactType==="CustomAction"){const i=e.declaredTypes||new Set(Tn(n)),o=lg(n,{functionName:t.artifactName,declaredTypes:i});o&&s.push(Qe(t,"error",o));const a=ig(r,n,t.artifactName);a&&s.push(Qe(t,"error",a))}if(t.artifactType==="CustomFunction"&&/class\s+\w+\s+extends\s+(StatelessWidget|StatefulWidget)/.test(n)&&s.push(Qe(t,"warning","CustomFunction should be a callable function, not a widget class.")),t.artifactType==="CustomClass"||t.artifactType==="CodeFile"){const i=ng(r,n);i&&s.push(Qe(t,"info",i))}return s}function ug(t){const e=Array.isArray(t?.artifacts)?t.artifacts:[],s=new Set(e.flatMap(i=>Tn(i.code||""))),r=e.flatMap(i=>cg(i,{declaredTypes:s})),n=e.map(i=>({artifactId:i.id,fileName:i.fileName,pathHint:Zl[i.artifactType]||Zl.CodeFile}));return{valid:r.every(i=>i.severity!=="error"),findings:r,deployHints:n}}const ec="// DO NOT REMOVE OR MODIFY THE CODE ABOVE!";function tc(t){return(/^\s*import\s+['"]([^'"]+)['"]/.exec(t)||[])[1]||null}function dg(t=""){const e=t.indexOf(ec);return e===-1?t:t.slice(e+ec.length).replace(/^\s*\n/,"")}const hg=/^\s*import\s+['"][^'"]+['"]\s*;\s*(?:\/\/.*)?$/;function pg(t="",e=""){const s=dg(t),r=new Set((e.match(/^\s*import .*$/gm)||[]).map(tc).filter(Boolean)),n=s.split(` +`).filter(i=>{const o=tc(i);return o===null||!r.has(o)?!0:!hg.test(i)}).join(` +`).replace(/^\s*\/\/ Automatic FlutterFlow imports\s*$/m,"").replace(/^\s*\n+/,"");return e+n}const fg=new Set(["flutter","flutter_test","flutter_driver","flutter_localizations"]);function vd(t){let e="",s=0;for(;s{const r=s.name||s.package;if(!r||r==="flutter")return e;const n=s.versionRequired||s.required;return e[r]=n&&s.version||"",e},{})}function yg(t){const e=new Map,s=new Map,r=[];for(const n of t)e.has(n.fileName)?r.push(`Duplicate deploy file name "${n.fileName}" for artifacts "${e.get(n.fileName)}" and "${n.artifactId}".`):e.set(n.fileName,n.artifactId),s.has(n.path)?r.push(`Duplicate deploy path "${n.path}" for artifacts "${s.get(n.path)}" and "${n.artifactId}".`):s.set(n.path,n.artifactId);return r}function wg(t,e={}){const s=Array.isArray(t?.artifacts)?t.artifacts:[],n=(e.selectedArtifactIds||t?.deployOrder||s.map(p=>p.id)).map(p=>s.find(f=>f.id===p)).filter(Boolean),i=[...t?.warnings||[]];let o=[];n.forEach(p=>{const f=_g(p),g=p.fixedCode||p.code||"",m=p.codeType||mg[p.artifactType]||Ne.OTHER;g.trim()||i.push(`${p.artifactName||p.id} has no generated code.`),o.push({artifactId:p.id,artifactName:p.artifactName,artifactType:p.artifactType,fileName:f,content:g,type:m,path:p.deployPath||vg(f,m),deployPath:p.deployPath||"",deployMode:"customCodeSync"})});const a="lib/flutter_flow/custom_functions.dart",l=o.map((p,f)=>({entry:p,index:f})).filter(({entry:p})=>p.type===Ne.FUNCTION&&p.path===a);if(l.length>1){const p=l[0],f={...p.entry,artifactId:l.map(({entry:m})=>m.artifactId).join("+"),artifactName:p.entry.artifactName,content:l.map(({entry:m})=>`// ${m.artifactId} ${m.content}`).join(` -`)},g=new Set(l.slice(1).map(({index:m})=>m));o=o.filter((m,_)=>!g.has(_)),o[p.index]=f}const u={...rc(t?.dependencies),...n.reduce((p,f)=>({...p,...rc(f.dependencies)}),{})},c={};n.forEach(p=>{na(p.code||"").forEach(f=>{f in u||(c[f]="")})});const d={...c,...u},h=bg(o);return{bundleId:t?.id||"bundle-current",title:t?.title||"Generated artifact bundle",fileEntries:o,dependencies:d,relationships:t?.relationships||[],warnings:i,errors:h}}function Sg(t){return String(t||"").match(/\bclass\s+([A-Z][A-Za-z0-9_]*)\b/)?.[1]}function xg(t){return String(t||"").split("/").pop().replace(/\.dart$/,"").split(/[^A-Za-z0-9]+/).filter(Boolean).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join("")}function kg(t,e){const r=[xg(t),Sg(e.content),e.artifactName].find(n=>/^[A-Z][A-Za-z0-9_]*$/.test(String(n||"")));if(!r)throw new Error(`Cannot derive a FlutterFlow custom class name for ${t}.`);return r}function Ig(t,e=new Map){const s=[];for(const[r,n]of t.entries())n.type!=="C"||e.has(n.path)||s.push({artifactId:n.artifactId||r,className:kg(r,n),content:n.content,fileName:r,path:n.path});return s}function Cg(t,e){const s=new Set(e.map(r=>r.path));return new Map(Array.from(t.entries()).filter(([,r])=>!s.has(r.path)))}const nc={pass:0,warning:1,fail:2},Fg=["manualActions"];function De(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function gt(...t){for(const e of t){if(typeof e=="string"&&e.trim())return e.trim();if(Array.isArray(e)&&e.length>0){const s=e.filter(r=>typeof r=="string").join(` -`);if(s)return s}}return""}function tt(t){return t==null?[]:Array.isArray(t)?t:[t]}function Pg(t){const e=De(t).value??t;if(e==null||typeof e=="string"&&e.trim()==="")return null;const s=Number(e);if(Number.isFinite(s))return s;const r=String(t||"").match(/\bscore\b[^\d]{0,12}(\d{1,3})(?:\s*\/\s*100)?/i);return r?Number(r[1]):null}function We(t){return String(t||"").trim().replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function ia(t){const e=String(t||"").toLowerCase();return/(fail|error|critical|block|reject|invalid)/.test(e)?"fail":/(warn|attention|manual|partial|incomplete|concern)/.test(e)?"warning":/(pass|success|ready|approve|valid|clean|info|notice)/.test(e)?"pass":null}function _o(...t){return t.filter(Boolean).reduce((e,s)=>nc[s]>nc[e]?s:e,"pass")}function wd(t,e="warning",s="review"){if(typeof t=="string")return{severity:e,message:t,suggestion:"",source:s};const r=De(t),n=gt(r.message,r.title,r.issue,r.description,r.summary);return n?{severity:ia(r.severity||r.status||r.level)||e,message:n,suggestion:gt(r.suggestion,r.fix,r.recommendation,r.action),source:r.source||s}:null}function yo(t,e="review"){const s=De(t);return[["findings","warning"],["issues","warning"],["criticalIssues","fail"],["errors","fail"],["warnings","warning"],["recommendations","warning"],["requiredFixes","fail"],["suggestions","warning"]].flatMap(([n,i])=>tt(s[n]).map(o=>wd(o,i,e)).filter(Boolean))}function Ag(t,e,s=null){if(typeof t=="string")return{id:`${s||"bundle"}-manual-${e+1}`,title:t,detail:"",location:"",timing:"unspecified",artifactId:s,source:"Code Review"};const r=De(t),n=gt(r.title,r.action,r.step,r.message,r.name,r.description);return n?{id:r.id||`${s||"bundle"}-manual-${e+1}`,title:n,detail:gt(r.detail,r.instructions,r.description),location:gt(r.location,r.flutterFlowPath,r.path),timing:gt(r.timing,r.phase)||"unspecified",artifactId:s,source:gt(r.source)||"Code Review"}:null}function wo(t,e=null){const s=De(t);return Fg.flatMap(r=>tt(s[r])).map((r,n)=>Ag(r,n,e)).filter(Boolean)}function $g(t){let e=typeof t=="string"?mo(t):t;if(!e&&typeof t=="string")return{rawText:t,root:{}};const s=De(e);typeof s.content=="string"&&(e=mo(s.content)||e);const r=De(e),n=De(r.reviewResult||r.codeReview||r.result);return{rawText:"",root:Object.keys(n).length?n:r}}function Rg(t,e){const s=[e.id,e.fileName,e.artifactName].map(We);return t.find(r=>{const n=De(r);return[n.id,n.fileName,n.artifactName,n.name].map(We).some(i=>i&&s.includes(i))})||null}function Tg(t,e){return tt(t?.metadata?.compatibility?.deployHints).find(n=>We(n?.artifactId)===We(e.id)||We(n?.fileName)===We(e.fileName))?.pathHint||""}function Ng(t,e){return tt(t?.relationships).filter(s=>We(s?.from)===We(e.id)||We(s?.to)===We(e.id))}function Mg(t,e){return tt(t?.metadata?.compatibility?.findings).filter(s=>!s?.artifactId||We(s.artifactId)===We(e.id)).map(s=>wd(s,"warning","Compatibility check")).filter(Boolean)}function Lg(t,e,s,r){const n=Rg(e,s),i=De(n?.review||n||s.review),o=Object.keys(i).length>0,a=[...yo(i),...Mg(t,s)],l=wo(i,s.id),u=ia(i.status||i.verdict||i.outcome||i.result),c=a.length?_o(...a.map(h=>h.severity)):null,d=_o(u,c,o?null:"warning");return{...s,index:r,status:d,statusReason:o?gt(i.summary,i.overview,i.assessment,i.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 i.fixedSource=="string"&&i.fixedSource.trim()?i.fixedSource.trim():null,pathHint:Tg(t,s),relationships:Ng(t,s)}}function Og({status:t,score:e,artifactPresentations:s,manualSteps:r}){const n=s.length;if(n===0&&r.length===0)return e==null?"Code review returned no overall summary and no score.":`Reviewed bundle with score ${e}/100.`;const i=s.reduce((a,l)=>(a[l.status]+=1,a),{pass:0,warning:0,fail:0}),o=[];return t&&o.push(`Overall verdict: ${t}.`),n&&o.push(`${n} artifact${n===1?"":"s"}: ${i.pass} pass, ${i.warning} warn, ${i.fail} fail.`),r.length&&o.push(`Do before deploy: ${r.map(a=>a.title).join("; ")}.`),e==null&&o.push("No numeric score (0-100) was returned."),o.join(" ")}function Dg({bundle:t,reviewResult:e}){const s=De(t),r=tt(s.artifacts),{root:n,rawText:i}=$g(e),o=[n.bundleReview,n.overallReview,n.overall,n.bundleSummary,n.summaryReview,n.review].map(De).find(E=>Object.keys(E).length)||{},a=tt(n.artifacts||n.files||n.reviews),l=r.map((E,I)=>Lg(s,a,E,I)),u=yo(n),d=[...yo(o),...u],h=[...wo(o),...wo(n),...l.flatMap(E=>E.manualSteps)].filter((E,I,F)=>F.findIndex(P=>P.title===E.title&&P.artifactId===E.artifactId)===I),p=ia(o.status||o.verdict||o.overallStatus||n.status||n.verdict||n.overallStatus||n.outcome),f=_o(p,...d.map(E=>E.severity),...l.map(E=>E.status)),g=o.score??n.score??n.overallScore??i,m=Pg(g),_=gt(o.headline,o.summary,o.executiveSummary,o.overview,o.assessment,o.conclusion,n.overallSummary,n.headline,n.summary,n.executiveSummary,n.overview,n.assessment,n.conclusion,i)||Og({status:f,score:m,artifactPresentations:l,manualSteps:h}),b=l.reduce((E,I)=>(E[I.status]+=1,E),{pass:0,warning:0,fail:0});return{title:s.title||"Generated artifact bundle",description:s.description||"",status:f,score:m,summary:_,findings:d,manualSteps:h,artifacts:l,counts:b,reviewCoverage:{reviewed:l.filter(E=>E.reviewComplete).length,total:l.length},deployOrder:tt(s.deployOrder),relationships:tt(s.relationships),warnings:tt(s.warnings),compatibility:De(s.metadata?.compatibility)}}const Bg=/^\uFEFF/;function Ds(t){let e=0,s=t.length;for(;ee&&!t[s-1].trim();)s--;return t.slice(e,s).join(` -`)}function jg(t){const e=String(t??"").replace(Bg,"");if(!e.trim())return"";const s=e.split(` -`),r=c=>{const d=c.trim();return/^`{3,}[A-Za-z0-9+#_.-]*$/.test(d)?c.length-c.trimStart().length:-1};let n=0,i=-1;const o=[];{let c=0;for(let d=0;d=0&&(n++,i<0&&(i=d),o.push(c+h)),c+=s[d].length+1}}if(n===0)return Ds(s);{const c=bo(e);if(!c.error&&o.every(h=>oc(h,c.commentAndStringRanges)))return Ds(s)}if(n===1){const c=Ds(s.slice(0,i)),d=Ds(s.slice(i+1));return d.length>=c.length?d:c}const a=[];let l=null;for(let c=0;cm));o=o.filter((m,_)=>!g.has(_)),o[p.index]=f}const u={...sc(t?.dependencies),...n.reduce((p,f)=>({...p,...sc(f.dependencies)}),{})},c={};n.forEach(p=>{ra(p.code||"").forEach(f=>{f in u||(c[f]="")})});const d={...c,...u},h=yg(o);return{bundleId:t?.id||"bundle-current",title:t?.title||"Generated artifact bundle",fileEntries:o,dependencies:d,relationships:t?.relationships||[],warnings:i,errors:h}}function bg(t){return String(t||"").match(/\bclass\s+([A-Z][A-Za-z0-9_]*)\b/)?.[1]}function Eg(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 Sg(t,e){const r=[Eg(t),bg(e.content),e.artifactName].find(n=>/^[A-Z][A-Za-z0-9_]*$/.test(String(n||"")));if(!r)throw new Error(`Cannot derive a FlutterFlow custom class name for ${t}.`);return r}function xg(t,e=new Map){const s=[];for(const[r,n]of t.entries())n.type!=="C"||e.has(n.path)||s.push({artifactId:n.artifactId||r,className:Sg(r,n),content:n.content,fileName:r,path:n.path});return s}function kg(t,e){const s=new Set(e.map(r=>r.path));return new Map(Array.from(t.entries()).filter(([,r])=>!s.has(r.path)))}const rc={pass:0,warning:1,fail:2},Ig=["manualActions"];function De(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function gt(...t){for(const e of t){if(typeof e=="string"&&e.trim())return e.trim();if(Array.isArray(e)&&e.length>0){const s=e.filter(r=>typeof r=="string").join(` +`);if(s)return s}}return""}function tt(t){return t==null?[]:Array.isArray(t)?t:[t]}function Cg(t){const e=De(t).value??t;if(e==null||typeof e=="string"&&e.trim()==="")return null;const s=Number(e);if(Number.isFinite(s))return s;const r=String(t||"").match(/\bscore\b[^\d]{0,12}(\d{1,3})(?:\s*\/\s*100)?/i);return r?Number(r[1]):null}function We(t){return String(t||"").trim().replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function na(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 vo(...t){return t.filter(Boolean).reduce((e,s)=>rc[s]>rc[e]?s:e,"pass")}function _d(t,e="warning",s="review"){if(typeof t=="string")return{severity:e,message:t,suggestion:"",source:s};const r=De(t),n=gt(r.message,r.title,r.issue,r.description,r.summary);return n?{severity:na(r.severity||r.status||r.level)||e,message:n,suggestion:gt(r.suggestion,r.fix,r.recommendation,r.action),source:r.source||s}:null}function _o(t,e="review"){const s=De(t);return[["findings","warning"],["issues","warning"],["criticalIssues","fail"],["errors","fail"],["warnings","warning"],["recommendations","warning"],["requiredFixes","fail"],["suggestions","warning"]].flatMap(([n,i])=>tt(s[n]).map(o=>_d(o,i,e)).filter(Boolean))}function Fg(t,e,s=null){if(typeof t=="string")return{id:`${s||"bundle"}-manual-${e+1}`,title:t,detail:"",location:"",timing:"unspecified",artifactId:s,source:"Code Review"};const r=De(t),n=gt(r.title,r.action,r.step,r.message,r.name,r.description);return n?{id:r.id||`${s||"bundle"}-manual-${e+1}`,title:n,detail:gt(r.detail,r.instructions,r.description),location:gt(r.location,r.flutterFlowPath,r.path),timing:gt(r.timing,r.phase)||"unspecified",artifactId:s,source:gt(r.source)||"Code Review"}:null}function yo(t,e=null){const s=De(t);return Ig.flatMap(r=>tt(s[r])).map((r,n)=>Fg(r,n,e)).filter(Boolean)}function Pg(t){let e=typeof t=="string"?go(t):t;if(!e&&typeof t=="string")return{rawText:t,root:{}};const s=De(e);typeof s.content=="string"&&(e=go(s.content)||e);const r=De(e),n=De(r.reviewResult||r.codeReview||r.result);return{rawText:"",root:Object.keys(n).length?n:r}}function Ag(t,e){const s=[e.id,e.fileName,e.artifactName].map(We);return t.find(r=>{const n=De(r);return[n.id,n.fileName,n.artifactName,n.name].map(We).some(i=>i&&s.includes(i))})||null}function $g(t,e){return tt(t?.metadata?.compatibility?.deployHints).find(n=>We(n?.artifactId)===We(e.id)||We(n?.fileName)===We(e.fileName))?.pathHint||""}function Rg(t,e){return tt(t?.relationships).filter(s=>We(s?.from)===We(e.id)||We(s?.to)===We(e.id))}function Tg(t,e){return tt(t?.metadata?.compatibility?.findings).filter(s=>!s?.artifactId||We(s.artifactId)===We(e.id)).map(s=>_d(s,"warning","Compatibility check")).filter(Boolean)}function Ng(t,e,s,r){const n=Ag(e,s),i=De(n?.review||n||s.review),o=Object.keys(i).length>0,a=[..._o(i),...Tg(t,s)],l=yo(i,s.id),u=na(i.status||i.verdict||i.outcome||i.result),c=a.length?vo(...a.map(h=>h.severity)):null,d=vo(u,c,o?null:"warning");return{...s,index:r,status:d,statusReason:o?gt(i.summary,i.overview,i.assessment,i.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 i.fixedSource=="string"&&i.fixedSource.trim()?i.fixedSource.trim():null,pathHint:$g(t,s),relationships:Rg(t,s)}}function Mg({status:t,score:e,artifactPresentations:s,manualSteps:r}){const n=s.length;if(n===0&&r.length===0)return e==null?"Code review returned no overall summary and no score.":`Reviewed bundle with score ${e}/100.`;const i=s.reduce((a,l)=>(a[l.status]+=1,a),{pass:0,warning:0,fail:0}),o=[];return t&&o.push(`Overall verdict: ${t}.`),n&&o.push(`${n} artifact${n===1?"":"s"}: ${i.pass} pass, ${i.warning} warn, ${i.fail} fail.`),r.length&&o.push(`Do before deploy: ${r.map(a=>a.title).join("; ")}.`),e==null&&o.push("No numeric score (0-100) was returned."),o.join(" ")}function Lg({bundle:t,reviewResult:e}){const s=De(t),r=tt(s.artifacts),{root:n,rawText:i}=Pg(e),o=[n.bundleReview,n.overallReview,n.overall,n.bundleSummary,n.summaryReview,n.review].map(De).find(E=>Object.keys(E).length)||{},a=tt(n.artifacts||n.files||n.reviews),l=r.map((E,I)=>Ng(s,a,E,I)),u=_o(n),d=[..._o(o),...u],h=[...yo(o),...yo(n),...l.flatMap(E=>E.manualSteps)].filter((E,I,F)=>F.findIndex(P=>P.title===E.title&&P.artifactId===E.artifactId)===I),p=na(o.status||o.verdict||o.overallStatus||n.status||n.verdict||n.overallStatus||n.outcome),f=vo(p,...d.map(E=>E.severity),...l.map(E=>E.status)),g=o.score??n.score??n.overallScore??i,m=Cg(g),_=gt(o.headline,o.summary,o.executiveSummary,o.overview,o.assessment,o.conclusion,n.overallSummary,n.headline,n.summary,n.executiveSummary,n.overview,n.assessment,n.conclusion,i)||Mg({status:f,score:m,artifactPresentations:l,manualSteps:h}),b=l.reduce((E,I)=>(E[I.status]+=1,E),{pass:0,warning:0,fail:0});return{title:s.title||"Generated artifact bundle",description:s.description||"",status:f,score:m,summary:_,findings:d,manualSteps:h,artifacts:l,counts:b,reviewCoverage:{reviewed:l.filter(E=>E.reviewComplete).length,total:l.length},deployOrder:tt(s.deployOrder),relationships:tt(s.relationships),warnings:tt(s.warnings),compatibility:De(s.metadata?.compatibility)}}const Og=/^\uFEFF/;function Os(t){let e=0,s=t.length;for(;ee&&!t[s-1].trim();)s--;return t.slice(e,s).join(` +`)}function Dg(t){const e=String(t??"").replace(Og,"");if(!e.trim())return"";const s=e.split(` +`),r=c=>{const d=c.trim();return/^`{3,}[A-Za-z0-9+#_.-]*$/.test(d)?c.length-c.trimStart().length:-1};let n=0,i=-1;const o=[];{let c=0;for(let d=0;d=0&&(n++,i<0&&(i=d),o.push(c+h)),c+=s[d].length+1}}if(n===0)return Os(s);{const c=wo(e);if(!c.error&&o.every(h=>ic(h,c.commentAndStringRanges)))return Os(s)}if(n===1){const c=Os(s.slice(0,i)),d=Os(s.slice(i+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(` +${d}`,{commentAndStringRanges:g}=wo(f),m=p.length+1+h;if(ic(m,g)){l.push(d);continue}a.push(Os(l)),l=null}const u=a.filter(c=>c.length>0);return u.length===0?"":u.join(` -`)}function Ug(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 bd(t){const e=Ug(t);return Array.from(e.matchAll(/class\s+([A-Z]\w*)\s+extends\s+[A-Za-z_]\w*Widget\b/g),s=>s[1])}function Ed(t){return`${ra(t)}.dart`}function Hg(t){return ta(t,"W")}const ic={"(":")","[":"]","{":"}"},Wg={")":"(","]":"[","}":"{"},zg=/[A-Za-z0-9_]/;function bo(t){const e=[{kind:"code",opener:null,openedLine:0}],s=[];let r=1,n=0;const i=(c,d)=>{(c===` +`)}function Bg(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 yd(t){const e=Bg(t);return Array.from(e.matchAll(/class\s+([A-Z]\w*)\s+extends\s+[A-Za-z_]\w*Widget\b/g),s=>s[1])}function wd(t){return`${sa(t)}.dart`}function jg(t){return ea(t,"W")}const nc={"(":")","[":"]","{":"}"},Ug={")":"(","]":"[","}":"{"},Hg=/[A-Za-z0-9_]/;function wo(t){const e=[{kind:"code",opener:null,openedLine:0}],s=[];let r=1,n=0;const i=(c,d)=>{(c===` `||c==="\r"&&d!==` `)&&r++};let o=null;const a=()=>{for(const c of e)(c.kind==="string"||c.kind==="block-comment"||c.kind==="line-comment")&&s.push({start:c.startIndex,end:t.length})};for(;n0?t[n-1]:"",f=n>1?t[n-2]:"",g=(p==="r"||p==="R")&&!zg.test(f);e.push({kind:"string",quote:c,triple:h,raw:g,startIndex:n,openedLine:r}),n+=h?3:1;continue}if(ic[c]){e.push({kind:"code",opener:c,openedLine:r}),n++;continue}if(Wg[c]){if(d.interpolation&&c==="}"){e.pop(),n++;continue}if(d.opener&&ic[d.opener]===c){e.pop(),n++;continue}return d.opener?(a(),{error:o??`line ${r}: "${c}" closes nothing - "${d.opener}" opened on line ${d.openedLine} is still open`,commentAndStringRanges:s}):(a(),{error:o??`line ${r}: unexpected "${c}" with no matching opener`,commentAndStringRanges:s})}i(c,t[n+1]),n++}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:s}}function qg(t){return bo(String(t??"")).error}function oc(t,e){return e.some(({start:s,end:r})=>t>=s&&ttypeof s=="string"?s:s?.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 Vg=/^dependencies\s*:\s*(?:#.*)?$/,Gg=/^(?:"([^"]+)"|'([^']+)'|([A-Za-z_][A-Za-z0-9_-]*))\s*:/;function Mn(t){const e=t.match(Gg);return e?e[1]??e[2]??e[3]:null}function fr(t){const e=t.trim();return e===""||e.startsWith("#")}function ks(t){const e=t.match(/^(\s*)/);return e?e[1].length:0}function oa(t,e){const s=t.findIndex(i=>e.test(i));if(s===-1)return null;let r=s,n=null;for(let i=s+1;i=0.0.0"}`}function Yg(t,e={}){const s=String(t||""),r=Object.entries(e).filter(([u])=>u&&u!=="flutter");if(r.length===0)return{yaml:s,added:[],alreadyPresent:[]};const n=s.split(` -`),i=new Set(kd(s)),o=[],a=[];for(const[u,c]of r)i.has(u)?a.push(u):(o.push([u,c]),i.add(u));if(o.length===0)return{yaml:s,added:[],alreadyPresent:a};const l=aa(n);if(l){const u=o.map(([c,d])=>ac(l.childIndent,c,d));n.splice(l.endIndex,0,...u)}else n.length>0&&n[n.length-1].trim()!==""&&n.push(""),n.push("dependencies:"),o.forEach(([u,c])=>{n.push(ac(" ",u,c))});return{yaml:n.join(` -`),added:o.map(([u])=>u),alreadyPresent:a}}function Zg(t,e={}){const s=String(t||""),r=Object.entries(e).filter(([l])=>l&&l!=="flutter");if(r.length===0)return{yaml:s,overridden:[],skipped:[]};const n=s.split(` -`),i=On(s),o=[],a=[];for(const[l,u]of r){const c=i.get(l);if(!c||!c.isScalar||!String(u||"").trim()){a.push(l);continue}const d=" ".repeat(ks(n[c.lineIndex]));n[c.lineIndex]=`${d}${l}: ${Cd(String(u).trim())}${c.comment}`,o.push({name:l,from:c.constraint,to:u})}return{yaml:n.join(` -`),overridden:o,skipped:a}}function Fd(t){const e=String(t||""),s=[];return e.trim()?(/^name:\s*\S+/m.test(e)||s.push("pubspec.yaml missing name field"),aa(e.split(` -`))||s.push("pubspec.yaml missing dependencies section"),kd(e).includes("flutter")||s.push("pubspec.yaml missing Flutter SDK dependency"),{valid:s.length===0,errors:s}):(s.push("pubspec.yaml is empty"),{valid:!1,errors:s})}const Xg=">=3.0.0 <4.0.0";function Eo(t){const e=String(t||"").trim(),s=e[0];return s!=="'"&&s!=='"'||e[e.length-1]!==s?e:e.slice(1,-1).replaceAll(`${s}${s}`,s)}function Qg(t=""){const e=vg(t).filter(s=>!s.startsWith("dart:")&&!s.startsWith("package:"));return{selfContained:e.length===0,unresolvableImports:e}}function lc(t,e,s){const r=[];for(const[n,i]of t){if(i.isScalar){e[n]=Eo(i.constraint);continue}if(i.sourceKey==="sdk"){s.add(n);continue}if(i.sourceKey==="version"){e[n]=Eo(i.sourceValue);continue}r.push(n)}return r}function em(t){const e=new Set,s={},r={},n=lc(On(t),s,e);n.push(...lc(Kg(t,"dependency_overrides"),r,e));const i=new Set([...Object.keys(s),...e]),{sdk:o}=Id(t);return{sdkConstraint:Eo(o)||Xg,dependencies:s,overrides:r,sdkPackages:[...e].sort(),availablePackages:i,unrepresentable:n}}function tm(t,e,s){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 ${s.join(", ")}, which your project's pubspec.yaml does not declare with a version constraint, so it could not be compiled before the deploy.`}function sm(t,e){const{sdkConstraint:s,dependencies:r,overrides:n,sdkPackages:i,availablePackages:o,unrepresentable:a}=em(e),l={sdkConstraint:s,dependencies:r,overrides:n,sdkPackages:i},u=[],c=[];for(const d of t){const{className:h,content:p}=d,f=na(p),g=f.filter(b=>a.includes(b));if(g.length>0){c.push({className:h,reason:`${h} was not compiled before deploying: it imports ${g.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:m}=Qg(p),_=f.filter(b=>!o.has(b));if(m.length>0||_.length>0){c.push({className:h,reason:tm(h,m,_)});continue}u.push({fileName:`${ra(h)}.dart`,content:p})}return{manifest:l,sources:u,skipped:c}}function cc(t,e){const s=`${t}${e}`.split(` -`),r=s.pop()??"",n=[];for(const i of s){const o=Pd(i);o&&n.push(o)}return{events:n,buffer:r}}function rm(t){const e=Pd(t);return e?[e]:[]}function Pd(t){const e=t.trim();if(!e)return null;try{const s=JSON.parse(e);return s&&typeof s=="object"&&!Array.isArray(s)?s:null}catch{return null}}async function nm(t,e={}){const{onPhase:s,onLog:r}=e;let n=null,i="";const o=a=>{if(a.event==="phase"){a.message&&s&&s(a.message);return}if(a.event==="log"){a.message&&r&&r(a.message);return}n=a};if(t.body?.getReader){const a=t.body.getReader(),l=new TextDecoder;for(;;){const{done:u,value:c}=await a.read();if(u)break;const d=cc(i,l.decode(c,{stream:!0}));i=d.buffer,d.events.forEach(o)}}else{const a=cc("",await t.text());i=a.buffer,a.events.forEach(o)}return rm(i).forEach(o),n?{...n,success:n.success===!0||n.success===void 0&&t.ok}:{success:!1,error:t.ok?"The FlutterFlow deploy runner closed the connection before it finished.":`FlutterFlow custom class provisioning failed (HTTP ${t.status}).`}}const im=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;function wt(t){const e=String(t||"").trim().match(im);return e?{major:Number(e[1]),minor:Number(e[2]),patch:Number(e[3]),prerelease:e[4]?e[4].split("."):[]}:null}function om(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 s=0;s0)}function lm(t){const e=wt(t);return e?e.major>0?`${e.major+1}.0.0`:`0.${e.minor+1}.0`:null}function la(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 wt(o)?{min:o,minInclusive:!0,max:lm(o),maxInclusive:!1}:null}if(wt(e))return{min:e,minInclusive:!0,max:e,maxInclusive:!0};const s={min:null,minInclusive:!1,max:null,maxInclusive:!1},r=/(>=|<=|>|<)\s*([0-9][0-9A-Za-z.+-]*)/g;let n=!1,i;for(;(i=r.exec(e))!==null;){const[,o,a]=i;if(!wt(a))return null;n=!0,o===">="||o===">"?(s.min=a,s.minInclusive=o===">="):(s.max=a,s.maxInclusive=o==="<=")}return n?s:null}function uc(t,e){const s=la(t);if(!s||!wt(e))return!1;if(s.min!==null){const r=_n(e,s.min);if(r<0||r===0&&!s.minInclusive)return!1}if(s.max!==null){const r=_n(e,s.max);if(r>0||r===0&&!s.maxInclusive)return!1}return!0}function cm(t,e){const s=la(t);if(!s||!wt(e))return!1;if(s.max===null)return!0;const r=_n(s.max,e);return r>0?!0:r===0&&s.maxInclusive}function is(t){const e=la(t);return e?e.min:null}const um="https://pub.dev/api/packages/",dm=8e3;function hm(t,e={}){const{dartSdkFloor:s=null,flutterSdkFloor:r=null}=e,n=Array.isArray(t?.versions)?t.versions:[];let i=null;for(const o of n){const a=o?.version;if(!a||o.retracted||am(a))continue;const l=o.pubspec?.environment||{};s&&l.sdk&&!uc(l.sdk,s)||r&&l.flutter&&!uc(l.flutter,r)||(!i||_n(a,i)>0)&&(i=a)}return i?{version:i,constraint:`^${i}`}:null}async function pm(t,e={}){const{dartSdkFloor:s=null,flutterSdkFloor:r=null,fetchImpl:n=fetch}=e;let i;try{const a=await n(`${um}${encodeURIComponent(t)}`,{signal:AbortSignal.timeout(dm)});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}"`};i=await a.json()}catch(a){return{name:t,constraint:null,version:null,error:`could not reach pub.dev for "${t}" (${a.message})`}}const o=hm(i,{dartSdkFloor:s,flutterSdkFloor:r});return o?{name:t,...o,error:null}:{name:t,constraint:null,version:null,error:s?`no published "${t}" release supports Dart ${s}`:`no published "${t}" release could be read`}}async function fm(t,e={}){const s=await Promise.all(t.map(r=>pm(r,e)));return new Map(s.map(({name:r,...n})=>[r,n]))}async function gm(t,e={},s={}){const{resolveVersions:r=fm}=s,n=Object.entries(e).filter(([c])=>c&&c!=="flutter"),i=Id(t),o={dartSdkFloor:is(i.sdk),flutterSdkFloor:is(i.flutter)},a={additions:{},overrides:{},kept:[],warnings:[],sdk:o};if(n.length===0)return a;const l=On(t),u=[];for(const[c,d]of n){const h=l.get(c);if(!h){u.push(c);continue}const p=is(d);if(!p){a.kept.push({name:c,constraint:h.constraint});continue}if(!h.isScalar){a.warnings.push(`"${c}" is declared in your project from a git, path, or SDK source, but the generated code needs at least ${p}. Left as-is — update it yourself if the build fails.`),a.kept.push({name:c,constraint:h.constraint});continue}if(cm(h.constraint,p)){a.kept.push({name:c,constraint:h.constraint});continue}a.overrides[c]=`^${p}`,a.warnings.push(`"${c}" was pinned to ${h.constraint} in your project, which cannot resolve the ${p} the generated code needs. Raising it to ^${p} — this changes a dependency the rest of your app also uses.`)}if(u.length>0){const c=await r(u,o);for(const d of u){const h=c.get(d);if(h?.constraint){a.additions[d]=h.constraint;continue}const p=e[d]||"";if(is(p)){a.additions[d]=`^${is(p)}`,a.warnings.push(`Could not confirm "${d}" version on pub.dev (${h?.error||"lookup failed"}). Using ^${is(p)} from the AI's recommendation — verify this is current.`);continue}a.additions[d]=">=0.0.0",a.warnings.push(`Could not determine a version for "${d}" (${h?.error||"lookup failed"}) and the AI supplied none. Added with a wide-open >=0.0.0 constraint — pin a concrete version in FlutterFlow before deploying.`)}}return a}const mm={"&":"&","<":"<",">":">",'"':""","'":"'"};function bt(t){return String(t??"").replace(/[&<>"']/g,e=>mm[e])}function j(t){return t?bt(t).replace(/\n/g,"
    "):""}function It(t){return bt(t).replace(/\r?\n/g," ")}function vm(t,e={}){const s=t?.pipelineStep;if(s!=null&&e[s]!=null)return e[s];const r=t?.message||"";return r.includes("Code Generator")?2:r.includes("Code Review")?3:1}function _m(t){const e={"Integration Audit Report":"📋","Critical Issues":"❌",Warnings:"⚠️",Recommendations:"✅","Overall Score":"📊"};for(const[s,r]of Object.entries(e))if(t.toLowerCase().includes(s.toLowerCase()))return r;return"📄"}function ym(t){const e={critical:"❌",warning:"⚠️",recommendation:"✅",score:"📊",issue:"🔍",fix:"🔧"};for(const[s,r]of Object.entries(e))if(t.toLowerCase().includes(s.toLowerCase()))return r;return"📝"}function wm(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 bs(t){if(!t)return"";if(typeof t!="string")return String(t);const e=/```(?:\w+)?\n?([\s\S]*?)```/,s=t.match(e);return s?s[1].trim():t.trim()}function dc(t){return t=bt(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 Ad(t,e="dart",s=globalThis.hljs){if(!t)return"";const r=bs(t);try{return s.highlight(r,{language:e}).value}catch(n){console.warn("Syntax highlighting failed:",n);try{return s.highlight(r,{language:"json"}).value}catch{return bt(r)}}}function Dn(t,e={}){const{highlighter:s=globalThis.hljs}=e;let r='
    ';const n=String(t??"").split(` -`);let i=!1,o="";for(const a of n){if(a.startsWith("```")){if(i){const l=wm(o),u=Ad(o.trim(),l,s);r+=`
    +`){s.push({start:d.startIndex,end:n}),o??=`line ${r}: string starting on line ${d.openedLine} is never closed`,e.pop();continue}if(!d.raw&&c==="\\"){i(t[n+1]??"",t[n+2]??""),n+=2;continue}if(!d.raw&&c==="$"&&t[n+1]==="{"){e.push({kind:"code",opener:null,interpolation:!0}),n+=2;continue}const h=d.triple?3:1;if(c===d.quote&&t.slice(n,n+h)===d.quote.repeat(h)){s.push({start:d.startIndex,end:n+h}),e.pop(),n+=h;continue}i(c,t[n+1]),n++;continue}if(c==="/"&&t[n+1]==="/"){e.push({kind:"line-comment",startIndex:n}),n+=2;continue}if(c==="/"&&t[n+1]==="*"){e.push({kind:"block-comment",startIndex:n,openedLine:r,depth:1}),n+=2;continue}if(c==="'"||c==='"'){const h=t.slice(n,n+3)===c.repeat(3),p=n>0?t[n-1]:"",f=n>1?t[n-2]:"",g=(p==="r"||p==="R")&&!Hg.test(f);e.push({kind:"string",quote:c,triple:h,raw:g,startIndex:n,openedLine:r}),n+=h?3:1;continue}if(nc[c]){e.push({kind:"code",opener:c,openedLine:r}),n++;continue}if(Ug[c]){if(d.interpolation&&c==="}"){e.pop(),n++;continue}if(d.opener&&nc[d.opener]===c){e.pop(),n++;continue}return d.opener?(a(),{error:o??`line ${r}: "${c}" closes nothing - "${d.opener}" opened on line ${d.openedLine} is still open`,commentAndStringRanges:s}):(a(),{error:o??`line ${r}: unexpected "${c}" with no matching opener`,commentAndStringRanges:s})}i(c,t[n+1]),n++}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:s}}function Wg(t){return wo(String(t??"")).error}function ic(t,e){return e.some(({start:s,end:r})=>t>=s&&ttypeof s=="string"?s:s?.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 zg=/^dependencies\s*:\s*(?:#.*)?$/,qg=/^(?:"([^"]+)"|'([^']+)'|([A-Za-z_][A-Za-z0-9_-]*))\s*:/;function Nn(t){const e=t.match(qg);return e?e[1]??e[2]??e[3]:null}function pr(t){const e=t.trim();return e===""||e.startsWith("#")}function xs(t){const e=t.match(/^(\s*)/);return e?e[1].length:0}function ia(t,e){const s=t.findIndex(i=>e.test(i));if(s===-1)return null;let r=s,n=null;for(let i=s+1;i=0.0.0"}`}function Jg(t,e={}){const s=String(t||""),r=Object.entries(e).filter(([u])=>u&&u!=="flutter");if(r.length===0)return{yaml:s,added:[],alreadyPresent:[]};const n=s.split(` +`),i=new Set(Sd(s)),o=[],a=[];for(const[u,c]of r)i.has(u)?a.push(u):(o.push([u,c]),i.add(u));if(o.length===0)return{yaml:s,added:[],alreadyPresent:a};const l=oa(n);if(l){const u=o.map(([c,d])=>oc(l.childIndent,c,d));n.splice(l.endIndex,0,...u)}else n.length>0&&n[n.length-1].trim()!==""&&n.push(""),n.push("dependencies:"),o.forEach(([u,c])=>{n.push(oc(" ",u,c))});return{yaml:n.join(` +`),added:o.map(([u])=>u),alreadyPresent:a}}function Yg(t,e={}){const s=String(t||""),r=Object.entries(e).filter(([l])=>l&&l!=="flutter");if(r.length===0)return{yaml:s,overridden:[],skipped:[]};const n=s.split(` +`),i=Ln(s),o=[],a=[];for(const[l,u]of r){const c=i.get(l);if(!c||!c.isScalar||!String(u||"").trim()){a.push(l);continue}const d=" ".repeat(xs(n[c.lineIndex]));n[c.lineIndex]=`${d}${l}: ${kd(String(u).trim())}${c.comment}`,o.push({name:l,from:c.constraint,to:u})}return{yaml:n.join(` +`),overridden:o,skipped:a}}function Id(t){const e=String(t||""),s=[];return e.trim()?(/^name:\s*\S+/m.test(e)||s.push("pubspec.yaml missing name field"),oa(e.split(` +`))||s.push("pubspec.yaml missing dependencies section"),Sd(e).includes("flutter")||s.push("pubspec.yaml missing Flutter SDK dependency"),{valid:s.length===0,errors:s}):(s.push("pubspec.yaml is empty"),{valid:!1,errors:s})}const Zg=">=3.0.0 <4.0.0";function bo(t){const e=String(t||"").trim(),s=e[0];return s!=="'"&&s!=='"'||e[e.length-1]!==s?e:e.slice(1,-1).replaceAll(`${s}${s}`,s)}function Xg(t=""){const e=gg(t).filter(s=>!s.startsWith("dart:")&&!s.startsWith("package:"));return{selfContained:e.length===0,unresolvableImports:e}}function ac(t,e,s){const r=[];for(const[n,i]of t){if(i.isScalar){e[n]=bo(i.constraint);continue}if(i.sourceKey==="sdk"){s.add(n);continue}if(i.sourceKey===null&&i.version){e[n]=bo(i.version);continue}r.push(n)}return r}function Qg(t){const e=new Set,s={},r={},n=ac(Ln(t),s,e);n.push(...ac(Gg(t,"dependency_overrides"),r,e));const i=new Set([...Object.keys(s),...e]),{sdk:o}=xd(t);return{sdkConstraint:bo(o)||Zg,dependencies:s,overrides:r,sdkPackages:[...e].sort(),availablePackages:i,unrepresentable:n}}function em(t,e,s){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 ${s.join(", ")}, which your project's pubspec.yaml does not declare with a version constraint, so it could not be compiled before the deploy.`}function tm(t,e){const{sdkConstraint:s,dependencies:r,overrides:n,sdkPackages:i,availablePackages:o,unrepresentable:a}=Qg(e),l={sdkConstraint:s,dependencies:r,overrides:n,sdkPackages:i},u=[],c=[];for(const d of t){const{className:h,content:p}=d,f=ra(p),g=f.filter(b=>a.includes(b));if(g.length>0){c.push({className:h,reason:`${h} was not compiled before deploying: it imports ${g.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:m}=Xg(p),_=f.filter(b=>!o.has(b));if(m.length>0||_.length>0){c.push({className:h,reason:em(h,m,_)});continue}u.push({fileName:`${sa(h)}.dart`,content:p})}return{manifest:l,sources:u,skipped:c}}function lc(t,e){const s=`${t}${e}`.split(` +`),r=s.pop()??"",n=[];for(const i of s){const o=Cd(i);o&&n.push(o)}return{events:n,buffer:r}}function sm(t){const e=Cd(t);return e?[e]:[]}function Cd(t){const e=t.trim();if(!e)return null;try{const s=JSON.parse(e);return s&&typeof s=="object"&&!Array.isArray(s)?s:null}catch{return null}}async function rm(t,e={}){const{onPhase:s,onLog:r}=e;let n=null,i="";const o=a=>{if(a.event==="phase"){a.message&&s&&s(a.message);return}if(a.event==="log"){a.message&&r&&r(a.message);return}n=a};if(t.body?.getReader){const a=t.body.getReader(),l=new TextDecoder;for(;;){const{done:u,value:c}=await a.read();if(u)break;const d=lc(i,l.decode(c,{stream:!0}));i=d.buffer,d.events.forEach(o)}}else{const a=lc("",await t.text());i=a.buffer,a.events.forEach(o)}return sm(i).forEach(o),n?{...n,success:n.success===!0||n.success===void 0&&t.ok}:{success:!1,error:t.ok?"The FlutterFlow deploy runner closed the connection before it finished.":`FlutterFlow custom class provisioning failed (HTTP ${t.status}).`}}const nm=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;function wt(t){const e=String(t||"").trim().match(nm);return e?{major:Number(e[1]),minor:Number(e[2]),patch:Number(e[3]),prerelease:e[4]?e[4].split("."):[]}:null}function im(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 s=0;s0)}function am(t){const e=wt(t);return e?e.major>0?`${e.major+1}.0.0`:`0.${e.minor+1}.0`:null}function aa(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 wt(o)?{min:o,minInclusive:!0,max:am(o),maxInclusive:!1}:null}if(wt(e))return{min:e,minInclusive:!0,max:e,maxInclusive:!0};const s={min:null,minInclusive:!1,max:null,maxInclusive:!1},r=/(>=|<=|>|<)\s*([0-9][0-9A-Za-z.+-]*)/g;let n=!1,i;for(;(i=r.exec(e))!==null;){const[,o,a]=i;if(!wt(a))return null;n=!0,o===">="||o===">"?(s.min=a,s.minInclusive=o===">="):(s.max=a,s.maxInclusive=o==="<=")}return n?s:null}function cc(t,e){const s=aa(t);if(!s||!wt(e))return!1;if(s.min!==null){const r=vn(e,s.min);if(r<0||r===0&&!s.minInclusive)return!1}if(s.max!==null){const r=vn(e,s.max);if(r>0||r===0&&!s.maxInclusive)return!1}return!0}function lm(t,e){const s=aa(t);if(!s||!wt(e))return!1;if(s.max===null)return!0;const r=vn(s.max,e);return r>0?!0:r===0&&s.maxInclusive}function ns(t){const e=aa(t);return e?e.min:null}const cm="https://pub.dev/api/packages/",um=8e3;function dm(t,e={}){const{dartSdkFloor:s=null,flutterSdkFloor:r=null}=e,n=Array.isArray(t?.versions)?t.versions:[];let i=null;for(const o of n){const a=o?.version;if(!a||o.retracted||om(a))continue;const l=o.pubspec?.environment||{};s&&l.sdk&&!cc(l.sdk,s)||r&&l.flutter&&!cc(l.flutter,r)||(!i||vn(a,i)>0)&&(i=a)}return i?{version:i,constraint:`^${i}`}:null}async function hm(t,e={}){const{dartSdkFloor:s=null,flutterSdkFloor:r=null,fetchImpl:n=fetch}=e;let i;try{const a=await n(`${cm}${encodeURIComponent(t)}`,{signal:AbortSignal.timeout(um)});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}"`};i=await a.json()}catch(a){return{name:t,constraint:null,version:null,error:`could not reach pub.dev for "${t}" (${a.message})`}}const o=dm(i,{dartSdkFloor:s,flutterSdkFloor:r});return o?{name:t,...o,error:null}:{name:t,constraint:null,version:null,error:s?`no published "${t}" release supports Dart ${s}`:`no published "${t}" release could be read`}}async function pm(t,e={}){const s=await Promise.all(t.map(r=>hm(r,e)));return new Map(s.map(({name:r,...n})=>[r,n]))}async function fm(t,e={},s={}){const{resolveVersions:r=pm}=s,n=Object.entries(e).filter(([c])=>c&&c!=="flutter"),i=xd(t),o={dartSdkFloor:ns(i.sdk),flutterSdkFloor:ns(i.flutter)},a={additions:{},overrides:{},kept:[],warnings:[],sdk:o};if(n.length===0)return a;const l=Ln(t),u=[];for(const[c,d]of n){const h=l.get(c);if(!h){u.push(c);continue}const p=ns(d);if(!p){a.kept.push({name:c,constraint:h.constraint});continue}if(!h.isScalar){a.warnings.push(`"${c}" is declared in your project from a git, path, or SDK source, but the generated code needs at least ${p}. Left as-is — update it yourself if the build fails.`),a.kept.push({name:c,constraint:h.constraint});continue}if(lm(h.constraint,p)){a.kept.push({name:c,constraint:h.constraint});continue}a.overrides[c]=`^${p}`,a.warnings.push(`"${c}" was pinned to ${h.constraint} in your project, which cannot resolve the ${p} the generated code needs. Raising it to ^${p} — this changes a dependency the rest of your app also uses.`)}if(u.length>0){const c=await r(u,o);for(const d of u){const h=c.get(d);if(h?.constraint){a.additions[d]=h.constraint;continue}const p=e[d]||"";if(ns(p)){a.additions[d]=`^${ns(p)}`,a.warnings.push(`Could not confirm "${d}" version on pub.dev (${h?.error||"lookup failed"}). Using ^${ns(p)} from the AI's recommendation — verify this is current.`);continue}a.additions[d]=">=0.0.0",a.warnings.push(`Could not determine a version for "${d}" (${h?.error||"lookup failed"}) and the AI supplied none. Added with a wide-open >=0.0.0 constraint — pin a concrete version in FlutterFlow before deploying.`)}}return a}const gm={"&":"&","<":"<",">":">",'"':""","'":"'"};function bt(t){return String(t??"").replace(/[&<>"']/g,e=>gm[e])}function j(t){return t?bt(t).replace(/\n/g,"
    "):""}function It(t){return bt(t).replace(/\r?\n/g," ")}function mm(t,e={}){const s=t?.pipelineStep;if(s!=null&&e[s]!=null)return e[s];const r=t?.message||"";return r.includes("Code Generator")?2:r.includes("Code Review")?3:1}function vm(t){const e={"Integration Audit Report":"📋","Critical Issues":"❌",Warnings:"⚠️",Recommendations:"✅","Overall Score":"📊"};for(const[s,r]of Object.entries(e))if(t.toLowerCase().includes(s.toLowerCase()))return r;return"📄"}function _m(t){const e={critical:"❌",warning:"⚠️",recommendation:"✅",score:"📊",issue:"🔍",fix:"🔧"};for(const[s,r]of Object.entries(e))if(t.toLowerCase().includes(s.toLowerCase()))return r;return"📝"}function ym(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 ws(t){if(!t)return"";if(typeof t!="string")return String(t);const e=/```(?:\w+)?\n?([\s\S]*?)```/,s=t.match(e);return s?s[1].trim():t.trim()}function uc(t){return t=bt(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 Fd(t,e="dart",s=globalThis.hljs){if(!t)return"";const r=ws(t);try{return s.highlight(r,{language:e}).value}catch(n){console.warn("Syntax highlighting failed:",n);try{return s.highlight(r,{language:"json"}).value}catch{return bt(r)}}}function On(t,e={}){const{highlighter:s=globalThis.hljs}=e;let r='
    ';const n=String(t??"").split(` +`);let i=!1,o="";for(const a of n){if(a.startsWith("```")){if(i){const l=ym(o),u=Fd(o.trim(),l,s);r+=`
    ${u}
    `,o="",i=!1}else i=!0;continue}if(i){o+=a+` `;continue}if(a.startsWith("# ")){const l=a.substring(2).trim();r+=`

    - ${_m(l)} + ${vm(l)} ${bt(l)}

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

    - ${ym(l)} + ${_m(l)} ${bt(l)}

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

    ${dc(a)}

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

    ${uc(a)}

    `)}return r+="
    ",`
    @@ -76,14 +76,14 @@ ${d}`,{commentAndStringRanges:g}=bo(f),m=p.length+1+h;if(oc(m,g)){l.push(d);cont
    ${r}
    - `}const bm="https://ccc-ffai-runner-y5cyj3473a-uw.a.run.app/deployCustomClasses",Em="phc_KoqpBJCIiWMW5I6HKBM092DVXZbMmE4KkPHqI518pF3",Sm="https://us.i.posthog.com";ud.init(Em,{api_host:Sm,person_profiles:"identified_only"});function zt(t,e={}){try{ud.capture(t,e)}catch(s){console.error("PostHog tracking failed",s)}}const Je="https://4tgke4.buildship.run",$d={professional:"price_1T2ldCKszA2slvDXatdeCpbI",power:"price_1T2le9KszA2slvDXR4mPvw7M"},yn="ccc_auth_session",hc=new WeakSet;let G={email:null,sessionToken:null,isVerified:!1};function Es(t={}){return{tier:"free",status:"none",periodEnd:null,isLoading:!1,isResolved:!1,error:null,...t}}let fe=Es({isResolved:!0});const xm=`${Je}/service/runpipeline`,km="bs_user_id",Im="bs_identity_token",Cm=`${Je}/authUserCheck`;let Ge={userId:null,token:null,status:null,resolved:!1};const wn={free:2,professional:50,power:2e3},bn="ccc_subscription",pc=3,Fm=new Set(["active","trialing","paid"]),cr="google/gemini-3.7-flash",Ur=["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"],Pm={"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 qt(t){return Pm[t]||t}const Am=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 Rd(t){return Am.has(t)}const So=4,Fi=8*1024*1024,$m="https://4tgke4.buildship.run/service/runpipeline-image";let Pt=[];function Rm(t){return new Promise(e=>{const s=new FileReader;s.onload=()=>e(s.result),s.onerror=()=>e(null),s.readAsDataURL(t)})}async function Tm(t){const e=new FormData;return e.append("file",t),(await fetch($m,{method:"POST",body:e})).json()}function Nm(t){if(Array.isArray(t)){const e=t[0];if(e&&typeof e=="object")for(const s of Object.keys(e)){if(s==="item"||s==="index")continue;const r=e[s];if(r&&typeof r=="object"){if(typeof r.file=="string")return r.file;if(typeof r.url=="string")return r.url}if(typeof r=="string")return r}return""}return typeof t=="string"?t:t&&typeof t=="object"&&(t.url||t.fileUrl||t.file_url||t.downloadUrl||t.imageUrl||t.image_url||t.file)||""}async function Mm(t){const e=Array.from(t.target.files||[]);if(!e.length)return;const s=e.filter(l=>l.size>Fi);s.length&&ue(`Skipped ${s.length} image(s) over the ${(Fi/1024/1024).toFixed(0)} MB limit.`,"warning");const r=e.filter(l=>l.size<=Fi);if(!r.length){t.target.value="";return}const n=So-Pt.length,o=r.slice(0,n).map(async l=>{const u=await Rm(l);if(!u)return null;let c="";try{c=Nm(await Tm(l))}catch{c=""}return{dataUrl:u,name:l.name,url:c}}),a=(await Promise.all(o)).filter(Boolean);t.target.value="",!(a.length&&!Rd(document.getElementById("code-generator-model")?.value))&&(Pt.push(...a),r.length>n&&ue(`You can attach up to ${So} images.`,"info"),ca())}function Lm(t){Pt.splice(t,1),ca()}function ca(){const t=document.getElementById("prompt-image-thumbnails"),e=document.getElementById("prompt-image-btn-label");t&&(t.innerHTML="",Pt.forEach((s,r)=>{const n=document.createElement("div");n.className="prompt-img-thumb",n.innerHTML=`Prompt image`,t.appendChild(n)}),e&&(e.textContent=Pt.length>=So?"Image limit reached":"Add images"))}function Td(){const t=document.getElementById("prompt-image-upload");if(!t)return;const e=document.getElementById("code-generator-model"),s=Rd(e?.value);t.classList.toggle("hidden",!s),!s&&Pt.length&&(Pt=[],ca())}const Kt="ccc_usage",Nd="google/gemini-3.7-flash",Md="google/gemini-3.7-flash",Pi="google/gemini-3.7-flash",fc={professional:11,power:49},xo={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"},Hr={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 Wr={...Hr};async function Om(){const t=new AbortController,e=setTimeout(()=>t.abort(),5e3);try{const s=await fetch("https://open.er-api.com/v6/latest/AUD",{signal:t.signal});if(!s.ok)return;const r=await s.json();if(r.result!=="success"||!r.rates)return;const n=r.rates,i={AUD:1},o=new Set([...Object.keys(Hr),...Object.values(ko),...Object.values(xo)]);for(const a of o)a!=="AUD"&&(typeof n[a]=="number"&&n[a]>0?i[a]=n[a]:Hr[a]&&(i[a]=Hr[a]));Wr=i}catch{}finally{clearTimeout(e)}}const ko={"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 Ld(){try{const i=Intl.DateTimeFormat().resolvedOptions().timeZone;if(i&&ko[i])return ko[i]}catch{}const e=(navigator.language||"en-US").replace("-","_"),s=xo[e];if(s)return s;const r=e.split("_")[0],n=xo[r];return n||"USD"}function gc(t,e){const s=Wr[e]??Wr.USD,r=t*s,n=Math.round(r*100)/100;try{return new Intl.NumberFormat("en-US",{style:"currency",currency:e,minimumFractionDigits:0,maximumFractionDigits:n>=100||n%1===0?0:2}).format(n)}catch{return new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",minimumFractionDigits:0,maximumFractionDigits:2}).format(t*Wr.USD)}}const st="ccc_api_key_",_t="ccc_session_api_key_",it="ccc_encryption_key",ur="ccc_encryption_key_scope",Dm="ccc_keystore",En="keys",dr="ccc_encryption_key_version";let Io=null,Sn=null,hr=!1,xn=!1,mc=!1;class kn extends Error{constructor(){super("Secure browser key storage is unavailable."),this.name="CredentialStorageUnavailableError"}}function vc(){if(mc)return;mc=!0;const t="Secure browser key storage is unavailable. Existing credentials were left untouched; new credentials will be available only in this tab session.";console.warn(t),document.body&&ue(t,"warning")}function Od(){return localStorage.getItem(dr)||""}function Co(){return crypto.randomUUID?.()||Bd(crypto.getRandomValues(new Uint8Array(16)))}function Bm(){const t=Od();if(t)return t;const e=Co();return localStorage.setItem(dr,e),e}function Ss(){Io=null,Sn=null,hr=!1,xn=!1}window.addEventListener("storage",t=>{t.key===dr&&Ss()});function jm(){return new Promise((t,e)=>{const s=indexedDB.open(Dm,1);s.onupgradeneeded=()=>{const r=s.result;r.objectStoreNames.contains(En)||r.createObjectStore(En)},s.onsuccess=()=>t(s.result),s.onerror=()=>e(s.error)})}async function ua(t,e){const s=await jm();return new Promise((r,n)=>{const i=s.transaction(En,t);let o;try{o=e(i.objectStore(En))}catch(l){s.close(),n(l);return}let a;o.onsuccess=()=>{a=o.result},o.onerror=()=>n(o.error),i.oncomplete=()=>{s.close(),r(a)},i.onerror=()=>{s.close(),n(i.error||new Error("Encryption key transaction failed."))},i.onabort=()=>{s.close(),n(i.error||new Error("Encryption key transaction aborted."))}})}function Um(t){return t instanceof CryptoKey&&t.algorithm?.name==="AES-GCM"&&t.extractable===!1&&t.usages.includes("encrypt")&&t.usages.includes("decrypt")}async function Hm(){const t=await ua("readonly",e=>e.get(it));return Um(t)?t:null}async function Dd(t){await ua("readwrite",e=>e.put(t,it))}async function Wm(){Ss();try{await ua("readwrite",t=>t.delete(it))}catch(t){console.warn("Could not delete the stored encryption key:",t)}}async function zm(){const t=sessionStorage.getItem(it);if(!t)return null;const e=await crypto.subtle.importKey("jwk",JSON.parse(t),{name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);return await Dd(e),sessionStorage.removeItem(it),sessionStorage.removeItem(ur),localStorage.removeItem(st+"salt"),e}async function _c(t){const e=sessionStorage.getItem(it);if(e)return xn=sessionStorage.getItem(ur)!=="session",crypto.subtle.importKey("jwk",JSON.parse(e),{name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);if(!t)throw new kn;const s=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!0,["encrypt","decrypt"]),r=await crypto.subtle.exportKey("jwk",s);return sessionStorage.setItem(it,JSON.stringify(r)),sessionStorage.setItem(ur,"session"),xn=!1,crypto.subtle.importKey("jwk",r,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}async function qm(t){if(sessionStorage.getItem(ur)==="session"&&sessionStorage.getItem(it))return vc(),hr=!0,_c(t);try{const e=await Hm();if(e)return e;const s=await zm();if(s)return s;const r=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);return await Dd(r),r}catch(e){return console.warn("IndexedDB encryption-key storage failed:",e),vc(),hr=!0,_c(t)}}async function da(t={}){const{allowSessionFallbackCreation:e=!0}=t,s=Bm();Sn!==s&&Ss();const r=Io||qm(e);Io=r,Sn=s;try{return await r}catch(n){throw Ss(),n}}async function Vm(t){const e=await da(),s=Sn,r=new TextEncoder,n=crypto.getRandomValues(new Uint8Array(12)),i=await crypto.subtle.encrypt({name:"AES-GCM",iv:n},e,r.encode(t)),o=new Uint8Array(n.length+i.byteLength);return o.set(n),o.set(new Uint8Array(i),n.length),{ciphertext:Bd(o),keyVersion:s,sessionFallback:hr}}async function Gm(t,e={}){const{isSessionCredential:s=!1}=e;try{const r=await da({allowSessionFallbackCreation:!1});if(hr&&!s&&!xn)throw new kn;const n=Km(t),i=n.slice(0,12),o=n.slice(12),a=await crypto.subtle.decrypt({name:"AES-GCM",iv:i},r,o);return new TextDecoder().decode(a)}catch(r){if(r instanceof kn)throw r;return console.error("Decryption failed:",r),null}}function Bd(t){const e=new Uint8Array(t);let s="";for(let r=0;r0}let pr="",In="",Xs=null,wc=0;async function ha(){sessionStorage.getItem(it)&&await da(),pr=await Ee("flutterflow"),In=await Ee("flutterflow_project_id"),Qm(),Xt()}function pa(){document.getElementById("api-keys-modal").classList.add("open"),ga(),pr&&Wd(pr)}function jd(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("api-keys-modal");e&&e.classList.remove("open");const s=document.getElementById("walkthrough-modal");s&&(fa(),s.classList.add("open"))}let Et=1;function Ud(){const t=document.querySelector(".wt-steps");return t?Array.from(t.querySelectorAll(".wt-step-card")):[]}function Bn(){const t=Ud();t.length&&t.forEach((e,s)=>{const r=s+1;if(r===Et){e.classList.remove("opacity-60","bg-gray-50","border-gray-200"),e.classList.add("bg-blue-50","border-blue-200");const n=e.querySelector("div:first-child");n&&(n.classList.remove("bg-gray-400"),n.classList.add("bg-blue-500"),n.innerHTML=r)}else if(r0&&Et<=t&&(Et++,Bn())}function Ym(){const t=document.getElementById("walkthrough-modal");t&&(Et=1,Bn(),t.classList.add("open"))}function Zm(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("walkthrough-modal");e&&e.classList.remove("open");const s=document.getElementById("walkthrough-dont-show");s&&s.checked&&localStorage.setItem("hasSeenWalkthrough","true")}function Hd(){if(G.isVerified&&Yt()&&fe.tier!=="free")return;if(!localStorage.getItem("hasSeenWalkthrough")){const e=document.getElementById("walkthrough-modal");e&&(Et=1,Bn(),e.classList.add("open"))}}async function ga(){const t=document.getElementById("flutterflow-api-key-input");pr?(t.value="",t.placeholder="Key saved (enter new to replace)"):t.placeholder="Enter your FlutterFlow API key",Xm()}function Xm(){bc("flutterflow","flutterflow-key-status"),bc("flutterflow_project_id","flutterflow-project-status")}function bc(t,e){const s=document.getElementById(e);if(!s)return;const r=s.querySelector(".key-status-dot"),n=s.querySelector("span");ls(t)?(r.className="key-status-dot configured",n.className="text-green-600",n.textContent="User key configured"):(r.className="key-status-dot missing",n.className="text-gray-500",n.textContent="Not configured")}function Xt(){const t=y.step2Result&&y.step2Result.length>0,e=document.getElementById("btn-deploy-to-ff"),s=document.getElementById("btn-run-pipeline");s&&s.classList.remove("hidden"),e&&e.classList.toggle("hidden",!t)}function Qm(){const t=document.getElementById("api-keys-status");if(!t)return;const e=t.querySelectorAll(".key-status-dot"),s=["flutterflow"];e.forEach((r,n)=>{const i=s[n];i==="flutterflow"?ls("flutterflow")&&ls("flutterflow_project_id")?(r.className="key-status-dot configured",r.title="FlutterFlow (Fully configured)"):ls("flutterflow")||ls("flutterflow_project_id")?(r.className="key-status-dot env",r.title="FlutterFlow (Partially configured)"):(r.className="key-status-dot missing",r.title="FlutterFlow (Not configured)"):ls(i)?(r.className="key-status-dot configured",r.title=i.charAt(0).toUpperCase()+i.slice(1)+" (User key)"):(r.className="key-status-dot missing",r.title=i.charAt(0).toUpperCase()+i.slice(1)+" (Not configured)")}),Xt()}async function ev(){const t=document.getElementById("flutterflow-api-key-input"),e=document.getElementById("flutterflow-projects-select");t.value.trim()&&await yc("flutterflow",t.value);const s=e?.value.trim()||"";if(s){if(!jn(s)){ue("The selected FlutterFlow project has an unexpected ID format.","error"),e.focus();return}await yc("flutterflow_project_id",s)}await ha(),ga();const r=document.querySelector("#api-keys-modal .bg-blue-500"),n=r.textContent;r.textContent="Saved!",r.classList.remove("bg-blue-500","hover:bg-blue-600"),r.classList.add("bg-green-500"),setTimeout(()=>{r.textContent=n,r.classList.remove("bg-green-500"),r.classList.add("bg-blue-500","hover:bg-blue-600"),jd()},1e3)}async function tv(){if(!confirm("Are you sure you want to clear all stored API keys?"))return;localStorage.setItem(dr,Co()),Ss(),localStorage.removeItem(st+"flutterflow"),localStorage.removeItem(st+"flutterflow_project_id"),sessionStorage.removeItem(_t+"flutterflow"),sessionStorage.removeItem(_t+"flutterflow_project_id"),sessionStorage.removeItem(it),sessionStorage.removeItem(ur),localStorage.removeItem(st+"salt"),await Wm(),localStorage.setItem(dr,Co()),localStorage.removeItem(st+"flutterflow"),localStorage.removeItem(st+"flutterflow_project_id"),sessionStorage.removeItem(_t+"flutterflow"),sessionStorage.removeItem(_t+"flutterflow_project_id"),await ha();const t=document.getElementById("flutterflow-projects-select");t&&(t.innerHTML=''),ga()}function jn(t){return!t||t.trim().length<5||t.includes(" ")?!1:/^[a-zA-Z0-9-]+$/.test(t)}function sv(t,e){const s=document.getElementById(t);s&&(s.value?e?s.style.borderColor="#22c55e":s.style.borderColor="#ef4444":s.style.borderColor="")}function rv(){const t=document.getElementById("flutterflow-api-key-input");t&&(t.addEventListener("input",e=>{const s=e.target.value.trim().length>0;sv("flutterflow-api-key-input",s)}),t.addEventListener("blur",nv(async e=>{const s=e.target.value.trim();s&&await Wd(s)},500)))}function nv(t,e){let s;return function(...n){const i=()=>{clearTimeout(s),t(...n)};clearTimeout(s),s=setTimeout(i,e)}}async function Wd(t){const e=document.getElementById("flutterflow-projects-select"),s=document.getElementById("flutterflow-projects-error");if(!e){console.error("Projects dropdown element not found");return}e.innerHTML='',s&&s.classList.add("hidden");try{const n=await new mr(t,"").listProjects();if(!n||n.length===0){e.innerHTML='';return}e.innerHTML='',n.forEach(i=>{const o=document.createElement("option");o.value=i.id||i.projectId||"",o.textContent=i.name||i.projectName||`Project ${i.id}`,e.appendChild(o)}),In&&(e.value=In)}catch(r){console.error("Failed to fetch projects:",r),e.innerHTML='',s&&(s.textContent=`Failed to load projects: ${r.message}`,s.classList.remove("hidden"))}}function iv(t){const e=document.getElementById(t),r=e.nextElementSibling.querySelector("svg");e.type==="password"?(e.type="text",r.innerHTML=` + `}const wm="https://ccc-ffai-runner-y5cyj3473a-uw.a.run.app/deployCustomClasses";const Je="https://4tgke4.buildship.run",Pd={professional:"price_1T2ldCKszA2slvDXatdeCpbI",power:"price_1T2le9KszA2slvDXR4mPvw7M"},_n="ccc_auth_session",dc=new WeakSet;let G={email:null,sessionToken:null,isVerified:!1};function bs(t={}){return{tier:"free",status:"none",periodEnd:null,isLoading:!1,isResolved:!1,error:null,...t}}let fe=bs({isResolved:!0});const bm=`${Je}/service/runpipeline`,Em="bs_user_id",Sm="bs_identity_token",xm=`${Je}/authUserCheck`;let Ge={userId:null,token:null,status:null,resolved:!1};const yn={free:2,professional:50,power:2e3},wn="ccc_subscription",hc=3,km=new Set(["active","trialing","paid"]),lr="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"],Im={"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 zt(t){return Im[t]||t}const Cm=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 Ad(t){return Cm.has(t)}const Eo=4,Ci=8*1024*1024,Fm="https://4tgke4.buildship.run/service/runpipeline-image";let Pt=[];function Pm(t){return new Promise(e=>{const s=new FileReader;s.onload=()=>e(s.result),s.onerror=()=>e(null),s.readAsDataURL(t)})}async function Am(t){const e=new FormData;return e.append("file",t),(await fetch(Fm,{method:"POST",body:e})).json()}function $m(t){if(Array.isArray(t)){const e=t[0];if(e&&typeof e=="object")for(const s of Object.keys(e)){if(s==="item"||s==="index")continue;const r=e[s];if(r&&typeof r=="object"){if(typeof r.file=="string")return r.file;if(typeof r.url=="string")return r.url}if(typeof r=="string")return r}return""}return typeof t=="string"?t:t&&typeof t=="object"&&(t.url||t.fileUrl||t.file_url||t.downloadUrl||t.imageUrl||t.image_url||t.file)||""}async function Rm(t){const e=Array.from(t.target.files||[]);if(!e.length)return;const s=e.filter(l=>l.size>Ci);s.length&&ue(`Skipped ${s.length} image(s) over the ${(Ci/1024/1024).toFixed(0)} MB limit.`,"warning");const r=e.filter(l=>l.size<=Ci);if(!r.length){t.target.value="";return}const n=Eo-Pt.length,o=r.slice(0,n).map(async l=>{const u=await Pm(l);if(!u)return null;let c="";try{c=$m(await Am(l))}catch{c=""}return{dataUrl:u,name:l.name,url:c}}),a=(await Promise.all(o)).filter(Boolean);t.target.value="",!(a.length&&!Ad(document.getElementById("code-generator-model")?.value))&&(Pt.push(...a),r.length>n&&ue(`You can attach up to ${Eo} images.`,"info"),la())}function Tm(t){Pt.splice(t,1),la()}function la(){const t=document.getElementById("prompt-image-thumbnails"),e=document.getElementById("prompt-image-btn-label");t&&(t.innerHTML="",Pt.forEach((s,r)=>{const n=document.createElement("div");n.className="prompt-img-thumb",n.innerHTML=`Prompt image`,t.appendChild(n)}),e&&(e.textContent=Pt.length>=Eo?"Image limit reached":"Add images"))}function $d(){const t=document.getElementById("prompt-image-upload");if(!t)return;const e=document.getElementById("code-generator-model"),s=Ad(e?.value);t.classList.toggle("hidden",!s),!s&&Pt.length&&(Pt=[],la())}const Gt="ccc_usage",Rd="google/gemini-3.7-flash",Td="google/gemini-3.7-flash",Fi="google/gemini-3.7-flash",pc={professional:11,power:49},So={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 Nm(){const t=new AbortController,e=setTimeout(()=>t.abort(),5e3);try{const s=await fetch("https://open.er-api.com/v6/latest/AUD",{signal:t.signal});if(!s.ok)return;const r=await s.json();if(r.result!=="success"||!r.rates)return;const n=r.rates,i={AUD:1},o=new Set([...Object.keys(Ur),...Object.values(xo),...Object.values(So)]);for(const a of o)a!=="AUD"&&(typeof n[a]=="number"&&n[a]>0?i[a]=n[a]:Ur[a]&&(i[a]=Ur[a]));Hr=i}catch{}finally{clearTimeout(e)}}const xo={"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 Nd(){try{const i=Intl.DateTimeFormat().resolvedOptions().timeZone;if(i&&xo[i])return xo[i]}catch{}const e=(navigator.language||"en-US").replace("-","_"),s=So[e];if(s)return s;const r=e.split("_")[0],n=So[r];return n||"USD"}function fc(t,e){const s=Hr[e]??Hr.USD,r=t*s,n=Math.round(r*100)/100;try{return new Intl.NumberFormat("en-US",{style:"currency",currency:e,minimumFractionDigits:0,maximumFractionDigits:n>=100||n%1===0?0:2}).format(n)}catch{return new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",minimumFractionDigits:0,maximumFractionDigits:2}).format(t*Hr.USD)}}const st="ccc_api_key_",_t="ccc_session_api_key_",it="ccc_encryption_key",cr="ccc_encryption_key_scope",Mm="ccc_keystore",bn="keys",ur="ccc_encryption_key_version";let ko=null,En=null,dr=!1,Sn=!1,gc=!1;class xn extends Error{constructor(){super("Secure browser key storage is unavailable."),this.name="CredentialStorageUnavailableError"}}function mc(){if(gc)return;gc=!0;const t="Secure browser key storage is unavailable. Existing credentials were left untouched; new credentials will be available only in this tab session.";console.warn(t),document.body&&ue(t,"warning")}function Md(){return localStorage.getItem(ur)||""}function Io(){return crypto.randomUUID?.()||Od(crypto.getRandomValues(new Uint8Array(16)))}function Lm(){const t=Md();if(t)return t;const e=Io();return localStorage.setItem(ur,e),e}function Es(){ko=null,En=null,dr=!1,Sn=!1}window.addEventListener("storage",t=>{t.key===ur&&Es()});function Om(){return new Promise((t,e)=>{const s=indexedDB.open(Mm,1);s.onupgradeneeded=()=>{const r=s.result;r.objectStoreNames.contains(bn)||r.createObjectStore(bn)},s.onsuccess=()=>t(s.result),s.onerror=()=>e(s.error)})}async function ca(t,e){const s=await Om();return new Promise((r,n)=>{const i=s.transaction(bn,t);let o;try{o=e(i.objectStore(bn))}catch(l){s.close(),n(l);return}let a;o.onsuccess=()=>{a=o.result},o.onerror=()=>n(o.error),i.oncomplete=()=>{s.close(),r(a)},i.onerror=()=>{s.close(),n(i.error||new Error("Encryption key transaction failed."))},i.onabort=()=>{s.close(),n(i.error||new Error("Encryption key transaction aborted."))}})}function Dm(t){return t instanceof CryptoKey&&t.algorithm?.name==="AES-GCM"&&t.extractable===!1&&t.usages.includes("encrypt")&&t.usages.includes("decrypt")}async function Bm(){const t=await ca("readonly",e=>e.get(it));return Dm(t)?t:null}async function Ld(t){await ca("readwrite",e=>e.put(t,it))}async function jm(){Es();try{await ca("readwrite",t=>t.delete(it))}catch(t){console.warn("Could not delete the stored encryption key:",t)}}async function Um(){const t=sessionStorage.getItem(it);if(!t)return null;const e=await crypto.subtle.importKey("jwk",JSON.parse(t),{name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);return await Ld(e),sessionStorage.removeItem(it),sessionStorage.removeItem(cr),localStorage.removeItem(st+"salt"),e}async function vc(t){const e=sessionStorage.getItem(it);if(e)return Sn=sessionStorage.getItem(cr)!=="session",crypto.subtle.importKey("jwk",JSON.parse(e),{name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);if(!t)throw new xn;const s=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!0,["encrypt","decrypt"]),r=await crypto.subtle.exportKey("jwk",s);return sessionStorage.setItem(it,JSON.stringify(r)),sessionStorage.setItem(cr,"session"),Sn=!1,crypto.subtle.importKey("jwk",r,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}async function Hm(t){if(sessionStorage.getItem(cr)==="session"&&sessionStorage.getItem(it))return mc(),dr=!0,vc(t);try{const e=await Bm();if(e)return e;const s=await Um();if(s)return s;const r=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);return await Ld(r),r}catch(e){return console.warn("IndexedDB encryption-key storage failed:",e),mc(),dr=!0,vc(t)}}async function ua(t={}){const{allowSessionFallbackCreation:e=!0}=t,s=Lm();En!==s&&Es();const r=ko||Hm(e);ko=r,En=s;try{return await r}catch(n){throw Es(),n}}async function Wm(t){const e=await ua(),s=En,r=new TextEncoder,n=crypto.getRandomValues(new Uint8Array(12)),i=await crypto.subtle.encrypt({name:"AES-GCM",iv:n},e,r.encode(t)),o=new Uint8Array(n.length+i.byteLength);return o.set(n),o.set(new Uint8Array(i),n.length),{ciphertext:Od(o),keyVersion:s,sessionFallback:dr}}async function zm(t,e={}){const{isSessionCredential:s=!1}=e;try{const r=await ua({allowSessionFallbackCreation:!1});if(dr&&!s&&!Sn)throw new xn;const n=qm(t),i=n.slice(0,12),o=n.slice(12),a=await crypto.subtle.decrypt({name:"AES-GCM",iv:i},r,o);return new TextDecoder().decode(a)}catch(r){if(r instanceof xn)throw r;return console.error("Decryption failed:",r),null}}function Od(t){const e=new Uint8Array(t);let s="";for(let r=0;r0}let hr="",kn="",Zs=null,yc=0;async function da(){sessionStorage.getItem(it)&&await ua(),hr=await Ee("flutterflow"),kn=await Ee("flutterflow_project_id"),Ym(),Zt()}function ha(){document.getElementById("api-keys-modal").classList.add("open"),fa(),hr&&Ud(hr)}function Dd(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("api-keys-modal");e&&e.classList.remove("open");const s=document.getElementById("walkthrough-modal");s&&(pa(),s.classList.add("open"))}let Et=1;function Bd(){const t=document.querySelector(".wt-steps");return t?Array.from(t.querySelectorAll(".wt-step-card")):[]}function Dn(){const t=Bd();t.length&&t.forEach((e,s)=>{const r=s+1;if(r===Et){e.classList.remove("opacity-60","bg-gray-50","border-gray-200"),e.classList.add("bg-blue-50","border-blue-200");const n=e.querySelector("div:first-child");n&&(n.classList.remove("bg-gray-400"),n.classList.add("bg-blue-500"),n.innerHTML=r)}else if(r0&&Et<=t&&(Et++,Dn())}function Gm(){const t=document.getElementById("walkthrough-modal");t&&(Et=1,Dn(),t.classList.add("open"))}function Km(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("walkthrough-modal");e&&e.classList.remove("open");const s=document.getElementById("walkthrough-dont-show");s&&s.checked&&localStorage.setItem("hasSeenWalkthrough","true")}function jd(){if(G.isVerified&&Jt()&&fe.tier!=="free")return;if(!localStorage.getItem("hasSeenWalkthrough")){const e=document.getElementById("walkthrough-modal");e&&(Et=1,Dn(),e.classList.add("open"))}}async function fa(){const t=document.getElementById("flutterflow-api-key-input");hr?(t.value="",t.placeholder="Key saved (enter new to replace)"):t.placeholder="Enter your FlutterFlow API key",Jm()}function Jm(){wc("flutterflow","flutterflow-key-status"),wc("flutterflow_project_id","flutterflow-project-status")}function wc(t,e){const s=document.getElementById(e);if(!s)return;const r=s.querySelector(".key-status-dot"),n=s.querySelector("span");as(t)?(r.className="key-status-dot configured",n.className="text-green-600",n.textContent="User key configured"):(r.className="key-status-dot missing",n.className="text-gray-500",n.textContent="Not configured")}function Zt(){const t=y.step2Result&&y.step2Result.length>0,e=document.getElementById("btn-deploy-to-ff"),s=document.getElementById("btn-run-pipeline");s&&s.classList.remove("hidden"),e&&e.classList.toggle("hidden",!t)}function Ym(){const t=document.getElementById("api-keys-status");if(!t)return;const e=t.querySelectorAll(".key-status-dot"),s=["flutterflow"];e.forEach((r,n)=>{const i=s[n];i==="flutterflow"?as("flutterflow")&&as("flutterflow_project_id")?(r.className="key-status-dot configured",r.title="FlutterFlow (Fully configured)"):as("flutterflow")||as("flutterflow_project_id")?(r.className="key-status-dot env",r.title="FlutterFlow (Partially configured)"):(r.className="key-status-dot missing",r.title="FlutterFlow (Not configured)"):as(i)?(r.className="key-status-dot configured",r.title=i.charAt(0).toUpperCase()+i.slice(1)+" (User key)"):(r.className="key-status-dot missing",r.title=i.charAt(0).toUpperCase()+i.slice(1)+" (Not configured)")}),Zt()}async function Zm(){const t=document.getElementById("flutterflow-api-key-input"),e=document.getElementById("flutterflow-projects-select");t.value.trim()&&await _c("flutterflow",t.value);const s=e?.value.trim()||"";if(s){if(!Bn(s)){ue("The selected FlutterFlow project has an unexpected ID format.","error"),e.focus();return}await _c("flutterflow_project_id",s)}await da(),fa();const r=document.querySelector("#api-keys-modal .bg-blue-500"),n=r.textContent;r.textContent="Saved!",r.classList.remove("bg-blue-500","hover:bg-blue-600"),r.classList.add("bg-green-500"),setTimeout(()=>{r.textContent=n,r.classList.remove("bg-green-500"),r.classList.add("bg-blue-500","hover:bg-blue-600"),Dd()},1e3)}async function Xm(){if(!confirm("Are you sure you want to clear all stored API keys?"))return;localStorage.setItem(ur,Io()),Es(),localStorage.removeItem(st+"flutterflow"),localStorage.removeItem(st+"flutterflow_project_id"),sessionStorage.removeItem(_t+"flutterflow"),sessionStorage.removeItem(_t+"flutterflow_project_id"),sessionStorage.removeItem(it),sessionStorage.removeItem(cr),localStorage.removeItem(st+"salt"),await jm(),localStorage.setItem(ur,Io()),localStorage.removeItem(st+"flutterflow"),localStorage.removeItem(st+"flutterflow_project_id"),sessionStorage.removeItem(_t+"flutterflow"),sessionStorage.removeItem(_t+"flutterflow_project_id"),await da();const t=document.getElementById("flutterflow-projects-select");t&&(t.innerHTML=''),fa()}function Bn(t){return!t||t.trim().length<5||t.includes(" ")?!1:/^[a-zA-Z0-9-]+$/.test(t)}function Qm(t,e){const s=document.getElementById(t);s&&(s.value?e?s.style.borderColor="#22c55e":s.style.borderColor="#ef4444":s.style.borderColor="")}function ev(){const t=document.getElementById("flutterflow-api-key-input");t&&(t.addEventListener("input",e=>{const s=e.target.value.trim().length>0;Qm("flutterflow-api-key-input",s)}),t.addEventListener("blur",tv(async e=>{const s=e.target.value.trim();s&&await Ud(s)},500)))}function tv(t,e){let s;return function(...n){const i=()=>{clearTimeout(s),t(...n)};clearTimeout(s),s=setTimeout(i,e)}}async function Ud(t){const e=document.getElementById("flutterflow-projects-select"),s=document.getElementById("flutterflow-projects-error");if(!e){console.error("Projects dropdown element not found");return}e.innerHTML='',s&&s.classList.add("hidden");try{const n=await new gr(t,"").listProjects();if(!n||n.length===0){e.innerHTML='';return}e.innerHTML='',n.forEach(i=>{const o=document.createElement("option");o.value=i.id||i.projectId||"",o.textContent=i.name||i.projectName||`Project ${i.id}`,e.appendChild(o)}),kn&&(e.value=kn)}catch(r){console.error("Failed to fetch projects:",r),e.innerHTML='',s&&(s.textContent=`Failed to load projects: ${r.message}`,s.classList.remove("hidden"))}}function sv(t){const e=document.getElementById(t),r=e.nextElementSibling.querySelector("svg");e.type==="password"?(e.type="text",r.innerHTML=` `):(e.type="password",r.innerHTML=` - `)}let y={step1Result:null,step2Result:null,step3Result:null,bundleSpec:null,artifactBundle:null,bundleReview:null,selectedArtifactId:null,resultsViewMode:"summary",currentStep:0,isRunning:!1};function ov(){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 av(){y.bundleSpec=ar(y.step1Result,{artifactType:"CustomWidget",artifactName:"GeneratedWidget"})}function Un(){const t=mn(y.bundleSpec);y.artifactBundle=ar(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=hg(y.artifactBundle);y.artifactBundle={...y.artifactBundle,warnings:[...y.artifactBundle.warnings,...e.findings.map(s=>s.message)],metadata:{...y.artifactBundle.metadata,compatibility:e}},y.selectedArtifactId=mn(y.artifactBundle).id}function Hn(){const t=ar(y.step3Result,{id:y.artifactBundle?.id,title:y.artifactBundle?.title}),e=new Map(t.artifacts.map(r=>[r.id,r.review])),s=new Map(t.artifacts.filter(r=>{const n=r.review;return n&&typeof n.fixedSource=="string"&&n.fixedSource.trim()}).map(r=>[r.id,r.review.fixedSource.trim()]));y.bundleReview=ar({id:y.artifactBundle?.id,title:y.artifactBundle?.title,artifacts:y.artifactBundle?.artifacts?.map(r=>{const n=s.get(r.id)||null;return{...r,review:e.get(r.id)||r.review||y.step3Result||null,...n?{fixedCode:n}:{}}})||[],relationships:y.artifactBundle?.relationships,warnings:y.artifactBundle?.warnings})}function zd(){const t=ma();return{artifactType:t.artifactType||"CustomWidget",artifactName:t.artifactName||"GeneratedWidget",fileName:t.fileName||""}}function ma(){const t=y.artifactBundle||y.bundleSpec||null;return(Array.isArray(t?.artifacts)?t.artifacts:[]).find(s=>s.id===y.selectedArtifactId)||mn(t)}function va(){return ma().code||y.step2Result||""}async function lv(){try{await ha()}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 cv(t,e){const s=e?.trim()?` (${e.trim().slice(0,200)})`:"";return t===401?`Your FlutterFlow API key was rejected (401 Unauthorized)${s}. Re-enter a current key under API Keys settings, then try again.`:`Listing FlutterFlow projects was denied (403)${s}. 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 mr{constructor(e,s,r="main",n=zr.production){this.apiKey=e,this.baseUrl=n,this._projectId=s,this._branchName=r,this._endpoint=n}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 s=null;for(const r of e)try{const n=await fetch(`${this.baseUrl}exportCode`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify(r)});if(!n.ok){const a=await n.text();s=new Error(`Export failed: ${n.status} - ${a}`);continue}const i=await n.json(),o=i?.value?.project_zip||i?.project_zip;if(!o){s=new Error("Export response did not include project source.");continue}return o}catch(n){s=n}throw s||new Error("Export failed for an unknown reason.")}async fetchProjectSource(){const e=await this.exportProjectZip(),s=await JSZip.loadAsync(e,{base64:!0}),r=Object.keys(s.files).filter(a=>!s.files[a].dir&&(a==="pubspec.yaml"||a.endsWith("/pubspec.yaml"))).sort((a,l)=>a.split("/").length-l.split("/").length)[0];if(!r)throw new Error("Export did not contain a pubspec.yaml.");const n=r.slice(0,r.length-12),i=new Map,o=Object.keys(s.files).filter(a=>{if(s.files[a].dir||!a.startsWith(n))return!1;const l=a.slice(n.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=>{i.set(a.slice(n.length),await s.files[a].async("string"))})),{pubspecYaml:await s.files[r].async("string"),files:i}}async pushCodeWithRetry(e,s=3){const r=[zr.production,zr.staging],n=Math.max(0,r.indexOf(this._endpoint));for(let i=0;isetTimeout(d,1e3*(i+1)));continue}return l}catch(l){console.warn(`Push to ${a} failed: ${l.message}, trying next...`),await new Promise(u=>setTimeout(u,1e3*(i+1)))}}throw new Error("All API endpoints failed after retries")}async pushCode(e){return this.pushCodeWithRetry(e)}parseProjectsResponse(e){if(e?.success&&typeof e.value=="string")try{const r=JSON.parse(e.value);if(r&&Array.isArray(r.entries))return r.entries.map(n=>({id:n.id,name:n.project?.name||n.id}))}catch(r){console.error("Failed to parse stringified project value:",r)}const s=e?.projects||e?.items||e?.entries||(Array.isArray(e)?e:[]);return Array.isArray(s)?s:[]}async listProjects(){console.log("Listing projects for API key");const e=[`${this.baseUrl}listProjects`,"https://api.flutterflow.io/v2/l/listProjects"];let s=0,r="";for(const n of e){const i=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify({project_type:"ALL",deserialize_response:!0})});if(i.ok)return n!==e[0]&&console.log(`listProjects answered on legacy path ${n}`),this.parseProjectsResponse(await i.json());if(s=i.status,r=await i.text(),console.warn(`listProjects via ${n} returned ${s}: ${r}`),i.status===401||i.status===403)throw new Error(cv(i.status,r));if(i.status!==404)throw new Error(`List projects failed: ${i.status} - ${r}`)}throw new Error(`List projects failed: ${s} - ${r}`)}}async function _a(t){const e=t.clone();let s;try{s=await t.json()}catch{const i=await e.text();if(!t.ok)return{success:!1,responseCode:t.status,errorMessage:i||`HTTP ${t.status}`,errorMap:new Map};throw new Error(`Invalid JSON response: ${i}`)}if(!t.ok){let n=s.message||`HTTP ${t.status}`,i=new Map;if(s.errors)i=new Map(Object.entries(s.errors));else if(!s.message&&typeof s=="object"){const o=Object.keys(s).filter(a=>a.endsWith(".dart")&&Array.isArray(s[a]));o.length>0&&(i=new Map(Object.entries(s)),n=o.flatMap(l=>s[l].map(u=>`${l}: ${u.errorMessage}`)).join(` -`)||`HTTP ${t.status}`)}return{success:!1,responseCode:t.status,errorMessage:n,errorMap:i}}let r={};if(s.value)try{r=typeof s.value=="string"?JSON.parse(s.value):s.value}catch(n){console.warn("Ignoring malformed push response value:",n)}return{success:!0,responseCode:t.status,errorMap:new Map(Object.entries(r))}}function ya(t,e){return{401:"Authentication failed. Please check your FlutterFlow API key.",403:"Access denied. You may not have permission to modify this project.",404:"Project not found. Please check your Project ID.",409:"Conflict detected. The project may have been modified elsewhere.",422:"Validation failed: Invalid request format",429:"Rate limit exceeded. Please try again in a few minutes.",500:"FlutterFlow server error. Please try again later.",503:"FlutterFlow service temporarily unavailable."}[t]||`FlutterFlow API error: ${`HTTP ${t}`}`}const U={ACTION:"A",WIDGET:"W",FUNCTION:"F",CODE_FILE:"C",DEPENDENCIES:"D",OTHER:"O"},qd=/class\s+\w+\s+extends\s+(?:StatelessWidget|StatefulWidget)\b/,Vd=/extends\s+State<\w+>/;function uv(t,e=""){if(t==="pubspec.yaml")return U.DEPENDENCIES;if(!t.endsWith(".dart")||t.endsWith("index.dart"))return U.OTHER;if(t==="custom_functions.dart")return U.FUNCTION;if(e){const s=qd.test(e),r=Vd.test(e);if(s||r)return U.WIDGET;if(/^\s*Future(?:<[^>]+>)?\s+\w+\s*\(/m.test(e))return U.ACTION;if(e.match(/^\s*(String|int|double|bool|List|Map|dynamic|void)\s+\w+\s*\(/m))return U.FUNCTION}return U.CODE_FILE}function Gd(t,e){switch(e){case U.ACTION:return`lib/custom_code/actions/${t}`;case U.WIDGET:return`lib/custom_code/widgets/${t}`;case U.FUNCTION:return"lib/flutter_flow/custom_functions.dart";case U.CODE_FILE:return`lib/custom_code/${t}`;case U.DEPENDENCIES:return"pubspec.yaml";case U.OTHER:return`lib/custom_code/${t}`;default:return t}}async function wa(t,e=new Map){return Kf(t,e)}const Fo=new Map;function Kd(t){return`${t.baseUrl}|${t.projectId}|${t.branchName}`}function Wn(t){Fo.delete(Kd(t))}async function ba(t,e,s,r,n=""){const i=Ig(e,s);if(i.length===0)return{remoteFiles:s,syncFileMap:e,unverified:[]};const o=sm(i,n),a={...o.manifest,sources:o.sources},l=o.skipped.map(d=>d.reason);l.forEach(d=>console.warn(`[custom class deploy] ${d}`)),console.log(`Provisioning ${i.length} new FlutterFlow custom code file(s) before sync.`),be.set("provision");const u=await fetch(bm,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:t.apiKey,projectId:t.projectId,baseUrl:t.baseUrl,commitMessage:r,customClasses:i,verification:a,stream:!0})}),c=await nm(u,{onPhase:d=>be.setSubstatus(d),onLog:d=>console.log(`[custom class deploy] ${d}`)});if(!c.success){const d=c.details?` ${c.details}`:"";throw new Error(`${c.error||"FlutterFlow custom class provisioning failed."}${d}`)}return Wn(t),c.verificationSkipped&&(console.warn(`[custom class deploy] ${c.verificationSkipped}`),l.push(c.verificationSkipped)),{remoteFiles:s,syncFileMap:Cg(e,i),unverified:l}}async function Ea(t,e={}){const s=Kd(t);let r=Fo.get(s);if(r===void 0){try{r=await t.fetchProjectSource()}catch(l){throw new Error(`Could not read your project's pubspec.yaml (${l.message}). Deploy was stopped so your existing package dependencies aren't overwritten. Check your FlutterFlow API key and project, then try again.`)}const a=Fd(r.pubspecYaml);if(!a.valid)throw new Error(`Your project's pubspec.yaml could not be read reliably (${a.errors.join("; ")}). Deploy was stopped so your existing package dependencies aren't overwritten.`);Fo.set(s,r)}const n=await gm(r.pubspecYaml,e),i=Zg(r.pubspecYaml,n.overrides),o=Yg(i.yaml,n.additions);return n.warnings.forEach(a=>console.warn(`[pubspec] ${a}`)),o.added.length>0&&console.log("Adding dependencies:",o.added.map(a=>`${a}: ${n.additions[a]||"any"}`).join(", "),n.sdk.dartSdkFloor?`(resolved for Dart ${n.sdk.dartSdkFloor})`:""),n.kept.forEach(({name:a,constraint:l})=>console.log(`Keeping your existing ${a}: ${l||"(non-version source)"}`)),{...o,overridden:i.overridden,warnings:n.warnings,remoteFiles:r.files}}function dv(t){const e=[],s=[];t.content.length>5e4&&s.push("Code file is large (>50KB). This may take longer to commit."),t.content.length>1e5&&e.push("Code file is too large (>100KB). Consider splitting into smaller components.");const r=t.content.split(` -`).length;r>500&&s.push(`Code has ${r} lines. Consider breaking it into smaller widgets.`),t.content.includes("setState")&&t.codeType===U.ACTION&&s.push("Using setState in a Custom Action may not work as expected. Consider using a Custom Widget."),t.content.includes("dynamic")&&!t.content.includes("?")&&s.push('Code uses "dynamic" types. Consider adding explicit types for better null safety.'),t.content.match(/Color\(0xFF[0-9A-Fa-f]{6}\)/)&&s.push("Code contains hardcoded colors. Consider using FlutterFlowTheme.of(context) for theme consistency.");const n=t.content.match(/print\s*\(/g);n&&n.length>3&&s.push(`Code contains ${n.length} print statements. Consider removing debug prints before committing.`);const i=qg(t.content);if(i&&e.push(`FlutterFlow cannot format this code - ${i}. Fix or regenerate before committing.`),t.codeType===U.WIDGET){const o=bd(t.content),a=Hg(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=`${Ed(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:s}}function Jd(t,e={}){const{artifactType:s="CustomWidget",artifactName:r="GeneratedCode",fileName:n}=e,i=jg(t);let o=n||r;if(s==="CustomFunction")o="custom_functions.dart";else if(s==="CustomWidget"){const u=bd(i)[0],c=u?Ed(u):null;c&&o!==c?(console.warn(`Commit file name "${o}" does not match declared widget class "${u}"; renaming to "${c}" so FlutterFlow can find the widget.`),o=c):o.endsWith(".dart")||(o+=".dart")}else o.endsWith(".dart")||(o+=".dart");let a=U.CODE_FILE;switch(s){case"CustomAction":a=U.ACTION;break;case"CustomWidget":a=U.WIDGET;break;case"CustomFunction":a=U.FUNCTION;break;case"CustomClass":case"CodeFile":a=U.CODE_FILE;break}let l="";return a===U.WIDGET?l=`// Automatic FlutterFlow imports + `)}let y={step1Result:null,step2Result:null,step3Result:null,bundleSpec:null,artifactBundle:null,bundleReview:null,selectedArtifactId:null,resultsViewMode:"summary",currentStep:0,isRunning:!1};function rv(){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 nv(){y.bundleSpec=or(y.step1Result,{artifactType:"CustomWidget",artifactName:"GeneratedWidget"})}function jn(){const t=gn(y.bundleSpec);y.artifactBundle=or(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=ug(y.artifactBundle);y.artifactBundle={...y.artifactBundle,warnings:[...y.artifactBundle.warnings,...e.findings.map(s=>s.message)],metadata:{...y.artifactBundle.metadata,compatibility:e}},y.selectedArtifactId=gn(y.artifactBundle).id}function Un(){const t=or(y.step3Result,{id:y.artifactBundle?.id,title:y.artifactBundle?.title}),e=new Map(t.artifacts.map(r=>[r.id,r.review])),s=new Map(t.artifacts.filter(r=>{const n=r.review;return n&&typeof n.fixedSource=="string"&&n.fixedSource.trim()}).map(r=>[r.id,r.review.fixedSource.trim()]));y.bundleReview=or({id:y.artifactBundle?.id,title:y.artifactBundle?.title,artifacts:y.artifactBundle?.artifacts?.map(r=>{const n=s.get(r.id)||null;return{...r,review:e.get(r.id)||r.review||y.step3Result||null,...n?{fixedCode:n}:{}}})||[],relationships:y.artifactBundle?.relationships,warnings:y.artifactBundle?.warnings})}function Hd(){const t=ga();return{artifactType:t.artifactType||"CustomWidget",artifactName:t.artifactName||"GeneratedWidget",fileName:t.fileName||""}}function ga(){const t=y.artifactBundle||y.bundleSpec||null;return(Array.isArray(t?.artifacts)?t.artifacts:[]).find(s=>s.id===y.selectedArtifactId)||gn(t)}function ma(){return ga().code||y.step2Result||""}async function iv(){try{await da()}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 ov(t,e){const s=e?.trim()?` (${e.trim().slice(0,200)})`:"";return t===401?`Your FlutterFlow API key was rejected (401 Unauthorized)${s}. Re-enter a current key under API Keys settings, then try again.`:`Listing FlutterFlow projects was denied (403)${s}. 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 gr{constructor(e,s,r="main",n=Wr.production){this.apiKey=e,this.baseUrl=n,this._projectId=s,this._branchName=r,this._endpoint=n}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 s=null;for(const r of e)try{const n=await fetch(`${this.baseUrl}exportCode`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify(r)});if(!n.ok){const a=await n.text();s=new Error(`Export failed: ${n.status} - ${a}`);continue}const i=await n.json(),o=i?.value?.project_zip||i?.project_zip;if(!o){s=new Error("Export response did not include project source.");continue}return o}catch(n){s=n}throw s||new Error("Export failed for an unknown reason.")}async fetchProjectSource(){const e=await this.exportProjectZip(),s=await JSZip.loadAsync(e,{base64:!0}),r=Object.keys(s.files).filter(a=>!s.files[a].dir&&(a==="pubspec.yaml"||a.endsWith("/pubspec.yaml"))).sort((a,l)=>a.split("/").length-l.split("/").length)[0];if(!r)throw new Error("Export did not contain a pubspec.yaml.");const n=r.slice(0,r.length-12),i=new Map,o=Object.keys(s.files).filter(a=>{if(s.files[a].dir||!a.startsWith(n))return!1;const l=a.slice(n.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=>{i.set(a.slice(n.length),await s.files[a].async("string"))})),{pubspecYaml:await s.files[r].async("string"),files:i}}async pushCodeWithRetry(e,s=3){const r=[Wr.production,Wr.staging],n=Math.max(0,r.indexOf(this._endpoint));for(let i=0;isetTimeout(d,1e3*(i+1)));continue}return l}catch(l){console.warn(`Push to ${a} failed: ${l.message}, trying next...`),await new Promise(u=>setTimeout(u,1e3*(i+1)))}}throw new Error("All API endpoints failed after retries")}async pushCode(e){return this.pushCodeWithRetry(e)}parseProjectsResponse(e){if(e?.success&&typeof e.value=="string")try{const r=JSON.parse(e.value);if(r&&Array.isArray(r.entries))return r.entries.map(n=>({id:n.id,name:n.project?.name||n.id}))}catch(r){console.error("Failed to parse stringified project value:",r)}const s=e?.projects||e?.items||e?.entries||(Array.isArray(e)?e:[]);return Array.isArray(s)?s:[]}async listProjects(){console.log("Listing projects for API key");const e=[`${this.baseUrl}listProjects`,"https://api.flutterflow.io/v2/l/listProjects"];let s=0,r="";for(const n of e){const i=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify({project_type:"ALL",deserialize_response:!0})});if(i.ok)return n!==e[0]&&console.log(`listProjects answered on legacy path ${n}`),this.parseProjectsResponse(await i.json());if(s=i.status,r=await i.text(),console.warn(`listProjects via ${n} returned ${s}: ${r}`),i.status===401||i.status===403)throw new Error(ov(i.status,r));if(i.status!==404)throw new Error(`List projects failed: ${i.status} - ${r}`)}throw new Error(`List projects failed: ${s} - ${r}`)}}async function va(t){const e=t.clone();let s;try{s=await t.json()}catch{const i=await e.text();if(!t.ok)return{success:!1,responseCode:t.status,errorMessage:i||`HTTP ${t.status}`,errorMap:new Map};throw new Error(`Invalid JSON response: ${i}`)}if(!t.ok){let n=s.message||`HTTP ${t.status}`,i=new Map;if(s.errors)i=new Map(Object.entries(s.errors));else if(!s.message&&typeof s=="object"){const o=Object.keys(s).filter(a=>a.endsWith(".dart")&&Array.isArray(s[a]));o.length>0&&(i=new Map(Object.entries(s)),n=o.flatMap(l=>s[l].map(u=>`${l}: ${u.errorMessage}`)).join(` +`)||`HTTP ${t.status}`)}return{success:!1,responseCode:t.status,errorMessage:n,errorMap:i}}let r={};if(s.value)try{r=typeof s.value=="string"?JSON.parse(s.value):s.value}catch(n){console.warn("Ignoring malformed push response value:",n)}return{success:!0,responseCode:t.status,errorMap:new Map(Object.entries(r))}}function _a(t,e){return{401:"Authentication failed. Please check your FlutterFlow API key.",403:"Access denied. You may not have permission to modify this project.",404:"Project not found. Please check your Project ID.",409:"Conflict detected. The project may have been modified elsewhere.",422:"Validation failed: Invalid request format",429:"Rate limit exceeded. Please try again in a few minutes.",500:"FlutterFlow server error. Please try again later.",503:"FlutterFlow service temporarily unavailable."}[t]||`FlutterFlow API error: ${`HTTP ${t}`}`}const U={ACTION:"A",WIDGET:"W",FUNCTION:"F",CODE_FILE:"C",DEPENDENCIES:"D",OTHER:"O"},Wd=/class\s+\w+\s+extends\s+(?:StatelessWidget|StatefulWidget)\b/,zd=/extends\s+State<\w+>/;function av(t,e=""){if(t==="pubspec.yaml")return U.DEPENDENCIES;if(!t.endsWith(".dart")||t.endsWith("index.dart"))return U.OTHER;if(t==="custom_functions.dart")return U.FUNCTION;if(e){const s=Wd.test(e),r=zd.test(e);if(s||r)return U.WIDGET;if(/^\s*Future(?:<[^>]+>)?\s+\w+\s*\(/m.test(e))return U.ACTION;if(e.match(/^\s*(String|int|double|bool|List|Map|dynamic|void)\s+\w+\s*\(/m))return U.FUNCTION}return U.CODE_FILE}function qd(t,e){switch(e){case U.ACTION:return`lib/custom_code/actions/${t}`;case U.WIDGET:return`lib/custom_code/widgets/${t}`;case U.FUNCTION:return"lib/flutter_flow/custom_functions.dart";case U.CODE_FILE:return`lib/custom_code/${t}`;case U.DEPENDENCIES:return"pubspec.yaml";case U.OTHER:return`lib/custom_code/${t}`;default:return t}}async function ya(t,e=new Map){return Vf(t,e)}const Co=new Map;function Vd(t){return`${t.baseUrl}|${t.projectId}|${t.branchName}`}function Hn(t){Co.delete(Vd(t))}async function wa(t,e,s,r,n=""){const i=xg(e,s);if(i.length===0)return{remoteFiles:s,syncFileMap:e,unverified:[]};const o=tm(i,n),a={...o.manifest,sources:o.sources},l=o.skipped.map(d=>d.reason);l.forEach(d=>console.warn(`[custom class deploy] ${d}`)),console.log(`Provisioning ${i.length} new FlutterFlow custom code file(s) before sync.`),be.set("provision");const u=await fetch(wm,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:t.apiKey,projectId:t.projectId,baseUrl:t.baseUrl,commitMessage:r,customClasses:i,verification:a,stream:!0})}),c=await rm(u,{onPhase:d=>be.setSubstatus(d),onLog:d=>console.log(`[custom class deploy] ${d}`)});if(!c.success){const d=c.details?` ${c.details}`:"";throw new Error(`${c.error||"FlutterFlow custom class provisioning failed."}${d}`)}return Hn(t),c.verificationSkipped&&(console.warn(`[custom class deploy] ${c.verificationSkipped}`),l.push(c.verificationSkipped)),{remoteFiles:s,syncFileMap:kg(e,i),unverified:l}}async function ba(t,e={}){const s=Vd(t);let r=Co.get(s);if(r===void 0){try{r=await t.fetchProjectSource()}catch(l){throw new Error(`Could not read your project's pubspec.yaml (${l.message}). Deploy was stopped so your existing package dependencies aren't overwritten. Check your FlutterFlow API key and project, then try again.`)}const a=Id(r.pubspecYaml);if(!a.valid)throw new Error(`Your project's pubspec.yaml could not be read reliably (${a.errors.join("; ")}). Deploy was stopped so your existing package dependencies aren't overwritten.`);Co.set(s,r)}const n=await fm(r.pubspecYaml,e),i=Yg(r.pubspecYaml,n.overrides),o=Jg(i.yaml,n.additions);return n.warnings.forEach(a=>console.warn(`[pubspec] ${a}`)),o.added.length>0&&console.log("Adding dependencies:",o.added.map(a=>`${a}: ${n.additions[a]||"any"}`).join(", "),n.sdk.dartSdkFloor?`(resolved for Dart ${n.sdk.dartSdkFloor})`:""),n.kept.forEach(({name:a,constraint:l})=>console.log(`Keeping your existing ${a}: ${l||"(non-version source)"}`)),{...o,overridden:i.overridden,warnings:n.warnings,remoteFiles:r.files}}function lv(t){const e=[],s=[];t.content.length>5e4&&s.push("Code file is large (>50KB). This may take longer to commit."),t.content.length>1e5&&e.push("Code file is too large (>100KB). Consider splitting into smaller components.");const r=t.content.split(` +`).length;r>500&&s.push(`Code has ${r} lines. Consider breaking it into smaller widgets.`),t.content.includes("setState")&&t.codeType===U.ACTION&&s.push("Using setState in a Custom Action may not work as expected. Consider using a Custom Widget."),t.content.includes("dynamic")&&!t.content.includes("?")&&s.push('Code uses "dynamic" types. Consider adding explicit types for better null safety.'),t.content.match(/Color\(0xFF[0-9A-Fa-f]{6}\)/)&&s.push("Code contains hardcoded colors. Consider using FlutterFlowTheme.of(context) for theme consistency.");const n=t.content.match(/print\s*\(/g);n&&n.length>3&&s.push(`Code contains ${n.length} print statements. Consider removing debug prints before committing.`);const i=Wg(t.content);if(i&&e.push(`FlutterFlow cannot format this code - ${i}. Fix or regenerate before committing.`),t.codeType===U.WIDGET){const o=yd(t.content),a=jg(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=`${wd(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:s}}function Gd(t,e={}){const{artifactType:s="CustomWidget",artifactName:r="GeneratedCode",fileName:n}=e,i=Dg(t);let o=n||r;if(s==="CustomFunction")o="custom_functions.dart";else if(s==="CustomWidget"){const u=yd(i)[0],c=u?wd(u):null;c&&o!==c?(console.warn(`Commit file name "${o}" does not match declared widget class "${u}"; renaming to "${c}" so FlutterFlow can find the widget.`),o=c):o.endsWith(".dart")||(o+=".dart")}else o.endsWith(".dart")||(o+=".dart");let a=U.CODE_FILE;switch(s){case"CustomAction":a=U.ACTION;break;case"CustomWidget":a=U.WIDGET;break;case"CustomFunction":a=U.FUNCTION;break;case"CustomClass":case"CodeFile":a=U.CODE_FILE;break}let l="";return a===U.WIDGET?l=`// Automatic FlutterFlow imports import '/flutter_flow/flutter_flow_theme.dart'; import '/flutter_flow/flutter_flow_util.dart'; import 'package:flutter/material.dart'; @@ -109,15 +109,15 @@ import '/flutter_flow/lat_lng.dart'; import '/flutter_flow/place.dart'; import '/flutter_flow/uploaded_file.dart'; -`),{content:gg(i,l),fileName:o,codeType:a,artifactType:s,artifactName:r}}function hv(t){const e={};for(const s of na(t))e[s]="";return e}function pv(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 fv(t,e,s,r=new Set,n=""){const i=[],o=qd.test(e),a=Vd.test(e);return s===U.WIDGET&&!o&&!a&&i.push("No widget class definition found (must extend StatelessWidget or StatefulWidget)"),{valid:i.length===0,errors:i}}function zn(t){const e=[],s=[];if(!t||t.size===0)return e.push("No files to commit"),{valid:!1,errors:e,warnings:s};const r=new Set(Array.from(t.values()).flatMap(n=>Nn(n.content||"")));for(const[n,i]of t.entries()){if((!i.content||i.content.trim().length===0)&&e.push(`File ${n} is empty`),i.content&&i.content.length>1e5&&s.push(`File ${n} is very large (>100KB)`),n.endsWith(".dart")){const o=fv(n,i.content,i.type,r,i.artifactName);o.valid||e.push(...o.errors.map(a=>`${n}: ${a}`))}if(n==="pubspec.yaml"){const o=Fd(i.content);o.valid||e.push(...o.errors)}}return{valid:e.length===0,errors:e,warnings:s}}const V={IDLE:"IDLE",PREPARING:"PREPARING",VALIDATING:"VALIDATING",PUSHING:"PUSHING",SUCCESS:"SUCCESS",ERROR:"ERROR"},K={currentState:V.IDLE,startTime:null,endTime:null,error:null,result:null,filesProcessed:0,totalFiles:0,reset(){this.currentState=V.IDLE,this.startTime=null,this.endTime=null,this.error=null,this.result=null,this.filesProcessed=0,this.totalFiles=0},setState(t){if(!Object.values(V).includes(t)){console.error(`Invalid commit state: ${t}`);return}this.currentState=t,t===V.PREPARING&&(this.startTime=Date.now()),(t===V.SUCCESS||t===V.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(V.ERROR)},setSuccess(t){this.result=t,this.setState(V.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===V.PREPARING||this.currentState===V.VALIDATING||this.currentState===V.PUSHING}};async function gv(t,e,s={}){let{codeType:r="W"}=s;const{pubspecDeps:n={},artifactName:i=e}=s;r==="CustomWidget"&&(r=U.WIDGET),r==="CustomAction"&&(r=U.ACTION),r==="CustomFunction"&&(r=U.FUNCTION),r==="CustomClass"&&(r=U.CODE_FILE),r==="CodeFile"&&(r=U.CODE_FILE),K.reset(),K.setState(V.PREPARING);try{const o=await Ee("flutterflow"),a=await Ee("flutterflow_project_id");if(!o||!a)throw new Error("FlutterFlow credentials not configured. Please set your API key and Project ID in the API Keys settings.");if(!jn(a))throw new Error("Invalid FlutterFlow Project ID format.");const l=gr(),u=new mr(o,a,"main",l);K.setState(V.VALIDATING);const c=new Map,d=r||uv(e,t),h=Gd(e,d);c.set(e,{artifactName:i,content:t,type:d,path:h}),K.setProgress(0,c.size);const p=zn(c);if(!p.valid)throw new Error(`Validation failed: +`),{content:pg(i,l),fileName:o,codeType:a,artifactType:s,artifactName:r}}function cv(t){const e={};for(const s of ra(t))e[s]="";return e}function uv(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 dv(t,e,s,r=new Set,n=""){const i=[],o=Wd.test(e),a=zd.test(e);return s===U.WIDGET&&!o&&!a&&i.push("No widget class definition found (must extend StatelessWidget or StatefulWidget)"),{valid:i.length===0,errors:i}}function Wn(t){const e=[],s=[];if(!t||t.size===0)return e.push("No files to commit"),{valid:!1,errors:e,warnings:s};const r=new Set(Array.from(t.values()).flatMap(n=>Tn(n.content||"")));for(const[n,i]of t.entries()){if((!i.content||i.content.trim().length===0)&&e.push(`File ${n} is empty`),i.content&&i.content.length>1e5&&s.push(`File ${n} is very large (>100KB)`),n.endsWith(".dart")){const o=dv(n,i.content,i.type,r,i.artifactName);o.valid||e.push(...o.errors.map(a=>`${n}: ${a}`))}if(n==="pubspec.yaml"){const o=Id(i.content);o.valid||e.push(...o.errors)}}return{valid:e.length===0,errors:e,warnings:s}}const V={IDLE:"IDLE",PREPARING:"PREPARING",VALIDATING:"VALIDATING",PUSHING:"PUSHING",SUCCESS:"SUCCESS",ERROR:"ERROR"},K={currentState:V.IDLE,startTime:null,endTime:null,error:null,result:null,filesProcessed:0,totalFiles:0,reset(){this.currentState=V.IDLE,this.startTime=null,this.endTime=null,this.error=null,this.result=null,this.filesProcessed=0,this.totalFiles=0},setState(t){if(!Object.values(V).includes(t)){console.error(`Invalid commit state: ${t}`);return}this.currentState=t,t===V.PREPARING&&(this.startTime=Date.now()),(t===V.SUCCESS||t===V.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(V.ERROR)},setSuccess(t){this.result=t,this.setState(V.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===V.PREPARING||this.currentState===V.VALIDATING||this.currentState===V.PUSHING}};async function hv(t,e,s={}){let{codeType:r="W"}=s;const{pubspecDeps:n={},artifactName:i=e}=s;r==="CustomWidget"&&(r=U.WIDGET),r==="CustomAction"&&(r=U.ACTION),r==="CustomFunction"&&(r=U.FUNCTION),r==="CustomClass"&&(r=U.CODE_FILE),r==="CodeFile"&&(r=U.CODE_FILE),K.reset(),K.setState(V.PREPARING);try{const o=await Ee("flutterflow"),a=await Ee("flutterflow_project_id");if(!o||!a)throw new Error("FlutterFlow credentials not configured. Please set your API key and Project ID in the API Keys settings.");if(!Bn(a))throw new Error("Invalid FlutterFlow Project ID format.");const l=fr(),u=new gr(o,a,"main",l);K.setState(V.VALIDATING);const c=new Map,d=r||av(e,t),h=qd(e,d);c.set(e,{artifactName:i,content:t,type:d,path:h}),K.setProgress(0,c.size);const p=Wn(c);if(!p.valid)throw new Error(`Validation failed: ${p.errors.join(` -`)}`);const f=await Ea(u,n),g=f.yaml,m=await ba(u,c,f.remoteFiles,`Provision ${i} custom class`,g),_=await wa(m.syncFileMap,m.remoteFiles),b=new Map(m.syncFileMap);b.set("pubspec.yaml",{content:g,type:"D",path:"pubspec.yaml"}),be.set("package");const E=await Sa(b),I={project_id:a,zipped_custom_code:E,uid:`web_${Date.now()}`,branch_name:u.branchName,serialized_yaml:g,file_map:_.fileMapContents,functions_map:_.functionsMapContents};K.setState(V.PUSHING),K.setProgress(1,c.size),Wn(u),be.set("push");const F=await u.pushCode(I),P=await _a(F);if(P.success)K.setSuccess({fileCount:c.size,projectId:a,warnings:P.errorMap&&P.errorMap.size>0?Array.from(P.errorMap.entries()):[]});else{const B=P.errorMessage||ya(P.responseCode);throw new Error(B)}return{success:!0,message:`Successfully committed ${e} to FlutterFlow project ${a}`,addedDependencies:f.added,unverified:m.unverified,warnings:P.errorMap?Array.from(P.errorMap.entries()):[]}}catch(o){return console.error("Commit failed:",o),K.setError(o),{success:!1,error:o.message,state:K.currentState}}}async function Sa(t){const e=new JSZip;for(const[s,r]of t.entries())e.file(s,r.content);return e.generateAsync({type:"base64",compression:"DEFLATE",compressionOptions:{level:6}})}async function mv(t,e={}){const{artifactType:s,artifactName:r,fileName:n,pipelineResult:i}=e;console.log(`Starting commit for ${r} (${s})`);try{K.setState(V.PREPARING);const o=Jd(t,{artifactType:s,artifactName:r,fileName:n}),a=hv(o.content);console.log("Detected dependencies:",a),K.setState(V.VALIDATING);const l=await Ee("flutterflow"),u=Xs||await Ee("flutterflow_project_id");if(!l)throw new Error("FlutterFlow API Key not configured. Please add it in API Keys settings.");if(!u)throw new Error("FlutterFlow Project ID not configured. Please add it in API Keys settings.");if(!jn(u))throw new Error("Invalid FlutterFlow Project ID format.");const c=new Map;c.set(o.fileName,{artifactName:r,content:o.content,type:o.codeType,path:Gd(o.fileName,o.codeType),functionName:o.codeType===U.FUNCTION?r:void 0}),K.setProgress(0,c.size);const d=zn(c);if(!d.valid)throw new Error(`File validation failed: +`)}`);const f=await ba(u,n),g=f.yaml,m=await wa(u,c,f.remoteFiles,`Provision ${i} custom class`,g),_=await ya(m.syncFileMap,m.remoteFiles),b=new Map(m.syncFileMap);b.set("pubspec.yaml",{content:g,type:"D",path:"pubspec.yaml"}),be.set("package");const E=await Ea(b),I={project_id:a,zipped_custom_code:E,uid:`web_${Date.now()}`,branch_name:u.branchName,serialized_yaml:g,file_map:_.fileMapContents,functions_map:_.functionsMapContents};K.setState(V.PUSHING),K.setProgress(1,c.size),Hn(u),be.set("push");const F=await u.pushCode(I),P=await va(F);if(P.success)K.setSuccess({fileCount:c.size,projectId:a,warnings:P.errorMap&&P.errorMap.size>0?Array.from(P.errorMap.entries()):[]});else{const B=P.errorMessage||_a(P.responseCode);throw new Error(B)}return{success:!0,message:`Successfully committed ${e} to FlutterFlow project ${a}`,addedDependencies:f.added,unverified:m.unverified,warnings:P.errorMap?Array.from(P.errorMap.entries()):[]}}catch(o){return console.error("Commit failed:",o),K.setError(o),{success:!1,error:o.message,state:K.currentState}}}async function Ea(t){const e=new JSZip;for(const[s,r]of t.entries())e.file(s,r.content);return e.generateAsync({type:"base64",compression:"DEFLATE",compressionOptions:{level:6}})}async function pv(t,e={}){const{artifactType:s,artifactName:r,fileName:n,pipelineResult:i}=e;console.log(`Starting commit for ${r} (${s})`);try{K.setState(V.PREPARING);const o=Gd(t,{artifactType:s,artifactName:r,fileName:n}),a=cv(o.content);console.log("Detected dependencies:",a),K.setState(V.VALIDATING);const l=await Ee("flutterflow"),u=Zs||await Ee("flutterflow_project_id");if(!l)throw new Error("FlutterFlow API Key not configured. Please add it in API Keys settings.");if(!u)throw new Error("FlutterFlow Project ID not configured. Please add it in API Keys settings.");if(!Bn(u))throw new Error("Invalid FlutterFlow Project ID format.");const c=new Map;c.set(o.fileName,{artifactName:r,content:o.content,type:o.codeType,path:qd(o.fileName,o.codeType),functionName:o.codeType===U.FUNCTION?r:void 0}),K.setProgress(0,c.size);const d=Wn(c);if(!d.valid)throw new Error(`File validation failed: ${d.errors.join(` -`)}`);d.warnings.length>0&&console.warn("Validation warnings:",d.warnings),K.setState(V.PUSHING);const h=gr(),p=new mr(l,u,"main",h),f=await Ea(p,a),g=f.yaml,m=await ba(p,c,f.remoteFiles,`Provision ${r} custom class`,g),_=await wa(m.syncFileMap,m.remoteFiles),b=new Map(m.syncFileMap);b.set("pubspec.yaml",{content:g,type:U.DEPENDENCIES,path:"pubspec.yaml"}),be.set("package");const E=await Sa(b),I={project_id:u,zipped_custom_code:E,uid:`web_${Date.now()}`,branch_name:p.branchName,serialized_yaml:g,file_map:_.fileMapContents,functions_map:_.functionsMapContents};K.setProgress(1,c.size),Wn(p),be.set("push");const F=await p.pushCode(I),P=await _a(F);if(P.success){const B={...pv(o,i),projectId:u};return K.setSuccess({...B,fileCount:c.size,warnings:P.errorMap?Array.from(P.errorMap.entries()):[]}),{success:!0,message:`Successfully committed ${o.fileName} to FlutterFlow`,metadata:B,addedDependencies:f.added,unverified:m.unverified,warnings:P.errorMap?Array.from(P.errorMap.entries()):[],elapsedTime:K.getElapsedTime()}}else{const B=P.errorMessage||ya(P.responseCode),S=new Error(B);throw S.errorMap=P.errorMap,S}}catch(o){console.error("Commit execution failed:",o),K.setError(o);let a=new Map;if(o.errorMap)a=o.errorMap;else if(o.message&&o.message.includes("{"))try{const l=o.message.match(/\{[\s\S]*\}/);if(l){const u=JSON.parse(l[0]);a=new Map(Object.entries(u))}}catch(l){console.warn("Failed to parse error map from commit response:",l)}return{success:!1,error:o.message,errorMap:a,state:K.currentState,elapsedTime:K.getElapsedTime()}}}async function vv(t,e={}){const{pipelineResult:s}=e;try{if(K.setState(V.PREPARING),t.errors?.length>0)throw new Error(`Bundle validation failed: +`)}`);d.warnings.length>0&&console.warn("Validation warnings:",d.warnings),K.setState(V.PUSHING);const h=fr(),p=new gr(l,u,"main",h),f=await ba(p,a),g=f.yaml,m=await wa(p,c,f.remoteFiles,`Provision ${r} custom class`,g),_=await ya(m.syncFileMap,m.remoteFiles),b=new Map(m.syncFileMap);b.set("pubspec.yaml",{content:g,type:U.DEPENDENCIES,path:"pubspec.yaml"}),be.set("package");const E=await Ea(b),I={project_id:u,zipped_custom_code:E,uid:`web_${Date.now()}`,branch_name:p.branchName,serialized_yaml:g,file_map:_.fileMapContents,functions_map:_.functionsMapContents};K.setProgress(1,c.size),Hn(p),be.set("push");const F=await p.pushCode(I),P=await va(F);if(P.success){const B={...uv(o,i),projectId:u};return K.setSuccess({...B,fileCount:c.size,warnings:P.errorMap?Array.from(P.errorMap.entries()):[]}),{success:!0,message:`Successfully committed ${o.fileName} to FlutterFlow`,metadata:B,addedDependencies:f.added,unverified:m.unverified,warnings:P.errorMap?Array.from(P.errorMap.entries()):[],elapsedTime:K.getElapsedTime()}}else{const B=P.errorMessage||_a(P.responseCode),S=new Error(B);throw S.errorMap=P.errorMap,S}}catch(o){console.error("Commit execution failed:",o),K.setError(o);let a=new Map;if(o.errorMap)a=o.errorMap;else if(o.message&&o.message.includes("{"))try{const l=o.message.match(/\{[\s\S]*\}/);if(l){const u=JSON.parse(l[0]);a=new Map(Object.entries(u))}}catch(l){console.warn("Failed to parse error map from commit response:",l)}return{success:!1,error:o.message,errorMap:a,state:K.currentState,elapsedTime:K.getElapsedTime()}}}async function fv(t,e={}){const{pipelineResult:s}=e;try{if(K.setState(V.PREPARING),t.errors?.length>0)throw new Error(`Bundle validation failed: ${t.errors.join(` -`)}`);const r=new Map(t.fileEntries.map(I=>[I.fileName,{artifactId:I.artifactId,artifactName:I.artifactName,content:I.content,type:I.type,path:I.path,functionName:I.type===U.FUNCTION?I.artifactName:void 0}]));K.setProgress(0,r.size);const n=zn(r);if(!n.valid)throw new Error(`File validation failed: +`)}`);const r=new Map(t.fileEntries.map(I=>[I.fileName,{artifactId:I.artifactId,artifactName:I.artifactName,content:I.content,type:I.type,path:I.path,functionName:I.type===U.FUNCTION?I.artifactName:void 0}]));K.setProgress(0,r.size);const n=Wn(r);if(!n.valid)throw new Error(`File validation failed: ${n.errors.join(` -`)}`);K.setState(V.VALIDATING);const i=await Ee("flutterflow"),o=Xs||await Ee("flutterflow_project_id");if(!i)throw new Error("FlutterFlow API Key not configured. Please add it in API Keys settings.");if(!o)throw new Error("FlutterFlow Project ID not configured. Please add it in API Keys settings.");if(!jn(o))throw new Error("Invalid FlutterFlow Project ID format.");K.setState(V.PUSHING);const a=gr(),l=new mr(i,o,"main",a),u=await Ea(l,t.dependencies),c=u.yaml,d=await ba(l,r,u.remoteFiles,`Provision ${t.title} custom classes`,c),h=await wa(d.syncFileMap,d.remoteFiles),p=new Map(d.syncFileMap);p.set("pubspec.yaml",{content:c,type:U.DEPENDENCIES,path:"pubspec.yaml"}),be.set("package");const f=await Sa(p),g={project_id:o,zipped_custom_code:f,uid:`web_${Date.now()}`,branch_name:l.branchName,serialized_yaml:c,file_map:h.fileMapContents,functions_map:h.functionsMapContents};K.setProgress(1,r.size),Wn(l),be.set("push");const m=await l.pushCode(g),_=await _a(m);if(_.success){const I={...s,artifactType:"Bundle",artifactName:t.title,fileName:`${t.fileEntries.length} artifacts`,codeSize:t.fileEntries.reduce((F,P)=>F+P.content.length,0),projectId:o};return K.setSuccess({...I,fileCount:r.size,warnings:_.errorMap?Array.from(_.errorMap.entries()):[]}),{success:!0,message:`Successfully committed ${t.fileEntries.length} artifacts to FlutterFlow`,metadata:I,addedDependencies:u.added,unverified:d.unverified,warnings:_.errorMap?Array.from(_.errorMap.entries()):[],elapsedTime:K.getElapsedTime()}}const b=_.errorMessage||ya(_.responseCode),E=new Error(b);throw E.errorMap=_.errorMap,E}catch(r){return console.error("Bundle commit execution failed:",r),K.setError(r),{success:!1,error:r.message,errorMap:r.errorMap||new Map,state:K.currentState,elapsedTime:K.getElapsedTime()}}}async function _v(t,e=[]){const s=ea("architect");try{return await Cn("architect",Nd,Lf(t),s,e)}catch(r){throw r.isModelArmor?r:new Error(`Prompt Architect failed: ${r.message}`)}}async function qn(t,e,s=[]){const r=Of(t),n=ea("generator",y.bundleSpec);try{return await Cn("generator",e,r,n,s)}catch(i){if(i.isModelArmor)throw i;if(e!==Pi){console.warn(`Code Generator failed with ${e}, retrying with fallback model:`,i.message);try{return await Cn("generator",Pi,r,n,s)}catch(o){throw o.isModelArmor?o:new Error(`Code Generator failed: primary (${e}): ${i.message} | fallback (${Pi}): ${o.message}`)}}throw new Error(`Code Generator failed: ${i.message}`)}}async function Vn(t,e=null){const s={...ea("review",y.artifactBundle||y.bundleSpec),architect_output:e};try{return await Cn("review",Md,Df(t),s)}catch(r){throw r.isModelArmor?r:new Error(`Code Review failed: ${r.message}`)}}function xa(t,e){return t.isModelArmor?`${t.userTitle}: ${t.userMessage}`:`${e}: ${t.message}`}function Po(t,e){const s=document.getElementById(`step${t}-item`),r=document.getElementById(`step${t}-status`);!s||!r||(s.classList.remove("active","completed","error"),r.classList.remove("running","completed","error"),e==="active"?(s.classList.add("active"),r.classList.add("running"),r.innerHTML=` +`)}`);K.setState(V.VALIDATING);const i=await Ee("flutterflow"),o=Zs||await Ee("flutterflow_project_id");if(!i)throw new Error("FlutterFlow API Key not configured. Please add it in API Keys settings.");if(!o)throw new Error("FlutterFlow Project ID not configured. Please add it in API Keys settings.");if(!Bn(o))throw new Error("Invalid FlutterFlow Project ID format.");K.setState(V.PUSHING);const a=fr(),l=new gr(i,o,"main",a),u=await ba(l,t.dependencies),c=u.yaml,d=await wa(l,r,u.remoteFiles,`Provision ${t.title} custom classes`,c),h=await ya(d.syncFileMap,d.remoteFiles),p=new Map(d.syncFileMap);p.set("pubspec.yaml",{content:c,type:U.DEPENDENCIES,path:"pubspec.yaml"}),be.set("package");const f=await Ea(p),g={project_id:o,zipped_custom_code:f,uid:`web_${Date.now()}`,branch_name:l.branchName,serialized_yaml:c,file_map:h.fileMapContents,functions_map:h.functionsMapContents};K.setProgress(1,r.size),Hn(l),be.set("push");const m=await l.pushCode(g),_=await va(m);if(_.success){const I={...s,artifactType:"Bundle",artifactName:t.title,fileName:`${t.fileEntries.length} artifacts`,codeSize:t.fileEntries.reduce((F,P)=>F+P.content.length,0),projectId:o};return K.setSuccess({...I,fileCount:r.size,warnings:_.errorMap?Array.from(_.errorMap.entries()):[]}),{success:!0,message:`Successfully committed ${t.fileEntries.length} artifacts to FlutterFlow`,metadata:I,addedDependencies:u.added,unverified:d.unverified,warnings:_.errorMap?Array.from(_.errorMap.entries()):[],elapsedTime:K.getElapsedTime()}}const b=_.errorMessage||_a(_.responseCode),E=new Error(b);throw E.errorMap=_.errorMap,E}catch(r){return console.error("Bundle commit execution failed:",r),K.setError(r),{success:!1,error:r.message,errorMap:r.errorMap||new Map,state:K.currentState,elapsedTime:K.getElapsedTime()}}}async function gv(t,e=[]){const s=Qo("architect");try{return await In("architect",Rd,Nf(t),s,e)}catch(r){throw r.isModelArmor?r:new Error(`Prompt Architect failed: ${r.message}`)}}async function zn(t,e,s=[]){const r=Mf(t),n=Qo("generator",y.bundleSpec);try{return await In("generator",e,r,n,s)}catch(i){if(i.isModelArmor)throw i;if(e!==Fi){console.warn(`Code Generator failed with ${e}, retrying with fallback model:`,i.message);try{return await In("generator",Fi,r,n,s)}catch(o){throw o.isModelArmor?o:new Error(`Code Generator failed: primary (${e}): ${i.message} | fallback (${Fi}): ${o.message}`)}}throw new Error(`Code Generator failed: ${i.message}`)}}async function qn(t,e=null){const s={...Qo("review",y.artifactBundle||y.bundleSpec),architect_output:e};try{return await In("review",Td,Lf(t),s)}catch(r){throw r.isModelArmor?r:new Error(`Code Review failed: ${r.message}`)}}function Sa(t,e){return t.isModelArmor?`${t.userTitle}: ${t.userMessage}`:`${e}: ${t.message}`}function Fo(t,e){const s=document.getElementById(`step${t}-item`),r=document.getElementById(`step${t}-status`);!s||!r||(s.classList.remove("active","completed","error"),r.classList.remove("running","completed","error"),e==="active"?(s.classList.add("active"),r.classList.add("running"),r.innerHTML=` `):e==="completed"?(s.classList.add("completed"),r.classList.add("completed"),r.innerHTML=` @@ -125,19 +125,19 @@ ${n.errors.join(` `):r.innerHTML=` - `)}function ve(t,e){const s=document.getElementById(`step${t}-loading`),r=document.getElementById(`step${t}-result`);e?(s.classList.remove("hidden"),r.classList.add("hidden"),Po(t,"active")):(s.classList.add("hidden"),r.classList.remove("hidden"),Po(t,"completed"))}function yv(t){const e=document.getElementById(`${t}-content`),s=document.getElementById(`${t}-chevron`);e.classList.contains("open")?(e.classList.remove("open"),s&&(s.style.transform="rotate(0deg)")):(e.classList.add("open"),s&&(s.style.transform="rotate(180deg)"))}function wv(t){ze(parseInt(t.replace("step","")))}function ze(t){for(let o=1;o<=3;o++){const a=document.getElementById(`step${o}-item`);a&&a.classList.remove("active")}const e=document.getElementById(`step${t}-item`);e&&e.classList.add("active"),Zt();const s=document.getElementById("ready-state");s&&s.classList.add("hidden");for(let o=1;o<=3;o++){const a=document.getElementById(`step${o}-content`);a&&a.classList.add("hidden")}const r=document.getElementById(`step${t}-content`);r&&r.classList.remove("hidden");const n=document.getElementById("stage-title"),i={1:"Prompt Architect",2:"Code Generator",3:"Code Review"};n&&(n.textContent=i[t]||"Active Workflow Stage")}function bv(t){const e=document.getElementById(t);if(!e)return;const s=e.dataset.raw||e.textContent;navigator.clipboard.writeText(s).then(()=>{zt("Code Copied",{elementId:t});const n=e.closest(".code-container")?.querySelector(".copy-btn");n&&(n.classList.add("copied"),n.innerHTML=' Copied!',setTimeout(()=>{n.classList.remove("copied"),n.innerHTML=' Copy'},2e3))}).catch(r=>{console.warn("Failed to copy to clipboard:",r)})}function Ao(t){const e=Ro(t);console.log(`Step 1 (Prompt Architect): ${qt(Nd)}`),console.log(e!==t?`Step 2 (Code Generator): ${qt(t)} → ${qt(e)} (Free Tier fallback)`:`Step 2 (Code Generator): ${qt(t)}`),console.log(`Step 3 (Code Review): ${qt(Md)}`)}async function Ev(){if(console.log("runRefinement called"),y.isRunning)return;const t=document.getElementById("code-generator-model").value;y.isRunning=!0,ka("standardRegenerate",y.step2Result,y.step1Result);const e=document.querySelectorAll(".btn-refine-action");e.forEach(s=>{s.disabled=!0,s.innerHTML=` + `)}function ve(t,e){const s=document.getElementById(`step${t}-loading`),r=document.getElementById(`step${t}-result`);e?(s.classList.remove("hidden"),r.classList.add("hidden"),Fo(t,"active")):(s.classList.add("hidden"),r.classList.remove("hidden"),Fo(t,"completed"))}function mv(t){const e=document.getElementById(`${t}-content`),s=document.getElementById(`${t}-chevron`);e.classList.contains("open")?(e.classList.remove("open"),s&&(s.style.transform="rotate(0deg)")):(e.classList.add("open"),s&&(s.style.transform="rotate(180deg)"))}function vv(t){ze(parseInt(t.replace("step","")))}function ze(t){for(let o=1;o<=3;o++){const a=document.getElementById(`step${o}-item`);a&&a.classList.remove("active")}const e=document.getElementById(`step${t}-item`);e&&e.classList.add("active"),Yt();const s=document.getElementById("ready-state");s&&s.classList.add("hidden");for(let o=1;o<=3;o++){const a=document.getElementById(`step${o}-content`);a&&a.classList.add("hidden")}const r=document.getElementById(`step${t}-content`);r&&r.classList.remove("hidden");const n=document.getElementById("stage-title"),i={1:"Prompt Architect",2:"Code Generator",3:"Code Review"};n&&(n.textContent=i[t]||"Active Workflow Stage")}function _v(t){const e=document.getElementById(t);if(!e)return;const s=e.dataset.raw||e.textContent;navigator.clipboard.writeText(s).then(()=>{const n=e.closest(".code-container")?.querySelector(".copy-btn");n&&(n.classList.add("copied"),n.innerHTML=' Copied!',setTimeout(()=>{n.classList.remove("copied"),n.innerHTML=' Copy'},2e3))}).catch(r=>{console.warn("Failed to copy to clipboard:",r)})}function Po(t){const e=$o(t);console.log(`Step 1 (Prompt Architect): ${zt(Rd)}`),console.log(e!==t?`Step 2 (Code Generator): ${zt(t)} → ${zt(e)} (Free Tier fallback)`:`Step 2 (Code Generator): ${zt(t)}`),console.log(`Step 3 (Code Review): ${zt(Td)}`)}async function yv(){if(console.log("runRefinement called"),y.isRunning)return;const t=document.getElementById("code-generator-model").value;y.isRunning=!0,xa("standardRegenerate",y.step2Result,y.step1Result);const e=document.querySelectorAll(".btn-refine-action");e.forEach(s=>{s.disabled=!0,s.innerHTML=` - Refining...`});try{const s=ma(),r=Bf({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,artifactId:s.id,userFeedback:"Fix the issues listed in the audit report."});Jn(),nt(2),ze(2),ve(2,!0),y.step2Result=await qn(r,t),Un();const n=document.getElementById("step2-output"),i=bs(y.step2Result);n.textContent=i,n.dataset.raw=i,ve(2,!1),ze(3),nt(3),ve(3,!0),y.step3Result=await Vn(y.step2Result,y.step1Result),Hn();const o=document.getElementById("step3-output");o.textContent=y.step3Result,ve(3,!1),$t();const a=Dn(y.step3Result);Yn(i,a)}catch(s){console.error("Refinement failed:",s),$t(),ue(xa(s,"Refinement failed"),"error")}finally{y.isRunning=!1,e.forEach(s=>{s.disabled=!1,s.textContent="Refine & Regenerate"}),Xt()}}async function ka(t,e,s){const r=`${Je}/connectFeedback`,n={type:t,code:e,input:s};try{const i=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!i.ok){const a=await i.text();return console.error(`callEndpoint failed: ${i.status} ${i.statusText}`,a),{success:!1,status:i.status,error:a}}const o=await i.json();return console.log("Telemetry success:",o),o}catch(i){return console.error("callEndpoint failed:",i),{success:!1,error:i.message}}}function Sv(){const t=document.getElementById("ff-error-paste-input");t&&(t.value="")}async function xv(){const t=document.getElementById("ff-error-paste-input"),e=t?.value?.trim();if(!e){t?.focus(),t?.classList.add("ring-2","ring-red-400","border-red-300"),setTimeout(()=>t?.classList.remove("ring-2","ring-red-400","border-red-300"),2e3);return}if(!y.step2Result){ue("No generated code found. Please run the full pipeline first.","warning");return}if(y.isRunning)return;const s=document.getElementById("code-generator-model").value;y.isRunning=!0,ka("flutterflowError",y.step2Result,e);const r=document.getElementById("btn-fix-from-errors");r&&(r.disabled=!0,r.innerHTML=` + Refining...`});try{const s=ga(),r=Of({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,artifactId:s.id,userFeedback:"Fix the issues listed in the audit report."});Kn(),nt(2),ze(2),ve(2,!0),y.step2Result=await zn(r,t),jn();const n=document.getElementById("step2-output"),i=ws(y.step2Result);n.textContent=i,n.dataset.raw=i,ve(2,!1),ze(3),nt(3),ve(3,!0),y.step3Result=await qn(y.step2Result,y.step1Result),Un();const o=document.getElementById("step3-output");o.textContent=y.step3Result,ve(3,!1),$t();const a=On(y.step3Result);Jn(i,a)}catch(s){console.error("Refinement failed:",s),$t(),ue(Sa(s,"Refinement failed"),"error")}finally{y.isRunning=!1,e.forEach(s=>{s.disabled=!1,s.textContent="Refine & Regenerate"}),Zt()}}async function xa(t,e,s){const r=`${Je}/connectFeedback`,n={type:t,code:e,input:s};try{const i=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!i.ok){const a=await i.text();return console.error(`callEndpoint failed: ${i.status} ${i.statusText}`,a),{success:!1,status:i.status,error:a}}const o=await i.json();return console.log("Telemetry success:",o),o}catch(i){return console.error("callEndpoint failed:",i),{success:!1,error:i.message}}}function wv(){const t=document.getElementById("ff-error-paste-input");t&&(t.value="")}async function bv(){const t=document.getElementById("ff-error-paste-input"),e=t?.value?.trim();if(!e){t?.focus(),t?.classList.add("ring-2","ring-red-400","border-red-300"),setTimeout(()=>t?.classList.remove("ring-2","ring-red-400","border-red-300"),2e3);return}if(!y.step2Result){ue("No generated code found. Please run the full pipeline first.","warning");return}if(y.isRunning)return;const s=document.getElementById("code-generator-model").value;y.isRunning=!0,xa("flutterflowError",y.step2Result,e);const r=document.getElementById("btn-fix-from-errors");r&&(r.disabled=!0,r.innerHTML=` - Fixing…`);try{const n=md({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,userFeedback:e});lh(),Jn(),nt(2),ze(2),ve(2,!0),y.step2Result=await qn(n,s),Un();const i=document.getElementById("step2-output"),o=bs(y.step2Result);i.textContent=o,i.dataset.raw=o,ve(2,!1),ze(3),nt(3),ve(3,!0),y.step3Result=await Vn(y.step2Result,y.step1Result),Hn();const a=document.getElementById("step3-output");a.textContent=y.step3Result,ve(3,!1),$t();const l=Dn(y.step3Result);Yn(o,l),t&&(t.value="")}catch(n){console.error("Fix from errors failed:",n),$t(),ue(xa(n,"Failed to fix errors"),"error")}finally{y.isRunning=!1,r&&(r.disabled=!1,r.textContent="Fix Errors & Regenerate"),Xt()}}async function $o(){if(console.log("runThinkingPipeline called"),y.isRunning)return;localStorage.setItem("hasSeenWalkthrough","true");const t=document.getElementById("pipeline-input").value,e=document.getElementById("code-generator-model").value;if(!t.trim()){ue("Please describe your FlutterFlow widget first.","warning");return}if(!await zv())return;await Dv();const s=Ro(e);zt("Pipeline Started",{selectedModel:e,effectiveModel:s,inputLength:t.length});const r=document.getElementById("btn-run-pipeline");y.isRunning=!0,ov(),r.disabled=!0,r.innerHTML=` + Fixing…`);try{const n=fd({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,userFeedback:e});oh(),Kn(),nt(2),ze(2),ve(2,!0),y.step2Result=await zn(n,s),jn();const i=document.getElementById("step2-output"),o=ws(y.step2Result);i.textContent=o,i.dataset.raw=o,ve(2,!1),ze(3),nt(3),ve(3,!0),y.step3Result=await qn(y.step2Result,y.step1Result),Un();const a=document.getElementById("step3-output");a.textContent=y.step3Result,ve(3,!1),$t();const l=On(y.step3Result);Jn(o,l),t&&(t.value="")}catch(n){console.error("Fix from errors failed:",n),$t(),ue(Sa(n,"Failed to fix errors"),"error")}finally{y.isRunning=!1,r&&(r.disabled=!1,r.textContent="Fix Errors & Regenerate"),Zt()}}async function Ao(){if(console.log("runThinkingPipeline called"),y.isRunning)return;localStorage.setItem("hasSeenWalkthrough","true");const t=document.getElementById("pipeline-input").value,e=document.getElementById("code-generator-model").value;if(!t.trim()){ue("Please describe your FlutterFlow widget first.","warning");return}if(!await Uv())return;await Mv();const s=$o(e);t.length;const r=document.getElementById("btn-run-pipeline");y.isRunning=!0,rv(),r.disabled=!0,r.innerHTML=` - Running...`,Ao(s);try{Zt();const n=document.getElementById("ready-state");n&&n.classList.add("hidden");const i=document.getElementById("paywall-exhausted");i&&i.classList.add("hidden"),Jn(),ze(1),nt(1),ve(1,!0);const o=Pt.filter(p=>p.url).map(p=>({url:p.url}));y.step1Result=await _v(t,o),av(),zt("Prompt Architect Completed");const a=document.getElementById("step1-output"),l=bs(y.step1Result);a.textContent=l,a.dataset.raw=l,ve(1,!1),ze(2),nt(2),ve(2,!0),y.step2Result=await qn(y.step1Result,s,o),Un(),zt("Code Generator Completed");const u=document.getElementById("step2-output"),c=bs(y.step2Result);u.textContent=c,u.dataset.raw=c,ve(2,!1),ze(3),nt(3),ve(3,!0),y.step3Result=await Vn(y.step2Result,y.step1Result),Hn(),zt("Code Review Completed");const d=document.getElementById("step3-output");d.textContent=y.step3Result,ve(3,!1),$t();const h=Dn(y.step3Result);Yn(c,h)}catch(n){if(console.error("Pipeline failed:",n),$t(),n.isUsageLimit){const{count:c}=Gn();$a(c,Aa(),{openModal:!0});return}zt("Pipeline Failed",{error:n.message,effectiveModel:Ro(document.getElementById("code-generator-model").value)});const o=vm(n,{architect:1,generator:2,review:3});ze(o);const a=document.getElementById(`step${o}-result`),l=document.getElementById(`step${o}-loading`),u=document.getElementById(`step${o}-output`);if(l&&l.classList.add("hidden"),a&&a.classList.remove("hidden"),u)if(n.isModelArmor)u.innerHTML=``}Fo(o,"error")}finally{y.isRunning=!1,r.disabled=!1,r.innerHTML=` - Run Pipeline`,Xt()}}function kv(){const t=document.getElementById("code-generator-model").value,e=[cr,"anthropic/claude-opus-5","openai/gpt-5.6-sol"].filter(r=>r!==t),s=prompt(`Retry with different model? + Run Pipeline`,Zt()}}function Ev(){const t=document.getElementById("code-generator-model").value,e=[lr,"anthropic/claude-opus-5","openai/gpt-5.6-sol"].filter(r=>r!==t),s=prompt(`Retry with different model? Current: ${t} @@ -156,14 +156,14 @@ Options: 1. ${e[0]} 2. ${e[1]} -Enter 1 or 2:`);s==="1"?(document.getElementById("code-generator-model").value=e[0],$o()):s==="2"&&(document.getElementById("code-generator-model").value=e[1],$o())}async function Iv(){const t=va();if(!t){ue("No code to commit. Please run the pipeline first.","warning");return}const e=await Ee("flutterflow"),s=await Ee("flutterflow_project_id");if(!e||!s){ue("FlutterFlow credentials not configured. Add your API Key and Project ID in settings.","warning"),pa();return}if(y.artifactBundle?.artifacts?.length>1){await Cv();return}const{artifactType:r,artifactName:n,fileName:i}=zd(),o=Jd(t,{artifactType:r,artifactName:n,fileName:i}),a=dv(o);if(!a.canProceed){ue(`Pre-commit checks failed: ${a.issues.join("; ")}`,"error");return}th(o,a,null,null)}async function Cv(){const t=await Ee("flutterflow"),e=await Ee("flutterflow_project_id");if(!t||!e){ue("FlutterFlow credentials not configured. Add your API Key and Project ID in settings.","warning"),pa();return}const s=Eg(y.artifactBundle);if(s.errors.length>0){ue(`Bundle validation failed: ${s.errors.join("; ")}`,"error");return}const r=new Map(s.fileEntries.map(a=>[a.fileName,{content:a.content,type:a.type,path:a.path}])),n=zn(r),i={canProceed:n.valid&&s.errors.length===0,issues:[...s.errors,...n.errors],warnings:[...s.warnings,...n.warnings]};if(!i.canProceed){ue(`Bundle validation failed: ${i.issues.join("; ")}`,"error");return}const o={content:s.fileEntries.map(a=>`// ${a.fileName} +Enter 1 or 2:`);s==="1"?(document.getElementById("code-generator-model").value=e[0],Ao()):s==="2"&&(document.getElementById("code-generator-model").value=e[1],Ao())}async function Sv(){const t=ma();if(!t){ue("No code to commit. Please run the pipeline first.","warning");return}const e=await Ee("flutterflow"),s=await Ee("flutterflow_project_id");if(!e||!s){ue("FlutterFlow credentials not configured. Add your API Key and Project ID in settings.","warning"),ha();return}if(y.artifactBundle?.artifacts?.length>1){await xv();return}const{artifactType:r,artifactName:n,fileName:i}=Hd(),o=Gd(t,{artifactType:r,artifactName:n,fileName:i}),a=lv(o);if(!a.canProceed){ue(`Pre-commit checks failed: ${a.issues.join("; ")}`,"error");return}Qd(o,a,null,null)}async function xv(){const t=await Ee("flutterflow"),e=await Ee("flutterflow_project_id");if(!t||!e){ue("FlutterFlow credentials not configured. Add your API Key and Project ID in settings.","warning"),ha();return}const s=wg(y.artifactBundle);if(s.errors.length>0){ue(`Bundle validation failed: ${s.errors.join("; ")}`,"error");return}const r=new Map(s.fileEntries.map(a=>[a.fileName,{content:a.content,type:a.type,path:a.path}])),n=Wn(r),i={canProceed:n.valid&&s.errors.length===0,issues:[...s.errors,...n.errors],warnings:[...s.warnings,...n.warnings]};if(!i.canProceed){ue(`Bundle validation failed: ${i.issues.join("; ")}`,"error");return}const o={content:s.fileEntries.map(a=>`// ${a.fileName} ${a.content}`).join(` -`),fileName:`${s.fileEntries.length} files`,codeType:"bundle",artifactType:"Bundle",artifactName:s.title};th(o,i,s.dependencies,s)}function Fv(t){let e=t.errorMap||new Map;!(e instanceof Map)&&typeof e=="object"&&(e=new Map(Object.entries(e)));let s=`
    +`),fileName:`${s.fileEntries.length} files`,codeType:"bundle",artifactType:"Bundle",artifactName:s.title};Qd(o,i,s.dependencies,s)}function kv(t){let e=t.errorMap||new Map;!(e instanceof Map)&&typeof e=="object"&&(e=new Map(Object.entries(e)));let s=`

    FlutterFlow Commit Failed

    ${j(t.error)}

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

    Errors:

    -
      `;for(const[n,i]of e.entries()){const o=Sd(i);s+=`
    • +
        `;for(const[n,i]of e.entries()){const o=bd(i);s+=`
      • ${j(n)}: ${j(o)}
      • `}s+="
    "}s+="
    ",s+=`
    -
    `;const r=document.getElementById("step3-output");r&&(r.innerHTML=s,document.getElementById("btn-regenerate-from-error")?.addEventListener("click",()=>{Pv(t.error,e)}))}async function Pv(t,e){if(y.isRunning)return;const s=document.getElementById("code-generator-model").value;y.isRunning=!0;const r=document.getElementById("btn-regenerate-from-error");r&&(r.disabled=!0,r.innerHTML=` +
    `;const r=document.getElementById("step3-output");r&&(r.innerHTML=s,document.getElementById("btn-regenerate-from-error")?.addEventListener("click",()=>{Iv(t.error,e)}))}async function Iv(t,e){if(y.isRunning)return;const s=document.getElementById("code-generator-model").value;y.isRunning=!0;const r=document.getElementById("btn-regenerate-from-error");r&&(r.disabled=!0,r.innerHTML=` Fixing...`);try{let n=`The previous code had the following errors when committing to FlutterFlow: -`;if(e&&e.size>0)for(const[c,d]of e.entries()){const h=Sd(d);n+=`File: ${c} +`;if(e&&e.size>0)for(const[c,d]of e.entries()){const h=bd(d);n+=`File: ${c} Error: ${h} `}else n+=`${t} -`;const i=md({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,userFeedback:n});Jn(),nt(2),ze(2),ve(2,!0),y.step2Result=await qn(i,s),Un();const o=document.getElementById("step2-output"),a=bs(y.step2Result);o.textContent=a,o.dataset.raw=a,ve(2,!1),ze(3),nt(3),ve(3,!0),y.step3Result=await Vn(y.step2Result,y.step1Result),Hn();const l=document.getElementById("step3-output");l.textContent=y.step3Result,ve(3,!1),$t();const u=Dn(y.step3Result);Yn(a,u)}catch(n){console.error("Regeneration failed:",n),$t(),ue(xa(n,"Regeneration failed"),"error")}finally{y.isRunning=!1,r&&(r.disabled=!1,r.textContent="Fix Errors & Regenerate"),Xt()}}async function Av(){const t=document.getElementById("ff-status-dot"),e=document.getElementById("ff-status-text");if(!t||!e)return;const s=await Ee("flutterflow"),r=await Ee("flutterflow_project_id");s&&r?(t.className="w-2 h-2 rounded-full bg-green-500",e.textContent="FlutterFlow credentials configured",e.className="text-green-600"):s||r?(t.className="w-2 h-2 rounded-full bg-yellow-500",e.textContent="FlutterFlow credentials incomplete",e.className="text-yellow-600"):(t.className="w-2 h-2 rounded-full bg-red-500",e.textContent="FlutterFlow credentials not configured",e.className="text-red-600")}async function $v(t){try{const e=await fetch(`${Je}/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 Rv(t){try{const s=await(await fetch(`${Je}/auth/verify-magic-link`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:t})})).json();if(s.error||!s.email||!s.sessionToken)throw new Error(s.error||"Invalid or expired link");return s}catch(e){throw console.error("verifyMagicLink failed:",{message:e.message,stack:e.stack}),e}}async function Tv(t){try{const e=await fetch(`${Je}/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:`${Je}/auth/refresh-session`,status:e.status}),null;const s=await e.json();return s.error||!s.email||!s.sessionToken?(console.warn("refreshSession: validation failed",{error:s.error,hasEmail:!!s.email,hasToken:!!s.sessionToken}),null):s}catch(e){return console.error("refreshSession: fetch failed",{url:`${Je}/auth/refresh-session`,message:e.message,stack:e.stack}),null}}function Ec(t,e){const s=Yd(),r=(G.email||s.email)!==t;G.email=t,G.sessionToken=e,G.isVerified=!0,fe=Es({isLoading:!0}),localStorage.setItem(yn,JSON.stringify({email:t,sessionToken:e})),r&&Ra()}function Ia(){G.email=null,G.sessionToken=null,G.isVerified=!1,fe=Es({isResolved:!0}),localStorage.removeItem(yn),localStorage.removeItem(bn)}function Yd(){try{const t=localStorage.getItem(yn);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(yn),{email:null,sessionToken:null}}}async function Nv(){const e=new URLSearchParams(window.location.search).get("token");if(e){window.history.replaceState({},"",window.location.pathname);try{const{email:s,sessionToken:r}=await Rv(e);Ec(s,r)}catch(s){ue(s.message||"Sign-in link invalid or expired.","error")}}else{const{email:s,sessionToken:r}=Yd();if(s&&r){const n=await Tv(r);n?Ec(n.email,n.sessionToken):Ia()}}Fa()}function Ca(){const t=document.getElementById("signin-modal");t&&t.classList.add("open")}function Mv(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("signin-modal");e&&e.classList.remove("open")}async function Lv(){const t=document.getElementById("signin-email-input"),e=document.getElementById("signin-submit-btn"),s=document.getElementById("signin-message"),r=t?.value?.trim();if(!r||!/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/.test(r)||r.length>254){s&&(s.textContent="Please enter a valid email address.");return}e&&(e.disabled=!0,e.textContent="Sending…"),s&&(s.textContent="");try{await $v(r),t&&(t.value=""),s&&(s.textContent=`Check your email — we sent a link to ${r}`),e&&(e.textContent="Sent!")}catch(i){console.error("handleMagicLinkRequest: sendMagicLink failed",{email:r,err:i}),s&&(s.textContent="Something went wrong. Please try again."),e&&(e.disabled=!1,e.textContent="Send Link")}}function Ov(){Ia(),Ra(),Fa(),Kn()}function Fa(){const t=G.isVerified&&!!G.email,e=document.getElementById("auth-signedout"),s=document.getElementById("auth-signedin"),r=document.getElementById("auth-guest-usage");e&&e.classList.toggle("hidden",t),s&&s.classList.toggle("hidden",!t),r&&r.classList.toggle("hidden",t);const n=document.getElementById("auth-user-email");n&&(n.textContent=G.email||""),qr(),Kn()}async function Zd(){try{if(typeof FingerprintJS>"u"){console.warn("resolveIdentity: FingerprintJS not loaded, skipping");return}const e=await(await FingerprintJS.load()).get(),s=e.visitorId,r=await fetch(Cm,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({fingerprint:e.visitorId,cookie_id:s})});if(!r.ok)throw new Error(`Identity check HTTP ${r.status}`);const n=await r.json();if(Ge.userId=n.user_id,Ge.token=n.identity_token||null,Ge.status=n.status,Ge.resolved=!0,sessionStorage.setItem(km,n.user_id),Ge.token&&sessionStorage.setItem(Im,Ge.token),n.usage_count!==void 0){const i=At(),a=(n.usage_month||i)===i?n.usage_count:0;localStorage.setItem(Kt,JSON.stringify({count:a,month:i})),Qs()}console.log(`Identity resolved: ${n.status} (${n.user_id.slice(0,8)}...) usage: ${n.usage_count??"n/a"}`)}catch(t){console.error("resolveIdentity failed:",t)}}let Ai=null;function Dv(t=5e3){return Ge.resolved?Promise.resolve():(Ai||(Ai=Zd().catch(e=>{console.warn("ensureIdentityReady: identity resolution failed",e)})),Promise.race([Ai,new Promise(e=>setTimeout(e,t))]))}function Xd(){const t=At();try{const e=localStorage.getItem(Kt);return e?JSON.parse(e):{count:0,month:t}}catch(e){return console.warn("getUsageData: failed to parse usage storage",{key:Kt,month:t,err:e}),localStorage.removeItem(Kt),{count:0,month:t}}}function At(){const t=new Date;return`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,"0")}`}function Gn(){const t=Xd();return t.month!==At()?{count:0,month:At()}:t}function Bv(){const e={count:Gn().count+1,month:At()};return localStorage.setItem(Kt,JSON.stringify(e)),e}function Pa(){return!!fe.isLoading}function Yt(){return!!fe.isResolved}function jv(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(wn,e)?e:null}function Uv(t){return t&&Object.entries($d).find(([,e])=>e===t)?.[0]||null}function Rr(...t){return t.find(e=>e!=null&&e!=="")}function Hv(...t){return t.find(e=>e&&typeof e=="object")||{}}function Wv(t){const e=t.data&&typeof t.data=="object"?t.data:t,s=Hv(e.subscription,e.stripeSubscription,e.currentSubscription,e.customer?.subscriptions?.data?.[0],e.subscriptions?.data?.[0],e.subscriptions?.[0]),r=e.metadata||s.metadata||e.customer?.metadata||{},n=Rr(e.priceId,e.price_id,e.stripePriceId,e.stripe_price_id,s.priceId,s.price_id,s.plan?.id,s.price?.id,s.items?.data?.[0]?.price?.id,s.items?.[0]?.price?.id,s.lines?.data?.[0]?.price?.id),i=Rr(e.status,e.subscriptionStatus,e.subscription_status,s.status,"none"),o=jv(Rr(e.tier,e.plan,e.planId,e.plan_id,e.subscriptionTier,e.subscription_tier,e.product,e.productName,s.tier,s.plan,r.tier,r.plan)),a=Fm.has(String(i).toLowerCase()),l=e.active===!0||e.isSubscribed===!0||e.subscribed===!0||e.hasSubscription===!0,u=o||Uv(n)||(a||l?"professional":"free");return Es({tier:u,status:i,periodEnd:Rr(e.periodEnd,e.currentPeriodEnd,e.current_period_end,s.current_period_end,s.periodEnd,null),isResolved:!0})}function Aa(){return wn[fe.tier]??wn.free}async function zv(){if(G.isVerified&&(!Yt()||Pa())&&(await Qd({force:!0}),Kn()),G.isVerified&&!Yt())return ue("Could not verify your subscription. Please refresh or try Manage billing.","error"),!1;const{count:t}=Gn(),e=Aa();if(t>=e)return $a(t,e,{openModal:!0}),!1;const s=Math.floor(e*.8);if(t>=s){const r=e-t;ue(`${r} run${r===1?"":"s"} remaining this month.`,"warning")}return!0}function $i(){const t=document.getElementById("paywall-exhausted");t&&t.classList.add("hidden")}function $a(t,e,s={}){const r=document.getElementById("walkthrough-modal");r&&r.classList.remove("open");const n=document.getElementById("ready-state");n&&n.classList.add("hidden");const i=document.getElementById("preview-frame-container");i&&(i.style.display="none");const o=document.getElementById("main-stage-container");o&&o.classList.add("visible");const a=document.getElementById("results-view");a&&a.classList.remove("visible"),document.body.classList.remove("results-fullscreen","results-with-sidebar");const l=document.getElementById("pipeline-progress");l&&l.classList.remove("visible");const u=document.getElementById("paywall-exhausted");if(!u){ue(`You've used all ${e} runs for this month. Upgrade to continue.`,"error"),Fn();return}const c=document.getElementById("paywall-exhausted-text");if(c){const h=fe.tier;h==="free"?c.textContent=`You've used all ${e} free generations this month. Upgrade to Pro for 50 generations/month and access to all AI models.`:c.textContent=`You've used all ${e} generations this month on your ${h} plan. Your limit resets next month.`}const d=document.getElementById("paywall-signin-btn");d&&d.classList.toggle("hidden",G.isVerified),u.classList.remove("hidden"),s.openModal&&Fn()}function Ro(t){return fe.tier==="free"&&Ur.includes(t)?cr:t}function qv(){const t=document.getElementById("code-options-content"),e=document.getElementById("code-generator-model");if(!t||!e)return;const s=fe.tier,n=!(G.isVerified&&!Yt())&&s==="free";Array.from(e.options).forEach(o=>{const a=qt(o.value),l=Ur.includes(o.value);o.textContent=l&&n?`${a} (PRO)`:a,o.disabled=!1}),n&&Ur.includes(e.value)&&(e.value=cr),e.disabled=!1,hc.has(e)||(e.addEventListener("change",()=>{Yt()&&fe.tier==="free"&&Ur.includes(e.value)&&(e.value=cr,Fn()),Ao(e.value),Td()}),hc.add(e));let i=document.getElementById("model-selector-free-notice");n?(i||(i=document.createElement("p"),i.id="model-selector-free-notice",i.className="text-xs text-gray-400 mt-1",t.appendChild(i)),i.innerHTML='Free plan — Gemini only. '):i&&i.remove(),Ao(e.value)}function Qs(){const t=document.getElementById("usage-counter");if(!t)return;if(G.isVerified&&Pa()){t.textContent="Checking plan…",t.className="text-xs text-gray-500",qr(),$i();return}if(G.isVerified&&!Yt()){t.textContent="Plan check failed",t.className="text-xs text-red-600 font-medium",qr(),$i();return}const{count:e}=Gn(),s=Aa();t.textContent=`${e} / ${s} runs this month`;const r=s>0?e/s:0;t.className=r>=1?"text-xs text-red-600 font-medium":r>=.8?"text-xs text-yellow-600 font-medium":"text-xs text-gray-500",qr(),e>=s&&!y.isRunning?$a(e,s):$i()}function qr(){const t=document.getElementById("guest-usage-text");if(!t)return;const e=Xd(),s=e.month===At()?e.count??0:0,r=wn.free;t.textContent=`${s} / ${r} generations used`}async function Qd(t={}){const e=t.force===!0;if(!G.isVerified||!G.sessionToken){fe=Es({isResolved:!0});return}fe={...fe,isLoading:!0,error:null};const s=localStorage.getItem(bn);if(!e&&s)try{const{data:r,email:n,ts:i,version:o}=JSON.parse(s);if(o===pc&&n===G.email&&Date.now()-i<300*1e3){fe={...r,isLoading:!1,isResolved:r.isResolved!==!1};return}}catch(r){console.warn("Failed to parse subscription cache:",r,"| raw value:",s)}try{const n=await(await fetch(`${Je}/stripe/get-subscription`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:G.sessionToken,user_id:Ge.userId})})).json();if(n.error){if(["unauthorized","invalid session","expired session"].some(o=>String(n.error).toLowerCase().includes(o))){Ia(),Fa();return}fe=Es({isResolved:!1,error:n.error});return}fe=Wv(n),localStorage.setItem(bn,JSON.stringify({version:pc,data:fe,email:G.email,ts:Date.now()}))}catch(r){console.error("fetchSubscription failed:",r),fe={...fe,isLoading:!1,isResolved:!1,error:r.message}}}function Ra(){localStorage.removeItem(bn)}async function Vv(t){if(!G.isVerified||!G.sessionToken){eh(),Ca();return}if(!$d[t]){ue("Invalid plan selected.","error");return}const e=document.getElementById(`checkout-btn-${t}`);e&&(e.disabled=!0,e.textContent="Redirecting…");try{const r=await(await fetch(`${Je}/stripe/create-checkout-session-intl`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tierId:t,sessionToken:G.sessionToken,currency:Ld()})})).json();if(r.error||!r.url)throw new Error(r.error||"Failed to create checkout session");const{url:n}=r;window.location.href=n}catch(s){console.error("startCheckout failed:",s),e&&(e.disabled=!1,e.textContent="Subscribe"),ue("Could not start checkout. Please try again.","error")}}async function Gv(){if(!G.isVerified||!G.sessionToken){Ca();return}const t=document.getElementById("manage-billing-btn");t&&(t.disabled=!0,t.textContent="Loading…");try{const s=await(await fetch(`${Je}/stripe/create-portal-session`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:G.sessionToken})})).json();if(s.error||!s.url)throw new Error(s.error||"Failed to open billing portal");const{url:r}=s;window.location.href=r}catch(e){console.error("openCustomerPortal failed:",e),t&&(t.disabled=!1,t.textContent="Manage billing"),ue("Could not open billing portal. Please try again.","error")}}async function Cn(t,e,s,r={},n=[]){const o=new AbortController,a=setTimeout(()=>o.abort(),12e4);try{const l=await fetch(xm,{method:"POST",headers:{"Content-Type":"application/json",...Ge.token?{Authorization:`Bearer ${Ge.token}`}:{}},signal:o.signal,body:JSON.stringify({user_id:Ge.userId,step:t,model:e,prompt:s,images:n,context:r})}),u=await l.text();let c={};try{c=u?JSON.parse(u):{}}catch{c={}}if(l.status===429){c.serverCount!==void 0&&(localStorage.setItem(Kt,JSON.stringify({count:c.serverCount,month:At()})),Qs());const p=new Error(c.message||"Monthly usage limit reached. Upgrade to continue.");throw p.isUsageLimit=!0,p}const d=Vf(c,t);if(d)throw d;if(console.log(`[BuildShip] ${t} response keys:`,Object.keys(c),"content type:",typeof c.content),!l.ok)throw new Error(`${c.message||c.error||"BuildShip pipeline error"} (HTTP ${l.status})`);if(t==="generator")if(c.usage_status==="success"&&Number.isFinite(c.usage_count)){const p=At();(c.usage_month||p)===p&&(localStorage.setItem(Kt,JSON.stringify({count:c.usage_count,month:p})),Qs())}else Bv(),Qs();let h=c.output||c.content;if(!h){const p=u?` (body: ${u.slice(0,120)})`:"";throw new Error(`BuildShip returned no output for step "${t}"${p}`)}return Array.isArray(h)&&(h=h.map(p=>typeof p=="string"?p:p.text||"").join("")),typeof h!="string"&&(h=JSON.stringify(h)),h}catch(l){throw l.name==="AbortError"?new Error(`BuildShip ${t} timed out after ${12e4/1e3}s`):l instanceof TypeError?new Error(`BuildShip unreachable: ${l.message}`):l}finally{clearTimeout(a)}}function Kv(){const e=new URLSearchParams(window.location.search).get("checkout");e==="success"?(window.history.replaceState({},"",window.location.pathname),Ra(),ue("Subscription active! Welcome aboard.","success")):e==="cancel"&&(window.history.replaceState({},"",window.location.pathname),ue("Checkout cancelled.","info"))}function Kn(){const t=G.isVerified&&!!G.email,e=fe.tier,s=t&&Pa(),r=!t||Yt(),n=document.getElementById("subscription-tier-badge");if(n){const a={free:"Free",professional:"Professional",power:"Power Developer"},l={free:"bg-gray-100 text-gray-600",professional:"bg-indigo-100 text-indigo-700",power:"bg-purple-100 text-purple-700",unresolved:"bg-red-50 text-red-600"};n.textContent=s?"Checking…":r?a[e]||"Free":"Plan unavailable",n.className=`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${r?l[e]||l.free:l.unresolved}`}const i=document.getElementById("upgrade-prompt");i&&i.classList.toggle("hidden",!t||s||!r||e!=="free");const o=document.getElementById("manage-billing-btn");o&&o.classList.toggle("hidden",!t||s||r&&e==="free"),Jv(r?e:null),qv(),Td(),Qs()}function Jv(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(([n,{btnId:i,defaultText:o}])=>{const a=document.getElementById(i);a&&(n===t?(a.disabled=!0,a.textContent="Current plan",a.classList.add(...e)):(a.disabled=!1,a.textContent=o,a.classList.remove(...e)))});const r=document.getElementById("free-tier-current");r&&r.classList.toggle("hidden",t!=="free")}function To(){const t=Ld(),e=document.getElementById("pro-price"),s=document.getElementById("power-price"),r=document.getElementById("pro-price-note"),n=document.getElementById("power-price-note");e&&(e.textContent=gc(fc.professional,t)),s&&(s.textContent=gc(fc.power,t));const i="billed monthly";r&&(r.textContent=i),n&&(n.textContent=i)}function Fn(){To();const t=document.getElementById("pricing-modal");t&&t.classList.add("open"),Om().then(()=>To())}function eh(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("pricing-modal");e&&e.classList.remove("open")}function ue(t,e="info"){const s={success:"bg-green-600 text-white",error:"bg-red-600 text-white",warning:"bg-amber-500 text-white",info:"bg-gray-800 text-white"},r=document.createElement("div");r.className=`fixed bottom-6 left-1/2 -translate-x-1/2 px-5 py-3 rounded-lg text-sm font-medium shadow-lg z-50 transition-opacity duration-300 ${s[e]||s.info}`,r.textContent=t,document.body.appendChild(r),setTimeout(()=>{r.style.opacity="0",setTimeout(()=>r.remove(),300)},3500)}document.addEventListener("DOMContentLoaded",async()=>{hljs.configure({tabReplace:" ",classPrefix:"hljs-"}),Yv(),await Nv(),Kv(),await Qd(),Kn(),To(),await lv(),rv();const t=document.getElementById("flutterflow-endpoint-select");if(t){const s=gr();t.value=s}Hd(),Zd();const e=document.getElementById("pipeline-input");e&&(e.addEventListener("input",()=>{Et===2&&e.value.trim().length>0&&(fa(),Bn())}),e.addEventListener("blur",()=>{const s=document.getElementById("walkthrough-modal");Et===2&&s&&s.classList.add("open")}),e.addEventListener("keydown",s=>{if(s.key==="Tab"){const r=document.getElementById("walkthrough-modal");Et===2&&r&&setTimeout(()=>{r.classList.add("open")},100)}})),window.addEventListener("commitStateChange",s=>{const{state:r}=s.detail;r===V.PREPARING||r===V.VALIDATING||r===V.PUSHING?(be.phaseId||rh(),xc(r)):(r===V.SUCCESS||r===V.ERROR)&&(xc(r),setTimeout(Pn,1e3))})});function Yv(){const t=document.getElementById("preview-frame-container");t&&(t.style.display="")}function Zv(){const t=document.getElementById("welcome-video-player");t&&(t.addEventListener("click",Zt),document.addEventListener("keydown",Zt))}function Zt(){const t=document.getElementById("preview-frame-container"),e=document.getElementById("main-stage-container"),s=document.getElementById("ready-state");t&&(t.style.display="none"),e&&e.classList.add("visible"),s&&s.classList.remove("hidden");const r=document.getElementById("welcome-video-player");r&&r.removeEventListener("click",Zt),document.removeEventListener("keydown",Zt),Hd()}let er=null;async function Xv(){const t=document.getElementById("confirm-project-select");if(!t)return;const e=++wc,s=()=>e===wc,r=await Ee("flutterflow"),n=await Ee("flutterflow_project_id");if(s()){if(!r){t.innerHTML='',t.disabled=!0;return}t.disabled=!1,t.innerHTML='';try{const o=await new mr(r,"").listProjects();if(!s())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)}),n&&(t.value=n)}catch(i){if(!s())return;console.error("Failed to load projects for deploy:",i),t.innerHTML=''}}}function Qv(){return document.getElementById("confirm-project-select")?.value?.trim()||null}function th(t,e,s,r=null){er={codeInfo:t,checks:e,deps:s,bundlePlan:r},document.getElementById("confirm-file-name").textContent=t.fileName,document.getElementById("confirm-artifact-type").textContent=t.artifactType,document.getElementById("confirm-file-size").textContent=`${(t.content.length/1024).toFixed(1)} KB`,document.getElementById("confirm-line-count").textContent=r?`${r.fileEntries.length} files`:t.content.split(` -`).length,Xv();const n=document.getElementById("confirm-deps-list"),i=document.getElementById("confirm-deps-section");s&&Object.keys(s).length>0?(n.innerHTML=Object.entries(s).map(([u,c])=>{const d=c?`at least ${bt(c)}`:"version resolved from your project";return`
  • • ${bt(u)}: ${d}
  • `}).join(""),i.classList.remove("hidden")):i.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=>`
  • • ${bt(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&&l.classList.add("open")}function sh(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("commit-confirm-modal");e&&e.classList.remove("open"),er=null}function e_(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("commit-success-modal");e&&e.classList.remove("open");const s=["success-message","success-project-id","success-file-name","success-artifact-type","success-time","success-size"];for(const i of s){const o=document.getElementById(i);o&&(o.textContent="")}const r=document.getElementById("success-warnings-section");r&&r.classList.add("hidden");const n=document.getElementById("success-warnings-list");n&&(n.innerHTML="")}function No(t){const e=(g,m)=>{const _=document.getElementById(g);_&&(_.textContent=m||"")},s=t.metadata?.fileName||"",r=t.metadata?.projectId||"",n=t.metadata?.artifactType||"",i=t.elapsedTime?`${(t.elapsedTime/1e3).toFixed(1)}s`:"",o=t.metadata?.codeSize?`${(t.metadata.codeSize/1024).toFixed(1)} KB`:"";e("success-message",t.message||"Code committed successfully!"),e("success-project-id",r),e("success-file-name",s),e("success-artifact-type",n),e("success-time",i),e("success-size",o);const a=t.addedDependencies||[],l=document.getElementById("success-deps-row");l&&l.classList.toggle("hidden",a.length===0),e("success-deps",a.join(", "));const u=document.getElementById("success-open-ff-link");u&&r&&(u.href=`https://app.flutterflow.io/project/${r}`);const c=document.getElementById("success-warnings-section"),d=document.getElementById("success-warnings-list"),h=t.unverified||[],p=t.warnings||[];(p.length>0||h.length>0)&&c&&d&&(d.innerHTML=[...h.map(g=>`
  • Not verified before deploying: ${j(String(g))}
  • `),...p.map(([g,m])=>`
  • ${j(g)}: ${j(String(m))}
  • `)].join(""),c.classList.remove("hidden"));const f=document.getElementById("commit-success-modal");f&&f.classList.add("open")}function Mo(t){Pn(),Fv(t)}function t_(){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 Sc={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}},s_=[{after:0,text:"Starting a FlutterFlow build runner..."},{after:12,text:"Preparing the FlutterFlow AI workspace..."},{after:35,text:"Uploading your custom classes..."},{after:60,text:"FlutterFlow is applying the changes..."},{after:100,text:"Still working — this can take a couple of minutes..."}],be={sequence:[],phaseId:null,phaseStartedAt:null,timer:null,substatus:null,liveSubstatus:!1,start({withProvisioning:t=!1}={}){this.sequence=["prepare","validate","project"],t&&this.sequence.push("provision"),this.sequence.push("package","push","done");const e=document.getElementById("commit-progress-overlay");e&&e.classList.add("open"),this.set("prepare")},set(t,e=null){if(!(!Sc[t]||t===this.phaseId)){if(!this.sequence.includes(t)){const s=this.sequence.indexOf("package");this.sequence.splice(s===-1?this.sequence.length:s,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=Sc[this.phaseId];if(!t)return;const e=(Date.now()-this.phaseStartedAt)/1e3,s=t.start+(t.end-t.start)*(1-Math.exp(-e/25));if(this.phaseId==="provision"&&!this.liveSubstatus){const o=s_.filter(a=>e>=a.after).pop();o&&(this.substatus=o.text)}const r=this.sequence.indexOf(this.phaseId),i=[`Step ${r===-1?1:r+1} of ${this.sequence.length}`];e>=5&&i.push(r_(e)),nh(this.phaseId==="done"?100:s,t.message,i.join(" · "),this.substatus)},stop(){this.timer&&clearInterval(this.timer),this.timer=null,this.phaseId=null;const t=document.getElementById("commit-progress-overlay");t&&t.classList.remove("open")}};function r_(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 rh(t){be.start(t)}function Pn(){be.stop()}function nh(t,e,s,r=null){const n=document.getElementById("commit-progress-bar"),i=document.getElementById("progress-message"),o=document.getElementById("progress-detail"),a=document.getElementById("progress-substatus");n&&(n.style.width=`${Math.round(t*10)/10}%`),i&&(i.textContent=e),o&&(o.textContent=s),a&&(a.textContent=r||"",a.classList.toggle("hidden",!r))}function xc(t){const e={[V.PREPARING]:"prepare",[V.VALIDATING]:"validate",[V.PUSHING]:"project",[V.SUCCESS]:"done"};if(t===V.ERROR){be.timer&&clearInterval(be.timer),be.timer=null,nh(100,"Failed","Error occurred");return}const s=e[t];s&&be.set(s)}function n_(t){return t.bundlePlan?t.bundlePlan.fileEntries.some(e=>e.type===U.CODE_FILE):t.codeInfo?.codeType===U.CODE_FILE}async function i_(){if(!er){console.error("No pending commit data");return}const t=er;if(er=null,Xs=Qv(),sh(),rh({withProvisioning:n_(t)}),t.bundlePlan){const o=await vv(t.bundlePlan,{pipelineResult:{step1Result:y.step1Result,selectedModel:document.getElementById("code-generator-model")?.value}});Xs=null,Pn(),o.success?No(o):Mo(o);return}const{codeInfo:e}=t,{artifactType:s,artifactName:r,fileName:n}=zd(),i=await mv(e.content,{artifactType:s,artifactName:r,fileName:n,pipelineResult:{step1Result:y.step1Result,selectedModel:document.getElementById("code-generator-model")?.value}});Xs=null,Pn(),i.success?No(i):Mo(i)}window.runThinkingPipeline=$o;window.toggleStep=wv;window.toggleSection=yv;window.selectWorkflowStep=ze;window.copyCode=bv;window.retryWithDifferentModel=kv;window.openApiKeysModal=pa;window.closeApiKeysModal=jd;window.closeWalkthroughModal=Zm;window.openWalkthroughModal=Ym;window.advanceWalkthrough=fa;window.commitToFlutterFlow=gv;function o_(){const t=document.getElementById("pipeline-input");t&&t.focus()}function a_(){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=o_;window.openModelSelector=a_;window.handlePromptImageSelect=Mm;window.removePromptImage=Lm;window.saveApiKeys=ev;window.clearAllApiKeys=tv;window.toggleKeyVisibility=iv;window.handleWelcomeVideoEnd=Zv;window.dismissWelcomeVideo=Zt;window.initiateCommitToFlutterFlow=Iv;window.updateFlutterFlowCredentialStatus=Av;window.closeCommitConfirmModal=sh;window.closeCommitSuccessModal=e_;window.showCommitSuccessModal=No;window.showCommitFailureModal=Mo;window.toggleCodePreview=t_;window.confirmCommitToFlutterFlow=i_;window.runRefinement=Ev;window.regenerateFromPastedErrors=xv;window.clearErrorInput=Sv;window.setFlutterFlowEndpoint=Jm;window.getFlutterFlowEndpoint=gr;window.commitProgress=be;window.openSignInModal=Ca;window.closeSignInModal=Mv;window.handleMagicLinkRequest=Lv;window.handleSignOut=Ov;window.startCheckout=Vv;window.openCustomerPortal=Gv;window.openPricingModal=Fn;window.closePricingModal=eh;let ps=null,ih=null;const kc=120;function Jn(){const t=document.getElementById("pipeline-progress"),e=document.getElementById("results-view"),s=document.getElementById("ready-state");s&&s.classList.add("hidden"),e&&e.classList.remove("visible"),document.body.classList.remove("results-fullscreen","results-with-sidebar"),t&&t.classList.add("visible"),ih=Date.now();for(let r=1;r<=3;r++){const n=document.getElementById(`pdot-${r}`);n&&(n.className="progress-dot")}nt(1),l_()}function nt(t){const e={1:"Analyzing your prompt...",2:"Generating Dart code...",3:"Running code audit..."},s={1:"Step 1 of 3 — Prompt Architect",2:"Step 2 of 3 — Code Generator",3:"Step 3 of 3 — Code Review"},r=document.getElementById("progress-title-text"),n=document.getElementById("progress-substep-text");r&&(r.textContent=e[t]||e[1]),n&&(n.textContent=s[t]||s[1]);for(let i=1;i<=3;i++){const o=document.getElementById(`pdot-${i}`);o&&(i{const t=(Date.now()-ih)/1e3,e=document.getElementById("progress-elapsed"),s=document.getElementById("pipeline-progress-fill");e&&(e.textContent=`${Math.floor(t)}s`);const r=t/kc*100,n=Math.min(95,r*(1-Math.exp(-t/(kc*.6)))*1.2);s&&(s.style.width=`${n}%`)},250)}function $t(){ps&&(clearInterval(ps),ps=null);const t=document.getElementById("pipeline-progress-fill");t&&(t.style.width="100%");for(let e=1;e<=3;e++){const s=document.getElementById(`pdot-${e}`);s&&(s.className="progress-dot completed")}setTimeout(()=>{const e=document.getElementById("pipeline-progress");e&&e.classList.remove("visible"),t&&(t.style.width="0%")},400)}function xs(t,e=""){const s={pass:'',warning:'',fail:'',info:''};return``}function oh(t){return{pass:"Passed review",warning:"Needs attention",fail:"Blocking issues"}[t]||"Needs attention"}function c_(){return Dg({bundle:y.artifactBundle,reviewResult:y.step3Result})}function u_(t){return` +`;const i=fd({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,userFeedback:n});Kn(),nt(2),ze(2),ve(2,!0),y.step2Result=await zn(i,s),jn();const o=document.getElementById("step2-output"),a=ws(y.step2Result);o.textContent=a,o.dataset.raw=a,ve(2,!1),ze(3),nt(3),ve(3,!0),y.step3Result=await qn(y.step2Result,y.step1Result),Un();const l=document.getElementById("step3-output");l.textContent=y.step3Result,ve(3,!1),$t();const u=On(y.step3Result);Jn(a,u)}catch(n){console.error("Regeneration failed:",n),$t(),ue(Sa(n,"Regeneration failed"),"error")}finally{y.isRunning=!1,r&&(r.disabled=!1,r.textContent="Fix Errors & Regenerate"),Zt()}}async function Cv(){const t=document.getElementById("ff-status-dot"),e=document.getElementById("ff-status-text");if(!t||!e)return;const s=await Ee("flutterflow"),r=await Ee("flutterflow_project_id");s&&r?(t.className="w-2 h-2 rounded-full bg-green-500",e.textContent="FlutterFlow credentials configured",e.className="text-green-600"):s||r?(t.className="w-2 h-2 rounded-full bg-yellow-500",e.textContent="FlutterFlow credentials incomplete",e.className="text-yellow-600"):(t.className="w-2 h-2 rounded-full bg-red-500",e.textContent="FlutterFlow credentials not configured",e.className="text-red-600")}async function Fv(t){try{const e=await fetch(`${Je}/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 Pv(t){try{const s=await(await fetch(`${Je}/auth/verify-magic-link`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:t})})).json();if(s.error||!s.email||!s.sessionToken)throw new Error(s.error||"Invalid or expired link");return s}catch(e){throw console.error("verifyMagicLink failed:",{message:e.message,stack:e.stack}),e}}async function Av(t){try{const e=await fetch(`${Je}/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:`${Je}/auth/refresh-session`,status:e.status}),null;const s=await e.json();return s.error||!s.email||!s.sessionToken?(console.warn("refreshSession: validation failed",{error:s.error,hasEmail:!!s.email,hasToken:!!s.sessionToken}),null):s}catch(e){return console.error("refreshSession: fetch failed",{url:`${Je}/auth/refresh-session`,message:e.message,stack:e.stack}),null}}function bc(t,e){const s=Kd(),r=(G.email||s.email)!==t;G.email=t,G.sessionToken=e,G.isVerified=!0,fe=bs({isLoading:!0}),localStorage.setItem(_n,JSON.stringify({email:t,sessionToken:e})),r&&$a()}function ka(){G.email=null,G.sessionToken=null,G.isVerified=!1,fe=bs({isResolved:!0}),localStorage.removeItem(_n),localStorage.removeItem(wn)}function Kd(){try{const t=localStorage.getItem(_n);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(_n),{email:null,sessionToken:null}}}async function $v(){const e=new URLSearchParams(window.location.search).get("token");if(e){window.history.replaceState({},"",window.location.pathname);try{const{email:s,sessionToken:r}=await Pv(e);bc(s,r)}catch(s){ue(s.message||"Sign-in link invalid or expired.","error")}}else{const{email:s,sessionToken:r}=Kd();if(s&&r){const n=await Av(r);n?bc(n.email,n.sessionToken):ka()}}Ca()}function Ia(){const t=document.getElementById("signin-modal");t&&t.classList.add("open")}function Rv(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("signin-modal");e&&e.classList.remove("open")}async function Tv(){const t=document.getElementById("signin-email-input"),e=document.getElementById("signin-submit-btn"),s=document.getElementById("signin-message"),r=t?.value?.trim();if(!r||!/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/.test(r)||r.length>254){s&&(s.textContent="Please enter a valid email address.");return}e&&(e.disabled=!0,e.textContent="Sending…"),s&&(s.textContent="");try{await Fv(r),t&&(t.value=""),s&&(s.textContent=`Check your email — we sent a link to ${r}`),e&&(e.textContent="Sent!")}catch(i){console.error("handleMagicLinkRequest: sendMagicLink failed",{email:r,err:i}),s&&(s.textContent="Something went wrong. Please try again."),e&&(e.disabled=!1,e.textContent="Send Link")}}function Nv(){ka(),$a(),Ca(),Gn()}function Ca(){const t=G.isVerified&&!!G.email,e=document.getElementById("auth-signedout"),s=document.getElementById("auth-signedin"),r=document.getElementById("auth-guest-usage");e&&e.classList.toggle("hidden",t),s&&s.classList.toggle("hidden",!t),r&&r.classList.toggle("hidden",t);const n=document.getElementById("auth-user-email");n&&(n.textContent=G.email||""),zr(),Gn()}async function Jd(){try{if(typeof FingerprintJS>"u"){console.warn("resolveIdentity: FingerprintJS not loaded, skipping");return}const e=await(await FingerprintJS.load()).get(),s=e.visitorId,r=await fetch(xm,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({fingerprint:e.visitorId,cookie_id:s})});if(!r.ok)throw new Error(`Identity check HTTP ${r.status}`);const n=await r.json();if(Ge.userId=n.user_id,Ge.token=n.identity_token||null,Ge.status=n.status,Ge.resolved=!0,sessionStorage.setItem(Em,n.user_id),Ge.token&&sessionStorage.setItem(Sm,Ge.token),n.usage_count!==void 0){const i=At(),a=(n.usage_month||i)===i?n.usage_count:0;localStorage.setItem(Gt,JSON.stringify({count:a,month:i})),Xs()}console.log(`Identity resolved: ${n.status} (${n.user_id.slice(0,8)}...) usage: ${n.usage_count??"n/a"}`)}catch(t){console.error("resolveIdentity failed:",t)}}let Pi=null;function Mv(t=5e3){return Ge.resolved?Promise.resolve():(Pi||(Pi=Jd().catch(e=>{console.warn("ensureIdentityReady: identity resolution failed",e)})),Promise.race([Pi,new Promise(e=>setTimeout(e,t))]))}function Yd(){const t=At();try{const e=localStorage.getItem(Gt);return e?JSON.parse(e):{count:0,month:t}}catch(e){return console.warn("getUsageData: failed to parse usage storage",{key:Gt,month:t,err:e}),localStorage.removeItem(Gt),{count:0,month:t}}}function At(){const t=new Date;return`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,"0")}`}function Vn(){const t=Yd();return t.month!==At()?{count:0,month:At()}:t}function Lv(){const e={count:Vn().count+1,month:At()};return localStorage.setItem(Gt,JSON.stringify(e)),e}function Fa(){return!!fe.isLoading}function Jt(){return!!fe.isResolved}function Ov(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(yn,e)?e:null}function Dv(t){return t&&Object.entries(Pd).find(([,e])=>e===t)?.[0]||null}function $r(...t){return t.find(e=>e!=null&&e!=="")}function Bv(...t){return t.find(e=>e&&typeof e=="object")||{}}function jv(t){const e=t.data&&typeof t.data=="object"?t.data:t,s=Bv(e.subscription,e.stripeSubscription,e.currentSubscription,e.customer?.subscriptions?.data?.[0],e.subscriptions?.data?.[0],e.subscriptions?.[0]),r=e.metadata||s.metadata||e.customer?.metadata||{},n=$r(e.priceId,e.price_id,e.stripePriceId,e.stripe_price_id,s.priceId,s.price_id,s.plan?.id,s.price?.id,s.items?.data?.[0]?.price?.id,s.items?.[0]?.price?.id,s.lines?.data?.[0]?.price?.id),i=$r(e.status,e.subscriptionStatus,e.subscription_status,s.status,"none"),o=Ov($r(e.tier,e.plan,e.planId,e.plan_id,e.subscriptionTier,e.subscription_tier,e.product,e.productName,s.tier,s.plan,r.tier,r.plan)),a=km.has(String(i).toLowerCase()),l=e.active===!0||e.isSubscribed===!0||e.subscribed===!0||e.hasSubscription===!0,u=o||Dv(n)||(a||l?"professional":"free");return bs({tier:u,status:i,periodEnd:$r(e.periodEnd,e.currentPeriodEnd,e.current_period_end,s.current_period_end,s.periodEnd,null),isResolved:!0})}function Pa(){return yn[fe.tier]??yn.free}async function Uv(){if(G.isVerified&&(!Jt()||Fa())&&(await Zd({force:!0}),Gn()),G.isVerified&&!Jt())return ue("Could not verify your subscription. Please refresh or try Manage billing.","error"),!1;const{count:t}=Vn(),e=Pa();if(t>=e)return Aa(t,e,{openModal:!0}),!1;const s=Math.floor(e*.8);if(t>=s){const r=e-t;ue(`${r} run${r===1?"":"s"} remaining this month.`,"warning")}return!0}function Ai(){const t=document.getElementById("paywall-exhausted");t&&t.classList.add("hidden")}function Aa(t,e,s={}){const r=document.getElementById("walkthrough-modal");r&&r.classList.remove("open");const n=document.getElementById("ready-state");n&&n.classList.add("hidden");const i=document.getElementById("preview-frame-container");i&&(i.style.display="none");const o=document.getElementById("main-stage-container");o&&o.classList.add("visible");const a=document.getElementById("results-view");a&&a.classList.remove("visible"),document.body.classList.remove("results-fullscreen","results-with-sidebar");const l=document.getElementById("pipeline-progress");l&&l.classList.remove("visible");const u=document.getElementById("paywall-exhausted");if(!u){ue(`You've used all ${e} runs for this month. Upgrade to continue.`,"error"),Cn();return}const c=document.getElementById("paywall-exhausted-text");if(c){const h=fe.tier;h==="free"?c.textContent=`You've used all ${e} free generations this month. Upgrade to Pro for 50 generations/month and access to all AI models.`:c.textContent=`You've used all ${e} generations this month on your ${h} plan. Your limit resets next month.`}const d=document.getElementById("paywall-signin-btn");d&&d.classList.toggle("hidden",G.isVerified),u.classList.remove("hidden"),s.openModal&&Cn()}function $o(t){return fe.tier==="free"&&jr.includes(t)?lr:t}function Hv(){const t=document.getElementById("code-options-content"),e=document.getElementById("code-generator-model");if(!t||!e)return;const s=fe.tier,n=!(G.isVerified&&!Jt())&&s==="free";Array.from(e.options).forEach(o=>{const a=zt(o.value),l=jr.includes(o.value);o.textContent=l&&n?`${a} (PRO)`:a,o.disabled=!1}),n&&jr.includes(e.value)&&(e.value=lr),e.disabled=!1,dc.has(e)||(e.addEventListener("change",()=>{Jt()&&fe.tier==="free"&&jr.includes(e.value)&&(e.value=lr,Cn()),Po(e.value),$d()}),dc.add(e));let i=document.getElementById("model-selector-free-notice");n?(i||(i=document.createElement("p"),i.id="model-selector-free-notice",i.className="text-xs text-gray-400 mt-1",t.appendChild(i)),i.innerHTML='Free plan — Gemini only. '):i&&i.remove(),Po(e.value)}function Xs(){const t=document.getElementById("usage-counter");if(!t)return;if(G.isVerified&&Fa()){t.textContent="Checking plan…",t.className="text-xs text-gray-500",zr(),Ai();return}if(G.isVerified&&!Jt()){t.textContent="Plan check failed",t.className="text-xs text-red-600 font-medium",zr(),Ai();return}const{count:e}=Vn(),s=Pa();t.textContent=`${e} / ${s} runs this month`;const r=s>0?e/s:0;t.className=r>=1?"text-xs text-red-600 font-medium":r>=.8?"text-xs text-yellow-600 font-medium":"text-xs text-gray-500",zr(),e>=s&&!y.isRunning?Aa(e,s):Ai()}function zr(){const t=document.getElementById("guest-usage-text");if(!t)return;const e=Yd(),s=e.month===At()?e.count??0:0,r=yn.free;t.textContent=`${s} / ${r} generations used`}async function Zd(t={}){const e=t.force===!0;if(!G.isVerified||!G.sessionToken){fe=bs({isResolved:!0});return}fe={...fe,isLoading:!0,error:null};const s=localStorage.getItem(wn);if(!e&&s)try{const{data:r,email:n,ts:i,version:o}=JSON.parse(s);if(o===hc&&n===G.email&&Date.now()-i<300*1e3){fe={...r,isLoading:!1,isResolved:r.isResolved!==!1};return}}catch(r){console.warn("Failed to parse subscription cache:",r,"| raw value:",s)}try{const n=await(await fetch(`${Je}/stripe/get-subscription`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:G.sessionToken,user_id:Ge.userId})})).json();if(n.error){if(["unauthorized","invalid session","expired session"].some(o=>String(n.error).toLowerCase().includes(o))){ka(),Ca();return}fe=bs({isResolved:!1,error:n.error});return}fe=jv(n),localStorage.setItem(wn,JSON.stringify({version:hc,data:fe,email:G.email,ts:Date.now()}))}catch(r){console.error("fetchSubscription failed:",r),fe={...fe,isLoading:!1,isResolved:!1,error:r.message}}}function $a(){localStorage.removeItem(wn)}async function Wv(t){if(!G.isVerified||!G.sessionToken){Xd(),Ia();return}if(!Pd[t]){ue("Invalid plan selected.","error");return}const e=document.getElementById(`checkout-btn-${t}`);e&&(e.disabled=!0,e.textContent="Redirecting…");try{const r=await(await fetch(`${Je}/stripe/create-checkout-session-intl`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tierId:t,sessionToken:G.sessionToken,currency:Nd()})})).json();if(r.error||!r.url)throw new Error(r.error||"Failed to create checkout session");const{url:n}=r;window.location.href=n}catch(s){console.error("startCheckout failed:",s),e&&(e.disabled=!1,e.textContent="Subscribe"),ue("Could not start checkout. Please try again.","error")}}async function zv(){if(!G.isVerified||!G.sessionToken){Ia();return}const t=document.getElementById("manage-billing-btn");t&&(t.disabled=!0,t.textContent="Loading…");try{const s=await(await fetch(`${Je}/stripe/create-portal-session`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:G.sessionToken})})).json();if(s.error||!s.url)throw new Error(s.error||"Failed to open billing portal");const{url:r}=s;window.location.href=r}catch(e){console.error("openCustomerPortal failed:",e),t&&(t.disabled=!1,t.textContent="Manage billing"),ue("Could not open billing portal. Please try again.","error")}}async function In(t,e,s,r={},n=[]){const o=new AbortController,a=setTimeout(()=>o.abort(),12e4);try{const l=await fetch(bm,{method:"POST",headers:{"Content-Type":"application/json",...Ge.token?{Authorization:`Bearer ${Ge.token}`}:{}},signal:o.signal,body:JSON.stringify({user_id:Ge.userId,step:t,model:e,prompt:s,images:n,context:r})}),u=await l.text();let c={};try{c=u?JSON.parse(u):{}}catch{c={}}if(l.status===429){c.serverCount!==void 0&&(localStorage.setItem(Gt,JSON.stringify({count:c.serverCount,month:At()})),Xs());const p=new Error(c.message||"Monthly usage limit reached. Upgrade to continue.");throw p.isUsageLimit=!0,p}const d=zf(c,t);if(d)throw d;if(console.log(`[BuildShip] ${t} response keys:`,Object.keys(c),"content type:",typeof c.content),!l.ok)throw new Error(`${c.message||c.error||"BuildShip pipeline error"} (HTTP ${l.status})`);if(t==="generator")if(c.usage_status==="success"&&Number.isFinite(c.usage_count)){const p=At();(c.usage_month||p)===p&&(localStorage.setItem(Gt,JSON.stringify({count:c.usage_count,month:p})),Xs())}else Lv(),Xs();let h=c.output||c.content;if(!h){const p=u?` (body: ${u.slice(0,120)})`:"";throw new Error(`BuildShip returned no output for step "${t}"${p}`)}return Array.isArray(h)&&(h=h.map(p=>typeof p=="string"?p:p.text||"").join("")),typeof h!="string"&&(h=JSON.stringify(h)),h}catch(l){throw l.name==="AbortError"?new Error(`BuildShip ${t} timed out after ${12e4/1e3}s`):l instanceof TypeError?new Error(`BuildShip unreachable: ${l.message}`):l}finally{clearTimeout(a)}}function qv(){const e=new URLSearchParams(window.location.search).get("checkout");e==="success"?(window.history.replaceState({},"",window.location.pathname),$a(),ue("Subscription active! Welcome aboard.","success")):e==="cancel"&&(window.history.replaceState({},"",window.location.pathname),ue("Checkout cancelled.","info"))}function Gn(){const t=G.isVerified&&!!G.email,e=fe.tier,s=t&&Fa(),r=!t||Jt(),n=document.getElementById("subscription-tier-badge");if(n){const a={free:"Free",professional:"Professional",power:"Power Developer"},l={free:"bg-gray-100 text-gray-600",professional:"bg-indigo-100 text-indigo-700",power:"bg-purple-100 text-purple-700",unresolved:"bg-red-50 text-red-600"};n.textContent=s?"Checking…":r?a[e]||"Free":"Plan unavailable",n.className=`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${r?l[e]||l.free:l.unresolved}`}const i=document.getElementById("upgrade-prompt");i&&i.classList.toggle("hidden",!t||s||!r||e!=="free");const o=document.getElementById("manage-billing-btn");o&&o.classList.toggle("hidden",!t||s||r&&e==="free"),Vv(r?e:null),Hv(),$d(),Xs()}function Vv(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(([n,{btnId:i,defaultText:o}])=>{const a=document.getElementById(i);a&&(n===t?(a.disabled=!0,a.textContent="Current plan",a.classList.add(...e)):(a.disabled=!1,a.textContent=o,a.classList.remove(...e)))});const r=document.getElementById("free-tier-current");r&&r.classList.toggle("hidden",t!=="free")}function Ro(){const t=Nd(),e=document.getElementById("pro-price"),s=document.getElementById("power-price"),r=document.getElementById("pro-price-note"),n=document.getElementById("power-price-note");e&&(e.textContent=fc(pc.professional,t)),s&&(s.textContent=fc(pc.power,t));const i="billed monthly";r&&(r.textContent=i),n&&(n.textContent=i)}function Cn(){Ro();const t=document.getElementById("pricing-modal");t&&t.classList.add("open"),Nm().then(()=>Ro())}function Xd(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("pricing-modal");e&&e.classList.remove("open")}function ue(t,e="info"){const s={success:"bg-green-600 text-white",error:"bg-red-600 text-white",warning:"bg-amber-500 text-white",info:"bg-gray-800 text-white"},r=document.createElement("div");r.className=`fixed bottom-6 left-1/2 -translate-x-1/2 px-5 py-3 rounded-lg text-sm font-medium shadow-lg z-50 transition-opacity duration-300 ${s[e]||s.info}`,r.textContent=t,document.body.appendChild(r),setTimeout(()=>{r.style.opacity="0",setTimeout(()=>r.remove(),300)},3500)}document.addEventListener("DOMContentLoaded",async()=>{hljs.configure({tabReplace:" ",classPrefix:"hljs-"}),Gv(),await $v(),qv(),await Zd(),Gn(),Ro(),await iv(),ev();const t=document.getElementById("flutterflow-endpoint-select");if(t){const s=fr();t.value=s}jd(),Jd();const e=document.getElementById("pipeline-input");e&&(e.addEventListener("input",()=>{Et===2&&e.value.trim().length>0&&(pa(),Dn())}),e.addEventListener("blur",()=>{const s=document.getElementById("walkthrough-modal");Et===2&&s&&s.classList.add("open")}),e.addEventListener("keydown",s=>{if(s.key==="Tab"){const r=document.getElementById("walkthrough-modal");Et===2&&r&&setTimeout(()=>{r.classList.add("open")},100)}})),window.addEventListener("commitStateChange",s=>{const{state:r}=s.detail;r===V.PREPARING||r===V.VALIDATING||r===V.PUSHING?(be.phaseId||th(),Sc(r)):(r===V.SUCCESS||r===V.ERROR)&&(Sc(r),setTimeout(Fn,1e3))})});function Gv(){const t=document.getElementById("preview-frame-container");t&&(t.style.display="")}function Kv(){const t=document.getElementById("welcome-video-player");t&&(t.addEventListener("click",Yt),document.addEventListener("keydown",Yt))}function Yt(){const t=document.getElementById("preview-frame-container"),e=document.getElementById("main-stage-container"),s=document.getElementById("ready-state");t&&(t.style.display="none"),e&&e.classList.add("visible"),s&&s.classList.remove("hidden");const r=document.getElementById("welcome-video-player");r&&r.removeEventListener("click",Yt),document.removeEventListener("keydown",Yt),jd()}let Qs=null;async function Jv(){const t=document.getElementById("confirm-project-select");if(!t)return;const e=++yc,s=()=>e===yc,r=await Ee("flutterflow"),n=await Ee("flutterflow_project_id");if(s()){if(!r){t.innerHTML='',t.disabled=!0;return}t.disabled=!1,t.innerHTML='';try{const o=await new gr(r,"").listProjects();if(!s())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)}),n&&(t.value=n)}catch(i){if(!s())return;console.error("Failed to load projects for deploy:",i),t.innerHTML=''}}}function Yv(){return document.getElementById("confirm-project-select")?.value?.trim()||null}function Qd(t,e,s,r=null){Qs={codeInfo:t,checks:e,deps:s,bundlePlan:r},document.getElementById("confirm-file-name").textContent=t.fileName,document.getElementById("confirm-artifact-type").textContent=t.artifactType,document.getElementById("confirm-file-size").textContent=`${(t.content.length/1024).toFixed(1)} KB`,document.getElementById("confirm-line-count").textContent=r?`${r.fileEntries.length} files`:t.content.split(` +`).length,Jv();const n=document.getElementById("confirm-deps-list"),i=document.getElementById("confirm-deps-section");s&&Object.keys(s).length>0?(n.innerHTML=Object.entries(s).map(([u,c])=>{const d=c?`at least ${bt(c)}`:"version resolved from your project";return`
  • • ${bt(u)}: ${d}
  • `}).join(""),i.classList.remove("hidden")):i.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=>`
  • • ${bt(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&&l.classList.add("open")}function eh(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("commit-confirm-modal");e&&e.classList.remove("open"),Qs=null}function Zv(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("commit-success-modal");e&&e.classList.remove("open");const s=["success-message","success-project-id","success-file-name","success-artifact-type","success-time","success-size"];for(const i of s){const o=document.getElementById(i);o&&(o.textContent="")}const r=document.getElementById("success-warnings-section");r&&r.classList.add("hidden");const n=document.getElementById("success-warnings-list");n&&(n.innerHTML="")}function To(t){const e=(g,m)=>{const _=document.getElementById(g);_&&(_.textContent=m||"")},s=t.metadata?.fileName||"",r=t.metadata?.projectId||"",n=t.metadata?.artifactType||"",i=t.elapsedTime?`${(t.elapsedTime/1e3).toFixed(1)}s`:"",o=t.metadata?.codeSize?`${(t.metadata.codeSize/1024).toFixed(1)} KB`:"";e("success-message",t.message||"Code committed successfully!"),e("success-project-id",r),e("success-file-name",s),e("success-artifact-type",n),e("success-time",i),e("success-size",o);const a=t.addedDependencies||[],l=document.getElementById("success-deps-row");l&&l.classList.toggle("hidden",a.length===0),e("success-deps",a.join(", "));const u=document.getElementById("success-open-ff-link");u&&r&&(u.href=`https://app.flutterflow.io/project/${r}`);const c=document.getElementById("success-warnings-section"),d=document.getElementById("success-warnings-list"),h=t.unverified||[],p=t.warnings||[];(p.length>0||h.length>0)&&c&&d&&(d.innerHTML=[...h.map(g=>`
  • Not verified before deploying: ${j(String(g))}
  • `),...p.map(([g,m])=>`
  • ${j(g)}: ${j(String(m))}
  • `)].join(""),c.classList.remove("hidden"));const f=document.getElementById("commit-success-modal");f&&f.classList.add("open")}function No(t){Fn(),kv(t)}function Xv(){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 Ec={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}},Qv=[{after:0,text:"Starting a FlutterFlow build runner..."},{after:12,text:"Preparing the FlutterFlow AI workspace..."},{after:35,text:"Uploading your custom classes..."},{after:60,text:"FlutterFlow is applying the changes..."},{after:100,text:"Still working — this can take a couple of minutes..."}],be={sequence:[],phaseId:null,phaseStartedAt:null,timer:null,substatus:null,liveSubstatus:!1,start({withProvisioning:t=!1}={}){this.sequence=["prepare","validate","project"],t&&this.sequence.push("provision"),this.sequence.push("package","push","done");const e=document.getElementById("commit-progress-overlay");e&&e.classList.add("open"),this.set("prepare")},set(t,e=null){if(!(!Ec[t]||t===this.phaseId)){if(!this.sequence.includes(t)){const s=this.sequence.indexOf("package");this.sequence.splice(s===-1?this.sequence.length:s,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=Ec[this.phaseId];if(!t)return;const e=(Date.now()-this.phaseStartedAt)/1e3,s=t.start+(t.end-t.start)*(1-Math.exp(-e/25));if(this.phaseId==="provision"&&!this.liveSubstatus){const o=Qv.filter(a=>e>=a.after).pop();o&&(this.substatus=o.text)}const r=this.sequence.indexOf(this.phaseId),i=[`Step ${r===-1?1:r+1} of ${this.sequence.length}`];e>=5&&i.push(e_(e)),sh(this.phaseId==="done"?100:s,t.message,i.join(" · "),this.substatus)},stop(){this.timer&&clearInterval(this.timer),this.timer=null,this.phaseId=null;const t=document.getElementById("commit-progress-overlay");t&&t.classList.remove("open")}};function e_(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 th(t){be.start(t)}function Fn(){be.stop()}function sh(t,e,s,r=null){const n=document.getElementById("commit-progress-bar"),i=document.getElementById("progress-message"),o=document.getElementById("progress-detail"),a=document.getElementById("progress-substatus");n&&(n.style.width=`${Math.round(t*10)/10}%`),i&&(i.textContent=e),o&&(o.textContent=s),a&&(a.textContent=r||"",a.classList.toggle("hidden",!r))}function Sc(t){const e={[V.PREPARING]:"prepare",[V.VALIDATING]:"validate",[V.PUSHING]:"project",[V.SUCCESS]:"done"};if(t===V.ERROR){be.timer&&clearInterval(be.timer),be.timer=null,sh(100,"Failed","Error occurred");return}const s=e[t];s&&be.set(s)}function t_(t){return t.bundlePlan?t.bundlePlan.fileEntries.some(e=>e.type===U.CODE_FILE):t.codeInfo?.codeType===U.CODE_FILE}async function s_(){if(!Qs){console.error("No pending commit data");return}const t=Qs;if(Qs=null,Zs=Yv(),eh(),th({withProvisioning:t_(t)}),t.bundlePlan){const o=await fv(t.bundlePlan,{pipelineResult:{step1Result:y.step1Result,selectedModel:document.getElementById("code-generator-model")?.value}});Zs=null,Fn(),o.success?To(o):No(o);return}const{codeInfo:e}=t,{artifactType:s,artifactName:r,fileName:n}=Hd(),i=await pv(e.content,{artifactType:s,artifactName:r,fileName:n,pipelineResult:{step1Result:y.step1Result,selectedModel:document.getElementById("code-generator-model")?.value}});Zs=null,Fn(),i.success?To(i):No(i)}window.runThinkingPipeline=Ao;window.toggleStep=vv;window.toggleSection=mv;window.selectWorkflowStep=ze;window.copyCode=_v;window.retryWithDifferentModel=Ev;window.openApiKeysModal=ha;window.closeApiKeysModal=Dd;window.closeWalkthroughModal=Km;window.openWalkthroughModal=Gm;window.advanceWalkthrough=pa;window.commitToFlutterFlow=hv;function r_(){const t=document.getElementById("pipeline-input");t&&t.focus()}function n_(){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=r_;window.openModelSelector=n_;window.handlePromptImageSelect=Rm;window.removePromptImage=Tm;window.saveApiKeys=Zm;window.clearAllApiKeys=Xm;window.toggleKeyVisibility=sv;window.handleWelcomeVideoEnd=Kv;window.dismissWelcomeVideo=Yt;window.initiateCommitToFlutterFlow=Sv;window.updateFlutterFlowCredentialStatus=Cv;window.closeCommitConfirmModal=eh;window.closeCommitSuccessModal=Zv;window.showCommitSuccessModal=To;window.showCommitFailureModal=No;window.toggleCodePreview=Xv;window.confirmCommitToFlutterFlow=s_;window.runRefinement=yv;window.regenerateFromPastedErrors=bv;window.clearErrorInput=wv;window.setFlutterFlowEndpoint=Vm;window.getFlutterFlowEndpoint=fr;window.commitProgress=be;window.openSignInModal=Ia;window.closeSignInModal=Rv;window.handleMagicLinkRequest=Tv;window.handleSignOut=Nv;window.startCheckout=Wv;window.openCustomerPortal=zv;window.openPricingModal=Cn;window.closePricingModal=Xd;let hs=null,rh=null;const xc=120;function Kn(){const t=document.getElementById("pipeline-progress"),e=document.getElementById("results-view"),s=document.getElementById("ready-state");s&&s.classList.add("hidden"),e&&e.classList.remove("visible"),document.body.classList.remove("results-fullscreen","results-with-sidebar"),t&&t.classList.add("visible"),rh=Date.now();for(let r=1;r<=3;r++){const n=document.getElementById(`pdot-${r}`);n&&(n.className="progress-dot")}nt(1),i_()}function nt(t){const e={1:"Analyzing your prompt...",2:"Generating Dart code...",3:"Running code audit..."},s={1:"Step 1 of 3 — Prompt Architect",2:"Step 2 of 3 — Code Generator",3:"Step 3 of 3 — Code Review"},r=document.getElementById("progress-title-text"),n=document.getElementById("progress-substep-text");r&&(r.textContent=e[t]||e[1]),n&&(n.textContent=s[t]||s[1]);for(let i=1;i<=3;i++){const o=document.getElementById(`pdot-${i}`);o&&(i{const t=(Date.now()-rh)/1e3,e=document.getElementById("progress-elapsed"),s=document.getElementById("pipeline-progress-fill");e&&(e.textContent=`${Math.floor(t)}s`);const r=t/xc*100,n=Math.min(95,r*(1-Math.exp(-t/(xc*.6)))*1.2);s&&(s.style.width=`${n}%`)},250)}function $t(){hs&&(clearInterval(hs),hs=null);const t=document.getElementById("pipeline-progress-fill");t&&(t.style.width="100%");for(let e=1;e<=3;e++){const s=document.getElementById(`pdot-${e}`);s&&(s.className="progress-dot completed")}setTimeout(()=>{const e=document.getElementById("pipeline-progress");e&&e.classList.remove("visible"),t&&(t.style.width="0%")},400)}function Ss(t,e=""){const s={pass:'',warning:'',fail:'',info:''};return``}function nh(t){return{pass:"Passed review",warning:"Needs attention",fail:"Blocking issues"}[t]||"Needs attention"}function o_(){return Lg({bundle:y.artifactBundle,reviewResult:y.step3Result})}function a_(t){return`
    - ${xs(t.severity)} + ${Ss(t.severity)}
    ${j(t.message)}
    ${t.suggestion?`
    ${j(t.suggestion)}
    `:""} ${j(t.source)}
    - `}function d_(t){return` + `}function l_(t){return`
  • ${j(t.title)} ${t.detail&&t.detail!==t.title?`

    ${j(t.detail)}

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

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

    +

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

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

      ${t.manualSteps.map(l=>` @@ -249,14 +249,14 @@ Error: ${h}
    - `}function p_(t){const e=t.artifacts.find(l=>l.id===y.selectedArtifactId)||t.artifacts[0];if(!e)return"";const s={pass:{icon:"pass",message:"No file-specific issues were found."},warning:{icon:"warning",message:"This file needs attention, but Code Review did not return a specific finding."},fail:{icon:"fail",message:"This file is blocked, but Code Review did not return a specific finding."}}[e.status],r=e.findings.length?e.findings.map(u_).join(""):`
    ${xs(s.icon)} ${j(s.message)}
    `,n=e.dependencies?.length?e.dependencies.map(l=>` + `}function u_(t){const e=t.artifacts.find(l=>l.id===y.selectedArtifactId)||t.artifacts[0];if(!e)return"";const s={pass:{icon:"pass",message:"No file-specific issues were found."},warning:{icon:"warning",message:"This file needs attention, but Code Review did not return a specific finding."},fail:{icon:"fail",message:"This file is blocked, but Code Review did not return a specific finding."}}[e.status],r=e.findings.length?e.findings.map(a_).join(""):`
    ${Ss(s.icon)} ${j(s.message)}
    `,n=e.dependencies?.length?e.dependencies.map(l=>`
  • ${j(l.name)}${l.version?` ${j(l.version)}`:""}${l.reason?`

    ${j(l.reason)}

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

    ${j(l.description)}

    `:""}
  • `).join(""):'
  • No relationships for this file
  • ';return`
    - ${xs(e.status)} ${j(oh(e.status))} + ${Ss(e.status)} ${j(nh(e.status))}

    ${j(e.artifactName)}

    ${e.description?`

    ${j(e.description)}

    `:""}
    @@ -272,7 +272,7 @@ Error: ${h} ${e.manualSteps.length?`

    Manual FlutterFlow steps for this file

    -
      ${e.manualSteps.map(d_).join("")}
    +
      ${e.manualSteps.map(l_).join("")}
    `:""}
    @@ -304,17 +304,17 @@ Error: ${h}
      ${a}
    - `}function f_(t){const e=document.getElementById("bundle-strip"),s=document.getElementById("results-summary-tab"),r=document.getElementById("artifact-tabs"),n=document.getElementById("results-file-count");if(s&&s.classList.toggle("active",y.resultsViewMode==="summary"),!t.artifacts.length){n&&(n.textContent="0 files"),e&&e.classList.remove("visible"),r&&(r.innerHTML="");return}if(n){const i=t.artifacts.length;n.textContent=`${i} ${i===1?"file":"files"}`}r&&(r.innerHTML=t.artifacts.map(i=>` + `}function d_(t){const e=document.getElementById("bundle-strip"),s=document.getElementById("results-summary-tab"),r=document.getElementById("artifact-tabs"),n=document.getElementById("results-file-count");if(s&&s.classList.toggle("active",y.resultsViewMode==="summary"),!t.artifacts.length){n&&(n.textContent="0 files"),e&&e.classList.remove("visible"),r&&(r.innerHTML="");return}if(n){const i=t.artifacts.length;n.textContent=`${i} ${i===1?"file":"files"}`}r&&(r.innerHTML=t.artifacts.map(i=>` - `).join(""),r.onclick=i=>{const o=i.target.closest(".artifact-tab");o?.dataset?.artifactId&&ah(o.dataset.artifactId)}),e&&e.classList.add("visible")}function Ta(){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"),s=document.getElementById("results-audit-output"),r=document.getElementById("results-summary-detail"),n=document.getElementById("artifact-results-split"),i=c_(),o=va();if(h_(i),f_(i),e&&(e.textContent=""),e){const a=Ad(o);e.innerHTML=a}s&&(s.innerHTML=p_(i)),r&&r.classList.toggle("hidden",y.resultsViewMode!=="summary"),n&&n.classList.toggle("hidden",y.resultsViewMode!=="file"),t&&t.classList.add("visible")}function Yn(t,e){y.selectedArtifactId||(y.selectedArtifactId=mn(y.artifactBundle).id),y.resultsViewMode="summary",document.body.classList.add("results-fullscreen");const s=document.getElementById("step3-output");s&&(s.textContent=""),Ta(),Xt();const r=document.getElementById("btn-feedback-up"),n=document.getElementById("btn-feedback-down");r&&(r.className="feedback-btn"),n&&(n.className="feedback-btn")}function ah(t){y.selectedArtifactId=t,y.resultsViewMode="file",Ta()}function g_(){y.resultsViewMode="summary",Ta()}function m_(){const t=document.getElementById("btn-copy-results"),e=va();navigator.clipboard.writeText(e).then(()=>{if(t){t.classList.add("copied");const s=t.querySelector("span");if(s){const r=s.textContent;s.textContent="Copied!",setTimeout(()=>{t.classList.remove("copied"),s.textContent=r},2e3)}}})}function v_(t){const e=document.getElementById("btn-feedback-up"),s=document.getElementById("btn-feedback-down");t==="up"?(e.classList.toggle("active-up"),s.classList.remove("active-down")):(s.classList.toggle("active-down"),e.classList.remove("active-up"));const r=t==="up"?"thumbsUp":"thumbsDown";ka(r,y.step2Result,y.step1Result),zt("Generation Feedback",{feedback:r})}function __(){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 lh(){const t=document.getElementById("error-input-panel");t&&(t.classList.add("hidden"),t.style.display="none")}window.copyResultsCode=m_;window.selectArtifact=ah;window.selectResultsSummary=g_;window.submitResultsFeedback=v_;window.showErrorInputPanel=__;window.hideErrorInputPanel=lh; + `).join(""),r.onclick=i=>{const o=i.target.closest(".artifact-tab");o?.dataset?.artifactId&&ih(o.dataset.artifactId)}),e&&e.classList.add("visible")}function Ra(){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"),s=document.getElementById("results-audit-output"),r=document.getElementById("results-summary-detail"),n=document.getElementById("artifact-results-split"),i=o_(),o=ma();if(c_(i),d_(i),e&&(e.textContent=""),e){const a=Fd(o);e.innerHTML=a}s&&(s.innerHTML=u_(i)),r&&r.classList.toggle("hidden",y.resultsViewMode!=="summary"),n&&n.classList.toggle("hidden",y.resultsViewMode!=="file"),t&&t.classList.add("visible")}function Jn(t,e){y.selectedArtifactId||(y.selectedArtifactId=gn(y.artifactBundle).id),y.resultsViewMode="summary",document.body.classList.add("results-fullscreen");const s=document.getElementById("step3-output");s&&(s.textContent=""),Ra(),Zt();const r=document.getElementById("btn-feedback-up"),n=document.getElementById("btn-feedback-down");r&&(r.className="feedback-btn"),n&&(n.className="feedback-btn")}function ih(t){y.selectedArtifactId=t,y.resultsViewMode="file",Ra()}function h_(){y.resultsViewMode="summary",Ra()}function p_(){const t=document.getElementById("btn-copy-results"),e=ma();navigator.clipboard.writeText(e).then(()=>{if(t){t.classList.add("copied");const s=t.querySelector("span");if(s){const r=s.textContent;s.textContent="Copied!",setTimeout(()=>{t.classList.remove("copied"),s.textContent=r},2e3)}}})}function f_(t){const e=document.getElementById("btn-feedback-up"),s=document.getElementById("btn-feedback-down");t==="up"?(e.classList.toggle("active-up"),s.classList.remove("active-down")):(s.classList.toggle("active-down"),e.classList.remove("active-up")),xa(t==="up"?"thumbsUp":"thumbsDown",y.step2Result,y.step1Result)}function g_(){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 oh(){const t=document.getElementById("error-input-panel");t&&(t.classList.add("hidden"),t.style.display="none")}window.copyResultsCode=p_;window.selectArtifact=ih;window.selectResultsSummary=h_;window.submitResultsFeedback=f_;window.showErrorInputPanel=g_;window.hideErrorInputPanel=oh; diff --git a/dist/index.html b/dist/index.html index 21d5260..8c2cb06 100644 --- a/dist/index.html +++ b/dist/index.html @@ -2420,7 +2420,7 @@ .pm-cards { padding: 0 16px; } } - +
    diff --git a/src/customCodeVerification.js b/src/customCodeVerification.js index 82e0f72..beaaacf 100644 --- a/src/customCodeVerification.js +++ b/src/customCodeVerification.js @@ -76,16 +76,17 @@ function collect(declared, into, sdkPackages) { continue; } - // A block-form entry's first own-key says where the package comes from. - // `sdk:` is the Flutter SDK, which the runner reproduces from the name - // alone as `name: {sdk: flutter}`. A nested `version:` is simply a - // constraint written on its own line. + // A block-form entry's own keys say where the package comes from, in + // whatever order YAML allows. `sdk:` is the Flutter SDK, which the runner + // reproduces from the name alone as `name: {sdk: flutter}`. A mapping + // whose only own key is `version:` is a normal pub.dev dependency with + // its constraint written on its own line. if (info.sourceKey === "sdk") { sdkPackages.add(name); continue; } - if (info.sourceKey === "version") { - into[name] = unquoteConstraint(info.sourceValue); + if (info.sourceKey === null && info.version) { + into[name] = unquoteConstraint(info.version); continue; } diff --git a/src/customCodeVerification.test.js b/src/customCodeVerification.test.js index 02e3d4b..8fb4789 100644 --- a/src/customCodeVerification.test.js +++ b/src/customCodeVerification.test.js @@ -119,6 +119,32 @@ test("a dependency from a git or path source is reported unrepresentable", () => assert.deepEqual(manifest.unrepresentable, ["private_thing"]); }); +test("a hosted source stays unrepresentable when version is written first", () => { + const pubspec = `name: my_app + +environment: + sdk: '>=3.0.0 <4.0.0' + +dependencies: + flutter: + sdk: flutter + hosted_thing: + version: ^1.0.0 + hosted: + name: hosted_thing + url: https://example.invalid +`; + + const manifest = buildAnalysisManifest(pubspec); + + // YAML mappings are order-independent: reading only the first nested key + // classified this entry as a plain pub.dev dependency with constraint + // "^1.0.0", so the scratch manifest would resolve hosted_thing from pub.dev + // while the project ships it from its own host. + assert.deepEqual(manifest.unrepresentable, ["hosted_thing"]); + assert.equal("hosted_thing" in manifest.dependencies, false); +}); + test("a git dependency does not stop a class that never imports it", () => { const plan = planCustomCodeVerification( [{ className: "BackgroundDownloaderService", content: SELF_CONTAINED }], diff --git a/src/pubspecSync.js b/src/pubspecSync.js index 1cdbbb9..52a69d3 100644 --- a/src/pubspecSync.js +++ b/src/pubspecSync.js @@ -103,52 +103,70 @@ function splitValueAndComment(rest) { }; } +// The keys that say where a block-form dependency comes from. `version` is +// deliberately absent: it is a constraint, not a source, so a mapping whose +// only own key is `version:` describes a normal pub.dev dependency. +const SOURCE_KEYS = new Set(["sdk", "git", "path", "hosted"]); + /** - * Reads the first key of a block-form dependency's own mapping. + * Reads where a block-form dependency comes from, scanning every key of its + * own mapping. * * A block-form entry says where a package comes from on a following, more * deeply indented line: `sdk:`, `git:`, `path:`, a nested `hosted:`, or a - * `version:` written on its own line. That key is the only thing that - * distinguishes a package the Flutter SDK supplies from one the analysis - * manifest cannot reproduce, so it is read here rather than guessed from the - * package's name. A name list cannot work: 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. + * `version:` written on its own line. YAML mappings are unordered, so the + * source key can sit after `version:` or between any other keys — reading + * only the first key would classify a valid custom-hosted dependency whose + * `version:` happens to come first as a plain pub.dev one, and the + * verification runner would then compile against a different package source + * than the project ships. + * + * That key is the only thing that distinguishes a package the Flutter SDK + * supplies from one the analysis manifest cannot reproduce, so it is read + * here rather than guessed from the package's name. A name list cannot work: + * 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. * * @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 * @param {number} parentIndent - Indent of the dependency entry itself - * @returns {{key: string, value: string}|null} First own-key, or null if the - * entry has no mapping below it + * @returns {{key: string|null, value: string|null, version: string|null}} + * The source directive's key and inline value — null when the mapping + * holds no sdk/git/path/hosted key — plus the entry's own `version:` value + * when one appears */ function readSourceDirective(lines, entryIndex, endIndex, parentIndent) { + let version = null; for (let i = entryIndex + 1; i < endIndex; i += 1) { const line = lines[i]; if (isBlankOrComment(line)) continue; // 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 to read. - if (indentOf(line) <= parentIndent) return null; + // a sibling dependency, so there is nothing of this entry's own left to read. + if (indentOf(line) <= parentIndent) break; const trimmed = line.trim(); const key = parseDependencyName(trimmed); if (!key) continue; const { value } = splitValueAndComment( trimmed.slice(trimmed.indexOf(":") + 1), ); - return { key, value }; + if (SOURCE_KEYS.has(key)) return { key, value, version }; + if (key === "version" && version === null) version = value; } - return null; + return { key: null, value: null, version }; } /** * Reads every package declared under `dependencies:` with its constraint. * - * A dependency written in block form (`sdk:`, `git:`, `path:`, or a nested - * `version:`) has no scalar constraint and must never be rewritten as one, so - * it is reported with `isScalar: false`. + * 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`. * * @param {string} yamlContent - Raw pubspec.yaml content - * @returns {Map} + * @returns {Map} */ export function parseExistingDependencies(yamlContent) { const lines = String(yamlContent || "").split("\n"); @@ -185,6 +203,7 @@ export function parseExistingDependencies(yamlContent) { isScalar, sourceKey: directive ? directive.key : null, sourceValue: directive ? directive.value : null, + version: directive ? directive.version : null, }); } return declared; @@ -206,7 +225,7 @@ export function parseExistingDependencies(yamlContent) { * * @param {string} yamlContent - Raw pubspec.yaml content * @param {string} blockName - Top-level key, e.g. "dependency_overrides" - * @returns {Map} + * @returns {Map} */ export function parseDependencyBlock(yamlContent, blockName) { const lines = String(yamlContent || "").split("\n"); @@ -243,6 +262,7 @@ export function parseDependencyBlock(yamlContent, blockName) { isScalar, sourceKey: directive ? directive.key : null, sourceValue: directive ? directive.value : null, + version: directive ? directive.version : null, }); } return declared; diff --git a/src/pubspecSync.test.js b/src/pubspecSync.test.js index 0499a77..a9b0e5b 100644 --- a/src/pubspecSync.test.js +++ b/src/pubspecSync.test.js @@ -210,8 +210,62 @@ test("a nested version block is read as a constraint, not as a source", () => { `; const declared = parseExistingDependencies(pubspec); - assert.equal(declared.get("intl").sourceKey, "version"); - assert.equal(declared.get("intl").sourceValue, "^0.20.3"); + // `version` is a constraint, not a source: with no sdk/git/path/hosted key + // present, the dependency is a normal pub.dev one. + assert.equal(declared.get("intl").sourceKey, null); + assert.equal(declared.get("intl").sourceValue, null); + assert.equal(declared.get("intl").version, "^0.20.3"); +}); + +test("a source key is classified wherever it sits among the nested keys", () => { + const pubspec = `dependencies: + hosted_thing: + version: ^1.0.0 + hosted: + name: hosted_thing + url: https://example.invalid + sdk_thing: + version: ^2.0.0 + sdk: flutter + git_thing: + version: ^3.0.0 + git: + url: https://example.invalid/private.git + path_thing: + version: ^4.0.0 + path: ../nearby +`; + const declared = parseExistingDependencies(pubspec); + + // YAML mappings are order-independent, so a `version:` written before the + // source directive must not hide it: reading only the first key classified + // this hosted dependency as a plain pub.dev one, and the verification + // runner compiled against a different package source than the project ships. + assert.equal(declared.get("hosted_thing").sourceKey, "hosted"); + assert.equal(declared.get("sdk_thing").sourceKey, "sdk"); + assert.equal(declared.get("sdk_thing").sourceValue, "flutter"); + assert.equal(declared.get("git_thing").sourceKey, "git"); + assert.equal(declared.get("path_thing").sourceKey, "path"); + assert.equal(declared.get("path_thing").sourceValue, "../nearby"); + + // The version line survives alongside the source key even though the + // source is what classifies the entry. + assert.equal(declared.get("hosted_thing").version, "^1.0.0"); +}); + +test("a version written before an unrecognized key does not invent a source", () => { + const pubspec = `dependencies: + odd_thing: + version: ^5.0.0 + description: not a real pubspec key +`; + const declared = parseExistingDependencies(pubspec); + + // Keys that are neither sources nor `version` are skipped without ending + // the scan, so a source below them is still found and a missing one still + // reads as null. + assert.equal(declared.get("odd_thing").sourceKey, null); + assert.equal(declared.get("odd_thing").version, "^5.0.0"); }); test("a git source keeps only its first key, whatever the nested shape", () => { From dad5c48c04839b009b7e9f28126e8e9ca4620cd4 Mon Sep 17 00:00:00 2001 From: Stuart Date: Tue, 22 Sep 2026 17:21:23 +1000 Subject: [PATCH 06/13] fix: skip verification conservatively when an unrepresentable source can reach a class transitively (cherry picked from commit 9d338ad4fbcc7a06f63b12fd6ef702552ca80620) --- .../{index-DheZmoMN.js => index-BnJVlbD-.js} | 100 +++++++++--------- dist/index.html | 2 +- src/customCodeVerification.js | 65 +++++++++--- src/customCodeVerification.test.js | 95 +++++++++++++---- 4 files changed, 177 insertions(+), 85 deletions(-) rename dist/assets/{index-DheZmoMN.js => index-BnJVlbD-.js} (87%) diff --git a/dist/assets/index-DheZmoMN.js b/dist/assets/index-BnJVlbD-.js similarity index 87% rename from dist/assets/index-DheZmoMN.js rename to dist/assets/index-BnJVlbD-.js index 7722dbb..169da47 100644 --- a/dist/assets/index-DheZmoMN.js +++ b/dist/assets/index-BnJVlbD-.js @@ -1,7 +1,7 @@ -(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const n of document.querySelectorAll('link[rel="modulepreload"]'))r(n);new MutationObserver(n=>{for(const i of n)if(i.type==="childList")for(const o of i.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&r(o)}).observe(document,{childList:!0,subtree:!0});function s(n){const i={};return n.integrity&&(i.integrity=n.integrity),n.referrerPolicy&&(i.referrerPolicy=n.referrerPolicy),n.crossOrigin==="use-credentials"?i.credentials="include":n.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function r(n){if(n.ep)return;n.ep=!0;const i=s(n);fetch(n.href,i)}})();var v=typeof window<"u"?window:void 0,we=typeof globalThis<"u"?globalThis:v,ke=we?.navigator,C=we?.document,re=we?.location,Mo=we?.fetch,$i=we!=null&&we.XMLHttpRequest&&"withCredentials"in new we.XMLHttpRequest?we.XMLHttpRequest:void 0,Ma=we?.AbortController,ah=we?.CompressionStream,Pe=ke?.userAgent;function kc(){return!(!v||v.navigator.onLine===!1)}var Cs=typeof globalThis<"u"?globalThis:v;Cs&&typeof self>"u"&&(Cs.self=Cs),Cs&&typeof File>"u"&&(Cs.File=function(){});var $=v??{},Y={DEBUG:!1,LIB_VERSION:"0.5.0",LIB_NAME:"browser-common"};function La(t,e,s,r,n,i,o){try{var a=t[i](o),l=a.value}catch(u){return void s(u)}a.done?e(l):Promise.resolve(l).then(r,n)}function X(t){return function(){var e=this,s=arguments;return new Promise((function(r,n){var i=t.apply(e,s);function o(l){La(i,r,n,o,a,"next",l)}function a(l){La(i,r,n,o,a,"throw",l)}o(void 0)}))}}function w(){return w=Object.assign?Object.assign.bind():function(t){for(var e=1;arguments.length>e;e++){var s=arguments[e];for(var r in s)({}).hasOwnProperty.call(s,r)&&(t[r]=s[r])}return t},w.apply(null,arguments)}function Ic(t,e){if(t==null)return{};var s={};for(var r in t)if({}.hasOwnProperty.call(t,r)){if(e.indexOf(r)!==-1)continue;s[r]=t[r]}return s}var Oa=t=>{if(typeof t!="string")return t;try{return JSON.parse(t)}catch{return t}};function Da(t){return typeof t=="string"||t}function Ba(t){return typeof t=="string"?t:void 0}var Fs,lh=["$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})({}),ja=(function(t){return t.GZipJS="gzip-js",t.Base64="base64",t})({}),ch=["$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"],uh=["token"],Cc="NativeGzipValidationError",Ri=t=>t.length>=2&&t[0]===31&&t[1]===139,Ua=(t,e)=>t===ja.GZipJS||e===ja.GZipJS||e==="gzip",Ha=t=>!(!t||typeof t!="object")&&("name"in t?String(t.name):"")==="NotReadableError",yr=t=>{var e=new Error("Native gzip produced invalid output: "+t);throw e.name=Cc,e},dh=(function(){var t=X((function*(e,s){18>e.size&&yr("too-short");var r=new Uint8Array(yield e.slice(0,10).arrayBuffer());Ri(r)&&r[2]===8||yr("invalid-header");var n=new DataView(yield e.slice(e.size-8).arrayBuffer());n.getUint32(0,!0)!==(o=>{for(var a=(()=>{if(Fs)return Fs;Fs=[];for(var c=0;256>c;c++){for(var d=c,h=0;8>h;h++)d=1&d?3988292384^d>>>1:d>>>1;Fs[c]=d>>>0}return Fs})(),l=4294967295,u=0;o.length>u;u++)l=a[255&(l^o[u])]^l>>>8;return(4294967295^l)>>>0})(s)&&yr("invalid-crc");var i=s.length>>>0;n.getUint32(4,!0)!==i&&yr("invalid-size")}));return function(e,s){return t.apply(this,arguments)}})();function Ti(){return Ti=X((function*(t,e,s){e===void 0&&(e=!0);try{var r=new TextEncoder().encode(t),n=new globalThis.CompressionStream("gzip"),i=n.writable.getWriter(),o=i.write(r).then((()=>i.close())).catch((function(){var u=X((function*(c){try{yield i.abort(c)}catch{}throw c}));return function(c){return u.apply(this,arguments)}})()),a=new Response(n.readable).blob(),l=(yield Promise.all([a,o]))[0];return yield dh(l,r),l}catch(u){if(s!=null&&s.rethrow)throw u;return e&&console.error("Failed to gzip compress data",u),null}})),Ti.apply(this,arguments)}var hh=["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"],Wa=function(t,e){if(e===void 0&&(e=[]),!t)return!1;var s=t.toLowerCase();return hh.concat(e).some((r=>{var n=r.toLowerCase();return s.indexOf(n)!==-1}))};function M(t,e){return t.indexOf(e)!==-1}var Pn=function(t){return t.trim()},Ni=function(t){return t.replace(/^\$/,"")};function Fc(t){var e,s=[];return(e=JSON.stringify(t,(function(r,n){if(typeof n=="bigint")return n.toString();if(typeof n!="function"&&typeof n!="symbol"){if(n instanceof Error)return{name:n.name,message:n.message,stack:n.stack};if(n&&typeof n=="object"){for(;s.length>0&&s[s.length-1]!==this;)s.pop();if(s.includes(n))return"[Circular]";s.push(n)}return n}})))!==null&&e!==void 0?e:"null"}var Pc=Object.prototype,Ac=Pc.hasOwnProperty,An=Pc.toString,L=Array.isArray||function(t){return An.call(t)==="[object Array]"},Se=t=>typeof t=="function",te=t=>t===Object(t)&&!L(t),mt=t=>{if(te(t)){for(var e in t)if(Ac.call(t,e))return!1;return!0}return!1},x=t=>t===void 0,W=t=>An.call(t)=="[object String]",Mi=t=>W(t)&&t.trim().length===0,$e=t=>t===null,D=t=>x(t)||$e(t),he=t=>An.call(t)=="[object Number]"&&t==t,lt=t=>he(t)&&t>0,Ke=t=>An.call(t)==="[object Boolean]",ph=t=>t instanceof FormData,fh=t=>M(ch,t),gh=t=>M(uh,t);function $c(t){return t===null||typeof t!="object"}function qr(t,e){return{}.toString.call(t)==="[object "+e+"]"}function Lo(t){return typeof Event<"u"&&Rc(t,Event)}function Rc(t,e){try{return t instanceof e}catch{return!1}}var mh=[!0,"true",1,"1","yes"],Zn=t=>M(mh,t),vh=[!1,"false",0,"0","no"];function rt(t,e,s,r,n){return e>s&&(r.warn("min cannot be greater than max."),e=s),he(t)?t>s?(r.warn(" cannot be greater than max: "+s+". Using max value instead."),s):e>t?(r.warn(" cannot be less than min: "+e+". Using min value instead."),e):t:(r.warn(" must be a number. using max or fallback. max: "+s+", fallback: "+n),rt(n||s,e,s,r))}class _h{constructor(e){this.tt={},this.et=e.et,this.it=rt(e.bucketSize,0,100,e.rt),this.nt=rt(e.refillRate,0,this.it,e.rt),this.st=rt(e.refillInterval,0,864e5,e.rt)}ot(e,s){var r=Math.floor((s-e.lastAccess)/this.st);r>0&&(e.tokens=Math.min(e.tokens+r*this.nt,this.it),e.lastAccess=e.lastAccess+r*this.st)}consumeRateLimit(e){var s,r=Date.now(),n=String(e),i=this.tt[n];return i?this.ot(i,r):this.tt[n]=i={tokens:this.it,lastAccess:r},i.tokens===0||(i.tokens--,i.tokens===0&&((s=this.et)==null||s.call(this,e)),i.tokens===0)}stop(){this.tt={}}}var Oe="Mobile",Vr="iOS",vt="Android",ps="Tablet",Tc=vt+" "+ps,Nc="iPad",Mc="Apple",Lc=Mc+" Watch",qs="Safari",fs="BlackBerry",Oc="Samsung",Dc=Oc+"Browser",Bc=Oc+" Internet",Vt="Chrome",yh=Vt+" OS",jc=Vt+" "+Vr,Oo="Internet Explorer",Uc=Oo+" "+Oe,Do="Opera",wh=Do+" Mini",Bo="Edge",Hc="Microsoft "+Bo,us="Firefox",Wc=us+" "+Vr,er="Nintendo",tr="PlayStation",ds="Xbox",zc=vt+" "+Oe,qc=Oe+" "+qs,Ds="Windows",Li=Ds+" Phone",za="Nokia",Oi="Ouya",Vc="Generic",bh=Vc+" "+Oe.toLowerCase(),Gc=Vc+" "+ps.toLowerCase(),Di="Konqueror",Kc="Oculus Browser",Gr="Vivaldi",Jc="Yandex",Kr="Whale",Bi="DuckDuckGo",Yc="Pale Moon",Jr="Waterfox",Vs="Brave",Zc="Google Search App",le="(\\d+(\\.\\d+)?)",Xn=new RegExp("Version/"+le),Eh=new RegExp(ds,"i"),Sh=new RegExp(tr+" \\w+","i"),xh=new RegExp(er+" \\w+","i"),jo=new RegExp(fs+"|PlayBook|BB10","i"),kh={"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"},Xc=function(t,e,s,r){e=e||"";var n=(function(i){return i!=null&&i.brave?Vs:null})(s);return n||(r!=null&&r.detectGoogleSearchApp&&M(t,"GSA/")?Zc:M(t," OPR/")&&M(t,"Mini")?wh:M(t," OPR/")?Do:jo.test(t)?fs:M(t,"IE"+Oe)||M(t,"WPDesktop")?Uc:M(t,"OculusBrowser")?Kc:M(t,Dc)?Bc:M(t,Bo)||M(t,"Edg/")?Hc:M(t,Gr+"/")?Gr:M(t,"YaBrowser/")?Jc:M(t,Kr+"/")?Kr:M(t,Bi+"/")||M(t,"Ddg/")?Bi:M(t,"FBIOS")?"Facebook "+Oe:M(t,"UCWEB")||M(t,"UCBrowser")?"UC Browser":M(t,"CriOS")?jc:M(t,"CrMo")||M(t,Vt)?Vt:M(t,vt)&&M(t,qs)?zc:M(t,"FxiOS")?Wc:M(t.toLowerCase(),Di.toLowerCase())?Di:M(t,Vs+"/")?Vs:((i,o)=>o&&M(o,Mc)||(function(a){return M(a,qs)&&!M(a,Vt)&&!M(a,vt)})(i))(t,e)?M(t,Oe)?qc:qs:M(t,"PaleMoon/")?Yc:M(t,Jr+"/")?Jr:M(t,us)?us:M(t,"MSIE")||M(t,"Trident/")?Oo:M(t,"Gecko")?us:"")},Ih={[Uc]:[new RegExp("rv:"+le)],[Hc]:[new RegExp(Bo+"?\\/"+le)],[Vt]:[new RegExp("("+Vt+"|CrMo)\\/"+le)],[jc]:[new RegExp("CriOS\\/"+le)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+le)],[qs]:[Xn],[qc]:[Xn],[Do]:[new RegExp("(Opera|OPR)\\/"+le)],[us]:[new RegExp(us+"\\/"+le)],[Wc]:[new RegExp("FxiOS\\/"+le)],[Di]:[new RegExp("Konqueror[:/]?"+le,"i")],[fs]:[new RegExp(fs+" "+le),Xn],[zc]:[new RegExp("android\\s"+le,"i")],[Bc]:[new RegExp(Dc+"\\/"+le)],[Kc]:[new RegExp("OculusBrowser\\/"+le)],[Gr]:[new RegExp(Gr+"\\/"+le)],[Jc]:[new RegExp("YaBrowser\\/"+le)],[Kr]:[new RegExp(Kr+"\\/"+le)],[Vs]:[new RegExp(Vs+"\\/"+le)],[Bi]:[new RegExp("(DuckDuckGo|Ddg)\\/"+le)],[Yc]:[new RegExp("PaleMoon\\/"+le)],[Jr]:[new RegExp(Jr+"\\/"+le)],[Zc]:[new RegExp("GSA\\/"+le)],[Oo]:[new RegExp("(rv:|MSIE )"+le)],Mozilla:[new RegExp("rv:"+le)]},Ch=function(t,e,s,r){var n=Xc(t,e,s,r),i=Ih[n];if(x(i))return null;for(var o=0;i.length>o;o++){var a=t.match(i[o]);if(a)return parseFloat(a[a.length-2])}return null},qa=[[new RegExp(ds+"; "+ds+" (.*?)[);]","i"),t=>[ds,t&&t[1]||""]],[new RegExp(er,"i"),[er,""]],[new RegExp(tr,"i"),[tr,""]],[jo,[fs,""]],[new RegExp(Ds,"i"),(t,e)=>{if(/Phone/.test(e)||/WPDesktop/.test(e))return[Li,""];if(new RegExp(Oe).test(e)&&!/IEMobile\b/.test(e))return[Ds+" "+Oe,""];var s=/Windows NT ([0-9.]+)/i.exec(e);if(s&&s[1]){var r=kh[s[1]]||"";return/arm/i.test(e)&&(r="RT"),[Ds,r]}return[Ds,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,t=>t&&t[3]?[Vr,[t[3],t[4],t[5]||"0"].join(".")]:[Vr,""]],[/(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i,t=>{var e="";return t&&t.length>=3&&(e=x(t[2])?t[3]:t[2]),["watchOS",e]}],[new RegExp("("+vt+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+vt+")","i"),t=>t&&t[2]?[vt,[t[2],t[3],t[4]||"0"].join(".")]:[vt,""]],[/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/,[yh,""]],[/Linux|debian/i,["Linux",""]]],Va=function(t){return xh.test(t)?er:Sh.test(t)?tr:Eh.test(t)?ds:new RegExp(Oi,"i").test(t)?Oi:new RegExp("("+Li+"|WPDesktop)","i").test(t)?Li:/iPad/.test(t)?Nc:/iPod/.test(t)?"iPod Touch":/iPhone/.test(t)?"iPhone":/(watch)(?: ?os[,/]|\d,\d\/)[\d.]+/i.test(t)?Lc:jo.test(t)?fs:/(kobo)\s(ereader|touch)/i.test(t)?"Kobo":new RegExp(za,"i").test(t)?za:/(kf[a-z]{2}wi|aeo[c-r]{2})( bui|\))/i.test(t)||/(kf[a-z]+)( bui|\)).+silk\//i.test(t)?"Kindle Fire":/(Android|ZTE)/i.test(t)?new RegExp(Oe).test(t)&&!/(9138B|TB782B|Nexus [97]|pixel c|HUAWEISHT|BTV|noble nook|smart ultra 6)/i.test(t)||/pixel[\daxl ]{1,6}/i.test(t)&&!/pixel c/i.test(t)||/(huaweimed-al00|tah-|APA|SM-G92|i980|zte|U304AA)/i.test(t)||/lmy47v/i.test(t)&&!/QTAQZ3/i.test(t)?vt:Tc:new RegExp("(pda|"+Oe+")","i").test(t)?bh:new RegExp(ps,"i").test(t)&&!new RegExp(ps+" pc","i").test(t)?Gc:""},Fh=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Ga(t,e){return typeof(s=t)=="string"&&Fh.test(s)?t:e();var s}function Ct(t){return t&&t.split("#")[0]}function Uo(t,e){var s=setTimeout(t,e);return s?.unref&&s?.unref(),s}function Ka(t,e,s){return Qc.apply(this,arguments)}function Qc(){return(Qc=X((function*(t,e,s){var r;try{return yield Promise.race([t,new Promise(((n,i)=>{r=Uo((()=>{try{s?.(),n()}catch(o){i(o)}}),e)}))])}finally{clearTimeout(r)}}))).apply(this,arguments)}var Ph=t=>t instanceof Error,eu={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}},Ah=eu.info;function tu(t){if(Ke(t))return{boolValue:t};if(typeof t=="number")return Number.isFinite(t)?Number.isInteger(t)?{intValue:t}:{doubleValue:t}:{stringValue:String(t)};if(typeof t=="string")return{stringValue:t};if(L(t))return{arrayValue:{values:t.map((e=>tu(e)))}};try{return{stringValue:JSON.stringify(t)}}catch{return{stringValue:String(t)}}}function Yr(t){var e=[];for(var s in t){var r=t[s];$e(r)||x(r)||e.push({key:s,value:tu(r)})}return e}function $h(t,e){var s=eu[t.level||"info"]||Ah,r=s.text,n=s.number,i=String(Date.now())+"000000",o={};e.distinctId&&(o.posthogDistinctId=e.distinctId),e.sessionId&&(o.sessionId=e.sessionId),e.windowId&&(o["window.id"]=e.windowId),D(e.sessionStartTimestamp)||(o.sessionStartTimestamp=String(e.sessionStartTimestamp)),D(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=w({},o,t.attributes||{}),l={timeUnixNano:i,observedTimeUnixNano:i,severityNumber:n,severityText:r,body:{stringValue:t.body},attributes:Yr(a)};return t.trace_id&&(l.traceId=t.trace_id),t.span_id&&(l.spanId=t.span_id),x(t.trace_flags)||(l.flags=t.trace_flags),l}function su(t,e,s){return w({},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":s})}function ru(t,e,s,r){return{resourceLogs:[{resource:{attributes:Yr(e)},scopeLogs:[{scope:{name:s,version:r},logRecords:t}]}]}}let Rh=class{constructor(t,e,s,r,n,i,o){var a;i===void 0&&(i=()=>Promise.resolve()),this._instance=t,this.Ne=e,this.rt=s,this.ut=r,this.ht=n,this.dt=i,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 s={record:$h(e,this.ut())};this.ht((()=>this.At(s)))}}else this.rt.info("Log was rejected in beforeSend function")}}Pt(t){var e=this.Ne.beforeSend;if(!e)return t;var s=L(e)?e:[e],r=t;for(var n of s)try{var i=n(r);if(!i)return this.rt.info("Log was rejected in beforeSend function"),null;r=i}catch(o){return this.rt.error("Error in beforeSend function for log:",o),null}return r}Rt(){if(this.Tt===void 0)return!0;var t=Date.now(),e=t-this.bt;return this.Mt>e&&e>=0||(this.bt=t,this._t=0,this.wt=!1),this.Tt>this._t?(this._t++,!0):(this.wt||(this.rt.warn("captureLog dropping logs: exceeded "+this.Tt+" logs per "+this.Mt+"ms"),this.wt=!0),!1)}flush(){var t=this;return X((function*(){if(!t._instance.isDisabled)return t.ct||(t.ct=t.Ft().finally((()=>{t.ct=null}))),t.ct}))()}Ft(){var t=this;return X((function*(){var e;t.Et();var s=(e=t._instance.getPersistedProperty(ut.LogsQueue))!==null&&e!==void 0?e:[];if(s.length!==0)for(var r=s.length,n=0;s.length>0&&r>n;){var i,o;t.ft=0;var a=Math.min(s.length,t.Ct),l=s.slice(0,a),u=ru(l.map((d=>d.record)),t.Lt(),(i=t.vt)!==null&&i!==void 0?i: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),s=(o=t._instance.getPersistedProperty(ut.LogsQueue))!==null&&o!==void 0?o:[],n+=l.length,c.kind==="fatal"))throw c.error}}))()}Dt(t){var e=this;return X((function*(){var s,r=Math.max(0,t-e.ft),n=(s=e._instance.getPersistedProperty(ut.LogsQueue))!==null&&s!==void 0?s:[];e._instance.setPersistedProperty(ut.LogsQueue,n.slice(r)),yield e.dt()}))()}Lt(){return su(this.Ne,this._instance.getLibraryId(),this._instance.getLibraryVersion())}At(t){var e;if(!this._instance.optedOut){var s=(e=this._instance.getPersistedProperty(ut.LogsQueue))!==null&&e!==void 0?e:[];this.xt>s.length||(s.shift(),this.ft++,this.rt.info("Logs queue is full, dropping oldest record.")),s.push(t),this._instance.setPersistedProperty(ut.LogsQueue,s),this.kt>s.length?this.$t():this.It()}}$t(t){t===void 0&&(t=this.St),this.Nt||(this.Nt=Uo((()=>{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 X((function*(){e.Et();var s=e.flush().catch((()=>{}));t!==void 0?yield Ka(s,t):yield s}))()}flushWithTimeout(t){var e=this;return X((function*(){var s=e.flush();yield Ka(s,t,(()=>{s.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 Qn=[0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4];function Ja(t){return String(t)+"000000"}function Ya(t,e,s,r){var n="";return r&&(n=Object.keys(r).sort().map((i=>JSON.stringify(i)+":"+JSON.stringify(r[i]))).join(",")),t+"\0"+e+"\0"+(s??"")+"\0"+n}let Th=class{constructor(t,e,s){this._instance=t,this.Ne=e,this.rt=s,this.Bt=new Map,this.ct=null,this.Ht=!1,this.Ut=new Map,this.zt=new Set,this.Wt=0}count(t,e,s){e===void 0&&(e=1),this.Vt({name:t,type:"count",value:e,unit:s?.unit,attributes:s?.attributes})}gauge(t,e,s){this.Vt({name:t,type:"gauge",value:e,unit:s?.unit,attributes:s?.attributes})}histogram(t,e,s){this.Vt({name:t,type:"histogram",value:e,unit:s?.unit,attributes:s?.attributes})}flush(){var t=this,e=this.ct,s=(function(){var n=X((function*(){e&&(yield e.catch((()=>{}))),yield t.Zt()}));return function(){return n.apply(this,arguments)}})(),r=s().finally((()=>{this.ct===r&&(this.ct=null)}));return this.ct=r,r}drainWindow(){if(this.Bt.size===0)return null;var t=this.Bt;return this.Bt=new Map,this.Ht=!1,this.Ut=new Map,this.zt=new Set,this.Gt(t)}reset(){this.Wt++,this.Et(),this.Bt=new Map,this.ct=null,this.Ht=!1,this.Ut=new Map,this.zt=new Set}Vt(t){if(!this._instance.isDisabled&&!this._instance.optedOut){var e=this.Pt(t);if(e!==null)if(e.name&&typeof e.name=="string")if(typeof e.value=="number"&&Number.isFinite(e.value))if(e.type==="count"&&0>e.value)this.rt.warn("Dropping count '"+e.name+"': counters are monotonic, value must be >= 0");else{var s,r;try{s=e.attributes?w({},e.attributes):void 0,r=Ya(e.type,e.name,e.unit,s)}catch(o){return void this.rt.warn("Dropping metric '"+e.name+"': attributes could not be serialized",o)}var n=this.Bt.get(r);if(!n){if(!this.Qt())return;n={name:e.name,type:e.type,unit:e.unit,attributes:s,windowStartMs:Date.now()},this.Bt.set(r,n)}var i=this.Ut.get(e.name);i===void 0?this.Ut.set(e.name,e.type):i===e.type||this.zt.has(e.name)||(this.zt.add(e.name),this.rt.warn("Metric name '"+e.name+"' is already used as a "+i+"; recording it as a "+e.type+" too will blend both series in charts. Use a distinct name.")),this.Kt(n,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 s;switch(t.type){case"count":t.total=((s=t.total)!==null&&s!==void 0?s: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(Qn.length+1).fill(0)});var r=t.hist;r.count+=1,r.sum+=e,r.min=Math.min(r.min,e),r.max=Math.max(r.max,e),r.bucketCounts[(function(n,i){for(var o=0;i.length>o;o++)if(i[o]>=n)return o;return i.length})(e,Qn)]+=1}}Pt(t){var e=this.Ne.beforeSend;if(!e)return t;var s=L(e)?e:[e],r=t;for(var n of s)try{var i=n(r);if(!i)return this.rt.info("Metric was rejected in beforeSend function"),null;r=i}catch(o){return this.rt.error("Error in beforeSend function for metric:",o),null}return r}$t(){this.Nt||(this.Nt=Uo((()=>{this.Nt=void 0,this.flush().catch((t=>{this.rt.error("Metrics flush failed:",t)}))}),this.Ne.flushIntervalMs))}Et(){this.Nt&&(clearTimeout(this.Nt),this.Nt=void 0)}Zt(){var t=this;return X((function*(){if(t.Bt.size!==0){var e=t.Bt;t.Bt=new Map,t.Ht=!1,t.Ut=new Map,t.zt=new Set;var s=t.Wt,r=yield t._instance.Jt(t.Gt(e));if(s===t.Wt)switch(r.kind){case"ok":return;case"retry-later":return t.Yt(e),void t.$t();case"too-large":return void t.rt.warn("Metrics batch exceeded the server size limit and was dropped");case"fatal":return void t.rt.error("Failed to send metrics batch:",r.error)}}}))()}Gt(t){return e=this.Xt(t),s=(function(i,o,a){return w({},i.resourceAttributes,{"service.name":i.serviceName||"unknown_service"},i.environment&&{"deployment.environment":i.environment},i.serviceVersion&&{"service.version":i.serviceVersion},{"telemetry.sdk.name":o,"telemetry.sdk.version":a})})(this.Ne,this._instance.getLibraryId(),this._instance.getLibraryVersion()),r=this._instance.getLibraryId(),n=this._instance.getLibraryVersion(),{resourceMetrics:[{resource:{attributes:Yr(s)},scopeMetrics:[{scope:{name:r,version:n},metrics:e}]}]};var e,s,r,n}Xt(t){var e=Ja(Date.now()),s=new Map;for(var r of t.values()){var n,i=Ya(r.type,r.name,r.unit,void 0),o=s.get(i);o||(o=w({name:r.name},r.unit&&{unit:r.unit}),r.type==="count"?o.sum={aggregationTemporality:1,isMonotonic:!0,dataPoints:[]}:r.type==="gauge"?o.gauge={dataPoints:[]}:o.histogram={aggregationTemporality:1,dataPoints:[]},s.set(i,o));var a=Yr((n=r.attributes)!==null&&n!==void 0?n:{}),l=Ja(r.windowStartMs);if(r.type==="count"){var u,c={attributes:a,startTimeUnixNano:l,timeUnixNano:e,asDouble:(u=r.total)!==null&&u!==void 0?u:0};o.sum.dataPoints.push(c)}else if(r.type==="gauge"){var d,h={attributes:a,timeUnixNano:e,asDouble:(d=r.last)!==null&&d!==void 0?d:0};o.gauge.dataPoints.push(h)}else r.hist&&o.histogram.dataPoints.push({attributes:a,startTimeUnixNano:l,timeUnixNano:e,count:r.hist.count,sum:r.hist.sum,min:r.hist.min,max:r.hist.max,bucketCounts:r.hist.bucketCounts,explicitBounds:Qn})}return Array.from(s.values())}Yt(t){var e,s;for(var r of t){var n=r[0],i=r[1],o=this.Bt.get(n);if(o)switch(o.windowStartMs=Math.min(o.windowStartMs,i.windowStartMs),o.type){case"count":o.total=((e=o.total)!==null&&e!==void 0?e:0)+((s=i.total)!==null&&s!==void 0?s:0);break;case"gauge":break;case"histogram":if(i.hist)if(o.hist){o.hist.count+=i.hist.count,o.hist.sum+=i.hist.sum,o.hist.min=Math.min(o.hist.min,i.hist.min),o.hist.max=Math.max(o.hist.max,i.hist.max);for(var a=0;o.hist.bucketCounts.length>a;a++)o.hist.bucketCounts[a]+=i.hist.bucketCounts[a]}else o.hist=i.hist}else this.Qt()&&this.Bt.set(n,i)}}};var wr,Za,ei;function Nh(t){var e=globalThis._posthogChunkIds;if(e){var s=Object.keys(e);return ei&&s.length===Za||(Za=s.length,ei=s.reduce(((r,n)=>{wr||(wr={});var i=wr[n];if(i)r[i[0]]=i[1];else for(var o=t(n),a=o.length-1;a>=0;a--){var l=o[a],u=l?.filename,c=e[n];if(u&&c){r[u]=c,wr[n]=[u,c];break}}return r}),{})),ei}}class Mh{constructor(e,s,r){r===void 0&&(r=[]),this.coercers=e,this.stackParser=s,this.modifiers=r}buildFromUnknown(e,s){s===void 0&&(s={});var r=s&&s.mechanism||{handled:!0,type:"generic"},n=this.buildCoercingContext(r,s,0).apply(e),i=this.buildParsingContext(s),o=this.parseStacktrace(n,i);return{$exception_list:this.convertToExceptionList(o,r),$exception_level:"error"}}modifyFrames(e){var s=this;return X((function*(){for(var r of e)r.stacktrace&&r.stacktrace.frames&&L(r.stacktrace.frames)&&(r.stacktrace.frames=yield s.applyModifiers(r.stacktrace.frames));return e}))()}coerceFallback(e){var s;return{type:"Error",value:"Unknown error",stack:(s=e.syntheticException)==null?void 0:s.stack,synthetic:!0}}parseStacktrace(e,s){var r,n;return e.cause!=null&&(r=this.parseStacktrace(e.cause,s)),e.stack!=""&&e.stack!=null&&(n=this.applyChunkIds(this.stackParser(e.stack,e.synthetic?s.skipFirstLines:0),s.chunkIdMap)),w({},e,{cause:r,stack:n})}applyChunkIds(e,s){return e.map((r=>(r.filename&&s&&(r.chunk_id=s[r.filename]),r)))}applyCoercers(e,s){for(var r of this.coercers)if(r.match(e))return r.coerce(e,s);return this.coerceFallback(s)}applyModifiers(e){var s=this;return X((function*(){var r=e;for(var n of s.modifiers)r=yield n(r);return r}))()}convertToExceptionList(e,s){var r,n,i,o={type:e.type,value:e.value,mechanism:{type:(r=s.type)!==null&&r!==void 0?r:"generic",handled:(n=s.handled)===null||n===void 0||n,synthetic:(i=e.synthetic)!==null&&i!==void 0&&i}};e.stack&&(o.stacktrace={type:"raw",frames:e.stack});var a=[o];return e.cause!=null&&a.push(...this.convertToExceptionList(e.cause,w({},s,{handled:!0}))),a}buildParsingContext(e){var s;return{chunkIdMap:Nh(this.stackParser),skipFirstLines:(s=e.skipFirstLines)!==null&&s!==void 0?s:1}}buildCoercingContext(e,s,r){r===void 0&&(r=0);var n=(i,o)=>{if(4>=o){var a=this.buildCoercingContext(e,s,o);return this.applyCoercers(i,a)}};return w({},s,{syntheticException:r==0?s.syntheticException:void 0,mechanism:e,apply:i=>n(i,r),next:i=>n(i,r+1)})}}var gs="?";function ji(t,e,s,r,n){var i={platform:t,filename:e,function:s===""?gs:s,in_app:!0};return x(r)||(i.lineno=r),x(n)||(i.colno=n),i}var nu=(t,e)=>{var s=t.indexOf("safari-extension")!==-1,r=t.indexOf("safari-web-extension")!==-1;return s||r?[t.indexOf("@")!==-1?t.split("@")[0]:gs,s?"safari-extension:"+e:"safari-web-extension:"+e]:[t,e]},Lh=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,Oh=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,Dh=/\((\S*)(?::(\d+))(?::(\d+))\)/,Bh=(t,e)=>{var s=Lh.exec(t);if(s)return ji(e,s[1],gs,+s[2],+s[3]);var r=Oh.exec(t);if(r){if(r[2]&&r[2].indexOf("eval")===0){var n=Dh.exec(r[2]);n&&(r[2]=n[1],r[3]=n[2],r[4]=n[3])}var i=nu(r[1]||gs,r[2]);return ji(e,i[1],i[0],r[3]?+r[3]:void 0,r[4]?+r[4]:void 0)}},jh=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,Uh=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,Hh=(t,e)=>{var s=jh.exec(t);if(s){if(s[3]&&s[3].indexOf(" > eval")>-1){var r=Uh.exec(s[3]);r&&(s[1]=s[1]||"eval",s[3]=r[1],s[4]=r[2],s[5]="")}var n=s[3],i=s[1]||gs,o=nu(i,n);return ji(e,n=o[1],i=o[0],s[4]?+s[4]:void 0,s[5]?+s[5]:void 0)}},Xa=/\(error: (.*)\)/;class Wh{match(e){return this.isDOMException(e)||this.isDOMError(e)}coerce(e,s){var r=W(e.stack);return{type:this.getType(e),value:this.getValue(e),stack:r?e.stack:void 0,cause:e.cause?s.next(e.cause):void 0,synthetic:!1}}getType(e){return this.isDOMError(e)?"DOMError":"DOMException"}getValue(e){var s=e.name||(this.isDOMError(e)?"DOMError":"DOMException");return e.message?s+": "+e.message:s}isDOMException(e){return qr(e,"DOMException")}isDOMError(e){return qr(e,"DOMError")}}class zh{match(e){return(function(s){switch({}.toString.call(s)){case"[object Error]":case"[object Exception]":case"[object DOMException]":case"[object DOMError]":case"[object WebAssembly.Exception]":return!0;default:return Rc(s,Error)}})(e)}coerce(e,s){return{type:this.getType(e),value:this.getMessage(e,s),stack:this.getStack(e),cause:e.cause?s.next(e.cause):void 0,synthetic:!1}}getType(e){return e.name||e.constructor.name}getMessage(e,s){var r=e.message;return String(r.error&&typeof r.error.message=="string"?r.error.message:r)}getStack(e){return e.stacktrace||e.stack||void 0}}class qh{constructor(){}match(e){return!!qr(e,"ErrorEvent")&&(e.error!=null||this.fe(e))}coerce(e,s){var r;if(e.error!=null)return s.apply(e.error);var n=s.apply(e.message);return w({},n,{stack:(r=this.pe(e))!==null&&r!==void 0?r:n.stack,synthetic:!0})}fe(e){return W(e.message)&&e.message.length>0}pe(e){var s=e;if(W(s.filename)&&s.filename.length>0){var r,n,i=(r=s.lineno)!==null&&r!==void 0?r:0,o=(n=s.colno)!==null&&n!==void 0?n:0;return`Error - at `+s.filename+":"+i+":"+o}}}var Vh=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;class Gh{match(e){return typeof e=="string"}coerce(e,s){var r,n=this.getInfos(e),i=n[0],o=n[1];return{type:i??"Error",value:o??e,stack:(r=s.syntheticException)==null?void 0:r.stack,synthetic:!0}}getInfos(e){var s="Error",r=e,n=e.match(Vh);return n&&(s=n[1],r=n[2]),[s,r]}}var Kh=["fatal","error","warning","log","info","debug"];function iu(t,e){e===void 0&&(e=40);var s=Object.keys(t);if(s.sort(),!s.length)return"[object has no keys]";for(var r=s.length;r>0;r--){var n=s.slice(0,r).join(", ");if(e>=n.length)return r===s.length?n:n.length>e?n.slice(0,e)+"...":n}return""}class Jh{match(e){return typeof e=="object"&&e!==null}coerce(e,s){var r,n,i=this.getErrorPropertyFromObject(e);return i?s.apply(i):{type:this.getType(e),value:this.getValue(e),stack:(r=this.getStack(e))!==null&&r!==void 0?r:(n=s.syntheticException)==null?void 0:n.stack,level:this.isSeverityLevel(e.level)?e.level:"error",synthetic:!0}}getType(e){return Lo(e)?e.constructor.name:"Error"}getValue(e){if("name"in e&&typeof e.name=="string"){var s="'"+e.name+"' captured as exception";return"message"in e&&typeof e.message=="string"&&(s+=" with message: '"+e.message+"'"),s}if("message"in e&&typeof e.message=="string")return e.message;var r=this.getObjectClassName(e);return(r&&r!=="Object"?"'"+r+"'":"Object")+" captured as exception with keys: "+iu(e)}isSeverityLevel(e){return W(e)&&!Mi(e)&&Kh.indexOf(e)>=0}getStack(e){try{return W(e.stacktrace)&&e.stacktrace.length>0?e.stacktrace:W(e.stack)&&e.stack.length>0?e.stack:void 0}catch{return}}getErrorPropertyFromObject(e){for(var s in e)if({}.hasOwnProperty.call(e,s)){var r=e[s];if(Ph(r))return r}}getObjectClassName(e){try{var s=Object.getPrototypeOf(e);return s?s.constructor.name:void 0}catch{return}}}class Yh{match(e){return Lo(e)}coerce(e,s){var r,n=e.constructor.name;return{type:n,value:n+" captured as exception with keys: "+iu(e),stack:(r=s.syntheticException)==null?void 0:r.stack,synthetic:!0}}}class Zh{match(e){return $c(e)}coerce(e,s){var r;return{type:"Error",value:"Primitive value captured as exception: "+String(e),stack:(r=s.syntheticException)==null?void 0:r.stack,synthetic:!0}}}class Xh{match(e){return qr(e,"PromiseRejectionEvent")||this.isCustomEventWrappingRejection(e)}isCustomEventWrappingRejection(e){if(!Lo(e))return!1;try{var s=e.detail;return s!=null&&typeof s=="object"&&"reason"in s}catch{return!1}}coerce(e,s){var r,n=this.getUnhandledRejectionReason(e);return $c(n)?{type:"UnhandledRejection",value:"Non-Error promise rejection captured with value: "+String(n),stack:(r=s.syntheticException)==null?void 0:r.stack,synthetic:!0}:s.apply(n)}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 Zr="$message",Xr="$timestamp",Qh=new Set([Zr,Xr]),ti={enabled:!0,max_bytes:32768};function Qr(t){var e;return t?{enabled:(e=t.enabled)!==null&&e!==void 0?e:ti.enabled,max_bytes:tp(t.max_bytes,ti.max_bytes)}:w({},ti)}class ep{constructor(e){this.Ke=[],this.Je=0,this.Ne=Qr(e)}setConfig(e){this.Ne=Qr(e),this.Xe()}add(e){var s=(function(n){var i;try{i=Fc(n)}catch{return}try{var o=JSON.parse(i);if(!te(o))return;var a=o,l=a[Zr],u=a[Xr];return!W(l)||l.trim().length===0||!W(u)&&!he(u)?void 0:{step:a,json:i}}catch{return}})(e);if(s){var r=(function(n){if(typeof TextEncoder<"u")return new TextEncoder().encode(n).length;for(var i=encodeURIComponent(n),o=0,a=0;i.length>a;a++)i[a]==="%"?(o+=1,a+=2):o+=1;return o})(s.json);r>this.Ne.max_bytes||(this.Ke.push({step:s.step,bytes:r}),this.Je+=r,this.Xe())}}getAttachable(){return this.Ke.map((e=>e.step))}clear(){this.Ke=[],this.Je=0}size(){return this.Ke.length}Xe(){for(;this.Je>this.Ne.max_bytes&&this.Ke.length>0;){var e=this.Ke.shift();e&&(this.Je-=e.bytes)}}}function tp(t,e){if(!he(t)||t===1/0||t===-1/0)return e;var s=Math.floor(t);return 0>s?e:s}var ou=function(t,e){var s=(e===void 0?{}:e).debugEnabled,r={k(n){if(v&&(Y.DEBUG||v.POSTHOG_DEBUG||s)&&!x(v.console)&&v.console){for(var i=("__rrweb_original__"in v.console[n])?v.console[n].__rrweb_original__:v.console[n],o=arguments.length,a=new Array(o>1?o-1:0),l=1;o>l;l++)a[l-1]=arguments[l];i(t,...a)}},debug(){for(var n=arguments.length,i=new Array(n),o=0;n>o;o++)i[o]=arguments[o];r.k("debug",...i)},info(){for(var n=arguments.length,i=new Array(n),o=0;n>o;o++)i[o]=arguments[o];r.k("log",...i)},warn(){for(var n=arguments.length,i=new Array(n),o=0;n>o;o++)i[o]=arguments[o];r.k("warn",...i)},error(){for(var n=arguments.length,i=new Array(n),o=0;n>o;o++)i[o]=arguments[o];r.k("error",...i)},critical(){for(var n=arguments.length,i=new Array(n),o=0;n>o;o++)i[o]=arguments[o];console.error(t,...i)},uninitializedWarning(n){r.error("You must initialize PostHog before calling "+n)},createLogger:(n,i)=>ou(t+" "+n,i)};return r},k=ou("[PostHog.js]"),se=k.createLogger,sp=se("[ExternalScriptsLoader]"),si=(t,e,s)=>{if(t.config.disable_external_dependency_loading)return sp.warn(e+" was requested but loading of external scripts is disabled."),s("Loading of external scripts is disabled");var r=C?.querySelectorAll("script");if(r){for(var n,i=function(){if(r[o].src===e){var l=r[o];return l.__posthog_loading_callback_fired?{v:s()}:(l.addEventListener("load",(u=>{l.__posthog_loading_callback_fired=!0,s(void 0,u)})),l.onerror=u=>s(u),{v:void 0})}},o=0;r.length>o;o++)if(n=i())return n.v}var a=()=>{if(!C)return s("document not found");var l=C.createElement("script");if(l.type="text/javascript",l.crossOrigin="anonymous",l.src=e,l.onload=d=>{l.__posthog_loading_callback_fired=!0,s(void 0,d)},l.onerror=d=>s(d),t.config.prepare_external_dependency_script&&(l=t.config.prepare_external_dependency_script(l)),!l)return s("prepare_external_dependency_script returned null");if(t.config.external_scripts_inject_target==="head")C.head.appendChild(l);else{var u,c=C.querySelectorAll("body > script");c.length>0?(u=c[0].parentNode)==null||u.insertBefore(l,c[0]):C.body.appendChild(l)}};C!=null&&C.body?a():C?.addEventListener("DOMContentLoaded",a)};$.__PosthogExtensions__=$.__PosthogExtensions__||{},$.__PosthogExtensions__.loadExternalDependency=(t,e,s)=>{if(e!=="remote-config"){var r;if(t.config.strict_script_versioning)r=t.requestRouter.endpointFor("assets","/static/"+t.version+"/"+e+".js");else{var n="/static/"+e+".js?v="+t.version;if(e==="toolbar"){var i=3e5;n=n+"&t="+Math.floor(Date.now()/i)*i}r=t.requestRouter.endpointFor("assets",n)}si(t,r,s)}else{var o=t.requestRouter.endpointFor("assets","/array/"+t.config.token+"/config.js");si(t,o,s)}},$.__PosthogExtensions__.loadSiteApp=(t,e,s)=>{var r=t.requestRouter.endpointFor("api",e);si(t,r,s)};Y.DEBUG=!1,Y.LIB_VERSION="1.415.7",Y.LIB_NAME="web";var au="$people_distinct_id",sr="$device_id",ri="$device_model",Bs="__alias",js="__timers",Ui="$autocapture_disabled_server_side",Hi="$heatmaps_enabled_server_side",Wi="$exception_capture_enabled_server_side",zi="$error_tracking_suppression_rules",qi="$error_tracking_capture_extension_exceptions",Vi="$web_vitals_enabled_server_side",Ho="$dead_clicks_enabled_server_side",Wo="$product_tours_enabled_server_side",Gi="$web_vitals_allowed_metrics",qt="$session_recording_remote_config",lu="$replay_sample_rate",cu="$replay_override_sampling",uu="$replay_override_linked_flag",du="$replay_override_url_trigger",hu="$replay_override_event_trigger",ls="$sesid",zo="$session_is_sampled",Bt="$enabled_feature_flags",Us="$active_feature_flags",Rr="$early_access_features",Ki="$feature_flag_details",Hs="$feature_flag_payloads",Tr="$feature_flag_request_id",en="$minimal_flag_called_events",et="$override_feature_flags",jt="$override_feature_flag_payloads",ct="$stored_person_properties",Ut="$stored_group_properties",Ji="$surveys",tn="$surveys_loaded_at",Yi="$surveys_activated",Nr="$surveys_activated_session",Mr="$surveys_activated_timestamps",Ws="ph_product_tours",Wt="$flag_call_reported",zs="$flag_call_reported_session_id",Lr="$feature_flag_errors",Gs="$feature_flag_evaluated_at",He="$user_state",Zi="$client_session_props",Xi="$capture_rate_limit",Qi="$initial_campaign_params",eo="$initial_referrer_info",sn="$initial_person_info",rn="$epp",br="$posthog_cookieless",pu="$cookieless_mode",fu="$sdk_debug_extensions_init_method",gu="$sdk_debug_extensions_init_time_ms",mu="$sdk_debug_recording_script_not_loaded",qo="PostHog loadExternalDependency extension not found.",Ht="on_reject",ht="always",es="anonymous",Tt="identified",to="identified_only",nn="visibilitychange",on="beforeunload",is="$pageview",ni="$pageleave",ii="$identify",Qa="$groupidentify";function Er(t,e){L(t)&&t.forEach(e)}function Z(t,e){if(!D(t))if(L(t))t.forEach(e);else if(ph(t))t.forEach(((r,n)=>e(r,n)));else for(var s in t)Ac.call(t,s)&&e(t[s],s)}var ee=function(t){for(var e=arguments.length,s=new Array(e>1?e-1:0),r=1;e>r;r++)s[r-1]=arguments[r];for(var n of s)for(var i in n)n[i]!==void 0&&(t[i]=n[i]);return t};function Or(t){for(var e=Object.keys(t),s=e.length,r=new Array(s);s--;)r[s]=[e[s],t[e[s]]];return r}var el=function(t){try{return t()}catch{return}},rp=function(t){return function(){try{for(var e=arguments.length,s=new Array(e),r=0;e>r;r++)s[r]=arguments[r];return t.apply(this,s)}catch(n){k.critical("Implementation error. Please turn on debug mode and open a ticket on https://app.posthog.com/home#panel=support%3Asupport%3A."),k.critical(n)}}},Vo=function(t){var e={};return Z(t,(function(s,r){(W(s)&&s.length>0||he(s))&&(e[r]=s)})),e},np=["herokuapp.com","vercel.app","netlify.app"];function ip(t){var e=t?.hostname;if(!W(e))return!1;var s=e.split(".").slice(-2).join(".");for(var r of np)if(s===r)return!1;return!0}function ne(t,e,s,r){var n=r??{},i=n.capture,o=n.passive;t?.addEventListener(e,s,{capture:i!==void 0&&i,passive:o===void 0||o})}function so(t){return t.name==="ph_toolbar_internal"}var vu=t=>{if(C){try{for(var e=t+"=",s=C.cookie.split(";").filter((i=>i.length)),r=0;s.length>r;r++){for(var n=s[r];n.charAt(0)==" ";)n=n.substring(1,n.length);if(n.indexOf(e)===0)return decodeURIComponent(n.substring(e.length,n.length))}}catch{}return null}};Math.trunc||(Math.trunc=function(t){return 0>t?Math.ceil(t):Math.floor(t)}),Number.isInteger||(Number.isInteger=function(t){return he(t)&&isFinite(t)&&Math.floor(t)===t});class an{constructor(e){if(this.bytes=e,e.length!==16)throw new TypeError("not 128-bit length")}static fromFieldsV7(e,s,r,n){if(!Number.isInteger(e)||!Number.isInteger(s)||!Number.isInteger(r)||!Number.isInteger(n)||0>e||0>s||0>r||0>n||e>0xffffffffffff||s>4095||r>1073741823||n>4294967295)throw new RangeError("invalid field value");var i=new Uint8Array(16);return i[0]=e/Math.pow(2,40),i[1]=e/Math.pow(2,32),i[2]=e/Math.pow(2,24),i[3]=e/Math.pow(2,16),i[4]=e/256,i[5]=e,i[6]=112|s>>>8,i[7]=s,i[8]=128|r>>>24,i[9]=r>>>16,i[10]=r>>>8,i[11]=r,i[12]=n>>>24,i[13]=n>>>16,i[14]=n>>>8,i[15]=n,new an(i)}toString(){for(var e="",s=0;this.bytes.length>s;s++)e=e+(this.bytes[s]>>>4).toString(16)+(15&this.bytes[s]).toString(16),s!==3&&s!==5&&s!==7&&s!==9||(e+="-");if(e.length!==36)throw new Error("Invalid UUIDv7 was generated");return e}clone(){return new an(this.bytes.slice(0))}equals(e){return this.compareTo(e)===0}compareTo(e){for(var s=0;16>s;s++){var r=this.bytes[s]-e.bytes[s];if(r!==0)return Math.sign(r)}return 0}}class op{generate(){var e=this.generateOrAbort();if(!x(e))return e;this.S=0;var s=this.generateOrAbort();if(x(s))throw new Error("Could not generate UUID after timestamp reset");return s}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 an.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 ap}}var tl,_u=t=>{if(typeof UUIDV7_DENY_WEAK_RNG<"u"&&UUIDV7_DENY_WEAK_RNG)throw new Error("no cryptographically strong RNG available");for(var e=0;t.length>e;e++)t[e]=65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random());return t};v&&!x(v.crypto)&&crypto.getRandomValues&&(_u=t=>crypto.getRandomValues(t));class ap{nextUint32(){return this.R.length>this.O||(_u(this.R),this.O=0),this.R[this.O++]}constructor(){this.R=new Uint32Array(8),this.O=1/0}}var dt=()=>lp().toString(),lp=()=>(tl||(tl=new op)).generate(),Ps="",cp=/[a-z0-9][a-z0-9-]+\.[a-z]{2,}$/i,pt={N:()=>!!C,j(t){k.error("cookieStore error: "+t)},P:vu,H(t){var e;try{e=JSON.parse(pt.P(t))||{}}catch{}return e},F(t,e,s,r,n){if(!C)return!1;try{var i="",o="",a=(function(c,d){if(d){var h=(function(f,g){if(g===void 0&&(g=C),Ps)return Ps;if(!g||["localhost","127.0.0.1"].includes(f))return"";for(var m=f.split("."),_=Math.min(m.length,8),b="dmn_chk_"+dt();!Ps&&_--;){var E=m.slice(_).join("."),I=b+"=1;domain=."+E+";path=/";g.cookie=I+";max-age=3",g.cookie.includes(b)&&(g.cookie=I+";max-age=0",Ps=E)}return Ps})(c);if(!h){var p=(f=>{var g=f.match(cp);return g?g[0]:""})(c);p!==h&&k.info("Warning: cookie subdomain discovery mismatch",p,h),h=p}return h?"; domain=."+h:""}return""})(C.location.hostname,r);if(s){var l=new Date;l.setTime(l.getTime()+864e5*s),i="; expires="+l.toUTCString()}n&&(o="; secure");var u=t+"="+encodeURIComponent(JSON.stringify(e))+i+"; SameSite=Lax; path=/"+a+o;return u.length>3686.4&&k.warn("cookieStore warning: large cookie, len="+u.length),C.cookie=u,!0}catch{return!1}},q(t,e){if(C!=null&&C.cookie)try{pt.F(t,"",-1,e)}catch{return}}},oi=null,Q={N(){if(!$e(oi))return oi;var t=!0;if(x(v))t=!1;else try{var e="__mplssupport__";Q.F(e,"xyz"),Q.P(e)!=='"xyz"'&&(t=!1),Q.q(e)}catch{t=!1}return t||k.error("localStorage unsupported; falling back to cookie store"),oi=t,t},j(t){k.error("localStorage error: "+t)},P(t){try{return v?.localStorage.getItem(t)}catch(e){Q.j(e)}return null},H(t){try{return JSON.parse(Q.P(t))||{}}catch{}return null},F(t,e){try{return v?.localStorage.setItem(t,JSON.stringify(e)),!0}catch(s){Q.j(s)}return!1},q(t){try{v?.localStorage.removeItem(t)}catch(e){Q.j(e)}}},up=[sr,"distinct_id",ls,zo,rn,sn,He],Sr={},dp={N:()=>!0,j(t){k.error("memoryStorage error: "+t)},P:t=>Sr[t]||null,H:t=>Sr[t]||null,F:(t,e)=>(Sr[t]=e,!0),q(t){delete Sr[t]}},Nt=null,ce={N(){if(!$e(Nt))return Nt;if(Nt=!0,x(v))Nt=!1;else try{var t="__support__";ce.F(t,"xyz"),ce.P(t)!=='"xyz"'&&(Nt=!1),ce.q(t)}catch{Nt=!1}return Nt},j(t){k.error("sessionStorage error: ",t)},P(t){try{return v?.sessionStorage.getItem(t)}catch(e){ce.j(e)}return null},H(t){try{return JSON.parse(ce.P(t))||null}catch{}return null},F(t,e){try{return v?.sessionStorage.setItem(t,JSON.stringify(e)),!0}catch(s){ce.j(s)}return!1},q(t){try{v?.sessionStorage.removeItem(t)}catch(e){ce.j(e)}}};class hp{constructor(e){this._instance=e}get Ne(){return this._instance.config}get consent(){return this.ti()?0:this.ei}isOptedOut(){return this.Ne.cookieless_mode===ht||this.isRejected()||this.consent===-1&&this.Ne.cookieless_mode===Ht}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,s=e.token,r=e.opt_out_capturing_cookie_prefix;return e.consent_persistence_name||(r?r+s:"__ph_opt_in_out_"+s)}get ei(){var e=this.ii.P(this.ri);return Zn(e)?1:M(vh,e)?0:-1}get ii(){var e=this.Ne.opt_out_capturing_persistence_type,s=e==="localStorage"?Q:pt;if(!this.ni||this.ni!==s){this.ni=s;var r=e==="localStorage"?pt:Q;r.P(this.ri)&&(this.ni.P(this.ri)||this.optInOut(Zn(r.P(this.ri))),r.q(this.ri,this.Ne.cross_subdomain_cookie))}return this.ni}ti(){return!!this.Ne.respect_dnt&&[ke?.doNotTrack,ke?.msDoNotTrack,$.doNotTrack].some((e=>Zn(e)))}}function yu(t,e){var s,r=t==null||(s=t.config)==null?void 0:s.get_current_url;if(!Se(r))return e;try{var n=r(e);return W(n)&&n?n:e}catch(i){return k.error("Error in get_current_url, falling back to window.location.href",i),e}}var wu="__POSTHOG_TOOLBAR__",pp=1,fp=3,gp=11;function sl(t){return t instanceof Element&&(t.id===wu||!(t.closest==null||!t.closest(".toolbar-global-fade-container")))}function Ft(t){return!!t&&t.nodeType===pp}function Me(t,e){return!!t&&!!t.tagName&&t.tagName.toLowerCase()===e.toLowerCase()}function bu(t){return!!t&&t.nodeType===fp}function Eu(t){return!!t&&t.nodeType===gp&&Ft(t.host)}var Su=1e3;function Go(t){return t?Pn(t).split(/\s+/):[]}function rl(t,e){var s=(function(r){var n,i=v==null||(n=v.location)==null?void 0:n.href;return x(i)?void 0:yu(r,i)})(e);return!!(s&&t&&t.some((r=>s.match(r))))}function ln(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 Go(e)}function xu(t){return D(t)?null:Pn(t).split(/(\s+)/).filter((e=>Ks(e))).join("").replace(/[\r\n]/g," ").replace(/[ ]+/g," ").substring(0,255)}function rr(t){var e="";return no(t)&&!Fu(t)&&t.childNodes&&t.childNodes.length&&Z(t.childNodes,(function(s){var r;bu(s)&&s.textContent&&(e+=(r=xu(s.textContent))!==null&&r!==void 0?r:"")})),Pn(e)}function ai(t){var e;return x(t.target)?t.srcElement||null:(e=t.target)!=null&&e.shadowRoot?t.composedPath()[0]||null:t.target||null}var Ko=["a","button","form","input","select","textarea","label"];function ro(t,e){if(x(e))return!0;var s,r=function(i){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}})(i,o))))return{v:!0}};for(var n of t)if(s=r(n))return s.v;return!1}function ku(t){var e=t.parentNode;return!(!e||!Ft(e))&&e}var mp=[".ph-no-autocapture","[data-ph-no-autocapture]"],Iu=["next","previous","prev",">","<"],vp=[...Iu,"+","-","−","–"],nl=(t,e)=>/[a-z0-9]/i.test(e)?t.includes(e):t===e,il=[".ph-no-rageclick",".ph-no-capture"],_p=["","text","search","email","password","url","tel","number"];function ol(t,e){if(!v||Jo(t))return!1;var s,r,n,i,o;if(Ke(e)?(s=!!e&&il,r=void 0,n=!1):(s=(i=e?.css_selector_ignorelist)!==null&&i!==void 0?i:il,r=e?.content_ignorelist,n=(o=e?.ignore_text_selection)!==null&&o!==void 0&&o),s===!1||n&&(function(l){return!(!l||!Ft(l))&&(!!Me(l,"textarea")||(Me(l,"input")?M(_p,(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=Cu(t,!1).targetElementList;return!(function(l,u){if(l===!1||x(l))return!1;var c;if(l===!0)c=Iu;else{if(!L(l))return!1;if(l.length>10)return k.error("[PostHog] content_ignorelist array cannot exceed 10 items. Use css_selector_ignorelist for more complex matching."),!1;c=l.map((d=>d.toLowerCase()))}return u.some((d=>{var h=d.safeText,p=d.ariaLabel;return c.some((f=>nl(h,f)||nl(p,f)))}))})(r,a.map((l=>{var u;return{safeText:rr(l).toLowerCase(),ariaLabel:((u=l.getAttribute("aria-label"))==null?void 0:u.toLowerCase().trim())||""}})))&&!ro(a,s)}var Jo=t=>!t||Me(t,"html")||!Ft(t),Cu=(t,e)=>{if(!v||Jo(t))return{parentIsUsefulElement:!1,targetElementList:[]};for(var s=!1,r=[t],n=t;n.parentNode&&!Me(n,"body");)if(Eu(n.parentNode))r.push(n.parentNode.host),n=n.parentNode.host;else{var i=ku(n);if(!i)break;if(e||Ko.indexOf(i.tagName.toLowerCase())>-1)s=!0;else try{var o=v.getComputedStyle(i);o&&o.getPropertyValue("cursor")==="pointer"&&(s=!0)}catch{}r.push(i),n=i}return{parentIsUsefulElement:s,targetElementList:r}};function no(t){for(var e=new Set,s=0,r=t;r.parentNode&&!Me(r,"body");r=r.parentNode){if(s++>=Su||e.has(r))return!1;e.add(r);var n=ln(r);if(M(n,"ph-sensitive")||M(n,"ph-no-capture"))return!1}if(M(ln(t),"ph-include"))return!0;var i=t.type||"";if(W(i))switch(i.toLowerCase()){case"hidden":case"password":return!1}var o=t.name||t.id||"";return!W(o)||!/^cc|cardnum|ccnum|creditcard|csc|cvc|cvv|exp|pass|pwd|routing|seccode|securitycode|securitynum|socialsec|socsec|ssn/i.test(o.replace(/[^a-zA-Z0-9]/g,""))}function Fu(t){return!!(Me(t,"input")&&!["button","checkbox","submit","reset"].includes(t.type)||Me(t,"select")||Me(t,"textarea")||t.getAttribute("contenteditable")==="true")}var al=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}))$"),ll=/(^|[^0-9A-Za-z_])([0-9][0-9 -]*[0-9])(?=$|[^0-9A-Za-z_])/g,yp=[16,15,14,13],wp=new RegExp("^(\\d{3}-?\\d{2}-?\\d{4})$"),cl=new RegExp("(^|[^0-9])((?!000|666)[0-9]{3}-?(?!00)[0-9]{2}-?(?!0000)[0-9]{4})(?=$|([^0-9]))","g"),ul=/[0-9A-Za-z_]/;function bp(t){for(var e=0,s=!1,r=t.length-1;r>=0;r--){var n=t.charCodeAt(r)-48;s&&(n*=2)>9&&(n-=9),e+=n,s=!s}return e%10==0}function Ks(t,e){if(e===void 0&&(e=!0),D(t))return!1;if(W(t)){t=Pn(t);var s=e?al.test((t||"").replace(/[- ]/g,"")):(function(n){var i;for(ll.lastIndex=0;i=ll.exec(n);){var o=i[2];if(o)for(var a=o.replace(/[- ]/g,""),l=0;a.length>l;l++)for(var u of yp){var c=l+u;if(a.length>=c){var d=a.slice(l,c);if(al.test(d)&&bp(d))return!0}}}return!1})(t);if(s)return!1;var r=e?wp.test(t):(function(n){var i;for(cl.lastIndex=0;i=cl.exec(n);){var o=i[1],a=i[3];if(!(o&&a&&ul.test(o)&&ul.test(a)))return!0}return!1})(t);if(r)return!1}return!0}function dl(t){var e=rr(t);return Ks(e=(e+" "+Pu(t)).trim())?e:""}function Pu(t){var e="";return t&&t.childNodes&&t.childNodes.length&&Z(t.childNodes,(function(s){var r;if(s&&((r=s.tagName)==null?void 0:r.toLowerCase())==="span")try{var n=rr(s);e=(e+" "+n).trim(),s.childNodes&&s.childNodes.length&&(e=(e+" "+Pu(s)).trim())}catch(i){k.error("[AutoCapture]",i)}})),e}function hl(t){return t.replace(/"|\\"/g,'\\"')}function Ep(t){var e=t.attr__class;if(e)return L(e)?e:Go(e)}var xr=se("[Dead Clicks]"),Sp=()=>!0,xp=t=>{var e,s=!((e=t.instance.persistence)==null||!e.get_property(Ho)),r=t.instance.config.capture_dead_clicks;return Ke(r)?r:!!te(r)||s};class pl{get lazyLoadedDeadClicksAutocapture(){return this.si}constructor(e,s,r){this.instance=e,this.isEnabled=s,this.onCapture=r,this.startIfEnabledOrStop()}onRemoteConfig(e){if(e.ok){var s=e.config;"captureDeadClicks"in s&&(this.instance.persistence&&this.instance.persistence.register({[Ho]:s.captureDeadClicks}),this.startIfEnabledOrStop())}}startIfEnabledOrStop(){this.isEnabled(this)?this.ai((()=>{this.oi()})):this.stop()}ai(e){var s,r;(s=$.__PosthogExtensions__)!=null&&s.initDeadClicksAutocapture?e():(r=$.__PosthogExtensions__)==null||r.loadExternalDependency==null||r.loadExternalDependency(this.instance,"dead-clicks-autocapture",(n=>{n?xr.error("failed to load script",n):e()}))}oi(){var e;if(C){if(!this.si&&(e=$.__PosthogExtensions__)!=null&&e.initDeadClicksAutocapture){var s=te(this.instance.config.capture_dead_clicks)?w({},this.instance.config.capture_dead_clicks):{};s.__onCapture=this.onCapture,this.onCapture&&(s.capture_dead_swipes=!1),this.si=$.__PosthogExtensions__.initDeadClicksAutocapture(this.instance,s),this.si.start(C),xr.info("starting...")}}else xr.error("`document` not found. Cannot start.")}stop(){this.si&&(this.si.stop(),this.si=void 0,xr.info("stopping..."))}}var li=se("[SegmentIntegration]"),Au="posthog-js";function $u(t,e){var s=e===void 0?{}:e,r=s.organization,n=s.projectId,i=s.prefix,o=s.severityAllowList,a=o===void 0?["error"]:o,l=s.sendExceptionsToPostHog,u=l===void 0||l;return c=>{var d,h,p,f,g;if(a!=="*"&&!a.includes(c.level)||!t.__loaded)return c;c.tags||(c.tags={});var m=t.requestRouter.endpointFor("ui","/project/"+t.config.token+"/person/"+t.get_distinct_id());c.tags["PostHog Person URL"]=m,t.sessionRecordingStarted()&&(c.tags["PostHog Recording URL"]=t.get_session_replay_url({withTimestamp:!0}));var _,b=((d=c.exception)==null?void 0:d.values)||[],E=b.map((F=>w({},F,{stacktrace:F.stacktrace?w({},F.stacktrace,{type:"raw",frames:(F.stacktrace.frames||[]).map((P=>w({},P,{platform:"web:javascript"})))}):void 0}))),I={$exception_message:((h=b[0])==null?void 0:h.value)||c.message,$exception_type:(p=b[0])==null?void 0:p.type,$exception_level:c.level,$exception_list:E,$sentry_event_id:c.event_id,$sentry_exception:c.exception,$sentry_exception_message:((f=b[0])==null?void 0:f.value)||c.message,$sentry_exception_type:(g=b[0])==null?void 0:g.type,$sentry_tags:c.tags};return r&&n&&(I.$sentry_url=(i||"https://sentry.io/organizations/")+r+"/issues/?project="+n+"&query="+c.event_id),u&&((_=t.exceptions)==null||_.sendExceptionEvent(I)),c}}class kp{constructor(e,s,r,n,i,o){this.name=Au,this.setupOnce=function(a){a($u(e,{organization:s,projectId:r,prefix:n,severityAllowList:i,sendExceptionsToPostHog:o==null||o}))}}}class fl{constructor(e){this.li=(s,r,n)=>{n&&(n.noSessionId||n.activityTimeout||n.sessionPastMaximumLength||n.crossTabAdoption)&&(k.info("[PageViewManager] Session rotated, clearing pageview state",{sessionId:s,changeReason:n}),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,s){var r,n=this.vi(e,s);return this.ui={pathname:(r=v?.location.pathname)!==null&&r!==void 0?r:"",pageViewId:s,timestamp:e},this._instance.scrollManager.resetContext(),n}doPageLeave(e){var s;return this.vi(e,(s=this.ui)==null?void 0:s.pageViewId)}doEvent(){var e;return{$pageview_id:(e=this.ui)==null?void 0:e.pageViewId}}vi(e,s){var r=this.ui;if(!r)return{$pageview_id:s};var n={$pageview_id:s,$prev_pageview_id:r.pageViewId},i=this._instance.scrollManager.getContext();if(i&&!this._instance.config.disable_scroll_properties){var o=i.maxScrollHeight,a=i.lastScrollY,l=i.maxScrollY,u=i.maxContentHeight,c=i.lastContentY,d=i.maxContentY;if(!(x(o)||x(a)||x(l)||x(u)||x(c)||x(d))){o=Math.ceil(o),a=Math.ceil(a),l=Math.ceil(l),u=Math.ceil(u),c=Math.ceil(c),d=Math.ceil(d);var h=o>1?rt(a/o,0,1,k):1,p=o>1?rt(l/o,0,1,k):1,f=u>1?rt(c/u,0,1,k):1,g=u>1?rt(d/u,0,1,k):1;n=ee(n,{$prev_pageview_last_scroll:a,$prev_pageview_last_scroll_percentage:h,$prev_pageview_max_scroll:l,$prev_pageview_max_scroll_percentage:p,$prev_pageview_last_content:c,$prev_pageview_last_content_percentage:f,$prev_pageview_max_content:d,$prev_pageview_max_content_percentage:g})}}return r.pathname&&(n.$prev_pageview_pathname=r.pathname),r.timestamp&&(n.$prev_pageview_duration=(e.getTime()-r.timestamp.getTime())/1e3),n}}var ci=["flags","surveys"],Ip={[au]:{exposure:"hidden"},[Bs]:{exposure:"hidden"},__cmpns:{exposure:"hidden"},[js]:{exposure:"hidden"},[Ui]:{exposure:"event"},[Hi]:{exposure:"hidden"},[Wi]:{exposure:"event"},[zi]:{exposure:"hidden"},[qi]:{exposure:"event"},[Vi]:{exposure:"event"},[Ho]:{exposure:"event"},[Wo]:{exposure:"hidden"},[Gi]:{exposure:"event"},[qt]:{exposure:"hidden"},$session_recording_enabled_server_side:{exposure:"hidden"},[ls]:{exposure:"hidden"},[zo]:{exposure:"event"},[lu]:{exposure:"event",shouldSkipFromEventProperties:t=>$e(t)},$session_past_minimum_duration:{exposure:"event"},$session_recording_url_trigger_activated_session:{exposure:"event"},$session_recording_event_trigger_activated_session:{exposure:"event"},$debug_first_full_snapshot_timestamp:{exposure:"event"},$sess_rec_flush_size:{exposure:"hidden"},[Bt]:{exposure:"hidden",storageGroup:"flags"},[Us]:{exposure:"hidden",storageGroup:"flags"},[Rr]:{exposure:"hidden"},[Ki]:{exposure:"hidden",storageGroup:"flags"},[Hs]:{exposure:"hidden",storageGroup:"flags"},[Tr]:{exposure:"hidden",storageGroup:"flags",volatile:!0},[en]:{exposure:"hidden",storageGroup:"flags"},[et]:{exposure:"hidden"},[jt]:{exposure:"hidden"},[ct]:{exposure:"hidden"},[Ut]:{exposure:"hidden"},[Ji]:{exposure:"hidden",storageGroup:"surveys"},[tn]:{exposure:"hidden",storageGroup:"surveys",volatile:!0},[Yi]:{exposure:"event"},[Nr]:{exposure:"hidden"},[Mr]:{exposure:"hidden"},[Ws]:{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"},[Wt]:{exposure:"hidden"},[zs]:{exposure:"hidden"},[Lr]:{exposure:"hidden"},[Gs]:{exposure:"hidden",storageGroup:"flags",volatile:!0},[He]:{exposure:"hidden"},[Zi]:{exposure:"hidden"},[Xi]:{exposure:"hidden"},[Qi]:{exposure:"hidden"},[eo]:{exposure:"hidden"},[sn]:{exposure:"hidden"},[rn]:{exposure:"hidden"},[cu]:{exposure:"event"},[uu]:{exposure:"event"},[du]:{exposure:"event"},[hu]:{exposure:"event"},[fu]:{exposure:"event"},[gu]:{exposure:"event"},[mu]:{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"}},Cp=[["$posthog_sr_group_event_trigger_",{exposure:"hidden"}],["$posthog_sr_group_url_trigger_",{exposure:"hidden"}],["$posthog_sr_group_sampling_",{exposure:"hidden"}]],Mt=t=>{var e=Ip[t];if(e)return e;for(var s of Cp){var r=s[1];if(t.indexOf(s[0])===0)return r}},cs=(t,e)=>{try{return JSON.stringify(t,((s,r)=>typeof r=="bigint"?r.toString():r),e)}catch{return Fc(t)}},cn=t=>{var e=C?.createElement("a");return x(e)?null:(e.href=t,e)},ms=function(t,e){for(var s,r=((t.split("#")[0]||"").split(/\?(.*)/)[1]||"").replace(/^\?+/g,"").split("&"),n=0;r.length>n;n++){var i=r[n].split("=");if(i[0]===e){s=i;break}}if(!L(s)||2>s.length)return"";var o=s[1];try{o=decodeURIComponent(o)}catch{k.error("Skipping decoding for malformed query param: "+o)}return o.replace(/\+/g," ")},nr=function(t,e,s){if(!t||!e||!e.length)return t;for(var r=t.split("#"),n=r[1],i=(r[0]||"").split("?"),o=i[1],a=i[0],l=(o||"").split("&"),u=[],c=0;l.length>c;c++){var d=l[c].split("=");L(d)&&(e.includes(d[0])?u.push(d[0]+"="+s):u.push(l[c]))}var h=a;return o!=null&&(h+="?"+u.join("&")),n!=null&&(h+="#"+n),h},un=function(t,e){var s=t.match(new RegExp(e+"=([^&]*)"));return s?s[1]:null},Ru=(t,e)=>t>=e&&kc(),Tu=(t,e,s,r)=>{if(t===0){if(kc()){var n=e+1;return n===s&&r(),n}return e}return 0},kr="https?://(.*)",vs=["gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","irclid","_kx"],Fp=["utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid",...vs],ir="",Pp=["li_fat_id"];function Nu(t,e,s){if(!C)return{};var r,n=e?[...vs,...s||[]]:[],i=Mu(nr(C.URL,n,ir),t),o=(r={},Z(Pp,(function(a){var l=vu(a);r[a]=l||null})),r);return ee(o,i)}function Mu(t,e){var s=Fp.concat(e||[]),r={};return Z(s,(function(n){var i=ms(t,n);r[n]=i||null})),r}function Lu(t){var e=(function(i){return i?i.search(kr+"google.([^/?]*)")===0?"google":i.search(kr+"bing.com")===0?"bing":i.search(kr+"yahoo.com")===0?"yahoo":i.search(kr+"duckduckgo.com")===0?"duckduckgo":null:null})(t),s=e!="yahoo"?"q":"p",r={};if(!$e(e)){r.$search_engine=e;var n=C?ms(C.referrer,s):"";n.length&&(r.ph_keyword=n)}return r}function gl(){return navigator.language||navigator.userLanguage}var dn="$direct";function Ou(){return C?.referrer||dn}function Du(t,e,s){s===void 0&&(s=!1);var r=t?[...vs,...e||[]]:[],n=s?Ct(re?.href):re?.href,i=n?.substring(0,1e3);return{r:Ou().substring(0,1e3),u:i?nr(i,r,ir):void 0}}function Bu(t,e){var s;e===void 0&&(e=!1);var r=t.r,n=t.u,i=e?Ct(n):n,o={$referrer:r,$referring_domain:r==null?void 0:r==dn?dn:(s=cn(r))==null?void 0:s.host};if(i){o.$current_url=i;var a=cn(i);o.$host=a?.host,o.$pathname=a?.pathname;var l=Mu(i);ee(o,l)}if(r){var u=Lu(r);ee(o,u)}return o}function ju(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return}}function Ap(){try{return new Date().getTimezoneOffset()}catch{return}}var $p={flags:Gs,surveys:tn},Rp=["cookie","localstorage","localstorage+cookie","sessionstorage","memory"],ts="main";class ui{constructor(e,s,r){if(r===void 0&&(r=!0),this.ci={},this.fi=!1,this.pi=!1,this.Ne=e,this.gi=r,this.props={},this.mi=void 0,this.yi=(i=>{var o="";return i.token&&(o=i.token.replace(/\+/g,"PL").replace(/\//g,"SL").replace(/=/g,"EQ")),i.persistence_name?"ph_"+i.persistence_name:"ph_"+o+"_posthog"})(e),this.ii=this.bi(e),this.pi=this.wi(e),this.load(),e.debug&&k.info("Persistence loaded",e.persistence,w({},this.props)),this.update_config(e,e,s),this.save(),v){var n=()=>this.flush();ne(v,"beforeunload",n,{capture:!1}),ne(v,"pagehide",n,{capture:!1})}}ki(){var e,s=(e=this.Ne)==null?void 0:e.persistence_save_debounce_ms;return he(s)&&s>0?s:0}isDisabled(){return!!this.xi}bi(e){Rp.indexOf(e.persistence.toLowerCase())===-1&&(k.critical("Unknown persistence type "+e.persistence+"; falling back to localStorage+cookie"),e.persistence="localStorage+cookie");var s,r=(function(o,a){o===void 0&&(o=[]),a===void 0&&(a=!1);var l=[...up,...o];return w({},Q,{H(u){try{var c={};try{c=pt.H(u)||{}}catch{}var d,h=JSON.parse(Q.P(u)||"{}");if(a){var p={};for(var f in c){var g=c[f];$e(g)||g===""||(p[f]=g)}d=ee(h,p)}else d=ee(c,h);return Q.F(u,d),d}catch{}return null},F(u,c,d,h,p,f){var g=Q.F(u,c,void 0,void 0,f);try{var m={};l.forEach((_=>{c[_]&&(m[_]=c[_])})),Object.keys(m).length&&pt.F(u,m,d,h,p,f)}catch(_){Q.j(_)}return g},q(u,c){try{v?.localStorage.removeItem(u),pt.q(u,c)}catch(d){Q.j(d)}}})})(e.cookie_persisted_properties||[],e.__preview_cookie_wins_on_conflict||!1),n=!1,i=e.persistence.toLowerCase();return i==="localstorage"&&Q.N()?(s=Q,n=!0):i==="localstorage+cookie"&&r.N()?(s=r,n=!0):i==="sessionstorage"&&ce.N()?s=ce:i==="memory"?s=dp:i==="cookie"?s=pt:r.N()?(s=r,n=!0):s=pt,this.fi=n,s}Si(e){return this.yi+"__"+e}wi(e){return this.fi&&!!e.split_storage}properties(){var e={};return Z(this.props,((s,r)=>{var n=Mt(r);if(!n||n.exposure==="event"){if(n!=null&&n.shouldSkipFromEventProperties!=null&&n.shouldSkipFromEventProperties(s))return;e[r]=s}})),e}load(){if(!this.xi){var e=this.ii.H(this.yi);e&&(this.props=ee({},e)),this.pi&&this.Ci()}}Ci(){for(var e of ci){var s=Q.H(this.Si(e));if(s&&!mt(s)){var r=this.Mi(e);r.persisted=!0,this.Ti(e)||(r.fingerprint=this.Ei(s,e)),this.Ii(e,s)||ee(this.props,s)}}}Ti(e){return Object.keys(this.props).some((s=>{var r;return((r=Mt(s))==null?void 0:r.storageGroup)===e}))}Ii(e,s){var r=$p[e];if(!r)return!1;var n=s[r],i=this.props[r];return he(n)&&he(i)&&i>n}refreshKey(e){var s;if(!this.xi){var r=this.pi?(s=Mt(e))==null?void 0:s.storageGroup:void 0,n=r?Q.H(this.Si(r)):this.ii.H(this.yi);if(n&&e in n)this.Pi(e,n[e]);else{if(r){var i=this.ii.H(this.yi);if(i&&e in i)return void this.Pi(e,i[e])}this.Ri(e)}}}save(){if(!this.xi){var e=this.ki();e>0?x(this.Ai)&&(this.Ai=setTimeout((()=>{this.Ai=void 0,this.Fi()}),e)):this.Fi()}}flush(){x(this.Ai)||(clearTimeout(this.Ai),this.Ai=void 0,this.Fi())}Fi(){this.xi||(this.pi?this.Li():this.Oi(this.ii,this.yi,this.props,ts))}Li(){var e=this.Di(),s=e.main,r=e.groups;for(var n of(this.Oi(this.ii,this.yi,s,ts),ci)){var i,o=r[n];(!mt(o)||(i=this.ci[n])!=null&&i.persisted)&&this.Oi(Q,this.Si(n),o,n)}}Di(){var e={},s={flags:{},surveys:{}};return Z(this.props,((r,n)=>{var i,o=(i=Mt(n))==null?void 0:i.storageGroup;o?s[o][n]=r:e[n]=r})),{main:e,groups:s}}Ei(e,s){if(s===ts)return JSON.stringify(e)+"|"+this.$i+"|"+this.Ni+"|"+this.qi;var r={};return Z(e,((n,i)=>{var o;r[i]=(o=Mt(i))!=null&&o.volatile?"__volatile__":n})),JSON.stringify(r)}Oi(e,s,r,n){var i=this.Mi(n);if(n===ts||i.dirty||x(i.fingerprint)){var o;try{if((o=this.Ei(r,n))===i.fingerprint)return void(i.dirty=!1)}catch{o=void 0}e.F(s,r,this.$i,this.Ni,this.qi,this.Ne.debug)?(i.dirty=!1,n!==ts&&(i.persisted=!0),x(o)||(i.fingerprint=o)):this.Ne.debug&&k.warn('failed to persist storage entry "'+s+'"; will retry on next save')}}remove(e){var s=(e===void 0?{}:e).keepGroupEntries,r=s!==void 0&&s;if(x(this.Ai)||(clearTimeout(this.Ai),this.Ai=void 0),this.ii.q(this.yi,!1),this.ii.q(this.yi,!0),!r&&this.gi)for(var n of ci)Q.q(this.Si(n));r?delete this.ci[ts]:this.ci={}}clear(){this.remove(),this.props={}}register_once(e,s,r){if(te(e)){x(s)&&(s="None"),this.$i=x(r)?this.ji:r;var n=!1;if(Z(e,((i,o)=>{this.props.hasOwnProperty(o)&&this.props[o]!==s||(this.Pi(o,i),n=!0)})),n)return this.save(),!0}return!1}register(e,s){if(te(e)){this.$i=x(s)?this.ji:s;var r=!1;if(Z(e,((n,i)=>{e.hasOwnProperty(i)&&(this.props[i]!==n||te(n)||L(n))&&(this.Pi(i,n),r=!0)})),r)return this.save(),!0}return!1}unregister(e){var s=typeof e=="string"?[e]:e,r=!1;for(var n of s)n in this.props&&(this.Ri(n),r=!0);r&&this.save()}update_campaign_params(){var e=C?.URL;if(e!==this.mi){var s=Nu(this.Ne.custom_campaign_params,this.Ne.mask_personal_data_properties,this.Ne.custom_personal_data_properties);mt(Vo(s))||this.register(s),this.mi=e}}update_search_keyword(){var e;this.register((e=C?.referrer)?Lu(e):{})}update_referrer_info(){var e;this.register_once({$referrer:Ou(),$referring_domain:C!=null&&C.referrer&&((e=cn(C.referrer))==null?void 0:e.host)||dn},void 0)}set_initial_person_info(){this.props[Qi]||this.props[eo]||this.register_once({[sn]:Du(this.Ne.mask_personal_data_properties,this.Ne.custom_personal_data_properties,this.Ne.disable_capture_url_hashes)},void 0)}get_initial_props(){var e={};Z([eo,Qi],(n=>{var i=this.props[n];i&&Z(i,(function(o,a){e["$initial_"+Ni(a)]=o}))}));var s=this.props[sn];if(s){var r=(function(n,i){i===void 0&&(i=!1);var o=Bu(n,i),a={};return Z(o,(function(l,u){a["$initial_"+Ni(u)]=l})),a})(s,this.Ne.disable_capture_url_hashes);ee(e,r)}return e}safe_merge(e){return Z(this.props,(function(s,r){r in e||(e[r]=s)})),e}update_config(e,s,r){this.ji=this.$i=e.cookie_expiration,this.set_disabled(e.disable_persistence||!!r),this.set_cross_subdomain(e.cross_subdomain_cookie),this.set_secure(e.secure_cookie);var n=e.persistence!==s.persistence||!((l,u)=>{if(l.length!==u.length)return!1;var c=[...l].sort(),d=[...u].sort();return c.every(((h,p)=>h===d[p]))})(e.cookie_persisted_properties||[],s.cookie_persisted_properties||[]),i=n?this.bi(e):this.ii,o=this.wi(e);if(n||o!==this.pi){var a=this.props;this.clear(),this.ii=i,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,s){var r=this.props[js]||{};r[e]=s,this.Pi(js,r),this.save()}remove_event_timer(e){var s=this.props[js]||{},r=s[e];return x(r)||(delete s[e],this.Pi(js,s),this.save()),r}get_property(e){return this.props[e]}set_property(e,s){this.Pi(e,s),this.save()}Pi(e,s){var r;this.props[e]=s,(r=Mt(e))!=null&&r.volatile||this.Bi(e)}Ri(e){delete this.props[e],this.Bi(e)}Bi(e){var s,r=(s=Mt(e))==null?void 0:s.storageGroup;r&&(this.Mi(r).dirty=!0)}Mi(e){return this.ci[e]||(this.ci[e]={})}}function Ir(t){var e=!0;return{dispose(){if(e){e=!1;var s=t();s&&Se(s.then)&&s.then(void 0,(()=>{}))}}}}var xe={GZipJS:"gzip-js",Base64:"base64"},As={Activation:"events",Cancellation:"cancelEvents"},di={Popover:"popover",API:"api",Widget:"widget"},ft={SHOWN:"survey shown",DISMISSED:"survey dismissed",SENT:"survey sent"},hi={SURVEY_ID:"$survey_id",SURVEY_ITERATION:"$survey_iteration",SURVEY_LAST_SEEN_DATE:"$survey_last_seen_date"},io={Popover:"popover",Inline:"inline"},Tp={SHOWN:"product tour shown"},ml={TOUR_LAST_SEEN_DATE:"$product_tour_last_seen_date",TOUR_TYPE:"$product_tour_type"},vl=se("[RateLimiter]");class Np{constructor(e){this.serverLimits={},this.lastEventRateLimited=!1,this.checkForLimiting=s=>{var r=s.text;if(r&&r.length)try{(JSON.parse(r).quota_limited||[]).forEach((n=>{vl.info((n||"events")+" is quota limited."),this.serverLimits[n]=new Date().getTime()+6e4}))}catch(n){return void vl.warn('could not rate limit - continuing. Error: "'+n?.message+'"',{text:r})}},this.instance=e,this.lastEventRateLimited=this.clientRateLimitContext(!0).isRateLimited}get captureEventsPerSecond(){var e;return((e=this.instance.config.rate_limiting)==null?void 0:e.events_per_second)||10}get captureEventsBurstLimit(){var e;return Math.max(((e=this.instance.config.rate_limiting)==null?void 0:e.events_burst_limit)||10*this.captureEventsPerSecond,this.captureEventsPerSecond)}clientRateLimitContext(e){var s,r,n;e===void 0&&(e=!1);var i=this.captureEventsBurstLimit,o=this.captureEventsPerSecond,a=new Date().getTime(),l=(s=(r=this.instance.persistence)==null?void 0:r.get_property(Xi))!==null&&s!==void 0?s:{tokens:i,last:a};l.tokens+=(a-l.last)/1e3*o,l.last=a,l.tokens>i&&(l.tokens=i);var u=1>l.tokens;if(u||e||(l.tokens=Math.max(0,l.tokens-1)),u&&!e){var c=(he(l.dropped)?l.dropped:0)+1;l.dropped=c,!this.lastEventRateLimited&&this.Hi(c)&&(l.dropped=0)}return this.lastEventRateLimited=u,(n=this.instance.persistence)==null||n.set_property(Xi,l),{isRateLimited:u,remainingTokens:l.tokens}}Ui(e){var s=this.instance.config.property_denylist;return!L(s)||!s.includes(e)}zi(){var e;if(this.Ui("$current_url")&&this.Ui("$pathname")&&re!=null&&re.pathname)return""+((e=re.origin)!==null&&e!==void 0?e:"")+re.pathname}Hi(e){var s,r,n=this.captureEventsBurstLimit,i=this.captureEventsPerSecond,o=this.zi(),a=this.Ui("$session_id")?(s=(r=this.instance).get_session_id)==null?void 0:s.call(r):void 0,l=[e+" event(s) dropped since the last warning",o?"triggered on "+o:void 0,a?"session "+a:void 0].filter(Boolean).join(", ");return!!this.instance.capture("$$client_ingestion_warning",{$$client_ingestion_warning_message:"posthog-js client rate limited: "+l+". Config is set to "+i+" events per second and "+n+" events burst limit."},{skip_client_rate_limiting:!0})}isServerRateLimited(e){var s=this.serverLimits[e||"events"]||!1;return s!==!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 xt.info("Using preloaded remote config",this.remoteConfig),this.Zi(this.remoteConfig),void this.Gi();if(this._instance.Qi())return void xt.warn("Remote config is disabled. Falling back to local config.");this.Wi((e=>{if(!e)return xt.info("No config found after loading remote JS config. Falling back to JSON."),void this.Vi((s=>{this.Zi(s.json,s),this.Gi()}));this.Zi(e),this.Gi()}))}catch(e){xt.error("Error loading remote config",e),this.Zi()}}stop(){this.Ki&&(clearInterval(this.Ki),this.Ki=void 0)}refresh(){!this._instance.Qi()&&C&&C.visibilityState!=="hidden"&&this._instance.reloadFeatureFlags()}Gi(){var e;if(!this.Ki){var s=(e=this._instance.config.remote_config_refresh_interval_ms)!==null&&e!==void 0?e:3e5;s!==0&&(this.Ki=setInterval((()=>{this.refresh()}),s))}}Zi(e,s){!e&&s&&(s.statusCode===0?s.error||xt.warn("Failed to fetch remote config from PostHog."):xt.error("Failed to fetch remote config from PostHog."));try{this._instance.Zi(e?{ok:!0,config:e}:{ok:!1})}catch(n){xt.error("Error applying remote config",n)}if(e?.hasFeatureFlags!==!1&&!this._instance.config.advanced_disable_feature_flags_on_first_load)try{var r;(r=this._instance.featureFlags)==null||r.ensureFlagsLoaded()}catch(n){xt.error("Error loading feature flags",n)}}}var qe=Uint8Array,Ae=Uint16Array,_s=Uint32Array,Yo=new qe([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),Zo=new qe([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),_l=new qe([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Hu=function(t,e){for(var s=new Ae(31),r=0;31>r;++r)s[r]=e+=1<r;++r)for(var i=s[r];s[r+1]>i;++i)n[i]=i-s[r]<<5|r;return[s,n]},Wu=Hu(Yo,2),oo=Wu[1];Wu[0][28]=258,oo[258]=28;for(var yl=Hu(Zo,0)[1],zu=new Ae(32768),ie=0;32768>ie;++ie){var ss=(43690&ie)>>>1|(21845&ie)<<1;zu[ie]=((65280&(ss=(61680&(ss=(52428&ss)>>>2|(13107&ss)<<2))>>>4|(3855&ss)<<4))>>>8|(255&ss)<<8)>>>1}var Js=function(t,e,s){for(var r=t.length,n=0,i=new Ae(e);r>n;++n)++i[t[n]-1];var o,a=new Ae(e);for(n=0;e>n;++n)a[n]=a[n-1]+i[n-1]<<1;for(o=new Ae(r),n=0;r>n;++n)o[n]=zu[a[t[n]-1]++]>>>15-t[n];return o},Kt=new qe(288);for(ie=0;144>ie;++ie)Kt[ie]=8;for(ie=144;256>ie;++ie)Kt[ie]=9;for(ie=256;280>ie;++ie)Kt[ie]=7;for(ie=280;288>ie;++ie)Kt[ie]=8;var hn=new qe(32);for(ie=0;32>ie;++ie)hn[ie]=5;var Mp=Js(Kt,9),Lp=Js(hn,5),qu=function(t){return(t/8>>0)+(7&t&&1)},Vu=function(t,e,s){(s==null||s>t.length)&&(s=t.length);var r=new(t instanceof Ae?Ae:t instanceof _s?_s:qe)(s-e);return r.set(t.subarray(e,s)),r},ot=function(t,e,s){var r=e/8>>0;t[r]|=s<<=7&e,t[r+1]|=s>>>8},$s=function(t,e,s){var r=e/8>>0;t[r]|=s<<=7&e,t[r+1]|=s>>>8,t[r+2]|=s>>>16},pi=function(t,e){for(var s=[],r=0;t.length>r;++r)t[r]&&s.push({s:r,f:t[r]});var n=s.length,i=s.slice();if(!n)return[new qe(0),0];if(n==1){var o=new qe(s[0].s+1);return o[s[0].s]=1,[o,1]}s.sort((function(F,P){return F.f-P.f})),s.push({s:-1,f:25001});var a=s[0],l=s[1],u=0,c=1,d=2;for(s[0]={s:-1,f:a.f+l.f,l:a,r:l};c!=n-1;)a=s[s[d].f>s[u].f?u++:d++],l=s[u!=c&&s[d].f>s[u].f?u++:d++],s[c++]={s:-1,f:a.f+l.f,l:a,r:l};var h=i[0].s;for(r=1;n>r;++r)i[r].s>h&&(h=i[r].s);var p=new Ae(h+1),f=ao(s[c-1],p,0);if(f>e){r=0;var g=0,m=f-e,_=1<r;++r){var b=i[r].s;if(e>=p[b])break;g+=_-(1<>>=m;g>0;){var E=i[r].s;e>p[E]?g-=1<=0&&g;--r){var I=i[r].s;p[I]==e&&(--p[I],++g)}f=e}return[new qe(p),f]},ao=function(t,e,s){return t.s==-1?Math.max(ao(t.l,e,s+1),ao(t.r,e,s+1)):e[t.s]=s},wl=function(t){for(var e=t.length;e&&!t[--e];);for(var s=new Ae(++e),r=0,n=t[0],i=1,o=function(l){s[r++]=l},a=1;e>=a;++a)if(t[a]==n&&a!=e)++i;else{if(!n&&i>2){for(;i>138;i-=138)o(32754);i>2&&(o(i>10?i-11<<5|28690:i-3<<5|12305),i=0)}else if(i>3){for(o(n),--i;i>6;i-=6)o(8304);i>2&&(o(i-3<<5|8208),i=0)}for(;i--;)o(n);i=1,n=t[a]}return[s.subarray(0,r),e]},Rs=function(t,e){for(var s=0,r=0;e.length>r;++r)s+=t[r]*e[r];return s},lo=function(t,e,s){var r=s.length,n=qu(e+2);t[n]=255&r,t[n+1]=r>>>8,t[n+2]=255^t[n],t[n+3]=255^t[n+1];for(var i=0;r>i;++i)t[n+i+4]=s[i];return 8*(n+4+r)},bl=function(t,e,s,r,n,i,o,a,l,u,c){ot(e,c++,s),++n[256];for(var d=pi(n,15),h=d[0],p=d[1],f=pi(i,15),g=f[0],m=f[1],_=wl(h),b=_[0],E=_[1],I=wl(g),F=I[0],P=I[1],B=new Ae(19),S=0;b.length>S;++S)B[31&b[S]]++;for(S=0;F.length>S;++S)B[31&F[S]]++;for(var A=pi(B,7),R=A[0],N=A[1],T=19;T>4&&!R[_l[T-1]];--T);var O,J,z,H,oe=u+5<<3,pe=Rs(n,Kt)+Rs(i,hn)+o,Ie=Rs(n,h)+Rs(i,g)+o+14+3*T+Rs(B,R)+(2*B[16]+3*B[17]+7*B[18]);if(pe>=oe&&Ie>=oe)return lo(e,c,t.subarray(l,l+u));if(ot(e,c,1+(pe>Ie)),c+=2,pe>Ie){O=Js(h,p),J=h,z=Js(g,m),H=g;var _e=Js(R,N);for(ot(e,c,E-257),ot(e,c+5,P-1),ot(e,c+10,T-4),c+=14,S=0;T>S;++S)ot(e,c+3*S,R[_l[S]]);c+=3*T;for(var Ce=[b,F],Re=0;2>Re;++Re){var ae=Ce[Re];for(S=0;ae.length>S;++S)ot(e,c,_e[me=31&ae[S]]),c+=R[me],me>15&&(ot(e,c,ae[S]>>>5&127),c+=ae[S]>>>12)}}else O=Mp,J=Kt,z=Lp,H=hn;for(S=0;a>S;++S)if(r[S]>255){var me;$s(e,c,O[257+(me=r[S]>>>18&31)]),c+=J[me+257],me>7&&(ot(e,c,r[S]>>>23&31),c+=Yo[me]);var ge=31&r[S];$s(e,c,z[ge]),c+=H[ge],ge>3&&($s(e,c,r[S]>>>5&8191),c+=Zo[ge])}else $s(e,c,O[r[S]]),c+=J[r[S]];return $s(e,c,O[256]),c+J[256]},Op=new _s([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),Dp=(function(){for(var t=new _s(256),e=0;256>e;++e){for(var s=e,r=9;--r;)s=(1&s&&3988292384)^s>>>1;t[e]=s}return t})(),fi=function(t,e,s){for(;s;++e)t[e]=s,s>>>=8};function Bp(t,e){e===void 0&&(e={});var s=(function(){var d=4294967295;return{p(h){for(var p=d,f=0;h.length>f;++f)p=Dp[255&p^h[f]]^p>>>8;d=p},d(){return 4294967295^d}}})(),r=t.length;s.p(t);var n,i,o,a,l,u=(a=10+((n=e).filename&&n.filename.length+1||0),l=8,(function(d,h,p,f,g,m){var _=d.length,b=new qe(f+_+5*(1+Math.floor(_/7e3))+g),E=b.subarray(f,b.length-g),I=0;if(!h||8>_)for(var F=0;_>=F;F+=65535){var P=F+65535;_>P?I=lo(E,I,d.subarray(F,P)):(E[F]=!0,I=lo(E,I,d.subarray(F,_)))}else{for(var B=Op[h-1],S=B>>>13,A=8191&B,R=(1<F;++F){var me=z(F),ge=32767&F,Ye=T[me];if(N[ge]=Ye,T[me]=ge,F>=Re){var Rt=_-F;if((Ie>7e3||Ce>24576)&&Rt>423){I=bl(d,E,0,H,oe,pe,_e,Ce,ae,F-ae,I),Ce=Ie=_e=0,ae=F;for(var de=0;286>de;++de)oe[de]=0;for(de=0;30>de;++de)pe[de]=0}var Ve=2,St=0,ks=A,Be=ge-Ye&32767;if(Rt>2&&me==z(F-Be))for(var Fe=Math.min(S,Rt)-1,mr=Math.min(32767,F),vr=Math.min(258,Rt);mr>=Be&&--ks&&ge!=Ye;){if(d[F+Ve]==d[F+Ve-Be]){for(var je=0;vr>je&&d[F+je]==d[F+je-Be];++je);if(je>Ve){if(Ve=je,St=Be,je>Fe)break;var _r=Math.min(Be,je-2),Xt=0;for(de=0;_r>de;++de){var Qt=F-Be+de+32768&32767,Is=Qt-N[Qt]+32768&32767;Is>Xt&&(Xt=Is,Ye=Qt)}}}Be+=(ge=Ye)-(Ye=N[ge])+32768&32767}if(St){H[Ce++]=268435456|oo[Ve]<<18|yl[St];var Ta=31&oo[Ve],Na=31&yl[St];_e+=Yo[Ta]+Zo[Na],++oe[257+Ta],++pe[Na],Re=F+Ve,++Ie}else H[Ce++]=d[F],++oe[d[F]]}}I=bl(d,E,!0,H,oe,pe,_e,Ce,ae,F-ae,I)}return Vu(b,0,f+qu(I)+g)})(i=t,(o=e).level==null?6:o.level,o.mem==null?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(i.length)))):12+o.mem,a,l)),c=u.length;return(function(d,h){var p=h.filename;if(d[0]=31,d[1]=139,d[2]=8,d[8]=2>h.level?4:h.level==9?2:0,d[9]=3,h.mtime!=0&&fi(d,4,Math.floor(new Date(h.mtime||Date.now())/1e3)),p){d[3]=8;for(var f=0;p.length>=f;++f)d[f+10]=p.charCodeAt(f)}})(u,e),fi(u,c-8,s.d()),fi(u,c-4,r),u}var jp=!!$i||!!Mo,Gu="text/plain",Dr=!1,Ku=(t,e)=>{var s=t.split("#"),r=s[1],n=s[0].split("?"),i=n[0],o=n[1];if(!o)return t;var a=o.split("&").filter((l=>l.split("=")[0]!==e)).join("&");return i+(a?"?"+a:"")+(r?"#"+r:"")},$n=function(t,e,s){var r;s===void 0&&(s=!0);var n=t.split("?"),i=n[0],o=n[1],a=w({},e),l=(r=o?.split("&").map((c=>{var d,h=c.split("="),p=h[0],f=s&&(d=a[p])!==null&&d!==void 0?d:h[1];return delete a[p],p+"="+f})))!==null&&r!==void 0?r:[],u=(function(c,d){var h,p;d===void 0&&(d="&");var f=[];return Z(c,(function(g,m){x(g)||x(m)||m==="undefined"||(h=encodeURIComponent((_=>_ instanceof File)(g)?g.name:g.toString()),p=encodeURIComponent(m),f[f.length]=p+"="+h)})),f.join(d)})(a);return u&&l.push(u),l.length>0?i+"?"+l.join("&"):i},gi=t=>{if(t.Ji)return t.Ji;var e=t.data,s=t.compression;if(e){if(s===xe.GZipJS){var r=Bp((function(a,l){var u=a.length;if(typeof TextEncoder<"u")return new TextEncoder().encode(a);for(var c=new qe(a.length+(a.length>>>1)),d=0,h=function(m){c[d++]=m},p=0;u>p;++p){if(d+5>c.length){var f=new qe(d+8+(u-p<<1));f.set(c),c=f}var g=a.charCodeAt(p);128>g?h(g):2048>g?(h(192|g>>>6),h(128|63&g)):g>55295&&57344>g?(h(240|(g=65536+(1047552&g)|1023&a.charCodeAt(++p))>>>18),h(128|g>>>12&63),h(128|g>>>6&63),h(128|63&g)):(h(224|g>>>12),h(128|g>>>6&63),h(128|63&g))}return Vu(c,0,d)})(cs(e)),{mtime:0});return{contentType:Gu,body:r.buffer.slice(r.byteOffset,r.byteOffset+r.byteLength),estimatedSize:r.byteLength}}if(s===xe.Base64){var n=(function(a){return a&&btoa(encodeURIComponent(a).replace(/%([0-9A-F]{2})/g,((l,u)=>String.fromCharCode(parseInt(u,16)))))})(cs(e)),i=(a=>"data="+encodeURIComponent(typeof a=="string"?a:cs(a)))(n);return{contentType:"application/x-www-form-urlencoded",body:i,estimatedSize:new Blob([i]).size}}var o=cs(e);return{contentType:"application/json",body:o,estimatedSize:new Blob([o]).size}}},Ju=t=>{var e,s,r=()=>t.transport==="sendBeacon"?{url:$n(t.url,{compression:xe.Base64}),encodedBody:gi(w({},t,{compression:xe.Base64,Ji:void 0}))}:{url:Ku(t.url,"compression"),encodedBody:gi(w({},t,{compression:void 0,Ji:void 0}))};try{e=gi(t)}catch(n){if(Ua(t.compression,ms(t.url,"compression")))return k.error("Failed to gzip request body, sending uncompressed payload",n),r();throw n}return e&&Ua(t.compression,ms(t.url,"compression"))&&!((s=e.body)instanceof ArrayBuffer?Ri(new Uint8Array(s)):ArrayBuffer.isView(s)&&Ri(new Uint8Array(s.buffer,s.byteOffset,s.byteLength)))?(Dr=!0,r()):{url:t.url,encodedBody:e}},Yu=t=>{try{return Ju(t)}catch(e){return k.error(e),void(t.callback==null||t.callback({statusCode:0,error:e}))}},Up=(function(){var t=X((function*(e){var s=cs(e.data),r=yield(function(i,o,a){return Ti.apply(this,arguments)})(s,Y.DEBUG,{rethrow:!0});if(!r)return e;var n=yield r.arrayBuffer();return w({},e,{Ji:{contentType:Gu,body:n,estimatedSize:n.byteLength}})}));return function(e){return t.apply(this,arguments)}})(),Hp=/Failed to fetch|NetworkError|Load failed/i,Zu=t=>t?.name==="TypeError"&&Hp.test(t?.message||""),Xu=t=>{var e=Yu(t);if(e){var s=e.url,r=e.encodedBody,n=r??{},i=n.contentType,o=n.body,a=n.estimatedSize,l=new Headers;Z(t.headers,(function(f,g){l.append(g,f)})),i&&l.append("Content-Type",i);var u=null,c=!1;if(Ma){var d=new Ma;u={signal:d.signal,timeout:setTimeout((()=>{var f,g;c=!0,d.abort((f=t.timeout,(g=new Error("PostHog request timed out"+(f?" after "+f+"ms":""))).name="AbortError",g))}),t.timeout)}}var h=f=>{c&&f?.name==="AbortError"||Zu(f)?k.warn(f):k.error(f),t.callback==null||t.callback({statusCode:0,error:f})};try{var p;Mo(s,w({method:t?.method||"GET",headers:l,keepalive:t.method==="POST"&&!t.Yi&&52428.8>(a||0),body:o,signal:(p=u)==null?void 0:p.signal},t.fetchOptions)).then((f=>f.text().then((g=>{var m={statusCode:f.status,text:g};if(f.status===200)try{m.json=JSON.parse(g)}catch(_){k.error(_)}t.callback==null||t.callback(m)})))).catch(h).finally((()=>u?clearTimeout(u.timeout):null))}catch(f){u&&clearTimeout(u.timeout),h(f)}}},co=t=>{try{var e,s=Ju(t),r=s.url,n=s.encodedBody,i=n??{},o=i.body,a=i.estimatedSize;if(!o)return;var l=o instanceof Blob?o:new Blob([o],{type:i.contentType});if(ke.sendBeacon(r,l))return;var u=L(t.data)?t.data:(e=t.data)==null?void 0:e.batch;if(L(u)&&u.length>1&&(a??0)>16384){var c=Math.ceil(u.length/2),d=h=>L(t.data)?h:w({},t.data,{batch:h});return co(w({},t,{data:d(u.slice(0,c))})),void co(w({},t,{data:d(u.slice(c))}))}k.warn("Beacon of ~"+(a??0)+" bytes was rejected by the browser, falling back to fetch"),Xu(w({},t,{Yi:!0}))}catch(h){k.warn("Beacon send failed",h)}},El=(t,e,s,r)=>{var n=r==="query"?e==="POST"?"sent_at":"_":void 0;return $n(s===xe.GZipJS?Ku(t,"compression"):t,w({},n?{[n]:Date.now().toString()}:{},s===xe.GZipJS?{}:{compression:s}))},Br=[];Mo&&Br.push({transport:"fetch",method:Xu}),$i&&Br.push({transport:"XHR",method(t){var e=Yu(t);if(e){var s=new $i,r=e.encodedBody;s.open(t.method||"GET",e.url,!0);var n=r??{},i=n.contentType,o=n.body;Z(t.headers,(function(a,l){s.setRequestHeader(l,a)})),i&&s.setRequestHeader("Content-Type",i),t.timeout&&(s.timeout=t.timeout),s.onreadystatechange=()=>{if(s.readyState===4){var a={statusCode:s.status,text:s.responseText};if(s.status===200)try{a.json=JSON.parse(s.responseText)}catch{}t.callback==null||t.callback(a)}},s.send(o)}}}),ke!=null&&ke.sendBeacon&&Br.push({transport:"sendBeacon",method:co});var uo=3e3;class Wp{constructor(e,s){this.Xi=!0,this.tr=[],this.er=rt(s?.flush_interval_ms||uo,250,5e3,k.createLogger("flush interval"),uo),this.ir=e}enqueue(e){this.tr.push(e),this.rr||this.nr()}unload(){this.sr();var e=this.tr.length>0?this.ar():{},s=Object.values(e);[...s.filter((r=>r.url.indexOf("/e")===0)),...s.filter((r=>r.url.indexOf("/e")!==0))].map((r=>{this.lr(w({},r,{transport:"sendBeacon"}))}))}enable(){this.Xi=!1,this.nr()}nr(){var e=this;this.Xi||(this.rr=setTimeout((()=>{if(this.sr(),this.tr.length>0){var s=this.ar(),r=function(){var i=s[n],o=new Date().getTime();i.data&&L(i.data)&&Z(i.data,(a=>{a.offset=Math.abs(a.timestamp-o),delete a.timestamp})),e.lr(i)};for(var n in s)r()}}),this.er))}lr(e){try{this.ir(e)}catch(s){k.error(s)}}sr(){clearTimeout(this.rr),this.rr=void 0}ar(){var e={};return Z(this.tr,(s=>{var r,n=s,i=(n?n.batchKey:null)||n.url;x(e[i])&&(e[i]=w({},n,{data:[]})),(r=e[i].data)==null||r.push(n.data)})),this.tr=[],e}}var zp=["retriesPerformedSoFar"];class qp{constructor(e){this.ur=!1,this.hr=3e3,this.tr=[],this._instance=e,this.tr=[],this.dr=!0,!x(v)&&"onLine"in v.navigator&&(this.dr=v.navigator.onLine,this.vr=()=>{this.dr=!0,this.cr()},this.pr=()=>{this.dr=!1},ne(v,"online",this.vr),ne(v,"offline",this.pr))}get length(){return this.tr.length}retriableRequest(e){var s=e.retriesPerformedSoFar,r=Ic(e,zp);lt(s)&&(r.url=$n(r.url,{retry_count:s})),this._instance._send_request(w({},r,{callback:n=>{if(n.statusCode!==200&&(400>n.statusCode||n.statusCode>=500)){if((n.statusCode===0?3:10)>(s??0))return void this.At(w({retriesPerformedSoFar:s},r));n.statusCode===0&&k.warn("Request failed before receiving an HTTP response; this can happen due to network issues, CORS, browser blocking, or ad blockers. Stopped retrying after "+(s??0)+" retries.")}r.callback==null||r.callback(n)}}))}At(e){var s=e.retriesPerformedSoFar||0;e.retriesPerformedSoFar=s+1;var r=(function(o){var a=3e3*Math.pow(2,o),l=a/2,u=Math.min(18e5,a),c=Math.random()-.5;return Math.ceil(u+c*(u-l))})(s),n=Date.now()+r;this.tr.push({retryAt:n,requestOptions:e});var i="Enqueued failed request for retry in "+r;navigator.onLine||(i+=" (Browser is offline)"),k.warn(i),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(),s=[],r=this.tr.filter((i=>e>i.retryAt||(s.push(i),!1)));if(this.tr=s,r.length>0)for(var n of r)this.retriableRequest(n.requestOptions)}unload(){for(var e of(this.mr&&(clearTimeout(this.mr),this.mr=void 0),this.ur=!1,x(v)||(this.vr&&(v.removeEventListener("online",this.vr),this.vr=void 0),this.pr&&(v.removeEventListener("offline",this.pr),this.pr=void 0)),this.tr)){var s=e.requestOptions;try{this._instance._send_request(w({},s,{transport:"sendBeacon"}))}catch(r){k.error(r)}}this.tr=[]}}class Vp{constructor(e){this.yr=()=>{var s,r,n,i;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,(s=this.br.maxScrollY)!==null&&s!==void 0?s:0),this.br.maxScrollHeight=Math.max(l,(r=this.br.maxScrollHeight)!==null&&r!==void 0?r:0),this.br.lastContentY=u,this.br.maxContentY=Math.max(u,(n=this.br.maxContentY)!==null&&n!==void 0?n:0),this.br.maxContentHeight=Math.max(c,(i=this.br.maxContentHeight)!==null&&i!==void 0?i: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(){ne(v,"scroll",this.yr,{capture:!0}),ne(v,"scrollend",this.yr,{capture:!0}),ne(v,"resize",this.yr)}scrollElement(){if(!this._r)return v?.document.documentElement;var e=L(this._r)?this._r:[this._r];for(var s of e){var r=v?.document.querySelector(s);if(r)return r}}wr(e){var s=e==="y"?"scrollTop":"scrollLeft";if(this._r){var r=this.scrollElement();return r&&r[s]||0}return v?e==="y"?v.scrollY||v.pageYOffset||v.document.documentElement.scrollTop||0:v.scrollX||v.pageXOffset||v.document.documentElement.scrollLeft||0:0}scrollY(){return this.wr("y")}scrollX(){return this.wr("x")}}var Gp=t=>Du(t?.config.mask_personal_data_properties,t?.config.custom_personal_data_properties,t?.config.disable_capture_url_hashes);class Sl{constructor(e,s,r,n){this.kr=i=>{var o=this.Sr();if(!o||o.sessionId!==i){var a={sessionId:i,props:this.Cr(this._instance)};this.Mr.register({[Zi]:a})}},this._instance=e,this.Tr=s,this.Mr=r,this.Cr=n||Gp,this.Tr.onSessionId(this.kr)}Sr(){return this.Mr.props[Zi]}getSetOnceProps(){var e,s=(e=this.Sr())==null?void 0:e.props;return s?"r"in s?Bu(s,this._instance.config.disable_capture_url_hashes):{$referring_domain:s.referringDomain,$pathname:s.initialPathName,utm_source:s.utm_source,utm_campaign:s.utm_campaign,utm_medium:s.utm_medium,utm_content:s.utm_content,utm_term:s.utm_term}:{}}getSessionProps(){var e={};return Z(Vo(this.getSetOnceProps()),((s,r)=>{r==="$current_url"&&(r="url"),e["$session_entry_"+Ni(r)]=s})),e}}class Xo{on(e,s){return this.Er[e]||(this.Er[e]=[]),this.Er[e].push(s),()=>{this.Er[e]=this.Er[e].filter((r=>r!==s))}}emit(e,s){for(var r of this.Er[e]||[])r(s);for(var n of this.Er["*"]||[])n(e,s)}constructor(){this.Er={}}}var Ts=se("[SessionId]");class xl{on(e,s){return this.Ir.on(e,s)}constructor(e,s,r){var n;if(this.Pr=null,this.Rr=[],this.Ar=void 0,this.Fr=!1,this.Ir=new Xo,this.Lr=(u,c)=>!(!lt(u)||!lt(c))&&Math.abs(u-c)>this.sessionTimeoutMs,!e.persistence)throw new Error("SessionIdManager requires a PostHogPersistence instance");if(e.config.cookieless_mode===ht)throw new Error('SessionIdManager cannot be used with cookieless_mode="always"');this.Ne=e.config,this.Mr=e.persistence,this.Or=void 0,this.Dr=void 0,this._sessionStartTimestamp=null,this._sessionActivityTimestamp=null,this.$r=s||dt,this.Nr=r||dt;var i=this.Ne.persistence_name||this.Ne.token;if(this._sessionTimeoutMs=1e3*rt(this.Ne.session_idle_timeout_seconds||1800,60,36e3,Ts.createLogger("session_idle_timeout_seconds"),1800),e.register({$configured_session_timeout_ms:this._sessionTimeoutMs}),this.qr(),this.jr="ph_"+i+"_window_id",this.Br="ph_"+i+"_primary_window_exists",this.Hr()){var o=ce.H(this.jr),a=ce.H(this.Br);o&&!a?this.Or=o:ce.q(this.jr),ce.F(this.Br,!0)}if((n=this.Ne.bootstrap)!=null&&n.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){Ts.error("Invalid sessionID in bootstrap",u)}this.zr()}get sessionTimeoutMs(){return this._sessionTimeoutMs}onSessionId(e){return x(this.Rr)&&(this.Rr=[]),this.Rr.push(e),this.Dr&&e(this.Dr,this.Or),()=>{this.Rr=this.Rr.filter((s=>s!==e))}}Hr(){return this.Ne.persistence!=="memory"&&!this.Mr.xi&&ce.N()}Wr(e){e!==this.Or&&(this.Or=e,this.Hr()&&ce.F(this.jr,e))}Vr(){return this.Or?this.Or:this.Hr()?ce.H(this.jr):null}Zr(e){var s=this.Pr;return!$e(s)&&!$e(e)&&5e3>Math.abs(e-s)}Ur(e,s,r){var n=s!==this._sessionActivityTimestamp,i=!(e!==this.Dr||r!==this._sessionStartTimestamp);this._sessionStartTimestamp=r,this._sessionActivityTimestamp=s,this.Dr=e,i&&!n||i&&this.Zr(s)||(this.Pr=s,this.Mr.register({[ls]:[s,e,r]}))}Gr(){var e,s=(e=this.Ne)==null?void 0:e.persistence_save_debounce_ms;return lt(s)&&s>0}Qr(){this.Gr()?this.Mr.refreshKey(ls):(this.Mr.flush(),this.Mr.load())}Kr(){var e;if(!$e(this._sessionActivityTimestamp)&&this._sessionActivityTimestamp!==this.Pr){this.Qr();var s=this.Jr();s[1]===this.Dr&&s[2]===this._sessionStartTimestamp&&(this.Pr=this._sessionActivityTimestamp,this.Mr.register({[ls]:[this._sessionActivityTimestamp,(e=this.Dr)!==null&&e!==void 0?e:null,this._sessionStartTimestamp]}),this.Mr.flush())}}Yr(){var e=this.Jr()[0],s=lt(e)?e:0,r=lt(this._sessionActivityTimestamp)?this._sessionActivityTimestamp:0;return Math.max(s,r)}Xr(e){return this.Qr(),this.Lr(e,this.Yr())}Jr(){var e=this.Mr.props[ls];return L(e)&&e.length===2&&e.push(e[0]),e||[0,null,0]}resetSessionId(){this.Pr=null,clearTimeout(this.tn),this.tn=void 0,this.Ur(null,null,null)}destroy(){this.Fr=!0,this.Kr(),clearTimeout(this.tn),this.tn=void 0,this.Ar&&v&&(v.removeEventListener(on,this.Ar,{capture:!1}),this.Ar=void 0),this.Rr=[]}zr(){this.Ar=()=>{this.Kr(),this.Hr()&&ce.q(this.Br)},ne(v,on,this.Ar,{capture:!1})}checkAndGetSessionAndWindowId(e,s){if(e===void 0&&(e=!1),s===void 0&&(s=null),this.Ne.cookieless_mode===ht)throw new Error('checkAndGetSessionAndWindowId should not be called with cookieless_mode="always"');var r=s||new Date().getTime(),n=this.Jr(),i=n[1],o=n[2],a=this.Yr(),l=this.Vr(),u=lt(o)&&Math.abs(r-o)>864e5,c=!1,d=!1,h=!i,p=i,f=!h&&!e&&this.Lr(r,a);if(f){(f=this.Xr(r))||Ts.info("cross-tab refresh kept the session alive",{sessionId:i});var g=this.Jr();i=g[1],o=g[2]}h||f||u?(i=this.$r(),l=this.Nr(),Ts.info("new session ID generated",{sessionId:i,windowId:l,changeReason:{noSessionId:h,activityTimeout:f,sessionPastMaximumLength:u}}),o=r,c=!0):(l||(l=this.Nr(),c=!0),(d=i!==p)&&(Ts.info("adopted cross-tab session id",{sessionId:i,windowId:l}),c=!0));var m=lt(a)&&e&&!u?a:r,_=lt(o)?o:new Date().getTime();this.Wr(l),this.Ur(i,m,_),e||this.qr();var b={noSessionId:h,activityTimeout:f,sessionPastMaximumLength:u,crossTabAdoption:d};return c&&this.Rr.forEach((E=>E(i,l,b))),{sessionId:i,windowId:l,sessionStartTimestamp:_,changeReason:c?b:void 0,lastActivityTimestamp:a}}qr(){this.Fr||(clearTimeout(this.tn),this.tn=setTimeout((()=>{if(!this.Fr)if(this.Xr(new Date().getTime())){var e=this.Dr;this.resetSessionId(),this.Ir.emit("forcedIdleReset",{idleSessionId:e})}else this.qr()}),1.1*this.sessionTimeoutMs))}}var Qu=function(t,e){if(!t)return!1;var s=t.userAgent;if(s&&Wa(s,e))return!0;try{var r=t?.userAgentData;if(r!=null&&r.brands&&r.brands.some((n=>Wa(n?.brand,e))))return!0}catch{}return!!t.webdriver};function ed(){return(ed=X((function*(){var t=ke?.userAgentData;if(t!=null&&t.getHighEntropyValues)try{var e=yield t.getHighEntropyValues(["model"]),s=e?.model;return W(s)&&s.length>0?s:void 0}catch(r){return void k.info("Unable to resolve $device_model from userAgentData.getHighEntropyValues",r)}}))).apply(this,arguments)}var pn=function(t,e){if(!(function(s){try{new RegExp(s)}catch{return!1}return!0})(e))return!1;try{return new RegExp(e).test(t)}catch{return!1}};function mi(t,e,s){return cs({distinct_id:t,userPropertiesToSet:e,userPropertiesToSetOnce:s})}var td={exact:(t,e)=>e.some((s=>t.some((r=>s===r)))),is_not:(t,e)=>e.every((s=>t.every((r=>s!==r)))),regex:(t,e)=>e.some((s=>t.some((r=>pn(s,r))))),not_regex:(t,e)=>e.every((s=>t.every((r=>!pn(s,r))))),icontains:(t,e)=>e.map(Cr).some((s=>t.map(Cr).some((r=>s.includes(r))))),not_icontains:(t,e)=>e.map(Cr).every((s=>t.map(Cr).every((r=>!s.includes(r))))),gt:(t,e)=>e.some((s=>{var r=parseFloat(s);return!isNaN(r)&&t.some((n=>r>parseFloat(n)))})),lt:(t,e)=>e.some((s=>{var r=parseFloat(s);return!isNaN(r)&&t.some((n=>rt.toLowerCase();function sd(t,e){return!t||Object.entries(t).every((s=>{var r=s[1],n=e?.[s[0]];if(x(n)||$e(n))return!1;var i=[String(n)],o=td[r.operator];return!!o&&o(r.values,i)}))}var ho="custom",kl="i.posthog.com",Kp=/^\/static\//;class Jp{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,s=(e=this.instance.config.ui_host)==null?void 0:e.replace(/\/$/,"");return s||(s=this.apiHost.replace("."+kl,".posthog.com")),s==="https://app.posthog.com"?"https://us.posthog.com":s}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":ho),this.en[this.apiHost]}rn(e){if(Kp.test(e)){var s=this.instance.config.asset_host;if(typeof s=="string")return s.trim().replace(/\/$/,"")||void 0}}endpointFor(e,s){if(s===void 0&&(s=""),s&&(s=s[0]==="/"?s:"/"+s),e==="ui")return this.uiHost+s;if(e==="flags")return this.flagsApiHost+s;if(e==="assets"){var r=this.rn(s);if(r)return""+r+s}if(this.region===ho)return this.apiHost+s;var n=kl+s;switch(e){case"assets":return"https://"+this.region+"-assets."+n;case"api":return"https://"+this.region+"."+n}}}function rd(t){var e;return!((e=t.conditions)==null||(e=e.events)==null||(e=e.values)==null||!e.length)}var q=se("[Surveys]"),nd="seenSurvey_",id=t=>{try{var e=(s=>((r,n)=>""+nd+(function(i){return i.current_iteration&&i.current_iteration>0?i.id+"_"+i.current_iteration:i.id})(n))(0,s))(t);if(localStorage.getItem(e))return;localStorage.setItem(e,"true")}catch(s){q.error("Failed to persist survey seen state",s)}},Yp=[di.Popover,di.Widget,di.API],Zp={ignoreConditions:!1,ignoreDelay:!1,displayType:io.Popover},Xp=se("[PostHog ExternalIntegrations]"),Qp={intercom:"intercom-integration",crispChat:"crisp-chat-integration"};class ef{constructor(e){this._instance=e}ai(e,s){var r;(r=$.__PosthogExtensions__)==null||r.loadExternalDependency==null||r.loadExternalDependency(this._instance,e,(n=>{if(n)return Xp.error("failed to load script",n);s()}))}startIfEnabledOrStop(){var e=this,s=function(){var i,o,a,l=r[0],u=r[1];!u||(i=$.__PosthogExtensions__)!=null&&(i=i.integrations)!=null&&i[l]||e.ai(Qp[l],(()=>{var c;(c=$.__PosthogExtensions__)==null||(c=c.integrations)==null||(c=c[l])==null||c.start(e._instance)})),!u&&(o=$.__PosthogExtensions__)!=null&&(o=o.integrations)!=null&&o[l]&&((a=$.__PosthogExtensions__)==null||(a=a.integrations)==null||(a=a[l])==null||a.stop())};for(var r of Object.entries((n=this._instance.config.integrations)!==null&&n!==void 0?n:{})){var n;s()}}}class tf{constructor(e,s){this.rt=e,this.nn=s,this.sn=new Map,this.an=!1}add(e){var s=this;return X((function*(){if(s.an)throw new Error("Cannot add an extension to a disposed ExtensionRuntime");if(s.sn.has(e.name))throw new Error('Browser extension "'+e.name+'" is already registered');s.sn.set(e.name,e);try{var r=e.setup(s.nn);r&&(yield r)}catch(i){var n=s.sn.get(e.name)===e;n&&s.sn.delete(e.name),s.rt.error('Failed to set up browser extension "'+e.name+'"',i),n&&s.ln(e)}}))()}dispose(){if(!this.an){this.an=!0;var e=Array.from(this.sn.values()).reverse();for(var s of(this.sn.clear(),e))this.ln(s)}}ln(e){try{var s=e.dispose==null?void 0:e.dispose();s&&Se(s.then)&&s.then(void 0,(r=>{this.rt.error('Failed to dispose browser extension "'+e.name+'"',r)}))}catch(r){this.rt.error('Failed to dispose browser extension "'+e.name+'"',r)}}}class sf{constructor(e){this._instance=e}initialize(){}get(e){var s=this._instance.persistence;if(typeof e=="string")return s?.get_property(e);var r={};for(var n of e){var i=s?.get_property(n);x(i)||(r[n]=i)}return r}set(e,s){var r;(r=this._instance.persistence)==null||r.register(typeof e=="string"?{[e]:s}:e)}remove(e){var s;(s=this._instance.persistence)==null||s.unregister(e)}}var Il="extensionsRemoteConfig";class rf{constructor(e){this.an=!1,this.instance=e,this.rt=k,this.un=e.hn,this.kv=new sf(e),this.onEvent=s=>Ir(this.instance.on("eventCaptured",(r=>{try{s({event:r.event,properties:r.properties})}catch(n){this.rt.error("Browser extension event listener failed",n)}}))),this.onRemoteConfig=s=>{if(this.an)return Ir((()=>{}));var r=i=>{try{s(i)}catch(o){this.rt.error("Browser extension remote config listener failed",o)}},n=this.instance.dn.on(Il,r);return this.un&&r(this.un),Ir(n)},this.vn=new tf(k.createLogger("[BrowserExtensions]"),this)}get logger(){return this.rt}get distinctId(){return this.instance.get_distinct_id()}get anonymousId(){var e;return(e=this.instance.get_property(sr))!==null&&e!==void 0?e:this.distinctId}get deviceId(){var e=this.instance.get_property(sr);return typeof e=="string"?e:void 0}get library(){return{name:Y.LIB_NAME,version:Y.LIB_VERSION}}get initialPersonProperties(){var e,s;return(e=(s=this.instance.persistence)==null?void 0:s.get_initial_props())!==null&&e!==void 0?e:{}}get groups(){return this.instance.getGroups()}get session(){try{var e,s,r,n,i=(e=this.instance.sessionManager)==null?void 0:e.checkAndGetSessionAndWindowId(!0);return{sessionId:(s=i?.sessionId)!==null&&s!==void 0?s:"",windowId:(r=i?.windowId)!==null&&r!==void 0?r:"",sessionStartTimestamp:(n=i?.sessionStartTimestamp)!==null&&n!==void 0?n:0}}catch{return{sessionId:"",windowId:"",sessionStartTimestamp:0}}}get projectToken(){return this.instance.config.token}add(e){return this.vn.add(e)}capture(e,s,r){var n=this;return X((function*(){r?n.instance.capture(e,s,{timestamp:r.timestamp,uuid:r.uuid,$set:r.set,$set_once:r.setOnce}):n.instance.capture(e,s)}))()}registerDynamicEventProperties(e){return Ir(this.instance.cn(e))}handleRemoteConfig(e){this.an||(this.un=e,this.instance.dn.emit(Il,e))}sendRequest(e,s){var r=this;return X((function*(){var n;s===void 0&&(s={});var i=r.instance.requestRouter.endpointFor((n=s.target)!==null&&n!==void 0?n:"api",e),o={method:s.method,url:s.query?$n(i,s.query):i,data:s.body,headers:s.headers,timeout:s.timeoutMs,fireCallbackOnDrop:!0,transport:s.transport,compression:s.compression,timestampMode:s.sentAt};return s.transport==="sendBeacon"?(r.instance._send_request(o),{statusCode:202}):new Promise((a=>{o.callback=a,r.instance._send_request(o)}))}))()}dispose(){this.an||(this.an=!0,this.vn.dispose())}}var Ys={},vi=0,fn=()=>{},Cl='Consent opt in/out is not valid with cookieless_mode="always" and will be ignored',Ns="Surveys module not available",Fl="sanitize_properties is deprecated. Use before_send instead",od="Invalid value for property_denylist config: ",nf=["token","distinct_id",pu],os="posthog",ad=!jp&&Pe?.indexOf("MSIE")===-1&&Pe?.indexOf("Mozilla")===-1,_i=t=>{var e;return w({api_host:"https://us.i.posthog.com",flags_api_host:null,ui_host:null,asset_host:null,token:"",autocapture:!0,cross_subdomain_cookie:ip(C?.location),persistence:"localStorage+cookie",persistence_name:"",cookie_persisted_properties:[],loaded:fn,save_campaign_params:!0,custom_campaign_params:[],custom_blocked_useragents:[],save_referrer:!0,capture_pageleave:"if_capture_pageview",defaults:t??"unset",__preview_deferred_init_extensions:!1,__preview_external_dependency_versioned_paths:!1,__preview_cookie_wins_on_conflict:!1,debug:re&&W(re?.search)&&re.search.indexOf("__posthog_debug=true")!==-1||!1,cookie_expiration:365,upgrade:!1,disable_session_recording:!1,disable_persistence:!1,disable_web_experiments:!0,disable_surveys:!1,disable_surveys_automatic_display:!1,disable_conversations:!1,disable_product_tours:!1,disableDeviceModel:!1,disable_external_dependency_loading:!1,strict_script_versioning:!1,enable_recording_console_log:void 0,secure_cookie:(v==null||(e=v.location)==null?void 0:e.protocol)==="https:",ip:!1,opt_out_capturing_by_default:!1,opt_out_persistence_by_default:!1,opt_out_useragent_filter:!1,opt_out_capturing_persistence_type:"localStorage",consent_persistence_name:null,opt_out_capturing_cookie_prefix:null,opt_in_site_apps:!1,property_denylist:[],respect_dnt:!1,sanitize_properties:null,request_headers:{},request_batching:!0,properties_string_max_length:65535,mask_all_element_attributes:!1,mask_all_text:!1,mask_personal_data_properties:!1,custom_personal_data_properties:[],advanced_disable_flags:!1,advanced_disable_decide:!1,advanced_disable_feature_flags:!1,advanced_disable_feature_flags_on_first_load:!1,advanced_only_evaluate_survey_feature_flags:!1,advanced_feature_flags_dedup_per_session:!1,advanced_enable_surveys:!1,advanced_disable_toolbar_metrics:!1,feature_flag_request_timeout_ms:3e3,surveys_request_timeout_ms:1e4,on_request_error(s){k.error("Bad HTTP status: "+s.statusCode+" "+s.text)},get_device_id:s=>s,capture_performance:void 0,name:"posthog",bootstrap:{},disable_compression:!1,session_idle_timeout_seconds:1800,person_profiles:to,before_send:void 0,get_current_url:void 0,request_queue_config:{flush_interval_ms:uo},error_tracking:{},_onCapture:fn},(s=>({rageclick:s&&s>="2026-05-30"?{content_ignorelist:vp,ignore_text_selection:!0}:!s||"2025-11-30">s||{content_ignorelist:!0},capture_pageview:!s||"2025-05-24">s||"history_change",session_recording:s&&s>="2026-06-25"?{strictMinimumDuration:!0,canvasCapture:{resolutionScale:.6},streamNetworkBody:!0}:s&&s>="2026-05-30"?{strictMinimumDuration:!0,canvasCapture:{resolutionScale:.6}}:s&&s>="2025-11-30"?{strictMinimumDuration:!0}:{},external_scripts_inject_target:s&&s>="2026-01-30"?"head":"body",internal_or_test_user_hostname:s&&s>="2026-01-30"?/^(localhost|127\.0\.0\.1)$/:void 0,persistence_save_debounce_ms:s&&s>="2026-05-30"?250:0,split_storage:!(!s||"2026-05-30">s),detect_google_search_app:!(!s||"2026-05-30">s),disable_capture_url_hashes:!(!s||"2026-06-25">s)}))(t))},of=[["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"]],Pl=t=>{var e={};for(var s of of){var r=s[0],n=s[1];x(t[r])||(e[n]=t[r])}var i=ee({},e,t),o=t.__preview_external_dependency_versioned_paths;return x(o)||(x(t.strict_script_versioning)&&(i.strict_script_versioning=!!o),W(o)&&x(t.asset_host)&&(i.asset_host=o)),L(t.property_blacklist)&&(x(t.property_denylist)?i.property_denylist=t.property_blacklist:L(t.property_denylist)?i.property_denylist=[...t.property_blacklist,...t.property_denylist]:k.error(od+t.property_denylist)),i};class af{constructor(){this.__forceAllowLocalhost=!1}get fn(){return this.__forceAllowLocalhost}set fn(e){k.error("WebPerformanceObserver is deprecated and has no impact on network capture. Use `_forceAllowLocalhostNetworkCapture` on `posthog.sessionRecording`"),this.__forceAllowLocalhost=e}}class Te{pn(e,s){if(e){var r=this.sn.indexOf(e);r!==-1&&this.sn.splice(r,1)}return this.sn.push(s),s.initialize==null||s.initialize(),s}gn(){return this.config.cookieless_mode===ht||this.config.cookieless_mode===Ht&&this.consent.isRejected()}get decideEndpointWasHit(){var e,s;return(e=(s=this.featureFlags)==null?void 0:s.hasLoadedFlags)!==null&&e!==void 0&&e}get flagsEndpointWasHit(){var e,s;return(e=(s=this.featureFlags)==null?void 0:s.hasLoadedFlags)!==null&&e!==void 0&&e}constructor(){var e;this.webPerformance=new af,this.mn=!1,this.version=Y.LIB_VERSION,this.yn=new Set,this.bn="",this.dn=new Xo,this.sn=[],this._n=[],this._calculate_event_properties=this.calculateEventProperties.bind(this),this.config=_i(),this.SentryIntegration=kp,this.sentryIntegration=r=>(function(n,i){var o=$u(n,i);return{name:Au,processEvent:a=>o(a)}})(this,r),this.__request_queue=[],this.__loaded=!1,this.analyticsDefaultEndpoint="/e/",this.wn=!1,this.kn=null,this.xn=null,this.Sn=null,this.scrollManager=new Vp(this),this.pageViewManager=new fl(this),this.rateLimiter=new Np(this),this.requestRouter=new Jp(this),this.consent=new hp(this),this.externalIntegrations=new ef(this);var s=(e=Te.__defaultExtensionClasses)!==null&&e!==void 0?e:{};this.featureFlags=s.featureFlags&&new s.featureFlags(this),this.toolbar=s.toolbar&&new s.toolbar(this),this.surveys=s.surveys&&new s.surveys(this),this.conversations=s.conversations&&new s.conversations(this),this.logs=s.logs&&new s.logs(this),this.metrics=s.metrics&&new s.metrics(this),this.experiments=s.experiments&&new s.experiments(this),this.exceptions=s.exceptions&&new s.exceptions(this),this.people={set:(r,n,i)=>{var o=W(r)?{[r]:n}:r;this.setPersonProperties(o),i?.({})},set_once:(r,n,i)=>{var o=W(r)?{[r]:n}:r;this.setPersonProperties(void 0,o),i?.({})}},this.on("eventCaptured",(r=>k.info('send "'+r?.event+'"',r)))}init(e,s,r){if(r&&r!==os){var n,i=(n=Ys[r])!==null&&n!==void 0?n:new Te;return i._init(e,s,r),Ys[r]=i,Ys[os][r]=i,i}return this._init(e,s,r)}_init(e,s,r){var n,i;s===void 0&&(s={});var o,a=W(e)?e.trim():"";if(!a)return k.critical("PostHog was initialized without a token. This likely indicates a misconfiguration. Please check the first argument passed to posthog.init()"),this;if(this.__loaded)return a!==((o=this.config)==null?void 0:o.token)?console.warn("[PostHog.js]","You have already initialized PostHog with a different project token! Re-initializing is a no-op, so events will keep going to the project this instance was initialized with. To capture into a second project, load PostHog once, then initialize a named instance after the SDK has loaded, e.g. posthog.init('"+a+"', { ... }, 'project2')"):console.warn("[PostHog.js]","You have already initialized PostHog! Re-initializing is a no-op"),this;this.__loaded=!0,this.config=_i(s.defaults),s.debug=this.Cn(s.debug),this.Mn=s,this.Tn=[],s.person_profiles?this.xn=s.person_profiles:s.process_person&&(this.xn=s.process_person);var l=_i(s.defaults),u=Pl(s),c=ee({},l,u,{name:r,token:a});te(l.rageclick)&&te(u.rageclick)&&(c.rageclick=ee({},l.rageclick,u.rageclick)),te(l.session_recording)&&te(u.session_recording)&&(c.session_recording=ee({},l.session_recording,u.session_recording)),this.set_config(c),this.config.on_xhr_error&&k.error("on_xhr_error is deprecated. Use on_request_error instead"),this.compression=s.disable_compression?void 0:xe.GZipJS;var d=this.En();if(this.persistence=new ui(this.config,d),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new ui(w({},this.config,{persistence:"sessionStorage"}),d,!1),this.bn="ph_"+(this.config.persistence_name||this.config.token)+"_session_registered_properties",this.config.persistence!=="memory"&&!d&&ce.N()){var h=ce.H(this.bn);L(h)&&h.forEach((P=>{W(P)&&this.yn.add(P)}))}else ce.q(this.bn);var p=w({},this.persistence.props),f=w({},this.sessionPersistence.props);this.register({$initialization_time:new Date().toISOString()}),this.In=new Wp((P=>this.Pn(P)),this.config.request_queue_config),this.Rn=new qp(this),this.__request_queue=[];var g=this.gn();if(g||(this.sessionManager=new xl(this),this.sessionPropsManager=new Sl(this,this.sessionManager,this.persistence),this.sessionManager.onSessionId(((P,B,S)=>{(S!=null&&S.activityTimeout||S!=null&&S.sessionPastMaximumLength||S!=null&&S.crossTabAdoption)&&this.An()}))),this.Fn(),this.config.__preview_deferred_init_extensions?(k.info("Deferring extension initialization to improve startup performance"),setTimeout((()=>{this.Ln(g)}),0)):(k.info("Initializing extensions synchronously"),this.Ln(g)),Y.DEBUG=Y.DEBUG||this.config.debug,Y.DEBUG&&k.info("Starting in debug mode",{this:this,config:s,thisC:w({},this.config),p,s:f}),!this.config.identity_distinct_id||(n=s.bootstrap)!=null&&n.distinctID||(s.bootstrap=w({},s.bootstrap,{distinctID:this.config.identity_distinct_id,isIdentifiedID:!0})),((i=s.bootstrap)==null?void 0:i.distinctID)!==void 0){var m=s.bootstrap.distinctID,_=this.get_distinct_id(),b=this.persistence.get_property(He);if(s.bootstrap.isIdentifiedID&&_!=null&&_!==m&&b===es)this.identify(m);else if(s.bootstrap.isIdentifiedID&&_!=null&&_!==m&&b===Tt)k.warn("Bootstrap distinctID differs from an already-identified user. The existing identity is preserved. Call reset() before reinitializing if you intend to switch users.");else{var E=this.config.get_device_id(dt()),I=s.bootstrap.isIdentifiedID?E:m;this.persistence.set_property(He,s.bootstrap.isIdentifiedID?Tt:es),this.register({distinct_id:m,$device_id:I})}}if(g)this.register_once({distinct_id:br,$device_id:null},"");else if(!this.get_distinct_id()){var F=this.config.get_device_id(dt());this.register_once({distinct_id:F,$device_id:F},""),this.persistence.set_property(He,es)}return ne(v,"onpagehide"in self?"pagehide":"unload",this._handle_unload.bind(this),{passive:!1}),s.segment?(function(P,B){var S=P.config.segment;if(!S)return B();(function(A,R){var N=A.config.segment;if(!N)return R();var T=J=>{var z=()=>J.anonymousId()||dt();A.config.get_device_id=z,J.id()&&(A.register({distinct_id:J.id(),$device_id:z()}),A.persistence.set_property(He,Tt)),R()},O=N.user();"then"in O&&Se(O.then)?O.then(T):T(O)})(P,(()=>{S.register((A=>{typeof Promise<"u"&&Promise.resolve||li.warn("This browser does not have Promise support, and can not use the segment integration");var R=(N,T)=>{if(!T)return N;N.event.userId||N.event.anonymousId===A.get_distinct_id()||(li.info("No userId set, resetting PostHog"),A.reset()),N.event.userId&&N.event.userId!==A.get_distinct_id()&&(li.info("UserId set, identifying with PostHog"),A.identify(N.event.userId));var O=A.calculateEventProperties(T,N.event.properties);return N.event.properties=Object.assign({},O,N.event.properties),N};return{name:"PostHog JS",type:"enrichment",version:"1.0.0",isLoaded:()=>!0,load:()=>Promise.resolve(),track:N=>R(N,N.event.event),page:N=>R(N,is),identify:N=>R(N,ii),screen:N=>R(N,"$screen")}})(P)).then((()=>{B()}))}))})(this,(()=>this.On())):this.On(),Se(this.config._onCapture)&&this.config._onCapture!==fn&&(k.warn("onCapture is deprecated. Please use `before_send` instead"),this.on("eventCaptured",(P=>this.config._onCapture(P.event,P)))),this.config.ip&&k.warn('The `ip` config option has NO EFFECT AT ALL and has been deprecated. Use a custom transformation or "Discard IP data" project setting instead. See https://posthog.com/tutorials/web-redact-properties#hiding-customer-ip-address for more information.'),this.config.disableDeviceModel||(function(){return ed.apply(this,arguments)})().then((P=>{P&&this.register({[ri]:P})})).catch(fn),this}Fn(){var e,s,r,n,i,o,a=(e=(s=this.config.__extensionClasses)==null?void 0:s.featureFlags)!==null&&e!==void 0?e:(r=Te.__defaultExtensionClasses)==null?void 0:r.featureFlags;a&&(this.featureFlags&&this.featureFlags instanceof a||((n=this.Dn)==null||n.call(this),this.Dn=void 0,this.featureFlags=new a(this)),Se(this.featureFlags.onReloading)&&Se(this.featureFlags.setup)?this.Dn||(this.Dn=this.featureFlags.onReloading((()=>{this.dn.emit("featureFlagsReloading",!0)})),this.$n().add(this.featureFlags)):(i=(o=this.featureFlags).initialize)==null||i.call(o))}Ln(e){var s,r,n,i,o,a,l,u=performance.now(),c=w({},Te.__defaultExtensionClasses,this.config.__extensionClasses),d=[];c.exceptions&&this.sn.push(this.exceptions=(s=this.exceptions)!==null&&s!==void 0?s:new c.exceptions(this)),c.historyAutocapture&&this.sn.push(this.historyAutocapture=new c.historyAutocapture(this)),c.tracingHeaders&&this.sn.push(this.tracingHeaders=new c.tracingHeaders(this)),c.siteApps&&this.sn.push(this.siteApps=new c.siteApps(this)),c.sessionRecording&&!e&&this.sn.push(this.sessionRecording=new c.sessionRecording(this)),this.config.disable_scroll_properties||d.push((()=>{this.scrollManager.startMeasuringScrollPosition()})),c.autocapture&&this.sn.push(this.autocapture=new c.autocapture(this)),c.surveys&&this.sn.push(this.surveys=(r=this.surveys)!==null&&r!==void 0?r:new c.surveys(this)),c.logs&&this.sn.push(this.logs=(n=this.logs)!==null&&n!==void 0?n:new c.logs(this)),c.metrics&&this.sn.push(this.metrics=(i=this.metrics)!==null&&i!==void 0?i: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,xp)),c.toolbar&&this.sn.push(this.toolbar=(a=this.toolbar)!==null&&a!==void 0?a:new c.toolbar(this)),c.experiments&&this.sn.push(this.experiments=(l=this.experiments)!==null&&l!==void 0?l:new c.experiments(this)),this.sn.forEach((h=>{h.initialize&&d.push((()=>{h.initialize==null||h.initialize()}))})),d.push((()=>{if(this.Nn){var h=this.Nn;this.Nn=void 0,this.sn.forEach((p=>p.onRemoteConfig==null?void 0:p.onRemoteConfig(h)))}})),this.qn(d,u)}qn(e,s){for(;e.length>0;){if(this.config.__preview_deferred_init_extensions&&performance.now()-s>=30&&e.length>0)return void setTimeout((()=>{this.qn(e,s)}),0);var r=e.shift();if(r)try{r()}catch(i){k.error("Error initializing extension:",i)}}var n=Math.round(performance.now()-s);this.register_for_session({[fu]:this.config.__preview_deferred_init_extensions?"deferred":"synchronous",[gu]:n}),this.config.__preview_deferred_init_extensions&&k.info("PostHog extensions initialized ("+n+"ms)")}Zi(e){var s;if(!C||!C.body)return k.info("document not ready yet, trying again in 500 milliseconds..."),void setTimeout((()=>{this.Zi(e)}),500);if(this.config.__preview_deferred_init_extensions&&(this.Nn=e),this.hn=e,this.compression=void 0,e.ok){var r,n=e.config;n.supportedCompression&&!this.config.disable_compression&&(this.compression=M(n.supportedCompression,xe.GZipJS)?xe.GZipJS:M(n.supportedCompression,xe.Base64)?xe.Base64:void 0),(r=n.analytics)!=null&&r.endpoint&&(this.analyticsDefaultEndpoint=n.analytics.endpoint)}this.set_config({person_profiles:this.xn?this.xn:to}),(s=this.jn)==null||s.handleRemoteConfig(e),this.sn.forEach((i=>i.onRemoteConfig==null?void 0:i.onRemoteConfig(e)))}On(){try{this.config.loaded(this)}catch(r){k.critical("`loaded` function failed",r)}if(this.Bn(),this.config.internal_or_test_user_hostname&&re!=null&&re.hostname){var e=re.hostname,s=this.config.internal_or_test_user_hostname;(typeof s=="string"?e===s:s.test(e))&&this.setInternalOrTestUser()}this.config.capture_pageview&&setTimeout((()=>{(this.consent.isOptedIn()||this.gn())&&this.Hn()}),1),this.Un=new Uu(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()&&Er(this.__request_queue,(e=>this.Pn(e))),this.__request_queue=[],this.Bn()}_handle_unload(){var e,s,r,n,i;(e=this.surveys)==null||e.handlePageUnload==null||e.handlePageUnload(),(s=this.metrics)==null||s.flush("sendBeacon"),this.config.request_batching?(this.zn()&&this.capture(ni),(r=this.logs)==null||r.flushLogs("sendBeacon"),(n=this.In)==null||n.unload(),(i=this.Rn)==null||i.unload()):this.zn()&&this.capture(ni,null,{transport:"sendBeacon"})}_send_request(e){this.__loaded?ad?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=w({},this.config.request_headers,e.headers),e.compression=e.compression==="best-available"?this.compression:e.compression,(x(this.config.disable_beacon)?this.config.__preview_disable_beacon:this.config.disable_beacon)&&(e.disableTransport=["sendBeacon"]),e.fetchOptions=e.fetchOptions||this.config.fetch_options,(s=>{var r,n,i,o=w({},s);o.timeout=o.timeout||6e4;var a,l,u,c,d,h=(r=o.transport)!==null&&r!==void 0?r:"fetch";h==="sendBeacon"&&x(o.compression)&&o.data&&(o.compression=xe.Base64),o.method==="POST"&&o.data&&(o.timestampMode==="capture-body"?o.data={api_key:(l=(d=(c=L(a=o.data)?a:[a])[0])==null||(u=d.properties)==null?void 0:u.token)!==null&&l!==void 0?l:d?.token,batch:c,sent_at:new Date().toISOString()}:o.timestampMode==="body"&&(o.data=(function(m,_){return _===void 0&&(_=new Date().toISOString()),L(m)?m.map((b=>w({},b,{sent_at:_}))):w({},m,{sent_at:_})})(o.data))),o.url=El(o.url,o.method,o.compression,o.timestampMode);var p=Br.filter((m=>!o.disableTransport||!m.transport||!o.disableTransport.includes(m.transport))),f=(n=(i=(function(m,_){for(var b=0;m.length>b;b++)if(m[b].transport===h)return m[b]})(p))==null?void 0:i.method)!==null&&n!==void 0?n:p[0].method;if(!f)throw new Error("No available transport method");var g=m=>{try{f(m)}catch(_){Zu(_)?k.warn(_):k.error(_),o.callback==null||o.callback({statusCode:0,error:_})}};h!=="sendBeacon"&&o.data&&o.compression===xe.GZipJS&&ah&&typeof Promise<"u"&&!Dr?Up(o).then((m=>{g(m)})).catch((m=>{if(Ha(m))return Dr=!0,void g(w({},o,{compression:void 0,url:El(s.url,s.method,void 0,s.timestampMode)}));(_=>{if(!_||typeof _!="object")return!1;var b="name"in _?String(_.name):"";return Ha(_)||b===Cc})(m)&&(Dr=!0),g(o)})):f(o)})(w({},e,{callback:s=>{var r,n;this.rateLimiter.checkForLimiting(s),400>s.statusCode||(r=(n=this.config).on_request_error)==null||r.call(n,s),e.callback==null||e.callback(s)}}))):e.fireCallbackOnDrop&&(e.callback==null||e.callback({statusCode:0}))}Pn(e){this.Rn?this.Rn.retriableRequest(e):this._send_request(e)}_execute_array(e){vi++;try{var s,r=[],n=[],i=[];Er(e,(a=>{if(a)if(L(s=a[0]))i.push(a);else if(Se(a))try{a.call(this)}catch(l){k.error("Error executing queued PostHog call",a,l)}else L(a)&&s==="alias"?r.push(a):L(a)&&s.indexOf("capture")!==-1&&Se(this[s])?i.push(a):n.push(a)}));var o=function(a,l){Er(a,(function(u){try{if(L(u[0])){var c=l;Z(u,(function(d){c=c[d[0]].apply(c,d.slice(1))}))}else l[u[0]].apply(l,u.slice(1))}catch(d){k.error("Error executing queued PostHog call",u,d)}}))};o(r,this),o(n,this),o(i,this)}finally{vi--}}push(e){if(vi>0&&L(e)&&W(e[0])){var s=Te.prototype[e[0]];Se(s)&&s.apply(this,e.slice(1))}else this._execute_array([e])}capture(e,s,r){var n,i,o,a,l;if(this.__loaded&&this.persistence&&this.sessionPersistence&&this.In){if(this.is_capturing())if(!x(e)&&W(e)){var u=!this.config.opt_out_useragent_filter&&this._is_bot();if(!u||this.config.__preview_capture_bot_pageviews){var c=r!=null&&r.skip_client_rate_limiting?void 0:this.rateLimiter.clientRateLimitContext();if(c==null||!c.isRateLimited){s!=null&&s.$current_url&&!W(s?.$current_url)&&(k.error("Invalid `$current_url` property provided to `posthog.capture`. Input must be a string. Ignoring provided value."),s==null||delete s.$current_url),e!=="$exception"||r!=null&&r.Wn||k.warn("Using `posthog.capture('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureException(error)` instead, which attaches required metadata automatically."),this.sessionPersistence.update_search_keyword(),this.config.save_campaign_params&&this.sessionPersistence.update_campaign_params(),this.config.save_referrer&&this.sessionPersistence.update_referrer_info(),(this.config.save_campaign_params||this.config.save_referrer)&&this.persistence.set_initial_person_info();var d=new Date,h=r?.timestamp||d,p=Ga(r?.uuid,dt),f={uuid:p,event:e,properties:this.calculateEventProperties(e,s||{},h,p)};e===is&&this.config.__preview_capture_bot_pageviews&&u&&(f.event="$bot_pageview",f.properties.$browser_type="bot"),c&&(f.properties.$lib_rate_limit_remaining_tokens=c.remainingTokens);var g=e==="$feature_flag_called"&&f.properties.$feature_flag_has_experiment===!1&&this.get_property(en)===!0;r?.$set&&!g&&(f.$set=r?.$set);var m=r?.$unset;m&&(f.$unset=m);var _,b,E,I=g?void 0:this.Vn(r?.$set_once,e!==Qa,e===ii);if(I&&(f.$set_once=I),r!=null&&r._noTruncate||(i=this.config.properties_string_max_length,o=f,a=T=>W(T)?T.slice(0,i):T,l=new Set,f=(function T(O,J){if(O!==Object(O))return a?a(O):O;if(!l.has(O)){var z;if(l.add(O),L(O))z=[],Er(O,(oe=>{z.push(T(oe))}));else{var H={};Z(O,((oe,pe)=>{l.has(oe)||(H[pe]=T(oe))})),z=H}return z}})(o)),f.timestamp=h,x(r?.timestamp)||(f.properties.$event_time_override_provided=!0,f.properties.$event_time_override_system_time=d),g&&(f.properties=(function(T,O){O===void 0&&(O=[]);var J={},z=H=>{T[H]!==void 0&&(J[H]=T[H])};return lh.forEach(z),O.forEach(z),J})(f.properties,nf)),e===ft.DISMISSED||e===ft.SENT){var F=s?.[hi.SURVEY_ID],P=s?.[hi.SURVEY_ITERATION];id({id:F,current_iteration:P}),f.$set=w({},f.$set,{[(_={id:F,current_iteration:P},b=e===ft.SENT?"responded":"dismissed",E="$survey_"+b+"/"+_.id,_.current_iteration&&_.current_iteration>0&&(E="$survey_"+b+"/"+_.id+"/"+_.current_iteration),E)]:!0})}else e===ft.SHOWN&&(f.$set=w({},f.$set,{[hi.SURVEY_LAST_SEEN_DATE]:new Date().toISOString()}));if(e===Tp.SHOWN){var B=s?.[ml.TOUR_TYPE];B&&(f.$set=w({},f.$set,{[ml.TOUR_LAST_SEEN_DATE+"/"+B]:new Date().toISOString()}))}var S=w({},f.properties.$set,f.$set);if(mt(S)||this.setPersonPropertiesForFlags(S),!D(this.config.before_send)){var A=this.Pt(f);if(!A)return;(f=A).uuid=Ga(f.uuid,dt)}this.dn.emit("eventCaptured",f);var R=(n=r?._url)!==null&&n!==void 0?n:this.requestRouter.endpointFor("api",this.analyticsDefaultEndpoint),N={method:"POST",url:R,data:f,compression:"best-available",timestampMode:r?._batchKey==="recordings"||/\/s\/(?:\?|$)/.test(R)?"body":"capture-body",batchKey:r?._batchKey,transport:r?.transport};return!this.config.request_batching||r&&(r==null||!r._batchKey)||r!=null&&r.send_instantly?this.Pn(N):this.In.enqueue(N),f}k.critical("This capture call is ignored due to client rate limiting.")}}else k.error("No event name provided to posthog.capture")}else k.uninitializedWarning("posthog.capture")}_addCaptureHook(e){return this.on("eventCaptured",(s=>e(s.event,s)))}$n(){var e;return(e=this.jn)!==null&&e!==void 0?e:this.jn=new rf(this)}cn(e){this._n.push(e);var s=!0;return()=>{if(s){s=!1;var r=this._n.indexOf(e);r!==-1&&this._n.splice(r,1)}}}calculateEventProperties(e,s,r,n,i){if(r=r||new Date,!this.persistence||!this.sessionPersistence)return s;var o=i?void 0:this.persistence.remove_event_timer(e),a=w({},s);if(a.token=this.config.token,a.$config_defaults=this.config.defaults,this.gn()&&(a[pu]=!0),e==="$snapshot"){var l=w({},this.persistence.properties(),this.sessionPersistence.properties());return a.distinct_id=l.distinct_id,(!W(a.distinct_id)&&!he(a.distinct_id)||Mi(a.distinct_id))&&k.error("Invalid distinct_id for replay event. This indicates a bug in your implementation"),a}var u,c=(function(F,P,B,S){var A,R,N,T;if(S===void 0&&(S=!1),!Pe)return{};var O,J=F?[...vs,...P||[]]:[],z=(function(vr){for(var je=0;qa.length>je;je++){var _r=qa[je],Xt=_r[1],Qt=_r[0].exec(vr),Is=Qt&&(Se(Xt)?Xt(Qt,vr):Xt);if(Is)return Is}return["",""]})(Pe),H=z[0],oe=z[1],pe=(O=typeof navigator<"u"?navigator:void 0)!=null&&O.brave?{brave:!0}:{},Ie={};x(B)||(Ie.detectGoogleSearchApp=B);var _e={},Ce=(A=navigator)==null||(A=A.userAgentData)==null?void 0:A.platform,Re=(R=navigator)==null?void 0:R.maxTouchPoints,ae=v==null||(N=v.screen)==null?void 0:N.width,me=v==null||(T=v.screen)==null?void 0:T.height,ge=v?.devicePixelRatio;x(Ce)||(_e.userAgentDataPlatform=Ce),x(Re)||(_e.maxTouchPoints=Re),x(ae)||(_e.screenWidth=ae),x(me)||(_e.screenHeight=me),x(ge)||(_e.devicePixelRatio=ge);var Ye,Rt,de,Ve,St,ks,Be,Fe,mr=ee(Vo({$os:H,$os_version:oe,$browser:Xc(Pe,navigator.vendor,pe,Ie),$device:Va(Pe),$device_type:(Rt=Pe,de=_e,Fe=Va(Rt),Fe===Nc||Fe===Tc||Fe==="Kobo"||Fe==="Kindle Fire"||Fe===Gc?ps:Fe===er||Fe===ds||Fe===tr||Fe===Oi?"Console":Fe===Lc?"Wearable":Fe?Oe:de?.userAgentDataPlatform==="Android"&&((Ve=de?.maxTouchPoints)!==null&&Ve!==void 0?Ve:0)>0?600>Math.min((St=de?.screenWidth)!==null&&St!==void 0?St:0,(ks=de?.screenHeight)!==null&&ks!==void 0?ks:0)/((Be=de?.devicePixelRatio)!==null&&Be!==void 0?Be:1)?Oe:ps:"Desktop"),$timezone:ju(),$timezone_offset:Ap()}),{$current_url:nr(S?Ct(re?.href):re?.href,J,ir),$host:re?.host,$pathname:re?.pathname,$raw_user_agent:Pe.length>1e3?Pe.substring(0,997)+"...":Pe,$browser_version:Ch(Pe,navigator.vendor,pe,Ie),$browser_language:gl(),$browser_language_prefix:(Ye=gl(),typeof Ye=="string"?Ye.split("-")[0]:void 0),$screen_height:v?.screen.height,$screen_width:v?.screen.width,$viewport_height:v?.innerHeight,$viewport_width:v?.innerWidth,$lib:Y.LIB_NAME,$lib_version:Y.LIB_VERSION,$insert_id:Math.random().toString(36).substring(2,10)+Math.random().toString(36).substring(2,10),$time:Date.now()/1e3});return Y.SDK_DIST_CHANNEL&&(mr.$sdk_dist_channel=Y.SDK_DIST_CHANNEL),mr})(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(i,r.getTime()),h=d.windowId;a.$session_id=d.sessionId,a.$window_id=h}this.sessionPropsManager&&ee(a,this.sessionPropsManager.getSessionProps());try{var p;this.sessionRecording&&ee(a,this.sessionRecording.sdkDebugProperties),a.$sdk_debug_retry_queue_size=(p=this.Rn)==null?void 0:p.length}catch(F){a.$sdk_debug_error_capturing_properties=String(F)}if(this.requestRouter.region===ho&&(a.$lib_custom_api_host=this.config.api_host),u=e!==is||i?e!==ni||i?this.pageViewManager.doEvent():this.pageViewManager.doPageLeave(r):this.pageViewManager.doPageView(r,n),a=ee(a,u),e===is&&C&&(a.title=C.title),!x(o)){var f=r.getTime()-o;a.$duration=parseFloat((f/1e3).toFixed(3))}Pe&&this.config.opt_out_useragent_filter&&(a.$browser_type=this._is_bot()?"bot":"browser");var g=this.persistence.properties(),m=this.sessionPersistence.properties();Z(["$referrer","$referring_domain"],(F=>{F in g&&delete m[F]}));var _={};if(this._n.length>0)for(var b of this._n.slice())try{ee(_,b())}catch(F){k.error("Failed to produce browser extension event properties",F)}(a=ee({},c,g,m,w({},_,a))).$is_identified=this._isIdentified(),L(this.config.property_denylist)?Z(this.config.property_denylist,(function(F){delete a[F]})):k.error(od+this.config.property_denylist+" or property_blacklist config: "+this.config.property_blacklist);var E=this.config.sanitize_properties;E&&(k.error(Fl),a=E(a,e));var I=this.Zn();return a.$process_person_profile=I,I&&!i&&this.Gn("_calculate_event_properties"),a}Vn(e,s,r){var n;if(s===void 0&&(s=!0),r===void 0&&(r=!1),!this.persistence||!this.Zn()||this.mn&&!r)return e;var i=this.persistence.get_initial_props(),o=(n=this.sessionPropsManager)==null?void 0:n.getSetOnceProps(),a=ee({},i,o||{},e||{}),l=this.config.sanitize_properties;return l&&(k.error(Fl),a=l(a,"$set_once")),s&&(this.mn=!0),mt(a)?void 0:a}register(e,s){var r;(r=this.persistence)==null||r.register(e,s)}register_once(e,s,r){var n;(n=this.persistence)==null||n.register_once(e,s,r)}register_for_session(e){var s;(s=this.sessionPersistence)==null||s.register(e),Object.keys(e).forEach((r=>this.yn.add(r))),this.Qn()}unregister(e){var s;(s=this.persistence)==null||s.unregister(e)}unregister_for_session(e){var s;(s=this.sessionPersistence)==null||s.unregister(e),this.yn.delete(e),this.Qn()}Kn(e,s){this.register({[e]:s})}An(){this.yn.forEach((e=>{var s;(s=this.sessionPersistence)==null||s.unregister(e)})),this.yn.clear(),this.Qn()}Qn(){var e;if(this.bn)if(this.config.persistence==="memory"||(e=this.sessionPersistence)!=null&&e.xi||!ce.N())ce.q(this.bn);else{var s=[];this.yn.forEach((r=>s.push(r))),s.length>0?ce.F(this.bn,s):ce.q(this.bn)}}getFeatureFlag(e,s){var r;return(r=this.featureFlags)==null?void 0:r.getFeatureFlag(e,s)}getFeatureFlagPayload(e){var s;return(s=this.featureFlags)==null?void 0:s.getFeatureFlagPayload(e)}getFeatureFlagResult(e,s){var r;return(r=this.featureFlags)==null?void 0:r.getFeatureFlagResult(e,s)}getAllFeatureFlags(){var e,s;return(e=(s=this.featureFlags)==null?void 0:s.getAllFeatureFlags())!==null&&e!==void 0?e:[]}isFeatureEnabled(e,s){var r,n;return(r=(n=this.featureFlags)==null?void 0:n.isFeatureEnabled(e,s))!==null&&r!==void 0?r:s?.defaultValue}reloadFeatureFlags(){var e;(e=this.featureFlags)==null||e.reloadFeatureFlags()}updateFlags(e,s,r){var n;(n=this.featureFlags)==null||n.updateFlags(e,s,r)}updateEarlyAccessFeatureEnrollment(e,s,r){var n;(n=this.featureFlags)==null||n.updateEarlyAccessFeatureEnrollment(e,s,r)}getEarlyAccessFeatures(e,s,r){var n;return s===void 0&&(s=!1),(n=this.featureFlags)==null?void 0:n.getEarlyAccessFeatures(e,s,r)}on(e,s){return this.dn.on(e,s)}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:Ns}),()=>{})}onSessionId(e){var s,r;return(s=(r=this.sessionManager)==null?void 0:r.onSessionId(e))!==null&&s!==void 0?s:()=>{}}getSurveys(e,s){s===void 0&&(s=!1),this.surveys?this.surveys.getSurveys(e,s):e([],{isLoaded:!1,error:Ns})}getActiveMatchingSurveys(e,s){s===void 0&&(s=!1),this.surveys?this.surveys.getActiveMatchingSurveys(e,s):e([],{isLoaded:!1,error:Ns})}renderSurvey(e,s){var r;(r=this.surveys)==null||r.renderSurvey(e,s)}displaySurvey(e,s){var r;s===void 0&&(s=Zp),(r=this.surveys)==null||r.displaySurvey(e,s)}cancelPendingSurvey(e){var s;(s=this.surveys)==null||s.cancelPendingSurvey(e)}canRenderSurvey(e){var s,r;return(s=(r=this.surveys)==null?void 0:r.canRenderSurvey(e))!==null&&s!==void 0?s:{visible:!1,disabledReason:Ns}}canRenderSurveyAsync(e,s){var r,n;return s===void 0&&(s=!1),(r=(n=this.surveys)==null?void 0:n.canRenderSurveyAsync(e,s))!==null&&r!==void 0?r:Promise.resolve({visible:!1,disabledReason:Ns})}Jn(e){return!e||Mi(e)?(k.critical("Unique user id has not been set in posthog.identify"),!1):e===br?(k.critical('The string "'+e+'" was set in posthog.identify which indicates an error. This ID is only used as a sentinel value.'),!1):!["distinct_id","distinctid"].includes(e.toLowerCase())&&!["undefined","null"].includes(e.toLowerCase())||(k.critical('The string "'+e+'" was set in posthog.identify which indicates an error. This ID should be unique to the user and not a hardcoded string.'),!1)}identify(e,s,r){if(!this.__loaded||!this.persistence)return k.uninitializedWarning("posthog.identify");if(he(e)&&(e=e.toString(),k.warn("The first argument to posthog.identify was a number, but it should be a string. It has been converted to a string.")),this.Jn(e)&&this.Gn("posthog.identify")){var n=this.get_distinct_id();this.register({$user_id:e}),this.get_property(sr)||this.register_once({$had_persisted_distinct_id:!0,$device_id:n},""),e!==n&&e!==this.get_property(Bs)&&(this.unregister(Bs),this.register({distinct_id:e}));var i,o=(this.persistence.get_property(He)||es)===es,a=e!==n,l=!a&&o;if(a&&o)this.persistence.set_property(He,Tt),this.setPersonPropertiesForFlags({$set:s||{},$set_once:r||{}},!1),this.capture(ii,{distinct_id:e,$anon_distinct_id:n},{$set:s||{},$set_once:r||{}}),this.Sn=mi(e,s,r),(i=this.featureFlags)==null||i.setAnonymousDistinctId(n);else if(l){this.persistence.set_property(He,Tt);var u=s||{},c=r||{};this.setPersonPropertiesForFlags({$set:u,$set_once:c},!1),this.capture("$set",{$set:u,$set_once:c}),this.Sn=mi(e,s,r)}else(s||r)&&this.setPersonProperties(s,r);a?(this.reloadFeatureFlags(),this.featureFlags?this.featureFlags.resetFlagCallReported():this.unregister(Wt)):l&&(s||r)&&this.reloadFeatureFlags()}}setPersonProperties(e,s){if((e||s)&&this.Gn("posthog.setPersonProperties")){var r=mi(this.get_distinct_id(),e,s);this.Sn!==r?(this.setPersonPropertiesForFlags({$set:e||{},$set_once:s||{}},!0),this.capture("$set",{$set:e||{},$set_once:s||{}}),this.Sn=r):k.info("A duplicate setPersonProperties call was made with the same properties. It has been ignored.")}}unsetPersonProperties(e){var s,r=(L(e)?e:[e]).filter((n=>W(n)&&n.length>0));r.length!==0&&this.Gn("posthog.unsetPersonProperties")&&((s=this.featureFlags)==null||s.unsetPersonPropertiesForFlags(r,!0),this.capture("$set",{$unset:r}),this.Sn=null)}group(e,s,r){if(e&&s){var n=this.getGroups(),i=n[e]!==s;if(i&&this.resetGroupPropertiesForFlags(e),this.register({$groups:w({},n,{[e]:s})}),i||r){var o={$group_type:e,$group_key:s};r&&(o.$group_set=r),this.capture(Qa,o)}r&&this.setGroupPropertiesForFlags({[e]:r}),i&&!r&&this.reloadFeatureFlags()}else k.error("posthog.group requires a group type and group key")}resetGroups(){this.register({$groups:{}}),this.resetGroupPropertiesForFlags(),this.reloadFeatureFlags()}setPersonPropertiesForFlags(e,s){var r;s===void 0&&(s=!0),(r=this.featureFlags)==null||r.setPersonPropertiesForFlags(e,s)}resetPersonPropertiesForFlags(e){var s;e===void 0&&(e=!0),(s=this.featureFlags)==null||s.resetPersonPropertiesForFlags(e)}setGroupPropertiesForFlags(e,s){var r;s===void 0&&(s=!0),this.Gn("posthog.setGroupPropertiesForFlags")&&((r=this.featureFlags)==null||r.setGroupPropertiesForFlags(e,s))}resetGroupPropertiesForFlags(e){var s;(s=this.featureFlags)==null||s.resetGroupPropertiesForFlags(e)}reset(e){this.Yn(e)}Yn(e,s){var r,n,i,o,a,l,u,c,d,h;if(s===void 0&&(s=!1),k.info("reset"),!this.__loaded)return k.uninitializedWarning("posthog.reset");var p,f=this.get_property(sr),g=this.get_property(ri),m=this.get_property(qt),_=this.is_capturing();if(this.consent.reset(),s||!_||this.is_capturing()||console.warn("[PostHog.js]","reset() cleared the stored consent, and capturing is now off because of `opt_out_capturing_by_default`. Call opt_in_capturing() again, and prefer calling reset() before opting in rather than after."),(r=this.persistence)==null||r.clear(),(n=this.sessionPersistence)==null||n.clear(),this.yn.clear(),this.Qn(),x(m)||(p=this.persistence)==null||p.register({[qt]:m}),(i=this.surveys)==null||i.reset(),(o=this.Un)==null||o.stop(),(a=this.featureFlags)==null||a.reset(),(l=this.conversations)==null||l.reset(),(u=this.logs)==null||u.reset(),(c=this.metrics)==null||c.reset(),(d=this.persistence)==null||d.set_property(He,es),(h=this.sessionManager)==null||h.resetSessionId(),this.Sn=null,this.config.cookieless_mode===ht)this.register_once({distinct_id:br,$device_id:null},"");else{var b=this.config.get_device_id(dt());this.register_once({distinct_id:b,$device_id:e?b:f},""),e||x(g)||this.register({[ri]: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 s=this;return X((function*(){var r,n,i,o,a,l,u;if(s.__loaded){(r=s.Un)==null||r.stop(),(n=s.jn)==null||n.dispose(),(i=s.sessionRecording)==null||i.dispose(),(o=s.logs)==null||o.flushLogs("sendBeacon"),(a=s.metrics)==null||a.flush("sendBeacon"),(l=s.In)==null||l.unload(),(u=s.Rn)==null||u.unload();try{var c;(c=s.featureFlags)==null||c.destroy()}catch(d){k.error("Error while destroying feature flags",d)}}else k.uninitializedWarning("posthog.shutdown")}))()}setIdentity(e,s){var r;this.config.identity_distinct_id=e,this.config.identity_hash=s,this.alias(e),(r=this.conversations)==null||r.Xn()}clearIdentity(){var e;delete this.config.identity_distinct_id,delete this.config.identity_hash,(e=this.conversations)==null||e.ts()}get_distinct_id(){return this.get_property("distinct_id")}getGroups(){return this.get_property("$groups")||{}}get_session_id(){var e,s;return(e=(s=this.sessionManager)==null?void 0:s.checkAndGetSessionAndWindowId(!0).sessionId)!==null&&e!==void 0?e:""}get_session_replay_url(e){if(!this.sessionManager)return"";var s=this.sessionManager.checkAndGetSessionAndWindowId(!0),r=s.sessionStartTimestamp,n=this.requestRouter.endpointFor("ui","/project/"+this.config.token+"/replay/"+s.sessionId);if(e!=null&&e.withTimestamp&&r){var i,o=(i=e.timestampLookBack)!==null&&i!==void 0?i:10;if(!r)return n;n+="?t="+Math.max(Math.floor((new Date().getTime()-r)/1e3)-o,0)}return n}alias(e,s){return e===this.get_property(au)?(k.critical("Attempting to create alias for existing People user - aborting."),-2):this.Gn("posthog.alias")?(x(s)&&(s=this.get_distinct_id()),e!==s?(this.Kn(Bs,e),this.capture("$create_alias",{alias:e,distinct_id:s})):(k.warn("alias matches current distinct_id - skipping api call."),this.identify(e),-1)):void 0}set_config(e){var s=w({},this.config);if(te(e)){var r,n,i,o,a,l,u,c,d,h,p,f;ee(this.config,Pl(e));var g=this.En();(r=this.persistence)==null||r.update_config(this.config,s,g),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new ui(w({},this.config,{persistence:"sessionStorage"}),g,!1);var m=this.Cn(this.config.debug);Ke(m)&&(this.config.debug=m),Ke(this.config.debug)&&(this.config.debug?(Y.DEBUG=!0,Q.N()&&Q.F("ph_debug",!0),k.info("set_config",{config:e,oldConfig:s,newConfig:w({},this.config)})):(Y.DEBUG=!1,Q.N()&&Q.q("ph_debug"))),(n=this.featureFlags)==null||n.updateConfig==null||n.updateConfig(this.config,this.Qi()),(i=this.exceptionObserver)==null||i.onConfigChange(),(o=this.exceptions)==null||o.onConfigChange(),(a=this.sessionRecording)==null||a.startIfEnabledOrStop(),(l=this.tracingHeaders)==null||l.startIfEnabledOrStop(),(u=this.autocapture)==null||u.startIfEnabled(),(c=this.heatmaps)==null||c.startIfEnabled(),(d=this.exceptionObserver)==null||d.startIfEnabledOrStop(),(h=this.deadClicksAutocapture)==null||h.startIfEnabledOrStop(),(p=this.surveys)==null||p.loadIfEnabled(),this.es(),(f=this.externalIntegrations)==null||f.startIfEnabledOrStop()}}_overrideSDKInfo(e,s){Y.LIB_NAME=e,Y.LIB_VERSION=s}startSessionRecording(e){var s,r,n,i,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)&&((s=this.sessionManager)==null||s.checkAndGetSessionAndWindowId(),l.sampling&&((r=this.sessionRecording)==null||r.overrideSampling()),l.linked_flag&&((n=this.sessionRecording)==null||n.overrideLinkedFlag()),l.url_trigger&&((i=this.sessionRecording)==null||i.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,s){if(this.exceptions){var r=new Error("PostHog syntheticException"),n=this.exceptions.buildProperties(e,{handled:!0,syntheticException:r});return this.exceptions.sendExceptionEvent(w({},n,s))}}addExceptionStep(e,s){var r;(r=this.exceptions)==null||r.addExceptionStep(e,s)}captureLog(e){var s;(s=this.logs)==null||s.captureLog(e)}get logger(){var e,s;return(e=(s=this.logs)==null?void 0:s.logger)!==null&&e!==void 0?e:Te.rs}startExceptionAutocapture(e){this.set_config({capture_exceptions:e==null||e})}stopExceptionAutocapture(){this.set_config({capture_exceptions:!1})}loadToolbar(e){var s,r;return(s=(r=this.toolbar)==null?void 0:r.loadToolbar(e))!==null&&s!==void 0&&s}get_property(e){var s;return(s=this.persistence)==null?void 0:s.props[e]}getSessionProperty(e){var s;return(s=this.sessionPersistence)==null?void 0:s.props[e]}toString(){var e,s=(e=this.config.name)!==null&&e!==void 0?e:os;return s!==os&&(s=os+"."+s),s}_isIdentified(){var e,s;return((e=this.persistence)==null?void 0:e.get_property(He))===Tt||((s=this.sessionPersistence)==null?void 0:s.get_property(He))===Tt}Zn(){var e,s;return!(this.config.person_profiles==="never"||this.config.person_profiles===to&&!this._isIdentified()&&mt(this.getGroups())&&((e=this.persistence)==null||(e=e.props)==null||!e[Bs])&&((s=this.persistence)==null||(s=s.props)==null||!s[rn]))}zn(){return this.config.capture_pageleave===!0||this.config.capture_pageleave==="if_capture_pageview"&&(this.config.capture_pageview===!0||this.config.capture_pageview==="history_change")}createPersonProfile(){this.Zn()||this.Gn("posthog.createPersonProfile")&&this.setPersonProperties({},{})}setInternalOrTestUser(){this.Gn("posthog.setInternalOrTestUser")&&this.setPersonProperties({$internal_or_test_user:!0})}Gn(e){return this.config.person_profiles==="never"?(k.error(e+' was called, but process_person is set to "never". This call will be ignored.'),!1):(this.Kn(rn,!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!==Ht)}es(){var e,s,r,n,i=this.En();return((e=this.persistence)==null?void 0:e.xi)!==i&&((r=this.persistence)==null||r.set_disabled(i)),((s=this.sessionPersistence)==null?void 0:s.xi)!==i&&((n=this.sessionPersistence)==null||n.set_disabled(i)),i&&(this.yn.clear(),this.Qn()),i}opt_in_capturing(e){var s;if(this.config.cookieless_mode!==ht){if(this.gn()){var r,n,i,o,a;this.Yn(!0,!0),(r=this.sessionManager)==null||r.destroy(),(n=this.pageViewManager)==null||n.destroy(),this.sessionManager=new xl(this),this.pageViewManager=new fl(this),this.persistence&&(this.sessionPropsManager=new Sl(this,this.sessionManager,this.persistence));var l,u=(i=(o=this.config.__extensionClasses)==null?void 0:o.sessionRecording)!==null&&i!==void 0?i:(a=Te.__defaultExtensionClasses)==null?void 0:a.sessionRecording;u&&(this.sessionRecording=this.pn(this.sessionRecording,new u(this)),this.hn&&((l=this.sessionRecording)==null||l.onRemoteConfig==null||l.onRemoteConfig(this.hn)))}var c,d;this.consent.optInOut(!0),this.es(),this.Bn(),(s=this.sessionRecording)==null||s.startIfEnabledOrStop(),this.config.cookieless_mode==Ht&&((c=this.surveys)==null||c.loadIfEnabled()),(x(e?.captureEventName)||e!=null&&e.captureEventName)&&this.capture((d=e?.captureEventName)!==null&&d!==void 0?d:"$opt_in",e?.captureProperties,{send_instantly:!0}),this.config.capture_pageview&&this.Hn()}else k.warn(Cl)}opt_out_capturing(){var e,s,r;this.config.cookieless_mode!==ht?(this.config.cookieless_mode===Ht&&this.consent.isOptedIn()&&this.Yn(!0,!0),this.consent.optInOut(!1),this.es(),this.config.cookieless_mode===Ht&&(this.register({distinct_id:br,$device_id:null}),(e=this.sessionRecording)==null||e.stopRecording(),this.sessionRecording=void 0,(s=this.sessionManager)==null||s.destroy(),(r=this.pageViewManager)==null||r.destroy(),this.sessionManager=void 0,this.sessionPropsManager=void 0,this.config.capture_pageview&&this.Hn(),this.Bn())):k.warn(Cl)}has_opted_in_capturing(){return this.consent.isOptedIn()}has_opted_out_capturing(){return this.consent.isOptedOut()}get_explicit_consent_status(){var e=this.consent.consent;return e===1?"granted":e===0?"denied":"pending"}is_capturing(){return this.config.cookieless_mode===ht||(this.config.cookieless_mode===Ht?this.consent.isRejected()||this.consent.isOptedIn():!this.has_opted_out_capturing())}clear_opt_in_out_capturing(){this.consent.reset(),this.es()}_is_bot(){return ke?Qu(ke,this.config.custom_blocked_useragents):void 0}Hn(){C&&(C.visibilityState==="visible"?this.wn||(this.wn=!0,this.capture(is,{title:C.title},{send_instantly:!0}),this.kn&&(C.removeEventListener(nn,this.kn),this.kn=null)):this.kn||(this.kn=this.Hn.bind(this),ne(C,nn,this.kn)))}debug(e){e===!1?(v?.console.log("You've disabled debug mode."),this.set_config({debug:!1})):(v?.console.log("You're now in debug mode. All calls to PostHog will be logged in your console.\nYou can disable this with `posthog.debug(false)`."),this.set_config({debug:!0}))}Qi(){var e=this.Mn||{};return"advanced_disable_flags"in e?!!e.advanced_disable_flags:this.config.advanced_disable_flags!==!1?!!this.config.advanced_disable_flags:this.config.advanced_disable_decide===!0?(k.warn("Config field 'advanced_disable_decide' is deprecated. Please use 'advanced_disable_flags' instead. The old field will be removed in a future major version."),!0):(function(s,r,n,i,o){var a=r in s&&!D(s[r]),l=n in s&&!D(s[n]);return a?s[r]:!!l&&(o&&o.warn("Config field '"+n+"' is deprecated. Please use '"+r+"' instead. The old field will be removed in a future major version."),s[n])})(e,"advanced_disable_flags","advanced_disable_decide",0,k)}Pt(e){var s;if(D(this.config.before_send))return e;var r=Object.keys((s=e.properties)!==null&&s!==void 0?s:{}).filter(gh),n=L(this.config.before_send)?this.config.before_send:[this.config.before_send],i=e;for(var o of n){if(i=o(i),D(i)){var a="Event '"+e.event+"' was rejected in beforeSend function";return fh(e.event)?k.warn(a+". This can cause unexpected behavior."):k.info(a),null}i.properties&&!mt(i.properties)||k.warn("Event '"+e.event+"' has no properties after beforeSend function, this is likely an error.")}for(var l of r)if(i.properties&&D(i.properties[l]))return k.warn("Event '"+e.event+"' had its '"+l+"' property removed in a beforeSend function. This property is required for ingestion, so the event will be dropped."),null;return i}getPageViewId(){var e;return(e=this.pageViewManager.ui)==null?void 0:e.pageViewId}captureTraceFeedback(e,s){this.capture("$ai_feedback",{$ai_trace_id:String(e),$ai_feedback_text:s})}captureTraceMetric(e,s,r){this.capture("$ai_metric",{$ai_trace_id:String(e),$ai_metric_name:s,$ai_metric_value:String(r)})}Cn(e){var s=Ke(e)&&!e,r=Q.N()&&Q.P("ph_debug")==="true";return!s&&(!!r||e)}}Te.__defaultExtensionClasses={},Te.rs=(()=>{var t=()=>{};return{trace:t,debug:t,info:t,warn:t,error:t,fatal:t}})(),(function(t,e){for(var s=0;e.length>s;s++)t.prototype[e[s]]=rp(t.prototype[e[s]])})(Te,["identify"]);class Al{constructor(e){this.disabled=e===!1;var s=te(e)?e:{};this.thresholdPx=s.threshold_px||30,this.timeoutMs=s.timeout_ms||1e3,this.clickCount=s.click_count||3,this.clicks=[]}isRageClick(e,s,r){if(this.disabled)return!1;var n=this.clicks[this.clicks.length-1];if(n&&Math.abs(e-n.x)+Math.abs(s-n.y)r-n.timestamp){if(this.clicks.push({x:e,y:s,timestamp:r}),this.clicks.length===this.clickCount)return!0}else this.clicks=[{x:e,y:s,timestamp:r}];return!1}}var yi="$copy_autocapture",wi=se("[AutoCapture]");function bi(t,e){return e.length>t?e.slice(0,t)+"...":e}function lf(t){if(t.previousElementSibling)return t.previousElementSibling;var e=t;do e=e.previousSibling;while(e&&!Ft(e));return e}function cf(t,e){var s,r,n=e.e,i=e.maskAllElementAttributes,o=e.maskAllText,a=e.elementAttributeIgnoreList,l=e.elementsChainAsString,u=e.disableCaptureUrlHashes;if(!Ft(t))return{props:{}};for(var c=[t],d=new Set([t]),h=t;h.parentNode&&!Me(h,"body")&&Su>c.length;)if(Eu(h.parentNode)){var p=h.parentNode.host;if(d.has(p))break;d.add(p),c.push(p),h=p}else{if(!Ft(h.parentNode)||d.has(h.parentNode))break;d.add(h.parentNode),c.push(h.parentNode),h=h.parentNode}var f,g,m=[],_={},b=!1,E=!1;if(Z(c,(S=>{var A=no(S);if(Me(S,"a")){var R=S.getAttribute("href");b=!!(A&&R&&Ks(R))&&(u?Ct(R):R)}M(ln(S),"ph-no-capture")&&(E=!0),m.push((function(T,O,J,z,H){H===void 0&&(H=!1);var oe=T.tagName.toLowerCase(),pe={tag_name:oe};Ko.indexOf(oe)>-1&&!J&&(pe.$el_text=oe.toLowerCase()==="a"||oe.toLowerCase()==="button"?bi(1024,dl(T)):bi(1024,rr(T)));var Ie=ln(T);Ie.length>0&&(pe.classes=Ie.filter((function(ae){return ae!==""}))),Z(T.attributes,(function(ae){var me;if((!Fu(T)||["name","id","class","aria-label"].indexOf(ae.name)!==-1)&&(z==null||!z.includes(ae.name))&&!O&&Ks(ae.value)&&(!W(me=ae.name)||me.substring(0,10)!=="_ngcontent"&&me.substring(0,7)!=="_nghost")){var ge=ae.value;ae.name==="class"&&(ge=Go(ge).join(" ")),pe["attr__"+ae.name]=bi(1024,ae.name==="href"&&H?Ct(ge):ge)}}));for(var _e=1,Ce=1,Re=T;Re=lf(Re);)_e++,Re.tagName===T.tagName&&Ce++;return pe.nth_child=_e,pe.nth_of_type=Ce,pe})(S,i,o,a,u));var N=(function(T){if(!no(T))return{};var O={};return Z(T.attributes,(function(J){if(J.name&&J.name.indexOf("data-ph-capture-attribute")===0){var z=J.name.replace("data-ph-capture-attribute-",""),H=J.value;z&&H&&Ks(H)&&(O[z]=H)}})),O})(S);ee(_,N)})),E)return{props:{},explicitNoCapture:E};if(o||(m[0].$el_text=Me(t,"a")||Me(t,"button")?dl(t):rr(t)),b){var I,F;m[0].attr__href=b;var P=(I=cn(b))==null?void 0:I.host,B=v==null||(F=v.location)==null?void 0:F.host;P&&B&&P!==B&&(f=b)}return{props:ee({$event_type:n.type,$ce_version:1},l?{}:{$elements:m},{$elements_chain:(g=m,(function(S){return S.map((A=>{var R,N,T="";if(A.tag_name&&(T+=A.tag_name),A.attr_class)for(var O of(A.attr_class.sort(),A.attr_class))T+="."+O.replace(/"/g,"");var J=w({},A.text?{text:A.text}:{},{"nth-child":(R=A.nth_child)!==null&&R!==void 0?R:0,"nth-of-type":(N=A.nth_of_type)!==null&&N!==void 0?N:0},A.href?{href:A.href}:{},A.attr_id?{attr_id:A.attr_id}:{},A.attributes),z={};return Or(J).sort(((H,oe)=>H[0].localeCompare(oe[0]))).forEach((H=>{var oe=H[1];return z[hl(H[0].toString())]=hl(oe.toString())})),(T+=":")+Or(z).map((H=>H[0]+'="'+H[1]+'"')).join("")})).join(";")})((function(S){return S.map((A=>{var R,N,T={text:(R=A.$el_text)==null?void 0:R.slice(0,400),tag_name:A.tag_name,href:(N=A.attr__href)==null?void 0:N.slice(0,2048),attr_class:Ep(A),attr_id:A.attr__id,nth_child:A.nth_child,nth_of_type:A.nth_of_type,attributes:{}};return Or(A).filter((O=>O[0].indexOf("attr__")===0)).forEach((O=>T.attributes[O[0]]=O[1])),T}))})(g)))},(s=m[0])!=null&&s.$el_text?{$el_text:(r=m[0])==null?void 0:r.$el_text}:{},f&&n.type==="click"?{$external_click_url:f}:{},_)}}var Ms=se("[ExceptionAutocapture]"),$l=()=>{},uf=se("[TracingHeaders]"),Lt=se("[Web Vitals]"),Rl=9e5,Tl="disabled",Nl="lazy_loading",Ls="awaiting_config",Fr="missing_config";se("[SessionRecording]"),se("[SessionRecording]");var po="[SessionRecording]",at=se(po),df=se("[Heatmaps]");function Ei(t){return te(t)&&"clientX"in t&&"clientY"in t&&he(t.clientX)&&he(t.clientY)}var Pr=se("[Product Tours]"),Si=t=>{var e;return!t.config.disable_product_tours&&!((e=t.persistence)==null||!e.get_property(Wo))},hf=["$set_once","$set"],Ze=se("[SiteApps]"),Ml="Error while initializing PostHog app with config id ";function rs(t,e,s){if(D(t))return!1;switch(s){case"exact":return t===e;case"contains":var r=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/_/g,".").replace(/%/g,".*");return new RegExp(r,"i").test(t);case"regex":try{return new RegExp(e).test(t)}catch{return!1}default:return!1}}class pf{constructor(e){this.ns=new Xo,this.ss=(s,r)=>this.os(s,r)&&this.ls(s,r)&&this.us(s,r)&&this.hs(s,r),this.os=(s,r)=>r==null||!r.event||s?.event===r?.event,this._instance=e,this.ds=new Set,this.vs=new Set}init(){var e,s;x((e=this._instance)==null?void 0:e._addCaptureHook)||(s=this._instance)==null||s._addCaptureHook(((r,n)=>{this.on(r,n)}))}register(e){var s,r;if(!x((s=this._instance)==null?void 0:s._addCaptureHook)&&(e.forEach((o=>{var a,l;(a=this.vs)==null||a.add(o),(l=o.steps)==null||l.forEach((u=>{var c;(c=this.ds)==null||c.add(u?.event||"")}))})),(r=this._instance)!=null&&r.autocapture)){var n,i=new Set;e.forEach((o=>{var a;(a=o.steps)==null||a.forEach((l=>{l!=null&&l.selector&&i.add(l?.selector)}))})),(n=this._instance)==null||n.autocapture.setElementSelectors(i)}}on(e,s){var r;s!=null&&e.length!=0&&(this.ds.has(e)||this.ds.has(s.event))&&this.vs&&((r=this.vs)==null?void 0:r.size)>0&&this.vs.forEach((n=>{this.cs(s,n)&&this.ns.emit("actionCaptured",n.name)}))}fs(e){this.onAction("actionCaptured",(s=>e(s)))}cs(e,s){if(s?.steps==null)return!1;for(var r of s.steps)if(this.ss(e,r))return!0;return!1}onAction(e,s){return this.ns.on(e,s)}ls(e,s){if(s!=null&&s.url){var r,n=e==null||(r=e.properties)==null?void 0:r.$current_url;if(!n||typeof n!="string"||!rs(n,s.url,s.url_matching||"contains"))return!1}return!0}us(e,s){return!!this.ps(e,s)&&!!this.gs(e,s)&&!!this.ys(e,s)}ps(e,s){var r;if(s==null||!s.href)return!0;var n=this.bs(e);if(n.length>0)return n.some((a=>rs(a.href,s.href,s.href_matching||"exact")));var i,o=(e==null||(r=e.properties)==null?void 0:r.$elements_chain)||"";return!!o&&rs((i=o.match(/(?::|")href="(.*?)"/))?i[1]:"",s.href,s.href_matching||"exact")}gs(e,s){var r;if(s==null||!s.text)return!0;var n=this.bs(e);if(n.length>0)return n.some((u=>rs(u.text,s.text,s.text_matching||"exact")||rs(u.$el_text,s.text,s.text_matching||"exact")));var i,o,a,l=(e==null||(r=e.properties)==null?void 0:r.$elements_chain)||"";return!!l&&(i=(function(u){for(var c,d=[],h=/(?::|")text="(.*?)"/g;!D(c=h.exec(u));)d.includes(c[1])||d.push(c[1]);return d})(l),o=s.text,a=s.text_matching||"exact",i.some((u=>rs(u,o,a))))}ys(e,s){var r,n;if(s==null||!s.selector)return!0;var i=e==null||(r=e.properties)==null?void 0:r.$element_selectors;if(i!=null&&i.includes(s.selector))return!0;var o=(e==null||(n=e.properties)==null?void 0:n.$elements_chain)||"";if(s.selector_regex&&o)try{return new RegExp(s.selector_regex).test(o)}catch{return!1}return!1}bs(e){var s;return(e==null||(s=e.properties)==null?void 0:s.$elements)==null?[]:e?.properties.$elements}hs(e,s){return s==null||!s.properties||s.properties.length===0||sd(s.properties.reduce(((r,n)=>{var i=L(n.value)?n.value.map(String):n.value!=null?[String(n.value)]:[];return r[n.key]={values:i,operator:n.operator||"exact"},r}),{}),e?.properties)}}class ff{constructor(e){var s;this._s=[],this._instance=e,this.ws=new Map,this.ks=new Map,this.xs=new Map,(s=this._instance)==null||s.onSessionId==null||s.onSessionId((r=>this.Ss(r)))}Cs(e){return!1}Ms(){return null}Ts(e){}Es(){}Is(e,s){return!!e&&sd(e.propertyFilters,s?.properties)}Ps(e,s){var r=new Map;return e.forEach((n=>{var i;(i=n.conditions)==null||(i=i[s])==null||(i=i.values)==null||i.forEach((o=>{if(o!=null&&o.name){var a=r.get(o.name)||[];a.push(n.id),r.set(o.name,a)}}))})),r}Rs(e,s,r){var n=(r===As.Activation?this.ws:this.ks).get(e),i=[];return this.As((o=>{i=o.filter((a=>n?.includes(a.id)))})),i.filter((o=>{var a,l=(a=o.conditions)==null||(a=a[r])==null||(a=a.values)==null?void 0:a.find((u=>u.name===e));return this.Is(l,s)}))}register(e){var s;x((s=this._instance)==null?void 0:s._addCaptureHook)||(this.Fs(e),this.Ls(e))}Ls(e){var s=e.filter((r=>{var n,i;return((n=r.conditions)==null?void 0:n.actions)&&((i=r.conditions)==null||(i=i.actions)==null||(i=i.values)==null?void 0:i.length)>0}));s.length!==0&&(this.Os==null&&(this.Os=new pf(this._instance),this.Os.init(),this.Os.fs((r=>{this.onAction(r)}))),s.forEach((r=>{var n,i,o,a,l;r.conditions&&(n=r.conditions)!=null&&n.actions&&(i=r.conditions)!=null&&(i=i.actions)!=null&&i.values&&((o=r.conditions)==null||(o=o.actions)==null||(o=o.values)==null?void 0:o.length)>0&&((a=this.Os)==null||a.register(r.conditions.actions.values),(l=r.conditions)==null||(l=l.actions)==null||(l=l.values)==null||l.forEach((u=>{if(u&&u.name){var c=this.xs.get(u.name);c&&c.push(r.id),this.xs.set(u.name,c||[r.id])}})))})))}Fs(e){var s,r=e.filter((i=>{var o,a;return((o=i.conditions)==null?void 0:o.events)&&((a=i.conditions)==null||(a=a.events)==null||(a=a.values)==null?void 0:a.length)>0})),n=e.filter((i=>{var o,a;return((o=i.conditions)==null?void 0:o.cancelEvents)&&((a=i.conditions)==null||(a=a.cancelEvents)==null||(a=a.values)==null?void 0:a.length)>0}));r.length===0&&n.length===0||((s=this._instance)==null||s._addCaptureHook(((i,o)=>{this.onEvent(i,o)})),this.ws=this.Ps(e,As.Activation),this.ks=this.Ps(e,As.Cancellation))}onEvent(e,s){var r,n,i=this.Ds(),o=(s==null||(r=s.properties)==null?void 0:r.$survey_id)||(s==null||(n=s.properties)==null?void 0:n.$product_tour_id);if(o&&this.getActivatedIds().includes(o)){var a=this.$s(e,o);if(a==="consume")return i.info("event consumed activated item, removing it",{event:e,itemId:o}),void this.Ns([o]);if(a==="persist")return i.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,s,As.Cancellation);l.length>0&&(i.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)){i.info("event name matched",{event:e,eventPayload:s,items:this.ws.get(e)});var u=this.Rs(e,s,As.Activation);this.Hs(u.map((c=>c.id)))}}onAction(e){this.xs.has(e)&&this.Hs(this.xs.get(e)||[])}Hs(e){var s;if(e.length!==0){var r=!((s=this._instance)==null||s.get_session_id==null||!s.get_session_id()),n=[];for(var i of e)r&&this.Cs(i)?this.qs(i)&&this.Us(i):n.push(i);n.length>0&&(this._s=[...new Set([...this._s,...n])]),this.Ds().info("updating activated items",{activatedItems:this.getActivatedIds()})}}qs(e){this._s=this._s.filter((r=>r!==e));var s=this.zs();return!s.includes(e)&&(this.Ws([...s,e]),this.Vs(),!0)}Ns(e){var s=new Set(e);this._s=this._s.filter((i=>!s.has(i)));var r=this.Zs(),n=r.filter((i=>!s.has(i)));n.length!==r.length&&(this.Ws(n),n.length===0&&this.Gs()),this.js(e)}Qs(){var e,s=this.Ms();if(!s)return{};var r=(e=this._instance)==null||(e=e.persistence)==null?void 0:e.props[s];return r&&typeof r=="object"?r:{}}Us(e){if(this.Ms()){var s=this.Qs();this.Ts(w({},s,{[e]:Date.now()}))}}js(e){if(this.Ms()){var s=this.Qs(),r={},n=!1;for(var i of Object.entries(s)){var o=i[0],a=i[1];e.includes(o)?n=!0:r[o]=a}n&&(mt(r)?this.Es():this.Ts(r))}}Ks(){this.Ms()&&this.Es()}getActivationTimestamp(e){if(this.zs().includes(e)){var s=this.Qs()[e];return he(s)?s:void 0}}Zs(){var e,s=this.Js();return((e=this._instance)==null||(e=e.persistence)==null?void 0:e.props[s])||[]}zs(){var e,s,r=this.Zs();if(r.length===0)return[];var n=(e=this._instance)==null||(e=e.persistence)==null?void 0:e.props[this.Ys()],i=(s=this._instance)==null||s.get_session_id==null?void 0:s.get_session_id();return i&&n===i?r:[]}Vs(){var e,s=(e=this._instance)==null||e.get_session_id==null?void 0:e.get_session_id();s&&this.Xs(s)}Gs(){this.ta()}Ss(e){var s,r=(s=this._instance)==null||(s=s.persistence)==null?void 0:s.props[this.Ys()];if(r&&r!==e){var n=this.Zs(),i=this.Qs();n.length>0&&(this.Ws([]),n.filter((o=>he(i[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 gf extends ff{constructor(e){super(e)}Js(){return Yi}Ys(){return Nr}Ms(){return Mr}Ts(e){var s;(s=this._instance)==null||(s=s.persistence)==null||s.register({[Mr]:e})}Es(){var e;(e=this._instance)==null||(e=e.persistence)==null||e.unregister(Mr)}Cs(e){var s,r;this.As((i=>{r=i.find((o=>o.id===e))}));var n=(s=r)==null||(s=s.appearance)==null?void 0:s.surveyPopupDelaySeconds;return he(n)&&n>0}ra(){return ft.SHOWN}As(e){var s;(s=this._instance)==null||s.getSurveys(e)}Bs(e){var s;(s=this._instance)==null||s.cancelPendingSurvey(e)}Ds(){return q}Ws(e){var s;(s=this._instance)==null||(s=s.persistence)==null||s.register({[Yi]:e})}Xs(e){var s;(s=this._instance)==null||(s=s.persistence)==null||s.register({[Nr]:e})}ta(){var e;(e=this._instance)==null||(e=e.persistence)==null||e.unregister(Nr)}ea(){return!1}$s(e,s){var r;this.As((i=>{r=i.find((o=>o.id===s))}));var n=!r||(function(i){var o;return rd(i)&&!((o=i.conditions)==null||(o=o.events)==null||!o.repeatedActivation)||i.schedule==="always"})(r);return n?e===ft.SHOWN?"consume":"ignore":e===ft.SHOWN?"persist":e===ft.DISMISSED||e===ft.SENT?"consume":"ignore"}getSurveys(){return this.getActivatedIds()}getEventToSurveys(){return this.getEventToItemsMap()}}var Ar="SDK is not enabled or survey functionality is not yet loaded",Ll="Disabled. Not loading surveys.",mf=v!=null&&v.location?un(v.location.hash,"__posthog")||un(location.hash,"state"):null,Ol="_postHogToolbarParams",Dl=se("[Toolbar]"),Bl=se("[FeatureFlags]");class vf{constructor(e,s){s===void 0&&(s=!1),this.na=!1,this.update(e,s)}update(e,s){this.sa=((r,n)=>{var i,o,a,l;return{bootstrap:{featureFlags:(i=r.bootstrap)==null?void 0:i.featureFlags,featureFlagPayloads:(o=r.bootstrap)==null?void 0:o.featureFlagPayloads},remoteRequestsDisabled:n,featureFlagsDisabled:!!r.advanced_disable_feature_flags,onlyEvaluateSurveyFeatureFlags:!!r.advanced_only_evaluate_survey_feature_flags,deduplicateCallsPerSession:!!r.advanced_feature_flags_dedup_per_session,cacheTtlMs:r.feature_flag_cache_ttl_ms,requestTimeoutMs:r.feature_flag_request_timeout_ms,compression:r.disable_compression?"none":"base64",evaluationContexts:(a=(l=r.evaluation_contexts)!==null&&l!==void 0?l:r.evaluation_environments)!==null&&a!==void 0?a:[],flagKeys:L(r.flag_keys)?r.flag_keys:void 0}})(e,s),!e.evaluation_environments||e.evaluation_contexts||this.na||(Bl.warn("evaluation_environments is deprecated. Use evaluation_contexts instead. evaluation_environments will be removed in a future version."),this.na=!0),x(e.flag_keys)||L(e.flag_keys)||Bl.error("Invalid flag_keys found:",e.flag_keys,"Expected array of non-empty strings")}get(){return this.sa}}var jl=se("[FeatureFlags]"),Ot=se("[FeatureFlags]",{debugEnabled:!0}),xi=`" failed. Feature flags didn't load in time.`,Ul="connection_error",Hl=t=>{for(var e={},s=0;t.length>s;s++)e[t[s]]=!0;return e},Wl=t=>{var e={};for(var s of Or(t||{})){var r=s[1];r&&(e[s[0]]=r)}return e},Xe=se("[Error tracking]"),zl="Refusing to render web experiment since the viewer is a likely bot",_f={icontains:(t,e)=>e.toLowerCase().indexOf(t.toLowerCase())>-1,not_icontains:(t,e)=>e.toLowerCase().indexOf(t.toLowerCase())===-1,regex:(t,e)=>pn(e,t),not_regex:(t,e)=>!pn(e,t),exact:(t,e)=>e===t,is_not:(t,e)=>e!==t};class ye{get Ne(){return this._instance.config}constructor(e){var s=this;this.getWebExperimentsAndEvaluateDisplayLogic=function(r){r===void 0&&(r=!1),s.getWebExperiments((n=>{ye.aa("retrieved web experiments from the server"),s.oa=new Map,n.forEach((i=>{if(i.feature_flag_key){var o;s.oa&&(ye.aa("setting flag key ",i.feature_flag_key," to web experiment ",i),(o=s.oa)==null||o.set(i.feature_flag_key,i));var a=s._instance.getFeatureFlag(i.feature_flag_key);W(a)&&i.variants[a]&&s.la(i.name,a,i.variants[a].transforms)}else if(i.variants)for(var l in i.variants){var u=i.variants[l];ye.ua(u,s._instance)&&s.la(i.name,l,u.transforms)}}))}),r)},this._instance=e,this._instance.onFeatureFlags((r=>{this.onFeatureFlags(r)}))}initialize(){}onFeatureFlags(e){if(this._is_bot())ye.aa(zl);else if(!this.Ne.disable_web_experiments){if(D(this.oa))return this.oa=new Map,this.loadIfEnabled(),void this.previewWebExperiment();ye.aa("applying feature flags",e),e.forEach((s=>{var r;if(this.oa&&(r=this.oa)!=null&&r.has(s)){var n,i=this._instance.getFeatureFlag(s),o=(n=this.oa)==null?void 0:n.get(s);i&&o!=null&&o.variants[i]&&this.la(o.name,i,o.variants[i].transforms)}}))}}previewWebExperiment(){var e=ye.getWindowLocation();if(e!=null&&e.search){var s=ms(e?.search,"__experiment_id"),r=ms(e?.search,"__experiment_variant");s&&r&&(ye.aa("previewing web experiments "+s+" && "+r),this.getWebExperiments((n=>{this.ha(parseInt(s),r,n)}),!1,!0))}}loadIfEnabled(){this.Ne.disable_web_experiments||this.getWebExperimentsAndEvaluateDisplayLogic()}getWebExperiments(e,s,r){if(this.Ne.disable_web_experiments&&!r)return e([]);var n=this._instance.get_property("$web_experiments");if(n&&!s)return e(n);this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/web_experiments/?token="+this.Ne.token),method:"GET",timestampMode:"query",callback:i=>e(i.statusCode===200&&i.json&&i.json.experiments||[])})}ha(e,s,r){var n=r.filter((i=>i.id===e));n&&n.length>0&&(ye.aa("Previewing web experiment ["+n[0].name+"] with variant ["+s+"]"),this.la(n[0].name,s,n[0].variants[s].transforms))}static ua(e,s){return!D(e.conditions)&&ye.da(e,s)&&ye.va(e)}static da(e,s){var r;if(D(e.conditions)||D((r=e.conditions)==null?void 0:r.url))return!0;var n=ye.getWindowLocation();if(n){var i,o,a,l=yu(s,n.href);return(i=e.conditions)==null||!i.url||_f[(o=(a=e.conditions)==null?void 0:a.urlMatchType)!==null&&o!==void 0?o:"icontains"](e.conditions.url,l)}return!1}static getWindowLocation(){return v?.location}static va(e){var s;if(D(e.conditions)||D((s=e.conditions)==null?void 0:s.utm))return!0;var r=Nu();if(r.utm_source){var n,i,o,a,l,u,c,d,h=(n=e.conditions)==null||(n=n.utm)==null||!n.utm_campaign||((i=e.conditions)==null||(i=i.utm)==null?void 0:i.utm_campaign)==r.utm_campaign,p=(o=e.conditions)==null||(o=o.utm)==null||!o.utm_source||((a=e.conditions)==null||(a=a.utm)==null?void 0:a.utm_source)==r.utm_source,f=(l=e.conditions)==null||(l=l.utm)==null||!l.utm_medium||((u=e.conditions)==null||(u=u.utm)==null?void 0:u.utm_medium)==r.utm_medium,g=(c=e.conditions)==null||(c=c.utm)==null||!c.utm_term||((d=e.conditions)==null||(d=d.utm)==null?void 0:d.utm_term)==r.utm_term;return h&&f&&g&&p}return!1}static aa(e){for(var s=arguments.length,r=new Array(s>1?s-1:0),n=1;s>n;n++)r[n-1]=arguments[n];k.info("[WebExperiments] "+e,r)}la(e,s,r){this._is_bot()?ye.aa(zl):s!=="control"?r.forEach((n=>{if(n.selector){var i;ye.aa("applying transform of variant "+s+" for experiment "+e+" ",n);var o=(i=document)==null?void 0:i.querySelectorAll(n.selector);o?.forEach((a=>{var l=a;n.html&&(l.innerHTML=n.html),n.css&&l.setAttribute("style",n.css)}))}})):ye.aa("Control variants leave the page unmodified.")}_is_bot(){return ke&&this._instance?Qu(ke,this.Ne.custom_blocked_useragents):void 0}}var Ue=se("[Conversations]"),Dt="Conversations not available yet.",ql="console",ld="__posthogHandledLogsRequestError",ki=(t,e)=>{var s=t instanceof Error?t:new Error(e);return s[ld]=!0,s},Vl=t=>!!t&&typeof t=="object"&&t[ld]===!0,Rn={featureFlags:class{constructor(t){this.name="featureFlags",this.ca=!1,this.featureFlagEventHandlers=[],this.rt=jl,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 vf(t.config,t.Qi()),this.Ta=this.Ea)}updateConfig(t,e){var s;(s=this.Ea)==null||s.update(t,e)}setup(t){return this.Ia=t,this.rt=t.logger.createLogger("[FeatureFlags]"),s=()=>{this.Ia===t&&(this.Ia=void 0,this.nn=t,this.Pa(t))},(e=t.kv.initialize())!=null&&e.then?e.then(s):s();var e,s}Pa(t){if(this.nn===t)return v&&ne(v,"online",this.Ca),this.Ra=t.registerDynamicEventProperties((()=>this.Aa()?this.fa:this.pa)),this.Fa(),this.initialize()}destroy(){v?.removeEventListener("online",this.Ca)}dispose(){var t;this.ba++,this.wa=!1,this.Ia=void 0,this.nn&&(this.La(),(t=this.Ra)==null||t.dispose(),this.Ra=void 0,this.ga=[],v?.removeEventListener("online",this.Ca),this.nn=void 0)}get Ne(){return this.Ta.get()}Oa(t){var e;return(e=this.nn)==null?void 0:e.kv.get(t)}F(t){this.Da((()=>{var e;return(e=this.nn)==null?void 0:e.kv.set(t)}))}q(t){this.Da((()=>{var e;return(e=this.nn)==null?void 0:e.kv.remove(t)}))}Da(t){try{t()}catch(e){this.rt.error("Failed to update feature flag persistence",e)}}Fa(){var t={};for(var e of[Us,Hs,Tr,et]){var s=this.Oa(e);x(s)||(t[e]=s)}this.fa=t;var r=w({},t),n=this.Oa(Bt);if(n)for(var i of Object.entries(n))r["$feature/"+i[0]]=i[1];this.pa=r}Aa(){var t=this.Ne.cacheTtlMs;if(!t||0>=t)return!1;var e=this.Oa(Gs);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 s=e&&typeof e=="string"&&e.trim().length>0;return s||this.rt.error("Invalid evaluation context found:",e,"Expected non-empty string"),s})):[]}qa(){var t=this.Ne.flagKeys;if(!x(t))return t.filter((e=>{var s=e&&typeof e=="string"&&e.trim().length>0;return s||this.rt.error("Invalid flag key found:",e,"Expected non-empty string"),s}))}initialize(){var t,e,s=this.Ne,r=(t=(e=s.bootstrap)==null?void 0:e.featureFlags)!==null&&t!==void 0?t:{};if(Object.keys(r).length){var n,i,o=(n=(i=s.bootstrap)==null?void 0:i.featureFlagPayloads)!==null&&n!==void 0?n:{},a=Object.keys(r).filter((u=>!!r[u])).reduce(((u,c)=>(u[c]=r[c]||!1,u)),{}),l=Object.keys(o).filter((u=>a[u])).reduce(((u,c)=>(o[c]&&(u[c]=o[c]),u)),{});return this.ja({featureFlags:a,featureFlagPayloads:l})}}updateFlags(t,e,s){var r,n,i=s!=null&&s.merge&&(r=this.Oa(Bt))!==null&&r!==void 0?r:{},o=s!=null&&s.merge&&(n=this.Oa(Hs))!==null&&n!==void 0?n:{},a=w({},i,t),l=w({},o,e),u={};for(var c of Object.entries(a)){var d=c[0],h=c[1];u[d]={key:d,enabled:Da(h),variant:Ba(h),reason:void 0,metadata:x(l?.[d])?void 0:{id:0,version:void 0,description:void 0,payload:l[d]}}}this.ja({flags:u})}get hasLoadedFlags(){return this.ma}getFlags(){return Object.keys(this.getFlagVariants())}getFlagsWithDetails(){var t=this.Oa(Ki),e=this.Oa(et),s=this.Oa(jt);if(!s&&!e)return t||{};var r=ee({},t||{}),n=[...new Set([...Object.keys(s||{}),...Object.keys(e||{})])];for(var i of n){var o,a,l=r[i],u=e?.[i],c=x(u)?(o=l?.enabled)!==null&&o!==void 0&&o:!!u,d=x(u)?l?.variant:typeof u=="string"?u:void 0,h=s?.[i],p=w({},l,{enabled:c,variant:c?d??l?.variant:void 0});c!==l?.enabled&&(p.original_enabled=l?.enabled),d!==l?.variant&&(p.original_variant=l?.variant),h&&(p.metadata=w({},l?.metadata,{payload:h,original_payload:l==null||(a=l.metadata)==null?void 0:a.payload})),r[i]=p}return this.ca||(this.rt.warn(" Overriding feature flag details!",{flagDetails:t,overriddenPayloads:s,finalDetails:r}),this.ca=!0),r}getAllFeatureFlags(){var t=this.getFlagVariants(),e=this.getFlagPayloads();return Object.keys(t).map((s=>{var r=t[s];return{key:s,enabled:Da(r),variant:Ba(r),payload:Oa(e[s])}}))}getFlagVariants(){var t=this.Oa(Bt),e=this.Oa(et);if(!e)return t||{};for(var s=ee({},t||{}),r=Object.keys(e),n=0;r.length>n;n++)s[r[n]]=e[r[n]];return this.ca||(this.rt.warn(" Overriding feature flags!",{enabledFlags:t,overriddenFlags:e,finalFlags:s}),this.ca=!0),s}getFlagPayloads(){var t=this.Oa(Hs),e=this.Oa(jt);if(!e)return t||{};for(var s=ee({},t||{}),r=Object.keys(e),n=0;r.length>n;n++)s[r[n]]=e[r[n]];return this.ca||(this.rt.warn(" Overriding feature flag payloads!",{flagPayloads:t,overriddenPayloads:e,finalPayloads:s}),this.ca=!0),s}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(Wt)}Ha(t){this.La();var e=this.nn;if(e&&!this.Ne.remoteRequestsDisabled&&!this.Ma())if(this.ya)this.wa=!0;else{var s={token:e.projectToken,distinct_id:e.distinctId,groups:e.groups,$anon_distinct_id:this.$anon_distinct_id,person_properties:w({},e.initialPersonProperties,this.Oa(ct)||{},{$lib:e.library.name,$lib_version:e.library.version}),group_properties:this.Oa(Ut),timezone:ju()};x(e.deviceId)||(s.$device_id=e.deviceId),(t!=null&&t.disableFlags||this.Ne.featureFlagsDisabled)&&(s.disable_flags=!0);var r=this.Na();r.length&&(s.evaluation_contexts=r);var n=this.qa();x(n)||(s.flag_keys=n);var i=this.Ne.onlyEvaluateSurveyFeatureFlags,o="/flags/?v=2"+(i?"&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({[Lr]:[Ul]}),this.rt.error("Feature flag request failed",c)),l()};try{e.sendRequest(o,{target:"flags",method:"POST",body:s,compression:this.Ne.compression==="base64"?xe.Base64:void 0,sentAt:"body",timeoutMs:this.Ne.requestTimeoutMs}).then((c=>{var d,h,p=(d=c.json)!==null&&d!==void 0?d:{},f=c.statusCode!==200;if(this.ya=!1,a===this.ba){if(this.Ua(c.statusCode),f||this.wa||(this.$anon_distinct_id=void 0),!s.disable_flags||this.wa){this.ka=!f;var g=[];c.error?g.push(c.error instanceof Error&&c.error.name==="AbortError"?"timeout":c.error instanceof Error?Ul:"unknown_error"):c.statusCode!==200&&g.push("api_error_"+c.statusCode),p.errorsWhileComputingFlags&&g.push("errors_while_computing_flags");var m=!((h=p.quotaLimited)==null||!h.includes("feature_flags"));m&&g.push("quota_limited"),this.F({[Lr]: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."):s.disable_flags||this.ja(p,f,{partialResponse:i}),l()}}else l()})).catch(u)}catch(c){u(c)}}}Ma(){return Ru(this.Sa,3)}Ua(t){this.Sa=Tu(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 s;if(e===void 0&&(e={}),!e.fresh||this.ka)if(this.ma||this.getFlags()&&this.getFlags().length>0){if(!this.$a()){var r=this.getFeatureFlagResult(t,e);return(s=r?.variant)!==null&&s!==void 0?s:r?.enabled}}else this.rt.warn('getFeatureFlag for key "'+t+xi)}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 s,r=this.getFlagVariants(),n=t in r,i=r[t],o=this.getFlagPayloads()[t],a=String(i),l=this.Oa(Tr)||void 0,u=this.Oa(Gs)||void 0,c=this.Oa(Wt)||{};if(this.Ne.deduplicateCallsPerSession){var d,h=(d=this.nn)==null?void 0:d.session.sessionId,p=this.Oa(zs);h&&h!==p&&(c={},s=h)}if(e.send_event||!("send_event"in e))if(t in c&&c[t].includes(a))s&&this.F({[Wt]:c,[zs]:s});else{var f,g,m,_,b,E,I,F,P,B;L(c[t])?c[t].push(a):c[t]=[a],this.F(w({[Wt]:c},s?{[zs]:s}:{}));var S=this.getFeatureFlagDetails(t),A=[...(f=this.Oa(Lr))!==null&&f!==void 0?f:[]];x(i)&&A.push("flag_missing");var R={$feature_flag:t,$feature_flag_response:i,$feature_flag_payload:o||null,$feature_flag_request_id:l,$feature_flag_evaluated_at:u,$feature_flag_bootstrapped_response:((g=this.Ne.bootstrap)==null||(g=g.featureFlags)==null?void 0:g[t])||null,$feature_flag_bootstrapped_payload:((m=this.Ne.bootstrap)==null||(m=m.featureFlagPayloads)==null?void 0:m[t])||null,$used_bootstrap_value:!this.ka};x(S==null||(_=S.metadata)==null?void 0:_.has_experiment)||(R.$feature_flag_has_experiment=S.metadata.has_experiment),x(S==null||(b=S.metadata)==null?void 0:b.version)||(R.$feature_flag_version=S.metadata.version);var N,T=(E=S==null||(I=S.reason)==null?void 0:I.description)!==null&&E!==void 0?E:S==null||(F=S.reason)==null?void 0:F.code;T&&(R.$feature_flag_reason=T),S!=null&&(P=S.metadata)!=null&&P.id&&(R.$feature_flag_id=S.metadata.id),x(S?.original_variant)&&x(S?.original_enabled)||(R.$feature_flag_original_response=x(S.original_variant)?S.original_enabled:S.original_variant),S!=null&&(B=S.metadata)!=null&&B.original_payload&&(R.$feature_flag_original_payload=S==null||(N=S.metadata)==null?void 0:N.original_payload),A.length&&(R.$feature_flag_error=A.join(",")),this.za(R)}else s&&this.F({[Wt]:c,[zs]:s});if(n)return{key:t,enabled:!!i,variant:typeof i=="string"?i:void 0,payload:Oa(o)}}}else this.rt.warn('getFeatureFlagResult for key "'+t+xi)}za(t){try{var e;(e=this.nn)==null||e.capture("$feature_flag_called",t).catch((s=>{this.rt.error("Failed to capture feature flag call",s)}))}catch(s){this.rt.error("Failed to capture feature flag call",s)}}getRemoteConfigPayload(t,e){this.Wa(t,e)}Wa(t,e){var s=this;return X((function*(){var r=s.nn;if(r){var n={distinct_id:r.distinctId,token:r.projectToken,person_properties:{$lib:r.library.name,$lib_version:r.library.version}},i=s.Na();i.length&&(n.evaluation_contexts=i);var o,a=s.qa();x(a)||(n.flag_keys=a);try{var l,u=(l=(yield r.sendRequest("/flags/?v=2",{target:"flags",method:"POST",body:n,compression:s.Ne.compression==="base64"?xe.Base64:void 0,sentAt:"body",timeoutMs:s.Ne.requestTimeoutMs})).json)==null?void 0:l.featureFlagPayloads;o=u?.[t]||void 0}catch(c){return void s.rt.error("Remote config feature flag request failed",c)}try{e(o)}catch(c){s.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+xi),e.defaultValue;var s=this.getFeatureFlag(t,e);return x(s)?e.defaultValue:!!s}addFeatureFlagsHandler(t){this.featureFlagEventHandlers.push(t)}removeFeatureFlagsHandler(t){this.featureFlagEventHandlers=this.featureFlagEventHandlers.filter((e=>e!==t))}receivedFeatureFlags(t,e,s){this.ja(t,e,s)}ja(t,e,s){if(this.nn){this.ma=!0;var r=(function(n,i,o,a,l,u){i===void 0&&(i={}),o===void 0&&(o={}),a===void 0&&(a={}),u===void 0&&(u=jl);var c=((P,B)=>{var S=P.flags;return S?w({},P,{featureFlags:Object.fromEntries(Object.keys(S).map((A=>{var R;return[A,(R=S[A].variant)!==null&&R!==void 0?R:S[A].enabled]}))),featureFlagPayloads:Object.fromEntries(Object.keys(S).filter((A=>S[A].enabled)).filter((A=>{var R;return(R=S[A].metadata)==null?void 0:R.payload})).map((A=>{var R;return[A,(R=S[A].metadata)==null?void 0:R.payload]})))}):(P.featureFlags&&B.warn("Using an older version of the feature flags endpoint. Please upgrade your PostHog server to the latest version"),P)})(n,u),d=c.flags,h=c.featureFlags,p=c.featureFlagPayloads;if(h){var f=n.requestId,g=n.evaluatedAt;if(L(h)){u.warn("v1 of the feature flags endpoint is deprecated. Please use the latest version.");var m={};if(h)for(var _=0;h.length>_;_++)m[h[_]]=!0;return{[Us]:h,[Bt]:m,[en]:!1}}var b=h,E=p,I=d;if(l!=null&&l.partialResponse)b=w({},i,b),E=w({},o,E),I=w({},a,I);else if(n.errorsWhileComputingFlags)if(d){var F=new Set(Object.keys(d).filter((P=>{var B;return!((B=d[P])!=null&&B.failed)})));b=w({},i,Object.fromEntries(Object.entries(b).filter((P=>F.has(P[0]))))),E=w({},o,Object.fromEntries(Object.entries(E||{}).filter((P=>F.has(P[0]))))),I=w({},a,Object.fromEntries(Object.entries(I||{}).filter((P=>F.has(P[0])))))}else b=w({},i,b),E=w({},o,E),I=w({},a,I);return w({[Us]:Object.keys(Wl(b)),[Bt]:b||{},[Hs]:E||{},[Ki]:I||{},[en]:n.minimalFlagCalledEvents===!0},f?{[Tr]:f}:{},g?{[Gs]:g}:{})}})(t,this.getFlagVariants(),this.getFlagPayloads(),this.getFlagsWithDetails(),s,this.rt);r&&this.F(r),e||(this.xa=!1),this.Va(e)}}override(t,e){e===void 0&&(e=!1),this.rt.warn("override is deprecated. Please use overrideFeatureFlags instead."),this.overrideFeatureFlags({flags:t,suppressWarning:e})}overrideFeatureFlags(t){this.Za(t)}Za(t){if(this.nn){if(t===!1)return this.q([et,jt]),this.Va(),void Ot.info("All overrides cleared");if(L(t))return this.F({[et]:Hl(t)}),this.Va(),void Ot.info("Flag overrides set",{flags:t});if(t&&typeof t=="object"&&("flags"in t||"payloads"in t)){var e,s=t;this.ca=!!((e=s.suppressWarning)!==null&&e!==void 0&&e);var r={},n=s.flags,i=s.payloads;return n&&(r[et]=L(n)?Hl(n):n),i&&(r[jt]=i),Object.keys(r).length&&this.F(r),n===!1&&i===!1?this.q([et,jt]):n===!1?this.q(et):i===!1&&this.q(jt),this.Va(),n===!1?Ot.info("Flag overrides cleared"):n&&Ot.info("Flag overrides set",{flags:n}),void(i===!1?Ot.info("Payload overrides cleared"):i&&Ot.info("Payload overrides set",{payloads:i}))}if(t&&typeof t=="object")return this.F({[et]:t}),this.Va(),void Ot.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(),s=e.flags,r=e.flagVariants;try{t(s,r)}catch(n){this.rt.error("Error while running feature flags callback",n)}}return()=>this.removeFeatureFlagsHandler(t)}updateEarlyAccessFeatureEnrollment(t,e,s){var r=(this.Oa(Rr)||[]).find((l=>l.flagKey===t)),n={["$feature_enrollment/"+t]:e},i={$feature_flag:t,$feature_enrollment:e,$set:n};r&&(i.$early_access_feature_name=r.name),s&&(i.$feature_enrollment_stage=s);var o=w({},this.getFlagVariants(),{[t]:e});this.F({[Us]:Object.keys(Wl(o)),[Bt]:o,[ct]:w({},this.Oa(ct)||{},n)}),this.Va();try{var a;(a=this.nn)==null||a.capture("$feature_enrollment_update",i).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,s){e===void 0&&(e=!1);var r=this.Oa(Rr);!r||e?this.Qa(t,s):t(r)}Qa(t,e){var s=this;return X((function*(){var r=s.nn;if(r){var n,i=e?"&"+e.map((a=>"stage="+a)).join("&"):"";try{var o=yield r.sendRequest("/api/early_access_features/?token="+r.projectToken+i,{target:"api",method:"GET",sentAt:"query"});if(!o.json)return;s.F({[Rr]:n=o.json.earlyAccessFeatures})}catch(a){return void s.rt.error("Early access feature request failed",a)}try{t(n)}catch(a){s.rt.error("Early access feature callback failed",a)}}}))()}Ga(){var t=this.getFlags(),e=this.getFlagVariants();return{flags:t.filter((s=>e[s])),flagVariants:Object.keys(e).filter((s=>e[s])).reduce(((s,r)=>(s[r]=e[r],s)),{})}}Va(t){this.Fa();var e=this.Ga(),s=e.flags,r=e.flagVariants;this.featureFlagEventHandlers.forEach((n=>{try{n(s,r,{errorsLoading:t})}catch(i){this.rt.error("Error while running feature flags callback",i)}}))}setPersonPropertiesForFlags(t,e){e===void 0&&(e=!0),this.Ka(t,e)}Ka(t,e){e===void 0&&(e=!0);var s=this.Oa(ct)||{},r=t?.$set||(t!=null&&t.$set_once?{}:t),n=t?.$set_once,i={};if(n)for(var o in n)({}).hasOwnProperty.call(n,o)&&(o in s||(i[o]=n[o]));this.F({[ct]:w({},s,i,r)}),e&&this.reloadFeatureFlags()}unsetPersonPropertiesForFlags(t,e){e===void 0&&(e=!0);var s=w({},this.Oa(ct)||{});t.forEach((r=>{delete s[r]})),this.F({[ct]:s}),e&&this.reloadFeatureFlags()}resetPersonPropertiesForFlags(t){t===void 0&&(t=!0),this.q(ct),t&&this.reloadFeatureFlags()}setGroupPropertiesForFlags(t,e){e===void 0&&(e=!0);var s=this.Oa(Ut)||{},r=w({},s);for(var n of Object.keys(t))r[n]=w({},s[n],t[n]);this.F({[Ut]:r}),e&&this.reloadFeatureFlags()}resetGroupPropertiesForFlags(t){if(t){var e=this.Oa(Ut)||{};this.F({[Ut]:w({},e,{[t]:{}})})}else this.q(Ut)}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}}},yf={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===Ls||this.Ya===Fr?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=Tl,this.Xa=void 0,this.eo=!1,this.io=(()=>{var e;if(C==null||!C.visibilityState||C.visibilityState==="visible")return!0;var s=v==null||(e=v.performance)==null||e.getEntriesByType==null?void 0:e.getEntriesByType("visibility-state");return!(s!=null&&s.length)||s.some((r=>r.name==="visible"))})(),this.Ie=()=>{var e;C?.visibilityState==="visible"&&(this.io=!0,(e=this.Ja)==null||e.setDocumentWasEverVisible==null||e.setDocumentWasEverVisible(!0))},this._instance=t,!this._instance.sessionManager)throw at.error("started without valid sessionManager"),new Error(po+" started without valid sessionManager. This is a bug.");if(this.Ne.cookieless_mode===ht)throw new Error(po+' cannot be used with cookieless_mode="always"');C!=null&&C.addEventListener&&ne(C,"visibilitychange",this.Ie)}initialize(){this.startIfEnabledOrStop()}dispose(){this.eo=!0,C==null||C.removeEventListener==null||C.removeEventListener("visibilitychange",this.Ie),this.stopRecording()}get ro(){var t,e=!((t=this._instance.get_property(qt))==null||!t.enabled),s=!this.Ne.disable_session_recording,r=this.Ne.disable_session_recording||this._instance.consent.isOptedOut();return v&&e&&s&&!r}startIfEnabledOrStop(t){var e;if(!(this.eo||this.ro&&(e=this.Ja)!=null&&e.isStarted)){var s=!x(Object.assign)&&!x(Array.from);this.ro&&s?(this.no(t),at.info("starting")):(this.Ya=Tl,this.stopRecording())}}no(t){var e,s,r;this.ro&&(this.Ya!==Ls&&this.Ya!==Fr&&(this.Ya=Nl),$!=null&&(e=$.__PosthogExtensions__)!=null&&(e=e.rrweb)!=null&&e.record&&(s=$.__PosthogExtensions__)!=null&&s.initSessionRecording?this.so(t):(r=$.__PosthogExtensions__)==null||r.loadExternalDependency==null||r.loadExternalDependency(this._instance,this.ao,(n=>{if(n)return at.error("could not load recorder",n);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(zo),(e=this.Mr)==null||e.unregister(lu)}uo(t,e){if(D(t))return null;var s,r=he(t)?t:parseFloat(t);return typeof(s=r)!="number"||!Number.isFinite(s)||0>s||s>1?(at.warn(e+" must be between 0 and 1. Ignoring invalid value:",t),null):r}ho(t){if(this.Mr){var e,s,r=this.Mr,n=()=>{var i,o=t.sessionRecording===!1?void 0:t.sessionRecording,a=this.uo((i=this.Ne.session_recording)==null?void 0:i.sampleRate,"session_recording.sampleRate"),l=this.uo(o?.sampleRate,"remote config sampleRate"),u=a??l;D(u)&&this.lo();var c=o?.minimumDurationMilliseconds;r.register({[qt]:w({cache_timestamp:Date.now(),enabled:!!o},o,{networkPayloadCapture:w({capturePerformance:t.capturePerformance},o?.networkPayloadCapture),canvasRecording:{enabled:o?.recordCanvas,fps:o?.canvasFps,quality:o?.canvasQuality},sampleRate:u,minimumDurationMilliseconds:x(c)?null:c,endpoint:o?.endpoint,triggerMatchType:o?.triggerMatchType,masking:o?.masking,urlTriggers:o?.urlTriggers,version:o?.version,triggerGroups:o?.triggerGroups})})};n(),(e=this.Xa)==null||e.call(this),this.Xa=(s=this._instance.sessionManager)==null?void 0:s.onSessionId(n)}}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===Ls&&(this.Ya=Fr,at.warn("config refresh failed, recording will not start until page reload")),void this.startIfEnabledOrStop())}log(t,e){var s;e===void 0&&(e="log"),(s=this.Ja)!=null&&s.log?this.Ja.log(t,e):at.warn("log called before recorder was ready")}get ao(){var t,e,s=(t=this._instance)==null||(t=t.persistence)==null?void 0:t.get_property(qt);return(s==null||(e=s.scriptConfig)==null?void 0:e.script)||"lazy-recorder"}do(){var t,e=this._instance.get_property(qt);if(!e)return!1;try{t=typeof e=="object"?e:JSON.parse(e)}catch(s){return at.warn("persisted remote config for session recording is invalid and will be ignored",s),!1}return!D(t.cache_timestamp)&&36e5>=Date.now()-t.cache_timestamp}so(t){var e,s,r;if(!this.eo){if((e=$.__PosthogExtensions__)==null||!e.initSessionRecording)return at.warn("Called on script loaded before session recording is available. This can be caused by adblockers."),void this._instance.register_for_session({[mu]:!0});var n;if(this.Ja||(this.Ja=(n=$.__PosthogExtensions__)==null?void 0:n.initSessionRecording(this._instance,this.io),this.Ja._forceAllowLocalhostNetworkCapture=this._forceAllowLocalhostNetworkCapture),!this.do())return this.Ya===Fr||this.Ya===Ls?void 0:(this.Ya=Ls,at.info("persisted remote config is stale, requesting fresh config before starting"),void new Uu(this._instance).load());this.Ya=Nl,(s=(r=this.Ja).setDocumentWasEverVisible)==null||s.call(r,this.io),this.Ja.start(t)}}onRRwebEmit(t){var e;(e=this.Ja)==null||e.onRRwebEmit==null||e.onRRwebEmit(t)}overrideLinkedFlag(){var t,e;this.Ja||(e=this.Mr)==null||e.register({[uu]:!0}),(t=this.Ja)==null||t.overrideLinkedFlag()}overrideSampling(){var t,e;this.Ja||(e=this.Mr)==null||e.register({[cu]:!0}),(t=this.Ja)==null||t.overrideSampling()}overrideTrigger(t){var e,s;this.Ja||(s=this.Mr)==null||s.register({[t==="url"?du:hu]:!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 s;return!((s=this.Ja)==null||!s.tryAddCustomEvent(t,e))}}},wf={autocapture:class{constructor(t){this.vo=!1,this.co=null,this.fo=!1,this.po=!1,this.instance=t,this.rageclicks=new Al(t.config.rageclick),this.mo=null}initialize(){this.startIfEnabled()}get Ne(){var t,e,s=te(this.instance.config.autocapture)?this.instance.config.autocapture:{};return s.url_allowlist=(t=s.url_allowlist)==null?void 0:t.map((r=>new RegExp(r))),s.url_ignorelist=(e=s.url_ignorelist)==null?void 0:e.map((r=>new RegExp(r))),s}yo(){if(this.isBrowserSupported()){if(v&&C){var t=s=>{s=s||v?.event;try{this.bo(s)}catch(r){wi.error("Failed to capture event",r)}};if(ne(C,"submit",t,{capture:!0}),ne(C,"change",t,{capture:!0}),ne(C,"click",t,{capture:!0}),this.Ne.capture_copied_text){var e=s=>{s=s||v?.event;try{this.bo(s,yi)}catch(r){wi.error("Failed to capture copy/cut event",r)}};ne(C,"copy",e,{capture:!0}),ne(C,"cut",e,{capture:!0})}}}else wi.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 s=e.autocapture_opt_out;Ke(s)&&(this.instance.persistence&&this.instance.persistence.register({[Ui]:s}),this.co=s),this.startIfEnabled()}else this.startIfEnabled()}setElementSelectors(t){this.mo=t}getElementSelectors(t){var e,s=[];return(e=this.mo)==null||e.forEach((r=>{var n=C?.querySelectorAll(r);n?.forEach((i=>{t===i&&s.push(r)}))})),s}get isEnabled(){var t,e,s=(t=this.instance.persistence)==null?void 0:t.props[Ui],r=this.co,n=this.instance.Qi()&&!this.fo;if($e(r)&&!Ke(s)&&!n)return!1;var i=(e=this.co)!==null&&e!==void 0?e:!!s;return!!this.instance.config.autocapture&&!i}bo(t,e){if(e===void 0&&(e="$autocapture"),this.isEnabled){var s,r=ai(t);bu(r)&&(r=r.parentNode||null),e==="$autocapture"&&t.type==="click"&&t instanceof MouseEvent&&this.instance.config.rageclick&&(s=this.rageclicks)!=null&&s.isRageClick(t.clientX,t.clientY,t.timeStamp||new Date().getTime())&&ol(r,this.instance.config.rageclick)&&this.bo(t,"$rageclick");var n=e===yi;if(r&&(function(d,h,p,f,g,m){var _;if(!v||Jo(d)||p!=null&&p.url_allowlist&&!rl(p.url_allowlist,m)||p!=null&&p.url_ignorelist&&rl(p.url_ignorelist,m))return!1;if(p!=null&&p.dom_event_allowlist){var b=p.dom_event_allowlist;if(b&&!b.some((S=>h.type===S)))return!1}var E=Cu(d,f),I=E.parentIsUsefulElement,F=E.targetElementList;if(!(function(S,A){var R=A?.element_allowlist;if(x(R))return!0;var N,T=function(J){if(R.some((z=>J.tagName.toLowerCase()===z)))return{v:!0}};for(var O of S)if(N=T(O))return N.v;return!1})(F,p)||!ro(F,p?.css_selector_allowlist)||ro(F,(_=p?.css_selector_ignorelist)!==null&&_!==void 0?_:mp))return!1;try{var P=v.getComputedStyle(d);if(P&&P.getPropertyValue("cursor")==="pointer"&&h.type==="click")return!0}catch{}var B=d.tagName.toLowerCase();switch(B){case"html":return!1;case"form":return(g||["submit"]).indexOf(h.type)>=0;case"input":case"select":case"textarea":return(g||["change","click"]).indexOf(h.type)>=0;default:return I?(g||["click"]).indexOf(h.type)>=0:(g||["click"]).indexOf(h.type)>=0&&(Ko.indexOf(B)>-1||d.getAttribute("contenteditable")==="true")}})(r,t,this.Ne,n,n?["copy","cut"]:void 0,this.instance)){var i=cf(r,{e:t,maskAllElementAttributes:this.instance.config.mask_all_element_attributes,maskAllText:this.instance.config.mask_all_text,elementAttributeIgnoreList:this.Ne.element_attribute_ignorelist,elementsChainAsString:this.po,disableCaptureUrlHashes:this.instance.config.disable_capture_url_hashes}),o=i.props;if(i.explicitNoCapture)return!1;var a=this.getElementSelectors(r);if(a&&a.length>0&&(o.$element_selectors=a),e===yi){var l,u=xu(v==null||(l=v.getSelection())==null?void 0:l.toString()),c=t.type||"clipboard";if(!u)return!1;o.$selected_content=u,o.$copy_type=c}return this.instance.capture(e,o),!0}}}isBrowserSupported(){return Se(C?.querySelectorAll)}},historyAutocapture:class{constructor(t){var e;this._instance=t,this._o=(v==null||(e=v.location)==null?void 0:e.pathname)||""}initialize(){this.startIfEnabled()}get isEnabled(){return this._instance.config.capture_pageview==="history_change"}startIfEnabled(){this.isEnabled&&(k.info("History API monitoring enabled, starting..."),this.monitorHistoryChanges())}stop(){this.wo&&this.wo(),this.wo=void 0,k.info("History API monitoring stopped")}monitorHistoryChanges(){v&&v.history&&(this.ko("pushState"),this.ko("replaceState"),this.xo())}ko(t){var e;if(v&&((e=v.history[t])==null||!e.__posthog_wrapped__)){var s=this;(function(r,n,i){try{if(!(n in r))return $l;var o={next:r[n]},a=i((function(){for(var l=arguments.length,u=new Array(l),c=0;l>c;c++)u[c]=arguments[c];return o.next.apply(this,u)}));return Se(a)&&(a.prototype=a.prototype||{},Object.defineProperties(a,{__posthog_wrapped__:{enumerable:!1,value:!0},__posthog_layer__:{enumerable:!1,value:o}})),r[n]=a,()=>{if(r[n]!==a)for(var l=r[n];Se(l)&&l.__posthog_layer__;){var u=l.__posthog_layer__;if(u.next===a)return void(u.next=o.next);l=u.next}else r[n]=o.next}}catch{return $l}})(v.history,t,(r=>function(n,i,o){r.call(this,n,i,o),s.So(t)}))}}So(t){try{var e,s=v==null||(e=v.location)==null?void 0:e.pathname;if(!s)return;s!==this._o&&this.isEnabled&&this._instance.capture(is,{navigation_type:t}),this._o=s}catch(r){k.error("Error capturing "+t+" pageview",r)}}xo(){if(!this.wo){var t=()=>{this.So("popstate")};ne(v,"popstate",t),this.wo=()=>{v&&v.removeEventListener("popstate",t)}}}},heatmaps:class{get Ne(){return this.instance.config}constructor(t){var e;this.Co=!1,this.vo=!1,this.Mo=null,this.instance=t,this.Co=!((e=this.instance.persistence)==null||!e.props[Hi]),this.rageclicks=new Al(t.config.rageclick)}initialize(){this.startIfEnabled()}get flushIntervalMilliseconds(){var t=5e3;return te(this.Ne.capture_heatmaps)&&this.Ne.capture_heatmaps.flush_interval_milliseconds&&(t=this.Ne.capture_heatmaps.flush_interval_milliseconds),t}get isEnabled(){return D(this.Ne.capture_heatmaps)?D(this.Ne.enable_heatmaps)?this.Co:this.Ne.enable_heatmaps:this.Ne.capture_heatmaps!==!1}startIfEnabled(){if(this.isEnabled){if(this.vo)return;df.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 s=!!e.heatmaps;this.instance.persistence&&this.instance.persistence.register({[Hi]:s}),this.Co=s,this.startIfEnabled()}}}getAndClearBuffer(){var t=this.R;return this.R=void 0,t}Io(t){Ei(t.originalEvent)&&this.ke(t.originalEvent,"deadclick")}Ie(){this.Mo&&clearInterval(this.Mo),this.Mo=C?.visibilityState==="visible"?setInterval(this.cr.bind(this),this.flushIntervalMilliseconds):null}To(){v&&C&&(this.Po=this.cr.bind(this),ne(v,on,this.Po),this.Ro=t=>this.ke(t||v?.event),ne(C,"click",this.Ro,{capture:!0}),this.Ao=t=>this.Fo(t||v?.event),ne(C,"mousemove",this.Ao,{capture:!0}),this.Lo=new pl(this.instance,Sp,this.Io.bind(this)),this.Lo.startIfEnabledOrStop(),this.Oo=this.Ie.bind(this),ne(C,nn,this.Oo),this.vo=!0)}Eo(){var t;v&&C&&(this.Po&&v.removeEventListener(on,this.Po),this.Ro&&C.removeEventListener("click",this.Ro,{capture:!0}),this.Ao&&C.removeEventListener("mousemove",this.Ao,{capture:!0}),this.Oo&&C.removeEventListener(nn,this.Oo),clearTimeout(this.Do),(t=this.Lo)==null||t.stop(),this.vo=!1)}$o(t,e){var s=this.instance.scrollManager.scrollY(),r=this.instance.scrollManager.scrollX(),n=this.instance.scrollManager.scrollElement(),i=(function(o,a,l){for(var u=o;u&&Ft(u)&&!Me(u,"body");){if(u===l)return!1;var c=void 0;try{var d,h,p;c=(d=(h=(p=u.ownerDocument)==null?void 0:p.defaultView)!==null&&h!==void 0?h:v)==null?void 0:d.getComputedStyle(u).position}catch{return!1}if(M(a,c))return!0;u=ku(u)}return!1})(ai(t),["fixed","sticky"],n);return{x:t.clientX+(i?0:r),y:t.clientY+(i?0:s),target_fixed:i,type:e}}ke(t,e){var s;if(e===void 0&&(e="click"),!sl(t.target)&&Ei(t)){var r=this.$o(t,e);(s=this.rageclicks)!=null&&s.isRageClick(t.clientX,t.clientY,new Date().getTime())&&ol(ai(t),this.instance.config.rageclick)&&this.Vt(w({},r,{type:"rageclick"})),this.Vt(r)}}Fo(t){!sl(t.target)&&Ei(t)&&(clearTimeout(this.Do),this.Do=setTimeout((()=>{this.Vt(this.$o(t,"mousemove"))}),500))}Vt(t){if(v){var e=this.Ne.disable_capture_url_hashes?Ct(v.location.href):v.location.href,s=this.Ne.custom_personal_data_properties,r=this.Ne.mask_personal_data_properties?[...vs,...s||[]]:[],n=nr(e,r,ir);this.R=this.R||{},this.R[n]||(this.R[n]=[]),this.R[n].push(t)}}cr(){this.R&&!mt(this.R)&&this.instance.capture("$$heatmap",{$heatmap_data:this.getAndClearBuffer()})}},deadClicksAutocapture:pl,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",w({$current_url:this.R.url},this.R.metrics.reduce(((s,r)=>w({},s,{["$web_vitals_"+r.name+"_event"]:w({},r),["$web_vitals_"+r.name+"_value"]:r.value})),{}))),this.R={navigationKey:void 0,url:void 0,metrics:[],firstMetricTimestamp:void 0})},this.jo=s=>{var r;if(this.R=this.R||{navigationKey:void 0,url:void 0,metrics:[],firstMetricTimestamp:void 0},D(s?.name)||D(s?.value))Lt.error("Invalid metric received",s);else{var n=typeof s.navigationURL=="string"?s.navigationURL:void 0,i=this.Bo(n);if(!x(i)){var o=he(s.navigationId)||typeof s.navigationId=="string"?"navigation:"+s.navigationId:"url:"+i;if(!this.Ho||this.Ho>s.value){this.R.navigationKey!==o&&(this.No(),this.qo=setTimeout(this.No,this.flushToCaptureTimeoutMs)),x(this.R.navigationKey)&&(this.R.navigationKey=o,this.R.url=i),this.R.firstMetricTimestamp=x(this.R.firstMetricTimestamp)?Date.now():this.R.firstMetricTimestamp,s.attribution&&s.attribution.interactionTargetElement&&(s.attribution.interactionTargetElement=void 0);var a=(r=this._instance.sessionManager)==null?void 0:r.checkAndGetSessionAndWindowId(!0),l=w({},s,n?{navigationURL:i}:{},{$current_url:i,timestamp:Date.now()});x(a)||(l.$session_id=a.sessionId,l.$window_id=a.windowId),this.R.metrics.push(l),this.R.metrics.length===this.allowedMetrics.length&&this.No()}else Lt.error("Ignoring metric with value >= "+this.Ho,s)}}},this.Uo=()=>{if(!this.vo){var s,r,n,i,o=$.__PosthogExtensions__,a=o?.postHogWebVitalsCallbacksByFlavor,l=a?.[this.zo]||(this.zo==="web-vitals"&&x(a)?o?.postHogWebVitalsCallbacks:void 0);if(x(l)||(s=l.onLCP,r=l.onCLS,n=l.onFCP,i=l.onINP),s&&r&&n&&i){var u={reportSoftNavs:this.useSoftNavs};this.allowedMetrics.indexOf("LCP")>-1&&s(this.jo.bind(this),u),this.allowedMetrics.indexOf("CLS")>-1&&r(this.jo.bind(this),u),this.allowedMetrics.indexOf("FCP")>-1&&n(this.jo.bind(this),u),this.allowedMetrics.indexOf("INP")>-1&&i(this.jo.bind(this),u),this.vo=!0}else Lt.error("web vitals callbacks not loaded - not starting")}},this._instance=t,this.Co=!((e=this._instance.persistence)==null||!e.props[Vi]),this.startIfEnabled()}get Wo(){return this._instance.config.capture_performance}get allowedMetrics(){var t,e,s=te(this.Wo)?(t=this.Wo)==null?void 0:t.web_vitals_allowed_metrics:void 0;return D(s)?((e=this._instance.persistence)==null?void 0:e.props[Gi])||["CLS","FCP","INP","LCP"]:s}get flushToCaptureTimeoutMs(){return(te(this.Wo)?this.Wo.web_vitals_delayed_flush_ms:void 0)||5e3}get useAttribution(){var t=te(this.Wo)?this.Wo.web_vitals_attribution:void 0;return t!=null&&t}get useSoftNavs(){var t=te(this.Wo)?this.Wo.__preview_web_vitals_soft_navs:void 0;return t!=null&&t}get Ho(){var t=te(this.Wo)&&he(this.Wo.__web_vitals_max_value)?this.Wo.__web_vitals_max_value:Rl;return t>0&&6e4>=t?Rl:t}get isEnabled(){var t=re?.protocol;if(t!=="http:"&&t!=="https:")return Lt.info("Web Vitals are disabled on non-http/https protocols"),!1;var e=te(this.Wo)?this.Wo.web_vitals:Ke(this.Wo)?this.Wo:void 0;return Ke(e)?e:this.Co}startIfEnabled(){this.isEnabled&&!this.vo&&(Lt.info("enabled, starting..."),this.ai(this.Uo))}onRemoteConfig(t){if(t.ok){var e=t.config;if("capturePerformance"in e){var s=te(e.capturePerformance)&&!!e.capturePerformance.web_vitals,r=te(e.capturePerformance)?e.capturePerformance.web_vitals_allowed_metrics:void 0;this._instance.persistence&&(this._instance.persistence.register({[Vi]:s}),this._instance.persistence.register({[Gi]:r})),this.Co=s,this.startIfEnabled()}}}get zo(){return this.useSoftNavs?this.useAttribution?"web-vitals-with-attribution-soft-navs":"web-vitals-soft-navs":this.useAttribution?"web-vitals-with-attribution":"web-vitals"}ai(t){var e=$.__PosthogExtensions__,s=this.zo,r=e?.postHogWebVitalsCallbacksByFlavor;r!=null&&r[s]||s==="web-vitals"&&x(r)&&e!=null&&e.postHogWebVitalsCallbacks?t():e==null||e.loadExternalDependency==null||e.loadExternalDependency(this._instance,s,(n=>{n?Lt.error("failed to load script",n):t()}))}Bo(t){var e=t||v?.location.href;if(e){var s=this._instance.config.disable_capture_url_hashes?Ct(e):e,r=this._instance.config.custom_personal_data_properties,n=this._instance.config.mask_personal_data_properties?[...vs,...r||[]]:[];return nr(s,n,ir)}Lt.error("Could not determine current URL")}}},bf={exceptionObserver:class{constructor(t){var e;this.Uo=()=>{var s;if(v&&this.isEnabled&&(s=$.__PosthogExtensions__)!=null&&s.errorWrappingFunctions){var r=$.__PosthogExtensions__.errorWrappingFunctions.wrapOnError,n=$.__PosthogExtensions__.errorWrappingFunctions.wrapUnhandledRejection,i=$.__PosthogExtensions__.errorWrappingFunctions.wrapConsoleError;try{!this.Vo&&this.Ne.capture_unhandled_errors&&(this.Vo=r(this.captureException.bind(this))),!this.Zo&&this.Ne.capture_unhandled_rejections&&(this.Zo=n(this.captureException.bind(this))),!this.Go&&this.Ne.capture_console_errors&&(this.Go=i(this.captureException.bind(this)))}catch(o){Ms.error("failed to start",o),this.Qo()}}},this._instance=t,this.Ko=!((e=this._instance.persistence)==null||!e.props[Wi]),this.Jo=new _h(w({},(function(s){var r,n,i,o;return s===void 0&&(s={}),{refillRate:(r=(n=s.exceptionRateLimiterRefillRate)!==null&&n!==void 0?n:s.__exceptionRateLimiterRefillRate)!==null&&r!==void 0?r:1,bucketSize:(i=(o=s.exceptionRateLimiterBucketSize)!==null&&o!==void 0?o:s.__exceptionRateLimiterBucketSize)!==null&&i!==void 0?i:10}})(this._instance.config.error_tracking),{refillInterval:1e4,rt:Ms})),this.Ne=this.Yo(),this.startIfEnabledOrStop()}Yo(){var t=this._instance.config.capture_exceptions,e={capture_unhandled_errors:!1,capture_unhandled_rejections:!1,capture_console_errors:!1};return te(t)?e=w({},e,t):(x(t)?this.Ko:t)&&(e=w({},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?(Ms.info("enabled"),this.Qo(),this.ai(this.Uo)):this.Qo()}ai(t){var e,s;(e=$.__PosthogExtensions__)!=null&&e.errorWrappingFunctions?t():(s=$.__PosthogExtensions__)==null||s.loadExternalDependency==null||s.loadExternalDependency(this._instance,"exception-autocapture",(r=>{if(r)return Ms.error("failed to load script",r);t()}))}Qo(){var t,e,s;(t=this.Vo)==null||t.call(this),this.Vo=void 0,(e=this.Zo)==null||e.call(this),this.Zo=void 0,(s=this.Go)==null||s.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({[Wi]:this.Ko}),this.Ne=this.Yo(),this.startIfEnabledOrStop())}}onConfigChange(){this.Ne=this.Yo()}captureException(t){var e,s,r,n=(e=t==null||(s=t.$exception_list)==null||(s=s[0])==null?void 0:s.type)!==null&&e!==void 0?e:"Exception";this.Jo.consumeRateLimit(n)?Ms.info("Skipping exception capture because of client rate limiting.",{exception:n}):(r=this._instance.exceptions)==null||r.sendExceptionEvent(t)}},exceptions:class{constructor(t){var e,s;this.Xo=[],this.tl=new Mh([new Wh,new Xh,new qh,new zh,new Yh,new Jh,new Gh,new Zh],(function(r){for(var n=arguments.length,i=new Array(n>1?n-1:0),o=1;n>o;o++)i[o-1]=arguments[o];return function(a,l){l===void 0&&(l=0);for(var u=[],c=a.split(` -`),d=l;c.length>d;d++){var h=c[d];if(1024>=h.length){var p=Xa.test(h)?h.replace(Xa,"$1"):h;if(!p.match(/\S*Error: /)){for(var f of i){var g=f(p,r);if(g){u.push(g);break}}if(u.length>=50)break}}}return(function(m){if(!m.length)return[];var _=Array.from(m);return _.reverse(),_.slice(0,50).map((b=>{return w({},b,{filename:b.filename||(E=_,E[E.length-1]||{}).filename,function:b.function||gs});var E}))})(u)}})("web:javascript",Bh,Hh)),this._instance=t,this.Xo=(e=(s=this._instance.persistence)==null?void 0:s.get_property(zi))!==null&&e!==void 0?e:[],this.el=Qr(this.il()),this.rl=new ep(this.el)}onConfigChange(){this.el=Qr(this.il()),this.rl.setConfig(this.el)}onRemoteConfig(t){var e,s,r;if(t.ok){var n=t.config;if("errorTracking"in n){var i=(e=(s=n.errorTracking)==null?void 0:s.suppressionRules)!==null&&e!==void 0?e:[],o=(r=n.errorTracking)==null?void 0:r.captureExtensionExceptions;this.Xo=i,this._instance.persistence&&this._instance.persistence.register({[zi]:this.Xo,[qi]:o})}}}get nl(){var t,e=!!this._instance.get_property(qi),s=this._instance.config.error_tracking.captureExtensionExceptions;return(t=s??e)!==null&&t!==void 0&&t}buildProperties(t,e){return this.tl.buildFromUnknown(t,{syntheticException:e?.syntheticException,mechanism:{handled:e?.handled}})}addExceptionStep(t,e){if(this.el.enabled)try{if(!W(t)||t.trim().length===0)return void Xe.warn("Ignoring exception step because message must be a non-empty string");var s=(function(i){if(!i)return{sanitizedProperties:{},droppedKeys:[]};var o=[];return{sanitizedProperties:Object.keys(i).reduce(((a,l)=>Qh.has(l)?(o.push(l),a):(a[l]=i[l],a)),{}),droppedKeys:o}})(this.sl(e)),r=s.sanitizedProperties,n=s.droppedKeys;n.length>0&&Xe.warn("Ignoring reserved exception step fields",{droppedKeys:n}),this.rl.add(w({[Zr]:t,[Xr]:new Date().toISOString()},r))}catch(i){Xe.error("Failed to add exception step. Ignoring breadcrumb.",i)}}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 Xe.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 Xe.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 Xe.info("Skipping exception capture because it was thrown by the PostHog SDK")}var s=this.el.enabled&&D(t.$exception_steps)?this.dl(t):t,r=typeof(i=globalThis._posthogReleaseId)=="string"&&i.length>0?i:void 0;r&&(s.$release_id=r);try{var n=this._instance.capture("$exception",s,{_noTruncate:!0,_batchKey:"exceptionEvent",Wn:!0});return n&&this.rl.clear(),n}catch(o){return Xe.error("Failed to capture exception event. Dropping this exception.",o),void this.rl.clear()}}catch(o){return void Xe.error("Failed to process exception event. Ignoring this exception.",o)}var i}dl(t){try{var e=this.rl.getAttachable();return e.length===0?t:w({},t,{$exception_steps:e})}catch(s){return Xe.error("Failed to read buffered exception steps. Capturing exception without steps.",s),t}}ll(t){this.el.enabled&&this.rl.add({[Zr]:t,[Xr]:new Date().toISOString()})}sl(t){return te(t)?w({},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(((s,r)=>{var n=r.type,i=r.value;return W(n)&&n.length>0&&s.$exception_types.push(n),W(i)&&i.length>0&&s.$exception_values.push(i),s}),{$exception_types:[],$exception_values:[]});return this.Xo.some((s=>{var r=s.values.map((n=>{var i=td[n.operator],o=e[n.key];if(!i||!o)return!1;var a=L(n.value)?n.value:[n.value];return a.length>0&&i(a,o)}));return s.type==="OR"?r.some(Boolean):r.every(Boolean)}))}catch(s){return Xe.warn("Failed to evaluate suppression rules. Capturing the exception.",s),!1}}ul(t){return t.flatMap((e=>{var s,r;return(s=(r=e.stacktrace)==null?void 0:r.frames)!==null&&s!==void 0?s:[]})).some((e=>e.filename&&e.filename.startsWith("chrome-extension://")))}hl(t){if(t.length>0){var e,s,r,n,i=(e=(s=t[0].stacktrace)==null?void 0:s.frames)!==null&&e!==void 0?e:[],o=i[i.length-1];return(r=o==null||(n=o.filename)==null?void 0:n.includes("posthog.com/static"))!==null&&r!==void 0&&r}return!1}al(t){return!D(t)&&L(t)}}},Ef=w({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 s,r;if(this.Mr&&this.Mr.register({[Wo]:!!e.productTours}),!Si(this._instance))return!this.vl&&D((s=this.Mr)==null?void 0:s.props[Ws])||Pr.info("product tours disabled; stopping and clearing cached tours"),(r=this.vl)==null||r.stop(),this.vl=null,void this.clearCache();this.loadIfEnabled()}}}loadIfEnabled(){!this.vl&&Si(this._instance)&&this.ai((()=>this.fl()))}ai(t){var e,s;(e=$.__PosthogExtensions__)!=null&&e.generateProductTours?t():(s=$.__PosthogExtensions__)==null||s.loadExternalDependency==null||s.loadExternalDependency(this._instance,"product-tours",(r=>{r?Pr.error("Could not load product tours script",r):t()}))}fl(){var t;!this.vl&&(t=$.__PosthogExtensions__)!=null&&t.generateProductTours&&(this.vl=$.__PosthogExtensions__.generateProductTours(this._instance,!0))}getProductTours(t,e){if(e===void 0&&(e=!1),!L(this.cl)||e){var s=this.Mr;if(s){var r=s.props[Ws];if(L(r)&&!e)return this.cl=r,void t(r,{isLoaded:!0})}this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/product_tours/?token="+this._instance.config.token),method:"GET",timestampMode:"query",callback:n=>{if(Si(this._instance)){var i=n.statusCode;if(i!==200||!n.json){var o="Product Tours API could not be loaded, status: "+i;return i===0?n.error||Pr.warn(o):Pr.error(o),void t([],{isLoaded:!1,error:o})}var a=L(n.json.product_tours)?n.json.product_tours:[];this.cl=a,s&&s.register({[Ws]:a}),t(a,{isLoaded:!0})}else t([],{isLoaded:!0})}})}else t(this.cl,{isLoaded:!0})}getActiveProductTours(t){D(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(Ws)}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)}}},Rn),Sf={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 s=this.globalsForEvent(e);this.gl.push(s),this.gl.length>1e3&&(this.gl=this.gl.slice(10))}}get siteAppLoaders(){var t;return(t=$._POSTHOG_REMOTE_CONFIG)==null||(t=t[this._instance.config.token])==null?void 0:t.siteApps}initialize(){if(this.isEnabled){var t=this._instance._addCaptureHook(this.ml.bind(this));this.yl=()=>{t(),this.gl=[],this.yl=void 0}}}globalsForEvent(t){var e,s,r,n,i,o,a;if(!t)throw new Error("Event payload is required");var l={},u=this._instance.get_property("$groups")||[],c=this._instance.get_property("$stored_group_properties")||{};for(var d of Object.entries(c)){var h=d[0];l[h]={id:u[h],type:h,properties:d[1]}}var p=t.$set_once,f=t.$set;return{event:w({},Ic(t,hf),{properties:w({},t.properties,f?{$set:w({},(e=(s=t.properties)==null?void 0:s.$set)!==null&&e!==void 0?e:{},f)}:{},p?{$set_once:w({},(r=(n=t.properties)==null?void 0:n.$set_once)!==null&&r!==void 0?r:{},p)}:{}),elements_chain:(i=(o=t.properties)==null?void 0:o.$elements_chain)!==null&&i!==void 0?i:"",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,s=(e=t.tagName)==null?void 0:e.toLowerCase();return s==="style"&&this._instance.config.prepare_external_dependency_stylesheet?this._instance.config.prepare_external_dependency_stylesheet(t)||(Ze.error("prepare_external_dependency_stylesheet returned null"),null):s==="script"&&this._instance.config.prepare_external_dependency_script?this._instance.config.prepare_external_dependency_script(t)||(Ze.error("prepare_external_dependency_script returned null"),null):t}_l(){var t,e,s,r,n,i,o,a;if(!this._instance.config.prepare_external_dependency_stylesheet&&!this._instance.config.prepare_external_dependency_script)return()=>{};var l=C?.defaultView,u=l==null||(t=l.Node)==null?void 0:t.prototype;if(!l||!u)return()=>{};if(this.pl++,this.wl)return this.kl();var c=[],d=this,h=new WeakSet,p=(m,_,b)=>{if(m!=null&&m[_]){var E=m[_];m[_]=b(E),c.push((()=>{m[_]=E}))}},f=m=>{if(h.has(m))return m;var _=d.bl(m);return _&&h.add(_),_},g=m=>m.map((_=>typeof _=="string"?_:f(_))).filter((_=>!$e(_)));return p(u,"appendChild",(m=>function(_){var b=f(_);return b?m.call(this,b):_})),p(u,"insertBefore",(m=>function(_,b){var E=f(_);return E?m.call(this,E,b):_})),p(u,"replaceChild",(m=>function(_,b){var E=f(_);return E?m.call(this,E,b):b})),[(e=l.Element)==null?void 0:e.prototype,(s=l.Document)==null?void 0:s.prototype,(r=l.DocumentFragment)==null?void 0:r.prototype].forEach((m=>{p(m,"append",(_=>function(){for(var b=arguments.length,E=new Array(b),I=0;b>I;I++)E[I]=arguments[I];return _.apply(this,g(E))})),p(m,"prepend",(_=>function(){for(var b=arguments.length,E=new Array(b),I=0;b>I;I++)E[I]=arguments[I];return _.apply(this,g(E))}))})),[(n=l.Element)==null?void 0:n.prototype,(i=l.CharacterData)==null?void 0:i.prototype,(o=l.DocumentType)==null?void 0:o.prototype].forEach((m=>{p(m,"before",(_=>function(){for(var b=arguments.length,E=new Array(b),I=0;b>I;I++)E[I]=arguments[I];return _.apply(this,g(E))})),p(m,"after",(_=>function(){for(var b=arguments.length,E=new Array(b),I=0;b>I;I++)E[I]=arguments[I];return _.apply(this,g(E))})),p(m,"replaceWith",(_=>function(){for(var b=arguments.length,E=new Array(b),I=0;b>I;I++)E[I]=arguments[I];var F=g(E);return E.length&&!F.length?void 0:_.apply(this,F)}))})),p((a=l.Element)==null?void 0:a.prototype,"insertAdjacentElement",(m=>function(_,b){var E=f(b);return E?m.call(this,_,E):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 s=this._l();try{var r=t(s);return e&&s(),r}catch(n){throw s(),n}}setupSiteApp(t){var e=this.apps[t.id],s=()=>{var o;!e.errored&&this.gl.length&&(Ze.info("Processing "+this.gl.length+" events for site app with id "+t.id),this.gl.forEach((a=>this.xl((()=>e.processEvent==null?void 0:e.processEvent(a))))),e.processedBuffer=!0),Object.values(this.apps).every((a=>a.processedBuffer||a.errored))&&((o=this.yl)==null||o.call(this))},r=!1,n=o=>{e.errored=!o,e.loaded=!0,Ze.info("Site app with id "+t.id+" "+(o?"loaded":"errored")),r&&s()};try{var i=this.xl((o=>t.init({posthog:this._instance,callback(a){o(),n(a)}})),!1).processEvent;i&&(e.processEvent=i),r=!0}catch(o){Ze.error(Ml+t.id,o),n(!1)}if(r&&e.loaded)try{s()}catch(o){Ze.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 s of t)this.setupSiteApp(s)}Cl(t){var e=this;if(Object.keys(this.apps).length!==0){var s=this.globalsForEvent(t),r=function(i){try{e.xl((()=>i.processEvent==null?void 0:i.processEvent(s)))}catch(o){Ze.error("Error while processing event "+t.event+" for site app "+i.id,o)}};for(var n of Object.values(this.apps))r(n)}}onRemoteConfig(t){var e,s,r,n=this;if((e=this.siteAppLoaders)!=null&&e.length)return this.isEnabled?(this.Sl(),void this._instance.on("eventCaptured",(l=>this.Cl(l)))):void Ze.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.');if((s=this.yl)==null||s.call(this),t.ok){var i=t.config;if((r=i.siteApps)!=null&&r.length)if(this.isEnabled){var o=function(){var l,u=a.id,c=a.url;$["__$$ph_site_app_"+u]=n._instance,(l=$.__PosthogExtensions__)==null||l.loadSiteApp==null||l.loadSiteApp(n._instance,c,(d=>{if(d)return Ze.error(Ml+u,d)}))};for(var a of i.siteApps)o()}else Ze.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.')}}}},xf={tracingHeaders:class{constructor(t){this.Ml=void 0,this.Tl=void 0,this.El=void 0,this.Uo=()=>{var e,s,r=this.Il();r?(x(this.Ml)&&(this.Ml=(e=$.__PosthogExtensions__)==null||(e=e.tracingHeadersPatchFns)==null?void 0:e._patchXHR(r,(()=>this._instance.get_distinct_id()),this._instance.sessionManager)),x(this.Tl)&&(this.Tl=(s=$.__PosthogExtensions__)==null||(s=s.tracingHeadersPatchFns)==null?void 0:s._patchFetch(r,(()=>this._instance.get_distinct_id()),this._instance.sessionManager))):this.Qo()},this._instance=t}initialize(){this.startIfEnabledOrStop()}ai(t){var e,s;(e=$.__PosthogExtensions__)!=null&&e.tracingHeadersPatchFns?t():(s=$.__PosthogExtensions__)==null||s.loadExternalDependency==null||s.loadExternalDependency(this._instance,"tracing-headers",(r=>{if(r)return uf.error("failed to load script",r);t()}))}Pl(){var t,e;return(t=(e=this._instance.config.tracing_headers)!==null&&e!==void 0?e:this._instance.config.addTracingHeaders)!==null&&t!==void 0?t:this._instance.config.__add_tracing_headers}Il(){var t=this.Pl();return L(t)?(L(this.El)?this.El.splice(0,this.El.length,...t):this.El=[...t],t.length>0?this.El:void 0):(L(this.El)&&this.El.splice(0),this.El=t||void 0,this.El)}Qo(){var t,e;(t=this.Ml)==null||t.call(this),(e=this.Tl)==null||e.call(this),this.Ml=void 0,this.Tl=void 0}startIfEnabledOrStop(){this.Il()?this.ai(this.Uo):this.Qo()}}},kf=w({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(D(e))return q.warn("Flags not loaded yet. Not loading surveys.");var s=L(e);this.Rl=s?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=[],s=0;slocalStorage.removeItem(n)))}catch{}}loadIfEnabled(){if(!this._surveyManager)if(this.Al)q.info("Already initializing surveys, skipping...");else if(this.Ne.disable_surveys)q.info(Ll);else if(this.Ne.cookieless_mode&&this._instance.consent.isOptedOut())q.info("Not loading surveys in cookieless mode without consent.");else{var t=$?.__PosthogExtensions__;if(t){if(!x(this.Rl)||this.Ne.advanced_enable_surveys){var e=this.Rl||this.Ne.advanced_enable_surveys;this.Al=!0;try{var s=t.generateSurveys;if(s)return void this.Dl(s,e);var r=t.loadExternalDependency;if(!r)return void this.$l(qo);r(this._instance,"surveys",(n=>{n||!t.generateSurveys?this.$l("Could not load surveys script",n):this.Dl(t.generateSurveys,e)}))}catch(n){throw this.$l("Error initializing surveys",n),n}finally{this.Al=!1}}}else q.error("PostHog Extensions not found.")}}Dl(t,e){this._surveyManager=t(this._instance,e),this._surveyEventReceiver=new gf(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(Ll),t([]);var s,r=this._instance.get_property(Ji);if(r&&!e)return t(r,{isLoaded:!0}),void(this.ql()&&this.getSurveys((()=>{}),!0));typeof Promise<"u"&&this.Ll?this.Ll.then((n=>t(n.surveys,n.context))):(typeof Promise<"u"&&(this.Ll=new Promise((n=>{s=n}))),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:n=>{var i;this.Ll=null;var o=n.statusCode;if(o!==200||!n.json){var a="Surveys API could not be loaded, status: "+o;o!==0?q.error(a):n.error||q.warn(a),this.Ol=Date.now();var l={isLoaded:!1,error:a};return t([],l),void(s==null||s({surveys:[],context:l}))}this.Ol=null;var u,c=n.json.surveys||[],d=c.filter((p=>(function(f){return!(!f.start_date||f.end_date)})(p)&&(rd(p)||(function(f){var g;return!((g=f.conditions)==null||(g=g.actions)==null||(g=g.values)==null||!g.length)})(p))));d.length>0&&((u=this._surveyEventReceiver)==null||u.register(d)),(i=this._instance.persistence)==null||i.register({[Ji]:c,[tn]:Date.now()});var h={isLoaded:!0};t(c,h),s?.({surveys:c,context:h})}}))}ql(){return this.jl()&&!this.Ll&&!this.Bl()}jl(){var t=this._instance.get_property(tn);return he(t)&&Date.now()-t>3e5}Bl(){return he(this.Ol)&&3e5>Date.now()-this.Ol}markSurveyAsSeen(t,e){var s,r={id:t,current_iteration:(s=e?.iteration)!==null&&s!==void 0?s:null};id(r);try{localStorage.setItem("lastSeenSurveyDate",new Date().toISOString())}catch{}}Nl(t){for(var e of this.Fl)try{if(!t.isLoaded)return e([],t);this.getSurveys(e)}catch(s){q.error("Error in survey callback",s)}}getActiveMatchingSurveys(t,e){if(e===void 0&&(e=!1),!D(this._surveyManager))return this._surveyManager.getActiveMatchingSurveys(t,e);q.warn("init was not called")}Hl(t){var e=null;return this.getSurveys((s=>{var r;e=(r=s.find((n=>n.id===t)))!==null&&r!==void 0?r:null})),e}Ul(t){if(D(this._surveyManager))return{eligible:!1,reason:Ar};var e=typeof t=="string"?this.Hl(t):t;return e?this._surveyManager.checkSurveyEligibility(e):{eligible:!1,reason:"Survey not found"}}zl(t){if(D(this._surveyManager))return{eligible:!1,reason:Ar};var e=typeof t=="string"?this.Hl(t):t;return e?this._surveyManager.checkSurveyRenderability(e):{eligible:!1,reason:"Survey not found"}}canRenderSurvey(t){if(D(this._surveyManager))return q.warn("init was not called"),{visible:!1,disabledReason:Ar};var e=this.zl(t);return{visible:e.eligible,disabledReason:e.reason}}canRenderSurveyAsync(t,e){return D(this._surveyManager)?(q.warn("init was not called"),Promise.resolve({visible:!1,disabledReason:Ar})):new Promise((s=>{this.getSurveys((r=>{var n,i=(n=r.find((a=>a.id===t)))!==null&&n!==void 0?n:null;if(i){var o=this.zl(i);s({visible:o.eligible,disabledReason:o.reason})}else s({visible:!1,disabledReason:"Survey not found"})}),e)}))}renderSurvey(t,e,s){var r;if(D(this._surveyManager))q.warn("init was not called");else{var n=typeof t=="string"?this.Hl(t):t;if(n!=null&&n.id)if(Yp.includes(n.type)){var i=C?.querySelector(e);if(i)return(r=n.appearance)!=null&&r.surveyPopupDelaySeconds?(q.info("Rendering survey "+n.id+" with delay of "+n.appearance.surveyPopupDelaySeconds+" seconds"),void setTimeout((()=>{var o,a;q.info("Rendering survey "+n.id+" with delay of "+((o=n.appearance)==null?void 0:o.surveyPopupDelaySeconds)+" seconds"),(a=this._surveyManager)==null||a.renderSurvey(n,i,s),q.info("Survey "+n.id+" rendered")}),1e3*n.appearance.surveyPopupDelaySeconds)):void this._surveyManager.renderSurvey(n,i,s);q.warn("Survey element not found")}else q.warn("Surveys of type "+n.type+" cannot be rendered in the app");else q.warn("Survey not found")}}displaySurvey(t,e){var s;if(D(this._surveyManager))q.warn("init was not called");else{var r=this.Hl(t);if(r){var n=r;if((s=r.appearance)!=null&&s.surveyPopupDelaySeconds&&e.ignoreDelay&&(n=w({},r,{appearance:w({},r.appearance,{surveyPopupDelaySeconds:0})})),e.displayType!==io.Popover&&e.initialResponses&&q.warn("initialResponses is only supported for popover surveys. prefill will not be applied."),e.ignoreConditions===!1){var i=this.Ul(r);if(!i.eligible)return void q.warn("Survey is not eligible to be displayed: ",i.reason)}e.displayType!==io.Inline?this._surveyManager.handlePopoverSurvey(n,e):this.renderSurvey(n,e.selector,e.properties)}else q.warn("Survey not found")}}cancelPendingSurvey(t){D(this._surveyManager)?q.warn("init was not called"):this._surveyManager.cancelSurvey(t)}handlePageUnload(){var t;(t=this._surveyManager)==null||t.handlePageUnload==null||t.handlePageUnload()}}},Rn),If={toolbar:class{constructor(t){this.instance=t}Wl(t){$.ph_toolbar_state=t}Vl(){var t;return(t=$.ph_toolbar_state)!==null&&t!==void 0?t:0}initialize(){return this.maybeLoadToolbar()}maybeLoadToolbar(t,e,s){if(t===void 0&&(t=void 0),e===void 0&&(e=void 0),s===void 0&&(s=void 0),so(this.instance.config)||!v||!C)return!1;t=t??v.location,s=s??v.history;try{if(!e){try{v.localStorage.setItem("test","test"),v.localStorage.removeItem("test")}catch{return!1}e=v?.localStorage}var r,n=mf||un(t.hash,"__posthog")||un(t.hash,"state"),i=n?el((()=>JSON.parse(atob(decodeURIComponent(n)))))||el((()=>JSON.parse(decodeURIComponent(n)))):null;return i&&i.action==="ph_authorize"?((r=i).source="url",r&&Object.keys(r).length>0&&(i.desiredHash?t.hash=i.desiredHash:s?s.replaceState(s.state,"",t.pathname+t.search):t.hash="")):((r=JSON.parse(e.getItem(Ol)||"{}")).source="localstorage",delete r.userIntent),!(!r.token||this.instance.config.token!==r.token||(this.loadToolbar(r),0))}catch{return!1}}Zl(t){var e=$.ph_load_toolbar||$.ph_load_editor;!D(e)&&Se(e)?e(t,this.instance):Dl.warn("No toolbar load function found")}loadToolbar(t){var e=!(C==null||!C.getElementById(wu));if(!v||e)return!1;var s=this.instance.requestRouter.region==="custom"&&this.instance.config.advanced_disable_toolbar_metrics,r=w({token:this.instance.config.token},t,{apiURL:this.instance.requestRouter.endpointFor("ui")},s?{instrument:!1}:{});if(v.localStorage.setItem(Ol,JSON.stringify(w({},r,{source:void 0}))),this.Vl()===2)this.Zl(r);else if(this.Vl()===0){var n;this.Wl(1),(n=$.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this.instance,"toolbar",(i=>{if(i)return Dl.error("[Toolbar] Failed to load",i),void this.Wl(0);this.Wl(2),this.Zl(r)})),ne(v,"turbolinks:load",(()=>{this.Wl(0),this.loadToolbar(r)}))}return!0}Gl(t){return this.loadToolbar(t)}maybeLoadEditor(t,e,s){return t===void 0&&(t=void 0),e===void 0&&(e=void 0),s===void 0&&(s=void 0),this.maybeLoadToolbar(t,e,s)}}},Cf=w({experiments:ye},Rn),Ff={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;D(e)||(Ke(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||so(this._instance.config)||this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut())){var t=$?.__PosthogExtensions__;if(t&&!x(this.Ql)&&this.Ql)if(this.Jl&&this.Jl.token){this.Kl=!0;try{var e=t.initConversations;if(e)return this.tu(e),void(this.Kl=!1);var s=t.loadExternalDependency;if(!s)return void this.eu(qo);s(this._instance,"conversations",(r=>{r||!t.initConversations?this.eu("Could not load conversations script",r):this.tu(t.initConversations),this.Kl=!1}))}catch(r){this.eu("Error initializing conversations",r),this.Kl=!1}}else Ue.error("Conversations enabled but missing token in remote config.")}}tu(t){if(this.Jl)try{this._conversationsManager=t(this.Jl,this._instance),this.Yl=!1,Ue.info("Conversations loaded successfully")}catch(e){this.eu("Error completing conversations initialization",e)}else Ue.error("Cannot complete initialization: remote config is null")}eu(t,e){Ue.error(t,e),this._conversationsManager=null,this.Kl=!1,this.Yl=!0}show(){this._conversationsManager?this._conversationsManager.show():Ue.warn("Conversations not loaded yet.")}hide(){this._conversationsManager&&this._conversationsManager.hide()}isAvailable(){return this.Ql===!0&&!$e(this._conversationsManager)}getUnavailableReason(){return this.isAvailable()?null:this._instance.config.disable_conversations?"disabled_by_config":so(this._instance.config)?"disabled_for_toolbar":this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut()?"consent_opted_out":this.Xl===!1?"remote_config_failed":x(this.Ql)?this.Xl?"disabled_in_project":"remote_config_pending":this.Ql?D(this.Jl)||!this.Jl.token?"missing_token":$!=null&&$.__PosthogExtensions__?this.Kl?"initializing":this.Yl?"load_failed":"not_loaded":"extensions_unavailable":"disabled_in_project"}isVisible(){var t,e;return(t=(e=this._conversationsManager)==null?void 0:e.isVisible())!==null&&t!==void 0&&t}sendMessage(t,e,s){var r=this;return X((function*(){return r._conversationsManager?r._conversationsManager.sendMessage(t,e,s):(Ue.warn(Dt),null)}))()}getMessages(t,e){var s=this;return X((function*(){return s._conversationsManager?s._conversationsManager.getMessages(t,e):(Ue.warn(Dt),null)}))()}markAsRead(t){var e=this;return X((function*(){return e._conversationsManager?e._conversationsManager.markAsRead(t):(Ue.warn(Dt),null)}))()}getTickets(t){var e=this;return X((function*(){return e._conversationsManager?e._conversationsManager.getTickets(t):(Ue.warn(Dt),null)}))()}requestRestoreLink(t){var e=this;return X((function*(){return e._conversationsManager?e._conversationsManager.requestRestoreLink(t):(Ue.warn(Dt),null)}))()}restoreFromToken(t){var e=this;return X((function*(){return e._conversationsManager?e._conversationsManager.restoreFromToken(t):(Ue.warn(Dt),null)}))()}restoreFromUrlToken(){var t=this;return X((function*(){return t._conversationsManager?t._conversationsManager.restoreFromUrlToken():(Ue.warn(Dt),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()}}},Pf={logs:class{constructor(t){var e,s=this;this.iu=!1,this.ru=!1,this.rt=se("[logs]"),this.nu=w({},this.rt,{error(){for(var r=arguments.length,n=new Array(r),i=0;r>i;i++)n[i]=arguments[i];n.some(Vl)||s.rt.error(...n)}}),this.tr=[],this.su=[],this.Sa=0,this.au=()=>{var r,n;this.Sa=0,(r=this.ou)==null||r.onReconnect(),(n=this.lu)==null||n.onReconnect()},this._instance=t,this._instance&&(e=this._instance.config.logs)!=null&&e.captureConsoleLogs&&(this.iu=!0),v&&ne(v,"online",this.au)}uu(t,e,s,r){var n,i=(function(o,a){var l,u,c,d,h,p,f,g=(l=o?.flushIntervalMs)!==null&&l!==void 0?l:3e3,m=(u=o?.maxBufferSize)!==null&&u!==void 0?u:100,_=a!=null&&a.consoleCapture?void 0:(c=o?.maxLogsPerInterval)!==null&&c!==void 0?c:1e3,b=x(_)?Math.max(m,2048):Math.max(m,_),E=o?.resourceAttributes;return{serviceName:(d=(h=E?.["service.name"])!==null&&h!==void 0?h:o?.serviceName)!==null&&d!==void 0?d:a?.serviceNameDefault,serviceVersion:(p=E?.["service.version"])!==null&&p!==void 0?p:o?.serviceVersion,environment:(f=E?.["deployment.environment"])!==null&&f!==void 0?f:o?.environment,resourceAttributes:E,beforeSend:o?.beforeSend,flushIntervalMs:g,maxBufferSize:m,maxQueueSize:b,maxBatchRecordsPerPost:100,rateCapWindowMs:g,maxLogsPerInterval:_,backgroundFlushBudgetMs:0,terminationFlushBudgetMs:0}})((n=this._instance)==null||(n=n.config)==null?void 0:n.logs,s);return[new Rh(this.hu(t,e),i,this.nu,(()=>this.du()),(o=>o()),void 0,r),i]}vu(){var t,e=(t=this._instance)==null||(t=t.config)==null?void 0:t.logs;if(!this.ou||this.cu!==e){var s;(s=this.ou)==null||s.reset(),this.cu=e;var r=this.uu((()=>this.tr),(n=>{this.tr=n}));this.ou=r[0],this.fu=r[1]}return this.ou}pu(){var t,e=(t=this._instance)==null||(t=t.config)==null?void 0:t.logs;if(!this.lu||this.gu!==e){var s;(s=this.lu)==null||s.reset(),this.gu=e;var r=this.uu((()=>this.su),(n=>{this.su=n}),{serviceNameDefault:"posthog-browser-logs",consoleCapture:!0},ql);this.lu=r[0],this.mu=r[1]}return this.lu}initialize(){this.loadIfEnabled()}onRemoteConfig(t){var e;if(t.ok){var s=(e=t.config.logs)==null?void 0:e.captureConsoleLogs;!D(s)&&s&&(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){Vl(t)||this.rt.error("PostHog logs flush failed:",t)}loadIfEnabled(){if(this.iu&&!this.ru){var t=$?.__PosthogExtensions__;if(t){var e=t.loadExternalDependency;e?e(this._instance,"logs",(s=>{var r;s||(r=t.logs)==null||!r.initializeLogs?this.rt.error("Could not load logs script",s):(t.logs.initializeLogs(this._instance),this.ru=!0)})):this.rt.error(qo)}else this.rt.error("PostHog Extensions not found.")}}hu(t,e){var s=this._instance;return{get isDisabled(){return!1},get optedOut(){return!s.is_capturing()},getPersistedProperty:r=>r===ut.LogsQueue?t():void 0,setPersistedProperty(r,n){var i;r===ut.LogsQueue&&e((i=n)!==null&&i!==void 0?i:[])},Ot:r=>this.Ot(r),getLibraryId:()=>Y.LIB_NAME,getLibraryVersion:()=>Y.LIB_VERSION}}Ot(t){return new Promise((e=>{if(Ru(this.Sa,3))e({kind:"fatal",error:ki(void 0,"logs endpoint is unreachable, dropping batch")});else{var s=!1,r=i=>{s||(s=!0,clearTimeout(n),e(i))},n=setTimeout((()=>{this.rt.warn("Logs request timed out before receiving a response"),r({kind:"retry-later",error:ki(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:i=>{var o=i.statusCode;if(this.ku(o),o>=200&&300>o)r({kind:"ok"});else if(o===413)r({kind:"too-large"});else if(o!==0&&o!==429&&500>o)r({kind:"fatal",error:new Error("logs request failed with status "+o)});else{var a;o===0?(i.error||this.rt.warn("Logs request failed before receiving an HTTP response"),r({kind:"retry-later",error:ki(i.error,"logs request failed before receiving an HTTP response")})):r({kind:"retry-later",error:(a=i.error)!==null&&a!==void 0?a:new Error("logs request failed with status "+o)})}}})}}))}ku(t){(t!==0||this._instance.__loaded)&&(this.Sa=Tu(t,this.Sa,3,(()=>this.rt.warn("Log requests are failing before receiving an HTTP response; this can happen due to network issues, CORS, browser blocking, or ad blockers. Stopped sending logs; will try again when connectivity changes."))))}bu(t){this.tr.length>0&&this.xu(t,this.tr,this.fu,Y.LIB_NAME,(e=>{this.tr=e})),this.su.length>0&&this.xu(t,this.su,this.mu,ql,(e=>{this.su=e}))}xu(t,e,s,r,n){if(e.length!==0){var i=e.map((a=>a.record));n([]);var o=ru(i,su(s,Y.LIB_NAME,Y.LIB_VERSION),r,Y.LIB_VERSION);this._instance._send_request({method:"POST",url:this.wu(),data:o,compression:"best-available",batchKey:"logs",transport:t})}}wu(){return this._instance.requestRouter.endpointFor("api","/i/v1/logs")+"?token="+encodeURIComponent(this._instance.config.token)}du(){var t,e={};if(e.distinctId=this._instance.get_distinct_id(),this._instance.sessionManager){var s=this._instance.sessionManager.checkAndGetSessionAndWindowId(!0),r=s.windowId,n=s.sessionStartTimestamp,i=s.lastActivityTimestamp;e.sessionId=s.sessionId,e.windowId=r,D(n)||(e.sessionStartTimestamp=n),D(i)||(e.lastActivityTimestamp=i)}if($!=null&&(t=$.location)!=null&&t.href&&(e.currentUrl=this._instance.config.disable_capture_url_hashes?Ct($.location.href):$.location.href),this._instance.featureFlags){var o=this._instance.featureFlags.getFlags();o&&o.length>0&&(e.activeFeatureFlags=o)}return e}}},Af={metrics:class{constructor(t){this.rt=se("[metrics]"),this._instance=t}initialize(){}vu(){var t,e,s=(t=this._instance)==null||(t=t.config)==null?void 0:t.metrics;return this.ou&&this.cu===s||((e=this.ou)==null||e.reset(),this.cu=s,this.ou=new Th(this.hu(),(function(r){var n,i,o,a,l,u=r?.resourceAttributes;return{serviceName:(n=u?.["service.name"])!==null&&n!==void 0?n:r?.serviceName,serviceVersion:(i=u?.["service.version"])!==null&&i!==void 0?i:r?.serviceVersion,environment:(o=u?.["deployment.environment"])!==null&&o!==void 0?o:r?.environment,resourceAttributes:u,beforeSend:r?.beforeSend,flushIntervalMs:(a=r?.flushIntervalMs)!==null&&a!==void 0?a:1e4,maxSeriesPerFlush:(l=r?.maxSeriesPerFlush)!==null&&l!==void 0?l:1e3}})(s),this.rt)),this.ou}count(t,e,s){e===void 0&&(e=1),this.vu().count(t,e,s)}gauge(t,e,s){this.vu().gauge(t,e,s)}histogram(t,e,s){this.vu().histogram(t,e,s)}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((s=>this.rt.error("PostHog metrics flush failed:",s)))}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:s=>e.Jt(s),getLibraryId:()=>Y.LIB_NAME,getLibraryVersion:()=>Y.LIB_VERSION}}Jt(t,e){return new Promise((s=>{var r=!1,n=o=>{r||(r=!0,clearTimeout(i),s(o))},i=setTimeout((()=>n({kind:"retry-later",error:new Error("metrics request timed out")})),9e4);this._instance._send_request(w({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)n({kind:"ok"});else if(a===413)n({kind:"too-large"});else if(a!==0&&a!==429&&500>a)n({kind:"fatal",error:new Error("metrics request failed with status "+a)});else{var l;n({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)}}},$f=w({},Rn,yf,wf,bf,Ef,Sf,kf,xf,If,Cf,Ff,Pf,Af);Te.__defaultExtensionClasses=w({},$f);(function(){Y.SDK_DIST_CHANNEL="npm";var t=Ys[os]=new Te;return(function(){function e(){e.done||(e.done=!0,ad=!1,Z(Ys,(function(s){s._dom_loaded()})))}C!=null&&C.addEventListener?C.readyState==="complete"?e():ne(C,"DOMContentLoaded",e,{capture:!1}):v&&k.error("Browser doesn't support `document.addEventListener` so PostHog couldn't be initialized")})(),t})();const cd="CodeFile",ud="GeneratedCode",Rf={CustomAction:"A",CustomWidget:"W",CustomFunction:"F",CustomClass:"C",CodeFile:"C"};function kt(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function fo(t){return String(t||"").trim().replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function Tf(t={},e=0){const s=fo(t.artifactType||t.type||cd),r=fo(t.artifactName||t.name||t.fileName||`${ud}-${e+1}`);return`${s||"artifact"}-${r||e+1}`}function dd(t={},e=0){const s=kt(t),r=s.artifactType||s.type||cd,n=s.artifactName||s.name||ud;let i=s.fileName||n;return i.endsWith(".dart")||(i+=".dart"),{id:fo(s.id)||Tf({...s,artifactType:r,artifactName:n,fileName:i},e),artifactType:r,artifactName:n,fileName:i,deployPath:s.deployPath||"",description:s.description||"",code:s.code||s.content||"",dependencies:hd(s.dependencies),imports:Array.isArray(s.imports)?s.imports:[],publicApi:Array.isArray(s.publicApi)?s.publicApi:[],relationships:pd(s.relationships),deployStatus:s.deployStatus||"pending",review:s.review||null,metadata:kt(s.metadata),codeType:s.codeType||Rf[r]||"O"}}function hd(t){return t?Array.isArray(t)?t.map(e=>{if(typeof e=="string")return{name:e,version:null,inferred:!1};const s=kt(e),r=s.name||s.package;return r?{name:r,version:s.version||null,versionRequired:!!(s.versionRequired||s.required),inferred:!!s.inferred,...s.reason?{reason:s.reason}:{}}:null}).filter(Boolean):Object.entries(kt(t)).map(([e,s])=>({name:e,version:s||null,inferred:!1})):[]}function pd(t){return t?(Array.isArray(t)?t:[t]).map(e=>{const s=kt(e);return!s.from&&!s.to?null:{from:s.from||null,to:s.to||null,type:s.type||"uses",description:s.description||""}}).filter(Boolean):[]}function go(t){if(typeof t!="string")return null;const e=t.trim();if(!e)return null;try{return JSON.parse(e)}catch{const s=e.match(/```(?:json)?\s*([\s\S]*?)```/i);if(!s)return null;try{return JSON.parse(s[1].trim())}catch{return null}}}function or(t,e={}){const s=[],r=typeof t=="string"?go(t):t,i=kt(r||{});!r&&typeof t=="string"&&s.push("Structured bundle parse failed; using legacy single-artifact fallback.");const o=Array.isArray(i.artifacts)?i.artifacts:[{artifactType:i.artifactType||e.artifactType,artifactName:i.artifactName||e.artifactName,fileName:i.fileName||e.fileName,description:i.description,code:i.code||e.code||(typeof t=="string"?t:""),dependencies:i.dependencies||e.dependencies,relationships:i.relationships||e.relationships}];o.forEach((d,h)=>{!d?.artifactType&&!d?.type&&s.push(`Artifact ${h+1} has no artifactType; it will deploy as a standalone code file under lib/custom_code/ root.`)});const a=o.map((d,h)=>dd(d,h)),l=new Map(o.map((d,h)=>[kt(d).id,a[h]?.id]).filter(([d,h])=>d&&h)),u=d=>l.get(d)||d,c=pd(i.relationships||e.relationships).map(d=>({...d,from:d.from?u(d.from):d.from,to:d.to?u(d.to):d.to}));return{schemaVersion:i.schemaVersion||e.schemaVersion||null,id:i.id||e.id||"bundle-current",title:i.title||i.name||e.title||"Generated artifact bundle",description:i.description||e.description||"",artifacts:a,dependencies:hd(i.dependencies||e.dependencies),relationships:c,deployOrder:Array.isArray(i.deployOrder)?i.deployOrder.map(u):a.map(d=>d.id),warnings:[...s,...Array.isArray(i.warnings)?i.warnings:[]],metadata:kt(i.metadata)}}function gn(t){return or(t).artifacts[0]||dd()}function yt(t){if(typeof t!="string")return t??"";const e=t.trim();if(!e)return"";try{return JSON.parse(e)}catch{return t}}function ys(t){return JSON.stringify(t,null,2)}function Nf(t){return ys({task:"architect",userRequest:String(t??"")})}function Mf(t){const e=yt(t);return e&&typeof e=="object"&&typeof e.task=="string"?ys(e):ys({task:"generate_bundle",bundleSpec:e})}function Lf(t){return ys({task:"review_bundle",generatedBundle:yt(t),outputRequirements:{bundleReview:["status","score","summary","manualActions","findings"],scoreRange:[0,100],eachArtifact:["id","review.status","review.findings"],manualActions:{definition:"Setup the developer must perform by hand in the FlutterFlow editor that FlutterFlow will NOT do for them.",exclude:["creating the Custom Action, Widget or Code File itself - deploying the code creates it","declaring parameters or return values FlutterFlow derives from the function signature","anything that resolves as a side effect of using the action or widget in the editor","generic advice such as testing, reviewing or rebuilding the app"],preferEmpty:"Return an empty array when nothing qualifies - an empty list is the expected result for most bundles."}}})}function Qo(t,e=null){const s={stage:t};return e!=null&&(s.bundle=yt(e)),s}function Of({bundleSpec:t,artifactBundle:e,bundleReview:s,artifactId:r,userFeedback:n}){return ys({task:"regenerate_artifact",artifactId:r,bundleSpec:yt(t),artifactBundle:yt(e),bundleReview:yt(s),userFeedback:String(n)})}function fd({bundleSpec:t,artifactBundle:e,bundleReview:s,userFeedback:r}){return ys({task:"regenerate_bundle",bundleSpec:yt(t),artifactBundle:yt(e),bundleReview:yt(s),userFeedback:String(r??"")})}const Gl={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"},Df=["sanitizationResult","modelArmor","modelArmorResult","data","result","error"];function Le(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function Bf(t){return Le(t)?typeof t.filterMatchState=="string"||typeof t.invocationResult=="string"||Array.isArray(t.matchedFilters)||Le(t.filterSummary)||Le(t.filterResults):!1}function gd(t,e=0){if(!Le(t)||e>3)return null;if(Bf(t))return t;for(const s of Df){const r=t[s];if(Le(r)){const n=gd(r,e+1);if(n)return n}}return null}function mn(t){return Array.isArray(t)?t.some(mn):Le(t)?t.matched===!0||t.matchState==="MATCH_FOUND"?!0:Object.values(t).some(mn):!1}function mo(t){return Array.isArray(t)?t.some(mo):Le(t)?typeof t.executionState=="string"&&t.executionState!=="EXECUTION_SUCCESS"?!0:Object.values(t).some(mo):!1}function md(t){return{csamFilterFilterResult:"csam",maliciousUriFilterResult:"malicious_uris",piAndJailbreakFilterResult:"pi_and_jailbreak",raiFilterResult:"rai",sdpFilterResult:"sdp",virusScanFilterResult:"virus_scan"}[t]||t}function jf(t,e){if(Le(t))for(const[s,r]of Object.entries(t)){if(!Le(r))continue;const n=Le(r.categories)?r.categories:{},i=Object.entries(n).filter(([,o])=>Le(o)&&o.matched===!0).map(([o])=>o);i.length>0?i.forEach(o=>e.add(o)):r.matched===!0&&e.add(md(s))}}function Uf(t,e){if(!t)return;const s=Array.isArray(t)?t.flatMap(r=>Le(r)?Object.entries(r):[]):Object.entries(t);for(const[r,n]of s){if(!mn(n))continue;const i=md(r),o=n?.raiFilterResult?.raiFilterTypeResults||(i==="rai"?n?.raiFilterTypeResults:null),a=Le(o)?Object.entries(o).filter(([,l])=>mn(l)).map(([l])=>l):[];a.length>0?a.forEach(l=>e.add(l)):e.add(i)}}function Hf(t){return Gl[t]?Gl[t]:String(t).replace(/([a-z])([A-Z])/g,"$1 $2").replace(/_/g," ").toLowerCase()}function Kl(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 Wf(t){const e=gd(t);if(!e)return null;const s=new Set(Array.isArray(e.matchedFilters)?e.matchedFilters:[]);jf(e.filterSummary,s),Uf(e.filterResults,s);const r=e.blocked===!0||e.filterMatchState==="MATCH_FOUND"||s.size>0,n=e.invocationResult||null,i=mo(e.filterSummary||e.filterResults);return!r&&!i&&!["PARTIAL","FAILURE"].includes(n)?null:{kind:r?"blocked":"unavailable",invocationResult:n,matchedFilters:[...s]}}function zf(t,e){const s=Wf(t);if(!s)return null;const r=[...new Set(s.matchedFilters.map(Hf))],n=s.kind==="blocked",i=new Error(n?`Safety screening blocked this pipeline step for ${Kl(r)}.`:"Safety screening could not be completed. Please try again.");return i.name="ModelArmorError",i.code=n?"MODEL_ARMOR_BLOCKED":"MODEL_ARMOR_UNAVAILABLE",i.isModelArmor=!0,i.pipelineStep=e,i.userTitle=n?"Request blocked for safety":"Safety check unavailable",i.userMessage=n?`The safety check detected ${Kl(r)}. Edit your request to remove or rephrase the flagged content, then run the pipeline again.`:"The safety service did not finish all of its checks. Please wait a moment and run the pipeline again.",i.retryExplanation=n?"Trying another model would not change this safety decision.":"A fallback model was not attempted because safety screening must complete first.",i.matchedFilters=s.matchedFilters,i}function qf(t){return String(t||"").replace(/\/\*[\s\S]*?\*\//g,"").replace(/\/\/[^\n]*/g,"")}function Jl(t){const e=/^(import|export|part|library|class|enum|extension|typedef|mixin|abstract|const|final|var|late)\b/,s=[];for(const r of qf(t).split(` -`)){if(!/^[A-Za-z_$]/.test(r)||e.test(r))continue;const n=r.match(/^[\w$<>,?\s[\]]+?\s([a-zA-Z_$][\w$]*)\s*\(/);n&&s.push(n[1])}return s}function ea(t,e){const s=t.replace(/\.dart$/,"");if(e==="W")return s.replace(/(^|_)(\w)/g,(r,n,i)=>i.toUpperCase());if(e==="A"){const r=s.replace(/(^|_)(\w)/g,(n,i,o)=>o.toUpperCase());return r.charAt(0).toLowerCase()+r.slice(1)}return e==="F"?"CustomFunctions":e==="C"?t.endsWith(".dart")?t:`${t}.dart`:s}async function Yl(t){const e=new TextEncoder().encode(String(t||"")),s=await globalThis.crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(s),r=>r.toString(16).padStart(2,"0")).join("")}async function Vf(t,e=new Map){const s={},r=new Set;for(const[o,a]of t.entries()){if(a.type==="D"||a.type==="O")continue;const l=ea(o,a.type),u={old_identifier_name:l,new_identifier_name:l,type:a.type,is_deleted:!1,current_checksum:await Yl(a.content)},c=e.get(a.path);if(c!==void 0&&(u.original_checksum=await Yl(c)),s[o]=u,a.type==="F"){const d=Jl(a.content);(d.length>0?d:[a.functionName].filter(Boolean)).forEach(p=>r.add(p))}}const n=new Set(Jl(e.get("lib/flutter_flow/custom_functions.dart")||"")),i={functions_to_rename:[],functions_to_delete:[],functions_to_add:Array.from(r).filter(o=>!n.has(o))};return{fileMapContents:JSON.stringify(s),functionsMapContents:JSON.stringify(i)}}const Gf=new Set(["CustomWidget","CustomAction","CustomFunction","CustomClass","CodeFile"]),Zl={CustomWidget:"custom_code/widgets/",CustomAction:"custom_code/actions/",CustomFunction:"flutter_flow/custom_functions.dart",CustomClass:"custom_code/",CodeFile:"custom_code/"},Kf=new Set(["void","dynamic","String","int","double","num","bool","Color","DateTime","DateTimeRange","LatLng","FFPlace","FFUploadedFile","DocumentReference","List"]),Jf=["Struct","Record"],Yf=[{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=>Ii(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 n of document.querySelectorAll('link[rel="modulepreload"]'))r(n);new MutationObserver(n=>{for(const i of n)if(i.type==="childList")for(const o of i.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&r(o)}).observe(document,{childList:!0,subtree:!0});function s(n){const i={};return n.integrity&&(i.integrity=n.integrity),n.referrerPolicy&&(i.referrerPolicy=n.referrerPolicy),n.crossOrigin==="use-credentials"?i.credentials="include":n.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function r(n){if(n.ep)return;n.ep=!0;const i=s(n);fetch(n.href,i)}})();var v=typeof window<"u"?window:void 0,we=typeof globalThis<"u"?globalThis:v,ke=we?.navigator,C=we?.document,re=we?.location,Mo=we?.fetch,$i=we!=null&&we.XMLHttpRequest&&"withCredentials"in new we.XMLHttpRequest?we.XMLHttpRequest:void 0,Ma=we?.AbortController,lh=we?.CompressionStream,Pe=ke?.userAgent;function kc(){return!(!v||v.navigator.onLine===!1)}var Cs=typeof globalThis<"u"?globalThis:v;Cs&&typeof self>"u"&&(Cs.self=Cs),Cs&&typeof File>"u"&&(Cs.File=function(){});var $=v??{},Y={DEBUG:!1,LIB_VERSION:"0.5.0",LIB_NAME:"browser-common"};function La(t,e,s,r,n,i,o){try{var a=t[i](o),l=a.value}catch(u){return void s(u)}a.done?e(l):Promise.resolve(l).then(r,n)}function X(t){return function(){var e=this,s=arguments;return new Promise((function(r,n){var i=t.apply(e,s);function o(l){La(i,r,n,o,a,"next",l)}function a(l){La(i,r,n,o,a,"throw",l)}o(void 0)}))}}function b(){return b=Object.assign?Object.assign.bind():function(t){for(var e=1;arguments.length>e;e++){var s=arguments[e];for(var r in s)({}).hasOwnProperty.call(s,r)&&(t[r]=s[r])}return t},b.apply(null,arguments)}function Ic(t,e){if(t==null)return{};var s={};for(var r in t)if({}.hasOwnProperty.call(t,r)){if(e.indexOf(r)!==-1)continue;s[r]=t[r]}return s}var Oa=t=>{if(typeof t!="string")return t;try{return JSON.parse(t)}catch{return t}};function Da(t){return typeof t=="string"||t}function Ba(t){return typeof t=="string"?t:void 0}var Fs,ch=["$feature_flag","$feature_flag_response","$feature_flag_has_experiment","$feature_flag_id","$feature_flag_version","$feature_flag_reason","$feature_flag_request_id","$feature_flag_evaluated_at","$feature_flag_error","locally_evaluated","$groups","$process_person_profile","$geoip_disable","$current_url","$pathname","$referring_domain","utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid","gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","irclid","_kx","$session_id","$window_id","$lib","$lib_version","$device_id","$is_server"],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})({}),ja=(function(t){return t.GZipJS="gzip-js",t.Base64="base64",t})({}),uh=["$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"],dh=["token"],Cc="NativeGzipValidationError",Ri=t=>t.length>=2&&t[0]===31&&t[1]===139,Ua=(t,e)=>t===ja.GZipJS||e===ja.GZipJS||e==="gzip",Ha=t=>!(!t||typeof t!="object")&&("name"in t?String(t.name):"")==="NotReadableError",yr=t=>{var e=new Error("Native gzip produced invalid output: "+t);throw e.name=Cc,e},hh=(function(){var t=X((function*(e,s){18>e.size&&yr("too-short");var r=new Uint8Array(yield e.slice(0,10).arrayBuffer());Ri(r)&&r[2]===8||yr("invalid-header");var n=new DataView(yield e.slice(e.size-8).arrayBuffer());n.getUint32(0,!0)!==(o=>{for(var a=(()=>{if(Fs)return Fs;Fs=[];for(var c=0;256>c;c++){for(var d=c,h=0;8>h;h++)d=1&d?3988292384^d>>>1:d>>>1;Fs[c]=d>>>0}return Fs})(),l=4294967295,u=0;o.length>u;u++)l=a[255&(l^o[u])]^l>>>8;return(4294967295^l)>>>0})(s)&&yr("invalid-crc");var i=s.length>>>0;n.getUint32(4,!0)!==i&&yr("invalid-size")}));return function(e,s){return t.apply(this,arguments)}})();function Ti(){return Ti=X((function*(t,e,s){e===void 0&&(e=!0);try{var r=new TextEncoder().encode(t),n=new globalThis.CompressionStream("gzip"),i=n.writable.getWriter(),o=i.write(r).then((()=>i.close())).catch((function(){var u=X((function*(c){try{yield i.abort(c)}catch{}throw c}));return function(c){return u.apply(this,arguments)}})()),a=new Response(n.readable).blob(),l=(yield Promise.all([a,o]))[0];return yield hh(l,r),l}catch(u){if(s!=null&&s.rethrow)throw u;return e&&console.error("Failed to gzip compress data",u),null}})),Ti.apply(this,arguments)}var ph=["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"],Wa=function(t,e){if(e===void 0&&(e=[]),!t)return!1;var s=t.toLowerCase();return ph.concat(e).some((r=>{var n=r.toLowerCase();return s.indexOf(n)!==-1}))};function M(t,e){return t.indexOf(e)!==-1}var Pn=function(t){return t.trim()},Ni=function(t){return t.replace(/^\$/,"")};function Fc(t){var e,s=[];return(e=JSON.stringify(t,(function(r,n){if(typeof n=="bigint")return n.toString();if(typeof n!="function"&&typeof n!="symbol"){if(n instanceof Error)return{name:n.name,message:n.message,stack:n.stack};if(n&&typeof n=="object"){for(;s.length>0&&s[s.length-1]!==this;)s.pop();if(s.includes(n))return"[Circular]";s.push(n)}return n}})))!==null&&e!==void 0?e:"null"}var Pc=Object.prototype,Ac=Pc.hasOwnProperty,An=Pc.toString,L=Array.isArray||function(t){return An.call(t)==="[object Array]"},Se=t=>typeof t=="function",te=t=>t===Object(t)&&!L(t),mt=t=>{if(te(t)){for(var e in t)if(Ac.call(t,e))return!1;return!0}return!1},x=t=>t===void 0,W=t=>An.call(t)=="[object String]",Mi=t=>W(t)&&t.trim().length===0,$e=t=>t===null,D=t=>x(t)||$e(t),he=t=>An.call(t)=="[object Number]"&&t==t,lt=t=>he(t)&&t>0,Ke=t=>An.call(t)==="[object Boolean]",fh=t=>t instanceof FormData,gh=t=>M(uh,t),mh=t=>M(dh,t);function $c(t){return t===null||typeof t!="object"}function qr(t,e){return{}.toString.call(t)==="[object "+e+"]"}function Lo(t){return typeof Event<"u"&&Rc(t,Event)}function Rc(t,e){try{return t instanceof e}catch{return!1}}var vh=[!0,"true",1,"1","yes"],Zn=t=>M(vh,t),_h=[!1,"false",0,"0","no"];function rt(t,e,s,r,n){return e>s&&(r.warn("min cannot be greater than max."),e=s),he(t)?t>s?(r.warn(" cannot be greater than max: "+s+". Using max value instead."),s):e>t?(r.warn(" cannot be less than min: "+e+". Using min value instead."),e):t:(r.warn(" must be a number. using max or fallback. max: "+s+", fallback: "+n),rt(n||s,e,s,r))}class yh{constructor(e){this.tt={},this.et=e.et,this.it=rt(e.bucketSize,0,100,e.rt),this.nt=rt(e.refillRate,0,this.it,e.rt),this.st=rt(e.refillInterval,0,864e5,e.rt)}ot(e,s){var r=Math.floor((s-e.lastAccess)/this.st);r>0&&(e.tokens=Math.min(e.tokens+r*this.nt,this.it),e.lastAccess=e.lastAccess+r*this.st)}consumeRateLimit(e){var s,r=Date.now(),n=String(e),i=this.tt[n];return i?this.ot(i,r):this.tt[n]=i={tokens:this.it,lastAccess:r},i.tokens===0||(i.tokens--,i.tokens===0&&((s=this.et)==null||s.call(this,e)),i.tokens===0)}stop(){this.tt={}}}var Oe="Mobile",Vr="iOS",vt="Android",ps="Tablet",Tc=vt+" "+ps,Nc="iPad",Mc="Apple",Lc=Mc+" Watch",qs="Safari",fs="BlackBerry",Oc="Samsung",Dc=Oc+"Browser",Bc=Oc+" Internet",Vt="Chrome",wh=Vt+" OS",jc=Vt+" "+Vr,Oo="Internet Explorer",Uc=Oo+" "+Oe,Do="Opera",bh=Do+" Mini",Bo="Edge",Hc="Microsoft "+Bo,us="Firefox",Wc=us+" "+Vr,er="Nintendo",tr="PlayStation",ds="Xbox",zc=vt+" "+Oe,qc=Oe+" "+qs,Ds="Windows",Li=Ds+" Phone",za="Nokia",Oi="Ouya",Vc="Generic",Eh=Vc+" "+Oe.toLowerCase(),Gc=Vc+" "+ps.toLowerCase(),Di="Konqueror",Kc="Oculus Browser",Gr="Vivaldi",Jc="Yandex",Kr="Whale",Bi="DuckDuckGo",Yc="Pale Moon",Jr="Waterfox",Vs="Brave",Zc="Google Search App",le="(\\d+(\\.\\d+)?)",Xn=new RegExp("Version/"+le),Sh=new RegExp(ds,"i"),xh=new RegExp(tr+" \\w+","i"),kh=new RegExp(er+" \\w+","i"),jo=new RegExp(fs+"|PlayBook|BB10","i"),Ih={"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"},Xc=function(t,e,s,r){e=e||"";var n=(function(i){return i!=null&&i.brave?Vs:null})(s);return n||(r!=null&&r.detectGoogleSearchApp&&M(t,"GSA/")?Zc:M(t," OPR/")&&M(t,"Mini")?bh:M(t," OPR/")?Do:jo.test(t)?fs:M(t,"IE"+Oe)||M(t,"WPDesktop")?Uc:M(t,"OculusBrowser")?Kc:M(t,Dc)?Bc:M(t,Bo)||M(t,"Edg/")?Hc:M(t,Gr+"/")?Gr:M(t,"YaBrowser/")?Jc:M(t,Kr+"/")?Kr:M(t,Bi+"/")||M(t,"Ddg/")?Bi:M(t,"FBIOS")?"Facebook "+Oe:M(t,"UCWEB")||M(t,"UCBrowser")?"UC Browser":M(t,"CriOS")?jc:M(t,"CrMo")||M(t,Vt)?Vt:M(t,vt)&&M(t,qs)?zc:M(t,"FxiOS")?Wc:M(t.toLowerCase(),Di.toLowerCase())?Di:M(t,Vs+"/")?Vs:((i,o)=>o&&M(o,Mc)||(function(a){return M(a,qs)&&!M(a,Vt)&&!M(a,vt)})(i))(t,e)?M(t,Oe)?qc:qs:M(t,"PaleMoon/")?Yc:M(t,Jr+"/")?Jr:M(t,us)?us:M(t,"MSIE")||M(t,"Trident/")?Oo:M(t,"Gecko")?us:"")},Ch={[Uc]:[new RegExp("rv:"+le)],[Hc]:[new RegExp(Bo+"?\\/"+le)],[Vt]:[new RegExp("("+Vt+"|CrMo)\\/"+le)],[jc]:[new RegExp("CriOS\\/"+le)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+le)],[qs]:[Xn],[qc]:[Xn],[Do]:[new RegExp("(Opera|OPR)\\/"+le)],[us]:[new RegExp(us+"\\/"+le)],[Wc]:[new RegExp("FxiOS\\/"+le)],[Di]:[new RegExp("Konqueror[:/]?"+le,"i")],[fs]:[new RegExp(fs+" "+le),Xn],[zc]:[new RegExp("android\\s"+le,"i")],[Bc]:[new RegExp(Dc+"\\/"+le)],[Kc]:[new RegExp("OculusBrowser\\/"+le)],[Gr]:[new RegExp(Gr+"\\/"+le)],[Jc]:[new RegExp("YaBrowser\\/"+le)],[Kr]:[new RegExp(Kr+"\\/"+le)],[Vs]:[new RegExp(Vs+"\\/"+le)],[Bi]:[new RegExp("(DuckDuckGo|Ddg)\\/"+le)],[Yc]:[new RegExp("PaleMoon\\/"+le)],[Jr]:[new RegExp(Jr+"\\/"+le)],[Zc]:[new RegExp("GSA\\/"+le)],[Oo]:[new RegExp("(rv:|MSIE )"+le)],Mozilla:[new RegExp("rv:"+le)]},Fh=function(t,e,s,r){var n=Xc(t,e,s,r),i=Ch[n];if(x(i))return null;for(var o=0;i.length>o;o++){var a=t.match(i[o]);if(a)return parseFloat(a[a.length-2])}return null},qa=[[new RegExp(ds+"; "+ds+" (.*?)[);]","i"),t=>[ds,t&&t[1]||""]],[new RegExp(er,"i"),[er,""]],[new RegExp(tr,"i"),[tr,""]],[jo,[fs,""]],[new RegExp(Ds,"i"),(t,e)=>{if(/Phone/.test(e)||/WPDesktop/.test(e))return[Li,""];if(new RegExp(Oe).test(e)&&!/IEMobile\b/.test(e))return[Ds+" "+Oe,""];var s=/Windows NT ([0-9.]+)/i.exec(e);if(s&&s[1]){var r=Ih[s[1]]||"";return/arm/i.test(e)&&(r="RT"),[Ds,r]}return[Ds,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,t=>t&&t[3]?[Vr,[t[3],t[4],t[5]||"0"].join(".")]:[Vr,""]],[/(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i,t=>{var e="";return t&&t.length>=3&&(e=x(t[2])?t[3]:t[2]),["watchOS",e]}],[new RegExp("("+vt+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+vt+")","i"),t=>t&&t[2]?[vt,[t[2],t[3],t[4]||"0"].join(".")]:[vt,""]],[/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/,[wh,""]],[/Linux|debian/i,["Linux",""]]],Va=function(t){return kh.test(t)?er:xh.test(t)?tr:Sh.test(t)?ds:new RegExp(Oi,"i").test(t)?Oi:new RegExp("("+Li+"|WPDesktop)","i").test(t)?Li:/iPad/.test(t)?Nc:/iPod/.test(t)?"iPod Touch":/iPhone/.test(t)?"iPhone":/(watch)(?: ?os[,/]|\d,\d\/)[\d.]+/i.test(t)?Lc:jo.test(t)?fs:/(kobo)\s(ereader|touch)/i.test(t)?"Kobo":new RegExp(za,"i").test(t)?za:/(kf[a-z]{2}wi|aeo[c-r]{2})( bui|\))/i.test(t)||/(kf[a-z]+)( bui|\)).+silk\//i.test(t)?"Kindle Fire":/(Android|ZTE)/i.test(t)?new RegExp(Oe).test(t)&&!/(9138B|TB782B|Nexus [97]|pixel c|HUAWEISHT|BTV|noble nook|smart ultra 6)/i.test(t)||/pixel[\daxl ]{1,6}/i.test(t)&&!/pixel c/i.test(t)||/(huaweimed-al00|tah-|APA|SM-G92|i980|zte|U304AA)/i.test(t)||/lmy47v/i.test(t)&&!/QTAQZ3/i.test(t)?vt:Tc:new RegExp("(pda|"+Oe+")","i").test(t)?Eh:new RegExp(ps,"i").test(t)&&!new RegExp(ps+" pc","i").test(t)?Gc:""},Ph=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Ga(t,e){return typeof(s=t)=="string"&&Ph.test(s)?t:e();var s}function Ct(t){return t&&t.split("#")[0]}function Uo(t,e){var s=setTimeout(t,e);return s?.unref&&s?.unref(),s}function Ka(t,e,s){return Qc.apply(this,arguments)}function Qc(){return(Qc=X((function*(t,e,s){var r;try{return yield Promise.race([t,new Promise(((n,i)=>{r=Uo((()=>{try{s?.(),n()}catch(o){i(o)}}),e)}))])}finally{clearTimeout(r)}}))).apply(this,arguments)}var Ah=t=>t instanceof Error,eu={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}},$h=eu.info;function tu(t){if(Ke(t))return{boolValue:t};if(typeof t=="number")return Number.isFinite(t)?Number.isInteger(t)?{intValue:t}:{doubleValue:t}:{stringValue:String(t)};if(typeof t=="string")return{stringValue:t};if(L(t))return{arrayValue:{values:t.map((e=>tu(e)))}};try{return{stringValue:JSON.stringify(t)}}catch{return{stringValue:String(t)}}}function Yr(t){var e=[];for(var s in t){var r=t[s];$e(r)||x(r)||e.push({key:s,value:tu(r)})}return e}function Rh(t,e){var s=eu[t.level||"info"]||$h,r=s.text,n=s.number,i=String(Date.now())+"000000",o={};e.distinctId&&(o.posthogDistinctId=e.distinctId),e.sessionId&&(o.sessionId=e.sessionId),e.windowId&&(o["window.id"]=e.windowId),D(e.sessionStartTimestamp)||(o.sessionStartTimestamp=String(e.sessionStartTimestamp)),D(e.lastActivityTimestamp)||(o.lastActivityTimestamp=String(e.lastActivityTimestamp)),e.currentUrl&&(o["url.full"]=e.currentUrl),e.screenName&&(o["screen.name"]=e.screenName),e.appState&&(o["app.state"]=e.appState),e.activeFeatureFlags&&e.activeFeatureFlags.length>0&&(o.feature_flags=e.activeFeatureFlags);var a=b({},o,t.attributes||{}),l={timeUnixNano:i,observedTimeUnixNano:i,severityNumber:n,severityText:r,body:{stringValue:t.body},attributes:Yr(a)};return t.trace_id&&(l.traceId=t.trace_id),t.span_id&&(l.spanId=t.span_id),x(t.trace_flags)||(l.flags=t.trace_flags),l}function su(t,e,s){return b({},t.resourceAttributes,{"service.name":t.serviceName||"unknown_service"},t.environment&&{"deployment.environment":t.environment},t.serviceVersion&&{"service.version":t.serviceVersion},{"telemetry.sdk.name":e,"telemetry.sdk.version":s})}function ru(t,e,s,r){return{resourceLogs:[{resource:{attributes:Yr(e)},scopeLogs:[{scope:{name:s,version:r},logRecords:t}]}]}}let Th=class{constructor(t,e,s,r,n,i,o){var a;i===void 0&&(i=()=>Promise.resolve()),this._instance=t,this.Ne=e,this.rt=s,this.ut=r,this.ht=n,this.dt=i,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 s={record:Rh(e,this.ut())};this.ht((()=>this.At(s)))}}else this.rt.info("Log was rejected in beforeSend function")}}Pt(t){var e=this.Ne.beforeSend;if(!e)return t;var s=L(e)?e:[e],r=t;for(var n of s)try{var i=n(r);if(!i)return this.rt.info("Log was rejected in beforeSend function"),null;r=i}catch(o){return this.rt.error("Error in beforeSend function for log:",o),null}return r}Rt(){if(this.Tt===void 0)return!0;var t=Date.now(),e=t-this.bt;return this.Mt>e&&e>=0||(this.bt=t,this._t=0,this.wt=!1),this.Tt>this._t?(this._t++,!0):(this.wt||(this.rt.warn("captureLog dropping logs: exceeded "+this.Tt+" logs per "+this.Mt+"ms"),this.wt=!0),!1)}flush(){var t=this;return X((function*(){if(!t._instance.isDisabled)return t.ct||(t.ct=t.Ft().finally((()=>{t.ct=null}))),t.ct}))()}Ft(){var t=this;return X((function*(){var e;t.Et();var s=(e=t._instance.getPersistedProperty(ut.LogsQueue))!==null&&e!==void 0?e:[];if(s.length!==0)for(var r=s.length,n=0;s.length>0&&r>n;){var i,o;t.ft=0;var a=Math.min(s.length,t.Ct),l=s.slice(0,a),u=ru(l.map((d=>d.record)),t.Lt(),(i=t.vt)!==null&&i!==void 0?i: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),s=(o=t._instance.getPersistedProperty(ut.LogsQueue))!==null&&o!==void 0?o:[],n+=l.length,c.kind==="fatal"))throw c.error}}))()}Dt(t){var e=this;return X((function*(){var s,r=Math.max(0,t-e.ft),n=(s=e._instance.getPersistedProperty(ut.LogsQueue))!==null&&s!==void 0?s:[];e._instance.setPersistedProperty(ut.LogsQueue,n.slice(r)),yield e.dt()}))()}Lt(){return su(this.Ne,this._instance.getLibraryId(),this._instance.getLibraryVersion())}At(t){var e;if(!this._instance.optedOut){var s=(e=this._instance.getPersistedProperty(ut.LogsQueue))!==null&&e!==void 0?e:[];this.xt>s.length||(s.shift(),this.ft++,this.rt.info("Logs queue is full, dropping oldest record.")),s.push(t),this._instance.setPersistedProperty(ut.LogsQueue,s),this.kt>s.length?this.$t():this.It()}}$t(t){t===void 0&&(t=this.St),this.Nt||(this.Nt=Uo((()=>{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 X((function*(){e.Et();var s=e.flush().catch((()=>{}));t!==void 0?yield Ka(s,t):yield s}))()}flushWithTimeout(t){var e=this;return X((function*(){var s=e.flush();yield Ka(s,t,(()=>{s.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 Qn=[0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4];function Ja(t){return String(t)+"000000"}function Ya(t,e,s,r){var n="";return r&&(n=Object.keys(r).sort().map((i=>JSON.stringify(i)+":"+JSON.stringify(r[i]))).join(",")),t+"\0"+e+"\0"+(s??"")+"\0"+n}let Nh=class{constructor(t,e,s){this._instance=t,this.Ne=e,this.rt=s,this.Bt=new Map,this.ct=null,this.Ht=!1,this.Ut=new Map,this.zt=new Set,this.Wt=0}count(t,e,s){e===void 0&&(e=1),this.Vt({name:t,type:"count",value:e,unit:s?.unit,attributes:s?.attributes})}gauge(t,e,s){this.Vt({name:t,type:"gauge",value:e,unit:s?.unit,attributes:s?.attributes})}histogram(t,e,s){this.Vt({name:t,type:"histogram",value:e,unit:s?.unit,attributes:s?.attributes})}flush(){var t=this,e=this.ct,s=(function(){var n=X((function*(){e&&(yield e.catch((()=>{}))),yield t.Zt()}));return function(){return n.apply(this,arguments)}})(),r=s().finally((()=>{this.ct===r&&(this.ct=null)}));return this.ct=r,r}drainWindow(){if(this.Bt.size===0)return null;var t=this.Bt;return this.Bt=new Map,this.Ht=!1,this.Ut=new Map,this.zt=new Set,this.Gt(t)}reset(){this.Wt++,this.Et(),this.Bt=new Map,this.ct=null,this.Ht=!1,this.Ut=new Map,this.zt=new Set}Vt(t){if(!this._instance.isDisabled&&!this._instance.optedOut){var e=this.Pt(t);if(e!==null)if(e.name&&typeof e.name=="string")if(typeof e.value=="number"&&Number.isFinite(e.value))if(e.type==="count"&&0>e.value)this.rt.warn("Dropping count '"+e.name+"': counters are monotonic, value must be >= 0");else{var s,r;try{s=e.attributes?b({},e.attributes):void 0,r=Ya(e.type,e.name,e.unit,s)}catch(o){return void this.rt.warn("Dropping metric '"+e.name+"': attributes could not be serialized",o)}var n=this.Bt.get(r);if(!n){if(!this.Qt())return;n={name:e.name,type:e.type,unit:e.unit,attributes:s,windowStartMs:Date.now()},this.Bt.set(r,n)}var i=this.Ut.get(e.name);i===void 0?this.Ut.set(e.name,e.type):i===e.type||this.zt.has(e.name)||(this.zt.add(e.name),this.rt.warn("Metric name '"+e.name+"' is already used as a "+i+"; recording it as a "+e.type+" too will blend both series in charts. Use a distinct name.")),this.Kt(n,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 s;switch(t.type){case"count":t.total=((s=t.total)!==null&&s!==void 0?s: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(Qn.length+1).fill(0)});var r=t.hist;r.count+=1,r.sum+=e,r.min=Math.min(r.min,e),r.max=Math.max(r.max,e),r.bucketCounts[(function(n,i){for(var o=0;i.length>o;o++)if(i[o]>=n)return o;return i.length})(e,Qn)]+=1}}Pt(t){var e=this.Ne.beforeSend;if(!e)return t;var s=L(e)?e:[e],r=t;for(var n of s)try{var i=n(r);if(!i)return this.rt.info("Metric was rejected in beforeSend function"),null;r=i}catch(o){return this.rt.error("Error in beforeSend function for metric:",o),null}return r}$t(){this.Nt||(this.Nt=Uo((()=>{this.Nt=void 0,this.flush().catch((t=>{this.rt.error("Metrics flush failed:",t)}))}),this.Ne.flushIntervalMs))}Et(){this.Nt&&(clearTimeout(this.Nt),this.Nt=void 0)}Zt(){var t=this;return X((function*(){if(t.Bt.size!==0){var e=t.Bt;t.Bt=new Map,t.Ht=!1,t.Ut=new Map,t.zt=new Set;var s=t.Wt,r=yield t._instance.Jt(t.Gt(e));if(s===t.Wt)switch(r.kind){case"ok":return;case"retry-later":return t.Yt(e),void t.$t();case"too-large":return void t.rt.warn("Metrics batch exceeded the server size limit and was dropped");case"fatal":return void t.rt.error("Failed to send metrics batch:",r.error)}}}))()}Gt(t){return e=this.Xt(t),s=(function(i,o,a){return b({},i.resourceAttributes,{"service.name":i.serviceName||"unknown_service"},i.environment&&{"deployment.environment":i.environment},i.serviceVersion&&{"service.version":i.serviceVersion},{"telemetry.sdk.name":o,"telemetry.sdk.version":a})})(this.Ne,this._instance.getLibraryId(),this._instance.getLibraryVersion()),r=this._instance.getLibraryId(),n=this._instance.getLibraryVersion(),{resourceMetrics:[{resource:{attributes:Yr(s)},scopeMetrics:[{scope:{name:r,version:n},metrics:e}]}]};var e,s,r,n}Xt(t){var e=Ja(Date.now()),s=new Map;for(var r of t.values()){var n,i=Ya(r.type,r.name,r.unit,void 0),o=s.get(i);o||(o=b({name:r.name},r.unit&&{unit:r.unit}),r.type==="count"?o.sum={aggregationTemporality:1,isMonotonic:!0,dataPoints:[]}:r.type==="gauge"?o.gauge={dataPoints:[]}:o.histogram={aggregationTemporality:1,dataPoints:[]},s.set(i,o));var a=Yr((n=r.attributes)!==null&&n!==void 0?n:{}),l=Ja(r.windowStartMs);if(r.type==="count"){var u,c={attributes:a,startTimeUnixNano:l,timeUnixNano:e,asDouble:(u=r.total)!==null&&u!==void 0?u:0};o.sum.dataPoints.push(c)}else if(r.type==="gauge"){var d,h={attributes:a,timeUnixNano:e,asDouble:(d=r.last)!==null&&d!==void 0?d:0};o.gauge.dataPoints.push(h)}else r.hist&&o.histogram.dataPoints.push({attributes:a,startTimeUnixNano:l,timeUnixNano:e,count:r.hist.count,sum:r.hist.sum,min:r.hist.min,max:r.hist.max,bucketCounts:r.hist.bucketCounts,explicitBounds:Qn})}return Array.from(s.values())}Yt(t){var e,s;for(var r of t){var n=r[0],i=r[1],o=this.Bt.get(n);if(o)switch(o.windowStartMs=Math.min(o.windowStartMs,i.windowStartMs),o.type){case"count":o.total=((e=o.total)!==null&&e!==void 0?e:0)+((s=i.total)!==null&&s!==void 0?s:0);break;case"gauge":break;case"histogram":if(i.hist)if(o.hist){o.hist.count+=i.hist.count,o.hist.sum+=i.hist.sum,o.hist.min=Math.min(o.hist.min,i.hist.min),o.hist.max=Math.max(o.hist.max,i.hist.max);for(var a=0;o.hist.bucketCounts.length>a;a++)o.hist.bucketCounts[a]+=i.hist.bucketCounts[a]}else o.hist=i.hist}else this.Qt()&&this.Bt.set(n,i)}}};var wr,Za,ei;function Mh(t){var e=globalThis._posthogChunkIds;if(e){var s=Object.keys(e);return ei&&s.length===Za||(Za=s.length,ei=s.reduce(((r,n)=>{wr||(wr={});var i=wr[n];if(i)r[i[0]]=i[1];else for(var o=t(n),a=o.length-1;a>=0;a--){var l=o[a],u=l?.filename,c=e[n];if(u&&c){r[u]=c,wr[n]=[u,c];break}}return r}),{})),ei}}class Lh{constructor(e,s,r){r===void 0&&(r=[]),this.coercers=e,this.stackParser=s,this.modifiers=r}buildFromUnknown(e,s){s===void 0&&(s={});var r=s&&s.mechanism||{handled:!0,type:"generic"},n=this.buildCoercingContext(r,s,0).apply(e),i=this.buildParsingContext(s),o=this.parseStacktrace(n,i);return{$exception_list:this.convertToExceptionList(o,r),$exception_level:"error"}}modifyFrames(e){var s=this;return X((function*(){for(var r of e)r.stacktrace&&r.stacktrace.frames&&L(r.stacktrace.frames)&&(r.stacktrace.frames=yield s.applyModifiers(r.stacktrace.frames));return e}))()}coerceFallback(e){var s;return{type:"Error",value:"Unknown error",stack:(s=e.syntheticException)==null?void 0:s.stack,synthetic:!0}}parseStacktrace(e,s){var r,n;return e.cause!=null&&(r=this.parseStacktrace(e.cause,s)),e.stack!=""&&e.stack!=null&&(n=this.applyChunkIds(this.stackParser(e.stack,e.synthetic?s.skipFirstLines:0),s.chunkIdMap)),b({},e,{cause:r,stack:n})}applyChunkIds(e,s){return e.map((r=>(r.filename&&s&&(r.chunk_id=s[r.filename]),r)))}applyCoercers(e,s){for(var r of this.coercers)if(r.match(e))return r.coerce(e,s);return this.coerceFallback(s)}applyModifiers(e){var s=this;return X((function*(){var r=e;for(var n of s.modifiers)r=yield n(r);return r}))()}convertToExceptionList(e,s){var r,n,i,o={type:e.type,value:e.value,mechanism:{type:(r=s.type)!==null&&r!==void 0?r:"generic",handled:(n=s.handled)===null||n===void 0||n,synthetic:(i=e.synthetic)!==null&&i!==void 0&&i}};e.stack&&(o.stacktrace={type:"raw",frames:e.stack});var a=[o];return e.cause!=null&&a.push(...this.convertToExceptionList(e.cause,b({},s,{handled:!0}))),a}buildParsingContext(e){var s;return{chunkIdMap:Mh(this.stackParser),skipFirstLines:(s=e.skipFirstLines)!==null&&s!==void 0?s:1}}buildCoercingContext(e,s,r){r===void 0&&(r=0);var n=(i,o)=>{if(4>=o){var a=this.buildCoercingContext(e,s,o);return this.applyCoercers(i,a)}};return b({},s,{syntheticException:r==0?s.syntheticException:void 0,mechanism:e,apply:i=>n(i,r),next:i=>n(i,r+1)})}}var gs="?";function ji(t,e,s,r,n){var i={platform:t,filename:e,function:s===""?gs:s,in_app:!0};return x(r)||(i.lineno=r),x(n)||(i.colno=n),i}var nu=(t,e)=>{var s=t.indexOf("safari-extension")!==-1,r=t.indexOf("safari-web-extension")!==-1;return s||r?[t.indexOf("@")!==-1?t.split("@")[0]:gs,s?"safari-extension:"+e:"safari-web-extension:"+e]:[t,e]},Oh=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,Dh=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,Bh=/\((\S*)(?::(\d+))(?::(\d+))\)/,jh=(t,e)=>{var s=Oh.exec(t);if(s)return ji(e,s[1],gs,+s[2],+s[3]);var r=Dh.exec(t);if(r){if(r[2]&&r[2].indexOf("eval")===0){var n=Bh.exec(r[2]);n&&(r[2]=n[1],r[3]=n[2],r[4]=n[3])}var i=nu(r[1]||gs,r[2]);return ji(e,i[1],i[0],r[3]?+r[3]:void 0,r[4]?+r[4]:void 0)}},Uh=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,Hh=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,Wh=(t,e)=>{var s=Uh.exec(t);if(s){if(s[3]&&s[3].indexOf(" > eval")>-1){var r=Hh.exec(s[3]);r&&(s[1]=s[1]||"eval",s[3]=r[1],s[4]=r[2],s[5]="")}var n=s[3],i=s[1]||gs,o=nu(i,n);return ji(e,n=o[1],i=o[0],s[4]?+s[4]:void 0,s[5]?+s[5]:void 0)}},Xa=/\(error: (.*)\)/;class zh{match(e){return this.isDOMException(e)||this.isDOMError(e)}coerce(e,s){var r=W(e.stack);return{type:this.getType(e),value:this.getValue(e),stack:r?e.stack:void 0,cause:e.cause?s.next(e.cause):void 0,synthetic:!1}}getType(e){return this.isDOMError(e)?"DOMError":"DOMException"}getValue(e){var s=e.name||(this.isDOMError(e)?"DOMError":"DOMException");return e.message?s+": "+e.message:s}isDOMException(e){return qr(e,"DOMException")}isDOMError(e){return qr(e,"DOMError")}}class qh{match(e){return(function(s){switch({}.toString.call(s)){case"[object Error]":case"[object Exception]":case"[object DOMException]":case"[object DOMError]":case"[object WebAssembly.Exception]":return!0;default:return Rc(s,Error)}})(e)}coerce(e,s){return{type:this.getType(e),value:this.getMessage(e,s),stack:this.getStack(e),cause:e.cause?s.next(e.cause):void 0,synthetic:!1}}getType(e){return e.name||e.constructor.name}getMessage(e,s){var r=e.message;return String(r.error&&typeof r.error.message=="string"?r.error.message:r)}getStack(e){return e.stacktrace||e.stack||void 0}}class Vh{constructor(){}match(e){return!!qr(e,"ErrorEvent")&&(e.error!=null||this.fe(e))}coerce(e,s){var r;if(e.error!=null)return s.apply(e.error);var n=s.apply(e.message);return b({},n,{stack:(r=this.pe(e))!==null&&r!==void 0?r:n.stack,synthetic:!0})}fe(e){return W(e.message)&&e.message.length>0}pe(e){var s=e;if(W(s.filename)&&s.filename.length>0){var r,n,i=(r=s.lineno)!==null&&r!==void 0?r:0,o=(n=s.colno)!==null&&n!==void 0?n:0;return`Error + at `+s.filename+":"+i+":"+o}}}var Gh=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;class Kh{match(e){return typeof e=="string"}coerce(e,s){var r,n=this.getInfos(e),i=n[0],o=n[1];return{type:i??"Error",value:o??e,stack:(r=s.syntheticException)==null?void 0:r.stack,synthetic:!0}}getInfos(e){var s="Error",r=e,n=e.match(Gh);return n&&(s=n[1],r=n[2]),[s,r]}}var Jh=["fatal","error","warning","log","info","debug"];function iu(t,e){e===void 0&&(e=40);var s=Object.keys(t);if(s.sort(),!s.length)return"[object has no keys]";for(var r=s.length;r>0;r--){var n=s.slice(0,r).join(", ");if(e>=n.length)return r===s.length?n:n.length>e?n.slice(0,e)+"...":n}return""}class Yh{match(e){return typeof e=="object"&&e!==null}coerce(e,s){var r,n,i=this.getErrorPropertyFromObject(e);return i?s.apply(i):{type:this.getType(e),value:this.getValue(e),stack:(r=this.getStack(e))!==null&&r!==void 0?r:(n=s.syntheticException)==null?void 0:n.stack,level:this.isSeverityLevel(e.level)?e.level:"error",synthetic:!0}}getType(e){return Lo(e)?e.constructor.name:"Error"}getValue(e){if("name"in e&&typeof e.name=="string"){var s="'"+e.name+"' captured as exception";return"message"in e&&typeof e.message=="string"&&(s+=" with message: '"+e.message+"'"),s}if("message"in e&&typeof e.message=="string")return e.message;var r=this.getObjectClassName(e);return(r&&r!=="Object"?"'"+r+"'":"Object")+" captured as exception with keys: "+iu(e)}isSeverityLevel(e){return W(e)&&!Mi(e)&&Jh.indexOf(e)>=0}getStack(e){try{return W(e.stacktrace)&&e.stacktrace.length>0?e.stacktrace:W(e.stack)&&e.stack.length>0?e.stack:void 0}catch{return}}getErrorPropertyFromObject(e){for(var s in e)if({}.hasOwnProperty.call(e,s)){var r=e[s];if(Ah(r))return r}}getObjectClassName(e){try{var s=Object.getPrototypeOf(e);return s?s.constructor.name:void 0}catch{return}}}class Zh{match(e){return Lo(e)}coerce(e,s){var r,n=e.constructor.name;return{type:n,value:n+" captured as exception with keys: "+iu(e),stack:(r=s.syntheticException)==null?void 0:r.stack,synthetic:!0}}}class Xh{match(e){return $c(e)}coerce(e,s){var r;return{type:"Error",value:"Primitive value captured as exception: "+String(e),stack:(r=s.syntheticException)==null?void 0:r.stack,synthetic:!0}}}class Qh{match(e){return qr(e,"PromiseRejectionEvent")||this.isCustomEventWrappingRejection(e)}isCustomEventWrappingRejection(e){if(!Lo(e))return!1;try{var s=e.detail;return s!=null&&typeof s=="object"&&"reason"in s}catch{return!1}}coerce(e,s){var r,n=this.getUnhandledRejectionReason(e);return $c(n)?{type:"UnhandledRejection",value:"Non-Error promise rejection captured with value: "+String(n),stack:(r=s.syntheticException)==null?void 0:r.stack,synthetic:!0}:s.apply(n)}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 Zr="$message",Xr="$timestamp",ep=new Set([Zr,Xr]),ti={enabled:!0,max_bytes:32768};function Qr(t){var e;return t?{enabled:(e=t.enabled)!==null&&e!==void 0?e:ti.enabled,max_bytes:sp(t.max_bytes,ti.max_bytes)}:b({},ti)}class tp{constructor(e){this.Ke=[],this.Je=0,this.Ne=Qr(e)}setConfig(e){this.Ne=Qr(e),this.Xe()}add(e){var s=(function(n){var i;try{i=Fc(n)}catch{return}try{var o=JSON.parse(i);if(!te(o))return;var a=o,l=a[Zr],u=a[Xr];return!W(l)||l.trim().length===0||!W(u)&&!he(u)?void 0:{step:a,json:i}}catch{return}})(e);if(s){var r=(function(n){if(typeof TextEncoder<"u")return new TextEncoder().encode(n).length;for(var i=encodeURIComponent(n),o=0,a=0;i.length>a;a++)i[a]==="%"?(o+=1,a+=2):o+=1;return o})(s.json);r>this.Ne.max_bytes||(this.Ke.push({step:s.step,bytes:r}),this.Je+=r,this.Xe())}}getAttachable(){return this.Ke.map((e=>e.step))}clear(){this.Ke=[],this.Je=0}size(){return this.Ke.length}Xe(){for(;this.Je>this.Ne.max_bytes&&this.Ke.length>0;){var e=this.Ke.shift();e&&(this.Je-=e.bytes)}}}function sp(t,e){if(!he(t)||t===1/0||t===-1/0)return e;var s=Math.floor(t);return 0>s?e:s}var ou=function(t,e){var s=(e===void 0?{}:e).debugEnabled,r={k(n){if(v&&(Y.DEBUG||v.POSTHOG_DEBUG||s)&&!x(v.console)&&v.console){for(var i=("__rrweb_original__"in v.console[n])?v.console[n].__rrweb_original__:v.console[n],o=arguments.length,a=new Array(o>1?o-1:0),l=1;o>l;l++)a[l-1]=arguments[l];i(t,...a)}},debug(){for(var n=arguments.length,i=new Array(n),o=0;n>o;o++)i[o]=arguments[o];r.k("debug",...i)},info(){for(var n=arguments.length,i=new Array(n),o=0;n>o;o++)i[o]=arguments[o];r.k("log",...i)},warn(){for(var n=arguments.length,i=new Array(n),o=0;n>o;o++)i[o]=arguments[o];r.k("warn",...i)},error(){for(var n=arguments.length,i=new Array(n),o=0;n>o;o++)i[o]=arguments[o];r.k("error",...i)},critical(){for(var n=arguments.length,i=new Array(n),o=0;n>o;o++)i[o]=arguments[o];console.error(t,...i)},uninitializedWarning(n){r.error("You must initialize PostHog before calling "+n)},createLogger:(n,i)=>ou(t+" "+n,i)};return r},k=ou("[PostHog.js]"),se=k.createLogger,rp=se("[ExternalScriptsLoader]"),si=(t,e,s)=>{if(t.config.disable_external_dependency_loading)return rp.warn(e+" was requested but loading of external scripts is disabled."),s("Loading of external scripts is disabled");var r=C?.querySelectorAll("script");if(r){for(var n,i=function(){if(r[o].src===e){var l=r[o];return l.__posthog_loading_callback_fired?{v:s()}:(l.addEventListener("load",(u=>{l.__posthog_loading_callback_fired=!0,s(void 0,u)})),l.onerror=u=>s(u),{v:void 0})}},o=0;r.length>o;o++)if(n=i())return n.v}var a=()=>{if(!C)return s("document not found");var l=C.createElement("script");if(l.type="text/javascript",l.crossOrigin="anonymous",l.src=e,l.onload=d=>{l.__posthog_loading_callback_fired=!0,s(void 0,d)},l.onerror=d=>s(d),t.config.prepare_external_dependency_script&&(l=t.config.prepare_external_dependency_script(l)),!l)return s("prepare_external_dependency_script returned null");if(t.config.external_scripts_inject_target==="head")C.head.appendChild(l);else{var u,c=C.querySelectorAll("body > script");c.length>0?(u=c[0].parentNode)==null||u.insertBefore(l,c[0]):C.body.appendChild(l)}};C!=null&&C.body?a():C?.addEventListener("DOMContentLoaded",a)};$.__PosthogExtensions__=$.__PosthogExtensions__||{},$.__PosthogExtensions__.loadExternalDependency=(t,e,s)=>{if(e!=="remote-config"){var r;if(t.config.strict_script_versioning)r=t.requestRouter.endpointFor("assets","/static/"+t.version+"/"+e+".js");else{var n="/static/"+e+".js?v="+t.version;if(e==="toolbar"){var i=3e5;n=n+"&t="+Math.floor(Date.now()/i)*i}r=t.requestRouter.endpointFor("assets",n)}si(t,r,s)}else{var o=t.requestRouter.endpointFor("assets","/array/"+t.config.token+"/config.js");si(t,o,s)}},$.__PosthogExtensions__.loadSiteApp=(t,e,s)=>{var r=t.requestRouter.endpointFor("api",e);si(t,r,s)};Y.DEBUG=!1,Y.LIB_VERSION="1.415.7",Y.LIB_NAME="web";var au="$people_distinct_id",sr="$device_id",ri="$device_model",Bs="__alias",js="__timers",Ui="$autocapture_disabled_server_side",Hi="$heatmaps_enabled_server_side",Wi="$exception_capture_enabled_server_side",zi="$error_tracking_suppression_rules",qi="$error_tracking_capture_extension_exceptions",Vi="$web_vitals_enabled_server_side",Ho="$dead_clicks_enabled_server_side",Wo="$product_tours_enabled_server_side",Gi="$web_vitals_allowed_metrics",qt="$session_recording_remote_config",lu="$replay_sample_rate",cu="$replay_override_sampling",uu="$replay_override_linked_flag",du="$replay_override_url_trigger",hu="$replay_override_event_trigger",ls="$sesid",zo="$session_is_sampled",Bt="$enabled_feature_flags",Us="$active_feature_flags",Rr="$early_access_features",Ki="$feature_flag_details",Hs="$feature_flag_payloads",Tr="$feature_flag_request_id",en="$minimal_flag_called_events",et="$override_feature_flags",jt="$override_feature_flag_payloads",ct="$stored_person_properties",Ut="$stored_group_properties",Ji="$surveys",tn="$surveys_loaded_at",Yi="$surveys_activated",Nr="$surveys_activated_session",Mr="$surveys_activated_timestamps",Ws="ph_product_tours",Wt="$flag_call_reported",zs="$flag_call_reported_session_id",Lr="$feature_flag_errors",Gs="$feature_flag_evaluated_at",He="$user_state",Zi="$client_session_props",Xi="$capture_rate_limit",Qi="$initial_campaign_params",eo="$initial_referrer_info",sn="$initial_person_info",rn="$epp",br="$posthog_cookieless",pu="$cookieless_mode",fu="$sdk_debug_extensions_init_method",gu="$sdk_debug_extensions_init_time_ms",mu="$sdk_debug_recording_script_not_loaded",qo="PostHog loadExternalDependency extension not found.",Ht="on_reject",ht="always",es="anonymous",Tt="identified",to="identified_only",nn="visibilitychange",on="beforeunload",is="$pageview",ni="$pageleave",ii="$identify",Qa="$groupidentify";function Er(t,e){L(t)&&t.forEach(e)}function Z(t,e){if(!D(t))if(L(t))t.forEach(e);else if(fh(t))t.forEach(((r,n)=>e(r,n)));else for(var s in t)Ac.call(t,s)&&e(t[s],s)}var ee=function(t){for(var e=arguments.length,s=new Array(e>1?e-1:0),r=1;e>r;r++)s[r-1]=arguments[r];for(var n of s)for(var i in n)n[i]!==void 0&&(t[i]=n[i]);return t};function Or(t){for(var e=Object.keys(t),s=e.length,r=new Array(s);s--;)r[s]=[e[s],t[e[s]]];return r}var el=function(t){try{return t()}catch{return}},np=function(t){return function(){try{for(var e=arguments.length,s=new Array(e),r=0;e>r;r++)s[r]=arguments[r];return t.apply(this,s)}catch(n){k.critical("Implementation error. Please turn on debug mode and open a ticket on https://app.posthog.com/home#panel=support%3Asupport%3A."),k.critical(n)}}},Vo=function(t){var e={};return Z(t,(function(s,r){(W(s)&&s.length>0||he(s))&&(e[r]=s)})),e},ip=["herokuapp.com","vercel.app","netlify.app"];function op(t){var e=t?.hostname;if(!W(e))return!1;var s=e.split(".").slice(-2).join(".");for(var r of ip)if(s===r)return!1;return!0}function ne(t,e,s,r){var n=r??{},i=n.capture,o=n.passive;t?.addEventListener(e,s,{capture:i!==void 0&&i,passive:o===void 0||o})}function so(t){return t.name==="ph_toolbar_internal"}var vu=t=>{if(C){try{for(var e=t+"=",s=C.cookie.split(";").filter((i=>i.length)),r=0;s.length>r;r++){for(var n=s[r];n.charAt(0)==" ";)n=n.substring(1,n.length);if(n.indexOf(e)===0)return decodeURIComponent(n.substring(e.length,n.length))}}catch{}return null}};Math.trunc||(Math.trunc=function(t){return 0>t?Math.ceil(t):Math.floor(t)}),Number.isInteger||(Number.isInteger=function(t){return he(t)&&isFinite(t)&&Math.floor(t)===t});class an{constructor(e){if(this.bytes=e,e.length!==16)throw new TypeError("not 128-bit length")}static fromFieldsV7(e,s,r,n){if(!Number.isInteger(e)||!Number.isInteger(s)||!Number.isInteger(r)||!Number.isInteger(n)||0>e||0>s||0>r||0>n||e>0xffffffffffff||s>4095||r>1073741823||n>4294967295)throw new RangeError("invalid field value");var i=new Uint8Array(16);return i[0]=e/Math.pow(2,40),i[1]=e/Math.pow(2,32),i[2]=e/Math.pow(2,24),i[3]=e/Math.pow(2,16),i[4]=e/256,i[5]=e,i[6]=112|s>>>8,i[7]=s,i[8]=128|r>>>24,i[9]=r>>>16,i[10]=r>>>8,i[11]=r,i[12]=n>>>24,i[13]=n>>>16,i[14]=n>>>8,i[15]=n,new an(i)}toString(){for(var e="",s=0;this.bytes.length>s;s++)e=e+(this.bytes[s]>>>4).toString(16)+(15&this.bytes[s]).toString(16),s!==3&&s!==5&&s!==7&&s!==9||(e+="-");if(e.length!==36)throw new Error("Invalid UUIDv7 was generated");return e}clone(){return new an(this.bytes.slice(0))}equals(e){return this.compareTo(e)===0}compareTo(e){for(var s=0;16>s;s++){var r=this.bytes[s]-e.bytes[s];if(r!==0)return Math.sign(r)}return 0}}class ap{generate(){var e=this.generateOrAbort();if(!x(e))return e;this.S=0;var s=this.generateOrAbort();if(x(s))throw new Error("Could not generate UUID after timestamp reset");return s}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 an.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 lp}}var tl,_u=t=>{if(typeof UUIDV7_DENY_WEAK_RNG<"u"&&UUIDV7_DENY_WEAK_RNG)throw new Error("no cryptographically strong RNG available");for(var e=0;t.length>e;e++)t[e]=65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random());return t};v&&!x(v.crypto)&&crypto.getRandomValues&&(_u=t=>crypto.getRandomValues(t));class lp{nextUint32(){return this.R.length>this.O||(_u(this.R),this.O=0),this.R[this.O++]}constructor(){this.R=new Uint32Array(8),this.O=1/0}}var dt=()=>cp().toString(),cp=()=>(tl||(tl=new ap)).generate(),Ps="",up=/[a-z0-9][a-z0-9-]+\.[a-z]{2,}$/i,pt={N:()=>!!C,j(t){k.error("cookieStore error: "+t)},P:vu,H(t){var e;try{e=JSON.parse(pt.P(t))||{}}catch{}return e},F(t,e,s,r,n){if(!C)return!1;try{var i="",o="",a=(function(c,d){if(d){var h=(function(f,g){if(g===void 0&&(g=C),Ps)return Ps;if(!g||["localhost","127.0.0.1"].includes(f))return"";for(var m=f.split("."),_=Math.min(m.length,8),w="dmn_chk_"+dt();!Ps&&_--;){var E=m.slice(_).join("."),I=w+"=1;domain=."+E+";path=/";g.cookie=I+";max-age=3",g.cookie.includes(w)&&(g.cookie=I+";max-age=0",Ps=E)}return Ps})(c);if(!h){var p=(f=>{var g=f.match(up);return g?g[0]:""})(c);p!==h&&k.info("Warning: cookie subdomain discovery mismatch",p,h),h=p}return h?"; domain=."+h:""}return""})(C.location.hostname,r);if(s){var l=new Date;l.setTime(l.getTime()+864e5*s),i="; expires="+l.toUTCString()}n&&(o="; secure");var u=t+"="+encodeURIComponent(JSON.stringify(e))+i+"; SameSite=Lax; path=/"+a+o;return u.length>3686.4&&k.warn("cookieStore warning: large cookie, len="+u.length),C.cookie=u,!0}catch{return!1}},q(t,e){if(C!=null&&C.cookie)try{pt.F(t,"",-1,e)}catch{return}}},oi=null,Q={N(){if(!$e(oi))return oi;var t=!0;if(x(v))t=!1;else try{var e="__mplssupport__";Q.F(e,"xyz"),Q.P(e)!=='"xyz"'&&(t=!1),Q.q(e)}catch{t=!1}return t||k.error("localStorage unsupported; falling back to cookie store"),oi=t,t},j(t){k.error("localStorage error: "+t)},P(t){try{return v?.localStorage.getItem(t)}catch(e){Q.j(e)}return null},H(t){try{return JSON.parse(Q.P(t))||{}}catch{}return null},F(t,e){try{return v?.localStorage.setItem(t,JSON.stringify(e)),!0}catch(s){Q.j(s)}return!1},q(t){try{v?.localStorage.removeItem(t)}catch(e){Q.j(e)}}},dp=[sr,"distinct_id",ls,zo,rn,sn,He],Sr={},hp={N:()=>!0,j(t){k.error("memoryStorage error: "+t)},P:t=>Sr[t]||null,H:t=>Sr[t]||null,F:(t,e)=>(Sr[t]=e,!0),q(t){delete Sr[t]}},Nt=null,ce={N(){if(!$e(Nt))return Nt;if(Nt=!0,x(v))Nt=!1;else try{var t="__support__";ce.F(t,"xyz"),ce.P(t)!=='"xyz"'&&(Nt=!1),ce.q(t)}catch{Nt=!1}return Nt},j(t){k.error("sessionStorage error: ",t)},P(t){try{return v?.sessionStorage.getItem(t)}catch(e){ce.j(e)}return null},H(t){try{return JSON.parse(ce.P(t))||null}catch{}return null},F(t,e){try{return v?.sessionStorage.setItem(t,JSON.stringify(e)),!0}catch(s){ce.j(s)}return!1},q(t){try{v?.sessionStorage.removeItem(t)}catch(e){ce.j(e)}}};class pp{constructor(e){this._instance=e}get Ne(){return this._instance.config}get consent(){return this.ti()?0:this.ei}isOptedOut(){return this.Ne.cookieless_mode===ht||this.isRejected()||this.consent===-1&&this.Ne.cookieless_mode===Ht}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,s=e.token,r=e.opt_out_capturing_cookie_prefix;return e.consent_persistence_name||(r?r+s:"__ph_opt_in_out_"+s)}get ei(){var e=this.ii.P(this.ri);return Zn(e)?1:M(_h,e)?0:-1}get ii(){var e=this.Ne.opt_out_capturing_persistence_type,s=e==="localStorage"?Q:pt;if(!this.ni||this.ni!==s){this.ni=s;var r=e==="localStorage"?pt:Q;r.P(this.ri)&&(this.ni.P(this.ri)||this.optInOut(Zn(r.P(this.ri))),r.q(this.ri,this.Ne.cross_subdomain_cookie))}return this.ni}ti(){return!!this.Ne.respect_dnt&&[ke?.doNotTrack,ke?.msDoNotTrack,$.doNotTrack].some((e=>Zn(e)))}}function yu(t,e){var s,r=t==null||(s=t.config)==null?void 0:s.get_current_url;if(!Se(r))return e;try{var n=r(e);return W(n)&&n?n:e}catch(i){return k.error("Error in get_current_url, falling back to window.location.href",i),e}}var wu="__POSTHOG_TOOLBAR__",fp=1,gp=3,mp=11;function sl(t){return t instanceof Element&&(t.id===wu||!(t.closest==null||!t.closest(".toolbar-global-fade-container")))}function Ft(t){return!!t&&t.nodeType===fp}function Me(t,e){return!!t&&!!t.tagName&&t.tagName.toLowerCase()===e.toLowerCase()}function bu(t){return!!t&&t.nodeType===gp}function Eu(t){return!!t&&t.nodeType===mp&&Ft(t.host)}var Su=1e3;function Go(t){return t?Pn(t).split(/\s+/):[]}function rl(t,e){var s=(function(r){var n,i=v==null||(n=v.location)==null?void 0:n.href;return x(i)?void 0:yu(r,i)})(e);return!!(s&&t&&t.some((r=>s.match(r))))}function ln(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 Go(e)}function xu(t){return D(t)?null:Pn(t).split(/(\s+)/).filter((e=>Ks(e))).join("").replace(/[\r\n]/g," ").replace(/[ ]+/g," ").substring(0,255)}function rr(t){var e="";return no(t)&&!Fu(t)&&t.childNodes&&t.childNodes.length&&Z(t.childNodes,(function(s){var r;bu(s)&&s.textContent&&(e+=(r=xu(s.textContent))!==null&&r!==void 0?r:"")})),Pn(e)}function ai(t){var e;return x(t.target)?t.srcElement||null:(e=t.target)!=null&&e.shadowRoot?t.composedPath()[0]||null:t.target||null}var Ko=["a","button","form","input","select","textarea","label"];function ro(t,e){if(x(e))return!0;var s,r=function(i){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}})(i,o))))return{v:!0}};for(var n of t)if(s=r(n))return s.v;return!1}function ku(t){var e=t.parentNode;return!(!e||!Ft(e))&&e}var vp=[".ph-no-autocapture","[data-ph-no-autocapture]"],Iu=["next","previous","prev",">","<"],_p=[...Iu,"+","-","−","–"],nl=(t,e)=>/[a-z0-9]/i.test(e)?t.includes(e):t===e,il=[".ph-no-rageclick",".ph-no-capture"],yp=["","text","search","email","password","url","tel","number"];function ol(t,e){if(!v||Jo(t))return!1;var s,r,n,i,o;if(Ke(e)?(s=!!e&&il,r=void 0,n=!1):(s=(i=e?.css_selector_ignorelist)!==null&&i!==void 0?i:il,r=e?.content_ignorelist,n=(o=e?.ignore_text_selection)!==null&&o!==void 0&&o),s===!1||n&&(function(l){return!(!l||!Ft(l))&&(!!Me(l,"textarea")||(Me(l,"input")?M(yp,(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=Cu(t,!1).targetElementList;return!(function(l,u){if(l===!1||x(l))return!1;var c;if(l===!0)c=Iu;else{if(!L(l))return!1;if(l.length>10)return k.error("[PostHog] content_ignorelist array cannot exceed 10 items. Use css_selector_ignorelist for more complex matching."),!1;c=l.map((d=>d.toLowerCase()))}return u.some((d=>{var h=d.safeText,p=d.ariaLabel;return c.some((f=>nl(h,f)||nl(p,f)))}))})(r,a.map((l=>{var u;return{safeText:rr(l).toLowerCase(),ariaLabel:((u=l.getAttribute("aria-label"))==null?void 0:u.toLowerCase().trim())||""}})))&&!ro(a,s)}var Jo=t=>!t||Me(t,"html")||!Ft(t),Cu=(t,e)=>{if(!v||Jo(t))return{parentIsUsefulElement:!1,targetElementList:[]};for(var s=!1,r=[t],n=t;n.parentNode&&!Me(n,"body");)if(Eu(n.parentNode))r.push(n.parentNode.host),n=n.parentNode.host;else{var i=ku(n);if(!i)break;if(e||Ko.indexOf(i.tagName.toLowerCase())>-1)s=!0;else try{var o=v.getComputedStyle(i);o&&o.getPropertyValue("cursor")==="pointer"&&(s=!0)}catch{}r.push(i),n=i}return{parentIsUsefulElement:s,targetElementList:r}};function no(t){for(var e=new Set,s=0,r=t;r.parentNode&&!Me(r,"body");r=r.parentNode){if(s++>=Su||e.has(r))return!1;e.add(r);var n=ln(r);if(M(n,"ph-sensitive")||M(n,"ph-no-capture"))return!1}if(M(ln(t),"ph-include"))return!0;var i=t.type||"";if(W(i))switch(i.toLowerCase()){case"hidden":case"password":return!1}var o=t.name||t.id||"";return!W(o)||!/^cc|cardnum|ccnum|creditcard|csc|cvc|cvv|exp|pass|pwd|routing|seccode|securitycode|securitynum|socialsec|socsec|ssn/i.test(o.replace(/[^a-zA-Z0-9]/g,""))}function Fu(t){return!!(Me(t,"input")&&!["button","checkbox","submit","reset"].includes(t.type)||Me(t,"select")||Me(t,"textarea")||t.getAttribute("contenteditable")==="true")}var al=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}))$"),ll=/(^|[^0-9A-Za-z_])([0-9][0-9 -]*[0-9])(?=$|[^0-9A-Za-z_])/g,wp=[16,15,14,13],bp=new RegExp("^(\\d{3}-?\\d{2}-?\\d{4})$"),cl=new RegExp("(^|[^0-9])((?!000|666)[0-9]{3}-?(?!00)[0-9]{2}-?(?!0000)[0-9]{4})(?=$|([^0-9]))","g"),ul=/[0-9A-Za-z_]/;function Ep(t){for(var e=0,s=!1,r=t.length-1;r>=0;r--){var n=t.charCodeAt(r)-48;s&&(n*=2)>9&&(n-=9),e+=n,s=!s}return e%10==0}function Ks(t,e){if(e===void 0&&(e=!0),D(t))return!1;if(W(t)){t=Pn(t);var s=e?al.test((t||"").replace(/[- ]/g,"")):(function(n){var i;for(ll.lastIndex=0;i=ll.exec(n);){var o=i[2];if(o)for(var a=o.replace(/[- ]/g,""),l=0;a.length>l;l++)for(var u of wp){var c=l+u;if(a.length>=c){var d=a.slice(l,c);if(al.test(d)&&Ep(d))return!0}}}return!1})(t);if(s)return!1;var r=e?bp.test(t):(function(n){var i;for(cl.lastIndex=0;i=cl.exec(n);){var o=i[1],a=i[3];if(!(o&&a&&ul.test(o)&&ul.test(a)))return!0}return!1})(t);if(r)return!1}return!0}function dl(t){var e=rr(t);return Ks(e=(e+" "+Pu(t)).trim())?e:""}function Pu(t){var e="";return t&&t.childNodes&&t.childNodes.length&&Z(t.childNodes,(function(s){var r;if(s&&((r=s.tagName)==null?void 0:r.toLowerCase())==="span")try{var n=rr(s);e=(e+" "+n).trim(),s.childNodes&&s.childNodes.length&&(e=(e+" "+Pu(s)).trim())}catch(i){k.error("[AutoCapture]",i)}})),e}function hl(t){return t.replace(/"|\\"/g,'\\"')}function Sp(t){var e=t.attr__class;if(e)return L(e)?e:Go(e)}var xr=se("[Dead Clicks]"),xp=()=>!0,kp=t=>{var e,s=!((e=t.instance.persistence)==null||!e.get_property(Ho)),r=t.instance.config.capture_dead_clicks;return Ke(r)?r:!!te(r)||s};class pl{get lazyLoadedDeadClicksAutocapture(){return this.si}constructor(e,s,r){this.instance=e,this.isEnabled=s,this.onCapture=r,this.startIfEnabledOrStop()}onRemoteConfig(e){if(e.ok){var s=e.config;"captureDeadClicks"in s&&(this.instance.persistence&&this.instance.persistence.register({[Ho]:s.captureDeadClicks}),this.startIfEnabledOrStop())}}startIfEnabledOrStop(){this.isEnabled(this)?this.ai((()=>{this.oi()})):this.stop()}ai(e){var s,r;(s=$.__PosthogExtensions__)!=null&&s.initDeadClicksAutocapture?e():(r=$.__PosthogExtensions__)==null||r.loadExternalDependency==null||r.loadExternalDependency(this.instance,"dead-clicks-autocapture",(n=>{n?xr.error("failed to load script",n):e()}))}oi(){var e;if(C){if(!this.si&&(e=$.__PosthogExtensions__)!=null&&e.initDeadClicksAutocapture){var s=te(this.instance.config.capture_dead_clicks)?b({},this.instance.config.capture_dead_clicks):{};s.__onCapture=this.onCapture,this.onCapture&&(s.capture_dead_swipes=!1),this.si=$.__PosthogExtensions__.initDeadClicksAutocapture(this.instance,s),this.si.start(C),xr.info("starting...")}}else xr.error("`document` not found. Cannot start.")}stop(){this.si&&(this.si.stop(),this.si=void 0,xr.info("stopping..."))}}var li=se("[SegmentIntegration]"),Au="posthog-js";function $u(t,e){var s=e===void 0?{}:e,r=s.organization,n=s.projectId,i=s.prefix,o=s.severityAllowList,a=o===void 0?["error"]:o,l=s.sendExceptionsToPostHog,u=l===void 0||l;return c=>{var d,h,p,f,g;if(a!=="*"&&!a.includes(c.level)||!t.__loaded)return c;c.tags||(c.tags={});var m=t.requestRouter.endpointFor("ui","/project/"+t.config.token+"/person/"+t.get_distinct_id());c.tags["PostHog Person URL"]=m,t.sessionRecordingStarted()&&(c.tags["PostHog Recording URL"]=t.get_session_replay_url({withTimestamp:!0}));var _,w=((d=c.exception)==null?void 0:d.values)||[],E=w.map((F=>b({},F,{stacktrace:F.stacktrace?b({},F.stacktrace,{type:"raw",frames:(F.stacktrace.frames||[]).map((P=>b({},P,{platform:"web:javascript"})))}):void 0}))),I={$exception_message:((h=w[0])==null?void 0:h.value)||c.message,$exception_type:(p=w[0])==null?void 0:p.type,$exception_level:c.level,$exception_list:E,$sentry_event_id:c.event_id,$sentry_exception:c.exception,$sentry_exception_message:((f=w[0])==null?void 0:f.value)||c.message,$sentry_exception_type:(g=w[0])==null?void 0:g.type,$sentry_tags:c.tags};return r&&n&&(I.$sentry_url=(i||"https://sentry.io/organizations/")+r+"/issues/?project="+n+"&query="+c.event_id),u&&((_=t.exceptions)==null||_.sendExceptionEvent(I)),c}}class Ip{constructor(e,s,r,n,i,o){this.name=Au,this.setupOnce=function(a){a($u(e,{organization:s,projectId:r,prefix:n,severityAllowList:i,sendExceptionsToPostHog:o==null||o}))}}}class fl{constructor(e){this.li=(s,r,n)=>{n&&(n.noSessionId||n.activityTimeout||n.sessionPastMaximumLength||n.crossTabAdoption)&&(k.info("[PageViewManager] Session rotated, clearing pageview state",{sessionId:s,changeReason:n}),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,s){var r,n=this.vi(e,s);return this.ui={pathname:(r=v?.location.pathname)!==null&&r!==void 0?r:"",pageViewId:s,timestamp:e},this._instance.scrollManager.resetContext(),n}doPageLeave(e){var s;return this.vi(e,(s=this.ui)==null?void 0:s.pageViewId)}doEvent(){var e;return{$pageview_id:(e=this.ui)==null?void 0:e.pageViewId}}vi(e,s){var r=this.ui;if(!r)return{$pageview_id:s};var n={$pageview_id:s,$prev_pageview_id:r.pageViewId},i=this._instance.scrollManager.getContext();if(i&&!this._instance.config.disable_scroll_properties){var o=i.maxScrollHeight,a=i.lastScrollY,l=i.maxScrollY,u=i.maxContentHeight,c=i.lastContentY,d=i.maxContentY;if(!(x(o)||x(a)||x(l)||x(u)||x(c)||x(d))){o=Math.ceil(o),a=Math.ceil(a),l=Math.ceil(l),u=Math.ceil(u),c=Math.ceil(c),d=Math.ceil(d);var h=o>1?rt(a/o,0,1,k):1,p=o>1?rt(l/o,0,1,k):1,f=u>1?rt(c/u,0,1,k):1,g=u>1?rt(d/u,0,1,k):1;n=ee(n,{$prev_pageview_last_scroll:a,$prev_pageview_last_scroll_percentage:h,$prev_pageview_max_scroll:l,$prev_pageview_max_scroll_percentage:p,$prev_pageview_last_content:c,$prev_pageview_last_content_percentage:f,$prev_pageview_max_content:d,$prev_pageview_max_content_percentage:g})}}return r.pathname&&(n.$prev_pageview_pathname=r.pathname),r.timestamp&&(n.$prev_pageview_duration=(e.getTime()-r.timestamp.getTime())/1e3),n}}var ci=["flags","surveys"],Cp={[au]:{exposure:"hidden"},[Bs]:{exposure:"hidden"},__cmpns:{exposure:"hidden"},[js]:{exposure:"hidden"},[Ui]:{exposure:"event"},[Hi]:{exposure:"hidden"},[Wi]:{exposure:"event"},[zi]:{exposure:"hidden"},[qi]:{exposure:"event"},[Vi]:{exposure:"event"},[Ho]:{exposure:"event"},[Wo]:{exposure:"hidden"},[Gi]:{exposure:"event"},[qt]:{exposure:"hidden"},$session_recording_enabled_server_side:{exposure:"hidden"},[ls]:{exposure:"hidden"},[zo]:{exposure:"event"},[lu]:{exposure:"event",shouldSkipFromEventProperties:t=>$e(t)},$session_past_minimum_duration:{exposure:"event"},$session_recording_url_trigger_activated_session:{exposure:"event"},$session_recording_event_trigger_activated_session:{exposure:"event"},$debug_first_full_snapshot_timestamp:{exposure:"event"},$sess_rec_flush_size:{exposure:"hidden"},[Bt]:{exposure:"hidden",storageGroup:"flags"},[Us]:{exposure:"hidden",storageGroup:"flags"},[Rr]:{exposure:"hidden"},[Ki]:{exposure:"hidden",storageGroup:"flags"},[Hs]:{exposure:"hidden",storageGroup:"flags"},[Tr]:{exposure:"hidden",storageGroup:"flags",volatile:!0},[en]:{exposure:"hidden",storageGroup:"flags"},[et]:{exposure:"hidden"},[jt]:{exposure:"hidden"},[ct]:{exposure:"hidden"},[Ut]:{exposure:"hidden"},[Ji]:{exposure:"hidden",storageGroup:"surveys"},[tn]:{exposure:"hidden",storageGroup:"surveys",volatile:!0},[Yi]:{exposure:"event"},[Nr]:{exposure:"hidden"},[Mr]:{exposure:"hidden"},[Ws]:{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"},[Wt]:{exposure:"hidden"},[zs]:{exposure:"hidden"},[Lr]:{exposure:"hidden"},[Gs]:{exposure:"hidden",storageGroup:"flags",volatile:!0},[He]:{exposure:"hidden"},[Zi]:{exposure:"hidden"},[Xi]:{exposure:"hidden"},[Qi]:{exposure:"hidden"},[eo]:{exposure:"hidden"},[sn]:{exposure:"hidden"},[rn]:{exposure:"hidden"},[cu]:{exposure:"event"},[uu]:{exposure:"event"},[du]:{exposure:"event"},[hu]:{exposure:"event"},[fu]:{exposure:"event"},[gu]:{exposure:"event"},[mu]:{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"}},Fp=[["$posthog_sr_group_event_trigger_",{exposure:"hidden"}],["$posthog_sr_group_url_trigger_",{exposure:"hidden"}],["$posthog_sr_group_sampling_",{exposure:"hidden"}]],Mt=t=>{var e=Cp[t];if(e)return e;for(var s of Fp){var r=s[1];if(t.indexOf(s[0])===0)return r}},cs=(t,e)=>{try{return JSON.stringify(t,((s,r)=>typeof r=="bigint"?r.toString():r),e)}catch{return Fc(t)}},cn=t=>{var e=C?.createElement("a");return x(e)?null:(e.href=t,e)},ms=function(t,e){for(var s,r=((t.split("#")[0]||"").split(/\?(.*)/)[1]||"").replace(/^\?+/g,"").split("&"),n=0;r.length>n;n++){var i=r[n].split("=");if(i[0]===e){s=i;break}}if(!L(s)||2>s.length)return"";var o=s[1];try{o=decodeURIComponent(o)}catch{k.error("Skipping decoding for malformed query param: "+o)}return o.replace(/\+/g," ")},nr=function(t,e,s){if(!t||!e||!e.length)return t;for(var r=t.split("#"),n=r[1],i=(r[0]||"").split("?"),o=i[1],a=i[0],l=(o||"").split("&"),u=[],c=0;l.length>c;c++){var d=l[c].split("=");L(d)&&(e.includes(d[0])?u.push(d[0]+"="+s):u.push(l[c]))}var h=a;return o!=null&&(h+="?"+u.join("&")),n!=null&&(h+="#"+n),h},un=function(t,e){var s=t.match(new RegExp(e+"=([^&]*)"));return s?s[1]:null},Ru=(t,e)=>t>=e&&kc(),Tu=(t,e,s,r)=>{if(t===0){if(kc()){var n=e+1;return n===s&&r(),n}return e}return 0},kr="https?://(.*)",vs=["gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","irclid","_kx"],Pp=["utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid",...vs],ir="",Ap=["li_fat_id"];function Nu(t,e,s){if(!C)return{};var r,n=e?[...vs,...s||[]]:[],i=Mu(nr(C.URL,n,ir),t),o=(r={},Z(Ap,(function(a){var l=vu(a);r[a]=l||null})),r);return ee(o,i)}function Mu(t,e){var s=Pp.concat(e||[]),r={};return Z(s,(function(n){var i=ms(t,n);r[n]=i||null})),r}function Lu(t){var e=(function(i){return i?i.search(kr+"google.([^/?]*)")===0?"google":i.search(kr+"bing.com")===0?"bing":i.search(kr+"yahoo.com")===0?"yahoo":i.search(kr+"duckduckgo.com")===0?"duckduckgo":null:null})(t),s=e!="yahoo"?"q":"p",r={};if(!$e(e)){r.$search_engine=e;var n=C?ms(C.referrer,s):"";n.length&&(r.ph_keyword=n)}return r}function gl(){return navigator.language||navigator.userLanguage}var dn="$direct";function Ou(){return C?.referrer||dn}function Du(t,e,s){s===void 0&&(s=!1);var r=t?[...vs,...e||[]]:[],n=s?Ct(re?.href):re?.href,i=n?.substring(0,1e3);return{r:Ou().substring(0,1e3),u:i?nr(i,r,ir):void 0}}function Bu(t,e){var s;e===void 0&&(e=!1);var r=t.r,n=t.u,i=e?Ct(n):n,o={$referrer:r,$referring_domain:r==null?void 0:r==dn?dn:(s=cn(r))==null?void 0:s.host};if(i){o.$current_url=i;var a=cn(i);o.$host=a?.host,o.$pathname=a?.pathname;var l=Mu(i);ee(o,l)}if(r){var u=Lu(r);ee(o,u)}return o}function ju(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return}}function $p(){try{return new Date().getTimezoneOffset()}catch{return}}var Rp={flags:Gs,surveys:tn},Tp=["cookie","localstorage","localstorage+cookie","sessionstorage","memory"],ts="main";class ui{constructor(e,s,r){if(r===void 0&&(r=!0),this.ci={},this.fi=!1,this.pi=!1,this.Ne=e,this.gi=r,this.props={},this.mi=void 0,this.yi=(i=>{var o="";return i.token&&(o=i.token.replace(/\+/g,"PL").replace(/\//g,"SL").replace(/=/g,"EQ")),i.persistence_name?"ph_"+i.persistence_name:"ph_"+o+"_posthog"})(e),this.ii=this.bi(e),this.pi=this.wi(e),this.load(),e.debug&&k.info("Persistence loaded",e.persistence,b({},this.props)),this.update_config(e,e,s),this.save(),v){var n=()=>this.flush();ne(v,"beforeunload",n,{capture:!1}),ne(v,"pagehide",n,{capture:!1})}}ki(){var e,s=(e=this.Ne)==null?void 0:e.persistence_save_debounce_ms;return he(s)&&s>0?s:0}isDisabled(){return!!this.xi}bi(e){Tp.indexOf(e.persistence.toLowerCase())===-1&&(k.critical("Unknown persistence type "+e.persistence+"; falling back to localStorage+cookie"),e.persistence="localStorage+cookie");var s,r=(function(o,a){o===void 0&&(o=[]),a===void 0&&(a=!1);var l=[...dp,...o];return b({},Q,{H(u){try{var c={};try{c=pt.H(u)||{}}catch{}var d,h=JSON.parse(Q.P(u)||"{}");if(a){var p={};for(var f in c){var g=c[f];$e(g)||g===""||(p[f]=g)}d=ee(h,p)}else d=ee(c,h);return Q.F(u,d),d}catch{}return null},F(u,c,d,h,p,f){var g=Q.F(u,c,void 0,void 0,f);try{var m={};l.forEach((_=>{c[_]&&(m[_]=c[_])})),Object.keys(m).length&&pt.F(u,m,d,h,p,f)}catch(_){Q.j(_)}return g},q(u,c){try{v?.localStorage.removeItem(u),pt.q(u,c)}catch(d){Q.j(d)}}})})(e.cookie_persisted_properties||[],e.__preview_cookie_wins_on_conflict||!1),n=!1,i=e.persistence.toLowerCase();return i==="localstorage"&&Q.N()?(s=Q,n=!0):i==="localstorage+cookie"&&r.N()?(s=r,n=!0):i==="sessionstorage"&&ce.N()?s=ce:i==="memory"?s=hp:i==="cookie"?s=pt:r.N()?(s=r,n=!0):s=pt,this.fi=n,s}Si(e){return this.yi+"__"+e}wi(e){return this.fi&&!!e.split_storage}properties(){var e={};return Z(this.props,((s,r)=>{var n=Mt(r);if(!n||n.exposure==="event"){if(n!=null&&n.shouldSkipFromEventProperties!=null&&n.shouldSkipFromEventProperties(s))return;e[r]=s}})),e}load(){if(!this.xi){var e=this.ii.H(this.yi);e&&(this.props=ee({},e)),this.pi&&this.Ci()}}Ci(){for(var e of ci){var s=Q.H(this.Si(e));if(s&&!mt(s)){var r=this.Mi(e);r.persisted=!0,this.Ti(e)||(r.fingerprint=this.Ei(s,e)),this.Ii(e,s)||ee(this.props,s)}}}Ti(e){return Object.keys(this.props).some((s=>{var r;return((r=Mt(s))==null?void 0:r.storageGroup)===e}))}Ii(e,s){var r=Rp[e];if(!r)return!1;var n=s[r],i=this.props[r];return he(n)&&he(i)&&i>n}refreshKey(e){var s;if(!this.xi){var r=this.pi?(s=Mt(e))==null?void 0:s.storageGroup:void 0,n=r?Q.H(this.Si(r)):this.ii.H(this.yi);if(n&&e in n)this.Pi(e,n[e]);else{if(r){var i=this.ii.H(this.yi);if(i&&e in i)return void this.Pi(e,i[e])}this.Ri(e)}}}save(){if(!this.xi){var e=this.ki();e>0?x(this.Ai)&&(this.Ai=setTimeout((()=>{this.Ai=void 0,this.Fi()}),e)):this.Fi()}}flush(){x(this.Ai)||(clearTimeout(this.Ai),this.Ai=void 0,this.Fi())}Fi(){this.xi||(this.pi?this.Li():this.Oi(this.ii,this.yi,this.props,ts))}Li(){var e=this.Di(),s=e.main,r=e.groups;for(var n of(this.Oi(this.ii,this.yi,s,ts),ci)){var i,o=r[n];(!mt(o)||(i=this.ci[n])!=null&&i.persisted)&&this.Oi(Q,this.Si(n),o,n)}}Di(){var e={},s={flags:{},surveys:{}};return Z(this.props,((r,n)=>{var i,o=(i=Mt(n))==null?void 0:i.storageGroup;o?s[o][n]=r:e[n]=r})),{main:e,groups:s}}Ei(e,s){if(s===ts)return JSON.stringify(e)+"|"+this.$i+"|"+this.Ni+"|"+this.qi;var r={};return Z(e,((n,i)=>{var o;r[i]=(o=Mt(i))!=null&&o.volatile?"__volatile__":n})),JSON.stringify(r)}Oi(e,s,r,n){var i=this.Mi(n);if(n===ts||i.dirty||x(i.fingerprint)){var o;try{if((o=this.Ei(r,n))===i.fingerprint)return void(i.dirty=!1)}catch{o=void 0}e.F(s,r,this.$i,this.Ni,this.qi,this.Ne.debug)?(i.dirty=!1,n!==ts&&(i.persisted=!0),x(o)||(i.fingerprint=o)):this.Ne.debug&&k.warn('failed to persist storage entry "'+s+'"; will retry on next save')}}remove(e){var s=(e===void 0?{}:e).keepGroupEntries,r=s!==void 0&&s;if(x(this.Ai)||(clearTimeout(this.Ai),this.Ai=void 0),this.ii.q(this.yi,!1),this.ii.q(this.yi,!0),!r&&this.gi)for(var n of ci)Q.q(this.Si(n));r?delete this.ci[ts]:this.ci={}}clear(){this.remove(),this.props={}}register_once(e,s,r){if(te(e)){x(s)&&(s="None"),this.$i=x(r)?this.ji:r;var n=!1;if(Z(e,((i,o)=>{this.props.hasOwnProperty(o)&&this.props[o]!==s||(this.Pi(o,i),n=!0)})),n)return this.save(),!0}return!1}register(e,s){if(te(e)){this.$i=x(s)?this.ji:s;var r=!1;if(Z(e,((n,i)=>{e.hasOwnProperty(i)&&(this.props[i]!==n||te(n)||L(n))&&(this.Pi(i,n),r=!0)})),r)return this.save(),!0}return!1}unregister(e){var s=typeof e=="string"?[e]:e,r=!1;for(var n of s)n in this.props&&(this.Ri(n),r=!0);r&&this.save()}update_campaign_params(){var e=C?.URL;if(e!==this.mi){var s=Nu(this.Ne.custom_campaign_params,this.Ne.mask_personal_data_properties,this.Ne.custom_personal_data_properties);mt(Vo(s))||this.register(s),this.mi=e}}update_search_keyword(){var e;this.register((e=C?.referrer)?Lu(e):{})}update_referrer_info(){var e;this.register_once({$referrer:Ou(),$referring_domain:C!=null&&C.referrer&&((e=cn(C.referrer))==null?void 0:e.host)||dn},void 0)}set_initial_person_info(){this.props[Qi]||this.props[eo]||this.register_once({[sn]:Du(this.Ne.mask_personal_data_properties,this.Ne.custom_personal_data_properties,this.Ne.disable_capture_url_hashes)},void 0)}get_initial_props(){var e={};Z([eo,Qi],(n=>{var i=this.props[n];i&&Z(i,(function(o,a){e["$initial_"+Ni(a)]=o}))}));var s=this.props[sn];if(s){var r=(function(n,i){i===void 0&&(i=!1);var o=Bu(n,i),a={};return Z(o,(function(l,u){a["$initial_"+Ni(u)]=l})),a})(s,this.Ne.disable_capture_url_hashes);ee(e,r)}return e}safe_merge(e){return Z(this.props,(function(s,r){r in e||(e[r]=s)})),e}update_config(e,s,r){this.ji=this.$i=e.cookie_expiration,this.set_disabled(e.disable_persistence||!!r),this.set_cross_subdomain(e.cross_subdomain_cookie),this.set_secure(e.secure_cookie);var n=e.persistence!==s.persistence||!((l,u)=>{if(l.length!==u.length)return!1;var c=[...l].sort(),d=[...u].sort();return c.every(((h,p)=>h===d[p]))})(e.cookie_persisted_properties||[],s.cookie_persisted_properties||[]),i=n?this.bi(e):this.ii,o=this.wi(e);if(n||o!==this.pi){var a=this.props;this.clear(),this.ii=i,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,s){var r=this.props[js]||{};r[e]=s,this.Pi(js,r),this.save()}remove_event_timer(e){var s=this.props[js]||{},r=s[e];return x(r)||(delete s[e],this.Pi(js,s),this.save()),r}get_property(e){return this.props[e]}set_property(e,s){this.Pi(e,s),this.save()}Pi(e,s){var r;this.props[e]=s,(r=Mt(e))!=null&&r.volatile||this.Bi(e)}Ri(e){delete this.props[e],this.Bi(e)}Bi(e){var s,r=(s=Mt(e))==null?void 0:s.storageGroup;r&&(this.Mi(r).dirty=!0)}Mi(e){return this.ci[e]||(this.ci[e]={})}}function Ir(t){var e=!0;return{dispose(){if(e){e=!1;var s=t();s&&Se(s.then)&&s.then(void 0,(()=>{}))}}}}var xe={GZipJS:"gzip-js",Base64:"base64"},As={Activation:"events",Cancellation:"cancelEvents"},di={Popover:"popover",API:"api",Widget:"widget"},ft={SHOWN:"survey shown",DISMISSED:"survey dismissed",SENT:"survey sent"},hi={SURVEY_ID:"$survey_id",SURVEY_ITERATION:"$survey_iteration",SURVEY_LAST_SEEN_DATE:"$survey_last_seen_date"},io={Popover:"popover",Inline:"inline"},Np={SHOWN:"product tour shown"},ml={TOUR_LAST_SEEN_DATE:"$product_tour_last_seen_date",TOUR_TYPE:"$product_tour_type"},vl=se("[RateLimiter]");class Mp{constructor(e){this.serverLimits={},this.lastEventRateLimited=!1,this.checkForLimiting=s=>{var r=s.text;if(r&&r.length)try{(JSON.parse(r).quota_limited||[]).forEach((n=>{vl.info((n||"events")+" is quota limited."),this.serverLimits[n]=new Date().getTime()+6e4}))}catch(n){return void vl.warn('could not rate limit - continuing. Error: "'+n?.message+'"',{text:r})}},this.instance=e,this.lastEventRateLimited=this.clientRateLimitContext(!0).isRateLimited}get captureEventsPerSecond(){var e;return((e=this.instance.config.rate_limiting)==null?void 0:e.events_per_second)||10}get captureEventsBurstLimit(){var e;return Math.max(((e=this.instance.config.rate_limiting)==null?void 0:e.events_burst_limit)||10*this.captureEventsPerSecond,this.captureEventsPerSecond)}clientRateLimitContext(e){var s,r,n;e===void 0&&(e=!1);var i=this.captureEventsBurstLimit,o=this.captureEventsPerSecond,a=new Date().getTime(),l=(s=(r=this.instance.persistence)==null?void 0:r.get_property(Xi))!==null&&s!==void 0?s:{tokens:i,last:a};l.tokens+=(a-l.last)/1e3*o,l.last=a,l.tokens>i&&(l.tokens=i);var u=1>l.tokens;if(u||e||(l.tokens=Math.max(0,l.tokens-1)),u&&!e){var c=(he(l.dropped)?l.dropped:0)+1;l.dropped=c,!this.lastEventRateLimited&&this.Hi(c)&&(l.dropped=0)}return this.lastEventRateLimited=u,(n=this.instance.persistence)==null||n.set_property(Xi,l),{isRateLimited:u,remainingTokens:l.tokens}}Ui(e){var s=this.instance.config.property_denylist;return!L(s)||!s.includes(e)}zi(){var e;if(this.Ui("$current_url")&&this.Ui("$pathname")&&re!=null&&re.pathname)return""+((e=re.origin)!==null&&e!==void 0?e:"")+re.pathname}Hi(e){var s,r,n=this.captureEventsBurstLimit,i=this.captureEventsPerSecond,o=this.zi(),a=this.Ui("$session_id")?(s=(r=this.instance).get_session_id)==null?void 0:s.call(r):void 0,l=[e+" event(s) dropped since the last warning",o?"triggered on "+o:void 0,a?"session "+a:void 0].filter(Boolean).join(", ");return!!this.instance.capture("$$client_ingestion_warning",{$$client_ingestion_warning_message:"posthog-js client rate limited: "+l+". Config is set to "+i+" events per second and "+n+" events burst limit."},{skip_client_rate_limiting:!0})}isServerRateLimited(e){var s=this.serverLimits[e||"events"]||!1;return s!==!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 xt.info("Using preloaded remote config",this.remoteConfig),this.Zi(this.remoteConfig),void this.Gi();if(this._instance.Qi())return void xt.warn("Remote config is disabled. Falling back to local config.");this.Wi((e=>{if(!e)return xt.info("No config found after loading remote JS config. Falling back to JSON."),void this.Vi((s=>{this.Zi(s.json,s),this.Gi()}));this.Zi(e),this.Gi()}))}catch(e){xt.error("Error loading remote config",e),this.Zi()}}stop(){this.Ki&&(clearInterval(this.Ki),this.Ki=void 0)}refresh(){!this._instance.Qi()&&C&&C.visibilityState!=="hidden"&&this._instance.reloadFeatureFlags()}Gi(){var e;if(!this.Ki){var s=(e=this._instance.config.remote_config_refresh_interval_ms)!==null&&e!==void 0?e:3e5;s!==0&&(this.Ki=setInterval((()=>{this.refresh()}),s))}}Zi(e,s){!e&&s&&(s.statusCode===0?s.error||xt.warn("Failed to fetch remote config from PostHog."):xt.error("Failed to fetch remote config from PostHog."));try{this._instance.Zi(e?{ok:!0,config:e}:{ok:!1})}catch(n){xt.error("Error applying remote config",n)}if(e?.hasFeatureFlags!==!1&&!this._instance.config.advanced_disable_feature_flags_on_first_load)try{var r;(r=this._instance.featureFlags)==null||r.ensureFlagsLoaded()}catch(n){xt.error("Error loading feature flags",n)}}}var qe=Uint8Array,Ae=Uint16Array,_s=Uint32Array,Yo=new qe([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),Zo=new qe([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),_l=new qe([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Hu=function(t,e){for(var s=new Ae(31),r=0;31>r;++r)s[r]=e+=1<r;++r)for(var i=s[r];s[r+1]>i;++i)n[i]=i-s[r]<<5|r;return[s,n]},Wu=Hu(Yo,2),oo=Wu[1];Wu[0][28]=258,oo[258]=28;for(var yl=Hu(Zo,0)[1],zu=new Ae(32768),ie=0;32768>ie;++ie){var ss=(43690&ie)>>>1|(21845&ie)<<1;zu[ie]=((65280&(ss=(61680&(ss=(52428&ss)>>>2|(13107&ss)<<2))>>>4|(3855&ss)<<4))>>>8|(255&ss)<<8)>>>1}var Js=function(t,e,s){for(var r=t.length,n=0,i=new Ae(e);r>n;++n)++i[t[n]-1];var o,a=new Ae(e);for(n=0;e>n;++n)a[n]=a[n-1]+i[n-1]<<1;for(o=new Ae(r),n=0;r>n;++n)o[n]=zu[a[t[n]-1]++]>>>15-t[n];return o},Kt=new qe(288);for(ie=0;144>ie;++ie)Kt[ie]=8;for(ie=144;256>ie;++ie)Kt[ie]=9;for(ie=256;280>ie;++ie)Kt[ie]=7;for(ie=280;288>ie;++ie)Kt[ie]=8;var hn=new qe(32);for(ie=0;32>ie;++ie)hn[ie]=5;var Lp=Js(Kt,9),Op=Js(hn,5),qu=function(t){return(t/8>>0)+(7&t&&1)},Vu=function(t,e,s){(s==null||s>t.length)&&(s=t.length);var r=new(t instanceof Ae?Ae:t instanceof _s?_s:qe)(s-e);return r.set(t.subarray(e,s)),r},ot=function(t,e,s){var r=e/8>>0;t[r]|=s<<=7&e,t[r+1]|=s>>>8},$s=function(t,e,s){var r=e/8>>0;t[r]|=s<<=7&e,t[r+1]|=s>>>8,t[r+2]|=s>>>16},pi=function(t,e){for(var s=[],r=0;t.length>r;++r)t[r]&&s.push({s:r,f:t[r]});var n=s.length,i=s.slice();if(!n)return[new qe(0),0];if(n==1){var o=new qe(s[0].s+1);return o[s[0].s]=1,[o,1]}s.sort((function(F,P){return F.f-P.f})),s.push({s:-1,f:25001});var a=s[0],l=s[1],u=0,c=1,d=2;for(s[0]={s:-1,f:a.f+l.f,l:a,r:l};c!=n-1;)a=s[s[d].f>s[u].f?u++:d++],l=s[u!=c&&s[d].f>s[u].f?u++:d++],s[c++]={s:-1,f:a.f+l.f,l:a,r:l};var h=i[0].s;for(r=1;n>r;++r)i[r].s>h&&(h=i[r].s);var p=new Ae(h+1),f=ao(s[c-1],p,0);if(f>e){r=0;var g=0,m=f-e,_=1<r;++r){var w=i[r].s;if(e>=p[w])break;g+=_-(1<>>=m;g>0;){var E=i[r].s;e>p[E]?g-=1<=0&&g;--r){var I=i[r].s;p[I]==e&&(--p[I],++g)}f=e}return[new qe(p),f]},ao=function(t,e,s){return t.s==-1?Math.max(ao(t.l,e,s+1),ao(t.r,e,s+1)):e[t.s]=s},wl=function(t){for(var e=t.length;e&&!t[--e];);for(var s=new Ae(++e),r=0,n=t[0],i=1,o=function(l){s[r++]=l},a=1;e>=a;++a)if(t[a]==n&&a!=e)++i;else{if(!n&&i>2){for(;i>138;i-=138)o(32754);i>2&&(o(i>10?i-11<<5|28690:i-3<<5|12305),i=0)}else if(i>3){for(o(n),--i;i>6;i-=6)o(8304);i>2&&(o(i-3<<5|8208),i=0)}for(;i--;)o(n);i=1,n=t[a]}return[s.subarray(0,r),e]},Rs=function(t,e){for(var s=0,r=0;e.length>r;++r)s+=t[r]*e[r];return s},lo=function(t,e,s){var r=s.length,n=qu(e+2);t[n]=255&r,t[n+1]=r>>>8,t[n+2]=255^t[n],t[n+3]=255^t[n+1];for(var i=0;r>i;++i)t[n+i+4]=s[i];return 8*(n+4+r)},bl=function(t,e,s,r,n,i,o,a,l,u,c){ot(e,c++,s),++n[256];for(var d=pi(n,15),h=d[0],p=d[1],f=pi(i,15),g=f[0],m=f[1],_=wl(h),w=_[0],E=_[1],I=wl(g),F=I[0],P=I[1],B=new Ae(19),S=0;w.length>S;++S)B[31&w[S]]++;for(S=0;F.length>S;++S)B[31&F[S]]++;for(var A=pi(B,7),R=A[0],N=A[1],T=19;T>4&&!R[_l[T-1]];--T);var O,J,z,H,oe=u+5<<3,pe=Rs(n,Kt)+Rs(i,hn)+o,Ie=Rs(n,h)+Rs(i,g)+o+14+3*T+Rs(B,R)+(2*B[16]+3*B[17]+7*B[18]);if(pe>=oe&&Ie>=oe)return lo(e,c,t.subarray(l,l+u));if(ot(e,c,1+(pe>Ie)),c+=2,pe>Ie){O=Js(h,p),J=h,z=Js(g,m),H=g;var _e=Js(R,N);for(ot(e,c,E-257),ot(e,c+5,P-1),ot(e,c+10,T-4),c+=14,S=0;T>S;++S)ot(e,c+3*S,R[_l[S]]);c+=3*T;for(var Ce=[w,F],Re=0;2>Re;++Re){var ae=Ce[Re];for(S=0;ae.length>S;++S)ot(e,c,_e[me=31&ae[S]]),c+=R[me],me>15&&(ot(e,c,ae[S]>>>5&127),c+=ae[S]>>>12)}}else O=Lp,J=Kt,z=Op,H=hn;for(S=0;a>S;++S)if(r[S]>255){var me;$s(e,c,O[257+(me=r[S]>>>18&31)]),c+=J[me+257],me>7&&(ot(e,c,r[S]>>>23&31),c+=Yo[me]);var ge=31&r[S];$s(e,c,z[ge]),c+=H[ge],ge>3&&($s(e,c,r[S]>>>5&8191),c+=Zo[ge])}else $s(e,c,O[r[S]]),c+=J[r[S]];return $s(e,c,O[256]),c+J[256]},Dp=new _s([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),Bp=(function(){for(var t=new _s(256),e=0;256>e;++e){for(var s=e,r=9;--r;)s=(1&s&&3988292384)^s>>>1;t[e]=s}return t})(),fi=function(t,e,s){for(;s;++e)t[e]=s,s>>>=8};function jp(t,e){e===void 0&&(e={});var s=(function(){var d=4294967295;return{p(h){for(var p=d,f=0;h.length>f;++f)p=Bp[255&p^h[f]]^p>>>8;d=p},d(){return 4294967295^d}}})(),r=t.length;s.p(t);var n,i,o,a,l,u=(a=10+((n=e).filename&&n.filename.length+1||0),l=8,(function(d,h,p,f,g,m){var _=d.length,w=new qe(f+_+5*(1+Math.floor(_/7e3))+g),E=w.subarray(f,w.length-g),I=0;if(!h||8>_)for(var F=0;_>=F;F+=65535){var P=F+65535;_>P?I=lo(E,I,d.subarray(F,P)):(E[F]=!0,I=lo(E,I,d.subarray(F,_)))}else{for(var B=Dp[h-1],S=B>>>13,A=8191&B,R=(1<F;++F){var me=z(F),ge=32767&F,Ye=T[me];if(N[ge]=Ye,T[me]=ge,F>=Re){var Rt=_-F;if((Ie>7e3||Ce>24576)&&Rt>423){I=bl(d,E,0,H,oe,pe,_e,Ce,ae,F-ae,I),Ce=Ie=_e=0,ae=F;for(var de=0;286>de;++de)oe[de]=0;for(de=0;30>de;++de)pe[de]=0}var Ve=2,St=0,ks=A,Be=ge-Ye&32767;if(Rt>2&&me==z(F-Be))for(var Fe=Math.min(S,Rt)-1,mr=Math.min(32767,F),vr=Math.min(258,Rt);mr>=Be&&--ks&&ge!=Ye;){if(d[F+Ve]==d[F+Ve-Be]){for(var je=0;vr>je&&d[F+je]==d[F+je-Be];++je);if(je>Ve){if(Ve=je,St=Be,je>Fe)break;var _r=Math.min(Be,je-2),Xt=0;for(de=0;_r>de;++de){var Qt=F-Be+de+32768&32767,Is=Qt-N[Qt]+32768&32767;Is>Xt&&(Xt=Is,Ye=Qt)}}}Be+=(ge=Ye)-(Ye=N[ge])+32768&32767}if(St){H[Ce++]=268435456|oo[Ve]<<18|yl[St];var Ta=31&oo[Ve],Na=31&yl[St];_e+=Yo[Ta]+Zo[Na],++oe[257+Ta],++pe[Na],Re=F+Ve,++Ie}else H[Ce++]=d[F],++oe[d[F]]}}I=bl(d,E,!0,H,oe,pe,_e,Ce,ae,F-ae,I)}return Vu(w,0,f+qu(I)+g)})(i=t,(o=e).level==null?6:o.level,o.mem==null?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(i.length)))):12+o.mem,a,l)),c=u.length;return(function(d,h){var p=h.filename;if(d[0]=31,d[1]=139,d[2]=8,d[8]=2>h.level?4:h.level==9?2:0,d[9]=3,h.mtime!=0&&fi(d,4,Math.floor(new Date(h.mtime||Date.now())/1e3)),p){d[3]=8;for(var f=0;p.length>=f;++f)d[f+10]=p.charCodeAt(f)}})(u,e),fi(u,c-8,s.d()),fi(u,c-4,r),u}var Up=!!$i||!!Mo,Gu="text/plain",Dr=!1,Ku=(t,e)=>{var s=t.split("#"),r=s[1],n=s[0].split("?"),i=n[0],o=n[1];if(!o)return t;var a=o.split("&").filter((l=>l.split("=")[0]!==e)).join("&");return i+(a?"?"+a:"")+(r?"#"+r:"")},$n=function(t,e,s){var r;s===void 0&&(s=!0);var n=t.split("?"),i=n[0],o=n[1],a=b({},e),l=(r=o?.split("&").map((c=>{var d,h=c.split("="),p=h[0],f=s&&(d=a[p])!==null&&d!==void 0?d:h[1];return delete a[p],p+"="+f})))!==null&&r!==void 0?r:[],u=(function(c,d){var h,p;d===void 0&&(d="&");var f=[];return Z(c,(function(g,m){x(g)||x(m)||m==="undefined"||(h=encodeURIComponent((_=>_ instanceof File)(g)?g.name:g.toString()),p=encodeURIComponent(m),f[f.length]=p+"="+h)})),f.join(d)})(a);return u&&l.push(u),l.length>0?i+"?"+l.join("&"):i},gi=t=>{if(t.Ji)return t.Ji;var e=t.data,s=t.compression;if(e){if(s===xe.GZipJS){var r=jp((function(a,l){var u=a.length;if(typeof TextEncoder<"u")return new TextEncoder().encode(a);for(var c=new qe(a.length+(a.length>>>1)),d=0,h=function(m){c[d++]=m},p=0;u>p;++p){if(d+5>c.length){var f=new qe(d+8+(u-p<<1));f.set(c),c=f}var g=a.charCodeAt(p);128>g?h(g):2048>g?(h(192|g>>>6),h(128|63&g)):g>55295&&57344>g?(h(240|(g=65536+(1047552&g)|1023&a.charCodeAt(++p))>>>18),h(128|g>>>12&63),h(128|g>>>6&63),h(128|63&g)):(h(224|g>>>12),h(128|g>>>6&63),h(128|63&g))}return Vu(c,0,d)})(cs(e)),{mtime:0});return{contentType:Gu,body:r.buffer.slice(r.byteOffset,r.byteOffset+r.byteLength),estimatedSize:r.byteLength}}if(s===xe.Base64){var n=(function(a){return a&&btoa(encodeURIComponent(a).replace(/%([0-9A-F]{2})/g,((l,u)=>String.fromCharCode(parseInt(u,16)))))})(cs(e)),i=(a=>"data="+encodeURIComponent(typeof a=="string"?a:cs(a)))(n);return{contentType:"application/x-www-form-urlencoded",body:i,estimatedSize:new Blob([i]).size}}var o=cs(e);return{contentType:"application/json",body:o,estimatedSize:new Blob([o]).size}}},Ju=t=>{var e,s,r=()=>t.transport==="sendBeacon"?{url:$n(t.url,{compression:xe.Base64}),encodedBody:gi(b({},t,{compression:xe.Base64,Ji:void 0}))}:{url:Ku(t.url,"compression"),encodedBody:gi(b({},t,{compression:void 0,Ji:void 0}))};try{e=gi(t)}catch(n){if(Ua(t.compression,ms(t.url,"compression")))return k.error("Failed to gzip request body, sending uncompressed payload",n),r();throw n}return e&&Ua(t.compression,ms(t.url,"compression"))&&!((s=e.body)instanceof ArrayBuffer?Ri(new Uint8Array(s)):ArrayBuffer.isView(s)&&Ri(new Uint8Array(s.buffer,s.byteOffset,s.byteLength)))?(Dr=!0,r()):{url:t.url,encodedBody:e}},Yu=t=>{try{return Ju(t)}catch(e){return k.error(e),void(t.callback==null||t.callback({statusCode:0,error:e}))}},Hp=(function(){var t=X((function*(e){var s=cs(e.data),r=yield(function(i,o,a){return Ti.apply(this,arguments)})(s,Y.DEBUG,{rethrow:!0});if(!r)return e;var n=yield r.arrayBuffer();return b({},e,{Ji:{contentType:Gu,body:n,estimatedSize:n.byteLength}})}));return function(e){return t.apply(this,arguments)}})(),Wp=/Failed to fetch|NetworkError|Load failed/i,Zu=t=>t?.name==="TypeError"&&Wp.test(t?.message||""),Xu=t=>{var e=Yu(t);if(e){var s=e.url,r=e.encodedBody,n=r??{},i=n.contentType,o=n.body,a=n.estimatedSize,l=new Headers;Z(t.headers,(function(f,g){l.append(g,f)})),i&&l.append("Content-Type",i);var u=null,c=!1;if(Ma){var d=new Ma;u={signal:d.signal,timeout:setTimeout((()=>{var f,g;c=!0,d.abort((f=t.timeout,(g=new Error("PostHog request timed out"+(f?" after "+f+"ms":""))).name="AbortError",g))}),t.timeout)}}var h=f=>{c&&f?.name==="AbortError"||Zu(f)?k.warn(f):k.error(f),t.callback==null||t.callback({statusCode:0,error:f})};try{var p;Mo(s,b({method:t?.method||"GET",headers:l,keepalive:t.method==="POST"&&!t.Yi&&52428.8>(a||0),body:o,signal:(p=u)==null?void 0:p.signal},t.fetchOptions)).then((f=>f.text().then((g=>{var m={statusCode:f.status,text:g};if(f.status===200)try{m.json=JSON.parse(g)}catch(_){k.error(_)}t.callback==null||t.callback(m)})))).catch(h).finally((()=>u?clearTimeout(u.timeout):null))}catch(f){u&&clearTimeout(u.timeout),h(f)}}},co=t=>{try{var e,s=Ju(t),r=s.url,n=s.encodedBody,i=n??{},o=i.body,a=i.estimatedSize;if(!o)return;var l=o instanceof Blob?o:new Blob([o],{type:i.contentType});if(ke.sendBeacon(r,l))return;var u=L(t.data)?t.data:(e=t.data)==null?void 0:e.batch;if(L(u)&&u.length>1&&(a??0)>16384){var c=Math.ceil(u.length/2),d=h=>L(t.data)?h:b({},t.data,{batch:h});return co(b({},t,{data:d(u.slice(0,c))})),void co(b({},t,{data:d(u.slice(c))}))}k.warn("Beacon of ~"+(a??0)+" bytes was rejected by the browser, falling back to fetch"),Xu(b({},t,{Yi:!0}))}catch(h){k.warn("Beacon send failed",h)}},El=(t,e,s,r)=>{var n=r==="query"?e==="POST"?"sent_at":"_":void 0;return $n(s===xe.GZipJS?Ku(t,"compression"):t,b({},n?{[n]:Date.now().toString()}:{},s===xe.GZipJS?{}:{compression:s}))},Br=[];Mo&&Br.push({transport:"fetch",method:Xu}),$i&&Br.push({transport:"XHR",method(t){var e=Yu(t);if(e){var s=new $i,r=e.encodedBody;s.open(t.method||"GET",e.url,!0);var n=r??{},i=n.contentType,o=n.body;Z(t.headers,(function(a,l){s.setRequestHeader(l,a)})),i&&s.setRequestHeader("Content-Type",i),t.timeout&&(s.timeout=t.timeout),s.onreadystatechange=()=>{if(s.readyState===4){var a={statusCode:s.status,text:s.responseText};if(s.status===200)try{a.json=JSON.parse(s.responseText)}catch{}t.callback==null||t.callback(a)}},s.send(o)}}}),ke!=null&&ke.sendBeacon&&Br.push({transport:"sendBeacon",method:co});var uo=3e3;class zp{constructor(e,s){this.Xi=!0,this.tr=[],this.er=rt(s?.flush_interval_ms||uo,250,5e3,k.createLogger("flush interval"),uo),this.ir=e}enqueue(e){this.tr.push(e),this.rr||this.nr()}unload(){this.sr();var e=this.tr.length>0?this.ar():{},s=Object.values(e);[...s.filter((r=>r.url.indexOf("/e")===0)),...s.filter((r=>r.url.indexOf("/e")!==0))].map((r=>{this.lr(b({},r,{transport:"sendBeacon"}))}))}enable(){this.Xi=!1,this.nr()}nr(){var e=this;this.Xi||(this.rr=setTimeout((()=>{if(this.sr(),this.tr.length>0){var s=this.ar(),r=function(){var i=s[n],o=new Date().getTime();i.data&&L(i.data)&&Z(i.data,(a=>{a.offset=Math.abs(a.timestamp-o),delete a.timestamp})),e.lr(i)};for(var n in s)r()}}),this.er))}lr(e){try{this.ir(e)}catch(s){k.error(s)}}sr(){clearTimeout(this.rr),this.rr=void 0}ar(){var e={};return Z(this.tr,(s=>{var r,n=s,i=(n?n.batchKey:null)||n.url;x(e[i])&&(e[i]=b({},n,{data:[]})),(r=e[i].data)==null||r.push(n.data)})),this.tr=[],e}}var qp=["retriesPerformedSoFar"];class Vp{constructor(e){this.ur=!1,this.hr=3e3,this.tr=[],this._instance=e,this.tr=[],this.dr=!0,!x(v)&&"onLine"in v.navigator&&(this.dr=v.navigator.onLine,this.vr=()=>{this.dr=!0,this.cr()},this.pr=()=>{this.dr=!1},ne(v,"online",this.vr),ne(v,"offline",this.pr))}get length(){return this.tr.length}retriableRequest(e){var s=e.retriesPerformedSoFar,r=Ic(e,qp);lt(s)&&(r.url=$n(r.url,{retry_count:s})),this._instance._send_request(b({},r,{callback:n=>{if(n.statusCode!==200&&(400>n.statusCode||n.statusCode>=500)){if((n.statusCode===0?3:10)>(s??0))return void this.At(b({retriesPerformedSoFar:s},r));n.statusCode===0&&k.warn("Request failed before receiving an HTTP response; this can happen due to network issues, CORS, browser blocking, or ad blockers. Stopped retrying after "+(s??0)+" retries.")}r.callback==null||r.callback(n)}}))}At(e){var s=e.retriesPerformedSoFar||0;e.retriesPerformedSoFar=s+1;var r=(function(o){var a=3e3*Math.pow(2,o),l=a/2,u=Math.min(18e5,a),c=Math.random()-.5;return Math.ceil(u+c*(u-l))})(s),n=Date.now()+r;this.tr.push({retryAt:n,requestOptions:e});var i="Enqueued failed request for retry in "+r;navigator.onLine||(i+=" (Browser is offline)"),k.warn(i),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(),s=[],r=this.tr.filter((i=>e>i.retryAt||(s.push(i),!1)));if(this.tr=s,r.length>0)for(var n of r)this.retriableRequest(n.requestOptions)}unload(){for(var e of(this.mr&&(clearTimeout(this.mr),this.mr=void 0),this.ur=!1,x(v)||(this.vr&&(v.removeEventListener("online",this.vr),this.vr=void 0),this.pr&&(v.removeEventListener("offline",this.pr),this.pr=void 0)),this.tr)){var s=e.requestOptions;try{this._instance._send_request(b({},s,{transport:"sendBeacon"}))}catch(r){k.error(r)}}this.tr=[]}}class Gp{constructor(e){this.yr=()=>{var s,r,n,i;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,(s=this.br.maxScrollY)!==null&&s!==void 0?s:0),this.br.maxScrollHeight=Math.max(l,(r=this.br.maxScrollHeight)!==null&&r!==void 0?r:0),this.br.lastContentY=u,this.br.maxContentY=Math.max(u,(n=this.br.maxContentY)!==null&&n!==void 0?n:0),this.br.maxContentHeight=Math.max(c,(i=this.br.maxContentHeight)!==null&&i!==void 0?i: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(){ne(v,"scroll",this.yr,{capture:!0}),ne(v,"scrollend",this.yr,{capture:!0}),ne(v,"resize",this.yr)}scrollElement(){if(!this._r)return v?.document.documentElement;var e=L(this._r)?this._r:[this._r];for(var s of e){var r=v?.document.querySelector(s);if(r)return r}}wr(e){var s=e==="y"?"scrollTop":"scrollLeft";if(this._r){var r=this.scrollElement();return r&&r[s]||0}return v?e==="y"?v.scrollY||v.pageYOffset||v.document.documentElement.scrollTop||0:v.scrollX||v.pageXOffset||v.document.documentElement.scrollLeft||0:0}scrollY(){return this.wr("y")}scrollX(){return this.wr("x")}}var Kp=t=>Du(t?.config.mask_personal_data_properties,t?.config.custom_personal_data_properties,t?.config.disable_capture_url_hashes);class Sl{constructor(e,s,r,n){this.kr=i=>{var o=this.Sr();if(!o||o.sessionId!==i){var a={sessionId:i,props:this.Cr(this._instance)};this.Mr.register({[Zi]:a})}},this._instance=e,this.Tr=s,this.Mr=r,this.Cr=n||Kp,this.Tr.onSessionId(this.kr)}Sr(){return this.Mr.props[Zi]}getSetOnceProps(){var e,s=(e=this.Sr())==null?void 0:e.props;return s?"r"in s?Bu(s,this._instance.config.disable_capture_url_hashes):{$referring_domain:s.referringDomain,$pathname:s.initialPathName,utm_source:s.utm_source,utm_campaign:s.utm_campaign,utm_medium:s.utm_medium,utm_content:s.utm_content,utm_term:s.utm_term}:{}}getSessionProps(){var e={};return Z(Vo(this.getSetOnceProps()),((s,r)=>{r==="$current_url"&&(r="url"),e["$session_entry_"+Ni(r)]=s})),e}}class Xo{on(e,s){return this.Er[e]||(this.Er[e]=[]),this.Er[e].push(s),()=>{this.Er[e]=this.Er[e].filter((r=>r!==s))}}emit(e,s){for(var r of this.Er[e]||[])r(s);for(var n of this.Er["*"]||[])n(e,s)}constructor(){this.Er={}}}var Ts=se("[SessionId]");class xl{on(e,s){return this.Ir.on(e,s)}constructor(e,s,r){var n;if(this.Pr=null,this.Rr=[],this.Ar=void 0,this.Fr=!1,this.Ir=new Xo,this.Lr=(u,c)=>!(!lt(u)||!lt(c))&&Math.abs(u-c)>this.sessionTimeoutMs,!e.persistence)throw new Error("SessionIdManager requires a PostHogPersistence instance");if(e.config.cookieless_mode===ht)throw new Error('SessionIdManager cannot be used with cookieless_mode="always"');this.Ne=e.config,this.Mr=e.persistence,this.Or=void 0,this.Dr=void 0,this._sessionStartTimestamp=null,this._sessionActivityTimestamp=null,this.$r=s||dt,this.Nr=r||dt;var i=this.Ne.persistence_name||this.Ne.token;if(this._sessionTimeoutMs=1e3*rt(this.Ne.session_idle_timeout_seconds||1800,60,36e3,Ts.createLogger("session_idle_timeout_seconds"),1800),e.register({$configured_session_timeout_ms:this._sessionTimeoutMs}),this.qr(),this.jr="ph_"+i+"_window_id",this.Br="ph_"+i+"_primary_window_exists",this.Hr()){var o=ce.H(this.jr),a=ce.H(this.Br);o&&!a?this.Or=o:ce.q(this.jr),ce.F(this.Br,!0)}if((n=this.Ne.bootstrap)!=null&&n.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){Ts.error("Invalid sessionID in bootstrap",u)}this.zr()}get sessionTimeoutMs(){return this._sessionTimeoutMs}onSessionId(e){return x(this.Rr)&&(this.Rr=[]),this.Rr.push(e),this.Dr&&e(this.Dr,this.Or),()=>{this.Rr=this.Rr.filter((s=>s!==e))}}Hr(){return this.Ne.persistence!=="memory"&&!this.Mr.xi&&ce.N()}Wr(e){e!==this.Or&&(this.Or=e,this.Hr()&&ce.F(this.jr,e))}Vr(){return this.Or?this.Or:this.Hr()?ce.H(this.jr):null}Zr(e){var s=this.Pr;return!$e(s)&&!$e(e)&&5e3>Math.abs(e-s)}Ur(e,s,r){var n=s!==this._sessionActivityTimestamp,i=!(e!==this.Dr||r!==this._sessionStartTimestamp);this._sessionStartTimestamp=r,this._sessionActivityTimestamp=s,this.Dr=e,i&&!n||i&&this.Zr(s)||(this.Pr=s,this.Mr.register({[ls]:[s,e,r]}))}Gr(){var e,s=(e=this.Ne)==null?void 0:e.persistence_save_debounce_ms;return lt(s)&&s>0}Qr(){this.Gr()?this.Mr.refreshKey(ls):(this.Mr.flush(),this.Mr.load())}Kr(){var e;if(!$e(this._sessionActivityTimestamp)&&this._sessionActivityTimestamp!==this.Pr){this.Qr();var s=this.Jr();s[1]===this.Dr&&s[2]===this._sessionStartTimestamp&&(this.Pr=this._sessionActivityTimestamp,this.Mr.register({[ls]:[this._sessionActivityTimestamp,(e=this.Dr)!==null&&e!==void 0?e:null,this._sessionStartTimestamp]}),this.Mr.flush())}}Yr(){var e=this.Jr()[0],s=lt(e)?e:0,r=lt(this._sessionActivityTimestamp)?this._sessionActivityTimestamp:0;return Math.max(s,r)}Xr(e){return this.Qr(),this.Lr(e,this.Yr())}Jr(){var e=this.Mr.props[ls];return L(e)&&e.length===2&&e.push(e[0]),e||[0,null,0]}resetSessionId(){this.Pr=null,clearTimeout(this.tn),this.tn=void 0,this.Ur(null,null,null)}destroy(){this.Fr=!0,this.Kr(),clearTimeout(this.tn),this.tn=void 0,this.Ar&&v&&(v.removeEventListener(on,this.Ar,{capture:!1}),this.Ar=void 0),this.Rr=[]}zr(){this.Ar=()=>{this.Kr(),this.Hr()&&ce.q(this.Br)},ne(v,on,this.Ar,{capture:!1})}checkAndGetSessionAndWindowId(e,s){if(e===void 0&&(e=!1),s===void 0&&(s=null),this.Ne.cookieless_mode===ht)throw new Error('checkAndGetSessionAndWindowId should not be called with cookieless_mode="always"');var r=s||new Date().getTime(),n=this.Jr(),i=n[1],o=n[2],a=this.Yr(),l=this.Vr(),u=lt(o)&&Math.abs(r-o)>864e5,c=!1,d=!1,h=!i,p=i,f=!h&&!e&&this.Lr(r,a);if(f){(f=this.Xr(r))||Ts.info("cross-tab refresh kept the session alive",{sessionId:i});var g=this.Jr();i=g[1],o=g[2]}h||f||u?(i=this.$r(),l=this.Nr(),Ts.info("new session ID generated",{sessionId:i,windowId:l,changeReason:{noSessionId:h,activityTimeout:f,sessionPastMaximumLength:u}}),o=r,c=!0):(l||(l=this.Nr(),c=!0),(d=i!==p)&&(Ts.info("adopted cross-tab session id",{sessionId:i,windowId:l}),c=!0));var m=lt(a)&&e&&!u?a:r,_=lt(o)?o:new Date().getTime();this.Wr(l),this.Ur(i,m,_),e||this.qr();var w={noSessionId:h,activityTimeout:f,sessionPastMaximumLength:u,crossTabAdoption:d};return c&&this.Rr.forEach((E=>E(i,l,w))),{sessionId:i,windowId:l,sessionStartTimestamp:_,changeReason:c?w:void 0,lastActivityTimestamp:a}}qr(){this.Fr||(clearTimeout(this.tn),this.tn=setTimeout((()=>{if(!this.Fr)if(this.Xr(new Date().getTime())){var e=this.Dr;this.resetSessionId(),this.Ir.emit("forcedIdleReset",{idleSessionId:e})}else this.qr()}),1.1*this.sessionTimeoutMs))}}var Qu=function(t,e){if(!t)return!1;var s=t.userAgent;if(s&&Wa(s,e))return!0;try{var r=t?.userAgentData;if(r!=null&&r.brands&&r.brands.some((n=>Wa(n?.brand,e))))return!0}catch{}return!!t.webdriver};function ed(){return(ed=X((function*(){var t=ke?.userAgentData;if(t!=null&&t.getHighEntropyValues)try{var e=yield t.getHighEntropyValues(["model"]),s=e?.model;return W(s)&&s.length>0?s:void 0}catch(r){return void k.info("Unable to resolve $device_model from userAgentData.getHighEntropyValues",r)}}))).apply(this,arguments)}var pn=function(t,e){if(!(function(s){try{new RegExp(s)}catch{return!1}return!0})(e))return!1;try{return new RegExp(e).test(t)}catch{return!1}};function mi(t,e,s){return cs({distinct_id:t,userPropertiesToSet:e,userPropertiesToSetOnce:s})}var td={exact:(t,e)=>e.some((s=>t.some((r=>s===r)))),is_not:(t,e)=>e.every((s=>t.every((r=>s!==r)))),regex:(t,e)=>e.some((s=>t.some((r=>pn(s,r))))),not_regex:(t,e)=>e.every((s=>t.every((r=>!pn(s,r))))),icontains:(t,e)=>e.map(Cr).some((s=>t.map(Cr).some((r=>s.includes(r))))),not_icontains:(t,e)=>e.map(Cr).every((s=>t.map(Cr).every((r=>!s.includes(r))))),gt:(t,e)=>e.some((s=>{var r=parseFloat(s);return!isNaN(r)&&t.some((n=>r>parseFloat(n)))})),lt:(t,e)=>e.some((s=>{var r=parseFloat(s);return!isNaN(r)&&t.some((n=>rt.toLowerCase();function sd(t,e){return!t||Object.entries(t).every((s=>{var r=s[1],n=e?.[s[0]];if(x(n)||$e(n))return!1;var i=[String(n)],o=td[r.operator];return!!o&&o(r.values,i)}))}var ho="custom",kl="i.posthog.com",Jp=/^\/static\//;class Yp{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,s=(e=this.instance.config.ui_host)==null?void 0:e.replace(/\/$/,"");return s||(s=this.apiHost.replace("."+kl,".posthog.com")),s==="https://app.posthog.com"?"https://us.posthog.com":s}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":ho),this.en[this.apiHost]}rn(e){if(Jp.test(e)){var s=this.instance.config.asset_host;if(typeof s=="string")return s.trim().replace(/\/$/,"")||void 0}}endpointFor(e,s){if(s===void 0&&(s=""),s&&(s=s[0]==="/"?s:"/"+s),e==="ui")return this.uiHost+s;if(e==="flags")return this.flagsApiHost+s;if(e==="assets"){var r=this.rn(s);if(r)return""+r+s}if(this.region===ho)return this.apiHost+s;var n=kl+s;switch(e){case"assets":return"https://"+this.region+"-assets."+n;case"api":return"https://"+this.region+"."+n}}}function rd(t){var e;return!((e=t.conditions)==null||(e=e.events)==null||(e=e.values)==null||!e.length)}var q=se("[Surveys]"),nd="seenSurvey_",id=t=>{try{var e=(s=>((r,n)=>""+nd+(function(i){return i.current_iteration&&i.current_iteration>0?i.id+"_"+i.current_iteration:i.id})(n))(0,s))(t);if(localStorage.getItem(e))return;localStorage.setItem(e,"true")}catch(s){q.error("Failed to persist survey seen state",s)}},Zp=[di.Popover,di.Widget,di.API],Xp={ignoreConditions:!1,ignoreDelay:!1,displayType:io.Popover},Qp=se("[PostHog ExternalIntegrations]"),ef={intercom:"intercom-integration",crispChat:"crisp-chat-integration"};class tf{constructor(e){this._instance=e}ai(e,s){var r;(r=$.__PosthogExtensions__)==null||r.loadExternalDependency==null||r.loadExternalDependency(this._instance,e,(n=>{if(n)return Qp.error("failed to load script",n);s()}))}startIfEnabledOrStop(){var e=this,s=function(){var i,o,a,l=r[0],u=r[1];!u||(i=$.__PosthogExtensions__)!=null&&(i=i.integrations)!=null&&i[l]||e.ai(ef[l],(()=>{var c;(c=$.__PosthogExtensions__)==null||(c=c.integrations)==null||(c=c[l])==null||c.start(e._instance)})),!u&&(o=$.__PosthogExtensions__)!=null&&(o=o.integrations)!=null&&o[l]&&((a=$.__PosthogExtensions__)==null||(a=a.integrations)==null||(a=a[l])==null||a.stop())};for(var r of Object.entries((n=this._instance.config.integrations)!==null&&n!==void 0?n:{})){var n;s()}}}class sf{constructor(e,s){this.rt=e,this.nn=s,this.sn=new Map,this.an=!1}add(e){var s=this;return X((function*(){if(s.an)throw new Error("Cannot add an extension to a disposed ExtensionRuntime");if(s.sn.has(e.name))throw new Error('Browser extension "'+e.name+'" is already registered');s.sn.set(e.name,e);try{var r=e.setup(s.nn);r&&(yield r)}catch(i){var n=s.sn.get(e.name)===e;n&&s.sn.delete(e.name),s.rt.error('Failed to set up browser extension "'+e.name+'"',i),n&&s.ln(e)}}))()}dispose(){if(!this.an){this.an=!0;var e=Array.from(this.sn.values()).reverse();for(var s of(this.sn.clear(),e))this.ln(s)}}ln(e){try{var s=e.dispose==null?void 0:e.dispose();s&&Se(s.then)&&s.then(void 0,(r=>{this.rt.error('Failed to dispose browser extension "'+e.name+'"',r)}))}catch(r){this.rt.error('Failed to dispose browser extension "'+e.name+'"',r)}}}class rf{constructor(e){this._instance=e}initialize(){}get(e){var s=this._instance.persistence;if(typeof e=="string")return s?.get_property(e);var r={};for(var n of e){var i=s?.get_property(n);x(i)||(r[n]=i)}return r}set(e,s){var r;(r=this._instance.persistence)==null||r.register(typeof e=="string"?{[e]:s}:e)}remove(e){var s;(s=this._instance.persistence)==null||s.unregister(e)}}var Il="extensionsRemoteConfig";class nf{constructor(e){this.an=!1,this.instance=e,this.rt=k,this.un=e.hn,this.kv=new rf(e),this.onEvent=s=>Ir(this.instance.on("eventCaptured",(r=>{try{s({event:r.event,properties:r.properties})}catch(n){this.rt.error("Browser extension event listener failed",n)}}))),this.onRemoteConfig=s=>{if(this.an)return Ir((()=>{}));var r=i=>{try{s(i)}catch(o){this.rt.error("Browser extension remote config listener failed",o)}},n=this.instance.dn.on(Il,r);return this.un&&r(this.un),Ir(n)},this.vn=new sf(k.createLogger("[BrowserExtensions]"),this)}get logger(){return this.rt}get distinctId(){return this.instance.get_distinct_id()}get anonymousId(){var e;return(e=this.instance.get_property(sr))!==null&&e!==void 0?e:this.distinctId}get deviceId(){var e=this.instance.get_property(sr);return typeof e=="string"?e:void 0}get library(){return{name:Y.LIB_NAME,version:Y.LIB_VERSION}}get initialPersonProperties(){var e,s;return(e=(s=this.instance.persistence)==null?void 0:s.get_initial_props())!==null&&e!==void 0?e:{}}get groups(){return this.instance.getGroups()}get session(){try{var e,s,r,n,i=(e=this.instance.sessionManager)==null?void 0:e.checkAndGetSessionAndWindowId(!0);return{sessionId:(s=i?.sessionId)!==null&&s!==void 0?s:"",windowId:(r=i?.windowId)!==null&&r!==void 0?r:"",sessionStartTimestamp:(n=i?.sessionStartTimestamp)!==null&&n!==void 0?n:0}}catch{return{sessionId:"",windowId:"",sessionStartTimestamp:0}}}get projectToken(){return this.instance.config.token}add(e){return this.vn.add(e)}capture(e,s,r){var n=this;return X((function*(){r?n.instance.capture(e,s,{timestamp:r.timestamp,uuid:r.uuid,$set:r.set,$set_once:r.setOnce}):n.instance.capture(e,s)}))()}registerDynamicEventProperties(e){return Ir(this.instance.cn(e))}handleRemoteConfig(e){this.an||(this.un=e,this.instance.dn.emit(Il,e))}sendRequest(e,s){var r=this;return X((function*(){var n;s===void 0&&(s={});var i=r.instance.requestRouter.endpointFor((n=s.target)!==null&&n!==void 0?n:"api",e),o={method:s.method,url:s.query?$n(i,s.query):i,data:s.body,headers:s.headers,timeout:s.timeoutMs,fireCallbackOnDrop:!0,transport:s.transport,compression:s.compression,timestampMode:s.sentAt};return s.transport==="sendBeacon"?(r.instance._send_request(o),{statusCode:202}):new Promise((a=>{o.callback=a,r.instance._send_request(o)}))}))()}dispose(){this.an||(this.an=!0,this.vn.dispose())}}var Ys={},vi=0,fn=()=>{},Cl='Consent opt in/out is not valid with cookieless_mode="always" and will be ignored',Ns="Surveys module not available",Fl="sanitize_properties is deprecated. Use before_send instead",od="Invalid value for property_denylist config: ",of=["token","distinct_id",pu],os="posthog",ad=!Up&&Pe?.indexOf("MSIE")===-1&&Pe?.indexOf("Mozilla")===-1,_i=t=>{var e;return b({api_host:"https://us.i.posthog.com",flags_api_host:null,ui_host:null,asset_host:null,token:"",autocapture:!0,cross_subdomain_cookie:op(C?.location),persistence:"localStorage+cookie",persistence_name:"",cookie_persisted_properties:[],loaded:fn,save_campaign_params:!0,custom_campaign_params:[],custom_blocked_useragents:[],save_referrer:!0,capture_pageleave:"if_capture_pageview",defaults:t??"unset",__preview_deferred_init_extensions:!1,__preview_external_dependency_versioned_paths:!1,__preview_cookie_wins_on_conflict:!1,debug:re&&W(re?.search)&&re.search.indexOf("__posthog_debug=true")!==-1||!1,cookie_expiration:365,upgrade:!1,disable_session_recording:!1,disable_persistence:!1,disable_web_experiments:!0,disable_surveys:!1,disable_surveys_automatic_display:!1,disable_conversations:!1,disable_product_tours:!1,disableDeviceModel:!1,disable_external_dependency_loading:!1,strict_script_versioning:!1,enable_recording_console_log:void 0,secure_cookie:(v==null||(e=v.location)==null?void 0:e.protocol)==="https:",ip:!1,opt_out_capturing_by_default:!1,opt_out_persistence_by_default:!1,opt_out_useragent_filter:!1,opt_out_capturing_persistence_type:"localStorage",consent_persistence_name:null,opt_out_capturing_cookie_prefix:null,opt_in_site_apps:!1,property_denylist:[],respect_dnt:!1,sanitize_properties:null,request_headers:{},request_batching:!0,properties_string_max_length:65535,mask_all_element_attributes:!1,mask_all_text:!1,mask_personal_data_properties:!1,custom_personal_data_properties:[],advanced_disable_flags:!1,advanced_disable_decide:!1,advanced_disable_feature_flags:!1,advanced_disable_feature_flags_on_first_load:!1,advanced_only_evaluate_survey_feature_flags:!1,advanced_feature_flags_dedup_per_session:!1,advanced_enable_surveys:!1,advanced_disable_toolbar_metrics:!1,feature_flag_request_timeout_ms:3e3,surveys_request_timeout_ms:1e4,on_request_error(s){k.error("Bad HTTP status: "+s.statusCode+" "+s.text)},get_device_id:s=>s,capture_performance:void 0,name:"posthog",bootstrap:{},disable_compression:!1,session_idle_timeout_seconds:1800,person_profiles:to,before_send:void 0,get_current_url:void 0,request_queue_config:{flush_interval_ms:uo},error_tracking:{},_onCapture:fn},(s=>({rageclick:s&&s>="2026-05-30"?{content_ignorelist:_p,ignore_text_selection:!0}:!s||"2025-11-30">s||{content_ignorelist:!0},capture_pageview:!s||"2025-05-24">s||"history_change",session_recording:s&&s>="2026-06-25"?{strictMinimumDuration:!0,canvasCapture:{resolutionScale:.6},streamNetworkBody:!0}:s&&s>="2026-05-30"?{strictMinimumDuration:!0,canvasCapture:{resolutionScale:.6}}:s&&s>="2025-11-30"?{strictMinimumDuration:!0}:{},external_scripts_inject_target:s&&s>="2026-01-30"?"head":"body",internal_or_test_user_hostname:s&&s>="2026-01-30"?/^(localhost|127\.0\.0\.1)$/:void 0,persistence_save_debounce_ms:s&&s>="2026-05-30"?250:0,split_storage:!(!s||"2026-05-30">s),detect_google_search_app:!(!s||"2026-05-30">s),disable_capture_url_hashes:!(!s||"2026-06-25">s)}))(t))},af=[["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"]],Pl=t=>{var e={};for(var s of af){var r=s[0],n=s[1];x(t[r])||(e[n]=t[r])}var i=ee({},e,t),o=t.__preview_external_dependency_versioned_paths;return x(o)||(x(t.strict_script_versioning)&&(i.strict_script_versioning=!!o),W(o)&&x(t.asset_host)&&(i.asset_host=o)),L(t.property_blacklist)&&(x(t.property_denylist)?i.property_denylist=t.property_blacklist:L(t.property_denylist)?i.property_denylist=[...t.property_blacklist,...t.property_denylist]:k.error(od+t.property_denylist)),i};class lf{constructor(){this.__forceAllowLocalhost=!1}get fn(){return this.__forceAllowLocalhost}set fn(e){k.error("WebPerformanceObserver is deprecated and has no impact on network capture. Use `_forceAllowLocalhostNetworkCapture` on `posthog.sessionRecording`"),this.__forceAllowLocalhost=e}}class Te{pn(e,s){if(e){var r=this.sn.indexOf(e);r!==-1&&this.sn.splice(r,1)}return this.sn.push(s),s.initialize==null||s.initialize(),s}gn(){return this.config.cookieless_mode===ht||this.config.cookieless_mode===Ht&&this.consent.isRejected()}get decideEndpointWasHit(){var e,s;return(e=(s=this.featureFlags)==null?void 0:s.hasLoadedFlags)!==null&&e!==void 0&&e}get flagsEndpointWasHit(){var e,s;return(e=(s=this.featureFlags)==null?void 0:s.hasLoadedFlags)!==null&&e!==void 0&&e}constructor(){var e;this.webPerformance=new lf,this.mn=!1,this.version=Y.LIB_VERSION,this.yn=new Set,this.bn="",this.dn=new Xo,this.sn=[],this._n=[],this._calculate_event_properties=this.calculateEventProperties.bind(this),this.config=_i(),this.SentryIntegration=Ip,this.sentryIntegration=r=>(function(n,i){var o=$u(n,i);return{name:Au,processEvent:a=>o(a)}})(this,r),this.__request_queue=[],this.__loaded=!1,this.analyticsDefaultEndpoint="/e/",this.wn=!1,this.kn=null,this.xn=null,this.Sn=null,this.scrollManager=new Gp(this),this.pageViewManager=new fl(this),this.rateLimiter=new Mp(this),this.requestRouter=new Yp(this),this.consent=new pp(this),this.externalIntegrations=new tf(this);var s=(e=Te.__defaultExtensionClasses)!==null&&e!==void 0?e:{};this.featureFlags=s.featureFlags&&new s.featureFlags(this),this.toolbar=s.toolbar&&new s.toolbar(this),this.surveys=s.surveys&&new s.surveys(this),this.conversations=s.conversations&&new s.conversations(this),this.logs=s.logs&&new s.logs(this),this.metrics=s.metrics&&new s.metrics(this),this.experiments=s.experiments&&new s.experiments(this),this.exceptions=s.exceptions&&new s.exceptions(this),this.people={set:(r,n,i)=>{var o=W(r)?{[r]:n}:r;this.setPersonProperties(o),i?.({})},set_once:(r,n,i)=>{var o=W(r)?{[r]:n}:r;this.setPersonProperties(void 0,o),i?.({})}},this.on("eventCaptured",(r=>k.info('send "'+r?.event+'"',r)))}init(e,s,r){if(r&&r!==os){var n,i=(n=Ys[r])!==null&&n!==void 0?n:new Te;return i._init(e,s,r),Ys[r]=i,Ys[os][r]=i,i}return this._init(e,s,r)}_init(e,s,r){var n,i;s===void 0&&(s={});var o,a=W(e)?e.trim():"";if(!a)return k.critical("PostHog was initialized without a token. This likely indicates a misconfiguration. Please check the first argument passed to posthog.init()"),this;if(this.__loaded)return a!==((o=this.config)==null?void 0:o.token)?console.warn("[PostHog.js]","You have already initialized PostHog with a different project token! Re-initializing is a no-op, so events will keep going to the project this instance was initialized with. To capture into a second project, load PostHog once, then initialize a named instance after the SDK has loaded, e.g. posthog.init('"+a+"', { ... }, 'project2')"):console.warn("[PostHog.js]","You have already initialized PostHog! Re-initializing is a no-op"),this;this.__loaded=!0,this.config=_i(s.defaults),s.debug=this.Cn(s.debug),this.Mn=s,this.Tn=[],s.person_profiles?this.xn=s.person_profiles:s.process_person&&(this.xn=s.process_person);var l=_i(s.defaults),u=Pl(s),c=ee({},l,u,{name:r,token:a});te(l.rageclick)&&te(u.rageclick)&&(c.rageclick=ee({},l.rageclick,u.rageclick)),te(l.session_recording)&&te(u.session_recording)&&(c.session_recording=ee({},l.session_recording,u.session_recording)),this.set_config(c),this.config.on_xhr_error&&k.error("on_xhr_error is deprecated. Use on_request_error instead"),this.compression=s.disable_compression?void 0:xe.GZipJS;var d=this.En();if(this.persistence=new ui(this.config,d),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new ui(b({},this.config,{persistence:"sessionStorage"}),d,!1),this.bn="ph_"+(this.config.persistence_name||this.config.token)+"_session_registered_properties",this.config.persistence!=="memory"&&!d&&ce.N()){var h=ce.H(this.bn);L(h)&&h.forEach((P=>{W(P)&&this.yn.add(P)}))}else ce.q(this.bn);var p=b({},this.persistence.props),f=b({},this.sessionPersistence.props);this.register({$initialization_time:new Date().toISOString()}),this.In=new zp((P=>this.Pn(P)),this.config.request_queue_config),this.Rn=new Vp(this),this.__request_queue=[];var g=this.gn();if(g||(this.sessionManager=new xl(this),this.sessionPropsManager=new Sl(this,this.sessionManager,this.persistence),this.sessionManager.onSessionId(((P,B,S)=>{(S!=null&&S.activityTimeout||S!=null&&S.sessionPastMaximumLength||S!=null&&S.crossTabAdoption)&&this.An()}))),this.Fn(),this.config.__preview_deferred_init_extensions?(k.info("Deferring extension initialization to improve startup performance"),setTimeout((()=>{this.Ln(g)}),0)):(k.info("Initializing extensions synchronously"),this.Ln(g)),Y.DEBUG=Y.DEBUG||this.config.debug,Y.DEBUG&&k.info("Starting in debug mode",{this:this,config:s,thisC:b({},this.config),p,s:f}),!this.config.identity_distinct_id||(n=s.bootstrap)!=null&&n.distinctID||(s.bootstrap=b({},s.bootstrap,{distinctID:this.config.identity_distinct_id,isIdentifiedID:!0})),((i=s.bootstrap)==null?void 0:i.distinctID)!==void 0){var m=s.bootstrap.distinctID,_=this.get_distinct_id(),w=this.persistence.get_property(He);if(s.bootstrap.isIdentifiedID&&_!=null&&_!==m&&w===es)this.identify(m);else if(s.bootstrap.isIdentifiedID&&_!=null&&_!==m&&w===Tt)k.warn("Bootstrap distinctID differs from an already-identified user. The existing identity is preserved. Call reset() before reinitializing if you intend to switch users.");else{var E=this.config.get_device_id(dt()),I=s.bootstrap.isIdentifiedID?E:m;this.persistence.set_property(He,s.bootstrap.isIdentifiedID?Tt:es),this.register({distinct_id:m,$device_id:I})}}if(g)this.register_once({distinct_id:br,$device_id:null},"");else if(!this.get_distinct_id()){var F=this.config.get_device_id(dt());this.register_once({distinct_id:F,$device_id:F},""),this.persistence.set_property(He,es)}return ne(v,"onpagehide"in self?"pagehide":"unload",this._handle_unload.bind(this),{passive:!1}),s.segment?(function(P,B){var S=P.config.segment;if(!S)return B();(function(A,R){var N=A.config.segment;if(!N)return R();var T=J=>{var z=()=>J.anonymousId()||dt();A.config.get_device_id=z,J.id()&&(A.register({distinct_id:J.id(),$device_id:z()}),A.persistence.set_property(He,Tt)),R()},O=N.user();"then"in O&&Se(O.then)?O.then(T):T(O)})(P,(()=>{S.register((A=>{typeof Promise<"u"&&Promise.resolve||li.warn("This browser does not have Promise support, and can not use the segment integration");var R=(N,T)=>{if(!T)return N;N.event.userId||N.event.anonymousId===A.get_distinct_id()||(li.info("No userId set, resetting PostHog"),A.reset()),N.event.userId&&N.event.userId!==A.get_distinct_id()&&(li.info("UserId set, identifying with PostHog"),A.identify(N.event.userId));var O=A.calculateEventProperties(T,N.event.properties);return N.event.properties=Object.assign({},O,N.event.properties),N};return{name:"PostHog JS",type:"enrichment",version:"1.0.0",isLoaded:()=>!0,load:()=>Promise.resolve(),track:N=>R(N,N.event.event),page:N=>R(N,is),identify:N=>R(N,ii),screen:N=>R(N,"$screen")}})(P)).then((()=>{B()}))}))})(this,(()=>this.On())):this.On(),Se(this.config._onCapture)&&this.config._onCapture!==fn&&(k.warn("onCapture is deprecated. Please use `before_send` instead"),this.on("eventCaptured",(P=>this.config._onCapture(P.event,P)))),this.config.ip&&k.warn('The `ip` config option has NO EFFECT AT ALL and has been deprecated. Use a custom transformation or "Discard IP data" project setting instead. See https://posthog.com/tutorials/web-redact-properties#hiding-customer-ip-address for more information.'),this.config.disableDeviceModel||(function(){return ed.apply(this,arguments)})().then((P=>{P&&this.register({[ri]:P})})).catch(fn),this}Fn(){var e,s,r,n,i,o,a=(e=(s=this.config.__extensionClasses)==null?void 0:s.featureFlags)!==null&&e!==void 0?e:(r=Te.__defaultExtensionClasses)==null?void 0:r.featureFlags;a&&(this.featureFlags&&this.featureFlags instanceof a||((n=this.Dn)==null||n.call(this),this.Dn=void 0,this.featureFlags=new a(this)),Se(this.featureFlags.onReloading)&&Se(this.featureFlags.setup)?this.Dn||(this.Dn=this.featureFlags.onReloading((()=>{this.dn.emit("featureFlagsReloading",!0)})),this.$n().add(this.featureFlags)):(i=(o=this.featureFlags).initialize)==null||i.call(o))}Ln(e){var s,r,n,i,o,a,l,u=performance.now(),c=b({},Te.__defaultExtensionClasses,this.config.__extensionClasses),d=[];c.exceptions&&this.sn.push(this.exceptions=(s=this.exceptions)!==null&&s!==void 0?s:new c.exceptions(this)),c.historyAutocapture&&this.sn.push(this.historyAutocapture=new c.historyAutocapture(this)),c.tracingHeaders&&this.sn.push(this.tracingHeaders=new c.tracingHeaders(this)),c.siteApps&&this.sn.push(this.siteApps=new c.siteApps(this)),c.sessionRecording&&!e&&this.sn.push(this.sessionRecording=new c.sessionRecording(this)),this.config.disable_scroll_properties||d.push((()=>{this.scrollManager.startMeasuringScrollPosition()})),c.autocapture&&this.sn.push(this.autocapture=new c.autocapture(this)),c.surveys&&this.sn.push(this.surveys=(r=this.surveys)!==null&&r!==void 0?r:new c.surveys(this)),c.logs&&this.sn.push(this.logs=(n=this.logs)!==null&&n!==void 0?n:new c.logs(this)),c.metrics&&this.sn.push(this.metrics=(i=this.metrics)!==null&&i!==void 0?i: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,kp)),c.toolbar&&this.sn.push(this.toolbar=(a=this.toolbar)!==null&&a!==void 0?a:new c.toolbar(this)),c.experiments&&this.sn.push(this.experiments=(l=this.experiments)!==null&&l!==void 0?l:new c.experiments(this)),this.sn.forEach((h=>{h.initialize&&d.push((()=>{h.initialize==null||h.initialize()}))})),d.push((()=>{if(this.Nn){var h=this.Nn;this.Nn=void 0,this.sn.forEach((p=>p.onRemoteConfig==null?void 0:p.onRemoteConfig(h)))}})),this.qn(d,u)}qn(e,s){for(;e.length>0;){if(this.config.__preview_deferred_init_extensions&&performance.now()-s>=30&&e.length>0)return void setTimeout((()=>{this.qn(e,s)}),0);var r=e.shift();if(r)try{r()}catch(i){k.error("Error initializing extension:",i)}}var n=Math.round(performance.now()-s);this.register_for_session({[fu]:this.config.__preview_deferred_init_extensions?"deferred":"synchronous",[gu]:n}),this.config.__preview_deferred_init_extensions&&k.info("PostHog extensions initialized ("+n+"ms)")}Zi(e){var s;if(!C||!C.body)return k.info("document not ready yet, trying again in 500 milliseconds..."),void setTimeout((()=>{this.Zi(e)}),500);if(this.config.__preview_deferred_init_extensions&&(this.Nn=e),this.hn=e,this.compression=void 0,e.ok){var r,n=e.config;n.supportedCompression&&!this.config.disable_compression&&(this.compression=M(n.supportedCompression,xe.GZipJS)?xe.GZipJS:M(n.supportedCompression,xe.Base64)?xe.Base64:void 0),(r=n.analytics)!=null&&r.endpoint&&(this.analyticsDefaultEndpoint=n.analytics.endpoint)}this.set_config({person_profiles:this.xn?this.xn:to}),(s=this.jn)==null||s.handleRemoteConfig(e),this.sn.forEach((i=>i.onRemoteConfig==null?void 0:i.onRemoteConfig(e)))}On(){try{this.config.loaded(this)}catch(r){k.critical("`loaded` function failed",r)}if(this.Bn(),this.config.internal_or_test_user_hostname&&re!=null&&re.hostname){var e=re.hostname,s=this.config.internal_or_test_user_hostname;(typeof s=="string"?e===s:s.test(e))&&this.setInternalOrTestUser()}this.config.capture_pageview&&setTimeout((()=>{(this.consent.isOptedIn()||this.gn())&&this.Hn()}),1),this.Un=new Uu(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()&&Er(this.__request_queue,(e=>this.Pn(e))),this.__request_queue=[],this.Bn()}_handle_unload(){var e,s,r,n,i;(e=this.surveys)==null||e.handlePageUnload==null||e.handlePageUnload(),(s=this.metrics)==null||s.flush("sendBeacon"),this.config.request_batching?(this.zn()&&this.capture(ni),(r=this.logs)==null||r.flushLogs("sendBeacon"),(n=this.In)==null||n.unload(),(i=this.Rn)==null||i.unload()):this.zn()&&this.capture(ni,null,{transport:"sendBeacon"})}_send_request(e){this.__loaded?ad?this.__request_queue.push(e):this.rateLimiter.isServerRateLimited(e.batchKey)?e.fireCallbackOnDrop&&(e.callback==null||e.callback({statusCode:429})):(e.transport=e.transport||this.config.api_transport,e.headers=b({},this.config.request_headers,e.headers),e.compression=e.compression==="best-available"?this.compression:e.compression,(x(this.config.disable_beacon)?this.config.__preview_disable_beacon:this.config.disable_beacon)&&(e.disableTransport=["sendBeacon"]),e.fetchOptions=e.fetchOptions||this.config.fetch_options,(s=>{var r,n,i,o=b({},s);o.timeout=o.timeout||6e4;var a,l,u,c,d,h=(r=o.transport)!==null&&r!==void 0?r:"fetch";h==="sendBeacon"&&x(o.compression)&&o.data&&(o.compression=xe.Base64),o.method==="POST"&&o.data&&(o.timestampMode==="capture-body"?o.data={api_key:(l=(d=(c=L(a=o.data)?a:[a])[0])==null||(u=d.properties)==null?void 0:u.token)!==null&&l!==void 0?l:d?.token,batch:c,sent_at:new Date().toISOString()}:o.timestampMode==="body"&&(o.data=(function(m,_){return _===void 0&&(_=new Date().toISOString()),L(m)?m.map((w=>b({},w,{sent_at:_}))):b({},m,{sent_at:_})})(o.data))),o.url=El(o.url,o.method,o.compression,o.timestampMode);var p=Br.filter((m=>!o.disableTransport||!m.transport||!o.disableTransport.includes(m.transport))),f=(n=(i=(function(m,_){for(var w=0;m.length>w;w++)if(m[w].transport===h)return m[w]})(p))==null?void 0:i.method)!==null&&n!==void 0?n:p[0].method;if(!f)throw new Error("No available transport method");var g=m=>{try{f(m)}catch(_){Zu(_)?k.warn(_):k.error(_),o.callback==null||o.callback({statusCode:0,error:_})}};h!=="sendBeacon"&&o.data&&o.compression===xe.GZipJS&&lh&&typeof Promise<"u"&&!Dr?Hp(o).then((m=>{g(m)})).catch((m=>{if(Ha(m))return Dr=!0,void g(b({},o,{compression:void 0,url:El(s.url,s.method,void 0,s.timestampMode)}));(_=>{if(!_||typeof _!="object")return!1;var w="name"in _?String(_.name):"";return Ha(_)||w===Cc})(m)&&(Dr=!0),g(o)})):f(o)})(b({},e,{callback:s=>{var r,n;this.rateLimiter.checkForLimiting(s),400>s.statusCode||(r=(n=this.config).on_request_error)==null||r.call(n,s),e.callback==null||e.callback(s)}}))):e.fireCallbackOnDrop&&(e.callback==null||e.callback({statusCode:0}))}Pn(e){this.Rn?this.Rn.retriableRequest(e):this._send_request(e)}_execute_array(e){vi++;try{var s,r=[],n=[],i=[];Er(e,(a=>{if(a)if(L(s=a[0]))i.push(a);else if(Se(a))try{a.call(this)}catch(l){k.error("Error executing queued PostHog call",a,l)}else L(a)&&s==="alias"?r.push(a):L(a)&&s.indexOf("capture")!==-1&&Se(this[s])?i.push(a):n.push(a)}));var o=function(a,l){Er(a,(function(u){try{if(L(u[0])){var c=l;Z(u,(function(d){c=c[d[0]].apply(c,d.slice(1))}))}else l[u[0]].apply(l,u.slice(1))}catch(d){k.error("Error executing queued PostHog call",u,d)}}))};o(r,this),o(n,this),o(i,this)}finally{vi--}}push(e){if(vi>0&&L(e)&&W(e[0])){var s=Te.prototype[e[0]];Se(s)&&s.apply(this,e.slice(1))}else this._execute_array([e])}capture(e,s,r){var n,i,o,a,l;if(this.__loaded&&this.persistence&&this.sessionPersistence&&this.In){if(this.is_capturing())if(!x(e)&&W(e)){var u=!this.config.opt_out_useragent_filter&&this._is_bot();if(!u||this.config.__preview_capture_bot_pageviews){var c=r!=null&&r.skip_client_rate_limiting?void 0:this.rateLimiter.clientRateLimitContext();if(c==null||!c.isRateLimited){s!=null&&s.$current_url&&!W(s?.$current_url)&&(k.error("Invalid `$current_url` property provided to `posthog.capture`. Input must be a string. Ignoring provided value."),s==null||delete s.$current_url),e!=="$exception"||r!=null&&r.Wn||k.warn("Using `posthog.capture('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureException(error)` instead, which attaches required metadata automatically."),this.sessionPersistence.update_search_keyword(),this.config.save_campaign_params&&this.sessionPersistence.update_campaign_params(),this.config.save_referrer&&this.sessionPersistence.update_referrer_info(),(this.config.save_campaign_params||this.config.save_referrer)&&this.persistence.set_initial_person_info();var d=new Date,h=r?.timestamp||d,p=Ga(r?.uuid,dt),f={uuid:p,event:e,properties:this.calculateEventProperties(e,s||{},h,p)};e===is&&this.config.__preview_capture_bot_pageviews&&u&&(f.event="$bot_pageview",f.properties.$browser_type="bot"),c&&(f.properties.$lib_rate_limit_remaining_tokens=c.remainingTokens);var g=e==="$feature_flag_called"&&f.properties.$feature_flag_has_experiment===!1&&this.get_property(en)===!0;r?.$set&&!g&&(f.$set=r?.$set);var m=r?.$unset;m&&(f.$unset=m);var _,w,E,I=g?void 0:this.Vn(r?.$set_once,e!==Qa,e===ii);if(I&&(f.$set_once=I),r!=null&&r._noTruncate||(i=this.config.properties_string_max_length,o=f,a=T=>W(T)?T.slice(0,i):T,l=new Set,f=(function T(O,J){if(O!==Object(O))return a?a(O):O;if(!l.has(O)){var z;if(l.add(O),L(O))z=[],Er(O,(oe=>{z.push(T(oe))}));else{var H={};Z(O,((oe,pe)=>{l.has(oe)||(H[pe]=T(oe))})),z=H}return z}})(o)),f.timestamp=h,x(r?.timestamp)||(f.properties.$event_time_override_provided=!0,f.properties.$event_time_override_system_time=d),g&&(f.properties=(function(T,O){O===void 0&&(O=[]);var J={},z=H=>{T[H]!==void 0&&(J[H]=T[H])};return ch.forEach(z),O.forEach(z),J})(f.properties,of)),e===ft.DISMISSED||e===ft.SENT){var F=s?.[hi.SURVEY_ID],P=s?.[hi.SURVEY_ITERATION];id({id:F,current_iteration:P}),f.$set=b({},f.$set,{[(_={id:F,current_iteration:P},w=e===ft.SENT?"responded":"dismissed",E="$survey_"+w+"/"+_.id,_.current_iteration&&_.current_iteration>0&&(E="$survey_"+w+"/"+_.id+"/"+_.current_iteration),E)]:!0})}else e===ft.SHOWN&&(f.$set=b({},f.$set,{[hi.SURVEY_LAST_SEEN_DATE]:new Date().toISOString()}));if(e===Np.SHOWN){var B=s?.[ml.TOUR_TYPE];B&&(f.$set=b({},f.$set,{[ml.TOUR_LAST_SEEN_DATE+"/"+B]:new Date().toISOString()}))}var S=b({},f.properties.$set,f.$set);if(mt(S)||this.setPersonPropertiesForFlags(S),!D(this.config.before_send)){var A=this.Pt(f);if(!A)return;(f=A).uuid=Ga(f.uuid,dt)}this.dn.emit("eventCaptured",f);var R=(n=r?._url)!==null&&n!==void 0?n:this.requestRouter.endpointFor("api",this.analyticsDefaultEndpoint),N={method:"POST",url:R,data:f,compression:"best-available",timestampMode:r?._batchKey==="recordings"||/\/s\/(?:\?|$)/.test(R)?"body":"capture-body",batchKey:r?._batchKey,transport:r?.transport};return!this.config.request_batching||r&&(r==null||!r._batchKey)||r!=null&&r.send_instantly?this.Pn(N):this.In.enqueue(N),f}k.critical("This capture call is ignored due to client rate limiting.")}}else k.error("No event name provided to posthog.capture")}else k.uninitializedWarning("posthog.capture")}_addCaptureHook(e){return this.on("eventCaptured",(s=>e(s.event,s)))}$n(){var e;return(e=this.jn)!==null&&e!==void 0?e:this.jn=new nf(this)}cn(e){this._n.push(e);var s=!0;return()=>{if(s){s=!1;var r=this._n.indexOf(e);r!==-1&&this._n.splice(r,1)}}}calculateEventProperties(e,s,r,n,i){if(r=r||new Date,!this.persistence||!this.sessionPersistence)return s;var o=i?void 0:this.persistence.remove_event_timer(e),a=b({},s);if(a.token=this.config.token,a.$config_defaults=this.config.defaults,this.gn()&&(a[pu]=!0),e==="$snapshot"){var l=b({},this.persistence.properties(),this.sessionPersistence.properties());return a.distinct_id=l.distinct_id,(!W(a.distinct_id)&&!he(a.distinct_id)||Mi(a.distinct_id))&&k.error("Invalid distinct_id for replay event. This indicates a bug in your implementation"),a}var u,c=(function(F,P,B,S){var A,R,N,T;if(S===void 0&&(S=!1),!Pe)return{};var O,J=F?[...vs,...P||[]]:[],z=(function(vr){for(var je=0;qa.length>je;je++){var _r=qa[je],Xt=_r[1],Qt=_r[0].exec(vr),Is=Qt&&(Se(Xt)?Xt(Qt,vr):Xt);if(Is)return Is}return["",""]})(Pe),H=z[0],oe=z[1],pe=(O=typeof navigator<"u"?navigator:void 0)!=null&&O.brave?{brave:!0}:{},Ie={};x(B)||(Ie.detectGoogleSearchApp=B);var _e={},Ce=(A=navigator)==null||(A=A.userAgentData)==null?void 0:A.platform,Re=(R=navigator)==null?void 0:R.maxTouchPoints,ae=v==null||(N=v.screen)==null?void 0:N.width,me=v==null||(T=v.screen)==null?void 0:T.height,ge=v?.devicePixelRatio;x(Ce)||(_e.userAgentDataPlatform=Ce),x(Re)||(_e.maxTouchPoints=Re),x(ae)||(_e.screenWidth=ae),x(me)||(_e.screenHeight=me),x(ge)||(_e.devicePixelRatio=ge);var Ye,Rt,de,Ve,St,ks,Be,Fe,mr=ee(Vo({$os:H,$os_version:oe,$browser:Xc(Pe,navigator.vendor,pe,Ie),$device:Va(Pe),$device_type:(Rt=Pe,de=_e,Fe=Va(Rt),Fe===Nc||Fe===Tc||Fe==="Kobo"||Fe==="Kindle Fire"||Fe===Gc?ps:Fe===er||Fe===ds||Fe===tr||Fe===Oi?"Console":Fe===Lc?"Wearable":Fe?Oe:de?.userAgentDataPlatform==="Android"&&((Ve=de?.maxTouchPoints)!==null&&Ve!==void 0?Ve:0)>0?600>Math.min((St=de?.screenWidth)!==null&&St!==void 0?St:0,(ks=de?.screenHeight)!==null&&ks!==void 0?ks:0)/((Be=de?.devicePixelRatio)!==null&&Be!==void 0?Be:1)?Oe:ps:"Desktop"),$timezone:ju(),$timezone_offset:$p()}),{$current_url:nr(S?Ct(re?.href):re?.href,J,ir),$host:re?.host,$pathname:re?.pathname,$raw_user_agent:Pe.length>1e3?Pe.substring(0,997)+"...":Pe,$browser_version:Fh(Pe,navigator.vendor,pe,Ie),$browser_language:gl(),$browser_language_prefix:(Ye=gl(),typeof Ye=="string"?Ye.split("-")[0]:void 0),$screen_height:v?.screen.height,$screen_width:v?.screen.width,$viewport_height:v?.innerHeight,$viewport_width:v?.innerWidth,$lib:Y.LIB_NAME,$lib_version:Y.LIB_VERSION,$insert_id:Math.random().toString(36).substring(2,10)+Math.random().toString(36).substring(2,10),$time:Date.now()/1e3});return Y.SDK_DIST_CHANNEL&&(mr.$sdk_dist_channel=Y.SDK_DIST_CHANNEL),mr})(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(i,r.getTime()),h=d.windowId;a.$session_id=d.sessionId,a.$window_id=h}this.sessionPropsManager&&ee(a,this.sessionPropsManager.getSessionProps());try{var p;this.sessionRecording&&ee(a,this.sessionRecording.sdkDebugProperties),a.$sdk_debug_retry_queue_size=(p=this.Rn)==null?void 0:p.length}catch(F){a.$sdk_debug_error_capturing_properties=String(F)}if(this.requestRouter.region===ho&&(a.$lib_custom_api_host=this.config.api_host),u=e!==is||i?e!==ni||i?this.pageViewManager.doEvent():this.pageViewManager.doPageLeave(r):this.pageViewManager.doPageView(r,n),a=ee(a,u),e===is&&C&&(a.title=C.title),!x(o)){var f=r.getTime()-o;a.$duration=parseFloat((f/1e3).toFixed(3))}Pe&&this.config.opt_out_useragent_filter&&(a.$browser_type=this._is_bot()?"bot":"browser");var g=this.persistence.properties(),m=this.sessionPersistence.properties();Z(["$referrer","$referring_domain"],(F=>{F in g&&delete m[F]}));var _={};if(this._n.length>0)for(var w of this._n.slice())try{ee(_,w())}catch(F){k.error("Failed to produce browser extension event properties",F)}(a=ee({},c,g,m,b({},_,a))).$is_identified=this._isIdentified(),L(this.config.property_denylist)?Z(this.config.property_denylist,(function(F){delete a[F]})):k.error(od+this.config.property_denylist+" or property_blacklist config: "+this.config.property_blacklist);var E=this.config.sanitize_properties;E&&(k.error(Fl),a=E(a,e));var I=this.Zn();return a.$process_person_profile=I,I&&!i&&this.Gn("_calculate_event_properties"),a}Vn(e,s,r){var n;if(s===void 0&&(s=!0),r===void 0&&(r=!1),!this.persistence||!this.Zn()||this.mn&&!r)return e;var i=this.persistence.get_initial_props(),o=(n=this.sessionPropsManager)==null?void 0:n.getSetOnceProps(),a=ee({},i,o||{},e||{}),l=this.config.sanitize_properties;return l&&(k.error(Fl),a=l(a,"$set_once")),s&&(this.mn=!0),mt(a)?void 0:a}register(e,s){var r;(r=this.persistence)==null||r.register(e,s)}register_once(e,s,r){var n;(n=this.persistence)==null||n.register_once(e,s,r)}register_for_session(e){var s;(s=this.sessionPersistence)==null||s.register(e),Object.keys(e).forEach((r=>this.yn.add(r))),this.Qn()}unregister(e){var s;(s=this.persistence)==null||s.unregister(e)}unregister_for_session(e){var s;(s=this.sessionPersistence)==null||s.unregister(e),this.yn.delete(e),this.Qn()}Kn(e,s){this.register({[e]:s})}An(){this.yn.forEach((e=>{var s;(s=this.sessionPersistence)==null||s.unregister(e)})),this.yn.clear(),this.Qn()}Qn(){var e;if(this.bn)if(this.config.persistence==="memory"||(e=this.sessionPersistence)!=null&&e.xi||!ce.N())ce.q(this.bn);else{var s=[];this.yn.forEach((r=>s.push(r))),s.length>0?ce.F(this.bn,s):ce.q(this.bn)}}getFeatureFlag(e,s){var r;return(r=this.featureFlags)==null?void 0:r.getFeatureFlag(e,s)}getFeatureFlagPayload(e){var s;return(s=this.featureFlags)==null?void 0:s.getFeatureFlagPayload(e)}getFeatureFlagResult(e,s){var r;return(r=this.featureFlags)==null?void 0:r.getFeatureFlagResult(e,s)}getAllFeatureFlags(){var e,s;return(e=(s=this.featureFlags)==null?void 0:s.getAllFeatureFlags())!==null&&e!==void 0?e:[]}isFeatureEnabled(e,s){var r,n;return(r=(n=this.featureFlags)==null?void 0:n.isFeatureEnabled(e,s))!==null&&r!==void 0?r:s?.defaultValue}reloadFeatureFlags(){var e;(e=this.featureFlags)==null||e.reloadFeatureFlags()}updateFlags(e,s,r){var n;(n=this.featureFlags)==null||n.updateFlags(e,s,r)}updateEarlyAccessFeatureEnrollment(e,s,r){var n;(n=this.featureFlags)==null||n.updateEarlyAccessFeatureEnrollment(e,s,r)}getEarlyAccessFeatures(e,s,r){var n;return s===void 0&&(s=!1),(n=this.featureFlags)==null?void 0:n.getEarlyAccessFeatures(e,s,r)}on(e,s){return this.dn.on(e,s)}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:Ns}),()=>{})}onSessionId(e){var s,r;return(s=(r=this.sessionManager)==null?void 0:r.onSessionId(e))!==null&&s!==void 0?s:()=>{}}getSurveys(e,s){s===void 0&&(s=!1),this.surveys?this.surveys.getSurveys(e,s):e([],{isLoaded:!1,error:Ns})}getActiveMatchingSurveys(e,s){s===void 0&&(s=!1),this.surveys?this.surveys.getActiveMatchingSurveys(e,s):e([],{isLoaded:!1,error:Ns})}renderSurvey(e,s){var r;(r=this.surveys)==null||r.renderSurvey(e,s)}displaySurvey(e,s){var r;s===void 0&&(s=Xp),(r=this.surveys)==null||r.displaySurvey(e,s)}cancelPendingSurvey(e){var s;(s=this.surveys)==null||s.cancelPendingSurvey(e)}canRenderSurvey(e){var s,r;return(s=(r=this.surveys)==null?void 0:r.canRenderSurvey(e))!==null&&s!==void 0?s:{visible:!1,disabledReason:Ns}}canRenderSurveyAsync(e,s){var r,n;return s===void 0&&(s=!1),(r=(n=this.surveys)==null?void 0:n.canRenderSurveyAsync(e,s))!==null&&r!==void 0?r:Promise.resolve({visible:!1,disabledReason:Ns})}Jn(e){return!e||Mi(e)?(k.critical("Unique user id has not been set in posthog.identify"),!1):e===br?(k.critical('The string "'+e+'" was set in posthog.identify which indicates an error. This ID is only used as a sentinel value.'),!1):!["distinct_id","distinctid"].includes(e.toLowerCase())&&!["undefined","null"].includes(e.toLowerCase())||(k.critical('The string "'+e+'" was set in posthog.identify which indicates an error. This ID should be unique to the user and not a hardcoded string.'),!1)}identify(e,s,r){if(!this.__loaded||!this.persistence)return k.uninitializedWarning("posthog.identify");if(he(e)&&(e=e.toString(),k.warn("The first argument to posthog.identify was a number, but it should be a string. It has been converted to a string.")),this.Jn(e)&&this.Gn("posthog.identify")){var n=this.get_distinct_id();this.register({$user_id:e}),this.get_property(sr)||this.register_once({$had_persisted_distinct_id:!0,$device_id:n},""),e!==n&&e!==this.get_property(Bs)&&(this.unregister(Bs),this.register({distinct_id:e}));var i,o=(this.persistence.get_property(He)||es)===es,a=e!==n,l=!a&&o;if(a&&o)this.persistence.set_property(He,Tt),this.setPersonPropertiesForFlags({$set:s||{},$set_once:r||{}},!1),this.capture(ii,{distinct_id:e,$anon_distinct_id:n},{$set:s||{},$set_once:r||{}}),this.Sn=mi(e,s,r),(i=this.featureFlags)==null||i.setAnonymousDistinctId(n);else if(l){this.persistence.set_property(He,Tt);var u=s||{},c=r||{};this.setPersonPropertiesForFlags({$set:u,$set_once:c},!1),this.capture("$set",{$set:u,$set_once:c}),this.Sn=mi(e,s,r)}else(s||r)&&this.setPersonProperties(s,r);a?(this.reloadFeatureFlags(),this.featureFlags?this.featureFlags.resetFlagCallReported():this.unregister(Wt)):l&&(s||r)&&this.reloadFeatureFlags()}}setPersonProperties(e,s){if((e||s)&&this.Gn("posthog.setPersonProperties")){var r=mi(this.get_distinct_id(),e,s);this.Sn!==r?(this.setPersonPropertiesForFlags({$set:e||{},$set_once:s||{}},!0),this.capture("$set",{$set:e||{},$set_once:s||{}}),this.Sn=r):k.info("A duplicate setPersonProperties call was made with the same properties. It has been ignored.")}}unsetPersonProperties(e){var s,r=(L(e)?e:[e]).filter((n=>W(n)&&n.length>0));r.length!==0&&this.Gn("posthog.unsetPersonProperties")&&((s=this.featureFlags)==null||s.unsetPersonPropertiesForFlags(r,!0),this.capture("$set",{$unset:r}),this.Sn=null)}group(e,s,r){if(e&&s){var n=this.getGroups(),i=n[e]!==s;if(i&&this.resetGroupPropertiesForFlags(e),this.register({$groups:b({},n,{[e]:s})}),i||r){var o={$group_type:e,$group_key:s};r&&(o.$group_set=r),this.capture(Qa,o)}r&&this.setGroupPropertiesForFlags({[e]:r}),i&&!r&&this.reloadFeatureFlags()}else k.error("posthog.group requires a group type and group key")}resetGroups(){this.register({$groups:{}}),this.resetGroupPropertiesForFlags(),this.reloadFeatureFlags()}setPersonPropertiesForFlags(e,s){var r;s===void 0&&(s=!0),(r=this.featureFlags)==null||r.setPersonPropertiesForFlags(e,s)}resetPersonPropertiesForFlags(e){var s;e===void 0&&(e=!0),(s=this.featureFlags)==null||s.resetPersonPropertiesForFlags(e)}setGroupPropertiesForFlags(e,s){var r;s===void 0&&(s=!0),this.Gn("posthog.setGroupPropertiesForFlags")&&((r=this.featureFlags)==null||r.setGroupPropertiesForFlags(e,s))}resetGroupPropertiesForFlags(e){var s;(s=this.featureFlags)==null||s.resetGroupPropertiesForFlags(e)}reset(e){this.Yn(e)}Yn(e,s){var r,n,i,o,a,l,u,c,d,h;if(s===void 0&&(s=!1),k.info("reset"),!this.__loaded)return k.uninitializedWarning("posthog.reset");var p,f=this.get_property(sr),g=this.get_property(ri),m=this.get_property(qt),_=this.is_capturing();if(this.consent.reset(),s||!_||this.is_capturing()||console.warn("[PostHog.js]","reset() cleared the stored consent, and capturing is now off because of `opt_out_capturing_by_default`. Call opt_in_capturing() again, and prefer calling reset() before opting in rather than after."),(r=this.persistence)==null||r.clear(),(n=this.sessionPersistence)==null||n.clear(),this.yn.clear(),this.Qn(),x(m)||(p=this.persistence)==null||p.register({[qt]:m}),(i=this.surveys)==null||i.reset(),(o=this.Un)==null||o.stop(),(a=this.featureFlags)==null||a.reset(),(l=this.conversations)==null||l.reset(),(u=this.logs)==null||u.reset(),(c=this.metrics)==null||c.reset(),(d=this.persistence)==null||d.set_property(He,es),(h=this.sessionManager)==null||h.resetSessionId(),this.Sn=null,this.config.cookieless_mode===ht)this.register_once({distinct_id:br,$device_id:null},"");else{var w=this.config.get_device_id(dt());this.register_once({distinct_id:w,$device_id:e?w:f},""),e||x(g)||this.register({[ri]: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 s=this;return X((function*(){var r,n,i,o,a,l,u;if(s.__loaded){(r=s.Un)==null||r.stop(),(n=s.jn)==null||n.dispose(),(i=s.sessionRecording)==null||i.dispose(),(o=s.logs)==null||o.flushLogs("sendBeacon"),(a=s.metrics)==null||a.flush("sendBeacon"),(l=s.In)==null||l.unload(),(u=s.Rn)==null||u.unload();try{var c;(c=s.featureFlags)==null||c.destroy()}catch(d){k.error("Error while destroying feature flags",d)}}else k.uninitializedWarning("posthog.shutdown")}))()}setIdentity(e,s){var r;this.config.identity_distinct_id=e,this.config.identity_hash=s,this.alias(e),(r=this.conversations)==null||r.Xn()}clearIdentity(){var e;delete this.config.identity_distinct_id,delete this.config.identity_hash,(e=this.conversations)==null||e.ts()}get_distinct_id(){return this.get_property("distinct_id")}getGroups(){return this.get_property("$groups")||{}}get_session_id(){var e,s;return(e=(s=this.sessionManager)==null?void 0:s.checkAndGetSessionAndWindowId(!0).sessionId)!==null&&e!==void 0?e:""}get_session_replay_url(e){if(!this.sessionManager)return"";var s=this.sessionManager.checkAndGetSessionAndWindowId(!0),r=s.sessionStartTimestamp,n=this.requestRouter.endpointFor("ui","/project/"+this.config.token+"/replay/"+s.sessionId);if(e!=null&&e.withTimestamp&&r){var i,o=(i=e.timestampLookBack)!==null&&i!==void 0?i:10;if(!r)return n;n+="?t="+Math.max(Math.floor((new Date().getTime()-r)/1e3)-o,0)}return n}alias(e,s){return e===this.get_property(au)?(k.critical("Attempting to create alias for existing People user - aborting."),-2):this.Gn("posthog.alias")?(x(s)&&(s=this.get_distinct_id()),e!==s?(this.Kn(Bs,e),this.capture("$create_alias",{alias:e,distinct_id:s})):(k.warn("alias matches current distinct_id - skipping api call."),this.identify(e),-1)):void 0}set_config(e){var s=b({},this.config);if(te(e)){var r,n,i,o,a,l,u,c,d,h,p,f;ee(this.config,Pl(e));var g=this.En();(r=this.persistence)==null||r.update_config(this.config,s,g),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new ui(b({},this.config,{persistence:"sessionStorage"}),g,!1);var m=this.Cn(this.config.debug);Ke(m)&&(this.config.debug=m),Ke(this.config.debug)&&(this.config.debug?(Y.DEBUG=!0,Q.N()&&Q.F("ph_debug",!0),k.info("set_config",{config:e,oldConfig:s,newConfig:b({},this.config)})):(Y.DEBUG=!1,Q.N()&&Q.q("ph_debug"))),(n=this.featureFlags)==null||n.updateConfig==null||n.updateConfig(this.config,this.Qi()),(i=this.exceptionObserver)==null||i.onConfigChange(),(o=this.exceptions)==null||o.onConfigChange(),(a=this.sessionRecording)==null||a.startIfEnabledOrStop(),(l=this.tracingHeaders)==null||l.startIfEnabledOrStop(),(u=this.autocapture)==null||u.startIfEnabled(),(c=this.heatmaps)==null||c.startIfEnabled(),(d=this.exceptionObserver)==null||d.startIfEnabledOrStop(),(h=this.deadClicksAutocapture)==null||h.startIfEnabledOrStop(),(p=this.surveys)==null||p.loadIfEnabled(),this.es(),(f=this.externalIntegrations)==null||f.startIfEnabledOrStop()}}_overrideSDKInfo(e,s){Y.LIB_NAME=e,Y.LIB_VERSION=s}startSessionRecording(e){var s,r,n,i,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)&&((s=this.sessionManager)==null||s.checkAndGetSessionAndWindowId(),l.sampling&&((r=this.sessionRecording)==null||r.overrideSampling()),l.linked_flag&&((n=this.sessionRecording)==null||n.overrideLinkedFlag()),l.url_trigger&&((i=this.sessionRecording)==null||i.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,s){if(this.exceptions){var r=new Error("PostHog syntheticException"),n=this.exceptions.buildProperties(e,{handled:!0,syntheticException:r});return this.exceptions.sendExceptionEvent(b({},n,s))}}addExceptionStep(e,s){var r;(r=this.exceptions)==null||r.addExceptionStep(e,s)}captureLog(e){var s;(s=this.logs)==null||s.captureLog(e)}get logger(){var e,s;return(e=(s=this.logs)==null?void 0:s.logger)!==null&&e!==void 0?e:Te.rs}startExceptionAutocapture(e){this.set_config({capture_exceptions:e==null||e})}stopExceptionAutocapture(){this.set_config({capture_exceptions:!1})}loadToolbar(e){var s,r;return(s=(r=this.toolbar)==null?void 0:r.loadToolbar(e))!==null&&s!==void 0&&s}get_property(e){var s;return(s=this.persistence)==null?void 0:s.props[e]}getSessionProperty(e){var s;return(s=this.sessionPersistence)==null?void 0:s.props[e]}toString(){var e,s=(e=this.config.name)!==null&&e!==void 0?e:os;return s!==os&&(s=os+"."+s),s}_isIdentified(){var e,s;return((e=this.persistence)==null?void 0:e.get_property(He))===Tt||((s=this.sessionPersistence)==null?void 0:s.get_property(He))===Tt}Zn(){var e,s;return!(this.config.person_profiles==="never"||this.config.person_profiles===to&&!this._isIdentified()&&mt(this.getGroups())&&((e=this.persistence)==null||(e=e.props)==null||!e[Bs])&&((s=this.persistence)==null||(s=s.props)==null||!s[rn]))}zn(){return this.config.capture_pageleave===!0||this.config.capture_pageleave==="if_capture_pageview"&&(this.config.capture_pageview===!0||this.config.capture_pageview==="history_change")}createPersonProfile(){this.Zn()||this.Gn("posthog.createPersonProfile")&&this.setPersonProperties({},{})}setInternalOrTestUser(){this.Gn("posthog.setInternalOrTestUser")&&this.setPersonProperties({$internal_or_test_user:!0})}Gn(e){return this.config.person_profiles==="never"?(k.error(e+' was called, but process_person is set to "never". This call will be ignored.'),!1):(this.Kn(rn,!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!==Ht)}es(){var e,s,r,n,i=this.En();return((e=this.persistence)==null?void 0:e.xi)!==i&&((r=this.persistence)==null||r.set_disabled(i)),((s=this.sessionPersistence)==null?void 0:s.xi)!==i&&((n=this.sessionPersistence)==null||n.set_disabled(i)),i&&(this.yn.clear(),this.Qn()),i}opt_in_capturing(e){var s;if(this.config.cookieless_mode!==ht){if(this.gn()){var r,n,i,o,a;this.Yn(!0,!0),(r=this.sessionManager)==null||r.destroy(),(n=this.pageViewManager)==null||n.destroy(),this.sessionManager=new xl(this),this.pageViewManager=new fl(this),this.persistence&&(this.sessionPropsManager=new Sl(this,this.sessionManager,this.persistence));var l,u=(i=(o=this.config.__extensionClasses)==null?void 0:o.sessionRecording)!==null&&i!==void 0?i:(a=Te.__defaultExtensionClasses)==null?void 0:a.sessionRecording;u&&(this.sessionRecording=this.pn(this.sessionRecording,new u(this)),this.hn&&((l=this.sessionRecording)==null||l.onRemoteConfig==null||l.onRemoteConfig(this.hn)))}var c,d;this.consent.optInOut(!0),this.es(),this.Bn(),(s=this.sessionRecording)==null||s.startIfEnabledOrStop(),this.config.cookieless_mode==Ht&&((c=this.surveys)==null||c.loadIfEnabled()),(x(e?.captureEventName)||e!=null&&e.captureEventName)&&this.capture((d=e?.captureEventName)!==null&&d!==void 0?d:"$opt_in",e?.captureProperties,{send_instantly:!0}),this.config.capture_pageview&&this.Hn()}else k.warn(Cl)}opt_out_capturing(){var e,s,r;this.config.cookieless_mode!==ht?(this.config.cookieless_mode===Ht&&this.consent.isOptedIn()&&this.Yn(!0,!0),this.consent.optInOut(!1),this.es(),this.config.cookieless_mode===Ht&&(this.register({distinct_id:br,$device_id:null}),(e=this.sessionRecording)==null||e.stopRecording(),this.sessionRecording=void 0,(s=this.sessionManager)==null||s.destroy(),(r=this.pageViewManager)==null||r.destroy(),this.sessionManager=void 0,this.sessionPropsManager=void 0,this.config.capture_pageview&&this.Hn(),this.Bn())):k.warn(Cl)}has_opted_in_capturing(){return this.consent.isOptedIn()}has_opted_out_capturing(){return this.consent.isOptedOut()}get_explicit_consent_status(){var e=this.consent.consent;return e===1?"granted":e===0?"denied":"pending"}is_capturing(){return this.config.cookieless_mode===ht||(this.config.cookieless_mode===Ht?this.consent.isRejected()||this.consent.isOptedIn():!this.has_opted_out_capturing())}clear_opt_in_out_capturing(){this.consent.reset(),this.es()}_is_bot(){return ke?Qu(ke,this.config.custom_blocked_useragents):void 0}Hn(){C&&(C.visibilityState==="visible"?this.wn||(this.wn=!0,this.capture(is,{title:C.title},{send_instantly:!0}),this.kn&&(C.removeEventListener(nn,this.kn),this.kn=null)):this.kn||(this.kn=this.Hn.bind(this),ne(C,nn,this.kn)))}debug(e){e===!1?(v?.console.log("You've disabled debug mode."),this.set_config({debug:!1})):(v?.console.log("You're now in debug mode. All calls to PostHog will be logged in your console.\nYou can disable this with `posthog.debug(false)`."),this.set_config({debug:!0}))}Qi(){var e=this.Mn||{};return"advanced_disable_flags"in e?!!e.advanced_disable_flags:this.config.advanced_disable_flags!==!1?!!this.config.advanced_disable_flags:this.config.advanced_disable_decide===!0?(k.warn("Config field 'advanced_disable_decide' is deprecated. Please use 'advanced_disable_flags' instead. The old field will be removed in a future major version."),!0):(function(s,r,n,i,o){var a=r in s&&!D(s[r]),l=n in s&&!D(s[n]);return a?s[r]:!!l&&(o&&o.warn("Config field '"+n+"' is deprecated. Please use '"+r+"' instead. The old field will be removed in a future major version."),s[n])})(e,"advanced_disable_flags","advanced_disable_decide",0,k)}Pt(e){var s;if(D(this.config.before_send))return e;var r=Object.keys((s=e.properties)!==null&&s!==void 0?s:{}).filter(mh),n=L(this.config.before_send)?this.config.before_send:[this.config.before_send],i=e;for(var o of n){if(i=o(i),D(i)){var a="Event '"+e.event+"' was rejected in beforeSend function";return gh(e.event)?k.warn(a+". This can cause unexpected behavior."):k.info(a),null}i.properties&&!mt(i.properties)||k.warn("Event '"+e.event+"' has no properties after beforeSend function, this is likely an error.")}for(var l of r)if(i.properties&&D(i.properties[l]))return k.warn("Event '"+e.event+"' had its '"+l+"' property removed in a beforeSend function. This property is required for ingestion, so the event will be dropped."),null;return i}getPageViewId(){var e;return(e=this.pageViewManager.ui)==null?void 0:e.pageViewId}captureTraceFeedback(e,s){this.capture("$ai_feedback",{$ai_trace_id:String(e),$ai_feedback_text:s})}captureTraceMetric(e,s,r){this.capture("$ai_metric",{$ai_trace_id:String(e),$ai_metric_name:s,$ai_metric_value:String(r)})}Cn(e){var s=Ke(e)&&!e,r=Q.N()&&Q.P("ph_debug")==="true";return!s&&(!!r||e)}}Te.__defaultExtensionClasses={},Te.rs=(()=>{var t=()=>{};return{trace:t,debug:t,info:t,warn:t,error:t,fatal:t}})(),(function(t,e){for(var s=0;e.length>s;s++)t.prototype[e[s]]=np(t.prototype[e[s]])})(Te,["identify"]);class Al{constructor(e){this.disabled=e===!1;var s=te(e)?e:{};this.thresholdPx=s.threshold_px||30,this.timeoutMs=s.timeout_ms||1e3,this.clickCount=s.click_count||3,this.clicks=[]}isRageClick(e,s,r){if(this.disabled)return!1;var n=this.clicks[this.clicks.length-1];if(n&&Math.abs(e-n.x)+Math.abs(s-n.y)r-n.timestamp){if(this.clicks.push({x:e,y:s,timestamp:r}),this.clicks.length===this.clickCount)return!0}else this.clicks=[{x:e,y:s,timestamp:r}];return!1}}var yi="$copy_autocapture",wi=se("[AutoCapture]");function bi(t,e){return e.length>t?e.slice(0,t)+"...":e}function cf(t){if(t.previousElementSibling)return t.previousElementSibling;var e=t;do e=e.previousSibling;while(e&&!Ft(e));return e}function uf(t,e){var s,r,n=e.e,i=e.maskAllElementAttributes,o=e.maskAllText,a=e.elementAttributeIgnoreList,l=e.elementsChainAsString,u=e.disableCaptureUrlHashes;if(!Ft(t))return{props:{}};for(var c=[t],d=new Set([t]),h=t;h.parentNode&&!Me(h,"body")&&Su>c.length;)if(Eu(h.parentNode)){var p=h.parentNode.host;if(d.has(p))break;d.add(p),c.push(p),h=p}else{if(!Ft(h.parentNode)||d.has(h.parentNode))break;d.add(h.parentNode),c.push(h.parentNode),h=h.parentNode}var f,g,m=[],_={},w=!1,E=!1;if(Z(c,(S=>{var A=no(S);if(Me(S,"a")){var R=S.getAttribute("href");w=!!(A&&R&&Ks(R))&&(u?Ct(R):R)}M(ln(S),"ph-no-capture")&&(E=!0),m.push((function(T,O,J,z,H){H===void 0&&(H=!1);var oe=T.tagName.toLowerCase(),pe={tag_name:oe};Ko.indexOf(oe)>-1&&!J&&(pe.$el_text=oe.toLowerCase()==="a"||oe.toLowerCase()==="button"?bi(1024,dl(T)):bi(1024,rr(T)));var Ie=ln(T);Ie.length>0&&(pe.classes=Ie.filter((function(ae){return ae!==""}))),Z(T.attributes,(function(ae){var me;if((!Fu(T)||["name","id","class","aria-label"].indexOf(ae.name)!==-1)&&(z==null||!z.includes(ae.name))&&!O&&Ks(ae.value)&&(!W(me=ae.name)||me.substring(0,10)!=="_ngcontent"&&me.substring(0,7)!=="_nghost")){var ge=ae.value;ae.name==="class"&&(ge=Go(ge).join(" ")),pe["attr__"+ae.name]=bi(1024,ae.name==="href"&&H?Ct(ge):ge)}}));for(var _e=1,Ce=1,Re=T;Re=cf(Re);)_e++,Re.tagName===T.tagName&&Ce++;return pe.nth_child=_e,pe.nth_of_type=Ce,pe})(S,i,o,a,u));var N=(function(T){if(!no(T))return{};var O={};return Z(T.attributes,(function(J){if(J.name&&J.name.indexOf("data-ph-capture-attribute")===0){var z=J.name.replace("data-ph-capture-attribute-",""),H=J.value;z&&H&&Ks(H)&&(O[z]=H)}})),O})(S);ee(_,N)})),E)return{props:{},explicitNoCapture:E};if(o||(m[0].$el_text=Me(t,"a")||Me(t,"button")?dl(t):rr(t)),w){var I,F;m[0].attr__href=w;var P=(I=cn(w))==null?void 0:I.host,B=v==null||(F=v.location)==null?void 0:F.host;P&&B&&P!==B&&(f=w)}return{props:ee({$event_type:n.type,$ce_version:1},l?{}:{$elements:m},{$elements_chain:(g=m,(function(S){return S.map((A=>{var R,N,T="";if(A.tag_name&&(T+=A.tag_name),A.attr_class)for(var O of(A.attr_class.sort(),A.attr_class))T+="."+O.replace(/"/g,"");var J=b({},A.text?{text:A.text}:{},{"nth-child":(R=A.nth_child)!==null&&R!==void 0?R:0,"nth-of-type":(N=A.nth_of_type)!==null&&N!==void 0?N:0},A.href?{href:A.href}:{},A.attr_id?{attr_id:A.attr_id}:{},A.attributes),z={};return Or(J).sort(((H,oe)=>H[0].localeCompare(oe[0]))).forEach((H=>{var oe=H[1];return z[hl(H[0].toString())]=hl(oe.toString())})),(T+=":")+Or(z).map((H=>H[0]+'="'+H[1]+'"')).join("")})).join(";")})((function(S){return S.map((A=>{var R,N,T={text:(R=A.$el_text)==null?void 0:R.slice(0,400),tag_name:A.tag_name,href:(N=A.attr__href)==null?void 0:N.slice(0,2048),attr_class:Sp(A),attr_id:A.attr__id,nth_child:A.nth_child,nth_of_type:A.nth_of_type,attributes:{}};return Or(A).filter((O=>O[0].indexOf("attr__")===0)).forEach((O=>T.attributes[O[0]]=O[1])),T}))})(g)))},(s=m[0])!=null&&s.$el_text?{$el_text:(r=m[0])==null?void 0:r.$el_text}:{},f&&n.type==="click"?{$external_click_url:f}:{},_)}}var Ms=se("[ExceptionAutocapture]"),$l=()=>{},df=se("[TracingHeaders]"),Lt=se("[Web Vitals]"),Rl=9e5,Tl="disabled",Nl="lazy_loading",Ls="awaiting_config",Fr="missing_config";se("[SessionRecording]"),se("[SessionRecording]");var po="[SessionRecording]",at=se(po),hf=se("[Heatmaps]");function Ei(t){return te(t)&&"clientX"in t&&"clientY"in t&&he(t.clientX)&&he(t.clientY)}var Pr=se("[Product Tours]"),Si=t=>{var e;return!t.config.disable_product_tours&&!((e=t.persistence)==null||!e.get_property(Wo))},pf=["$set_once","$set"],Ze=se("[SiteApps]"),Ml="Error while initializing PostHog app with config id ";function rs(t,e,s){if(D(t))return!1;switch(s){case"exact":return t===e;case"contains":var r=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/_/g,".").replace(/%/g,".*");return new RegExp(r,"i").test(t);case"regex":try{return new RegExp(e).test(t)}catch{return!1}default:return!1}}class ff{constructor(e){this.ns=new Xo,this.ss=(s,r)=>this.os(s,r)&&this.ls(s,r)&&this.us(s,r)&&this.hs(s,r),this.os=(s,r)=>r==null||!r.event||s?.event===r?.event,this._instance=e,this.ds=new Set,this.vs=new Set}init(){var e,s;x((e=this._instance)==null?void 0:e._addCaptureHook)||(s=this._instance)==null||s._addCaptureHook(((r,n)=>{this.on(r,n)}))}register(e){var s,r;if(!x((s=this._instance)==null?void 0:s._addCaptureHook)&&(e.forEach((o=>{var a,l;(a=this.vs)==null||a.add(o),(l=o.steps)==null||l.forEach((u=>{var c;(c=this.ds)==null||c.add(u?.event||"")}))})),(r=this._instance)!=null&&r.autocapture)){var n,i=new Set;e.forEach((o=>{var a;(a=o.steps)==null||a.forEach((l=>{l!=null&&l.selector&&i.add(l?.selector)}))})),(n=this._instance)==null||n.autocapture.setElementSelectors(i)}}on(e,s){var r;s!=null&&e.length!=0&&(this.ds.has(e)||this.ds.has(s.event))&&this.vs&&((r=this.vs)==null?void 0:r.size)>0&&this.vs.forEach((n=>{this.cs(s,n)&&this.ns.emit("actionCaptured",n.name)}))}fs(e){this.onAction("actionCaptured",(s=>e(s)))}cs(e,s){if(s?.steps==null)return!1;for(var r of s.steps)if(this.ss(e,r))return!0;return!1}onAction(e,s){return this.ns.on(e,s)}ls(e,s){if(s!=null&&s.url){var r,n=e==null||(r=e.properties)==null?void 0:r.$current_url;if(!n||typeof n!="string"||!rs(n,s.url,s.url_matching||"contains"))return!1}return!0}us(e,s){return!!this.ps(e,s)&&!!this.gs(e,s)&&!!this.ys(e,s)}ps(e,s){var r;if(s==null||!s.href)return!0;var n=this.bs(e);if(n.length>0)return n.some((a=>rs(a.href,s.href,s.href_matching||"exact")));var i,o=(e==null||(r=e.properties)==null?void 0:r.$elements_chain)||"";return!!o&&rs((i=o.match(/(?::|")href="(.*?)"/))?i[1]:"",s.href,s.href_matching||"exact")}gs(e,s){var r;if(s==null||!s.text)return!0;var n=this.bs(e);if(n.length>0)return n.some((u=>rs(u.text,s.text,s.text_matching||"exact")||rs(u.$el_text,s.text,s.text_matching||"exact")));var i,o,a,l=(e==null||(r=e.properties)==null?void 0:r.$elements_chain)||"";return!!l&&(i=(function(u){for(var c,d=[],h=/(?::|")text="(.*?)"/g;!D(c=h.exec(u));)d.includes(c[1])||d.push(c[1]);return d})(l),o=s.text,a=s.text_matching||"exact",i.some((u=>rs(u,o,a))))}ys(e,s){var r,n;if(s==null||!s.selector)return!0;var i=e==null||(r=e.properties)==null?void 0:r.$element_selectors;if(i!=null&&i.includes(s.selector))return!0;var o=(e==null||(n=e.properties)==null?void 0:n.$elements_chain)||"";if(s.selector_regex&&o)try{return new RegExp(s.selector_regex).test(o)}catch{return!1}return!1}bs(e){var s;return(e==null||(s=e.properties)==null?void 0:s.$elements)==null?[]:e?.properties.$elements}hs(e,s){return s==null||!s.properties||s.properties.length===0||sd(s.properties.reduce(((r,n)=>{var i=L(n.value)?n.value.map(String):n.value!=null?[String(n.value)]:[];return r[n.key]={values:i,operator:n.operator||"exact"},r}),{}),e?.properties)}}class gf{constructor(e){var s;this._s=[],this._instance=e,this.ws=new Map,this.ks=new Map,this.xs=new Map,(s=this._instance)==null||s.onSessionId==null||s.onSessionId((r=>this.Ss(r)))}Cs(e){return!1}Ms(){return null}Ts(e){}Es(){}Is(e,s){return!!e&&sd(e.propertyFilters,s?.properties)}Ps(e,s){var r=new Map;return e.forEach((n=>{var i;(i=n.conditions)==null||(i=i[s])==null||(i=i.values)==null||i.forEach((o=>{if(o!=null&&o.name){var a=r.get(o.name)||[];a.push(n.id),r.set(o.name,a)}}))})),r}Rs(e,s,r){var n=(r===As.Activation?this.ws:this.ks).get(e),i=[];return this.As((o=>{i=o.filter((a=>n?.includes(a.id)))})),i.filter((o=>{var a,l=(a=o.conditions)==null||(a=a[r])==null||(a=a.values)==null?void 0:a.find((u=>u.name===e));return this.Is(l,s)}))}register(e){var s;x((s=this._instance)==null?void 0:s._addCaptureHook)||(this.Fs(e),this.Ls(e))}Ls(e){var s=e.filter((r=>{var n,i;return((n=r.conditions)==null?void 0:n.actions)&&((i=r.conditions)==null||(i=i.actions)==null||(i=i.values)==null?void 0:i.length)>0}));s.length!==0&&(this.Os==null&&(this.Os=new ff(this._instance),this.Os.init(),this.Os.fs((r=>{this.onAction(r)}))),s.forEach((r=>{var n,i,o,a,l;r.conditions&&(n=r.conditions)!=null&&n.actions&&(i=r.conditions)!=null&&(i=i.actions)!=null&&i.values&&((o=r.conditions)==null||(o=o.actions)==null||(o=o.values)==null?void 0:o.length)>0&&((a=this.Os)==null||a.register(r.conditions.actions.values),(l=r.conditions)==null||(l=l.actions)==null||(l=l.values)==null||l.forEach((u=>{if(u&&u.name){var c=this.xs.get(u.name);c&&c.push(r.id),this.xs.set(u.name,c||[r.id])}})))})))}Fs(e){var s,r=e.filter((i=>{var o,a;return((o=i.conditions)==null?void 0:o.events)&&((a=i.conditions)==null||(a=a.events)==null||(a=a.values)==null?void 0:a.length)>0})),n=e.filter((i=>{var o,a;return((o=i.conditions)==null?void 0:o.cancelEvents)&&((a=i.conditions)==null||(a=a.cancelEvents)==null||(a=a.values)==null?void 0:a.length)>0}));r.length===0&&n.length===0||((s=this._instance)==null||s._addCaptureHook(((i,o)=>{this.onEvent(i,o)})),this.ws=this.Ps(e,As.Activation),this.ks=this.Ps(e,As.Cancellation))}onEvent(e,s){var r,n,i=this.Ds(),o=(s==null||(r=s.properties)==null?void 0:r.$survey_id)||(s==null||(n=s.properties)==null?void 0:n.$product_tour_id);if(o&&this.getActivatedIds().includes(o)){var a=this.$s(e,o);if(a==="consume")return i.info("event consumed activated item, removing it",{event:e,itemId:o}),void this.Ns([o]);if(a==="persist")return i.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,s,As.Cancellation);l.length>0&&(i.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)){i.info("event name matched",{event:e,eventPayload:s,items:this.ws.get(e)});var u=this.Rs(e,s,As.Activation);this.Hs(u.map((c=>c.id)))}}onAction(e){this.xs.has(e)&&this.Hs(this.xs.get(e)||[])}Hs(e){var s;if(e.length!==0){var r=!((s=this._instance)==null||s.get_session_id==null||!s.get_session_id()),n=[];for(var i of e)r&&this.Cs(i)?this.qs(i)&&this.Us(i):n.push(i);n.length>0&&(this._s=[...new Set([...this._s,...n])]),this.Ds().info("updating activated items",{activatedItems:this.getActivatedIds()})}}qs(e){this._s=this._s.filter((r=>r!==e));var s=this.zs();return!s.includes(e)&&(this.Ws([...s,e]),this.Vs(),!0)}Ns(e){var s=new Set(e);this._s=this._s.filter((i=>!s.has(i)));var r=this.Zs(),n=r.filter((i=>!s.has(i)));n.length!==r.length&&(this.Ws(n),n.length===0&&this.Gs()),this.js(e)}Qs(){var e,s=this.Ms();if(!s)return{};var r=(e=this._instance)==null||(e=e.persistence)==null?void 0:e.props[s];return r&&typeof r=="object"?r:{}}Us(e){if(this.Ms()){var s=this.Qs();this.Ts(b({},s,{[e]:Date.now()}))}}js(e){if(this.Ms()){var s=this.Qs(),r={},n=!1;for(var i of Object.entries(s)){var o=i[0],a=i[1];e.includes(o)?n=!0:r[o]=a}n&&(mt(r)?this.Es():this.Ts(r))}}Ks(){this.Ms()&&this.Es()}getActivationTimestamp(e){if(this.zs().includes(e)){var s=this.Qs()[e];return he(s)?s:void 0}}Zs(){var e,s=this.Js();return((e=this._instance)==null||(e=e.persistence)==null?void 0:e.props[s])||[]}zs(){var e,s,r=this.Zs();if(r.length===0)return[];var n=(e=this._instance)==null||(e=e.persistence)==null?void 0:e.props[this.Ys()],i=(s=this._instance)==null||s.get_session_id==null?void 0:s.get_session_id();return i&&n===i?r:[]}Vs(){var e,s=(e=this._instance)==null||e.get_session_id==null?void 0:e.get_session_id();s&&this.Xs(s)}Gs(){this.ta()}Ss(e){var s,r=(s=this._instance)==null||(s=s.persistence)==null?void 0:s.props[this.Ys()];if(r&&r!==e){var n=this.Zs(),i=this.Qs();n.length>0&&(this.Ws([]),n.filter((o=>he(i[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 mf extends gf{constructor(e){super(e)}Js(){return Yi}Ys(){return Nr}Ms(){return Mr}Ts(e){var s;(s=this._instance)==null||(s=s.persistence)==null||s.register({[Mr]:e})}Es(){var e;(e=this._instance)==null||(e=e.persistence)==null||e.unregister(Mr)}Cs(e){var s,r;this.As((i=>{r=i.find((o=>o.id===e))}));var n=(s=r)==null||(s=s.appearance)==null?void 0:s.surveyPopupDelaySeconds;return he(n)&&n>0}ra(){return ft.SHOWN}As(e){var s;(s=this._instance)==null||s.getSurveys(e)}Bs(e){var s;(s=this._instance)==null||s.cancelPendingSurvey(e)}Ds(){return q}Ws(e){var s;(s=this._instance)==null||(s=s.persistence)==null||s.register({[Yi]:e})}Xs(e){var s;(s=this._instance)==null||(s=s.persistence)==null||s.register({[Nr]:e})}ta(){var e;(e=this._instance)==null||(e=e.persistence)==null||e.unregister(Nr)}ea(){return!1}$s(e,s){var r;this.As((i=>{r=i.find((o=>o.id===s))}));var n=!r||(function(i){var o;return rd(i)&&!((o=i.conditions)==null||(o=o.events)==null||!o.repeatedActivation)||i.schedule==="always"})(r);return n?e===ft.SHOWN?"consume":"ignore":e===ft.SHOWN?"persist":e===ft.DISMISSED||e===ft.SENT?"consume":"ignore"}getSurveys(){return this.getActivatedIds()}getEventToSurveys(){return this.getEventToItemsMap()}}var Ar="SDK is not enabled or survey functionality is not yet loaded",Ll="Disabled. Not loading surveys.",vf=v!=null&&v.location?un(v.location.hash,"__posthog")||un(location.hash,"state"):null,Ol="_postHogToolbarParams",Dl=se("[Toolbar]"),Bl=se("[FeatureFlags]");class _f{constructor(e,s){s===void 0&&(s=!1),this.na=!1,this.update(e,s)}update(e,s){this.sa=((r,n)=>{var i,o,a,l;return{bootstrap:{featureFlags:(i=r.bootstrap)==null?void 0:i.featureFlags,featureFlagPayloads:(o=r.bootstrap)==null?void 0:o.featureFlagPayloads},remoteRequestsDisabled:n,featureFlagsDisabled:!!r.advanced_disable_feature_flags,onlyEvaluateSurveyFeatureFlags:!!r.advanced_only_evaluate_survey_feature_flags,deduplicateCallsPerSession:!!r.advanced_feature_flags_dedup_per_session,cacheTtlMs:r.feature_flag_cache_ttl_ms,requestTimeoutMs:r.feature_flag_request_timeout_ms,compression:r.disable_compression?"none":"base64",evaluationContexts:(a=(l=r.evaluation_contexts)!==null&&l!==void 0?l:r.evaluation_environments)!==null&&a!==void 0?a:[],flagKeys:L(r.flag_keys)?r.flag_keys:void 0}})(e,s),!e.evaluation_environments||e.evaluation_contexts||this.na||(Bl.warn("evaluation_environments is deprecated. Use evaluation_contexts instead. evaluation_environments will be removed in a future version."),this.na=!0),x(e.flag_keys)||L(e.flag_keys)||Bl.error("Invalid flag_keys found:",e.flag_keys,"Expected array of non-empty strings")}get(){return this.sa}}var jl=se("[FeatureFlags]"),Ot=se("[FeatureFlags]",{debugEnabled:!0}),xi=`" failed. Feature flags didn't load in time.`,Ul="connection_error",Hl=t=>{for(var e={},s=0;t.length>s;s++)e[t[s]]=!0;return e},Wl=t=>{var e={};for(var s of Or(t||{})){var r=s[1];r&&(e[s[0]]=r)}return e},Xe=se("[Error tracking]"),zl="Refusing to render web experiment since the viewer is a likely bot",yf={icontains:(t,e)=>e.toLowerCase().indexOf(t.toLowerCase())>-1,not_icontains:(t,e)=>e.toLowerCase().indexOf(t.toLowerCase())===-1,regex:(t,e)=>pn(e,t),not_regex:(t,e)=>!pn(e,t),exact:(t,e)=>e===t,is_not:(t,e)=>e!==t};class ye{get Ne(){return this._instance.config}constructor(e){var s=this;this.getWebExperimentsAndEvaluateDisplayLogic=function(r){r===void 0&&(r=!1),s.getWebExperiments((n=>{ye.aa("retrieved web experiments from the server"),s.oa=new Map,n.forEach((i=>{if(i.feature_flag_key){var o;s.oa&&(ye.aa("setting flag key ",i.feature_flag_key," to web experiment ",i),(o=s.oa)==null||o.set(i.feature_flag_key,i));var a=s._instance.getFeatureFlag(i.feature_flag_key);W(a)&&i.variants[a]&&s.la(i.name,a,i.variants[a].transforms)}else if(i.variants)for(var l in i.variants){var u=i.variants[l];ye.ua(u,s._instance)&&s.la(i.name,l,u.transforms)}}))}),r)},this._instance=e,this._instance.onFeatureFlags((r=>{this.onFeatureFlags(r)}))}initialize(){}onFeatureFlags(e){if(this._is_bot())ye.aa(zl);else if(!this.Ne.disable_web_experiments){if(D(this.oa))return this.oa=new Map,this.loadIfEnabled(),void this.previewWebExperiment();ye.aa("applying feature flags",e),e.forEach((s=>{var r;if(this.oa&&(r=this.oa)!=null&&r.has(s)){var n,i=this._instance.getFeatureFlag(s),o=(n=this.oa)==null?void 0:n.get(s);i&&o!=null&&o.variants[i]&&this.la(o.name,i,o.variants[i].transforms)}}))}}previewWebExperiment(){var e=ye.getWindowLocation();if(e!=null&&e.search){var s=ms(e?.search,"__experiment_id"),r=ms(e?.search,"__experiment_variant");s&&r&&(ye.aa("previewing web experiments "+s+" && "+r),this.getWebExperiments((n=>{this.ha(parseInt(s),r,n)}),!1,!0))}}loadIfEnabled(){this.Ne.disable_web_experiments||this.getWebExperimentsAndEvaluateDisplayLogic()}getWebExperiments(e,s,r){if(this.Ne.disable_web_experiments&&!r)return e([]);var n=this._instance.get_property("$web_experiments");if(n&&!s)return e(n);this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/web_experiments/?token="+this.Ne.token),method:"GET",timestampMode:"query",callback:i=>e(i.statusCode===200&&i.json&&i.json.experiments||[])})}ha(e,s,r){var n=r.filter((i=>i.id===e));n&&n.length>0&&(ye.aa("Previewing web experiment ["+n[0].name+"] with variant ["+s+"]"),this.la(n[0].name,s,n[0].variants[s].transforms))}static ua(e,s){return!D(e.conditions)&&ye.da(e,s)&&ye.va(e)}static da(e,s){var r;if(D(e.conditions)||D((r=e.conditions)==null?void 0:r.url))return!0;var n=ye.getWindowLocation();if(n){var i,o,a,l=yu(s,n.href);return(i=e.conditions)==null||!i.url||yf[(o=(a=e.conditions)==null?void 0:a.urlMatchType)!==null&&o!==void 0?o:"icontains"](e.conditions.url,l)}return!1}static getWindowLocation(){return v?.location}static va(e){var s;if(D(e.conditions)||D((s=e.conditions)==null?void 0:s.utm))return!0;var r=Nu();if(r.utm_source){var n,i,o,a,l,u,c,d,h=(n=e.conditions)==null||(n=n.utm)==null||!n.utm_campaign||((i=e.conditions)==null||(i=i.utm)==null?void 0:i.utm_campaign)==r.utm_campaign,p=(o=e.conditions)==null||(o=o.utm)==null||!o.utm_source||((a=e.conditions)==null||(a=a.utm)==null?void 0:a.utm_source)==r.utm_source,f=(l=e.conditions)==null||(l=l.utm)==null||!l.utm_medium||((u=e.conditions)==null||(u=u.utm)==null?void 0:u.utm_medium)==r.utm_medium,g=(c=e.conditions)==null||(c=c.utm)==null||!c.utm_term||((d=e.conditions)==null||(d=d.utm)==null?void 0:d.utm_term)==r.utm_term;return h&&f&&g&&p}return!1}static aa(e){for(var s=arguments.length,r=new Array(s>1?s-1:0),n=1;s>n;n++)r[n-1]=arguments[n];k.info("[WebExperiments] "+e,r)}la(e,s,r){this._is_bot()?ye.aa(zl):s!=="control"?r.forEach((n=>{if(n.selector){var i;ye.aa("applying transform of variant "+s+" for experiment "+e+" ",n);var o=(i=document)==null?void 0:i.querySelectorAll(n.selector);o?.forEach((a=>{var l=a;n.html&&(l.innerHTML=n.html),n.css&&l.setAttribute("style",n.css)}))}})):ye.aa("Control variants leave the page unmodified.")}_is_bot(){return ke&&this._instance?Qu(ke,this.Ne.custom_blocked_useragents):void 0}}var Ue=se("[Conversations]"),Dt="Conversations not available yet.",ql="console",ld="__posthogHandledLogsRequestError",ki=(t,e)=>{var s=t instanceof Error?t:new Error(e);return s[ld]=!0,s},Vl=t=>!!t&&typeof t=="object"&&t[ld]===!0,Rn={featureFlags:class{constructor(t){this.name="featureFlags",this.ca=!1,this.featureFlagEventHandlers=[],this.rt=jl,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 _f(t.config,t.Qi()),this.Ta=this.Ea)}updateConfig(t,e){var s;(s=this.Ea)==null||s.update(t,e)}setup(t){return this.Ia=t,this.rt=t.logger.createLogger("[FeatureFlags]"),s=()=>{this.Ia===t&&(this.Ia=void 0,this.nn=t,this.Pa(t))},(e=t.kv.initialize())!=null&&e.then?e.then(s):s();var e,s}Pa(t){if(this.nn===t)return v&&ne(v,"online",this.Ca),this.Ra=t.registerDynamicEventProperties((()=>this.Aa()?this.fa:this.pa)),this.Fa(),this.initialize()}destroy(){v?.removeEventListener("online",this.Ca)}dispose(){var t;this.ba++,this.wa=!1,this.Ia=void 0,this.nn&&(this.La(),(t=this.Ra)==null||t.dispose(),this.Ra=void 0,this.ga=[],v?.removeEventListener("online",this.Ca),this.nn=void 0)}get Ne(){return this.Ta.get()}Oa(t){var e;return(e=this.nn)==null?void 0:e.kv.get(t)}F(t){this.Da((()=>{var e;return(e=this.nn)==null?void 0:e.kv.set(t)}))}q(t){this.Da((()=>{var e;return(e=this.nn)==null?void 0:e.kv.remove(t)}))}Da(t){try{t()}catch(e){this.rt.error("Failed to update feature flag persistence",e)}}Fa(){var t={};for(var e of[Us,Hs,Tr,et]){var s=this.Oa(e);x(s)||(t[e]=s)}this.fa=t;var r=b({},t),n=this.Oa(Bt);if(n)for(var i of Object.entries(n))r["$feature/"+i[0]]=i[1];this.pa=r}Aa(){var t=this.Ne.cacheTtlMs;if(!t||0>=t)return!1;var e=this.Oa(Gs);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 s=e&&typeof e=="string"&&e.trim().length>0;return s||this.rt.error("Invalid evaluation context found:",e,"Expected non-empty string"),s})):[]}qa(){var t=this.Ne.flagKeys;if(!x(t))return t.filter((e=>{var s=e&&typeof e=="string"&&e.trim().length>0;return s||this.rt.error("Invalid flag key found:",e,"Expected non-empty string"),s}))}initialize(){var t,e,s=this.Ne,r=(t=(e=s.bootstrap)==null?void 0:e.featureFlags)!==null&&t!==void 0?t:{};if(Object.keys(r).length){var n,i,o=(n=(i=s.bootstrap)==null?void 0:i.featureFlagPayloads)!==null&&n!==void 0?n:{},a=Object.keys(r).filter((u=>!!r[u])).reduce(((u,c)=>(u[c]=r[c]||!1,u)),{}),l=Object.keys(o).filter((u=>a[u])).reduce(((u,c)=>(o[c]&&(u[c]=o[c]),u)),{});return this.ja({featureFlags:a,featureFlagPayloads:l})}}updateFlags(t,e,s){var r,n,i=s!=null&&s.merge&&(r=this.Oa(Bt))!==null&&r!==void 0?r:{},o=s!=null&&s.merge&&(n=this.Oa(Hs))!==null&&n!==void 0?n:{},a=b({},i,t),l=b({},o,e),u={};for(var c of Object.entries(a)){var d=c[0],h=c[1];u[d]={key:d,enabled:Da(h),variant:Ba(h),reason:void 0,metadata:x(l?.[d])?void 0:{id:0,version:void 0,description:void 0,payload:l[d]}}}this.ja({flags:u})}get hasLoadedFlags(){return this.ma}getFlags(){return Object.keys(this.getFlagVariants())}getFlagsWithDetails(){var t=this.Oa(Ki),e=this.Oa(et),s=this.Oa(jt);if(!s&&!e)return t||{};var r=ee({},t||{}),n=[...new Set([...Object.keys(s||{}),...Object.keys(e||{})])];for(var i of n){var o,a,l=r[i],u=e?.[i],c=x(u)?(o=l?.enabled)!==null&&o!==void 0&&o:!!u,d=x(u)?l?.variant:typeof u=="string"?u:void 0,h=s?.[i],p=b({},l,{enabled:c,variant:c?d??l?.variant:void 0});c!==l?.enabled&&(p.original_enabled=l?.enabled),d!==l?.variant&&(p.original_variant=l?.variant),h&&(p.metadata=b({},l?.metadata,{payload:h,original_payload:l==null||(a=l.metadata)==null?void 0:a.payload})),r[i]=p}return this.ca||(this.rt.warn(" Overriding feature flag details!",{flagDetails:t,overriddenPayloads:s,finalDetails:r}),this.ca=!0),r}getAllFeatureFlags(){var t=this.getFlagVariants(),e=this.getFlagPayloads();return Object.keys(t).map((s=>{var r=t[s];return{key:s,enabled:Da(r),variant:Ba(r),payload:Oa(e[s])}}))}getFlagVariants(){var t=this.Oa(Bt),e=this.Oa(et);if(!e)return t||{};for(var s=ee({},t||{}),r=Object.keys(e),n=0;r.length>n;n++)s[r[n]]=e[r[n]];return this.ca||(this.rt.warn(" Overriding feature flags!",{enabledFlags:t,overriddenFlags:e,finalFlags:s}),this.ca=!0),s}getFlagPayloads(){var t=this.Oa(Hs),e=this.Oa(jt);if(!e)return t||{};for(var s=ee({},t||{}),r=Object.keys(e),n=0;r.length>n;n++)s[r[n]]=e[r[n]];return this.ca||(this.rt.warn(" Overriding feature flag payloads!",{flagPayloads:t,overriddenPayloads:e,finalPayloads:s}),this.ca=!0),s}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(Wt)}Ha(t){this.La();var e=this.nn;if(e&&!this.Ne.remoteRequestsDisabled&&!this.Ma())if(this.ya)this.wa=!0;else{var s={token:e.projectToken,distinct_id:e.distinctId,groups:e.groups,$anon_distinct_id:this.$anon_distinct_id,person_properties:b({},e.initialPersonProperties,this.Oa(ct)||{},{$lib:e.library.name,$lib_version:e.library.version}),group_properties:this.Oa(Ut),timezone:ju()};x(e.deviceId)||(s.$device_id=e.deviceId),(t!=null&&t.disableFlags||this.Ne.featureFlagsDisabled)&&(s.disable_flags=!0);var r=this.Na();r.length&&(s.evaluation_contexts=r);var n=this.qa();x(n)||(s.flag_keys=n);var i=this.Ne.onlyEvaluateSurveyFeatureFlags,o="/flags/?v=2"+(i?"&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({[Lr]:[Ul]}),this.rt.error("Feature flag request failed",c)),l()};try{e.sendRequest(o,{target:"flags",method:"POST",body:s,compression:this.Ne.compression==="base64"?xe.Base64:void 0,sentAt:"body",timeoutMs:this.Ne.requestTimeoutMs}).then((c=>{var d,h,p=(d=c.json)!==null&&d!==void 0?d:{},f=c.statusCode!==200;if(this.ya=!1,a===this.ba){if(this.Ua(c.statusCode),f||this.wa||(this.$anon_distinct_id=void 0),!s.disable_flags||this.wa){this.ka=!f;var g=[];c.error?g.push(c.error instanceof Error&&c.error.name==="AbortError"?"timeout":c.error instanceof Error?Ul:"unknown_error"):c.statusCode!==200&&g.push("api_error_"+c.statusCode),p.errorsWhileComputingFlags&&g.push("errors_while_computing_flags");var m=!((h=p.quotaLimited)==null||!h.includes("feature_flags"));m&&g.push("quota_limited"),this.F({[Lr]: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."):s.disable_flags||this.ja(p,f,{partialResponse:i}),l()}}else l()})).catch(u)}catch(c){u(c)}}}Ma(){return Ru(this.Sa,3)}Ua(t){this.Sa=Tu(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 s;if(e===void 0&&(e={}),!e.fresh||this.ka)if(this.ma||this.getFlags()&&this.getFlags().length>0){if(!this.$a()){var r=this.getFeatureFlagResult(t,e);return(s=r?.variant)!==null&&s!==void 0?s:r?.enabled}}else this.rt.warn('getFeatureFlag for key "'+t+xi)}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 s,r=this.getFlagVariants(),n=t in r,i=r[t],o=this.getFlagPayloads()[t],a=String(i),l=this.Oa(Tr)||void 0,u=this.Oa(Gs)||void 0,c=this.Oa(Wt)||{};if(this.Ne.deduplicateCallsPerSession){var d,h=(d=this.nn)==null?void 0:d.session.sessionId,p=this.Oa(zs);h&&h!==p&&(c={},s=h)}if(e.send_event||!("send_event"in e))if(t in c&&c[t].includes(a))s&&this.F({[Wt]:c,[zs]:s});else{var f,g,m,_,w,E,I,F,P,B;L(c[t])?c[t].push(a):c[t]=[a],this.F(b({[Wt]:c},s?{[zs]:s}:{}));var S=this.getFeatureFlagDetails(t),A=[...(f=this.Oa(Lr))!==null&&f!==void 0?f:[]];x(i)&&A.push("flag_missing");var R={$feature_flag:t,$feature_flag_response:i,$feature_flag_payload:o||null,$feature_flag_request_id:l,$feature_flag_evaluated_at:u,$feature_flag_bootstrapped_response:((g=this.Ne.bootstrap)==null||(g=g.featureFlags)==null?void 0:g[t])||null,$feature_flag_bootstrapped_payload:((m=this.Ne.bootstrap)==null||(m=m.featureFlagPayloads)==null?void 0:m[t])||null,$used_bootstrap_value:!this.ka};x(S==null||(_=S.metadata)==null?void 0:_.has_experiment)||(R.$feature_flag_has_experiment=S.metadata.has_experiment),x(S==null||(w=S.metadata)==null?void 0:w.version)||(R.$feature_flag_version=S.metadata.version);var N,T=(E=S==null||(I=S.reason)==null?void 0:I.description)!==null&&E!==void 0?E:S==null||(F=S.reason)==null?void 0:F.code;T&&(R.$feature_flag_reason=T),S!=null&&(P=S.metadata)!=null&&P.id&&(R.$feature_flag_id=S.metadata.id),x(S?.original_variant)&&x(S?.original_enabled)||(R.$feature_flag_original_response=x(S.original_variant)?S.original_enabled:S.original_variant),S!=null&&(B=S.metadata)!=null&&B.original_payload&&(R.$feature_flag_original_payload=S==null||(N=S.metadata)==null?void 0:N.original_payload),A.length&&(R.$feature_flag_error=A.join(",")),this.za(R)}else s&&this.F({[Wt]:c,[zs]:s});if(n)return{key:t,enabled:!!i,variant:typeof i=="string"?i:void 0,payload:Oa(o)}}}else this.rt.warn('getFeatureFlagResult for key "'+t+xi)}za(t){try{var e;(e=this.nn)==null||e.capture("$feature_flag_called",t).catch((s=>{this.rt.error("Failed to capture feature flag call",s)}))}catch(s){this.rt.error("Failed to capture feature flag call",s)}}getRemoteConfigPayload(t,e){this.Wa(t,e)}Wa(t,e){var s=this;return X((function*(){var r=s.nn;if(r){var n={distinct_id:r.distinctId,token:r.projectToken,person_properties:{$lib:r.library.name,$lib_version:r.library.version}},i=s.Na();i.length&&(n.evaluation_contexts=i);var o,a=s.qa();x(a)||(n.flag_keys=a);try{var l,u=(l=(yield r.sendRequest("/flags/?v=2",{target:"flags",method:"POST",body:n,compression:s.Ne.compression==="base64"?xe.Base64:void 0,sentAt:"body",timeoutMs:s.Ne.requestTimeoutMs})).json)==null?void 0:l.featureFlagPayloads;o=u?.[t]||void 0}catch(c){return void s.rt.error("Remote config feature flag request failed",c)}try{e(o)}catch(c){s.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+xi),e.defaultValue;var s=this.getFeatureFlag(t,e);return x(s)?e.defaultValue:!!s}addFeatureFlagsHandler(t){this.featureFlagEventHandlers.push(t)}removeFeatureFlagsHandler(t){this.featureFlagEventHandlers=this.featureFlagEventHandlers.filter((e=>e!==t))}receivedFeatureFlags(t,e,s){this.ja(t,e,s)}ja(t,e,s){if(this.nn){this.ma=!0;var r=(function(n,i,o,a,l,u){i===void 0&&(i={}),o===void 0&&(o={}),a===void 0&&(a={}),u===void 0&&(u=jl);var c=((P,B)=>{var S=P.flags;return S?b({},P,{featureFlags:Object.fromEntries(Object.keys(S).map((A=>{var R;return[A,(R=S[A].variant)!==null&&R!==void 0?R:S[A].enabled]}))),featureFlagPayloads:Object.fromEntries(Object.keys(S).filter((A=>S[A].enabled)).filter((A=>{var R;return(R=S[A].metadata)==null?void 0:R.payload})).map((A=>{var R;return[A,(R=S[A].metadata)==null?void 0:R.payload]})))}):(P.featureFlags&&B.warn("Using an older version of the feature flags endpoint. Please upgrade your PostHog server to the latest version"),P)})(n,u),d=c.flags,h=c.featureFlags,p=c.featureFlagPayloads;if(h){var f=n.requestId,g=n.evaluatedAt;if(L(h)){u.warn("v1 of the feature flags endpoint is deprecated. Please use the latest version.");var m={};if(h)for(var _=0;h.length>_;_++)m[h[_]]=!0;return{[Us]:h,[Bt]:m,[en]:!1}}var w=h,E=p,I=d;if(l!=null&&l.partialResponse)w=b({},i,w),E=b({},o,E),I=b({},a,I);else if(n.errorsWhileComputingFlags)if(d){var F=new Set(Object.keys(d).filter((P=>{var B;return!((B=d[P])!=null&&B.failed)})));w=b({},i,Object.fromEntries(Object.entries(w).filter((P=>F.has(P[0]))))),E=b({},o,Object.fromEntries(Object.entries(E||{}).filter((P=>F.has(P[0]))))),I=b({},a,Object.fromEntries(Object.entries(I||{}).filter((P=>F.has(P[0])))))}else w=b({},i,w),E=b({},o,E),I=b({},a,I);return b({[Us]:Object.keys(Wl(w)),[Bt]:w||{},[Hs]:E||{},[Ki]:I||{},[en]:n.minimalFlagCalledEvents===!0},f?{[Tr]:f}:{},g?{[Gs]:g}:{})}})(t,this.getFlagVariants(),this.getFlagPayloads(),this.getFlagsWithDetails(),s,this.rt);r&&this.F(r),e||(this.xa=!1),this.Va(e)}}override(t,e){e===void 0&&(e=!1),this.rt.warn("override is deprecated. Please use overrideFeatureFlags instead."),this.overrideFeatureFlags({flags:t,suppressWarning:e})}overrideFeatureFlags(t){this.Za(t)}Za(t){if(this.nn){if(t===!1)return this.q([et,jt]),this.Va(),void Ot.info("All overrides cleared");if(L(t))return this.F({[et]:Hl(t)}),this.Va(),void Ot.info("Flag overrides set",{flags:t});if(t&&typeof t=="object"&&("flags"in t||"payloads"in t)){var e,s=t;this.ca=!!((e=s.suppressWarning)!==null&&e!==void 0&&e);var r={},n=s.flags,i=s.payloads;return n&&(r[et]=L(n)?Hl(n):n),i&&(r[jt]=i),Object.keys(r).length&&this.F(r),n===!1&&i===!1?this.q([et,jt]):n===!1?this.q(et):i===!1&&this.q(jt),this.Va(),n===!1?Ot.info("Flag overrides cleared"):n&&Ot.info("Flag overrides set",{flags:n}),void(i===!1?Ot.info("Payload overrides cleared"):i&&Ot.info("Payload overrides set",{payloads:i}))}if(t&&typeof t=="object")return this.F({[et]:t}),this.Va(),void Ot.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(),s=e.flags,r=e.flagVariants;try{t(s,r)}catch(n){this.rt.error("Error while running feature flags callback",n)}}return()=>this.removeFeatureFlagsHandler(t)}updateEarlyAccessFeatureEnrollment(t,e,s){var r=(this.Oa(Rr)||[]).find((l=>l.flagKey===t)),n={["$feature_enrollment/"+t]:e},i={$feature_flag:t,$feature_enrollment:e,$set:n};r&&(i.$early_access_feature_name=r.name),s&&(i.$feature_enrollment_stage=s);var o=b({},this.getFlagVariants(),{[t]:e});this.F({[Us]:Object.keys(Wl(o)),[Bt]:o,[ct]:b({},this.Oa(ct)||{},n)}),this.Va();try{var a;(a=this.nn)==null||a.capture("$feature_enrollment_update",i).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,s){e===void 0&&(e=!1);var r=this.Oa(Rr);!r||e?this.Qa(t,s):t(r)}Qa(t,e){var s=this;return X((function*(){var r=s.nn;if(r){var n,i=e?"&"+e.map((a=>"stage="+a)).join("&"):"";try{var o=yield r.sendRequest("/api/early_access_features/?token="+r.projectToken+i,{target:"api",method:"GET",sentAt:"query"});if(!o.json)return;s.F({[Rr]:n=o.json.earlyAccessFeatures})}catch(a){return void s.rt.error("Early access feature request failed",a)}try{t(n)}catch(a){s.rt.error("Early access feature callback failed",a)}}}))()}Ga(){var t=this.getFlags(),e=this.getFlagVariants();return{flags:t.filter((s=>e[s])),flagVariants:Object.keys(e).filter((s=>e[s])).reduce(((s,r)=>(s[r]=e[r],s)),{})}}Va(t){this.Fa();var e=this.Ga(),s=e.flags,r=e.flagVariants;this.featureFlagEventHandlers.forEach((n=>{try{n(s,r,{errorsLoading:t})}catch(i){this.rt.error("Error while running feature flags callback",i)}}))}setPersonPropertiesForFlags(t,e){e===void 0&&(e=!0),this.Ka(t,e)}Ka(t,e){e===void 0&&(e=!0);var s=this.Oa(ct)||{},r=t?.$set||(t!=null&&t.$set_once?{}:t),n=t?.$set_once,i={};if(n)for(var o in n)({}).hasOwnProperty.call(n,o)&&(o in s||(i[o]=n[o]));this.F({[ct]:b({},s,i,r)}),e&&this.reloadFeatureFlags()}unsetPersonPropertiesForFlags(t,e){e===void 0&&(e=!0);var s=b({},this.Oa(ct)||{});t.forEach((r=>{delete s[r]})),this.F({[ct]:s}),e&&this.reloadFeatureFlags()}resetPersonPropertiesForFlags(t){t===void 0&&(t=!0),this.q(ct),t&&this.reloadFeatureFlags()}setGroupPropertiesForFlags(t,e){e===void 0&&(e=!0);var s=this.Oa(Ut)||{},r=b({},s);for(var n of Object.keys(t))r[n]=b({},s[n],t[n]);this.F({[Ut]:r}),e&&this.reloadFeatureFlags()}resetGroupPropertiesForFlags(t){if(t){var e=this.Oa(Ut)||{};this.F({[Ut]:b({},e,{[t]:{}})})}else this.q(Ut)}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}}},wf={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===Ls||this.Ya===Fr?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=Tl,this.Xa=void 0,this.eo=!1,this.io=(()=>{var e;if(C==null||!C.visibilityState||C.visibilityState==="visible")return!0;var s=v==null||(e=v.performance)==null||e.getEntriesByType==null?void 0:e.getEntriesByType("visibility-state");return!(s!=null&&s.length)||s.some((r=>r.name==="visible"))})(),this.Ie=()=>{var e;C?.visibilityState==="visible"&&(this.io=!0,(e=this.Ja)==null||e.setDocumentWasEverVisible==null||e.setDocumentWasEverVisible(!0))},this._instance=t,!this._instance.sessionManager)throw at.error("started without valid sessionManager"),new Error(po+" started without valid sessionManager. This is a bug.");if(this.Ne.cookieless_mode===ht)throw new Error(po+' cannot be used with cookieless_mode="always"');C!=null&&C.addEventListener&&ne(C,"visibilitychange",this.Ie)}initialize(){this.startIfEnabledOrStop()}dispose(){this.eo=!0,C==null||C.removeEventListener==null||C.removeEventListener("visibilitychange",this.Ie),this.stopRecording()}get ro(){var t,e=!((t=this._instance.get_property(qt))==null||!t.enabled),s=!this.Ne.disable_session_recording,r=this.Ne.disable_session_recording||this._instance.consent.isOptedOut();return v&&e&&s&&!r}startIfEnabledOrStop(t){var e;if(!(this.eo||this.ro&&(e=this.Ja)!=null&&e.isStarted)){var s=!x(Object.assign)&&!x(Array.from);this.ro&&s?(this.no(t),at.info("starting")):(this.Ya=Tl,this.stopRecording())}}no(t){var e,s,r;this.ro&&(this.Ya!==Ls&&this.Ya!==Fr&&(this.Ya=Nl),$!=null&&(e=$.__PosthogExtensions__)!=null&&(e=e.rrweb)!=null&&e.record&&(s=$.__PosthogExtensions__)!=null&&s.initSessionRecording?this.so(t):(r=$.__PosthogExtensions__)==null||r.loadExternalDependency==null||r.loadExternalDependency(this._instance,this.ao,(n=>{if(n)return at.error("could not load recorder",n);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(zo),(e=this.Mr)==null||e.unregister(lu)}uo(t,e){if(D(t))return null;var s,r=he(t)?t:parseFloat(t);return typeof(s=r)!="number"||!Number.isFinite(s)||0>s||s>1?(at.warn(e+" must be between 0 and 1. Ignoring invalid value:",t),null):r}ho(t){if(this.Mr){var e,s,r=this.Mr,n=()=>{var i,o=t.sessionRecording===!1?void 0:t.sessionRecording,a=this.uo((i=this.Ne.session_recording)==null?void 0:i.sampleRate,"session_recording.sampleRate"),l=this.uo(o?.sampleRate,"remote config sampleRate"),u=a??l;D(u)&&this.lo();var c=o?.minimumDurationMilliseconds;r.register({[qt]:b({cache_timestamp:Date.now(),enabled:!!o},o,{networkPayloadCapture:b({capturePerformance:t.capturePerformance},o?.networkPayloadCapture),canvasRecording:{enabled:o?.recordCanvas,fps:o?.canvasFps,quality:o?.canvasQuality},sampleRate:u,minimumDurationMilliseconds:x(c)?null:c,endpoint:o?.endpoint,triggerMatchType:o?.triggerMatchType,masking:o?.masking,urlTriggers:o?.urlTriggers,version:o?.version,triggerGroups:o?.triggerGroups})})};n(),(e=this.Xa)==null||e.call(this),this.Xa=(s=this._instance.sessionManager)==null?void 0:s.onSessionId(n)}}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===Ls&&(this.Ya=Fr,at.warn("config refresh failed, recording will not start until page reload")),void this.startIfEnabledOrStop())}log(t,e){var s;e===void 0&&(e="log"),(s=this.Ja)!=null&&s.log?this.Ja.log(t,e):at.warn("log called before recorder was ready")}get ao(){var t,e,s=(t=this._instance)==null||(t=t.persistence)==null?void 0:t.get_property(qt);return(s==null||(e=s.scriptConfig)==null?void 0:e.script)||"lazy-recorder"}do(){var t,e=this._instance.get_property(qt);if(!e)return!1;try{t=typeof e=="object"?e:JSON.parse(e)}catch(s){return at.warn("persisted remote config for session recording is invalid and will be ignored",s),!1}return!D(t.cache_timestamp)&&36e5>=Date.now()-t.cache_timestamp}so(t){var e,s,r;if(!this.eo){if((e=$.__PosthogExtensions__)==null||!e.initSessionRecording)return at.warn("Called on script loaded before session recording is available. This can be caused by adblockers."),void this._instance.register_for_session({[mu]:!0});var n;if(this.Ja||(this.Ja=(n=$.__PosthogExtensions__)==null?void 0:n.initSessionRecording(this._instance,this.io),this.Ja._forceAllowLocalhostNetworkCapture=this._forceAllowLocalhostNetworkCapture),!this.do())return this.Ya===Fr||this.Ya===Ls?void 0:(this.Ya=Ls,at.info("persisted remote config is stale, requesting fresh config before starting"),void new Uu(this._instance).load());this.Ya=Nl,(s=(r=this.Ja).setDocumentWasEverVisible)==null||s.call(r,this.io),this.Ja.start(t)}}onRRwebEmit(t){var e;(e=this.Ja)==null||e.onRRwebEmit==null||e.onRRwebEmit(t)}overrideLinkedFlag(){var t,e;this.Ja||(e=this.Mr)==null||e.register({[uu]:!0}),(t=this.Ja)==null||t.overrideLinkedFlag()}overrideSampling(){var t,e;this.Ja||(e=this.Mr)==null||e.register({[cu]:!0}),(t=this.Ja)==null||t.overrideSampling()}overrideTrigger(t){var e,s;this.Ja||(s=this.Mr)==null||s.register({[t==="url"?du:hu]:!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 s;return!((s=this.Ja)==null||!s.tryAddCustomEvent(t,e))}}},bf={autocapture:class{constructor(t){this.vo=!1,this.co=null,this.fo=!1,this.po=!1,this.instance=t,this.rageclicks=new Al(t.config.rageclick),this.mo=null}initialize(){this.startIfEnabled()}get Ne(){var t,e,s=te(this.instance.config.autocapture)?this.instance.config.autocapture:{};return s.url_allowlist=(t=s.url_allowlist)==null?void 0:t.map((r=>new RegExp(r))),s.url_ignorelist=(e=s.url_ignorelist)==null?void 0:e.map((r=>new RegExp(r))),s}yo(){if(this.isBrowserSupported()){if(v&&C){var t=s=>{s=s||v?.event;try{this.bo(s)}catch(r){wi.error("Failed to capture event",r)}};if(ne(C,"submit",t,{capture:!0}),ne(C,"change",t,{capture:!0}),ne(C,"click",t,{capture:!0}),this.Ne.capture_copied_text){var e=s=>{s=s||v?.event;try{this.bo(s,yi)}catch(r){wi.error("Failed to capture copy/cut event",r)}};ne(C,"copy",e,{capture:!0}),ne(C,"cut",e,{capture:!0})}}}else wi.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 s=e.autocapture_opt_out;Ke(s)&&(this.instance.persistence&&this.instance.persistence.register({[Ui]:s}),this.co=s),this.startIfEnabled()}else this.startIfEnabled()}setElementSelectors(t){this.mo=t}getElementSelectors(t){var e,s=[];return(e=this.mo)==null||e.forEach((r=>{var n=C?.querySelectorAll(r);n?.forEach((i=>{t===i&&s.push(r)}))})),s}get isEnabled(){var t,e,s=(t=this.instance.persistence)==null?void 0:t.props[Ui],r=this.co,n=this.instance.Qi()&&!this.fo;if($e(r)&&!Ke(s)&&!n)return!1;var i=(e=this.co)!==null&&e!==void 0?e:!!s;return!!this.instance.config.autocapture&&!i}bo(t,e){if(e===void 0&&(e="$autocapture"),this.isEnabled){var s,r=ai(t);bu(r)&&(r=r.parentNode||null),e==="$autocapture"&&t.type==="click"&&t instanceof MouseEvent&&this.instance.config.rageclick&&(s=this.rageclicks)!=null&&s.isRageClick(t.clientX,t.clientY,t.timeStamp||new Date().getTime())&&ol(r,this.instance.config.rageclick)&&this.bo(t,"$rageclick");var n=e===yi;if(r&&(function(d,h,p,f,g,m){var _;if(!v||Jo(d)||p!=null&&p.url_allowlist&&!rl(p.url_allowlist,m)||p!=null&&p.url_ignorelist&&rl(p.url_ignorelist,m))return!1;if(p!=null&&p.dom_event_allowlist){var w=p.dom_event_allowlist;if(w&&!w.some((S=>h.type===S)))return!1}var E=Cu(d,f),I=E.parentIsUsefulElement,F=E.targetElementList;if(!(function(S,A){var R=A?.element_allowlist;if(x(R))return!0;var N,T=function(J){if(R.some((z=>J.tagName.toLowerCase()===z)))return{v:!0}};for(var O of S)if(N=T(O))return N.v;return!1})(F,p)||!ro(F,p?.css_selector_allowlist)||ro(F,(_=p?.css_selector_ignorelist)!==null&&_!==void 0?_:vp))return!1;try{var P=v.getComputedStyle(d);if(P&&P.getPropertyValue("cursor")==="pointer"&&h.type==="click")return!0}catch{}var B=d.tagName.toLowerCase();switch(B){case"html":return!1;case"form":return(g||["submit"]).indexOf(h.type)>=0;case"input":case"select":case"textarea":return(g||["change","click"]).indexOf(h.type)>=0;default:return I?(g||["click"]).indexOf(h.type)>=0:(g||["click"]).indexOf(h.type)>=0&&(Ko.indexOf(B)>-1||d.getAttribute("contenteditable")==="true")}})(r,t,this.Ne,n,n?["copy","cut"]:void 0,this.instance)){var i=uf(r,{e:t,maskAllElementAttributes:this.instance.config.mask_all_element_attributes,maskAllText:this.instance.config.mask_all_text,elementAttributeIgnoreList:this.Ne.element_attribute_ignorelist,elementsChainAsString:this.po,disableCaptureUrlHashes:this.instance.config.disable_capture_url_hashes}),o=i.props;if(i.explicitNoCapture)return!1;var a=this.getElementSelectors(r);if(a&&a.length>0&&(o.$element_selectors=a),e===yi){var l,u=xu(v==null||(l=v.getSelection())==null?void 0:l.toString()),c=t.type||"clipboard";if(!u)return!1;o.$selected_content=u,o.$copy_type=c}return this.instance.capture(e,o),!0}}}isBrowserSupported(){return Se(C?.querySelectorAll)}},historyAutocapture:class{constructor(t){var e;this._instance=t,this._o=(v==null||(e=v.location)==null?void 0:e.pathname)||""}initialize(){this.startIfEnabled()}get isEnabled(){return this._instance.config.capture_pageview==="history_change"}startIfEnabled(){this.isEnabled&&(k.info("History API monitoring enabled, starting..."),this.monitorHistoryChanges())}stop(){this.wo&&this.wo(),this.wo=void 0,k.info("History API monitoring stopped")}monitorHistoryChanges(){v&&v.history&&(this.ko("pushState"),this.ko("replaceState"),this.xo())}ko(t){var e;if(v&&((e=v.history[t])==null||!e.__posthog_wrapped__)){var s=this;(function(r,n,i){try{if(!(n in r))return $l;var o={next:r[n]},a=i((function(){for(var l=arguments.length,u=new Array(l),c=0;l>c;c++)u[c]=arguments[c];return o.next.apply(this,u)}));return Se(a)&&(a.prototype=a.prototype||{},Object.defineProperties(a,{__posthog_wrapped__:{enumerable:!1,value:!0},__posthog_layer__:{enumerable:!1,value:o}})),r[n]=a,()=>{if(r[n]!==a)for(var l=r[n];Se(l)&&l.__posthog_layer__;){var u=l.__posthog_layer__;if(u.next===a)return void(u.next=o.next);l=u.next}else r[n]=o.next}}catch{return $l}})(v.history,t,(r=>function(n,i,o){r.call(this,n,i,o),s.So(t)}))}}So(t){try{var e,s=v==null||(e=v.location)==null?void 0:e.pathname;if(!s)return;s!==this._o&&this.isEnabled&&this._instance.capture(is,{navigation_type:t}),this._o=s}catch(r){k.error("Error capturing "+t+" pageview",r)}}xo(){if(!this.wo){var t=()=>{this.So("popstate")};ne(v,"popstate",t),this.wo=()=>{v&&v.removeEventListener("popstate",t)}}}},heatmaps:class{get Ne(){return this.instance.config}constructor(t){var e;this.Co=!1,this.vo=!1,this.Mo=null,this.instance=t,this.Co=!((e=this.instance.persistence)==null||!e.props[Hi]),this.rageclicks=new Al(t.config.rageclick)}initialize(){this.startIfEnabled()}get flushIntervalMilliseconds(){var t=5e3;return te(this.Ne.capture_heatmaps)&&this.Ne.capture_heatmaps.flush_interval_milliseconds&&(t=this.Ne.capture_heatmaps.flush_interval_milliseconds),t}get isEnabled(){return D(this.Ne.capture_heatmaps)?D(this.Ne.enable_heatmaps)?this.Co:this.Ne.enable_heatmaps:this.Ne.capture_heatmaps!==!1}startIfEnabled(){if(this.isEnabled){if(this.vo)return;hf.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 s=!!e.heatmaps;this.instance.persistence&&this.instance.persistence.register({[Hi]:s}),this.Co=s,this.startIfEnabled()}}}getAndClearBuffer(){var t=this.R;return this.R=void 0,t}Io(t){Ei(t.originalEvent)&&this.ke(t.originalEvent,"deadclick")}Ie(){this.Mo&&clearInterval(this.Mo),this.Mo=C?.visibilityState==="visible"?setInterval(this.cr.bind(this),this.flushIntervalMilliseconds):null}To(){v&&C&&(this.Po=this.cr.bind(this),ne(v,on,this.Po),this.Ro=t=>this.ke(t||v?.event),ne(C,"click",this.Ro,{capture:!0}),this.Ao=t=>this.Fo(t||v?.event),ne(C,"mousemove",this.Ao,{capture:!0}),this.Lo=new pl(this.instance,xp,this.Io.bind(this)),this.Lo.startIfEnabledOrStop(),this.Oo=this.Ie.bind(this),ne(C,nn,this.Oo),this.vo=!0)}Eo(){var t;v&&C&&(this.Po&&v.removeEventListener(on,this.Po),this.Ro&&C.removeEventListener("click",this.Ro,{capture:!0}),this.Ao&&C.removeEventListener("mousemove",this.Ao,{capture:!0}),this.Oo&&C.removeEventListener(nn,this.Oo),clearTimeout(this.Do),(t=this.Lo)==null||t.stop(),this.vo=!1)}$o(t,e){var s=this.instance.scrollManager.scrollY(),r=this.instance.scrollManager.scrollX(),n=this.instance.scrollManager.scrollElement(),i=(function(o,a,l){for(var u=o;u&&Ft(u)&&!Me(u,"body");){if(u===l)return!1;var c=void 0;try{var d,h,p;c=(d=(h=(p=u.ownerDocument)==null?void 0:p.defaultView)!==null&&h!==void 0?h:v)==null?void 0:d.getComputedStyle(u).position}catch{return!1}if(M(a,c))return!0;u=ku(u)}return!1})(ai(t),["fixed","sticky"],n);return{x:t.clientX+(i?0:r),y:t.clientY+(i?0:s),target_fixed:i,type:e}}ke(t,e){var s;if(e===void 0&&(e="click"),!sl(t.target)&&Ei(t)){var r=this.$o(t,e);(s=this.rageclicks)!=null&&s.isRageClick(t.clientX,t.clientY,new Date().getTime())&&ol(ai(t),this.instance.config.rageclick)&&this.Vt(b({},r,{type:"rageclick"})),this.Vt(r)}}Fo(t){!sl(t.target)&&Ei(t)&&(clearTimeout(this.Do),this.Do=setTimeout((()=>{this.Vt(this.$o(t,"mousemove"))}),500))}Vt(t){if(v){var e=this.Ne.disable_capture_url_hashes?Ct(v.location.href):v.location.href,s=this.Ne.custom_personal_data_properties,r=this.Ne.mask_personal_data_properties?[...vs,...s||[]]:[],n=nr(e,r,ir);this.R=this.R||{},this.R[n]||(this.R[n]=[]),this.R[n].push(t)}}cr(){this.R&&!mt(this.R)&&this.instance.capture("$$heatmap",{$heatmap_data:this.getAndClearBuffer()})}},deadClicksAutocapture:pl,webVitalsAutocapture:class{constructor(t){var e;this.Co=!1,this.vo=!1,this.R={navigationKey:void 0,url:void 0,metrics:[],firstMetricTimestamp:void 0},this.No=()=>{clearTimeout(this.qo),this.qo=void 0,this.R.metrics.length!==0&&(this._instance.capture("$web_vitals",b({$current_url:this.R.url},this.R.metrics.reduce(((s,r)=>b({},s,{["$web_vitals_"+r.name+"_event"]:b({},r),["$web_vitals_"+r.name+"_value"]:r.value})),{}))),this.R={navigationKey:void 0,url:void 0,metrics:[],firstMetricTimestamp:void 0})},this.jo=s=>{var r;if(this.R=this.R||{navigationKey:void 0,url:void 0,metrics:[],firstMetricTimestamp:void 0},D(s?.name)||D(s?.value))Lt.error("Invalid metric received",s);else{var n=typeof s.navigationURL=="string"?s.navigationURL:void 0,i=this.Bo(n);if(!x(i)){var o=he(s.navigationId)||typeof s.navigationId=="string"?"navigation:"+s.navigationId:"url:"+i;if(!this.Ho||this.Ho>s.value){this.R.navigationKey!==o&&(this.No(),this.qo=setTimeout(this.No,this.flushToCaptureTimeoutMs)),x(this.R.navigationKey)&&(this.R.navigationKey=o,this.R.url=i),this.R.firstMetricTimestamp=x(this.R.firstMetricTimestamp)?Date.now():this.R.firstMetricTimestamp,s.attribution&&s.attribution.interactionTargetElement&&(s.attribution.interactionTargetElement=void 0);var a=(r=this._instance.sessionManager)==null?void 0:r.checkAndGetSessionAndWindowId(!0),l=b({},s,n?{navigationURL:i}:{},{$current_url:i,timestamp:Date.now()});x(a)||(l.$session_id=a.sessionId,l.$window_id=a.windowId),this.R.metrics.push(l),this.R.metrics.length===this.allowedMetrics.length&&this.No()}else Lt.error("Ignoring metric with value >= "+this.Ho,s)}}},this.Uo=()=>{if(!this.vo){var s,r,n,i,o=$.__PosthogExtensions__,a=o?.postHogWebVitalsCallbacksByFlavor,l=a?.[this.zo]||(this.zo==="web-vitals"&&x(a)?o?.postHogWebVitalsCallbacks:void 0);if(x(l)||(s=l.onLCP,r=l.onCLS,n=l.onFCP,i=l.onINP),s&&r&&n&&i){var u={reportSoftNavs:this.useSoftNavs};this.allowedMetrics.indexOf("LCP")>-1&&s(this.jo.bind(this),u),this.allowedMetrics.indexOf("CLS")>-1&&r(this.jo.bind(this),u),this.allowedMetrics.indexOf("FCP")>-1&&n(this.jo.bind(this),u),this.allowedMetrics.indexOf("INP")>-1&&i(this.jo.bind(this),u),this.vo=!0}else Lt.error("web vitals callbacks not loaded - not starting")}},this._instance=t,this.Co=!((e=this._instance.persistence)==null||!e.props[Vi]),this.startIfEnabled()}get Wo(){return this._instance.config.capture_performance}get allowedMetrics(){var t,e,s=te(this.Wo)?(t=this.Wo)==null?void 0:t.web_vitals_allowed_metrics:void 0;return D(s)?((e=this._instance.persistence)==null?void 0:e.props[Gi])||["CLS","FCP","INP","LCP"]:s}get flushToCaptureTimeoutMs(){return(te(this.Wo)?this.Wo.web_vitals_delayed_flush_ms:void 0)||5e3}get useAttribution(){var t=te(this.Wo)?this.Wo.web_vitals_attribution:void 0;return t!=null&&t}get useSoftNavs(){var t=te(this.Wo)?this.Wo.__preview_web_vitals_soft_navs:void 0;return t!=null&&t}get Ho(){var t=te(this.Wo)&&he(this.Wo.__web_vitals_max_value)?this.Wo.__web_vitals_max_value:Rl;return t>0&&6e4>=t?Rl:t}get isEnabled(){var t=re?.protocol;if(t!=="http:"&&t!=="https:")return Lt.info("Web Vitals are disabled on non-http/https protocols"),!1;var e=te(this.Wo)?this.Wo.web_vitals:Ke(this.Wo)?this.Wo:void 0;return Ke(e)?e:this.Co}startIfEnabled(){this.isEnabled&&!this.vo&&(Lt.info("enabled, starting..."),this.ai(this.Uo))}onRemoteConfig(t){if(t.ok){var e=t.config;if("capturePerformance"in e){var s=te(e.capturePerformance)&&!!e.capturePerformance.web_vitals,r=te(e.capturePerformance)?e.capturePerformance.web_vitals_allowed_metrics:void 0;this._instance.persistence&&(this._instance.persistence.register({[Vi]:s}),this._instance.persistence.register({[Gi]:r})),this.Co=s,this.startIfEnabled()}}}get zo(){return this.useSoftNavs?this.useAttribution?"web-vitals-with-attribution-soft-navs":"web-vitals-soft-navs":this.useAttribution?"web-vitals-with-attribution":"web-vitals"}ai(t){var e=$.__PosthogExtensions__,s=this.zo,r=e?.postHogWebVitalsCallbacksByFlavor;r!=null&&r[s]||s==="web-vitals"&&x(r)&&e!=null&&e.postHogWebVitalsCallbacks?t():e==null||e.loadExternalDependency==null||e.loadExternalDependency(this._instance,s,(n=>{n?Lt.error("failed to load script",n):t()}))}Bo(t){var e=t||v?.location.href;if(e){var s=this._instance.config.disable_capture_url_hashes?Ct(e):e,r=this._instance.config.custom_personal_data_properties,n=this._instance.config.mask_personal_data_properties?[...vs,...r||[]]:[];return nr(s,n,ir)}Lt.error("Could not determine current URL")}}},Ef={exceptionObserver:class{constructor(t){var e;this.Uo=()=>{var s;if(v&&this.isEnabled&&(s=$.__PosthogExtensions__)!=null&&s.errorWrappingFunctions){var r=$.__PosthogExtensions__.errorWrappingFunctions.wrapOnError,n=$.__PosthogExtensions__.errorWrappingFunctions.wrapUnhandledRejection,i=$.__PosthogExtensions__.errorWrappingFunctions.wrapConsoleError;try{!this.Vo&&this.Ne.capture_unhandled_errors&&(this.Vo=r(this.captureException.bind(this))),!this.Zo&&this.Ne.capture_unhandled_rejections&&(this.Zo=n(this.captureException.bind(this))),!this.Go&&this.Ne.capture_console_errors&&(this.Go=i(this.captureException.bind(this)))}catch(o){Ms.error("failed to start",o),this.Qo()}}},this._instance=t,this.Ko=!((e=this._instance.persistence)==null||!e.props[Wi]),this.Jo=new yh(b({},(function(s){var r,n,i,o;return s===void 0&&(s={}),{refillRate:(r=(n=s.exceptionRateLimiterRefillRate)!==null&&n!==void 0?n:s.__exceptionRateLimiterRefillRate)!==null&&r!==void 0?r:1,bucketSize:(i=(o=s.exceptionRateLimiterBucketSize)!==null&&o!==void 0?o:s.__exceptionRateLimiterBucketSize)!==null&&i!==void 0?i:10}})(this._instance.config.error_tracking),{refillInterval:1e4,rt:Ms})),this.Ne=this.Yo(),this.startIfEnabledOrStop()}Yo(){var t=this._instance.config.capture_exceptions,e={capture_unhandled_errors:!1,capture_unhandled_rejections:!1,capture_console_errors:!1};return te(t)?e=b({},e,t):(x(t)?this.Ko:t)&&(e=b({},e,{capture_unhandled_errors:!0,capture_unhandled_rejections:!0})),e}get isEnabled(){return this.Ne.capture_console_errors||this.Ne.capture_unhandled_errors||this.Ne.capture_unhandled_rejections}startIfEnabledOrStop(){this.isEnabled?(Ms.info("enabled"),this.Qo(),this.ai(this.Uo)):this.Qo()}ai(t){var e,s;(e=$.__PosthogExtensions__)!=null&&e.errorWrappingFunctions?t():(s=$.__PosthogExtensions__)==null||s.loadExternalDependency==null||s.loadExternalDependency(this._instance,"exception-autocapture",(r=>{if(r)return Ms.error("failed to load script",r);t()}))}Qo(){var t,e,s;(t=this.Vo)==null||t.call(this),this.Vo=void 0,(e=this.Zo)==null||e.call(this),this.Zo=void 0,(s=this.Go)==null||s.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({[Wi]:this.Ko}),this.Ne=this.Yo(),this.startIfEnabledOrStop())}}onConfigChange(){this.Ne=this.Yo()}captureException(t){var e,s,r,n=(e=t==null||(s=t.$exception_list)==null||(s=s[0])==null?void 0:s.type)!==null&&e!==void 0?e:"Exception";this.Jo.consumeRateLimit(n)?Ms.info("Skipping exception capture because of client rate limiting.",{exception:n}):(r=this._instance.exceptions)==null||r.sendExceptionEvent(t)}},exceptions:class{constructor(t){var e,s;this.Xo=[],this.tl=new Lh([new zh,new Qh,new Vh,new qh,new Zh,new Yh,new Kh,new Xh],(function(r){for(var n=arguments.length,i=new Array(n>1?n-1:0),o=1;n>o;o++)i[o-1]=arguments[o];return function(a,l){l===void 0&&(l=0);for(var u=[],c=a.split(` +`),d=l;c.length>d;d++){var h=c[d];if(1024>=h.length){var p=Xa.test(h)?h.replace(Xa,"$1"):h;if(!p.match(/\S*Error: /)){for(var f of i){var g=f(p,r);if(g){u.push(g);break}}if(u.length>=50)break}}}return(function(m){if(!m.length)return[];var _=Array.from(m);return _.reverse(),_.slice(0,50).map((w=>{return b({},w,{filename:w.filename||(E=_,E[E.length-1]||{}).filename,function:w.function||gs});var E}))})(u)}})("web:javascript",jh,Wh)),this._instance=t,this.Xo=(e=(s=this._instance.persistence)==null?void 0:s.get_property(zi))!==null&&e!==void 0?e:[],this.el=Qr(this.il()),this.rl=new tp(this.el)}onConfigChange(){this.el=Qr(this.il()),this.rl.setConfig(this.el)}onRemoteConfig(t){var e,s,r;if(t.ok){var n=t.config;if("errorTracking"in n){var i=(e=(s=n.errorTracking)==null?void 0:s.suppressionRules)!==null&&e!==void 0?e:[],o=(r=n.errorTracking)==null?void 0:r.captureExtensionExceptions;this.Xo=i,this._instance.persistence&&this._instance.persistence.register({[zi]:this.Xo,[qi]:o})}}}get nl(){var t,e=!!this._instance.get_property(qi),s=this._instance.config.error_tracking.captureExtensionExceptions;return(t=s??e)!==null&&t!==void 0&&t}buildProperties(t,e){return this.tl.buildFromUnknown(t,{syntheticException:e?.syntheticException,mechanism:{handled:e?.handled}})}addExceptionStep(t,e){if(this.el.enabled)try{if(!W(t)||t.trim().length===0)return void Xe.warn("Ignoring exception step because message must be a non-empty string");var s=(function(i){if(!i)return{sanitizedProperties:{},droppedKeys:[]};var o=[];return{sanitizedProperties:Object.keys(i).reduce(((a,l)=>ep.has(l)?(o.push(l),a):(a[l]=i[l],a)),{}),droppedKeys:o}})(this.sl(e)),r=s.sanitizedProperties,n=s.droppedKeys;n.length>0&&Xe.warn("Ignoring reserved exception step fields",{droppedKeys:n}),this.rl.add(b({[Zr]:t,[Xr]:new Date().toISOString()},r))}catch(i){Xe.error("Failed to add exception step. Ignoring breadcrumb.",i)}}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 Xe.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 Xe.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 Xe.info("Skipping exception capture because it was thrown by the PostHog SDK")}var s=this.el.enabled&&D(t.$exception_steps)?this.dl(t):t,r=typeof(i=globalThis._posthogReleaseId)=="string"&&i.length>0?i:void 0;r&&(s.$release_id=r);try{var n=this._instance.capture("$exception",s,{_noTruncate:!0,_batchKey:"exceptionEvent",Wn:!0});return n&&this.rl.clear(),n}catch(o){return Xe.error("Failed to capture exception event. Dropping this exception.",o),void this.rl.clear()}}catch(o){return void Xe.error("Failed to process exception event. Ignoring this exception.",o)}var i}dl(t){try{var e=this.rl.getAttachable();return e.length===0?t:b({},t,{$exception_steps:e})}catch(s){return Xe.error("Failed to read buffered exception steps. Capturing exception without steps.",s),t}}ll(t){this.el.enabled&&this.rl.add({[Zr]:t,[Xr]:new Date().toISOString()})}sl(t){return te(t)?b({},t):{}}il(){var t,e;return(t=(e=this._instance.config.error_tracking)==null?void 0:e.exception_steps)!==null&&t!==void 0?t:{}}ol(t){if(t.length===0)return!1;try{var e=t.reduce(((s,r)=>{var n=r.type,i=r.value;return W(n)&&n.length>0&&s.$exception_types.push(n),W(i)&&i.length>0&&s.$exception_values.push(i),s}),{$exception_types:[],$exception_values:[]});return this.Xo.some((s=>{var r=s.values.map((n=>{var i=td[n.operator],o=e[n.key];if(!i||!o)return!1;var a=L(n.value)?n.value:[n.value];return a.length>0&&i(a,o)}));return s.type==="OR"?r.some(Boolean):r.every(Boolean)}))}catch(s){return Xe.warn("Failed to evaluate suppression rules. Capturing the exception.",s),!1}}ul(t){return t.flatMap((e=>{var s,r;return(s=(r=e.stacktrace)==null?void 0:r.frames)!==null&&s!==void 0?s:[]})).some((e=>e.filename&&e.filename.startsWith("chrome-extension://")))}hl(t){if(t.length>0){var e,s,r,n,i=(e=(s=t[0].stacktrace)==null?void 0:s.frames)!==null&&e!==void 0?e:[],o=i[i.length-1];return(r=o==null||(n=o.filename)==null?void 0:n.includes("posthog.com/static"))!==null&&r!==void 0&&r}return!1}al(t){return!D(t)&&L(t)}}},Sf=b({productTours:class{get Mr(){return this._instance.persistence}constructor(t){this.vl=null,this.cl=null,this._instance=t}initialize(){this.loadIfEnabled()}onRemoteConfig(t){if(t.ok){var e=t.config;if("productTours"in e){var s,r;if(this.Mr&&this.Mr.register({[Wo]:!!e.productTours}),!Si(this._instance))return!this.vl&&D((s=this.Mr)==null?void 0:s.props[Ws])||Pr.info("product tours disabled; stopping and clearing cached tours"),(r=this.vl)==null||r.stop(),this.vl=null,void this.clearCache();this.loadIfEnabled()}}}loadIfEnabled(){!this.vl&&Si(this._instance)&&this.ai((()=>this.fl()))}ai(t){var e,s;(e=$.__PosthogExtensions__)!=null&&e.generateProductTours?t():(s=$.__PosthogExtensions__)==null||s.loadExternalDependency==null||s.loadExternalDependency(this._instance,"product-tours",(r=>{r?Pr.error("Could not load product tours script",r):t()}))}fl(){var t;!this.vl&&(t=$.__PosthogExtensions__)!=null&&t.generateProductTours&&(this.vl=$.__PosthogExtensions__.generateProductTours(this._instance,!0))}getProductTours(t,e){if(e===void 0&&(e=!1),!L(this.cl)||e){var s=this.Mr;if(s){var r=s.props[Ws];if(L(r)&&!e)return this.cl=r,void t(r,{isLoaded:!0})}this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/product_tours/?token="+this._instance.config.token),method:"GET",timestampMode:"query",callback:n=>{if(Si(this._instance)){var i=n.statusCode;if(i!==200||!n.json){var o="Product Tours API could not be loaded, status: "+i;return i===0?n.error||Pr.warn(o):Pr.error(o),void t([],{isLoaded:!1,error:o})}var a=L(n.json.product_tours)?n.json.product_tours:[];this.cl=a,s&&s.register({[Ws]:a}),t(a,{isLoaded:!0})}else t([],{isLoaded:!0})}})}else t(this.cl,{isLoaded:!0})}getActiveProductTours(t){D(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(Ws)}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)}}},Rn),xf={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 s=this.globalsForEvent(e);this.gl.push(s),this.gl.length>1e3&&(this.gl=this.gl.slice(10))}}get siteAppLoaders(){var t;return(t=$._POSTHOG_REMOTE_CONFIG)==null||(t=t[this._instance.config.token])==null?void 0:t.siteApps}initialize(){if(this.isEnabled){var t=this._instance._addCaptureHook(this.ml.bind(this));this.yl=()=>{t(),this.gl=[],this.yl=void 0}}}globalsForEvent(t){var e,s,r,n,i,o,a;if(!t)throw new Error("Event payload is required");var l={},u=this._instance.get_property("$groups")||[],c=this._instance.get_property("$stored_group_properties")||{};for(var d of Object.entries(c)){var h=d[0];l[h]={id:u[h],type:h,properties:d[1]}}var p=t.$set_once,f=t.$set;return{event:b({},Ic(t,pf),{properties:b({},t.properties,f?{$set:b({},(e=(s=t.properties)==null?void 0:s.$set)!==null&&e!==void 0?e:{},f)}:{},p?{$set_once:b({},(r=(n=t.properties)==null?void 0:n.$set_once)!==null&&r!==void 0?r:{},p)}:{}),elements_chain:(i=(o=t.properties)==null?void 0:o.$elements_chain)!==null&&i!==void 0?i:"",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,s=(e=t.tagName)==null?void 0:e.toLowerCase();return s==="style"&&this._instance.config.prepare_external_dependency_stylesheet?this._instance.config.prepare_external_dependency_stylesheet(t)||(Ze.error("prepare_external_dependency_stylesheet returned null"),null):s==="script"&&this._instance.config.prepare_external_dependency_script?this._instance.config.prepare_external_dependency_script(t)||(Ze.error("prepare_external_dependency_script returned null"),null):t}_l(){var t,e,s,r,n,i,o,a;if(!this._instance.config.prepare_external_dependency_stylesheet&&!this._instance.config.prepare_external_dependency_script)return()=>{};var l=C?.defaultView,u=l==null||(t=l.Node)==null?void 0:t.prototype;if(!l||!u)return()=>{};if(this.pl++,this.wl)return this.kl();var c=[],d=this,h=new WeakSet,p=(m,_,w)=>{if(m!=null&&m[_]){var E=m[_];m[_]=w(E),c.push((()=>{m[_]=E}))}},f=m=>{if(h.has(m))return m;var _=d.bl(m);return _&&h.add(_),_},g=m=>m.map((_=>typeof _=="string"?_:f(_))).filter((_=>!$e(_)));return p(u,"appendChild",(m=>function(_){var w=f(_);return w?m.call(this,w):_})),p(u,"insertBefore",(m=>function(_,w){var E=f(_);return E?m.call(this,E,w):_})),p(u,"replaceChild",(m=>function(_,w){var E=f(_);return E?m.call(this,E,w):w})),[(e=l.Element)==null?void 0:e.prototype,(s=l.Document)==null?void 0:s.prototype,(r=l.DocumentFragment)==null?void 0:r.prototype].forEach((m=>{p(m,"append",(_=>function(){for(var w=arguments.length,E=new Array(w),I=0;w>I;I++)E[I]=arguments[I];return _.apply(this,g(E))})),p(m,"prepend",(_=>function(){for(var w=arguments.length,E=new Array(w),I=0;w>I;I++)E[I]=arguments[I];return _.apply(this,g(E))}))})),[(n=l.Element)==null?void 0:n.prototype,(i=l.CharacterData)==null?void 0:i.prototype,(o=l.DocumentType)==null?void 0:o.prototype].forEach((m=>{p(m,"before",(_=>function(){for(var w=arguments.length,E=new Array(w),I=0;w>I;I++)E[I]=arguments[I];return _.apply(this,g(E))})),p(m,"after",(_=>function(){for(var w=arguments.length,E=new Array(w),I=0;w>I;I++)E[I]=arguments[I];return _.apply(this,g(E))})),p(m,"replaceWith",(_=>function(){for(var w=arguments.length,E=new Array(w),I=0;w>I;I++)E[I]=arguments[I];var F=g(E);return E.length&&!F.length?void 0:_.apply(this,F)}))})),p((a=l.Element)==null?void 0:a.prototype,"insertAdjacentElement",(m=>function(_,w){var E=f(w);return E?m.call(this,_,E):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 s=this._l();try{var r=t(s);return e&&s(),r}catch(n){throw s(),n}}setupSiteApp(t){var e=this.apps[t.id],s=()=>{var o;!e.errored&&this.gl.length&&(Ze.info("Processing "+this.gl.length+" events for site app with id "+t.id),this.gl.forEach((a=>this.xl((()=>e.processEvent==null?void 0:e.processEvent(a))))),e.processedBuffer=!0),Object.values(this.apps).every((a=>a.processedBuffer||a.errored))&&((o=this.yl)==null||o.call(this))},r=!1,n=o=>{e.errored=!o,e.loaded=!0,Ze.info("Site app with id "+t.id+" "+(o?"loaded":"errored")),r&&s()};try{var i=this.xl((o=>t.init({posthog:this._instance,callback(a){o(),n(a)}})),!1).processEvent;i&&(e.processEvent=i),r=!0}catch(o){Ze.error(Ml+t.id,o),n(!1)}if(r&&e.loaded)try{s()}catch(o){Ze.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 s of t)this.setupSiteApp(s)}Cl(t){var e=this;if(Object.keys(this.apps).length!==0){var s=this.globalsForEvent(t),r=function(i){try{e.xl((()=>i.processEvent==null?void 0:i.processEvent(s)))}catch(o){Ze.error("Error while processing event "+t.event+" for site app "+i.id,o)}};for(var n of Object.values(this.apps))r(n)}}onRemoteConfig(t){var e,s,r,n=this;if((e=this.siteAppLoaders)!=null&&e.length)return this.isEnabled?(this.Sl(),void this._instance.on("eventCaptured",(l=>this.Cl(l)))):void Ze.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.');if((s=this.yl)==null||s.call(this),t.ok){var i=t.config;if((r=i.siteApps)!=null&&r.length)if(this.isEnabled){var o=function(){var l,u=a.id,c=a.url;$["__$$ph_site_app_"+u]=n._instance,(l=$.__PosthogExtensions__)==null||l.loadSiteApp==null||l.loadSiteApp(n._instance,c,(d=>{if(d)return Ze.error(Ml+u,d)}))};for(var a of i.siteApps)o()}else Ze.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.')}}}},kf={tracingHeaders:class{constructor(t){this.Ml=void 0,this.Tl=void 0,this.El=void 0,this.Uo=()=>{var e,s,r=this.Il();r?(x(this.Ml)&&(this.Ml=(e=$.__PosthogExtensions__)==null||(e=e.tracingHeadersPatchFns)==null?void 0:e._patchXHR(r,(()=>this._instance.get_distinct_id()),this._instance.sessionManager)),x(this.Tl)&&(this.Tl=(s=$.__PosthogExtensions__)==null||(s=s.tracingHeadersPatchFns)==null?void 0:s._patchFetch(r,(()=>this._instance.get_distinct_id()),this._instance.sessionManager))):this.Qo()},this._instance=t}initialize(){this.startIfEnabledOrStop()}ai(t){var e,s;(e=$.__PosthogExtensions__)!=null&&e.tracingHeadersPatchFns?t():(s=$.__PosthogExtensions__)==null||s.loadExternalDependency==null||s.loadExternalDependency(this._instance,"tracing-headers",(r=>{if(r)return df.error("failed to load script",r);t()}))}Pl(){var t,e;return(t=(e=this._instance.config.tracing_headers)!==null&&e!==void 0?e:this._instance.config.addTracingHeaders)!==null&&t!==void 0?t:this._instance.config.__add_tracing_headers}Il(){var t=this.Pl();return L(t)?(L(this.El)?this.El.splice(0,this.El.length,...t):this.El=[...t],t.length>0?this.El:void 0):(L(this.El)&&this.El.splice(0),this.El=t||void 0,this.El)}Qo(){var t,e;(t=this.Ml)==null||t.call(this),(e=this.Tl)==null||e.call(this),this.Ml=void 0,this.Tl=void 0}startIfEnabledOrStop(){this.Il()?this.ai(this.Uo):this.Qo()}}},If=b({surveys:class{get Ne(){return this._instance.config}constructor(t){this.Rl=void 0,this._surveyManager=null,this.Al=!1,this.Fl=[],this.Ll=null,this.Ol=null,this._instance=t,this._surveyEventReceiver=null}initialize(){this.loadIfEnabled()}onRemoteConfig(t){if(!this.Ne.disable_surveys){if(!t.ok)return q.warn("Remote config unavailable. Not loading surveys.");var e=t.config.surveys;if(D(e))return q.warn("Flags not loaded yet. Not loading surveys.");var s=L(e);this.Rl=s?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=[],s=0;slocalStorage.removeItem(n)))}catch{}}loadIfEnabled(){if(!this._surveyManager)if(this.Al)q.info("Already initializing surveys, skipping...");else if(this.Ne.disable_surveys)q.info(Ll);else if(this.Ne.cookieless_mode&&this._instance.consent.isOptedOut())q.info("Not loading surveys in cookieless mode without consent.");else{var t=$?.__PosthogExtensions__;if(t){if(!x(this.Rl)||this.Ne.advanced_enable_surveys){var e=this.Rl||this.Ne.advanced_enable_surveys;this.Al=!0;try{var s=t.generateSurveys;if(s)return void this.Dl(s,e);var r=t.loadExternalDependency;if(!r)return void this.$l(qo);r(this._instance,"surveys",(n=>{n||!t.generateSurveys?this.$l("Could not load surveys script",n):this.Dl(t.generateSurveys,e)}))}catch(n){throw this.$l("Error initializing surveys",n),n}finally{this.Al=!1}}}else q.error("PostHog Extensions not found.")}}Dl(t,e){this._surveyManager=t(this._instance,e),this._surveyEventReceiver=new mf(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(Ll),t([]);var s,r=this._instance.get_property(Ji);if(r&&!e)return t(r,{isLoaded:!0}),void(this.ql()&&this.getSurveys((()=>{}),!0));typeof Promise<"u"&&this.Ll?this.Ll.then((n=>t(n.surveys,n.context))):(typeof Promise<"u"&&(this.Ll=new Promise((n=>{s=n}))),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:n=>{var i;this.Ll=null;var o=n.statusCode;if(o!==200||!n.json){var a="Surveys API could not be loaded, status: "+o;o!==0?q.error(a):n.error||q.warn(a),this.Ol=Date.now();var l={isLoaded:!1,error:a};return t([],l),void(s==null||s({surveys:[],context:l}))}this.Ol=null;var u,c=n.json.surveys||[],d=c.filter((p=>(function(f){return!(!f.start_date||f.end_date)})(p)&&(rd(p)||(function(f){var g;return!((g=f.conditions)==null||(g=g.actions)==null||(g=g.values)==null||!g.length)})(p))));d.length>0&&((u=this._surveyEventReceiver)==null||u.register(d)),(i=this._instance.persistence)==null||i.register({[Ji]:c,[tn]:Date.now()});var h={isLoaded:!0};t(c,h),s?.({surveys:c,context:h})}}))}ql(){return this.jl()&&!this.Ll&&!this.Bl()}jl(){var t=this._instance.get_property(tn);return he(t)&&Date.now()-t>3e5}Bl(){return he(this.Ol)&&3e5>Date.now()-this.Ol}markSurveyAsSeen(t,e){var s,r={id:t,current_iteration:(s=e?.iteration)!==null&&s!==void 0?s:null};id(r);try{localStorage.setItem("lastSeenSurveyDate",new Date().toISOString())}catch{}}Nl(t){for(var e of this.Fl)try{if(!t.isLoaded)return e([],t);this.getSurveys(e)}catch(s){q.error("Error in survey callback",s)}}getActiveMatchingSurveys(t,e){if(e===void 0&&(e=!1),!D(this._surveyManager))return this._surveyManager.getActiveMatchingSurveys(t,e);q.warn("init was not called")}Hl(t){var e=null;return this.getSurveys((s=>{var r;e=(r=s.find((n=>n.id===t)))!==null&&r!==void 0?r:null})),e}Ul(t){if(D(this._surveyManager))return{eligible:!1,reason:Ar};var e=typeof t=="string"?this.Hl(t):t;return e?this._surveyManager.checkSurveyEligibility(e):{eligible:!1,reason:"Survey not found"}}zl(t){if(D(this._surveyManager))return{eligible:!1,reason:Ar};var e=typeof t=="string"?this.Hl(t):t;return e?this._surveyManager.checkSurveyRenderability(e):{eligible:!1,reason:"Survey not found"}}canRenderSurvey(t){if(D(this._surveyManager))return q.warn("init was not called"),{visible:!1,disabledReason:Ar};var e=this.zl(t);return{visible:e.eligible,disabledReason:e.reason}}canRenderSurveyAsync(t,e){return D(this._surveyManager)?(q.warn("init was not called"),Promise.resolve({visible:!1,disabledReason:Ar})):new Promise((s=>{this.getSurveys((r=>{var n,i=(n=r.find((a=>a.id===t)))!==null&&n!==void 0?n:null;if(i){var o=this.zl(i);s({visible:o.eligible,disabledReason:o.reason})}else s({visible:!1,disabledReason:"Survey not found"})}),e)}))}renderSurvey(t,e,s){var r;if(D(this._surveyManager))q.warn("init was not called");else{var n=typeof t=="string"?this.Hl(t):t;if(n!=null&&n.id)if(Zp.includes(n.type)){var i=C?.querySelector(e);if(i)return(r=n.appearance)!=null&&r.surveyPopupDelaySeconds?(q.info("Rendering survey "+n.id+" with delay of "+n.appearance.surveyPopupDelaySeconds+" seconds"),void setTimeout((()=>{var o,a;q.info("Rendering survey "+n.id+" with delay of "+((o=n.appearance)==null?void 0:o.surveyPopupDelaySeconds)+" seconds"),(a=this._surveyManager)==null||a.renderSurvey(n,i,s),q.info("Survey "+n.id+" rendered")}),1e3*n.appearance.surveyPopupDelaySeconds)):void this._surveyManager.renderSurvey(n,i,s);q.warn("Survey element not found")}else q.warn("Surveys of type "+n.type+" cannot be rendered in the app");else q.warn("Survey not found")}}displaySurvey(t,e){var s;if(D(this._surveyManager))q.warn("init was not called");else{var r=this.Hl(t);if(r){var n=r;if((s=r.appearance)!=null&&s.surveyPopupDelaySeconds&&e.ignoreDelay&&(n=b({},r,{appearance:b({},r.appearance,{surveyPopupDelaySeconds:0})})),e.displayType!==io.Popover&&e.initialResponses&&q.warn("initialResponses is only supported for popover surveys. prefill will not be applied."),e.ignoreConditions===!1){var i=this.Ul(r);if(!i.eligible)return void q.warn("Survey is not eligible to be displayed: ",i.reason)}e.displayType!==io.Inline?this._surveyManager.handlePopoverSurvey(n,e):this.renderSurvey(n,e.selector,e.properties)}else q.warn("Survey not found")}}cancelPendingSurvey(t){D(this._surveyManager)?q.warn("init was not called"):this._surveyManager.cancelSurvey(t)}handlePageUnload(){var t;(t=this._surveyManager)==null||t.handlePageUnload==null||t.handlePageUnload()}}},Rn),Cf={toolbar:class{constructor(t){this.instance=t}Wl(t){$.ph_toolbar_state=t}Vl(){var t;return(t=$.ph_toolbar_state)!==null&&t!==void 0?t:0}initialize(){return this.maybeLoadToolbar()}maybeLoadToolbar(t,e,s){if(t===void 0&&(t=void 0),e===void 0&&(e=void 0),s===void 0&&(s=void 0),so(this.instance.config)||!v||!C)return!1;t=t??v.location,s=s??v.history;try{if(!e){try{v.localStorage.setItem("test","test"),v.localStorage.removeItem("test")}catch{return!1}e=v?.localStorage}var r,n=vf||un(t.hash,"__posthog")||un(t.hash,"state"),i=n?el((()=>JSON.parse(atob(decodeURIComponent(n)))))||el((()=>JSON.parse(decodeURIComponent(n)))):null;return i&&i.action==="ph_authorize"?((r=i).source="url",r&&Object.keys(r).length>0&&(i.desiredHash?t.hash=i.desiredHash:s?s.replaceState(s.state,"",t.pathname+t.search):t.hash="")):((r=JSON.parse(e.getItem(Ol)||"{}")).source="localstorage",delete r.userIntent),!(!r.token||this.instance.config.token!==r.token||(this.loadToolbar(r),0))}catch{return!1}}Zl(t){var e=$.ph_load_toolbar||$.ph_load_editor;!D(e)&&Se(e)?e(t,this.instance):Dl.warn("No toolbar load function found")}loadToolbar(t){var e=!(C==null||!C.getElementById(wu));if(!v||e)return!1;var s=this.instance.requestRouter.region==="custom"&&this.instance.config.advanced_disable_toolbar_metrics,r=b({token:this.instance.config.token},t,{apiURL:this.instance.requestRouter.endpointFor("ui")},s?{instrument:!1}:{});if(v.localStorage.setItem(Ol,JSON.stringify(b({},r,{source:void 0}))),this.Vl()===2)this.Zl(r);else if(this.Vl()===0){var n;this.Wl(1),(n=$.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this.instance,"toolbar",(i=>{if(i)return Dl.error("[Toolbar] Failed to load",i),void this.Wl(0);this.Wl(2),this.Zl(r)})),ne(v,"turbolinks:load",(()=>{this.Wl(0),this.loadToolbar(r)}))}return!0}Gl(t){return this.loadToolbar(t)}maybeLoadEditor(t,e,s){return t===void 0&&(t=void 0),e===void 0&&(e=void 0),s===void 0&&(s=void 0),this.maybeLoadToolbar(t,e,s)}}},Ff=b({experiments:ye},Rn),Pf={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;D(e)||(Ke(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||so(this._instance.config)||this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut())){var t=$?.__PosthogExtensions__;if(t&&!x(this.Ql)&&this.Ql)if(this.Jl&&this.Jl.token){this.Kl=!0;try{var e=t.initConversations;if(e)return this.tu(e),void(this.Kl=!1);var s=t.loadExternalDependency;if(!s)return void this.eu(qo);s(this._instance,"conversations",(r=>{r||!t.initConversations?this.eu("Could not load conversations script",r):this.tu(t.initConversations),this.Kl=!1}))}catch(r){this.eu("Error initializing conversations",r),this.Kl=!1}}else Ue.error("Conversations enabled but missing token in remote config.")}}tu(t){if(this.Jl)try{this._conversationsManager=t(this.Jl,this._instance),this.Yl=!1,Ue.info("Conversations loaded successfully")}catch(e){this.eu("Error completing conversations initialization",e)}else Ue.error("Cannot complete initialization: remote config is null")}eu(t,e){Ue.error(t,e),this._conversationsManager=null,this.Kl=!1,this.Yl=!0}show(){this._conversationsManager?this._conversationsManager.show():Ue.warn("Conversations not loaded yet.")}hide(){this._conversationsManager&&this._conversationsManager.hide()}isAvailable(){return this.Ql===!0&&!$e(this._conversationsManager)}getUnavailableReason(){return this.isAvailable()?null:this._instance.config.disable_conversations?"disabled_by_config":so(this._instance.config)?"disabled_for_toolbar":this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut()?"consent_opted_out":this.Xl===!1?"remote_config_failed":x(this.Ql)?this.Xl?"disabled_in_project":"remote_config_pending":this.Ql?D(this.Jl)||!this.Jl.token?"missing_token":$!=null&&$.__PosthogExtensions__?this.Kl?"initializing":this.Yl?"load_failed":"not_loaded":"extensions_unavailable":"disabled_in_project"}isVisible(){var t,e;return(t=(e=this._conversationsManager)==null?void 0:e.isVisible())!==null&&t!==void 0&&t}sendMessage(t,e,s){var r=this;return X((function*(){return r._conversationsManager?r._conversationsManager.sendMessage(t,e,s):(Ue.warn(Dt),null)}))()}getMessages(t,e){var s=this;return X((function*(){return s._conversationsManager?s._conversationsManager.getMessages(t,e):(Ue.warn(Dt),null)}))()}markAsRead(t){var e=this;return X((function*(){return e._conversationsManager?e._conversationsManager.markAsRead(t):(Ue.warn(Dt),null)}))()}getTickets(t){var e=this;return X((function*(){return e._conversationsManager?e._conversationsManager.getTickets(t):(Ue.warn(Dt),null)}))()}requestRestoreLink(t){var e=this;return X((function*(){return e._conversationsManager?e._conversationsManager.requestRestoreLink(t):(Ue.warn(Dt),null)}))()}restoreFromToken(t){var e=this;return X((function*(){return e._conversationsManager?e._conversationsManager.restoreFromToken(t):(Ue.warn(Dt),null)}))()}restoreFromUrlToken(){var t=this;return X((function*(){return t._conversationsManager?t._conversationsManager.restoreFromUrlToken():(Ue.warn(Dt),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()}}},Af={logs:class{constructor(t){var e,s=this;this.iu=!1,this.ru=!1,this.rt=se("[logs]"),this.nu=b({},this.rt,{error(){for(var r=arguments.length,n=new Array(r),i=0;r>i;i++)n[i]=arguments[i];n.some(Vl)||s.rt.error(...n)}}),this.tr=[],this.su=[],this.Sa=0,this.au=()=>{var r,n;this.Sa=0,(r=this.ou)==null||r.onReconnect(),(n=this.lu)==null||n.onReconnect()},this._instance=t,this._instance&&(e=this._instance.config.logs)!=null&&e.captureConsoleLogs&&(this.iu=!0),v&&ne(v,"online",this.au)}uu(t,e,s,r){var n,i=(function(o,a){var l,u,c,d,h,p,f,g=(l=o?.flushIntervalMs)!==null&&l!==void 0?l:3e3,m=(u=o?.maxBufferSize)!==null&&u!==void 0?u:100,_=a!=null&&a.consoleCapture?void 0:(c=o?.maxLogsPerInterval)!==null&&c!==void 0?c:1e3,w=x(_)?Math.max(m,2048):Math.max(m,_),E=o?.resourceAttributes;return{serviceName:(d=(h=E?.["service.name"])!==null&&h!==void 0?h:o?.serviceName)!==null&&d!==void 0?d:a?.serviceNameDefault,serviceVersion:(p=E?.["service.version"])!==null&&p!==void 0?p:o?.serviceVersion,environment:(f=E?.["deployment.environment"])!==null&&f!==void 0?f:o?.environment,resourceAttributes:E,beforeSend:o?.beforeSend,flushIntervalMs:g,maxBufferSize:m,maxQueueSize:w,maxBatchRecordsPerPost:100,rateCapWindowMs:g,maxLogsPerInterval:_,backgroundFlushBudgetMs:0,terminationFlushBudgetMs:0}})((n=this._instance)==null||(n=n.config)==null?void 0:n.logs,s);return[new Th(this.hu(t,e),i,this.nu,(()=>this.du()),(o=>o()),void 0,r),i]}vu(){var t,e=(t=this._instance)==null||(t=t.config)==null?void 0:t.logs;if(!this.ou||this.cu!==e){var s;(s=this.ou)==null||s.reset(),this.cu=e;var r=this.uu((()=>this.tr),(n=>{this.tr=n}));this.ou=r[0],this.fu=r[1]}return this.ou}pu(){var t,e=(t=this._instance)==null||(t=t.config)==null?void 0:t.logs;if(!this.lu||this.gu!==e){var s;(s=this.lu)==null||s.reset(),this.gu=e;var r=this.uu((()=>this.su),(n=>{this.su=n}),{serviceNameDefault:"posthog-browser-logs",consoleCapture:!0},ql);this.lu=r[0],this.mu=r[1]}return this.lu}initialize(){this.loadIfEnabled()}onRemoteConfig(t){var e;if(t.ok){var s=(e=t.config.logs)==null?void 0:e.captureConsoleLogs;!D(s)&&s&&(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){Vl(t)||this.rt.error("PostHog logs flush failed:",t)}loadIfEnabled(){if(this.iu&&!this.ru){var t=$?.__PosthogExtensions__;if(t){var e=t.loadExternalDependency;e?e(this._instance,"logs",(s=>{var r;s||(r=t.logs)==null||!r.initializeLogs?this.rt.error("Could not load logs script",s):(t.logs.initializeLogs(this._instance),this.ru=!0)})):this.rt.error(qo)}else this.rt.error("PostHog Extensions not found.")}}hu(t,e){var s=this._instance;return{get isDisabled(){return!1},get optedOut(){return!s.is_capturing()},getPersistedProperty:r=>r===ut.LogsQueue?t():void 0,setPersistedProperty(r,n){var i;r===ut.LogsQueue&&e((i=n)!==null&&i!==void 0?i:[])},Ot:r=>this.Ot(r),getLibraryId:()=>Y.LIB_NAME,getLibraryVersion:()=>Y.LIB_VERSION}}Ot(t){return new Promise((e=>{if(Ru(this.Sa,3))e({kind:"fatal",error:ki(void 0,"logs endpoint is unreachable, dropping batch")});else{var s=!1,r=i=>{s||(s=!0,clearTimeout(n),e(i))},n=setTimeout((()=>{this.rt.warn("Logs request timed out before receiving a response"),r({kind:"retry-later",error:ki(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:i=>{var o=i.statusCode;if(this.ku(o),o>=200&&300>o)r({kind:"ok"});else if(o===413)r({kind:"too-large"});else if(o!==0&&o!==429&&500>o)r({kind:"fatal",error:new Error("logs request failed with status "+o)});else{var a;o===0?(i.error||this.rt.warn("Logs request failed before receiving an HTTP response"),r({kind:"retry-later",error:ki(i.error,"logs request failed before receiving an HTTP response")})):r({kind:"retry-later",error:(a=i.error)!==null&&a!==void 0?a:new Error("logs request failed with status "+o)})}}})}}))}ku(t){(t!==0||this._instance.__loaded)&&(this.Sa=Tu(t,this.Sa,3,(()=>this.rt.warn("Log requests are failing before receiving an HTTP response; this can happen due to network issues, CORS, browser blocking, or ad blockers. Stopped sending logs; will try again when connectivity changes."))))}bu(t){this.tr.length>0&&this.xu(t,this.tr,this.fu,Y.LIB_NAME,(e=>{this.tr=e})),this.su.length>0&&this.xu(t,this.su,this.mu,ql,(e=>{this.su=e}))}xu(t,e,s,r,n){if(e.length!==0){var i=e.map((a=>a.record));n([]);var o=ru(i,su(s,Y.LIB_NAME,Y.LIB_VERSION),r,Y.LIB_VERSION);this._instance._send_request({method:"POST",url:this.wu(),data:o,compression:"best-available",batchKey:"logs",transport:t})}}wu(){return this._instance.requestRouter.endpointFor("api","/i/v1/logs")+"?token="+encodeURIComponent(this._instance.config.token)}du(){var t,e={};if(e.distinctId=this._instance.get_distinct_id(),this._instance.sessionManager){var s=this._instance.sessionManager.checkAndGetSessionAndWindowId(!0),r=s.windowId,n=s.sessionStartTimestamp,i=s.lastActivityTimestamp;e.sessionId=s.sessionId,e.windowId=r,D(n)||(e.sessionStartTimestamp=n),D(i)||(e.lastActivityTimestamp=i)}if($!=null&&(t=$.location)!=null&&t.href&&(e.currentUrl=this._instance.config.disable_capture_url_hashes?Ct($.location.href):$.location.href),this._instance.featureFlags){var o=this._instance.featureFlags.getFlags();o&&o.length>0&&(e.activeFeatureFlags=o)}return e}}},$f={metrics:class{constructor(t){this.rt=se("[metrics]"),this._instance=t}initialize(){}vu(){var t,e,s=(t=this._instance)==null||(t=t.config)==null?void 0:t.metrics;return this.ou&&this.cu===s||((e=this.ou)==null||e.reset(),this.cu=s,this.ou=new Nh(this.hu(),(function(r){var n,i,o,a,l,u=r?.resourceAttributes;return{serviceName:(n=u?.["service.name"])!==null&&n!==void 0?n:r?.serviceName,serviceVersion:(i=u?.["service.version"])!==null&&i!==void 0?i:r?.serviceVersion,environment:(o=u?.["deployment.environment"])!==null&&o!==void 0?o:r?.environment,resourceAttributes:u,beforeSend:r?.beforeSend,flushIntervalMs:(a=r?.flushIntervalMs)!==null&&a!==void 0?a:1e4,maxSeriesPerFlush:(l=r?.maxSeriesPerFlush)!==null&&l!==void 0?l:1e3}})(s),this.rt)),this.ou}count(t,e,s){e===void 0&&(e=1),this.vu().count(t,e,s)}gauge(t,e,s){this.vu().gauge(t,e,s)}histogram(t,e,s){this.vu().histogram(t,e,s)}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((s=>this.rt.error("PostHog metrics flush failed:",s)))}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:s=>e.Jt(s),getLibraryId:()=>Y.LIB_NAME,getLibraryVersion:()=>Y.LIB_VERSION}}Jt(t,e){return new Promise((s=>{var r=!1,n=o=>{r||(r=!0,clearTimeout(i),s(o))},i=setTimeout((()=>n({kind:"retry-later",error:new Error("metrics request timed out")})),9e4);this._instance._send_request(b({method:"POST",url:this.Su(),data:t,compression:"best-available",batchKey:"metrics"},e&&{transport:e},{fireCallbackOnDrop:!0,callback(o){var a=o.statusCode;if(a>=200&&300>a)n({kind:"ok"});else if(a===413)n({kind:"too-large"});else if(a!==0&&a!==429&&500>a)n({kind:"fatal",error:new Error("metrics request failed with status "+a)});else{var l;n({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)}}},Rf=b({},Rn,wf,bf,Ef,Sf,xf,If,kf,Cf,Ff,Pf,Af,$f);Te.__defaultExtensionClasses=b({},Rf);(function(){Y.SDK_DIST_CHANNEL="npm";var t=Ys[os]=new Te;return(function(){function e(){e.done||(e.done=!0,ad=!1,Z(Ys,(function(s){s._dom_loaded()})))}C!=null&&C.addEventListener?C.readyState==="complete"?e():ne(C,"DOMContentLoaded",e,{capture:!1}):v&&k.error("Browser doesn't support `document.addEventListener` so PostHog couldn't be initialized")})(),t})();const cd="CodeFile",ud="GeneratedCode",Tf={CustomAction:"A",CustomWidget:"W",CustomFunction:"F",CustomClass:"C",CodeFile:"C"};function kt(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function fo(t){return String(t||"").trim().replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function Nf(t={},e=0){const s=fo(t.artifactType||t.type||cd),r=fo(t.artifactName||t.name||t.fileName||`${ud}-${e+1}`);return`${s||"artifact"}-${r||e+1}`}function dd(t={},e=0){const s=kt(t),r=s.artifactType||s.type||cd,n=s.artifactName||s.name||ud;let i=s.fileName||n;return i.endsWith(".dart")||(i+=".dart"),{id:fo(s.id)||Nf({...s,artifactType:r,artifactName:n,fileName:i},e),artifactType:r,artifactName:n,fileName:i,deployPath:s.deployPath||"",description:s.description||"",code:s.code||s.content||"",dependencies:hd(s.dependencies),imports:Array.isArray(s.imports)?s.imports:[],publicApi:Array.isArray(s.publicApi)?s.publicApi:[],relationships:pd(s.relationships),deployStatus:s.deployStatus||"pending",review:s.review||null,metadata:kt(s.metadata),codeType:s.codeType||Tf[r]||"O"}}function hd(t){return t?Array.isArray(t)?t.map(e=>{if(typeof e=="string")return{name:e,version:null,inferred:!1};const s=kt(e),r=s.name||s.package;return r?{name:r,version:s.version||null,versionRequired:!!(s.versionRequired||s.required),inferred:!!s.inferred,...s.reason?{reason:s.reason}:{}}:null}).filter(Boolean):Object.entries(kt(t)).map(([e,s])=>({name:e,version:s||null,inferred:!1})):[]}function pd(t){return t?(Array.isArray(t)?t:[t]).map(e=>{const s=kt(e);return!s.from&&!s.to?null:{from:s.from||null,to:s.to||null,type:s.type||"uses",description:s.description||""}}).filter(Boolean):[]}function go(t){if(typeof t!="string")return null;const e=t.trim();if(!e)return null;try{return JSON.parse(e)}catch{const s=e.match(/```(?:json)?\s*([\s\S]*?)```/i);if(!s)return null;try{return JSON.parse(s[1].trim())}catch{return null}}}function or(t,e={}){const s=[],r=typeof t=="string"?go(t):t,i=kt(r||{});!r&&typeof t=="string"&&s.push("Structured bundle parse failed; using legacy single-artifact fallback.");const o=Array.isArray(i.artifacts)?i.artifacts:[{artifactType:i.artifactType||e.artifactType,artifactName:i.artifactName||e.artifactName,fileName:i.fileName||e.fileName,description:i.description,code:i.code||e.code||(typeof t=="string"?t:""),dependencies:i.dependencies||e.dependencies,relationships:i.relationships||e.relationships}];o.forEach((d,h)=>{!d?.artifactType&&!d?.type&&s.push(`Artifact ${h+1} has no artifactType; it will deploy as a standalone code file under lib/custom_code/ root.`)});const a=o.map((d,h)=>dd(d,h)),l=new Map(o.map((d,h)=>[kt(d).id,a[h]?.id]).filter(([d,h])=>d&&h)),u=d=>l.get(d)||d,c=pd(i.relationships||e.relationships).map(d=>({...d,from:d.from?u(d.from):d.from,to:d.to?u(d.to):d.to}));return{schemaVersion:i.schemaVersion||e.schemaVersion||null,id:i.id||e.id||"bundle-current",title:i.title||i.name||e.title||"Generated artifact bundle",description:i.description||e.description||"",artifacts:a,dependencies:hd(i.dependencies||e.dependencies),relationships:c,deployOrder:Array.isArray(i.deployOrder)?i.deployOrder.map(u):a.map(d=>d.id),warnings:[...s,...Array.isArray(i.warnings)?i.warnings:[]],metadata:kt(i.metadata)}}function gn(t){return or(t).artifacts[0]||dd()}function yt(t){if(typeof t!="string")return t??"";const e=t.trim();if(!e)return"";try{return JSON.parse(e)}catch{return t}}function ys(t){return JSON.stringify(t,null,2)}function Mf(t){return ys({task:"architect",userRequest:String(t??"")})}function Lf(t){const e=yt(t);return e&&typeof e=="object"&&typeof e.task=="string"?ys(e):ys({task:"generate_bundle",bundleSpec:e})}function Of(t){return ys({task:"review_bundle",generatedBundle:yt(t),outputRequirements:{bundleReview:["status","score","summary","manualActions","findings"],scoreRange:[0,100],eachArtifact:["id","review.status","review.findings"],manualActions:{definition:"Setup the developer must perform by hand in the FlutterFlow editor that FlutterFlow will NOT do for them.",exclude:["creating the Custom Action, Widget or Code File itself - deploying the code creates it","declaring parameters or return values FlutterFlow derives from the function signature","anything that resolves as a side effect of using the action or widget in the editor","generic advice such as testing, reviewing or rebuilding the app"],preferEmpty:"Return an empty array when nothing qualifies - an empty list is the expected result for most bundles."}}})}function Qo(t,e=null){const s={stage:t};return e!=null&&(s.bundle=yt(e)),s}function Df({bundleSpec:t,artifactBundle:e,bundleReview:s,artifactId:r,userFeedback:n}){return ys({task:"regenerate_artifact",artifactId:r,bundleSpec:yt(t),artifactBundle:yt(e),bundleReview:yt(s),userFeedback:String(n)})}function fd({bundleSpec:t,artifactBundle:e,bundleReview:s,userFeedback:r}){return ys({task:"regenerate_bundle",bundleSpec:yt(t),artifactBundle:yt(e),bundleReview:yt(s),userFeedback:String(r??"")})}const Gl={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"},Bf=["sanitizationResult","modelArmor","modelArmorResult","data","result","error"];function Le(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function jf(t){return Le(t)?typeof t.filterMatchState=="string"||typeof t.invocationResult=="string"||Array.isArray(t.matchedFilters)||Le(t.filterSummary)||Le(t.filterResults):!1}function gd(t,e=0){if(!Le(t)||e>3)return null;if(jf(t))return t;for(const s of Bf){const r=t[s];if(Le(r)){const n=gd(r,e+1);if(n)return n}}return null}function mn(t){return Array.isArray(t)?t.some(mn):Le(t)?t.matched===!0||t.matchState==="MATCH_FOUND"?!0:Object.values(t).some(mn):!1}function mo(t){return Array.isArray(t)?t.some(mo):Le(t)?typeof t.executionState=="string"&&t.executionState!=="EXECUTION_SUCCESS"?!0:Object.values(t).some(mo):!1}function md(t){return{csamFilterFilterResult:"csam",maliciousUriFilterResult:"malicious_uris",piAndJailbreakFilterResult:"pi_and_jailbreak",raiFilterResult:"rai",sdpFilterResult:"sdp",virusScanFilterResult:"virus_scan"}[t]||t}function Uf(t,e){if(Le(t))for(const[s,r]of Object.entries(t)){if(!Le(r))continue;const n=Le(r.categories)?r.categories:{},i=Object.entries(n).filter(([,o])=>Le(o)&&o.matched===!0).map(([o])=>o);i.length>0?i.forEach(o=>e.add(o)):r.matched===!0&&e.add(md(s))}}function Hf(t,e){if(!t)return;const s=Array.isArray(t)?t.flatMap(r=>Le(r)?Object.entries(r):[]):Object.entries(t);for(const[r,n]of s){if(!mn(n))continue;const i=md(r),o=n?.raiFilterResult?.raiFilterTypeResults||(i==="rai"?n?.raiFilterTypeResults:null),a=Le(o)?Object.entries(o).filter(([,l])=>mn(l)).map(([l])=>l):[];a.length>0?a.forEach(l=>e.add(l)):e.add(i)}}function Wf(t){return Gl[t]?Gl[t]:String(t).replace(/([a-z])([A-Z])/g,"$1 $2").replace(/_/g," ").toLowerCase()}function Kl(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 zf(t){const e=gd(t);if(!e)return null;const s=new Set(Array.isArray(e.matchedFilters)?e.matchedFilters:[]);Uf(e.filterSummary,s),Hf(e.filterResults,s);const r=e.blocked===!0||e.filterMatchState==="MATCH_FOUND"||s.size>0,n=e.invocationResult||null,i=mo(e.filterSummary||e.filterResults);return!r&&!i&&!["PARTIAL","FAILURE"].includes(n)?null:{kind:r?"blocked":"unavailable",invocationResult:n,matchedFilters:[...s]}}function qf(t,e){const s=zf(t);if(!s)return null;const r=[...new Set(s.matchedFilters.map(Wf))],n=s.kind==="blocked",i=new Error(n?`Safety screening blocked this pipeline step for ${Kl(r)}.`:"Safety screening could not be completed. Please try again.");return i.name="ModelArmorError",i.code=n?"MODEL_ARMOR_BLOCKED":"MODEL_ARMOR_UNAVAILABLE",i.isModelArmor=!0,i.pipelineStep=e,i.userTitle=n?"Request blocked for safety":"Safety check unavailable",i.userMessage=n?`The safety check detected ${Kl(r)}. Edit your request to remove or rephrase the flagged content, then run the pipeline again.`:"The safety service did not finish all of its checks. Please wait a moment and run the pipeline again.",i.retryExplanation=n?"Trying another model would not change this safety decision.":"A fallback model was not attempted because safety screening must complete first.",i.matchedFilters=s.matchedFilters,i}function Vf(t){return String(t||"").replace(/\/\*[\s\S]*?\*\//g,"").replace(/\/\/[^\n]*/g,"")}function Jl(t){const e=/^(import|export|part|library|class|enum|extension|typedef|mixin|abstract|const|final|var|late)\b/,s=[];for(const r of Vf(t).split(` +`)){if(!/^[A-Za-z_$]/.test(r)||e.test(r))continue;const n=r.match(/^[\w$<>,?\s[\]]+?\s([a-zA-Z_$][\w$]*)\s*\(/);n&&s.push(n[1])}return s}function ea(t,e){const s=t.replace(/\.dart$/,"");if(e==="W")return s.replace(/(^|_)(\w)/g,(r,n,i)=>i.toUpperCase());if(e==="A"){const r=s.replace(/(^|_)(\w)/g,(n,i,o)=>o.toUpperCase());return r.charAt(0).toLowerCase()+r.slice(1)}return e==="F"?"CustomFunctions":e==="C"?t.endsWith(".dart")?t:`${t}.dart`:s}async function Yl(t){const e=new TextEncoder().encode(String(t||"")),s=await globalThis.crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(s),r=>r.toString(16).padStart(2,"0")).join("")}async function Gf(t,e=new Map){const s={},r=new Set;for(const[o,a]of t.entries()){if(a.type==="D"||a.type==="O")continue;const l=ea(o,a.type),u={old_identifier_name:l,new_identifier_name:l,type:a.type,is_deleted:!1,current_checksum:await Yl(a.content)},c=e.get(a.path);if(c!==void 0&&(u.original_checksum=await Yl(c)),s[o]=u,a.type==="F"){const d=Jl(a.content);(d.length>0?d:[a.functionName].filter(Boolean)).forEach(p=>r.add(p))}}const n=new Set(Jl(e.get("lib/flutter_flow/custom_functions.dart")||"")),i={functions_to_rename:[],functions_to_delete:[],functions_to_add:Array.from(r).filter(o=>!n.has(o))};return{fileMapContents:JSON.stringify(s),functionsMapContents:JSON.stringify(i)}}const Kf=new Set(["CustomWidget","CustomAction","CustomFunction","CustomClass","CodeFile"]),Zl={CustomWidget:"custom_code/widgets/",CustomAction:"custom_code/actions/",CustomFunction:"flutter_flow/custom_functions.dart",CustomClass:"custom_code/",CodeFile:"custom_code/"},Jf=new Set(["void","dynamic","String","int","double","num","bool","Color","DateTime","DateTimeRange","LatLng","FFPlace","FFUploadedFile","DocumentReference","List"]),Yf=["Struct","Record"],Zf=[{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=>Ii(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=>Ii(t).some(e=>{const s=/^\s*final\s+(?:double|int|String|bool|Color|num)\s+(\w+)\s*;/gm;let r;for(;(r=s.exec(e))!==null;){const n=r[1];if(!(new RegExp(`this\\.${n}\\s*=(?!=)`).test(e)||new RegExp(`[:,]\\s*${n}\\s*=(?!=)`).test(e)))return!0}return!1}),pos:`class W extends StatefulWidget { const W({required this.value}); final double value; @@ -25,44 +25,44 @@ 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 Qe(t,e,s){return{artifactId:t.id,artifactName:t.artifactName,artifactType:t.artifactType,severity:e,message:s}}function ar(t){let e="",s=0;for(;s"&&(s--,s===0))return{inner:t.slice(e+1,r),end:r+1};return null}function Xf(t,e){const s=new RegExp(`class\\s+${e}\\b[^{]*\\{`).exec(t);if(!s)return null;let r=0;for(let n=s.index+s[0].length-1;nQf(t).usable);function tg(t=""){const e=ar(t);return eg.filter(s=>s.detect(e)).map(({id:s,severity:r,message:n})=>({id:s,severity:r,message:n}))}function sg(t){const e=[],s=t.matchAll(/\bFuture\b/g);for(const r of s){let n=r.index+6,i=null;const o=n;for(;no;if(t[n]==="<"){const u=Zf(t,n);if(!u||(i=u.inner.replace(/\s+/g," ").trim(),n=u.end,!/\s/.test(t[n]||"")))continue;for(;nXl(o.functionName)===r);if(n)return n;const i=o=>!o.functionName.startsWith("_");return s.find(i)||s[0]}function Tn(t=""){return Array.from(ar(t).matchAll(/\b(?:class|enum)\s+([A-Za-z_]\w*)/g),e=>e[1])}function rg(t="",e=""){return ta(t,e)?.returnType||null}function Ql(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 ng(t,e){const s=Tn(e);if(s.length===0)return null;const n=String(t||"").split("/").pop().replace(/\.dart$/,"");if(s.some(l=>Ql(l)===n)||s.length>1)return null;const[o]=s,a=`${Ql(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 sa(t){return String(t||"").replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,"")}function ig(t,e,s=""){const r=ta(e,s)?.functionName;if(!r)return null;const n=String(t||"").split("/").pop(),i=ea(n,"A");if(i===r)return null;const o=`${sa(r)}.dart`;return`File name "${n}" does not match Action "${r}". FlutterFlow derives the action from the file name, so it looks for "${i}" and reports Action "${i}" declaration not found. Rename the file to "${o}" - FlutterFlow puts an underscore before every capital - or rename the function to "${i}".`}function og(t="",e=""){return ta(t,e)!==null}function ag(t,e=new Set){return(t?.match(/[A-Za-z_]\w*/g)||[]).filter(r=>Kf.has(r)?!1:!Jf.some(i=>r.endsWith(i))||e.has(r))}function lg(t,{functionName:e="",declaredTypes:s=new Set}={}){const r=rg(t,e),n=ag(r,s);if(n.length===0)return null;const[i]=n;let o;return s.has(i)?o=`uses Code File type "${i}", which FlutterFlow cannot process as an Action Return Value`:r===i?o="is not a FlutterFlow Action Return Value":o=`uses type "${i}", which is not a FlutterFlow Action Return Value`,`CustomAction return type "${r}" ${o}. Return JSON (Future) or an existing FlutterFlow Data Type (*Struct) instead.`}function cg(t,e={}){const s=[],r=t.fileName||"",n=t.code||"";if(Gf.has(t.artifactType)||s.push(Qe(t,"error",`Unsupported artifact type "${t.artifactType}".`)),r.endsWith(".dart")||s.push(Qe(t,"error","FlutterFlow custom code artifacts must use .dart files.")),!n.trim())return s.push(Qe(t,"warning","Generated artifact has no Dart code yet.")),s;if(t.artifactType==="CustomWidget"){/class\s+\w+\s+extends\s+(StatelessWidget|StatefulWidget)/.test(n)||s.push(Qe(t,"warning","CustomWidget code should declare a widget class extending StatelessWidget or StatefulWidget."));for(const i of tg(n))s.push(Qe(t,i.severity,i.message))}if(t.artifactType==="CustomAction"&&!og(n,t.artifactName)&&s.push(Qe(t,"warning","CustomAction code should expose an async Future function callable from FlutterFlow.")),t.artifactType==="CustomAction"){const i=e.declaredTypes||new Set(Tn(n)),o=lg(n,{functionName:t.artifactName,declaredTypes:i});o&&s.push(Qe(t,"error",o));const a=ig(r,n,t.artifactName);a&&s.push(Qe(t,"error",a))}if(t.artifactType==="CustomFunction"&&/class\s+\w+\s+extends\s+(StatelessWidget|StatefulWidget)/.test(n)&&s.push(Qe(t,"warning","CustomFunction should be a callable function, not a widget class.")),t.artifactType==="CustomClass"||t.artifactType==="CodeFile"){const i=ng(r,n);i&&s.push(Qe(t,"info",i))}return s}function ug(t){const e=Array.isArray(t?.artifacts)?t.artifacts:[],s=new Set(e.flatMap(i=>Tn(i.code||""))),r=e.flatMap(i=>cg(i,{declaredTypes:s})),n=e.map(i=>({artifactId:i.id,fileName:i.fileName,pathHint:Zl[i.artifactType]||Zl.CodeFile}));return{valid:r.every(i=>i.severity!=="error"),findings:r,deployHints:n}}const ec="// DO NOT REMOVE OR MODIFY THE CODE ABOVE!";function tc(t){return(/^\s*import\s+['"]([^'"]+)['"]/.exec(t)||[])[1]||null}function dg(t=""){const e=t.indexOf(ec);return e===-1?t:t.slice(e+ec.length).replace(/^\s*\n/,"")}const hg=/^\s*import\s+['"][^'"]+['"]\s*;\s*(?:\/\/.*)?$/;function pg(t="",e=""){const s=dg(t),r=new Set((e.match(/^\s*import .*$/gm)||[]).map(tc).filter(Boolean)),n=s.split(` -`).filter(i=>{const o=tc(i);return o===null||!r.has(o)?!0:!hg.test(i)}).join(` -`).replace(/^\s*\/\/ Automatic FlutterFlow imports\s*$/m,"").replace(/^\s*\n+/,"");return e+n}const fg=new Set(["flutter","flutter_test","flutter_driver","flutter_localizations"]);function vd(t){let e="",s=0;for(;s{const r=s.name||s.package;if(!r||r==="flutter")return e;const n=s.versionRequired||s.required;return e[r]=n&&s.version||"",e},{})}function yg(t){const e=new Map,s=new Map,r=[];for(const n of t)e.has(n.fileName)?r.push(`Duplicate deploy file name "${n.fileName}" for artifacts "${e.get(n.fileName)}" and "${n.artifactId}".`):e.set(n.fileName,n.artifactId),s.has(n.path)?r.push(`Duplicate deploy path "${n.path}" for artifacts "${s.get(n.path)}" and "${n.artifactId}".`):s.set(n.path,n.artifactId);return r}function wg(t,e={}){const s=Array.isArray(t?.artifacts)?t.artifacts:[],n=(e.selectedArtifactIds||t?.deployOrder||s.map(p=>p.id)).map(p=>s.find(f=>f.id===p)).filter(Boolean),i=[...t?.warnings||[]];let o=[];n.forEach(p=>{const f=_g(p),g=p.fixedCode||p.code||"",m=p.codeType||mg[p.artifactType]||Ne.OTHER;g.trim()||i.push(`${p.artifactName||p.id} has no generated code.`),o.push({artifactId:p.id,artifactName:p.artifactName,artifactType:p.artifactType,fileName:f,content:g,type:m,path:p.deployPath||vg(f,m),deployPath:p.deployPath||"",deployMode:"customCodeSync"})});const a="lib/flutter_flow/custom_functions.dart",l=o.map((p,f)=>({entry:p,index:f})).filter(({entry:p})=>p.type===Ne.FUNCTION&&p.path===a);if(l.length>1){const p=l[0],f={...p.entry,artifactId:l.map(({entry:m})=>m.artifactId).join("+"),artifactName:p.entry.artifactName,content:l.map(({entry:m})=>`// ${m.artifactId} +`;)s++;e+=" "}else if(r==="/*"){for(s+=2;s"&&(s--,s===0))return{inner:t.slice(e+1,r),end:r+1};return null}function Qf(t,e){const s=new RegExp(`class\\s+${e}\\b[^{]*\\{`).exec(t);if(!s)return null;let r=0;for(let n=s.index+s[0].length-1;neg(t).usable);function sg(t=""){const e=ar(t);return tg.filter(s=>s.detect(e)).map(({id:s,severity:r,message:n})=>({id:s,severity:r,message:n}))}function rg(t){const e=[],s=t.matchAll(/\bFuture\b/g);for(const r of s){let n=r.index+6,i=null;const o=n;for(;no;if(t[n]==="<"){const u=Xf(t,n);if(!u||(i=u.inner.replace(/\s+/g," ").trim(),n=u.end,!/\s/.test(t[n]||"")))continue;for(;nXl(o.functionName)===r);if(n)return n;const i=o=>!o.functionName.startsWith("_");return s.find(i)||s[0]}function Tn(t=""){return Array.from(ar(t).matchAll(/\b(?:class|enum)\s+([A-Za-z_]\w*)/g),e=>e[1])}function ng(t="",e=""){return ta(t,e)?.returnType||null}function Ql(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 ig(t,e){const s=Tn(e);if(s.length===0)return null;const n=String(t||"").split("/").pop().replace(/\.dart$/,"");if(s.some(l=>Ql(l)===n)||s.length>1)return null;const[o]=s,a=`${Ql(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 sa(t){return String(t||"").replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,"")}function og(t,e,s=""){const r=ta(e,s)?.functionName;if(!r)return null;const n=String(t||"").split("/").pop(),i=ea(n,"A");if(i===r)return null;const o=`${sa(r)}.dart`;return`File name "${n}" does not match Action "${r}". FlutterFlow derives the action from the file name, so it looks for "${i}" and reports Action "${i}" declaration not found. Rename the file to "${o}" - FlutterFlow puts an underscore before every capital - or rename the function to "${i}".`}function ag(t="",e=""){return ta(t,e)!==null}function lg(t,e=new Set){return(t?.match(/[A-Za-z_]\w*/g)||[]).filter(r=>Jf.has(r)?!1:!Yf.some(i=>r.endsWith(i))||e.has(r))}function cg(t,{functionName:e="",declaredTypes:s=new Set}={}){const r=ng(t,e),n=lg(r,s);if(n.length===0)return null;const[i]=n;let o;return s.has(i)?o=`uses Code File type "${i}", which FlutterFlow cannot process as an Action Return Value`:r===i?o="is not a FlutterFlow Action Return Value":o=`uses type "${i}", which is not a FlutterFlow Action Return Value`,`CustomAction return type "${r}" ${o}. Return JSON (Future) or an existing FlutterFlow Data Type (*Struct) instead.`}function ug(t,e={}){const s=[],r=t.fileName||"",n=t.code||"";if(Kf.has(t.artifactType)||s.push(Qe(t,"error",`Unsupported artifact type "${t.artifactType}".`)),r.endsWith(".dart")||s.push(Qe(t,"error","FlutterFlow custom code artifacts must use .dart files.")),!n.trim())return s.push(Qe(t,"warning","Generated artifact has no Dart code yet.")),s;if(t.artifactType==="CustomWidget"){/class\s+\w+\s+extends\s+(StatelessWidget|StatefulWidget)/.test(n)||s.push(Qe(t,"warning","CustomWidget code should declare a widget class extending StatelessWidget or StatefulWidget."));for(const i of sg(n))s.push(Qe(t,i.severity,i.message))}if(t.artifactType==="CustomAction"&&!ag(n,t.artifactName)&&s.push(Qe(t,"warning","CustomAction code should expose an async Future function callable from FlutterFlow.")),t.artifactType==="CustomAction"){const i=e.declaredTypes||new Set(Tn(n)),o=cg(n,{functionName:t.artifactName,declaredTypes:i});o&&s.push(Qe(t,"error",o));const a=og(r,n,t.artifactName);a&&s.push(Qe(t,"error",a))}if(t.artifactType==="CustomFunction"&&/class\s+\w+\s+extends\s+(StatelessWidget|StatefulWidget)/.test(n)&&s.push(Qe(t,"warning","CustomFunction should be a callable function, not a widget class.")),t.artifactType==="CustomClass"||t.artifactType==="CodeFile"){const i=ig(r,n);i&&s.push(Qe(t,"info",i))}return s}function dg(t){const e=Array.isArray(t?.artifacts)?t.artifacts:[],s=new Set(e.flatMap(i=>Tn(i.code||""))),r=e.flatMap(i=>ug(i,{declaredTypes:s})),n=e.map(i=>({artifactId:i.id,fileName:i.fileName,pathHint:Zl[i.artifactType]||Zl.CodeFile}));return{valid:r.every(i=>i.severity!=="error"),findings:r,deployHints:n}}const ec="// DO NOT REMOVE OR MODIFY THE CODE ABOVE!";function tc(t){return(/^\s*import\s+['"]([^'"]+)['"]/.exec(t)||[])[1]||null}function hg(t=""){const e=t.indexOf(ec);return e===-1?t:t.slice(e+ec.length).replace(/^\s*\n/,"")}const pg=/^\s*import\s+['"][^'"]+['"]\s*;\s*(?:\/\/.*)?$/;function fg(t="",e=""){const s=hg(t),r=new Set((e.match(/^\s*import .*$/gm)||[]).map(tc).filter(Boolean)),n=s.split(` +`).filter(i=>{const o=tc(i);return o===null||!r.has(o)?!0:!pg.test(i)}).join(` +`).replace(/^\s*\/\/ Automatic FlutterFlow imports\s*$/m,"").replace(/^\s*\n+/,"");return e+n}const gg=new Set(["flutter","flutter_test","flutter_driver","flutter_localizations"]);function vd(t){let e="",s=0;for(;s{const r=s.name||s.package;if(!r||r==="flutter")return e;const n=s.versionRequired||s.required;return e[r]=n&&s.version||"",e},{})}function yg(t){const e=new Map,s=new Map,r=[];for(const n of t)e.has(n.fileName)?r.push(`Duplicate deploy file name "${n.fileName}" for artifacts "${e.get(n.fileName)}" and "${n.artifactId}".`):e.set(n.fileName,n.artifactId),s.has(n.path)?r.push(`Duplicate deploy path "${n.path}" for artifacts "${s.get(n.path)}" and "${n.artifactId}".`):s.set(n.path,n.artifactId);return r}function wg(t,e={}){const s=Array.isArray(t?.artifacts)?t.artifacts:[],n=(e.selectedArtifactIds||t?.deployOrder||s.map(p=>p.id)).map(p=>s.find(f=>f.id===p)).filter(Boolean),i=[...t?.warnings||[]];let o=[];n.forEach(p=>{const f=_g(p),g=p.fixedCode||p.code||"",m=p.codeType||mg[p.artifactType]||Ne.OTHER;g.trim()||i.push(`${p.artifactName||p.id} has no generated code.`),o.push({artifactId:p.id,artifactName:p.artifactName,artifactType:p.artifactType,fileName:f,content:g,type:m,path:p.deployPath||vg(f,m),deployPath:p.deployPath||"",deployMode:"customCodeSync"})});const a="lib/flutter_flow/custom_functions.dart",l=o.map((p,f)=>({entry:p,index:f})).filter(({entry:p})=>p.type===Ne.FUNCTION&&p.path===a);if(l.length>1){const p=l[0],f={...p.entry,artifactId:l.map(({entry:m})=>m.artifactId).join("+"),artifactName:p.entry.artifactName,content:l.map(({entry:m})=>`// ${m.artifactId} ${m.content}`).join(` `)},g=new Set(l.slice(1).map(({index:m})=>m));o=o.filter((m,_)=>!g.has(_)),o[p.index]=f}const u={...sc(t?.dependencies),...n.reduce((p,f)=>({...p,...sc(f.dependencies)}),{})},c={};n.forEach(p=>{ra(p.code||"").forEach(f=>{f in u||(c[f]="")})});const d={...c,...u},h=yg(o);return{bundleId:t?.id||"bundle-current",title:t?.title||"Generated artifact bundle",fileEntries:o,dependencies:d,relationships:t?.relationships||[],warnings:i,errors:h}}function bg(t){return String(t||"").match(/\bclass\s+([A-Z][A-Za-z0-9_]*)\b/)?.[1]}function Eg(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 Sg(t,e){const r=[Eg(t),bg(e.content),e.artifactName].find(n=>/^[A-Z][A-Za-z0-9_]*$/.test(String(n||"")));if(!r)throw new Error(`Cannot derive a FlutterFlow custom class name for ${t}.`);return r}function xg(t,e=new Map){const s=[];for(const[r,n]of t.entries())n.type!=="C"||e.has(n.path)||s.push({artifactId:n.artifactId||r,className:Sg(r,n),content:n.content,fileName:r,path:n.path});return s}function kg(t,e){const s=new Set(e.map(r=>r.path));return new Map(Array.from(t.entries()).filter(([,r])=>!s.has(r.path)))}const rc={pass:0,warning:1,fail:2},Ig=["manualActions"];function De(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function gt(...t){for(const e of t){if(typeof e=="string"&&e.trim())return e.trim();if(Array.isArray(e)&&e.length>0){const s=e.filter(r=>typeof r=="string").join(` -`);if(s)return s}}return""}function tt(t){return t==null?[]:Array.isArray(t)?t:[t]}function Cg(t){const e=De(t).value??t;if(e==null||typeof e=="string"&&e.trim()==="")return null;const s=Number(e);if(Number.isFinite(s))return s;const r=String(t||"").match(/\bscore\b[^\d]{0,12}(\d{1,3})(?:\s*\/\s*100)?/i);return r?Number(r[1]):null}function We(t){return String(t||"").trim().replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function na(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 vo(...t){return t.filter(Boolean).reduce((e,s)=>rc[s]>rc[e]?s:e,"pass")}function _d(t,e="warning",s="review"){if(typeof t=="string")return{severity:e,message:t,suggestion:"",source:s};const r=De(t),n=gt(r.message,r.title,r.issue,r.description,r.summary);return n?{severity:na(r.severity||r.status||r.level)||e,message:n,suggestion:gt(r.suggestion,r.fix,r.recommendation,r.action),source:r.source||s}:null}function _o(t,e="review"){const s=De(t);return[["findings","warning"],["issues","warning"],["criticalIssues","fail"],["errors","fail"],["warnings","warning"],["recommendations","warning"],["requiredFixes","fail"],["suggestions","warning"]].flatMap(([n,i])=>tt(s[n]).map(o=>_d(o,i,e)).filter(Boolean))}function Fg(t,e,s=null){if(typeof t=="string")return{id:`${s||"bundle"}-manual-${e+1}`,title:t,detail:"",location:"",timing:"unspecified",artifactId:s,source:"Code Review"};const r=De(t),n=gt(r.title,r.action,r.step,r.message,r.name,r.description);return n?{id:r.id||`${s||"bundle"}-manual-${e+1}`,title:n,detail:gt(r.detail,r.instructions,r.description),location:gt(r.location,r.flutterFlowPath,r.path),timing:gt(r.timing,r.phase)||"unspecified",artifactId:s,source:gt(r.source)||"Code Review"}:null}function yo(t,e=null){const s=De(t);return Ig.flatMap(r=>tt(s[r])).map((r,n)=>Fg(r,n,e)).filter(Boolean)}function Pg(t){let e=typeof t=="string"?go(t):t;if(!e&&typeof t=="string")return{rawText:t,root:{}};const s=De(e);typeof s.content=="string"&&(e=go(s.content)||e);const r=De(e),n=De(r.reviewResult||r.codeReview||r.result);return{rawText:"",root:Object.keys(n).length?n:r}}function Ag(t,e){const s=[e.id,e.fileName,e.artifactName].map(We);return t.find(r=>{const n=De(r);return[n.id,n.fileName,n.artifactName,n.name].map(We).some(i=>i&&s.includes(i))})||null}function $g(t,e){return tt(t?.metadata?.compatibility?.deployHints).find(n=>We(n?.artifactId)===We(e.id)||We(n?.fileName)===We(e.fileName))?.pathHint||""}function Rg(t,e){return tt(t?.relationships).filter(s=>We(s?.from)===We(e.id)||We(s?.to)===We(e.id))}function Tg(t,e){return tt(t?.metadata?.compatibility?.findings).filter(s=>!s?.artifactId||We(s.artifactId)===We(e.id)).map(s=>_d(s,"warning","Compatibility check")).filter(Boolean)}function Ng(t,e,s,r){const n=Ag(e,s),i=De(n?.review||n||s.review),o=Object.keys(i).length>0,a=[..._o(i),...Tg(t,s)],l=yo(i,s.id),u=na(i.status||i.verdict||i.outcome||i.result),c=a.length?vo(...a.map(h=>h.severity)):null,d=vo(u,c,o?null:"warning");return{...s,index:r,status:d,statusReason:o?gt(i.summary,i.overview,i.assessment,i.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 i.fixedSource=="string"&&i.fixedSource.trim()?i.fixedSource.trim():null,pathHint:$g(t,s),relationships:Rg(t,s)}}function Mg({status:t,score:e,artifactPresentations:s,manualSteps:r}){const n=s.length;if(n===0&&r.length===0)return e==null?"Code review returned no overall summary and no score.":`Reviewed bundle with score ${e}/100.`;const i=s.reduce((a,l)=>(a[l.status]+=1,a),{pass:0,warning:0,fail:0}),o=[];return t&&o.push(`Overall verdict: ${t}.`),n&&o.push(`${n} artifact${n===1?"":"s"}: ${i.pass} pass, ${i.warning} warn, ${i.fail} fail.`),r.length&&o.push(`Do before deploy: ${r.map(a=>a.title).join("; ")}.`),e==null&&o.push("No numeric score (0-100) was returned."),o.join(" ")}function Lg({bundle:t,reviewResult:e}){const s=De(t),r=tt(s.artifacts),{root:n,rawText:i}=Pg(e),o=[n.bundleReview,n.overallReview,n.overall,n.bundleSummary,n.summaryReview,n.review].map(De).find(E=>Object.keys(E).length)||{},a=tt(n.artifacts||n.files||n.reviews),l=r.map((E,I)=>Ng(s,a,E,I)),u=_o(n),d=[..._o(o),...u],h=[...yo(o),...yo(n),...l.flatMap(E=>E.manualSteps)].filter((E,I,F)=>F.findIndex(P=>P.title===E.title&&P.artifactId===E.artifactId)===I),p=na(o.status||o.verdict||o.overallStatus||n.status||n.verdict||n.overallStatus||n.outcome),f=vo(p,...d.map(E=>E.severity),...l.map(E=>E.status)),g=o.score??n.score??n.overallScore??i,m=Cg(g),_=gt(o.headline,o.summary,o.executiveSummary,o.overview,o.assessment,o.conclusion,n.overallSummary,n.headline,n.summary,n.executiveSummary,n.overview,n.assessment,n.conclusion,i)||Mg({status:f,score:m,artifactPresentations:l,manualSteps:h}),b=l.reduce((E,I)=>(E[I.status]+=1,E),{pass:0,warning:0,fail:0});return{title:s.title||"Generated artifact bundle",description:s.description||"",status:f,score:m,summary:_,findings:d,manualSteps:h,artifacts:l,counts:b,reviewCoverage:{reviewed:l.filter(E=>E.reviewComplete).length,total:l.length},deployOrder:tt(s.deployOrder),relationships:tt(s.relationships),warnings:tt(s.warnings),compatibility:De(s.metadata?.compatibility)}}const Og=/^\uFEFF/;function Os(t){let e=0,s=t.length;for(;ee&&!t[s-1].trim();)s--;return t.slice(e,s).join(` +`);if(s)return s}}return""}function tt(t){return t==null?[]:Array.isArray(t)?t:[t]}function Cg(t){const e=De(t).value??t;if(e==null||typeof e=="string"&&e.trim()==="")return null;const s=Number(e);if(Number.isFinite(s))return s;const r=String(t||"").match(/\bscore\b[^\d]{0,12}(\d{1,3})(?:\s*\/\s*100)?/i);return r?Number(r[1]):null}function We(t){return String(t||"").trim().replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function na(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 vo(...t){return t.filter(Boolean).reduce((e,s)=>rc[s]>rc[e]?s:e,"pass")}function yd(t,e="warning",s="review"){if(typeof t=="string")return{severity:e,message:t,suggestion:"",source:s};const r=De(t),n=gt(r.message,r.title,r.issue,r.description,r.summary);return n?{severity:na(r.severity||r.status||r.level)||e,message:n,suggestion:gt(r.suggestion,r.fix,r.recommendation,r.action),source:r.source||s}:null}function _o(t,e="review"){const s=De(t);return[["findings","warning"],["issues","warning"],["criticalIssues","fail"],["errors","fail"],["warnings","warning"],["recommendations","warning"],["requiredFixes","fail"],["suggestions","warning"]].flatMap(([n,i])=>tt(s[n]).map(o=>yd(o,i,e)).filter(Boolean))}function Fg(t,e,s=null){if(typeof t=="string")return{id:`${s||"bundle"}-manual-${e+1}`,title:t,detail:"",location:"",timing:"unspecified",artifactId:s,source:"Code Review"};const r=De(t),n=gt(r.title,r.action,r.step,r.message,r.name,r.description);return n?{id:r.id||`${s||"bundle"}-manual-${e+1}`,title:n,detail:gt(r.detail,r.instructions,r.description),location:gt(r.location,r.flutterFlowPath,r.path),timing:gt(r.timing,r.phase)||"unspecified",artifactId:s,source:gt(r.source)||"Code Review"}:null}function yo(t,e=null){const s=De(t);return Ig.flatMap(r=>tt(s[r])).map((r,n)=>Fg(r,n,e)).filter(Boolean)}function Pg(t){let e=typeof t=="string"?go(t):t;if(!e&&typeof t=="string")return{rawText:t,root:{}};const s=De(e);typeof s.content=="string"&&(e=go(s.content)||e);const r=De(e),n=De(r.reviewResult||r.codeReview||r.result);return{rawText:"",root:Object.keys(n).length?n:r}}function Ag(t,e){const s=[e.id,e.fileName,e.artifactName].map(We);return t.find(r=>{const n=De(r);return[n.id,n.fileName,n.artifactName,n.name].map(We).some(i=>i&&s.includes(i))})||null}function $g(t,e){return tt(t?.metadata?.compatibility?.deployHints).find(n=>We(n?.artifactId)===We(e.id)||We(n?.fileName)===We(e.fileName))?.pathHint||""}function Rg(t,e){return tt(t?.relationships).filter(s=>We(s?.from)===We(e.id)||We(s?.to)===We(e.id))}function Tg(t,e){return tt(t?.metadata?.compatibility?.findings).filter(s=>!s?.artifactId||We(s.artifactId)===We(e.id)).map(s=>yd(s,"warning","Compatibility check")).filter(Boolean)}function Ng(t,e,s,r){const n=Ag(e,s),i=De(n?.review||n||s.review),o=Object.keys(i).length>0,a=[..._o(i),...Tg(t,s)],l=yo(i,s.id),u=na(i.status||i.verdict||i.outcome||i.result),c=a.length?vo(...a.map(h=>h.severity)):null,d=vo(u,c,o?null:"warning");return{...s,index:r,status:d,statusReason:o?gt(i.summary,i.overview,i.assessment,i.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 i.fixedSource=="string"&&i.fixedSource.trim()?i.fixedSource.trim():null,pathHint:$g(t,s),relationships:Rg(t,s)}}function Mg({status:t,score:e,artifactPresentations:s,manualSteps:r}){const n=s.length;if(n===0&&r.length===0)return e==null?"Code review returned no overall summary and no score.":`Reviewed bundle with score ${e}/100.`;const i=s.reduce((a,l)=>(a[l.status]+=1,a),{pass:0,warning:0,fail:0}),o=[];return t&&o.push(`Overall verdict: ${t}.`),n&&o.push(`${n} artifact${n===1?"":"s"}: ${i.pass} pass, ${i.warning} warn, ${i.fail} fail.`),r.length&&o.push(`Do before deploy: ${r.map(a=>a.title).join("; ")}.`),e==null&&o.push("No numeric score (0-100) was returned."),o.join(" ")}function Lg({bundle:t,reviewResult:e}){const s=De(t),r=tt(s.artifacts),{root:n,rawText:i}=Pg(e),o=[n.bundleReview,n.overallReview,n.overall,n.bundleSummary,n.summaryReview,n.review].map(De).find(E=>Object.keys(E).length)||{},a=tt(n.artifacts||n.files||n.reviews),l=r.map((E,I)=>Ng(s,a,E,I)),u=_o(n),d=[..._o(o),...u],h=[...yo(o),...yo(n),...l.flatMap(E=>E.manualSteps)].filter((E,I,F)=>F.findIndex(P=>P.title===E.title&&P.artifactId===E.artifactId)===I),p=na(o.status||o.verdict||o.overallStatus||n.status||n.verdict||n.overallStatus||n.outcome),f=vo(p,...d.map(E=>E.severity),...l.map(E=>E.status)),g=o.score??n.score??n.overallScore??i,m=Cg(g),_=gt(o.headline,o.summary,o.executiveSummary,o.overview,o.assessment,o.conclusion,n.overallSummary,n.headline,n.summary,n.executiveSummary,n.overview,n.assessment,n.conclusion,i)||Mg({status:f,score:m,artifactPresentations:l,manualSteps:h}),w=l.reduce((E,I)=>(E[I.status]+=1,E),{pass:0,warning:0,fail:0});return{title:s.title||"Generated artifact bundle",description:s.description||"",status:f,score:m,summary:_,findings:d,manualSteps:h,artifacts:l,counts:w,reviewCoverage:{reviewed:l.filter(E=>E.reviewComplete).length,total:l.length},deployOrder:tt(s.deployOrder),relationships:tt(s.relationships),warnings:tt(s.warnings),compatibility:De(s.metadata?.compatibility)}}const Og=/^\uFEFF/;function Os(t){let e=0,s=t.length;for(;ee&&!t[s-1].trim();)s--;return t.slice(e,s).join(` `)}function Dg(t){const e=String(t??"").replace(Og,"");if(!e.trim())return"";const s=e.split(` `),r=c=>{const d=c.trim();return/^`{3,}[A-Za-z0-9+#_.-]*$/.test(d)?c.length-c.trimStart().length:-1};let n=0,i=-1;const o=[];{let c=0;for(let d=0;d=0&&(n++,i<0&&(i=d),o.push(c+h)),c+=s[d].length+1}}if(n===0)return Os(s);{const c=wo(e);if(!c.error&&o.every(h=>ic(h,c.commentAndStringRanges)))return Os(s)}if(n===1){const c=Os(s.slice(0,i)),d=Os(s.slice(i+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 Bg(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 yd(t){const e=Bg(t);return Array.from(e.matchAll(/class\s+([A-Z]\w*)\s+extends\s+[A-Za-z_]\w*Widget\b/g),s=>s[1])}function wd(t){return`${sa(t)}.dart`}function jg(t){return ea(t,"W")}const nc={"(":")","[":"]","{":"}"},Ug={")":"(","]":"[","}":"{"},Hg=/[A-Za-z0-9_]/;function wo(t){const e=[{kind:"code",opener:null,openedLine:0}],s=[];let r=1,n=0;const i=(c,d)=>{(c===` +`)}function Bg(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 wd(t){const e=Bg(t);return Array.from(e.matchAll(/class\s+([A-Z]\w*)\s+extends\s+[A-Za-z_]\w*Widget\b/g),s=>s[1])}function bd(t){return`${sa(t)}.dart`}function jg(t){return ea(t,"W")}const nc={"(":")","[":"]","{":"}"},Ug={")":"(","]":"[","}":"{"},Hg=/[A-Za-z0-9_]/;function wo(t){const e=[{kind:"code",opener:null,openedLine:0}],s=[];let r=1,n=0;const i=(c,d)=>{(c===` `||c==="\r"&&d!==` `)&&r++};let o=null;const a=()=>{for(const c of e)(c.kind==="string"||c.kind==="block-comment"||c.kind==="line-comment")&&s.push({start:c.startIndex,end:t.length})};for(;n0?t[n-1]:"",f=n>1?t[n-2]:"",g=(p==="r"||p==="R")&&!Hg.test(f);e.push({kind:"string",quote:c,triple:h,raw:g,startIndex:n,openedLine:r}),n+=h?3:1;continue}if(nc[c]){e.push({kind:"code",opener:c,openedLine:r}),n++;continue}if(Ug[c]){if(d.interpolation&&c==="}"){e.pop(),n++;continue}if(d.opener&&nc[d.opener]===c){e.pop(),n++;continue}return d.opener?(a(),{error:o??`line ${r}: "${c}" closes nothing - "${d.opener}" opened on line ${d.openedLine} is still open`,commentAndStringRanges:s}):(a(),{error:o??`line ${r}: unexpected "${c}" with no matching opener`,commentAndStringRanges:s})}i(c,t[n+1]),n++}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:s}}function Wg(t){return wo(String(t??"")).error}function ic(t,e){return e.some(({start:s,end:r})=>t>=s&&ttypeof s=="string"?s:s?.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 zg=/^dependencies\s*:\s*(?:#.*)?$/,qg=/^(?:"([^"]+)"|'([^']+)'|([A-Za-z_][A-Za-z0-9_-]*))\s*:/;function Nn(t){const e=t.match(qg);return e?e[1]??e[2]??e[3]:null}function pr(t){const e=t.trim();return e===""||e.startsWith("#")}function xs(t){const e=t.match(/^(\s*)/);return e?e[1].length:0}function ia(t,e){const s=t.findIndex(i=>e.test(i));if(s===-1)return null;let r=s,n=null;for(let i=s+1;i=0.0.0"}`}function Jg(t,e={}){const s=String(t||""),r=Object.entries(e).filter(([u])=>u&&u!=="flutter");if(r.length===0)return{yaml:s,added:[],alreadyPresent:[]};const n=s.split(` -`),i=new Set(Sd(s)),o=[],a=[];for(const[u,c]of r)i.has(u)?a.push(u):(o.push([u,c]),i.add(u));if(o.length===0)return{yaml:s,added:[],alreadyPresent:a};const l=oa(n);if(l){const u=o.map(([c,d])=>oc(l.childIndent,c,d));n.splice(l.endIndex,0,...u)}else n.length>0&&n[n.length-1].trim()!==""&&n.push(""),n.push("dependencies:"),o.forEach(([u,c])=>{n.push(oc(" ",u,c))});return{yaml:n.join(` +`){s.push({start:d.startIndex,end:n}),o??=`line ${r}: string starting on line ${d.openedLine} is never closed`,e.pop();continue}if(!d.raw&&c==="\\"){i(t[n+1]??"",t[n+2]??""),n+=2;continue}if(!d.raw&&c==="$"&&t[n+1]==="{"){e.push({kind:"code",opener:null,interpolation:!0}),n+=2;continue}const h=d.triple?3:1;if(c===d.quote&&t.slice(n,n+h)===d.quote.repeat(h)){s.push({start:d.startIndex,end:n+h}),e.pop(),n+=h;continue}i(c,t[n+1]),n++;continue}if(c==="/"&&t[n+1]==="/"){e.push({kind:"line-comment",startIndex:n}),n+=2;continue}if(c==="/"&&t[n+1]==="*"){e.push({kind:"block-comment",startIndex:n,openedLine:r,depth:1}),n+=2;continue}if(c==="'"||c==='"'){const h=t.slice(n,n+3)===c.repeat(3),p=n>0?t[n-1]:"",f=n>1?t[n-2]:"",g=(p==="r"||p==="R")&&!Hg.test(f);e.push({kind:"string",quote:c,triple:h,raw:g,startIndex:n,openedLine:r}),n+=h?3:1;continue}if(nc[c]){e.push({kind:"code",opener:c,openedLine:r}),n++;continue}if(Ug[c]){if(d.interpolation&&c==="}"){e.pop(),n++;continue}if(d.opener&&nc[d.opener]===c){e.pop(),n++;continue}return d.opener?(a(),{error:o??`line ${r}: "${c}" closes nothing - "${d.opener}" opened on line ${d.openedLine} is still open`,commentAndStringRanges:s}):(a(),{error:o??`line ${r}: unexpected "${c}" with no matching opener`,commentAndStringRanges:s})}i(c,t[n+1]),n++}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:s}}function Wg(t){return wo(String(t??"")).error}function ic(t,e){return e.some(({start:s,end:r})=>t>=s&&ttypeof s=="string"?s:s?.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 zg=/^dependencies\s*:\s*(?:#.*)?$/,qg=/^(?:"([^"]+)"|'([^']+)'|([A-Za-z_][A-Za-z0-9_-]*))\s*:/;function Nn(t){const e=t.match(qg);return e?e[1]??e[2]??e[3]:null}function pr(t){const e=t.trim();return e===""||e.startsWith("#")}function xs(t){const e=t.match(/^(\s*)/);return e?e[1].length:0}function ia(t,e){const s=t.findIndex(i=>e.test(i));if(s===-1)return null;let r=s,n=null;for(let i=s+1;i=0.0.0"}`}function Jg(t,e={}){const s=String(t||""),r=Object.entries(e).filter(([u])=>u&&u!=="flutter");if(r.length===0)return{yaml:s,added:[],alreadyPresent:[]};const n=s.split(` +`),i=new Set(xd(s)),o=[],a=[];for(const[u,c]of r)i.has(u)?a.push(u):(o.push([u,c]),i.add(u));if(o.length===0)return{yaml:s,added:[],alreadyPresent:a};const l=oa(n);if(l){const u=o.map(([c,d])=>oc(l.childIndent,c,d));n.splice(l.endIndex,0,...u)}else n.length>0&&n[n.length-1].trim()!==""&&n.push(""),n.push("dependencies:"),o.forEach(([u,c])=>{n.push(oc(" ",u,c))});return{yaml:n.join(` `),added:o.map(([u])=>u),alreadyPresent:a}}function Yg(t,e={}){const s=String(t||""),r=Object.entries(e).filter(([l])=>l&&l!=="flutter");if(r.length===0)return{yaml:s,overridden:[],skipped:[]};const n=s.split(` -`),i=Ln(s),o=[],a=[];for(const[l,u]of r){const c=i.get(l);if(!c||!c.isScalar||!String(u||"").trim()){a.push(l);continue}const d=" ".repeat(xs(n[c.lineIndex]));n[c.lineIndex]=`${d}${l}: ${kd(String(u).trim())}${c.comment}`,o.push({name:l,from:c.constraint,to:u})}return{yaml:n.join(` -`),overridden:o,skipped:a}}function Id(t){const e=String(t||""),s=[];return e.trim()?(/^name:\s*\S+/m.test(e)||s.push("pubspec.yaml missing name field"),oa(e.split(` -`))||s.push("pubspec.yaml missing dependencies section"),Sd(e).includes("flutter")||s.push("pubspec.yaml missing Flutter SDK dependency"),{valid:s.length===0,errors:s}):(s.push("pubspec.yaml is empty"),{valid:!1,errors:s})}const Zg=">=3.0.0 <4.0.0";function bo(t){const e=String(t||"").trim(),s=e[0];return s!=="'"&&s!=='"'||e[e.length-1]!==s?e:e.slice(1,-1).replaceAll(`${s}${s}`,s)}function Xg(t=""){const e=gg(t).filter(s=>!s.startsWith("dart:")&&!s.startsWith("package:"));return{selfContained:e.length===0,unresolvableImports:e}}function ac(t,e,s){const r=[];for(const[n,i]of t){if(i.isScalar){e[n]=bo(i.constraint);continue}if(i.sourceKey==="sdk"){s.add(n);continue}if(i.sourceKey===null&&i.version){e[n]=bo(i.version);continue}r.push(n)}return r}function Qg(t){const e=new Set,s={},r={},n=ac(Ln(t),s,e);n.push(...ac(Gg(t,"dependency_overrides"),r,e));const i=new Set([...Object.keys(s),...e]),{sdk:o}=xd(t);return{sdkConstraint:bo(o)||Zg,dependencies:s,overrides:r,sdkPackages:[...e].sort(),availablePackages:i,unrepresentable:n}}function em(t,e,s){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 ${s.join(", ")}, which your project's pubspec.yaml does not declare with a version constraint, so it could not be compiled before the deploy.`}function tm(t,e){const{sdkConstraint:s,dependencies:r,overrides:n,sdkPackages:i,availablePackages:o,unrepresentable:a}=Qg(e),l={sdkConstraint:s,dependencies:r,overrides:n,sdkPackages:i},u=[],c=[];for(const d of t){const{className:h,content:p}=d,f=ra(p),g=f.filter(b=>a.includes(b));if(g.length>0){c.push({className:h,reason:`${h} was not compiled before deploying: it imports ${g.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:m}=Xg(p),_=f.filter(b=>!o.has(b));if(m.length>0||_.length>0){c.push({className:h,reason:em(h,m,_)});continue}u.push({fileName:`${sa(h)}.dart`,content:p})}return{manifest:l,sources:u,skipped:c}}function lc(t,e){const s=`${t}${e}`.split(` -`),r=s.pop()??"",n=[];for(const i of s){const o=Cd(i);o&&n.push(o)}return{events:n,buffer:r}}function sm(t){const e=Cd(t);return e?[e]:[]}function Cd(t){const e=t.trim();if(!e)return null;try{const s=JSON.parse(e);return s&&typeof s=="object"&&!Array.isArray(s)?s:null}catch{return null}}async function rm(t,e={}){const{onPhase:s,onLog:r}=e;let n=null,i="";const o=a=>{if(a.event==="phase"){a.message&&s&&s(a.message);return}if(a.event==="log"){a.message&&r&&r(a.message);return}n=a};if(t.body?.getReader){const a=t.body.getReader(),l=new TextDecoder;for(;;){const{done:u,value:c}=await a.read();if(u)break;const d=lc(i,l.decode(c,{stream:!0}));i=d.buffer,d.events.forEach(o)}}else{const a=lc("",await t.text());i=a.buffer,a.events.forEach(o)}return sm(i).forEach(o),n?{...n,success:n.success===!0||n.success===void 0&&t.ok}:{success:!1,error:t.ok?"The FlutterFlow deploy runner closed the connection before it finished.":`FlutterFlow custom class provisioning failed (HTTP ${t.status}).`}}const nm=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;function wt(t){const e=String(t||"").trim().match(nm);return e?{major:Number(e[1]),minor:Number(e[2]),patch:Number(e[3]),prerelease:e[4]?e[4].split("."):[]}:null}function im(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 s=0;s0)}function am(t){const e=wt(t);return e?e.major>0?`${e.major+1}.0.0`:`0.${e.minor+1}.0`:null}function aa(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 wt(o)?{min:o,minInclusive:!0,max:am(o),maxInclusive:!1}:null}if(wt(e))return{min:e,minInclusive:!0,max:e,maxInclusive:!0};const s={min:null,minInclusive:!1,max:null,maxInclusive:!1},r=/(>=|<=|>|<)\s*([0-9][0-9A-Za-z.+-]*)/g;let n=!1,i;for(;(i=r.exec(e))!==null;){const[,o,a]=i;if(!wt(a))return null;n=!0,o===">="||o===">"?(s.min=a,s.minInclusive=o===">="):(s.max=a,s.maxInclusive=o==="<=")}return n?s:null}function cc(t,e){const s=aa(t);if(!s||!wt(e))return!1;if(s.min!==null){const r=vn(e,s.min);if(r<0||r===0&&!s.minInclusive)return!1}if(s.max!==null){const r=vn(e,s.max);if(r>0||r===0&&!s.maxInclusive)return!1}return!0}function lm(t,e){const s=aa(t);if(!s||!wt(e))return!1;if(s.max===null)return!0;const r=vn(s.max,e);return r>0?!0:r===0&&s.maxInclusive}function ns(t){const e=aa(t);return e?e.min:null}const cm="https://pub.dev/api/packages/",um=8e3;function dm(t,e={}){const{dartSdkFloor:s=null,flutterSdkFloor:r=null}=e,n=Array.isArray(t?.versions)?t.versions:[];let i=null;for(const o of n){const a=o?.version;if(!a||o.retracted||om(a))continue;const l=o.pubspec?.environment||{};s&&l.sdk&&!cc(l.sdk,s)||r&&l.flutter&&!cc(l.flutter,r)||(!i||vn(a,i)>0)&&(i=a)}return i?{version:i,constraint:`^${i}`}:null}async function hm(t,e={}){const{dartSdkFloor:s=null,flutterSdkFloor:r=null,fetchImpl:n=fetch}=e;let i;try{const a=await n(`${cm}${encodeURIComponent(t)}`,{signal:AbortSignal.timeout(um)});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}"`};i=await a.json()}catch(a){return{name:t,constraint:null,version:null,error:`could not reach pub.dev for "${t}" (${a.message})`}}const o=dm(i,{dartSdkFloor:s,flutterSdkFloor:r});return o?{name:t,...o,error:null}:{name:t,constraint:null,version:null,error:s?`no published "${t}" release supports Dart ${s}`:`no published "${t}" release could be read`}}async function pm(t,e={}){const s=await Promise.all(t.map(r=>hm(r,e)));return new Map(s.map(({name:r,...n})=>[r,n]))}async function fm(t,e={},s={}){const{resolveVersions:r=pm}=s,n=Object.entries(e).filter(([c])=>c&&c!=="flutter"),i=xd(t),o={dartSdkFloor:ns(i.sdk),flutterSdkFloor:ns(i.flutter)},a={additions:{},overrides:{},kept:[],warnings:[],sdk:o};if(n.length===0)return a;const l=Ln(t),u=[];for(const[c,d]of n){const h=l.get(c);if(!h){u.push(c);continue}const p=ns(d);if(!p){a.kept.push({name:c,constraint:h.constraint});continue}if(!h.isScalar){a.warnings.push(`"${c}" is declared in your project from a git, path, or SDK source, but the generated code needs at least ${p}. Left as-is — update it yourself if the build fails.`),a.kept.push({name:c,constraint:h.constraint});continue}if(lm(h.constraint,p)){a.kept.push({name:c,constraint:h.constraint});continue}a.overrides[c]=`^${p}`,a.warnings.push(`"${c}" was pinned to ${h.constraint} in your project, which cannot resolve the ${p} the generated code needs. Raising it to ^${p} — this changes a dependency the rest of your app also uses.`)}if(u.length>0){const c=await r(u,o);for(const d of u){const h=c.get(d);if(h?.constraint){a.additions[d]=h.constraint;continue}const p=e[d]||"";if(ns(p)){a.additions[d]=`^${ns(p)}`,a.warnings.push(`Could not confirm "${d}" version on pub.dev (${h?.error||"lookup failed"}). Using ^${ns(p)} from the AI's recommendation — verify this is current.`);continue}a.additions[d]=">=0.0.0",a.warnings.push(`Could not determine a version for "${d}" (${h?.error||"lookup failed"}) and the AI supplied none. Added with a wide-open >=0.0.0 constraint — pin a concrete version in FlutterFlow before deploying.`)}}return a}const gm={"&":"&","<":"<",">":">",'"':""","'":"'"};function bt(t){return String(t??"").replace(/[&<>"']/g,e=>gm[e])}function j(t){return t?bt(t).replace(/\n/g,"
    "):""}function It(t){return bt(t).replace(/\r?\n/g," ")}function mm(t,e={}){const s=t?.pipelineStep;if(s!=null&&e[s]!=null)return e[s];const r=t?.message||"";return r.includes("Code Generator")?2:r.includes("Code Review")?3:1}function vm(t){const e={"Integration Audit Report":"📋","Critical Issues":"❌",Warnings:"⚠️",Recommendations:"✅","Overall Score":"📊"};for(const[s,r]of Object.entries(e))if(t.toLowerCase().includes(s.toLowerCase()))return r;return"📄"}function _m(t){const e={critical:"❌",warning:"⚠️",recommendation:"✅",score:"📊",issue:"🔍",fix:"🔧"};for(const[s,r]of Object.entries(e))if(t.toLowerCase().includes(s.toLowerCase()))return r;return"📝"}function ym(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 ws(t){if(!t)return"";if(typeof t!="string")return String(t);const e=/```(?:\w+)?\n?([\s\S]*?)```/,s=t.match(e);return s?s[1].trim():t.trim()}function uc(t){return t=bt(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 Fd(t,e="dart",s=globalThis.hljs){if(!t)return"";const r=ws(t);try{return s.highlight(r,{language:e}).value}catch(n){console.warn("Syntax highlighting failed:",n);try{return s.highlight(r,{language:"json"}).value}catch{return bt(r)}}}function On(t,e={}){const{highlighter:s=globalThis.hljs}=e;let r='
    ';const n=String(t??"").split(` -`);let i=!1,o="";for(const a of n){if(a.startsWith("```")){if(i){const l=ym(o),u=Fd(o.trim(),l,s);r+=`
    +`),i=Ln(s),o=[],a=[];for(const[l,u]of r){const c=i.get(l);if(!c||!c.isScalar||!String(u||"").trim()){a.push(l);continue}const d=" ".repeat(xs(n[c.lineIndex]));n[c.lineIndex]=`${d}${l}: ${Id(String(u).trim())}${c.comment}`,o.push({name:l,from:c.constraint,to:u})}return{yaml:n.join(` +`),overridden:o,skipped:a}}function Cd(t){const e=String(t||""),s=[];return e.trim()?(/^name:\s*\S+/m.test(e)||s.push("pubspec.yaml missing name field"),oa(e.split(` +`))||s.push("pubspec.yaml missing dependencies section"),xd(e).includes("flutter")||s.push("pubspec.yaml missing Flutter SDK dependency"),{valid:s.length===0,errors:s}):(s.push("pubspec.yaml is empty"),{valid:!1,errors:s})}const Zg=">=3.0.0 <4.0.0";function bo(t){const e=String(t||"").trim(),s=e[0];return s!=="'"&&s!=='"'||e[e.length-1]!==s?e:e.slice(1,-1).replaceAll(`${s}${s}`,s)}function Xg(t=""){const e=_d(t).filter(s=>!s.startsWith("dart:")&&!s.startsWith("package:"));return{selfContained:e.length===0,unresolvableImports:e}}function ac(t,e,s){const r=[];for(const[n,i]of t){if(i.isScalar){e[n]=bo(i.constraint);continue}if(i.sourceKey==="sdk"){s.add(n);continue}if(i.sourceKey===null&&i.version){e[n]=bo(i.version);continue}r.push(n)}return r}function Qg(t){const e=new Set,s={},r={},n=ac(Ln(t),s,e);n.push(...ac(Gg(t,"dependency_overrides"),r,e));const i=new Set([...Object.keys(s),...e]),{sdk:o}=kd(t);return{sdkConstraint:bo(o)||Zg,dependencies:s,overrides:r,sdkPackages:[...e].sort(),availablePackages:i,unrepresentable:n}}function em(t,e,s){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 ${s.join(", ")}, which your project's pubspec.yaml does not declare with a version constraint, so it could not be compiled before the deploy.`}function tm(t,e){return`${t} was not compiled before deploying: your project declares ${e.join(", ")} from a source that cannot be reproduced outside it, and whether the packages ${t} imports depend on one of them transitively cannot be checked before the deploy, so package resolution could not be matched exactly.`}function sm(t,e){const{sdkConstraint:s,dependencies:r,overrides:n,sdkPackages:i,availablePackages:o,unrepresentable:a}=Qg(e),l={sdkConstraint:s,dependencies:r,overrides:n,sdkPackages:i},u=[],c=[];for(const d of t){const{className:h,content:p}=d,f=ra(p),g=f.filter(w=>a.includes(w));if(g.length>0){c.push({className:h,reason:`${h} was not compiled before deploying: it imports ${g.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:m}=Xg(p),_=f.filter(w=>!o.has(w));if(m.length>0||_.length>0){c.push({className:h,reason:em(h,m,_)});continue}if(a.length>0&&_d(p).some(w=>w.startsWith("package:"))){c.push({className:h,reason:tm(h,a)});continue}u.push({fileName:`${sa(h)}.dart`,content:p})}return{manifest:l,sources:u,skipped:c}}function lc(t,e){const s=`${t}${e}`.split(` +`),r=s.pop()??"",n=[];for(const i of s){const o=Fd(i);o&&n.push(o)}return{events:n,buffer:r}}function rm(t){const e=Fd(t);return e?[e]:[]}function Fd(t){const e=t.trim();if(!e)return null;try{const s=JSON.parse(e);return s&&typeof s=="object"&&!Array.isArray(s)?s:null}catch{return null}}async function nm(t,e={}){const{onPhase:s,onLog:r}=e;let n=null,i="";const o=a=>{if(a.event==="phase"){a.message&&s&&s(a.message);return}if(a.event==="log"){a.message&&r&&r(a.message);return}n=a};if(t.body?.getReader){const a=t.body.getReader(),l=new TextDecoder;for(;;){const{done:u,value:c}=await a.read();if(u)break;const d=lc(i,l.decode(c,{stream:!0}));i=d.buffer,d.events.forEach(o)}}else{const a=lc("",await t.text());i=a.buffer,a.events.forEach(o)}return rm(i).forEach(o),n?{...n,success:n.success===!0||n.success===void 0&&t.ok}:{success:!1,error:t.ok?"The FlutterFlow deploy runner closed the connection before it finished.":`FlutterFlow custom class provisioning failed (HTTP ${t.status}).`}}const im=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;function wt(t){const e=String(t||"").trim().match(im);return e?{major:Number(e[1]),minor:Number(e[2]),patch:Number(e[3]),prerelease:e[4]?e[4].split("."):[]}:null}function om(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 s=0;s0)}function lm(t){const e=wt(t);return e?e.major>0?`${e.major+1}.0.0`:`0.${e.minor+1}.0`:null}function aa(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 wt(o)?{min:o,minInclusive:!0,max:lm(o),maxInclusive:!1}:null}if(wt(e))return{min:e,minInclusive:!0,max:e,maxInclusive:!0};const s={min:null,minInclusive:!1,max:null,maxInclusive:!1},r=/(>=|<=|>|<)\s*([0-9][0-9A-Za-z.+-]*)/g;let n=!1,i;for(;(i=r.exec(e))!==null;){const[,o,a]=i;if(!wt(a))return null;n=!0,o===">="||o===">"?(s.min=a,s.minInclusive=o===">="):(s.max=a,s.maxInclusive=o==="<=")}return n?s:null}function cc(t,e){const s=aa(t);if(!s||!wt(e))return!1;if(s.min!==null){const r=vn(e,s.min);if(r<0||r===0&&!s.minInclusive)return!1}if(s.max!==null){const r=vn(e,s.max);if(r>0||r===0&&!s.maxInclusive)return!1}return!0}function cm(t,e){const s=aa(t);if(!s||!wt(e))return!1;if(s.max===null)return!0;const r=vn(s.max,e);return r>0?!0:r===0&&s.maxInclusive}function ns(t){const e=aa(t);return e?e.min:null}const um="https://pub.dev/api/packages/",dm=8e3;function hm(t,e={}){const{dartSdkFloor:s=null,flutterSdkFloor:r=null}=e,n=Array.isArray(t?.versions)?t.versions:[];let i=null;for(const o of n){const a=o?.version;if(!a||o.retracted||am(a))continue;const l=o.pubspec?.environment||{};s&&l.sdk&&!cc(l.sdk,s)||r&&l.flutter&&!cc(l.flutter,r)||(!i||vn(a,i)>0)&&(i=a)}return i?{version:i,constraint:`^${i}`}:null}async function pm(t,e={}){const{dartSdkFloor:s=null,flutterSdkFloor:r=null,fetchImpl:n=fetch}=e;let i;try{const a=await n(`${um}${encodeURIComponent(t)}`,{signal:AbortSignal.timeout(dm)});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}"`};i=await a.json()}catch(a){return{name:t,constraint:null,version:null,error:`could not reach pub.dev for "${t}" (${a.message})`}}const o=hm(i,{dartSdkFloor:s,flutterSdkFloor:r});return o?{name:t,...o,error:null}:{name:t,constraint:null,version:null,error:s?`no published "${t}" release supports Dart ${s}`:`no published "${t}" release could be read`}}async function fm(t,e={}){const s=await Promise.all(t.map(r=>pm(r,e)));return new Map(s.map(({name:r,...n})=>[r,n]))}async function gm(t,e={},s={}){const{resolveVersions:r=fm}=s,n=Object.entries(e).filter(([c])=>c&&c!=="flutter"),i=kd(t),o={dartSdkFloor:ns(i.sdk),flutterSdkFloor:ns(i.flutter)},a={additions:{},overrides:{},kept:[],warnings:[],sdk:o};if(n.length===0)return a;const l=Ln(t),u=[];for(const[c,d]of n){const h=l.get(c);if(!h){u.push(c);continue}const p=ns(d);if(!p){a.kept.push({name:c,constraint:h.constraint});continue}if(!h.isScalar){a.warnings.push(`"${c}" is declared in your project from a git, path, or SDK source, but the generated code needs at least ${p}. Left as-is — update it yourself if the build fails.`),a.kept.push({name:c,constraint:h.constraint});continue}if(cm(h.constraint,p)){a.kept.push({name:c,constraint:h.constraint});continue}a.overrides[c]=`^${p}`,a.warnings.push(`"${c}" was pinned to ${h.constraint} in your project, which cannot resolve the ${p} the generated code needs. Raising it to ^${p} — this changes a dependency the rest of your app also uses.`)}if(u.length>0){const c=await r(u,o);for(const d of u){const h=c.get(d);if(h?.constraint){a.additions[d]=h.constraint;continue}const p=e[d]||"";if(ns(p)){a.additions[d]=`^${ns(p)}`,a.warnings.push(`Could not confirm "${d}" version on pub.dev (${h?.error||"lookup failed"}). Using ^${ns(p)} from the AI's recommendation — verify this is current.`);continue}a.additions[d]=">=0.0.0",a.warnings.push(`Could not determine a version for "${d}" (${h?.error||"lookup failed"}) and the AI supplied none. Added with a wide-open >=0.0.0 constraint — pin a concrete version in FlutterFlow before deploying.`)}}return a}const mm={"&":"&","<":"<",">":">",'"':""","'":"'"};function bt(t){return String(t??"").replace(/[&<>"']/g,e=>mm[e])}function j(t){return t?bt(t).replace(/\n/g,"
    "):""}function It(t){return bt(t).replace(/\r?\n/g," ")}function vm(t,e={}){const s=t?.pipelineStep;if(s!=null&&e[s]!=null)return e[s];const r=t?.message||"";return r.includes("Code Generator")?2:r.includes("Code Review")?3:1}function _m(t){const e={"Integration Audit Report":"📋","Critical Issues":"❌",Warnings:"⚠️",Recommendations:"✅","Overall Score":"📊"};for(const[s,r]of Object.entries(e))if(t.toLowerCase().includes(s.toLowerCase()))return r;return"📄"}function ym(t){const e={critical:"❌",warning:"⚠️",recommendation:"✅",score:"📊",issue:"🔍",fix:"🔧"};for(const[s,r]of Object.entries(e))if(t.toLowerCase().includes(s.toLowerCase()))return r;return"📝"}function wm(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 ws(t){if(!t)return"";if(typeof t!="string")return String(t);const e=/```(?:\w+)?\n?([\s\S]*?)```/,s=t.match(e);return s?s[1].trim():t.trim()}function uc(t){return t=bt(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 Pd(t,e="dart",s=globalThis.hljs){if(!t)return"";const r=ws(t);try{return s.highlight(r,{language:e}).value}catch(n){console.warn("Syntax highlighting failed:",n);try{return s.highlight(r,{language:"json"}).value}catch{return bt(r)}}}function On(t,e={}){const{highlighter:s=globalThis.hljs}=e;let r='
    ';const n=String(t??"").split(` +`);let i=!1,o="";for(const a of n){if(a.startsWith("```")){if(i){const l=wm(o),u=Pd(o.trim(),l,s);r+=`
    ${u}
    `,o="",i=!1}else i=!0;continue}if(i){o+=a+` `;continue}if(a.startsWith("# ")){const l=a.substring(2).trim();r+=`

    - ${vm(l)} + ${_m(l)} ${bt(l)}

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

    - ${_m(l)} + ${ym(l)} ${bt(l)}

    `;continue}if(/^[-*+]\s+/.test(a)||/^\d+\.\s+/.test(a)){const l=a.replace(/^([-*+]|\d+\.)\s+/,"").trim();r+=`
    @@ -76,14 +76,14 @@ ${d}`,{commentAndStringRanges:g}=wo(f),m=p.length+1+h;if(ic(m,g)){l.push(d);cont
    ${r}
    - `}const wm="https://ccc-ffai-runner-y5cyj3473a-uw.a.run.app/deployCustomClasses";const Je="https://4tgke4.buildship.run",Pd={professional:"price_1T2ldCKszA2slvDXatdeCpbI",power:"price_1T2le9KszA2slvDXR4mPvw7M"},_n="ccc_auth_session",dc=new WeakSet;let G={email:null,sessionToken:null,isVerified:!1};function bs(t={}){return{tier:"free",status:"none",periodEnd:null,isLoading:!1,isResolved:!1,error:null,...t}}let fe=bs({isResolved:!0});const bm=`${Je}/service/runpipeline`,Em="bs_user_id",Sm="bs_identity_token",xm=`${Je}/authUserCheck`;let Ge={userId:null,token:null,status:null,resolved:!1};const yn={free:2,professional:50,power:2e3},wn="ccc_subscription",hc=3,km=new Set(["active","trialing","paid"]),lr="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"],Im={"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 zt(t){return Im[t]||t}const Cm=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 Ad(t){return Cm.has(t)}const Eo=4,Ci=8*1024*1024,Fm="https://4tgke4.buildship.run/service/runpipeline-image";let Pt=[];function Pm(t){return new Promise(e=>{const s=new FileReader;s.onload=()=>e(s.result),s.onerror=()=>e(null),s.readAsDataURL(t)})}async function Am(t){const e=new FormData;return e.append("file",t),(await fetch(Fm,{method:"POST",body:e})).json()}function $m(t){if(Array.isArray(t)){const e=t[0];if(e&&typeof e=="object")for(const s of Object.keys(e)){if(s==="item"||s==="index")continue;const r=e[s];if(r&&typeof r=="object"){if(typeof r.file=="string")return r.file;if(typeof r.url=="string")return r.url}if(typeof r=="string")return r}return""}return typeof t=="string"?t:t&&typeof t=="object"&&(t.url||t.fileUrl||t.file_url||t.downloadUrl||t.imageUrl||t.image_url||t.file)||""}async function Rm(t){const e=Array.from(t.target.files||[]);if(!e.length)return;const s=e.filter(l=>l.size>Ci);s.length&&ue(`Skipped ${s.length} image(s) over the ${(Ci/1024/1024).toFixed(0)} MB limit.`,"warning");const r=e.filter(l=>l.size<=Ci);if(!r.length){t.target.value="";return}const n=Eo-Pt.length,o=r.slice(0,n).map(async l=>{const u=await Pm(l);if(!u)return null;let c="";try{c=$m(await Am(l))}catch{c=""}return{dataUrl:u,name:l.name,url:c}}),a=(await Promise.all(o)).filter(Boolean);t.target.value="",!(a.length&&!Ad(document.getElementById("code-generator-model")?.value))&&(Pt.push(...a),r.length>n&&ue(`You can attach up to ${Eo} images.`,"info"),la())}function Tm(t){Pt.splice(t,1),la()}function la(){const t=document.getElementById("prompt-image-thumbnails"),e=document.getElementById("prompt-image-btn-label");t&&(t.innerHTML="",Pt.forEach((s,r)=>{const n=document.createElement("div");n.className="prompt-img-thumb",n.innerHTML=`Prompt image`,t.appendChild(n)}),e&&(e.textContent=Pt.length>=Eo?"Image limit reached":"Add images"))}function $d(){const t=document.getElementById("prompt-image-upload");if(!t)return;const e=document.getElementById("code-generator-model"),s=Ad(e?.value);t.classList.toggle("hidden",!s),!s&&Pt.length&&(Pt=[],la())}const Gt="ccc_usage",Rd="google/gemini-3.7-flash",Td="google/gemini-3.7-flash",Fi="google/gemini-3.7-flash",pc={professional:11,power:49},So={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 Nm(){const t=new AbortController,e=setTimeout(()=>t.abort(),5e3);try{const s=await fetch("https://open.er-api.com/v6/latest/AUD",{signal:t.signal});if(!s.ok)return;const r=await s.json();if(r.result!=="success"||!r.rates)return;const n=r.rates,i={AUD:1},o=new Set([...Object.keys(Ur),...Object.values(xo),...Object.values(So)]);for(const a of o)a!=="AUD"&&(typeof n[a]=="number"&&n[a]>0?i[a]=n[a]:Ur[a]&&(i[a]=Ur[a]));Hr=i}catch{}finally{clearTimeout(e)}}const xo={"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 Nd(){try{const i=Intl.DateTimeFormat().resolvedOptions().timeZone;if(i&&xo[i])return xo[i]}catch{}const e=(navigator.language||"en-US").replace("-","_"),s=So[e];if(s)return s;const r=e.split("_")[0],n=So[r];return n||"USD"}function fc(t,e){const s=Hr[e]??Hr.USD,r=t*s,n=Math.round(r*100)/100;try{return new Intl.NumberFormat("en-US",{style:"currency",currency:e,minimumFractionDigits:0,maximumFractionDigits:n>=100||n%1===0?0:2}).format(n)}catch{return new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",minimumFractionDigits:0,maximumFractionDigits:2}).format(t*Hr.USD)}}const st="ccc_api_key_",_t="ccc_session_api_key_",it="ccc_encryption_key",cr="ccc_encryption_key_scope",Mm="ccc_keystore",bn="keys",ur="ccc_encryption_key_version";let ko=null,En=null,dr=!1,Sn=!1,gc=!1;class xn extends Error{constructor(){super("Secure browser key storage is unavailable."),this.name="CredentialStorageUnavailableError"}}function mc(){if(gc)return;gc=!0;const t="Secure browser key storage is unavailable. Existing credentials were left untouched; new credentials will be available only in this tab session.";console.warn(t),document.body&&ue(t,"warning")}function Md(){return localStorage.getItem(ur)||""}function Io(){return crypto.randomUUID?.()||Od(crypto.getRandomValues(new Uint8Array(16)))}function Lm(){const t=Md();if(t)return t;const e=Io();return localStorage.setItem(ur,e),e}function Es(){ko=null,En=null,dr=!1,Sn=!1}window.addEventListener("storage",t=>{t.key===ur&&Es()});function Om(){return new Promise((t,e)=>{const s=indexedDB.open(Mm,1);s.onupgradeneeded=()=>{const r=s.result;r.objectStoreNames.contains(bn)||r.createObjectStore(bn)},s.onsuccess=()=>t(s.result),s.onerror=()=>e(s.error)})}async function ca(t,e){const s=await Om();return new Promise((r,n)=>{const i=s.transaction(bn,t);let o;try{o=e(i.objectStore(bn))}catch(l){s.close(),n(l);return}let a;o.onsuccess=()=>{a=o.result},o.onerror=()=>n(o.error),i.oncomplete=()=>{s.close(),r(a)},i.onerror=()=>{s.close(),n(i.error||new Error("Encryption key transaction failed."))},i.onabort=()=>{s.close(),n(i.error||new Error("Encryption key transaction aborted."))}})}function Dm(t){return t instanceof CryptoKey&&t.algorithm?.name==="AES-GCM"&&t.extractable===!1&&t.usages.includes("encrypt")&&t.usages.includes("decrypt")}async function Bm(){const t=await ca("readonly",e=>e.get(it));return Dm(t)?t:null}async function Ld(t){await ca("readwrite",e=>e.put(t,it))}async function jm(){Es();try{await ca("readwrite",t=>t.delete(it))}catch(t){console.warn("Could not delete the stored encryption key:",t)}}async function Um(){const t=sessionStorage.getItem(it);if(!t)return null;const e=await crypto.subtle.importKey("jwk",JSON.parse(t),{name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);return await Ld(e),sessionStorage.removeItem(it),sessionStorage.removeItem(cr),localStorage.removeItem(st+"salt"),e}async function vc(t){const e=sessionStorage.getItem(it);if(e)return Sn=sessionStorage.getItem(cr)!=="session",crypto.subtle.importKey("jwk",JSON.parse(e),{name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);if(!t)throw new xn;const s=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!0,["encrypt","decrypt"]),r=await crypto.subtle.exportKey("jwk",s);return sessionStorage.setItem(it,JSON.stringify(r)),sessionStorage.setItem(cr,"session"),Sn=!1,crypto.subtle.importKey("jwk",r,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}async function Hm(t){if(sessionStorage.getItem(cr)==="session"&&sessionStorage.getItem(it))return mc(),dr=!0,vc(t);try{const e=await Bm();if(e)return e;const s=await Um();if(s)return s;const r=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);return await Ld(r),r}catch(e){return console.warn("IndexedDB encryption-key storage failed:",e),mc(),dr=!0,vc(t)}}async function ua(t={}){const{allowSessionFallbackCreation:e=!0}=t,s=Lm();En!==s&&Es();const r=ko||Hm(e);ko=r,En=s;try{return await r}catch(n){throw Es(),n}}async function Wm(t){const e=await ua(),s=En,r=new TextEncoder,n=crypto.getRandomValues(new Uint8Array(12)),i=await crypto.subtle.encrypt({name:"AES-GCM",iv:n},e,r.encode(t)),o=new Uint8Array(n.length+i.byteLength);return o.set(n),o.set(new Uint8Array(i),n.length),{ciphertext:Od(o),keyVersion:s,sessionFallback:dr}}async function zm(t,e={}){const{isSessionCredential:s=!1}=e;try{const r=await ua({allowSessionFallbackCreation:!1});if(dr&&!s&&!Sn)throw new xn;const n=qm(t),i=n.slice(0,12),o=n.slice(12),a=await crypto.subtle.decrypt({name:"AES-GCM",iv:i},r,o);return new TextDecoder().decode(a)}catch(r){if(r instanceof xn)throw r;return console.error("Decryption failed:",r),null}}function Od(t){const e=new Uint8Array(t);let s="";for(let r=0;r0}let hr="",kn="",Zs=null,yc=0;async function da(){sessionStorage.getItem(it)&&await ua(),hr=await Ee("flutterflow"),kn=await Ee("flutterflow_project_id"),Ym(),Zt()}function ha(){document.getElementById("api-keys-modal").classList.add("open"),fa(),hr&&Ud(hr)}function Dd(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("api-keys-modal");e&&e.classList.remove("open");const s=document.getElementById("walkthrough-modal");s&&(pa(),s.classList.add("open"))}let Et=1;function Bd(){const t=document.querySelector(".wt-steps");return t?Array.from(t.querySelectorAll(".wt-step-card")):[]}function Dn(){const t=Bd();t.length&&t.forEach((e,s)=>{const r=s+1;if(r===Et){e.classList.remove("opacity-60","bg-gray-50","border-gray-200"),e.classList.add("bg-blue-50","border-blue-200");const n=e.querySelector("div:first-child");n&&(n.classList.remove("bg-gray-400"),n.classList.add("bg-blue-500"),n.innerHTML=r)}else if(r0&&Et<=t&&(Et++,Dn())}function Gm(){const t=document.getElementById("walkthrough-modal");t&&(Et=1,Dn(),t.classList.add("open"))}function Km(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("walkthrough-modal");e&&e.classList.remove("open");const s=document.getElementById("walkthrough-dont-show");s&&s.checked&&localStorage.setItem("hasSeenWalkthrough","true")}function jd(){if(G.isVerified&&Jt()&&fe.tier!=="free")return;if(!localStorage.getItem("hasSeenWalkthrough")){const e=document.getElementById("walkthrough-modal");e&&(Et=1,Dn(),e.classList.add("open"))}}async function fa(){const t=document.getElementById("flutterflow-api-key-input");hr?(t.value="",t.placeholder="Key saved (enter new to replace)"):t.placeholder="Enter your FlutterFlow API key",Jm()}function Jm(){wc("flutterflow","flutterflow-key-status"),wc("flutterflow_project_id","flutterflow-project-status")}function wc(t,e){const s=document.getElementById(e);if(!s)return;const r=s.querySelector(".key-status-dot"),n=s.querySelector("span");as(t)?(r.className="key-status-dot configured",n.className="text-green-600",n.textContent="User key configured"):(r.className="key-status-dot missing",n.className="text-gray-500",n.textContent="Not configured")}function Zt(){const t=y.step2Result&&y.step2Result.length>0,e=document.getElementById("btn-deploy-to-ff"),s=document.getElementById("btn-run-pipeline");s&&s.classList.remove("hidden"),e&&e.classList.toggle("hidden",!t)}function Ym(){const t=document.getElementById("api-keys-status");if(!t)return;const e=t.querySelectorAll(".key-status-dot"),s=["flutterflow"];e.forEach((r,n)=>{const i=s[n];i==="flutterflow"?as("flutterflow")&&as("flutterflow_project_id")?(r.className="key-status-dot configured",r.title="FlutterFlow (Fully configured)"):as("flutterflow")||as("flutterflow_project_id")?(r.className="key-status-dot env",r.title="FlutterFlow (Partially configured)"):(r.className="key-status-dot missing",r.title="FlutterFlow (Not configured)"):as(i)?(r.className="key-status-dot configured",r.title=i.charAt(0).toUpperCase()+i.slice(1)+" (User key)"):(r.className="key-status-dot missing",r.title=i.charAt(0).toUpperCase()+i.slice(1)+" (Not configured)")}),Zt()}async function Zm(){const t=document.getElementById("flutterflow-api-key-input"),e=document.getElementById("flutterflow-projects-select");t.value.trim()&&await _c("flutterflow",t.value);const s=e?.value.trim()||"";if(s){if(!Bn(s)){ue("The selected FlutterFlow project has an unexpected ID format.","error"),e.focus();return}await _c("flutterflow_project_id",s)}await da(),fa();const r=document.querySelector("#api-keys-modal .bg-blue-500"),n=r.textContent;r.textContent="Saved!",r.classList.remove("bg-blue-500","hover:bg-blue-600"),r.classList.add("bg-green-500"),setTimeout(()=>{r.textContent=n,r.classList.remove("bg-green-500"),r.classList.add("bg-blue-500","hover:bg-blue-600"),Dd()},1e3)}async function Xm(){if(!confirm("Are you sure you want to clear all stored API keys?"))return;localStorage.setItem(ur,Io()),Es(),localStorage.removeItem(st+"flutterflow"),localStorage.removeItem(st+"flutterflow_project_id"),sessionStorage.removeItem(_t+"flutterflow"),sessionStorage.removeItem(_t+"flutterflow_project_id"),sessionStorage.removeItem(it),sessionStorage.removeItem(cr),localStorage.removeItem(st+"salt"),await jm(),localStorage.setItem(ur,Io()),localStorage.removeItem(st+"flutterflow"),localStorage.removeItem(st+"flutterflow_project_id"),sessionStorage.removeItem(_t+"flutterflow"),sessionStorage.removeItem(_t+"flutterflow_project_id"),await da();const t=document.getElementById("flutterflow-projects-select");t&&(t.innerHTML=''),fa()}function Bn(t){return!t||t.trim().length<5||t.includes(" ")?!1:/^[a-zA-Z0-9-]+$/.test(t)}function Qm(t,e){const s=document.getElementById(t);s&&(s.value?e?s.style.borderColor="#22c55e":s.style.borderColor="#ef4444":s.style.borderColor="")}function ev(){const t=document.getElementById("flutterflow-api-key-input");t&&(t.addEventListener("input",e=>{const s=e.target.value.trim().length>0;Qm("flutterflow-api-key-input",s)}),t.addEventListener("blur",tv(async e=>{const s=e.target.value.trim();s&&await Ud(s)},500)))}function tv(t,e){let s;return function(...n){const i=()=>{clearTimeout(s),t(...n)};clearTimeout(s),s=setTimeout(i,e)}}async function Ud(t){const e=document.getElementById("flutterflow-projects-select"),s=document.getElementById("flutterflow-projects-error");if(!e){console.error("Projects dropdown element not found");return}e.innerHTML='',s&&s.classList.add("hidden");try{const n=await new gr(t,"").listProjects();if(!n||n.length===0){e.innerHTML='';return}e.innerHTML='',n.forEach(i=>{const o=document.createElement("option");o.value=i.id||i.projectId||"",o.textContent=i.name||i.projectName||`Project ${i.id}`,e.appendChild(o)}),kn&&(e.value=kn)}catch(r){console.error("Failed to fetch projects:",r),e.innerHTML='',s&&(s.textContent=`Failed to load projects: ${r.message}`,s.classList.remove("hidden"))}}function sv(t){const e=document.getElementById(t),r=e.nextElementSibling.querySelector("svg");e.type==="password"?(e.type="text",r.innerHTML=` + `}const bm="https://ccc-ffai-runner-y5cyj3473a-uw.a.run.app/deployCustomClasses";const Je="https://4tgke4.buildship.run",Ad={professional:"price_1T2ldCKszA2slvDXatdeCpbI",power:"price_1T2le9KszA2slvDXR4mPvw7M"},_n="ccc_auth_session",dc=new WeakSet;let G={email:null,sessionToken:null,isVerified:!1};function bs(t={}){return{tier:"free",status:"none",periodEnd:null,isLoading:!1,isResolved:!1,error:null,...t}}let fe=bs({isResolved:!0});const Em=`${Je}/service/runpipeline`,Sm="bs_user_id",xm="bs_identity_token",km=`${Je}/authUserCheck`;let Ge={userId:null,token:null,status:null,resolved:!1};const yn={free:2,professional:50,power:2e3},wn="ccc_subscription",hc=3,Im=new Set(["active","trialing","paid"]),lr="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"],Cm={"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 zt(t){return Cm[t]||t}const Fm=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 $d(t){return Fm.has(t)}const Eo=4,Ci=8*1024*1024,Pm="https://4tgke4.buildship.run/service/runpipeline-image";let Pt=[];function Am(t){return new Promise(e=>{const s=new FileReader;s.onload=()=>e(s.result),s.onerror=()=>e(null),s.readAsDataURL(t)})}async function $m(t){const e=new FormData;return e.append("file",t),(await fetch(Pm,{method:"POST",body:e})).json()}function Rm(t){if(Array.isArray(t)){const e=t[0];if(e&&typeof e=="object")for(const s of Object.keys(e)){if(s==="item"||s==="index")continue;const r=e[s];if(r&&typeof r=="object"){if(typeof r.file=="string")return r.file;if(typeof r.url=="string")return r.url}if(typeof r=="string")return r}return""}return typeof t=="string"?t:t&&typeof t=="object"&&(t.url||t.fileUrl||t.file_url||t.downloadUrl||t.imageUrl||t.image_url||t.file)||""}async function Tm(t){const e=Array.from(t.target.files||[]);if(!e.length)return;const s=e.filter(l=>l.size>Ci);s.length&&ue(`Skipped ${s.length} image(s) over the ${(Ci/1024/1024).toFixed(0)} MB limit.`,"warning");const r=e.filter(l=>l.size<=Ci);if(!r.length){t.target.value="";return}const n=Eo-Pt.length,o=r.slice(0,n).map(async l=>{const u=await Am(l);if(!u)return null;let c="";try{c=Rm(await $m(l))}catch{c=""}return{dataUrl:u,name:l.name,url:c}}),a=(await Promise.all(o)).filter(Boolean);t.target.value="",!(a.length&&!$d(document.getElementById("code-generator-model")?.value))&&(Pt.push(...a),r.length>n&&ue(`You can attach up to ${Eo} images.`,"info"),la())}function Nm(t){Pt.splice(t,1),la()}function la(){const t=document.getElementById("prompt-image-thumbnails"),e=document.getElementById("prompt-image-btn-label");t&&(t.innerHTML="",Pt.forEach((s,r)=>{const n=document.createElement("div");n.className="prompt-img-thumb",n.innerHTML=`Prompt image`,t.appendChild(n)}),e&&(e.textContent=Pt.length>=Eo?"Image limit reached":"Add images"))}function Rd(){const t=document.getElementById("prompt-image-upload");if(!t)return;const e=document.getElementById("code-generator-model"),s=$d(e?.value);t.classList.toggle("hidden",!s),!s&&Pt.length&&(Pt=[],la())}const Gt="ccc_usage",Td="google/gemini-3.7-flash",Nd="google/gemini-3.7-flash",Fi="google/gemini-3.7-flash",pc={professional:11,power:49},So={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 Mm(){const t=new AbortController,e=setTimeout(()=>t.abort(),5e3);try{const s=await fetch("https://open.er-api.com/v6/latest/AUD",{signal:t.signal});if(!s.ok)return;const r=await s.json();if(r.result!=="success"||!r.rates)return;const n=r.rates,i={AUD:1},o=new Set([...Object.keys(Ur),...Object.values(xo),...Object.values(So)]);for(const a of o)a!=="AUD"&&(typeof n[a]=="number"&&n[a]>0?i[a]=n[a]:Ur[a]&&(i[a]=Ur[a]));Hr=i}catch{}finally{clearTimeout(e)}}const xo={"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 Md(){try{const i=Intl.DateTimeFormat().resolvedOptions().timeZone;if(i&&xo[i])return xo[i]}catch{}const e=(navigator.language||"en-US").replace("-","_"),s=So[e];if(s)return s;const r=e.split("_")[0],n=So[r];return n||"USD"}function fc(t,e){const s=Hr[e]??Hr.USD,r=t*s,n=Math.round(r*100)/100;try{return new Intl.NumberFormat("en-US",{style:"currency",currency:e,minimumFractionDigits:0,maximumFractionDigits:n>=100||n%1===0?0:2}).format(n)}catch{return new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",minimumFractionDigits:0,maximumFractionDigits:2}).format(t*Hr.USD)}}const st="ccc_api_key_",_t="ccc_session_api_key_",it="ccc_encryption_key",cr="ccc_encryption_key_scope",Lm="ccc_keystore",bn="keys",ur="ccc_encryption_key_version";let ko=null,En=null,dr=!1,Sn=!1,gc=!1;class xn extends Error{constructor(){super("Secure browser key storage is unavailable."),this.name="CredentialStorageUnavailableError"}}function mc(){if(gc)return;gc=!0;const t="Secure browser key storage is unavailable. Existing credentials were left untouched; new credentials will be available only in this tab session.";console.warn(t),document.body&&ue(t,"warning")}function Ld(){return localStorage.getItem(ur)||""}function Io(){return crypto.randomUUID?.()||Dd(crypto.getRandomValues(new Uint8Array(16)))}function Om(){const t=Ld();if(t)return t;const e=Io();return localStorage.setItem(ur,e),e}function Es(){ko=null,En=null,dr=!1,Sn=!1}window.addEventListener("storage",t=>{t.key===ur&&Es()});function Dm(){return new Promise((t,e)=>{const s=indexedDB.open(Lm,1);s.onupgradeneeded=()=>{const r=s.result;r.objectStoreNames.contains(bn)||r.createObjectStore(bn)},s.onsuccess=()=>t(s.result),s.onerror=()=>e(s.error)})}async function ca(t,e){const s=await Dm();return new Promise((r,n)=>{const i=s.transaction(bn,t);let o;try{o=e(i.objectStore(bn))}catch(l){s.close(),n(l);return}let a;o.onsuccess=()=>{a=o.result},o.onerror=()=>n(o.error),i.oncomplete=()=>{s.close(),r(a)},i.onerror=()=>{s.close(),n(i.error||new Error("Encryption key transaction failed."))},i.onabort=()=>{s.close(),n(i.error||new Error("Encryption key transaction aborted."))}})}function Bm(t){return t instanceof CryptoKey&&t.algorithm?.name==="AES-GCM"&&t.extractable===!1&&t.usages.includes("encrypt")&&t.usages.includes("decrypt")}async function jm(){const t=await ca("readonly",e=>e.get(it));return Bm(t)?t:null}async function Od(t){await ca("readwrite",e=>e.put(t,it))}async function Um(){Es();try{await ca("readwrite",t=>t.delete(it))}catch(t){console.warn("Could not delete the stored encryption key:",t)}}async function Hm(){const t=sessionStorage.getItem(it);if(!t)return null;const e=await crypto.subtle.importKey("jwk",JSON.parse(t),{name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);return await Od(e),sessionStorage.removeItem(it),sessionStorage.removeItem(cr),localStorage.removeItem(st+"salt"),e}async function vc(t){const e=sessionStorage.getItem(it);if(e)return Sn=sessionStorage.getItem(cr)!=="session",crypto.subtle.importKey("jwk",JSON.parse(e),{name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);if(!t)throw new xn;const s=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!0,["encrypt","decrypt"]),r=await crypto.subtle.exportKey("jwk",s);return sessionStorage.setItem(it,JSON.stringify(r)),sessionStorage.setItem(cr,"session"),Sn=!1,crypto.subtle.importKey("jwk",r,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}async function Wm(t){if(sessionStorage.getItem(cr)==="session"&&sessionStorage.getItem(it))return mc(),dr=!0,vc(t);try{const e=await jm();if(e)return e;const s=await Hm();if(s)return s;const r=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);return await Od(r),r}catch(e){return console.warn("IndexedDB encryption-key storage failed:",e),mc(),dr=!0,vc(t)}}async function ua(t={}){const{allowSessionFallbackCreation:e=!0}=t,s=Om();En!==s&&Es();const r=ko||Wm(e);ko=r,En=s;try{return await r}catch(n){throw Es(),n}}async function zm(t){const e=await ua(),s=En,r=new TextEncoder,n=crypto.getRandomValues(new Uint8Array(12)),i=await crypto.subtle.encrypt({name:"AES-GCM",iv:n},e,r.encode(t)),o=new Uint8Array(n.length+i.byteLength);return o.set(n),o.set(new Uint8Array(i),n.length),{ciphertext:Dd(o),keyVersion:s,sessionFallback:dr}}async function qm(t,e={}){const{isSessionCredential:s=!1}=e;try{const r=await ua({allowSessionFallbackCreation:!1});if(dr&&!s&&!Sn)throw new xn;const n=Vm(t),i=n.slice(0,12),o=n.slice(12),a=await crypto.subtle.decrypt({name:"AES-GCM",iv:i},r,o);return new TextDecoder().decode(a)}catch(r){if(r instanceof xn)throw r;return console.error("Decryption failed:",r),null}}function Dd(t){const e=new Uint8Array(t);let s="";for(let r=0;r0}let hr="",kn="",Zs=null,yc=0;async function da(){sessionStorage.getItem(it)&&await ua(),hr=await Ee("flutterflow"),kn=await Ee("flutterflow_project_id"),Zm(),Zt()}function ha(){document.getElementById("api-keys-modal").classList.add("open"),fa(),hr&&Hd(hr)}function Bd(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("api-keys-modal");e&&e.classList.remove("open");const s=document.getElementById("walkthrough-modal");s&&(pa(),s.classList.add("open"))}let Et=1;function jd(){const t=document.querySelector(".wt-steps");return t?Array.from(t.querySelectorAll(".wt-step-card")):[]}function Dn(){const t=jd();t.length&&t.forEach((e,s)=>{const r=s+1;if(r===Et){e.classList.remove("opacity-60","bg-gray-50","border-gray-200"),e.classList.add("bg-blue-50","border-blue-200");const n=e.querySelector("div:first-child");n&&(n.classList.remove("bg-gray-400"),n.classList.add("bg-blue-500"),n.innerHTML=r)}else if(r0&&Et<=t&&(Et++,Dn())}function Km(){const t=document.getElementById("walkthrough-modal");t&&(Et=1,Dn(),t.classList.add("open"))}function Jm(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("walkthrough-modal");e&&e.classList.remove("open");const s=document.getElementById("walkthrough-dont-show");s&&s.checked&&localStorage.setItem("hasSeenWalkthrough","true")}function Ud(){if(G.isVerified&&Jt()&&fe.tier!=="free")return;if(!localStorage.getItem("hasSeenWalkthrough")){const e=document.getElementById("walkthrough-modal");e&&(Et=1,Dn(),e.classList.add("open"))}}async function fa(){const t=document.getElementById("flutterflow-api-key-input");hr?(t.value="",t.placeholder="Key saved (enter new to replace)"):t.placeholder="Enter your FlutterFlow API key",Ym()}function Ym(){wc("flutterflow","flutterflow-key-status"),wc("flutterflow_project_id","flutterflow-project-status")}function wc(t,e){const s=document.getElementById(e);if(!s)return;const r=s.querySelector(".key-status-dot"),n=s.querySelector("span");as(t)?(r.className="key-status-dot configured",n.className="text-green-600",n.textContent="User key configured"):(r.className="key-status-dot missing",n.className="text-gray-500",n.textContent="Not configured")}function Zt(){const t=y.step2Result&&y.step2Result.length>0,e=document.getElementById("btn-deploy-to-ff"),s=document.getElementById("btn-run-pipeline");s&&s.classList.remove("hidden"),e&&e.classList.toggle("hidden",!t)}function Zm(){const t=document.getElementById("api-keys-status");if(!t)return;const e=t.querySelectorAll(".key-status-dot"),s=["flutterflow"];e.forEach((r,n)=>{const i=s[n];i==="flutterflow"?as("flutterflow")&&as("flutterflow_project_id")?(r.className="key-status-dot configured",r.title="FlutterFlow (Fully configured)"):as("flutterflow")||as("flutterflow_project_id")?(r.className="key-status-dot env",r.title="FlutterFlow (Partially configured)"):(r.className="key-status-dot missing",r.title="FlutterFlow (Not configured)"):as(i)?(r.className="key-status-dot configured",r.title=i.charAt(0).toUpperCase()+i.slice(1)+" (User key)"):(r.className="key-status-dot missing",r.title=i.charAt(0).toUpperCase()+i.slice(1)+" (Not configured)")}),Zt()}async function Xm(){const t=document.getElementById("flutterflow-api-key-input"),e=document.getElementById("flutterflow-projects-select");t.value.trim()&&await _c("flutterflow",t.value);const s=e?.value.trim()||"";if(s){if(!Bn(s)){ue("The selected FlutterFlow project has an unexpected ID format.","error"),e.focus();return}await _c("flutterflow_project_id",s)}await da(),fa();const r=document.querySelector("#api-keys-modal .bg-blue-500"),n=r.textContent;r.textContent="Saved!",r.classList.remove("bg-blue-500","hover:bg-blue-600"),r.classList.add("bg-green-500"),setTimeout(()=>{r.textContent=n,r.classList.remove("bg-green-500"),r.classList.add("bg-blue-500","hover:bg-blue-600"),Bd()},1e3)}async function Qm(){if(!confirm("Are you sure you want to clear all stored API keys?"))return;localStorage.setItem(ur,Io()),Es(),localStorage.removeItem(st+"flutterflow"),localStorage.removeItem(st+"flutterflow_project_id"),sessionStorage.removeItem(_t+"flutterflow"),sessionStorage.removeItem(_t+"flutterflow_project_id"),sessionStorage.removeItem(it),sessionStorage.removeItem(cr),localStorage.removeItem(st+"salt"),await Um(),localStorage.setItem(ur,Io()),localStorage.removeItem(st+"flutterflow"),localStorage.removeItem(st+"flutterflow_project_id"),sessionStorage.removeItem(_t+"flutterflow"),sessionStorage.removeItem(_t+"flutterflow_project_id"),await da();const t=document.getElementById("flutterflow-projects-select");t&&(t.innerHTML=''),fa()}function Bn(t){return!t||t.trim().length<5||t.includes(" ")?!1:/^[a-zA-Z0-9-]+$/.test(t)}function ev(t,e){const s=document.getElementById(t);s&&(s.value?e?s.style.borderColor="#22c55e":s.style.borderColor="#ef4444":s.style.borderColor="")}function tv(){const t=document.getElementById("flutterflow-api-key-input");t&&(t.addEventListener("input",e=>{const s=e.target.value.trim().length>0;ev("flutterflow-api-key-input",s)}),t.addEventListener("blur",sv(async e=>{const s=e.target.value.trim();s&&await Hd(s)},500)))}function sv(t,e){let s;return function(...n){const i=()=>{clearTimeout(s),t(...n)};clearTimeout(s),s=setTimeout(i,e)}}async function Hd(t){const e=document.getElementById("flutterflow-projects-select"),s=document.getElementById("flutterflow-projects-error");if(!e){console.error("Projects dropdown element not found");return}e.innerHTML='',s&&s.classList.add("hidden");try{const n=await new gr(t,"").listProjects();if(!n||n.length===0){e.innerHTML='';return}e.innerHTML='',n.forEach(i=>{const o=document.createElement("option");o.value=i.id||i.projectId||"",o.textContent=i.name||i.projectName||`Project ${i.id}`,e.appendChild(o)}),kn&&(e.value=kn)}catch(r){console.error("Failed to fetch projects:",r),e.innerHTML='',s&&(s.textContent=`Failed to load projects: ${r.message}`,s.classList.remove("hidden"))}}function rv(t){const e=document.getElementById(t),r=e.nextElementSibling.querySelector("svg");e.type==="password"?(e.type="text",r.innerHTML=` `):(e.type="password",r.innerHTML=` - `)}let y={step1Result:null,step2Result:null,step3Result:null,bundleSpec:null,artifactBundle:null,bundleReview:null,selectedArtifactId:null,resultsViewMode:"summary",currentStep:0,isRunning:!1};function rv(){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 nv(){y.bundleSpec=or(y.step1Result,{artifactType:"CustomWidget",artifactName:"GeneratedWidget"})}function jn(){const t=gn(y.bundleSpec);y.artifactBundle=or(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=ug(y.artifactBundle);y.artifactBundle={...y.artifactBundle,warnings:[...y.artifactBundle.warnings,...e.findings.map(s=>s.message)],metadata:{...y.artifactBundle.metadata,compatibility:e}},y.selectedArtifactId=gn(y.artifactBundle).id}function Un(){const t=or(y.step3Result,{id:y.artifactBundle?.id,title:y.artifactBundle?.title}),e=new Map(t.artifacts.map(r=>[r.id,r.review])),s=new Map(t.artifacts.filter(r=>{const n=r.review;return n&&typeof n.fixedSource=="string"&&n.fixedSource.trim()}).map(r=>[r.id,r.review.fixedSource.trim()]));y.bundleReview=or({id:y.artifactBundle?.id,title:y.artifactBundle?.title,artifacts:y.artifactBundle?.artifacts?.map(r=>{const n=s.get(r.id)||null;return{...r,review:e.get(r.id)||r.review||y.step3Result||null,...n?{fixedCode:n}:{}}})||[],relationships:y.artifactBundle?.relationships,warnings:y.artifactBundle?.warnings})}function Hd(){const t=ga();return{artifactType:t.artifactType||"CustomWidget",artifactName:t.artifactName||"GeneratedWidget",fileName:t.fileName||""}}function ga(){const t=y.artifactBundle||y.bundleSpec||null;return(Array.isArray(t?.artifacts)?t.artifacts:[]).find(s=>s.id===y.selectedArtifactId)||gn(t)}function ma(){return ga().code||y.step2Result||""}async function iv(){try{await da()}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 ov(t,e){const s=e?.trim()?` (${e.trim().slice(0,200)})`:"";return t===401?`Your FlutterFlow API key was rejected (401 Unauthorized)${s}. Re-enter a current key under API Keys settings, then try again.`:`Listing FlutterFlow projects was denied (403)${s}. 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 gr{constructor(e,s,r="main",n=Wr.production){this.apiKey=e,this.baseUrl=n,this._projectId=s,this._branchName=r,this._endpoint=n}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 s=null;for(const r of e)try{const n=await fetch(`${this.baseUrl}exportCode`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify(r)});if(!n.ok){const a=await n.text();s=new Error(`Export failed: ${n.status} - ${a}`);continue}const i=await n.json(),o=i?.value?.project_zip||i?.project_zip;if(!o){s=new Error("Export response did not include project source.");continue}return o}catch(n){s=n}throw s||new Error("Export failed for an unknown reason.")}async fetchProjectSource(){const e=await this.exportProjectZip(),s=await JSZip.loadAsync(e,{base64:!0}),r=Object.keys(s.files).filter(a=>!s.files[a].dir&&(a==="pubspec.yaml"||a.endsWith("/pubspec.yaml"))).sort((a,l)=>a.split("/").length-l.split("/").length)[0];if(!r)throw new Error("Export did not contain a pubspec.yaml.");const n=r.slice(0,r.length-12),i=new Map,o=Object.keys(s.files).filter(a=>{if(s.files[a].dir||!a.startsWith(n))return!1;const l=a.slice(n.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=>{i.set(a.slice(n.length),await s.files[a].async("string"))})),{pubspecYaml:await s.files[r].async("string"),files:i}}async pushCodeWithRetry(e,s=3){const r=[Wr.production,Wr.staging],n=Math.max(0,r.indexOf(this._endpoint));for(let i=0;isetTimeout(d,1e3*(i+1)));continue}return l}catch(l){console.warn(`Push to ${a} failed: ${l.message}, trying next...`),await new Promise(u=>setTimeout(u,1e3*(i+1)))}}throw new Error("All API endpoints failed after retries")}async pushCode(e){return this.pushCodeWithRetry(e)}parseProjectsResponse(e){if(e?.success&&typeof e.value=="string")try{const r=JSON.parse(e.value);if(r&&Array.isArray(r.entries))return r.entries.map(n=>({id:n.id,name:n.project?.name||n.id}))}catch(r){console.error("Failed to parse stringified project value:",r)}const s=e?.projects||e?.items||e?.entries||(Array.isArray(e)?e:[]);return Array.isArray(s)?s:[]}async listProjects(){console.log("Listing projects for API key");const e=[`${this.baseUrl}listProjects`,"https://api.flutterflow.io/v2/l/listProjects"];let s=0,r="";for(const n of e){const i=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify({project_type:"ALL",deserialize_response:!0})});if(i.ok)return n!==e[0]&&console.log(`listProjects answered on legacy path ${n}`),this.parseProjectsResponse(await i.json());if(s=i.status,r=await i.text(),console.warn(`listProjects via ${n} returned ${s}: ${r}`),i.status===401||i.status===403)throw new Error(ov(i.status,r));if(i.status!==404)throw new Error(`List projects failed: ${i.status} - ${r}`)}throw new Error(`List projects failed: ${s} - ${r}`)}}async function va(t){const e=t.clone();let s;try{s=await t.json()}catch{const i=await e.text();if(!t.ok)return{success:!1,responseCode:t.status,errorMessage:i||`HTTP ${t.status}`,errorMap:new Map};throw new Error(`Invalid JSON response: ${i}`)}if(!t.ok){let n=s.message||`HTTP ${t.status}`,i=new Map;if(s.errors)i=new Map(Object.entries(s.errors));else if(!s.message&&typeof s=="object"){const o=Object.keys(s).filter(a=>a.endsWith(".dart")&&Array.isArray(s[a]));o.length>0&&(i=new Map(Object.entries(s)),n=o.flatMap(l=>s[l].map(u=>`${l}: ${u.errorMessage}`)).join(` -`)||`HTTP ${t.status}`)}return{success:!1,responseCode:t.status,errorMessage:n,errorMap:i}}let r={};if(s.value)try{r=typeof s.value=="string"?JSON.parse(s.value):s.value}catch(n){console.warn("Ignoring malformed push response value:",n)}return{success:!0,responseCode:t.status,errorMap:new Map(Object.entries(r))}}function _a(t,e){return{401:"Authentication failed. Please check your FlutterFlow API key.",403:"Access denied. You may not have permission to modify this project.",404:"Project not found. Please check your Project ID.",409:"Conflict detected. The project may have been modified elsewhere.",422:"Validation failed: Invalid request format",429:"Rate limit exceeded. Please try again in a few minutes.",500:"FlutterFlow server error. Please try again later.",503:"FlutterFlow service temporarily unavailable."}[t]||`FlutterFlow API error: ${`HTTP ${t}`}`}const U={ACTION:"A",WIDGET:"W",FUNCTION:"F",CODE_FILE:"C",DEPENDENCIES:"D",OTHER:"O"},Wd=/class\s+\w+\s+extends\s+(?:StatelessWidget|StatefulWidget)\b/,zd=/extends\s+State<\w+>/;function av(t,e=""){if(t==="pubspec.yaml")return U.DEPENDENCIES;if(!t.endsWith(".dart")||t.endsWith("index.dart"))return U.OTHER;if(t==="custom_functions.dart")return U.FUNCTION;if(e){const s=Wd.test(e),r=zd.test(e);if(s||r)return U.WIDGET;if(/^\s*Future(?:<[^>]+>)?\s+\w+\s*\(/m.test(e))return U.ACTION;if(e.match(/^\s*(String|int|double|bool|List|Map|dynamic|void)\s+\w+\s*\(/m))return U.FUNCTION}return U.CODE_FILE}function qd(t,e){switch(e){case U.ACTION:return`lib/custom_code/actions/${t}`;case U.WIDGET:return`lib/custom_code/widgets/${t}`;case U.FUNCTION:return"lib/flutter_flow/custom_functions.dart";case U.CODE_FILE:return`lib/custom_code/${t}`;case U.DEPENDENCIES:return"pubspec.yaml";case U.OTHER:return`lib/custom_code/${t}`;default:return t}}async function ya(t,e=new Map){return Vf(t,e)}const Co=new Map;function Vd(t){return`${t.baseUrl}|${t.projectId}|${t.branchName}`}function Hn(t){Co.delete(Vd(t))}async function wa(t,e,s,r,n=""){const i=xg(e,s);if(i.length===0)return{remoteFiles:s,syncFileMap:e,unverified:[]};const o=tm(i,n),a={...o.manifest,sources:o.sources},l=o.skipped.map(d=>d.reason);l.forEach(d=>console.warn(`[custom class deploy] ${d}`)),console.log(`Provisioning ${i.length} new FlutterFlow custom code file(s) before sync.`),be.set("provision");const u=await fetch(wm,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:t.apiKey,projectId:t.projectId,baseUrl:t.baseUrl,commitMessage:r,customClasses:i,verification:a,stream:!0})}),c=await rm(u,{onPhase:d=>be.setSubstatus(d),onLog:d=>console.log(`[custom class deploy] ${d}`)});if(!c.success){const d=c.details?` ${c.details}`:"";throw new Error(`${c.error||"FlutterFlow custom class provisioning failed."}${d}`)}return Hn(t),c.verificationSkipped&&(console.warn(`[custom class deploy] ${c.verificationSkipped}`),l.push(c.verificationSkipped)),{remoteFiles:s,syncFileMap:kg(e,i),unverified:l}}async function ba(t,e={}){const s=Vd(t);let r=Co.get(s);if(r===void 0){try{r=await t.fetchProjectSource()}catch(l){throw new Error(`Could not read your project's pubspec.yaml (${l.message}). Deploy was stopped so your existing package dependencies aren't overwritten. Check your FlutterFlow API key and project, then try again.`)}const a=Id(r.pubspecYaml);if(!a.valid)throw new Error(`Your project's pubspec.yaml could not be read reliably (${a.errors.join("; ")}). Deploy was stopped so your existing package dependencies aren't overwritten.`);Co.set(s,r)}const n=await fm(r.pubspecYaml,e),i=Yg(r.pubspecYaml,n.overrides),o=Jg(i.yaml,n.additions);return n.warnings.forEach(a=>console.warn(`[pubspec] ${a}`)),o.added.length>0&&console.log("Adding dependencies:",o.added.map(a=>`${a}: ${n.additions[a]||"any"}`).join(", "),n.sdk.dartSdkFloor?`(resolved for Dart ${n.sdk.dartSdkFloor})`:""),n.kept.forEach(({name:a,constraint:l})=>console.log(`Keeping your existing ${a}: ${l||"(non-version source)"}`)),{...o,overridden:i.overridden,warnings:n.warnings,remoteFiles:r.files}}function lv(t){const e=[],s=[];t.content.length>5e4&&s.push("Code file is large (>50KB). This may take longer to commit."),t.content.length>1e5&&e.push("Code file is too large (>100KB). Consider splitting into smaller components.");const r=t.content.split(` -`).length;r>500&&s.push(`Code has ${r} lines. Consider breaking it into smaller widgets.`),t.content.includes("setState")&&t.codeType===U.ACTION&&s.push("Using setState in a Custom Action may not work as expected. Consider using a Custom Widget."),t.content.includes("dynamic")&&!t.content.includes("?")&&s.push('Code uses "dynamic" types. Consider adding explicit types for better null safety.'),t.content.match(/Color\(0xFF[0-9A-Fa-f]{6}\)/)&&s.push("Code contains hardcoded colors. Consider using FlutterFlowTheme.of(context) for theme consistency.");const n=t.content.match(/print\s*\(/g);n&&n.length>3&&s.push(`Code contains ${n.length} print statements. Consider removing debug prints before committing.`);const i=Wg(t.content);if(i&&e.push(`FlutterFlow cannot format this code - ${i}. Fix or regenerate before committing.`),t.codeType===U.WIDGET){const o=yd(t.content),a=jg(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=`${wd(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:s}}function Gd(t,e={}){const{artifactType:s="CustomWidget",artifactName:r="GeneratedCode",fileName:n}=e,i=Dg(t);let o=n||r;if(s==="CustomFunction")o="custom_functions.dart";else if(s==="CustomWidget"){const u=yd(i)[0],c=u?wd(u):null;c&&o!==c?(console.warn(`Commit file name "${o}" does not match declared widget class "${u}"; renaming to "${c}" so FlutterFlow can find the widget.`),o=c):o.endsWith(".dart")||(o+=".dart")}else o.endsWith(".dart")||(o+=".dart");let a=U.CODE_FILE;switch(s){case"CustomAction":a=U.ACTION;break;case"CustomWidget":a=U.WIDGET;break;case"CustomFunction":a=U.FUNCTION;break;case"CustomClass":case"CodeFile":a=U.CODE_FILE;break}let l="";return a===U.WIDGET?l=`// Automatic FlutterFlow imports + `)}let y={step1Result:null,step2Result:null,step3Result:null,bundleSpec:null,artifactBundle:null,bundleReview:null,selectedArtifactId:null,resultsViewMode:"summary",currentStep:0,isRunning:!1};function nv(){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 iv(){y.bundleSpec=or(y.step1Result,{artifactType:"CustomWidget",artifactName:"GeneratedWidget"})}function jn(){const t=gn(y.bundleSpec);y.artifactBundle=or(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=dg(y.artifactBundle);y.artifactBundle={...y.artifactBundle,warnings:[...y.artifactBundle.warnings,...e.findings.map(s=>s.message)],metadata:{...y.artifactBundle.metadata,compatibility:e}},y.selectedArtifactId=gn(y.artifactBundle).id}function Un(){const t=or(y.step3Result,{id:y.artifactBundle?.id,title:y.artifactBundle?.title}),e=new Map(t.artifacts.map(r=>[r.id,r.review])),s=new Map(t.artifacts.filter(r=>{const n=r.review;return n&&typeof n.fixedSource=="string"&&n.fixedSource.trim()}).map(r=>[r.id,r.review.fixedSource.trim()]));y.bundleReview=or({id:y.artifactBundle?.id,title:y.artifactBundle?.title,artifacts:y.artifactBundle?.artifacts?.map(r=>{const n=s.get(r.id)||null;return{...r,review:e.get(r.id)||r.review||y.step3Result||null,...n?{fixedCode:n}:{}}})||[],relationships:y.artifactBundle?.relationships,warnings:y.artifactBundle?.warnings})}function Wd(){const t=ga();return{artifactType:t.artifactType||"CustomWidget",artifactName:t.artifactName||"GeneratedWidget",fileName:t.fileName||""}}function ga(){const t=y.artifactBundle||y.bundleSpec||null;return(Array.isArray(t?.artifacts)?t.artifacts:[]).find(s=>s.id===y.selectedArtifactId)||gn(t)}function ma(){return ga().code||y.step2Result||""}async function ov(){try{await da()}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 av(t,e){const s=e?.trim()?` (${e.trim().slice(0,200)})`:"";return t===401?`Your FlutterFlow API key was rejected (401 Unauthorized)${s}. Re-enter a current key under API Keys settings, then try again.`:`Listing FlutterFlow projects was denied (403)${s}. 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 gr{constructor(e,s,r="main",n=Wr.production){this.apiKey=e,this.baseUrl=n,this._projectId=s,this._branchName=r,this._endpoint=n}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 s=null;for(const r of e)try{const n=await fetch(`${this.baseUrl}exportCode`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify(r)});if(!n.ok){const a=await n.text();s=new Error(`Export failed: ${n.status} - ${a}`);continue}const i=await n.json(),o=i?.value?.project_zip||i?.project_zip;if(!o){s=new Error("Export response did not include project source.");continue}return o}catch(n){s=n}throw s||new Error("Export failed for an unknown reason.")}async fetchProjectSource(){const e=await this.exportProjectZip(),s=await JSZip.loadAsync(e,{base64:!0}),r=Object.keys(s.files).filter(a=>!s.files[a].dir&&(a==="pubspec.yaml"||a.endsWith("/pubspec.yaml"))).sort((a,l)=>a.split("/").length-l.split("/").length)[0];if(!r)throw new Error("Export did not contain a pubspec.yaml.");const n=r.slice(0,r.length-12),i=new Map,o=Object.keys(s.files).filter(a=>{if(s.files[a].dir||!a.startsWith(n))return!1;const l=a.slice(n.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=>{i.set(a.slice(n.length),await s.files[a].async("string"))})),{pubspecYaml:await s.files[r].async("string"),files:i}}async pushCodeWithRetry(e,s=3){const r=[Wr.production,Wr.staging],n=Math.max(0,r.indexOf(this._endpoint));for(let i=0;isetTimeout(d,1e3*(i+1)));continue}return l}catch(l){console.warn(`Push to ${a} failed: ${l.message}, trying next...`),await new Promise(u=>setTimeout(u,1e3*(i+1)))}}throw new Error("All API endpoints failed after retries")}async pushCode(e){return this.pushCodeWithRetry(e)}parseProjectsResponse(e){if(e?.success&&typeof e.value=="string")try{const r=JSON.parse(e.value);if(r&&Array.isArray(r.entries))return r.entries.map(n=>({id:n.id,name:n.project?.name||n.id}))}catch(r){console.error("Failed to parse stringified project value:",r)}const s=e?.projects||e?.items||e?.entries||(Array.isArray(e)?e:[]);return Array.isArray(s)?s:[]}async listProjects(){console.log("Listing projects for API key");const e=[`${this.baseUrl}listProjects`,"https://api.flutterflow.io/v2/l/listProjects"];let s=0,r="";for(const n of e){const i=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify({project_type:"ALL",deserialize_response:!0})});if(i.ok)return n!==e[0]&&console.log(`listProjects answered on legacy path ${n}`),this.parseProjectsResponse(await i.json());if(s=i.status,r=await i.text(),console.warn(`listProjects via ${n} returned ${s}: ${r}`),i.status===401||i.status===403)throw new Error(av(i.status,r));if(i.status!==404)throw new Error(`List projects failed: ${i.status} - ${r}`)}throw new Error(`List projects failed: ${s} - ${r}`)}}async function va(t){const e=t.clone();let s;try{s=await t.json()}catch{const i=await e.text();if(!t.ok)return{success:!1,responseCode:t.status,errorMessage:i||`HTTP ${t.status}`,errorMap:new Map};throw new Error(`Invalid JSON response: ${i}`)}if(!t.ok){let n=s.message||`HTTP ${t.status}`,i=new Map;if(s.errors)i=new Map(Object.entries(s.errors));else if(!s.message&&typeof s=="object"){const o=Object.keys(s).filter(a=>a.endsWith(".dart")&&Array.isArray(s[a]));o.length>0&&(i=new Map(Object.entries(s)),n=o.flatMap(l=>s[l].map(u=>`${l}: ${u.errorMessage}`)).join(` +`)||`HTTP ${t.status}`)}return{success:!1,responseCode:t.status,errorMessage:n,errorMap:i}}let r={};if(s.value)try{r=typeof s.value=="string"?JSON.parse(s.value):s.value}catch(n){console.warn("Ignoring malformed push response value:",n)}return{success:!0,responseCode:t.status,errorMap:new Map(Object.entries(r))}}function _a(t,e){return{401:"Authentication failed. Please check your FlutterFlow API key.",403:"Access denied. You may not have permission to modify this project.",404:"Project not found. Please check your Project ID.",409:"Conflict detected. The project may have been modified elsewhere.",422:"Validation failed: Invalid request format",429:"Rate limit exceeded. Please try again in a few minutes.",500:"FlutterFlow server error. Please try again later.",503:"FlutterFlow service temporarily unavailable."}[t]||`FlutterFlow API error: ${`HTTP ${t}`}`}const U={ACTION:"A",WIDGET:"W",FUNCTION:"F",CODE_FILE:"C",DEPENDENCIES:"D",OTHER:"O"},zd=/class\s+\w+\s+extends\s+(?:StatelessWidget|StatefulWidget)\b/,qd=/extends\s+State<\w+>/;function lv(t,e=""){if(t==="pubspec.yaml")return U.DEPENDENCIES;if(!t.endsWith(".dart")||t.endsWith("index.dart"))return U.OTHER;if(t==="custom_functions.dart")return U.FUNCTION;if(e){const s=zd.test(e),r=qd.test(e);if(s||r)return U.WIDGET;if(/^\s*Future(?:<[^>]+>)?\s+\w+\s*\(/m.test(e))return U.ACTION;if(e.match(/^\s*(String|int|double|bool|List|Map|dynamic|void)\s+\w+\s*\(/m))return U.FUNCTION}return U.CODE_FILE}function Vd(t,e){switch(e){case U.ACTION:return`lib/custom_code/actions/${t}`;case U.WIDGET:return`lib/custom_code/widgets/${t}`;case U.FUNCTION:return"lib/flutter_flow/custom_functions.dart";case U.CODE_FILE:return`lib/custom_code/${t}`;case U.DEPENDENCIES:return"pubspec.yaml";case U.OTHER:return`lib/custom_code/${t}`;default:return t}}async function ya(t,e=new Map){return Gf(t,e)}const Co=new Map;function Gd(t){return`${t.baseUrl}|${t.projectId}|${t.branchName}`}function Hn(t){Co.delete(Gd(t))}async function wa(t,e,s,r,n=""){const i=xg(e,s);if(i.length===0)return{remoteFiles:s,syncFileMap:e,unverified:[]};const o=sm(i,n),a={...o.manifest,sources:o.sources},l=o.skipped.map(d=>d.reason);l.forEach(d=>console.warn(`[custom class deploy] ${d}`)),console.log(`Provisioning ${i.length} new FlutterFlow custom code file(s) before sync.`),be.set("provision");const u=await fetch(bm,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:t.apiKey,projectId:t.projectId,baseUrl:t.baseUrl,commitMessage:r,customClasses:i,verification:a,stream:!0})}),c=await nm(u,{onPhase:d=>be.setSubstatus(d),onLog:d=>console.log(`[custom class deploy] ${d}`)});if(!c.success){const d=c.details?` ${c.details}`:"";throw new Error(`${c.error||"FlutterFlow custom class provisioning failed."}${d}`)}return Hn(t),c.verificationSkipped&&(console.warn(`[custom class deploy] ${c.verificationSkipped}`),l.push(c.verificationSkipped)),{remoteFiles:s,syncFileMap:kg(e,i),unverified:l}}async function ba(t,e={}){const s=Gd(t);let r=Co.get(s);if(r===void 0){try{r=await t.fetchProjectSource()}catch(l){throw new Error(`Could not read your project's pubspec.yaml (${l.message}). Deploy was stopped so your existing package dependencies aren't overwritten. Check your FlutterFlow API key and project, then try again.`)}const a=Cd(r.pubspecYaml);if(!a.valid)throw new Error(`Your project's pubspec.yaml could not be read reliably (${a.errors.join("; ")}). Deploy was stopped so your existing package dependencies aren't overwritten.`);Co.set(s,r)}const n=await gm(r.pubspecYaml,e),i=Yg(r.pubspecYaml,n.overrides),o=Jg(i.yaml,n.additions);return n.warnings.forEach(a=>console.warn(`[pubspec] ${a}`)),o.added.length>0&&console.log("Adding dependencies:",o.added.map(a=>`${a}: ${n.additions[a]||"any"}`).join(", "),n.sdk.dartSdkFloor?`(resolved for Dart ${n.sdk.dartSdkFloor})`:""),n.kept.forEach(({name:a,constraint:l})=>console.log(`Keeping your existing ${a}: ${l||"(non-version source)"}`)),{...o,overridden:i.overridden,warnings:n.warnings,remoteFiles:r.files}}function cv(t){const e=[],s=[];t.content.length>5e4&&s.push("Code file is large (>50KB). This may take longer to commit."),t.content.length>1e5&&e.push("Code file is too large (>100KB). Consider splitting into smaller components.");const r=t.content.split(` +`).length;r>500&&s.push(`Code has ${r} lines. Consider breaking it into smaller widgets.`),t.content.includes("setState")&&t.codeType===U.ACTION&&s.push("Using setState in a Custom Action may not work as expected. Consider using a Custom Widget."),t.content.includes("dynamic")&&!t.content.includes("?")&&s.push('Code uses "dynamic" types. Consider adding explicit types for better null safety.'),t.content.match(/Color\(0xFF[0-9A-Fa-f]{6}\)/)&&s.push("Code contains hardcoded colors. Consider using FlutterFlowTheme.of(context) for theme consistency.");const n=t.content.match(/print\s*\(/g);n&&n.length>3&&s.push(`Code contains ${n.length} print statements. Consider removing debug prints before committing.`);const i=Wg(t.content);if(i&&e.push(`FlutterFlow cannot format this code - ${i}. Fix or regenerate before committing.`),t.codeType===U.WIDGET){const o=wd(t.content),a=jg(t.fileName);if(o.length===0)e.push("No public widget class found (must extend StatelessWidget or StatefulWidget).");else if(!o.includes(a)){const l=`${bd(o[0])}`;e.push(`Widget class name "${o[0]}" does not match the file name "${t.fileName}". FlutterFlow derives the widget from the file name, so it will report "No widget ${a} found". Rename the file to "${l}" or the class to match before committing.`)}}return{canProceed:e.length===0,issues:e,warnings:s}}function Kd(t,e={}){const{artifactType:s="CustomWidget",artifactName:r="GeneratedCode",fileName:n}=e,i=Dg(t);let o=n||r;if(s==="CustomFunction")o="custom_functions.dart";else if(s==="CustomWidget"){const u=wd(i)[0],c=u?bd(u):null;c&&o!==c?(console.warn(`Commit file name "${o}" does not match declared widget class "${u}"; renaming to "${c}" so FlutterFlow can find the widget.`),o=c):o.endsWith(".dart")||(o+=".dart")}else o.endsWith(".dart")||(o+=".dart");let a=U.CODE_FILE;switch(s){case"CustomAction":a=U.ACTION;break;case"CustomWidget":a=U.WIDGET;break;case"CustomFunction":a=U.FUNCTION;break;case"CustomClass":case"CodeFile":a=U.CODE_FILE;break}let l="";return a===U.WIDGET?l=`// Automatic FlutterFlow imports import '/flutter_flow/flutter_flow_theme.dart'; import '/flutter_flow/flutter_flow_util.dart'; import 'package:flutter/material.dart'; @@ -109,15 +109,15 @@ import '/flutter_flow/lat_lng.dart'; import '/flutter_flow/place.dart'; import '/flutter_flow/uploaded_file.dart'; -`),{content:pg(i,l),fileName:o,codeType:a,artifactType:s,artifactName:r}}function cv(t){const e={};for(const s of ra(t))e[s]="";return e}function uv(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 dv(t,e,s,r=new Set,n=""){const i=[],o=Wd.test(e),a=zd.test(e);return s===U.WIDGET&&!o&&!a&&i.push("No widget class definition found (must extend StatelessWidget or StatefulWidget)"),{valid:i.length===0,errors:i}}function Wn(t){const e=[],s=[];if(!t||t.size===0)return e.push("No files to commit"),{valid:!1,errors:e,warnings:s};const r=new Set(Array.from(t.values()).flatMap(n=>Tn(n.content||"")));for(const[n,i]of t.entries()){if((!i.content||i.content.trim().length===0)&&e.push(`File ${n} is empty`),i.content&&i.content.length>1e5&&s.push(`File ${n} is very large (>100KB)`),n.endsWith(".dart")){const o=dv(n,i.content,i.type,r,i.artifactName);o.valid||e.push(...o.errors.map(a=>`${n}: ${a}`))}if(n==="pubspec.yaml"){const o=Id(i.content);o.valid||e.push(...o.errors)}}return{valid:e.length===0,errors:e,warnings:s}}const V={IDLE:"IDLE",PREPARING:"PREPARING",VALIDATING:"VALIDATING",PUSHING:"PUSHING",SUCCESS:"SUCCESS",ERROR:"ERROR"},K={currentState:V.IDLE,startTime:null,endTime:null,error:null,result:null,filesProcessed:0,totalFiles:0,reset(){this.currentState=V.IDLE,this.startTime=null,this.endTime=null,this.error=null,this.result=null,this.filesProcessed=0,this.totalFiles=0},setState(t){if(!Object.values(V).includes(t)){console.error(`Invalid commit state: ${t}`);return}this.currentState=t,t===V.PREPARING&&(this.startTime=Date.now()),(t===V.SUCCESS||t===V.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(V.ERROR)},setSuccess(t){this.result=t,this.setState(V.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===V.PREPARING||this.currentState===V.VALIDATING||this.currentState===V.PUSHING}};async function hv(t,e,s={}){let{codeType:r="W"}=s;const{pubspecDeps:n={},artifactName:i=e}=s;r==="CustomWidget"&&(r=U.WIDGET),r==="CustomAction"&&(r=U.ACTION),r==="CustomFunction"&&(r=U.FUNCTION),r==="CustomClass"&&(r=U.CODE_FILE),r==="CodeFile"&&(r=U.CODE_FILE),K.reset(),K.setState(V.PREPARING);try{const o=await Ee("flutterflow"),a=await Ee("flutterflow_project_id");if(!o||!a)throw new Error("FlutterFlow credentials not configured. Please set your API key and Project ID in the API Keys settings.");if(!Bn(a))throw new Error("Invalid FlutterFlow Project ID format.");const l=fr(),u=new gr(o,a,"main",l);K.setState(V.VALIDATING);const c=new Map,d=r||av(e,t),h=qd(e,d);c.set(e,{artifactName:i,content:t,type:d,path:h}),K.setProgress(0,c.size);const p=Wn(c);if(!p.valid)throw new Error(`Validation failed: +`),{content:fg(i,l),fileName:o,codeType:a,artifactType:s,artifactName:r}}function uv(t){const e={};for(const s of ra(t))e[s]="";return e}function dv(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 hv(t,e,s,r=new Set,n=""){const i=[],o=zd.test(e),a=qd.test(e);return s===U.WIDGET&&!o&&!a&&i.push("No widget class definition found (must extend StatelessWidget or StatefulWidget)"),{valid:i.length===0,errors:i}}function Wn(t){const e=[],s=[];if(!t||t.size===0)return e.push("No files to commit"),{valid:!1,errors:e,warnings:s};const r=new Set(Array.from(t.values()).flatMap(n=>Tn(n.content||"")));for(const[n,i]of t.entries()){if((!i.content||i.content.trim().length===0)&&e.push(`File ${n} is empty`),i.content&&i.content.length>1e5&&s.push(`File ${n} is very large (>100KB)`),n.endsWith(".dart")){const o=hv(n,i.content,i.type,r,i.artifactName);o.valid||e.push(...o.errors.map(a=>`${n}: ${a}`))}if(n==="pubspec.yaml"){const o=Cd(i.content);o.valid||e.push(...o.errors)}}return{valid:e.length===0,errors:e,warnings:s}}const V={IDLE:"IDLE",PREPARING:"PREPARING",VALIDATING:"VALIDATING",PUSHING:"PUSHING",SUCCESS:"SUCCESS",ERROR:"ERROR"},K={currentState:V.IDLE,startTime:null,endTime:null,error:null,result:null,filesProcessed:0,totalFiles:0,reset(){this.currentState=V.IDLE,this.startTime=null,this.endTime=null,this.error=null,this.result=null,this.filesProcessed=0,this.totalFiles=0},setState(t){if(!Object.values(V).includes(t)){console.error(`Invalid commit state: ${t}`);return}this.currentState=t,t===V.PREPARING&&(this.startTime=Date.now()),(t===V.SUCCESS||t===V.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(V.ERROR)},setSuccess(t){this.result=t,this.setState(V.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===V.PREPARING||this.currentState===V.VALIDATING||this.currentState===V.PUSHING}};async function pv(t,e,s={}){let{codeType:r="W"}=s;const{pubspecDeps:n={},artifactName:i=e}=s;r==="CustomWidget"&&(r=U.WIDGET),r==="CustomAction"&&(r=U.ACTION),r==="CustomFunction"&&(r=U.FUNCTION),r==="CustomClass"&&(r=U.CODE_FILE),r==="CodeFile"&&(r=U.CODE_FILE),K.reset(),K.setState(V.PREPARING);try{const o=await Ee("flutterflow"),a=await Ee("flutterflow_project_id");if(!o||!a)throw new Error("FlutterFlow credentials not configured. Please set your API key and Project ID in the API Keys settings.");if(!Bn(a))throw new Error("Invalid FlutterFlow Project ID format.");const l=fr(),u=new gr(o,a,"main",l);K.setState(V.VALIDATING);const c=new Map,d=r||lv(e,t),h=Vd(e,d);c.set(e,{artifactName:i,content:t,type:d,path:h}),K.setProgress(0,c.size);const p=Wn(c);if(!p.valid)throw new Error(`Validation failed: ${p.errors.join(` -`)}`);const f=await ba(u,n),g=f.yaml,m=await wa(u,c,f.remoteFiles,`Provision ${i} custom class`,g),_=await ya(m.syncFileMap,m.remoteFiles),b=new Map(m.syncFileMap);b.set("pubspec.yaml",{content:g,type:"D",path:"pubspec.yaml"}),be.set("package");const E=await Ea(b),I={project_id:a,zipped_custom_code:E,uid:`web_${Date.now()}`,branch_name:u.branchName,serialized_yaml:g,file_map:_.fileMapContents,functions_map:_.functionsMapContents};K.setState(V.PUSHING),K.setProgress(1,c.size),Hn(u),be.set("push");const F=await u.pushCode(I),P=await va(F);if(P.success)K.setSuccess({fileCount:c.size,projectId:a,warnings:P.errorMap&&P.errorMap.size>0?Array.from(P.errorMap.entries()):[]});else{const B=P.errorMessage||_a(P.responseCode);throw new Error(B)}return{success:!0,message:`Successfully committed ${e} to FlutterFlow project ${a}`,addedDependencies:f.added,unverified:m.unverified,warnings:P.errorMap?Array.from(P.errorMap.entries()):[]}}catch(o){return console.error("Commit failed:",o),K.setError(o),{success:!1,error:o.message,state:K.currentState}}}async function Ea(t){const e=new JSZip;for(const[s,r]of t.entries())e.file(s,r.content);return e.generateAsync({type:"base64",compression:"DEFLATE",compressionOptions:{level:6}})}async function pv(t,e={}){const{artifactType:s,artifactName:r,fileName:n,pipelineResult:i}=e;console.log(`Starting commit for ${r} (${s})`);try{K.setState(V.PREPARING);const o=Gd(t,{artifactType:s,artifactName:r,fileName:n}),a=cv(o.content);console.log("Detected dependencies:",a),K.setState(V.VALIDATING);const l=await Ee("flutterflow"),u=Zs||await Ee("flutterflow_project_id");if(!l)throw new Error("FlutterFlow API Key not configured. Please add it in API Keys settings.");if(!u)throw new Error("FlutterFlow Project ID not configured. Please add it in API Keys settings.");if(!Bn(u))throw new Error("Invalid FlutterFlow Project ID format.");const c=new Map;c.set(o.fileName,{artifactName:r,content:o.content,type:o.codeType,path:qd(o.fileName,o.codeType),functionName:o.codeType===U.FUNCTION?r:void 0}),K.setProgress(0,c.size);const d=Wn(c);if(!d.valid)throw new Error(`File validation failed: +`)}`);const f=await ba(u,n),g=f.yaml,m=await wa(u,c,f.remoteFiles,`Provision ${i} custom class`,g),_=await ya(m.syncFileMap,m.remoteFiles),w=new Map(m.syncFileMap);w.set("pubspec.yaml",{content:g,type:"D",path:"pubspec.yaml"}),be.set("package");const E=await Ea(w),I={project_id:a,zipped_custom_code:E,uid:`web_${Date.now()}`,branch_name:u.branchName,serialized_yaml:g,file_map:_.fileMapContents,functions_map:_.functionsMapContents};K.setState(V.PUSHING),K.setProgress(1,c.size),Hn(u),be.set("push");const F=await u.pushCode(I),P=await va(F);if(P.success)K.setSuccess({fileCount:c.size,projectId:a,warnings:P.errorMap&&P.errorMap.size>0?Array.from(P.errorMap.entries()):[]});else{const B=P.errorMessage||_a(P.responseCode);throw new Error(B)}return{success:!0,message:`Successfully committed ${e} to FlutterFlow project ${a}`,addedDependencies:f.added,unverified:m.unverified,warnings:P.errorMap?Array.from(P.errorMap.entries()):[]}}catch(o){return console.error("Commit failed:",o),K.setError(o),{success:!1,error:o.message,state:K.currentState}}}async function Ea(t){const e=new JSZip;for(const[s,r]of t.entries())e.file(s,r.content);return e.generateAsync({type:"base64",compression:"DEFLATE",compressionOptions:{level:6}})}async function fv(t,e={}){const{artifactType:s,artifactName:r,fileName:n,pipelineResult:i}=e;console.log(`Starting commit for ${r} (${s})`);try{K.setState(V.PREPARING);const o=Kd(t,{artifactType:s,artifactName:r,fileName:n}),a=uv(o.content);console.log("Detected dependencies:",a),K.setState(V.VALIDATING);const l=await Ee("flutterflow"),u=Zs||await Ee("flutterflow_project_id");if(!l)throw new Error("FlutterFlow API Key not configured. Please add it in API Keys settings.");if(!u)throw new Error("FlutterFlow Project ID not configured. Please add it in API Keys settings.");if(!Bn(u))throw new Error("Invalid FlutterFlow Project ID format.");const c=new Map;c.set(o.fileName,{artifactName:r,content:o.content,type:o.codeType,path:Vd(o.fileName,o.codeType),functionName:o.codeType===U.FUNCTION?r:void 0}),K.setProgress(0,c.size);const d=Wn(c);if(!d.valid)throw new Error(`File validation failed: ${d.errors.join(` -`)}`);d.warnings.length>0&&console.warn("Validation warnings:",d.warnings),K.setState(V.PUSHING);const h=fr(),p=new gr(l,u,"main",h),f=await ba(p,a),g=f.yaml,m=await wa(p,c,f.remoteFiles,`Provision ${r} custom class`,g),_=await ya(m.syncFileMap,m.remoteFiles),b=new Map(m.syncFileMap);b.set("pubspec.yaml",{content:g,type:U.DEPENDENCIES,path:"pubspec.yaml"}),be.set("package");const E=await Ea(b),I={project_id:u,zipped_custom_code:E,uid:`web_${Date.now()}`,branch_name:p.branchName,serialized_yaml:g,file_map:_.fileMapContents,functions_map:_.functionsMapContents};K.setProgress(1,c.size),Hn(p),be.set("push");const F=await p.pushCode(I),P=await va(F);if(P.success){const B={...uv(o,i),projectId:u};return K.setSuccess({...B,fileCount:c.size,warnings:P.errorMap?Array.from(P.errorMap.entries()):[]}),{success:!0,message:`Successfully committed ${o.fileName} to FlutterFlow`,metadata:B,addedDependencies:f.added,unverified:m.unverified,warnings:P.errorMap?Array.from(P.errorMap.entries()):[],elapsedTime:K.getElapsedTime()}}else{const B=P.errorMessage||_a(P.responseCode),S=new Error(B);throw S.errorMap=P.errorMap,S}}catch(o){console.error("Commit execution failed:",o),K.setError(o);let a=new Map;if(o.errorMap)a=o.errorMap;else if(o.message&&o.message.includes("{"))try{const l=o.message.match(/\{[\s\S]*\}/);if(l){const u=JSON.parse(l[0]);a=new Map(Object.entries(u))}}catch(l){console.warn("Failed to parse error map from commit response:",l)}return{success:!1,error:o.message,errorMap:a,state:K.currentState,elapsedTime:K.getElapsedTime()}}}async function fv(t,e={}){const{pipelineResult:s}=e;try{if(K.setState(V.PREPARING),t.errors?.length>0)throw new Error(`Bundle validation failed: +`)}`);d.warnings.length>0&&console.warn("Validation warnings:",d.warnings),K.setState(V.PUSHING);const h=fr(),p=new gr(l,u,"main",h),f=await ba(p,a),g=f.yaml,m=await wa(p,c,f.remoteFiles,`Provision ${r} custom class`,g),_=await ya(m.syncFileMap,m.remoteFiles),w=new Map(m.syncFileMap);w.set("pubspec.yaml",{content:g,type:U.DEPENDENCIES,path:"pubspec.yaml"}),be.set("package");const E=await Ea(w),I={project_id:u,zipped_custom_code:E,uid:`web_${Date.now()}`,branch_name:p.branchName,serialized_yaml:g,file_map:_.fileMapContents,functions_map:_.functionsMapContents};K.setProgress(1,c.size),Hn(p),be.set("push");const F=await p.pushCode(I),P=await va(F);if(P.success){const B={...dv(o,i),projectId:u};return K.setSuccess({...B,fileCount:c.size,warnings:P.errorMap?Array.from(P.errorMap.entries()):[]}),{success:!0,message:`Successfully committed ${o.fileName} to FlutterFlow`,metadata:B,addedDependencies:f.added,unverified:m.unverified,warnings:P.errorMap?Array.from(P.errorMap.entries()):[],elapsedTime:K.getElapsedTime()}}else{const B=P.errorMessage||_a(P.responseCode),S=new Error(B);throw S.errorMap=P.errorMap,S}}catch(o){console.error("Commit execution failed:",o),K.setError(o);let a=new Map;if(o.errorMap)a=o.errorMap;else if(o.message&&o.message.includes("{"))try{const l=o.message.match(/\{[\s\S]*\}/);if(l){const u=JSON.parse(l[0]);a=new Map(Object.entries(u))}}catch(l){console.warn("Failed to parse error map from commit response:",l)}return{success:!1,error:o.message,errorMap:a,state:K.currentState,elapsedTime:K.getElapsedTime()}}}async function gv(t,e={}){const{pipelineResult:s}=e;try{if(K.setState(V.PREPARING),t.errors?.length>0)throw new Error(`Bundle validation failed: ${t.errors.join(` `)}`);const r=new Map(t.fileEntries.map(I=>[I.fileName,{artifactId:I.artifactId,artifactName:I.artifactName,content:I.content,type:I.type,path:I.path,functionName:I.type===U.FUNCTION?I.artifactName:void 0}]));K.setProgress(0,r.size);const n=Wn(r);if(!n.valid)throw new Error(`File validation failed: ${n.errors.join(` -`)}`);K.setState(V.VALIDATING);const i=await Ee("flutterflow"),o=Zs||await Ee("flutterflow_project_id");if(!i)throw new Error("FlutterFlow API Key not configured. Please add it in API Keys settings.");if(!o)throw new Error("FlutterFlow Project ID not configured. Please add it in API Keys settings.");if(!Bn(o))throw new Error("Invalid FlutterFlow Project ID format.");K.setState(V.PUSHING);const a=fr(),l=new gr(i,o,"main",a),u=await ba(l,t.dependencies),c=u.yaml,d=await wa(l,r,u.remoteFiles,`Provision ${t.title} custom classes`,c),h=await ya(d.syncFileMap,d.remoteFiles),p=new Map(d.syncFileMap);p.set("pubspec.yaml",{content:c,type:U.DEPENDENCIES,path:"pubspec.yaml"}),be.set("package");const f=await Ea(p),g={project_id:o,zipped_custom_code:f,uid:`web_${Date.now()}`,branch_name:l.branchName,serialized_yaml:c,file_map:h.fileMapContents,functions_map:h.functionsMapContents};K.setProgress(1,r.size),Hn(l),be.set("push");const m=await l.pushCode(g),_=await va(m);if(_.success){const I={...s,artifactType:"Bundle",artifactName:t.title,fileName:`${t.fileEntries.length} artifacts`,codeSize:t.fileEntries.reduce((F,P)=>F+P.content.length,0),projectId:o};return K.setSuccess({...I,fileCount:r.size,warnings:_.errorMap?Array.from(_.errorMap.entries()):[]}),{success:!0,message:`Successfully committed ${t.fileEntries.length} artifacts to FlutterFlow`,metadata:I,addedDependencies:u.added,unverified:d.unverified,warnings:_.errorMap?Array.from(_.errorMap.entries()):[],elapsedTime:K.getElapsedTime()}}const b=_.errorMessage||_a(_.responseCode),E=new Error(b);throw E.errorMap=_.errorMap,E}catch(r){return console.error("Bundle commit execution failed:",r),K.setError(r),{success:!1,error:r.message,errorMap:r.errorMap||new Map,state:K.currentState,elapsedTime:K.getElapsedTime()}}}async function gv(t,e=[]){const s=Qo("architect");try{return await In("architect",Rd,Nf(t),s,e)}catch(r){throw r.isModelArmor?r:new Error(`Prompt Architect failed: ${r.message}`)}}async function zn(t,e,s=[]){const r=Mf(t),n=Qo("generator",y.bundleSpec);try{return await In("generator",e,r,n,s)}catch(i){if(i.isModelArmor)throw i;if(e!==Fi){console.warn(`Code Generator failed with ${e}, retrying with fallback model:`,i.message);try{return await In("generator",Fi,r,n,s)}catch(o){throw o.isModelArmor?o:new Error(`Code Generator failed: primary (${e}): ${i.message} | fallback (${Fi}): ${o.message}`)}}throw new Error(`Code Generator failed: ${i.message}`)}}async function qn(t,e=null){const s={...Qo("review",y.artifactBundle||y.bundleSpec),architect_output:e};try{return await In("review",Td,Lf(t),s)}catch(r){throw r.isModelArmor?r:new Error(`Code Review failed: ${r.message}`)}}function Sa(t,e){return t.isModelArmor?`${t.userTitle}: ${t.userMessage}`:`${e}: ${t.message}`}function Fo(t,e){const s=document.getElementById(`step${t}-item`),r=document.getElementById(`step${t}-status`);!s||!r||(s.classList.remove("active","completed","error"),r.classList.remove("running","completed","error"),e==="active"?(s.classList.add("active"),r.classList.add("running"),r.innerHTML=` +`)}`);K.setState(V.VALIDATING);const i=await Ee("flutterflow"),o=Zs||await Ee("flutterflow_project_id");if(!i)throw new Error("FlutterFlow API Key not configured. Please add it in API Keys settings.");if(!o)throw new Error("FlutterFlow Project ID not configured. Please add it in API Keys settings.");if(!Bn(o))throw new Error("Invalid FlutterFlow Project ID format.");K.setState(V.PUSHING);const a=fr(),l=new gr(i,o,"main",a),u=await ba(l,t.dependencies),c=u.yaml,d=await wa(l,r,u.remoteFiles,`Provision ${t.title} custom classes`,c),h=await ya(d.syncFileMap,d.remoteFiles),p=new Map(d.syncFileMap);p.set("pubspec.yaml",{content:c,type:U.DEPENDENCIES,path:"pubspec.yaml"}),be.set("package");const f=await Ea(p),g={project_id:o,zipped_custom_code:f,uid:`web_${Date.now()}`,branch_name:l.branchName,serialized_yaml:c,file_map:h.fileMapContents,functions_map:h.functionsMapContents};K.setProgress(1,r.size),Hn(l),be.set("push");const m=await l.pushCode(g),_=await va(m);if(_.success){const I={...s,artifactType:"Bundle",artifactName:t.title,fileName:`${t.fileEntries.length} artifacts`,codeSize:t.fileEntries.reduce((F,P)=>F+P.content.length,0),projectId:o};return K.setSuccess({...I,fileCount:r.size,warnings:_.errorMap?Array.from(_.errorMap.entries()):[]}),{success:!0,message:`Successfully committed ${t.fileEntries.length} artifacts to FlutterFlow`,metadata:I,addedDependencies:u.added,unverified:d.unverified,warnings:_.errorMap?Array.from(_.errorMap.entries()):[],elapsedTime:K.getElapsedTime()}}const w=_.errorMessage||_a(_.responseCode),E=new Error(w);throw E.errorMap=_.errorMap,E}catch(r){return console.error("Bundle commit execution failed:",r),K.setError(r),{success:!1,error:r.message,errorMap:r.errorMap||new Map,state:K.currentState,elapsedTime:K.getElapsedTime()}}}async function mv(t,e=[]){const s=Qo("architect");try{return await In("architect",Td,Mf(t),s,e)}catch(r){throw r.isModelArmor?r:new Error(`Prompt Architect failed: ${r.message}`)}}async function zn(t,e,s=[]){const r=Lf(t),n=Qo("generator",y.bundleSpec);try{return await In("generator",e,r,n,s)}catch(i){if(i.isModelArmor)throw i;if(e!==Fi){console.warn(`Code Generator failed with ${e}, retrying with fallback model:`,i.message);try{return await In("generator",Fi,r,n,s)}catch(o){throw o.isModelArmor?o:new Error(`Code Generator failed: primary (${e}): ${i.message} | fallback (${Fi}): ${o.message}`)}}throw new Error(`Code Generator failed: ${i.message}`)}}async function qn(t,e=null){const s={...Qo("review",y.artifactBundle||y.bundleSpec),architect_output:e};try{return await In("review",Nd,Of(t),s)}catch(r){throw r.isModelArmor?r:new Error(`Code Review failed: ${r.message}`)}}function Sa(t,e){return t.isModelArmor?`${t.userTitle}: ${t.userMessage}`:`${e}: ${t.message}`}function Fo(t,e){const s=document.getElementById(`step${t}-item`),r=document.getElementById(`step${t}-status`);!s||!r||(s.classList.remove("active","completed","error"),r.classList.remove("running","completed","error"),e==="active"?(s.classList.add("active"),r.classList.add("running"),r.innerHTML=` `):e==="completed"?(s.classList.add("completed"),r.classList.add("completed"),r.innerHTML=` @@ -125,15 +125,15 @@ ${n.errors.join(` `):r.innerHTML=` - `)}function ve(t,e){const s=document.getElementById(`step${t}-loading`),r=document.getElementById(`step${t}-result`);e?(s.classList.remove("hidden"),r.classList.add("hidden"),Fo(t,"active")):(s.classList.add("hidden"),r.classList.remove("hidden"),Fo(t,"completed"))}function mv(t){const e=document.getElementById(`${t}-content`),s=document.getElementById(`${t}-chevron`);e.classList.contains("open")?(e.classList.remove("open"),s&&(s.style.transform="rotate(0deg)")):(e.classList.add("open"),s&&(s.style.transform="rotate(180deg)"))}function vv(t){ze(parseInt(t.replace("step","")))}function ze(t){for(let o=1;o<=3;o++){const a=document.getElementById(`step${o}-item`);a&&a.classList.remove("active")}const e=document.getElementById(`step${t}-item`);e&&e.classList.add("active"),Yt();const s=document.getElementById("ready-state");s&&s.classList.add("hidden");for(let o=1;o<=3;o++){const a=document.getElementById(`step${o}-content`);a&&a.classList.add("hidden")}const r=document.getElementById(`step${t}-content`);r&&r.classList.remove("hidden");const n=document.getElementById("stage-title"),i={1:"Prompt Architect",2:"Code Generator",3:"Code Review"};n&&(n.textContent=i[t]||"Active Workflow Stage")}function _v(t){const e=document.getElementById(t);if(!e)return;const s=e.dataset.raw||e.textContent;navigator.clipboard.writeText(s).then(()=>{const n=e.closest(".code-container")?.querySelector(".copy-btn");n&&(n.classList.add("copied"),n.innerHTML=' Copied!',setTimeout(()=>{n.classList.remove("copied"),n.innerHTML=' Copy'},2e3))}).catch(r=>{console.warn("Failed to copy to clipboard:",r)})}function Po(t){const e=$o(t);console.log(`Step 1 (Prompt Architect): ${zt(Rd)}`),console.log(e!==t?`Step 2 (Code Generator): ${zt(t)} → ${zt(e)} (Free Tier fallback)`:`Step 2 (Code Generator): ${zt(t)}`),console.log(`Step 3 (Code Review): ${zt(Td)}`)}async function yv(){if(console.log("runRefinement called"),y.isRunning)return;const t=document.getElementById("code-generator-model").value;y.isRunning=!0,xa("standardRegenerate",y.step2Result,y.step1Result);const e=document.querySelectorAll(".btn-refine-action");e.forEach(s=>{s.disabled=!0,s.innerHTML=` + `)}function ve(t,e){const s=document.getElementById(`step${t}-loading`),r=document.getElementById(`step${t}-result`);e?(s.classList.remove("hidden"),r.classList.add("hidden"),Fo(t,"active")):(s.classList.add("hidden"),r.classList.remove("hidden"),Fo(t,"completed"))}function vv(t){const e=document.getElementById(`${t}-content`),s=document.getElementById(`${t}-chevron`);e.classList.contains("open")?(e.classList.remove("open"),s&&(s.style.transform="rotate(0deg)")):(e.classList.add("open"),s&&(s.style.transform="rotate(180deg)"))}function _v(t){ze(parseInt(t.replace("step","")))}function ze(t){for(let o=1;o<=3;o++){const a=document.getElementById(`step${o}-item`);a&&a.classList.remove("active")}const e=document.getElementById(`step${t}-item`);e&&e.classList.add("active"),Yt();const s=document.getElementById("ready-state");s&&s.classList.add("hidden");for(let o=1;o<=3;o++){const a=document.getElementById(`step${o}-content`);a&&a.classList.add("hidden")}const r=document.getElementById(`step${t}-content`);r&&r.classList.remove("hidden");const n=document.getElementById("stage-title"),i={1:"Prompt Architect",2:"Code Generator",3:"Code Review"};n&&(n.textContent=i[t]||"Active Workflow Stage")}function yv(t){const e=document.getElementById(t);if(!e)return;const s=e.dataset.raw||e.textContent;navigator.clipboard.writeText(s).then(()=>{const n=e.closest(".code-container")?.querySelector(".copy-btn");n&&(n.classList.add("copied"),n.innerHTML=' Copied!',setTimeout(()=>{n.classList.remove("copied"),n.innerHTML=' Copy'},2e3))}).catch(r=>{console.warn("Failed to copy to clipboard:",r)})}function Po(t){const e=$o(t);console.log(`Step 1 (Prompt Architect): ${zt(Td)}`),console.log(e!==t?`Step 2 (Code Generator): ${zt(t)} → ${zt(e)} (Free Tier fallback)`:`Step 2 (Code Generator): ${zt(t)}`),console.log(`Step 3 (Code Review): ${zt(Nd)}`)}async function wv(){if(console.log("runRefinement called"),y.isRunning)return;const t=document.getElementById("code-generator-model").value;y.isRunning=!0,xa("standardRegenerate",y.step2Result,y.step1Result);const e=document.querySelectorAll(".btn-refine-action");e.forEach(s=>{s.disabled=!0,s.innerHTML=` - Refining...`});try{const s=ga(),r=Of({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,artifactId:s.id,userFeedback:"Fix the issues listed in the audit report."});Kn(),nt(2),ze(2),ve(2,!0),y.step2Result=await zn(r,t),jn();const n=document.getElementById("step2-output"),i=ws(y.step2Result);n.textContent=i,n.dataset.raw=i,ve(2,!1),ze(3),nt(3),ve(3,!0),y.step3Result=await qn(y.step2Result,y.step1Result),Un();const o=document.getElementById("step3-output");o.textContent=y.step3Result,ve(3,!1),$t();const a=On(y.step3Result);Jn(i,a)}catch(s){console.error("Refinement failed:",s),$t(),ue(Sa(s,"Refinement failed"),"error")}finally{y.isRunning=!1,e.forEach(s=>{s.disabled=!1,s.textContent="Refine & Regenerate"}),Zt()}}async function xa(t,e,s){const r=`${Je}/connectFeedback`,n={type:t,code:e,input:s};try{const i=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!i.ok){const a=await i.text();return console.error(`callEndpoint failed: ${i.status} ${i.statusText}`,a),{success:!1,status:i.status,error:a}}const o=await i.json();return console.log("Telemetry success:",o),o}catch(i){return console.error("callEndpoint failed:",i),{success:!1,error:i.message}}}function wv(){const t=document.getElementById("ff-error-paste-input");t&&(t.value="")}async function bv(){const t=document.getElementById("ff-error-paste-input"),e=t?.value?.trim();if(!e){t?.focus(),t?.classList.add("ring-2","ring-red-400","border-red-300"),setTimeout(()=>t?.classList.remove("ring-2","ring-red-400","border-red-300"),2e3);return}if(!y.step2Result){ue("No generated code found. Please run the full pipeline first.","warning");return}if(y.isRunning)return;const s=document.getElementById("code-generator-model").value;y.isRunning=!0,xa("flutterflowError",y.step2Result,e);const r=document.getElementById("btn-fix-from-errors");r&&(r.disabled=!0,r.innerHTML=` + Refining...`});try{const s=ga(),r=Df({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,artifactId:s.id,userFeedback:"Fix the issues listed in the audit report."});Kn(),nt(2),ze(2),ve(2,!0),y.step2Result=await zn(r,t),jn();const n=document.getElementById("step2-output"),i=ws(y.step2Result);n.textContent=i,n.dataset.raw=i,ve(2,!1),ze(3),nt(3),ve(3,!0),y.step3Result=await qn(y.step2Result,y.step1Result),Un();const o=document.getElementById("step3-output");o.textContent=y.step3Result,ve(3,!1),$t();const a=On(y.step3Result);Jn(i,a)}catch(s){console.error("Refinement failed:",s),$t(),ue(Sa(s,"Refinement failed"),"error")}finally{y.isRunning=!1,e.forEach(s=>{s.disabled=!1,s.textContent="Refine & Regenerate"}),Zt()}}async function xa(t,e,s){const r=`${Je}/connectFeedback`,n={type:t,code:e,input:s};try{const i=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!i.ok){const a=await i.text();return console.error(`callEndpoint failed: ${i.status} ${i.statusText}`,a),{success:!1,status:i.status,error:a}}const o=await i.json();return console.log("Telemetry success:",o),o}catch(i){return console.error("callEndpoint failed:",i),{success:!1,error:i.message}}}function bv(){const t=document.getElementById("ff-error-paste-input");t&&(t.value="")}async function Ev(){const t=document.getElementById("ff-error-paste-input"),e=t?.value?.trim();if(!e){t?.focus(),t?.classList.add("ring-2","ring-red-400","border-red-300"),setTimeout(()=>t?.classList.remove("ring-2","ring-red-400","border-red-300"),2e3);return}if(!y.step2Result){ue("No generated code found. Please run the full pipeline first.","warning");return}if(y.isRunning)return;const s=document.getElementById("code-generator-model").value;y.isRunning=!0,xa("flutterflowError",y.step2Result,e);const r=document.getElementById("btn-fix-from-errors");r&&(r.disabled=!0,r.innerHTML=` - Fixing…`);try{const n=fd({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,userFeedback:e});oh(),Kn(),nt(2),ze(2),ve(2,!0),y.step2Result=await zn(n,s),jn();const i=document.getElementById("step2-output"),o=ws(y.step2Result);i.textContent=o,i.dataset.raw=o,ve(2,!1),ze(3),nt(3),ve(3,!0),y.step3Result=await qn(y.step2Result,y.step1Result),Un();const a=document.getElementById("step3-output");a.textContent=y.step3Result,ve(3,!1),$t();const l=On(y.step3Result);Jn(o,l),t&&(t.value="")}catch(n){console.error("Fix from errors failed:",n),$t(),ue(Sa(n,"Failed to fix errors"),"error")}finally{y.isRunning=!1,r&&(r.disabled=!1,r.textContent="Fix Errors & Regenerate"),Zt()}}async function Ao(){if(console.log("runThinkingPipeline called"),y.isRunning)return;localStorage.setItem("hasSeenWalkthrough","true");const t=document.getElementById("pipeline-input").value,e=document.getElementById("code-generator-model").value;if(!t.trim()){ue("Please describe your FlutterFlow widget first.","warning");return}if(!await Uv())return;await Mv();const s=$o(e);t.length;const r=document.getElementById("btn-run-pipeline");y.isRunning=!0,rv(),r.disabled=!0,r.innerHTML=` + Fixing…`);try{const n=fd({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,userFeedback:e});ah(),Kn(),nt(2),ze(2),ve(2,!0),y.step2Result=await zn(n,s),jn();const i=document.getElementById("step2-output"),o=ws(y.step2Result);i.textContent=o,i.dataset.raw=o,ve(2,!1),ze(3),nt(3),ve(3,!0),y.step3Result=await qn(y.step2Result,y.step1Result),Un();const a=document.getElementById("step3-output");a.textContent=y.step3Result,ve(3,!1),$t();const l=On(y.step3Result);Jn(o,l),t&&(t.value="")}catch(n){console.error("Fix from errors failed:",n),$t(),ue(Sa(n,"Failed to fix errors"),"error")}finally{y.isRunning=!1,r&&(r.disabled=!1,r.textContent="Fix Errors & Regenerate"),Zt()}}async function Ao(){if(console.log("runThinkingPipeline called"),y.isRunning)return;localStorage.setItem("hasSeenWalkthrough","true");const t=document.getElementById("pipeline-input").value,e=document.getElementById("code-generator-model").value;if(!t.trim()){ue("Please describe your FlutterFlow widget first.","warning");return}if(!await Hv())return;await Lv();const s=$o(e);t.length;const r=document.getElementById("btn-run-pipeline");y.isRunning=!0,nv(),r.disabled=!0,r.innerHTML=` - Running...`,Po(s);try{Yt();const n=document.getElementById("ready-state");n&&n.classList.add("hidden");const i=document.getElementById("paywall-exhausted");i&&i.classList.add("hidden"),Kn(),ze(1),nt(1),ve(1,!0);const o=Pt.filter(p=>p.url).map(p=>({url:p.url}));y.step1Result=await gv(t,o),nv();const a=document.getElementById("step1-output"),l=ws(y.step1Result);a.textContent=l,a.dataset.raw=l,ve(1,!1),ze(2),nt(2),ve(2,!0),y.step2Result=await zn(y.step1Result,s,o),jn();const u=document.getElementById("step2-output"),c=ws(y.step2Result);u.textContent=c,u.dataset.raw=c,ve(2,!1),ze(3),nt(3),ve(3,!0),y.step3Result=await qn(y.step2Result,y.step1Result),Un();const d=document.getElementById("step3-output");d.textContent=y.step3Result,ve(3,!1),$t();const h=On(y.step3Result);Jn(c,h)}catch(n){if(console.error("Pipeline failed:",n),$t(),n.isUsageLimit){const{count:c}=Vn();Aa(c,Pa(),{openModal:!0});return}n.message,$o(document.getElementById("code-generator-model").value);const o=mm(n,{architect:1,generator:2,review:3});ze(o);const a=document.getElementById(`step${o}-result`),l=document.getElementById(`step${o}-loading`),u=document.getElementById(`step${o}-output`);if(l&&l.classList.add("hidden"),a&&a.classList.remove("hidden"),u)if(n.isModelArmor)u.innerHTML=`
    - `}function u_(t){const e=t.artifacts.find(l=>l.id===y.selectedArtifactId)||t.artifacts[0];if(!e)return"";const s={pass:{icon:"pass",message:"No file-specific issues were found."},warning:{icon:"warning",message:"This file needs attention, but Code Review did not return a specific finding."},fail:{icon:"fail",message:"This file is blocked, but Code Review did not return a specific finding."}}[e.status],r=e.findings.length?e.findings.map(a_).join(""):`
    ${Ss(s.icon)} ${j(s.message)}
    `,n=e.dependencies?.length?e.dependencies.map(l=>` + `}function d_(t){const e=t.artifacts.find(l=>l.id===y.selectedArtifactId)||t.artifacts[0];if(!e)return"";const s={pass:{icon:"pass",message:"No file-specific issues were found."},warning:{icon:"warning",message:"This file needs attention, but Code Review did not return a specific finding."},fail:{icon:"fail",message:"This file is blocked, but Code Review did not return a specific finding."}}[e.status],r=e.findings.length?e.findings.map(l_).join(""):`
    ${Ss(s.icon)} ${j(s.message)}
    `,n=e.dependencies?.length?e.dependencies.map(l=>`
  • ${j(l.name)}${l.version?` ${j(l.version)}`:""}${l.reason?`

    ${j(l.reason)}

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

    ${j(l.description)}

    `:""}
  • `).join(""):'
  • No relationships for this file
  • ';return`
    - ${Ss(e.status)} ${j(nh(e.status))} + ${Ss(e.status)} ${j(ih(e.status))}

    ${j(e.artifactName)}

    ${e.description?`

    ${j(e.description)}

    `:""}
    @@ -272,7 +272,7 @@ Error: ${h} ${e.manualSteps.length?`

    Manual FlutterFlow steps for this file

    -
      ${e.manualSteps.map(l_).join("")}
    +
      ${e.manualSteps.map(c_).join("")}
    `:""}
    @@ -304,12 +304,12 @@ Error: ${h}
      ${a}
    - `}function d_(t){const e=document.getElementById("bundle-strip"),s=document.getElementById("results-summary-tab"),r=document.getElementById("artifact-tabs"),n=document.getElementById("results-file-count");if(s&&s.classList.toggle("active",y.resultsViewMode==="summary"),!t.artifacts.length){n&&(n.textContent="0 files"),e&&e.classList.remove("visible"),r&&(r.innerHTML="");return}if(n){const i=t.artifacts.length;n.textContent=`${i} ${i===1?"file":"files"}`}r&&(r.innerHTML=t.artifacts.map(i=>` + `}function h_(t){const e=document.getElementById("bundle-strip"),s=document.getElementById("results-summary-tab"),r=document.getElementById("artifact-tabs"),n=document.getElementById("results-file-count");if(s&&s.classList.toggle("active",y.resultsViewMode==="summary"),!t.artifacts.length){n&&(n.textContent="0 files"),e&&e.classList.remove("visible"),r&&(r.innerHTML="");return}if(n){const i=t.artifacts.length;n.textContent=`${i} ${i===1?"file":"files"}`}r&&(r.innerHTML=t.artifacts.map(i=>` - `).join(""),r.onclick=i=>{const o=i.target.closest(".artifact-tab");o?.dataset?.artifactId&&ih(o.dataset.artifactId)}),e&&e.classList.add("visible")}function Ra(){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"),s=document.getElementById("results-audit-output"),r=document.getElementById("results-summary-detail"),n=document.getElementById("artifact-results-split"),i=o_(),o=ma();if(c_(i),d_(i),e&&(e.textContent=""),e){const a=Fd(o);e.innerHTML=a}s&&(s.innerHTML=u_(i)),r&&r.classList.toggle("hidden",y.resultsViewMode!=="summary"),n&&n.classList.toggle("hidden",y.resultsViewMode!=="file"),t&&t.classList.add("visible")}function Jn(t,e){y.selectedArtifactId||(y.selectedArtifactId=gn(y.artifactBundle).id),y.resultsViewMode="summary",document.body.classList.add("results-fullscreen");const s=document.getElementById("step3-output");s&&(s.textContent=""),Ra(),Zt();const r=document.getElementById("btn-feedback-up"),n=document.getElementById("btn-feedback-down");r&&(r.className="feedback-btn"),n&&(n.className="feedback-btn")}function ih(t){y.selectedArtifactId=t,y.resultsViewMode="file",Ra()}function h_(){y.resultsViewMode="summary",Ra()}function p_(){const t=document.getElementById("btn-copy-results"),e=ma();navigator.clipboard.writeText(e).then(()=>{if(t){t.classList.add("copied");const s=t.querySelector("span");if(s){const r=s.textContent;s.textContent="Copied!",setTimeout(()=>{t.classList.remove("copied"),s.textContent=r},2e3)}}})}function f_(t){const e=document.getElementById("btn-feedback-up"),s=document.getElementById("btn-feedback-down");t==="up"?(e.classList.toggle("active-up"),s.classList.remove("active-down")):(s.classList.toggle("active-down"),e.classList.remove("active-up")),xa(t==="up"?"thumbsUp":"thumbsDown",y.step2Result,y.step1Result)}function g_(){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 oh(){const t=document.getElementById("error-input-panel");t&&(t.classList.add("hidden"),t.style.display="none")}window.copyResultsCode=p_;window.selectArtifact=ih;window.selectResultsSummary=h_;window.submitResultsFeedback=f_;window.showErrorInputPanel=g_;window.hideErrorInputPanel=oh; + `).join(""),r.onclick=i=>{const o=i.target.closest(".artifact-tab");o?.dataset?.artifactId&&oh(o.dataset.artifactId)}),e&&e.classList.add("visible")}function Ra(){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"),s=document.getElementById("results-audit-output"),r=document.getElementById("results-summary-detail"),n=document.getElementById("artifact-results-split"),i=a_(),o=ma();if(u_(i),h_(i),e&&(e.textContent=""),e){const a=Pd(o);e.innerHTML=a}s&&(s.innerHTML=d_(i)),r&&r.classList.toggle("hidden",y.resultsViewMode!=="summary"),n&&n.classList.toggle("hidden",y.resultsViewMode!=="file"),t&&t.classList.add("visible")}function Jn(t,e){y.selectedArtifactId||(y.selectedArtifactId=gn(y.artifactBundle).id),y.resultsViewMode="summary",document.body.classList.add("results-fullscreen");const s=document.getElementById("step3-output");s&&(s.textContent=""),Ra(),Zt();const r=document.getElementById("btn-feedback-up"),n=document.getElementById("btn-feedback-down");r&&(r.className="feedback-btn"),n&&(n.className="feedback-btn")}function oh(t){y.selectedArtifactId=t,y.resultsViewMode="file",Ra()}function p_(){y.resultsViewMode="summary",Ra()}function f_(){const t=document.getElementById("btn-copy-results"),e=ma();navigator.clipboard.writeText(e).then(()=>{if(t){t.classList.add("copied");const s=t.querySelector("span");if(s){const r=s.textContent;s.textContent="Copied!",setTimeout(()=>{t.classList.remove("copied"),s.textContent=r},2e3)}}})}function g_(t){const e=document.getElementById("btn-feedback-up"),s=document.getElementById("btn-feedback-down");t==="up"?(e.classList.toggle("active-up"),s.classList.remove("active-down")):(s.classList.toggle("active-down"),e.classList.remove("active-up")),xa(t==="up"?"thumbsUp":"thumbsDown",y.step2Result,y.step1Result)}function m_(){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 ah(){const t=document.getElementById("error-input-panel");t&&(t.classList.add("hidden"),t.style.display="none")}window.copyResultsCode=f_;window.selectArtifact=oh;window.selectResultsSummary=p_;window.submitResultsFeedback=g_;window.showErrorInputPanel=m_;window.hideErrorInputPanel=ah; diff --git a/dist/index.html b/dist/index.html index 8c2cb06..b8d9443 100644 --- a/dist/index.html +++ b/dist/index.html @@ -2420,7 +2420,7 @@ .pm-cards { padding: 0 16px; } } - +
    diff --git a/src/customCodeVerification.js b/src/customCodeVerification.js index beaaacf..5fc19a3 100644 --- a/src/customCodeVerification.js +++ b/src/customCodeVerification.js @@ -159,6 +159,18 @@ function skipReason(className, unresolvableImports, missingPackages) { return `${className} imports ${missingPackages.join(", ")}, which your project's pubspec.yaml does not declare with a version constraint, so it could not be compiled before the deploy.`; } +/** + * The reason a class is skipped over a package it never names itself. + * + * @param {string} className - The class being skipped + * @param {string[]} unrepresentablePackages - Packages the project declares + * from sources the manifest cannot express + * @returns {string} User-facing reason naming both + */ +function transitiveSkipReason(className, unrepresentablePackages) { + return `${className} was not compiled before deploying: your project declares ${unrepresentablePackages.join(", ")} from a source that cannot be reproduced outside it, and whether the packages ${className} imports depend on one of them transitively cannot be checked before the deploy, so package resolution could not be matched exactly.`; +} + /** * Plans the compile check that runs before custom classes are pushed. * @@ -168,18 +180,25 @@ function skipReason(className, unresolvableImports, missingPackages) { * FlutterFlow. Classes that depend on the generated app are reported in * `skipped` so the deploy can say plainly what it did not verify. * - * A dependency that cannot be reproduced outside the project - a `git:` or - * `path:` source - stops only a class that imports it. For that class the - * scratch package would resolve different code from the project, and a check - * against the wrong versions reports a result that does not describe what - * ships, so it is left out of `sources` and named in `skipped`. A class that - * does not import it resolves everything it uses to the same versions the - * project will, so it is verified normally. + * A dependency that cannot be reproduced outside the project - a `git:`, + * `path:`, or custom-`hosted:` source - stops any class whose compilation + * shares a package graph with it. Importing it directly is the clear case and + * names itself in `skipped`. But a class that imports only representable + * packages can still be affected: pub resolution is one shared graph, so a + * representable import may depend on the unrepresentable package transitively, + * and whether it does is knowable only by resolving the graph, which cannot + * happen here. The scratch manifest omits the package, so `pub get` resolves + * that transitive slot differently there and the check could report a result + * that does not describe what ships. When the project declares any + * unrepresentable source, every class that imports a `package:` URI is + * therefore skipped and named with that reason; a class compiled from + * `dart:` alone does not touch package resolution and verifies normally. * - * That scoping is the point. Deciding it once for the whole project meant a - * single `git:` entry - or a package the SDK supplied but a hand-kept name list - * had not heard of - left every class in the deploy uncompiled, including the - * ones that never touched it. + * A project with no unrepresentable sources verifies exactly as before, and + * the class that directly imports such a package is still told so plainly. + * The earlier scoping - skipping only the classes that directly imported it - + * kept classes compiling that shared a graph with a package they never named, + * which was not a check on what ships. * * @param {Array<{className: string, content: string}>} classes - Classes to deploy * @param {string} projectPubspecYaml - The project's merged pubspec.yaml @@ -204,9 +223,8 @@ export function planCustomCodeVerification(classes, projectPubspecYaml) { const importedPackages = extractPackageImports(content); - // Scoped to this class's own imports. A dependency the project declares - // from a source the manifest cannot express is only a problem for a class - // that actually imports it. + // A direct import of a dependency the manifest cannot express is this + // class's own problem, and the reason names it as such. const unresolvablePackages = importedPackages.filter((name) => unrepresentable.includes(name), ); @@ -232,6 +250,25 @@ export function planCustomCodeVerification(classes, projectPubspecYaml) { continue; } + // The transitive hole: pub resolves one shared graph, so even a class + // whose every import is representable may reach a package the manifest + // omits through the dependencies of what it does import. Reachability is + // knowable only by resolving the graph, so while the project declares + // any unrepresentable source the class is skipped rather than compiled + // against a graph that differs from the project's. A class importing + // nothing from `package:` never touches pub resolution and compiles + // against exactly what the project will. + if ( + unrepresentable.length > 0 && + extractImportUris(content).some((uri) => uri.startsWith("package:")) + ) { + skipped.push({ + className, + reason: transitiveSkipReason(className, unrepresentable), + }); + continue; + } + sources.push({ fileName: `${identifierToFlutterFlowFileStem(className)}.dart`, content, diff --git a/src/customCodeVerification.test.js b/src/customCodeVerification.test.js index 8fb4789..4179e57 100644 --- a/src/customCodeVerification.test.js +++ b/src/customCodeVerification.test.js @@ -145,24 +145,22 @@ dependencies: assert.equal("hosted_thing" in manifest.dependencies, false); }); -test("a git dependency does not stop a class that never imports it", () => { +test("a git dependency stops even a class that never imports it, because resolution is shared", () => { const plan = planCustomCodeVerification( [{ className: "BackgroundDownloaderService", content: SELF_CONTAINED }], PROJECT_PUBSPEC, ); - // The project declares `private_thing` from git, which cannot be reproduced - // outside it - but this class does not import it, so the scratch package - // resolves everything it does use to the versions the project will, and the - // check still describes the code that ships. Deciding this once for the whole - // project left every class uncompiled over a dependency it never touched. - assert.deepEqual(plan.sources, [ - { - fileName: "background_downloader_service.dart", - content: SELF_CONTAINED, - }, - ]); - assert.deepEqual(plan.skipped, []); + // The project declares `private_thing` from git, which the scratch manifest + // cannot express. `background_downloader` may depend on it transitively - + // knowable only by resolving the graph - so compiling this class elsewhere + // could report a result that does not describe what ships. The skip says + // that instead of silently compiling against a differently-resolved graph. + assert.deepEqual(plan.sources, []); + assert.equal(plan.skipped.length, 1); + assert.equal(plan.skipped[0].className, "BackgroundDownloaderService"); + assert.match(plan.skipped[0].reason, /private_thing/); + assert.match(plan.skipped[0].reason, /BackgroundDownloaderService/); }); test("a class that imports the unreproducible dependency is skipped, and named as the reason", () => { @@ -179,15 +177,72 @@ class UsesPrivateThing {} PROJECT_PUBSPEC, ); - assert.deepEqual( - plan.sources.map((entry) => entry.fileName), - ["background_downloader_service.dart"], - ); - assert.equal(plan.skipped.length, 1); + // The direct import keeps its own reason: it names this class's own import, + // so it says what to do about this class. + assert.deepEqual(plan.sources, []); + assert.equal(plan.skipped.length, 2); assert.equal(plan.skipped[0].className, "UsesPrivateThing"); - // The reason names this class's own import, not the project's whole - // dependency set, so it says what to do about this class. assert.match(plan.skipped[0].reason, /it imports private_thing/); + // The sibling never imports it, but the shared graph still cannot be + // reproduced, so it is skipped with the transitive reason rather than + // compiled against a graph that differs from the project's. + assert.equal(plan.skipped[1].className, "BackgroundDownloaderService"); + assert.match(plan.skipped[1].reason, /private_thing/); +}); + +test("a representable import is skipped when an override elsewhere is unrepresentable", () => { + const pubspec = `name: my_app + +environment: + sdk: '>=3.0.0 <4.0.0' + +dependencies: + flutter: + sdk: flutter + background_downloader: ^8.5.0 + +dependency_overrides: + intl: + git: + url: https://example.invalid/intl-fork.git +`; + + const plan = planCustomCodeVerification( + [{ className: "BackgroundDownloaderService", content: SELF_CONTAINED }], + pubspec, + ); + + // The class imports `background_downloader`, which the manifest can express, + // and never touches `intl` - but the git override of `intl` cannot be + // carried, and whether `background_downloader` depends on `intl` + // transitively is knowable only by resolving the graph. The conservative + // skip names the package and the class truthfully. + assert.deepEqual(plan.sources, []); + assert.equal(plan.skipped.length, 1); + assert.equal(plan.skipped[0].className, "BackgroundDownloaderService"); + assert.match(plan.skipped[0].reason, /intl/); + assert.match(plan.skipped[0].reason, /BackgroundDownloaderService/); +}); + +test("a class compiled from dart: alone still verifies beside a git dependency", () => { + const plan = planCustomCodeVerification( + [ + { + className: "PureDartService", + content: "import 'dart:convert';\nclass PureDartService {}", + }, + ], + PROJECT_PUBSPEC, + ); + + // `dart:` libraries come from the SDK rather than pub resolution, so a class + // importing nothing from `package:` compiles against exactly what the + // project will, whatever the project's sources are. + assert.deepEqual( + plan.sources.map((source) => source.fileName), + ["pure_dart_service.dart"], + ); + assert.deepEqual(plan.skipped, []); }); test("an SDK package no list has heard of is reproduced from its pubspec source", () => { From b7057dd9a63d0f5ff1cfa9fbdaee7b59a90907d6 Mon Sep 17 00:00:00 2001 From: Stuart Date: Tue, 22 Sep 2026 17:21:39 +1000 Subject: [PATCH 07/13] fix(ci): scan the bundle for every provider endpoint and credential shape (cherry picked from commit ff9bfacbdba3fa536689eb90890ab2703309198e) --- scripts/scan_bundle_for_leaks.py | 50 +++++++++++++++++++++++++++++--- 1 file changed, 46 insertions(+), 4 deletions(-) diff --git a/scripts/scan_bundle_for_leaks.py b/scripts/scan_bundle_for_leaks.py index 700615b..1e29a4a 100755 --- a/scripts/scan_bundle_for_leaks.py +++ b/scripts/scan_bundle_for_leaks.py @@ -4,11 +4,52 @@ import sys DIST_DIR = "dist" -PATTERNS = { - "api.groq.com endpoint": re.compile(r"api\.groq\.com"), - "apiKey assignment": re.compile(r"apiKey\s*[:=]\s*['\"][^'\"]+['\"]", re.IGNORECASE), + +# The PHP proxies under dist/api/ exist to forward same-origin browser calls +# to the provider endpoints, so naming an endpoint there is the architecture, +# not a leak. Everywhere else in the bundle a provider endpoint means client +# code is calling the provider directly - the credential exposure those +# proxies exist to prevent - so the endpoint patterns skip only that +# directory. +PROXY_DIR = os.path.join(DIST_DIR, "api") + +# Every provider the app supports. The shipped client must reach all of them +# through the same-origin proxies, never by naming the provider's host. +ENDPOINT_PATTERNS = { + "Groq endpoint": re.compile(r"api\.groq\.com"), + "Google Gemini endpoint": re.compile(r"generativelanguage\.googleapis\.com"), + "Anthropic endpoint": re.compile(r"api\.anthropic\.com"), + "OpenAI endpoint": re.compile(r"api\.openai\.com"), + "OpenRouter endpoint": re.compile(r"openrouter\.ai"), } +# Credential literals, matched by shape rather than by the property they are +# assigned to, so provider-specific or minified identifiers cannot hide them. +# The sk- prefix is anchored so ordinary kebab-case text ("task-...") does not +# match; a real key is a leak anywhere in dist/, the proxies included. +CREDENTIAL_PATTERNS = { + "apiKey assignment": re.compile( + r"apiKey\s*[:=]\s*['\"][^'\"]+['\"]", re.IGNORECASE + ), + "OpenAI API key": re.compile(r"(? int: if not os.path.isdir(DIST_DIR): print(f"{DIST_DIR}/ directory not found; skipping scan.") @@ -26,7 +67,7 @@ def main() -> int: except OSError as e: print(f"WARN: could not read {path}: {e}", file=sys.stderr) continue - for label, pattern in PATTERNS.items(): + for label, pattern in patterns_for(path).items(): for match in pattern.finditer(content): snippet = content[max(0, match.start()-20):match.end()+20].replace("\n", " ") leaks.append((path, label, snippet)) @@ -40,5 +81,6 @@ def main() -> int: print("No API key/endpoint leaks found.") return 0 + if __name__ == "__main__": sys.exit(main()) From 585c580261b75d79493845c39a08212e36802517 Mon Sep 17 00:00:00 2001 From: Stuart Date: Tue, 22 Sep 2026 17:21:48 +1000 Subject: [PATCH 08/13] ci: pin workflow actions to commit SHAs and minimize token permissions (cherry picked from commit 1ed78b6ffc6b43531593526d44dd3179f7ee1442) --- .github/workflows/ci.yml | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 2004d4d..5e5e11f 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -5,22 +5,26 @@ on: branches: [main] pull_request: +# The workflow only checks out code and runs tests; it never needs write access. +permissions: + contents: read + jobs: ci: runs-on: ubuntu-latest steps: - name: Checkout - uses: actions/checkout@v4 + uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 - name: Set up Node.js - uses: actions/setup-node@v4 + uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4 with: node-version-file: '.nvmrc' cache: 'npm' - name: Set up PHP - uses: shivammathur/setup-php@v2 + uses: shivammathur/setup-php@f3e473d116dcccaddc5834248c87452386958240 # v2 with: php-version: '8.3' From b839f1f9d37bce5f1245f287fa091d75499280bc Mon Sep 17 00:00:00 2001 From: Stuart Date: Tue, 22 Sep 2026 17:22:08 +1000 Subject: [PATCH 09/13] test: derive the deploy guard's expected absent bundles from the built HTML (cherry picked from commit ece12373880e744669bda50a9bad4aa1fc6c1893) --- scripts/test-deploy-guard.py | 34 +++++++++++++++++++++++++++------- 1 file changed, 27 insertions(+), 7 deletions(-) diff --git a/scripts/test-deploy-guard.py b/scripts/test-deploy-guard.py index 495e3b8..6fb0cf8 100644 --- a/scripts/test-deploy-guard.py +++ b/scripts/test-deploy-guard.py @@ -25,9 +25,33 @@ def load_deploy_module(): return module +def expected_absent_bundles(deploy, html): + """The absent bundle paths the guard must report for this document. + + Every assets/index-* reference in the HTML, rewritten to a hash nobody + built, in the order missing_referenced_assets returns them. Derived from + the document itself so the case holds however many bundles the build + emits - the redesign adds a CSS bundle beside the JS one, and hard-coding + a single expected file is exactly what broke the test on those branches. + """ + rewritten = set() + for pattern in (deploy.ASSET_REFERENCE, deploy.CSS_URL_REFERENCE): + for match in pattern.finditer(html): + ref = match.group("path").strip() + if ref.startswith(("#", "//")) or deploy.URI_SCHEME.match(ref): + continue + rel = ref.split("?", 1)[0].split("#", 1)[0].lstrip("/") + if rel.startswith("assets/index-"): + rewritten.add( + rel.replace("assets/index-", "assets/index-absent-", 1) + ) + return sorted(rewritten) + + def main(): deploy = load_deploy_module() built_html = (deploy.DIST / "index.html").read_text(encoding="utf-8") + absent_html = built_html.replace("assets/index-", "assets/index-absent-") cases = [ ( @@ -37,8 +61,8 @@ def main(): ), ( "a bundle hash with no built file is caught", - built_html.replace("assets/index-", "assets/index-absent-"), - None, # asserted below - the real hash is not known here + absent_html, + expected_absent_bundles(deploy, built_html), ), ( "external, protocol-relative, data and anchor refs are ignored", @@ -96,11 +120,7 @@ def main(): for name, document, expected in cases: document = document.replace("PLACEHOLDER", real_bundle) actual = deploy.missing_referenced_assets(document) - - if expected is None: - ok = len(actual) == 1 and actual[0].startswith("assets/index-absent-") - else: - ok = actual == expected + ok = actual == expected print(f"{'PASS' if ok else 'FAIL'} {name}") if not ok: From 8f462d5a1ff633cd588c486c912aad7ace8d3549 Mon Sep 17 00:00:00 2001 From: Stuart Date: Tue, 22 Sep 2026 17:39:07 +1000 Subject: [PATCH 10/13] fix(auth): derive the magic-link guard contract from the shared fixture Greptile: the provider domains and response codes were hardcoded in src/authMagicLink.js while the tests used literals instead of reading authMagicLinkFixtures.json, so a backend fixture update could leave the frontend stale while every frontend test still passed. - src/authMagicLink.js now takes domains, codes and the rejection message template from authMagicLinkFixtures.json (JSON import attribute works in both the node --test run and the Vite bundle). - app.js compares the server's validation code against the exported PLUS_ALIAS_REJECTED_CODE instead of a local literal, so the button and input handling cannot drift from the fixture either. - src/authMagicLink.test.js feeds every allowlisted domain and response code from the same fixture, verifying the wiring against the contract instead of restating it. dist/ rebuilt. --- app.js | 7 +- dist/assets/index-BnJVlbD-.js | 320 ---------------------------------- dist/assets/index-BsMV38gk.js | 320 ++++++++++++++++++++++++++++++++++ dist/index.html | 2 +- src/authMagicLink.js | 26 +-- src/authMagicLink.test.js | 53 +++--- 6 files changed, 369 insertions(+), 359 deletions(-) delete mode 100644 dist/assets/index-BnJVlbD-.js create mode 100644 dist/assets/index-BsMV38gk.js diff --git a/app.js b/app.js index 4f99ce4..b84ac88 100644 --- a/app.js +++ b/app.js @@ -36,6 +36,7 @@ import { explainPlusAliasRule, getMagicLinkResultMessage, isKnownProviderPlusAlias, + PLUS_ALIAS_REJECTED_CODE, trimEmail, } from "./src/authMagicLink.js"; import { planCustomCodeVerification } from "./src/customCodeVerification.js"; @@ -4296,10 +4297,10 @@ async function handleMagicLinkRequest() { try { const data = await sendMagicLink(email) - if (input && data?.code !== 'PLUS_ALIAS_REJECTED') input.value = '' + if (input && data?.code !== PLUS_ALIAS_REJECTED_CODE) input.value = '' if (msg) msg.textContent = getMagicLinkResultMessage(data, email) - if (btn) btn.textContent = data?.code === 'PLUS_ALIAS_REJECTED' ? 'Send Link' : 'Sent!' - if (btn && data?.code === 'PLUS_ALIAS_REJECTED') btn.disabled = false + if (btn) btn.textContent = data?.code === PLUS_ALIAS_REJECTED_CODE ? 'Send Link' : 'Sent!' + if (btn && data?.code === PLUS_ALIAS_REJECTED_CODE) btn.disabled = false } catch (err) { console.error('handleMagicLinkRequest: sendMagicLink failed', { email, err }) if (msg) msg.textContent = 'Something went wrong. Please try again.' diff --git a/dist/assets/index-BnJVlbD-.js b/dist/assets/index-BnJVlbD-.js deleted file mode 100644 index 169da47..0000000 --- a/dist/assets/index-BnJVlbD-.js +++ /dev/null @@ -1,320 +0,0 @@ -(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const n of document.querySelectorAll('link[rel="modulepreload"]'))r(n);new MutationObserver(n=>{for(const i of n)if(i.type==="childList")for(const o of i.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&r(o)}).observe(document,{childList:!0,subtree:!0});function s(n){const i={};return n.integrity&&(i.integrity=n.integrity),n.referrerPolicy&&(i.referrerPolicy=n.referrerPolicy),n.crossOrigin==="use-credentials"?i.credentials="include":n.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function r(n){if(n.ep)return;n.ep=!0;const i=s(n);fetch(n.href,i)}})();var v=typeof window<"u"?window:void 0,we=typeof globalThis<"u"?globalThis:v,ke=we?.navigator,C=we?.document,re=we?.location,Mo=we?.fetch,$i=we!=null&&we.XMLHttpRequest&&"withCredentials"in new we.XMLHttpRequest?we.XMLHttpRequest:void 0,Ma=we?.AbortController,lh=we?.CompressionStream,Pe=ke?.userAgent;function kc(){return!(!v||v.navigator.onLine===!1)}var Cs=typeof globalThis<"u"?globalThis:v;Cs&&typeof self>"u"&&(Cs.self=Cs),Cs&&typeof File>"u"&&(Cs.File=function(){});var $=v??{},Y={DEBUG:!1,LIB_VERSION:"0.5.0",LIB_NAME:"browser-common"};function La(t,e,s,r,n,i,o){try{var a=t[i](o),l=a.value}catch(u){return void s(u)}a.done?e(l):Promise.resolve(l).then(r,n)}function X(t){return function(){var e=this,s=arguments;return new Promise((function(r,n){var i=t.apply(e,s);function o(l){La(i,r,n,o,a,"next",l)}function a(l){La(i,r,n,o,a,"throw",l)}o(void 0)}))}}function b(){return b=Object.assign?Object.assign.bind():function(t){for(var e=1;arguments.length>e;e++){var s=arguments[e];for(var r in s)({}).hasOwnProperty.call(s,r)&&(t[r]=s[r])}return t},b.apply(null,arguments)}function Ic(t,e){if(t==null)return{};var s={};for(var r in t)if({}.hasOwnProperty.call(t,r)){if(e.indexOf(r)!==-1)continue;s[r]=t[r]}return s}var Oa=t=>{if(typeof t!="string")return t;try{return JSON.parse(t)}catch{return t}};function Da(t){return typeof t=="string"||t}function Ba(t){return typeof t=="string"?t:void 0}var Fs,ch=["$feature_flag","$feature_flag_response","$feature_flag_has_experiment","$feature_flag_id","$feature_flag_version","$feature_flag_reason","$feature_flag_request_id","$feature_flag_evaluated_at","$feature_flag_error","locally_evaluated","$groups","$process_person_profile","$geoip_disable","$current_url","$pathname","$referring_domain","utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid","gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","irclid","_kx","$session_id","$window_id","$lib","$lib_version","$device_id","$is_server"],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})({}),ja=(function(t){return t.GZipJS="gzip-js",t.Base64="base64",t})({}),uh=["$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"],dh=["token"],Cc="NativeGzipValidationError",Ri=t=>t.length>=2&&t[0]===31&&t[1]===139,Ua=(t,e)=>t===ja.GZipJS||e===ja.GZipJS||e==="gzip",Ha=t=>!(!t||typeof t!="object")&&("name"in t?String(t.name):"")==="NotReadableError",yr=t=>{var e=new Error("Native gzip produced invalid output: "+t);throw e.name=Cc,e},hh=(function(){var t=X((function*(e,s){18>e.size&&yr("too-short");var r=new Uint8Array(yield e.slice(0,10).arrayBuffer());Ri(r)&&r[2]===8||yr("invalid-header");var n=new DataView(yield e.slice(e.size-8).arrayBuffer());n.getUint32(0,!0)!==(o=>{for(var a=(()=>{if(Fs)return Fs;Fs=[];for(var c=0;256>c;c++){for(var d=c,h=0;8>h;h++)d=1&d?3988292384^d>>>1:d>>>1;Fs[c]=d>>>0}return Fs})(),l=4294967295,u=0;o.length>u;u++)l=a[255&(l^o[u])]^l>>>8;return(4294967295^l)>>>0})(s)&&yr("invalid-crc");var i=s.length>>>0;n.getUint32(4,!0)!==i&&yr("invalid-size")}));return function(e,s){return t.apply(this,arguments)}})();function Ti(){return Ti=X((function*(t,e,s){e===void 0&&(e=!0);try{var r=new TextEncoder().encode(t),n=new globalThis.CompressionStream("gzip"),i=n.writable.getWriter(),o=i.write(r).then((()=>i.close())).catch((function(){var u=X((function*(c){try{yield i.abort(c)}catch{}throw c}));return function(c){return u.apply(this,arguments)}})()),a=new Response(n.readable).blob(),l=(yield Promise.all([a,o]))[0];return yield hh(l,r),l}catch(u){if(s!=null&&s.rethrow)throw u;return e&&console.error("Failed to gzip compress data",u),null}})),Ti.apply(this,arguments)}var ph=["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"],Wa=function(t,e){if(e===void 0&&(e=[]),!t)return!1;var s=t.toLowerCase();return ph.concat(e).some((r=>{var n=r.toLowerCase();return s.indexOf(n)!==-1}))};function M(t,e){return t.indexOf(e)!==-1}var Pn=function(t){return t.trim()},Ni=function(t){return t.replace(/^\$/,"")};function Fc(t){var e,s=[];return(e=JSON.stringify(t,(function(r,n){if(typeof n=="bigint")return n.toString();if(typeof n!="function"&&typeof n!="symbol"){if(n instanceof Error)return{name:n.name,message:n.message,stack:n.stack};if(n&&typeof n=="object"){for(;s.length>0&&s[s.length-1]!==this;)s.pop();if(s.includes(n))return"[Circular]";s.push(n)}return n}})))!==null&&e!==void 0?e:"null"}var Pc=Object.prototype,Ac=Pc.hasOwnProperty,An=Pc.toString,L=Array.isArray||function(t){return An.call(t)==="[object Array]"},Se=t=>typeof t=="function",te=t=>t===Object(t)&&!L(t),mt=t=>{if(te(t)){for(var e in t)if(Ac.call(t,e))return!1;return!0}return!1},x=t=>t===void 0,W=t=>An.call(t)=="[object String]",Mi=t=>W(t)&&t.trim().length===0,$e=t=>t===null,D=t=>x(t)||$e(t),he=t=>An.call(t)=="[object Number]"&&t==t,lt=t=>he(t)&&t>0,Ke=t=>An.call(t)==="[object Boolean]",fh=t=>t instanceof FormData,gh=t=>M(uh,t),mh=t=>M(dh,t);function $c(t){return t===null||typeof t!="object"}function qr(t,e){return{}.toString.call(t)==="[object "+e+"]"}function Lo(t){return typeof Event<"u"&&Rc(t,Event)}function Rc(t,e){try{return t instanceof e}catch{return!1}}var vh=[!0,"true",1,"1","yes"],Zn=t=>M(vh,t),_h=[!1,"false",0,"0","no"];function rt(t,e,s,r,n){return e>s&&(r.warn("min cannot be greater than max."),e=s),he(t)?t>s?(r.warn(" cannot be greater than max: "+s+". Using max value instead."),s):e>t?(r.warn(" cannot be less than min: "+e+". Using min value instead."),e):t:(r.warn(" must be a number. using max or fallback. max: "+s+", fallback: "+n),rt(n||s,e,s,r))}class yh{constructor(e){this.tt={},this.et=e.et,this.it=rt(e.bucketSize,0,100,e.rt),this.nt=rt(e.refillRate,0,this.it,e.rt),this.st=rt(e.refillInterval,0,864e5,e.rt)}ot(e,s){var r=Math.floor((s-e.lastAccess)/this.st);r>0&&(e.tokens=Math.min(e.tokens+r*this.nt,this.it),e.lastAccess=e.lastAccess+r*this.st)}consumeRateLimit(e){var s,r=Date.now(),n=String(e),i=this.tt[n];return i?this.ot(i,r):this.tt[n]=i={tokens:this.it,lastAccess:r},i.tokens===0||(i.tokens--,i.tokens===0&&((s=this.et)==null||s.call(this,e)),i.tokens===0)}stop(){this.tt={}}}var Oe="Mobile",Vr="iOS",vt="Android",ps="Tablet",Tc=vt+" "+ps,Nc="iPad",Mc="Apple",Lc=Mc+" Watch",qs="Safari",fs="BlackBerry",Oc="Samsung",Dc=Oc+"Browser",Bc=Oc+" Internet",Vt="Chrome",wh=Vt+" OS",jc=Vt+" "+Vr,Oo="Internet Explorer",Uc=Oo+" "+Oe,Do="Opera",bh=Do+" Mini",Bo="Edge",Hc="Microsoft "+Bo,us="Firefox",Wc=us+" "+Vr,er="Nintendo",tr="PlayStation",ds="Xbox",zc=vt+" "+Oe,qc=Oe+" "+qs,Ds="Windows",Li=Ds+" Phone",za="Nokia",Oi="Ouya",Vc="Generic",Eh=Vc+" "+Oe.toLowerCase(),Gc=Vc+" "+ps.toLowerCase(),Di="Konqueror",Kc="Oculus Browser",Gr="Vivaldi",Jc="Yandex",Kr="Whale",Bi="DuckDuckGo",Yc="Pale Moon",Jr="Waterfox",Vs="Brave",Zc="Google Search App",le="(\\d+(\\.\\d+)?)",Xn=new RegExp("Version/"+le),Sh=new RegExp(ds,"i"),xh=new RegExp(tr+" \\w+","i"),kh=new RegExp(er+" \\w+","i"),jo=new RegExp(fs+"|PlayBook|BB10","i"),Ih={"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"},Xc=function(t,e,s,r){e=e||"";var n=(function(i){return i!=null&&i.brave?Vs:null})(s);return n||(r!=null&&r.detectGoogleSearchApp&&M(t,"GSA/")?Zc:M(t," OPR/")&&M(t,"Mini")?bh:M(t," OPR/")?Do:jo.test(t)?fs:M(t,"IE"+Oe)||M(t,"WPDesktop")?Uc:M(t,"OculusBrowser")?Kc:M(t,Dc)?Bc:M(t,Bo)||M(t,"Edg/")?Hc:M(t,Gr+"/")?Gr:M(t,"YaBrowser/")?Jc:M(t,Kr+"/")?Kr:M(t,Bi+"/")||M(t,"Ddg/")?Bi:M(t,"FBIOS")?"Facebook "+Oe:M(t,"UCWEB")||M(t,"UCBrowser")?"UC Browser":M(t,"CriOS")?jc:M(t,"CrMo")||M(t,Vt)?Vt:M(t,vt)&&M(t,qs)?zc:M(t,"FxiOS")?Wc:M(t.toLowerCase(),Di.toLowerCase())?Di:M(t,Vs+"/")?Vs:((i,o)=>o&&M(o,Mc)||(function(a){return M(a,qs)&&!M(a,Vt)&&!M(a,vt)})(i))(t,e)?M(t,Oe)?qc:qs:M(t,"PaleMoon/")?Yc:M(t,Jr+"/")?Jr:M(t,us)?us:M(t,"MSIE")||M(t,"Trident/")?Oo:M(t,"Gecko")?us:"")},Ch={[Uc]:[new RegExp("rv:"+le)],[Hc]:[new RegExp(Bo+"?\\/"+le)],[Vt]:[new RegExp("("+Vt+"|CrMo)\\/"+le)],[jc]:[new RegExp("CriOS\\/"+le)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+le)],[qs]:[Xn],[qc]:[Xn],[Do]:[new RegExp("(Opera|OPR)\\/"+le)],[us]:[new RegExp(us+"\\/"+le)],[Wc]:[new RegExp("FxiOS\\/"+le)],[Di]:[new RegExp("Konqueror[:/]?"+le,"i")],[fs]:[new RegExp(fs+" "+le),Xn],[zc]:[new RegExp("android\\s"+le,"i")],[Bc]:[new RegExp(Dc+"\\/"+le)],[Kc]:[new RegExp("OculusBrowser\\/"+le)],[Gr]:[new RegExp(Gr+"\\/"+le)],[Jc]:[new RegExp("YaBrowser\\/"+le)],[Kr]:[new RegExp(Kr+"\\/"+le)],[Vs]:[new RegExp(Vs+"\\/"+le)],[Bi]:[new RegExp("(DuckDuckGo|Ddg)\\/"+le)],[Yc]:[new RegExp("PaleMoon\\/"+le)],[Jr]:[new RegExp(Jr+"\\/"+le)],[Zc]:[new RegExp("GSA\\/"+le)],[Oo]:[new RegExp("(rv:|MSIE )"+le)],Mozilla:[new RegExp("rv:"+le)]},Fh=function(t,e,s,r){var n=Xc(t,e,s,r),i=Ch[n];if(x(i))return null;for(var o=0;i.length>o;o++){var a=t.match(i[o]);if(a)return parseFloat(a[a.length-2])}return null},qa=[[new RegExp(ds+"; "+ds+" (.*?)[);]","i"),t=>[ds,t&&t[1]||""]],[new RegExp(er,"i"),[er,""]],[new RegExp(tr,"i"),[tr,""]],[jo,[fs,""]],[new RegExp(Ds,"i"),(t,e)=>{if(/Phone/.test(e)||/WPDesktop/.test(e))return[Li,""];if(new RegExp(Oe).test(e)&&!/IEMobile\b/.test(e))return[Ds+" "+Oe,""];var s=/Windows NT ([0-9.]+)/i.exec(e);if(s&&s[1]){var r=Ih[s[1]]||"";return/arm/i.test(e)&&(r="RT"),[Ds,r]}return[Ds,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,t=>t&&t[3]?[Vr,[t[3],t[4],t[5]||"0"].join(".")]:[Vr,""]],[/(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i,t=>{var e="";return t&&t.length>=3&&(e=x(t[2])?t[3]:t[2]),["watchOS",e]}],[new RegExp("("+vt+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+vt+")","i"),t=>t&&t[2]?[vt,[t[2],t[3],t[4]||"0"].join(".")]:[vt,""]],[/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/,[wh,""]],[/Linux|debian/i,["Linux",""]]],Va=function(t){return kh.test(t)?er:xh.test(t)?tr:Sh.test(t)?ds:new RegExp(Oi,"i").test(t)?Oi:new RegExp("("+Li+"|WPDesktop)","i").test(t)?Li:/iPad/.test(t)?Nc:/iPod/.test(t)?"iPod Touch":/iPhone/.test(t)?"iPhone":/(watch)(?: ?os[,/]|\d,\d\/)[\d.]+/i.test(t)?Lc:jo.test(t)?fs:/(kobo)\s(ereader|touch)/i.test(t)?"Kobo":new RegExp(za,"i").test(t)?za:/(kf[a-z]{2}wi|aeo[c-r]{2})( bui|\))/i.test(t)||/(kf[a-z]+)( bui|\)).+silk\//i.test(t)?"Kindle Fire":/(Android|ZTE)/i.test(t)?new RegExp(Oe).test(t)&&!/(9138B|TB782B|Nexus [97]|pixel c|HUAWEISHT|BTV|noble nook|smart ultra 6)/i.test(t)||/pixel[\daxl ]{1,6}/i.test(t)&&!/pixel c/i.test(t)||/(huaweimed-al00|tah-|APA|SM-G92|i980|zte|U304AA)/i.test(t)||/lmy47v/i.test(t)&&!/QTAQZ3/i.test(t)?vt:Tc:new RegExp("(pda|"+Oe+")","i").test(t)?Eh:new RegExp(ps,"i").test(t)&&!new RegExp(ps+" pc","i").test(t)?Gc:""},Ph=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Ga(t,e){return typeof(s=t)=="string"&&Ph.test(s)?t:e();var s}function Ct(t){return t&&t.split("#")[0]}function Uo(t,e){var s=setTimeout(t,e);return s?.unref&&s?.unref(),s}function Ka(t,e,s){return Qc.apply(this,arguments)}function Qc(){return(Qc=X((function*(t,e,s){var r;try{return yield Promise.race([t,new Promise(((n,i)=>{r=Uo((()=>{try{s?.(),n()}catch(o){i(o)}}),e)}))])}finally{clearTimeout(r)}}))).apply(this,arguments)}var Ah=t=>t instanceof Error,eu={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}},$h=eu.info;function tu(t){if(Ke(t))return{boolValue:t};if(typeof t=="number")return Number.isFinite(t)?Number.isInteger(t)?{intValue:t}:{doubleValue:t}:{stringValue:String(t)};if(typeof t=="string")return{stringValue:t};if(L(t))return{arrayValue:{values:t.map((e=>tu(e)))}};try{return{stringValue:JSON.stringify(t)}}catch{return{stringValue:String(t)}}}function Yr(t){var e=[];for(var s in t){var r=t[s];$e(r)||x(r)||e.push({key:s,value:tu(r)})}return e}function Rh(t,e){var s=eu[t.level||"info"]||$h,r=s.text,n=s.number,i=String(Date.now())+"000000",o={};e.distinctId&&(o.posthogDistinctId=e.distinctId),e.sessionId&&(o.sessionId=e.sessionId),e.windowId&&(o["window.id"]=e.windowId),D(e.sessionStartTimestamp)||(o.sessionStartTimestamp=String(e.sessionStartTimestamp)),D(e.lastActivityTimestamp)||(o.lastActivityTimestamp=String(e.lastActivityTimestamp)),e.currentUrl&&(o["url.full"]=e.currentUrl),e.screenName&&(o["screen.name"]=e.screenName),e.appState&&(o["app.state"]=e.appState),e.activeFeatureFlags&&e.activeFeatureFlags.length>0&&(o.feature_flags=e.activeFeatureFlags);var a=b({},o,t.attributes||{}),l={timeUnixNano:i,observedTimeUnixNano:i,severityNumber:n,severityText:r,body:{stringValue:t.body},attributes:Yr(a)};return t.trace_id&&(l.traceId=t.trace_id),t.span_id&&(l.spanId=t.span_id),x(t.trace_flags)||(l.flags=t.trace_flags),l}function su(t,e,s){return b({},t.resourceAttributes,{"service.name":t.serviceName||"unknown_service"},t.environment&&{"deployment.environment":t.environment},t.serviceVersion&&{"service.version":t.serviceVersion},{"telemetry.sdk.name":e,"telemetry.sdk.version":s})}function ru(t,e,s,r){return{resourceLogs:[{resource:{attributes:Yr(e)},scopeLogs:[{scope:{name:s,version:r},logRecords:t}]}]}}let Th=class{constructor(t,e,s,r,n,i,o){var a;i===void 0&&(i=()=>Promise.resolve()),this._instance=t,this.Ne=e,this.rt=s,this.ut=r,this.ht=n,this.dt=i,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 s={record:Rh(e,this.ut())};this.ht((()=>this.At(s)))}}else this.rt.info("Log was rejected in beforeSend function")}}Pt(t){var e=this.Ne.beforeSend;if(!e)return t;var s=L(e)?e:[e],r=t;for(var n of s)try{var i=n(r);if(!i)return this.rt.info("Log was rejected in beforeSend function"),null;r=i}catch(o){return this.rt.error("Error in beforeSend function for log:",o),null}return r}Rt(){if(this.Tt===void 0)return!0;var t=Date.now(),e=t-this.bt;return this.Mt>e&&e>=0||(this.bt=t,this._t=0,this.wt=!1),this.Tt>this._t?(this._t++,!0):(this.wt||(this.rt.warn("captureLog dropping logs: exceeded "+this.Tt+" logs per "+this.Mt+"ms"),this.wt=!0),!1)}flush(){var t=this;return X((function*(){if(!t._instance.isDisabled)return t.ct||(t.ct=t.Ft().finally((()=>{t.ct=null}))),t.ct}))()}Ft(){var t=this;return X((function*(){var e;t.Et();var s=(e=t._instance.getPersistedProperty(ut.LogsQueue))!==null&&e!==void 0?e:[];if(s.length!==0)for(var r=s.length,n=0;s.length>0&&r>n;){var i,o;t.ft=0;var a=Math.min(s.length,t.Ct),l=s.slice(0,a),u=ru(l.map((d=>d.record)),t.Lt(),(i=t.vt)!==null&&i!==void 0?i: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),s=(o=t._instance.getPersistedProperty(ut.LogsQueue))!==null&&o!==void 0?o:[],n+=l.length,c.kind==="fatal"))throw c.error}}))()}Dt(t){var e=this;return X((function*(){var s,r=Math.max(0,t-e.ft),n=(s=e._instance.getPersistedProperty(ut.LogsQueue))!==null&&s!==void 0?s:[];e._instance.setPersistedProperty(ut.LogsQueue,n.slice(r)),yield e.dt()}))()}Lt(){return su(this.Ne,this._instance.getLibraryId(),this._instance.getLibraryVersion())}At(t){var e;if(!this._instance.optedOut){var s=(e=this._instance.getPersistedProperty(ut.LogsQueue))!==null&&e!==void 0?e:[];this.xt>s.length||(s.shift(),this.ft++,this.rt.info("Logs queue is full, dropping oldest record.")),s.push(t),this._instance.setPersistedProperty(ut.LogsQueue,s),this.kt>s.length?this.$t():this.It()}}$t(t){t===void 0&&(t=this.St),this.Nt||(this.Nt=Uo((()=>{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 X((function*(){e.Et();var s=e.flush().catch((()=>{}));t!==void 0?yield Ka(s,t):yield s}))()}flushWithTimeout(t){var e=this;return X((function*(){var s=e.flush();yield Ka(s,t,(()=>{s.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 Qn=[0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4];function Ja(t){return String(t)+"000000"}function Ya(t,e,s,r){var n="";return r&&(n=Object.keys(r).sort().map((i=>JSON.stringify(i)+":"+JSON.stringify(r[i]))).join(",")),t+"\0"+e+"\0"+(s??"")+"\0"+n}let Nh=class{constructor(t,e,s){this._instance=t,this.Ne=e,this.rt=s,this.Bt=new Map,this.ct=null,this.Ht=!1,this.Ut=new Map,this.zt=new Set,this.Wt=0}count(t,e,s){e===void 0&&(e=1),this.Vt({name:t,type:"count",value:e,unit:s?.unit,attributes:s?.attributes})}gauge(t,e,s){this.Vt({name:t,type:"gauge",value:e,unit:s?.unit,attributes:s?.attributes})}histogram(t,e,s){this.Vt({name:t,type:"histogram",value:e,unit:s?.unit,attributes:s?.attributes})}flush(){var t=this,e=this.ct,s=(function(){var n=X((function*(){e&&(yield e.catch((()=>{}))),yield t.Zt()}));return function(){return n.apply(this,arguments)}})(),r=s().finally((()=>{this.ct===r&&(this.ct=null)}));return this.ct=r,r}drainWindow(){if(this.Bt.size===0)return null;var t=this.Bt;return this.Bt=new Map,this.Ht=!1,this.Ut=new Map,this.zt=new Set,this.Gt(t)}reset(){this.Wt++,this.Et(),this.Bt=new Map,this.ct=null,this.Ht=!1,this.Ut=new Map,this.zt=new Set}Vt(t){if(!this._instance.isDisabled&&!this._instance.optedOut){var e=this.Pt(t);if(e!==null)if(e.name&&typeof e.name=="string")if(typeof e.value=="number"&&Number.isFinite(e.value))if(e.type==="count"&&0>e.value)this.rt.warn("Dropping count '"+e.name+"': counters are monotonic, value must be >= 0");else{var s,r;try{s=e.attributes?b({},e.attributes):void 0,r=Ya(e.type,e.name,e.unit,s)}catch(o){return void this.rt.warn("Dropping metric '"+e.name+"': attributes could not be serialized",o)}var n=this.Bt.get(r);if(!n){if(!this.Qt())return;n={name:e.name,type:e.type,unit:e.unit,attributes:s,windowStartMs:Date.now()},this.Bt.set(r,n)}var i=this.Ut.get(e.name);i===void 0?this.Ut.set(e.name,e.type):i===e.type||this.zt.has(e.name)||(this.zt.add(e.name),this.rt.warn("Metric name '"+e.name+"' is already used as a "+i+"; recording it as a "+e.type+" too will blend both series in charts. Use a distinct name.")),this.Kt(n,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 s;switch(t.type){case"count":t.total=((s=t.total)!==null&&s!==void 0?s: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(Qn.length+1).fill(0)});var r=t.hist;r.count+=1,r.sum+=e,r.min=Math.min(r.min,e),r.max=Math.max(r.max,e),r.bucketCounts[(function(n,i){for(var o=0;i.length>o;o++)if(i[o]>=n)return o;return i.length})(e,Qn)]+=1}}Pt(t){var e=this.Ne.beforeSend;if(!e)return t;var s=L(e)?e:[e],r=t;for(var n of s)try{var i=n(r);if(!i)return this.rt.info("Metric was rejected in beforeSend function"),null;r=i}catch(o){return this.rt.error("Error in beforeSend function for metric:",o),null}return r}$t(){this.Nt||(this.Nt=Uo((()=>{this.Nt=void 0,this.flush().catch((t=>{this.rt.error("Metrics flush failed:",t)}))}),this.Ne.flushIntervalMs))}Et(){this.Nt&&(clearTimeout(this.Nt),this.Nt=void 0)}Zt(){var t=this;return X((function*(){if(t.Bt.size!==0){var e=t.Bt;t.Bt=new Map,t.Ht=!1,t.Ut=new Map,t.zt=new Set;var s=t.Wt,r=yield t._instance.Jt(t.Gt(e));if(s===t.Wt)switch(r.kind){case"ok":return;case"retry-later":return t.Yt(e),void t.$t();case"too-large":return void t.rt.warn("Metrics batch exceeded the server size limit and was dropped");case"fatal":return void t.rt.error("Failed to send metrics batch:",r.error)}}}))()}Gt(t){return e=this.Xt(t),s=(function(i,o,a){return b({},i.resourceAttributes,{"service.name":i.serviceName||"unknown_service"},i.environment&&{"deployment.environment":i.environment},i.serviceVersion&&{"service.version":i.serviceVersion},{"telemetry.sdk.name":o,"telemetry.sdk.version":a})})(this.Ne,this._instance.getLibraryId(),this._instance.getLibraryVersion()),r=this._instance.getLibraryId(),n=this._instance.getLibraryVersion(),{resourceMetrics:[{resource:{attributes:Yr(s)},scopeMetrics:[{scope:{name:r,version:n},metrics:e}]}]};var e,s,r,n}Xt(t){var e=Ja(Date.now()),s=new Map;for(var r of t.values()){var n,i=Ya(r.type,r.name,r.unit,void 0),o=s.get(i);o||(o=b({name:r.name},r.unit&&{unit:r.unit}),r.type==="count"?o.sum={aggregationTemporality:1,isMonotonic:!0,dataPoints:[]}:r.type==="gauge"?o.gauge={dataPoints:[]}:o.histogram={aggregationTemporality:1,dataPoints:[]},s.set(i,o));var a=Yr((n=r.attributes)!==null&&n!==void 0?n:{}),l=Ja(r.windowStartMs);if(r.type==="count"){var u,c={attributes:a,startTimeUnixNano:l,timeUnixNano:e,asDouble:(u=r.total)!==null&&u!==void 0?u:0};o.sum.dataPoints.push(c)}else if(r.type==="gauge"){var d,h={attributes:a,timeUnixNano:e,asDouble:(d=r.last)!==null&&d!==void 0?d:0};o.gauge.dataPoints.push(h)}else r.hist&&o.histogram.dataPoints.push({attributes:a,startTimeUnixNano:l,timeUnixNano:e,count:r.hist.count,sum:r.hist.sum,min:r.hist.min,max:r.hist.max,bucketCounts:r.hist.bucketCounts,explicitBounds:Qn})}return Array.from(s.values())}Yt(t){var e,s;for(var r of t){var n=r[0],i=r[1],o=this.Bt.get(n);if(o)switch(o.windowStartMs=Math.min(o.windowStartMs,i.windowStartMs),o.type){case"count":o.total=((e=o.total)!==null&&e!==void 0?e:0)+((s=i.total)!==null&&s!==void 0?s:0);break;case"gauge":break;case"histogram":if(i.hist)if(o.hist){o.hist.count+=i.hist.count,o.hist.sum+=i.hist.sum,o.hist.min=Math.min(o.hist.min,i.hist.min),o.hist.max=Math.max(o.hist.max,i.hist.max);for(var a=0;o.hist.bucketCounts.length>a;a++)o.hist.bucketCounts[a]+=i.hist.bucketCounts[a]}else o.hist=i.hist}else this.Qt()&&this.Bt.set(n,i)}}};var wr,Za,ei;function Mh(t){var e=globalThis._posthogChunkIds;if(e){var s=Object.keys(e);return ei&&s.length===Za||(Za=s.length,ei=s.reduce(((r,n)=>{wr||(wr={});var i=wr[n];if(i)r[i[0]]=i[1];else for(var o=t(n),a=o.length-1;a>=0;a--){var l=o[a],u=l?.filename,c=e[n];if(u&&c){r[u]=c,wr[n]=[u,c];break}}return r}),{})),ei}}class Lh{constructor(e,s,r){r===void 0&&(r=[]),this.coercers=e,this.stackParser=s,this.modifiers=r}buildFromUnknown(e,s){s===void 0&&(s={});var r=s&&s.mechanism||{handled:!0,type:"generic"},n=this.buildCoercingContext(r,s,0).apply(e),i=this.buildParsingContext(s),o=this.parseStacktrace(n,i);return{$exception_list:this.convertToExceptionList(o,r),$exception_level:"error"}}modifyFrames(e){var s=this;return X((function*(){for(var r of e)r.stacktrace&&r.stacktrace.frames&&L(r.stacktrace.frames)&&(r.stacktrace.frames=yield s.applyModifiers(r.stacktrace.frames));return e}))()}coerceFallback(e){var s;return{type:"Error",value:"Unknown error",stack:(s=e.syntheticException)==null?void 0:s.stack,synthetic:!0}}parseStacktrace(e,s){var r,n;return e.cause!=null&&(r=this.parseStacktrace(e.cause,s)),e.stack!=""&&e.stack!=null&&(n=this.applyChunkIds(this.stackParser(e.stack,e.synthetic?s.skipFirstLines:0),s.chunkIdMap)),b({},e,{cause:r,stack:n})}applyChunkIds(e,s){return e.map((r=>(r.filename&&s&&(r.chunk_id=s[r.filename]),r)))}applyCoercers(e,s){for(var r of this.coercers)if(r.match(e))return r.coerce(e,s);return this.coerceFallback(s)}applyModifiers(e){var s=this;return X((function*(){var r=e;for(var n of s.modifiers)r=yield n(r);return r}))()}convertToExceptionList(e,s){var r,n,i,o={type:e.type,value:e.value,mechanism:{type:(r=s.type)!==null&&r!==void 0?r:"generic",handled:(n=s.handled)===null||n===void 0||n,synthetic:(i=e.synthetic)!==null&&i!==void 0&&i}};e.stack&&(o.stacktrace={type:"raw",frames:e.stack});var a=[o];return e.cause!=null&&a.push(...this.convertToExceptionList(e.cause,b({},s,{handled:!0}))),a}buildParsingContext(e){var s;return{chunkIdMap:Mh(this.stackParser),skipFirstLines:(s=e.skipFirstLines)!==null&&s!==void 0?s:1}}buildCoercingContext(e,s,r){r===void 0&&(r=0);var n=(i,o)=>{if(4>=o){var a=this.buildCoercingContext(e,s,o);return this.applyCoercers(i,a)}};return b({},s,{syntheticException:r==0?s.syntheticException:void 0,mechanism:e,apply:i=>n(i,r),next:i=>n(i,r+1)})}}var gs="?";function ji(t,e,s,r,n){var i={platform:t,filename:e,function:s===""?gs:s,in_app:!0};return x(r)||(i.lineno=r),x(n)||(i.colno=n),i}var nu=(t,e)=>{var s=t.indexOf("safari-extension")!==-1,r=t.indexOf("safari-web-extension")!==-1;return s||r?[t.indexOf("@")!==-1?t.split("@")[0]:gs,s?"safari-extension:"+e:"safari-web-extension:"+e]:[t,e]},Oh=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,Dh=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,Bh=/\((\S*)(?::(\d+))(?::(\d+))\)/,jh=(t,e)=>{var s=Oh.exec(t);if(s)return ji(e,s[1],gs,+s[2],+s[3]);var r=Dh.exec(t);if(r){if(r[2]&&r[2].indexOf("eval")===0){var n=Bh.exec(r[2]);n&&(r[2]=n[1],r[3]=n[2],r[4]=n[3])}var i=nu(r[1]||gs,r[2]);return ji(e,i[1],i[0],r[3]?+r[3]:void 0,r[4]?+r[4]:void 0)}},Uh=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,Hh=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,Wh=(t,e)=>{var s=Uh.exec(t);if(s){if(s[3]&&s[3].indexOf(" > eval")>-1){var r=Hh.exec(s[3]);r&&(s[1]=s[1]||"eval",s[3]=r[1],s[4]=r[2],s[5]="")}var n=s[3],i=s[1]||gs,o=nu(i,n);return ji(e,n=o[1],i=o[0],s[4]?+s[4]:void 0,s[5]?+s[5]:void 0)}},Xa=/\(error: (.*)\)/;class zh{match(e){return this.isDOMException(e)||this.isDOMError(e)}coerce(e,s){var r=W(e.stack);return{type:this.getType(e),value:this.getValue(e),stack:r?e.stack:void 0,cause:e.cause?s.next(e.cause):void 0,synthetic:!1}}getType(e){return this.isDOMError(e)?"DOMError":"DOMException"}getValue(e){var s=e.name||(this.isDOMError(e)?"DOMError":"DOMException");return e.message?s+": "+e.message:s}isDOMException(e){return qr(e,"DOMException")}isDOMError(e){return qr(e,"DOMError")}}class qh{match(e){return(function(s){switch({}.toString.call(s)){case"[object Error]":case"[object Exception]":case"[object DOMException]":case"[object DOMError]":case"[object WebAssembly.Exception]":return!0;default:return Rc(s,Error)}})(e)}coerce(e,s){return{type:this.getType(e),value:this.getMessage(e,s),stack:this.getStack(e),cause:e.cause?s.next(e.cause):void 0,synthetic:!1}}getType(e){return e.name||e.constructor.name}getMessage(e,s){var r=e.message;return String(r.error&&typeof r.error.message=="string"?r.error.message:r)}getStack(e){return e.stacktrace||e.stack||void 0}}class Vh{constructor(){}match(e){return!!qr(e,"ErrorEvent")&&(e.error!=null||this.fe(e))}coerce(e,s){var r;if(e.error!=null)return s.apply(e.error);var n=s.apply(e.message);return b({},n,{stack:(r=this.pe(e))!==null&&r!==void 0?r:n.stack,synthetic:!0})}fe(e){return W(e.message)&&e.message.length>0}pe(e){var s=e;if(W(s.filename)&&s.filename.length>0){var r,n,i=(r=s.lineno)!==null&&r!==void 0?r:0,o=(n=s.colno)!==null&&n!==void 0?n:0;return`Error - at `+s.filename+":"+i+":"+o}}}var Gh=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;class Kh{match(e){return typeof e=="string"}coerce(e,s){var r,n=this.getInfos(e),i=n[0],o=n[1];return{type:i??"Error",value:o??e,stack:(r=s.syntheticException)==null?void 0:r.stack,synthetic:!0}}getInfos(e){var s="Error",r=e,n=e.match(Gh);return n&&(s=n[1],r=n[2]),[s,r]}}var Jh=["fatal","error","warning","log","info","debug"];function iu(t,e){e===void 0&&(e=40);var s=Object.keys(t);if(s.sort(),!s.length)return"[object has no keys]";for(var r=s.length;r>0;r--){var n=s.slice(0,r).join(", ");if(e>=n.length)return r===s.length?n:n.length>e?n.slice(0,e)+"...":n}return""}class Yh{match(e){return typeof e=="object"&&e!==null}coerce(e,s){var r,n,i=this.getErrorPropertyFromObject(e);return i?s.apply(i):{type:this.getType(e),value:this.getValue(e),stack:(r=this.getStack(e))!==null&&r!==void 0?r:(n=s.syntheticException)==null?void 0:n.stack,level:this.isSeverityLevel(e.level)?e.level:"error",synthetic:!0}}getType(e){return Lo(e)?e.constructor.name:"Error"}getValue(e){if("name"in e&&typeof e.name=="string"){var s="'"+e.name+"' captured as exception";return"message"in e&&typeof e.message=="string"&&(s+=" with message: '"+e.message+"'"),s}if("message"in e&&typeof e.message=="string")return e.message;var r=this.getObjectClassName(e);return(r&&r!=="Object"?"'"+r+"'":"Object")+" captured as exception with keys: "+iu(e)}isSeverityLevel(e){return W(e)&&!Mi(e)&&Jh.indexOf(e)>=0}getStack(e){try{return W(e.stacktrace)&&e.stacktrace.length>0?e.stacktrace:W(e.stack)&&e.stack.length>0?e.stack:void 0}catch{return}}getErrorPropertyFromObject(e){for(var s in e)if({}.hasOwnProperty.call(e,s)){var r=e[s];if(Ah(r))return r}}getObjectClassName(e){try{var s=Object.getPrototypeOf(e);return s?s.constructor.name:void 0}catch{return}}}class Zh{match(e){return Lo(e)}coerce(e,s){var r,n=e.constructor.name;return{type:n,value:n+" captured as exception with keys: "+iu(e),stack:(r=s.syntheticException)==null?void 0:r.stack,synthetic:!0}}}class Xh{match(e){return $c(e)}coerce(e,s){var r;return{type:"Error",value:"Primitive value captured as exception: "+String(e),stack:(r=s.syntheticException)==null?void 0:r.stack,synthetic:!0}}}class Qh{match(e){return qr(e,"PromiseRejectionEvent")||this.isCustomEventWrappingRejection(e)}isCustomEventWrappingRejection(e){if(!Lo(e))return!1;try{var s=e.detail;return s!=null&&typeof s=="object"&&"reason"in s}catch{return!1}}coerce(e,s){var r,n=this.getUnhandledRejectionReason(e);return $c(n)?{type:"UnhandledRejection",value:"Non-Error promise rejection captured with value: "+String(n),stack:(r=s.syntheticException)==null?void 0:r.stack,synthetic:!0}:s.apply(n)}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 Zr="$message",Xr="$timestamp",ep=new Set([Zr,Xr]),ti={enabled:!0,max_bytes:32768};function Qr(t){var e;return t?{enabled:(e=t.enabled)!==null&&e!==void 0?e:ti.enabled,max_bytes:sp(t.max_bytes,ti.max_bytes)}:b({},ti)}class tp{constructor(e){this.Ke=[],this.Je=0,this.Ne=Qr(e)}setConfig(e){this.Ne=Qr(e),this.Xe()}add(e){var s=(function(n){var i;try{i=Fc(n)}catch{return}try{var o=JSON.parse(i);if(!te(o))return;var a=o,l=a[Zr],u=a[Xr];return!W(l)||l.trim().length===0||!W(u)&&!he(u)?void 0:{step:a,json:i}}catch{return}})(e);if(s){var r=(function(n){if(typeof TextEncoder<"u")return new TextEncoder().encode(n).length;for(var i=encodeURIComponent(n),o=0,a=0;i.length>a;a++)i[a]==="%"?(o+=1,a+=2):o+=1;return o})(s.json);r>this.Ne.max_bytes||(this.Ke.push({step:s.step,bytes:r}),this.Je+=r,this.Xe())}}getAttachable(){return this.Ke.map((e=>e.step))}clear(){this.Ke=[],this.Je=0}size(){return this.Ke.length}Xe(){for(;this.Je>this.Ne.max_bytes&&this.Ke.length>0;){var e=this.Ke.shift();e&&(this.Je-=e.bytes)}}}function sp(t,e){if(!he(t)||t===1/0||t===-1/0)return e;var s=Math.floor(t);return 0>s?e:s}var ou=function(t,e){var s=(e===void 0?{}:e).debugEnabled,r={k(n){if(v&&(Y.DEBUG||v.POSTHOG_DEBUG||s)&&!x(v.console)&&v.console){for(var i=("__rrweb_original__"in v.console[n])?v.console[n].__rrweb_original__:v.console[n],o=arguments.length,a=new Array(o>1?o-1:0),l=1;o>l;l++)a[l-1]=arguments[l];i(t,...a)}},debug(){for(var n=arguments.length,i=new Array(n),o=0;n>o;o++)i[o]=arguments[o];r.k("debug",...i)},info(){for(var n=arguments.length,i=new Array(n),o=0;n>o;o++)i[o]=arguments[o];r.k("log",...i)},warn(){for(var n=arguments.length,i=new Array(n),o=0;n>o;o++)i[o]=arguments[o];r.k("warn",...i)},error(){for(var n=arguments.length,i=new Array(n),o=0;n>o;o++)i[o]=arguments[o];r.k("error",...i)},critical(){for(var n=arguments.length,i=new Array(n),o=0;n>o;o++)i[o]=arguments[o];console.error(t,...i)},uninitializedWarning(n){r.error("You must initialize PostHog before calling "+n)},createLogger:(n,i)=>ou(t+" "+n,i)};return r},k=ou("[PostHog.js]"),se=k.createLogger,rp=se("[ExternalScriptsLoader]"),si=(t,e,s)=>{if(t.config.disable_external_dependency_loading)return rp.warn(e+" was requested but loading of external scripts is disabled."),s("Loading of external scripts is disabled");var r=C?.querySelectorAll("script");if(r){for(var n,i=function(){if(r[o].src===e){var l=r[o];return l.__posthog_loading_callback_fired?{v:s()}:(l.addEventListener("load",(u=>{l.__posthog_loading_callback_fired=!0,s(void 0,u)})),l.onerror=u=>s(u),{v:void 0})}},o=0;r.length>o;o++)if(n=i())return n.v}var a=()=>{if(!C)return s("document not found");var l=C.createElement("script");if(l.type="text/javascript",l.crossOrigin="anonymous",l.src=e,l.onload=d=>{l.__posthog_loading_callback_fired=!0,s(void 0,d)},l.onerror=d=>s(d),t.config.prepare_external_dependency_script&&(l=t.config.prepare_external_dependency_script(l)),!l)return s("prepare_external_dependency_script returned null");if(t.config.external_scripts_inject_target==="head")C.head.appendChild(l);else{var u,c=C.querySelectorAll("body > script");c.length>0?(u=c[0].parentNode)==null||u.insertBefore(l,c[0]):C.body.appendChild(l)}};C!=null&&C.body?a():C?.addEventListener("DOMContentLoaded",a)};$.__PosthogExtensions__=$.__PosthogExtensions__||{},$.__PosthogExtensions__.loadExternalDependency=(t,e,s)=>{if(e!=="remote-config"){var r;if(t.config.strict_script_versioning)r=t.requestRouter.endpointFor("assets","/static/"+t.version+"/"+e+".js");else{var n="/static/"+e+".js?v="+t.version;if(e==="toolbar"){var i=3e5;n=n+"&t="+Math.floor(Date.now()/i)*i}r=t.requestRouter.endpointFor("assets",n)}si(t,r,s)}else{var o=t.requestRouter.endpointFor("assets","/array/"+t.config.token+"/config.js");si(t,o,s)}},$.__PosthogExtensions__.loadSiteApp=(t,e,s)=>{var r=t.requestRouter.endpointFor("api",e);si(t,r,s)};Y.DEBUG=!1,Y.LIB_VERSION="1.415.7",Y.LIB_NAME="web";var au="$people_distinct_id",sr="$device_id",ri="$device_model",Bs="__alias",js="__timers",Ui="$autocapture_disabled_server_side",Hi="$heatmaps_enabled_server_side",Wi="$exception_capture_enabled_server_side",zi="$error_tracking_suppression_rules",qi="$error_tracking_capture_extension_exceptions",Vi="$web_vitals_enabled_server_side",Ho="$dead_clicks_enabled_server_side",Wo="$product_tours_enabled_server_side",Gi="$web_vitals_allowed_metrics",qt="$session_recording_remote_config",lu="$replay_sample_rate",cu="$replay_override_sampling",uu="$replay_override_linked_flag",du="$replay_override_url_trigger",hu="$replay_override_event_trigger",ls="$sesid",zo="$session_is_sampled",Bt="$enabled_feature_flags",Us="$active_feature_flags",Rr="$early_access_features",Ki="$feature_flag_details",Hs="$feature_flag_payloads",Tr="$feature_flag_request_id",en="$minimal_flag_called_events",et="$override_feature_flags",jt="$override_feature_flag_payloads",ct="$stored_person_properties",Ut="$stored_group_properties",Ji="$surveys",tn="$surveys_loaded_at",Yi="$surveys_activated",Nr="$surveys_activated_session",Mr="$surveys_activated_timestamps",Ws="ph_product_tours",Wt="$flag_call_reported",zs="$flag_call_reported_session_id",Lr="$feature_flag_errors",Gs="$feature_flag_evaluated_at",He="$user_state",Zi="$client_session_props",Xi="$capture_rate_limit",Qi="$initial_campaign_params",eo="$initial_referrer_info",sn="$initial_person_info",rn="$epp",br="$posthog_cookieless",pu="$cookieless_mode",fu="$sdk_debug_extensions_init_method",gu="$sdk_debug_extensions_init_time_ms",mu="$sdk_debug_recording_script_not_loaded",qo="PostHog loadExternalDependency extension not found.",Ht="on_reject",ht="always",es="anonymous",Tt="identified",to="identified_only",nn="visibilitychange",on="beforeunload",is="$pageview",ni="$pageleave",ii="$identify",Qa="$groupidentify";function Er(t,e){L(t)&&t.forEach(e)}function Z(t,e){if(!D(t))if(L(t))t.forEach(e);else if(fh(t))t.forEach(((r,n)=>e(r,n)));else for(var s in t)Ac.call(t,s)&&e(t[s],s)}var ee=function(t){for(var e=arguments.length,s=new Array(e>1?e-1:0),r=1;e>r;r++)s[r-1]=arguments[r];for(var n of s)for(var i in n)n[i]!==void 0&&(t[i]=n[i]);return t};function Or(t){for(var e=Object.keys(t),s=e.length,r=new Array(s);s--;)r[s]=[e[s],t[e[s]]];return r}var el=function(t){try{return t()}catch{return}},np=function(t){return function(){try{for(var e=arguments.length,s=new Array(e),r=0;e>r;r++)s[r]=arguments[r];return t.apply(this,s)}catch(n){k.critical("Implementation error. Please turn on debug mode and open a ticket on https://app.posthog.com/home#panel=support%3Asupport%3A."),k.critical(n)}}},Vo=function(t){var e={};return Z(t,(function(s,r){(W(s)&&s.length>0||he(s))&&(e[r]=s)})),e},ip=["herokuapp.com","vercel.app","netlify.app"];function op(t){var e=t?.hostname;if(!W(e))return!1;var s=e.split(".").slice(-2).join(".");for(var r of ip)if(s===r)return!1;return!0}function ne(t,e,s,r){var n=r??{},i=n.capture,o=n.passive;t?.addEventListener(e,s,{capture:i!==void 0&&i,passive:o===void 0||o})}function so(t){return t.name==="ph_toolbar_internal"}var vu=t=>{if(C){try{for(var e=t+"=",s=C.cookie.split(";").filter((i=>i.length)),r=0;s.length>r;r++){for(var n=s[r];n.charAt(0)==" ";)n=n.substring(1,n.length);if(n.indexOf(e)===0)return decodeURIComponent(n.substring(e.length,n.length))}}catch{}return null}};Math.trunc||(Math.trunc=function(t){return 0>t?Math.ceil(t):Math.floor(t)}),Number.isInteger||(Number.isInteger=function(t){return he(t)&&isFinite(t)&&Math.floor(t)===t});class an{constructor(e){if(this.bytes=e,e.length!==16)throw new TypeError("not 128-bit length")}static fromFieldsV7(e,s,r,n){if(!Number.isInteger(e)||!Number.isInteger(s)||!Number.isInteger(r)||!Number.isInteger(n)||0>e||0>s||0>r||0>n||e>0xffffffffffff||s>4095||r>1073741823||n>4294967295)throw new RangeError("invalid field value");var i=new Uint8Array(16);return i[0]=e/Math.pow(2,40),i[1]=e/Math.pow(2,32),i[2]=e/Math.pow(2,24),i[3]=e/Math.pow(2,16),i[4]=e/256,i[5]=e,i[6]=112|s>>>8,i[7]=s,i[8]=128|r>>>24,i[9]=r>>>16,i[10]=r>>>8,i[11]=r,i[12]=n>>>24,i[13]=n>>>16,i[14]=n>>>8,i[15]=n,new an(i)}toString(){for(var e="",s=0;this.bytes.length>s;s++)e=e+(this.bytes[s]>>>4).toString(16)+(15&this.bytes[s]).toString(16),s!==3&&s!==5&&s!==7&&s!==9||(e+="-");if(e.length!==36)throw new Error("Invalid UUIDv7 was generated");return e}clone(){return new an(this.bytes.slice(0))}equals(e){return this.compareTo(e)===0}compareTo(e){for(var s=0;16>s;s++){var r=this.bytes[s]-e.bytes[s];if(r!==0)return Math.sign(r)}return 0}}class ap{generate(){var e=this.generateOrAbort();if(!x(e))return e;this.S=0;var s=this.generateOrAbort();if(x(s))throw new Error("Could not generate UUID after timestamp reset");return s}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 an.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 lp}}var tl,_u=t=>{if(typeof UUIDV7_DENY_WEAK_RNG<"u"&&UUIDV7_DENY_WEAK_RNG)throw new Error("no cryptographically strong RNG available");for(var e=0;t.length>e;e++)t[e]=65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random());return t};v&&!x(v.crypto)&&crypto.getRandomValues&&(_u=t=>crypto.getRandomValues(t));class lp{nextUint32(){return this.R.length>this.O||(_u(this.R),this.O=0),this.R[this.O++]}constructor(){this.R=new Uint32Array(8),this.O=1/0}}var dt=()=>cp().toString(),cp=()=>(tl||(tl=new ap)).generate(),Ps="",up=/[a-z0-9][a-z0-9-]+\.[a-z]{2,}$/i,pt={N:()=>!!C,j(t){k.error("cookieStore error: "+t)},P:vu,H(t){var e;try{e=JSON.parse(pt.P(t))||{}}catch{}return e},F(t,e,s,r,n){if(!C)return!1;try{var i="",o="",a=(function(c,d){if(d){var h=(function(f,g){if(g===void 0&&(g=C),Ps)return Ps;if(!g||["localhost","127.0.0.1"].includes(f))return"";for(var m=f.split("."),_=Math.min(m.length,8),w="dmn_chk_"+dt();!Ps&&_--;){var E=m.slice(_).join("."),I=w+"=1;domain=."+E+";path=/";g.cookie=I+";max-age=3",g.cookie.includes(w)&&(g.cookie=I+";max-age=0",Ps=E)}return Ps})(c);if(!h){var p=(f=>{var g=f.match(up);return g?g[0]:""})(c);p!==h&&k.info("Warning: cookie subdomain discovery mismatch",p,h),h=p}return h?"; domain=."+h:""}return""})(C.location.hostname,r);if(s){var l=new Date;l.setTime(l.getTime()+864e5*s),i="; expires="+l.toUTCString()}n&&(o="; secure");var u=t+"="+encodeURIComponent(JSON.stringify(e))+i+"; SameSite=Lax; path=/"+a+o;return u.length>3686.4&&k.warn("cookieStore warning: large cookie, len="+u.length),C.cookie=u,!0}catch{return!1}},q(t,e){if(C!=null&&C.cookie)try{pt.F(t,"",-1,e)}catch{return}}},oi=null,Q={N(){if(!$e(oi))return oi;var t=!0;if(x(v))t=!1;else try{var e="__mplssupport__";Q.F(e,"xyz"),Q.P(e)!=='"xyz"'&&(t=!1),Q.q(e)}catch{t=!1}return t||k.error("localStorage unsupported; falling back to cookie store"),oi=t,t},j(t){k.error("localStorage error: "+t)},P(t){try{return v?.localStorage.getItem(t)}catch(e){Q.j(e)}return null},H(t){try{return JSON.parse(Q.P(t))||{}}catch{}return null},F(t,e){try{return v?.localStorage.setItem(t,JSON.stringify(e)),!0}catch(s){Q.j(s)}return!1},q(t){try{v?.localStorage.removeItem(t)}catch(e){Q.j(e)}}},dp=[sr,"distinct_id",ls,zo,rn,sn,He],Sr={},hp={N:()=>!0,j(t){k.error("memoryStorage error: "+t)},P:t=>Sr[t]||null,H:t=>Sr[t]||null,F:(t,e)=>(Sr[t]=e,!0),q(t){delete Sr[t]}},Nt=null,ce={N(){if(!$e(Nt))return Nt;if(Nt=!0,x(v))Nt=!1;else try{var t="__support__";ce.F(t,"xyz"),ce.P(t)!=='"xyz"'&&(Nt=!1),ce.q(t)}catch{Nt=!1}return Nt},j(t){k.error("sessionStorage error: ",t)},P(t){try{return v?.sessionStorage.getItem(t)}catch(e){ce.j(e)}return null},H(t){try{return JSON.parse(ce.P(t))||null}catch{}return null},F(t,e){try{return v?.sessionStorage.setItem(t,JSON.stringify(e)),!0}catch(s){ce.j(s)}return!1},q(t){try{v?.sessionStorage.removeItem(t)}catch(e){ce.j(e)}}};class pp{constructor(e){this._instance=e}get Ne(){return this._instance.config}get consent(){return this.ti()?0:this.ei}isOptedOut(){return this.Ne.cookieless_mode===ht||this.isRejected()||this.consent===-1&&this.Ne.cookieless_mode===Ht}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,s=e.token,r=e.opt_out_capturing_cookie_prefix;return e.consent_persistence_name||(r?r+s:"__ph_opt_in_out_"+s)}get ei(){var e=this.ii.P(this.ri);return Zn(e)?1:M(_h,e)?0:-1}get ii(){var e=this.Ne.opt_out_capturing_persistence_type,s=e==="localStorage"?Q:pt;if(!this.ni||this.ni!==s){this.ni=s;var r=e==="localStorage"?pt:Q;r.P(this.ri)&&(this.ni.P(this.ri)||this.optInOut(Zn(r.P(this.ri))),r.q(this.ri,this.Ne.cross_subdomain_cookie))}return this.ni}ti(){return!!this.Ne.respect_dnt&&[ke?.doNotTrack,ke?.msDoNotTrack,$.doNotTrack].some((e=>Zn(e)))}}function yu(t,e){var s,r=t==null||(s=t.config)==null?void 0:s.get_current_url;if(!Se(r))return e;try{var n=r(e);return W(n)&&n?n:e}catch(i){return k.error("Error in get_current_url, falling back to window.location.href",i),e}}var wu="__POSTHOG_TOOLBAR__",fp=1,gp=3,mp=11;function sl(t){return t instanceof Element&&(t.id===wu||!(t.closest==null||!t.closest(".toolbar-global-fade-container")))}function Ft(t){return!!t&&t.nodeType===fp}function Me(t,e){return!!t&&!!t.tagName&&t.tagName.toLowerCase()===e.toLowerCase()}function bu(t){return!!t&&t.nodeType===gp}function Eu(t){return!!t&&t.nodeType===mp&&Ft(t.host)}var Su=1e3;function Go(t){return t?Pn(t).split(/\s+/):[]}function rl(t,e){var s=(function(r){var n,i=v==null||(n=v.location)==null?void 0:n.href;return x(i)?void 0:yu(r,i)})(e);return!!(s&&t&&t.some((r=>s.match(r))))}function ln(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 Go(e)}function xu(t){return D(t)?null:Pn(t).split(/(\s+)/).filter((e=>Ks(e))).join("").replace(/[\r\n]/g," ").replace(/[ ]+/g," ").substring(0,255)}function rr(t){var e="";return no(t)&&!Fu(t)&&t.childNodes&&t.childNodes.length&&Z(t.childNodes,(function(s){var r;bu(s)&&s.textContent&&(e+=(r=xu(s.textContent))!==null&&r!==void 0?r:"")})),Pn(e)}function ai(t){var e;return x(t.target)?t.srcElement||null:(e=t.target)!=null&&e.shadowRoot?t.composedPath()[0]||null:t.target||null}var Ko=["a","button","form","input","select","textarea","label"];function ro(t,e){if(x(e))return!0;var s,r=function(i){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}})(i,o))))return{v:!0}};for(var n of t)if(s=r(n))return s.v;return!1}function ku(t){var e=t.parentNode;return!(!e||!Ft(e))&&e}var vp=[".ph-no-autocapture","[data-ph-no-autocapture]"],Iu=["next","previous","prev",">","<"],_p=[...Iu,"+","-","−","–"],nl=(t,e)=>/[a-z0-9]/i.test(e)?t.includes(e):t===e,il=[".ph-no-rageclick",".ph-no-capture"],yp=["","text","search","email","password","url","tel","number"];function ol(t,e){if(!v||Jo(t))return!1;var s,r,n,i,o;if(Ke(e)?(s=!!e&&il,r=void 0,n=!1):(s=(i=e?.css_selector_ignorelist)!==null&&i!==void 0?i:il,r=e?.content_ignorelist,n=(o=e?.ignore_text_selection)!==null&&o!==void 0&&o),s===!1||n&&(function(l){return!(!l||!Ft(l))&&(!!Me(l,"textarea")||(Me(l,"input")?M(yp,(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=Cu(t,!1).targetElementList;return!(function(l,u){if(l===!1||x(l))return!1;var c;if(l===!0)c=Iu;else{if(!L(l))return!1;if(l.length>10)return k.error("[PostHog] content_ignorelist array cannot exceed 10 items. Use css_selector_ignorelist for more complex matching."),!1;c=l.map((d=>d.toLowerCase()))}return u.some((d=>{var h=d.safeText,p=d.ariaLabel;return c.some((f=>nl(h,f)||nl(p,f)))}))})(r,a.map((l=>{var u;return{safeText:rr(l).toLowerCase(),ariaLabel:((u=l.getAttribute("aria-label"))==null?void 0:u.toLowerCase().trim())||""}})))&&!ro(a,s)}var Jo=t=>!t||Me(t,"html")||!Ft(t),Cu=(t,e)=>{if(!v||Jo(t))return{parentIsUsefulElement:!1,targetElementList:[]};for(var s=!1,r=[t],n=t;n.parentNode&&!Me(n,"body");)if(Eu(n.parentNode))r.push(n.parentNode.host),n=n.parentNode.host;else{var i=ku(n);if(!i)break;if(e||Ko.indexOf(i.tagName.toLowerCase())>-1)s=!0;else try{var o=v.getComputedStyle(i);o&&o.getPropertyValue("cursor")==="pointer"&&(s=!0)}catch{}r.push(i),n=i}return{parentIsUsefulElement:s,targetElementList:r}};function no(t){for(var e=new Set,s=0,r=t;r.parentNode&&!Me(r,"body");r=r.parentNode){if(s++>=Su||e.has(r))return!1;e.add(r);var n=ln(r);if(M(n,"ph-sensitive")||M(n,"ph-no-capture"))return!1}if(M(ln(t),"ph-include"))return!0;var i=t.type||"";if(W(i))switch(i.toLowerCase()){case"hidden":case"password":return!1}var o=t.name||t.id||"";return!W(o)||!/^cc|cardnum|ccnum|creditcard|csc|cvc|cvv|exp|pass|pwd|routing|seccode|securitycode|securitynum|socialsec|socsec|ssn/i.test(o.replace(/[^a-zA-Z0-9]/g,""))}function Fu(t){return!!(Me(t,"input")&&!["button","checkbox","submit","reset"].includes(t.type)||Me(t,"select")||Me(t,"textarea")||t.getAttribute("contenteditable")==="true")}var al=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}))$"),ll=/(^|[^0-9A-Za-z_])([0-9][0-9 -]*[0-9])(?=$|[^0-9A-Za-z_])/g,wp=[16,15,14,13],bp=new RegExp("^(\\d{3}-?\\d{2}-?\\d{4})$"),cl=new RegExp("(^|[^0-9])((?!000|666)[0-9]{3}-?(?!00)[0-9]{2}-?(?!0000)[0-9]{4})(?=$|([^0-9]))","g"),ul=/[0-9A-Za-z_]/;function Ep(t){for(var e=0,s=!1,r=t.length-1;r>=0;r--){var n=t.charCodeAt(r)-48;s&&(n*=2)>9&&(n-=9),e+=n,s=!s}return e%10==0}function Ks(t,e){if(e===void 0&&(e=!0),D(t))return!1;if(W(t)){t=Pn(t);var s=e?al.test((t||"").replace(/[- ]/g,"")):(function(n){var i;for(ll.lastIndex=0;i=ll.exec(n);){var o=i[2];if(o)for(var a=o.replace(/[- ]/g,""),l=0;a.length>l;l++)for(var u of wp){var c=l+u;if(a.length>=c){var d=a.slice(l,c);if(al.test(d)&&Ep(d))return!0}}}return!1})(t);if(s)return!1;var r=e?bp.test(t):(function(n){var i;for(cl.lastIndex=0;i=cl.exec(n);){var o=i[1],a=i[3];if(!(o&&a&&ul.test(o)&&ul.test(a)))return!0}return!1})(t);if(r)return!1}return!0}function dl(t){var e=rr(t);return Ks(e=(e+" "+Pu(t)).trim())?e:""}function Pu(t){var e="";return t&&t.childNodes&&t.childNodes.length&&Z(t.childNodes,(function(s){var r;if(s&&((r=s.tagName)==null?void 0:r.toLowerCase())==="span")try{var n=rr(s);e=(e+" "+n).trim(),s.childNodes&&s.childNodes.length&&(e=(e+" "+Pu(s)).trim())}catch(i){k.error("[AutoCapture]",i)}})),e}function hl(t){return t.replace(/"|\\"/g,'\\"')}function Sp(t){var e=t.attr__class;if(e)return L(e)?e:Go(e)}var xr=se("[Dead Clicks]"),xp=()=>!0,kp=t=>{var e,s=!((e=t.instance.persistence)==null||!e.get_property(Ho)),r=t.instance.config.capture_dead_clicks;return Ke(r)?r:!!te(r)||s};class pl{get lazyLoadedDeadClicksAutocapture(){return this.si}constructor(e,s,r){this.instance=e,this.isEnabled=s,this.onCapture=r,this.startIfEnabledOrStop()}onRemoteConfig(e){if(e.ok){var s=e.config;"captureDeadClicks"in s&&(this.instance.persistence&&this.instance.persistence.register({[Ho]:s.captureDeadClicks}),this.startIfEnabledOrStop())}}startIfEnabledOrStop(){this.isEnabled(this)?this.ai((()=>{this.oi()})):this.stop()}ai(e){var s,r;(s=$.__PosthogExtensions__)!=null&&s.initDeadClicksAutocapture?e():(r=$.__PosthogExtensions__)==null||r.loadExternalDependency==null||r.loadExternalDependency(this.instance,"dead-clicks-autocapture",(n=>{n?xr.error("failed to load script",n):e()}))}oi(){var e;if(C){if(!this.si&&(e=$.__PosthogExtensions__)!=null&&e.initDeadClicksAutocapture){var s=te(this.instance.config.capture_dead_clicks)?b({},this.instance.config.capture_dead_clicks):{};s.__onCapture=this.onCapture,this.onCapture&&(s.capture_dead_swipes=!1),this.si=$.__PosthogExtensions__.initDeadClicksAutocapture(this.instance,s),this.si.start(C),xr.info("starting...")}}else xr.error("`document` not found. Cannot start.")}stop(){this.si&&(this.si.stop(),this.si=void 0,xr.info("stopping..."))}}var li=se("[SegmentIntegration]"),Au="posthog-js";function $u(t,e){var s=e===void 0?{}:e,r=s.organization,n=s.projectId,i=s.prefix,o=s.severityAllowList,a=o===void 0?["error"]:o,l=s.sendExceptionsToPostHog,u=l===void 0||l;return c=>{var d,h,p,f,g;if(a!=="*"&&!a.includes(c.level)||!t.__loaded)return c;c.tags||(c.tags={});var m=t.requestRouter.endpointFor("ui","/project/"+t.config.token+"/person/"+t.get_distinct_id());c.tags["PostHog Person URL"]=m,t.sessionRecordingStarted()&&(c.tags["PostHog Recording URL"]=t.get_session_replay_url({withTimestamp:!0}));var _,w=((d=c.exception)==null?void 0:d.values)||[],E=w.map((F=>b({},F,{stacktrace:F.stacktrace?b({},F.stacktrace,{type:"raw",frames:(F.stacktrace.frames||[]).map((P=>b({},P,{platform:"web:javascript"})))}):void 0}))),I={$exception_message:((h=w[0])==null?void 0:h.value)||c.message,$exception_type:(p=w[0])==null?void 0:p.type,$exception_level:c.level,$exception_list:E,$sentry_event_id:c.event_id,$sentry_exception:c.exception,$sentry_exception_message:((f=w[0])==null?void 0:f.value)||c.message,$sentry_exception_type:(g=w[0])==null?void 0:g.type,$sentry_tags:c.tags};return r&&n&&(I.$sentry_url=(i||"https://sentry.io/organizations/")+r+"/issues/?project="+n+"&query="+c.event_id),u&&((_=t.exceptions)==null||_.sendExceptionEvent(I)),c}}class Ip{constructor(e,s,r,n,i,o){this.name=Au,this.setupOnce=function(a){a($u(e,{organization:s,projectId:r,prefix:n,severityAllowList:i,sendExceptionsToPostHog:o==null||o}))}}}class fl{constructor(e){this.li=(s,r,n)=>{n&&(n.noSessionId||n.activityTimeout||n.sessionPastMaximumLength||n.crossTabAdoption)&&(k.info("[PageViewManager] Session rotated, clearing pageview state",{sessionId:s,changeReason:n}),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,s){var r,n=this.vi(e,s);return this.ui={pathname:(r=v?.location.pathname)!==null&&r!==void 0?r:"",pageViewId:s,timestamp:e},this._instance.scrollManager.resetContext(),n}doPageLeave(e){var s;return this.vi(e,(s=this.ui)==null?void 0:s.pageViewId)}doEvent(){var e;return{$pageview_id:(e=this.ui)==null?void 0:e.pageViewId}}vi(e,s){var r=this.ui;if(!r)return{$pageview_id:s};var n={$pageview_id:s,$prev_pageview_id:r.pageViewId},i=this._instance.scrollManager.getContext();if(i&&!this._instance.config.disable_scroll_properties){var o=i.maxScrollHeight,a=i.lastScrollY,l=i.maxScrollY,u=i.maxContentHeight,c=i.lastContentY,d=i.maxContentY;if(!(x(o)||x(a)||x(l)||x(u)||x(c)||x(d))){o=Math.ceil(o),a=Math.ceil(a),l=Math.ceil(l),u=Math.ceil(u),c=Math.ceil(c),d=Math.ceil(d);var h=o>1?rt(a/o,0,1,k):1,p=o>1?rt(l/o,0,1,k):1,f=u>1?rt(c/u,0,1,k):1,g=u>1?rt(d/u,0,1,k):1;n=ee(n,{$prev_pageview_last_scroll:a,$prev_pageview_last_scroll_percentage:h,$prev_pageview_max_scroll:l,$prev_pageview_max_scroll_percentage:p,$prev_pageview_last_content:c,$prev_pageview_last_content_percentage:f,$prev_pageview_max_content:d,$prev_pageview_max_content_percentage:g})}}return r.pathname&&(n.$prev_pageview_pathname=r.pathname),r.timestamp&&(n.$prev_pageview_duration=(e.getTime()-r.timestamp.getTime())/1e3),n}}var ci=["flags","surveys"],Cp={[au]:{exposure:"hidden"},[Bs]:{exposure:"hidden"},__cmpns:{exposure:"hidden"},[js]:{exposure:"hidden"},[Ui]:{exposure:"event"},[Hi]:{exposure:"hidden"},[Wi]:{exposure:"event"},[zi]:{exposure:"hidden"},[qi]:{exposure:"event"},[Vi]:{exposure:"event"},[Ho]:{exposure:"event"},[Wo]:{exposure:"hidden"},[Gi]:{exposure:"event"},[qt]:{exposure:"hidden"},$session_recording_enabled_server_side:{exposure:"hidden"},[ls]:{exposure:"hidden"},[zo]:{exposure:"event"},[lu]:{exposure:"event",shouldSkipFromEventProperties:t=>$e(t)},$session_past_minimum_duration:{exposure:"event"},$session_recording_url_trigger_activated_session:{exposure:"event"},$session_recording_event_trigger_activated_session:{exposure:"event"},$debug_first_full_snapshot_timestamp:{exposure:"event"},$sess_rec_flush_size:{exposure:"hidden"},[Bt]:{exposure:"hidden",storageGroup:"flags"},[Us]:{exposure:"hidden",storageGroup:"flags"},[Rr]:{exposure:"hidden"},[Ki]:{exposure:"hidden",storageGroup:"flags"},[Hs]:{exposure:"hidden",storageGroup:"flags"},[Tr]:{exposure:"hidden",storageGroup:"flags",volatile:!0},[en]:{exposure:"hidden",storageGroup:"flags"},[et]:{exposure:"hidden"},[jt]:{exposure:"hidden"},[ct]:{exposure:"hidden"},[Ut]:{exposure:"hidden"},[Ji]:{exposure:"hidden",storageGroup:"surveys"},[tn]:{exposure:"hidden",storageGroup:"surveys",volatile:!0},[Yi]:{exposure:"event"},[Nr]:{exposure:"hidden"},[Mr]:{exposure:"hidden"},[Ws]:{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"},[Wt]:{exposure:"hidden"},[zs]:{exposure:"hidden"},[Lr]:{exposure:"hidden"},[Gs]:{exposure:"hidden",storageGroup:"flags",volatile:!0},[He]:{exposure:"hidden"},[Zi]:{exposure:"hidden"},[Xi]:{exposure:"hidden"},[Qi]:{exposure:"hidden"},[eo]:{exposure:"hidden"},[sn]:{exposure:"hidden"},[rn]:{exposure:"hidden"},[cu]:{exposure:"event"},[uu]:{exposure:"event"},[du]:{exposure:"event"},[hu]:{exposure:"event"},[fu]:{exposure:"event"},[gu]:{exposure:"event"},[mu]:{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"}},Fp=[["$posthog_sr_group_event_trigger_",{exposure:"hidden"}],["$posthog_sr_group_url_trigger_",{exposure:"hidden"}],["$posthog_sr_group_sampling_",{exposure:"hidden"}]],Mt=t=>{var e=Cp[t];if(e)return e;for(var s of Fp){var r=s[1];if(t.indexOf(s[0])===0)return r}},cs=(t,e)=>{try{return JSON.stringify(t,((s,r)=>typeof r=="bigint"?r.toString():r),e)}catch{return Fc(t)}},cn=t=>{var e=C?.createElement("a");return x(e)?null:(e.href=t,e)},ms=function(t,e){for(var s,r=((t.split("#")[0]||"").split(/\?(.*)/)[1]||"").replace(/^\?+/g,"").split("&"),n=0;r.length>n;n++){var i=r[n].split("=");if(i[0]===e){s=i;break}}if(!L(s)||2>s.length)return"";var o=s[1];try{o=decodeURIComponent(o)}catch{k.error("Skipping decoding for malformed query param: "+o)}return o.replace(/\+/g," ")},nr=function(t,e,s){if(!t||!e||!e.length)return t;for(var r=t.split("#"),n=r[1],i=(r[0]||"").split("?"),o=i[1],a=i[0],l=(o||"").split("&"),u=[],c=0;l.length>c;c++){var d=l[c].split("=");L(d)&&(e.includes(d[0])?u.push(d[0]+"="+s):u.push(l[c]))}var h=a;return o!=null&&(h+="?"+u.join("&")),n!=null&&(h+="#"+n),h},un=function(t,e){var s=t.match(new RegExp(e+"=([^&]*)"));return s?s[1]:null},Ru=(t,e)=>t>=e&&kc(),Tu=(t,e,s,r)=>{if(t===0){if(kc()){var n=e+1;return n===s&&r(),n}return e}return 0},kr="https?://(.*)",vs=["gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","irclid","_kx"],Pp=["utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid",...vs],ir="",Ap=["li_fat_id"];function Nu(t,e,s){if(!C)return{};var r,n=e?[...vs,...s||[]]:[],i=Mu(nr(C.URL,n,ir),t),o=(r={},Z(Ap,(function(a){var l=vu(a);r[a]=l||null})),r);return ee(o,i)}function Mu(t,e){var s=Pp.concat(e||[]),r={};return Z(s,(function(n){var i=ms(t,n);r[n]=i||null})),r}function Lu(t){var e=(function(i){return i?i.search(kr+"google.([^/?]*)")===0?"google":i.search(kr+"bing.com")===0?"bing":i.search(kr+"yahoo.com")===0?"yahoo":i.search(kr+"duckduckgo.com")===0?"duckduckgo":null:null})(t),s=e!="yahoo"?"q":"p",r={};if(!$e(e)){r.$search_engine=e;var n=C?ms(C.referrer,s):"";n.length&&(r.ph_keyword=n)}return r}function gl(){return navigator.language||navigator.userLanguage}var dn="$direct";function Ou(){return C?.referrer||dn}function Du(t,e,s){s===void 0&&(s=!1);var r=t?[...vs,...e||[]]:[],n=s?Ct(re?.href):re?.href,i=n?.substring(0,1e3);return{r:Ou().substring(0,1e3),u:i?nr(i,r,ir):void 0}}function Bu(t,e){var s;e===void 0&&(e=!1);var r=t.r,n=t.u,i=e?Ct(n):n,o={$referrer:r,$referring_domain:r==null?void 0:r==dn?dn:(s=cn(r))==null?void 0:s.host};if(i){o.$current_url=i;var a=cn(i);o.$host=a?.host,o.$pathname=a?.pathname;var l=Mu(i);ee(o,l)}if(r){var u=Lu(r);ee(o,u)}return o}function ju(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return}}function $p(){try{return new Date().getTimezoneOffset()}catch{return}}var Rp={flags:Gs,surveys:tn},Tp=["cookie","localstorage","localstorage+cookie","sessionstorage","memory"],ts="main";class ui{constructor(e,s,r){if(r===void 0&&(r=!0),this.ci={},this.fi=!1,this.pi=!1,this.Ne=e,this.gi=r,this.props={},this.mi=void 0,this.yi=(i=>{var o="";return i.token&&(o=i.token.replace(/\+/g,"PL").replace(/\//g,"SL").replace(/=/g,"EQ")),i.persistence_name?"ph_"+i.persistence_name:"ph_"+o+"_posthog"})(e),this.ii=this.bi(e),this.pi=this.wi(e),this.load(),e.debug&&k.info("Persistence loaded",e.persistence,b({},this.props)),this.update_config(e,e,s),this.save(),v){var n=()=>this.flush();ne(v,"beforeunload",n,{capture:!1}),ne(v,"pagehide",n,{capture:!1})}}ki(){var e,s=(e=this.Ne)==null?void 0:e.persistence_save_debounce_ms;return he(s)&&s>0?s:0}isDisabled(){return!!this.xi}bi(e){Tp.indexOf(e.persistence.toLowerCase())===-1&&(k.critical("Unknown persistence type "+e.persistence+"; falling back to localStorage+cookie"),e.persistence="localStorage+cookie");var s,r=(function(o,a){o===void 0&&(o=[]),a===void 0&&(a=!1);var l=[...dp,...o];return b({},Q,{H(u){try{var c={};try{c=pt.H(u)||{}}catch{}var d,h=JSON.parse(Q.P(u)||"{}");if(a){var p={};for(var f in c){var g=c[f];$e(g)||g===""||(p[f]=g)}d=ee(h,p)}else d=ee(c,h);return Q.F(u,d),d}catch{}return null},F(u,c,d,h,p,f){var g=Q.F(u,c,void 0,void 0,f);try{var m={};l.forEach((_=>{c[_]&&(m[_]=c[_])})),Object.keys(m).length&&pt.F(u,m,d,h,p,f)}catch(_){Q.j(_)}return g},q(u,c){try{v?.localStorage.removeItem(u),pt.q(u,c)}catch(d){Q.j(d)}}})})(e.cookie_persisted_properties||[],e.__preview_cookie_wins_on_conflict||!1),n=!1,i=e.persistence.toLowerCase();return i==="localstorage"&&Q.N()?(s=Q,n=!0):i==="localstorage+cookie"&&r.N()?(s=r,n=!0):i==="sessionstorage"&&ce.N()?s=ce:i==="memory"?s=hp:i==="cookie"?s=pt:r.N()?(s=r,n=!0):s=pt,this.fi=n,s}Si(e){return this.yi+"__"+e}wi(e){return this.fi&&!!e.split_storage}properties(){var e={};return Z(this.props,((s,r)=>{var n=Mt(r);if(!n||n.exposure==="event"){if(n!=null&&n.shouldSkipFromEventProperties!=null&&n.shouldSkipFromEventProperties(s))return;e[r]=s}})),e}load(){if(!this.xi){var e=this.ii.H(this.yi);e&&(this.props=ee({},e)),this.pi&&this.Ci()}}Ci(){for(var e of ci){var s=Q.H(this.Si(e));if(s&&!mt(s)){var r=this.Mi(e);r.persisted=!0,this.Ti(e)||(r.fingerprint=this.Ei(s,e)),this.Ii(e,s)||ee(this.props,s)}}}Ti(e){return Object.keys(this.props).some((s=>{var r;return((r=Mt(s))==null?void 0:r.storageGroup)===e}))}Ii(e,s){var r=Rp[e];if(!r)return!1;var n=s[r],i=this.props[r];return he(n)&&he(i)&&i>n}refreshKey(e){var s;if(!this.xi){var r=this.pi?(s=Mt(e))==null?void 0:s.storageGroup:void 0,n=r?Q.H(this.Si(r)):this.ii.H(this.yi);if(n&&e in n)this.Pi(e,n[e]);else{if(r){var i=this.ii.H(this.yi);if(i&&e in i)return void this.Pi(e,i[e])}this.Ri(e)}}}save(){if(!this.xi){var e=this.ki();e>0?x(this.Ai)&&(this.Ai=setTimeout((()=>{this.Ai=void 0,this.Fi()}),e)):this.Fi()}}flush(){x(this.Ai)||(clearTimeout(this.Ai),this.Ai=void 0,this.Fi())}Fi(){this.xi||(this.pi?this.Li():this.Oi(this.ii,this.yi,this.props,ts))}Li(){var e=this.Di(),s=e.main,r=e.groups;for(var n of(this.Oi(this.ii,this.yi,s,ts),ci)){var i,o=r[n];(!mt(o)||(i=this.ci[n])!=null&&i.persisted)&&this.Oi(Q,this.Si(n),o,n)}}Di(){var e={},s={flags:{},surveys:{}};return Z(this.props,((r,n)=>{var i,o=(i=Mt(n))==null?void 0:i.storageGroup;o?s[o][n]=r:e[n]=r})),{main:e,groups:s}}Ei(e,s){if(s===ts)return JSON.stringify(e)+"|"+this.$i+"|"+this.Ni+"|"+this.qi;var r={};return Z(e,((n,i)=>{var o;r[i]=(o=Mt(i))!=null&&o.volatile?"__volatile__":n})),JSON.stringify(r)}Oi(e,s,r,n){var i=this.Mi(n);if(n===ts||i.dirty||x(i.fingerprint)){var o;try{if((o=this.Ei(r,n))===i.fingerprint)return void(i.dirty=!1)}catch{o=void 0}e.F(s,r,this.$i,this.Ni,this.qi,this.Ne.debug)?(i.dirty=!1,n!==ts&&(i.persisted=!0),x(o)||(i.fingerprint=o)):this.Ne.debug&&k.warn('failed to persist storage entry "'+s+'"; will retry on next save')}}remove(e){var s=(e===void 0?{}:e).keepGroupEntries,r=s!==void 0&&s;if(x(this.Ai)||(clearTimeout(this.Ai),this.Ai=void 0),this.ii.q(this.yi,!1),this.ii.q(this.yi,!0),!r&&this.gi)for(var n of ci)Q.q(this.Si(n));r?delete this.ci[ts]:this.ci={}}clear(){this.remove(),this.props={}}register_once(e,s,r){if(te(e)){x(s)&&(s="None"),this.$i=x(r)?this.ji:r;var n=!1;if(Z(e,((i,o)=>{this.props.hasOwnProperty(o)&&this.props[o]!==s||(this.Pi(o,i),n=!0)})),n)return this.save(),!0}return!1}register(e,s){if(te(e)){this.$i=x(s)?this.ji:s;var r=!1;if(Z(e,((n,i)=>{e.hasOwnProperty(i)&&(this.props[i]!==n||te(n)||L(n))&&(this.Pi(i,n),r=!0)})),r)return this.save(),!0}return!1}unregister(e){var s=typeof e=="string"?[e]:e,r=!1;for(var n of s)n in this.props&&(this.Ri(n),r=!0);r&&this.save()}update_campaign_params(){var e=C?.URL;if(e!==this.mi){var s=Nu(this.Ne.custom_campaign_params,this.Ne.mask_personal_data_properties,this.Ne.custom_personal_data_properties);mt(Vo(s))||this.register(s),this.mi=e}}update_search_keyword(){var e;this.register((e=C?.referrer)?Lu(e):{})}update_referrer_info(){var e;this.register_once({$referrer:Ou(),$referring_domain:C!=null&&C.referrer&&((e=cn(C.referrer))==null?void 0:e.host)||dn},void 0)}set_initial_person_info(){this.props[Qi]||this.props[eo]||this.register_once({[sn]:Du(this.Ne.mask_personal_data_properties,this.Ne.custom_personal_data_properties,this.Ne.disable_capture_url_hashes)},void 0)}get_initial_props(){var e={};Z([eo,Qi],(n=>{var i=this.props[n];i&&Z(i,(function(o,a){e["$initial_"+Ni(a)]=o}))}));var s=this.props[sn];if(s){var r=(function(n,i){i===void 0&&(i=!1);var o=Bu(n,i),a={};return Z(o,(function(l,u){a["$initial_"+Ni(u)]=l})),a})(s,this.Ne.disable_capture_url_hashes);ee(e,r)}return e}safe_merge(e){return Z(this.props,(function(s,r){r in e||(e[r]=s)})),e}update_config(e,s,r){this.ji=this.$i=e.cookie_expiration,this.set_disabled(e.disable_persistence||!!r),this.set_cross_subdomain(e.cross_subdomain_cookie),this.set_secure(e.secure_cookie);var n=e.persistence!==s.persistence||!((l,u)=>{if(l.length!==u.length)return!1;var c=[...l].sort(),d=[...u].sort();return c.every(((h,p)=>h===d[p]))})(e.cookie_persisted_properties||[],s.cookie_persisted_properties||[]),i=n?this.bi(e):this.ii,o=this.wi(e);if(n||o!==this.pi){var a=this.props;this.clear(),this.ii=i,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,s){var r=this.props[js]||{};r[e]=s,this.Pi(js,r),this.save()}remove_event_timer(e){var s=this.props[js]||{},r=s[e];return x(r)||(delete s[e],this.Pi(js,s),this.save()),r}get_property(e){return this.props[e]}set_property(e,s){this.Pi(e,s),this.save()}Pi(e,s){var r;this.props[e]=s,(r=Mt(e))!=null&&r.volatile||this.Bi(e)}Ri(e){delete this.props[e],this.Bi(e)}Bi(e){var s,r=(s=Mt(e))==null?void 0:s.storageGroup;r&&(this.Mi(r).dirty=!0)}Mi(e){return this.ci[e]||(this.ci[e]={})}}function Ir(t){var e=!0;return{dispose(){if(e){e=!1;var s=t();s&&Se(s.then)&&s.then(void 0,(()=>{}))}}}}var xe={GZipJS:"gzip-js",Base64:"base64"},As={Activation:"events",Cancellation:"cancelEvents"},di={Popover:"popover",API:"api",Widget:"widget"},ft={SHOWN:"survey shown",DISMISSED:"survey dismissed",SENT:"survey sent"},hi={SURVEY_ID:"$survey_id",SURVEY_ITERATION:"$survey_iteration",SURVEY_LAST_SEEN_DATE:"$survey_last_seen_date"},io={Popover:"popover",Inline:"inline"},Np={SHOWN:"product tour shown"},ml={TOUR_LAST_SEEN_DATE:"$product_tour_last_seen_date",TOUR_TYPE:"$product_tour_type"},vl=se("[RateLimiter]");class Mp{constructor(e){this.serverLimits={},this.lastEventRateLimited=!1,this.checkForLimiting=s=>{var r=s.text;if(r&&r.length)try{(JSON.parse(r).quota_limited||[]).forEach((n=>{vl.info((n||"events")+" is quota limited."),this.serverLimits[n]=new Date().getTime()+6e4}))}catch(n){return void vl.warn('could not rate limit - continuing. Error: "'+n?.message+'"',{text:r})}},this.instance=e,this.lastEventRateLimited=this.clientRateLimitContext(!0).isRateLimited}get captureEventsPerSecond(){var e;return((e=this.instance.config.rate_limiting)==null?void 0:e.events_per_second)||10}get captureEventsBurstLimit(){var e;return Math.max(((e=this.instance.config.rate_limiting)==null?void 0:e.events_burst_limit)||10*this.captureEventsPerSecond,this.captureEventsPerSecond)}clientRateLimitContext(e){var s,r,n;e===void 0&&(e=!1);var i=this.captureEventsBurstLimit,o=this.captureEventsPerSecond,a=new Date().getTime(),l=(s=(r=this.instance.persistence)==null?void 0:r.get_property(Xi))!==null&&s!==void 0?s:{tokens:i,last:a};l.tokens+=(a-l.last)/1e3*o,l.last=a,l.tokens>i&&(l.tokens=i);var u=1>l.tokens;if(u||e||(l.tokens=Math.max(0,l.tokens-1)),u&&!e){var c=(he(l.dropped)?l.dropped:0)+1;l.dropped=c,!this.lastEventRateLimited&&this.Hi(c)&&(l.dropped=0)}return this.lastEventRateLimited=u,(n=this.instance.persistence)==null||n.set_property(Xi,l),{isRateLimited:u,remainingTokens:l.tokens}}Ui(e){var s=this.instance.config.property_denylist;return!L(s)||!s.includes(e)}zi(){var e;if(this.Ui("$current_url")&&this.Ui("$pathname")&&re!=null&&re.pathname)return""+((e=re.origin)!==null&&e!==void 0?e:"")+re.pathname}Hi(e){var s,r,n=this.captureEventsBurstLimit,i=this.captureEventsPerSecond,o=this.zi(),a=this.Ui("$session_id")?(s=(r=this.instance).get_session_id)==null?void 0:s.call(r):void 0,l=[e+" event(s) dropped since the last warning",o?"triggered on "+o:void 0,a?"session "+a:void 0].filter(Boolean).join(", ");return!!this.instance.capture("$$client_ingestion_warning",{$$client_ingestion_warning_message:"posthog-js client rate limited: "+l+". Config is set to "+i+" events per second and "+n+" events burst limit."},{skip_client_rate_limiting:!0})}isServerRateLimited(e){var s=this.serverLimits[e||"events"]||!1;return s!==!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 xt.info("Using preloaded remote config",this.remoteConfig),this.Zi(this.remoteConfig),void this.Gi();if(this._instance.Qi())return void xt.warn("Remote config is disabled. Falling back to local config.");this.Wi((e=>{if(!e)return xt.info("No config found after loading remote JS config. Falling back to JSON."),void this.Vi((s=>{this.Zi(s.json,s),this.Gi()}));this.Zi(e),this.Gi()}))}catch(e){xt.error("Error loading remote config",e),this.Zi()}}stop(){this.Ki&&(clearInterval(this.Ki),this.Ki=void 0)}refresh(){!this._instance.Qi()&&C&&C.visibilityState!=="hidden"&&this._instance.reloadFeatureFlags()}Gi(){var e;if(!this.Ki){var s=(e=this._instance.config.remote_config_refresh_interval_ms)!==null&&e!==void 0?e:3e5;s!==0&&(this.Ki=setInterval((()=>{this.refresh()}),s))}}Zi(e,s){!e&&s&&(s.statusCode===0?s.error||xt.warn("Failed to fetch remote config from PostHog."):xt.error("Failed to fetch remote config from PostHog."));try{this._instance.Zi(e?{ok:!0,config:e}:{ok:!1})}catch(n){xt.error("Error applying remote config",n)}if(e?.hasFeatureFlags!==!1&&!this._instance.config.advanced_disable_feature_flags_on_first_load)try{var r;(r=this._instance.featureFlags)==null||r.ensureFlagsLoaded()}catch(n){xt.error("Error loading feature flags",n)}}}var qe=Uint8Array,Ae=Uint16Array,_s=Uint32Array,Yo=new qe([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),Zo=new qe([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),_l=new qe([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Hu=function(t,e){for(var s=new Ae(31),r=0;31>r;++r)s[r]=e+=1<r;++r)for(var i=s[r];s[r+1]>i;++i)n[i]=i-s[r]<<5|r;return[s,n]},Wu=Hu(Yo,2),oo=Wu[1];Wu[0][28]=258,oo[258]=28;for(var yl=Hu(Zo,0)[1],zu=new Ae(32768),ie=0;32768>ie;++ie){var ss=(43690&ie)>>>1|(21845&ie)<<1;zu[ie]=((65280&(ss=(61680&(ss=(52428&ss)>>>2|(13107&ss)<<2))>>>4|(3855&ss)<<4))>>>8|(255&ss)<<8)>>>1}var Js=function(t,e,s){for(var r=t.length,n=0,i=new Ae(e);r>n;++n)++i[t[n]-1];var o,a=new Ae(e);for(n=0;e>n;++n)a[n]=a[n-1]+i[n-1]<<1;for(o=new Ae(r),n=0;r>n;++n)o[n]=zu[a[t[n]-1]++]>>>15-t[n];return o},Kt=new qe(288);for(ie=0;144>ie;++ie)Kt[ie]=8;for(ie=144;256>ie;++ie)Kt[ie]=9;for(ie=256;280>ie;++ie)Kt[ie]=7;for(ie=280;288>ie;++ie)Kt[ie]=8;var hn=new qe(32);for(ie=0;32>ie;++ie)hn[ie]=5;var Lp=Js(Kt,9),Op=Js(hn,5),qu=function(t){return(t/8>>0)+(7&t&&1)},Vu=function(t,e,s){(s==null||s>t.length)&&(s=t.length);var r=new(t instanceof Ae?Ae:t instanceof _s?_s:qe)(s-e);return r.set(t.subarray(e,s)),r},ot=function(t,e,s){var r=e/8>>0;t[r]|=s<<=7&e,t[r+1]|=s>>>8},$s=function(t,e,s){var r=e/8>>0;t[r]|=s<<=7&e,t[r+1]|=s>>>8,t[r+2]|=s>>>16},pi=function(t,e){for(var s=[],r=0;t.length>r;++r)t[r]&&s.push({s:r,f:t[r]});var n=s.length,i=s.slice();if(!n)return[new qe(0),0];if(n==1){var o=new qe(s[0].s+1);return o[s[0].s]=1,[o,1]}s.sort((function(F,P){return F.f-P.f})),s.push({s:-1,f:25001});var a=s[0],l=s[1],u=0,c=1,d=2;for(s[0]={s:-1,f:a.f+l.f,l:a,r:l};c!=n-1;)a=s[s[d].f>s[u].f?u++:d++],l=s[u!=c&&s[d].f>s[u].f?u++:d++],s[c++]={s:-1,f:a.f+l.f,l:a,r:l};var h=i[0].s;for(r=1;n>r;++r)i[r].s>h&&(h=i[r].s);var p=new Ae(h+1),f=ao(s[c-1],p,0);if(f>e){r=0;var g=0,m=f-e,_=1<r;++r){var w=i[r].s;if(e>=p[w])break;g+=_-(1<>>=m;g>0;){var E=i[r].s;e>p[E]?g-=1<=0&&g;--r){var I=i[r].s;p[I]==e&&(--p[I],++g)}f=e}return[new qe(p),f]},ao=function(t,e,s){return t.s==-1?Math.max(ao(t.l,e,s+1),ao(t.r,e,s+1)):e[t.s]=s},wl=function(t){for(var e=t.length;e&&!t[--e];);for(var s=new Ae(++e),r=0,n=t[0],i=1,o=function(l){s[r++]=l},a=1;e>=a;++a)if(t[a]==n&&a!=e)++i;else{if(!n&&i>2){for(;i>138;i-=138)o(32754);i>2&&(o(i>10?i-11<<5|28690:i-3<<5|12305),i=0)}else if(i>3){for(o(n),--i;i>6;i-=6)o(8304);i>2&&(o(i-3<<5|8208),i=0)}for(;i--;)o(n);i=1,n=t[a]}return[s.subarray(0,r),e]},Rs=function(t,e){for(var s=0,r=0;e.length>r;++r)s+=t[r]*e[r];return s},lo=function(t,e,s){var r=s.length,n=qu(e+2);t[n]=255&r,t[n+1]=r>>>8,t[n+2]=255^t[n],t[n+3]=255^t[n+1];for(var i=0;r>i;++i)t[n+i+4]=s[i];return 8*(n+4+r)},bl=function(t,e,s,r,n,i,o,a,l,u,c){ot(e,c++,s),++n[256];for(var d=pi(n,15),h=d[0],p=d[1],f=pi(i,15),g=f[0],m=f[1],_=wl(h),w=_[0],E=_[1],I=wl(g),F=I[0],P=I[1],B=new Ae(19),S=0;w.length>S;++S)B[31&w[S]]++;for(S=0;F.length>S;++S)B[31&F[S]]++;for(var A=pi(B,7),R=A[0],N=A[1],T=19;T>4&&!R[_l[T-1]];--T);var O,J,z,H,oe=u+5<<3,pe=Rs(n,Kt)+Rs(i,hn)+o,Ie=Rs(n,h)+Rs(i,g)+o+14+3*T+Rs(B,R)+(2*B[16]+3*B[17]+7*B[18]);if(pe>=oe&&Ie>=oe)return lo(e,c,t.subarray(l,l+u));if(ot(e,c,1+(pe>Ie)),c+=2,pe>Ie){O=Js(h,p),J=h,z=Js(g,m),H=g;var _e=Js(R,N);for(ot(e,c,E-257),ot(e,c+5,P-1),ot(e,c+10,T-4),c+=14,S=0;T>S;++S)ot(e,c+3*S,R[_l[S]]);c+=3*T;for(var Ce=[w,F],Re=0;2>Re;++Re){var ae=Ce[Re];for(S=0;ae.length>S;++S)ot(e,c,_e[me=31&ae[S]]),c+=R[me],me>15&&(ot(e,c,ae[S]>>>5&127),c+=ae[S]>>>12)}}else O=Lp,J=Kt,z=Op,H=hn;for(S=0;a>S;++S)if(r[S]>255){var me;$s(e,c,O[257+(me=r[S]>>>18&31)]),c+=J[me+257],me>7&&(ot(e,c,r[S]>>>23&31),c+=Yo[me]);var ge=31&r[S];$s(e,c,z[ge]),c+=H[ge],ge>3&&($s(e,c,r[S]>>>5&8191),c+=Zo[ge])}else $s(e,c,O[r[S]]),c+=J[r[S]];return $s(e,c,O[256]),c+J[256]},Dp=new _s([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),Bp=(function(){for(var t=new _s(256),e=0;256>e;++e){for(var s=e,r=9;--r;)s=(1&s&&3988292384)^s>>>1;t[e]=s}return t})(),fi=function(t,e,s){for(;s;++e)t[e]=s,s>>>=8};function jp(t,e){e===void 0&&(e={});var s=(function(){var d=4294967295;return{p(h){for(var p=d,f=0;h.length>f;++f)p=Bp[255&p^h[f]]^p>>>8;d=p},d(){return 4294967295^d}}})(),r=t.length;s.p(t);var n,i,o,a,l,u=(a=10+((n=e).filename&&n.filename.length+1||0),l=8,(function(d,h,p,f,g,m){var _=d.length,w=new qe(f+_+5*(1+Math.floor(_/7e3))+g),E=w.subarray(f,w.length-g),I=0;if(!h||8>_)for(var F=0;_>=F;F+=65535){var P=F+65535;_>P?I=lo(E,I,d.subarray(F,P)):(E[F]=!0,I=lo(E,I,d.subarray(F,_)))}else{for(var B=Dp[h-1],S=B>>>13,A=8191&B,R=(1<F;++F){var me=z(F),ge=32767&F,Ye=T[me];if(N[ge]=Ye,T[me]=ge,F>=Re){var Rt=_-F;if((Ie>7e3||Ce>24576)&&Rt>423){I=bl(d,E,0,H,oe,pe,_e,Ce,ae,F-ae,I),Ce=Ie=_e=0,ae=F;for(var de=0;286>de;++de)oe[de]=0;for(de=0;30>de;++de)pe[de]=0}var Ve=2,St=0,ks=A,Be=ge-Ye&32767;if(Rt>2&&me==z(F-Be))for(var Fe=Math.min(S,Rt)-1,mr=Math.min(32767,F),vr=Math.min(258,Rt);mr>=Be&&--ks&&ge!=Ye;){if(d[F+Ve]==d[F+Ve-Be]){for(var je=0;vr>je&&d[F+je]==d[F+je-Be];++je);if(je>Ve){if(Ve=je,St=Be,je>Fe)break;var _r=Math.min(Be,je-2),Xt=0;for(de=0;_r>de;++de){var Qt=F-Be+de+32768&32767,Is=Qt-N[Qt]+32768&32767;Is>Xt&&(Xt=Is,Ye=Qt)}}}Be+=(ge=Ye)-(Ye=N[ge])+32768&32767}if(St){H[Ce++]=268435456|oo[Ve]<<18|yl[St];var Ta=31&oo[Ve],Na=31&yl[St];_e+=Yo[Ta]+Zo[Na],++oe[257+Ta],++pe[Na],Re=F+Ve,++Ie}else H[Ce++]=d[F],++oe[d[F]]}}I=bl(d,E,!0,H,oe,pe,_e,Ce,ae,F-ae,I)}return Vu(w,0,f+qu(I)+g)})(i=t,(o=e).level==null?6:o.level,o.mem==null?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(i.length)))):12+o.mem,a,l)),c=u.length;return(function(d,h){var p=h.filename;if(d[0]=31,d[1]=139,d[2]=8,d[8]=2>h.level?4:h.level==9?2:0,d[9]=3,h.mtime!=0&&fi(d,4,Math.floor(new Date(h.mtime||Date.now())/1e3)),p){d[3]=8;for(var f=0;p.length>=f;++f)d[f+10]=p.charCodeAt(f)}})(u,e),fi(u,c-8,s.d()),fi(u,c-4,r),u}var Up=!!$i||!!Mo,Gu="text/plain",Dr=!1,Ku=(t,e)=>{var s=t.split("#"),r=s[1],n=s[0].split("?"),i=n[0],o=n[1];if(!o)return t;var a=o.split("&").filter((l=>l.split("=")[0]!==e)).join("&");return i+(a?"?"+a:"")+(r?"#"+r:"")},$n=function(t,e,s){var r;s===void 0&&(s=!0);var n=t.split("?"),i=n[0],o=n[1],a=b({},e),l=(r=o?.split("&").map((c=>{var d,h=c.split("="),p=h[0],f=s&&(d=a[p])!==null&&d!==void 0?d:h[1];return delete a[p],p+"="+f})))!==null&&r!==void 0?r:[],u=(function(c,d){var h,p;d===void 0&&(d="&");var f=[];return Z(c,(function(g,m){x(g)||x(m)||m==="undefined"||(h=encodeURIComponent((_=>_ instanceof File)(g)?g.name:g.toString()),p=encodeURIComponent(m),f[f.length]=p+"="+h)})),f.join(d)})(a);return u&&l.push(u),l.length>0?i+"?"+l.join("&"):i},gi=t=>{if(t.Ji)return t.Ji;var e=t.data,s=t.compression;if(e){if(s===xe.GZipJS){var r=jp((function(a,l){var u=a.length;if(typeof TextEncoder<"u")return new TextEncoder().encode(a);for(var c=new qe(a.length+(a.length>>>1)),d=0,h=function(m){c[d++]=m},p=0;u>p;++p){if(d+5>c.length){var f=new qe(d+8+(u-p<<1));f.set(c),c=f}var g=a.charCodeAt(p);128>g?h(g):2048>g?(h(192|g>>>6),h(128|63&g)):g>55295&&57344>g?(h(240|(g=65536+(1047552&g)|1023&a.charCodeAt(++p))>>>18),h(128|g>>>12&63),h(128|g>>>6&63),h(128|63&g)):(h(224|g>>>12),h(128|g>>>6&63),h(128|63&g))}return Vu(c,0,d)})(cs(e)),{mtime:0});return{contentType:Gu,body:r.buffer.slice(r.byteOffset,r.byteOffset+r.byteLength),estimatedSize:r.byteLength}}if(s===xe.Base64){var n=(function(a){return a&&btoa(encodeURIComponent(a).replace(/%([0-9A-F]{2})/g,((l,u)=>String.fromCharCode(parseInt(u,16)))))})(cs(e)),i=(a=>"data="+encodeURIComponent(typeof a=="string"?a:cs(a)))(n);return{contentType:"application/x-www-form-urlencoded",body:i,estimatedSize:new Blob([i]).size}}var o=cs(e);return{contentType:"application/json",body:o,estimatedSize:new Blob([o]).size}}},Ju=t=>{var e,s,r=()=>t.transport==="sendBeacon"?{url:$n(t.url,{compression:xe.Base64}),encodedBody:gi(b({},t,{compression:xe.Base64,Ji:void 0}))}:{url:Ku(t.url,"compression"),encodedBody:gi(b({},t,{compression:void 0,Ji:void 0}))};try{e=gi(t)}catch(n){if(Ua(t.compression,ms(t.url,"compression")))return k.error("Failed to gzip request body, sending uncompressed payload",n),r();throw n}return e&&Ua(t.compression,ms(t.url,"compression"))&&!((s=e.body)instanceof ArrayBuffer?Ri(new Uint8Array(s)):ArrayBuffer.isView(s)&&Ri(new Uint8Array(s.buffer,s.byteOffset,s.byteLength)))?(Dr=!0,r()):{url:t.url,encodedBody:e}},Yu=t=>{try{return Ju(t)}catch(e){return k.error(e),void(t.callback==null||t.callback({statusCode:0,error:e}))}},Hp=(function(){var t=X((function*(e){var s=cs(e.data),r=yield(function(i,o,a){return Ti.apply(this,arguments)})(s,Y.DEBUG,{rethrow:!0});if(!r)return e;var n=yield r.arrayBuffer();return b({},e,{Ji:{contentType:Gu,body:n,estimatedSize:n.byteLength}})}));return function(e){return t.apply(this,arguments)}})(),Wp=/Failed to fetch|NetworkError|Load failed/i,Zu=t=>t?.name==="TypeError"&&Wp.test(t?.message||""),Xu=t=>{var e=Yu(t);if(e){var s=e.url,r=e.encodedBody,n=r??{},i=n.contentType,o=n.body,a=n.estimatedSize,l=new Headers;Z(t.headers,(function(f,g){l.append(g,f)})),i&&l.append("Content-Type",i);var u=null,c=!1;if(Ma){var d=new Ma;u={signal:d.signal,timeout:setTimeout((()=>{var f,g;c=!0,d.abort((f=t.timeout,(g=new Error("PostHog request timed out"+(f?" after "+f+"ms":""))).name="AbortError",g))}),t.timeout)}}var h=f=>{c&&f?.name==="AbortError"||Zu(f)?k.warn(f):k.error(f),t.callback==null||t.callback({statusCode:0,error:f})};try{var p;Mo(s,b({method:t?.method||"GET",headers:l,keepalive:t.method==="POST"&&!t.Yi&&52428.8>(a||0),body:o,signal:(p=u)==null?void 0:p.signal},t.fetchOptions)).then((f=>f.text().then((g=>{var m={statusCode:f.status,text:g};if(f.status===200)try{m.json=JSON.parse(g)}catch(_){k.error(_)}t.callback==null||t.callback(m)})))).catch(h).finally((()=>u?clearTimeout(u.timeout):null))}catch(f){u&&clearTimeout(u.timeout),h(f)}}},co=t=>{try{var e,s=Ju(t),r=s.url,n=s.encodedBody,i=n??{},o=i.body,a=i.estimatedSize;if(!o)return;var l=o instanceof Blob?o:new Blob([o],{type:i.contentType});if(ke.sendBeacon(r,l))return;var u=L(t.data)?t.data:(e=t.data)==null?void 0:e.batch;if(L(u)&&u.length>1&&(a??0)>16384){var c=Math.ceil(u.length/2),d=h=>L(t.data)?h:b({},t.data,{batch:h});return co(b({},t,{data:d(u.slice(0,c))})),void co(b({},t,{data:d(u.slice(c))}))}k.warn("Beacon of ~"+(a??0)+" bytes was rejected by the browser, falling back to fetch"),Xu(b({},t,{Yi:!0}))}catch(h){k.warn("Beacon send failed",h)}},El=(t,e,s,r)=>{var n=r==="query"?e==="POST"?"sent_at":"_":void 0;return $n(s===xe.GZipJS?Ku(t,"compression"):t,b({},n?{[n]:Date.now().toString()}:{},s===xe.GZipJS?{}:{compression:s}))},Br=[];Mo&&Br.push({transport:"fetch",method:Xu}),$i&&Br.push({transport:"XHR",method(t){var e=Yu(t);if(e){var s=new $i,r=e.encodedBody;s.open(t.method||"GET",e.url,!0);var n=r??{},i=n.contentType,o=n.body;Z(t.headers,(function(a,l){s.setRequestHeader(l,a)})),i&&s.setRequestHeader("Content-Type",i),t.timeout&&(s.timeout=t.timeout),s.onreadystatechange=()=>{if(s.readyState===4){var a={statusCode:s.status,text:s.responseText};if(s.status===200)try{a.json=JSON.parse(s.responseText)}catch{}t.callback==null||t.callback(a)}},s.send(o)}}}),ke!=null&&ke.sendBeacon&&Br.push({transport:"sendBeacon",method:co});var uo=3e3;class zp{constructor(e,s){this.Xi=!0,this.tr=[],this.er=rt(s?.flush_interval_ms||uo,250,5e3,k.createLogger("flush interval"),uo),this.ir=e}enqueue(e){this.tr.push(e),this.rr||this.nr()}unload(){this.sr();var e=this.tr.length>0?this.ar():{},s=Object.values(e);[...s.filter((r=>r.url.indexOf("/e")===0)),...s.filter((r=>r.url.indexOf("/e")!==0))].map((r=>{this.lr(b({},r,{transport:"sendBeacon"}))}))}enable(){this.Xi=!1,this.nr()}nr(){var e=this;this.Xi||(this.rr=setTimeout((()=>{if(this.sr(),this.tr.length>0){var s=this.ar(),r=function(){var i=s[n],o=new Date().getTime();i.data&&L(i.data)&&Z(i.data,(a=>{a.offset=Math.abs(a.timestamp-o),delete a.timestamp})),e.lr(i)};for(var n in s)r()}}),this.er))}lr(e){try{this.ir(e)}catch(s){k.error(s)}}sr(){clearTimeout(this.rr),this.rr=void 0}ar(){var e={};return Z(this.tr,(s=>{var r,n=s,i=(n?n.batchKey:null)||n.url;x(e[i])&&(e[i]=b({},n,{data:[]})),(r=e[i].data)==null||r.push(n.data)})),this.tr=[],e}}var qp=["retriesPerformedSoFar"];class Vp{constructor(e){this.ur=!1,this.hr=3e3,this.tr=[],this._instance=e,this.tr=[],this.dr=!0,!x(v)&&"onLine"in v.navigator&&(this.dr=v.navigator.onLine,this.vr=()=>{this.dr=!0,this.cr()},this.pr=()=>{this.dr=!1},ne(v,"online",this.vr),ne(v,"offline",this.pr))}get length(){return this.tr.length}retriableRequest(e){var s=e.retriesPerformedSoFar,r=Ic(e,qp);lt(s)&&(r.url=$n(r.url,{retry_count:s})),this._instance._send_request(b({},r,{callback:n=>{if(n.statusCode!==200&&(400>n.statusCode||n.statusCode>=500)){if((n.statusCode===0?3:10)>(s??0))return void this.At(b({retriesPerformedSoFar:s},r));n.statusCode===0&&k.warn("Request failed before receiving an HTTP response; this can happen due to network issues, CORS, browser blocking, or ad blockers. Stopped retrying after "+(s??0)+" retries.")}r.callback==null||r.callback(n)}}))}At(e){var s=e.retriesPerformedSoFar||0;e.retriesPerformedSoFar=s+1;var r=(function(o){var a=3e3*Math.pow(2,o),l=a/2,u=Math.min(18e5,a),c=Math.random()-.5;return Math.ceil(u+c*(u-l))})(s),n=Date.now()+r;this.tr.push({retryAt:n,requestOptions:e});var i="Enqueued failed request for retry in "+r;navigator.onLine||(i+=" (Browser is offline)"),k.warn(i),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(),s=[],r=this.tr.filter((i=>e>i.retryAt||(s.push(i),!1)));if(this.tr=s,r.length>0)for(var n of r)this.retriableRequest(n.requestOptions)}unload(){for(var e of(this.mr&&(clearTimeout(this.mr),this.mr=void 0),this.ur=!1,x(v)||(this.vr&&(v.removeEventListener("online",this.vr),this.vr=void 0),this.pr&&(v.removeEventListener("offline",this.pr),this.pr=void 0)),this.tr)){var s=e.requestOptions;try{this._instance._send_request(b({},s,{transport:"sendBeacon"}))}catch(r){k.error(r)}}this.tr=[]}}class Gp{constructor(e){this.yr=()=>{var s,r,n,i;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,(s=this.br.maxScrollY)!==null&&s!==void 0?s:0),this.br.maxScrollHeight=Math.max(l,(r=this.br.maxScrollHeight)!==null&&r!==void 0?r:0),this.br.lastContentY=u,this.br.maxContentY=Math.max(u,(n=this.br.maxContentY)!==null&&n!==void 0?n:0),this.br.maxContentHeight=Math.max(c,(i=this.br.maxContentHeight)!==null&&i!==void 0?i: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(){ne(v,"scroll",this.yr,{capture:!0}),ne(v,"scrollend",this.yr,{capture:!0}),ne(v,"resize",this.yr)}scrollElement(){if(!this._r)return v?.document.documentElement;var e=L(this._r)?this._r:[this._r];for(var s of e){var r=v?.document.querySelector(s);if(r)return r}}wr(e){var s=e==="y"?"scrollTop":"scrollLeft";if(this._r){var r=this.scrollElement();return r&&r[s]||0}return v?e==="y"?v.scrollY||v.pageYOffset||v.document.documentElement.scrollTop||0:v.scrollX||v.pageXOffset||v.document.documentElement.scrollLeft||0:0}scrollY(){return this.wr("y")}scrollX(){return this.wr("x")}}var Kp=t=>Du(t?.config.mask_personal_data_properties,t?.config.custom_personal_data_properties,t?.config.disable_capture_url_hashes);class Sl{constructor(e,s,r,n){this.kr=i=>{var o=this.Sr();if(!o||o.sessionId!==i){var a={sessionId:i,props:this.Cr(this._instance)};this.Mr.register({[Zi]:a})}},this._instance=e,this.Tr=s,this.Mr=r,this.Cr=n||Kp,this.Tr.onSessionId(this.kr)}Sr(){return this.Mr.props[Zi]}getSetOnceProps(){var e,s=(e=this.Sr())==null?void 0:e.props;return s?"r"in s?Bu(s,this._instance.config.disable_capture_url_hashes):{$referring_domain:s.referringDomain,$pathname:s.initialPathName,utm_source:s.utm_source,utm_campaign:s.utm_campaign,utm_medium:s.utm_medium,utm_content:s.utm_content,utm_term:s.utm_term}:{}}getSessionProps(){var e={};return Z(Vo(this.getSetOnceProps()),((s,r)=>{r==="$current_url"&&(r="url"),e["$session_entry_"+Ni(r)]=s})),e}}class Xo{on(e,s){return this.Er[e]||(this.Er[e]=[]),this.Er[e].push(s),()=>{this.Er[e]=this.Er[e].filter((r=>r!==s))}}emit(e,s){for(var r of this.Er[e]||[])r(s);for(var n of this.Er["*"]||[])n(e,s)}constructor(){this.Er={}}}var Ts=se("[SessionId]");class xl{on(e,s){return this.Ir.on(e,s)}constructor(e,s,r){var n;if(this.Pr=null,this.Rr=[],this.Ar=void 0,this.Fr=!1,this.Ir=new Xo,this.Lr=(u,c)=>!(!lt(u)||!lt(c))&&Math.abs(u-c)>this.sessionTimeoutMs,!e.persistence)throw new Error("SessionIdManager requires a PostHogPersistence instance");if(e.config.cookieless_mode===ht)throw new Error('SessionIdManager cannot be used with cookieless_mode="always"');this.Ne=e.config,this.Mr=e.persistence,this.Or=void 0,this.Dr=void 0,this._sessionStartTimestamp=null,this._sessionActivityTimestamp=null,this.$r=s||dt,this.Nr=r||dt;var i=this.Ne.persistence_name||this.Ne.token;if(this._sessionTimeoutMs=1e3*rt(this.Ne.session_idle_timeout_seconds||1800,60,36e3,Ts.createLogger("session_idle_timeout_seconds"),1800),e.register({$configured_session_timeout_ms:this._sessionTimeoutMs}),this.qr(),this.jr="ph_"+i+"_window_id",this.Br="ph_"+i+"_primary_window_exists",this.Hr()){var o=ce.H(this.jr),a=ce.H(this.Br);o&&!a?this.Or=o:ce.q(this.jr),ce.F(this.Br,!0)}if((n=this.Ne.bootstrap)!=null&&n.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){Ts.error("Invalid sessionID in bootstrap",u)}this.zr()}get sessionTimeoutMs(){return this._sessionTimeoutMs}onSessionId(e){return x(this.Rr)&&(this.Rr=[]),this.Rr.push(e),this.Dr&&e(this.Dr,this.Or),()=>{this.Rr=this.Rr.filter((s=>s!==e))}}Hr(){return this.Ne.persistence!=="memory"&&!this.Mr.xi&&ce.N()}Wr(e){e!==this.Or&&(this.Or=e,this.Hr()&&ce.F(this.jr,e))}Vr(){return this.Or?this.Or:this.Hr()?ce.H(this.jr):null}Zr(e){var s=this.Pr;return!$e(s)&&!$e(e)&&5e3>Math.abs(e-s)}Ur(e,s,r){var n=s!==this._sessionActivityTimestamp,i=!(e!==this.Dr||r!==this._sessionStartTimestamp);this._sessionStartTimestamp=r,this._sessionActivityTimestamp=s,this.Dr=e,i&&!n||i&&this.Zr(s)||(this.Pr=s,this.Mr.register({[ls]:[s,e,r]}))}Gr(){var e,s=(e=this.Ne)==null?void 0:e.persistence_save_debounce_ms;return lt(s)&&s>0}Qr(){this.Gr()?this.Mr.refreshKey(ls):(this.Mr.flush(),this.Mr.load())}Kr(){var e;if(!$e(this._sessionActivityTimestamp)&&this._sessionActivityTimestamp!==this.Pr){this.Qr();var s=this.Jr();s[1]===this.Dr&&s[2]===this._sessionStartTimestamp&&(this.Pr=this._sessionActivityTimestamp,this.Mr.register({[ls]:[this._sessionActivityTimestamp,(e=this.Dr)!==null&&e!==void 0?e:null,this._sessionStartTimestamp]}),this.Mr.flush())}}Yr(){var e=this.Jr()[0],s=lt(e)?e:0,r=lt(this._sessionActivityTimestamp)?this._sessionActivityTimestamp:0;return Math.max(s,r)}Xr(e){return this.Qr(),this.Lr(e,this.Yr())}Jr(){var e=this.Mr.props[ls];return L(e)&&e.length===2&&e.push(e[0]),e||[0,null,0]}resetSessionId(){this.Pr=null,clearTimeout(this.tn),this.tn=void 0,this.Ur(null,null,null)}destroy(){this.Fr=!0,this.Kr(),clearTimeout(this.tn),this.tn=void 0,this.Ar&&v&&(v.removeEventListener(on,this.Ar,{capture:!1}),this.Ar=void 0),this.Rr=[]}zr(){this.Ar=()=>{this.Kr(),this.Hr()&&ce.q(this.Br)},ne(v,on,this.Ar,{capture:!1})}checkAndGetSessionAndWindowId(e,s){if(e===void 0&&(e=!1),s===void 0&&(s=null),this.Ne.cookieless_mode===ht)throw new Error('checkAndGetSessionAndWindowId should not be called with cookieless_mode="always"');var r=s||new Date().getTime(),n=this.Jr(),i=n[1],o=n[2],a=this.Yr(),l=this.Vr(),u=lt(o)&&Math.abs(r-o)>864e5,c=!1,d=!1,h=!i,p=i,f=!h&&!e&&this.Lr(r,a);if(f){(f=this.Xr(r))||Ts.info("cross-tab refresh kept the session alive",{sessionId:i});var g=this.Jr();i=g[1],o=g[2]}h||f||u?(i=this.$r(),l=this.Nr(),Ts.info("new session ID generated",{sessionId:i,windowId:l,changeReason:{noSessionId:h,activityTimeout:f,sessionPastMaximumLength:u}}),o=r,c=!0):(l||(l=this.Nr(),c=!0),(d=i!==p)&&(Ts.info("adopted cross-tab session id",{sessionId:i,windowId:l}),c=!0));var m=lt(a)&&e&&!u?a:r,_=lt(o)?o:new Date().getTime();this.Wr(l),this.Ur(i,m,_),e||this.qr();var w={noSessionId:h,activityTimeout:f,sessionPastMaximumLength:u,crossTabAdoption:d};return c&&this.Rr.forEach((E=>E(i,l,w))),{sessionId:i,windowId:l,sessionStartTimestamp:_,changeReason:c?w:void 0,lastActivityTimestamp:a}}qr(){this.Fr||(clearTimeout(this.tn),this.tn=setTimeout((()=>{if(!this.Fr)if(this.Xr(new Date().getTime())){var e=this.Dr;this.resetSessionId(),this.Ir.emit("forcedIdleReset",{idleSessionId:e})}else this.qr()}),1.1*this.sessionTimeoutMs))}}var Qu=function(t,e){if(!t)return!1;var s=t.userAgent;if(s&&Wa(s,e))return!0;try{var r=t?.userAgentData;if(r!=null&&r.brands&&r.brands.some((n=>Wa(n?.brand,e))))return!0}catch{}return!!t.webdriver};function ed(){return(ed=X((function*(){var t=ke?.userAgentData;if(t!=null&&t.getHighEntropyValues)try{var e=yield t.getHighEntropyValues(["model"]),s=e?.model;return W(s)&&s.length>0?s:void 0}catch(r){return void k.info("Unable to resolve $device_model from userAgentData.getHighEntropyValues",r)}}))).apply(this,arguments)}var pn=function(t,e){if(!(function(s){try{new RegExp(s)}catch{return!1}return!0})(e))return!1;try{return new RegExp(e).test(t)}catch{return!1}};function mi(t,e,s){return cs({distinct_id:t,userPropertiesToSet:e,userPropertiesToSetOnce:s})}var td={exact:(t,e)=>e.some((s=>t.some((r=>s===r)))),is_not:(t,e)=>e.every((s=>t.every((r=>s!==r)))),regex:(t,e)=>e.some((s=>t.some((r=>pn(s,r))))),not_regex:(t,e)=>e.every((s=>t.every((r=>!pn(s,r))))),icontains:(t,e)=>e.map(Cr).some((s=>t.map(Cr).some((r=>s.includes(r))))),not_icontains:(t,e)=>e.map(Cr).every((s=>t.map(Cr).every((r=>!s.includes(r))))),gt:(t,e)=>e.some((s=>{var r=parseFloat(s);return!isNaN(r)&&t.some((n=>r>parseFloat(n)))})),lt:(t,e)=>e.some((s=>{var r=parseFloat(s);return!isNaN(r)&&t.some((n=>rt.toLowerCase();function sd(t,e){return!t||Object.entries(t).every((s=>{var r=s[1],n=e?.[s[0]];if(x(n)||$e(n))return!1;var i=[String(n)],o=td[r.operator];return!!o&&o(r.values,i)}))}var ho="custom",kl="i.posthog.com",Jp=/^\/static\//;class Yp{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,s=(e=this.instance.config.ui_host)==null?void 0:e.replace(/\/$/,"");return s||(s=this.apiHost.replace("."+kl,".posthog.com")),s==="https://app.posthog.com"?"https://us.posthog.com":s}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":ho),this.en[this.apiHost]}rn(e){if(Jp.test(e)){var s=this.instance.config.asset_host;if(typeof s=="string")return s.trim().replace(/\/$/,"")||void 0}}endpointFor(e,s){if(s===void 0&&(s=""),s&&(s=s[0]==="/"?s:"/"+s),e==="ui")return this.uiHost+s;if(e==="flags")return this.flagsApiHost+s;if(e==="assets"){var r=this.rn(s);if(r)return""+r+s}if(this.region===ho)return this.apiHost+s;var n=kl+s;switch(e){case"assets":return"https://"+this.region+"-assets."+n;case"api":return"https://"+this.region+"."+n}}}function rd(t){var e;return!((e=t.conditions)==null||(e=e.events)==null||(e=e.values)==null||!e.length)}var q=se("[Surveys]"),nd="seenSurvey_",id=t=>{try{var e=(s=>((r,n)=>""+nd+(function(i){return i.current_iteration&&i.current_iteration>0?i.id+"_"+i.current_iteration:i.id})(n))(0,s))(t);if(localStorage.getItem(e))return;localStorage.setItem(e,"true")}catch(s){q.error("Failed to persist survey seen state",s)}},Zp=[di.Popover,di.Widget,di.API],Xp={ignoreConditions:!1,ignoreDelay:!1,displayType:io.Popover},Qp=se("[PostHog ExternalIntegrations]"),ef={intercom:"intercom-integration",crispChat:"crisp-chat-integration"};class tf{constructor(e){this._instance=e}ai(e,s){var r;(r=$.__PosthogExtensions__)==null||r.loadExternalDependency==null||r.loadExternalDependency(this._instance,e,(n=>{if(n)return Qp.error("failed to load script",n);s()}))}startIfEnabledOrStop(){var e=this,s=function(){var i,o,a,l=r[0],u=r[1];!u||(i=$.__PosthogExtensions__)!=null&&(i=i.integrations)!=null&&i[l]||e.ai(ef[l],(()=>{var c;(c=$.__PosthogExtensions__)==null||(c=c.integrations)==null||(c=c[l])==null||c.start(e._instance)})),!u&&(o=$.__PosthogExtensions__)!=null&&(o=o.integrations)!=null&&o[l]&&((a=$.__PosthogExtensions__)==null||(a=a.integrations)==null||(a=a[l])==null||a.stop())};for(var r of Object.entries((n=this._instance.config.integrations)!==null&&n!==void 0?n:{})){var n;s()}}}class sf{constructor(e,s){this.rt=e,this.nn=s,this.sn=new Map,this.an=!1}add(e){var s=this;return X((function*(){if(s.an)throw new Error("Cannot add an extension to a disposed ExtensionRuntime");if(s.sn.has(e.name))throw new Error('Browser extension "'+e.name+'" is already registered');s.sn.set(e.name,e);try{var r=e.setup(s.nn);r&&(yield r)}catch(i){var n=s.sn.get(e.name)===e;n&&s.sn.delete(e.name),s.rt.error('Failed to set up browser extension "'+e.name+'"',i),n&&s.ln(e)}}))()}dispose(){if(!this.an){this.an=!0;var e=Array.from(this.sn.values()).reverse();for(var s of(this.sn.clear(),e))this.ln(s)}}ln(e){try{var s=e.dispose==null?void 0:e.dispose();s&&Se(s.then)&&s.then(void 0,(r=>{this.rt.error('Failed to dispose browser extension "'+e.name+'"',r)}))}catch(r){this.rt.error('Failed to dispose browser extension "'+e.name+'"',r)}}}class rf{constructor(e){this._instance=e}initialize(){}get(e){var s=this._instance.persistence;if(typeof e=="string")return s?.get_property(e);var r={};for(var n of e){var i=s?.get_property(n);x(i)||(r[n]=i)}return r}set(e,s){var r;(r=this._instance.persistence)==null||r.register(typeof e=="string"?{[e]:s}:e)}remove(e){var s;(s=this._instance.persistence)==null||s.unregister(e)}}var Il="extensionsRemoteConfig";class nf{constructor(e){this.an=!1,this.instance=e,this.rt=k,this.un=e.hn,this.kv=new rf(e),this.onEvent=s=>Ir(this.instance.on("eventCaptured",(r=>{try{s({event:r.event,properties:r.properties})}catch(n){this.rt.error("Browser extension event listener failed",n)}}))),this.onRemoteConfig=s=>{if(this.an)return Ir((()=>{}));var r=i=>{try{s(i)}catch(o){this.rt.error("Browser extension remote config listener failed",o)}},n=this.instance.dn.on(Il,r);return this.un&&r(this.un),Ir(n)},this.vn=new sf(k.createLogger("[BrowserExtensions]"),this)}get logger(){return this.rt}get distinctId(){return this.instance.get_distinct_id()}get anonymousId(){var e;return(e=this.instance.get_property(sr))!==null&&e!==void 0?e:this.distinctId}get deviceId(){var e=this.instance.get_property(sr);return typeof e=="string"?e:void 0}get library(){return{name:Y.LIB_NAME,version:Y.LIB_VERSION}}get initialPersonProperties(){var e,s;return(e=(s=this.instance.persistence)==null?void 0:s.get_initial_props())!==null&&e!==void 0?e:{}}get groups(){return this.instance.getGroups()}get session(){try{var e,s,r,n,i=(e=this.instance.sessionManager)==null?void 0:e.checkAndGetSessionAndWindowId(!0);return{sessionId:(s=i?.sessionId)!==null&&s!==void 0?s:"",windowId:(r=i?.windowId)!==null&&r!==void 0?r:"",sessionStartTimestamp:(n=i?.sessionStartTimestamp)!==null&&n!==void 0?n:0}}catch{return{sessionId:"",windowId:"",sessionStartTimestamp:0}}}get projectToken(){return this.instance.config.token}add(e){return this.vn.add(e)}capture(e,s,r){var n=this;return X((function*(){r?n.instance.capture(e,s,{timestamp:r.timestamp,uuid:r.uuid,$set:r.set,$set_once:r.setOnce}):n.instance.capture(e,s)}))()}registerDynamicEventProperties(e){return Ir(this.instance.cn(e))}handleRemoteConfig(e){this.an||(this.un=e,this.instance.dn.emit(Il,e))}sendRequest(e,s){var r=this;return X((function*(){var n;s===void 0&&(s={});var i=r.instance.requestRouter.endpointFor((n=s.target)!==null&&n!==void 0?n:"api",e),o={method:s.method,url:s.query?$n(i,s.query):i,data:s.body,headers:s.headers,timeout:s.timeoutMs,fireCallbackOnDrop:!0,transport:s.transport,compression:s.compression,timestampMode:s.sentAt};return s.transport==="sendBeacon"?(r.instance._send_request(o),{statusCode:202}):new Promise((a=>{o.callback=a,r.instance._send_request(o)}))}))()}dispose(){this.an||(this.an=!0,this.vn.dispose())}}var Ys={},vi=0,fn=()=>{},Cl='Consent opt in/out is not valid with cookieless_mode="always" and will be ignored',Ns="Surveys module not available",Fl="sanitize_properties is deprecated. Use before_send instead",od="Invalid value for property_denylist config: ",of=["token","distinct_id",pu],os="posthog",ad=!Up&&Pe?.indexOf("MSIE")===-1&&Pe?.indexOf("Mozilla")===-1,_i=t=>{var e;return b({api_host:"https://us.i.posthog.com",flags_api_host:null,ui_host:null,asset_host:null,token:"",autocapture:!0,cross_subdomain_cookie:op(C?.location),persistence:"localStorage+cookie",persistence_name:"",cookie_persisted_properties:[],loaded:fn,save_campaign_params:!0,custom_campaign_params:[],custom_blocked_useragents:[],save_referrer:!0,capture_pageleave:"if_capture_pageview",defaults:t??"unset",__preview_deferred_init_extensions:!1,__preview_external_dependency_versioned_paths:!1,__preview_cookie_wins_on_conflict:!1,debug:re&&W(re?.search)&&re.search.indexOf("__posthog_debug=true")!==-1||!1,cookie_expiration:365,upgrade:!1,disable_session_recording:!1,disable_persistence:!1,disable_web_experiments:!0,disable_surveys:!1,disable_surveys_automatic_display:!1,disable_conversations:!1,disable_product_tours:!1,disableDeviceModel:!1,disable_external_dependency_loading:!1,strict_script_versioning:!1,enable_recording_console_log:void 0,secure_cookie:(v==null||(e=v.location)==null?void 0:e.protocol)==="https:",ip:!1,opt_out_capturing_by_default:!1,opt_out_persistence_by_default:!1,opt_out_useragent_filter:!1,opt_out_capturing_persistence_type:"localStorage",consent_persistence_name:null,opt_out_capturing_cookie_prefix:null,opt_in_site_apps:!1,property_denylist:[],respect_dnt:!1,sanitize_properties:null,request_headers:{},request_batching:!0,properties_string_max_length:65535,mask_all_element_attributes:!1,mask_all_text:!1,mask_personal_data_properties:!1,custom_personal_data_properties:[],advanced_disable_flags:!1,advanced_disable_decide:!1,advanced_disable_feature_flags:!1,advanced_disable_feature_flags_on_first_load:!1,advanced_only_evaluate_survey_feature_flags:!1,advanced_feature_flags_dedup_per_session:!1,advanced_enable_surveys:!1,advanced_disable_toolbar_metrics:!1,feature_flag_request_timeout_ms:3e3,surveys_request_timeout_ms:1e4,on_request_error(s){k.error("Bad HTTP status: "+s.statusCode+" "+s.text)},get_device_id:s=>s,capture_performance:void 0,name:"posthog",bootstrap:{},disable_compression:!1,session_idle_timeout_seconds:1800,person_profiles:to,before_send:void 0,get_current_url:void 0,request_queue_config:{flush_interval_ms:uo},error_tracking:{},_onCapture:fn},(s=>({rageclick:s&&s>="2026-05-30"?{content_ignorelist:_p,ignore_text_selection:!0}:!s||"2025-11-30">s||{content_ignorelist:!0},capture_pageview:!s||"2025-05-24">s||"history_change",session_recording:s&&s>="2026-06-25"?{strictMinimumDuration:!0,canvasCapture:{resolutionScale:.6},streamNetworkBody:!0}:s&&s>="2026-05-30"?{strictMinimumDuration:!0,canvasCapture:{resolutionScale:.6}}:s&&s>="2025-11-30"?{strictMinimumDuration:!0}:{},external_scripts_inject_target:s&&s>="2026-01-30"?"head":"body",internal_or_test_user_hostname:s&&s>="2026-01-30"?/^(localhost|127\.0\.0\.1)$/:void 0,persistence_save_debounce_ms:s&&s>="2026-05-30"?250:0,split_storage:!(!s||"2026-05-30">s),detect_google_search_app:!(!s||"2026-05-30">s),disable_capture_url_hashes:!(!s||"2026-06-25">s)}))(t))},af=[["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"]],Pl=t=>{var e={};for(var s of af){var r=s[0],n=s[1];x(t[r])||(e[n]=t[r])}var i=ee({},e,t),o=t.__preview_external_dependency_versioned_paths;return x(o)||(x(t.strict_script_versioning)&&(i.strict_script_versioning=!!o),W(o)&&x(t.asset_host)&&(i.asset_host=o)),L(t.property_blacklist)&&(x(t.property_denylist)?i.property_denylist=t.property_blacklist:L(t.property_denylist)?i.property_denylist=[...t.property_blacklist,...t.property_denylist]:k.error(od+t.property_denylist)),i};class lf{constructor(){this.__forceAllowLocalhost=!1}get fn(){return this.__forceAllowLocalhost}set fn(e){k.error("WebPerformanceObserver is deprecated and has no impact on network capture. Use `_forceAllowLocalhostNetworkCapture` on `posthog.sessionRecording`"),this.__forceAllowLocalhost=e}}class Te{pn(e,s){if(e){var r=this.sn.indexOf(e);r!==-1&&this.sn.splice(r,1)}return this.sn.push(s),s.initialize==null||s.initialize(),s}gn(){return this.config.cookieless_mode===ht||this.config.cookieless_mode===Ht&&this.consent.isRejected()}get decideEndpointWasHit(){var e,s;return(e=(s=this.featureFlags)==null?void 0:s.hasLoadedFlags)!==null&&e!==void 0&&e}get flagsEndpointWasHit(){var e,s;return(e=(s=this.featureFlags)==null?void 0:s.hasLoadedFlags)!==null&&e!==void 0&&e}constructor(){var e;this.webPerformance=new lf,this.mn=!1,this.version=Y.LIB_VERSION,this.yn=new Set,this.bn="",this.dn=new Xo,this.sn=[],this._n=[],this._calculate_event_properties=this.calculateEventProperties.bind(this),this.config=_i(),this.SentryIntegration=Ip,this.sentryIntegration=r=>(function(n,i){var o=$u(n,i);return{name:Au,processEvent:a=>o(a)}})(this,r),this.__request_queue=[],this.__loaded=!1,this.analyticsDefaultEndpoint="/e/",this.wn=!1,this.kn=null,this.xn=null,this.Sn=null,this.scrollManager=new Gp(this),this.pageViewManager=new fl(this),this.rateLimiter=new Mp(this),this.requestRouter=new Yp(this),this.consent=new pp(this),this.externalIntegrations=new tf(this);var s=(e=Te.__defaultExtensionClasses)!==null&&e!==void 0?e:{};this.featureFlags=s.featureFlags&&new s.featureFlags(this),this.toolbar=s.toolbar&&new s.toolbar(this),this.surveys=s.surveys&&new s.surveys(this),this.conversations=s.conversations&&new s.conversations(this),this.logs=s.logs&&new s.logs(this),this.metrics=s.metrics&&new s.metrics(this),this.experiments=s.experiments&&new s.experiments(this),this.exceptions=s.exceptions&&new s.exceptions(this),this.people={set:(r,n,i)=>{var o=W(r)?{[r]:n}:r;this.setPersonProperties(o),i?.({})},set_once:(r,n,i)=>{var o=W(r)?{[r]:n}:r;this.setPersonProperties(void 0,o),i?.({})}},this.on("eventCaptured",(r=>k.info('send "'+r?.event+'"',r)))}init(e,s,r){if(r&&r!==os){var n,i=(n=Ys[r])!==null&&n!==void 0?n:new Te;return i._init(e,s,r),Ys[r]=i,Ys[os][r]=i,i}return this._init(e,s,r)}_init(e,s,r){var n,i;s===void 0&&(s={});var o,a=W(e)?e.trim():"";if(!a)return k.critical("PostHog was initialized without a token. This likely indicates a misconfiguration. Please check the first argument passed to posthog.init()"),this;if(this.__loaded)return a!==((o=this.config)==null?void 0:o.token)?console.warn("[PostHog.js]","You have already initialized PostHog with a different project token! Re-initializing is a no-op, so events will keep going to the project this instance was initialized with. To capture into a second project, load PostHog once, then initialize a named instance after the SDK has loaded, e.g. posthog.init('"+a+"', { ... }, 'project2')"):console.warn("[PostHog.js]","You have already initialized PostHog! Re-initializing is a no-op"),this;this.__loaded=!0,this.config=_i(s.defaults),s.debug=this.Cn(s.debug),this.Mn=s,this.Tn=[],s.person_profiles?this.xn=s.person_profiles:s.process_person&&(this.xn=s.process_person);var l=_i(s.defaults),u=Pl(s),c=ee({},l,u,{name:r,token:a});te(l.rageclick)&&te(u.rageclick)&&(c.rageclick=ee({},l.rageclick,u.rageclick)),te(l.session_recording)&&te(u.session_recording)&&(c.session_recording=ee({},l.session_recording,u.session_recording)),this.set_config(c),this.config.on_xhr_error&&k.error("on_xhr_error is deprecated. Use on_request_error instead"),this.compression=s.disable_compression?void 0:xe.GZipJS;var d=this.En();if(this.persistence=new ui(this.config,d),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new ui(b({},this.config,{persistence:"sessionStorage"}),d,!1),this.bn="ph_"+(this.config.persistence_name||this.config.token)+"_session_registered_properties",this.config.persistence!=="memory"&&!d&&ce.N()){var h=ce.H(this.bn);L(h)&&h.forEach((P=>{W(P)&&this.yn.add(P)}))}else ce.q(this.bn);var p=b({},this.persistence.props),f=b({},this.sessionPersistence.props);this.register({$initialization_time:new Date().toISOString()}),this.In=new zp((P=>this.Pn(P)),this.config.request_queue_config),this.Rn=new Vp(this),this.__request_queue=[];var g=this.gn();if(g||(this.sessionManager=new xl(this),this.sessionPropsManager=new Sl(this,this.sessionManager,this.persistence),this.sessionManager.onSessionId(((P,B,S)=>{(S!=null&&S.activityTimeout||S!=null&&S.sessionPastMaximumLength||S!=null&&S.crossTabAdoption)&&this.An()}))),this.Fn(),this.config.__preview_deferred_init_extensions?(k.info("Deferring extension initialization to improve startup performance"),setTimeout((()=>{this.Ln(g)}),0)):(k.info("Initializing extensions synchronously"),this.Ln(g)),Y.DEBUG=Y.DEBUG||this.config.debug,Y.DEBUG&&k.info("Starting in debug mode",{this:this,config:s,thisC:b({},this.config),p,s:f}),!this.config.identity_distinct_id||(n=s.bootstrap)!=null&&n.distinctID||(s.bootstrap=b({},s.bootstrap,{distinctID:this.config.identity_distinct_id,isIdentifiedID:!0})),((i=s.bootstrap)==null?void 0:i.distinctID)!==void 0){var m=s.bootstrap.distinctID,_=this.get_distinct_id(),w=this.persistence.get_property(He);if(s.bootstrap.isIdentifiedID&&_!=null&&_!==m&&w===es)this.identify(m);else if(s.bootstrap.isIdentifiedID&&_!=null&&_!==m&&w===Tt)k.warn("Bootstrap distinctID differs from an already-identified user. The existing identity is preserved. Call reset() before reinitializing if you intend to switch users.");else{var E=this.config.get_device_id(dt()),I=s.bootstrap.isIdentifiedID?E:m;this.persistence.set_property(He,s.bootstrap.isIdentifiedID?Tt:es),this.register({distinct_id:m,$device_id:I})}}if(g)this.register_once({distinct_id:br,$device_id:null},"");else if(!this.get_distinct_id()){var F=this.config.get_device_id(dt());this.register_once({distinct_id:F,$device_id:F},""),this.persistence.set_property(He,es)}return ne(v,"onpagehide"in self?"pagehide":"unload",this._handle_unload.bind(this),{passive:!1}),s.segment?(function(P,B){var S=P.config.segment;if(!S)return B();(function(A,R){var N=A.config.segment;if(!N)return R();var T=J=>{var z=()=>J.anonymousId()||dt();A.config.get_device_id=z,J.id()&&(A.register({distinct_id:J.id(),$device_id:z()}),A.persistence.set_property(He,Tt)),R()},O=N.user();"then"in O&&Se(O.then)?O.then(T):T(O)})(P,(()=>{S.register((A=>{typeof Promise<"u"&&Promise.resolve||li.warn("This browser does not have Promise support, and can not use the segment integration");var R=(N,T)=>{if(!T)return N;N.event.userId||N.event.anonymousId===A.get_distinct_id()||(li.info("No userId set, resetting PostHog"),A.reset()),N.event.userId&&N.event.userId!==A.get_distinct_id()&&(li.info("UserId set, identifying with PostHog"),A.identify(N.event.userId));var O=A.calculateEventProperties(T,N.event.properties);return N.event.properties=Object.assign({},O,N.event.properties),N};return{name:"PostHog JS",type:"enrichment",version:"1.0.0",isLoaded:()=>!0,load:()=>Promise.resolve(),track:N=>R(N,N.event.event),page:N=>R(N,is),identify:N=>R(N,ii),screen:N=>R(N,"$screen")}})(P)).then((()=>{B()}))}))})(this,(()=>this.On())):this.On(),Se(this.config._onCapture)&&this.config._onCapture!==fn&&(k.warn("onCapture is deprecated. Please use `before_send` instead"),this.on("eventCaptured",(P=>this.config._onCapture(P.event,P)))),this.config.ip&&k.warn('The `ip` config option has NO EFFECT AT ALL and has been deprecated. Use a custom transformation or "Discard IP data" project setting instead. See https://posthog.com/tutorials/web-redact-properties#hiding-customer-ip-address for more information.'),this.config.disableDeviceModel||(function(){return ed.apply(this,arguments)})().then((P=>{P&&this.register({[ri]:P})})).catch(fn),this}Fn(){var e,s,r,n,i,o,a=(e=(s=this.config.__extensionClasses)==null?void 0:s.featureFlags)!==null&&e!==void 0?e:(r=Te.__defaultExtensionClasses)==null?void 0:r.featureFlags;a&&(this.featureFlags&&this.featureFlags instanceof a||((n=this.Dn)==null||n.call(this),this.Dn=void 0,this.featureFlags=new a(this)),Se(this.featureFlags.onReloading)&&Se(this.featureFlags.setup)?this.Dn||(this.Dn=this.featureFlags.onReloading((()=>{this.dn.emit("featureFlagsReloading",!0)})),this.$n().add(this.featureFlags)):(i=(o=this.featureFlags).initialize)==null||i.call(o))}Ln(e){var s,r,n,i,o,a,l,u=performance.now(),c=b({},Te.__defaultExtensionClasses,this.config.__extensionClasses),d=[];c.exceptions&&this.sn.push(this.exceptions=(s=this.exceptions)!==null&&s!==void 0?s:new c.exceptions(this)),c.historyAutocapture&&this.sn.push(this.historyAutocapture=new c.historyAutocapture(this)),c.tracingHeaders&&this.sn.push(this.tracingHeaders=new c.tracingHeaders(this)),c.siteApps&&this.sn.push(this.siteApps=new c.siteApps(this)),c.sessionRecording&&!e&&this.sn.push(this.sessionRecording=new c.sessionRecording(this)),this.config.disable_scroll_properties||d.push((()=>{this.scrollManager.startMeasuringScrollPosition()})),c.autocapture&&this.sn.push(this.autocapture=new c.autocapture(this)),c.surveys&&this.sn.push(this.surveys=(r=this.surveys)!==null&&r!==void 0?r:new c.surveys(this)),c.logs&&this.sn.push(this.logs=(n=this.logs)!==null&&n!==void 0?n:new c.logs(this)),c.metrics&&this.sn.push(this.metrics=(i=this.metrics)!==null&&i!==void 0?i: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,kp)),c.toolbar&&this.sn.push(this.toolbar=(a=this.toolbar)!==null&&a!==void 0?a:new c.toolbar(this)),c.experiments&&this.sn.push(this.experiments=(l=this.experiments)!==null&&l!==void 0?l:new c.experiments(this)),this.sn.forEach((h=>{h.initialize&&d.push((()=>{h.initialize==null||h.initialize()}))})),d.push((()=>{if(this.Nn){var h=this.Nn;this.Nn=void 0,this.sn.forEach((p=>p.onRemoteConfig==null?void 0:p.onRemoteConfig(h)))}})),this.qn(d,u)}qn(e,s){for(;e.length>0;){if(this.config.__preview_deferred_init_extensions&&performance.now()-s>=30&&e.length>0)return void setTimeout((()=>{this.qn(e,s)}),0);var r=e.shift();if(r)try{r()}catch(i){k.error("Error initializing extension:",i)}}var n=Math.round(performance.now()-s);this.register_for_session({[fu]:this.config.__preview_deferred_init_extensions?"deferred":"synchronous",[gu]:n}),this.config.__preview_deferred_init_extensions&&k.info("PostHog extensions initialized ("+n+"ms)")}Zi(e){var s;if(!C||!C.body)return k.info("document not ready yet, trying again in 500 milliseconds..."),void setTimeout((()=>{this.Zi(e)}),500);if(this.config.__preview_deferred_init_extensions&&(this.Nn=e),this.hn=e,this.compression=void 0,e.ok){var r,n=e.config;n.supportedCompression&&!this.config.disable_compression&&(this.compression=M(n.supportedCompression,xe.GZipJS)?xe.GZipJS:M(n.supportedCompression,xe.Base64)?xe.Base64:void 0),(r=n.analytics)!=null&&r.endpoint&&(this.analyticsDefaultEndpoint=n.analytics.endpoint)}this.set_config({person_profiles:this.xn?this.xn:to}),(s=this.jn)==null||s.handleRemoteConfig(e),this.sn.forEach((i=>i.onRemoteConfig==null?void 0:i.onRemoteConfig(e)))}On(){try{this.config.loaded(this)}catch(r){k.critical("`loaded` function failed",r)}if(this.Bn(),this.config.internal_or_test_user_hostname&&re!=null&&re.hostname){var e=re.hostname,s=this.config.internal_or_test_user_hostname;(typeof s=="string"?e===s:s.test(e))&&this.setInternalOrTestUser()}this.config.capture_pageview&&setTimeout((()=>{(this.consent.isOptedIn()||this.gn())&&this.Hn()}),1),this.Un=new Uu(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()&&Er(this.__request_queue,(e=>this.Pn(e))),this.__request_queue=[],this.Bn()}_handle_unload(){var e,s,r,n,i;(e=this.surveys)==null||e.handlePageUnload==null||e.handlePageUnload(),(s=this.metrics)==null||s.flush("sendBeacon"),this.config.request_batching?(this.zn()&&this.capture(ni),(r=this.logs)==null||r.flushLogs("sendBeacon"),(n=this.In)==null||n.unload(),(i=this.Rn)==null||i.unload()):this.zn()&&this.capture(ni,null,{transport:"sendBeacon"})}_send_request(e){this.__loaded?ad?this.__request_queue.push(e):this.rateLimiter.isServerRateLimited(e.batchKey)?e.fireCallbackOnDrop&&(e.callback==null||e.callback({statusCode:429})):(e.transport=e.transport||this.config.api_transport,e.headers=b({},this.config.request_headers,e.headers),e.compression=e.compression==="best-available"?this.compression:e.compression,(x(this.config.disable_beacon)?this.config.__preview_disable_beacon:this.config.disable_beacon)&&(e.disableTransport=["sendBeacon"]),e.fetchOptions=e.fetchOptions||this.config.fetch_options,(s=>{var r,n,i,o=b({},s);o.timeout=o.timeout||6e4;var a,l,u,c,d,h=(r=o.transport)!==null&&r!==void 0?r:"fetch";h==="sendBeacon"&&x(o.compression)&&o.data&&(o.compression=xe.Base64),o.method==="POST"&&o.data&&(o.timestampMode==="capture-body"?o.data={api_key:(l=(d=(c=L(a=o.data)?a:[a])[0])==null||(u=d.properties)==null?void 0:u.token)!==null&&l!==void 0?l:d?.token,batch:c,sent_at:new Date().toISOString()}:o.timestampMode==="body"&&(o.data=(function(m,_){return _===void 0&&(_=new Date().toISOString()),L(m)?m.map((w=>b({},w,{sent_at:_}))):b({},m,{sent_at:_})})(o.data))),o.url=El(o.url,o.method,o.compression,o.timestampMode);var p=Br.filter((m=>!o.disableTransport||!m.transport||!o.disableTransport.includes(m.transport))),f=(n=(i=(function(m,_){for(var w=0;m.length>w;w++)if(m[w].transport===h)return m[w]})(p))==null?void 0:i.method)!==null&&n!==void 0?n:p[0].method;if(!f)throw new Error("No available transport method");var g=m=>{try{f(m)}catch(_){Zu(_)?k.warn(_):k.error(_),o.callback==null||o.callback({statusCode:0,error:_})}};h!=="sendBeacon"&&o.data&&o.compression===xe.GZipJS&&lh&&typeof Promise<"u"&&!Dr?Hp(o).then((m=>{g(m)})).catch((m=>{if(Ha(m))return Dr=!0,void g(b({},o,{compression:void 0,url:El(s.url,s.method,void 0,s.timestampMode)}));(_=>{if(!_||typeof _!="object")return!1;var w="name"in _?String(_.name):"";return Ha(_)||w===Cc})(m)&&(Dr=!0),g(o)})):f(o)})(b({},e,{callback:s=>{var r,n;this.rateLimiter.checkForLimiting(s),400>s.statusCode||(r=(n=this.config).on_request_error)==null||r.call(n,s),e.callback==null||e.callback(s)}}))):e.fireCallbackOnDrop&&(e.callback==null||e.callback({statusCode:0}))}Pn(e){this.Rn?this.Rn.retriableRequest(e):this._send_request(e)}_execute_array(e){vi++;try{var s,r=[],n=[],i=[];Er(e,(a=>{if(a)if(L(s=a[0]))i.push(a);else if(Se(a))try{a.call(this)}catch(l){k.error("Error executing queued PostHog call",a,l)}else L(a)&&s==="alias"?r.push(a):L(a)&&s.indexOf("capture")!==-1&&Se(this[s])?i.push(a):n.push(a)}));var o=function(a,l){Er(a,(function(u){try{if(L(u[0])){var c=l;Z(u,(function(d){c=c[d[0]].apply(c,d.slice(1))}))}else l[u[0]].apply(l,u.slice(1))}catch(d){k.error("Error executing queued PostHog call",u,d)}}))};o(r,this),o(n,this),o(i,this)}finally{vi--}}push(e){if(vi>0&&L(e)&&W(e[0])){var s=Te.prototype[e[0]];Se(s)&&s.apply(this,e.slice(1))}else this._execute_array([e])}capture(e,s,r){var n,i,o,a,l;if(this.__loaded&&this.persistence&&this.sessionPersistence&&this.In){if(this.is_capturing())if(!x(e)&&W(e)){var u=!this.config.opt_out_useragent_filter&&this._is_bot();if(!u||this.config.__preview_capture_bot_pageviews){var c=r!=null&&r.skip_client_rate_limiting?void 0:this.rateLimiter.clientRateLimitContext();if(c==null||!c.isRateLimited){s!=null&&s.$current_url&&!W(s?.$current_url)&&(k.error("Invalid `$current_url` property provided to `posthog.capture`. Input must be a string. Ignoring provided value."),s==null||delete s.$current_url),e!=="$exception"||r!=null&&r.Wn||k.warn("Using `posthog.capture('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureException(error)` instead, which attaches required metadata automatically."),this.sessionPersistence.update_search_keyword(),this.config.save_campaign_params&&this.sessionPersistence.update_campaign_params(),this.config.save_referrer&&this.sessionPersistence.update_referrer_info(),(this.config.save_campaign_params||this.config.save_referrer)&&this.persistence.set_initial_person_info();var d=new Date,h=r?.timestamp||d,p=Ga(r?.uuid,dt),f={uuid:p,event:e,properties:this.calculateEventProperties(e,s||{},h,p)};e===is&&this.config.__preview_capture_bot_pageviews&&u&&(f.event="$bot_pageview",f.properties.$browser_type="bot"),c&&(f.properties.$lib_rate_limit_remaining_tokens=c.remainingTokens);var g=e==="$feature_flag_called"&&f.properties.$feature_flag_has_experiment===!1&&this.get_property(en)===!0;r?.$set&&!g&&(f.$set=r?.$set);var m=r?.$unset;m&&(f.$unset=m);var _,w,E,I=g?void 0:this.Vn(r?.$set_once,e!==Qa,e===ii);if(I&&(f.$set_once=I),r!=null&&r._noTruncate||(i=this.config.properties_string_max_length,o=f,a=T=>W(T)?T.slice(0,i):T,l=new Set,f=(function T(O,J){if(O!==Object(O))return a?a(O):O;if(!l.has(O)){var z;if(l.add(O),L(O))z=[],Er(O,(oe=>{z.push(T(oe))}));else{var H={};Z(O,((oe,pe)=>{l.has(oe)||(H[pe]=T(oe))})),z=H}return z}})(o)),f.timestamp=h,x(r?.timestamp)||(f.properties.$event_time_override_provided=!0,f.properties.$event_time_override_system_time=d),g&&(f.properties=(function(T,O){O===void 0&&(O=[]);var J={},z=H=>{T[H]!==void 0&&(J[H]=T[H])};return ch.forEach(z),O.forEach(z),J})(f.properties,of)),e===ft.DISMISSED||e===ft.SENT){var F=s?.[hi.SURVEY_ID],P=s?.[hi.SURVEY_ITERATION];id({id:F,current_iteration:P}),f.$set=b({},f.$set,{[(_={id:F,current_iteration:P},w=e===ft.SENT?"responded":"dismissed",E="$survey_"+w+"/"+_.id,_.current_iteration&&_.current_iteration>0&&(E="$survey_"+w+"/"+_.id+"/"+_.current_iteration),E)]:!0})}else e===ft.SHOWN&&(f.$set=b({},f.$set,{[hi.SURVEY_LAST_SEEN_DATE]:new Date().toISOString()}));if(e===Np.SHOWN){var B=s?.[ml.TOUR_TYPE];B&&(f.$set=b({},f.$set,{[ml.TOUR_LAST_SEEN_DATE+"/"+B]:new Date().toISOString()}))}var S=b({},f.properties.$set,f.$set);if(mt(S)||this.setPersonPropertiesForFlags(S),!D(this.config.before_send)){var A=this.Pt(f);if(!A)return;(f=A).uuid=Ga(f.uuid,dt)}this.dn.emit("eventCaptured",f);var R=(n=r?._url)!==null&&n!==void 0?n:this.requestRouter.endpointFor("api",this.analyticsDefaultEndpoint),N={method:"POST",url:R,data:f,compression:"best-available",timestampMode:r?._batchKey==="recordings"||/\/s\/(?:\?|$)/.test(R)?"body":"capture-body",batchKey:r?._batchKey,transport:r?.transport};return!this.config.request_batching||r&&(r==null||!r._batchKey)||r!=null&&r.send_instantly?this.Pn(N):this.In.enqueue(N),f}k.critical("This capture call is ignored due to client rate limiting.")}}else k.error("No event name provided to posthog.capture")}else k.uninitializedWarning("posthog.capture")}_addCaptureHook(e){return this.on("eventCaptured",(s=>e(s.event,s)))}$n(){var e;return(e=this.jn)!==null&&e!==void 0?e:this.jn=new nf(this)}cn(e){this._n.push(e);var s=!0;return()=>{if(s){s=!1;var r=this._n.indexOf(e);r!==-1&&this._n.splice(r,1)}}}calculateEventProperties(e,s,r,n,i){if(r=r||new Date,!this.persistence||!this.sessionPersistence)return s;var o=i?void 0:this.persistence.remove_event_timer(e),a=b({},s);if(a.token=this.config.token,a.$config_defaults=this.config.defaults,this.gn()&&(a[pu]=!0),e==="$snapshot"){var l=b({},this.persistence.properties(),this.sessionPersistence.properties());return a.distinct_id=l.distinct_id,(!W(a.distinct_id)&&!he(a.distinct_id)||Mi(a.distinct_id))&&k.error("Invalid distinct_id for replay event. This indicates a bug in your implementation"),a}var u,c=(function(F,P,B,S){var A,R,N,T;if(S===void 0&&(S=!1),!Pe)return{};var O,J=F?[...vs,...P||[]]:[],z=(function(vr){for(var je=0;qa.length>je;je++){var _r=qa[je],Xt=_r[1],Qt=_r[0].exec(vr),Is=Qt&&(Se(Xt)?Xt(Qt,vr):Xt);if(Is)return Is}return["",""]})(Pe),H=z[0],oe=z[1],pe=(O=typeof navigator<"u"?navigator:void 0)!=null&&O.brave?{brave:!0}:{},Ie={};x(B)||(Ie.detectGoogleSearchApp=B);var _e={},Ce=(A=navigator)==null||(A=A.userAgentData)==null?void 0:A.platform,Re=(R=navigator)==null?void 0:R.maxTouchPoints,ae=v==null||(N=v.screen)==null?void 0:N.width,me=v==null||(T=v.screen)==null?void 0:T.height,ge=v?.devicePixelRatio;x(Ce)||(_e.userAgentDataPlatform=Ce),x(Re)||(_e.maxTouchPoints=Re),x(ae)||(_e.screenWidth=ae),x(me)||(_e.screenHeight=me),x(ge)||(_e.devicePixelRatio=ge);var Ye,Rt,de,Ve,St,ks,Be,Fe,mr=ee(Vo({$os:H,$os_version:oe,$browser:Xc(Pe,navigator.vendor,pe,Ie),$device:Va(Pe),$device_type:(Rt=Pe,de=_e,Fe=Va(Rt),Fe===Nc||Fe===Tc||Fe==="Kobo"||Fe==="Kindle Fire"||Fe===Gc?ps:Fe===er||Fe===ds||Fe===tr||Fe===Oi?"Console":Fe===Lc?"Wearable":Fe?Oe:de?.userAgentDataPlatform==="Android"&&((Ve=de?.maxTouchPoints)!==null&&Ve!==void 0?Ve:0)>0?600>Math.min((St=de?.screenWidth)!==null&&St!==void 0?St:0,(ks=de?.screenHeight)!==null&&ks!==void 0?ks:0)/((Be=de?.devicePixelRatio)!==null&&Be!==void 0?Be:1)?Oe:ps:"Desktop"),$timezone:ju(),$timezone_offset:$p()}),{$current_url:nr(S?Ct(re?.href):re?.href,J,ir),$host:re?.host,$pathname:re?.pathname,$raw_user_agent:Pe.length>1e3?Pe.substring(0,997)+"...":Pe,$browser_version:Fh(Pe,navigator.vendor,pe,Ie),$browser_language:gl(),$browser_language_prefix:(Ye=gl(),typeof Ye=="string"?Ye.split("-")[0]:void 0),$screen_height:v?.screen.height,$screen_width:v?.screen.width,$viewport_height:v?.innerHeight,$viewport_width:v?.innerWidth,$lib:Y.LIB_NAME,$lib_version:Y.LIB_VERSION,$insert_id:Math.random().toString(36).substring(2,10)+Math.random().toString(36).substring(2,10),$time:Date.now()/1e3});return Y.SDK_DIST_CHANNEL&&(mr.$sdk_dist_channel=Y.SDK_DIST_CHANNEL),mr})(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(i,r.getTime()),h=d.windowId;a.$session_id=d.sessionId,a.$window_id=h}this.sessionPropsManager&&ee(a,this.sessionPropsManager.getSessionProps());try{var p;this.sessionRecording&&ee(a,this.sessionRecording.sdkDebugProperties),a.$sdk_debug_retry_queue_size=(p=this.Rn)==null?void 0:p.length}catch(F){a.$sdk_debug_error_capturing_properties=String(F)}if(this.requestRouter.region===ho&&(a.$lib_custom_api_host=this.config.api_host),u=e!==is||i?e!==ni||i?this.pageViewManager.doEvent():this.pageViewManager.doPageLeave(r):this.pageViewManager.doPageView(r,n),a=ee(a,u),e===is&&C&&(a.title=C.title),!x(o)){var f=r.getTime()-o;a.$duration=parseFloat((f/1e3).toFixed(3))}Pe&&this.config.opt_out_useragent_filter&&(a.$browser_type=this._is_bot()?"bot":"browser");var g=this.persistence.properties(),m=this.sessionPersistence.properties();Z(["$referrer","$referring_domain"],(F=>{F in g&&delete m[F]}));var _={};if(this._n.length>0)for(var w of this._n.slice())try{ee(_,w())}catch(F){k.error("Failed to produce browser extension event properties",F)}(a=ee({},c,g,m,b({},_,a))).$is_identified=this._isIdentified(),L(this.config.property_denylist)?Z(this.config.property_denylist,(function(F){delete a[F]})):k.error(od+this.config.property_denylist+" or property_blacklist config: "+this.config.property_blacklist);var E=this.config.sanitize_properties;E&&(k.error(Fl),a=E(a,e));var I=this.Zn();return a.$process_person_profile=I,I&&!i&&this.Gn("_calculate_event_properties"),a}Vn(e,s,r){var n;if(s===void 0&&(s=!0),r===void 0&&(r=!1),!this.persistence||!this.Zn()||this.mn&&!r)return e;var i=this.persistence.get_initial_props(),o=(n=this.sessionPropsManager)==null?void 0:n.getSetOnceProps(),a=ee({},i,o||{},e||{}),l=this.config.sanitize_properties;return l&&(k.error(Fl),a=l(a,"$set_once")),s&&(this.mn=!0),mt(a)?void 0:a}register(e,s){var r;(r=this.persistence)==null||r.register(e,s)}register_once(e,s,r){var n;(n=this.persistence)==null||n.register_once(e,s,r)}register_for_session(e){var s;(s=this.sessionPersistence)==null||s.register(e),Object.keys(e).forEach((r=>this.yn.add(r))),this.Qn()}unregister(e){var s;(s=this.persistence)==null||s.unregister(e)}unregister_for_session(e){var s;(s=this.sessionPersistence)==null||s.unregister(e),this.yn.delete(e),this.Qn()}Kn(e,s){this.register({[e]:s})}An(){this.yn.forEach((e=>{var s;(s=this.sessionPersistence)==null||s.unregister(e)})),this.yn.clear(),this.Qn()}Qn(){var e;if(this.bn)if(this.config.persistence==="memory"||(e=this.sessionPersistence)!=null&&e.xi||!ce.N())ce.q(this.bn);else{var s=[];this.yn.forEach((r=>s.push(r))),s.length>0?ce.F(this.bn,s):ce.q(this.bn)}}getFeatureFlag(e,s){var r;return(r=this.featureFlags)==null?void 0:r.getFeatureFlag(e,s)}getFeatureFlagPayload(e){var s;return(s=this.featureFlags)==null?void 0:s.getFeatureFlagPayload(e)}getFeatureFlagResult(e,s){var r;return(r=this.featureFlags)==null?void 0:r.getFeatureFlagResult(e,s)}getAllFeatureFlags(){var e,s;return(e=(s=this.featureFlags)==null?void 0:s.getAllFeatureFlags())!==null&&e!==void 0?e:[]}isFeatureEnabled(e,s){var r,n;return(r=(n=this.featureFlags)==null?void 0:n.isFeatureEnabled(e,s))!==null&&r!==void 0?r:s?.defaultValue}reloadFeatureFlags(){var e;(e=this.featureFlags)==null||e.reloadFeatureFlags()}updateFlags(e,s,r){var n;(n=this.featureFlags)==null||n.updateFlags(e,s,r)}updateEarlyAccessFeatureEnrollment(e,s,r){var n;(n=this.featureFlags)==null||n.updateEarlyAccessFeatureEnrollment(e,s,r)}getEarlyAccessFeatures(e,s,r){var n;return s===void 0&&(s=!1),(n=this.featureFlags)==null?void 0:n.getEarlyAccessFeatures(e,s,r)}on(e,s){return this.dn.on(e,s)}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:Ns}),()=>{})}onSessionId(e){var s,r;return(s=(r=this.sessionManager)==null?void 0:r.onSessionId(e))!==null&&s!==void 0?s:()=>{}}getSurveys(e,s){s===void 0&&(s=!1),this.surveys?this.surveys.getSurveys(e,s):e([],{isLoaded:!1,error:Ns})}getActiveMatchingSurveys(e,s){s===void 0&&(s=!1),this.surveys?this.surveys.getActiveMatchingSurveys(e,s):e([],{isLoaded:!1,error:Ns})}renderSurvey(e,s){var r;(r=this.surveys)==null||r.renderSurvey(e,s)}displaySurvey(e,s){var r;s===void 0&&(s=Xp),(r=this.surveys)==null||r.displaySurvey(e,s)}cancelPendingSurvey(e){var s;(s=this.surveys)==null||s.cancelPendingSurvey(e)}canRenderSurvey(e){var s,r;return(s=(r=this.surveys)==null?void 0:r.canRenderSurvey(e))!==null&&s!==void 0?s:{visible:!1,disabledReason:Ns}}canRenderSurveyAsync(e,s){var r,n;return s===void 0&&(s=!1),(r=(n=this.surveys)==null?void 0:n.canRenderSurveyAsync(e,s))!==null&&r!==void 0?r:Promise.resolve({visible:!1,disabledReason:Ns})}Jn(e){return!e||Mi(e)?(k.critical("Unique user id has not been set in posthog.identify"),!1):e===br?(k.critical('The string "'+e+'" was set in posthog.identify which indicates an error. This ID is only used as a sentinel value.'),!1):!["distinct_id","distinctid"].includes(e.toLowerCase())&&!["undefined","null"].includes(e.toLowerCase())||(k.critical('The string "'+e+'" was set in posthog.identify which indicates an error. This ID should be unique to the user and not a hardcoded string.'),!1)}identify(e,s,r){if(!this.__loaded||!this.persistence)return k.uninitializedWarning("posthog.identify");if(he(e)&&(e=e.toString(),k.warn("The first argument to posthog.identify was a number, but it should be a string. It has been converted to a string.")),this.Jn(e)&&this.Gn("posthog.identify")){var n=this.get_distinct_id();this.register({$user_id:e}),this.get_property(sr)||this.register_once({$had_persisted_distinct_id:!0,$device_id:n},""),e!==n&&e!==this.get_property(Bs)&&(this.unregister(Bs),this.register({distinct_id:e}));var i,o=(this.persistence.get_property(He)||es)===es,a=e!==n,l=!a&&o;if(a&&o)this.persistence.set_property(He,Tt),this.setPersonPropertiesForFlags({$set:s||{},$set_once:r||{}},!1),this.capture(ii,{distinct_id:e,$anon_distinct_id:n},{$set:s||{},$set_once:r||{}}),this.Sn=mi(e,s,r),(i=this.featureFlags)==null||i.setAnonymousDistinctId(n);else if(l){this.persistence.set_property(He,Tt);var u=s||{},c=r||{};this.setPersonPropertiesForFlags({$set:u,$set_once:c},!1),this.capture("$set",{$set:u,$set_once:c}),this.Sn=mi(e,s,r)}else(s||r)&&this.setPersonProperties(s,r);a?(this.reloadFeatureFlags(),this.featureFlags?this.featureFlags.resetFlagCallReported():this.unregister(Wt)):l&&(s||r)&&this.reloadFeatureFlags()}}setPersonProperties(e,s){if((e||s)&&this.Gn("posthog.setPersonProperties")){var r=mi(this.get_distinct_id(),e,s);this.Sn!==r?(this.setPersonPropertiesForFlags({$set:e||{},$set_once:s||{}},!0),this.capture("$set",{$set:e||{},$set_once:s||{}}),this.Sn=r):k.info("A duplicate setPersonProperties call was made with the same properties. It has been ignored.")}}unsetPersonProperties(e){var s,r=(L(e)?e:[e]).filter((n=>W(n)&&n.length>0));r.length!==0&&this.Gn("posthog.unsetPersonProperties")&&((s=this.featureFlags)==null||s.unsetPersonPropertiesForFlags(r,!0),this.capture("$set",{$unset:r}),this.Sn=null)}group(e,s,r){if(e&&s){var n=this.getGroups(),i=n[e]!==s;if(i&&this.resetGroupPropertiesForFlags(e),this.register({$groups:b({},n,{[e]:s})}),i||r){var o={$group_type:e,$group_key:s};r&&(o.$group_set=r),this.capture(Qa,o)}r&&this.setGroupPropertiesForFlags({[e]:r}),i&&!r&&this.reloadFeatureFlags()}else k.error("posthog.group requires a group type and group key")}resetGroups(){this.register({$groups:{}}),this.resetGroupPropertiesForFlags(),this.reloadFeatureFlags()}setPersonPropertiesForFlags(e,s){var r;s===void 0&&(s=!0),(r=this.featureFlags)==null||r.setPersonPropertiesForFlags(e,s)}resetPersonPropertiesForFlags(e){var s;e===void 0&&(e=!0),(s=this.featureFlags)==null||s.resetPersonPropertiesForFlags(e)}setGroupPropertiesForFlags(e,s){var r;s===void 0&&(s=!0),this.Gn("posthog.setGroupPropertiesForFlags")&&((r=this.featureFlags)==null||r.setGroupPropertiesForFlags(e,s))}resetGroupPropertiesForFlags(e){var s;(s=this.featureFlags)==null||s.resetGroupPropertiesForFlags(e)}reset(e){this.Yn(e)}Yn(e,s){var r,n,i,o,a,l,u,c,d,h;if(s===void 0&&(s=!1),k.info("reset"),!this.__loaded)return k.uninitializedWarning("posthog.reset");var p,f=this.get_property(sr),g=this.get_property(ri),m=this.get_property(qt),_=this.is_capturing();if(this.consent.reset(),s||!_||this.is_capturing()||console.warn("[PostHog.js]","reset() cleared the stored consent, and capturing is now off because of `opt_out_capturing_by_default`. Call opt_in_capturing() again, and prefer calling reset() before opting in rather than after."),(r=this.persistence)==null||r.clear(),(n=this.sessionPersistence)==null||n.clear(),this.yn.clear(),this.Qn(),x(m)||(p=this.persistence)==null||p.register({[qt]:m}),(i=this.surveys)==null||i.reset(),(o=this.Un)==null||o.stop(),(a=this.featureFlags)==null||a.reset(),(l=this.conversations)==null||l.reset(),(u=this.logs)==null||u.reset(),(c=this.metrics)==null||c.reset(),(d=this.persistence)==null||d.set_property(He,es),(h=this.sessionManager)==null||h.resetSessionId(),this.Sn=null,this.config.cookieless_mode===ht)this.register_once({distinct_id:br,$device_id:null},"");else{var w=this.config.get_device_id(dt());this.register_once({distinct_id:w,$device_id:e?w:f},""),e||x(g)||this.register({[ri]: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 s=this;return X((function*(){var r,n,i,o,a,l,u;if(s.__loaded){(r=s.Un)==null||r.stop(),(n=s.jn)==null||n.dispose(),(i=s.sessionRecording)==null||i.dispose(),(o=s.logs)==null||o.flushLogs("sendBeacon"),(a=s.metrics)==null||a.flush("sendBeacon"),(l=s.In)==null||l.unload(),(u=s.Rn)==null||u.unload();try{var c;(c=s.featureFlags)==null||c.destroy()}catch(d){k.error("Error while destroying feature flags",d)}}else k.uninitializedWarning("posthog.shutdown")}))()}setIdentity(e,s){var r;this.config.identity_distinct_id=e,this.config.identity_hash=s,this.alias(e),(r=this.conversations)==null||r.Xn()}clearIdentity(){var e;delete this.config.identity_distinct_id,delete this.config.identity_hash,(e=this.conversations)==null||e.ts()}get_distinct_id(){return this.get_property("distinct_id")}getGroups(){return this.get_property("$groups")||{}}get_session_id(){var e,s;return(e=(s=this.sessionManager)==null?void 0:s.checkAndGetSessionAndWindowId(!0).sessionId)!==null&&e!==void 0?e:""}get_session_replay_url(e){if(!this.sessionManager)return"";var s=this.sessionManager.checkAndGetSessionAndWindowId(!0),r=s.sessionStartTimestamp,n=this.requestRouter.endpointFor("ui","/project/"+this.config.token+"/replay/"+s.sessionId);if(e!=null&&e.withTimestamp&&r){var i,o=(i=e.timestampLookBack)!==null&&i!==void 0?i:10;if(!r)return n;n+="?t="+Math.max(Math.floor((new Date().getTime()-r)/1e3)-o,0)}return n}alias(e,s){return e===this.get_property(au)?(k.critical("Attempting to create alias for existing People user - aborting."),-2):this.Gn("posthog.alias")?(x(s)&&(s=this.get_distinct_id()),e!==s?(this.Kn(Bs,e),this.capture("$create_alias",{alias:e,distinct_id:s})):(k.warn("alias matches current distinct_id - skipping api call."),this.identify(e),-1)):void 0}set_config(e){var s=b({},this.config);if(te(e)){var r,n,i,o,a,l,u,c,d,h,p,f;ee(this.config,Pl(e));var g=this.En();(r=this.persistence)==null||r.update_config(this.config,s,g),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new ui(b({},this.config,{persistence:"sessionStorage"}),g,!1);var m=this.Cn(this.config.debug);Ke(m)&&(this.config.debug=m),Ke(this.config.debug)&&(this.config.debug?(Y.DEBUG=!0,Q.N()&&Q.F("ph_debug",!0),k.info("set_config",{config:e,oldConfig:s,newConfig:b({},this.config)})):(Y.DEBUG=!1,Q.N()&&Q.q("ph_debug"))),(n=this.featureFlags)==null||n.updateConfig==null||n.updateConfig(this.config,this.Qi()),(i=this.exceptionObserver)==null||i.onConfigChange(),(o=this.exceptions)==null||o.onConfigChange(),(a=this.sessionRecording)==null||a.startIfEnabledOrStop(),(l=this.tracingHeaders)==null||l.startIfEnabledOrStop(),(u=this.autocapture)==null||u.startIfEnabled(),(c=this.heatmaps)==null||c.startIfEnabled(),(d=this.exceptionObserver)==null||d.startIfEnabledOrStop(),(h=this.deadClicksAutocapture)==null||h.startIfEnabledOrStop(),(p=this.surveys)==null||p.loadIfEnabled(),this.es(),(f=this.externalIntegrations)==null||f.startIfEnabledOrStop()}}_overrideSDKInfo(e,s){Y.LIB_NAME=e,Y.LIB_VERSION=s}startSessionRecording(e){var s,r,n,i,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)&&((s=this.sessionManager)==null||s.checkAndGetSessionAndWindowId(),l.sampling&&((r=this.sessionRecording)==null||r.overrideSampling()),l.linked_flag&&((n=this.sessionRecording)==null||n.overrideLinkedFlag()),l.url_trigger&&((i=this.sessionRecording)==null||i.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,s){if(this.exceptions){var r=new Error("PostHog syntheticException"),n=this.exceptions.buildProperties(e,{handled:!0,syntheticException:r});return this.exceptions.sendExceptionEvent(b({},n,s))}}addExceptionStep(e,s){var r;(r=this.exceptions)==null||r.addExceptionStep(e,s)}captureLog(e){var s;(s=this.logs)==null||s.captureLog(e)}get logger(){var e,s;return(e=(s=this.logs)==null?void 0:s.logger)!==null&&e!==void 0?e:Te.rs}startExceptionAutocapture(e){this.set_config({capture_exceptions:e==null||e})}stopExceptionAutocapture(){this.set_config({capture_exceptions:!1})}loadToolbar(e){var s,r;return(s=(r=this.toolbar)==null?void 0:r.loadToolbar(e))!==null&&s!==void 0&&s}get_property(e){var s;return(s=this.persistence)==null?void 0:s.props[e]}getSessionProperty(e){var s;return(s=this.sessionPersistence)==null?void 0:s.props[e]}toString(){var e,s=(e=this.config.name)!==null&&e!==void 0?e:os;return s!==os&&(s=os+"."+s),s}_isIdentified(){var e,s;return((e=this.persistence)==null?void 0:e.get_property(He))===Tt||((s=this.sessionPersistence)==null?void 0:s.get_property(He))===Tt}Zn(){var e,s;return!(this.config.person_profiles==="never"||this.config.person_profiles===to&&!this._isIdentified()&&mt(this.getGroups())&&((e=this.persistence)==null||(e=e.props)==null||!e[Bs])&&((s=this.persistence)==null||(s=s.props)==null||!s[rn]))}zn(){return this.config.capture_pageleave===!0||this.config.capture_pageleave==="if_capture_pageview"&&(this.config.capture_pageview===!0||this.config.capture_pageview==="history_change")}createPersonProfile(){this.Zn()||this.Gn("posthog.createPersonProfile")&&this.setPersonProperties({},{})}setInternalOrTestUser(){this.Gn("posthog.setInternalOrTestUser")&&this.setPersonProperties({$internal_or_test_user:!0})}Gn(e){return this.config.person_profiles==="never"?(k.error(e+' was called, but process_person is set to "never". This call will be ignored.'),!1):(this.Kn(rn,!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!==Ht)}es(){var e,s,r,n,i=this.En();return((e=this.persistence)==null?void 0:e.xi)!==i&&((r=this.persistence)==null||r.set_disabled(i)),((s=this.sessionPersistence)==null?void 0:s.xi)!==i&&((n=this.sessionPersistence)==null||n.set_disabled(i)),i&&(this.yn.clear(),this.Qn()),i}opt_in_capturing(e){var s;if(this.config.cookieless_mode!==ht){if(this.gn()){var r,n,i,o,a;this.Yn(!0,!0),(r=this.sessionManager)==null||r.destroy(),(n=this.pageViewManager)==null||n.destroy(),this.sessionManager=new xl(this),this.pageViewManager=new fl(this),this.persistence&&(this.sessionPropsManager=new Sl(this,this.sessionManager,this.persistence));var l,u=(i=(o=this.config.__extensionClasses)==null?void 0:o.sessionRecording)!==null&&i!==void 0?i:(a=Te.__defaultExtensionClasses)==null?void 0:a.sessionRecording;u&&(this.sessionRecording=this.pn(this.sessionRecording,new u(this)),this.hn&&((l=this.sessionRecording)==null||l.onRemoteConfig==null||l.onRemoteConfig(this.hn)))}var c,d;this.consent.optInOut(!0),this.es(),this.Bn(),(s=this.sessionRecording)==null||s.startIfEnabledOrStop(),this.config.cookieless_mode==Ht&&((c=this.surveys)==null||c.loadIfEnabled()),(x(e?.captureEventName)||e!=null&&e.captureEventName)&&this.capture((d=e?.captureEventName)!==null&&d!==void 0?d:"$opt_in",e?.captureProperties,{send_instantly:!0}),this.config.capture_pageview&&this.Hn()}else k.warn(Cl)}opt_out_capturing(){var e,s,r;this.config.cookieless_mode!==ht?(this.config.cookieless_mode===Ht&&this.consent.isOptedIn()&&this.Yn(!0,!0),this.consent.optInOut(!1),this.es(),this.config.cookieless_mode===Ht&&(this.register({distinct_id:br,$device_id:null}),(e=this.sessionRecording)==null||e.stopRecording(),this.sessionRecording=void 0,(s=this.sessionManager)==null||s.destroy(),(r=this.pageViewManager)==null||r.destroy(),this.sessionManager=void 0,this.sessionPropsManager=void 0,this.config.capture_pageview&&this.Hn(),this.Bn())):k.warn(Cl)}has_opted_in_capturing(){return this.consent.isOptedIn()}has_opted_out_capturing(){return this.consent.isOptedOut()}get_explicit_consent_status(){var e=this.consent.consent;return e===1?"granted":e===0?"denied":"pending"}is_capturing(){return this.config.cookieless_mode===ht||(this.config.cookieless_mode===Ht?this.consent.isRejected()||this.consent.isOptedIn():!this.has_opted_out_capturing())}clear_opt_in_out_capturing(){this.consent.reset(),this.es()}_is_bot(){return ke?Qu(ke,this.config.custom_blocked_useragents):void 0}Hn(){C&&(C.visibilityState==="visible"?this.wn||(this.wn=!0,this.capture(is,{title:C.title},{send_instantly:!0}),this.kn&&(C.removeEventListener(nn,this.kn),this.kn=null)):this.kn||(this.kn=this.Hn.bind(this),ne(C,nn,this.kn)))}debug(e){e===!1?(v?.console.log("You've disabled debug mode."),this.set_config({debug:!1})):(v?.console.log("You're now in debug mode. All calls to PostHog will be logged in your console.\nYou can disable this with `posthog.debug(false)`."),this.set_config({debug:!0}))}Qi(){var e=this.Mn||{};return"advanced_disable_flags"in e?!!e.advanced_disable_flags:this.config.advanced_disable_flags!==!1?!!this.config.advanced_disable_flags:this.config.advanced_disable_decide===!0?(k.warn("Config field 'advanced_disable_decide' is deprecated. Please use 'advanced_disable_flags' instead. The old field will be removed in a future major version."),!0):(function(s,r,n,i,o){var a=r in s&&!D(s[r]),l=n in s&&!D(s[n]);return a?s[r]:!!l&&(o&&o.warn("Config field '"+n+"' is deprecated. Please use '"+r+"' instead. The old field will be removed in a future major version."),s[n])})(e,"advanced_disable_flags","advanced_disable_decide",0,k)}Pt(e){var s;if(D(this.config.before_send))return e;var r=Object.keys((s=e.properties)!==null&&s!==void 0?s:{}).filter(mh),n=L(this.config.before_send)?this.config.before_send:[this.config.before_send],i=e;for(var o of n){if(i=o(i),D(i)){var a="Event '"+e.event+"' was rejected in beforeSend function";return gh(e.event)?k.warn(a+". This can cause unexpected behavior."):k.info(a),null}i.properties&&!mt(i.properties)||k.warn("Event '"+e.event+"' has no properties after beforeSend function, this is likely an error.")}for(var l of r)if(i.properties&&D(i.properties[l]))return k.warn("Event '"+e.event+"' had its '"+l+"' property removed in a beforeSend function. This property is required for ingestion, so the event will be dropped."),null;return i}getPageViewId(){var e;return(e=this.pageViewManager.ui)==null?void 0:e.pageViewId}captureTraceFeedback(e,s){this.capture("$ai_feedback",{$ai_trace_id:String(e),$ai_feedback_text:s})}captureTraceMetric(e,s,r){this.capture("$ai_metric",{$ai_trace_id:String(e),$ai_metric_name:s,$ai_metric_value:String(r)})}Cn(e){var s=Ke(e)&&!e,r=Q.N()&&Q.P("ph_debug")==="true";return!s&&(!!r||e)}}Te.__defaultExtensionClasses={},Te.rs=(()=>{var t=()=>{};return{trace:t,debug:t,info:t,warn:t,error:t,fatal:t}})(),(function(t,e){for(var s=0;e.length>s;s++)t.prototype[e[s]]=np(t.prototype[e[s]])})(Te,["identify"]);class Al{constructor(e){this.disabled=e===!1;var s=te(e)?e:{};this.thresholdPx=s.threshold_px||30,this.timeoutMs=s.timeout_ms||1e3,this.clickCount=s.click_count||3,this.clicks=[]}isRageClick(e,s,r){if(this.disabled)return!1;var n=this.clicks[this.clicks.length-1];if(n&&Math.abs(e-n.x)+Math.abs(s-n.y)r-n.timestamp){if(this.clicks.push({x:e,y:s,timestamp:r}),this.clicks.length===this.clickCount)return!0}else this.clicks=[{x:e,y:s,timestamp:r}];return!1}}var yi="$copy_autocapture",wi=se("[AutoCapture]");function bi(t,e){return e.length>t?e.slice(0,t)+"...":e}function cf(t){if(t.previousElementSibling)return t.previousElementSibling;var e=t;do e=e.previousSibling;while(e&&!Ft(e));return e}function uf(t,e){var s,r,n=e.e,i=e.maskAllElementAttributes,o=e.maskAllText,a=e.elementAttributeIgnoreList,l=e.elementsChainAsString,u=e.disableCaptureUrlHashes;if(!Ft(t))return{props:{}};for(var c=[t],d=new Set([t]),h=t;h.parentNode&&!Me(h,"body")&&Su>c.length;)if(Eu(h.parentNode)){var p=h.parentNode.host;if(d.has(p))break;d.add(p),c.push(p),h=p}else{if(!Ft(h.parentNode)||d.has(h.parentNode))break;d.add(h.parentNode),c.push(h.parentNode),h=h.parentNode}var f,g,m=[],_={},w=!1,E=!1;if(Z(c,(S=>{var A=no(S);if(Me(S,"a")){var R=S.getAttribute("href");w=!!(A&&R&&Ks(R))&&(u?Ct(R):R)}M(ln(S),"ph-no-capture")&&(E=!0),m.push((function(T,O,J,z,H){H===void 0&&(H=!1);var oe=T.tagName.toLowerCase(),pe={tag_name:oe};Ko.indexOf(oe)>-1&&!J&&(pe.$el_text=oe.toLowerCase()==="a"||oe.toLowerCase()==="button"?bi(1024,dl(T)):bi(1024,rr(T)));var Ie=ln(T);Ie.length>0&&(pe.classes=Ie.filter((function(ae){return ae!==""}))),Z(T.attributes,(function(ae){var me;if((!Fu(T)||["name","id","class","aria-label"].indexOf(ae.name)!==-1)&&(z==null||!z.includes(ae.name))&&!O&&Ks(ae.value)&&(!W(me=ae.name)||me.substring(0,10)!=="_ngcontent"&&me.substring(0,7)!=="_nghost")){var ge=ae.value;ae.name==="class"&&(ge=Go(ge).join(" ")),pe["attr__"+ae.name]=bi(1024,ae.name==="href"&&H?Ct(ge):ge)}}));for(var _e=1,Ce=1,Re=T;Re=cf(Re);)_e++,Re.tagName===T.tagName&&Ce++;return pe.nth_child=_e,pe.nth_of_type=Ce,pe})(S,i,o,a,u));var N=(function(T){if(!no(T))return{};var O={};return Z(T.attributes,(function(J){if(J.name&&J.name.indexOf("data-ph-capture-attribute")===0){var z=J.name.replace("data-ph-capture-attribute-",""),H=J.value;z&&H&&Ks(H)&&(O[z]=H)}})),O})(S);ee(_,N)})),E)return{props:{},explicitNoCapture:E};if(o||(m[0].$el_text=Me(t,"a")||Me(t,"button")?dl(t):rr(t)),w){var I,F;m[0].attr__href=w;var P=(I=cn(w))==null?void 0:I.host,B=v==null||(F=v.location)==null?void 0:F.host;P&&B&&P!==B&&(f=w)}return{props:ee({$event_type:n.type,$ce_version:1},l?{}:{$elements:m},{$elements_chain:(g=m,(function(S){return S.map((A=>{var R,N,T="";if(A.tag_name&&(T+=A.tag_name),A.attr_class)for(var O of(A.attr_class.sort(),A.attr_class))T+="."+O.replace(/"/g,"");var J=b({},A.text?{text:A.text}:{},{"nth-child":(R=A.nth_child)!==null&&R!==void 0?R:0,"nth-of-type":(N=A.nth_of_type)!==null&&N!==void 0?N:0},A.href?{href:A.href}:{},A.attr_id?{attr_id:A.attr_id}:{},A.attributes),z={};return Or(J).sort(((H,oe)=>H[0].localeCompare(oe[0]))).forEach((H=>{var oe=H[1];return z[hl(H[0].toString())]=hl(oe.toString())})),(T+=":")+Or(z).map((H=>H[0]+'="'+H[1]+'"')).join("")})).join(";")})((function(S){return S.map((A=>{var R,N,T={text:(R=A.$el_text)==null?void 0:R.slice(0,400),tag_name:A.tag_name,href:(N=A.attr__href)==null?void 0:N.slice(0,2048),attr_class:Sp(A),attr_id:A.attr__id,nth_child:A.nth_child,nth_of_type:A.nth_of_type,attributes:{}};return Or(A).filter((O=>O[0].indexOf("attr__")===0)).forEach((O=>T.attributes[O[0]]=O[1])),T}))})(g)))},(s=m[0])!=null&&s.$el_text?{$el_text:(r=m[0])==null?void 0:r.$el_text}:{},f&&n.type==="click"?{$external_click_url:f}:{},_)}}var Ms=se("[ExceptionAutocapture]"),$l=()=>{},df=se("[TracingHeaders]"),Lt=se("[Web Vitals]"),Rl=9e5,Tl="disabled",Nl="lazy_loading",Ls="awaiting_config",Fr="missing_config";se("[SessionRecording]"),se("[SessionRecording]");var po="[SessionRecording]",at=se(po),hf=se("[Heatmaps]");function Ei(t){return te(t)&&"clientX"in t&&"clientY"in t&&he(t.clientX)&&he(t.clientY)}var Pr=se("[Product Tours]"),Si=t=>{var e;return!t.config.disable_product_tours&&!((e=t.persistence)==null||!e.get_property(Wo))},pf=["$set_once","$set"],Ze=se("[SiteApps]"),Ml="Error while initializing PostHog app with config id ";function rs(t,e,s){if(D(t))return!1;switch(s){case"exact":return t===e;case"contains":var r=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/_/g,".").replace(/%/g,".*");return new RegExp(r,"i").test(t);case"regex":try{return new RegExp(e).test(t)}catch{return!1}default:return!1}}class ff{constructor(e){this.ns=new Xo,this.ss=(s,r)=>this.os(s,r)&&this.ls(s,r)&&this.us(s,r)&&this.hs(s,r),this.os=(s,r)=>r==null||!r.event||s?.event===r?.event,this._instance=e,this.ds=new Set,this.vs=new Set}init(){var e,s;x((e=this._instance)==null?void 0:e._addCaptureHook)||(s=this._instance)==null||s._addCaptureHook(((r,n)=>{this.on(r,n)}))}register(e){var s,r;if(!x((s=this._instance)==null?void 0:s._addCaptureHook)&&(e.forEach((o=>{var a,l;(a=this.vs)==null||a.add(o),(l=o.steps)==null||l.forEach((u=>{var c;(c=this.ds)==null||c.add(u?.event||"")}))})),(r=this._instance)!=null&&r.autocapture)){var n,i=new Set;e.forEach((o=>{var a;(a=o.steps)==null||a.forEach((l=>{l!=null&&l.selector&&i.add(l?.selector)}))})),(n=this._instance)==null||n.autocapture.setElementSelectors(i)}}on(e,s){var r;s!=null&&e.length!=0&&(this.ds.has(e)||this.ds.has(s.event))&&this.vs&&((r=this.vs)==null?void 0:r.size)>0&&this.vs.forEach((n=>{this.cs(s,n)&&this.ns.emit("actionCaptured",n.name)}))}fs(e){this.onAction("actionCaptured",(s=>e(s)))}cs(e,s){if(s?.steps==null)return!1;for(var r of s.steps)if(this.ss(e,r))return!0;return!1}onAction(e,s){return this.ns.on(e,s)}ls(e,s){if(s!=null&&s.url){var r,n=e==null||(r=e.properties)==null?void 0:r.$current_url;if(!n||typeof n!="string"||!rs(n,s.url,s.url_matching||"contains"))return!1}return!0}us(e,s){return!!this.ps(e,s)&&!!this.gs(e,s)&&!!this.ys(e,s)}ps(e,s){var r;if(s==null||!s.href)return!0;var n=this.bs(e);if(n.length>0)return n.some((a=>rs(a.href,s.href,s.href_matching||"exact")));var i,o=(e==null||(r=e.properties)==null?void 0:r.$elements_chain)||"";return!!o&&rs((i=o.match(/(?::|")href="(.*?)"/))?i[1]:"",s.href,s.href_matching||"exact")}gs(e,s){var r;if(s==null||!s.text)return!0;var n=this.bs(e);if(n.length>0)return n.some((u=>rs(u.text,s.text,s.text_matching||"exact")||rs(u.$el_text,s.text,s.text_matching||"exact")));var i,o,a,l=(e==null||(r=e.properties)==null?void 0:r.$elements_chain)||"";return!!l&&(i=(function(u){for(var c,d=[],h=/(?::|")text="(.*?)"/g;!D(c=h.exec(u));)d.includes(c[1])||d.push(c[1]);return d})(l),o=s.text,a=s.text_matching||"exact",i.some((u=>rs(u,o,a))))}ys(e,s){var r,n;if(s==null||!s.selector)return!0;var i=e==null||(r=e.properties)==null?void 0:r.$element_selectors;if(i!=null&&i.includes(s.selector))return!0;var o=(e==null||(n=e.properties)==null?void 0:n.$elements_chain)||"";if(s.selector_regex&&o)try{return new RegExp(s.selector_regex).test(o)}catch{return!1}return!1}bs(e){var s;return(e==null||(s=e.properties)==null?void 0:s.$elements)==null?[]:e?.properties.$elements}hs(e,s){return s==null||!s.properties||s.properties.length===0||sd(s.properties.reduce(((r,n)=>{var i=L(n.value)?n.value.map(String):n.value!=null?[String(n.value)]:[];return r[n.key]={values:i,operator:n.operator||"exact"},r}),{}),e?.properties)}}class gf{constructor(e){var s;this._s=[],this._instance=e,this.ws=new Map,this.ks=new Map,this.xs=new Map,(s=this._instance)==null||s.onSessionId==null||s.onSessionId((r=>this.Ss(r)))}Cs(e){return!1}Ms(){return null}Ts(e){}Es(){}Is(e,s){return!!e&&sd(e.propertyFilters,s?.properties)}Ps(e,s){var r=new Map;return e.forEach((n=>{var i;(i=n.conditions)==null||(i=i[s])==null||(i=i.values)==null||i.forEach((o=>{if(o!=null&&o.name){var a=r.get(o.name)||[];a.push(n.id),r.set(o.name,a)}}))})),r}Rs(e,s,r){var n=(r===As.Activation?this.ws:this.ks).get(e),i=[];return this.As((o=>{i=o.filter((a=>n?.includes(a.id)))})),i.filter((o=>{var a,l=(a=o.conditions)==null||(a=a[r])==null||(a=a.values)==null?void 0:a.find((u=>u.name===e));return this.Is(l,s)}))}register(e){var s;x((s=this._instance)==null?void 0:s._addCaptureHook)||(this.Fs(e),this.Ls(e))}Ls(e){var s=e.filter((r=>{var n,i;return((n=r.conditions)==null?void 0:n.actions)&&((i=r.conditions)==null||(i=i.actions)==null||(i=i.values)==null?void 0:i.length)>0}));s.length!==0&&(this.Os==null&&(this.Os=new ff(this._instance),this.Os.init(),this.Os.fs((r=>{this.onAction(r)}))),s.forEach((r=>{var n,i,o,a,l;r.conditions&&(n=r.conditions)!=null&&n.actions&&(i=r.conditions)!=null&&(i=i.actions)!=null&&i.values&&((o=r.conditions)==null||(o=o.actions)==null||(o=o.values)==null?void 0:o.length)>0&&((a=this.Os)==null||a.register(r.conditions.actions.values),(l=r.conditions)==null||(l=l.actions)==null||(l=l.values)==null||l.forEach((u=>{if(u&&u.name){var c=this.xs.get(u.name);c&&c.push(r.id),this.xs.set(u.name,c||[r.id])}})))})))}Fs(e){var s,r=e.filter((i=>{var o,a;return((o=i.conditions)==null?void 0:o.events)&&((a=i.conditions)==null||(a=a.events)==null||(a=a.values)==null?void 0:a.length)>0})),n=e.filter((i=>{var o,a;return((o=i.conditions)==null?void 0:o.cancelEvents)&&((a=i.conditions)==null||(a=a.cancelEvents)==null||(a=a.values)==null?void 0:a.length)>0}));r.length===0&&n.length===0||((s=this._instance)==null||s._addCaptureHook(((i,o)=>{this.onEvent(i,o)})),this.ws=this.Ps(e,As.Activation),this.ks=this.Ps(e,As.Cancellation))}onEvent(e,s){var r,n,i=this.Ds(),o=(s==null||(r=s.properties)==null?void 0:r.$survey_id)||(s==null||(n=s.properties)==null?void 0:n.$product_tour_id);if(o&&this.getActivatedIds().includes(o)){var a=this.$s(e,o);if(a==="consume")return i.info("event consumed activated item, removing it",{event:e,itemId:o}),void this.Ns([o]);if(a==="persist")return i.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,s,As.Cancellation);l.length>0&&(i.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)){i.info("event name matched",{event:e,eventPayload:s,items:this.ws.get(e)});var u=this.Rs(e,s,As.Activation);this.Hs(u.map((c=>c.id)))}}onAction(e){this.xs.has(e)&&this.Hs(this.xs.get(e)||[])}Hs(e){var s;if(e.length!==0){var r=!((s=this._instance)==null||s.get_session_id==null||!s.get_session_id()),n=[];for(var i of e)r&&this.Cs(i)?this.qs(i)&&this.Us(i):n.push(i);n.length>0&&(this._s=[...new Set([...this._s,...n])]),this.Ds().info("updating activated items",{activatedItems:this.getActivatedIds()})}}qs(e){this._s=this._s.filter((r=>r!==e));var s=this.zs();return!s.includes(e)&&(this.Ws([...s,e]),this.Vs(),!0)}Ns(e){var s=new Set(e);this._s=this._s.filter((i=>!s.has(i)));var r=this.Zs(),n=r.filter((i=>!s.has(i)));n.length!==r.length&&(this.Ws(n),n.length===0&&this.Gs()),this.js(e)}Qs(){var e,s=this.Ms();if(!s)return{};var r=(e=this._instance)==null||(e=e.persistence)==null?void 0:e.props[s];return r&&typeof r=="object"?r:{}}Us(e){if(this.Ms()){var s=this.Qs();this.Ts(b({},s,{[e]:Date.now()}))}}js(e){if(this.Ms()){var s=this.Qs(),r={},n=!1;for(var i of Object.entries(s)){var o=i[0],a=i[1];e.includes(o)?n=!0:r[o]=a}n&&(mt(r)?this.Es():this.Ts(r))}}Ks(){this.Ms()&&this.Es()}getActivationTimestamp(e){if(this.zs().includes(e)){var s=this.Qs()[e];return he(s)?s:void 0}}Zs(){var e,s=this.Js();return((e=this._instance)==null||(e=e.persistence)==null?void 0:e.props[s])||[]}zs(){var e,s,r=this.Zs();if(r.length===0)return[];var n=(e=this._instance)==null||(e=e.persistence)==null?void 0:e.props[this.Ys()],i=(s=this._instance)==null||s.get_session_id==null?void 0:s.get_session_id();return i&&n===i?r:[]}Vs(){var e,s=(e=this._instance)==null||e.get_session_id==null?void 0:e.get_session_id();s&&this.Xs(s)}Gs(){this.ta()}Ss(e){var s,r=(s=this._instance)==null||(s=s.persistence)==null?void 0:s.props[this.Ys()];if(r&&r!==e){var n=this.Zs(),i=this.Qs();n.length>0&&(this.Ws([]),n.filter((o=>he(i[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 mf extends gf{constructor(e){super(e)}Js(){return Yi}Ys(){return Nr}Ms(){return Mr}Ts(e){var s;(s=this._instance)==null||(s=s.persistence)==null||s.register({[Mr]:e})}Es(){var e;(e=this._instance)==null||(e=e.persistence)==null||e.unregister(Mr)}Cs(e){var s,r;this.As((i=>{r=i.find((o=>o.id===e))}));var n=(s=r)==null||(s=s.appearance)==null?void 0:s.surveyPopupDelaySeconds;return he(n)&&n>0}ra(){return ft.SHOWN}As(e){var s;(s=this._instance)==null||s.getSurveys(e)}Bs(e){var s;(s=this._instance)==null||s.cancelPendingSurvey(e)}Ds(){return q}Ws(e){var s;(s=this._instance)==null||(s=s.persistence)==null||s.register({[Yi]:e})}Xs(e){var s;(s=this._instance)==null||(s=s.persistence)==null||s.register({[Nr]:e})}ta(){var e;(e=this._instance)==null||(e=e.persistence)==null||e.unregister(Nr)}ea(){return!1}$s(e,s){var r;this.As((i=>{r=i.find((o=>o.id===s))}));var n=!r||(function(i){var o;return rd(i)&&!((o=i.conditions)==null||(o=o.events)==null||!o.repeatedActivation)||i.schedule==="always"})(r);return n?e===ft.SHOWN?"consume":"ignore":e===ft.SHOWN?"persist":e===ft.DISMISSED||e===ft.SENT?"consume":"ignore"}getSurveys(){return this.getActivatedIds()}getEventToSurveys(){return this.getEventToItemsMap()}}var Ar="SDK is not enabled or survey functionality is not yet loaded",Ll="Disabled. Not loading surveys.",vf=v!=null&&v.location?un(v.location.hash,"__posthog")||un(location.hash,"state"):null,Ol="_postHogToolbarParams",Dl=se("[Toolbar]"),Bl=se("[FeatureFlags]");class _f{constructor(e,s){s===void 0&&(s=!1),this.na=!1,this.update(e,s)}update(e,s){this.sa=((r,n)=>{var i,o,a,l;return{bootstrap:{featureFlags:(i=r.bootstrap)==null?void 0:i.featureFlags,featureFlagPayloads:(o=r.bootstrap)==null?void 0:o.featureFlagPayloads},remoteRequestsDisabled:n,featureFlagsDisabled:!!r.advanced_disable_feature_flags,onlyEvaluateSurveyFeatureFlags:!!r.advanced_only_evaluate_survey_feature_flags,deduplicateCallsPerSession:!!r.advanced_feature_flags_dedup_per_session,cacheTtlMs:r.feature_flag_cache_ttl_ms,requestTimeoutMs:r.feature_flag_request_timeout_ms,compression:r.disable_compression?"none":"base64",evaluationContexts:(a=(l=r.evaluation_contexts)!==null&&l!==void 0?l:r.evaluation_environments)!==null&&a!==void 0?a:[],flagKeys:L(r.flag_keys)?r.flag_keys:void 0}})(e,s),!e.evaluation_environments||e.evaluation_contexts||this.na||(Bl.warn("evaluation_environments is deprecated. Use evaluation_contexts instead. evaluation_environments will be removed in a future version."),this.na=!0),x(e.flag_keys)||L(e.flag_keys)||Bl.error("Invalid flag_keys found:",e.flag_keys,"Expected array of non-empty strings")}get(){return this.sa}}var jl=se("[FeatureFlags]"),Ot=se("[FeatureFlags]",{debugEnabled:!0}),xi=`" failed. Feature flags didn't load in time.`,Ul="connection_error",Hl=t=>{for(var e={},s=0;t.length>s;s++)e[t[s]]=!0;return e},Wl=t=>{var e={};for(var s of Or(t||{})){var r=s[1];r&&(e[s[0]]=r)}return e},Xe=se("[Error tracking]"),zl="Refusing to render web experiment since the viewer is a likely bot",yf={icontains:(t,e)=>e.toLowerCase().indexOf(t.toLowerCase())>-1,not_icontains:(t,e)=>e.toLowerCase().indexOf(t.toLowerCase())===-1,regex:(t,e)=>pn(e,t),not_regex:(t,e)=>!pn(e,t),exact:(t,e)=>e===t,is_not:(t,e)=>e!==t};class ye{get Ne(){return this._instance.config}constructor(e){var s=this;this.getWebExperimentsAndEvaluateDisplayLogic=function(r){r===void 0&&(r=!1),s.getWebExperiments((n=>{ye.aa("retrieved web experiments from the server"),s.oa=new Map,n.forEach((i=>{if(i.feature_flag_key){var o;s.oa&&(ye.aa("setting flag key ",i.feature_flag_key," to web experiment ",i),(o=s.oa)==null||o.set(i.feature_flag_key,i));var a=s._instance.getFeatureFlag(i.feature_flag_key);W(a)&&i.variants[a]&&s.la(i.name,a,i.variants[a].transforms)}else if(i.variants)for(var l in i.variants){var u=i.variants[l];ye.ua(u,s._instance)&&s.la(i.name,l,u.transforms)}}))}),r)},this._instance=e,this._instance.onFeatureFlags((r=>{this.onFeatureFlags(r)}))}initialize(){}onFeatureFlags(e){if(this._is_bot())ye.aa(zl);else if(!this.Ne.disable_web_experiments){if(D(this.oa))return this.oa=new Map,this.loadIfEnabled(),void this.previewWebExperiment();ye.aa("applying feature flags",e),e.forEach((s=>{var r;if(this.oa&&(r=this.oa)!=null&&r.has(s)){var n,i=this._instance.getFeatureFlag(s),o=(n=this.oa)==null?void 0:n.get(s);i&&o!=null&&o.variants[i]&&this.la(o.name,i,o.variants[i].transforms)}}))}}previewWebExperiment(){var e=ye.getWindowLocation();if(e!=null&&e.search){var s=ms(e?.search,"__experiment_id"),r=ms(e?.search,"__experiment_variant");s&&r&&(ye.aa("previewing web experiments "+s+" && "+r),this.getWebExperiments((n=>{this.ha(parseInt(s),r,n)}),!1,!0))}}loadIfEnabled(){this.Ne.disable_web_experiments||this.getWebExperimentsAndEvaluateDisplayLogic()}getWebExperiments(e,s,r){if(this.Ne.disable_web_experiments&&!r)return e([]);var n=this._instance.get_property("$web_experiments");if(n&&!s)return e(n);this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/web_experiments/?token="+this.Ne.token),method:"GET",timestampMode:"query",callback:i=>e(i.statusCode===200&&i.json&&i.json.experiments||[])})}ha(e,s,r){var n=r.filter((i=>i.id===e));n&&n.length>0&&(ye.aa("Previewing web experiment ["+n[0].name+"] with variant ["+s+"]"),this.la(n[0].name,s,n[0].variants[s].transforms))}static ua(e,s){return!D(e.conditions)&&ye.da(e,s)&&ye.va(e)}static da(e,s){var r;if(D(e.conditions)||D((r=e.conditions)==null?void 0:r.url))return!0;var n=ye.getWindowLocation();if(n){var i,o,a,l=yu(s,n.href);return(i=e.conditions)==null||!i.url||yf[(o=(a=e.conditions)==null?void 0:a.urlMatchType)!==null&&o!==void 0?o:"icontains"](e.conditions.url,l)}return!1}static getWindowLocation(){return v?.location}static va(e){var s;if(D(e.conditions)||D((s=e.conditions)==null?void 0:s.utm))return!0;var r=Nu();if(r.utm_source){var n,i,o,a,l,u,c,d,h=(n=e.conditions)==null||(n=n.utm)==null||!n.utm_campaign||((i=e.conditions)==null||(i=i.utm)==null?void 0:i.utm_campaign)==r.utm_campaign,p=(o=e.conditions)==null||(o=o.utm)==null||!o.utm_source||((a=e.conditions)==null||(a=a.utm)==null?void 0:a.utm_source)==r.utm_source,f=(l=e.conditions)==null||(l=l.utm)==null||!l.utm_medium||((u=e.conditions)==null||(u=u.utm)==null?void 0:u.utm_medium)==r.utm_medium,g=(c=e.conditions)==null||(c=c.utm)==null||!c.utm_term||((d=e.conditions)==null||(d=d.utm)==null?void 0:d.utm_term)==r.utm_term;return h&&f&&g&&p}return!1}static aa(e){for(var s=arguments.length,r=new Array(s>1?s-1:0),n=1;s>n;n++)r[n-1]=arguments[n];k.info("[WebExperiments] "+e,r)}la(e,s,r){this._is_bot()?ye.aa(zl):s!=="control"?r.forEach((n=>{if(n.selector){var i;ye.aa("applying transform of variant "+s+" for experiment "+e+" ",n);var o=(i=document)==null?void 0:i.querySelectorAll(n.selector);o?.forEach((a=>{var l=a;n.html&&(l.innerHTML=n.html),n.css&&l.setAttribute("style",n.css)}))}})):ye.aa("Control variants leave the page unmodified.")}_is_bot(){return ke&&this._instance?Qu(ke,this.Ne.custom_blocked_useragents):void 0}}var Ue=se("[Conversations]"),Dt="Conversations not available yet.",ql="console",ld="__posthogHandledLogsRequestError",ki=(t,e)=>{var s=t instanceof Error?t:new Error(e);return s[ld]=!0,s},Vl=t=>!!t&&typeof t=="object"&&t[ld]===!0,Rn={featureFlags:class{constructor(t){this.name="featureFlags",this.ca=!1,this.featureFlagEventHandlers=[],this.rt=jl,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 _f(t.config,t.Qi()),this.Ta=this.Ea)}updateConfig(t,e){var s;(s=this.Ea)==null||s.update(t,e)}setup(t){return this.Ia=t,this.rt=t.logger.createLogger("[FeatureFlags]"),s=()=>{this.Ia===t&&(this.Ia=void 0,this.nn=t,this.Pa(t))},(e=t.kv.initialize())!=null&&e.then?e.then(s):s();var e,s}Pa(t){if(this.nn===t)return v&&ne(v,"online",this.Ca),this.Ra=t.registerDynamicEventProperties((()=>this.Aa()?this.fa:this.pa)),this.Fa(),this.initialize()}destroy(){v?.removeEventListener("online",this.Ca)}dispose(){var t;this.ba++,this.wa=!1,this.Ia=void 0,this.nn&&(this.La(),(t=this.Ra)==null||t.dispose(),this.Ra=void 0,this.ga=[],v?.removeEventListener("online",this.Ca),this.nn=void 0)}get Ne(){return this.Ta.get()}Oa(t){var e;return(e=this.nn)==null?void 0:e.kv.get(t)}F(t){this.Da((()=>{var e;return(e=this.nn)==null?void 0:e.kv.set(t)}))}q(t){this.Da((()=>{var e;return(e=this.nn)==null?void 0:e.kv.remove(t)}))}Da(t){try{t()}catch(e){this.rt.error("Failed to update feature flag persistence",e)}}Fa(){var t={};for(var e of[Us,Hs,Tr,et]){var s=this.Oa(e);x(s)||(t[e]=s)}this.fa=t;var r=b({},t),n=this.Oa(Bt);if(n)for(var i of Object.entries(n))r["$feature/"+i[0]]=i[1];this.pa=r}Aa(){var t=this.Ne.cacheTtlMs;if(!t||0>=t)return!1;var e=this.Oa(Gs);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 s=e&&typeof e=="string"&&e.trim().length>0;return s||this.rt.error("Invalid evaluation context found:",e,"Expected non-empty string"),s})):[]}qa(){var t=this.Ne.flagKeys;if(!x(t))return t.filter((e=>{var s=e&&typeof e=="string"&&e.trim().length>0;return s||this.rt.error("Invalid flag key found:",e,"Expected non-empty string"),s}))}initialize(){var t,e,s=this.Ne,r=(t=(e=s.bootstrap)==null?void 0:e.featureFlags)!==null&&t!==void 0?t:{};if(Object.keys(r).length){var n,i,o=(n=(i=s.bootstrap)==null?void 0:i.featureFlagPayloads)!==null&&n!==void 0?n:{},a=Object.keys(r).filter((u=>!!r[u])).reduce(((u,c)=>(u[c]=r[c]||!1,u)),{}),l=Object.keys(o).filter((u=>a[u])).reduce(((u,c)=>(o[c]&&(u[c]=o[c]),u)),{});return this.ja({featureFlags:a,featureFlagPayloads:l})}}updateFlags(t,e,s){var r,n,i=s!=null&&s.merge&&(r=this.Oa(Bt))!==null&&r!==void 0?r:{},o=s!=null&&s.merge&&(n=this.Oa(Hs))!==null&&n!==void 0?n:{},a=b({},i,t),l=b({},o,e),u={};for(var c of Object.entries(a)){var d=c[0],h=c[1];u[d]={key:d,enabled:Da(h),variant:Ba(h),reason:void 0,metadata:x(l?.[d])?void 0:{id:0,version:void 0,description:void 0,payload:l[d]}}}this.ja({flags:u})}get hasLoadedFlags(){return this.ma}getFlags(){return Object.keys(this.getFlagVariants())}getFlagsWithDetails(){var t=this.Oa(Ki),e=this.Oa(et),s=this.Oa(jt);if(!s&&!e)return t||{};var r=ee({},t||{}),n=[...new Set([...Object.keys(s||{}),...Object.keys(e||{})])];for(var i of n){var o,a,l=r[i],u=e?.[i],c=x(u)?(o=l?.enabled)!==null&&o!==void 0&&o:!!u,d=x(u)?l?.variant:typeof u=="string"?u:void 0,h=s?.[i],p=b({},l,{enabled:c,variant:c?d??l?.variant:void 0});c!==l?.enabled&&(p.original_enabled=l?.enabled),d!==l?.variant&&(p.original_variant=l?.variant),h&&(p.metadata=b({},l?.metadata,{payload:h,original_payload:l==null||(a=l.metadata)==null?void 0:a.payload})),r[i]=p}return this.ca||(this.rt.warn(" Overriding feature flag details!",{flagDetails:t,overriddenPayloads:s,finalDetails:r}),this.ca=!0),r}getAllFeatureFlags(){var t=this.getFlagVariants(),e=this.getFlagPayloads();return Object.keys(t).map((s=>{var r=t[s];return{key:s,enabled:Da(r),variant:Ba(r),payload:Oa(e[s])}}))}getFlagVariants(){var t=this.Oa(Bt),e=this.Oa(et);if(!e)return t||{};for(var s=ee({},t||{}),r=Object.keys(e),n=0;r.length>n;n++)s[r[n]]=e[r[n]];return this.ca||(this.rt.warn(" Overriding feature flags!",{enabledFlags:t,overriddenFlags:e,finalFlags:s}),this.ca=!0),s}getFlagPayloads(){var t=this.Oa(Hs),e=this.Oa(jt);if(!e)return t||{};for(var s=ee({},t||{}),r=Object.keys(e),n=0;r.length>n;n++)s[r[n]]=e[r[n]];return this.ca||(this.rt.warn(" Overriding feature flag payloads!",{flagPayloads:t,overriddenPayloads:e,finalPayloads:s}),this.ca=!0),s}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(Wt)}Ha(t){this.La();var e=this.nn;if(e&&!this.Ne.remoteRequestsDisabled&&!this.Ma())if(this.ya)this.wa=!0;else{var s={token:e.projectToken,distinct_id:e.distinctId,groups:e.groups,$anon_distinct_id:this.$anon_distinct_id,person_properties:b({},e.initialPersonProperties,this.Oa(ct)||{},{$lib:e.library.name,$lib_version:e.library.version}),group_properties:this.Oa(Ut),timezone:ju()};x(e.deviceId)||(s.$device_id=e.deviceId),(t!=null&&t.disableFlags||this.Ne.featureFlagsDisabled)&&(s.disable_flags=!0);var r=this.Na();r.length&&(s.evaluation_contexts=r);var n=this.qa();x(n)||(s.flag_keys=n);var i=this.Ne.onlyEvaluateSurveyFeatureFlags,o="/flags/?v=2"+(i?"&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({[Lr]:[Ul]}),this.rt.error("Feature flag request failed",c)),l()};try{e.sendRequest(o,{target:"flags",method:"POST",body:s,compression:this.Ne.compression==="base64"?xe.Base64:void 0,sentAt:"body",timeoutMs:this.Ne.requestTimeoutMs}).then((c=>{var d,h,p=(d=c.json)!==null&&d!==void 0?d:{},f=c.statusCode!==200;if(this.ya=!1,a===this.ba){if(this.Ua(c.statusCode),f||this.wa||(this.$anon_distinct_id=void 0),!s.disable_flags||this.wa){this.ka=!f;var g=[];c.error?g.push(c.error instanceof Error&&c.error.name==="AbortError"?"timeout":c.error instanceof Error?Ul:"unknown_error"):c.statusCode!==200&&g.push("api_error_"+c.statusCode),p.errorsWhileComputingFlags&&g.push("errors_while_computing_flags");var m=!((h=p.quotaLimited)==null||!h.includes("feature_flags"));m&&g.push("quota_limited"),this.F({[Lr]: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."):s.disable_flags||this.ja(p,f,{partialResponse:i}),l()}}else l()})).catch(u)}catch(c){u(c)}}}Ma(){return Ru(this.Sa,3)}Ua(t){this.Sa=Tu(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 s;if(e===void 0&&(e={}),!e.fresh||this.ka)if(this.ma||this.getFlags()&&this.getFlags().length>0){if(!this.$a()){var r=this.getFeatureFlagResult(t,e);return(s=r?.variant)!==null&&s!==void 0?s:r?.enabled}}else this.rt.warn('getFeatureFlag for key "'+t+xi)}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 s,r=this.getFlagVariants(),n=t in r,i=r[t],o=this.getFlagPayloads()[t],a=String(i),l=this.Oa(Tr)||void 0,u=this.Oa(Gs)||void 0,c=this.Oa(Wt)||{};if(this.Ne.deduplicateCallsPerSession){var d,h=(d=this.nn)==null?void 0:d.session.sessionId,p=this.Oa(zs);h&&h!==p&&(c={},s=h)}if(e.send_event||!("send_event"in e))if(t in c&&c[t].includes(a))s&&this.F({[Wt]:c,[zs]:s});else{var f,g,m,_,w,E,I,F,P,B;L(c[t])?c[t].push(a):c[t]=[a],this.F(b({[Wt]:c},s?{[zs]:s}:{}));var S=this.getFeatureFlagDetails(t),A=[...(f=this.Oa(Lr))!==null&&f!==void 0?f:[]];x(i)&&A.push("flag_missing");var R={$feature_flag:t,$feature_flag_response:i,$feature_flag_payload:o||null,$feature_flag_request_id:l,$feature_flag_evaluated_at:u,$feature_flag_bootstrapped_response:((g=this.Ne.bootstrap)==null||(g=g.featureFlags)==null?void 0:g[t])||null,$feature_flag_bootstrapped_payload:((m=this.Ne.bootstrap)==null||(m=m.featureFlagPayloads)==null?void 0:m[t])||null,$used_bootstrap_value:!this.ka};x(S==null||(_=S.metadata)==null?void 0:_.has_experiment)||(R.$feature_flag_has_experiment=S.metadata.has_experiment),x(S==null||(w=S.metadata)==null?void 0:w.version)||(R.$feature_flag_version=S.metadata.version);var N,T=(E=S==null||(I=S.reason)==null?void 0:I.description)!==null&&E!==void 0?E:S==null||(F=S.reason)==null?void 0:F.code;T&&(R.$feature_flag_reason=T),S!=null&&(P=S.metadata)!=null&&P.id&&(R.$feature_flag_id=S.metadata.id),x(S?.original_variant)&&x(S?.original_enabled)||(R.$feature_flag_original_response=x(S.original_variant)?S.original_enabled:S.original_variant),S!=null&&(B=S.metadata)!=null&&B.original_payload&&(R.$feature_flag_original_payload=S==null||(N=S.metadata)==null?void 0:N.original_payload),A.length&&(R.$feature_flag_error=A.join(",")),this.za(R)}else s&&this.F({[Wt]:c,[zs]:s});if(n)return{key:t,enabled:!!i,variant:typeof i=="string"?i:void 0,payload:Oa(o)}}}else this.rt.warn('getFeatureFlagResult for key "'+t+xi)}za(t){try{var e;(e=this.nn)==null||e.capture("$feature_flag_called",t).catch((s=>{this.rt.error("Failed to capture feature flag call",s)}))}catch(s){this.rt.error("Failed to capture feature flag call",s)}}getRemoteConfigPayload(t,e){this.Wa(t,e)}Wa(t,e){var s=this;return X((function*(){var r=s.nn;if(r){var n={distinct_id:r.distinctId,token:r.projectToken,person_properties:{$lib:r.library.name,$lib_version:r.library.version}},i=s.Na();i.length&&(n.evaluation_contexts=i);var o,a=s.qa();x(a)||(n.flag_keys=a);try{var l,u=(l=(yield r.sendRequest("/flags/?v=2",{target:"flags",method:"POST",body:n,compression:s.Ne.compression==="base64"?xe.Base64:void 0,sentAt:"body",timeoutMs:s.Ne.requestTimeoutMs})).json)==null?void 0:l.featureFlagPayloads;o=u?.[t]||void 0}catch(c){return void s.rt.error("Remote config feature flag request failed",c)}try{e(o)}catch(c){s.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+xi),e.defaultValue;var s=this.getFeatureFlag(t,e);return x(s)?e.defaultValue:!!s}addFeatureFlagsHandler(t){this.featureFlagEventHandlers.push(t)}removeFeatureFlagsHandler(t){this.featureFlagEventHandlers=this.featureFlagEventHandlers.filter((e=>e!==t))}receivedFeatureFlags(t,e,s){this.ja(t,e,s)}ja(t,e,s){if(this.nn){this.ma=!0;var r=(function(n,i,o,a,l,u){i===void 0&&(i={}),o===void 0&&(o={}),a===void 0&&(a={}),u===void 0&&(u=jl);var c=((P,B)=>{var S=P.flags;return S?b({},P,{featureFlags:Object.fromEntries(Object.keys(S).map((A=>{var R;return[A,(R=S[A].variant)!==null&&R!==void 0?R:S[A].enabled]}))),featureFlagPayloads:Object.fromEntries(Object.keys(S).filter((A=>S[A].enabled)).filter((A=>{var R;return(R=S[A].metadata)==null?void 0:R.payload})).map((A=>{var R;return[A,(R=S[A].metadata)==null?void 0:R.payload]})))}):(P.featureFlags&&B.warn("Using an older version of the feature flags endpoint. Please upgrade your PostHog server to the latest version"),P)})(n,u),d=c.flags,h=c.featureFlags,p=c.featureFlagPayloads;if(h){var f=n.requestId,g=n.evaluatedAt;if(L(h)){u.warn("v1 of the feature flags endpoint is deprecated. Please use the latest version.");var m={};if(h)for(var _=0;h.length>_;_++)m[h[_]]=!0;return{[Us]:h,[Bt]:m,[en]:!1}}var w=h,E=p,I=d;if(l!=null&&l.partialResponse)w=b({},i,w),E=b({},o,E),I=b({},a,I);else if(n.errorsWhileComputingFlags)if(d){var F=new Set(Object.keys(d).filter((P=>{var B;return!((B=d[P])!=null&&B.failed)})));w=b({},i,Object.fromEntries(Object.entries(w).filter((P=>F.has(P[0]))))),E=b({},o,Object.fromEntries(Object.entries(E||{}).filter((P=>F.has(P[0]))))),I=b({},a,Object.fromEntries(Object.entries(I||{}).filter((P=>F.has(P[0])))))}else w=b({},i,w),E=b({},o,E),I=b({},a,I);return b({[Us]:Object.keys(Wl(w)),[Bt]:w||{},[Hs]:E||{},[Ki]:I||{},[en]:n.minimalFlagCalledEvents===!0},f?{[Tr]:f}:{},g?{[Gs]:g}:{})}})(t,this.getFlagVariants(),this.getFlagPayloads(),this.getFlagsWithDetails(),s,this.rt);r&&this.F(r),e||(this.xa=!1),this.Va(e)}}override(t,e){e===void 0&&(e=!1),this.rt.warn("override is deprecated. Please use overrideFeatureFlags instead."),this.overrideFeatureFlags({flags:t,suppressWarning:e})}overrideFeatureFlags(t){this.Za(t)}Za(t){if(this.nn){if(t===!1)return this.q([et,jt]),this.Va(),void Ot.info("All overrides cleared");if(L(t))return this.F({[et]:Hl(t)}),this.Va(),void Ot.info("Flag overrides set",{flags:t});if(t&&typeof t=="object"&&("flags"in t||"payloads"in t)){var e,s=t;this.ca=!!((e=s.suppressWarning)!==null&&e!==void 0&&e);var r={},n=s.flags,i=s.payloads;return n&&(r[et]=L(n)?Hl(n):n),i&&(r[jt]=i),Object.keys(r).length&&this.F(r),n===!1&&i===!1?this.q([et,jt]):n===!1?this.q(et):i===!1&&this.q(jt),this.Va(),n===!1?Ot.info("Flag overrides cleared"):n&&Ot.info("Flag overrides set",{flags:n}),void(i===!1?Ot.info("Payload overrides cleared"):i&&Ot.info("Payload overrides set",{payloads:i}))}if(t&&typeof t=="object")return this.F({[et]:t}),this.Va(),void Ot.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(),s=e.flags,r=e.flagVariants;try{t(s,r)}catch(n){this.rt.error("Error while running feature flags callback",n)}}return()=>this.removeFeatureFlagsHandler(t)}updateEarlyAccessFeatureEnrollment(t,e,s){var r=(this.Oa(Rr)||[]).find((l=>l.flagKey===t)),n={["$feature_enrollment/"+t]:e},i={$feature_flag:t,$feature_enrollment:e,$set:n};r&&(i.$early_access_feature_name=r.name),s&&(i.$feature_enrollment_stage=s);var o=b({},this.getFlagVariants(),{[t]:e});this.F({[Us]:Object.keys(Wl(o)),[Bt]:o,[ct]:b({},this.Oa(ct)||{},n)}),this.Va();try{var a;(a=this.nn)==null||a.capture("$feature_enrollment_update",i).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,s){e===void 0&&(e=!1);var r=this.Oa(Rr);!r||e?this.Qa(t,s):t(r)}Qa(t,e){var s=this;return X((function*(){var r=s.nn;if(r){var n,i=e?"&"+e.map((a=>"stage="+a)).join("&"):"";try{var o=yield r.sendRequest("/api/early_access_features/?token="+r.projectToken+i,{target:"api",method:"GET",sentAt:"query"});if(!o.json)return;s.F({[Rr]:n=o.json.earlyAccessFeatures})}catch(a){return void s.rt.error("Early access feature request failed",a)}try{t(n)}catch(a){s.rt.error("Early access feature callback failed",a)}}}))()}Ga(){var t=this.getFlags(),e=this.getFlagVariants();return{flags:t.filter((s=>e[s])),flagVariants:Object.keys(e).filter((s=>e[s])).reduce(((s,r)=>(s[r]=e[r],s)),{})}}Va(t){this.Fa();var e=this.Ga(),s=e.flags,r=e.flagVariants;this.featureFlagEventHandlers.forEach((n=>{try{n(s,r,{errorsLoading:t})}catch(i){this.rt.error("Error while running feature flags callback",i)}}))}setPersonPropertiesForFlags(t,e){e===void 0&&(e=!0),this.Ka(t,e)}Ka(t,e){e===void 0&&(e=!0);var s=this.Oa(ct)||{},r=t?.$set||(t!=null&&t.$set_once?{}:t),n=t?.$set_once,i={};if(n)for(var o in n)({}).hasOwnProperty.call(n,o)&&(o in s||(i[o]=n[o]));this.F({[ct]:b({},s,i,r)}),e&&this.reloadFeatureFlags()}unsetPersonPropertiesForFlags(t,e){e===void 0&&(e=!0);var s=b({},this.Oa(ct)||{});t.forEach((r=>{delete s[r]})),this.F({[ct]:s}),e&&this.reloadFeatureFlags()}resetPersonPropertiesForFlags(t){t===void 0&&(t=!0),this.q(ct),t&&this.reloadFeatureFlags()}setGroupPropertiesForFlags(t,e){e===void 0&&(e=!0);var s=this.Oa(Ut)||{},r=b({},s);for(var n of Object.keys(t))r[n]=b({},s[n],t[n]);this.F({[Ut]:r}),e&&this.reloadFeatureFlags()}resetGroupPropertiesForFlags(t){if(t){var e=this.Oa(Ut)||{};this.F({[Ut]:b({},e,{[t]:{}})})}else this.q(Ut)}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}}},wf={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===Ls||this.Ya===Fr?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=Tl,this.Xa=void 0,this.eo=!1,this.io=(()=>{var e;if(C==null||!C.visibilityState||C.visibilityState==="visible")return!0;var s=v==null||(e=v.performance)==null||e.getEntriesByType==null?void 0:e.getEntriesByType("visibility-state");return!(s!=null&&s.length)||s.some((r=>r.name==="visible"))})(),this.Ie=()=>{var e;C?.visibilityState==="visible"&&(this.io=!0,(e=this.Ja)==null||e.setDocumentWasEverVisible==null||e.setDocumentWasEverVisible(!0))},this._instance=t,!this._instance.sessionManager)throw at.error("started without valid sessionManager"),new Error(po+" started without valid sessionManager. This is a bug.");if(this.Ne.cookieless_mode===ht)throw new Error(po+' cannot be used with cookieless_mode="always"');C!=null&&C.addEventListener&&ne(C,"visibilitychange",this.Ie)}initialize(){this.startIfEnabledOrStop()}dispose(){this.eo=!0,C==null||C.removeEventListener==null||C.removeEventListener("visibilitychange",this.Ie),this.stopRecording()}get ro(){var t,e=!((t=this._instance.get_property(qt))==null||!t.enabled),s=!this.Ne.disable_session_recording,r=this.Ne.disable_session_recording||this._instance.consent.isOptedOut();return v&&e&&s&&!r}startIfEnabledOrStop(t){var e;if(!(this.eo||this.ro&&(e=this.Ja)!=null&&e.isStarted)){var s=!x(Object.assign)&&!x(Array.from);this.ro&&s?(this.no(t),at.info("starting")):(this.Ya=Tl,this.stopRecording())}}no(t){var e,s,r;this.ro&&(this.Ya!==Ls&&this.Ya!==Fr&&(this.Ya=Nl),$!=null&&(e=$.__PosthogExtensions__)!=null&&(e=e.rrweb)!=null&&e.record&&(s=$.__PosthogExtensions__)!=null&&s.initSessionRecording?this.so(t):(r=$.__PosthogExtensions__)==null||r.loadExternalDependency==null||r.loadExternalDependency(this._instance,this.ao,(n=>{if(n)return at.error("could not load recorder",n);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(zo),(e=this.Mr)==null||e.unregister(lu)}uo(t,e){if(D(t))return null;var s,r=he(t)?t:parseFloat(t);return typeof(s=r)!="number"||!Number.isFinite(s)||0>s||s>1?(at.warn(e+" must be between 0 and 1. Ignoring invalid value:",t),null):r}ho(t){if(this.Mr){var e,s,r=this.Mr,n=()=>{var i,o=t.sessionRecording===!1?void 0:t.sessionRecording,a=this.uo((i=this.Ne.session_recording)==null?void 0:i.sampleRate,"session_recording.sampleRate"),l=this.uo(o?.sampleRate,"remote config sampleRate"),u=a??l;D(u)&&this.lo();var c=o?.minimumDurationMilliseconds;r.register({[qt]:b({cache_timestamp:Date.now(),enabled:!!o},o,{networkPayloadCapture:b({capturePerformance:t.capturePerformance},o?.networkPayloadCapture),canvasRecording:{enabled:o?.recordCanvas,fps:o?.canvasFps,quality:o?.canvasQuality},sampleRate:u,minimumDurationMilliseconds:x(c)?null:c,endpoint:o?.endpoint,triggerMatchType:o?.triggerMatchType,masking:o?.masking,urlTriggers:o?.urlTriggers,version:o?.version,triggerGroups:o?.triggerGroups})})};n(),(e=this.Xa)==null||e.call(this),this.Xa=(s=this._instance.sessionManager)==null?void 0:s.onSessionId(n)}}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===Ls&&(this.Ya=Fr,at.warn("config refresh failed, recording will not start until page reload")),void this.startIfEnabledOrStop())}log(t,e){var s;e===void 0&&(e="log"),(s=this.Ja)!=null&&s.log?this.Ja.log(t,e):at.warn("log called before recorder was ready")}get ao(){var t,e,s=(t=this._instance)==null||(t=t.persistence)==null?void 0:t.get_property(qt);return(s==null||(e=s.scriptConfig)==null?void 0:e.script)||"lazy-recorder"}do(){var t,e=this._instance.get_property(qt);if(!e)return!1;try{t=typeof e=="object"?e:JSON.parse(e)}catch(s){return at.warn("persisted remote config for session recording is invalid and will be ignored",s),!1}return!D(t.cache_timestamp)&&36e5>=Date.now()-t.cache_timestamp}so(t){var e,s,r;if(!this.eo){if((e=$.__PosthogExtensions__)==null||!e.initSessionRecording)return at.warn("Called on script loaded before session recording is available. This can be caused by adblockers."),void this._instance.register_for_session({[mu]:!0});var n;if(this.Ja||(this.Ja=(n=$.__PosthogExtensions__)==null?void 0:n.initSessionRecording(this._instance,this.io),this.Ja._forceAllowLocalhostNetworkCapture=this._forceAllowLocalhostNetworkCapture),!this.do())return this.Ya===Fr||this.Ya===Ls?void 0:(this.Ya=Ls,at.info("persisted remote config is stale, requesting fresh config before starting"),void new Uu(this._instance).load());this.Ya=Nl,(s=(r=this.Ja).setDocumentWasEverVisible)==null||s.call(r,this.io),this.Ja.start(t)}}onRRwebEmit(t){var e;(e=this.Ja)==null||e.onRRwebEmit==null||e.onRRwebEmit(t)}overrideLinkedFlag(){var t,e;this.Ja||(e=this.Mr)==null||e.register({[uu]:!0}),(t=this.Ja)==null||t.overrideLinkedFlag()}overrideSampling(){var t,e;this.Ja||(e=this.Mr)==null||e.register({[cu]:!0}),(t=this.Ja)==null||t.overrideSampling()}overrideTrigger(t){var e,s;this.Ja||(s=this.Mr)==null||s.register({[t==="url"?du:hu]:!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 s;return!((s=this.Ja)==null||!s.tryAddCustomEvent(t,e))}}},bf={autocapture:class{constructor(t){this.vo=!1,this.co=null,this.fo=!1,this.po=!1,this.instance=t,this.rageclicks=new Al(t.config.rageclick),this.mo=null}initialize(){this.startIfEnabled()}get Ne(){var t,e,s=te(this.instance.config.autocapture)?this.instance.config.autocapture:{};return s.url_allowlist=(t=s.url_allowlist)==null?void 0:t.map((r=>new RegExp(r))),s.url_ignorelist=(e=s.url_ignorelist)==null?void 0:e.map((r=>new RegExp(r))),s}yo(){if(this.isBrowserSupported()){if(v&&C){var t=s=>{s=s||v?.event;try{this.bo(s)}catch(r){wi.error("Failed to capture event",r)}};if(ne(C,"submit",t,{capture:!0}),ne(C,"change",t,{capture:!0}),ne(C,"click",t,{capture:!0}),this.Ne.capture_copied_text){var e=s=>{s=s||v?.event;try{this.bo(s,yi)}catch(r){wi.error("Failed to capture copy/cut event",r)}};ne(C,"copy",e,{capture:!0}),ne(C,"cut",e,{capture:!0})}}}else wi.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 s=e.autocapture_opt_out;Ke(s)&&(this.instance.persistence&&this.instance.persistence.register({[Ui]:s}),this.co=s),this.startIfEnabled()}else this.startIfEnabled()}setElementSelectors(t){this.mo=t}getElementSelectors(t){var e,s=[];return(e=this.mo)==null||e.forEach((r=>{var n=C?.querySelectorAll(r);n?.forEach((i=>{t===i&&s.push(r)}))})),s}get isEnabled(){var t,e,s=(t=this.instance.persistence)==null?void 0:t.props[Ui],r=this.co,n=this.instance.Qi()&&!this.fo;if($e(r)&&!Ke(s)&&!n)return!1;var i=(e=this.co)!==null&&e!==void 0?e:!!s;return!!this.instance.config.autocapture&&!i}bo(t,e){if(e===void 0&&(e="$autocapture"),this.isEnabled){var s,r=ai(t);bu(r)&&(r=r.parentNode||null),e==="$autocapture"&&t.type==="click"&&t instanceof MouseEvent&&this.instance.config.rageclick&&(s=this.rageclicks)!=null&&s.isRageClick(t.clientX,t.clientY,t.timeStamp||new Date().getTime())&&ol(r,this.instance.config.rageclick)&&this.bo(t,"$rageclick");var n=e===yi;if(r&&(function(d,h,p,f,g,m){var _;if(!v||Jo(d)||p!=null&&p.url_allowlist&&!rl(p.url_allowlist,m)||p!=null&&p.url_ignorelist&&rl(p.url_ignorelist,m))return!1;if(p!=null&&p.dom_event_allowlist){var w=p.dom_event_allowlist;if(w&&!w.some((S=>h.type===S)))return!1}var E=Cu(d,f),I=E.parentIsUsefulElement,F=E.targetElementList;if(!(function(S,A){var R=A?.element_allowlist;if(x(R))return!0;var N,T=function(J){if(R.some((z=>J.tagName.toLowerCase()===z)))return{v:!0}};for(var O of S)if(N=T(O))return N.v;return!1})(F,p)||!ro(F,p?.css_selector_allowlist)||ro(F,(_=p?.css_selector_ignorelist)!==null&&_!==void 0?_:vp))return!1;try{var P=v.getComputedStyle(d);if(P&&P.getPropertyValue("cursor")==="pointer"&&h.type==="click")return!0}catch{}var B=d.tagName.toLowerCase();switch(B){case"html":return!1;case"form":return(g||["submit"]).indexOf(h.type)>=0;case"input":case"select":case"textarea":return(g||["change","click"]).indexOf(h.type)>=0;default:return I?(g||["click"]).indexOf(h.type)>=0:(g||["click"]).indexOf(h.type)>=0&&(Ko.indexOf(B)>-1||d.getAttribute("contenteditable")==="true")}})(r,t,this.Ne,n,n?["copy","cut"]:void 0,this.instance)){var i=uf(r,{e:t,maskAllElementAttributes:this.instance.config.mask_all_element_attributes,maskAllText:this.instance.config.mask_all_text,elementAttributeIgnoreList:this.Ne.element_attribute_ignorelist,elementsChainAsString:this.po,disableCaptureUrlHashes:this.instance.config.disable_capture_url_hashes}),o=i.props;if(i.explicitNoCapture)return!1;var a=this.getElementSelectors(r);if(a&&a.length>0&&(o.$element_selectors=a),e===yi){var l,u=xu(v==null||(l=v.getSelection())==null?void 0:l.toString()),c=t.type||"clipboard";if(!u)return!1;o.$selected_content=u,o.$copy_type=c}return this.instance.capture(e,o),!0}}}isBrowserSupported(){return Se(C?.querySelectorAll)}},historyAutocapture:class{constructor(t){var e;this._instance=t,this._o=(v==null||(e=v.location)==null?void 0:e.pathname)||""}initialize(){this.startIfEnabled()}get isEnabled(){return this._instance.config.capture_pageview==="history_change"}startIfEnabled(){this.isEnabled&&(k.info("History API monitoring enabled, starting..."),this.monitorHistoryChanges())}stop(){this.wo&&this.wo(),this.wo=void 0,k.info("History API monitoring stopped")}monitorHistoryChanges(){v&&v.history&&(this.ko("pushState"),this.ko("replaceState"),this.xo())}ko(t){var e;if(v&&((e=v.history[t])==null||!e.__posthog_wrapped__)){var s=this;(function(r,n,i){try{if(!(n in r))return $l;var o={next:r[n]},a=i((function(){for(var l=arguments.length,u=new Array(l),c=0;l>c;c++)u[c]=arguments[c];return o.next.apply(this,u)}));return Se(a)&&(a.prototype=a.prototype||{},Object.defineProperties(a,{__posthog_wrapped__:{enumerable:!1,value:!0},__posthog_layer__:{enumerable:!1,value:o}})),r[n]=a,()=>{if(r[n]!==a)for(var l=r[n];Se(l)&&l.__posthog_layer__;){var u=l.__posthog_layer__;if(u.next===a)return void(u.next=o.next);l=u.next}else r[n]=o.next}}catch{return $l}})(v.history,t,(r=>function(n,i,o){r.call(this,n,i,o),s.So(t)}))}}So(t){try{var e,s=v==null||(e=v.location)==null?void 0:e.pathname;if(!s)return;s!==this._o&&this.isEnabled&&this._instance.capture(is,{navigation_type:t}),this._o=s}catch(r){k.error("Error capturing "+t+" pageview",r)}}xo(){if(!this.wo){var t=()=>{this.So("popstate")};ne(v,"popstate",t),this.wo=()=>{v&&v.removeEventListener("popstate",t)}}}},heatmaps:class{get Ne(){return this.instance.config}constructor(t){var e;this.Co=!1,this.vo=!1,this.Mo=null,this.instance=t,this.Co=!((e=this.instance.persistence)==null||!e.props[Hi]),this.rageclicks=new Al(t.config.rageclick)}initialize(){this.startIfEnabled()}get flushIntervalMilliseconds(){var t=5e3;return te(this.Ne.capture_heatmaps)&&this.Ne.capture_heatmaps.flush_interval_milliseconds&&(t=this.Ne.capture_heatmaps.flush_interval_milliseconds),t}get isEnabled(){return D(this.Ne.capture_heatmaps)?D(this.Ne.enable_heatmaps)?this.Co:this.Ne.enable_heatmaps:this.Ne.capture_heatmaps!==!1}startIfEnabled(){if(this.isEnabled){if(this.vo)return;hf.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 s=!!e.heatmaps;this.instance.persistence&&this.instance.persistence.register({[Hi]:s}),this.Co=s,this.startIfEnabled()}}}getAndClearBuffer(){var t=this.R;return this.R=void 0,t}Io(t){Ei(t.originalEvent)&&this.ke(t.originalEvent,"deadclick")}Ie(){this.Mo&&clearInterval(this.Mo),this.Mo=C?.visibilityState==="visible"?setInterval(this.cr.bind(this),this.flushIntervalMilliseconds):null}To(){v&&C&&(this.Po=this.cr.bind(this),ne(v,on,this.Po),this.Ro=t=>this.ke(t||v?.event),ne(C,"click",this.Ro,{capture:!0}),this.Ao=t=>this.Fo(t||v?.event),ne(C,"mousemove",this.Ao,{capture:!0}),this.Lo=new pl(this.instance,xp,this.Io.bind(this)),this.Lo.startIfEnabledOrStop(),this.Oo=this.Ie.bind(this),ne(C,nn,this.Oo),this.vo=!0)}Eo(){var t;v&&C&&(this.Po&&v.removeEventListener(on,this.Po),this.Ro&&C.removeEventListener("click",this.Ro,{capture:!0}),this.Ao&&C.removeEventListener("mousemove",this.Ao,{capture:!0}),this.Oo&&C.removeEventListener(nn,this.Oo),clearTimeout(this.Do),(t=this.Lo)==null||t.stop(),this.vo=!1)}$o(t,e){var s=this.instance.scrollManager.scrollY(),r=this.instance.scrollManager.scrollX(),n=this.instance.scrollManager.scrollElement(),i=(function(o,a,l){for(var u=o;u&&Ft(u)&&!Me(u,"body");){if(u===l)return!1;var c=void 0;try{var d,h,p;c=(d=(h=(p=u.ownerDocument)==null?void 0:p.defaultView)!==null&&h!==void 0?h:v)==null?void 0:d.getComputedStyle(u).position}catch{return!1}if(M(a,c))return!0;u=ku(u)}return!1})(ai(t),["fixed","sticky"],n);return{x:t.clientX+(i?0:r),y:t.clientY+(i?0:s),target_fixed:i,type:e}}ke(t,e){var s;if(e===void 0&&(e="click"),!sl(t.target)&&Ei(t)){var r=this.$o(t,e);(s=this.rageclicks)!=null&&s.isRageClick(t.clientX,t.clientY,new Date().getTime())&&ol(ai(t),this.instance.config.rageclick)&&this.Vt(b({},r,{type:"rageclick"})),this.Vt(r)}}Fo(t){!sl(t.target)&&Ei(t)&&(clearTimeout(this.Do),this.Do=setTimeout((()=>{this.Vt(this.$o(t,"mousemove"))}),500))}Vt(t){if(v){var e=this.Ne.disable_capture_url_hashes?Ct(v.location.href):v.location.href,s=this.Ne.custom_personal_data_properties,r=this.Ne.mask_personal_data_properties?[...vs,...s||[]]:[],n=nr(e,r,ir);this.R=this.R||{},this.R[n]||(this.R[n]=[]),this.R[n].push(t)}}cr(){this.R&&!mt(this.R)&&this.instance.capture("$$heatmap",{$heatmap_data:this.getAndClearBuffer()})}},deadClicksAutocapture:pl,webVitalsAutocapture:class{constructor(t){var e;this.Co=!1,this.vo=!1,this.R={navigationKey:void 0,url:void 0,metrics:[],firstMetricTimestamp:void 0},this.No=()=>{clearTimeout(this.qo),this.qo=void 0,this.R.metrics.length!==0&&(this._instance.capture("$web_vitals",b({$current_url:this.R.url},this.R.metrics.reduce(((s,r)=>b({},s,{["$web_vitals_"+r.name+"_event"]:b({},r),["$web_vitals_"+r.name+"_value"]:r.value})),{}))),this.R={navigationKey:void 0,url:void 0,metrics:[],firstMetricTimestamp:void 0})},this.jo=s=>{var r;if(this.R=this.R||{navigationKey:void 0,url:void 0,metrics:[],firstMetricTimestamp:void 0},D(s?.name)||D(s?.value))Lt.error("Invalid metric received",s);else{var n=typeof s.navigationURL=="string"?s.navigationURL:void 0,i=this.Bo(n);if(!x(i)){var o=he(s.navigationId)||typeof s.navigationId=="string"?"navigation:"+s.navigationId:"url:"+i;if(!this.Ho||this.Ho>s.value){this.R.navigationKey!==o&&(this.No(),this.qo=setTimeout(this.No,this.flushToCaptureTimeoutMs)),x(this.R.navigationKey)&&(this.R.navigationKey=o,this.R.url=i),this.R.firstMetricTimestamp=x(this.R.firstMetricTimestamp)?Date.now():this.R.firstMetricTimestamp,s.attribution&&s.attribution.interactionTargetElement&&(s.attribution.interactionTargetElement=void 0);var a=(r=this._instance.sessionManager)==null?void 0:r.checkAndGetSessionAndWindowId(!0),l=b({},s,n?{navigationURL:i}:{},{$current_url:i,timestamp:Date.now()});x(a)||(l.$session_id=a.sessionId,l.$window_id=a.windowId),this.R.metrics.push(l),this.R.metrics.length===this.allowedMetrics.length&&this.No()}else Lt.error("Ignoring metric with value >= "+this.Ho,s)}}},this.Uo=()=>{if(!this.vo){var s,r,n,i,o=$.__PosthogExtensions__,a=o?.postHogWebVitalsCallbacksByFlavor,l=a?.[this.zo]||(this.zo==="web-vitals"&&x(a)?o?.postHogWebVitalsCallbacks:void 0);if(x(l)||(s=l.onLCP,r=l.onCLS,n=l.onFCP,i=l.onINP),s&&r&&n&&i){var u={reportSoftNavs:this.useSoftNavs};this.allowedMetrics.indexOf("LCP")>-1&&s(this.jo.bind(this),u),this.allowedMetrics.indexOf("CLS")>-1&&r(this.jo.bind(this),u),this.allowedMetrics.indexOf("FCP")>-1&&n(this.jo.bind(this),u),this.allowedMetrics.indexOf("INP")>-1&&i(this.jo.bind(this),u),this.vo=!0}else Lt.error("web vitals callbacks not loaded - not starting")}},this._instance=t,this.Co=!((e=this._instance.persistence)==null||!e.props[Vi]),this.startIfEnabled()}get Wo(){return this._instance.config.capture_performance}get allowedMetrics(){var t,e,s=te(this.Wo)?(t=this.Wo)==null?void 0:t.web_vitals_allowed_metrics:void 0;return D(s)?((e=this._instance.persistence)==null?void 0:e.props[Gi])||["CLS","FCP","INP","LCP"]:s}get flushToCaptureTimeoutMs(){return(te(this.Wo)?this.Wo.web_vitals_delayed_flush_ms:void 0)||5e3}get useAttribution(){var t=te(this.Wo)?this.Wo.web_vitals_attribution:void 0;return t!=null&&t}get useSoftNavs(){var t=te(this.Wo)?this.Wo.__preview_web_vitals_soft_navs:void 0;return t!=null&&t}get Ho(){var t=te(this.Wo)&&he(this.Wo.__web_vitals_max_value)?this.Wo.__web_vitals_max_value:Rl;return t>0&&6e4>=t?Rl:t}get isEnabled(){var t=re?.protocol;if(t!=="http:"&&t!=="https:")return Lt.info("Web Vitals are disabled on non-http/https protocols"),!1;var e=te(this.Wo)?this.Wo.web_vitals:Ke(this.Wo)?this.Wo:void 0;return Ke(e)?e:this.Co}startIfEnabled(){this.isEnabled&&!this.vo&&(Lt.info("enabled, starting..."),this.ai(this.Uo))}onRemoteConfig(t){if(t.ok){var e=t.config;if("capturePerformance"in e){var s=te(e.capturePerformance)&&!!e.capturePerformance.web_vitals,r=te(e.capturePerformance)?e.capturePerformance.web_vitals_allowed_metrics:void 0;this._instance.persistence&&(this._instance.persistence.register({[Vi]:s}),this._instance.persistence.register({[Gi]:r})),this.Co=s,this.startIfEnabled()}}}get zo(){return this.useSoftNavs?this.useAttribution?"web-vitals-with-attribution-soft-navs":"web-vitals-soft-navs":this.useAttribution?"web-vitals-with-attribution":"web-vitals"}ai(t){var e=$.__PosthogExtensions__,s=this.zo,r=e?.postHogWebVitalsCallbacksByFlavor;r!=null&&r[s]||s==="web-vitals"&&x(r)&&e!=null&&e.postHogWebVitalsCallbacks?t():e==null||e.loadExternalDependency==null||e.loadExternalDependency(this._instance,s,(n=>{n?Lt.error("failed to load script",n):t()}))}Bo(t){var e=t||v?.location.href;if(e){var s=this._instance.config.disable_capture_url_hashes?Ct(e):e,r=this._instance.config.custom_personal_data_properties,n=this._instance.config.mask_personal_data_properties?[...vs,...r||[]]:[];return nr(s,n,ir)}Lt.error("Could not determine current URL")}}},Ef={exceptionObserver:class{constructor(t){var e;this.Uo=()=>{var s;if(v&&this.isEnabled&&(s=$.__PosthogExtensions__)!=null&&s.errorWrappingFunctions){var r=$.__PosthogExtensions__.errorWrappingFunctions.wrapOnError,n=$.__PosthogExtensions__.errorWrappingFunctions.wrapUnhandledRejection,i=$.__PosthogExtensions__.errorWrappingFunctions.wrapConsoleError;try{!this.Vo&&this.Ne.capture_unhandled_errors&&(this.Vo=r(this.captureException.bind(this))),!this.Zo&&this.Ne.capture_unhandled_rejections&&(this.Zo=n(this.captureException.bind(this))),!this.Go&&this.Ne.capture_console_errors&&(this.Go=i(this.captureException.bind(this)))}catch(o){Ms.error("failed to start",o),this.Qo()}}},this._instance=t,this.Ko=!((e=this._instance.persistence)==null||!e.props[Wi]),this.Jo=new yh(b({},(function(s){var r,n,i,o;return s===void 0&&(s={}),{refillRate:(r=(n=s.exceptionRateLimiterRefillRate)!==null&&n!==void 0?n:s.__exceptionRateLimiterRefillRate)!==null&&r!==void 0?r:1,bucketSize:(i=(o=s.exceptionRateLimiterBucketSize)!==null&&o!==void 0?o:s.__exceptionRateLimiterBucketSize)!==null&&i!==void 0?i:10}})(this._instance.config.error_tracking),{refillInterval:1e4,rt:Ms})),this.Ne=this.Yo(),this.startIfEnabledOrStop()}Yo(){var t=this._instance.config.capture_exceptions,e={capture_unhandled_errors:!1,capture_unhandled_rejections:!1,capture_console_errors:!1};return te(t)?e=b({},e,t):(x(t)?this.Ko:t)&&(e=b({},e,{capture_unhandled_errors:!0,capture_unhandled_rejections:!0})),e}get isEnabled(){return this.Ne.capture_console_errors||this.Ne.capture_unhandled_errors||this.Ne.capture_unhandled_rejections}startIfEnabledOrStop(){this.isEnabled?(Ms.info("enabled"),this.Qo(),this.ai(this.Uo)):this.Qo()}ai(t){var e,s;(e=$.__PosthogExtensions__)!=null&&e.errorWrappingFunctions?t():(s=$.__PosthogExtensions__)==null||s.loadExternalDependency==null||s.loadExternalDependency(this._instance,"exception-autocapture",(r=>{if(r)return Ms.error("failed to load script",r);t()}))}Qo(){var t,e,s;(t=this.Vo)==null||t.call(this),this.Vo=void 0,(e=this.Zo)==null||e.call(this),this.Zo=void 0,(s=this.Go)==null||s.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({[Wi]:this.Ko}),this.Ne=this.Yo(),this.startIfEnabledOrStop())}}onConfigChange(){this.Ne=this.Yo()}captureException(t){var e,s,r,n=(e=t==null||(s=t.$exception_list)==null||(s=s[0])==null?void 0:s.type)!==null&&e!==void 0?e:"Exception";this.Jo.consumeRateLimit(n)?Ms.info("Skipping exception capture because of client rate limiting.",{exception:n}):(r=this._instance.exceptions)==null||r.sendExceptionEvent(t)}},exceptions:class{constructor(t){var e,s;this.Xo=[],this.tl=new Lh([new zh,new Qh,new Vh,new qh,new Zh,new Yh,new Kh,new Xh],(function(r){for(var n=arguments.length,i=new Array(n>1?n-1:0),o=1;n>o;o++)i[o-1]=arguments[o];return function(a,l){l===void 0&&(l=0);for(var u=[],c=a.split(` -`),d=l;c.length>d;d++){var h=c[d];if(1024>=h.length){var p=Xa.test(h)?h.replace(Xa,"$1"):h;if(!p.match(/\S*Error: /)){for(var f of i){var g=f(p,r);if(g){u.push(g);break}}if(u.length>=50)break}}}return(function(m){if(!m.length)return[];var _=Array.from(m);return _.reverse(),_.slice(0,50).map((w=>{return b({},w,{filename:w.filename||(E=_,E[E.length-1]||{}).filename,function:w.function||gs});var E}))})(u)}})("web:javascript",jh,Wh)),this._instance=t,this.Xo=(e=(s=this._instance.persistence)==null?void 0:s.get_property(zi))!==null&&e!==void 0?e:[],this.el=Qr(this.il()),this.rl=new tp(this.el)}onConfigChange(){this.el=Qr(this.il()),this.rl.setConfig(this.el)}onRemoteConfig(t){var e,s,r;if(t.ok){var n=t.config;if("errorTracking"in n){var i=(e=(s=n.errorTracking)==null?void 0:s.suppressionRules)!==null&&e!==void 0?e:[],o=(r=n.errorTracking)==null?void 0:r.captureExtensionExceptions;this.Xo=i,this._instance.persistence&&this._instance.persistence.register({[zi]:this.Xo,[qi]:o})}}}get nl(){var t,e=!!this._instance.get_property(qi),s=this._instance.config.error_tracking.captureExtensionExceptions;return(t=s??e)!==null&&t!==void 0&&t}buildProperties(t,e){return this.tl.buildFromUnknown(t,{syntheticException:e?.syntheticException,mechanism:{handled:e?.handled}})}addExceptionStep(t,e){if(this.el.enabled)try{if(!W(t)||t.trim().length===0)return void Xe.warn("Ignoring exception step because message must be a non-empty string");var s=(function(i){if(!i)return{sanitizedProperties:{},droppedKeys:[]};var o=[];return{sanitizedProperties:Object.keys(i).reduce(((a,l)=>ep.has(l)?(o.push(l),a):(a[l]=i[l],a)),{}),droppedKeys:o}})(this.sl(e)),r=s.sanitizedProperties,n=s.droppedKeys;n.length>0&&Xe.warn("Ignoring reserved exception step fields",{droppedKeys:n}),this.rl.add(b({[Zr]:t,[Xr]:new Date().toISOString()},r))}catch(i){Xe.error("Failed to add exception step. Ignoring breadcrumb.",i)}}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 Xe.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 Xe.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 Xe.info("Skipping exception capture because it was thrown by the PostHog SDK")}var s=this.el.enabled&&D(t.$exception_steps)?this.dl(t):t,r=typeof(i=globalThis._posthogReleaseId)=="string"&&i.length>0?i:void 0;r&&(s.$release_id=r);try{var n=this._instance.capture("$exception",s,{_noTruncate:!0,_batchKey:"exceptionEvent",Wn:!0});return n&&this.rl.clear(),n}catch(o){return Xe.error("Failed to capture exception event. Dropping this exception.",o),void this.rl.clear()}}catch(o){return void Xe.error("Failed to process exception event. Ignoring this exception.",o)}var i}dl(t){try{var e=this.rl.getAttachable();return e.length===0?t:b({},t,{$exception_steps:e})}catch(s){return Xe.error("Failed to read buffered exception steps. Capturing exception without steps.",s),t}}ll(t){this.el.enabled&&this.rl.add({[Zr]:t,[Xr]:new Date().toISOString()})}sl(t){return te(t)?b({},t):{}}il(){var t,e;return(t=(e=this._instance.config.error_tracking)==null?void 0:e.exception_steps)!==null&&t!==void 0?t:{}}ol(t){if(t.length===0)return!1;try{var e=t.reduce(((s,r)=>{var n=r.type,i=r.value;return W(n)&&n.length>0&&s.$exception_types.push(n),W(i)&&i.length>0&&s.$exception_values.push(i),s}),{$exception_types:[],$exception_values:[]});return this.Xo.some((s=>{var r=s.values.map((n=>{var i=td[n.operator],o=e[n.key];if(!i||!o)return!1;var a=L(n.value)?n.value:[n.value];return a.length>0&&i(a,o)}));return s.type==="OR"?r.some(Boolean):r.every(Boolean)}))}catch(s){return Xe.warn("Failed to evaluate suppression rules. Capturing the exception.",s),!1}}ul(t){return t.flatMap((e=>{var s,r;return(s=(r=e.stacktrace)==null?void 0:r.frames)!==null&&s!==void 0?s:[]})).some((e=>e.filename&&e.filename.startsWith("chrome-extension://")))}hl(t){if(t.length>0){var e,s,r,n,i=(e=(s=t[0].stacktrace)==null?void 0:s.frames)!==null&&e!==void 0?e:[],o=i[i.length-1];return(r=o==null||(n=o.filename)==null?void 0:n.includes("posthog.com/static"))!==null&&r!==void 0&&r}return!1}al(t){return!D(t)&&L(t)}}},Sf=b({productTours:class{get Mr(){return this._instance.persistence}constructor(t){this.vl=null,this.cl=null,this._instance=t}initialize(){this.loadIfEnabled()}onRemoteConfig(t){if(t.ok){var e=t.config;if("productTours"in e){var s,r;if(this.Mr&&this.Mr.register({[Wo]:!!e.productTours}),!Si(this._instance))return!this.vl&&D((s=this.Mr)==null?void 0:s.props[Ws])||Pr.info("product tours disabled; stopping and clearing cached tours"),(r=this.vl)==null||r.stop(),this.vl=null,void this.clearCache();this.loadIfEnabled()}}}loadIfEnabled(){!this.vl&&Si(this._instance)&&this.ai((()=>this.fl()))}ai(t){var e,s;(e=$.__PosthogExtensions__)!=null&&e.generateProductTours?t():(s=$.__PosthogExtensions__)==null||s.loadExternalDependency==null||s.loadExternalDependency(this._instance,"product-tours",(r=>{r?Pr.error("Could not load product tours script",r):t()}))}fl(){var t;!this.vl&&(t=$.__PosthogExtensions__)!=null&&t.generateProductTours&&(this.vl=$.__PosthogExtensions__.generateProductTours(this._instance,!0))}getProductTours(t,e){if(e===void 0&&(e=!1),!L(this.cl)||e){var s=this.Mr;if(s){var r=s.props[Ws];if(L(r)&&!e)return this.cl=r,void t(r,{isLoaded:!0})}this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/product_tours/?token="+this._instance.config.token),method:"GET",timestampMode:"query",callback:n=>{if(Si(this._instance)){var i=n.statusCode;if(i!==200||!n.json){var o="Product Tours API could not be loaded, status: "+i;return i===0?n.error||Pr.warn(o):Pr.error(o),void t([],{isLoaded:!1,error:o})}var a=L(n.json.product_tours)?n.json.product_tours:[];this.cl=a,s&&s.register({[Ws]:a}),t(a,{isLoaded:!0})}else t([],{isLoaded:!0})}})}else t(this.cl,{isLoaded:!0})}getActiveProductTours(t){D(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(Ws)}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)}}},Rn),xf={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 s=this.globalsForEvent(e);this.gl.push(s),this.gl.length>1e3&&(this.gl=this.gl.slice(10))}}get siteAppLoaders(){var t;return(t=$._POSTHOG_REMOTE_CONFIG)==null||(t=t[this._instance.config.token])==null?void 0:t.siteApps}initialize(){if(this.isEnabled){var t=this._instance._addCaptureHook(this.ml.bind(this));this.yl=()=>{t(),this.gl=[],this.yl=void 0}}}globalsForEvent(t){var e,s,r,n,i,o,a;if(!t)throw new Error("Event payload is required");var l={},u=this._instance.get_property("$groups")||[],c=this._instance.get_property("$stored_group_properties")||{};for(var d of Object.entries(c)){var h=d[0];l[h]={id:u[h],type:h,properties:d[1]}}var p=t.$set_once,f=t.$set;return{event:b({},Ic(t,pf),{properties:b({},t.properties,f?{$set:b({},(e=(s=t.properties)==null?void 0:s.$set)!==null&&e!==void 0?e:{},f)}:{},p?{$set_once:b({},(r=(n=t.properties)==null?void 0:n.$set_once)!==null&&r!==void 0?r:{},p)}:{}),elements_chain:(i=(o=t.properties)==null?void 0:o.$elements_chain)!==null&&i!==void 0?i:"",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,s=(e=t.tagName)==null?void 0:e.toLowerCase();return s==="style"&&this._instance.config.prepare_external_dependency_stylesheet?this._instance.config.prepare_external_dependency_stylesheet(t)||(Ze.error("prepare_external_dependency_stylesheet returned null"),null):s==="script"&&this._instance.config.prepare_external_dependency_script?this._instance.config.prepare_external_dependency_script(t)||(Ze.error("prepare_external_dependency_script returned null"),null):t}_l(){var t,e,s,r,n,i,o,a;if(!this._instance.config.prepare_external_dependency_stylesheet&&!this._instance.config.prepare_external_dependency_script)return()=>{};var l=C?.defaultView,u=l==null||(t=l.Node)==null?void 0:t.prototype;if(!l||!u)return()=>{};if(this.pl++,this.wl)return this.kl();var c=[],d=this,h=new WeakSet,p=(m,_,w)=>{if(m!=null&&m[_]){var E=m[_];m[_]=w(E),c.push((()=>{m[_]=E}))}},f=m=>{if(h.has(m))return m;var _=d.bl(m);return _&&h.add(_),_},g=m=>m.map((_=>typeof _=="string"?_:f(_))).filter((_=>!$e(_)));return p(u,"appendChild",(m=>function(_){var w=f(_);return w?m.call(this,w):_})),p(u,"insertBefore",(m=>function(_,w){var E=f(_);return E?m.call(this,E,w):_})),p(u,"replaceChild",(m=>function(_,w){var E=f(_);return E?m.call(this,E,w):w})),[(e=l.Element)==null?void 0:e.prototype,(s=l.Document)==null?void 0:s.prototype,(r=l.DocumentFragment)==null?void 0:r.prototype].forEach((m=>{p(m,"append",(_=>function(){for(var w=arguments.length,E=new Array(w),I=0;w>I;I++)E[I]=arguments[I];return _.apply(this,g(E))})),p(m,"prepend",(_=>function(){for(var w=arguments.length,E=new Array(w),I=0;w>I;I++)E[I]=arguments[I];return _.apply(this,g(E))}))})),[(n=l.Element)==null?void 0:n.prototype,(i=l.CharacterData)==null?void 0:i.prototype,(o=l.DocumentType)==null?void 0:o.prototype].forEach((m=>{p(m,"before",(_=>function(){for(var w=arguments.length,E=new Array(w),I=0;w>I;I++)E[I]=arguments[I];return _.apply(this,g(E))})),p(m,"after",(_=>function(){for(var w=arguments.length,E=new Array(w),I=0;w>I;I++)E[I]=arguments[I];return _.apply(this,g(E))})),p(m,"replaceWith",(_=>function(){for(var w=arguments.length,E=new Array(w),I=0;w>I;I++)E[I]=arguments[I];var F=g(E);return E.length&&!F.length?void 0:_.apply(this,F)}))})),p((a=l.Element)==null?void 0:a.prototype,"insertAdjacentElement",(m=>function(_,w){var E=f(w);return E?m.call(this,_,E):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 s=this._l();try{var r=t(s);return e&&s(),r}catch(n){throw s(),n}}setupSiteApp(t){var e=this.apps[t.id],s=()=>{var o;!e.errored&&this.gl.length&&(Ze.info("Processing "+this.gl.length+" events for site app with id "+t.id),this.gl.forEach((a=>this.xl((()=>e.processEvent==null?void 0:e.processEvent(a))))),e.processedBuffer=!0),Object.values(this.apps).every((a=>a.processedBuffer||a.errored))&&((o=this.yl)==null||o.call(this))},r=!1,n=o=>{e.errored=!o,e.loaded=!0,Ze.info("Site app with id "+t.id+" "+(o?"loaded":"errored")),r&&s()};try{var i=this.xl((o=>t.init({posthog:this._instance,callback(a){o(),n(a)}})),!1).processEvent;i&&(e.processEvent=i),r=!0}catch(o){Ze.error(Ml+t.id,o),n(!1)}if(r&&e.loaded)try{s()}catch(o){Ze.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 s of t)this.setupSiteApp(s)}Cl(t){var e=this;if(Object.keys(this.apps).length!==0){var s=this.globalsForEvent(t),r=function(i){try{e.xl((()=>i.processEvent==null?void 0:i.processEvent(s)))}catch(o){Ze.error("Error while processing event "+t.event+" for site app "+i.id,o)}};for(var n of Object.values(this.apps))r(n)}}onRemoteConfig(t){var e,s,r,n=this;if((e=this.siteAppLoaders)!=null&&e.length)return this.isEnabled?(this.Sl(),void this._instance.on("eventCaptured",(l=>this.Cl(l)))):void Ze.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.');if((s=this.yl)==null||s.call(this),t.ok){var i=t.config;if((r=i.siteApps)!=null&&r.length)if(this.isEnabled){var o=function(){var l,u=a.id,c=a.url;$["__$$ph_site_app_"+u]=n._instance,(l=$.__PosthogExtensions__)==null||l.loadSiteApp==null||l.loadSiteApp(n._instance,c,(d=>{if(d)return Ze.error(Ml+u,d)}))};for(var a of i.siteApps)o()}else Ze.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.')}}}},kf={tracingHeaders:class{constructor(t){this.Ml=void 0,this.Tl=void 0,this.El=void 0,this.Uo=()=>{var e,s,r=this.Il();r?(x(this.Ml)&&(this.Ml=(e=$.__PosthogExtensions__)==null||(e=e.tracingHeadersPatchFns)==null?void 0:e._patchXHR(r,(()=>this._instance.get_distinct_id()),this._instance.sessionManager)),x(this.Tl)&&(this.Tl=(s=$.__PosthogExtensions__)==null||(s=s.tracingHeadersPatchFns)==null?void 0:s._patchFetch(r,(()=>this._instance.get_distinct_id()),this._instance.sessionManager))):this.Qo()},this._instance=t}initialize(){this.startIfEnabledOrStop()}ai(t){var e,s;(e=$.__PosthogExtensions__)!=null&&e.tracingHeadersPatchFns?t():(s=$.__PosthogExtensions__)==null||s.loadExternalDependency==null||s.loadExternalDependency(this._instance,"tracing-headers",(r=>{if(r)return df.error("failed to load script",r);t()}))}Pl(){var t,e;return(t=(e=this._instance.config.tracing_headers)!==null&&e!==void 0?e:this._instance.config.addTracingHeaders)!==null&&t!==void 0?t:this._instance.config.__add_tracing_headers}Il(){var t=this.Pl();return L(t)?(L(this.El)?this.El.splice(0,this.El.length,...t):this.El=[...t],t.length>0?this.El:void 0):(L(this.El)&&this.El.splice(0),this.El=t||void 0,this.El)}Qo(){var t,e;(t=this.Ml)==null||t.call(this),(e=this.Tl)==null||e.call(this),this.Ml=void 0,this.Tl=void 0}startIfEnabledOrStop(){this.Il()?this.ai(this.Uo):this.Qo()}}},If=b({surveys:class{get Ne(){return this._instance.config}constructor(t){this.Rl=void 0,this._surveyManager=null,this.Al=!1,this.Fl=[],this.Ll=null,this.Ol=null,this._instance=t,this._surveyEventReceiver=null}initialize(){this.loadIfEnabled()}onRemoteConfig(t){if(!this.Ne.disable_surveys){if(!t.ok)return q.warn("Remote config unavailable. Not loading surveys.");var e=t.config.surveys;if(D(e))return q.warn("Flags not loaded yet. Not loading surveys.");var s=L(e);this.Rl=s?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=[],s=0;slocalStorage.removeItem(n)))}catch{}}loadIfEnabled(){if(!this._surveyManager)if(this.Al)q.info("Already initializing surveys, skipping...");else if(this.Ne.disable_surveys)q.info(Ll);else if(this.Ne.cookieless_mode&&this._instance.consent.isOptedOut())q.info("Not loading surveys in cookieless mode without consent.");else{var t=$?.__PosthogExtensions__;if(t){if(!x(this.Rl)||this.Ne.advanced_enable_surveys){var e=this.Rl||this.Ne.advanced_enable_surveys;this.Al=!0;try{var s=t.generateSurveys;if(s)return void this.Dl(s,e);var r=t.loadExternalDependency;if(!r)return void this.$l(qo);r(this._instance,"surveys",(n=>{n||!t.generateSurveys?this.$l("Could not load surveys script",n):this.Dl(t.generateSurveys,e)}))}catch(n){throw this.$l("Error initializing surveys",n),n}finally{this.Al=!1}}}else q.error("PostHog Extensions not found.")}}Dl(t,e){this._surveyManager=t(this._instance,e),this._surveyEventReceiver=new mf(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(Ll),t([]);var s,r=this._instance.get_property(Ji);if(r&&!e)return t(r,{isLoaded:!0}),void(this.ql()&&this.getSurveys((()=>{}),!0));typeof Promise<"u"&&this.Ll?this.Ll.then((n=>t(n.surveys,n.context))):(typeof Promise<"u"&&(this.Ll=new Promise((n=>{s=n}))),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:n=>{var i;this.Ll=null;var o=n.statusCode;if(o!==200||!n.json){var a="Surveys API could not be loaded, status: "+o;o!==0?q.error(a):n.error||q.warn(a),this.Ol=Date.now();var l={isLoaded:!1,error:a};return t([],l),void(s==null||s({surveys:[],context:l}))}this.Ol=null;var u,c=n.json.surveys||[],d=c.filter((p=>(function(f){return!(!f.start_date||f.end_date)})(p)&&(rd(p)||(function(f){var g;return!((g=f.conditions)==null||(g=g.actions)==null||(g=g.values)==null||!g.length)})(p))));d.length>0&&((u=this._surveyEventReceiver)==null||u.register(d)),(i=this._instance.persistence)==null||i.register({[Ji]:c,[tn]:Date.now()});var h={isLoaded:!0};t(c,h),s?.({surveys:c,context:h})}}))}ql(){return this.jl()&&!this.Ll&&!this.Bl()}jl(){var t=this._instance.get_property(tn);return he(t)&&Date.now()-t>3e5}Bl(){return he(this.Ol)&&3e5>Date.now()-this.Ol}markSurveyAsSeen(t,e){var s,r={id:t,current_iteration:(s=e?.iteration)!==null&&s!==void 0?s:null};id(r);try{localStorage.setItem("lastSeenSurveyDate",new Date().toISOString())}catch{}}Nl(t){for(var e of this.Fl)try{if(!t.isLoaded)return e([],t);this.getSurveys(e)}catch(s){q.error("Error in survey callback",s)}}getActiveMatchingSurveys(t,e){if(e===void 0&&(e=!1),!D(this._surveyManager))return this._surveyManager.getActiveMatchingSurveys(t,e);q.warn("init was not called")}Hl(t){var e=null;return this.getSurveys((s=>{var r;e=(r=s.find((n=>n.id===t)))!==null&&r!==void 0?r:null})),e}Ul(t){if(D(this._surveyManager))return{eligible:!1,reason:Ar};var e=typeof t=="string"?this.Hl(t):t;return e?this._surveyManager.checkSurveyEligibility(e):{eligible:!1,reason:"Survey not found"}}zl(t){if(D(this._surveyManager))return{eligible:!1,reason:Ar};var e=typeof t=="string"?this.Hl(t):t;return e?this._surveyManager.checkSurveyRenderability(e):{eligible:!1,reason:"Survey not found"}}canRenderSurvey(t){if(D(this._surveyManager))return q.warn("init was not called"),{visible:!1,disabledReason:Ar};var e=this.zl(t);return{visible:e.eligible,disabledReason:e.reason}}canRenderSurveyAsync(t,e){return D(this._surveyManager)?(q.warn("init was not called"),Promise.resolve({visible:!1,disabledReason:Ar})):new Promise((s=>{this.getSurveys((r=>{var n,i=(n=r.find((a=>a.id===t)))!==null&&n!==void 0?n:null;if(i){var o=this.zl(i);s({visible:o.eligible,disabledReason:o.reason})}else s({visible:!1,disabledReason:"Survey not found"})}),e)}))}renderSurvey(t,e,s){var r;if(D(this._surveyManager))q.warn("init was not called");else{var n=typeof t=="string"?this.Hl(t):t;if(n!=null&&n.id)if(Zp.includes(n.type)){var i=C?.querySelector(e);if(i)return(r=n.appearance)!=null&&r.surveyPopupDelaySeconds?(q.info("Rendering survey "+n.id+" with delay of "+n.appearance.surveyPopupDelaySeconds+" seconds"),void setTimeout((()=>{var o,a;q.info("Rendering survey "+n.id+" with delay of "+((o=n.appearance)==null?void 0:o.surveyPopupDelaySeconds)+" seconds"),(a=this._surveyManager)==null||a.renderSurvey(n,i,s),q.info("Survey "+n.id+" rendered")}),1e3*n.appearance.surveyPopupDelaySeconds)):void this._surveyManager.renderSurvey(n,i,s);q.warn("Survey element not found")}else q.warn("Surveys of type "+n.type+" cannot be rendered in the app");else q.warn("Survey not found")}}displaySurvey(t,e){var s;if(D(this._surveyManager))q.warn("init was not called");else{var r=this.Hl(t);if(r){var n=r;if((s=r.appearance)!=null&&s.surveyPopupDelaySeconds&&e.ignoreDelay&&(n=b({},r,{appearance:b({},r.appearance,{surveyPopupDelaySeconds:0})})),e.displayType!==io.Popover&&e.initialResponses&&q.warn("initialResponses is only supported for popover surveys. prefill will not be applied."),e.ignoreConditions===!1){var i=this.Ul(r);if(!i.eligible)return void q.warn("Survey is not eligible to be displayed: ",i.reason)}e.displayType!==io.Inline?this._surveyManager.handlePopoverSurvey(n,e):this.renderSurvey(n,e.selector,e.properties)}else q.warn("Survey not found")}}cancelPendingSurvey(t){D(this._surveyManager)?q.warn("init was not called"):this._surveyManager.cancelSurvey(t)}handlePageUnload(){var t;(t=this._surveyManager)==null||t.handlePageUnload==null||t.handlePageUnload()}}},Rn),Cf={toolbar:class{constructor(t){this.instance=t}Wl(t){$.ph_toolbar_state=t}Vl(){var t;return(t=$.ph_toolbar_state)!==null&&t!==void 0?t:0}initialize(){return this.maybeLoadToolbar()}maybeLoadToolbar(t,e,s){if(t===void 0&&(t=void 0),e===void 0&&(e=void 0),s===void 0&&(s=void 0),so(this.instance.config)||!v||!C)return!1;t=t??v.location,s=s??v.history;try{if(!e){try{v.localStorage.setItem("test","test"),v.localStorage.removeItem("test")}catch{return!1}e=v?.localStorage}var r,n=vf||un(t.hash,"__posthog")||un(t.hash,"state"),i=n?el((()=>JSON.parse(atob(decodeURIComponent(n)))))||el((()=>JSON.parse(decodeURIComponent(n)))):null;return i&&i.action==="ph_authorize"?((r=i).source="url",r&&Object.keys(r).length>0&&(i.desiredHash?t.hash=i.desiredHash:s?s.replaceState(s.state,"",t.pathname+t.search):t.hash="")):((r=JSON.parse(e.getItem(Ol)||"{}")).source="localstorage",delete r.userIntent),!(!r.token||this.instance.config.token!==r.token||(this.loadToolbar(r),0))}catch{return!1}}Zl(t){var e=$.ph_load_toolbar||$.ph_load_editor;!D(e)&&Se(e)?e(t,this.instance):Dl.warn("No toolbar load function found")}loadToolbar(t){var e=!(C==null||!C.getElementById(wu));if(!v||e)return!1;var s=this.instance.requestRouter.region==="custom"&&this.instance.config.advanced_disable_toolbar_metrics,r=b({token:this.instance.config.token},t,{apiURL:this.instance.requestRouter.endpointFor("ui")},s?{instrument:!1}:{});if(v.localStorage.setItem(Ol,JSON.stringify(b({},r,{source:void 0}))),this.Vl()===2)this.Zl(r);else if(this.Vl()===0){var n;this.Wl(1),(n=$.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this.instance,"toolbar",(i=>{if(i)return Dl.error("[Toolbar] Failed to load",i),void this.Wl(0);this.Wl(2),this.Zl(r)})),ne(v,"turbolinks:load",(()=>{this.Wl(0),this.loadToolbar(r)}))}return!0}Gl(t){return this.loadToolbar(t)}maybeLoadEditor(t,e,s){return t===void 0&&(t=void 0),e===void 0&&(e=void 0),s===void 0&&(s=void 0),this.maybeLoadToolbar(t,e,s)}}},Ff=b({experiments:ye},Rn),Pf={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;D(e)||(Ke(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||so(this._instance.config)||this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut())){var t=$?.__PosthogExtensions__;if(t&&!x(this.Ql)&&this.Ql)if(this.Jl&&this.Jl.token){this.Kl=!0;try{var e=t.initConversations;if(e)return this.tu(e),void(this.Kl=!1);var s=t.loadExternalDependency;if(!s)return void this.eu(qo);s(this._instance,"conversations",(r=>{r||!t.initConversations?this.eu("Could not load conversations script",r):this.tu(t.initConversations),this.Kl=!1}))}catch(r){this.eu("Error initializing conversations",r),this.Kl=!1}}else Ue.error("Conversations enabled but missing token in remote config.")}}tu(t){if(this.Jl)try{this._conversationsManager=t(this.Jl,this._instance),this.Yl=!1,Ue.info("Conversations loaded successfully")}catch(e){this.eu("Error completing conversations initialization",e)}else Ue.error("Cannot complete initialization: remote config is null")}eu(t,e){Ue.error(t,e),this._conversationsManager=null,this.Kl=!1,this.Yl=!0}show(){this._conversationsManager?this._conversationsManager.show():Ue.warn("Conversations not loaded yet.")}hide(){this._conversationsManager&&this._conversationsManager.hide()}isAvailable(){return this.Ql===!0&&!$e(this._conversationsManager)}getUnavailableReason(){return this.isAvailable()?null:this._instance.config.disable_conversations?"disabled_by_config":so(this._instance.config)?"disabled_for_toolbar":this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut()?"consent_opted_out":this.Xl===!1?"remote_config_failed":x(this.Ql)?this.Xl?"disabled_in_project":"remote_config_pending":this.Ql?D(this.Jl)||!this.Jl.token?"missing_token":$!=null&&$.__PosthogExtensions__?this.Kl?"initializing":this.Yl?"load_failed":"not_loaded":"extensions_unavailable":"disabled_in_project"}isVisible(){var t,e;return(t=(e=this._conversationsManager)==null?void 0:e.isVisible())!==null&&t!==void 0&&t}sendMessage(t,e,s){var r=this;return X((function*(){return r._conversationsManager?r._conversationsManager.sendMessage(t,e,s):(Ue.warn(Dt),null)}))()}getMessages(t,e){var s=this;return X((function*(){return s._conversationsManager?s._conversationsManager.getMessages(t,e):(Ue.warn(Dt),null)}))()}markAsRead(t){var e=this;return X((function*(){return e._conversationsManager?e._conversationsManager.markAsRead(t):(Ue.warn(Dt),null)}))()}getTickets(t){var e=this;return X((function*(){return e._conversationsManager?e._conversationsManager.getTickets(t):(Ue.warn(Dt),null)}))()}requestRestoreLink(t){var e=this;return X((function*(){return e._conversationsManager?e._conversationsManager.requestRestoreLink(t):(Ue.warn(Dt),null)}))()}restoreFromToken(t){var e=this;return X((function*(){return e._conversationsManager?e._conversationsManager.restoreFromToken(t):(Ue.warn(Dt),null)}))()}restoreFromUrlToken(){var t=this;return X((function*(){return t._conversationsManager?t._conversationsManager.restoreFromUrlToken():(Ue.warn(Dt),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()}}},Af={logs:class{constructor(t){var e,s=this;this.iu=!1,this.ru=!1,this.rt=se("[logs]"),this.nu=b({},this.rt,{error(){for(var r=arguments.length,n=new Array(r),i=0;r>i;i++)n[i]=arguments[i];n.some(Vl)||s.rt.error(...n)}}),this.tr=[],this.su=[],this.Sa=0,this.au=()=>{var r,n;this.Sa=0,(r=this.ou)==null||r.onReconnect(),(n=this.lu)==null||n.onReconnect()},this._instance=t,this._instance&&(e=this._instance.config.logs)!=null&&e.captureConsoleLogs&&(this.iu=!0),v&&ne(v,"online",this.au)}uu(t,e,s,r){var n,i=(function(o,a){var l,u,c,d,h,p,f,g=(l=o?.flushIntervalMs)!==null&&l!==void 0?l:3e3,m=(u=o?.maxBufferSize)!==null&&u!==void 0?u:100,_=a!=null&&a.consoleCapture?void 0:(c=o?.maxLogsPerInterval)!==null&&c!==void 0?c:1e3,w=x(_)?Math.max(m,2048):Math.max(m,_),E=o?.resourceAttributes;return{serviceName:(d=(h=E?.["service.name"])!==null&&h!==void 0?h:o?.serviceName)!==null&&d!==void 0?d:a?.serviceNameDefault,serviceVersion:(p=E?.["service.version"])!==null&&p!==void 0?p:o?.serviceVersion,environment:(f=E?.["deployment.environment"])!==null&&f!==void 0?f:o?.environment,resourceAttributes:E,beforeSend:o?.beforeSend,flushIntervalMs:g,maxBufferSize:m,maxQueueSize:w,maxBatchRecordsPerPost:100,rateCapWindowMs:g,maxLogsPerInterval:_,backgroundFlushBudgetMs:0,terminationFlushBudgetMs:0}})((n=this._instance)==null||(n=n.config)==null?void 0:n.logs,s);return[new Th(this.hu(t,e),i,this.nu,(()=>this.du()),(o=>o()),void 0,r),i]}vu(){var t,e=(t=this._instance)==null||(t=t.config)==null?void 0:t.logs;if(!this.ou||this.cu!==e){var s;(s=this.ou)==null||s.reset(),this.cu=e;var r=this.uu((()=>this.tr),(n=>{this.tr=n}));this.ou=r[0],this.fu=r[1]}return this.ou}pu(){var t,e=(t=this._instance)==null||(t=t.config)==null?void 0:t.logs;if(!this.lu||this.gu!==e){var s;(s=this.lu)==null||s.reset(),this.gu=e;var r=this.uu((()=>this.su),(n=>{this.su=n}),{serviceNameDefault:"posthog-browser-logs",consoleCapture:!0},ql);this.lu=r[0],this.mu=r[1]}return this.lu}initialize(){this.loadIfEnabled()}onRemoteConfig(t){var e;if(t.ok){var s=(e=t.config.logs)==null?void 0:e.captureConsoleLogs;!D(s)&&s&&(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){Vl(t)||this.rt.error("PostHog logs flush failed:",t)}loadIfEnabled(){if(this.iu&&!this.ru){var t=$?.__PosthogExtensions__;if(t){var e=t.loadExternalDependency;e?e(this._instance,"logs",(s=>{var r;s||(r=t.logs)==null||!r.initializeLogs?this.rt.error("Could not load logs script",s):(t.logs.initializeLogs(this._instance),this.ru=!0)})):this.rt.error(qo)}else this.rt.error("PostHog Extensions not found.")}}hu(t,e){var s=this._instance;return{get isDisabled(){return!1},get optedOut(){return!s.is_capturing()},getPersistedProperty:r=>r===ut.LogsQueue?t():void 0,setPersistedProperty(r,n){var i;r===ut.LogsQueue&&e((i=n)!==null&&i!==void 0?i:[])},Ot:r=>this.Ot(r),getLibraryId:()=>Y.LIB_NAME,getLibraryVersion:()=>Y.LIB_VERSION}}Ot(t){return new Promise((e=>{if(Ru(this.Sa,3))e({kind:"fatal",error:ki(void 0,"logs endpoint is unreachable, dropping batch")});else{var s=!1,r=i=>{s||(s=!0,clearTimeout(n),e(i))},n=setTimeout((()=>{this.rt.warn("Logs request timed out before receiving a response"),r({kind:"retry-later",error:ki(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:i=>{var o=i.statusCode;if(this.ku(o),o>=200&&300>o)r({kind:"ok"});else if(o===413)r({kind:"too-large"});else if(o!==0&&o!==429&&500>o)r({kind:"fatal",error:new Error("logs request failed with status "+o)});else{var a;o===0?(i.error||this.rt.warn("Logs request failed before receiving an HTTP response"),r({kind:"retry-later",error:ki(i.error,"logs request failed before receiving an HTTP response")})):r({kind:"retry-later",error:(a=i.error)!==null&&a!==void 0?a:new Error("logs request failed with status "+o)})}}})}}))}ku(t){(t!==0||this._instance.__loaded)&&(this.Sa=Tu(t,this.Sa,3,(()=>this.rt.warn("Log requests are failing before receiving an HTTP response; this can happen due to network issues, CORS, browser blocking, or ad blockers. Stopped sending logs; will try again when connectivity changes."))))}bu(t){this.tr.length>0&&this.xu(t,this.tr,this.fu,Y.LIB_NAME,(e=>{this.tr=e})),this.su.length>0&&this.xu(t,this.su,this.mu,ql,(e=>{this.su=e}))}xu(t,e,s,r,n){if(e.length!==0){var i=e.map((a=>a.record));n([]);var o=ru(i,su(s,Y.LIB_NAME,Y.LIB_VERSION),r,Y.LIB_VERSION);this._instance._send_request({method:"POST",url:this.wu(),data:o,compression:"best-available",batchKey:"logs",transport:t})}}wu(){return this._instance.requestRouter.endpointFor("api","/i/v1/logs")+"?token="+encodeURIComponent(this._instance.config.token)}du(){var t,e={};if(e.distinctId=this._instance.get_distinct_id(),this._instance.sessionManager){var s=this._instance.sessionManager.checkAndGetSessionAndWindowId(!0),r=s.windowId,n=s.sessionStartTimestamp,i=s.lastActivityTimestamp;e.sessionId=s.sessionId,e.windowId=r,D(n)||(e.sessionStartTimestamp=n),D(i)||(e.lastActivityTimestamp=i)}if($!=null&&(t=$.location)!=null&&t.href&&(e.currentUrl=this._instance.config.disable_capture_url_hashes?Ct($.location.href):$.location.href),this._instance.featureFlags){var o=this._instance.featureFlags.getFlags();o&&o.length>0&&(e.activeFeatureFlags=o)}return e}}},$f={metrics:class{constructor(t){this.rt=se("[metrics]"),this._instance=t}initialize(){}vu(){var t,e,s=(t=this._instance)==null||(t=t.config)==null?void 0:t.metrics;return this.ou&&this.cu===s||((e=this.ou)==null||e.reset(),this.cu=s,this.ou=new Nh(this.hu(),(function(r){var n,i,o,a,l,u=r?.resourceAttributes;return{serviceName:(n=u?.["service.name"])!==null&&n!==void 0?n:r?.serviceName,serviceVersion:(i=u?.["service.version"])!==null&&i!==void 0?i:r?.serviceVersion,environment:(o=u?.["deployment.environment"])!==null&&o!==void 0?o:r?.environment,resourceAttributes:u,beforeSend:r?.beforeSend,flushIntervalMs:(a=r?.flushIntervalMs)!==null&&a!==void 0?a:1e4,maxSeriesPerFlush:(l=r?.maxSeriesPerFlush)!==null&&l!==void 0?l:1e3}})(s),this.rt)),this.ou}count(t,e,s){e===void 0&&(e=1),this.vu().count(t,e,s)}gauge(t,e,s){this.vu().gauge(t,e,s)}histogram(t,e,s){this.vu().histogram(t,e,s)}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((s=>this.rt.error("PostHog metrics flush failed:",s)))}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:s=>e.Jt(s),getLibraryId:()=>Y.LIB_NAME,getLibraryVersion:()=>Y.LIB_VERSION}}Jt(t,e){return new Promise((s=>{var r=!1,n=o=>{r||(r=!0,clearTimeout(i),s(o))},i=setTimeout((()=>n({kind:"retry-later",error:new Error("metrics request timed out")})),9e4);this._instance._send_request(b({method:"POST",url:this.Su(),data:t,compression:"best-available",batchKey:"metrics"},e&&{transport:e},{fireCallbackOnDrop:!0,callback(o){var a=o.statusCode;if(a>=200&&300>a)n({kind:"ok"});else if(a===413)n({kind:"too-large"});else if(a!==0&&a!==429&&500>a)n({kind:"fatal",error:new Error("metrics request failed with status "+a)});else{var l;n({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)}}},Rf=b({},Rn,wf,bf,Ef,Sf,xf,If,kf,Cf,Ff,Pf,Af,$f);Te.__defaultExtensionClasses=b({},Rf);(function(){Y.SDK_DIST_CHANNEL="npm";var t=Ys[os]=new Te;return(function(){function e(){e.done||(e.done=!0,ad=!1,Z(Ys,(function(s){s._dom_loaded()})))}C!=null&&C.addEventListener?C.readyState==="complete"?e():ne(C,"DOMContentLoaded",e,{capture:!1}):v&&k.error("Browser doesn't support `document.addEventListener` so PostHog couldn't be initialized")})(),t})();const cd="CodeFile",ud="GeneratedCode",Tf={CustomAction:"A",CustomWidget:"W",CustomFunction:"F",CustomClass:"C",CodeFile:"C"};function kt(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function fo(t){return String(t||"").trim().replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function Nf(t={},e=0){const s=fo(t.artifactType||t.type||cd),r=fo(t.artifactName||t.name||t.fileName||`${ud}-${e+1}`);return`${s||"artifact"}-${r||e+1}`}function dd(t={},e=0){const s=kt(t),r=s.artifactType||s.type||cd,n=s.artifactName||s.name||ud;let i=s.fileName||n;return i.endsWith(".dart")||(i+=".dart"),{id:fo(s.id)||Nf({...s,artifactType:r,artifactName:n,fileName:i},e),artifactType:r,artifactName:n,fileName:i,deployPath:s.deployPath||"",description:s.description||"",code:s.code||s.content||"",dependencies:hd(s.dependencies),imports:Array.isArray(s.imports)?s.imports:[],publicApi:Array.isArray(s.publicApi)?s.publicApi:[],relationships:pd(s.relationships),deployStatus:s.deployStatus||"pending",review:s.review||null,metadata:kt(s.metadata),codeType:s.codeType||Tf[r]||"O"}}function hd(t){return t?Array.isArray(t)?t.map(e=>{if(typeof e=="string")return{name:e,version:null,inferred:!1};const s=kt(e),r=s.name||s.package;return r?{name:r,version:s.version||null,versionRequired:!!(s.versionRequired||s.required),inferred:!!s.inferred,...s.reason?{reason:s.reason}:{}}:null}).filter(Boolean):Object.entries(kt(t)).map(([e,s])=>({name:e,version:s||null,inferred:!1})):[]}function pd(t){return t?(Array.isArray(t)?t:[t]).map(e=>{const s=kt(e);return!s.from&&!s.to?null:{from:s.from||null,to:s.to||null,type:s.type||"uses",description:s.description||""}}).filter(Boolean):[]}function go(t){if(typeof t!="string")return null;const e=t.trim();if(!e)return null;try{return JSON.parse(e)}catch{const s=e.match(/```(?:json)?\s*([\s\S]*?)```/i);if(!s)return null;try{return JSON.parse(s[1].trim())}catch{return null}}}function or(t,e={}){const s=[],r=typeof t=="string"?go(t):t,i=kt(r||{});!r&&typeof t=="string"&&s.push("Structured bundle parse failed; using legacy single-artifact fallback.");const o=Array.isArray(i.artifacts)?i.artifacts:[{artifactType:i.artifactType||e.artifactType,artifactName:i.artifactName||e.artifactName,fileName:i.fileName||e.fileName,description:i.description,code:i.code||e.code||(typeof t=="string"?t:""),dependencies:i.dependencies||e.dependencies,relationships:i.relationships||e.relationships}];o.forEach((d,h)=>{!d?.artifactType&&!d?.type&&s.push(`Artifact ${h+1} has no artifactType; it will deploy as a standalone code file under lib/custom_code/ root.`)});const a=o.map((d,h)=>dd(d,h)),l=new Map(o.map((d,h)=>[kt(d).id,a[h]?.id]).filter(([d,h])=>d&&h)),u=d=>l.get(d)||d,c=pd(i.relationships||e.relationships).map(d=>({...d,from:d.from?u(d.from):d.from,to:d.to?u(d.to):d.to}));return{schemaVersion:i.schemaVersion||e.schemaVersion||null,id:i.id||e.id||"bundle-current",title:i.title||i.name||e.title||"Generated artifact bundle",description:i.description||e.description||"",artifacts:a,dependencies:hd(i.dependencies||e.dependencies),relationships:c,deployOrder:Array.isArray(i.deployOrder)?i.deployOrder.map(u):a.map(d=>d.id),warnings:[...s,...Array.isArray(i.warnings)?i.warnings:[]],metadata:kt(i.metadata)}}function gn(t){return or(t).artifacts[0]||dd()}function yt(t){if(typeof t!="string")return t??"";const e=t.trim();if(!e)return"";try{return JSON.parse(e)}catch{return t}}function ys(t){return JSON.stringify(t,null,2)}function Mf(t){return ys({task:"architect",userRequest:String(t??"")})}function Lf(t){const e=yt(t);return e&&typeof e=="object"&&typeof e.task=="string"?ys(e):ys({task:"generate_bundle",bundleSpec:e})}function Of(t){return ys({task:"review_bundle",generatedBundle:yt(t),outputRequirements:{bundleReview:["status","score","summary","manualActions","findings"],scoreRange:[0,100],eachArtifact:["id","review.status","review.findings"],manualActions:{definition:"Setup the developer must perform by hand in the FlutterFlow editor that FlutterFlow will NOT do for them.",exclude:["creating the Custom Action, Widget or Code File itself - deploying the code creates it","declaring parameters or return values FlutterFlow derives from the function signature","anything that resolves as a side effect of using the action or widget in the editor","generic advice such as testing, reviewing or rebuilding the app"],preferEmpty:"Return an empty array when nothing qualifies - an empty list is the expected result for most bundles."}}})}function Qo(t,e=null){const s={stage:t};return e!=null&&(s.bundle=yt(e)),s}function Df({bundleSpec:t,artifactBundle:e,bundleReview:s,artifactId:r,userFeedback:n}){return ys({task:"regenerate_artifact",artifactId:r,bundleSpec:yt(t),artifactBundle:yt(e),bundleReview:yt(s),userFeedback:String(n)})}function fd({bundleSpec:t,artifactBundle:e,bundleReview:s,userFeedback:r}){return ys({task:"regenerate_bundle",bundleSpec:yt(t),artifactBundle:yt(e),bundleReview:yt(s),userFeedback:String(r??"")})}const Gl={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"},Bf=["sanitizationResult","modelArmor","modelArmorResult","data","result","error"];function Le(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function jf(t){return Le(t)?typeof t.filterMatchState=="string"||typeof t.invocationResult=="string"||Array.isArray(t.matchedFilters)||Le(t.filterSummary)||Le(t.filterResults):!1}function gd(t,e=0){if(!Le(t)||e>3)return null;if(jf(t))return t;for(const s of Bf){const r=t[s];if(Le(r)){const n=gd(r,e+1);if(n)return n}}return null}function mn(t){return Array.isArray(t)?t.some(mn):Le(t)?t.matched===!0||t.matchState==="MATCH_FOUND"?!0:Object.values(t).some(mn):!1}function mo(t){return Array.isArray(t)?t.some(mo):Le(t)?typeof t.executionState=="string"&&t.executionState!=="EXECUTION_SUCCESS"?!0:Object.values(t).some(mo):!1}function md(t){return{csamFilterFilterResult:"csam",maliciousUriFilterResult:"malicious_uris",piAndJailbreakFilterResult:"pi_and_jailbreak",raiFilterResult:"rai",sdpFilterResult:"sdp",virusScanFilterResult:"virus_scan"}[t]||t}function Uf(t,e){if(Le(t))for(const[s,r]of Object.entries(t)){if(!Le(r))continue;const n=Le(r.categories)?r.categories:{},i=Object.entries(n).filter(([,o])=>Le(o)&&o.matched===!0).map(([o])=>o);i.length>0?i.forEach(o=>e.add(o)):r.matched===!0&&e.add(md(s))}}function Hf(t,e){if(!t)return;const s=Array.isArray(t)?t.flatMap(r=>Le(r)?Object.entries(r):[]):Object.entries(t);for(const[r,n]of s){if(!mn(n))continue;const i=md(r),o=n?.raiFilterResult?.raiFilterTypeResults||(i==="rai"?n?.raiFilterTypeResults:null),a=Le(o)?Object.entries(o).filter(([,l])=>mn(l)).map(([l])=>l):[];a.length>0?a.forEach(l=>e.add(l)):e.add(i)}}function Wf(t){return Gl[t]?Gl[t]:String(t).replace(/([a-z])([A-Z])/g,"$1 $2").replace(/_/g," ").toLowerCase()}function Kl(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 zf(t){const e=gd(t);if(!e)return null;const s=new Set(Array.isArray(e.matchedFilters)?e.matchedFilters:[]);Uf(e.filterSummary,s),Hf(e.filterResults,s);const r=e.blocked===!0||e.filterMatchState==="MATCH_FOUND"||s.size>0,n=e.invocationResult||null,i=mo(e.filterSummary||e.filterResults);return!r&&!i&&!["PARTIAL","FAILURE"].includes(n)?null:{kind:r?"blocked":"unavailable",invocationResult:n,matchedFilters:[...s]}}function qf(t,e){const s=zf(t);if(!s)return null;const r=[...new Set(s.matchedFilters.map(Wf))],n=s.kind==="blocked",i=new Error(n?`Safety screening blocked this pipeline step for ${Kl(r)}.`:"Safety screening could not be completed. Please try again.");return i.name="ModelArmorError",i.code=n?"MODEL_ARMOR_BLOCKED":"MODEL_ARMOR_UNAVAILABLE",i.isModelArmor=!0,i.pipelineStep=e,i.userTitle=n?"Request blocked for safety":"Safety check unavailable",i.userMessage=n?`The safety check detected ${Kl(r)}. Edit your request to remove or rephrase the flagged content, then run the pipeline again.`:"The safety service did not finish all of its checks. Please wait a moment and run the pipeline again.",i.retryExplanation=n?"Trying another model would not change this safety decision.":"A fallback model was not attempted because safety screening must complete first.",i.matchedFilters=s.matchedFilters,i}function Vf(t){return String(t||"").replace(/\/\*[\s\S]*?\*\//g,"").replace(/\/\/[^\n]*/g,"")}function Jl(t){const e=/^(import|export|part|library|class|enum|extension|typedef|mixin|abstract|const|final|var|late)\b/,s=[];for(const r of Vf(t).split(` -`)){if(!/^[A-Za-z_$]/.test(r)||e.test(r))continue;const n=r.match(/^[\w$<>,?\s[\]]+?\s([a-zA-Z_$][\w$]*)\s*\(/);n&&s.push(n[1])}return s}function ea(t,e){const s=t.replace(/\.dart$/,"");if(e==="W")return s.replace(/(^|_)(\w)/g,(r,n,i)=>i.toUpperCase());if(e==="A"){const r=s.replace(/(^|_)(\w)/g,(n,i,o)=>o.toUpperCase());return r.charAt(0).toLowerCase()+r.slice(1)}return e==="F"?"CustomFunctions":e==="C"?t.endsWith(".dart")?t:`${t}.dart`:s}async function Yl(t){const e=new TextEncoder().encode(String(t||"")),s=await globalThis.crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(s),r=>r.toString(16).padStart(2,"0")).join("")}async function Gf(t,e=new Map){const s={},r=new Set;for(const[o,a]of t.entries()){if(a.type==="D"||a.type==="O")continue;const l=ea(o,a.type),u={old_identifier_name:l,new_identifier_name:l,type:a.type,is_deleted:!1,current_checksum:await Yl(a.content)},c=e.get(a.path);if(c!==void 0&&(u.original_checksum=await Yl(c)),s[o]=u,a.type==="F"){const d=Jl(a.content);(d.length>0?d:[a.functionName].filter(Boolean)).forEach(p=>r.add(p))}}const n=new Set(Jl(e.get("lib/flutter_flow/custom_functions.dart")||"")),i={functions_to_rename:[],functions_to_delete:[],functions_to_add:Array.from(r).filter(o=>!n.has(o))};return{fileMapContents:JSON.stringify(s),functionsMapContents:JSON.stringify(i)}}const Kf=new Set(["CustomWidget","CustomAction","CustomFunction","CustomClass","CodeFile"]),Zl={CustomWidget:"custom_code/widgets/",CustomAction:"custom_code/actions/",CustomFunction:"flutter_flow/custom_functions.dart",CustomClass:"custom_code/",CodeFile:"custom_code/"},Jf=new Set(["void","dynamic","String","int","double","num","bool","Color","DateTime","DateTimeRange","LatLng","FFPlace","FFUploadedFile","DocumentReference","List"]),Yf=["Struct","Record"],Zf=[{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=>Ii(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=>Ii(t).some(e=>{const s=/^\s*final\s+(?:double|int|String|bool|Color|num)\s+(\w+)\s*;/gm;let r;for(;(r=s.exec(e))!==null;){const n=r[1];if(!(new RegExp(`this\\.${n}\\s*=(?!=)`).test(e)||new RegExp(`[:,]\\s*${n}\\s*=(?!=)`).test(e)))return!0}return!1}),pos:`class W extends StatefulWidget { - const W({required this.value}); - final double value; -}`,neg:`class _P { - const _P({required this.t}); - final double t; -} -class W extends StatefulWidget { - const W({this.value = 1.0}); - final double value; -}`},{id:"asset-without-anchor",severity:"warning",message:'CustomWidget calls Image.asset with a path arriving as a String parameter. An asset reaches the build only when a FlutterFlow widget NODE references it - a filename passed as a parameter does not count, so the image renders as a broken-image icon on device. "Download Unused Project Assets" does not fix it (FlutterFlow issues 522, 2271, 3799). Keep something in the UI referencing the file, or load it over the network instead.',detect:t=>/Image\.asset\s*\(/.test(t)&&/final\s+String\??\s+\w*[Pp]ath\b/.test(t),pos:`class W extends StatefulWidget { final String? imagePath; } -var x = Image.asset(widget.imagePath);`,neg:`class W extends StatefulWidget { final String? imagePath; } -var x = Image.network(widget.imagePath);`},{id:"unsupported-param-type",severity:"error",message:"CustomWidget exposes a Flutter data type FlutterFlow cannot express as a Define Parameter: TextStyle, BoxShadow, FontWeight, FontStyle, TextDirection, TextAlign, EdgeInsets, Offset, Alignment/AlignmentGeometry, Border, BorderRadius, BoxDecoration, BoxConstraints, BorderSide, Gradient, or ThemeData. FlutterFlow's supported data types (docs.flutterflow.io/resources/data-representation/data-types) are only int, double, bool, string, Color, Image, DateTime, Json, LatLng, and the FF objects, so this parameter cannot be configured in the editor and the widget will not place or compile. Expose primitives instead (color, fontSize as double?, fontWeight via a custom enum, doubles for spacing).",detect:t=>Ii(t).some(e=>/final\s+(TextStyle|BoxShadow|FontWeight|FontStyle|TextDirection|TextAlign|EdgeInsets|Offset|Alignment(?:Geometry)?|Border(?:Radius|Side)?|BoxDecoration|BoxConstraints|Gradient|LinearGradient|RadialGradient|ThemeData)\??\s+\w+\s*;/.test(e)),pos:`class W extends StatefulWidget { - const W({this.textStyle}); - final TextStyle? textStyle; - @override _S createState() => _S(); -} -class _S extends State { @override Widget build(BuildContext c) => const SizedBox(); }`,neg:`class W extends StatefulWidget { - const W({this.width}); - final double? width; - @override _S createState() => _S(); -} -class _S extends State { @override Widget build(BuildContext c) => Padding(padding: const EdgeInsets.all(8), child: const SizedBox()); }`}];function Qe(t,e,s){return{artifactId:t.id,artifactName:t.artifactName,artifactType:t.artifactType,severity:e,message:s}}function ar(t){let e="",s=0;for(;s"&&(s--,s===0))return{inner:t.slice(e+1,r),end:r+1};return null}function Qf(t,e){const s=new RegExp(`class\\s+${e}\\b[^{]*\\{`).exec(t);if(!s)return null;let r=0;for(let n=s.index+s[0].length-1;neg(t).usable);function sg(t=""){const e=ar(t);return tg.filter(s=>s.detect(e)).map(({id:s,severity:r,message:n})=>({id:s,severity:r,message:n}))}function rg(t){const e=[],s=t.matchAll(/\bFuture\b/g);for(const r of s){let n=r.index+6,i=null;const o=n;for(;no;if(t[n]==="<"){const u=Xf(t,n);if(!u||(i=u.inner.replace(/\s+/g," ").trim(),n=u.end,!/\s/.test(t[n]||"")))continue;for(;nXl(o.functionName)===r);if(n)return n;const i=o=>!o.functionName.startsWith("_");return s.find(i)||s[0]}function Tn(t=""){return Array.from(ar(t).matchAll(/\b(?:class|enum)\s+([A-Za-z_]\w*)/g),e=>e[1])}function ng(t="",e=""){return ta(t,e)?.returnType||null}function Ql(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 ig(t,e){const s=Tn(e);if(s.length===0)return null;const n=String(t||"").split("/").pop().replace(/\.dart$/,"");if(s.some(l=>Ql(l)===n)||s.length>1)return null;const[o]=s,a=`${Ql(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 sa(t){return String(t||"").replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,"")}function og(t,e,s=""){const r=ta(e,s)?.functionName;if(!r)return null;const n=String(t||"").split("/").pop(),i=ea(n,"A");if(i===r)return null;const o=`${sa(r)}.dart`;return`File name "${n}" does not match Action "${r}". FlutterFlow derives the action from the file name, so it looks for "${i}" and reports Action "${i}" declaration not found. Rename the file to "${o}" - FlutterFlow puts an underscore before every capital - or rename the function to "${i}".`}function ag(t="",e=""){return ta(t,e)!==null}function lg(t,e=new Set){return(t?.match(/[A-Za-z_]\w*/g)||[]).filter(r=>Jf.has(r)?!1:!Yf.some(i=>r.endsWith(i))||e.has(r))}function cg(t,{functionName:e="",declaredTypes:s=new Set}={}){const r=ng(t,e),n=lg(r,s);if(n.length===0)return null;const[i]=n;let o;return s.has(i)?o=`uses Code File type "${i}", which FlutterFlow cannot process as an Action Return Value`:r===i?o="is not a FlutterFlow Action Return Value":o=`uses type "${i}", which is not a FlutterFlow Action Return Value`,`CustomAction return type "${r}" ${o}. Return JSON (Future) or an existing FlutterFlow Data Type (*Struct) instead.`}function ug(t,e={}){const s=[],r=t.fileName||"",n=t.code||"";if(Kf.has(t.artifactType)||s.push(Qe(t,"error",`Unsupported artifact type "${t.artifactType}".`)),r.endsWith(".dart")||s.push(Qe(t,"error","FlutterFlow custom code artifacts must use .dart files.")),!n.trim())return s.push(Qe(t,"warning","Generated artifact has no Dart code yet.")),s;if(t.artifactType==="CustomWidget"){/class\s+\w+\s+extends\s+(StatelessWidget|StatefulWidget)/.test(n)||s.push(Qe(t,"warning","CustomWidget code should declare a widget class extending StatelessWidget or StatefulWidget."));for(const i of sg(n))s.push(Qe(t,i.severity,i.message))}if(t.artifactType==="CustomAction"&&!ag(n,t.artifactName)&&s.push(Qe(t,"warning","CustomAction code should expose an async Future function callable from FlutterFlow.")),t.artifactType==="CustomAction"){const i=e.declaredTypes||new Set(Tn(n)),o=cg(n,{functionName:t.artifactName,declaredTypes:i});o&&s.push(Qe(t,"error",o));const a=og(r,n,t.artifactName);a&&s.push(Qe(t,"error",a))}if(t.artifactType==="CustomFunction"&&/class\s+\w+\s+extends\s+(StatelessWidget|StatefulWidget)/.test(n)&&s.push(Qe(t,"warning","CustomFunction should be a callable function, not a widget class.")),t.artifactType==="CustomClass"||t.artifactType==="CodeFile"){const i=ig(r,n);i&&s.push(Qe(t,"info",i))}return s}function dg(t){const e=Array.isArray(t?.artifacts)?t.artifacts:[],s=new Set(e.flatMap(i=>Tn(i.code||""))),r=e.flatMap(i=>ug(i,{declaredTypes:s})),n=e.map(i=>({artifactId:i.id,fileName:i.fileName,pathHint:Zl[i.artifactType]||Zl.CodeFile}));return{valid:r.every(i=>i.severity!=="error"),findings:r,deployHints:n}}const ec="// DO NOT REMOVE OR MODIFY THE CODE ABOVE!";function tc(t){return(/^\s*import\s+['"]([^'"]+)['"]/.exec(t)||[])[1]||null}function hg(t=""){const e=t.indexOf(ec);return e===-1?t:t.slice(e+ec.length).replace(/^\s*\n/,"")}const pg=/^\s*import\s+['"][^'"]+['"]\s*;\s*(?:\/\/.*)?$/;function fg(t="",e=""){const s=hg(t),r=new Set((e.match(/^\s*import .*$/gm)||[]).map(tc).filter(Boolean)),n=s.split(` -`).filter(i=>{const o=tc(i);return o===null||!r.has(o)?!0:!pg.test(i)}).join(` -`).replace(/^\s*\/\/ Automatic FlutterFlow imports\s*$/m,"").replace(/^\s*\n+/,"");return e+n}const gg=new Set(["flutter","flutter_test","flutter_driver","flutter_localizations"]);function vd(t){let e="",s=0;for(;s{const r=s.name||s.package;if(!r||r==="flutter")return e;const n=s.versionRequired||s.required;return e[r]=n&&s.version||"",e},{})}function yg(t){const e=new Map,s=new Map,r=[];for(const n of t)e.has(n.fileName)?r.push(`Duplicate deploy file name "${n.fileName}" for artifacts "${e.get(n.fileName)}" and "${n.artifactId}".`):e.set(n.fileName,n.artifactId),s.has(n.path)?r.push(`Duplicate deploy path "${n.path}" for artifacts "${s.get(n.path)}" and "${n.artifactId}".`):s.set(n.path,n.artifactId);return r}function wg(t,e={}){const s=Array.isArray(t?.artifacts)?t.artifacts:[],n=(e.selectedArtifactIds||t?.deployOrder||s.map(p=>p.id)).map(p=>s.find(f=>f.id===p)).filter(Boolean),i=[...t?.warnings||[]];let o=[];n.forEach(p=>{const f=_g(p),g=p.fixedCode||p.code||"",m=p.codeType||mg[p.artifactType]||Ne.OTHER;g.trim()||i.push(`${p.artifactName||p.id} has no generated code.`),o.push({artifactId:p.id,artifactName:p.artifactName,artifactType:p.artifactType,fileName:f,content:g,type:m,path:p.deployPath||vg(f,m),deployPath:p.deployPath||"",deployMode:"customCodeSync"})});const a="lib/flutter_flow/custom_functions.dart",l=o.map((p,f)=>({entry:p,index:f})).filter(({entry:p})=>p.type===Ne.FUNCTION&&p.path===a);if(l.length>1){const p=l[0],f={...p.entry,artifactId:l.map(({entry:m})=>m.artifactId).join("+"),artifactName:p.entry.artifactName,content:l.map(({entry:m})=>`// ${m.artifactId} -${m.content}`).join(` - -`)},g=new Set(l.slice(1).map(({index:m})=>m));o=o.filter((m,_)=>!g.has(_)),o[p.index]=f}const u={...sc(t?.dependencies),...n.reduce((p,f)=>({...p,...sc(f.dependencies)}),{})},c={};n.forEach(p=>{ra(p.code||"").forEach(f=>{f in u||(c[f]="")})});const d={...c,...u},h=yg(o);return{bundleId:t?.id||"bundle-current",title:t?.title||"Generated artifact bundle",fileEntries:o,dependencies:d,relationships:t?.relationships||[],warnings:i,errors:h}}function bg(t){return String(t||"").match(/\bclass\s+([A-Z][A-Za-z0-9_]*)\b/)?.[1]}function Eg(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 Sg(t,e){const r=[Eg(t),bg(e.content),e.artifactName].find(n=>/^[A-Z][A-Za-z0-9_]*$/.test(String(n||"")));if(!r)throw new Error(`Cannot derive a FlutterFlow custom class name for ${t}.`);return r}function xg(t,e=new Map){const s=[];for(const[r,n]of t.entries())n.type!=="C"||e.has(n.path)||s.push({artifactId:n.artifactId||r,className:Sg(r,n),content:n.content,fileName:r,path:n.path});return s}function kg(t,e){const s=new Set(e.map(r=>r.path));return new Map(Array.from(t.entries()).filter(([,r])=>!s.has(r.path)))}const rc={pass:0,warning:1,fail:2},Ig=["manualActions"];function De(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function gt(...t){for(const e of t){if(typeof e=="string"&&e.trim())return e.trim();if(Array.isArray(e)&&e.length>0){const s=e.filter(r=>typeof r=="string").join(` -`);if(s)return s}}return""}function tt(t){return t==null?[]:Array.isArray(t)?t:[t]}function Cg(t){const e=De(t).value??t;if(e==null||typeof e=="string"&&e.trim()==="")return null;const s=Number(e);if(Number.isFinite(s))return s;const r=String(t||"").match(/\bscore\b[^\d]{0,12}(\d{1,3})(?:\s*\/\s*100)?/i);return r?Number(r[1]):null}function We(t){return String(t||"").trim().replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function na(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 vo(...t){return t.filter(Boolean).reduce((e,s)=>rc[s]>rc[e]?s:e,"pass")}function yd(t,e="warning",s="review"){if(typeof t=="string")return{severity:e,message:t,suggestion:"",source:s};const r=De(t),n=gt(r.message,r.title,r.issue,r.description,r.summary);return n?{severity:na(r.severity||r.status||r.level)||e,message:n,suggestion:gt(r.suggestion,r.fix,r.recommendation,r.action),source:r.source||s}:null}function _o(t,e="review"){const s=De(t);return[["findings","warning"],["issues","warning"],["criticalIssues","fail"],["errors","fail"],["warnings","warning"],["recommendations","warning"],["requiredFixes","fail"],["suggestions","warning"]].flatMap(([n,i])=>tt(s[n]).map(o=>yd(o,i,e)).filter(Boolean))}function Fg(t,e,s=null){if(typeof t=="string")return{id:`${s||"bundle"}-manual-${e+1}`,title:t,detail:"",location:"",timing:"unspecified",artifactId:s,source:"Code Review"};const r=De(t),n=gt(r.title,r.action,r.step,r.message,r.name,r.description);return n?{id:r.id||`${s||"bundle"}-manual-${e+1}`,title:n,detail:gt(r.detail,r.instructions,r.description),location:gt(r.location,r.flutterFlowPath,r.path),timing:gt(r.timing,r.phase)||"unspecified",artifactId:s,source:gt(r.source)||"Code Review"}:null}function yo(t,e=null){const s=De(t);return Ig.flatMap(r=>tt(s[r])).map((r,n)=>Fg(r,n,e)).filter(Boolean)}function Pg(t){let e=typeof t=="string"?go(t):t;if(!e&&typeof t=="string")return{rawText:t,root:{}};const s=De(e);typeof s.content=="string"&&(e=go(s.content)||e);const r=De(e),n=De(r.reviewResult||r.codeReview||r.result);return{rawText:"",root:Object.keys(n).length?n:r}}function Ag(t,e){const s=[e.id,e.fileName,e.artifactName].map(We);return t.find(r=>{const n=De(r);return[n.id,n.fileName,n.artifactName,n.name].map(We).some(i=>i&&s.includes(i))})||null}function $g(t,e){return tt(t?.metadata?.compatibility?.deployHints).find(n=>We(n?.artifactId)===We(e.id)||We(n?.fileName)===We(e.fileName))?.pathHint||""}function Rg(t,e){return tt(t?.relationships).filter(s=>We(s?.from)===We(e.id)||We(s?.to)===We(e.id))}function Tg(t,e){return tt(t?.metadata?.compatibility?.findings).filter(s=>!s?.artifactId||We(s.artifactId)===We(e.id)).map(s=>yd(s,"warning","Compatibility check")).filter(Boolean)}function Ng(t,e,s,r){const n=Ag(e,s),i=De(n?.review||n||s.review),o=Object.keys(i).length>0,a=[..._o(i),...Tg(t,s)],l=yo(i,s.id),u=na(i.status||i.verdict||i.outcome||i.result),c=a.length?vo(...a.map(h=>h.severity)):null,d=vo(u,c,o?null:"warning");return{...s,index:r,status:d,statusReason:o?gt(i.summary,i.overview,i.assessment,i.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 i.fixedSource=="string"&&i.fixedSource.trim()?i.fixedSource.trim():null,pathHint:$g(t,s),relationships:Rg(t,s)}}function Mg({status:t,score:e,artifactPresentations:s,manualSteps:r}){const n=s.length;if(n===0&&r.length===0)return e==null?"Code review returned no overall summary and no score.":`Reviewed bundle with score ${e}/100.`;const i=s.reduce((a,l)=>(a[l.status]+=1,a),{pass:0,warning:0,fail:0}),o=[];return t&&o.push(`Overall verdict: ${t}.`),n&&o.push(`${n} artifact${n===1?"":"s"}: ${i.pass} pass, ${i.warning} warn, ${i.fail} fail.`),r.length&&o.push(`Do before deploy: ${r.map(a=>a.title).join("; ")}.`),e==null&&o.push("No numeric score (0-100) was returned."),o.join(" ")}function Lg({bundle:t,reviewResult:e}){const s=De(t),r=tt(s.artifacts),{root:n,rawText:i}=Pg(e),o=[n.bundleReview,n.overallReview,n.overall,n.bundleSummary,n.summaryReview,n.review].map(De).find(E=>Object.keys(E).length)||{},a=tt(n.artifacts||n.files||n.reviews),l=r.map((E,I)=>Ng(s,a,E,I)),u=_o(n),d=[..._o(o),...u],h=[...yo(o),...yo(n),...l.flatMap(E=>E.manualSteps)].filter((E,I,F)=>F.findIndex(P=>P.title===E.title&&P.artifactId===E.artifactId)===I),p=na(o.status||o.verdict||o.overallStatus||n.status||n.verdict||n.overallStatus||n.outcome),f=vo(p,...d.map(E=>E.severity),...l.map(E=>E.status)),g=o.score??n.score??n.overallScore??i,m=Cg(g),_=gt(o.headline,o.summary,o.executiveSummary,o.overview,o.assessment,o.conclusion,n.overallSummary,n.headline,n.summary,n.executiveSummary,n.overview,n.assessment,n.conclusion,i)||Mg({status:f,score:m,artifactPresentations:l,manualSteps:h}),w=l.reduce((E,I)=>(E[I.status]+=1,E),{pass:0,warning:0,fail:0});return{title:s.title||"Generated artifact bundle",description:s.description||"",status:f,score:m,summary:_,findings:d,manualSteps:h,artifacts:l,counts:w,reviewCoverage:{reviewed:l.filter(E=>E.reviewComplete).length,total:l.length},deployOrder:tt(s.deployOrder),relationships:tt(s.relationships),warnings:tt(s.warnings),compatibility:De(s.metadata?.compatibility)}}const Og=/^\uFEFF/;function Os(t){let e=0,s=t.length;for(;ee&&!t[s-1].trim();)s--;return t.slice(e,s).join(` -`)}function Dg(t){const e=String(t??"").replace(Og,"");if(!e.trim())return"";const s=e.split(` -`),r=c=>{const d=c.trim();return/^`{3,}[A-Za-z0-9+#_.-]*$/.test(d)?c.length-c.trimStart().length:-1};let n=0,i=-1;const o=[];{let c=0;for(let d=0;d=0&&(n++,i<0&&(i=d),o.push(c+h)),c+=s[d].length+1}}if(n===0)return Os(s);{const c=wo(e);if(!c.error&&o.every(h=>ic(h,c.commentAndStringRanges)))return Os(s)}if(n===1){const c=Os(s.slice(0,i)),d=Os(s.slice(i+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 Bg(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 wd(t){const e=Bg(t);return Array.from(e.matchAll(/class\s+([A-Z]\w*)\s+extends\s+[A-Za-z_]\w*Widget\b/g),s=>s[1])}function bd(t){return`${sa(t)}.dart`}function jg(t){return ea(t,"W")}const nc={"(":")","[":"]","{":"}"},Ug={")":"(","]":"[","}":"{"},Hg=/[A-Za-z0-9_]/;function wo(t){const e=[{kind:"code",opener:null,openedLine:0}],s=[];let r=1,n=0;const i=(c,d)=>{(c===` -`||c==="\r"&&d!==` -`)&&r++};let o=null;const a=()=>{for(const c of e)(c.kind==="string"||c.kind==="block-comment"||c.kind==="line-comment")&&s.push({start:c.startIndex,end:t.length})};for(;n0?t[n-1]:"",f=n>1?t[n-2]:"",g=(p==="r"||p==="R")&&!Hg.test(f);e.push({kind:"string",quote:c,triple:h,raw:g,startIndex:n,openedLine:r}),n+=h?3:1;continue}if(nc[c]){e.push({kind:"code",opener:c,openedLine:r}),n++;continue}if(Ug[c]){if(d.interpolation&&c==="}"){e.pop(),n++;continue}if(d.opener&&nc[d.opener]===c){e.pop(),n++;continue}return d.opener?(a(),{error:o??`line ${r}: "${c}" closes nothing - "${d.opener}" opened on line ${d.openedLine} is still open`,commentAndStringRanges:s}):(a(),{error:o??`line ${r}: unexpected "${c}" with no matching opener`,commentAndStringRanges:s})}i(c,t[n+1]),n++}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:s}}function Wg(t){return wo(String(t??"")).error}function ic(t,e){return e.some(({start:s,end:r})=>t>=s&&ttypeof s=="string"?s:s?.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 zg=/^dependencies\s*:\s*(?:#.*)?$/,qg=/^(?:"([^"]+)"|'([^']+)'|([A-Za-z_][A-Za-z0-9_-]*))\s*:/;function Nn(t){const e=t.match(qg);return e?e[1]??e[2]??e[3]:null}function pr(t){const e=t.trim();return e===""||e.startsWith("#")}function xs(t){const e=t.match(/^(\s*)/);return e?e[1].length:0}function ia(t,e){const s=t.findIndex(i=>e.test(i));if(s===-1)return null;let r=s,n=null;for(let i=s+1;i=0.0.0"}`}function Jg(t,e={}){const s=String(t||""),r=Object.entries(e).filter(([u])=>u&&u!=="flutter");if(r.length===0)return{yaml:s,added:[],alreadyPresent:[]};const n=s.split(` -`),i=new Set(xd(s)),o=[],a=[];for(const[u,c]of r)i.has(u)?a.push(u):(o.push([u,c]),i.add(u));if(o.length===0)return{yaml:s,added:[],alreadyPresent:a};const l=oa(n);if(l){const u=o.map(([c,d])=>oc(l.childIndent,c,d));n.splice(l.endIndex,0,...u)}else n.length>0&&n[n.length-1].trim()!==""&&n.push(""),n.push("dependencies:"),o.forEach(([u,c])=>{n.push(oc(" ",u,c))});return{yaml:n.join(` -`),added:o.map(([u])=>u),alreadyPresent:a}}function Yg(t,e={}){const s=String(t||""),r=Object.entries(e).filter(([l])=>l&&l!=="flutter");if(r.length===0)return{yaml:s,overridden:[],skipped:[]};const n=s.split(` -`),i=Ln(s),o=[],a=[];for(const[l,u]of r){const c=i.get(l);if(!c||!c.isScalar||!String(u||"").trim()){a.push(l);continue}const d=" ".repeat(xs(n[c.lineIndex]));n[c.lineIndex]=`${d}${l}: ${Id(String(u).trim())}${c.comment}`,o.push({name:l,from:c.constraint,to:u})}return{yaml:n.join(` -`),overridden:o,skipped:a}}function Cd(t){const e=String(t||""),s=[];return e.trim()?(/^name:\s*\S+/m.test(e)||s.push("pubspec.yaml missing name field"),oa(e.split(` -`))||s.push("pubspec.yaml missing dependencies section"),xd(e).includes("flutter")||s.push("pubspec.yaml missing Flutter SDK dependency"),{valid:s.length===0,errors:s}):(s.push("pubspec.yaml is empty"),{valid:!1,errors:s})}const Zg=">=3.0.0 <4.0.0";function bo(t){const e=String(t||"").trim(),s=e[0];return s!=="'"&&s!=='"'||e[e.length-1]!==s?e:e.slice(1,-1).replaceAll(`${s}${s}`,s)}function Xg(t=""){const e=_d(t).filter(s=>!s.startsWith("dart:")&&!s.startsWith("package:"));return{selfContained:e.length===0,unresolvableImports:e}}function ac(t,e,s){const r=[];for(const[n,i]of t){if(i.isScalar){e[n]=bo(i.constraint);continue}if(i.sourceKey==="sdk"){s.add(n);continue}if(i.sourceKey===null&&i.version){e[n]=bo(i.version);continue}r.push(n)}return r}function Qg(t){const e=new Set,s={},r={},n=ac(Ln(t),s,e);n.push(...ac(Gg(t,"dependency_overrides"),r,e));const i=new Set([...Object.keys(s),...e]),{sdk:o}=kd(t);return{sdkConstraint:bo(o)||Zg,dependencies:s,overrides:r,sdkPackages:[...e].sort(),availablePackages:i,unrepresentable:n}}function em(t,e,s){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 ${s.join(", ")}, which your project's pubspec.yaml does not declare with a version constraint, so it could not be compiled before the deploy.`}function tm(t,e){return`${t} was not compiled before deploying: your project declares ${e.join(", ")} from a source that cannot be reproduced outside it, and whether the packages ${t} imports depend on one of them transitively cannot be checked before the deploy, so package resolution could not be matched exactly.`}function sm(t,e){const{sdkConstraint:s,dependencies:r,overrides:n,sdkPackages:i,availablePackages:o,unrepresentable:a}=Qg(e),l={sdkConstraint:s,dependencies:r,overrides:n,sdkPackages:i},u=[],c=[];for(const d of t){const{className:h,content:p}=d,f=ra(p),g=f.filter(w=>a.includes(w));if(g.length>0){c.push({className:h,reason:`${h} was not compiled before deploying: it imports ${g.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:m}=Xg(p),_=f.filter(w=>!o.has(w));if(m.length>0||_.length>0){c.push({className:h,reason:em(h,m,_)});continue}if(a.length>0&&_d(p).some(w=>w.startsWith("package:"))){c.push({className:h,reason:tm(h,a)});continue}u.push({fileName:`${sa(h)}.dart`,content:p})}return{manifest:l,sources:u,skipped:c}}function lc(t,e){const s=`${t}${e}`.split(` -`),r=s.pop()??"",n=[];for(const i of s){const o=Fd(i);o&&n.push(o)}return{events:n,buffer:r}}function rm(t){const e=Fd(t);return e?[e]:[]}function Fd(t){const e=t.trim();if(!e)return null;try{const s=JSON.parse(e);return s&&typeof s=="object"&&!Array.isArray(s)?s:null}catch{return null}}async function nm(t,e={}){const{onPhase:s,onLog:r}=e;let n=null,i="";const o=a=>{if(a.event==="phase"){a.message&&s&&s(a.message);return}if(a.event==="log"){a.message&&r&&r(a.message);return}n=a};if(t.body?.getReader){const a=t.body.getReader(),l=new TextDecoder;for(;;){const{done:u,value:c}=await a.read();if(u)break;const d=lc(i,l.decode(c,{stream:!0}));i=d.buffer,d.events.forEach(o)}}else{const a=lc("",await t.text());i=a.buffer,a.events.forEach(o)}return rm(i).forEach(o),n?{...n,success:n.success===!0||n.success===void 0&&t.ok}:{success:!1,error:t.ok?"The FlutterFlow deploy runner closed the connection before it finished.":`FlutterFlow custom class provisioning failed (HTTP ${t.status}).`}}const im=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;function wt(t){const e=String(t||"").trim().match(im);return e?{major:Number(e[1]),minor:Number(e[2]),patch:Number(e[3]),prerelease:e[4]?e[4].split("."):[]}:null}function om(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 s=0;s0)}function lm(t){const e=wt(t);return e?e.major>0?`${e.major+1}.0.0`:`0.${e.minor+1}.0`:null}function aa(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 wt(o)?{min:o,minInclusive:!0,max:lm(o),maxInclusive:!1}:null}if(wt(e))return{min:e,minInclusive:!0,max:e,maxInclusive:!0};const s={min:null,minInclusive:!1,max:null,maxInclusive:!1},r=/(>=|<=|>|<)\s*([0-9][0-9A-Za-z.+-]*)/g;let n=!1,i;for(;(i=r.exec(e))!==null;){const[,o,a]=i;if(!wt(a))return null;n=!0,o===">="||o===">"?(s.min=a,s.minInclusive=o===">="):(s.max=a,s.maxInclusive=o==="<=")}return n?s:null}function cc(t,e){const s=aa(t);if(!s||!wt(e))return!1;if(s.min!==null){const r=vn(e,s.min);if(r<0||r===0&&!s.minInclusive)return!1}if(s.max!==null){const r=vn(e,s.max);if(r>0||r===0&&!s.maxInclusive)return!1}return!0}function cm(t,e){const s=aa(t);if(!s||!wt(e))return!1;if(s.max===null)return!0;const r=vn(s.max,e);return r>0?!0:r===0&&s.maxInclusive}function ns(t){const e=aa(t);return e?e.min:null}const um="https://pub.dev/api/packages/",dm=8e3;function hm(t,e={}){const{dartSdkFloor:s=null,flutterSdkFloor:r=null}=e,n=Array.isArray(t?.versions)?t.versions:[];let i=null;for(const o of n){const a=o?.version;if(!a||o.retracted||am(a))continue;const l=o.pubspec?.environment||{};s&&l.sdk&&!cc(l.sdk,s)||r&&l.flutter&&!cc(l.flutter,r)||(!i||vn(a,i)>0)&&(i=a)}return i?{version:i,constraint:`^${i}`}:null}async function pm(t,e={}){const{dartSdkFloor:s=null,flutterSdkFloor:r=null,fetchImpl:n=fetch}=e;let i;try{const a=await n(`${um}${encodeURIComponent(t)}`,{signal:AbortSignal.timeout(dm)});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}"`};i=await a.json()}catch(a){return{name:t,constraint:null,version:null,error:`could not reach pub.dev for "${t}" (${a.message})`}}const o=hm(i,{dartSdkFloor:s,flutterSdkFloor:r});return o?{name:t,...o,error:null}:{name:t,constraint:null,version:null,error:s?`no published "${t}" release supports Dart ${s}`:`no published "${t}" release could be read`}}async function fm(t,e={}){const s=await Promise.all(t.map(r=>pm(r,e)));return new Map(s.map(({name:r,...n})=>[r,n]))}async function gm(t,e={},s={}){const{resolveVersions:r=fm}=s,n=Object.entries(e).filter(([c])=>c&&c!=="flutter"),i=kd(t),o={dartSdkFloor:ns(i.sdk),flutterSdkFloor:ns(i.flutter)},a={additions:{},overrides:{},kept:[],warnings:[],sdk:o};if(n.length===0)return a;const l=Ln(t),u=[];for(const[c,d]of n){const h=l.get(c);if(!h){u.push(c);continue}const p=ns(d);if(!p){a.kept.push({name:c,constraint:h.constraint});continue}if(!h.isScalar){a.warnings.push(`"${c}" is declared in your project from a git, path, or SDK source, but the generated code needs at least ${p}. Left as-is — update it yourself if the build fails.`),a.kept.push({name:c,constraint:h.constraint});continue}if(cm(h.constraint,p)){a.kept.push({name:c,constraint:h.constraint});continue}a.overrides[c]=`^${p}`,a.warnings.push(`"${c}" was pinned to ${h.constraint} in your project, which cannot resolve the ${p} the generated code needs. Raising it to ^${p} — this changes a dependency the rest of your app also uses.`)}if(u.length>0){const c=await r(u,o);for(const d of u){const h=c.get(d);if(h?.constraint){a.additions[d]=h.constraint;continue}const p=e[d]||"";if(ns(p)){a.additions[d]=`^${ns(p)}`,a.warnings.push(`Could not confirm "${d}" version on pub.dev (${h?.error||"lookup failed"}). Using ^${ns(p)} from the AI's recommendation — verify this is current.`);continue}a.additions[d]=">=0.0.0",a.warnings.push(`Could not determine a version for "${d}" (${h?.error||"lookup failed"}) and the AI supplied none. Added with a wide-open >=0.0.0 constraint — pin a concrete version in FlutterFlow before deploying.`)}}return a}const mm={"&":"&","<":"<",">":">",'"':""","'":"'"};function bt(t){return String(t??"").replace(/[&<>"']/g,e=>mm[e])}function j(t){return t?bt(t).replace(/\n/g,"
    "):""}function It(t){return bt(t).replace(/\r?\n/g," ")}function vm(t,e={}){const s=t?.pipelineStep;if(s!=null&&e[s]!=null)return e[s];const r=t?.message||"";return r.includes("Code Generator")?2:r.includes("Code Review")?3:1}function _m(t){const e={"Integration Audit Report":"📋","Critical Issues":"❌",Warnings:"⚠️",Recommendations:"✅","Overall Score":"📊"};for(const[s,r]of Object.entries(e))if(t.toLowerCase().includes(s.toLowerCase()))return r;return"📄"}function ym(t){const e={critical:"❌",warning:"⚠️",recommendation:"✅",score:"📊",issue:"🔍",fix:"🔧"};for(const[s,r]of Object.entries(e))if(t.toLowerCase().includes(s.toLowerCase()))return r;return"📝"}function wm(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 ws(t){if(!t)return"";if(typeof t!="string")return String(t);const e=/```(?:\w+)?\n?([\s\S]*?)```/,s=t.match(e);return s?s[1].trim():t.trim()}function uc(t){return t=bt(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 Pd(t,e="dart",s=globalThis.hljs){if(!t)return"";const r=ws(t);try{return s.highlight(r,{language:e}).value}catch(n){console.warn("Syntax highlighting failed:",n);try{return s.highlight(r,{language:"json"}).value}catch{return bt(r)}}}function On(t,e={}){const{highlighter:s=globalThis.hljs}=e;let r='
    ';const n=String(t??"").split(` -`);let i=!1,o="";for(const a of n){if(a.startsWith("```")){if(i){const l=wm(o),u=Pd(o.trim(),l,s);r+=`
    -
    ${u}
    -
    `,o="",i=!1}else i=!0;continue}if(i){o+=a+` -`;continue}if(a.startsWith("# ")){const l=a.substring(2).trim();r+=`
    -

    - ${_m(l)} - ${bt(l)} -

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

    - ${ym(l)} - ${bt(l)} -

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

    ${uc(a)}

    `)}return r+="
    ",` -
    -
    -
    - Live Audit Report -
    - ${r} -
    - `}const bm="https://ccc-ffai-runner-y5cyj3473a-uw.a.run.app/deployCustomClasses";const Je="https://4tgke4.buildship.run",Ad={professional:"price_1T2ldCKszA2slvDXatdeCpbI",power:"price_1T2le9KszA2slvDXR4mPvw7M"},_n="ccc_auth_session",dc=new WeakSet;let G={email:null,sessionToken:null,isVerified:!1};function bs(t={}){return{tier:"free",status:"none",periodEnd:null,isLoading:!1,isResolved:!1,error:null,...t}}let fe=bs({isResolved:!0});const Em=`${Je}/service/runpipeline`,Sm="bs_user_id",xm="bs_identity_token",km=`${Je}/authUserCheck`;let Ge={userId:null,token:null,status:null,resolved:!1};const yn={free:2,professional:50,power:2e3},wn="ccc_subscription",hc=3,Im=new Set(["active","trialing","paid"]),lr="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"],Cm={"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 zt(t){return Cm[t]||t}const Fm=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 $d(t){return Fm.has(t)}const Eo=4,Ci=8*1024*1024,Pm="https://4tgke4.buildship.run/service/runpipeline-image";let Pt=[];function Am(t){return new Promise(e=>{const s=new FileReader;s.onload=()=>e(s.result),s.onerror=()=>e(null),s.readAsDataURL(t)})}async function $m(t){const e=new FormData;return e.append("file",t),(await fetch(Pm,{method:"POST",body:e})).json()}function Rm(t){if(Array.isArray(t)){const e=t[0];if(e&&typeof e=="object")for(const s of Object.keys(e)){if(s==="item"||s==="index")continue;const r=e[s];if(r&&typeof r=="object"){if(typeof r.file=="string")return r.file;if(typeof r.url=="string")return r.url}if(typeof r=="string")return r}return""}return typeof t=="string"?t:t&&typeof t=="object"&&(t.url||t.fileUrl||t.file_url||t.downloadUrl||t.imageUrl||t.image_url||t.file)||""}async function Tm(t){const e=Array.from(t.target.files||[]);if(!e.length)return;const s=e.filter(l=>l.size>Ci);s.length&&ue(`Skipped ${s.length} image(s) over the ${(Ci/1024/1024).toFixed(0)} MB limit.`,"warning");const r=e.filter(l=>l.size<=Ci);if(!r.length){t.target.value="";return}const n=Eo-Pt.length,o=r.slice(0,n).map(async l=>{const u=await Am(l);if(!u)return null;let c="";try{c=Rm(await $m(l))}catch{c=""}return{dataUrl:u,name:l.name,url:c}}),a=(await Promise.all(o)).filter(Boolean);t.target.value="",!(a.length&&!$d(document.getElementById("code-generator-model")?.value))&&(Pt.push(...a),r.length>n&&ue(`You can attach up to ${Eo} images.`,"info"),la())}function Nm(t){Pt.splice(t,1),la()}function la(){const t=document.getElementById("prompt-image-thumbnails"),e=document.getElementById("prompt-image-btn-label");t&&(t.innerHTML="",Pt.forEach((s,r)=>{const n=document.createElement("div");n.className="prompt-img-thumb",n.innerHTML=`Prompt image`,t.appendChild(n)}),e&&(e.textContent=Pt.length>=Eo?"Image limit reached":"Add images"))}function Rd(){const t=document.getElementById("prompt-image-upload");if(!t)return;const e=document.getElementById("code-generator-model"),s=$d(e?.value);t.classList.toggle("hidden",!s),!s&&Pt.length&&(Pt=[],la())}const Gt="ccc_usage",Td="google/gemini-3.7-flash",Nd="google/gemini-3.7-flash",Fi="google/gemini-3.7-flash",pc={professional:11,power:49},So={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 Mm(){const t=new AbortController,e=setTimeout(()=>t.abort(),5e3);try{const s=await fetch("https://open.er-api.com/v6/latest/AUD",{signal:t.signal});if(!s.ok)return;const r=await s.json();if(r.result!=="success"||!r.rates)return;const n=r.rates,i={AUD:1},o=new Set([...Object.keys(Ur),...Object.values(xo),...Object.values(So)]);for(const a of o)a!=="AUD"&&(typeof n[a]=="number"&&n[a]>0?i[a]=n[a]:Ur[a]&&(i[a]=Ur[a]));Hr=i}catch{}finally{clearTimeout(e)}}const xo={"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 Md(){try{const i=Intl.DateTimeFormat().resolvedOptions().timeZone;if(i&&xo[i])return xo[i]}catch{}const e=(navigator.language||"en-US").replace("-","_"),s=So[e];if(s)return s;const r=e.split("_")[0],n=So[r];return n||"USD"}function fc(t,e){const s=Hr[e]??Hr.USD,r=t*s,n=Math.round(r*100)/100;try{return new Intl.NumberFormat("en-US",{style:"currency",currency:e,minimumFractionDigits:0,maximumFractionDigits:n>=100||n%1===0?0:2}).format(n)}catch{return new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",minimumFractionDigits:0,maximumFractionDigits:2}).format(t*Hr.USD)}}const st="ccc_api_key_",_t="ccc_session_api_key_",it="ccc_encryption_key",cr="ccc_encryption_key_scope",Lm="ccc_keystore",bn="keys",ur="ccc_encryption_key_version";let ko=null,En=null,dr=!1,Sn=!1,gc=!1;class xn extends Error{constructor(){super("Secure browser key storage is unavailable."),this.name="CredentialStorageUnavailableError"}}function mc(){if(gc)return;gc=!0;const t="Secure browser key storage is unavailable. Existing credentials were left untouched; new credentials will be available only in this tab session.";console.warn(t),document.body&&ue(t,"warning")}function Ld(){return localStorage.getItem(ur)||""}function Io(){return crypto.randomUUID?.()||Dd(crypto.getRandomValues(new Uint8Array(16)))}function Om(){const t=Ld();if(t)return t;const e=Io();return localStorage.setItem(ur,e),e}function Es(){ko=null,En=null,dr=!1,Sn=!1}window.addEventListener("storage",t=>{t.key===ur&&Es()});function Dm(){return new Promise((t,e)=>{const s=indexedDB.open(Lm,1);s.onupgradeneeded=()=>{const r=s.result;r.objectStoreNames.contains(bn)||r.createObjectStore(bn)},s.onsuccess=()=>t(s.result),s.onerror=()=>e(s.error)})}async function ca(t,e){const s=await Dm();return new Promise((r,n)=>{const i=s.transaction(bn,t);let o;try{o=e(i.objectStore(bn))}catch(l){s.close(),n(l);return}let a;o.onsuccess=()=>{a=o.result},o.onerror=()=>n(o.error),i.oncomplete=()=>{s.close(),r(a)},i.onerror=()=>{s.close(),n(i.error||new Error("Encryption key transaction failed."))},i.onabort=()=>{s.close(),n(i.error||new Error("Encryption key transaction aborted."))}})}function Bm(t){return t instanceof CryptoKey&&t.algorithm?.name==="AES-GCM"&&t.extractable===!1&&t.usages.includes("encrypt")&&t.usages.includes("decrypt")}async function jm(){const t=await ca("readonly",e=>e.get(it));return Bm(t)?t:null}async function Od(t){await ca("readwrite",e=>e.put(t,it))}async function Um(){Es();try{await ca("readwrite",t=>t.delete(it))}catch(t){console.warn("Could not delete the stored encryption key:",t)}}async function Hm(){const t=sessionStorage.getItem(it);if(!t)return null;const e=await crypto.subtle.importKey("jwk",JSON.parse(t),{name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);return await Od(e),sessionStorage.removeItem(it),sessionStorage.removeItem(cr),localStorage.removeItem(st+"salt"),e}async function vc(t){const e=sessionStorage.getItem(it);if(e)return Sn=sessionStorage.getItem(cr)!=="session",crypto.subtle.importKey("jwk",JSON.parse(e),{name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);if(!t)throw new xn;const s=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!0,["encrypt","decrypt"]),r=await crypto.subtle.exportKey("jwk",s);return sessionStorage.setItem(it,JSON.stringify(r)),sessionStorage.setItem(cr,"session"),Sn=!1,crypto.subtle.importKey("jwk",r,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}async function Wm(t){if(sessionStorage.getItem(cr)==="session"&&sessionStorage.getItem(it))return mc(),dr=!0,vc(t);try{const e=await jm();if(e)return e;const s=await Hm();if(s)return s;const r=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);return await Od(r),r}catch(e){return console.warn("IndexedDB encryption-key storage failed:",e),mc(),dr=!0,vc(t)}}async function ua(t={}){const{allowSessionFallbackCreation:e=!0}=t,s=Om();En!==s&&Es();const r=ko||Wm(e);ko=r,En=s;try{return await r}catch(n){throw Es(),n}}async function zm(t){const e=await ua(),s=En,r=new TextEncoder,n=crypto.getRandomValues(new Uint8Array(12)),i=await crypto.subtle.encrypt({name:"AES-GCM",iv:n},e,r.encode(t)),o=new Uint8Array(n.length+i.byteLength);return o.set(n),o.set(new Uint8Array(i),n.length),{ciphertext:Dd(o),keyVersion:s,sessionFallback:dr}}async function qm(t,e={}){const{isSessionCredential:s=!1}=e;try{const r=await ua({allowSessionFallbackCreation:!1});if(dr&&!s&&!Sn)throw new xn;const n=Vm(t),i=n.slice(0,12),o=n.slice(12),a=await crypto.subtle.decrypt({name:"AES-GCM",iv:i},r,o);return new TextDecoder().decode(a)}catch(r){if(r instanceof xn)throw r;return console.error("Decryption failed:",r),null}}function Dd(t){const e=new Uint8Array(t);let s="";for(let r=0;r0}let hr="",kn="",Zs=null,yc=0;async function da(){sessionStorage.getItem(it)&&await ua(),hr=await Ee("flutterflow"),kn=await Ee("flutterflow_project_id"),Zm(),Zt()}function ha(){document.getElementById("api-keys-modal").classList.add("open"),fa(),hr&&Hd(hr)}function Bd(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("api-keys-modal");e&&e.classList.remove("open");const s=document.getElementById("walkthrough-modal");s&&(pa(),s.classList.add("open"))}let Et=1;function jd(){const t=document.querySelector(".wt-steps");return t?Array.from(t.querySelectorAll(".wt-step-card")):[]}function Dn(){const t=jd();t.length&&t.forEach((e,s)=>{const r=s+1;if(r===Et){e.classList.remove("opacity-60","bg-gray-50","border-gray-200"),e.classList.add("bg-blue-50","border-blue-200");const n=e.querySelector("div:first-child");n&&(n.classList.remove("bg-gray-400"),n.classList.add("bg-blue-500"),n.innerHTML=r)}else if(r0&&Et<=t&&(Et++,Dn())}function Km(){const t=document.getElementById("walkthrough-modal");t&&(Et=1,Dn(),t.classList.add("open"))}function Jm(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("walkthrough-modal");e&&e.classList.remove("open");const s=document.getElementById("walkthrough-dont-show");s&&s.checked&&localStorage.setItem("hasSeenWalkthrough","true")}function Ud(){if(G.isVerified&&Jt()&&fe.tier!=="free")return;if(!localStorage.getItem("hasSeenWalkthrough")){const e=document.getElementById("walkthrough-modal");e&&(Et=1,Dn(),e.classList.add("open"))}}async function fa(){const t=document.getElementById("flutterflow-api-key-input");hr?(t.value="",t.placeholder="Key saved (enter new to replace)"):t.placeholder="Enter your FlutterFlow API key",Ym()}function Ym(){wc("flutterflow","flutterflow-key-status"),wc("flutterflow_project_id","flutterflow-project-status")}function wc(t,e){const s=document.getElementById(e);if(!s)return;const r=s.querySelector(".key-status-dot"),n=s.querySelector("span");as(t)?(r.className="key-status-dot configured",n.className="text-green-600",n.textContent="User key configured"):(r.className="key-status-dot missing",n.className="text-gray-500",n.textContent="Not configured")}function Zt(){const t=y.step2Result&&y.step2Result.length>0,e=document.getElementById("btn-deploy-to-ff"),s=document.getElementById("btn-run-pipeline");s&&s.classList.remove("hidden"),e&&e.classList.toggle("hidden",!t)}function Zm(){const t=document.getElementById("api-keys-status");if(!t)return;const e=t.querySelectorAll(".key-status-dot"),s=["flutterflow"];e.forEach((r,n)=>{const i=s[n];i==="flutterflow"?as("flutterflow")&&as("flutterflow_project_id")?(r.className="key-status-dot configured",r.title="FlutterFlow (Fully configured)"):as("flutterflow")||as("flutterflow_project_id")?(r.className="key-status-dot env",r.title="FlutterFlow (Partially configured)"):(r.className="key-status-dot missing",r.title="FlutterFlow (Not configured)"):as(i)?(r.className="key-status-dot configured",r.title=i.charAt(0).toUpperCase()+i.slice(1)+" (User key)"):(r.className="key-status-dot missing",r.title=i.charAt(0).toUpperCase()+i.slice(1)+" (Not configured)")}),Zt()}async function Xm(){const t=document.getElementById("flutterflow-api-key-input"),e=document.getElementById("flutterflow-projects-select");t.value.trim()&&await _c("flutterflow",t.value);const s=e?.value.trim()||"";if(s){if(!Bn(s)){ue("The selected FlutterFlow project has an unexpected ID format.","error"),e.focus();return}await _c("flutterflow_project_id",s)}await da(),fa();const r=document.querySelector("#api-keys-modal .bg-blue-500"),n=r.textContent;r.textContent="Saved!",r.classList.remove("bg-blue-500","hover:bg-blue-600"),r.classList.add("bg-green-500"),setTimeout(()=>{r.textContent=n,r.classList.remove("bg-green-500"),r.classList.add("bg-blue-500","hover:bg-blue-600"),Bd()},1e3)}async function Qm(){if(!confirm("Are you sure you want to clear all stored API keys?"))return;localStorage.setItem(ur,Io()),Es(),localStorage.removeItem(st+"flutterflow"),localStorage.removeItem(st+"flutterflow_project_id"),sessionStorage.removeItem(_t+"flutterflow"),sessionStorage.removeItem(_t+"flutterflow_project_id"),sessionStorage.removeItem(it),sessionStorage.removeItem(cr),localStorage.removeItem(st+"salt"),await Um(),localStorage.setItem(ur,Io()),localStorage.removeItem(st+"flutterflow"),localStorage.removeItem(st+"flutterflow_project_id"),sessionStorage.removeItem(_t+"flutterflow"),sessionStorage.removeItem(_t+"flutterflow_project_id"),await da();const t=document.getElementById("flutterflow-projects-select");t&&(t.innerHTML=''),fa()}function Bn(t){return!t||t.trim().length<5||t.includes(" ")?!1:/^[a-zA-Z0-9-]+$/.test(t)}function ev(t,e){const s=document.getElementById(t);s&&(s.value?e?s.style.borderColor="#22c55e":s.style.borderColor="#ef4444":s.style.borderColor="")}function tv(){const t=document.getElementById("flutterflow-api-key-input");t&&(t.addEventListener("input",e=>{const s=e.target.value.trim().length>0;ev("flutterflow-api-key-input",s)}),t.addEventListener("blur",sv(async e=>{const s=e.target.value.trim();s&&await Hd(s)},500)))}function sv(t,e){let s;return function(...n){const i=()=>{clearTimeout(s),t(...n)};clearTimeout(s),s=setTimeout(i,e)}}async function Hd(t){const e=document.getElementById("flutterflow-projects-select"),s=document.getElementById("flutterflow-projects-error");if(!e){console.error("Projects dropdown element not found");return}e.innerHTML='',s&&s.classList.add("hidden");try{const n=await new gr(t,"").listProjects();if(!n||n.length===0){e.innerHTML='';return}e.innerHTML='',n.forEach(i=>{const o=document.createElement("option");o.value=i.id||i.projectId||"",o.textContent=i.name||i.projectName||`Project ${i.id}`,e.appendChild(o)}),kn&&(e.value=kn)}catch(r){console.error("Failed to fetch projects:",r),e.innerHTML='',s&&(s.textContent=`Failed to load projects: ${r.message}`,s.classList.remove("hidden"))}}function rv(t){const e=document.getElementById(t),r=e.nextElementSibling.querySelector("svg");e.type==="password"?(e.type="text",r.innerHTML=` - - `):(e.type="password",r.innerHTML=` - - - `)}let y={step1Result:null,step2Result:null,step3Result:null,bundleSpec:null,artifactBundle:null,bundleReview:null,selectedArtifactId:null,resultsViewMode:"summary",currentStep:0,isRunning:!1};function nv(){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 iv(){y.bundleSpec=or(y.step1Result,{artifactType:"CustomWidget",artifactName:"GeneratedWidget"})}function jn(){const t=gn(y.bundleSpec);y.artifactBundle=or(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=dg(y.artifactBundle);y.artifactBundle={...y.artifactBundle,warnings:[...y.artifactBundle.warnings,...e.findings.map(s=>s.message)],metadata:{...y.artifactBundle.metadata,compatibility:e}},y.selectedArtifactId=gn(y.artifactBundle).id}function Un(){const t=or(y.step3Result,{id:y.artifactBundle?.id,title:y.artifactBundle?.title}),e=new Map(t.artifacts.map(r=>[r.id,r.review])),s=new Map(t.artifacts.filter(r=>{const n=r.review;return n&&typeof n.fixedSource=="string"&&n.fixedSource.trim()}).map(r=>[r.id,r.review.fixedSource.trim()]));y.bundleReview=or({id:y.artifactBundle?.id,title:y.artifactBundle?.title,artifacts:y.artifactBundle?.artifacts?.map(r=>{const n=s.get(r.id)||null;return{...r,review:e.get(r.id)||r.review||y.step3Result||null,...n?{fixedCode:n}:{}}})||[],relationships:y.artifactBundle?.relationships,warnings:y.artifactBundle?.warnings})}function Wd(){const t=ga();return{artifactType:t.artifactType||"CustomWidget",artifactName:t.artifactName||"GeneratedWidget",fileName:t.fileName||""}}function ga(){const t=y.artifactBundle||y.bundleSpec||null;return(Array.isArray(t?.artifacts)?t.artifacts:[]).find(s=>s.id===y.selectedArtifactId)||gn(t)}function ma(){return ga().code||y.step2Result||""}async function ov(){try{await da()}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 av(t,e){const s=e?.trim()?` (${e.trim().slice(0,200)})`:"";return t===401?`Your FlutterFlow API key was rejected (401 Unauthorized)${s}. Re-enter a current key under API Keys settings, then try again.`:`Listing FlutterFlow projects was denied (403)${s}. 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 gr{constructor(e,s,r="main",n=Wr.production){this.apiKey=e,this.baseUrl=n,this._projectId=s,this._branchName=r,this._endpoint=n}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 s=null;for(const r of e)try{const n=await fetch(`${this.baseUrl}exportCode`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify(r)});if(!n.ok){const a=await n.text();s=new Error(`Export failed: ${n.status} - ${a}`);continue}const i=await n.json(),o=i?.value?.project_zip||i?.project_zip;if(!o){s=new Error("Export response did not include project source.");continue}return o}catch(n){s=n}throw s||new Error("Export failed for an unknown reason.")}async fetchProjectSource(){const e=await this.exportProjectZip(),s=await JSZip.loadAsync(e,{base64:!0}),r=Object.keys(s.files).filter(a=>!s.files[a].dir&&(a==="pubspec.yaml"||a.endsWith("/pubspec.yaml"))).sort((a,l)=>a.split("/").length-l.split("/").length)[0];if(!r)throw new Error("Export did not contain a pubspec.yaml.");const n=r.slice(0,r.length-12),i=new Map,o=Object.keys(s.files).filter(a=>{if(s.files[a].dir||!a.startsWith(n))return!1;const l=a.slice(n.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=>{i.set(a.slice(n.length),await s.files[a].async("string"))})),{pubspecYaml:await s.files[r].async("string"),files:i}}async pushCodeWithRetry(e,s=3){const r=[Wr.production,Wr.staging],n=Math.max(0,r.indexOf(this._endpoint));for(let i=0;isetTimeout(d,1e3*(i+1)));continue}return l}catch(l){console.warn(`Push to ${a} failed: ${l.message}, trying next...`),await new Promise(u=>setTimeout(u,1e3*(i+1)))}}throw new Error("All API endpoints failed after retries")}async pushCode(e){return this.pushCodeWithRetry(e)}parseProjectsResponse(e){if(e?.success&&typeof e.value=="string")try{const r=JSON.parse(e.value);if(r&&Array.isArray(r.entries))return r.entries.map(n=>({id:n.id,name:n.project?.name||n.id}))}catch(r){console.error("Failed to parse stringified project value:",r)}const s=e?.projects||e?.items||e?.entries||(Array.isArray(e)?e:[]);return Array.isArray(s)?s:[]}async listProjects(){console.log("Listing projects for API key");const e=[`${this.baseUrl}listProjects`,"https://api.flutterflow.io/v2/l/listProjects"];let s=0,r="";for(const n of e){const i=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify({project_type:"ALL",deserialize_response:!0})});if(i.ok)return n!==e[0]&&console.log(`listProjects answered on legacy path ${n}`),this.parseProjectsResponse(await i.json());if(s=i.status,r=await i.text(),console.warn(`listProjects via ${n} returned ${s}: ${r}`),i.status===401||i.status===403)throw new Error(av(i.status,r));if(i.status!==404)throw new Error(`List projects failed: ${i.status} - ${r}`)}throw new Error(`List projects failed: ${s} - ${r}`)}}async function va(t){const e=t.clone();let s;try{s=await t.json()}catch{const i=await e.text();if(!t.ok)return{success:!1,responseCode:t.status,errorMessage:i||`HTTP ${t.status}`,errorMap:new Map};throw new Error(`Invalid JSON response: ${i}`)}if(!t.ok){let n=s.message||`HTTP ${t.status}`,i=new Map;if(s.errors)i=new Map(Object.entries(s.errors));else if(!s.message&&typeof s=="object"){const o=Object.keys(s).filter(a=>a.endsWith(".dart")&&Array.isArray(s[a]));o.length>0&&(i=new Map(Object.entries(s)),n=o.flatMap(l=>s[l].map(u=>`${l}: ${u.errorMessage}`)).join(` -`)||`HTTP ${t.status}`)}return{success:!1,responseCode:t.status,errorMessage:n,errorMap:i}}let r={};if(s.value)try{r=typeof s.value=="string"?JSON.parse(s.value):s.value}catch(n){console.warn("Ignoring malformed push response value:",n)}return{success:!0,responseCode:t.status,errorMap:new Map(Object.entries(r))}}function _a(t,e){return{401:"Authentication failed. Please check your FlutterFlow API key.",403:"Access denied. You may not have permission to modify this project.",404:"Project not found. Please check your Project ID.",409:"Conflict detected. The project may have been modified elsewhere.",422:"Validation failed: Invalid request format",429:"Rate limit exceeded. Please try again in a few minutes.",500:"FlutterFlow server error. Please try again later.",503:"FlutterFlow service temporarily unavailable."}[t]||`FlutterFlow API error: ${`HTTP ${t}`}`}const U={ACTION:"A",WIDGET:"W",FUNCTION:"F",CODE_FILE:"C",DEPENDENCIES:"D",OTHER:"O"},zd=/class\s+\w+\s+extends\s+(?:StatelessWidget|StatefulWidget)\b/,qd=/extends\s+State<\w+>/;function lv(t,e=""){if(t==="pubspec.yaml")return U.DEPENDENCIES;if(!t.endsWith(".dart")||t.endsWith("index.dart"))return U.OTHER;if(t==="custom_functions.dart")return U.FUNCTION;if(e){const s=zd.test(e),r=qd.test(e);if(s||r)return U.WIDGET;if(/^\s*Future(?:<[^>]+>)?\s+\w+\s*\(/m.test(e))return U.ACTION;if(e.match(/^\s*(String|int|double|bool|List|Map|dynamic|void)\s+\w+\s*\(/m))return U.FUNCTION}return U.CODE_FILE}function Vd(t,e){switch(e){case U.ACTION:return`lib/custom_code/actions/${t}`;case U.WIDGET:return`lib/custom_code/widgets/${t}`;case U.FUNCTION:return"lib/flutter_flow/custom_functions.dart";case U.CODE_FILE:return`lib/custom_code/${t}`;case U.DEPENDENCIES:return"pubspec.yaml";case U.OTHER:return`lib/custom_code/${t}`;default:return t}}async function ya(t,e=new Map){return Gf(t,e)}const Co=new Map;function Gd(t){return`${t.baseUrl}|${t.projectId}|${t.branchName}`}function Hn(t){Co.delete(Gd(t))}async function wa(t,e,s,r,n=""){const i=xg(e,s);if(i.length===0)return{remoteFiles:s,syncFileMap:e,unverified:[]};const o=sm(i,n),a={...o.manifest,sources:o.sources},l=o.skipped.map(d=>d.reason);l.forEach(d=>console.warn(`[custom class deploy] ${d}`)),console.log(`Provisioning ${i.length} new FlutterFlow custom code file(s) before sync.`),be.set("provision");const u=await fetch(bm,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:t.apiKey,projectId:t.projectId,baseUrl:t.baseUrl,commitMessage:r,customClasses:i,verification:a,stream:!0})}),c=await nm(u,{onPhase:d=>be.setSubstatus(d),onLog:d=>console.log(`[custom class deploy] ${d}`)});if(!c.success){const d=c.details?` ${c.details}`:"";throw new Error(`${c.error||"FlutterFlow custom class provisioning failed."}${d}`)}return Hn(t),c.verificationSkipped&&(console.warn(`[custom class deploy] ${c.verificationSkipped}`),l.push(c.verificationSkipped)),{remoteFiles:s,syncFileMap:kg(e,i),unverified:l}}async function ba(t,e={}){const s=Gd(t);let r=Co.get(s);if(r===void 0){try{r=await t.fetchProjectSource()}catch(l){throw new Error(`Could not read your project's pubspec.yaml (${l.message}). Deploy was stopped so your existing package dependencies aren't overwritten. Check your FlutterFlow API key and project, then try again.`)}const a=Cd(r.pubspecYaml);if(!a.valid)throw new Error(`Your project's pubspec.yaml could not be read reliably (${a.errors.join("; ")}). Deploy was stopped so your existing package dependencies aren't overwritten.`);Co.set(s,r)}const n=await gm(r.pubspecYaml,e),i=Yg(r.pubspecYaml,n.overrides),o=Jg(i.yaml,n.additions);return n.warnings.forEach(a=>console.warn(`[pubspec] ${a}`)),o.added.length>0&&console.log("Adding dependencies:",o.added.map(a=>`${a}: ${n.additions[a]||"any"}`).join(", "),n.sdk.dartSdkFloor?`(resolved for Dart ${n.sdk.dartSdkFloor})`:""),n.kept.forEach(({name:a,constraint:l})=>console.log(`Keeping your existing ${a}: ${l||"(non-version source)"}`)),{...o,overridden:i.overridden,warnings:n.warnings,remoteFiles:r.files}}function cv(t){const e=[],s=[];t.content.length>5e4&&s.push("Code file is large (>50KB). This may take longer to commit."),t.content.length>1e5&&e.push("Code file is too large (>100KB). Consider splitting into smaller components.");const r=t.content.split(` -`).length;r>500&&s.push(`Code has ${r} lines. Consider breaking it into smaller widgets.`),t.content.includes("setState")&&t.codeType===U.ACTION&&s.push("Using setState in a Custom Action may not work as expected. Consider using a Custom Widget."),t.content.includes("dynamic")&&!t.content.includes("?")&&s.push('Code uses "dynamic" types. Consider adding explicit types for better null safety.'),t.content.match(/Color\(0xFF[0-9A-Fa-f]{6}\)/)&&s.push("Code contains hardcoded colors. Consider using FlutterFlowTheme.of(context) for theme consistency.");const n=t.content.match(/print\s*\(/g);n&&n.length>3&&s.push(`Code contains ${n.length} print statements. Consider removing debug prints before committing.`);const i=Wg(t.content);if(i&&e.push(`FlutterFlow cannot format this code - ${i}. Fix or regenerate before committing.`),t.codeType===U.WIDGET){const o=wd(t.content),a=jg(t.fileName);if(o.length===0)e.push("No public widget class found (must extend StatelessWidget or StatefulWidget).");else if(!o.includes(a)){const l=`${bd(o[0])}`;e.push(`Widget class name "${o[0]}" does not match the file name "${t.fileName}". FlutterFlow derives the widget from the file name, so it will report "No widget ${a} found". Rename the file to "${l}" or the class to match before committing.`)}}return{canProceed:e.length===0,issues:e,warnings:s}}function Kd(t,e={}){const{artifactType:s="CustomWidget",artifactName:r="GeneratedCode",fileName:n}=e,i=Dg(t);let o=n||r;if(s==="CustomFunction")o="custom_functions.dart";else if(s==="CustomWidget"){const u=wd(i)[0],c=u?bd(u):null;c&&o!==c?(console.warn(`Commit file name "${o}" does not match declared widget class "${u}"; renaming to "${c}" so FlutterFlow can find the widget.`),o=c):o.endsWith(".dart")||(o+=".dart")}else o.endsWith(".dart")||(o+=".dart");let a=U.CODE_FILE;switch(s){case"CustomAction":a=U.ACTION;break;case"CustomWidget":a=U.WIDGET;break;case"CustomFunction":a=U.FUNCTION;break;case"CustomClass":case"CodeFile":a=U.CODE_FILE;break}let l="";return a===U.WIDGET?l=`// Automatic FlutterFlow imports -import '/flutter_flow/flutter_flow_theme.dart'; -import '/flutter_flow/flutter_flow_util.dart'; -import 'package:flutter/material.dart'; -// Begin custom widget code -// DO NOT REMOVE OR MODIFY THE CODE ABOVE! - -`:a===U.ACTION?l=`// Automatic FlutterFlow imports -import '/flutter_flow/flutter_flow_theme.dart'; -import '/flutter_flow/flutter_flow_util.dart'; -import 'package:flutter/material.dart'; -// Begin custom action code -// DO NOT REMOVE OR MODIFY THE CODE ABOVE! - -`:a===U.FUNCTION&&(l=`// Automatic FlutterFlow imports -import 'dart:convert'; -import 'dart:math' as math; - -import 'package:flutter/material.dart'; -import 'package:google_fonts/google_fonts.dart'; -import 'package:intl/intl.dart'; -import 'package:timeago/timeago.dart' as timeago; -import '/flutter_flow/lat_lng.dart'; -import '/flutter_flow/place.dart'; -import '/flutter_flow/uploaded_file.dart'; - -`),{content:fg(i,l),fileName:o,codeType:a,artifactType:s,artifactName:r}}function uv(t){const e={};for(const s of ra(t))e[s]="";return e}function dv(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 hv(t,e,s,r=new Set,n=""){const i=[],o=zd.test(e),a=qd.test(e);return s===U.WIDGET&&!o&&!a&&i.push("No widget class definition found (must extend StatelessWidget or StatefulWidget)"),{valid:i.length===0,errors:i}}function Wn(t){const e=[],s=[];if(!t||t.size===0)return e.push("No files to commit"),{valid:!1,errors:e,warnings:s};const r=new Set(Array.from(t.values()).flatMap(n=>Tn(n.content||"")));for(const[n,i]of t.entries()){if((!i.content||i.content.trim().length===0)&&e.push(`File ${n} is empty`),i.content&&i.content.length>1e5&&s.push(`File ${n} is very large (>100KB)`),n.endsWith(".dart")){const o=hv(n,i.content,i.type,r,i.artifactName);o.valid||e.push(...o.errors.map(a=>`${n}: ${a}`))}if(n==="pubspec.yaml"){const o=Cd(i.content);o.valid||e.push(...o.errors)}}return{valid:e.length===0,errors:e,warnings:s}}const V={IDLE:"IDLE",PREPARING:"PREPARING",VALIDATING:"VALIDATING",PUSHING:"PUSHING",SUCCESS:"SUCCESS",ERROR:"ERROR"},K={currentState:V.IDLE,startTime:null,endTime:null,error:null,result:null,filesProcessed:0,totalFiles:0,reset(){this.currentState=V.IDLE,this.startTime=null,this.endTime=null,this.error=null,this.result=null,this.filesProcessed=0,this.totalFiles=0},setState(t){if(!Object.values(V).includes(t)){console.error(`Invalid commit state: ${t}`);return}this.currentState=t,t===V.PREPARING&&(this.startTime=Date.now()),(t===V.SUCCESS||t===V.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(V.ERROR)},setSuccess(t){this.result=t,this.setState(V.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===V.PREPARING||this.currentState===V.VALIDATING||this.currentState===V.PUSHING}};async function pv(t,e,s={}){let{codeType:r="W"}=s;const{pubspecDeps:n={},artifactName:i=e}=s;r==="CustomWidget"&&(r=U.WIDGET),r==="CustomAction"&&(r=U.ACTION),r==="CustomFunction"&&(r=U.FUNCTION),r==="CustomClass"&&(r=U.CODE_FILE),r==="CodeFile"&&(r=U.CODE_FILE),K.reset(),K.setState(V.PREPARING);try{const o=await Ee("flutterflow"),a=await Ee("flutterflow_project_id");if(!o||!a)throw new Error("FlutterFlow credentials not configured. Please set your API key and Project ID in the API Keys settings.");if(!Bn(a))throw new Error("Invalid FlutterFlow Project ID format.");const l=fr(),u=new gr(o,a,"main",l);K.setState(V.VALIDATING);const c=new Map,d=r||lv(e,t),h=Vd(e,d);c.set(e,{artifactName:i,content:t,type:d,path:h}),K.setProgress(0,c.size);const p=Wn(c);if(!p.valid)throw new Error(`Validation failed: -${p.errors.join(` -`)}`);const f=await ba(u,n),g=f.yaml,m=await wa(u,c,f.remoteFiles,`Provision ${i} custom class`,g),_=await ya(m.syncFileMap,m.remoteFiles),w=new Map(m.syncFileMap);w.set("pubspec.yaml",{content:g,type:"D",path:"pubspec.yaml"}),be.set("package");const E=await Ea(w),I={project_id:a,zipped_custom_code:E,uid:`web_${Date.now()}`,branch_name:u.branchName,serialized_yaml:g,file_map:_.fileMapContents,functions_map:_.functionsMapContents};K.setState(V.PUSHING),K.setProgress(1,c.size),Hn(u),be.set("push");const F=await u.pushCode(I),P=await va(F);if(P.success)K.setSuccess({fileCount:c.size,projectId:a,warnings:P.errorMap&&P.errorMap.size>0?Array.from(P.errorMap.entries()):[]});else{const B=P.errorMessage||_a(P.responseCode);throw new Error(B)}return{success:!0,message:`Successfully committed ${e} to FlutterFlow project ${a}`,addedDependencies:f.added,unverified:m.unverified,warnings:P.errorMap?Array.from(P.errorMap.entries()):[]}}catch(o){return console.error("Commit failed:",o),K.setError(o),{success:!1,error:o.message,state:K.currentState}}}async function Ea(t){const e=new JSZip;for(const[s,r]of t.entries())e.file(s,r.content);return e.generateAsync({type:"base64",compression:"DEFLATE",compressionOptions:{level:6}})}async function fv(t,e={}){const{artifactType:s,artifactName:r,fileName:n,pipelineResult:i}=e;console.log(`Starting commit for ${r} (${s})`);try{K.setState(V.PREPARING);const o=Kd(t,{artifactType:s,artifactName:r,fileName:n}),a=uv(o.content);console.log("Detected dependencies:",a),K.setState(V.VALIDATING);const l=await Ee("flutterflow"),u=Zs||await Ee("flutterflow_project_id");if(!l)throw new Error("FlutterFlow API Key not configured. Please add it in API Keys settings.");if(!u)throw new Error("FlutterFlow Project ID not configured. Please add it in API Keys settings.");if(!Bn(u))throw new Error("Invalid FlutterFlow Project ID format.");const c=new Map;c.set(o.fileName,{artifactName:r,content:o.content,type:o.codeType,path:Vd(o.fileName,o.codeType),functionName:o.codeType===U.FUNCTION?r:void 0}),K.setProgress(0,c.size);const d=Wn(c);if(!d.valid)throw new Error(`File validation failed: -${d.errors.join(` -`)}`);d.warnings.length>0&&console.warn("Validation warnings:",d.warnings),K.setState(V.PUSHING);const h=fr(),p=new gr(l,u,"main",h),f=await ba(p,a),g=f.yaml,m=await wa(p,c,f.remoteFiles,`Provision ${r} custom class`,g),_=await ya(m.syncFileMap,m.remoteFiles),w=new Map(m.syncFileMap);w.set("pubspec.yaml",{content:g,type:U.DEPENDENCIES,path:"pubspec.yaml"}),be.set("package");const E=await Ea(w),I={project_id:u,zipped_custom_code:E,uid:`web_${Date.now()}`,branch_name:p.branchName,serialized_yaml:g,file_map:_.fileMapContents,functions_map:_.functionsMapContents};K.setProgress(1,c.size),Hn(p),be.set("push");const F=await p.pushCode(I),P=await va(F);if(P.success){const B={...dv(o,i),projectId:u};return K.setSuccess({...B,fileCount:c.size,warnings:P.errorMap?Array.from(P.errorMap.entries()):[]}),{success:!0,message:`Successfully committed ${o.fileName} to FlutterFlow`,metadata:B,addedDependencies:f.added,unverified:m.unverified,warnings:P.errorMap?Array.from(P.errorMap.entries()):[],elapsedTime:K.getElapsedTime()}}else{const B=P.errorMessage||_a(P.responseCode),S=new Error(B);throw S.errorMap=P.errorMap,S}}catch(o){console.error("Commit execution failed:",o),K.setError(o);let a=new Map;if(o.errorMap)a=o.errorMap;else if(o.message&&o.message.includes("{"))try{const l=o.message.match(/\{[\s\S]*\}/);if(l){const u=JSON.parse(l[0]);a=new Map(Object.entries(u))}}catch(l){console.warn("Failed to parse error map from commit response:",l)}return{success:!1,error:o.message,errorMap:a,state:K.currentState,elapsedTime:K.getElapsedTime()}}}async function gv(t,e={}){const{pipelineResult:s}=e;try{if(K.setState(V.PREPARING),t.errors?.length>0)throw new Error(`Bundle validation failed: -${t.errors.join(` -`)}`);const r=new Map(t.fileEntries.map(I=>[I.fileName,{artifactId:I.artifactId,artifactName:I.artifactName,content:I.content,type:I.type,path:I.path,functionName:I.type===U.FUNCTION?I.artifactName:void 0}]));K.setProgress(0,r.size);const n=Wn(r);if(!n.valid)throw new Error(`File validation failed: -${n.errors.join(` -`)}`);K.setState(V.VALIDATING);const i=await Ee("flutterflow"),o=Zs||await Ee("flutterflow_project_id");if(!i)throw new Error("FlutterFlow API Key not configured. Please add it in API Keys settings.");if(!o)throw new Error("FlutterFlow Project ID not configured. Please add it in API Keys settings.");if(!Bn(o))throw new Error("Invalid FlutterFlow Project ID format.");K.setState(V.PUSHING);const a=fr(),l=new gr(i,o,"main",a),u=await ba(l,t.dependencies),c=u.yaml,d=await wa(l,r,u.remoteFiles,`Provision ${t.title} custom classes`,c),h=await ya(d.syncFileMap,d.remoteFiles),p=new Map(d.syncFileMap);p.set("pubspec.yaml",{content:c,type:U.DEPENDENCIES,path:"pubspec.yaml"}),be.set("package");const f=await Ea(p),g={project_id:o,zipped_custom_code:f,uid:`web_${Date.now()}`,branch_name:l.branchName,serialized_yaml:c,file_map:h.fileMapContents,functions_map:h.functionsMapContents};K.setProgress(1,r.size),Hn(l),be.set("push");const m=await l.pushCode(g),_=await va(m);if(_.success){const I={...s,artifactType:"Bundle",artifactName:t.title,fileName:`${t.fileEntries.length} artifacts`,codeSize:t.fileEntries.reduce((F,P)=>F+P.content.length,0),projectId:o};return K.setSuccess({...I,fileCount:r.size,warnings:_.errorMap?Array.from(_.errorMap.entries()):[]}),{success:!0,message:`Successfully committed ${t.fileEntries.length} artifacts to FlutterFlow`,metadata:I,addedDependencies:u.added,unverified:d.unverified,warnings:_.errorMap?Array.from(_.errorMap.entries()):[],elapsedTime:K.getElapsedTime()}}const w=_.errorMessage||_a(_.responseCode),E=new Error(w);throw E.errorMap=_.errorMap,E}catch(r){return console.error("Bundle commit execution failed:",r),K.setError(r),{success:!1,error:r.message,errorMap:r.errorMap||new Map,state:K.currentState,elapsedTime:K.getElapsedTime()}}}async function mv(t,e=[]){const s=Qo("architect");try{return await In("architect",Td,Mf(t),s,e)}catch(r){throw r.isModelArmor?r:new Error(`Prompt Architect failed: ${r.message}`)}}async function zn(t,e,s=[]){const r=Lf(t),n=Qo("generator",y.bundleSpec);try{return await In("generator",e,r,n,s)}catch(i){if(i.isModelArmor)throw i;if(e!==Fi){console.warn(`Code Generator failed with ${e}, retrying with fallback model:`,i.message);try{return await In("generator",Fi,r,n,s)}catch(o){throw o.isModelArmor?o:new Error(`Code Generator failed: primary (${e}): ${i.message} | fallback (${Fi}): ${o.message}`)}}throw new Error(`Code Generator failed: ${i.message}`)}}async function qn(t,e=null){const s={...Qo("review",y.artifactBundle||y.bundleSpec),architect_output:e};try{return await In("review",Nd,Of(t),s)}catch(r){throw r.isModelArmor?r:new Error(`Code Review failed: ${r.message}`)}}function Sa(t,e){return t.isModelArmor?`${t.userTitle}: ${t.userMessage}`:`${e}: ${t.message}`}function Fo(t,e){const s=document.getElementById(`step${t}-item`),r=document.getElementById(`step${t}-status`);!s||!r||(s.classList.remove("active","completed","error"),r.classList.remove("running","completed","error"),e==="active"?(s.classList.add("active"),r.classList.add("running"),r.innerHTML=` - - `):e==="completed"?(s.classList.add("completed"),r.classList.add("completed"),r.innerHTML=` - - `):e==="error"?(s.classList.add("error"),r.classList.add("error"),r.innerHTML=` - - `):r.innerHTML=` - - `)}function ve(t,e){const s=document.getElementById(`step${t}-loading`),r=document.getElementById(`step${t}-result`);e?(s.classList.remove("hidden"),r.classList.add("hidden"),Fo(t,"active")):(s.classList.add("hidden"),r.classList.remove("hidden"),Fo(t,"completed"))}function vv(t){const e=document.getElementById(`${t}-content`),s=document.getElementById(`${t}-chevron`);e.classList.contains("open")?(e.classList.remove("open"),s&&(s.style.transform="rotate(0deg)")):(e.classList.add("open"),s&&(s.style.transform="rotate(180deg)"))}function _v(t){ze(parseInt(t.replace("step","")))}function ze(t){for(let o=1;o<=3;o++){const a=document.getElementById(`step${o}-item`);a&&a.classList.remove("active")}const e=document.getElementById(`step${t}-item`);e&&e.classList.add("active"),Yt();const s=document.getElementById("ready-state");s&&s.classList.add("hidden");for(let o=1;o<=3;o++){const a=document.getElementById(`step${o}-content`);a&&a.classList.add("hidden")}const r=document.getElementById(`step${t}-content`);r&&r.classList.remove("hidden");const n=document.getElementById("stage-title"),i={1:"Prompt Architect",2:"Code Generator",3:"Code Review"};n&&(n.textContent=i[t]||"Active Workflow Stage")}function yv(t){const e=document.getElementById(t);if(!e)return;const s=e.dataset.raw||e.textContent;navigator.clipboard.writeText(s).then(()=>{const n=e.closest(".code-container")?.querySelector(".copy-btn");n&&(n.classList.add("copied"),n.innerHTML=' Copied!',setTimeout(()=>{n.classList.remove("copied"),n.innerHTML=' Copy'},2e3))}).catch(r=>{console.warn("Failed to copy to clipboard:",r)})}function Po(t){const e=$o(t);console.log(`Step 1 (Prompt Architect): ${zt(Td)}`),console.log(e!==t?`Step 2 (Code Generator): ${zt(t)} → ${zt(e)} (Free Tier fallback)`:`Step 2 (Code Generator): ${zt(t)}`),console.log(`Step 3 (Code Review): ${zt(Nd)}`)}async function wv(){if(console.log("runRefinement called"),y.isRunning)return;const t=document.getElementById("code-generator-model").value;y.isRunning=!0,xa("standardRegenerate",y.step2Result,y.step1Result);const e=document.querySelectorAll(".btn-refine-action");e.forEach(s=>{s.disabled=!0,s.innerHTML=` - - - Refining...`});try{const s=ga(),r=Df({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,artifactId:s.id,userFeedback:"Fix the issues listed in the audit report."});Kn(),nt(2),ze(2),ve(2,!0),y.step2Result=await zn(r,t),jn();const n=document.getElementById("step2-output"),i=ws(y.step2Result);n.textContent=i,n.dataset.raw=i,ve(2,!1),ze(3),nt(3),ve(3,!0),y.step3Result=await qn(y.step2Result,y.step1Result),Un();const o=document.getElementById("step3-output");o.textContent=y.step3Result,ve(3,!1),$t();const a=On(y.step3Result);Jn(i,a)}catch(s){console.error("Refinement failed:",s),$t(),ue(Sa(s,"Refinement failed"),"error")}finally{y.isRunning=!1,e.forEach(s=>{s.disabled=!1,s.textContent="Refine & Regenerate"}),Zt()}}async function xa(t,e,s){const r=`${Je}/connectFeedback`,n={type:t,code:e,input:s};try{const i=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!i.ok){const a=await i.text();return console.error(`callEndpoint failed: ${i.status} ${i.statusText}`,a),{success:!1,status:i.status,error:a}}const o=await i.json();return console.log("Telemetry success:",o),o}catch(i){return console.error("callEndpoint failed:",i),{success:!1,error:i.message}}}function bv(){const t=document.getElementById("ff-error-paste-input");t&&(t.value="")}async function Ev(){const t=document.getElementById("ff-error-paste-input"),e=t?.value?.trim();if(!e){t?.focus(),t?.classList.add("ring-2","ring-red-400","border-red-300"),setTimeout(()=>t?.classList.remove("ring-2","ring-red-400","border-red-300"),2e3);return}if(!y.step2Result){ue("No generated code found. Please run the full pipeline first.","warning");return}if(y.isRunning)return;const s=document.getElementById("code-generator-model").value;y.isRunning=!0,xa("flutterflowError",y.step2Result,e);const r=document.getElementById("btn-fix-from-errors");r&&(r.disabled=!0,r.innerHTML=` - - Fixing…`);try{const n=fd({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,userFeedback:e});ah(),Kn(),nt(2),ze(2),ve(2,!0),y.step2Result=await zn(n,s),jn();const i=document.getElementById("step2-output"),o=ws(y.step2Result);i.textContent=o,i.dataset.raw=o,ve(2,!1),ze(3),nt(3),ve(3,!0),y.step3Result=await qn(y.step2Result,y.step1Result),Un();const a=document.getElementById("step3-output");a.textContent=y.step3Result,ve(3,!1),$t();const l=On(y.step3Result);Jn(o,l),t&&(t.value="")}catch(n){console.error("Fix from errors failed:",n),$t(),ue(Sa(n,"Failed to fix errors"),"error")}finally{y.isRunning=!1,r&&(r.disabled=!1,r.textContent="Fix Errors & Regenerate"),Zt()}}async function Ao(){if(console.log("runThinkingPipeline called"),y.isRunning)return;localStorage.setItem("hasSeenWalkthrough","true");const t=document.getElementById("pipeline-input").value,e=document.getElementById("code-generator-model").value;if(!t.trim()){ue("Please describe your FlutterFlow widget first.","warning");return}if(!await Hv())return;await Lv();const s=$o(e);t.length;const r=document.getElementById("btn-run-pipeline");y.isRunning=!0,nv(),r.disabled=!0,r.innerHTML=` - - - Running...`,Po(s);try{Yt();const n=document.getElementById("ready-state");n&&n.classList.add("hidden");const i=document.getElementById("paywall-exhausted");i&&i.classList.add("hidden"),Kn(),ze(1),nt(1),ve(1,!0);const o=Pt.filter(p=>p.url).map(p=>({url:p.url}));y.step1Result=await mv(t,o),iv();const a=document.getElementById("step1-output"),l=ws(y.step1Result);a.textContent=l,a.dataset.raw=l,ve(1,!1),ze(2),nt(2),ve(2,!0),y.step2Result=await zn(y.step1Result,s,o),jn();const u=document.getElementById("step2-output"),c=ws(y.step2Result);u.textContent=c,u.dataset.raw=c,ve(2,!1),ze(3),nt(3),ve(3,!0),y.step3Result=await qn(y.step2Result,y.step1Result),Un();const d=document.getElementById("step3-output");d.textContent=y.step3Result,ve(3,!1),$t();const h=On(y.step3Result);Jn(c,h)}catch(n){if(console.error("Pipeline failed:",n),$t(),n.isUsageLimit){const{count:c}=Vn();Aa(c,Pa(),{openModal:!0});return}n.message,$o(document.getElementById("code-generator-model").value);const o=vm(n,{architect:1,generator:2,review:3});ze(o);const a=document.getElementById(`step${o}-result`),l=document.getElementById(`step${o}-loading`),u=document.getElementById(`step${o}-output`);if(l&&l.classList.add("hidden"),a&&a.classList.remove("hidden"),u)if(n.isModelArmor)u.innerHTML=``;else{let c=n.message;n.message.includes("image input")?c=`This model doesn't support image input. Please use ${zt(lr)} for image-based requests or remove image references from your prompt.`:(n.message.includes("Load failed")||n.message.includes("CORS"))&&(c="API connection failed. This might be due to CORS restrictions or network issues. Please check your API key and try again."),u.innerHTML=`
    -

    Connection Error

    -

    ${j(c)}

    -
    -

    Check if API key is valid

    -

    Try using a different model

    -

    Ensure network allows API calls

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

    FlutterFlow Commit Failed

    -

    ${j(t.error)}

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

    Errors:

    -
      `;for(const[n,i]of e.entries()){const o=Ed(i);s+=`
    • - ${j(n)}: ${j(o)} -
    • `}s+="
    "}s+="
    ",s+=`
    - -
    `;const r=document.getElementById("step3-output");r&&(r.innerHTML=s,document.getElementById("btn-regenerate-from-error")?.addEventListener("click",()=>{Cv(t.error,e)}))}async function Cv(t,e){if(y.isRunning)return;const s=document.getElementById("code-generator-model").value;y.isRunning=!0;const r=document.getElementById("btn-regenerate-from-error");r&&(r.disabled=!0,r.innerHTML=` - - Fixing...`);try{let n=`The previous code had the following errors when committing to FlutterFlow: - -`;if(e&&e.size>0)for(const[c,d]of e.entries()){const h=Ed(d);n+=`File: ${c} -Error: ${h} - -`}else n+=`${t} -`;const i=fd({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,userFeedback:n});Kn(),nt(2),ze(2),ve(2,!0),y.step2Result=await zn(i,s),jn();const o=document.getElementById("step2-output"),a=ws(y.step2Result);o.textContent=a,o.dataset.raw=a,ve(2,!1),ze(3),nt(3),ve(3,!0),y.step3Result=await qn(y.step2Result,y.step1Result),Un();const l=document.getElementById("step3-output");l.textContent=y.step3Result,ve(3,!1),$t();const u=On(y.step3Result);Jn(a,u)}catch(n){console.error("Regeneration failed:",n),$t(),ue(Sa(n,"Regeneration failed"),"error")}finally{y.isRunning=!1,r&&(r.disabled=!1,r.textContent="Fix Errors & Regenerate"),Zt()}}async function Fv(){const t=document.getElementById("ff-status-dot"),e=document.getElementById("ff-status-text");if(!t||!e)return;const s=await Ee("flutterflow"),r=await Ee("flutterflow_project_id");s&&r?(t.className="w-2 h-2 rounded-full bg-green-500",e.textContent="FlutterFlow credentials configured",e.className="text-green-600"):s||r?(t.className="w-2 h-2 rounded-full bg-yellow-500",e.textContent="FlutterFlow credentials incomplete",e.className="text-yellow-600"):(t.className="w-2 h-2 rounded-full bg-red-500",e.textContent="FlutterFlow credentials not configured",e.className="text-red-600")}async function Pv(t){try{const e=await fetch(`${Je}/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 Av(t){try{const s=await(await fetch(`${Je}/auth/verify-magic-link`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:t})})).json();if(s.error||!s.email||!s.sessionToken)throw new Error(s.error||"Invalid or expired link");return s}catch(e){throw console.error("verifyMagicLink failed:",{message:e.message,stack:e.stack}),e}}async function $v(t){try{const e=await fetch(`${Je}/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:`${Je}/auth/refresh-session`,status:e.status}),null;const s=await e.json();return s.error||!s.email||!s.sessionToken?(console.warn("refreshSession: validation failed",{error:s.error,hasEmail:!!s.email,hasToken:!!s.sessionToken}),null):s}catch(e){return console.error("refreshSession: fetch failed",{url:`${Je}/auth/refresh-session`,message:e.message,stack:e.stack}),null}}function bc(t,e){const s=Jd(),r=(G.email||s.email)!==t;G.email=t,G.sessionToken=e,G.isVerified=!0,fe=bs({isLoading:!0}),localStorage.setItem(_n,JSON.stringify({email:t,sessionToken:e})),r&&$a()}function ka(){G.email=null,G.sessionToken=null,G.isVerified=!1,fe=bs({isResolved:!0}),localStorage.removeItem(_n),localStorage.removeItem(wn)}function Jd(){try{const t=localStorage.getItem(_n);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(_n),{email:null,sessionToken:null}}}async function Rv(){const e=new URLSearchParams(window.location.search).get("token");if(e){window.history.replaceState({},"",window.location.pathname);try{const{email:s,sessionToken:r}=await Av(e);bc(s,r)}catch(s){ue(s.message||"Sign-in link invalid or expired.","error")}}else{const{email:s,sessionToken:r}=Jd();if(s&&r){const n=await $v(r);n?bc(n.email,n.sessionToken):ka()}}Ca()}function Ia(){const t=document.getElementById("signin-modal");t&&t.classList.add("open")}function Tv(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("signin-modal");e&&e.classList.remove("open")}async function Nv(){const t=document.getElementById("signin-email-input"),e=document.getElementById("signin-submit-btn"),s=document.getElementById("signin-message"),r=t?.value?.trim();if(!r||!/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/.test(r)||r.length>254){s&&(s.textContent="Please enter a valid email address.");return}e&&(e.disabled=!0,e.textContent="Sending…"),s&&(s.textContent="");try{await Pv(r),t&&(t.value=""),s&&(s.textContent=`Check your email — we sent a link to ${r}`),e&&(e.textContent="Sent!")}catch(i){console.error("handleMagicLinkRequest: sendMagicLink failed",{email:r,err:i}),s&&(s.textContent="Something went wrong. Please try again."),e&&(e.disabled=!1,e.textContent="Send Link")}}function Mv(){ka(),$a(),Ca(),Gn()}function Ca(){const t=G.isVerified&&!!G.email,e=document.getElementById("auth-signedout"),s=document.getElementById("auth-signedin"),r=document.getElementById("auth-guest-usage");e&&e.classList.toggle("hidden",t),s&&s.classList.toggle("hidden",!t),r&&r.classList.toggle("hidden",t);const n=document.getElementById("auth-user-email");n&&(n.textContent=G.email||""),zr(),Gn()}async function Yd(){try{if(typeof FingerprintJS>"u"){console.warn("resolveIdentity: FingerprintJS not loaded, skipping");return}const e=await(await FingerprintJS.load()).get(),s=e.visitorId,r=await fetch(km,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({fingerprint:e.visitorId,cookie_id:s})});if(!r.ok)throw new Error(`Identity check HTTP ${r.status}`);const n=await r.json();if(Ge.userId=n.user_id,Ge.token=n.identity_token||null,Ge.status=n.status,Ge.resolved=!0,sessionStorage.setItem(Sm,n.user_id),Ge.token&&sessionStorage.setItem(xm,Ge.token),n.usage_count!==void 0){const i=At(),a=(n.usage_month||i)===i?n.usage_count:0;localStorage.setItem(Gt,JSON.stringify({count:a,month:i})),Xs()}console.log(`Identity resolved: ${n.status} (${n.user_id.slice(0,8)}...) usage: ${n.usage_count??"n/a"}`)}catch(t){console.error("resolveIdentity failed:",t)}}let Pi=null;function Lv(t=5e3){return Ge.resolved?Promise.resolve():(Pi||(Pi=Yd().catch(e=>{console.warn("ensureIdentityReady: identity resolution failed",e)})),Promise.race([Pi,new Promise(e=>setTimeout(e,t))]))}function Zd(){const t=At();try{const e=localStorage.getItem(Gt);return e?JSON.parse(e):{count:0,month:t}}catch(e){return console.warn("getUsageData: failed to parse usage storage",{key:Gt,month:t,err:e}),localStorage.removeItem(Gt),{count:0,month:t}}}function At(){const t=new Date;return`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,"0")}`}function Vn(){const t=Zd();return t.month!==At()?{count:0,month:At()}:t}function Ov(){const e={count:Vn().count+1,month:At()};return localStorage.setItem(Gt,JSON.stringify(e)),e}function Fa(){return!!fe.isLoading}function Jt(){return!!fe.isResolved}function Dv(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(yn,e)?e:null}function Bv(t){return t&&Object.entries(Ad).find(([,e])=>e===t)?.[0]||null}function $r(...t){return t.find(e=>e!=null&&e!=="")}function jv(...t){return t.find(e=>e&&typeof e=="object")||{}}function Uv(t){const e=t.data&&typeof t.data=="object"?t.data:t,s=jv(e.subscription,e.stripeSubscription,e.currentSubscription,e.customer?.subscriptions?.data?.[0],e.subscriptions?.data?.[0],e.subscriptions?.[0]),r=e.metadata||s.metadata||e.customer?.metadata||{},n=$r(e.priceId,e.price_id,e.stripePriceId,e.stripe_price_id,s.priceId,s.price_id,s.plan?.id,s.price?.id,s.items?.data?.[0]?.price?.id,s.items?.[0]?.price?.id,s.lines?.data?.[0]?.price?.id),i=$r(e.status,e.subscriptionStatus,e.subscription_status,s.status,"none"),o=Dv($r(e.tier,e.plan,e.planId,e.plan_id,e.subscriptionTier,e.subscription_tier,e.product,e.productName,s.tier,s.plan,r.tier,r.plan)),a=Im.has(String(i).toLowerCase()),l=e.active===!0||e.isSubscribed===!0||e.subscribed===!0||e.hasSubscription===!0,u=o||Bv(n)||(a||l?"professional":"free");return bs({tier:u,status:i,periodEnd:$r(e.periodEnd,e.currentPeriodEnd,e.current_period_end,s.current_period_end,s.periodEnd,null),isResolved:!0})}function Pa(){return yn[fe.tier]??yn.free}async function Hv(){if(G.isVerified&&(!Jt()||Fa())&&(await Xd({force:!0}),Gn()),G.isVerified&&!Jt())return ue("Could not verify your subscription. Please refresh or try Manage billing.","error"),!1;const{count:t}=Vn(),e=Pa();if(t>=e)return Aa(t,e,{openModal:!0}),!1;const s=Math.floor(e*.8);if(t>=s){const r=e-t;ue(`${r} run${r===1?"":"s"} remaining this month.`,"warning")}return!0}function Ai(){const t=document.getElementById("paywall-exhausted");t&&t.classList.add("hidden")}function Aa(t,e,s={}){const r=document.getElementById("walkthrough-modal");r&&r.classList.remove("open");const n=document.getElementById("ready-state");n&&n.classList.add("hidden");const i=document.getElementById("preview-frame-container");i&&(i.style.display="none");const o=document.getElementById("main-stage-container");o&&o.classList.add("visible");const a=document.getElementById("results-view");a&&a.classList.remove("visible"),document.body.classList.remove("results-fullscreen","results-with-sidebar");const l=document.getElementById("pipeline-progress");l&&l.classList.remove("visible");const u=document.getElementById("paywall-exhausted");if(!u){ue(`You've used all ${e} runs for this month. Upgrade to continue.`,"error"),Cn();return}const c=document.getElementById("paywall-exhausted-text");if(c){const h=fe.tier;h==="free"?c.textContent=`You've used all ${e} free generations this month. Upgrade to Pro for 50 generations/month and access to all AI models.`:c.textContent=`You've used all ${e} generations this month on your ${h} plan. Your limit resets next month.`}const d=document.getElementById("paywall-signin-btn");d&&d.classList.toggle("hidden",G.isVerified),u.classList.remove("hidden"),s.openModal&&Cn()}function $o(t){return fe.tier==="free"&&jr.includes(t)?lr:t}function Wv(){const t=document.getElementById("code-options-content"),e=document.getElementById("code-generator-model");if(!t||!e)return;const s=fe.tier,n=!(G.isVerified&&!Jt())&&s==="free";Array.from(e.options).forEach(o=>{const a=zt(o.value),l=jr.includes(o.value);o.textContent=l&&n?`${a} (PRO)`:a,o.disabled=!1}),n&&jr.includes(e.value)&&(e.value=lr),e.disabled=!1,dc.has(e)||(e.addEventListener("change",()=>{Jt()&&fe.tier==="free"&&jr.includes(e.value)&&(e.value=lr,Cn()),Po(e.value),Rd()}),dc.add(e));let i=document.getElementById("model-selector-free-notice");n?(i||(i=document.createElement("p"),i.id="model-selector-free-notice",i.className="text-xs text-gray-400 mt-1",t.appendChild(i)),i.innerHTML='Free plan — Gemini only. '):i&&i.remove(),Po(e.value)}function Xs(){const t=document.getElementById("usage-counter");if(!t)return;if(G.isVerified&&Fa()){t.textContent="Checking plan…",t.className="text-xs text-gray-500",zr(),Ai();return}if(G.isVerified&&!Jt()){t.textContent="Plan check failed",t.className="text-xs text-red-600 font-medium",zr(),Ai();return}const{count:e}=Vn(),s=Pa();t.textContent=`${e} / ${s} runs this month`;const r=s>0?e/s:0;t.className=r>=1?"text-xs text-red-600 font-medium":r>=.8?"text-xs text-yellow-600 font-medium":"text-xs text-gray-500",zr(),e>=s&&!y.isRunning?Aa(e,s):Ai()}function zr(){const t=document.getElementById("guest-usage-text");if(!t)return;const e=Zd(),s=e.month===At()?e.count??0:0,r=yn.free;t.textContent=`${s} / ${r} generations used`}async function Xd(t={}){const e=t.force===!0;if(!G.isVerified||!G.sessionToken){fe=bs({isResolved:!0});return}fe={...fe,isLoading:!0,error:null};const s=localStorage.getItem(wn);if(!e&&s)try{const{data:r,email:n,ts:i,version:o}=JSON.parse(s);if(o===hc&&n===G.email&&Date.now()-i<300*1e3){fe={...r,isLoading:!1,isResolved:r.isResolved!==!1};return}}catch(r){console.warn("Failed to parse subscription cache:",r,"| raw value:",s)}try{const n=await(await fetch(`${Je}/stripe/get-subscription`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:G.sessionToken,user_id:Ge.userId})})).json();if(n.error){if(["unauthorized","invalid session","expired session"].some(o=>String(n.error).toLowerCase().includes(o))){ka(),Ca();return}fe=bs({isResolved:!1,error:n.error});return}fe=Uv(n),localStorage.setItem(wn,JSON.stringify({version:hc,data:fe,email:G.email,ts:Date.now()}))}catch(r){console.error("fetchSubscription failed:",r),fe={...fe,isLoading:!1,isResolved:!1,error:r.message}}}function $a(){localStorage.removeItem(wn)}async function zv(t){if(!G.isVerified||!G.sessionToken){Qd(),Ia();return}if(!Ad[t]){ue("Invalid plan selected.","error");return}const e=document.getElementById(`checkout-btn-${t}`);e&&(e.disabled=!0,e.textContent="Redirecting…");try{const r=await(await fetch(`${Je}/stripe/create-checkout-session-intl`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tierId:t,sessionToken:G.sessionToken,currency:Md()})})).json();if(r.error||!r.url)throw new Error(r.error||"Failed to create checkout session");const{url:n}=r;window.location.href=n}catch(s){console.error("startCheckout failed:",s),e&&(e.disabled=!1,e.textContent="Subscribe"),ue("Could not start checkout. Please try again.","error")}}async function qv(){if(!G.isVerified||!G.sessionToken){Ia();return}const t=document.getElementById("manage-billing-btn");t&&(t.disabled=!0,t.textContent="Loading…");try{const s=await(await fetch(`${Je}/stripe/create-portal-session`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:G.sessionToken})})).json();if(s.error||!s.url)throw new Error(s.error||"Failed to open billing portal");const{url:r}=s;window.location.href=r}catch(e){console.error("openCustomerPortal failed:",e),t&&(t.disabled=!1,t.textContent="Manage billing"),ue("Could not open billing portal. Please try again.","error")}}async function In(t,e,s,r={},n=[]){const o=new AbortController,a=setTimeout(()=>o.abort(),12e4);try{const l=await fetch(Em,{method:"POST",headers:{"Content-Type":"application/json",...Ge.token?{Authorization:`Bearer ${Ge.token}`}:{}},signal:o.signal,body:JSON.stringify({user_id:Ge.userId,step:t,model:e,prompt:s,images:n,context:r})}),u=await l.text();let c={};try{c=u?JSON.parse(u):{}}catch{c={}}if(l.status===429){c.serverCount!==void 0&&(localStorage.setItem(Gt,JSON.stringify({count:c.serverCount,month:At()})),Xs());const p=new Error(c.message||"Monthly usage limit reached. Upgrade to continue.");throw p.isUsageLimit=!0,p}const d=qf(c,t);if(d)throw d;if(console.log(`[BuildShip] ${t} response keys:`,Object.keys(c),"content type:",typeof c.content),!l.ok)throw new Error(`${c.message||c.error||"BuildShip pipeline error"} (HTTP ${l.status})`);if(t==="generator")if(c.usage_status==="success"&&Number.isFinite(c.usage_count)){const p=At();(c.usage_month||p)===p&&(localStorage.setItem(Gt,JSON.stringify({count:c.usage_count,month:p})),Xs())}else Ov(),Xs();let h=c.output||c.content;if(!h){const p=u?` (body: ${u.slice(0,120)})`:"";throw new Error(`BuildShip returned no output for step "${t}"${p}`)}return Array.isArray(h)&&(h=h.map(p=>typeof p=="string"?p:p.text||"").join("")),typeof h!="string"&&(h=JSON.stringify(h)),h}catch(l){throw l.name==="AbortError"?new Error(`BuildShip ${t} timed out after ${12e4/1e3}s`):l instanceof TypeError?new Error(`BuildShip unreachable: ${l.message}`):l}finally{clearTimeout(a)}}function Vv(){const e=new URLSearchParams(window.location.search).get("checkout");e==="success"?(window.history.replaceState({},"",window.location.pathname),$a(),ue("Subscription active! Welcome aboard.","success")):e==="cancel"&&(window.history.replaceState({},"",window.location.pathname),ue("Checkout cancelled.","info"))}function Gn(){const t=G.isVerified&&!!G.email,e=fe.tier,s=t&&Fa(),r=!t||Jt(),n=document.getElementById("subscription-tier-badge");if(n){const a={free:"Free",professional:"Professional",power:"Power Developer"},l={free:"bg-gray-100 text-gray-600",professional:"bg-indigo-100 text-indigo-700",power:"bg-purple-100 text-purple-700",unresolved:"bg-red-50 text-red-600"};n.textContent=s?"Checking…":r?a[e]||"Free":"Plan unavailable",n.className=`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${r?l[e]||l.free:l.unresolved}`}const i=document.getElementById("upgrade-prompt");i&&i.classList.toggle("hidden",!t||s||!r||e!=="free");const o=document.getElementById("manage-billing-btn");o&&o.classList.toggle("hidden",!t||s||r&&e==="free"),Gv(r?e:null),Wv(),Rd(),Xs()}function Gv(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(([n,{btnId:i,defaultText:o}])=>{const a=document.getElementById(i);a&&(n===t?(a.disabled=!0,a.textContent="Current plan",a.classList.add(...e)):(a.disabled=!1,a.textContent=o,a.classList.remove(...e)))});const r=document.getElementById("free-tier-current");r&&r.classList.toggle("hidden",t!=="free")}function Ro(){const t=Md(),e=document.getElementById("pro-price"),s=document.getElementById("power-price"),r=document.getElementById("pro-price-note"),n=document.getElementById("power-price-note");e&&(e.textContent=fc(pc.professional,t)),s&&(s.textContent=fc(pc.power,t));const i="billed monthly";r&&(r.textContent=i),n&&(n.textContent=i)}function Cn(){Ro();const t=document.getElementById("pricing-modal");t&&t.classList.add("open"),Mm().then(()=>Ro())}function Qd(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("pricing-modal");e&&e.classList.remove("open")}function ue(t,e="info"){const s={success:"bg-green-600 text-white",error:"bg-red-600 text-white",warning:"bg-amber-500 text-white",info:"bg-gray-800 text-white"},r=document.createElement("div");r.className=`fixed bottom-6 left-1/2 -translate-x-1/2 px-5 py-3 rounded-lg text-sm font-medium shadow-lg z-50 transition-opacity duration-300 ${s[e]||s.info}`,r.textContent=t,document.body.appendChild(r),setTimeout(()=>{r.style.opacity="0",setTimeout(()=>r.remove(),300)},3500)}document.addEventListener("DOMContentLoaded",async()=>{hljs.configure({tabReplace:" ",classPrefix:"hljs-"}),Kv(),await Rv(),Vv(),await Xd(),Gn(),Ro(),await ov(),tv();const t=document.getElementById("flutterflow-endpoint-select");if(t){const s=fr();t.value=s}Ud(),Yd();const e=document.getElementById("pipeline-input");e&&(e.addEventListener("input",()=>{Et===2&&e.value.trim().length>0&&(pa(),Dn())}),e.addEventListener("blur",()=>{const s=document.getElementById("walkthrough-modal");Et===2&&s&&s.classList.add("open")}),e.addEventListener("keydown",s=>{if(s.key==="Tab"){const r=document.getElementById("walkthrough-modal");Et===2&&r&&setTimeout(()=>{r.classList.add("open")},100)}})),window.addEventListener("commitStateChange",s=>{const{state:r}=s.detail;r===V.PREPARING||r===V.VALIDATING||r===V.PUSHING?(be.phaseId||sh(),Sc(r)):(r===V.SUCCESS||r===V.ERROR)&&(Sc(r),setTimeout(Fn,1e3))})});function Kv(){const t=document.getElementById("preview-frame-container");t&&(t.style.display="")}function Jv(){const t=document.getElementById("welcome-video-player");t&&(t.addEventListener("click",Yt),document.addEventListener("keydown",Yt))}function Yt(){const t=document.getElementById("preview-frame-container"),e=document.getElementById("main-stage-container"),s=document.getElementById("ready-state");t&&(t.style.display="none"),e&&e.classList.add("visible"),s&&s.classList.remove("hidden");const r=document.getElementById("welcome-video-player");r&&r.removeEventListener("click",Yt),document.removeEventListener("keydown",Yt),Ud()}let Qs=null;async function Yv(){const t=document.getElementById("confirm-project-select");if(!t)return;const e=++yc,s=()=>e===yc,r=await Ee("flutterflow"),n=await Ee("flutterflow_project_id");if(s()){if(!r){t.innerHTML='',t.disabled=!0;return}t.disabled=!1,t.innerHTML='';try{const o=await new gr(r,"").listProjects();if(!s())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)}),n&&(t.value=n)}catch(i){if(!s())return;console.error("Failed to load projects for deploy:",i),t.innerHTML=''}}}function Zv(){return document.getElementById("confirm-project-select")?.value?.trim()||null}function eh(t,e,s,r=null){Qs={codeInfo:t,checks:e,deps:s,bundlePlan:r},document.getElementById("confirm-file-name").textContent=t.fileName,document.getElementById("confirm-artifact-type").textContent=t.artifactType,document.getElementById("confirm-file-size").textContent=`${(t.content.length/1024).toFixed(1)} KB`,document.getElementById("confirm-line-count").textContent=r?`${r.fileEntries.length} files`:t.content.split(` -`).length,Yv();const n=document.getElementById("confirm-deps-list"),i=document.getElementById("confirm-deps-section");s&&Object.keys(s).length>0?(n.innerHTML=Object.entries(s).map(([u,c])=>{const d=c?`at least ${bt(c)}`:"version resolved from your project";return`
  • • ${bt(u)}: ${d}
  • `}).join(""),i.classList.remove("hidden")):i.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=>`
  • • ${bt(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&&l.classList.add("open")}function th(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("commit-confirm-modal");e&&e.classList.remove("open"),Qs=null}function Xv(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("commit-success-modal");e&&e.classList.remove("open");const s=["success-message","success-project-id","success-file-name","success-artifact-type","success-time","success-size"];for(const i of s){const o=document.getElementById(i);o&&(o.textContent="")}const r=document.getElementById("success-warnings-section");r&&r.classList.add("hidden");const n=document.getElementById("success-warnings-list");n&&(n.innerHTML="")}function To(t){const e=(g,m)=>{const _=document.getElementById(g);_&&(_.textContent=m||"")},s=t.metadata?.fileName||"",r=t.metadata?.projectId||"",n=t.metadata?.artifactType||"",i=t.elapsedTime?`${(t.elapsedTime/1e3).toFixed(1)}s`:"",o=t.metadata?.codeSize?`${(t.metadata.codeSize/1024).toFixed(1)} KB`:"";e("success-message",t.message||"Code committed successfully!"),e("success-project-id",r),e("success-file-name",s),e("success-artifact-type",n),e("success-time",i),e("success-size",o);const a=t.addedDependencies||[],l=document.getElementById("success-deps-row");l&&l.classList.toggle("hidden",a.length===0),e("success-deps",a.join(", "));const u=document.getElementById("success-open-ff-link");u&&r&&(u.href=`https://app.flutterflow.io/project/${r}`);const c=document.getElementById("success-warnings-section"),d=document.getElementById("success-warnings-list"),h=t.unverified||[],p=t.warnings||[];(p.length>0||h.length>0)&&c&&d&&(d.innerHTML=[...h.map(g=>`
  • Not verified before deploying: ${j(String(g))}
  • `),...p.map(([g,m])=>`
  • ${j(g)}: ${j(String(m))}
  • `)].join(""),c.classList.remove("hidden"));const f=document.getElementById("commit-success-modal");f&&f.classList.add("open")}function No(t){Fn(),Iv(t)}function Qv(){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 Ec={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}},e_=[{after:0,text:"Starting a FlutterFlow build runner..."},{after:12,text:"Preparing the FlutterFlow AI workspace..."},{after:35,text:"Uploading your custom classes..."},{after:60,text:"FlutterFlow is applying the changes..."},{after:100,text:"Still working — this can take a couple of minutes..."}],be={sequence:[],phaseId:null,phaseStartedAt:null,timer:null,substatus:null,liveSubstatus:!1,start({withProvisioning:t=!1}={}){this.sequence=["prepare","validate","project"],t&&this.sequence.push("provision"),this.sequence.push("package","push","done");const e=document.getElementById("commit-progress-overlay");e&&e.classList.add("open"),this.set("prepare")},set(t,e=null){if(!(!Ec[t]||t===this.phaseId)){if(!this.sequence.includes(t)){const s=this.sequence.indexOf("package");this.sequence.splice(s===-1?this.sequence.length:s,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=Ec[this.phaseId];if(!t)return;const e=(Date.now()-this.phaseStartedAt)/1e3,s=t.start+(t.end-t.start)*(1-Math.exp(-e/25));if(this.phaseId==="provision"&&!this.liveSubstatus){const o=e_.filter(a=>e>=a.after).pop();o&&(this.substatus=o.text)}const r=this.sequence.indexOf(this.phaseId),i=[`Step ${r===-1?1:r+1} of ${this.sequence.length}`];e>=5&&i.push(t_(e)),rh(this.phaseId==="done"?100:s,t.message,i.join(" · "),this.substatus)},stop(){this.timer&&clearInterval(this.timer),this.timer=null,this.phaseId=null;const t=document.getElementById("commit-progress-overlay");t&&t.classList.remove("open")}};function t_(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 sh(t){be.start(t)}function Fn(){be.stop()}function rh(t,e,s,r=null){const n=document.getElementById("commit-progress-bar"),i=document.getElementById("progress-message"),o=document.getElementById("progress-detail"),a=document.getElementById("progress-substatus");n&&(n.style.width=`${Math.round(t*10)/10}%`),i&&(i.textContent=e),o&&(o.textContent=s),a&&(a.textContent=r||"",a.classList.toggle("hidden",!r))}function Sc(t){const e={[V.PREPARING]:"prepare",[V.VALIDATING]:"validate",[V.PUSHING]:"project",[V.SUCCESS]:"done"};if(t===V.ERROR){be.timer&&clearInterval(be.timer),be.timer=null,rh(100,"Failed","Error occurred");return}const s=e[t];s&&be.set(s)}function s_(t){return t.bundlePlan?t.bundlePlan.fileEntries.some(e=>e.type===U.CODE_FILE):t.codeInfo?.codeType===U.CODE_FILE}async function r_(){if(!Qs){console.error("No pending commit data");return}const t=Qs;if(Qs=null,Zs=Zv(),th(),sh({withProvisioning:s_(t)}),t.bundlePlan){const o=await gv(t.bundlePlan,{pipelineResult:{step1Result:y.step1Result,selectedModel:document.getElementById("code-generator-model")?.value}});Zs=null,Fn(),o.success?To(o):No(o);return}const{codeInfo:e}=t,{artifactType:s,artifactName:r,fileName:n}=Wd(),i=await fv(e.content,{artifactType:s,artifactName:r,fileName:n,pipelineResult:{step1Result:y.step1Result,selectedModel:document.getElementById("code-generator-model")?.value}});Zs=null,Fn(),i.success?To(i):No(i)}window.runThinkingPipeline=Ao;window.toggleStep=_v;window.toggleSection=vv;window.selectWorkflowStep=ze;window.copyCode=yv;window.retryWithDifferentModel=Sv;window.openApiKeysModal=ha;window.closeApiKeysModal=Bd;window.closeWalkthroughModal=Jm;window.openWalkthroughModal=Km;window.advanceWalkthrough=pa;window.commitToFlutterFlow=pv;function n_(){const t=document.getElementById("pipeline-input");t&&t.focus()}function i_(){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=n_;window.openModelSelector=i_;window.handlePromptImageSelect=Tm;window.removePromptImage=Nm;window.saveApiKeys=Xm;window.clearAllApiKeys=Qm;window.toggleKeyVisibility=rv;window.handleWelcomeVideoEnd=Jv;window.dismissWelcomeVideo=Yt;window.initiateCommitToFlutterFlow=xv;window.updateFlutterFlowCredentialStatus=Fv;window.closeCommitConfirmModal=th;window.closeCommitSuccessModal=Xv;window.showCommitSuccessModal=To;window.showCommitFailureModal=No;window.toggleCodePreview=Qv;window.confirmCommitToFlutterFlow=r_;window.runRefinement=wv;window.regenerateFromPastedErrors=Ev;window.clearErrorInput=bv;window.setFlutterFlowEndpoint=Gm;window.getFlutterFlowEndpoint=fr;window.commitProgress=be;window.openSignInModal=Ia;window.closeSignInModal=Tv;window.handleMagicLinkRequest=Nv;window.handleSignOut=Mv;window.startCheckout=zv;window.openCustomerPortal=qv;window.openPricingModal=Cn;window.closePricingModal=Qd;let hs=null,nh=null;const xc=120;function Kn(){const t=document.getElementById("pipeline-progress"),e=document.getElementById("results-view"),s=document.getElementById("ready-state");s&&s.classList.add("hidden"),e&&e.classList.remove("visible"),document.body.classList.remove("results-fullscreen","results-with-sidebar"),t&&t.classList.add("visible"),nh=Date.now();for(let r=1;r<=3;r++){const n=document.getElementById(`pdot-${r}`);n&&(n.className="progress-dot")}nt(1),o_()}function nt(t){const e={1:"Analyzing your prompt...",2:"Generating Dart code...",3:"Running code audit..."},s={1:"Step 1 of 3 — Prompt Architect",2:"Step 2 of 3 — Code Generator",3:"Step 3 of 3 — Code Review"},r=document.getElementById("progress-title-text"),n=document.getElementById("progress-substep-text");r&&(r.textContent=e[t]||e[1]),n&&(n.textContent=s[t]||s[1]);for(let i=1;i<=3;i++){const o=document.getElementById(`pdot-${i}`);o&&(i{const t=(Date.now()-nh)/1e3,e=document.getElementById("progress-elapsed"),s=document.getElementById("pipeline-progress-fill");e&&(e.textContent=`${Math.floor(t)}s`);const r=t/xc*100,n=Math.min(95,r*(1-Math.exp(-t/(xc*.6)))*1.2);s&&(s.style.width=`${n}%`)},250)}function $t(){hs&&(clearInterval(hs),hs=null);const t=document.getElementById("pipeline-progress-fill");t&&(t.style.width="100%");for(let e=1;e<=3;e++){const s=document.getElementById(`pdot-${e}`);s&&(s.className="progress-dot completed")}setTimeout(()=>{const e=document.getElementById("pipeline-progress");e&&e.classList.remove("visible"),t&&(t.style.width="0%")},400)}function Ss(t,e=""){const s={pass:'',warning:'',fail:'',info:''};return``}function ih(t){return{pass:"Passed review",warning:"Needs attention",fail:"Blocking issues"}[t]||"Needs attention"}function a_(){return Lg({bundle:y.artifactBundle,reviewResult:y.step3Result})}function l_(t){return` -
    - ${Ss(t.severity)} -
    -
    ${j(t.message)}
    - ${t.suggestion?`
    ${j(t.suggestion)}
    `:""} - ${j(t.source)} -
    -
    - `}function c_(t){return` -
  • -
    - ${j(t.title)} - ${t.detail&&t.detail!==t.title?`

    ${j(t.detail)}

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

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

    -

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

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

    ${j(t.summary)}

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

    ${j(l.reason)}

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

    ${j(l.description)}

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

    ${j(e.artifactName)}

    - ${e.description?`

    ${j(e.description)}

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

    Code Review findings

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

    Manual FlutterFlow steps for this file

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

    Dependencies

    -
      ${n}
    -
    -
    -

    Deployment

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

    Public API

    -
    ${o}
    -
    -
    -

    Imports

    -
    ${i}
    -
    -
    -

    Relationships

    -
      ${a}
    -
    -
    - `}function h_(t){const e=document.getElementById("bundle-strip"),s=document.getElementById("results-summary-tab"),r=document.getElementById("artifact-tabs"),n=document.getElementById("results-file-count");if(s&&s.classList.toggle("active",y.resultsViewMode==="summary"),!t.artifacts.length){n&&(n.textContent="0 files"),e&&e.classList.remove("visible"),r&&(r.innerHTML="");return}if(n){const i=t.artifacts.length;n.textContent=`${i} ${i===1?"file":"files"}`}r&&(r.innerHTML=t.artifacts.map(i=>` - - `).join(""),r.onclick=i=>{const o=i.target.closest(".artifact-tab");o?.dataset?.artifactId&&oh(o.dataset.artifactId)}),e&&e.classList.add("visible")}function Ra(){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"),s=document.getElementById("results-audit-output"),r=document.getElementById("results-summary-detail"),n=document.getElementById("artifact-results-split"),i=a_(),o=ma();if(u_(i),h_(i),e&&(e.textContent=""),e){const a=Pd(o);e.innerHTML=a}s&&(s.innerHTML=d_(i)),r&&r.classList.toggle("hidden",y.resultsViewMode!=="summary"),n&&n.classList.toggle("hidden",y.resultsViewMode!=="file"),t&&t.classList.add("visible")}function Jn(t,e){y.selectedArtifactId||(y.selectedArtifactId=gn(y.artifactBundle).id),y.resultsViewMode="summary",document.body.classList.add("results-fullscreen");const s=document.getElementById("step3-output");s&&(s.textContent=""),Ra(),Zt();const r=document.getElementById("btn-feedback-up"),n=document.getElementById("btn-feedback-down");r&&(r.className="feedback-btn"),n&&(n.className="feedback-btn")}function oh(t){y.selectedArtifactId=t,y.resultsViewMode="file",Ra()}function p_(){y.resultsViewMode="summary",Ra()}function f_(){const t=document.getElementById("btn-copy-results"),e=ma();navigator.clipboard.writeText(e).then(()=>{if(t){t.classList.add("copied");const s=t.querySelector("span");if(s){const r=s.textContent;s.textContent="Copied!",setTimeout(()=>{t.classList.remove("copied"),s.textContent=r},2e3)}}})}function g_(t){const e=document.getElementById("btn-feedback-up"),s=document.getElementById("btn-feedback-down");t==="up"?(e.classList.toggle("active-up"),s.classList.remove("active-down")):(s.classList.toggle("active-down"),e.classList.remove("active-up")),xa(t==="up"?"thumbsUp":"thumbsDown",y.step2Result,y.step1Result)}function m_(){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 ah(){const t=document.getElementById("error-input-panel");t&&(t.classList.add("hidden"),t.style.display="none")}window.copyResultsCode=f_;window.selectArtifact=oh;window.selectResultsSummary=p_;window.submitResultsFeedback=g_;window.showErrorInputPanel=m_;window.hideErrorInputPanel=ah; diff --git a/dist/assets/index-BsMV38gk.js b/dist/assets/index-BsMV38gk.js new file mode 100644 index 0000000..42e19a1 --- /dev/null +++ b/dist/assets/index-BsMV38gk.js @@ -0,0 +1,320 @@ +(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const r of document.querySelectorAll('link[rel="modulepreload"]'))n(r);new MutationObserver(r=>{for(const i of r)if(i.type==="childList")for(const o of i.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&n(o)}).observe(document,{childList:!0,subtree:!0});function s(r){const i={};return r.integrity&&(i.integrity=r.integrity),r.referrerPolicy&&(i.referrerPolicy=r.referrerPolicy),r.crossOrigin==="use-credentials"?i.credentials="include":r.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function n(r){if(r.ep)return;r.ep=!0;const i=s(r);fetch(r.href,i)}})();var v=typeof window<"u"?window:void 0,we=typeof globalThis<"u"?globalThis:v,ke=we?.navigator,C=we?.document,ne=we?.location,Do=we?.fetch,Ni=we!=null&&we.XMLHttpRequest&&"withCredentials"in new we.XMLHttpRequest?we.XMLHttpRequest:void 0,Da=we?.AbortController,hh=we?.CompressionStream,Pe=ke?.userAgent;function Fc(){return!(!v||v.navigator.onLine===!1)}var Cs=typeof globalThis<"u"?globalThis:v;Cs&&typeof self>"u"&&(Cs.self=Cs),Cs&&typeof File>"u"&&(Cs.File=function(){});var $=v??{},Y={DEBUG:!1,LIB_VERSION:"0.5.0",LIB_NAME:"browser-common"};function Ba(t,e,s,n,r,i,o){try{var a=t[i](o),l=a.value}catch(u){return void s(u)}a.done?e(l):Promise.resolve(l).then(n,r)}function X(t){return function(){var e=this,s=arguments;return new Promise((function(n,r){var i=t.apply(e,s);function o(l){Ba(i,n,r,o,a,"next",l)}function a(l){Ba(i,n,r,o,a,"throw",l)}o(void 0)}))}}function b(){return b=Object.assign?Object.assign.bind():function(t){for(var e=1;arguments.length>e;e++){var s=arguments[e];for(var n in s)({}).hasOwnProperty.call(s,n)&&(t[n]=s[n])}return t},b.apply(null,arguments)}function Pc(t,e){if(t==null)return{};var s={};for(var n in t)if({}.hasOwnProperty.call(t,n)){if(e.indexOf(n)!==-1)continue;s[n]=t[n]}return s}var ja=t=>{if(typeof t!="string")return t;try{return JSON.parse(t)}catch{return t}};function Ua(t){return typeof t=="string"||t}function Ha(t){return typeof t=="string"?t:void 0}var Fs,ph=["$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})({}),Wa=(function(t){return t.GZipJS="gzip-js",t.Base64="base64",t})({}),fh=["$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"],gh=["token"],Ac="NativeGzipValidationError",Mi=t=>t.length>=2&&t[0]===31&&t[1]===139,za=(t,e)=>t===Wa.GZipJS||e===Wa.GZipJS||e==="gzip",qa=t=>!(!t||typeof t!="object")&&("name"in t?String(t.name):"")==="NotReadableError",wn=t=>{var e=new Error("Native gzip produced invalid output: "+t);throw e.name=Ac,e},mh=(function(){var t=X((function*(e,s){18>e.size&&wn("too-short");var n=new Uint8Array(yield e.slice(0,10).arrayBuffer());Mi(n)&&n[2]===8||wn("invalid-header");var r=new DataView(yield e.slice(e.size-8).arrayBuffer());r.getUint32(0,!0)!==(o=>{for(var a=(()=>{if(Fs)return Fs;Fs=[];for(var c=0;256>c;c++){for(var d=c,h=0;8>h;h++)d=1&d?3988292384^d>>>1:d>>>1;Fs[c]=d>>>0}return Fs})(),l=4294967295,u=0;o.length>u;u++)l=a[255&(l^o[u])]^l>>>8;return(4294967295^l)>>>0})(s)&&wn("invalid-crc");var i=s.length>>>0;r.getUint32(4,!0)!==i&&wn("invalid-size")}));return function(e,s){return t.apply(this,arguments)}})();function Li(){return Li=X((function*(t,e,s){e===void 0&&(e=!0);try{var n=new TextEncoder().encode(t),r=new globalThis.CompressionStream("gzip"),i=r.writable.getWriter(),o=i.write(n).then((()=>i.close())).catch((function(){var u=X((function*(c){try{yield i.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 mh(l,n),l}catch(u){if(s!=null&&s.rethrow)throw u;return e&&console.error("Failed to gzip compress data",u),null}})),Li.apply(this,arguments)}var vh=["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"],Va=function(t,e){if(e===void 0&&(e=[]),!t)return!1;var s=t.toLowerCase();return vh.concat(e).some((n=>{var r=n.toLowerCase();return s.indexOf(r)!==-1}))};function M(t,e){return t.indexOf(e)!==-1}var Ar=function(t){return t.trim()},Oi=function(t){return t.replace(/^\$/,"")};function $c(t){var e,s=[];return(e=JSON.stringify(t,(function(n,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(;s.length>0&&s[s.length-1]!==this;)s.pop();if(s.includes(r))return"[Circular]";s.push(r)}return r}})))!==null&&e!==void 0?e:"null"}var Rc=Object.prototype,Tc=Rc.hasOwnProperty,$r=Rc.toString,L=Array.isArray||function(t){return $r.call(t)==="[object Array]"},Se=t=>typeof t=="function",te=t=>t===Object(t)&&!L(t),mt=t=>{if(te(t)){for(var e in t)if(Tc.call(t,e))return!1;return!0}return!1},x=t=>t===void 0,W=t=>$r.call(t)=="[object String]",Di=t=>W(t)&&t.trim().length===0,$e=t=>t===null,D=t=>x(t)||$e(t),he=t=>$r.call(t)=="[object Number]"&&t==t,lt=t=>he(t)&&t>0,Ke=t=>$r.call(t)==="[object Boolean]",_h=t=>t instanceof FormData,yh=t=>M(fh,t),wh=t=>M(gh,t);function Nc(t){return t===null||typeof t!="object"}function Gn(t,e){return{}.toString.call(t)==="[object "+e+"]"}function Bo(t){return typeof Event<"u"&&Mc(t,Event)}function Mc(t,e){try{return t instanceof e}catch{return!1}}var bh=[!0,"true",1,"1","yes"],ei=t=>M(bh,t),Eh=[!1,"false",0,"0","no"];function nt(t,e,s,n,r){return e>s&&(n.warn("min cannot be greater than max."),e=s),he(t)?t>s?(n.warn(" cannot be greater than max: "+s+". Using max value instead."),s):e>t?(n.warn(" cannot be less than min: "+e+". Using min value instead."),e):t:(n.warn(" must be a number. using max or fallback. max: "+s+", fallback: "+r),nt(r||s,e,s,n))}class Sh{constructor(e){this.tt={},this.et=e.et,this.it=nt(e.bucketSize,0,100,e.rt),this.nt=nt(e.refillRate,0,this.it,e.rt),this.st=nt(e.refillInterval,0,864e5,e.rt)}ot(e,s){var n=Math.floor((s-e.lastAccess)/this.st);n>0&&(e.tokens=Math.min(e.tokens+n*this.nt,this.it),e.lastAccess=e.lastAccess+n*this.st)}consumeRateLimit(e){var s,n=Date.now(),r=String(e),i=this.tt[r];return i?this.ot(i,n):this.tt[r]=i={tokens:this.it,lastAccess:n},i.tokens===0||(i.tokens--,i.tokens===0&&((s=this.et)==null||s.call(this,e)),i.tokens===0)}stop(){this.tt={}}}var Oe="Mobile",Kn="iOS",vt="Android",ps="Tablet",Lc=vt+" "+ps,Oc="iPad",Dc="Apple",Bc=Dc+" Watch",qs="Safari",fs="BlackBerry",jc="Samsung",Uc=jc+"Browser",Hc=jc+" Internet",Vt="Chrome",xh=Vt+" OS",Wc=Vt+" "+Kn,jo="Internet Explorer",zc=jo+" "+Oe,Uo="Opera",kh=Uo+" Mini",Ho="Edge",qc="Microsoft "+Ho,us="Firefox",Vc=us+" "+Kn,en="Nintendo",tn="PlayStation",ds="Xbox",Gc=vt+" "+Oe,Kc=Oe+" "+qs,Ds="Windows",Bi=Ds+" Phone",Ga="Nokia",ji="Ouya",Jc="Generic",Ih=Jc+" "+Oe.toLowerCase(),Yc=Jc+" "+ps.toLowerCase(),Ui="Konqueror",Zc="Oculus Browser",Jn="Vivaldi",Xc="Yandex",Yn="Whale",Hi="DuckDuckGo",Qc="Pale Moon",Zn="Waterfox",Vs="Brave",eu="Google Search App",le="(\\d+(\\.\\d+)?)",ti=new RegExp("Version/"+le),Ch=new RegExp(ds,"i"),Fh=new RegExp(tn+" \\w+","i"),Ph=new RegExp(en+" \\w+","i"),Wo=new RegExp(fs+"|PlayBook|BB10","i"),Ah={"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"},tu=function(t,e,s,n){e=e||"";var r=(function(i){return i!=null&&i.brave?Vs:null})(s);return r||(n!=null&&n.detectGoogleSearchApp&&M(t,"GSA/")?eu:M(t," OPR/")&&M(t,"Mini")?kh:M(t," OPR/")?Uo:Wo.test(t)?fs:M(t,"IE"+Oe)||M(t,"WPDesktop")?zc:M(t,"OculusBrowser")?Zc:M(t,Uc)?Hc:M(t,Ho)||M(t,"Edg/")?qc:M(t,Jn+"/")?Jn:M(t,"YaBrowser/")?Xc:M(t,Yn+"/")?Yn:M(t,Hi+"/")||M(t,"Ddg/")?Hi:M(t,"FBIOS")?"Facebook "+Oe:M(t,"UCWEB")||M(t,"UCBrowser")?"UC Browser":M(t,"CriOS")?Wc:M(t,"CrMo")||M(t,Vt)?Vt:M(t,vt)&&M(t,qs)?Gc:M(t,"FxiOS")?Vc:M(t.toLowerCase(),Ui.toLowerCase())?Ui:M(t,Vs+"/")?Vs:((i,o)=>o&&M(o,Dc)||(function(a){return M(a,qs)&&!M(a,Vt)&&!M(a,vt)})(i))(t,e)?M(t,Oe)?Kc:qs:M(t,"PaleMoon/")?Qc:M(t,Zn+"/")?Zn:M(t,us)?us:M(t,"MSIE")||M(t,"Trident/")?jo:M(t,"Gecko")?us:"")},$h={[zc]:[new RegExp("rv:"+le)],[qc]:[new RegExp(Ho+"?\\/"+le)],[Vt]:[new RegExp("("+Vt+"|CrMo)\\/"+le)],[Wc]:[new RegExp("CriOS\\/"+le)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+le)],[qs]:[ti],[Kc]:[ti],[Uo]:[new RegExp("(Opera|OPR)\\/"+le)],[us]:[new RegExp(us+"\\/"+le)],[Vc]:[new RegExp("FxiOS\\/"+le)],[Ui]:[new RegExp("Konqueror[:/]?"+le,"i")],[fs]:[new RegExp(fs+" "+le),ti],[Gc]:[new RegExp("android\\s"+le,"i")],[Hc]:[new RegExp(Uc+"\\/"+le)],[Zc]:[new RegExp("OculusBrowser\\/"+le)],[Jn]:[new RegExp(Jn+"\\/"+le)],[Xc]:[new RegExp("YaBrowser\\/"+le)],[Yn]:[new RegExp(Yn+"\\/"+le)],[Vs]:[new RegExp(Vs+"\\/"+le)],[Hi]:[new RegExp("(DuckDuckGo|Ddg)\\/"+le)],[Qc]:[new RegExp("PaleMoon\\/"+le)],[Zn]:[new RegExp(Zn+"\\/"+le)],[eu]:[new RegExp("GSA\\/"+le)],[jo]:[new RegExp("(rv:|MSIE )"+le)],Mozilla:[new RegExp("rv:"+le)]},Rh=function(t,e,s,n){var r=tu(t,e,s,n),i=$h[r];if(x(i))return null;for(var o=0;i.length>o;o++){var a=t.match(i[o]);if(a)return parseFloat(a[a.length-2])}return null},Ka=[[new RegExp(ds+"; "+ds+" (.*?)[);]","i"),t=>[ds,t&&t[1]||""]],[new RegExp(en,"i"),[en,""]],[new RegExp(tn,"i"),[tn,""]],[Wo,[fs,""]],[new RegExp(Ds,"i"),(t,e)=>{if(/Phone/.test(e)||/WPDesktop/.test(e))return[Bi,""];if(new RegExp(Oe).test(e)&&!/IEMobile\b/.test(e))return[Ds+" "+Oe,""];var s=/Windows NT ([0-9.]+)/i.exec(e);if(s&&s[1]){var n=Ah[s[1]]||"";return/arm/i.test(e)&&(n="RT"),[Ds,n]}return[Ds,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,t=>t&&t[3]?[Kn,[t[3],t[4],t[5]||"0"].join(".")]:[Kn,""]],[/(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i,t=>{var e="";return t&&t.length>=3&&(e=x(t[2])?t[3]:t[2]),["watchOS",e]}],[new RegExp("("+vt+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+vt+")","i"),t=>t&&t[2]?[vt,[t[2],t[3],t[4]||"0"].join(".")]:[vt,""]],[/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/,[xh,""]],[/Linux|debian/i,["Linux",""]]],Ja=function(t){return Ph.test(t)?en:Fh.test(t)?tn:Ch.test(t)?ds:new RegExp(ji,"i").test(t)?ji:new RegExp("("+Bi+"|WPDesktop)","i").test(t)?Bi:/iPad/.test(t)?Oc:/iPod/.test(t)?"iPod Touch":/iPhone/.test(t)?"iPhone":/(watch)(?: ?os[,/]|\d,\d\/)[\d.]+/i.test(t)?Bc:Wo.test(t)?fs:/(kobo)\s(ereader|touch)/i.test(t)?"Kobo":new RegExp(Ga,"i").test(t)?Ga:/(kf[a-z]{2}wi|aeo[c-r]{2})( bui|\))/i.test(t)||/(kf[a-z]+)( bui|\)).+silk\//i.test(t)?"Kindle Fire":/(Android|ZTE)/i.test(t)?new RegExp(Oe).test(t)&&!/(9138B|TB782B|Nexus [97]|pixel c|HUAWEISHT|BTV|noble nook|smart ultra 6)/i.test(t)||/pixel[\daxl ]{1,6}/i.test(t)&&!/pixel c/i.test(t)||/(huaweimed-al00|tah-|APA|SM-G92|i980|zte|U304AA)/i.test(t)||/lmy47v/i.test(t)&&!/QTAQZ3/i.test(t)?vt:Lc:new RegExp("(pda|"+Oe+")","i").test(t)?Ih:new RegExp(ps,"i").test(t)&&!new RegExp(ps+" pc","i").test(t)?Yc:""},Th=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Ya(t,e){return typeof(s=t)=="string"&&Th.test(s)?t:e();var s}function Ct(t){return t&&t.split("#")[0]}function zo(t,e){var s=setTimeout(t,e);return s?.unref&&s?.unref(),s}function Za(t,e,s){return su.apply(this,arguments)}function su(){return(su=X((function*(t,e,s){var n;try{return yield Promise.race([t,new Promise(((r,i)=>{n=zo((()=>{try{s?.(),r()}catch(o){i(o)}}),e)}))])}finally{clearTimeout(n)}}))).apply(this,arguments)}var Nh=t=>t instanceof Error,nu={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}},Mh=nu.info;function ru(t){if(Ke(t))return{boolValue:t};if(typeof t=="number")return Number.isFinite(t)?Number.isInteger(t)?{intValue:t}:{doubleValue:t}:{stringValue:String(t)};if(typeof t=="string")return{stringValue:t};if(L(t))return{arrayValue:{values:t.map((e=>ru(e)))}};try{return{stringValue:JSON.stringify(t)}}catch{return{stringValue:String(t)}}}function Xn(t){var e=[];for(var s in t){var n=t[s];$e(n)||x(n)||e.push({key:s,value:ru(n)})}return e}function Lh(t,e){var s=nu[t.level||"info"]||Mh,n=s.text,r=s.number,i=String(Date.now())+"000000",o={};e.distinctId&&(o.posthogDistinctId=e.distinctId),e.sessionId&&(o.sessionId=e.sessionId),e.windowId&&(o["window.id"]=e.windowId),D(e.sessionStartTimestamp)||(o.sessionStartTimestamp=String(e.sessionStartTimestamp)),D(e.lastActivityTimestamp)||(o.lastActivityTimestamp=String(e.lastActivityTimestamp)),e.currentUrl&&(o["url.full"]=e.currentUrl),e.screenName&&(o["screen.name"]=e.screenName),e.appState&&(o["app.state"]=e.appState),e.activeFeatureFlags&&e.activeFeatureFlags.length>0&&(o.feature_flags=e.activeFeatureFlags);var a=b({},o,t.attributes||{}),l={timeUnixNano:i,observedTimeUnixNano:i,severityNumber:r,severityText:n,body:{stringValue:t.body},attributes:Xn(a)};return t.trace_id&&(l.traceId=t.trace_id),t.span_id&&(l.spanId=t.span_id),x(t.trace_flags)||(l.flags=t.trace_flags),l}function iu(t,e,s){return b({},t.resourceAttributes,{"service.name":t.serviceName||"unknown_service"},t.environment&&{"deployment.environment":t.environment},t.serviceVersion&&{"service.version":t.serviceVersion},{"telemetry.sdk.name":e,"telemetry.sdk.version":s})}function ou(t,e,s,n){return{resourceLogs:[{resource:{attributes:Xn(e)},scopeLogs:[{scope:{name:s,version:n},logRecords:t}]}]}}let Oh=class{constructor(t,e,s,n,r,i,o){var a;i===void 0&&(i=()=>Promise.resolve()),this._instance=t,this.Ne=e,this.rt=s,this.ut=n,this.ht=r,this.dt=i,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 s={record:Lh(e,this.ut())};this.ht((()=>this.At(s)))}}else this.rt.info("Log was rejected in beforeSend function")}}Pt(t){var e=this.Ne.beforeSend;if(!e)return t;var s=L(e)?e:[e],n=t;for(var r of s)try{var i=r(n);if(!i)return this.rt.info("Log was rejected in beforeSend function"),null;n=i}catch(o){return this.rt.error("Error in beforeSend function for log:",o),null}return n}Rt(){if(this.Tt===void 0)return!0;var t=Date.now(),e=t-this.bt;return this.Mt>e&&e>=0||(this.bt=t,this._t=0,this.wt=!1),this.Tt>this._t?(this._t++,!0):(this.wt||(this.rt.warn("captureLog dropping logs: exceeded "+this.Tt+" logs per "+this.Mt+"ms"),this.wt=!0),!1)}flush(){var t=this;return X((function*(){if(!t._instance.isDisabled)return t.ct||(t.ct=t.Ft().finally((()=>{t.ct=null}))),t.ct}))()}Ft(){var t=this;return X((function*(){var e;t.Et();var s=(e=t._instance.getPersistedProperty(ut.LogsQueue))!==null&&e!==void 0?e:[];if(s.length!==0)for(var n=s.length,r=0;s.length>0&&n>r;){var i,o;t.ft=0;var a=Math.min(s.length,t.Ct),l=s.slice(0,a),u=ou(l.map((d=>d.record)),t.Lt(),(i=t.vt)!==null&&i!==void 0?i: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),s=(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 X((function*(){var s,n=Math.max(0,t-e.ft),r=(s=e._instance.getPersistedProperty(ut.LogsQueue))!==null&&s!==void 0?s:[];e._instance.setPersistedProperty(ut.LogsQueue,r.slice(n)),yield e.dt()}))()}Lt(){return iu(this.Ne,this._instance.getLibraryId(),this._instance.getLibraryVersion())}At(t){var e;if(!this._instance.optedOut){var s=(e=this._instance.getPersistedProperty(ut.LogsQueue))!==null&&e!==void 0?e:[];this.xt>s.length||(s.shift(),this.ft++,this.rt.info("Logs queue is full, dropping oldest record.")),s.push(t),this._instance.setPersistedProperty(ut.LogsQueue,s),this.kt>s.length?this.$t():this.It()}}$t(t){t===void 0&&(t=this.St),this.Nt||(this.Nt=zo((()=>{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 X((function*(){e.Et();var s=e.flush().catch((()=>{}));t!==void 0?yield Za(s,t):yield s}))()}flushWithTimeout(t){var e=this;return X((function*(){var s=e.flush();yield Za(s,t,(()=>{s.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 si=[0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4];function Xa(t){return String(t)+"000000"}function Qa(t,e,s,n){var r="";return n&&(r=Object.keys(n).sort().map((i=>JSON.stringify(i)+":"+JSON.stringify(n[i]))).join(",")),t+"\0"+e+"\0"+(s??"")+"\0"+r}let Dh=class{constructor(t,e,s){this._instance=t,this.Ne=e,this.rt=s,this.Bt=new Map,this.ct=null,this.Ht=!1,this.Ut=new Map,this.zt=new Set,this.Wt=0}count(t,e,s){e===void 0&&(e=1),this.Vt({name:t,type:"count",value:e,unit:s?.unit,attributes:s?.attributes})}gauge(t,e,s){this.Vt({name:t,type:"gauge",value:e,unit:s?.unit,attributes:s?.attributes})}histogram(t,e,s){this.Vt({name:t,type:"histogram",value:e,unit:s?.unit,attributes:s?.attributes})}flush(){var t=this,e=this.ct,s=(function(){var r=X((function*(){e&&(yield e.catch((()=>{}))),yield t.Zt()}));return function(){return r.apply(this,arguments)}})(),n=s().finally((()=>{this.ct===n&&(this.ct=null)}));return this.ct=n,n}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 s,n;try{s=e.attributes?b({},e.attributes):void 0,n=Qa(e.type,e.name,e.unit,s)}catch(o){return void this.rt.warn("Dropping metric '"+e.name+"': attributes could not be serialized",o)}var r=this.Bt.get(n);if(!r){if(!this.Qt())return;r={name:e.name,type:e.type,unit:e.unit,attributes:s,windowStartMs:Date.now()},this.Bt.set(n,r)}var i=this.Ut.get(e.name);i===void 0?this.Ut.set(e.name,e.type):i===e.type||this.zt.has(e.name)||(this.zt.add(e.name),this.rt.warn("Metric name '"+e.name+"' is already used as a "+i+"; recording it as a "+e.type+" too will blend both series in charts. Use a distinct name.")),this.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 s;switch(t.type){case"count":t.total=((s=t.total)!==null&&s!==void 0?s: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(si.length+1).fill(0)});var n=t.hist;n.count+=1,n.sum+=e,n.min=Math.min(n.min,e),n.max=Math.max(n.max,e),n.bucketCounts[(function(r,i){for(var o=0;i.length>o;o++)if(i[o]>=r)return o;return i.length})(e,si)]+=1}}Pt(t){var e=this.Ne.beforeSend;if(!e)return t;var s=L(e)?e:[e],n=t;for(var r of s)try{var i=r(n);if(!i)return this.rt.info("Metric was rejected in beforeSend function"),null;n=i}catch(o){return this.rt.error("Error in beforeSend function for metric:",o),null}return n}$t(){this.Nt||(this.Nt=zo((()=>{this.Nt=void 0,this.flush().catch((t=>{this.rt.error("Metrics flush failed:",t)}))}),this.Ne.flushIntervalMs))}Et(){this.Nt&&(clearTimeout(this.Nt),this.Nt=void 0)}Zt(){var t=this;return X((function*(){if(t.Bt.size!==0){var e=t.Bt;t.Bt=new Map,t.Ht=!1,t.Ut=new Map,t.zt=new Set;var s=t.Wt,n=yield t._instance.Jt(t.Gt(e));if(s===t.Wt)switch(n.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:",n.error)}}}))()}Gt(t){return e=this.Xt(t),s=(function(i,o,a){return b({},i.resourceAttributes,{"service.name":i.serviceName||"unknown_service"},i.environment&&{"deployment.environment":i.environment},i.serviceVersion&&{"service.version":i.serviceVersion},{"telemetry.sdk.name":o,"telemetry.sdk.version":a})})(this.Ne,this._instance.getLibraryId(),this._instance.getLibraryVersion()),n=this._instance.getLibraryId(),r=this._instance.getLibraryVersion(),{resourceMetrics:[{resource:{attributes:Xn(s)},scopeMetrics:[{scope:{name:n,version:r},metrics:e}]}]};var e,s,n,r}Xt(t){var e=Xa(Date.now()),s=new Map;for(var n of t.values()){var r,i=Qa(n.type,n.name,n.unit,void 0),o=s.get(i);o||(o=b({name:n.name},n.unit&&{unit:n.unit}),n.type==="count"?o.sum={aggregationTemporality:1,isMonotonic:!0,dataPoints:[]}:n.type==="gauge"?o.gauge={dataPoints:[]}:o.histogram={aggregationTemporality:1,dataPoints:[]},s.set(i,o));var a=Xn((r=n.attributes)!==null&&r!==void 0?r:{}),l=Xa(n.windowStartMs);if(n.type==="count"){var u,c={attributes:a,startTimeUnixNano:l,timeUnixNano:e,asDouble:(u=n.total)!==null&&u!==void 0?u:0};o.sum.dataPoints.push(c)}else if(n.type==="gauge"){var d,h={attributes:a,timeUnixNano:e,asDouble:(d=n.last)!==null&&d!==void 0?d:0};o.gauge.dataPoints.push(h)}else n.hist&&o.histogram.dataPoints.push({attributes:a,startTimeUnixNano:l,timeUnixNano:e,count:n.hist.count,sum:n.hist.sum,min:n.hist.min,max:n.hist.max,bucketCounts:n.hist.bucketCounts,explicitBounds:si})}return Array.from(s.values())}Yt(t){var e,s;for(var n of t){var r=n[0],i=n[1],o=this.Bt.get(r);if(o)switch(o.windowStartMs=Math.min(o.windowStartMs,i.windowStartMs),o.type){case"count":o.total=((e=o.total)!==null&&e!==void 0?e:0)+((s=i.total)!==null&&s!==void 0?s:0);break;case"gauge":break;case"histogram":if(i.hist)if(o.hist){o.hist.count+=i.hist.count,o.hist.sum+=i.hist.sum,o.hist.min=Math.min(o.hist.min,i.hist.min),o.hist.max=Math.max(o.hist.max,i.hist.max);for(var a=0;o.hist.bucketCounts.length>a;a++)o.hist.bucketCounts[a]+=i.hist.bucketCounts[a]}else o.hist=i.hist}else this.Qt()&&this.Bt.set(r,i)}}};var bn,el,ni;function Bh(t){var e=globalThis._posthogChunkIds;if(e){var s=Object.keys(e);return ni&&s.length===el||(el=s.length,ni=s.reduce(((n,r)=>{bn||(bn={});var i=bn[r];if(i)n[i[0]]=i[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){n[u]=c,bn[r]=[u,c];break}}return n}),{})),ni}}class jh{constructor(e,s,n){n===void 0&&(n=[]),this.coercers=e,this.stackParser=s,this.modifiers=n}buildFromUnknown(e,s){s===void 0&&(s={});var n=s&&s.mechanism||{handled:!0,type:"generic"},r=this.buildCoercingContext(n,s,0).apply(e),i=this.buildParsingContext(s),o=this.parseStacktrace(r,i);return{$exception_list:this.convertToExceptionList(o,n),$exception_level:"error"}}modifyFrames(e){var s=this;return X((function*(){for(var n of e)n.stacktrace&&n.stacktrace.frames&&L(n.stacktrace.frames)&&(n.stacktrace.frames=yield s.applyModifiers(n.stacktrace.frames));return e}))()}coerceFallback(e){var s;return{type:"Error",value:"Unknown error",stack:(s=e.syntheticException)==null?void 0:s.stack,synthetic:!0}}parseStacktrace(e,s){var n,r;return e.cause!=null&&(n=this.parseStacktrace(e.cause,s)),e.stack!=""&&e.stack!=null&&(r=this.applyChunkIds(this.stackParser(e.stack,e.synthetic?s.skipFirstLines:0),s.chunkIdMap)),b({},e,{cause:n,stack:r})}applyChunkIds(e,s){return e.map((n=>(n.filename&&s&&(n.chunk_id=s[n.filename]),n)))}applyCoercers(e,s){for(var n of this.coercers)if(n.match(e))return n.coerce(e,s);return this.coerceFallback(s)}applyModifiers(e){var s=this;return X((function*(){var n=e;for(var r of s.modifiers)n=yield r(n);return n}))()}convertToExceptionList(e,s){var n,r,i,o={type:e.type,value:e.value,mechanism:{type:(n=s.type)!==null&&n!==void 0?n:"generic",handled:(r=s.handled)===null||r===void 0||r,synthetic:(i=e.synthetic)!==null&&i!==void 0&&i}};e.stack&&(o.stacktrace={type:"raw",frames:e.stack});var a=[o];return e.cause!=null&&a.push(...this.convertToExceptionList(e.cause,b({},s,{handled:!0}))),a}buildParsingContext(e){var s;return{chunkIdMap:Bh(this.stackParser),skipFirstLines:(s=e.skipFirstLines)!==null&&s!==void 0?s:1}}buildCoercingContext(e,s,n){n===void 0&&(n=0);var r=(i,o)=>{if(4>=o){var a=this.buildCoercingContext(e,s,o);return this.applyCoercers(i,a)}};return b({},s,{syntheticException:n==0?s.syntheticException:void 0,mechanism:e,apply:i=>r(i,n),next:i=>r(i,n+1)})}}var gs="?";function Wi(t,e,s,n,r){var i={platform:t,filename:e,function:s===""?gs:s,in_app:!0};return x(n)||(i.lineno=n),x(r)||(i.colno=r),i}var au=(t,e)=>{var s=t.indexOf("safari-extension")!==-1,n=t.indexOf("safari-web-extension")!==-1;return s||n?[t.indexOf("@")!==-1?t.split("@")[0]:gs,s?"safari-extension:"+e:"safari-web-extension:"+e]:[t,e]},Uh=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,Hh=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,Wh=/\((\S*)(?::(\d+))(?::(\d+))\)/,zh=(t,e)=>{var s=Uh.exec(t);if(s)return Wi(e,s[1],gs,+s[2],+s[3]);var n=Hh.exec(t);if(n){if(n[2]&&n[2].indexOf("eval")===0){var r=Wh.exec(n[2]);r&&(n[2]=r[1],n[3]=r[2],n[4]=r[3])}var i=au(n[1]||gs,n[2]);return Wi(e,i[1],i[0],n[3]?+n[3]:void 0,n[4]?+n[4]:void 0)}},qh=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,Vh=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,Gh=(t,e)=>{var s=qh.exec(t);if(s){if(s[3]&&s[3].indexOf(" > eval")>-1){var n=Vh.exec(s[3]);n&&(s[1]=s[1]||"eval",s[3]=n[1],s[4]=n[2],s[5]="")}var r=s[3],i=s[1]||gs,o=au(i,r);return Wi(e,r=o[1],i=o[0],s[4]?+s[4]:void 0,s[5]?+s[5]:void 0)}},tl=/\(error: (.*)\)/;class Kh{match(e){return this.isDOMException(e)||this.isDOMError(e)}coerce(e,s){var n=W(e.stack);return{type:this.getType(e),value:this.getValue(e),stack:n?e.stack:void 0,cause:e.cause?s.next(e.cause):void 0,synthetic:!1}}getType(e){return this.isDOMError(e)?"DOMError":"DOMException"}getValue(e){var s=e.name||(this.isDOMError(e)?"DOMError":"DOMException");return e.message?s+": "+e.message:s}isDOMException(e){return Gn(e,"DOMException")}isDOMError(e){return Gn(e,"DOMError")}}class Jh{match(e){return(function(s){switch({}.toString.call(s)){case"[object Error]":case"[object Exception]":case"[object DOMException]":case"[object DOMError]":case"[object WebAssembly.Exception]":return!0;default:return Mc(s,Error)}})(e)}coerce(e,s){return{type:this.getType(e),value:this.getMessage(e,s),stack:this.getStack(e),cause:e.cause?s.next(e.cause):void 0,synthetic:!1}}getType(e){return e.name||e.constructor.name}getMessage(e,s){var n=e.message;return String(n.error&&typeof n.error.message=="string"?n.error.message:n)}getStack(e){return e.stacktrace||e.stack||void 0}}class Yh{constructor(){}match(e){return!!Gn(e,"ErrorEvent")&&(e.error!=null||this.fe(e))}coerce(e,s){var n;if(e.error!=null)return s.apply(e.error);var r=s.apply(e.message);return b({},r,{stack:(n=this.pe(e))!==null&&n!==void 0?n:r.stack,synthetic:!0})}fe(e){return W(e.message)&&e.message.length>0}pe(e){var s=e;if(W(s.filename)&&s.filename.length>0){var n,r,i=(n=s.lineno)!==null&&n!==void 0?n:0,o=(r=s.colno)!==null&&r!==void 0?r:0;return`Error + at `+s.filename+":"+i+":"+o}}}var Zh=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;class Xh{match(e){return typeof e=="string"}coerce(e,s){var n,r=this.getInfos(e),i=r[0],o=r[1];return{type:i??"Error",value:o??e,stack:(n=s.syntheticException)==null?void 0:n.stack,synthetic:!0}}getInfos(e){var s="Error",n=e,r=e.match(Zh);return r&&(s=r[1],n=r[2]),[s,n]}}var Qh=["fatal","error","warning","log","info","debug"];function lu(t,e){e===void 0&&(e=40);var s=Object.keys(t);if(s.sort(),!s.length)return"[object has no keys]";for(var n=s.length;n>0;n--){var r=s.slice(0,n).join(", ");if(e>=r.length)return n===s.length?r:r.length>e?r.slice(0,e)+"...":r}return""}class ep{match(e){return typeof e=="object"&&e!==null}coerce(e,s){var n,r,i=this.getErrorPropertyFromObject(e);return i?s.apply(i):{type:this.getType(e),value:this.getValue(e),stack:(n=this.getStack(e))!==null&&n!==void 0?n:(r=s.syntheticException)==null?void 0:r.stack,level:this.isSeverityLevel(e.level)?e.level:"error",synthetic:!0}}getType(e){return Bo(e)?e.constructor.name:"Error"}getValue(e){if("name"in e&&typeof e.name=="string"){var s="'"+e.name+"' captured as exception";return"message"in e&&typeof e.message=="string"&&(s+=" with message: '"+e.message+"'"),s}if("message"in e&&typeof e.message=="string")return e.message;var n=this.getObjectClassName(e);return(n&&n!=="Object"?"'"+n+"'":"Object")+" captured as exception with keys: "+lu(e)}isSeverityLevel(e){return W(e)&&!Di(e)&&Qh.indexOf(e)>=0}getStack(e){try{return W(e.stacktrace)&&e.stacktrace.length>0?e.stacktrace:W(e.stack)&&e.stack.length>0?e.stack:void 0}catch{return}}getErrorPropertyFromObject(e){for(var s in e)if({}.hasOwnProperty.call(e,s)){var n=e[s];if(Nh(n))return n}}getObjectClassName(e){try{var s=Object.getPrototypeOf(e);return s?s.constructor.name:void 0}catch{return}}}class tp{match(e){return Bo(e)}coerce(e,s){var n,r=e.constructor.name;return{type:r,value:r+" captured as exception with keys: "+lu(e),stack:(n=s.syntheticException)==null?void 0:n.stack,synthetic:!0}}}class sp{match(e){return Nc(e)}coerce(e,s){var n;return{type:"Error",value:"Primitive value captured as exception: "+String(e),stack:(n=s.syntheticException)==null?void 0:n.stack,synthetic:!0}}}class np{match(e){return Gn(e,"PromiseRejectionEvent")||this.isCustomEventWrappingRejection(e)}isCustomEventWrappingRejection(e){if(!Bo(e))return!1;try{var s=e.detail;return s!=null&&typeof s=="object"&&"reason"in s}catch{return!1}}coerce(e,s){var n,r=this.getUnhandledRejectionReason(e);return Nc(r)?{type:"UnhandledRejection",value:"Non-Error promise rejection captured with value: "+String(r),stack:(n=s.syntheticException)==null?void 0:n.stack,synthetic:!0}:s.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 Qn="$message",er="$timestamp",rp=new Set([Qn,er]),ri={enabled:!0,max_bytes:32768};function tr(t){var e;return t?{enabled:(e=t.enabled)!==null&&e!==void 0?e:ri.enabled,max_bytes:op(t.max_bytes,ri.max_bytes)}:b({},ri)}class ip{constructor(e){this.Ke=[],this.Je=0,this.Ne=tr(e)}setConfig(e){this.Ne=tr(e),this.Xe()}add(e){var s=(function(r){var i;try{i=$c(r)}catch{return}try{var o=JSON.parse(i);if(!te(o))return;var a=o,l=a[Qn],u=a[er];return!W(l)||l.trim().length===0||!W(u)&&!he(u)?void 0:{step:a,json:i}}catch{return}})(e);if(s){var n=(function(r){if(typeof TextEncoder<"u")return new TextEncoder().encode(r).length;for(var i=encodeURIComponent(r),o=0,a=0;i.length>a;a++)i[a]==="%"?(o+=1,a+=2):o+=1;return o})(s.json);n>this.Ne.max_bytes||(this.Ke.push({step:s.step,bytes:n}),this.Je+=n,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 op(t,e){if(!he(t)||t===1/0||t===-1/0)return e;var s=Math.floor(t);return 0>s?e:s}var cu=function(t,e){var s=(e===void 0?{}:e).debugEnabled,n={k(r){if(v&&(Y.DEBUG||v.POSTHOG_DEBUG||s)&&!x(v.console)&&v.console){for(var i=("__rrweb_original__"in v.console[r])?v.console[r].__rrweb_original__:v.console[r],o=arguments.length,a=new Array(o>1?o-1:0),l=1;o>l;l++)a[l-1]=arguments[l];i(t,...a)}},debug(){for(var r=arguments.length,i=new Array(r),o=0;r>o;o++)i[o]=arguments[o];n.k("debug",...i)},info(){for(var r=arguments.length,i=new Array(r),o=0;r>o;o++)i[o]=arguments[o];n.k("log",...i)},warn(){for(var r=arguments.length,i=new Array(r),o=0;r>o;o++)i[o]=arguments[o];n.k("warn",...i)},error(){for(var r=arguments.length,i=new Array(r),o=0;r>o;o++)i[o]=arguments[o];n.k("error",...i)},critical(){for(var r=arguments.length,i=new Array(r),o=0;r>o;o++)i[o]=arguments[o];console.error(t,...i)},uninitializedWarning(r){n.error("You must initialize PostHog before calling "+r)},createLogger:(r,i)=>cu(t+" "+r,i)};return n},k=cu("[PostHog.js]"),se=k.createLogger,ap=se("[ExternalScriptsLoader]"),ii=(t,e,s)=>{if(t.config.disable_external_dependency_loading)return ap.warn(e+" was requested but loading of external scripts is disabled."),s("Loading of external scripts is disabled");var n=C?.querySelectorAll("script");if(n){for(var r,i=function(){if(n[o].src===e){var l=n[o];return l.__posthog_loading_callback_fired?{v:s()}:(l.addEventListener("load",(u=>{l.__posthog_loading_callback_fired=!0,s(void 0,u)})),l.onerror=u=>s(u),{v:void 0})}},o=0;n.length>o;o++)if(r=i())return r.v}var a=()=>{if(!C)return s("document not found");var l=C.createElement("script");if(l.type="text/javascript",l.crossOrigin="anonymous",l.src=e,l.onload=d=>{l.__posthog_loading_callback_fired=!0,s(void 0,d)},l.onerror=d=>s(d),t.config.prepare_external_dependency_script&&(l=t.config.prepare_external_dependency_script(l)),!l)return s("prepare_external_dependency_script returned null");if(t.config.external_scripts_inject_target==="head")C.head.appendChild(l);else{var u,c=C.querySelectorAll("body > script");c.length>0?(u=c[0].parentNode)==null||u.insertBefore(l,c[0]):C.body.appendChild(l)}};C!=null&&C.body?a():C?.addEventListener("DOMContentLoaded",a)};$.__PosthogExtensions__=$.__PosthogExtensions__||{},$.__PosthogExtensions__.loadExternalDependency=(t,e,s)=>{if(e!=="remote-config"){var n;if(t.config.strict_script_versioning)n=t.requestRouter.endpointFor("assets","/static/"+t.version+"/"+e+".js");else{var r="/static/"+e+".js?v="+t.version;if(e==="toolbar"){var i=3e5;r=r+"&t="+Math.floor(Date.now()/i)*i}n=t.requestRouter.endpointFor("assets",r)}ii(t,n,s)}else{var o=t.requestRouter.endpointFor("assets","/array/"+t.config.token+"/config.js");ii(t,o,s)}},$.__PosthogExtensions__.loadSiteApp=(t,e,s)=>{var n=t.requestRouter.endpointFor("api",e);ii(t,n,s)};Y.DEBUG=!1,Y.LIB_VERSION="1.415.7",Y.LIB_NAME="web";var uu="$people_distinct_id",sn="$device_id",oi="$device_model",Bs="__alias",js="__timers",zi="$autocapture_disabled_server_side",qi="$heatmaps_enabled_server_side",Vi="$exception_capture_enabled_server_side",Gi="$error_tracking_suppression_rules",Ki="$error_tracking_capture_extension_exceptions",Ji="$web_vitals_enabled_server_side",qo="$dead_clicks_enabled_server_side",Vo="$product_tours_enabled_server_side",Yi="$web_vitals_allowed_metrics",qt="$session_recording_remote_config",du="$replay_sample_rate",hu="$replay_override_sampling",pu="$replay_override_linked_flag",fu="$replay_override_url_trigger",gu="$replay_override_event_trigger",ls="$sesid",Go="$session_is_sampled",Bt="$enabled_feature_flags",Us="$active_feature_flags",Tn="$early_access_features",Zi="$feature_flag_details",Hs="$feature_flag_payloads",Nn="$feature_flag_request_id",sr="$minimal_flag_called_events",et="$override_feature_flags",jt="$override_feature_flag_payloads",ct="$stored_person_properties",Ut="$stored_group_properties",Xi="$surveys",nr="$surveys_loaded_at",Qi="$surveys_activated",Mn="$surveys_activated_session",Ln="$surveys_activated_timestamps",Ws="ph_product_tours",Wt="$flag_call_reported",zs="$flag_call_reported_session_id",On="$feature_flag_errors",Gs="$feature_flag_evaluated_at",He="$user_state",eo="$client_session_props",to="$capture_rate_limit",so="$initial_campaign_params",no="$initial_referrer_info",rr="$initial_person_info",ir="$epp",En="$posthog_cookieless",mu="$cookieless_mode",vu="$sdk_debug_extensions_init_method",_u="$sdk_debug_extensions_init_time_ms",yu="$sdk_debug_recording_script_not_loaded",Ko="PostHog loadExternalDependency extension not found.",Ht="on_reject",ht="always",es="anonymous",Tt="identified",ro="identified_only",or="visibilitychange",ar="beforeunload",is="$pageview",ai="$pageleave",li="$identify",sl="$groupidentify";function Sn(t,e){L(t)&&t.forEach(e)}function Z(t,e){if(!D(t))if(L(t))t.forEach(e);else if(_h(t))t.forEach(((n,r)=>e(n,r)));else for(var s in t)Tc.call(t,s)&&e(t[s],s)}var ee=function(t){for(var e=arguments.length,s=new Array(e>1?e-1:0),n=1;e>n;n++)s[n-1]=arguments[n];for(var r of s)for(var i in r)r[i]!==void 0&&(t[i]=r[i]);return t};function Dn(t){for(var e=Object.keys(t),s=e.length,n=new Array(s);s--;)n[s]=[e[s],t[e[s]]];return n}var nl=function(t){try{return t()}catch{return}},lp=function(t){return function(){try{for(var e=arguments.length,s=new Array(e),n=0;e>n;n++)s[n]=arguments[n];return t.apply(this,s)}catch(r){k.critical("Implementation error. Please turn on debug mode and open a ticket on https://app.posthog.com/home#panel=support%3Asupport%3A."),k.critical(r)}}},Jo=function(t){var e={};return Z(t,(function(s,n){(W(s)&&s.length>0||he(s))&&(e[n]=s)})),e},cp=["herokuapp.com","vercel.app","netlify.app"];function up(t){var e=t?.hostname;if(!W(e))return!1;var s=e.split(".").slice(-2).join(".");for(var n of cp)if(s===n)return!1;return!0}function re(t,e,s,n){var r=n??{},i=r.capture,o=r.passive;t?.addEventListener(e,s,{capture:i!==void 0&&i,passive:o===void 0||o})}function io(t){return t.name==="ph_toolbar_internal"}var wu=t=>{if(C){try{for(var e=t+"=",s=C.cookie.split(";").filter((i=>i.length)),n=0;s.length>n;n++){for(var r=s[n];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 he(t)&&isFinite(t)&&Math.floor(t)===t});class lr{constructor(e){if(this.bytes=e,e.length!==16)throw new TypeError("not 128-bit length")}static fromFieldsV7(e,s,n,r){if(!Number.isInteger(e)||!Number.isInteger(s)||!Number.isInteger(n)||!Number.isInteger(r)||0>e||0>s||0>n||0>r||e>0xffffffffffff||s>4095||n>1073741823||r>4294967295)throw new RangeError("invalid field value");var i=new Uint8Array(16);return i[0]=e/Math.pow(2,40),i[1]=e/Math.pow(2,32),i[2]=e/Math.pow(2,24),i[3]=e/Math.pow(2,16),i[4]=e/256,i[5]=e,i[6]=112|s>>>8,i[7]=s,i[8]=128|n>>>24,i[9]=n>>>16,i[10]=n>>>8,i[11]=n,i[12]=r>>>24,i[13]=r>>>16,i[14]=r>>>8,i[15]=r,new lr(i)}toString(){for(var e="",s=0;this.bytes.length>s;s++)e=e+(this.bytes[s]>>>4).toString(16)+(15&this.bytes[s]).toString(16),s!==3&&s!==5&&s!==7&&s!==9||(e+="-");if(e.length!==36)throw new Error("Invalid UUIDv7 was generated");return e}clone(){return new lr(this.bytes.slice(0))}equals(e){return this.compareTo(e)===0}compareTo(e){for(var s=0;16>s;s++){var n=this.bytes[s]-e.bytes[s];if(n!==0)return Math.sign(n)}return 0}}class dp{generate(){var e=this.generateOrAbort();if(!x(e))return e;this.S=0;var s=this.generateOrAbort();if(x(s))throw new Error("Could not generate UUID after timestamp reset");return s}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 lr.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 hp}}var rl,bu=t=>{if(typeof UUIDV7_DENY_WEAK_RNG<"u"&&UUIDV7_DENY_WEAK_RNG)throw new Error("no cryptographically strong RNG available");for(var e=0;t.length>e;e++)t[e]=65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random());return t};v&&!x(v.crypto)&&crypto.getRandomValues&&(bu=t=>crypto.getRandomValues(t));class hp{nextUint32(){return this.R.length>this.O||(bu(this.R),this.O=0),this.R[this.O++]}constructor(){this.R=new Uint32Array(8),this.O=1/0}}var dt=()=>pp().toString(),pp=()=>(rl||(rl=new dp)).generate(),Ps="",fp=/[a-z0-9][a-z0-9-]+\.[a-z]{2,}$/i,pt={N:()=>!!C,j(t){k.error("cookieStore error: "+t)},P:wu,H(t){var e;try{e=JSON.parse(pt.P(t))||{}}catch{}return e},F(t,e,s,n,r){if(!C)return!1;try{var i="",o="",a=(function(c,d){if(d){var h=(function(f,g){if(g===void 0&&(g=C),Ps)return Ps;if(!g||["localhost","127.0.0.1"].includes(f))return"";for(var m=f.split("."),_=Math.min(m.length,8),w="dmn_chk_"+dt();!Ps&&_--;){var E=m.slice(_).join("."),I=w+"=1;domain=."+E+";path=/";g.cookie=I+";max-age=3",g.cookie.includes(w)&&(g.cookie=I+";max-age=0",Ps=E)}return Ps})(c);if(!h){var p=(f=>{var g=f.match(fp);return g?g[0]:""})(c);p!==h&&k.info("Warning: cookie subdomain discovery mismatch",p,h),h=p}return h?"; domain=."+h:""}return""})(C.location.hostname,n);if(s){var l=new Date;l.setTime(l.getTime()+864e5*s),i="; expires="+l.toUTCString()}r&&(o="; secure");var u=t+"="+encodeURIComponent(JSON.stringify(e))+i+"; SameSite=Lax; path=/"+a+o;return u.length>3686.4&&k.warn("cookieStore warning: large cookie, len="+u.length),C.cookie=u,!0}catch{return!1}},q(t,e){if(C!=null&&C.cookie)try{pt.F(t,"",-1,e)}catch{return}}},ci=null,Q={N(){if(!$e(ci))return ci;var t=!0;if(x(v))t=!1;else try{var e="__mplssupport__";Q.F(e,"xyz"),Q.P(e)!=='"xyz"'&&(t=!1),Q.q(e)}catch{t=!1}return t||k.error("localStorage unsupported; falling back to cookie store"),ci=t,t},j(t){k.error("localStorage error: "+t)},P(t){try{return v?.localStorage.getItem(t)}catch(e){Q.j(e)}return null},H(t){try{return JSON.parse(Q.P(t))||{}}catch{}return null},F(t,e){try{return v?.localStorage.setItem(t,JSON.stringify(e)),!0}catch(s){Q.j(s)}return!1},q(t){try{v?.localStorage.removeItem(t)}catch(e){Q.j(e)}}},gp=[sn,"distinct_id",ls,Go,ir,rr,He],xn={},mp={N:()=>!0,j(t){k.error("memoryStorage error: "+t)},P:t=>xn[t]||null,H:t=>xn[t]||null,F:(t,e)=>(xn[t]=e,!0),q(t){delete xn[t]}},Nt=null,ce={N(){if(!$e(Nt))return Nt;if(Nt=!0,x(v))Nt=!1;else try{var t="__support__";ce.F(t,"xyz"),ce.P(t)!=='"xyz"'&&(Nt=!1),ce.q(t)}catch{Nt=!1}return Nt},j(t){k.error("sessionStorage error: ",t)},P(t){try{return v?.sessionStorage.getItem(t)}catch(e){ce.j(e)}return null},H(t){try{return JSON.parse(ce.P(t))||null}catch{}return null},F(t,e){try{return v?.sessionStorage.setItem(t,JSON.stringify(e)),!0}catch(s){ce.j(s)}return!1},q(t){try{v?.sessionStorage.removeItem(t)}catch(e){ce.j(e)}}};class vp{constructor(e){this._instance=e}get Ne(){return this._instance.config}get consent(){return this.ti()?0:this.ei}isOptedOut(){return this.Ne.cookieless_mode===ht||this.isRejected()||this.consent===-1&&this.Ne.cookieless_mode===Ht}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,s=e.token,n=e.opt_out_capturing_cookie_prefix;return e.consent_persistence_name||(n?n+s:"__ph_opt_in_out_"+s)}get ei(){var e=this.ii.P(this.ri);return ei(e)?1:M(Eh,e)?0:-1}get ii(){var e=this.Ne.opt_out_capturing_persistence_type,s=e==="localStorage"?Q:pt;if(!this.ni||this.ni!==s){this.ni=s;var n=e==="localStorage"?pt:Q;n.P(this.ri)&&(this.ni.P(this.ri)||this.optInOut(ei(n.P(this.ri))),n.q(this.ri,this.Ne.cross_subdomain_cookie))}return this.ni}ti(){return!!this.Ne.respect_dnt&&[ke?.doNotTrack,ke?.msDoNotTrack,$.doNotTrack].some((e=>ei(e)))}}function Eu(t,e){var s,n=t==null||(s=t.config)==null?void 0:s.get_current_url;if(!Se(n))return e;try{var r=n(e);return W(r)&&r?r:e}catch(i){return k.error("Error in get_current_url, falling back to window.location.href",i),e}}var Su="__POSTHOG_TOOLBAR__",_p=1,yp=3,wp=11;function il(t){return t instanceof Element&&(t.id===Su||!(t.closest==null||!t.closest(".toolbar-global-fade-container")))}function Ft(t){return!!t&&t.nodeType===_p}function Me(t,e){return!!t&&!!t.tagName&&t.tagName.toLowerCase()===e.toLowerCase()}function xu(t){return!!t&&t.nodeType===yp}function ku(t){return!!t&&t.nodeType===wp&&Ft(t.host)}var Iu=1e3;function Yo(t){return t?Ar(t).split(/\s+/):[]}function ol(t,e){var s=(function(n){var r,i=v==null||(r=v.location)==null?void 0:r.href;return x(i)?void 0:Eu(n,i)})(e);return!!(s&&t&&t.some((n=>s.match(n))))}function cr(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 Yo(e)}function Cu(t){return D(t)?null:Ar(t).split(/(\s+)/).filter((e=>Ks(e))).join("").replace(/[\r\n]/g," ").replace(/[ ]+/g," ").substring(0,255)}function nn(t){var e="";return ao(t)&&!$u(t)&&t.childNodes&&t.childNodes.length&&Z(t.childNodes,(function(s){var n;xu(s)&&s.textContent&&(e+=(n=Cu(s.textContent))!==null&&n!==void 0?n:"")})),Ar(e)}function ui(t){var e;return x(t.target)?t.srcElement||null:(e=t.target)!=null&&e.shadowRoot?t.composedPath()[0]||null:t.target||null}var Zo=["a","button","form","input","select","textarea","label"];function oo(t,e){if(x(e))return!0;var s,n=function(i){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}})(i,o))))return{v:!0}};for(var r of t)if(s=n(r))return s.v;return!1}function Fu(t){var e=t.parentNode;return!(!e||!Ft(e))&&e}var bp=[".ph-no-autocapture","[data-ph-no-autocapture]"],Pu=["next","previous","prev",">","<"],Ep=[...Pu,"+","-","−","–"],al=(t,e)=>/[a-z0-9]/i.test(e)?t.includes(e):t===e,ll=[".ph-no-rageclick",".ph-no-capture"],Sp=["","text","search","email","password","url","tel","number"];function cl(t,e){if(!v||Xo(t))return!1;var s,n,r,i,o;if(Ke(e)?(s=!!e&&ll,n=void 0,r=!1):(s=(i=e?.css_selector_ignorelist)!==null&&i!==void 0?i:ll,n=e?.content_ignorelist,r=(o=e?.ignore_text_selection)!==null&&o!==void 0&&o),s===!1||r&&(function(l){return!(!l||!Ft(l))&&(!!Me(l,"textarea")||(Me(l,"input")?M(Sp,(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=Au(t,!1).targetElementList;return!(function(l,u){if(l===!1||x(l))return!1;var c;if(l===!0)c=Pu;else{if(!L(l))return!1;if(l.length>10)return k.error("[PostHog] content_ignorelist array cannot exceed 10 items. Use css_selector_ignorelist for more complex matching."),!1;c=l.map((d=>d.toLowerCase()))}return u.some((d=>{var h=d.safeText,p=d.ariaLabel;return c.some((f=>al(h,f)||al(p,f)))}))})(n,a.map((l=>{var u;return{safeText:nn(l).toLowerCase(),ariaLabel:((u=l.getAttribute("aria-label"))==null?void 0:u.toLowerCase().trim())||""}})))&&!oo(a,s)}var Xo=t=>!t||Me(t,"html")||!Ft(t),Au=(t,e)=>{if(!v||Xo(t))return{parentIsUsefulElement:!1,targetElementList:[]};for(var s=!1,n=[t],r=t;r.parentNode&&!Me(r,"body");)if(ku(r.parentNode))n.push(r.parentNode.host),r=r.parentNode.host;else{var i=Fu(r);if(!i)break;if(e||Zo.indexOf(i.tagName.toLowerCase())>-1)s=!0;else try{var o=v.getComputedStyle(i);o&&o.getPropertyValue("cursor")==="pointer"&&(s=!0)}catch{}n.push(i),r=i}return{parentIsUsefulElement:s,targetElementList:n}};function ao(t){for(var e=new Set,s=0,n=t;n.parentNode&&!Me(n,"body");n=n.parentNode){if(s++>=Iu||e.has(n))return!1;e.add(n);var r=cr(n);if(M(r,"ph-sensitive")||M(r,"ph-no-capture"))return!1}if(M(cr(t),"ph-include"))return!0;var i=t.type||"";if(W(i))switch(i.toLowerCase()){case"hidden":case"password":return!1}var o=t.name||t.id||"";return!W(o)||!/^cc|cardnum|ccnum|creditcard|csc|cvc|cvv|exp|pass|pwd|routing|seccode|securitycode|securitynum|socialsec|socsec|ssn/i.test(o.replace(/[^a-zA-Z0-9]/g,""))}function $u(t){return!!(Me(t,"input")&&!["button","checkbox","submit","reset"].includes(t.type)||Me(t,"select")||Me(t,"textarea")||t.getAttribute("contenteditable")==="true")}var ul=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}))$"),dl=/(^|[^0-9A-Za-z_])([0-9][0-9 -]*[0-9])(?=$|[^0-9A-Za-z_])/g,xp=[16,15,14,13],kp=new RegExp("^(\\d{3}-?\\d{2}-?\\d{4})$"),hl=new RegExp("(^|[^0-9])((?!000|666)[0-9]{3}-?(?!00)[0-9]{2}-?(?!0000)[0-9]{4})(?=$|([^0-9]))","g"),pl=/[0-9A-Za-z_]/;function Ip(t){for(var e=0,s=!1,n=t.length-1;n>=0;n--){var r=t.charCodeAt(n)-48;s&&(r*=2)>9&&(r-=9),e+=r,s=!s}return e%10==0}function Ks(t,e){if(e===void 0&&(e=!0),D(t))return!1;if(W(t)){t=Ar(t);var s=e?ul.test((t||"").replace(/[- ]/g,"")):(function(r){var i;for(dl.lastIndex=0;i=dl.exec(r);){var o=i[2];if(o)for(var a=o.replace(/[- ]/g,""),l=0;a.length>l;l++)for(var u of xp){var c=l+u;if(a.length>=c){var d=a.slice(l,c);if(ul.test(d)&&Ip(d))return!0}}}return!1})(t);if(s)return!1;var n=e?kp.test(t):(function(r){var i;for(hl.lastIndex=0;i=hl.exec(r);){var o=i[1],a=i[3];if(!(o&&a&&pl.test(o)&&pl.test(a)))return!0}return!1})(t);if(n)return!1}return!0}function fl(t){var e=nn(t);return Ks(e=(e+" "+Ru(t)).trim())?e:""}function Ru(t){var e="";return t&&t.childNodes&&t.childNodes.length&&Z(t.childNodes,(function(s){var n;if(s&&((n=s.tagName)==null?void 0:n.toLowerCase())==="span")try{var r=nn(s);e=(e+" "+r).trim(),s.childNodes&&s.childNodes.length&&(e=(e+" "+Ru(s)).trim())}catch(i){k.error("[AutoCapture]",i)}})),e}function gl(t){return t.replace(/"|\\"/g,'\\"')}function Cp(t){var e=t.attr__class;if(e)return L(e)?e:Yo(e)}var kn=se("[Dead Clicks]"),Fp=()=>!0,Pp=t=>{var e,s=!((e=t.instance.persistence)==null||!e.get_property(qo)),n=t.instance.config.capture_dead_clicks;return Ke(n)?n:!!te(n)||s};class ml{get lazyLoadedDeadClicksAutocapture(){return this.si}constructor(e,s,n){this.instance=e,this.isEnabled=s,this.onCapture=n,this.startIfEnabledOrStop()}onRemoteConfig(e){if(e.ok){var s=e.config;"captureDeadClicks"in s&&(this.instance.persistence&&this.instance.persistence.register({[qo]:s.captureDeadClicks}),this.startIfEnabledOrStop())}}startIfEnabledOrStop(){this.isEnabled(this)?this.ai((()=>{this.oi()})):this.stop()}ai(e){var s,n;(s=$.__PosthogExtensions__)!=null&&s.initDeadClicksAutocapture?e():(n=$.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this.instance,"dead-clicks-autocapture",(r=>{r?kn.error("failed to load script",r):e()}))}oi(){var e;if(C){if(!this.si&&(e=$.__PosthogExtensions__)!=null&&e.initDeadClicksAutocapture){var s=te(this.instance.config.capture_dead_clicks)?b({},this.instance.config.capture_dead_clicks):{};s.__onCapture=this.onCapture,this.onCapture&&(s.capture_dead_swipes=!1),this.si=$.__PosthogExtensions__.initDeadClicksAutocapture(this.instance,s),this.si.start(C),kn.info("starting...")}}else kn.error("`document` not found. Cannot start.")}stop(){this.si&&(this.si.stop(),this.si=void 0,kn.info("stopping..."))}}var di=se("[SegmentIntegration]"),Tu="posthog-js";function Nu(t,e){var s=e===void 0?{}:e,n=s.organization,r=s.projectId,i=s.prefix,o=s.severityAllowList,a=o===void 0?["error"]:o,l=s.sendExceptionsToPostHog,u=l===void 0||l;return c=>{var d,h,p,f,g;if(a!=="*"&&!a.includes(c.level)||!t.__loaded)return c;c.tags||(c.tags={});var m=t.requestRouter.endpointFor("ui","/project/"+t.config.token+"/person/"+t.get_distinct_id());c.tags["PostHog Person URL"]=m,t.sessionRecordingStarted()&&(c.tags["PostHog Recording URL"]=t.get_session_replay_url({withTimestamp:!0}));var _,w=((d=c.exception)==null?void 0:d.values)||[],E=w.map((F=>b({},F,{stacktrace:F.stacktrace?b({},F.stacktrace,{type:"raw",frames:(F.stacktrace.frames||[]).map((P=>b({},P,{platform:"web:javascript"})))}):void 0}))),I={$exception_message:((h=w[0])==null?void 0:h.value)||c.message,$exception_type:(p=w[0])==null?void 0:p.type,$exception_level:c.level,$exception_list:E,$sentry_event_id:c.event_id,$sentry_exception:c.exception,$sentry_exception_message:((f=w[0])==null?void 0:f.value)||c.message,$sentry_exception_type:(g=w[0])==null?void 0:g.type,$sentry_tags:c.tags};return n&&r&&(I.$sentry_url=(i||"https://sentry.io/organizations/")+n+"/issues/?project="+r+"&query="+c.event_id),u&&((_=t.exceptions)==null||_.sendExceptionEvent(I)),c}}class Ap{constructor(e,s,n,r,i,o){this.name=Tu,this.setupOnce=function(a){a(Nu(e,{organization:s,projectId:n,prefix:r,severityAllowList:i,sendExceptionsToPostHog:o==null||o}))}}}class vl{constructor(e){this.li=(s,n,r)=>{r&&(r.noSessionId||r.activityTimeout||r.sessionPastMaximumLength||r.crossTabAdoption)&&(k.info("[PageViewManager] Session rotated, clearing pageview state",{sessionId:s,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,s){var n,r=this.vi(e,s);return this.ui={pathname:(n=v?.location.pathname)!==null&&n!==void 0?n:"",pageViewId:s,timestamp:e},this._instance.scrollManager.resetContext(),r}doPageLeave(e){var s;return this.vi(e,(s=this.ui)==null?void 0:s.pageViewId)}doEvent(){var e;return{$pageview_id:(e=this.ui)==null?void 0:e.pageViewId}}vi(e,s){var n=this.ui;if(!n)return{$pageview_id:s};var r={$pageview_id:s,$prev_pageview_id:n.pageViewId},i=this._instance.scrollManager.getContext();if(i&&!this._instance.config.disable_scroll_properties){var o=i.maxScrollHeight,a=i.lastScrollY,l=i.maxScrollY,u=i.maxContentHeight,c=i.lastContentY,d=i.maxContentY;if(!(x(o)||x(a)||x(l)||x(u)||x(c)||x(d))){o=Math.ceil(o),a=Math.ceil(a),l=Math.ceil(l),u=Math.ceil(u),c=Math.ceil(c),d=Math.ceil(d);var h=o>1?nt(a/o,0,1,k):1,p=o>1?nt(l/o,0,1,k):1,f=u>1?nt(c/u,0,1,k):1,g=u>1?nt(d/u,0,1,k):1;r=ee(r,{$prev_pageview_last_scroll:a,$prev_pageview_last_scroll_percentage:h,$prev_pageview_max_scroll:l,$prev_pageview_max_scroll_percentage:p,$prev_pageview_last_content:c,$prev_pageview_last_content_percentage:f,$prev_pageview_max_content:d,$prev_pageview_max_content_percentage:g})}}return n.pathname&&(r.$prev_pageview_pathname=n.pathname),n.timestamp&&(r.$prev_pageview_duration=(e.getTime()-n.timestamp.getTime())/1e3),r}}var hi=["flags","surveys"],$p={[uu]:{exposure:"hidden"},[Bs]:{exposure:"hidden"},__cmpns:{exposure:"hidden"},[js]:{exposure:"hidden"},[zi]:{exposure:"event"},[qi]:{exposure:"hidden"},[Vi]:{exposure:"event"},[Gi]:{exposure:"hidden"},[Ki]:{exposure:"event"},[Ji]:{exposure:"event"},[qo]:{exposure:"event"},[Vo]:{exposure:"hidden"},[Yi]:{exposure:"event"},[qt]:{exposure:"hidden"},$session_recording_enabled_server_side:{exposure:"hidden"},[ls]:{exposure:"hidden"},[Go]:{exposure:"event"},[du]:{exposure:"event",shouldSkipFromEventProperties:t=>$e(t)},$session_past_minimum_duration:{exposure:"event"},$session_recording_url_trigger_activated_session:{exposure:"event"},$session_recording_event_trigger_activated_session:{exposure:"event"},$debug_first_full_snapshot_timestamp:{exposure:"event"},$sess_rec_flush_size:{exposure:"hidden"},[Bt]:{exposure:"hidden",storageGroup:"flags"},[Us]:{exposure:"hidden",storageGroup:"flags"},[Tn]:{exposure:"hidden"},[Zi]:{exposure:"hidden",storageGroup:"flags"},[Hs]:{exposure:"hidden",storageGroup:"flags"},[Nn]:{exposure:"hidden",storageGroup:"flags",volatile:!0},[sr]:{exposure:"hidden",storageGroup:"flags"},[et]:{exposure:"hidden"},[jt]:{exposure:"hidden"},[ct]:{exposure:"hidden"},[Ut]:{exposure:"hidden"},[Xi]:{exposure:"hidden",storageGroup:"surveys"},[nr]:{exposure:"hidden",storageGroup:"surveys",volatile:!0},[Qi]:{exposure:"event"},[Mn]:{exposure:"hidden"},[Ln]:{exposure:"hidden"},[Ws]:{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"},[Wt]:{exposure:"hidden"},[zs]:{exposure:"hidden"},[On]:{exposure:"hidden"},[Gs]:{exposure:"hidden",storageGroup:"flags",volatile:!0},[He]:{exposure:"hidden"},[eo]:{exposure:"hidden"},[to]:{exposure:"hidden"},[so]:{exposure:"hidden"},[no]:{exposure:"hidden"},[rr]:{exposure:"hidden"},[ir]:{exposure:"hidden"},[hu]:{exposure:"event"},[pu]:{exposure:"event"},[fu]:{exposure:"event"},[gu]:{exposure:"event"},[vu]:{exposure:"event"},[_u]:{exposure:"event"},[yu]:{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"}},Rp=[["$posthog_sr_group_event_trigger_",{exposure:"hidden"}],["$posthog_sr_group_url_trigger_",{exposure:"hidden"}],["$posthog_sr_group_sampling_",{exposure:"hidden"}]],Mt=t=>{var e=$p[t];if(e)return e;for(var s of Rp){var n=s[1];if(t.indexOf(s[0])===0)return n}},cs=(t,e)=>{try{return JSON.stringify(t,((s,n)=>typeof n=="bigint"?n.toString():n),e)}catch{return $c(t)}},ur=t=>{var e=C?.createElement("a");return x(e)?null:(e.href=t,e)},ms=function(t,e){for(var s,n=((t.split("#")[0]||"").split(/\?(.*)/)[1]||"").replace(/^\?+/g,"").split("&"),r=0;n.length>r;r++){var i=n[r].split("=");if(i[0]===e){s=i;break}}if(!L(s)||2>s.length)return"";var o=s[1];try{o=decodeURIComponent(o)}catch{k.error("Skipping decoding for malformed query param: "+o)}return o.replace(/\+/g," ")},rn=function(t,e,s){if(!t||!e||!e.length)return t;for(var n=t.split("#"),r=n[1],i=(n[0]||"").split("?"),o=i[1],a=i[0],l=(o||"").split("&"),u=[],c=0;l.length>c;c++){var d=l[c].split("=");L(d)&&(e.includes(d[0])?u.push(d[0]+"="+s):u.push(l[c]))}var h=a;return o!=null&&(h+="?"+u.join("&")),r!=null&&(h+="#"+r),h},dr=function(t,e){var s=t.match(new RegExp(e+"=([^&]*)"));return s?s[1]:null},Mu=(t,e)=>t>=e&&Fc(),Lu=(t,e,s,n)=>{if(t===0){if(Fc()){var r=e+1;return r===s&&n(),r}return e}return 0},In="https?://(.*)",vs=["gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","irclid","_kx"],Tp=["utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid",...vs],on="",Np=["li_fat_id"];function Ou(t,e,s){if(!C)return{};var n,r=e?[...vs,...s||[]]:[],i=Du(rn(C.URL,r,on),t),o=(n={},Z(Np,(function(a){var l=wu(a);n[a]=l||null})),n);return ee(o,i)}function Du(t,e){var s=Tp.concat(e||[]),n={};return Z(s,(function(r){var i=ms(t,r);n[r]=i||null})),n}function Bu(t){var e=(function(i){return i?i.search(In+"google.([^/?]*)")===0?"google":i.search(In+"bing.com")===0?"bing":i.search(In+"yahoo.com")===0?"yahoo":i.search(In+"duckduckgo.com")===0?"duckduckgo":null:null})(t),s=e!="yahoo"?"q":"p",n={};if(!$e(e)){n.$search_engine=e;var r=C?ms(C.referrer,s):"";r.length&&(n.ph_keyword=r)}return n}function _l(){return navigator.language||navigator.userLanguage}var hr="$direct";function ju(){return C?.referrer||hr}function Uu(t,e,s){s===void 0&&(s=!1);var n=t?[...vs,...e||[]]:[],r=s?Ct(ne?.href):ne?.href,i=r?.substring(0,1e3);return{r:ju().substring(0,1e3),u:i?rn(i,n,on):void 0}}function Hu(t,e){var s;e===void 0&&(e=!1);var n=t.r,r=t.u,i=e?Ct(r):r,o={$referrer:n,$referring_domain:n==null?void 0:n==hr?hr:(s=ur(n))==null?void 0:s.host};if(i){o.$current_url=i;var a=ur(i);o.$host=a?.host,o.$pathname=a?.pathname;var l=Du(i);ee(o,l)}if(n){var u=Bu(n);ee(o,u)}return o}function Wu(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return}}function Mp(){try{return new Date().getTimezoneOffset()}catch{return}}var Lp={flags:Gs,surveys:nr},Op=["cookie","localstorage","localstorage+cookie","sessionstorage","memory"],ts="main";class pi{constructor(e,s,n){if(n===void 0&&(n=!0),this.ci={},this.fi=!1,this.pi=!1,this.Ne=e,this.gi=n,this.props={},this.mi=void 0,this.yi=(i=>{var o="";return i.token&&(o=i.token.replace(/\+/g,"PL").replace(/\//g,"SL").replace(/=/g,"EQ")),i.persistence_name?"ph_"+i.persistence_name:"ph_"+o+"_posthog"})(e),this.ii=this.bi(e),this.pi=this.wi(e),this.load(),e.debug&&k.info("Persistence loaded",e.persistence,b({},this.props)),this.update_config(e,e,s),this.save(),v){var r=()=>this.flush();re(v,"beforeunload",r,{capture:!1}),re(v,"pagehide",r,{capture:!1})}}ki(){var e,s=(e=this.Ne)==null?void 0:e.persistence_save_debounce_ms;return he(s)&&s>0?s:0}isDisabled(){return!!this.xi}bi(e){Op.indexOf(e.persistence.toLowerCase())===-1&&(k.critical("Unknown persistence type "+e.persistence+"; falling back to localStorage+cookie"),e.persistence="localStorage+cookie");var s,n=(function(o,a){o===void 0&&(o=[]),a===void 0&&(a=!1);var l=[...gp,...o];return b({},Q,{H(u){try{var c={};try{c=pt.H(u)||{}}catch{}var d,h=JSON.parse(Q.P(u)||"{}");if(a){var p={};for(var f in c){var g=c[f];$e(g)||g===""||(p[f]=g)}d=ee(h,p)}else d=ee(c,h);return Q.F(u,d),d}catch{}return null},F(u,c,d,h,p,f){var g=Q.F(u,c,void 0,void 0,f);try{var m={};l.forEach((_=>{c[_]&&(m[_]=c[_])})),Object.keys(m).length&&pt.F(u,m,d,h,p,f)}catch(_){Q.j(_)}return g},q(u,c){try{v?.localStorage.removeItem(u),pt.q(u,c)}catch(d){Q.j(d)}}})})(e.cookie_persisted_properties||[],e.__preview_cookie_wins_on_conflict||!1),r=!1,i=e.persistence.toLowerCase();return i==="localstorage"&&Q.N()?(s=Q,r=!0):i==="localstorage+cookie"&&n.N()?(s=n,r=!0):i==="sessionstorage"&&ce.N()?s=ce:i==="memory"?s=mp:i==="cookie"?s=pt:n.N()?(s=n,r=!0):s=pt,this.fi=r,s}Si(e){return this.yi+"__"+e}wi(e){return this.fi&&!!e.split_storage}properties(){var e={};return Z(this.props,((s,n)=>{var r=Mt(n);if(!r||r.exposure==="event"){if(r!=null&&r.shouldSkipFromEventProperties!=null&&r.shouldSkipFromEventProperties(s))return;e[n]=s}})),e}load(){if(!this.xi){var e=this.ii.H(this.yi);e&&(this.props=ee({},e)),this.pi&&this.Ci()}}Ci(){for(var e of hi){var s=Q.H(this.Si(e));if(s&&!mt(s)){var n=this.Mi(e);n.persisted=!0,this.Ti(e)||(n.fingerprint=this.Ei(s,e)),this.Ii(e,s)||ee(this.props,s)}}}Ti(e){return Object.keys(this.props).some((s=>{var n;return((n=Mt(s))==null?void 0:n.storageGroup)===e}))}Ii(e,s){var n=Lp[e];if(!n)return!1;var r=s[n],i=this.props[n];return he(r)&&he(i)&&i>r}refreshKey(e){var s;if(!this.xi){var n=this.pi?(s=Mt(e))==null?void 0:s.storageGroup:void 0,r=n?Q.H(this.Si(n)):this.ii.H(this.yi);if(r&&e in r)this.Pi(e,r[e]);else{if(n){var i=this.ii.H(this.yi);if(i&&e in i)return void this.Pi(e,i[e])}this.Ri(e)}}}save(){if(!this.xi){var e=this.ki();e>0?x(this.Ai)&&(this.Ai=setTimeout((()=>{this.Ai=void 0,this.Fi()}),e)):this.Fi()}}flush(){x(this.Ai)||(clearTimeout(this.Ai),this.Ai=void 0,this.Fi())}Fi(){this.xi||(this.pi?this.Li():this.Oi(this.ii,this.yi,this.props,ts))}Li(){var e=this.Di(),s=e.main,n=e.groups;for(var r of(this.Oi(this.ii,this.yi,s,ts),hi)){var i,o=n[r];(!mt(o)||(i=this.ci[r])!=null&&i.persisted)&&this.Oi(Q,this.Si(r),o,r)}}Di(){var e={},s={flags:{},surveys:{}};return Z(this.props,((n,r)=>{var i,o=(i=Mt(r))==null?void 0:i.storageGroup;o?s[o][r]=n:e[r]=n})),{main:e,groups:s}}Ei(e,s){if(s===ts)return JSON.stringify(e)+"|"+this.$i+"|"+this.Ni+"|"+this.qi;var n={};return Z(e,((r,i)=>{var o;n[i]=(o=Mt(i))!=null&&o.volatile?"__volatile__":r})),JSON.stringify(n)}Oi(e,s,n,r){var i=this.Mi(r);if(r===ts||i.dirty||x(i.fingerprint)){var o;try{if((o=this.Ei(n,r))===i.fingerprint)return void(i.dirty=!1)}catch{o=void 0}e.F(s,n,this.$i,this.Ni,this.qi,this.Ne.debug)?(i.dirty=!1,r!==ts&&(i.persisted=!0),x(o)||(i.fingerprint=o)):this.Ne.debug&&k.warn('failed to persist storage entry "'+s+'"; will retry on next save')}}remove(e){var s=(e===void 0?{}:e).keepGroupEntries,n=s!==void 0&&s;if(x(this.Ai)||(clearTimeout(this.Ai),this.Ai=void 0),this.ii.q(this.yi,!1),this.ii.q(this.yi,!0),!n&&this.gi)for(var r of hi)Q.q(this.Si(r));n?delete this.ci[ts]:this.ci={}}clear(){this.remove(),this.props={}}register_once(e,s,n){if(te(e)){x(s)&&(s="None"),this.$i=x(n)?this.ji:n;var r=!1;if(Z(e,((i,o)=>{this.props.hasOwnProperty(o)&&this.props[o]!==s||(this.Pi(o,i),r=!0)})),r)return this.save(),!0}return!1}register(e,s){if(te(e)){this.$i=x(s)?this.ji:s;var n=!1;if(Z(e,((r,i)=>{e.hasOwnProperty(i)&&(this.props[i]!==r||te(r)||L(r))&&(this.Pi(i,r),n=!0)})),n)return this.save(),!0}return!1}unregister(e){var s=typeof e=="string"?[e]:e,n=!1;for(var r of s)r in this.props&&(this.Ri(r),n=!0);n&&this.save()}update_campaign_params(){var e=C?.URL;if(e!==this.mi){var s=Ou(this.Ne.custom_campaign_params,this.Ne.mask_personal_data_properties,this.Ne.custom_personal_data_properties);mt(Jo(s))||this.register(s),this.mi=e}}update_search_keyword(){var e;this.register((e=C?.referrer)?Bu(e):{})}update_referrer_info(){var e;this.register_once({$referrer:ju(),$referring_domain:C!=null&&C.referrer&&((e=ur(C.referrer))==null?void 0:e.host)||hr},void 0)}set_initial_person_info(){this.props[so]||this.props[no]||this.register_once({[rr]:Uu(this.Ne.mask_personal_data_properties,this.Ne.custom_personal_data_properties,this.Ne.disable_capture_url_hashes)},void 0)}get_initial_props(){var e={};Z([no,so],(r=>{var i=this.props[r];i&&Z(i,(function(o,a){e["$initial_"+Oi(a)]=o}))}));var s=this.props[rr];if(s){var n=(function(r,i){i===void 0&&(i=!1);var o=Hu(r,i),a={};return Z(o,(function(l,u){a["$initial_"+Oi(u)]=l})),a})(s,this.Ne.disable_capture_url_hashes);ee(e,n)}return e}safe_merge(e){return Z(this.props,(function(s,n){n in e||(e[n]=s)})),e}update_config(e,s,n){this.ji=this.$i=e.cookie_expiration,this.set_disabled(e.disable_persistence||!!n),this.set_cross_subdomain(e.cross_subdomain_cookie),this.set_secure(e.secure_cookie);var r=e.persistence!==s.persistence||!((l,u)=>{if(l.length!==u.length)return!1;var c=[...l].sort(),d=[...u].sort();return c.every(((h,p)=>h===d[p]))})(e.cookie_persisted_properties||[],s.cookie_persisted_properties||[]),i=r?this.bi(e):this.ii,o=this.wi(e);if(r||o!==this.pi){var a=this.props;this.clear(),this.ii=i,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,s){var n=this.props[js]||{};n[e]=s,this.Pi(js,n),this.save()}remove_event_timer(e){var s=this.props[js]||{},n=s[e];return x(n)||(delete s[e],this.Pi(js,s),this.save()),n}get_property(e){return this.props[e]}set_property(e,s){this.Pi(e,s),this.save()}Pi(e,s){var n;this.props[e]=s,(n=Mt(e))!=null&&n.volatile||this.Bi(e)}Ri(e){delete this.props[e],this.Bi(e)}Bi(e){var s,n=(s=Mt(e))==null?void 0:s.storageGroup;n&&(this.Mi(n).dirty=!0)}Mi(e){return this.ci[e]||(this.ci[e]={})}}function Cn(t){var e=!0;return{dispose(){if(e){e=!1;var s=t();s&&Se(s.then)&&s.then(void 0,(()=>{}))}}}}var xe={GZipJS:"gzip-js",Base64:"base64"},As={Activation:"events",Cancellation:"cancelEvents"},fi={Popover:"popover",API:"api",Widget:"widget"},ft={SHOWN:"survey shown",DISMISSED:"survey dismissed",SENT:"survey sent"},gi={SURVEY_ID:"$survey_id",SURVEY_ITERATION:"$survey_iteration",SURVEY_LAST_SEEN_DATE:"$survey_last_seen_date"},lo={Popover:"popover",Inline:"inline"},Dp={SHOWN:"product tour shown"},yl={TOUR_LAST_SEEN_DATE:"$product_tour_last_seen_date",TOUR_TYPE:"$product_tour_type"},wl=se("[RateLimiter]");class Bp{constructor(e){this.serverLimits={},this.lastEventRateLimited=!1,this.checkForLimiting=s=>{var n=s.text;if(n&&n.length)try{(JSON.parse(n).quota_limited||[]).forEach((r=>{wl.info((r||"events")+" is quota limited."),this.serverLimits[r]=new Date().getTime()+6e4}))}catch(r){return void wl.warn('could not rate limit - continuing. Error: "'+r?.message+'"',{text:n})}},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 s,n,r;e===void 0&&(e=!1);var i=this.captureEventsBurstLimit,o=this.captureEventsPerSecond,a=new Date().getTime(),l=(s=(n=this.instance.persistence)==null?void 0:n.get_property(to))!==null&&s!==void 0?s:{tokens:i,last:a};l.tokens+=(a-l.last)/1e3*o,l.last=a,l.tokens>i&&(l.tokens=i);var u=1>l.tokens;if(u||e||(l.tokens=Math.max(0,l.tokens-1)),u&&!e){var c=(he(l.dropped)?l.dropped:0)+1;l.dropped=c,!this.lastEventRateLimited&&this.Hi(c)&&(l.dropped=0)}return this.lastEventRateLimited=u,(r=this.instance.persistence)==null||r.set_property(to,l),{isRateLimited:u,remainingTokens:l.tokens}}Ui(e){var s=this.instance.config.property_denylist;return!L(s)||!s.includes(e)}zi(){var e;if(this.Ui("$current_url")&&this.Ui("$pathname")&&ne!=null&&ne.pathname)return""+((e=ne.origin)!==null&&e!==void 0?e:"")+ne.pathname}Hi(e){var s,n,r=this.captureEventsBurstLimit,i=this.captureEventsPerSecond,o=this.zi(),a=this.Ui("$session_id")?(s=(n=this.instance).get_session_id)==null?void 0:s.call(n):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 "+i+" events per second and "+r+" events burst limit."},{skip_client_rate_limiting:!0})}isServerRateLimited(e){var s=this.serverLimits[e||"events"]||!1;return s!==!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 xt.info("Using preloaded remote config",this.remoteConfig),this.Zi(this.remoteConfig),void this.Gi();if(this._instance.Qi())return void xt.warn("Remote config is disabled. Falling back to local config.");this.Wi((e=>{if(!e)return xt.info("No config found after loading remote JS config. Falling back to JSON."),void this.Vi((s=>{this.Zi(s.json,s),this.Gi()}));this.Zi(e),this.Gi()}))}catch(e){xt.error("Error loading remote config",e),this.Zi()}}stop(){this.Ki&&(clearInterval(this.Ki),this.Ki=void 0)}refresh(){!this._instance.Qi()&&C&&C.visibilityState!=="hidden"&&this._instance.reloadFeatureFlags()}Gi(){var e;if(!this.Ki){var s=(e=this._instance.config.remote_config_refresh_interval_ms)!==null&&e!==void 0?e:3e5;s!==0&&(this.Ki=setInterval((()=>{this.refresh()}),s))}}Zi(e,s){!e&&s&&(s.statusCode===0?s.error||xt.warn("Failed to fetch remote config from PostHog."):xt.error("Failed to fetch remote config from PostHog."));try{this._instance.Zi(e?{ok:!0,config:e}:{ok:!1})}catch(r){xt.error("Error applying remote config",r)}if(e?.hasFeatureFlags!==!1&&!this._instance.config.advanced_disable_feature_flags_on_first_load)try{var n;(n=this._instance.featureFlags)==null||n.ensureFlagsLoaded()}catch(r){xt.error("Error loading feature flags",r)}}}var qe=Uint8Array,Ae=Uint16Array,_s=Uint32Array,Qo=new qe([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),ea=new qe([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),bl=new qe([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),qu=function(t,e){for(var s=new Ae(31),n=0;31>n;++n)s[n]=e+=1<n;++n)for(var i=s[n];s[n+1]>i;++i)r[i]=i-s[n]<<5|n;return[s,r]},Vu=qu(Qo,2),co=Vu[1];Vu[0][28]=258,co[258]=28;for(var El=qu(ea,0)[1],Gu=new Ae(32768),ie=0;32768>ie;++ie){var ss=(43690&ie)>>>1|(21845&ie)<<1;Gu[ie]=((65280&(ss=(61680&(ss=(52428&ss)>>>2|(13107&ss)<<2))>>>4|(3855&ss)<<4))>>>8|(255&ss)<<8)>>>1}var Js=function(t,e,s){for(var n=t.length,r=0,i=new Ae(e);n>r;++r)++i[t[r]-1];var o,a=new Ae(e);for(r=0;e>r;++r)a[r]=a[r-1]+i[r-1]<<1;for(o=new Ae(n),r=0;n>r;++r)o[r]=Gu[a[t[r]-1]++]>>>15-t[r];return o},Kt=new qe(288);for(ie=0;144>ie;++ie)Kt[ie]=8;for(ie=144;256>ie;++ie)Kt[ie]=9;for(ie=256;280>ie;++ie)Kt[ie]=7;for(ie=280;288>ie;++ie)Kt[ie]=8;var pr=new qe(32);for(ie=0;32>ie;++ie)pr[ie]=5;var jp=Js(Kt,9),Up=Js(pr,5),Ku=function(t){return(t/8>>0)+(7&t&&1)},Ju=function(t,e,s){(s==null||s>t.length)&&(s=t.length);var n=new(t instanceof Ae?Ae:t instanceof _s?_s:qe)(s-e);return n.set(t.subarray(e,s)),n},ot=function(t,e,s){var n=e/8>>0;t[n]|=s<<=7&e,t[n+1]|=s>>>8},$s=function(t,e,s){var n=e/8>>0;t[n]|=s<<=7&e,t[n+1]|=s>>>8,t[n+2]|=s>>>16},mi=function(t,e){for(var s=[],n=0;t.length>n;++n)t[n]&&s.push({s:n,f:t[n]});var r=s.length,i=s.slice();if(!r)return[new qe(0),0];if(r==1){var o=new qe(s[0].s+1);return o[s[0].s]=1,[o,1]}s.sort((function(F,P){return F.f-P.f})),s.push({s:-1,f:25001});var a=s[0],l=s[1],u=0,c=1,d=2;for(s[0]={s:-1,f:a.f+l.f,l:a,r:l};c!=r-1;)a=s[s[d].f>s[u].f?u++:d++],l=s[u!=c&&s[d].f>s[u].f?u++:d++],s[c++]={s:-1,f:a.f+l.f,l:a,r:l};var h=i[0].s;for(n=1;r>n;++n)i[n].s>h&&(h=i[n].s);var p=new Ae(h+1),f=uo(s[c-1],p,0);if(f>e){n=0;var g=0,m=f-e,_=1<n;++n){var w=i[n].s;if(e>=p[w])break;g+=_-(1<>>=m;g>0;){var E=i[n].s;e>p[E]?g-=1<=0&&g;--n){var I=i[n].s;p[I]==e&&(--p[I],++g)}f=e}return[new qe(p),f]},uo=function(t,e,s){return t.s==-1?Math.max(uo(t.l,e,s+1),uo(t.r,e,s+1)):e[t.s]=s},Sl=function(t){for(var e=t.length;e&&!t[--e];);for(var s=new Ae(++e),n=0,r=t[0],i=1,o=function(l){s[n++]=l},a=1;e>=a;++a)if(t[a]==r&&a!=e)++i;else{if(!r&&i>2){for(;i>138;i-=138)o(32754);i>2&&(o(i>10?i-11<<5|28690:i-3<<5|12305),i=0)}else if(i>3){for(o(r),--i;i>6;i-=6)o(8304);i>2&&(o(i-3<<5|8208),i=0)}for(;i--;)o(r);i=1,r=t[a]}return[s.subarray(0,n),e]},Rs=function(t,e){for(var s=0,n=0;e.length>n;++n)s+=t[n]*e[n];return s},ho=function(t,e,s){var n=s.length,r=Ku(e+2);t[r]=255&n,t[r+1]=n>>>8,t[r+2]=255^t[r],t[r+3]=255^t[r+1];for(var i=0;n>i;++i)t[r+i+4]=s[i];return 8*(r+4+n)},xl=function(t,e,s,n,r,i,o,a,l,u,c){ot(e,c++,s),++r[256];for(var d=mi(r,15),h=d[0],p=d[1],f=mi(i,15),g=f[0],m=f[1],_=Sl(h),w=_[0],E=_[1],I=Sl(g),F=I[0],P=I[1],B=new Ae(19),S=0;w.length>S;++S)B[31&w[S]]++;for(S=0;F.length>S;++S)B[31&F[S]]++;for(var A=mi(B,7),R=A[0],N=A[1],T=19;T>4&&!R[bl[T-1]];--T);var O,J,z,H,oe=u+5<<3,pe=Rs(r,Kt)+Rs(i,pr)+o,Ie=Rs(r,h)+Rs(i,g)+o+14+3*T+Rs(B,R)+(2*B[16]+3*B[17]+7*B[18]);if(pe>=oe&&Ie>=oe)return ho(e,c,t.subarray(l,l+u));if(ot(e,c,1+(pe>Ie)),c+=2,pe>Ie){O=Js(h,p),J=h,z=Js(g,m),H=g;var _e=Js(R,N);for(ot(e,c,E-257),ot(e,c+5,P-1),ot(e,c+10,T-4),c+=14,S=0;T>S;++S)ot(e,c+3*S,R[bl[S]]);c+=3*T;for(var Ce=[w,F],Re=0;2>Re;++Re){var ae=Ce[Re];for(S=0;ae.length>S;++S)ot(e,c,_e[me=31&ae[S]]),c+=R[me],me>15&&(ot(e,c,ae[S]>>>5&127),c+=ae[S]>>>12)}}else O=jp,J=Kt,z=Up,H=pr;for(S=0;a>S;++S)if(n[S]>255){var me;$s(e,c,O[257+(me=n[S]>>>18&31)]),c+=J[me+257],me>7&&(ot(e,c,n[S]>>>23&31),c+=Qo[me]);var ge=31&n[S];$s(e,c,z[ge]),c+=H[ge],ge>3&&($s(e,c,n[S]>>>5&8191),c+=ea[ge])}else $s(e,c,O[n[S]]),c+=J[n[S]];return $s(e,c,O[256]),c+J[256]},Hp=new _s([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),Wp=(function(){for(var t=new _s(256),e=0;256>e;++e){for(var s=e,n=9;--n;)s=(1&s&&3988292384)^s>>>1;t[e]=s}return t})(),vi=function(t,e,s){for(;s;++e)t[e]=s,s>>>=8};function zp(t,e){e===void 0&&(e={});var s=(function(){var d=4294967295;return{p(h){for(var p=d,f=0;h.length>f;++f)p=Wp[255&p^h[f]]^p>>>8;d=p},d(){return 4294967295^d}}})(),n=t.length;s.p(t);var r,i,o,a,l,u=(a=10+((r=e).filename&&r.filename.length+1||0),l=8,(function(d,h,p,f,g,m){var _=d.length,w=new qe(f+_+5*(1+Math.floor(_/7e3))+g),E=w.subarray(f,w.length-g),I=0;if(!h||8>_)for(var F=0;_>=F;F+=65535){var P=F+65535;_>P?I=ho(E,I,d.subarray(F,P)):(E[F]=!0,I=ho(E,I,d.subarray(F,_)))}else{for(var B=Hp[h-1],S=B>>>13,A=8191&B,R=(1<F;++F){var me=z(F),ge=32767&F,Ye=T[me];if(N[ge]=Ye,T[me]=ge,F>=Re){var Rt=_-F;if((Ie>7e3||Ce>24576)&&Rt>423){I=xl(d,E,0,H,oe,pe,_e,Ce,ae,F-ae,I),Ce=Ie=_e=0,ae=F;for(var de=0;286>de;++de)oe[de]=0;for(de=0;30>de;++de)pe[de]=0}var Ve=2,St=0,ks=A,Be=ge-Ye&32767;if(Rt>2&&me==z(F-Be))for(var Fe=Math.min(S,Rt)-1,vn=Math.min(32767,F),_n=Math.min(258,Rt);vn>=Be&&--ks&&ge!=Ye;){if(d[F+Ve]==d[F+Ve-Be]){for(var je=0;_n>je&&d[F+je]==d[F+je-Be];++je);if(je>Ve){if(Ve=je,St=Be,je>Fe)break;var yn=Math.min(Be,je-2),Xt=0;for(de=0;yn>de;++de){var Qt=F-Be+de+32768&32767,Is=Qt-N[Qt]+32768&32767;Is>Xt&&(Xt=Is,Ye=Qt)}}}Be+=(ge=Ye)-(Ye=N[ge])+32768&32767}if(St){H[Ce++]=268435456|co[Ve]<<18|El[St];var La=31&co[Ve],Oa=31&El[St];_e+=Qo[La]+ea[Oa],++oe[257+La],++pe[Oa],Re=F+Ve,++Ie}else H[Ce++]=d[F],++oe[d[F]]}}I=xl(d,E,!0,H,oe,pe,_e,Ce,ae,F-ae,I)}return Ju(w,0,f+Ku(I)+g)})(i=t,(o=e).level==null?6:o.level,o.mem==null?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(i.length)))):12+o.mem,a,l)),c=u.length;return(function(d,h){var p=h.filename;if(d[0]=31,d[1]=139,d[2]=8,d[8]=2>h.level?4:h.level==9?2:0,d[9]=3,h.mtime!=0&&vi(d,4,Math.floor(new Date(h.mtime||Date.now())/1e3)),p){d[3]=8;for(var f=0;p.length>=f;++f)d[f+10]=p.charCodeAt(f)}})(u,e),vi(u,c-8,s.d()),vi(u,c-4,n),u}var qp=!!Ni||!!Do,Yu="text/plain",Bn=!1,Zu=(t,e)=>{var s=t.split("#"),n=s[1],r=s[0].split("?"),i=r[0],o=r[1];if(!o)return t;var a=o.split("&").filter((l=>l.split("=")[0]!==e)).join("&");return i+(a?"?"+a:"")+(n?"#"+n:"")},Rr=function(t,e,s){var n;s===void 0&&(s=!0);var r=t.split("?"),i=r[0],o=r[1],a=b({},e),l=(n=o?.split("&").map((c=>{var d,h=c.split("="),p=h[0],f=s&&(d=a[p])!==null&&d!==void 0?d:h[1];return delete a[p],p+"="+f})))!==null&&n!==void 0?n:[],u=(function(c,d){var h,p;d===void 0&&(d="&");var f=[];return Z(c,(function(g,m){x(g)||x(m)||m==="undefined"||(h=encodeURIComponent((_=>_ instanceof File)(g)?g.name:g.toString()),p=encodeURIComponent(m),f[f.length]=p+"="+h)})),f.join(d)})(a);return u&&l.push(u),l.length>0?i+"?"+l.join("&"):i},_i=t=>{if(t.Ji)return t.Ji;var e=t.data,s=t.compression;if(e){if(s===xe.GZipJS){var n=zp((function(a,l){var u=a.length;if(typeof TextEncoder<"u")return new TextEncoder().encode(a);for(var c=new qe(a.length+(a.length>>>1)),d=0,h=function(m){c[d++]=m},p=0;u>p;++p){if(d+5>c.length){var f=new qe(d+8+(u-p<<1));f.set(c),c=f}var g=a.charCodeAt(p);128>g?h(g):2048>g?(h(192|g>>>6),h(128|63&g)):g>55295&&57344>g?(h(240|(g=65536+(1047552&g)|1023&a.charCodeAt(++p))>>>18),h(128|g>>>12&63),h(128|g>>>6&63),h(128|63&g)):(h(224|g>>>12),h(128|g>>>6&63),h(128|63&g))}return Ju(c,0,d)})(cs(e)),{mtime:0});return{contentType:Yu,body:n.buffer.slice(n.byteOffset,n.byteOffset+n.byteLength),estimatedSize:n.byteLength}}if(s===xe.Base64){var r=(function(a){return a&&btoa(encodeURIComponent(a).replace(/%([0-9A-F]{2})/g,((l,u)=>String.fromCharCode(parseInt(u,16)))))})(cs(e)),i=(a=>"data="+encodeURIComponent(typeof a=="string"?a:cs(a)))(r);return{contentType:"application/x-www-form-urlencoded",body:i,estimatedSize:new Blob([i]).size}}var o=cs(e);return{contentType:"application/json",body:o,estimatedSize:new Blob([o]).size}}},Xu=t=>{var e,s,n=()=>t.transport==="sendBeacon"?{url:Rr(t.url,{compression:xe.Base64}),encodedBody:_i(b({},t,{compression:xe.Base64,Ji:void 0}))}:{url:Zu(t.url,"compression"),encodedBody:_i(b({},t,{compression:void 0,Ji:void 0}))};try{e=_i(t)}catch(r){if(za(t.compression,ms(t.url,"compression")))return k.error("Failed to gzip request body, sending uncompressed payload",r),n();throw r}return e&&za(t.compression,ms(t.url,"compression"))&&!((s=e.body)instanceof ArrayBuffer?Mi(new Uint8Array(s)):ArrayBuffer.isView(s)&&Mi(new Uint8Array(s.buffer,s.byteOffset,s.byteLength)))?(Bn=!0,n()):{url:t.url,encodedBody:e}},Qu=t=>{try{return Xu(t)}catch(e){return k.error(e),void(t.callback==null||t.callback({statusCode:0,error:e}))}},Vp=(function(){var t=X((function*(e){var s=cs(e.data),n=yield(function(i,o,a){return Li.apply(this,arguments)})(s,Y.DEBUG,{rethrow:!0});if(!n)return e;var r=yield n.arrayBuffer();return b({},e,{Ji:{contentType:Yu,body:r,estimatedSize:r.byteLength}})}));return function(e){return t.apply(this,arguments)}})(),Gp=/Failed to fetch|NetworkError|Load failed/i,ed=t=>t?.name==="TypeError"&&Gp.test(t?.message||""),td=t=>{var e=Qu(t);if(e){var s=e.url,n=e.encodedBody,r=n??{},i=r.contentType,o=r.body,a=r.estimatedSize,l=new Headers;Z(t.headers,(function(f,g){l.append(g,f)})),i&&l.append("Content-Type",i);var u=null,c=!1;if(Da){var d=new Da;u={signal:d.signal,timeout:setTimeout((()=>{var f,g;c=!0,d.abort((f=t.timeout,(g=new Error("PostHog request timed out"+(f?" after "+f+"ms":""))).name="AbortError",g))}),t.timeout)}}var h=f=>{c&&f?.name==="AbortError"||ed(f)?k.warn(f):k.error(f),t.callback==null||t.callback({statusCode:0,error:f})};try{var p;Do(s,b({method:t?.method||"GET",headers:l,keepalive:t.method==="POST"&&!t.Yi&&52428.8>(a||0),body:o,signal:(p=u)==null?void 0:p.signal},t.fetchOptions)).then((f=>f.text().then((g=>{var m={statusCode:f.status,text:g};if(f.status===200)try{m.json=JSON.parse(g)}catch(_){k.error(_)}t.callback==null||t.callback(m)})))).catch(h).finally((()=>u?clearTimeout(u.timeout):null))}catch(f){u&&clearTimeout(u.timeout),h(f)}}},po=t=>{try{var e,s=Xu(t),n=s.url,r=s.encodedBody,i=r??{},o=i.body,a=i.estimatedSize;if(!o)return;var l=o instanceof Blob?o:new Blob([o],{type:i.contentType});if(ke.sendBeacon(n,l))return;var u=L(t.data)?t.data:(e=t.data)==null?void 0:e.batch;if(L(u)&&u.length>1&&(a??0)>16384){var c=Math.ceil(u.length/2),d=h=>L(t.data)?h:b({},t.data,{batch:h});return po(b({},t,{data:d(u.slice(0,c))})),void po(b({},t,{data:d(u.slice(c))}))}k.warn("Beacon of ~"+(a??0)+" bytes was rejected by the browser, falling back to fetch"),td(b({},t,{Yi:!0}))}catch(h){k.warn("Beacon send failed",h)}},kl=(t,e,s,n)=>{var r=n==="query"?e==="POST"?"sent_at":"_":void 0;return Rr(s===xe.GZipJS?Zu(t,"compression"):t,b({},r?{[r]:Date.now().toString()}:{},s===xe.GZipJS?{}:{compression:s}))},jn=[];Do&&jn.push({transport:"fetch",method:td}),Ni&&jn.push({transport:"XHR",method(t){var e=Qu(t);if(e){var s=new Ni,n=e.encodedBody;s.open(t.method||"GET",e.url,!0);var r=n??{},i=r.contentType,o=r.body;Z(t.headers,(function(a,l){s.setRequestHeader(l,a)})),i&&s.setRequestHeader("Content-Type",i),t.timeout&&(s.timeout=t.timeout),s.onreadystatechange=()=>{if(s.readyState===4){var a={statusCode:s.status,text:s.responseText};if(s.status===200)try{a.json=JSON.parse(s.responseText)}catch{}t.callback==null||t.callback(a)}},s.send(o)}}}),ke!=null&&ke.sendBeacon&&jn.push({transport:"sendBeacon",method:po});var fo=3e3;class Kp{constructor(e,s){this.Xi=!0,this.tr=[],this.er=nt(s?.flush_interval_ms||fo,250,5e3,k.createLogger("flush interval"),fo),this.ir=e}enqueue(e){this.tr.push(e),this.rr||this.nr()}unload(){this.sr();var e=this.tr.length>0?this.ar():{},s=Object.values(e);[...s.filter((n=>n.url.indexOf("/e")===0)),...s.filter((n=>n.url.indexOf("/e")!==0))].map((n=>{this.lr(b({},n,{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 s=this.ar(),n=function(){var i=s[r],o=new Date().getTime();i.data&&L(i.data)&&Z(i.data,(a=>{a.offset=Math.abs(a.timestamp-o),delete a.timestamp})),e.lr(i)};for(var r in s)n()}}),this.er))}lr(e){try{this.ir(e)}catch(s){k.error(s)}}sr(){clearTimeout(this.rr),this.rr=void 0}ar(){var e={};return Z(this.tr,(s=>{var n,r=s,i=(r?r.batchKey:null)||r.url;x(e[i])&&(e[i]=b({},r,{data:[]})),(n=e[i].data)==null||n.push(r.data)})),this.tr=[],e}}var Jp=["retriesPerformedSoFar"];class Yp{constructor(e){this.ur=!1,this.hr=3e3,this.tr=[],this._instance=e,this.tr=[],this.dr=!0,!x(v)&&"onLine"in v.navigator&&(this.dr=v.navigator.onLine,this.vr=()=>{this.dr=!0,this.cr()},this.pr=()=>{this.dr=!1},re(v,"online",this.vr),re(v,"offline",this.pr))}get length(){return this.tr.length}retriableRequest(e){var s=e.retriesPerformedSoFar,n=Pc(e,Jp);lt(s)&&(n.url=Rr(n.url,{retry_count:s})),this._instance._send_request(b({},n,{callback:r=>{if(r.statusCode!==200&&(400>r.statusCode||r.statusCode>=500)){if((r.statusCode===0?3:10)>(s??0))return void this.At(b({retriesPerformedSoFar:s},n));r.statusCode===0&&k.warn("Request failed before receiving an HTTP response; this can happen due to network issues, CORS, browser blocking, or ad blockers. Stopped retrying after "+(s??0)+" retries.")}n.callback==null||n.callback(r)}}))}At(e){var s=e.retriesPerformedSoFar||0;e.retriesPerformedSoFar=s+1;var n=(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))})(s),r=Date.now()+n;this.tr.push({retryAt:r,requestOptions:e});var i="Enqueued failed request for retry in "+n;navigator.onLine||(i+=" (Browser is offline)"),k.warn(i),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(),s=[],n=this.tr.filter((i=>e>i.retryAt||(s.push(i),!1)));if(this.tr=s,n.length>0)for(var r of n)this.retriableRequest(r.requestOptions)}unload(){for(var e of(this.mr&&(clearTimeout(this.mr),this.mr=void 0),this.ur=!1,x(v)||(this.vr&&(v.removeEventListener("online",this.vr),this.vr=void 0),this.pr&&(v.removeEventListener("offline",this.pr),this.pr=void 0)),this.tr)){var s=e.requestOptions;try{this._instance._send_request(b({},s,{transport:"sendBeacon"}))}catch(n){k.error(n)}}this.tr=[]}}class Zp{constructor(e){this.yr=()=>{var s,n,r,i;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,(s=this.br.maxScrollY)!==null&&s!==void 0?s:0),this.br.maxScrollHeight=Math.max(l,(n=this.br.maxScrollHeight)!==null&&n!==void 0?n: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,(i=this.br.maxContentHeight)!==null&&i!==void 0?i:0)},this._instance=e}get _r(){return this._instance.config.scroll_root_selector}getContext(){return this.br}resetContext(){var e=this.br;return setTimeout(this.yr,0),e}startMeasuringScrollPosition(){re(v,"scroll",this.yr,{capture:!0}),re(v,"scrollend",this.yr,{capture:!0}),re(v,"resize",this.yr)}scrollElement(){if(!this._r)return v?.document.documentElement;var e=L(this._r)?this._r:[this._r];for(var s of e){var n=v?.document.querySelector(s);if(n)return n}}wr(e){var s=e==="y"?"scrollTop":"scrollLeft";if(this._r){var n=this.scrollElement();return n&&n[s]||0}return v?e==="y"?v.scrollY||v.pageYOffset||v.document.documentElement.scrollTop||0:v.scrollX||v.pageXOffset||v.document.documentElement.scrollLeft||0:0}scrollY(){return this.wr("y")}scrollX(){return this.wr("x")}}var Xp=t=>Uu(t?.config.mask_personal_data_properties,t?.config.custom_personal_data_properties,t?.config.disable_capture_url_hashes);class Il{constructor(e,s,n,r){this.kr=i=>{var o=this.Sr();if(!o||o.sessionId!==i){var a={sessionId:i,props:this.Cr(this._instance)};this.Mr.register({[eo]:a})}},this._instance=e,this.Tr=s,this.Mr=n,this.Cr=r||Xp,this.Tr.onSessionId(this.kr)}Sr(){return this.Mr.props[eo]}getSetOnceProps(){var e,s=(e=this.Sr())==null?void 0:e.props;return s?"r"in s?Hu(s,this._instance.config.disable_capture_url_hashes):{$referring_domain:s.referringDomain,$pathname:s.initialPathName,utm_source:s.utm_source,utm_campaign:s.utm_campaign,utm_medium:s.utm_medium,utm_content:s.utm_content,utm_term:s.utm_term}:{}}getSessionProps(){var e={};return Z(Jo(this.getSetOnceProps()),((s,n)=>{n==="$current_url"&&(n="url"),e["$session_entry_"+Oi(n)]=s})),e}}class ta{on(e,s){return this.Er[e]||(this.Er[e]=[]),this.Er[e].push(s),()=>{this.Er[e]=this.Er[e].filter((n=>n!==s))}}emit(e,s){for(var n of this.Er[e]||[])n(s);for(var r of this.Er["*"]||[])r(e,s)}constructor(){this.Er={}}}var Ts=se("[SessionId]");class Cl{on(e,s){return this.Ir.on(e,s)}constructor(e,s,n){var r;if(this.Pr=null,this.Rr=[],this.Ar=void 0,this.Fr=!1,this.Ir=new ta,this.Lr=(u,c)=>!(!lt(u)||!lt(c))&&Math.abs(u-c)>this.sessionTimeoutMs,!e.persistence)throw new Error("SessionIdManager requires a PostHogPersistence instance");if(e.config.cookieless_mode===ht)throw new Error('SessionIdManager cannot be used with cookieless_mode="always"');this.Ne=e.config,this.Mr=e.persistence,this.Or=void 0,this.Dr=void 0,this._sessionStartTimestamp=null,this._sessionActivityTimestamp=null,this.$r=s||dt,this.Nr=n||dt;var i=this.Ne.persistence_name||this.Ne.token;if(this._sessionTimeoutMs=1e3*nt(this.Ne.session_idle_timeout_seconds||1800,60,36e3,Ts.createLogger("session_idle_timeout_seconds"),1800),e.register({$configured_session_timeout_ms:this._sessionTimeoutMs}),this.qr(),this.jr="ph_"+i+"_window_id",this.Br="ph_"+i+"_primary_window_exists",this.Hr()){var o=ce.H(this.jr),a=ce.H(this.Br);o&&!a?this.Or=o:ce.q(this.jr),ce.F(this.Br,!0)}if((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){Ts.error("Invalid sessionID in bootstrap",u)}this.zr()}get sessionTimeoutMs(){return this._sessionTimeoutMs}onSessionId(e){return x(this.Rr)&&(this.Rr=[]),this.Rr.push(e),this.Dr&&e(this.Dr,this.Or),()=>{this.Rr=this.Rr.filter((s=>s!==e))}}Hr(){return this.Ne.persistence!=="memory"&&!this.Mr.xi&&ce.N()}Wr(e){e!==this.Or&&(this.Or=e,this.Hr()&&ce.F(this.jr,e))}Vr(){return this.Or?this.Or:this.Hr()?ce.H(this.jr):null}Zr(e){var s=this.Pr;return!$e(s)&&!$e(e)&&5e3>Math.abs(e-s)}Ur(e,s,n){var r=s!==this._sessionActivityTimestamp,i=!(e!==this.Dr||n!==this._sessionStartTimestamp);this._sessionStartTimestamp=n,this._sessionActivityTimestamp=s,this.Dr=e,i&&!r||i&&this.Zr(s)||(this.Pr=s,this.Mr.register({[ls]:[s,e,n]}))}Gr(){var e,s=(e=this.Ne)==null?void 0:e.persistence_save_debounce_ms;return lt(s)&&s>0}Qr(){this.Gr()?this.Mr.refreshKey(ls):(this.Mr.flush(),this.Mr.load())}Kr(){var e;if(!$e(this._sessionActivityTimestamp)&&this._sessionActivityTimestamp!==this.Pr){this.Qr();var s=this.Jr();s[1]===this.Dr&&s[2]===this._sessionStartTimestamp&&(this.Pr=this._sessionActivityTimestamp,this.Mr.register({[ls]:[this._sessionActivityTimestamp,(e=this.Dr)!==null&&e!==void 0?e:null,this._sessionStartTimestamp]}),this.Mr.flush())}}Yr(){var e=this.Jr()[0],s=lt(e)?e:0,n=lt(this._sessionActivityTimestamp)?this._sessionActivityTimestamp:0;return Math.max(s,n)}Xr(e){return this.Qr(),this.Lr(e,this.Yr())}Jr(){var e=this.Mr.props[ls];return L(e)&&e.length===2&&e.push(e[0]),e||[0,null,0]}resetSessionId(){this.Pr=null,clearTimeout(this.tn),this.tn=void 0,this.Ur(null,null,null)}destroy(){this.Fr=!0,this.Kr(),clearTimeout(this.tn),this.tn=void 0,this.Ar&&v&&(v.removeEventListener(ar,this.Ar,{capture:!1}),this.Ar=void 0),this.Rr=[]}zr(){this.Ar=()=>{this.Kr(),this.Hr()&&ce.q(this.Br)},re(v,ar,this.Ar,{capture:!1})}checkAndGetSessionAndWindowId(e,s){if(e===void 0&&(e=!1),s===void 0&&(s=null),this.Ne.cookieless_mode===ht)throw new Error('checkAndGetSessionAndWindowId should not be called with cookieless_mode="always"');var n=s||new Date().getTime(),r=this.Jr(),i=r[1],o=r[2],a=this.Yr(),l=this.Vr(),u=lt(o)&&Math.abs(n-o)>864e5,c=!1,d=!1,h=!i,p=i,f=!h&&!e&&this.Lr(n,a);if(f){(f=this.Xr(n))||Ts.info("cross-tab refresh kept the session alive",{sessionId:i});var g=this.Jr();i=g[1],o=g[2]}h||f||u?(i=this.$r(),l=this.Nr(),Ts.info("new session ID generated",{sessionId:i,windowId:l,changeReason:{noSessionId:h,activityTimeout:f,sessionPastMaximumLength:u}}),o=n,c=!0):(l||(l=this.Nr(),c=!0),(d=i!==p)&&(Ts.info("adopted cross-tab session id",{sessionId:i,windowId:l}),c=!0));var m=lt(a)&&e&&!u?a:n,_=lt(o)?o:new Date().getTime();this.Wr(l),this.Ur(i,m,_),e||this.qr();var w={noSessionId:h,activityTimeout:f,sessionPastMaximumLength:u,crossTabAdoption:d};return c&&this.Rr.forEach((E=>E(i,l,w))),{sessionId:i,windowId:l,sessionStartTimestamp:_,changeReason:c?w:void 0,lastActivityTimestamp:a}}qr(){this.Fr||(clearTimeout(this.tn),this.tn=setTimeout((()=>{if(!this.Fr)if(this.Xr(new Date().getTime())){var e=this.Dr;this.resetSessionId(),this.Ir.emit("forcedIdleReset",{idleSessionId:e})}else this.qr()}),1.1*this.sessionTimeoutMs))}}var sd=function(t,e){if(!t)return!1;var s=t.userAgent;if(s&&Va(s,e))return!0;try{var n=t?.userAgentData;if(n!=null&&n.brands&&n.brands.some((r=>Va(r?.brand,e))))return!0}catch{}return!!t.webdriver};function nd(){return(nd=X((function*(){var t=ke?.userAgentData;if(t!=null&&t.getHighEntropyValues)try{var e=yield t.getHighEntropyValues(["model"]),s=e?.model;return W(s)&&s.length>0?s:void 0}catch(n){return void k.info("Unable to resolve $device_model from userAgentData.getHighEntropyValues",n)}}))).apply(this,arguments)}var fr=function(t,e){if(!(function(s){try{new RegExp(s)}catch{return!1}return!0})(e))return!1;try{return new RegExp(e).test(t)}catch{return!1}};function yi(t,e,s){return cs({distinct_id:t,userPropertiesToSet:e,userPropertiesToSetOnce:s})}var rd={exact:(t,e)=>e.some((s=>t.some((n=>s===n)))),is_not:(t,e)=>e.every((s=>t.every((n=>s!==n)))),regex:(t,e)=>e.some((s=>t.some((n=>fr(s,n))))),not_regex:(t,e)=>e.every((s=>t.every((n=>!fr(s,n))))),icontains:(t,e)=>e.map(Fn).some((s=>t.map(Fn).some((n=>s.includes(n))))),not_icontains:(t,e)=>e.map(Fn).every((s=>t.map(Fn).every((n=>!s.includes(n))))),gt:(t,e)=>e.some((s=>{var n=parseFloat(s);return!isNaN(n)&&t.some((r=>n>parseFloat(r)))})),lt:(t,e)=>e.some((s=>{var n=parseFloat(s);return!isNaN(n)&&t.some((r=>nt.toLowerCase();function id(t,e){return!t||Object.entries(t).every((s=>{var n=s[1],r=e?.[s[0]];if(x(r)||$e(r))return!1;var i=[String(r)],o=rd[n.operator];return!!o&&o(n.values,i)}))}var go="custom",Fl="i.posthog.com",Qp=/^\/static\//;class ef{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,s=(e=this.instance.config.ui_host)==null?void 0:e.replace(/\/$/,"");return s||(s=this.apiHost.replace("."+Fl,".posthog.com")),s==="https://app.posthog.com"?"https://us.posthog.com":s}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":go),this.en[this.apiHost]}rn(e){if(Qp.test(e)){var s=this.instance.config.asset_host;if(typeof s=="string")return s.trim().replace(/\/$/,"")||void 0}}endpointFor(e,s){if(s===void 0&&(s=""),s&&(s=s[0]==="/"?s:"/"+s),e==="ui")return this.uiHost+s;if(e==="flags")return this.flagsApiHost+s;if(e==="assets"){var n=this.rn(s);if(n)return""+n+s}if(this.region===go)return this.apiHost+s;var r=Fl+s;switch(e){case"assets":return"https://"+this.region+"-assets."+r;case"api":return"https://"+this.region+"."+r}}}function od(t){var e;return!((e=t.conditions)==null||(e=e.events)==null||(e=e.values)==null||!e.length)}var q=se("[Surveys]"),ad="seenSurvey_",ld=t=>{try{var e=(s=>((n,r)=>""+ad+(function(i){return i.current_iteration&&i.current_iteration>0?i.id+"_"+i.current_iteration:i.id})(r))(0,s))(t);if(localStorage.getItem(e))return;localStorage.setItem(e,"true")}catch(s){q.error("Failed to persist survey seen state",s)}},tf=[fi.Popover,fi.Widget,fi.API],sf={ignoreConditions:!1,ignoreDelay:!1,displayType:lo.Popover},nf=se("[PostHog ExternalIntegrations]"),rf={intercom:"intercom-integration",crispChat:"crisp-chat-integration"};class of{constructor(e){this._instance=e}ai(e,s){var n;(n=$.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,e,(r=>{if(r)return nf.error("failed to load script",r);s()}))}startIfEnabledOrStop(){var e=this,s=function(){var i,o,a,l=n[0],u=n[1];!u||(i=$.__PosthogExtensions__)!=null&&(i=i.integrations)!=null&&i[l]||e.ai(rf[l],(()=>{var c;(c=$.__PosthogExtensions__)==null||(c=c.integrations)==null||(c=c[l])==null||c.start(e._instance)})),!u&&(o=$.__PosthogExtensions__)!=null&&(o=o.integrations)!=null&&o[l]&&((a=$.__PosthogExtensions__)==null||(a=a.integrations)==null||(a=a[l])==null||a.stop())};for(var n of Object.entries((r=this._instance.config.integrations)!==null&&r!==void 0?r:{})){var r;s()}}}class af{constructor(e,s){this.rt=e,this.nn=s,this.sn=new Map,this.an=!1}add(e){var s=this;return X((function*(){if(s.an)throw new Error("Cannot add an extension to a disposed ExtensionRuntime");if(s.sn.has(e.name))throw new Error('Browser extension "'+e.name+'" is already registered');s.sn.set(e.name,e);try{var n=e.setup(s.nn);n&&(yield n)}catch(i){var r=s.sn.get(e.name)===e;r&&s.sn.delete(e.name),s.rt.error('Failed to set up browser extension "'+e.name+'"',i),r&&s.ln(e)}}))()}dispose(){if(!this.an){this.an=!0;var e=Array.from(this.sn.values()).reverse();for(var s of(this.sn.clear(),e))this.ln(s)}}ln(e){try{var s=e.dispose==null?void 0:e.dispose();s&&Se(s.then)&&s.then(void 0,(n=>{this.rt.error('Failed to dispose browser extension "'+e.name+'"',n)}))}catch(n){this.rt.error('Failed to dispose browser extension "'+e.name+'"',n)}}}class lf{constructor(e){this._instance=e}initialize(){}get(e){var s=this._instance.persistence;if(typeof e=="string")return s?.get_property(e);var n={};for(var r of e){var i=s?.get_property(r);x(i)||(n[r]=i)}return n}set(e,s){var n;(n=this._instance.persistence)==null||n.register(typeof e=="string"?{[e]:s}:e)}remove(e){var s;(s=this._instance.persistence)==null||s.unregister(e)}}var Pl="extensionsRemoteConfig";class cf{constructor(e){this.an=!1,this.instance=e,this.rt=k,this.un=e.hn,this.kv=new lf(e),this.onEvent=s=>Cn(this.instance.on("eventCaptured",(n=>{try{s({event:n.event,properties:n.properties})}catch(r){this.rt.error("Browser extension event listener failed",r)}}))),this.onRemoteConfig=s=>{if(this.an)return Cn((()=>{}));var n=i=>{try{s(i)}catch(o){this.rt.error("Browser extension remote config listener failed",o)}},r=this.instance.dn.on(Pl,n);return this.un&&n(this.un),Cn(r)},this.vn=new af(k.createLogger("[BrowserExtensions]"),this)}get logger(){return this.rt}get distinctId(){return this.instance.get_distinct_id()}get anonymousId(){var e;return(e=this.instance.get_property(sn))!==null&&e!==void 0?e:this.distinctId}get deviceId(){var e=this.instance.get_property(sn);return typeof e=="string"?e:void 0}get library(){return{name:Y.LIB_NAME,version:Y.LIB_VERSION}}get initialPersonProperties(){var e,s;return(e=(s=this.instance.persistence)==null?void 0:s.get_initial_props())!==null&&e!==void 0?e:{}}get groups(){return this.instance.getGroups()}get session(){try{var e,s,n,r,i=(e=this.instance.sessionManager)==null?void 0:e.checkAndGetSessionAndWindowId(!0);return{sessionId:(s=i?.sessionId)!==null&&s!==void 0?s:"",windowId:(n=i?.windowId)!==null&&n!==void 0?n:"",sessionStartTimestamp:(r=i?.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,s,n){var r=this;return X((function*(){n?r.instance.capture(e,s,{timestamp:n.timestamp,uuid:n.uuid,$set:n.set,$set_once:n.setOnce}):r.instance.capture(e,s)}))()}registerDynamicEventProperties(e){return Cn(this.instance.cn(e))}handleRemoteConfig(e){this.an||(this.un=e,this.instance.dn.emit(Pl,e))}sendRequest(e,s){var n=this;return X((function*(){var r;s===void 0&&(s={});var i=n.instance.requestRouter.endpointFor((r=s.target)!==null&&r!==void 0?r:"api",e),o={method:s.method,url:s.query?Rr(i,s.query):i,data:s.body,headers:s.headers,timeout:s.timeoutMs,fireCallbackOnDrop:!0,transport:s.transport,compression:s.compression,timestampMode:s.sentAt};return s.transport==="sendBeacon"?(n.instance._send_request(o),{statusCode:202}):new Promise((a=>{o.callback=a,n.instance._send_request(o)}))}))()}dispose(){this.an||(this.an=!0,this.vn.dispose())}}var Ys={},wi=0,gr=()=>{},Al='Consent opt in/out is not valid with cookieless_mode="always" and will be ignored',Ns="Surveys module not available",$l="sanitize_properties is deprecated. Use before_send instead",cd="Invalid value for property_denylist config: ",uf=["token","distinct_id",mu],os="posthog",ud=!qp&&Pe?.indexOf("MSIE")===-1&&Pe?.indexOf("Mozilla")===-1,bi=t=>{var e;return b({api_host:"https://us.i.posthog.com",flags_api_host:null,ui_host:null,asset_host:null,token:"",autocapture:!0,cross_subdomain_cookie:up(C?.location),persistence:"localStorage+cookie",persistence_name:"",cookie_persisted_properties:[],loaded:gr,save_campaign_params:!0,custom_campaign_params:[],custom_blocked_useragents:[],save_referrer:!0,capture_pageleave:"if_capture_pageview",defaults:t??"unset",__preview_deferred_init_extensions:!1,__preview_external_dependency_versioned_paths:!1,__preview_cookie_wins_on_conflict:!1,debug:ne&&W(ne?.search)&&ne.search.indexOf("__posthog_debug=true")!==-1||!1,cookie_expiration:365,upgrade:!1,disable_session_recording:!1,disable_persistence:!1,disable_web_experiments:!0,disable_surveys:!1,disable_surveys_automatic_display:!1,disable_conversations:!1,disable_product_tours:!1,disableDeviceModel:!1,disable_external_dependency_loading:!1,strict_script_versioning:!1,enable_recording_console_log:void 0,secure_cookie:(v==null||(e=v.location)==null?void 0:e.protocol)==="https:",ip:!1,opt_out_capturing_by_default:!1,opt_out_persistence_by_default:!1,opt_out_useragent_filter:!1,opt_out_capturing_persistence_type:"localStorage",consent_persistence_name:null,opt_out_capturing_cookie_prefix:null,opt_in_site_apps:!1,property_denylist:[],respect_dnt:!1,sanitize_properties:null,request_headers:{},request_batching:!0,properties_string_max_length:65535,mask_all_element_attributes:!1,mask_all_text:!1,mask_personal_data_properties:!1,custom_personal_data_properties:[],advanced_disable_flags:!1,advanced_disable_decide:!1,advanced_disable_feature_flags:!1,advanced_disable_feature_flags_on_first_load:!1,advanced_only_evaluate_survey_feature_flags:!1,advanced_feature_flags_dedup_per_session:!1,advanced_enable_surveys:!1,advanced_disable_toolbar_metrics:!1,feature_flag_request_timeout_ms:3e3,surveys_request_timeout_ms:1e4,on_request_error(s){k.error("Bad HTTP status: "+s.statusCode+" "+s.text)},get_device_id:s=>s,capture_performance:void 0,name:"posthog",bootstrap:{},disable_compression:!1,session_idle_timeout_seconds:1800,person_profiles:ro,before_send:void 0,get_current_url:void 0,request_queue_config:{flush_interval_ms:fo},error_tracking:{},_onCapture:gr},(s=>({rageclick:s&&s>="2026-05-30"?{content_ignorelist:Ep,ignore_text_selection:!0}:!s||"2025-11-30">s||{content_ignorelist:!0},capture_pageview:!s||"2025-05-24">s||"history_change",session_recording:s&&s>="2026-06-25"?{strictMinimumDuration:!0,canvasCapture:{resolutionScale:.6},streamNetworkBody:!0}:s&&s>="2026-05-30"?{strictMinimumDuration:!0,canvasCapture:{resolutionScale:.6}}:s&&s>="2025-11-30"?{strictMinimumDuration:!0}:{},external_scripts_inject_target:s&&s>="2026-01-30"?"head":"body",internal_or_test_user_hostname:s&&s>="2026-01-30"?/^(localhost|127\.0\.0\.1)$/:void 0,persistence_save_debounce_ms:s&&s>="2026-05-30"?250:0,split_storage:!(!s||"2026-05-30">s),detect_google_search_app:!(!s||"2026-05-30">s),disable_capture_url_hashes:!(!s||"2026-06-25">s)}))(t))},df=[["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"]],Rl=t=>{var e={};for(var s of df){var n=s[0],r=s[1];x(t[n])||(e[r]=t[n])}var i=ee({},e,t),o=t.__preview_external_dependency_versioned_paths;return x(o)||(x(t.strict_script_versioning)&&(i.strict_script_versioning=!!o),W(o)&&x(t.asset_host)&&(i.asset_host=o)),L(t.property_blacklist)&&(x(t.property_denylist)?i.property_denylist=t.property_blacklist:L(t.property_denylist)?i.property_denylist=[...t.property_blacklist,...t.property_denylist]:k.error(cd+t.property_denylist)),i};class hf{constructor(){this.__forceAllowLocalhost=!1}get fn(){return this.__forceAllowLocalhost}set fn(e){k.error("WebPerformanceObserver is deprecated and has no impact on network capture. Use `_forceAllowLocalhostNetworkCapture` on `posthog.sessionRecording`"),this.__forceAllowLocalhost=e}}class Te{pn(e,s){if(e){var n=this.sn.indexOf(e);n!==-1&&this.sn.splice(n,1)}return this.sn.push(s),s.initialize==null||s.initialize(),s}gn(){return this.config.cookieless_mode===ht||this.config.cookieless_mode===Ht&&this.consent.isRejected()}get decideEndpointWasHit(){var e,s;return(e=(s=this.featureFlags)==null?void 0:s.hasLoadedFlags)!==null&&e!==void 0&&e}get flagsEndpointWasHit(){var e,s;return(e=(s=this.featureFlags)==null?void 0:s.hasLoadedFlags)!==null&&e!==void 0&&e}constructor(){var e;this.webPerformance=new hf,this.mn=!1,this.version=Y.LIB_VERSION,this.yn=new Set,this.bn="",this.dn=new ta,this.sn=[],this._n=[],this._calculate_event_properties=this.calculateEventProperties.bind(this),this.config=bi(),this.SentryIntegration=Ap,this.sentryIntegration=n=>(function(r,i){var o=Nu(r,i);return{name:Tu,processEvent:a=>o(a)}})(this,n),this.__request_queue=[],this.__loaded=!1,this.analyticsDefaultEndpoint="/e/",this.wn=!1,this.kn=null,this.xn=null,this.Sn=null,this.scrollManager=new Zp(this),this.pageViewManager=new vl(this),this.rateLimiter=new Bp(this),this.requestRouter=new ef(this),this.consent=new vp(this),this.externalIntegrations=new of(this);var s=(e=Te.__defaultExtensionClasses)!==null&&e!==void 0?e:{};this.featureFlags=s.featureFlags&&new s.featureFlags(this),this.toolbar=s.toolbar&&new s.toolbar(this),this.surveys=s.surveys&&new s.surveys(this),this.conversations=s.conversations&&new s.conversations(this),this.logs=s.logs&&new s.logs(this),this.metrics=s.metrics&&new s.metrics(this),this.experiments=s.experiments&&new s.experiments(this),this.exceptions=s.exceptions&&new s.exceptions(this),this.people={set:(n,r,i)=>{var o=W(n)?{[n]:r}:n;this.setPersonProperties(o),i?.({})},set_once:(n,r,i)=>{var o=W(n)?{[n]:r}:n;this.setPersonProperties(void 0,o),i?.({})}},this.on("eventCaptured",(n=>k.info('send "'+n?.event+'"',n)))}init(e,s,n){if(n&&n!==os){var r,i=(r=Ys[n])!==null&&r!==void 0?r:new Te;return i._init(e,s,n),Ys[n]=i,Ys[os][n]=i,i}return this._init(e,s,n)}_init(e,s,n){var r,i;s===void 0&&(s={});var o,a=W(e)?e.trim():"";if(!a)return k.critical("PostHog was initialized without a token. This likely indicates a misconfiguration. Please check the first argument passed to posthog.init()"),this;if(this.__loaded)return a!==((o=this.config)==null?void 0:o.token)?console.warn("[PostHog.js]","You have already initialized PostHog with a different project token! Re-initializing is a no-op, so events will keep going to the project this instance was initialized with. To capture into a second project, load PostHog once, then initialize a named instance after the SDK has loaded, e.g. posthog.init('"+a+"', { ... }, 'project2')"):console.warn("[PostHog.js]","You have already initialized PostHog! Re-initializing is a no-op"),this;this.__loaded=!0,this.config=bi(s.defaults),s.debug=this.Cn(s.debug),this.Mn=s,this.Tn=[],s.person_profiles?this.xn=s.person_profiles:s.process_person&&(this.xn=s.process_person);var l=bi(s.defaults),u=Rl(s),c=ee({},l,u,{name:n,token:a});te(l.rageclick)&&te(u.rageclick)&&(c.rageclick=ee({},l.rageclick,u.rageclick)),te(l.session_recording)&&te(u.session_recording)&&(c.session_recording=ee({},l.session_recording,u.session_recording)),this.set_config(c),this.config.on_xhr_error&&k.error("on_xhr_error is deprecated. Use on_request_error instead"),this.compression=s.disable_compression?void 0:xe.GZipJS;var d=this.En();if(this.persistence=new pi(this.config,d),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new pi(b({},this.config,{persistence:"sessionStorage"}),d,!1),this.bn="ph_"+(this.config.persistence_name||this.config.token)+"_session_registered_properties",this.config.persistence!=="memory"&&!d&&ce.N()){var h=ce.H(this.bn);L(h)&&h.forEach((P=>{W(P)&&this.yn.add(P)}))}else ce.q(this.bn);var p=b({},this.persistence.props),f=b({},this.sessionPersistence.props);this.register({$initialization_time:new Date().toISOString()}),this.In=new Kp((P=>this.Pn(P)),this.config.request_queue_config),this.Rn=new Yp(this),this.__request_queue=[];var g=this.gn();if(g||(this.sessionManager=new Cl(this),this.sessionPropsManager=new Il(this,this.sessionManager,this.persistence),this.sessionManager.onSessionId(((P,B,S)=>{(S!=null&&S.activityTimeout||S!=null&&S.sessionPastMaximumLength||S!=null&&S.crossTabAdoption)&&this.An()}))),this.Fn(),this.config.__preview_deferred_init_extensions?(k.info("Deferring extension initialization to improve startup performance"),setTimeout((()=>{this.Ln(g)}),0)):(k.info("Initializing extensions synchronously"),this.Ln(g)),Y.DEBUG=Y.DEBUG||this.config.debug,Y.DEBUG&&k.info("Starting in debug mode",{this:this,config:s,thisC:b({},this.config),p,s:f}),!this.config.identity_distinct_id||(r=s.bootstrap)!=null&&r.distinctID||(s.bootstrap=b({},s.bootstrap,{distinctID:this.config.identity_distinct_id,isIdentifiedID:!0})),((i=s.bootstrap)==null?void 0:i.distinctID)!==void 0){var m=s.bootstrap.distinctID,_=this.get_distinct_id(),w=this.persistence.get_property(He);if(s.bootstrap.isIdentifiedID&&_!=null&&_!==m&&w===es)this.identify(m);else if(s.bootstrap.isIdentifiedID&&_!=null&&_!==m&&w===Tt)k.warn("Bootstrap distinctID differs from an already-identified user. The existing identity is preserved. Call reset() before reinitializing if you intend to switch users.");else{var E=this.config.get_device_id(dt()),I=s.bootstrap.isIdentifiedID?E:m;this.persistence.set_property(He,s.bootstrap.isIdentifiedID?Tt:es),this.register({distinct_id:m,$device_id:I})}}if(g)this.register_once({distinct_id:En,$device_id:null},"");else if(!this.get_distinct_id()){var F=this.config.get_device_id(dt());this.register_once({distinct_id:F,$device_id:F},""),this.persistence.set_property(He,es)}return re(v,"onpagehide"in self?"pagehide":"unload",this._handle_unload.bind(this),{passive:!1}),s.segment?(function(P,B){var S=P.config.segment;if(!S)return B();(function(A,R){var N=A.config.segment;if(!N)return R();var T=J=>{var z=()=>J.anonymousId()||dt();A.config.get_device_id=z,J.id()&&(A.register({distinct_id:J.id(),$device_id:z()}),A.persistence.set_property(He,Tt)),R()},O=N.user();"then"in O&&Se(O.then)?O.then(T):T(O)})(P,(()=>{S.register((A=>{typeof Promise<"u"&&Promise.resolve||di.warn("This browser does not have Promise support, and can not use the segment integration");var R=(N,T)=>{if(!T)return N;N.event.userId||N.event.anonymousId===A.get_distinct_id()||(di.info("No userId set, resetting PostHog"),A.reset()),N.event.userId&&N.event.userId!==A.get_distinct_id()&&(di.info("UserId set, identifying with PostHog"),A.identify(N.event.userId));var O=A.calculateEventProperties(T,N.event.properties);return N.event.properties=Object.assign({},O,N.event.properties),N};return{name:"PostHog JS",type:"enrichment",version:"1.0.0",isLoaded:()=>!0,load:()=>Promise.resolve(),track:N=>R(N,N.event.event),page:N=>R(N,is),identify:N=>R(N,li),screen:N=>R(N,"$screen")}})(P)).then((()=>{B()}))}))})(this,(()=>this.On())):this.On(),Se(this.config._onCapture)&&this.config._onCapture!==gr&&(k.warn("onCapture is deprecated. Please use `before_send` instead"),this.on("eventCaptured",(P=>this.config._onCapture(P.event,P)))),this.config.ip&&k.warn('The `ip` config option has NO EFFECT AT ALL and has been deprecated. Use a custom transformation or "Discard IP data" project setting instead. See https://posthog.com/tutorials/web-redact-properties#hiding-customer-ip-address for more information.'),this.config.disableDeviceModel||(function(){return nd.apply(this,arguments)})().then((P=>{P&&this.register({[oi]:P})})).catch(gr),this}Fn(){var e,s,n,r,i,o,a=(e=(s=this.config.__extensionClasses)==null?void 0:s.featureFlags)!==null&&e!==void 0?e:(n=Te.__defaultExtensionClasses)==null?void 0:n.featureFlags;a&&(this.featureFlags&&this.featureFlags instanceof a||((r=this.Dn)==null||r.call(this),this.Dn=void 0,this.featureFlags=new a(this)),Se(this.featureFlags.onReloading)&&Se(this.featureFlags.setup)?this.Dn||(this.Dn=this.featureFlags.onReloading((()=>{this.dn.emit("featureFlagsReloading",!0)})),this.$n().add(this.featureFlags)):(i=(o=this.featureFlags).initialize)==null||i.call(o))}Ln(e){var s,n,r,i,o,a,l,u=performance.now(),c=b({},Te.__defaultExtensionClasses,this.config.__extensionClasses),d=[];c.exceptions&&this.sn.push(this.exceptions=(s=this.exceptions)!==null&&s!==void 0?s: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=(n=this.surveys)!==null&&n!==void 0?n: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=(i=this.metrics)!==null&&i!==void 0?i: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,Pp)),c.toolbar&&this.sn.push(this.toolbar=(a=this.toolbar)!==null&&a!==void 0?a:new c.toolbar(this)),c.experiments&&this.sn.push(this.experiments=(l=this.experiments)!==null&&l!==void 0?l:new c.experiments(this)),this.sn.forEach((h=>{h.initialize&&d.push((()=>{h.initialize==null||h.initialize()}))})),d.push((()=>{if(this.Nn){var h=this.Nn;this.Nn=void 0,this.sn.forEach((p=>p.onRemoteConfig==null?void 0:p.onRemoteConfig(h)))}})),this.qn(d,u)}qn(e,s){for(;e.length>0;){if(this.config.__preview_deferred_init_extensions&&performance.now()-s>=30&&e.length>0)return void setTimeout((()=>{this.qn(e,s)}),0);var n=e.shift();if(n)try{n()}catch(i){k.error("Error initializing extension:",i)}}var r=Math.round(performance.now()-s);this.register_for_session({[vu]:this.config.__preview_deferred_init_extensions?"deferred":"synchronous",[_u]:r}),this.config.__preview_deferred_init_extensions&&k.info("PostHog extensions initialized ("+r+"ms)")}Zi(e){var s;if(!C||!C.body)return k.info("document not ready yet, trying again in 500 milliseconds..."),void setTimeout((()=>{this.Zi(e)}),500);if(this.config.__preview_deferred_init_extensions&&(this.Nn=e),this.hn=e,this.compression=void 0,e.ok){var n,r=e.config;r.supportedCompression&&!this.config.disable_compression&&(this.compression=M(r.supportedCompression,xe.GZipJS)?xe.GZipJS:M(r.supportedCompression,xe.Base64)?xe.Base64:void 0),(n=r.analytics)!=null&&n.endpoint&&(this.analyticsDefaultEndpoint=r.analytics.endpoint)}this.set_config({person_profiles:this.xn?this.xn:ro}),(s=this.jn)==null||s.handleRemoteConfig(e),this.sn.forEach((i=>i.onRemoteConfig==null?void 0:i.onRemoteConfig(e)))}On(){try{this.config.loaded(this)}catch(n){k.critical("`loaded` function failed",n)}if(this.Bn(),this.config.internal_or_test_user_hostname&&ne!=null&&ne.hostname){var e=ne.hostname,s=this.config.internal_or_test_user_hostname;(typeof s=="string"?e===s:s.test(e))&&this.setInternalOrTestUser()}this.config.capture_pageview&&setTimeout((()=>{(this.consent.isOptedIn()||this.gn())&&this.Hn()}),1),this.Un=new zu(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()&&Sn(this.__request_queue,(e=>this.Pn(e))),this.__request_queue=[],this.Bn()}_handle_unload(){var e,s,n,r,i;(e=this.surveys)==null||e.handlePageUnload==null||e.handlePageUnload(),(s=this.metrics)==null||s.flush("sendBeacon"),this.config.request_batching?(this.zn()&&this.capture(ai),(n=this.logs)==null||n.flushLogs("sendBeacon"),(r=this.In)==null||r.unload(),(i=this.Rn)==null||i.unload()):this.zn()&&this.capture(ai,null,{transport:"sendBeacon"})}_send_request(e){this.__loaded?ud?this.__request_queue.push(e):this.rateLimiter.isServerRateLimited(e.batchKey)?e.fireCallbackOnDrop&&(e.callback==null||e.callback({statusCode:429})):(e.transport=e.transport||this.config.api_transport,e.headers=b({},this.config.request_headers,e.headers),e.compression=e.compression==="best-available"?this.compression:e.compression,(x(this.config.disable_beacon)?this.config.__preview_disable_beacon:this.config.disable_beacon)&&(e.disableTransport=["sendBeacon"]),e.fetchOptions=e.fetchOptions||this.config.fetch_options,(s=>{var n,r,i,o=b({},s);o.timeout=o.timeout||6e4;var a,l,u,c,d,h=(n=o.transport)!==null&&n!==void 0?n:"fetch";h==="sendBeacon"&&x(o.compression)&&o.data&&(o.compression=xe.Base64),o.method==="POST"&&o.data&&(o.timestampMode==="capture-body"?o.data={api_key:(l=(d=(c=L(a=o.data)?a:[a])[0])==null||(u=d.properties)==null?void 0:u.token)!==null&&l!==void 0?l:d?.token,batch:c,sent_at:new Date().toISOString()}:o.timestampMode==="body"&&(o.data=(function(m,_){return _===void 0&&(_=new Date().toISOString()),L(m)?m.map((w=>b({},w,{sent_at:_}))):b({},m,{sent_at:_})})(o.data))),o.url=kl(o.url,o.method,o.compression,o.timestampMode);var p=jn.filter((m=>!o.disableTransport||!m.transport||!o.disableTransport.includes(m.transport))),f=(r=(i=(function(m,_){for(var w=0;m.length>w;w++)if(m[w].transport===h)return m[w]})(p))==null?void 0:i.method)!==null&&r!==void 0?r:p[0].method;if(!f)throw new Error("No available transport method");var g=m=>{try{f(m)}catch(_){ed(_)?k.warn(_):k.error(_),o.callback==null||o.callback({statusCode:0,error:_})}};h!=="sendBeacon"&&o.data&&o.compression===xe.GZipJS&&hh&&typeof Promise<"u"&&!Bn?Vp(o).then((m=>{g(m)})).catch((m=>{if(qa(m))return Bn=!0,void g(b({},o,{compression:void 0,url:kl(s.url,s.method,void 0,s.timestampMode)}));(_=>{if(!_||typeof _!="object")return!1;var w="name"in _?String(_.name):"";return qa(_)||w===Ac})(m)&&(Bn=!0),g(o)})):f(o)})(b({},e,{callback:s=>{var n,r;this.rateLimiter.checkForLimiting(s),400>s.statusCode||(n=(r=this.config).on_request_error)==null||n.call(r,s),e.callback==null||e.callback(s)}}))):e.fireCallbackOnDrop&&(e.callback==null||e.callback({statusCode:0}))}Pn(e){this.Rn?this.Rn.retriableRequest(e):this._send_request(e)}_execute_array(e){wi++;try{var s,n=[],r=[],i=[];Sn(e,(a=>{if(a)if(L(s=a[0]))i.push(a);else if(Se(a))try{a.call(this)}catch(l){k.error("Error executing queued PostHog call",a,l)}else L(a)&&s==="alias"?n.push(a):L(a)&&s.indexOf("capture")!==-1&&Se(this[s])?i.push(a):r.push(a)}));var o=function(a,l){Sn(a,(function(u){try{if(L(u[0])){var c=l;Z(u,(function(d){c=c[d[0]].apply(c,d.slice(1))}))}else l[u[0]].apply(l,u.slice(1))}catch(d){k.error("Error executing queued PostHog call",u,d)}}))};o(n,this),o(r,this),o(i,this)}finally{wi--}}push(e){if(wi>0&&L(e)&&W(e[0])){var s=Te.prototype[e[0]];Se(s)&&s.apply(this,e.slice(1))}else this._execute_array([e])}capture(e,s,n){var r,i,o,a,l;if(this.__loaded&&this.persistence&&this.sessionPersistence&&this.In){if(this.is_capturing())if(!x(e)&&W(e)){var u=!this.config.opt_out_useragent_filter&&this._is_bot();if(!u||this.config.__preview_capture_bot_pageviews){var c=n!=null&&n.skip_client_rate_limiting?void 0:this.rateLimiter.clientRateLimitContext();if(c==null||!c.isRateLimited){s!=null&&s.$current_url&&!W(s?.$current_url)&&(k.error("Invalid `$current_url` property provided to `posthog.capture`. Input must be a string. Ignoring provided value."),s==null||delete s.$current_url),e!=="$exception"||n!=null&&n.Wn||k.warn("Using `posthog.capture('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureException(error)` instead, which attaches required metadata automatically."),this.sessionPersistence.update_search_keyword(),this.config.save_campaign_params&&this.sessionPersistence.update_campaign_params(),this.config.save_referrer&&this.sessionPersistence.update_referrer_info(),(this.config.save_campaign_params||this.config.save_referrer)&&this.persistence.set_initial_person_info();var d=new Date,h=n?.timestamp||d,p=Ya(n?.uuid,dt),f={uuid:p,event:e,properties:this.calculateEventProperties(e,s||{},h,p)};e===is&&this.config.__preview_capture_bot_pageviews&&u&&(f.event="$bot_pageview",f.properties.$browser_type="bot"),c&&(f.properties.$lib_rate_limit_remaining_tokens=c.remainingTokens);var g=e==="$feature_flag_called"&&f.properties.$feature_flag_has_experiment===!1&&this.get_property(sr)===!0;n?.$set&&!g&&(f.$set=n?.$set);var m=n?.$unset;m&&(f.$unset=m);var _,w,E,I=g?void 0:this.Vn(n?.$set_once,e!==sl,e===li);if(I&&(f.$set_once=I),n!=null&&n._noTruncate||(i=this.config.properties_string_max_length,o=f,a=T=>W(T)?T.slice(0,i):T,l=new Set,f=(function T(O,J){if(O!==Object(O))return a?a(O):O;if(!l.has(O)){var z;if(l.add(O),L(O))z=[],Sn(O,(oe=>{z.push(T(oe))}));else{var H={};Z(O,((oe,pe)=>{l.has(oe)||(H[pe]=T(oe))})),z=H}return z}})(o)),f.timestamp=h,x(n?.timestamp)||(f.properties.$event_time_override_provided=!0,f.properties.$event_time_override_system_time=d),g&&(f.properties=(function(T,O){O===void 0&&(O=[]);var J={},z=H=>{T[H]!==void 0&&(J[H]=T[H])};return ph.forEach(z),O.forEach(z),J})(f.properties,uf)),e===ft.DISMISSED||e===ft.SENT){var F=s?.[gi.SURVEY_ID],P=s?.[gi.SURVEY_ITERATION];ld({id:F,current_iteration:P}),f.$set=b({},f.$set,{[(_={id:F,current_iteration:P},w=e===ft.SENT?"responded":"dismissed",E="$survey_"+w+"/"+_.id,_.current_iteration&&_.current_iteration>0&&(E="$survey_"+w+"/"+_.id+"/"+_.current_iteration),E)]:!0})}else e===ft.SHOWN&&(f.$set=b({},f.$set,{[gi.SURVEY_LAST_SEEN_DATE]:new Date().toISOString()}));if(e===Dp.SHOWN){var B=s?.[yl.TOUR_TYPE];B&&(f.$set=b({},f.$set,{[yl.TOUR_LAST_SEEN_DATE+"/"+B]:new Date().toISOString()}))}var S=b({},f.properties.$set,f.$set);if(mt(S)||this.setPersonPropertiesForFlags(S),!D(this.config.before_send)){var A=this.Pt(f);if(!A)return;(f=A).uuid=Ya(f.uuid,dt)}this.dn.emit("eventCaptured",f);var R=(r=n?._url)!==null&&r!==void 0?r:this.requestRouter.endpointFor("api",this.analyticsDefaultEndpoint),N={method:"POST",url:R,data:f,compression:"best-available",timestampMode:n?._batchKey==="recordings"||/\/s\/(?:\?|$)/.test(R)?"body":"capture-body",batchKey:n?._batchKey,transport:n?.transport};return!this.config.request_batching||n&&(n==null||!n._batchKey)||n!=null&&n.send_instantly?this.Pn(N):this.In.enqueue(N),f}k.critical("This capture call is ignored due to client rate limiting.")}}else k.error("No event name provided to posthog.capture")}else k.uninitializedWarning("posthog.capture")}_addCaptureHook(e){return this.on("eventCaptured",(s=>e(s.event,s)))}$n(){var e;return(e=this.jn)!==null&&e!==void 0?e:this.jn=new cf(this)}cn(e){this._n.push(e);var s=!0;return()=>{if(s){s=!1;var n=this._n.indexOf(e);n!==-1&&this._n.splice(n,1)}}}calculateEventProperties(e,s,n,r,i){if(n=n||new Date,!this.persistence||!this.sessionPersistence)return s;var o=i?void 0:this.persistence.remove_event_timer(e),a=b({},s);if(a.token=this.config.token,a.$config_defaults=this.config.defaults,this.gn()&&(a[mu]=!0),e==="$snapshot"){var l=b({},this.persistence.properties(),this.sessionPersistence.properties());return a.distinct_id=l.distinct_id,(!W(a.distinct_id)&&!he(a.distinct_id)||Di(a.distinct_id))&&k.error("Invalid distinct_id for replay event. This indicates a bug in your implementation"),a}var u,c=(function(F,P,B,S){var A,R,N,T;if(S===void 0&&(S=!1),!Pe)return{};var O,J=F?[...vs,...P||[]]:[],z=(function(_n){for(var je=0;Ka.length>je;je++){var yn=Ka[je],Xt=yn[1],Qt=yn[0].exec(_n),Is=Qt&&(Se(Xt)?Xt(Qt,_n):Xt);if(Is)return Is}return["",""]})(Pe),H=z[0],oe=z[1],pe=(O=typeof navigator<"u"?navigator:void 0)!=null&&O.brave?{brave:!0}:{},Ie={};x(B)||(Ie.detectGoogleSearchApp=B);var _e={},Ce=(A=navigator)==null||(A=A.userAgentData)==null?void 0:A.platform,Re=(R=navigator)==null?void 0:R.maxTouchPoints,ae=v==null||(N=v.screen)==null?void 0:N.width,me=v==null||(T=v.screen)==null?void 0:T.height,ge=v?.devicePixelRatio;x(Ce)||(_e.userAgentDataPlatform=Ce),x(Re)||(_e.maxTouchPoints=Re),x(ae)||(_e.screenWidth=ae),x(me)||(_e.screenHeight=me),x(ge)||(_e.devicePixelRatio=ge);var Ye,Rt,de,Ve,St,ks,Be,Fe,vn=ee(Jo({$os:H,$os_version:oe,$browser:tu(Pe,navigator.vendor,pe,Ie),$device:Ja(Pe),$device_type:(Rt=Pe,de=_e,Fe=Ja(Rt),Fe===Oc||Fe===Lc||Fe==="Kobo"||Fe==="Kindle Fire"||Fe===Yc?ps:Fe===en||Fe===ds||Fe===tn||Fe===ji?"Console":Fe===Bc?"Wearable":Fe?Oe:de?.userAgentDataPlatform==="Android"&&((Ve=de?.maxTouchPoints)!==null&&Ve!==void 0?Ve:0)>0?600>Math.min((St=de?.screenWidth)!==null&&St!==void 0?St:0,(ks=de?.screenHeight)!==null&&ks!==void 0?ks:0)/((Be=de?.devicePixelRatio)!==null&&Be!==void 0?Be:1)?Oe:ps:"Desktop"),$timezone:Wu(),$timezone_offset:Mp()}),{$current_url:rn(S?Ct(ne?.href):ne?.href,J,on),$host:ne?.host,$pathname:ne?.pathname,$raw_user_agent:Pe.length>1e3?Pe.substring(0,997)+"...":Pe,$browser_version:Rh(Pe,navigator.vendor,pe,Ie),$browser_language:_l(),$browser_language_prefix:(Ye=_l(),typeof Ye=="string"?Ye.split("-")[0]:void 0),$screen_height:v?.screen.height,$screen_width:v?.screen.width,$viewport_height:v?.innerHeight,$viewport_width:v?.innerWidth,$lib:Y.LIB_NAME,$lib_version:Y.LIB_VERSION,$insert_id:Math.random().toString(36).substring(2,10)+Math.random().toString(36).substring(2,10),$time:Date.now()/1e3});return Y.SDK_DIST_CHANNEL&&(vn.$sdk_dist_channel=Y.SDK_DIST_CHANNEL),vn})(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(i,n.getTime()),h=d.windowId;a.$session_id=d.sessionId,a.$window_id=h}this.sessionPropsManager&&ee(a,this.sessionPropsManager.getSessionProps());try{var p;this.sessionRecording&&ee(a,this.sessionRecording.sdkDebugProperties),a.$sdk_debug_retry_queue_size=(p=this.Rn)==null?void 0:p.length}catch(F){a.$sdk_debug_error_capturing_properties=String(F)}if(this.requestRouter.region===go&&(a.$lib_custom_api_host=this.config.api_host),u=e!==is||i?e!==ai||i?this.pageViewManager.doEvent():this.pageViewManager.doPageLeave(n):this.pageViewManager.doPageView(n,r),a=ee(a,u),e===is&&C&&(a.title=C.title),!x(o)){var f=n.getTime()-o;a.$duration=parseFloat((f/1e3).toFixed(3))}Pe&&this.config.opt_out_useragent_filter&&(a.$browser_type=this._is_bot()?"bot":"browser");var g=this.persistence.properties(),m=this.sessionPersistence.properties();Z(["$referrer","$referring_domain"],(F=>{F in g&&delete m[F]}));var _={};if(this._n.length>0)for(var w of this._n.slice())try{ee(_,w())}catch(F){k.error("Failed to produce browser extension event properties",F)}(a=ee({},c,g,m,b({},_,a))).$is_identified=this._isIdentified(),L(this.config.property_denylist)?Z(this.config.property_denylist,(function(F){delete a[F]})):k.error(cd+this.config.property_denylist+" or property_blacklist config: "+this.config.property_blacklist);var E=this.config.sanitize_properties;E&&(k.error($l),a=E(a,e));var I=this.Zn();return a.$process_person_profile=I,I&&!i&&this.Gn("_calculate_event_properties"),a}Vn(e,s,n){var r;if(s===void 0&&(s=!0),n===void 0&&(n=!1),!this.persistence||!this.Zn()||this.mn&&!n)return e;var i=this.persistence.get_initial_props(),o=(r=this.sessionPropsManager)==null?void 0:r.getSetOnceProps(),a=ee({},i,o||{},e||{}),l=this.config.sanitize_properties;return l&&(k.error($l),a=l(a,"$set_once")),s&&(this.mn=!0),mt(a)?void 0:a}register(e,s){var n;(n=this.persistence)==null||n.register(e,s)}register_once(e,s,n){var r;(r=this.persistence)==null||r.register_once(e,s,n)}register_for_session(e){var s;(s=this.sessionPersistence)==null||s.register(e),Object.keys(e).forEach((n=>this.yn.add(n))),this.Qn()}unregister(e){var s;(s=this.persistence)==null||s.unregister(e)}unregister_for_session(e){var s;(s=this.sessionPersistence)==null||s.unregister(e),this.yn.delete(e),this.Qn()}Kn(e,s){this.register({[e]:s})}An(){this.yn.forEach((e=>{var s;(s=this.sessionPersistence)==null||s.unregister(e)})),this.yn.clear(),this.Qn()}Qn(){var e;if(this.bn)if(this.config.persistence==="memory"||(e=this.sessionPersistence)!=null&&e.xi||!ce.N())ce.q(this.bn);else{var s=[];this.yn.forEach((n=>s.push(n))),s.length>0?ce.F(this.bn,s):ce.q(this.bn)}}getFeatureFlag(e,s){var n;return(n=this.featureFlags)==null?void 0:n.getFeatureFlag(e,s)}getFeatureFlagPayload(e){var s;return(s=this.featureFlags)==null?void 0:s.getFeatureFlagPayload(e)}getFeatureFlagResult(e,s){var n;return(n=this.featureFlags)==null?void 0:n.getFeatureFlagResult(e,s)}getAllFeatureFlags(){var e,s;return(e=(s=this.featureFlags)==null?void 0:s.getAllFeatureFlags())!==null&&e!==void 0?e:[]}isFeatureEnabled(e,s){var n,r;return(n=(r=this.featureFlags)==null?void 0:r.isFeatureEnabled(e,s))!==null&&n!==void 0?n:s?.defaultValue}reloadFeatureFlags(){var e;(e=this.featureFlags)==null||e.reloadFeatureFlags()}updateFlags(e,s,n){var r;(r=this.featureFlags)==null||r.updateFlags(e,s,n)}updateEarlyAccessFeatureEnrollment(e,s,n){var r;(r=this.featureFlags)==null||r.updateEarlyAccessFeatureEnrollment(e,s,n)}getEarlyAccessFeatures(e,s,n){var r;return s===void 0&&(s=!1),(r=this.featureFlags)==null?void 0:r.getEarlyAccessFeatures(e,s,n)}on(e,s){return this.dn.on(e,s)}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:Ns}),()=>{})}onSessionId(e){var s,n;return(s=(n=this.sessionManager)==null?void 0:n.onSessionId(e))!==null&&s!==void 0?s:()=>{}}getSurveys(e,s){s===void 0&&(s=!1),this.surveys?this.surveys.getSurveys(e,s):e([],{isLoaded:!1,error:Ns})}getActiveMatchingSurveys(e,s){s===void 0&&(s=!1),this.surveys?this.surveys.getActiveMatchingSurveys(e,s):e([],{isLoaded:!1,error:Ns})}renderSurvey(e,s){var n;(n=this.surveys)==null||n.renderSurvey(e,s)}displaySurvey(e,s){var n;s===void 0&&(s=sf),(n=this.surveys)==null||n.displaySurvey(e,s)}cancelPendingSurvey(e){var s;(s=this.surveys)==null||s.cancelPendingSurvey(e)}canRenderSurvey(e){var s,n;return(s=(n=this.surveys)==null?void 0:n.canRenderSurvey(e))!==null&&s!==void 0?s:{visible:!1,disabledReason:Ns}}canRenderSurveyAsync(e,s){var n,r;return s===void 0&&(s=!1),(n=(r=this.surveys)==null?void 0:r.canRenderSurveyAsync(e,s))!==null&&n!==void 0?n:Promise.resolve({visible:!1,disabledReason:Ns})}Jn(e){return!e||Di(e)?(k.critical("Unique user id has not been set in posthog.identify"),!1):e===En?(k.critical('The string "'+e+'" was set in posthog.identify which indicates an error. This ID is only used as a sentinel value.'),!1):!["distinct_id","distinctid"].includes(e.toLowerCase())&&!["undefined","null"].includes(e.toLowerCase())||(k.critical('The string "'+e+'" was set in posthog.identify which indicates an error. This ID should be unique to the user and not a hardcoded string.'),!1)}identify(e,s,n){if(!this.__loaded||!this.persistence)return k.uninitializedWarning("posthog.identify");if(he(e)&&(e=e.toString(),k.warn("The first argument to posthog.identify was a number, but it should be a string. It has been converted to a string.")),this.Jn(e)&&this.Gn("posthog.identify")){var r=this.get_distinct_id();this.register({$user_id:e}),this.get_property(sn)||this.register_once({$had_persisted_distinct_id:!0,$device_id:r},""),e!==r&&e!==this.get_property(Bs)&&(this.unregister(Bs),this.register({distinct_id:e}));var i,o=(this.persistence.get_property(He)||es)===es,a=e!==r,l=!a&&o;if(a&&o)this.persistence.set_property(He,Tt),this.setPersonPropertiesForFlags({$set:s||{},$set_once:n||{}},!1),this.capture(li,{distinct_id:e,$anon_distinct_id:r},{$set:s||{},$set_once:n||{}}),this.Sn=yi(e,s,n),(i=this.featureFlags)==null||i.setAnonymousDistinctId(r);else if(l){this.persistence.set_property(He,Tt);var u=s||{},c=n||{};this.setPersonPropertiesForFlags({$set:u,$set_once:c},!1),this.capture("$set",{$set:u,$set_once:c}),this.Sn=yi(e,s,n)}else(s||n)&&this.setPersonProperties(s,n);a?(this.reloadFeatureFlags(),this.featureFlags?this.featureFlags.resetFlagCallReported():this.unregister(Wt)):l&&(s||n)&&this.reloadFeatureFlags()}}setPersonProperties(e,s){if((e||s)&&this.Gn("posthog.setPersonProperties")){var n=yi(this.get_distinct_id(),e,s);this.Sn!==n?(this.setPersonPropertiesForFlags({$set:e||{},$set_once:s||{}},!0),this.capture("$set",{$set:e||{},$set_once:s||{}}),this.Sn=n):k.info("A duplicate setPersonProperties call was made with the same properties. It has been ignored.")}}unsetPersonProperties(e){var s,n=(L(e)?e:[e]).filter((r=>W(r)&&r.length>0));n.length!==0&&this.Gn("posthog.unsetPersonProperties")&&((s=this.featureFlags)==null||s.unsetPersonPropertiesForFlags(n,!0),this.capture("$set",{$unset:n}),this.Sn=null)}group(e,s,n){if(e&&s){var r=this.getGroups(),i=r[e]!==s;if(i&&this.resetGroupPropertiesForFlags(e),this.register({$groups:b({},r,{[e]:s})}),i||n){var o={$group_type:e,$group_key:s};n&&(o.$group_set=n),this.capture(sl,o)}n&&this.setGroupPropertiesForFlags({[e]:n}),i&&!n&&this.reloadFeatureFlags()}else k.error("posthog.group requires a group type and group key")}resetGroups(){this.register({$groups:{}}),this.resetGroupPropertiesForFlags(),this.reloadFeatureFlags()}setPersonPropertiesForFlags(e,s){var n;s===void 0&&(s=!0),(n=this.featureFlags)==null||n.setPersonPropertiesForFlags(e,s)}resetPersonPropertiesForFlags(e){var s;e===void 0&&(e=!0),(s=this.featureFlags)==null||s.resetPersonPropertiesForFlags(e)}setGroupPropertiesForFlags(e,s){var n;s===void 0&&(s=!0),this.Gn("posthog.setGroupPropertiesForFlags")&&((n=this.featureFlags)==null||n.setGroupPropertiesForFlags(e,s))}resetGroupPropertiesForFlags(e){var s;(s=this.featureFlags)==null||s.resetGroupPropertiesForFlags(e)}reset(e){this.Yn(e)}Yn(e,s){var n,r,i,o,a,l,u,c,d,h;if(s===void 0&&(s=!1),k.info("reset"),!this.__loaded)return k.uninitializedWarning("posthog.reset");var p,f=this.get_property(sn),g=this.get_property(oi),m=this.get_property(qt),_=this.is_capturing();if(this.consent.reset(),s||!_||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."),(n=this.persistence)==null||n.clear(),(r=this.sessionPersistence)==null||r.clear(),this.yn.clear(),this.Qn(),x(m)||(p=this.persistence)==null||p.register({[qt]:m}),(i=this.surveys)==null||i.reset(),(o=this.Un)==null||o.stop(),(a=this.featureFlags)==null||a.reset(),(l=this.conversations)==null||l.reset(),(u=this.logs)==null||u.reset(),(c=this.metrics)==null||c.reset(),(d=this.persistence)==null||d.set_property(He,es),(h=this.sessionManager)==null||h.resetSessionId(),this.Sn=null,this.config.cookieless_mode===ht)this.register_once({distinct_id:En,$device_id:null},"");else{var w=this.config.get_device_id(dt());this.register_once({distinct_id:w,$device_id:e?w:f},""),e||x(g)||this.register({[oi]: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 s=this;return X((function*(){var n,r,i,o,a,l,u;if(s.__loaded){(n=s.Un)==null||n.stop(),(r=s.jn)==null||r.dispose(),(i=s.sessionRecording)==null||i.dispose(),(o=s.logs)==null||o.flushLogs("sendBeacon"),(a=s.metrics)==null||a.flush("sendBeacon"),(l=s.In)==null||l.unload(),(u=s.Rn)==null||u.unload();try{var c;(c=s.featureFlags)==null||c.destroy()}catch(d){k.error("Error while destroying feature flags",d)}}else k.uninitializedWarning("posthog.shutdown")}))()}setIdentity(e,s){var n;this.config.identity_distinct_id=e,this.config.identity_hash=s,this.alias(e),(n=this.conversations)==null||n.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,s;return(e=(s=this.sessionManager)==null?void 0:s.checkAndGetSessionAndWindowId(!0).sessionId)!==null&&e!==void 0?e:""}get_session_replay_url(e){if(!this.sessionManager)return"";var s=this.sessionManager.checkAndGetSessionAndWindowId(!0),n=s.sessionStartTimestamp,r=this.requestRouter.endpointFor("ui","/project/"+this.config.token+"/replay/"+s.sessionId);if(e!=null&&e.withTimestamp&&n){var i,o=(i=e.timestampLookBack)!==null&&i!==void 0?i:10;if(!n)return r;r+="?t="+Math.max(Math.floor((new Date().getTime()-n)/1e3)-o,0)}return r}alias(e,s){return e===this.get_property(uu)?(k.critical("Attempting to create alias for existing People user - aborting."),-2):this.Gn("posthog.alias")?(x(s)&&(s=this.get_distinct_id()),e!==s?(this.Kn(Bs,e),this.capture("$create_alias",{alias:e,distinct_id:s})):(k.warn("alias matches current distinct_id - skipping api call."),this.identify(e),-1)):void 0}set_config(e){var s=b({},this.config);if(te(e)){var n,r,i,o,a,l,u,c,d,h,p,f;ee(this.config,Rl(e));var g=this.En();(n=this.persistence)==null||n.update_config(this.config,s,g),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new pi(b({},this.config,{persistence:"sessionStorage"}),g,!1);var m=this.Cn(this.config.debug);Ke(m)&&(this.config.debug=m),Ke(this.config.debug)&&(this.config.debug?(Y.DEBUG=!0,Q.N()&&Q.F("ph_debug",!0),k.info("set_config",{config:e,oldConfig:s,newConfig:b({},this.config)})):(Y.DEBUG=!1,Q.N()&&Q.q("ph_debug"))),(r=this.featureFlags)==null||r.updateConfig==null||r.updateConfig(this.config,this.Qi()),(i=this.exceptionObserver)==null||i.onConfigChange(),(o=this.exceptions)==null||o.onConfigChange(),(a=this.sessionRecording)==null||a.startIfEnabledOrStop(),(l=this.tracingHeaders)==null||l.startIfEnabledOrStop(),(u=this.autocapture)==null||u.startIfEnabled(),(c=this.heatmaps)==null||c.startIfEnabled(),(d=this.exceptionObserver)==null||d.startIfEnabledOrStop(),(h=this.deadClicksAutocapture)==null||h.startIfEnabledOrStop(),(p=this.surveys)==null||p.loadIfEnabled(),this.es(),(f=this.externalIntegrations)==null||f.startIfEnabledOrStop()}}_overrideSDKInfo(e,s){Y.LIB_NAME=e,Y.LIB_VERSION=s}startSessionRecording(e){var s,n,r,i,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)&&((s=this.sessionManager)==null||s.checkAndGetSessionAndWindowId(),l.sampling&&((n=this.sessionRecording)==null||n.overrideSampling()),l.linked_flag&&((r=this.sessionRecording)==null||r.overrideLinkedFlag()),l.url_trigger&&((i=this.sessionRecording)==null||i.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,s){if(this.exceptions){var n=new Error("PostHog syntheticException"),r=this.exceptions.buildProperties(e,{handled:!0,syntheticException:n});return this.exceptions.sendExceptionEvent(b({},r,s))}}addExceptionStep(e,s){var n;(n=this.exceptions)==null||n.addExceptionStep(e,s)}captureLog(e){var s;(s=this.logs)==null||s.captureLog(e)}get logger(){var e,s;return(e=(s=this.logs)==null?void 0:s.logger)!==null&&e!==void 0?e:Te.rs}startExceptionAutocapture(e){this.set_config({capture_exceptions:e==null||e})}stopExceptionAutocapture(){this.set_config({capture_exceptions:!1})}loadToolbar(e){var s,n;return(s=(n=this.toolbar)==null?void 0:n.loadToolbar(e))!==null&&s!==void 0&&s}get_property(e){var s;return(s=this.persistence)==null?void 0:s.props[e]}getSessionProperty(e){var s;return(s=this.sessionPersistence)==null?void 0:s.props[e]}toString(){var e,s=(e=this.config.name)!==null&&e!==void 0?e:os;return s!==os&&(s=os+"."+s),s}_isIdentified(){var e,s;return((e=this.persistence)==null?void 0:e.get_property(He))===Tt||((s=this.sessionPersistence)==null?void 0:s.get_property(He))===Tt}Zn(){var e,s;return!(this.config.person_profiles==="never"||this.config.person_profiles===ro&&!this._isIdentified()&&mt(this.getGroups())&&((e=this.persistence)==null||(e=e.props)==null||!e[Bs])&&((s=this.persistence)==null||(s=s.props)==null||!s[ir]))}zn(){return this.config.capture_pageleave===!0||this.config.capture_pageleave==="if_capture_pageview"&&(this.config.capture_pageview===!0||this.config.capture_pageview==="history_change")}createPersonProfile(){this.Zn()||this.Gn("posthog.createPersonProfile")&&this.setPersonProperties({},{})}setInternalOrTestUser(){this.Gn("posthog.setInternalOrTestUser")&&this.setPersonProperties({$internal_or_test_user:!0})}Gn(e){return this.config.person_profiles==="never"?(k.error(e+' was called, but process_person is set to "never". This call will be ignored.'),!1):(this.Kn(ir,!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!==Ht)}es(){var e,s,n,r,i=this.En();return((e=this.persistence)==null?void 0:e.xi)!==i&&((n=this.persistence)==null||n.set_disabled(i)),((s=this.sessionPersistence)==null?void 0:s.xi)!==i&&((r=this.sessionPersistence)==null||r.set_disabled(i)),i&&(this.yn.clear(),this.Qn()),i}opt_in_capturing(e){var s;if(this.config.cookieless_mode!==ht){if(this.gn()){var n,r,i,o,a;this.Yn(!0,!0),(n=this.sessionManager)==null||n.destroy(),(r=this.pageViewManager)==null||r.destroy(),this.sessionManager=new Cl(this),this.pageViewManager=new vl(this),this.persistence&&(this.sessionPropsManager=new Il(this,this.sessionManager,this.persistence));var l,u=(i=(o=this.config.__extensionClasses)==null?void 0:o.sessionRecording)!==null&&i!==void 0?i:(a=Te.__defaultExtensionClasses)==null?void 0:a.sessionRecording;u&&(this.sessionRecording=this.pn(this.sessionRecording,new u(this)),this.hn&&((l=this.sessionRecording)==null||l.onRemoteConfig==null||l.onRemoteConfig(this.hn)))}var c,d;this.consent.optInOut(!0),this.es(),this.Bn(),(s=this.sessionRecording)==null||s.startIfEnabledOrStop(),this.config.cookieless_mode==Ht&&((c=this.surveys)==null||c.loadIfEnabled()),(x(e?.captureEventName)||e!=null&&e.captureEventName)&&this.capture((d=e?.captureEventName)!==null&&d!==void 0?d:"$opt_in",e?.captureProperties,{send_instantly:!0}),this.config.capture_pageview&&this.Hn()}else k.warn(Al)}opt_out_capturing(){var e,s,n;this.config.cookieless_mode!==ht?(this.config.cookieless_mode===Ht&&this.consent.isOptedIn()&&this.Yn(!0,!0),this.consent.optInOut(!1),this.es(),this.config.cookieless_mode===Ht&&(this.register({distinct_id:En,$device_id:null}),(e=this.sessionRecording)==null||e.stopRecording(),this.sessionRecording=void 0,(s=this.sessionManager)==null||s.destroy(),(n=this.pageViewManager)==null||n.destroy(),this.sessionManager=void 0,this.sessionPropsManager=void 0,this.config.capture_pageview&&this.Hn(),this.Bn())):k.warn(Al)}has_opted_in_capturing(){return this.consent.isOptedIn()}has_opted_out_capturing(){return this.consent.isOptedOut()}get_explicit_consent_status(){var e=this.consent.consent;return e===1?"granted":e===0?"denied":"pending"}is_capturing(){return this.config.cookieless_mode===ht||(this.config.cookieless_mode===Ht?this.consent.isRejected()||this.consent.isOptedIn():!this.has_opted_out_capturing())}clear_opt_in_out_capturing(){this.consent.reset(),this.es()}_is_bot(){return ke?sd(ke,this.config.custom_blocked_useragents):void 0}Hn(){C&&(C.visibilityState==="visible"?this.wn||(this.wn=!0,this.capture(is,{title:C.title},{send_instantly:!0}),this.kn&&(C.removeEventListener(or,this.kn),this.kn=null)):this.kn||(this.kn=this.Hn.bind(this),re(C,or,this.kn)))}debug(e){e===!1?(v?.console.log("You've disabled debug mode."),this.set_config({debug:!1})):(v?.console.log("You're now in debug mode. All calls to PostHog will be logged in your console.\nYou can disable this with `posthog.debug(false)`."),this.set_config({debug:!0}))}Qi(){var e=this.Mn||{};return"advanced_disable_flags"in e?!!e.advanced_disable_flags:this.config.advanced_disable_flags!==!1?!!this.config.advanced_disable_flags:this.config.advanced_disable_decide===!0?(k.warn("Config field 'advanced_disable_decide' is deprecated. Please use 'advanced_disable_flags' instead. The old field will be removed in a future major version."),!0):(function(s,n,r,i,o){var a=n in s&&!D(s[n]),l=r in s&&!D(s[r]);return a?s[n]:!!l&&(o&&o.warn("Config field '"+r+"' is deprecated. Please use '"+n+"' instead. The old field will be removed in a future major version."),s[r])})(e,"advanced_disable_flags","advanced_disable_decide",0,k)}Pt(e){var s;if(D(this.config.before_send))return e;var n=Object.keys((s=e.properties)!==null&&s!==void 0?s:{}).filter(wh),r=L(this.config.before_send)?this.config.before_send:[this.config.before_send],i=e;for(var o of r){if(i=o(i),D(i)){var a="Event '"+e.event+"' was rejected in beforeSend function";return yh(e.event)?k.warn(a+". This can cause unexpected behavior."):k.info(a),null}i.properties&&!mt(i.properties)||k.warn("Event '"+e.event+"' has no properties after beforeSend function, this is likely an error.")}for(var l of n)if(i.properties&&D(i.properties[l]))return k.warn("Event '"+e.event+"' had its '"+l+"' property removed in a beforeSend function. This property is required for ingestion, so the event will be dropped."),null;return i}getPageViewId(){var e;return(e=this.pageViewManager.ui)==null?void 0:e.pageViewId}captureTraceFeedback(e,s){this.capture("$ai_feedback",{$ai_trace_id:String(e),$ai_feedback_text:s})}captureTraceMetric(e,s,n){this.capture("$ai_metric",{$ai_trace_id:String(e),$ai_metric_name:s,$ai_metric_value:String(n)})}Cn(e){var s=Ke(e)&&!e,n=Q.N()&&Q.P("ph_debug")==="true";return!s&&(!!n||e)}}Te.__defaultExtensionClasses={},Te.rs=(()=>{var t=()=>{};return{trace:t,debug:t,info:t,warn:t,error:t,fatal:t}})(),(function(t,e){for(var s=0;e.length>s;s++)t.prototype[e[s]]=lp(t.prototype[e[s]])})(Te,["identify"]);class Tl{constructor(e){this.disabled=e===!1;var s=te(e)?e:{};this.thresholdPx=s.threshold_px||30,this.timeoutMs=s.timeout_ms||1e3,this.clickCount=s.click_count||3,this.clicks=[]}isRageClick(e,s,n){if(this.disabled)return!1;var r=this.clicks[this.clicks.length-1];if(r&&Math.abs(e-r.x)+Math.abs(s-r.y)n-r.timestamp){if(this.clicks.push({x:e,y:s,timestamp:n}),this.clicks.length===this.clickCount)return!0}else this.clicks=[{x:e,y:s,timestamp:n}];return!1}}var Ei="$copy_autocapture",Si=se("[AutoCapture]");function xi(t,e){return e.length>t?e.slice(0,t)+"...":e}function pf(t){if(t.previousElementSibling)return t.previousElementSibling;var e=t;do e=e.previousSibling;while(e&&!Ft(e));return e}function ff(t,e){var s,n,r=e.e,i=e.maskAllElementAttributes,o=e.maskAllText,a=e.elementAttributeIgnoreList,l=e.elementsChainAsString,u=e.disableCaptureUrlHashes;if(!Ft(t))return{props:{}};for(var c=[t],d=new Set([t]),h=t;h.parentNode&&!Me(h,"body")&&Iu>c.length;)if(ku(h.parentNode)){var p=h.parentNode.host;if(d.has(p))break;d.add(p),c.push(p),h=p}else{if(!Ft(h.parentNode)||d.has(h.parentNode))break;d.add(h.parentNode),c.push(h.parentNode),h=h.parentNode}var f,g,m=[],_={},w=!1,E=!1;if(Z(c,(S=>{var A=ao(S);if(Me(S,"a")){var R=S.getAttribute("href");w=!!(A&&R&&Ks(R))&&(u?Ct(R):R)}M(cr(S),"ph-no-capture")&&(E=!0),m.push((function(T,O,J,z,H){H===void 0&&(H=!1);var oe=T.tagName.toLowerCase(),pe={tag_name:oe};Zo.indexOf(oe)>-1&&!J&&(pe.$el_text=oe.toLowerCase()==="a"||oe.toLowerCase()==="button"?xi(1024,fl(T)):xi(1024,nn(T)));var Ie=cr(T);Ie.length>0&&(pe.classes=Ie.filter((function(ae){return ae!==""}))),Z(T.attributes,(function(ae){var me;if((!$u(T)||["name","id","class","aria-label"].indexOf(ae.name)!==-1)&&(z==null||!z.includes(ae.name))&&!O&&Ks(ae.value)&&(!W(me=ae.name)||me.substring(0,10)!=="_ngcontent"&&me.substring(0,7)!=="_nghost")){var ge=ae.value;ae.name==="class"&&(ge=Yo(ge).join(" ")),pe["attr__"+ae.name]=xi(1024,ae.name==="href"&&H?Ct(ge):ge)}}));for(var _e=1,Ce=1,Re=T;Re=pf(Re);)_e++,Re.tagName===T.tagName&&Ce++;return pe.nth_child=_e,pe.nth_of_type=Ce,pe})(S,i,o,a,u));var N=(function(T){if(!ao(T))return{};var O={};return Z(T.attributes,(function(J){if(J.name&&J.name.indexOf("data-ph-capture-attribute")===0){var z=J.name.replace("data-ph-capture-attribute-",""),H=J.value;z&&H&&Ks(H)&&(O[z]=H)}})),O})(S);ee(_,N)})),E)return{props:{},explicitNoCapture:E};if(o||(m[0].$el_text=Me(t,"a")||Me(t,"button")?fl(t):nn(t)),w){var I,F;m[0].attr__href=w;var P=(I=ur(w))==null?void 0:I.host,B=v==null||(F=v.location)==null?void 0:F.host;P&&B&&P!==B&&(f=w)}return{props:ee({$event_type:r.type,$ce_version:1},l?{}:{$elements:m},{$elements_chain:(g=m,(function(S){return S.map((A=>{var R,N,T="";if(A.tag_name&&(T+=A.tag_name),A.attr_class)for(var O of(A.attr_class.sort(),A.attr_class))T+="."+O.replace(/"/g,"");var J=b({},A.text?{text:A.text}:{},{"nth-child":(R=A.nth_child)!==null&&R!==void 0?R:0,"nth-of-type":(N=A.nth_of_type)!==null&&N!==void 0?N:0},A.href?{href:A.href}:{},A.attr_id?{attr_id:A.attr_id}:{},A.attributes),z={};return Dn(J).sort(((H,oe)=>H[0].localeCompare(oe[0]))).forEach((H=>{var oe=H[1];return z[gl(H[0].toString())]=gl(oe.toString())})),(T+=":")+Dn(z).map((H=>H[0]+'="'+H[1]+'"')).join("")})).join(";")})((function(S){return S.map((A=>{var R,N,T={text:(R=A.$el_text)==null?void 0:R.slice(0,400),tag_name:A.tag_name,href:(N=A.attr__href)==null?void 0:N.slice(0,2048),attr_class:Cp(A),attr_id:A.attr__id,nth_child:A.nth_child,nth_of_type:A.nth_of_type,attributes:{}};return Dn(A).filter((O=>O[0].indexOf("attr__")===0)).forEach((O=>T.attributes[O[0]]=O[1])),T}))})(g)))},(s=m[0])!=null&&s.$el_text?{$el_text:(n=m[0])==null?void 0:n.$el_text}:{},f&&r.type==="click"?{$external_click_url:f}:{},_)}}var Ms=se("[ExceptionAutocapture]"),Nl=()=>{},gf=se("[TracingHeaders]"),Lt=se("[Web Vitals]"),Ml=9e5,Ll="disabled",Ol="lazy_loading",Ls="awaiting_config",Pn="missing_config";se("[SessionRecording]"),se("[SessionRecording]");var mo="[SessionRecording]",at=se(mo),mf=se("[Heatmaps]");function ki(t){return te(t)&&"clientX"in t&&"clientY"in t&&he(t.clientX)&&he(t.clientY)}var An=se("[Product Tours]"),Ii=t=>{var e;return!t.config.disable_product_tours&&!((e=t.persistence)==null||!e.get_property(Vo))},vf=["$set_once","$set"],Ze=se("[SiteApps]"),Dl="Error while initializing PostHog app with config id ";function ns(t,e,s){if(D(t))return!1;switch(s){case"exact":return t===e;case"contains":var n=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/_/g,".").replace(/%/g,".*");return new RegExp(n,"i").test(t);case"regex":try{return new RegExp(e).test(t)}catch{return!1}default:return!1}}class _f{constructor(e){this.ns=new ta,this.ss=(s,n)=>this.os(s,n)&&this.ls(s,n)&&this.us(s,n)&&this.hs(s,n),this.os=(s,n)=>n==null||!n.event||s?.event===n?.event,this._instance=e,this.ds=new Set,this.vs=new Set}init(){var e,s;x((e=this._instance)==null?void 0:e._addCaptureHook)||(s=this._instance)==null||s._addCaptureHook(((n,r)=>{this.on(n,r)}))}register(e){var s,n;if(!x((s=this._instance)==null?void 0:s._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||"")}))})),(n=this._instance)!=null&&n.autocapture)){var r,i=new Set;e.forEach((o=>{var a;(a=o.steps)==null||a.forEach((l=>{l!=null&&l.selector&&i.add(l?.selector)}))})),(r=this._instance)==null||r.autocapture.setElementSelectors(i)}}on(e,s){var n;s!=null&&e.length!=0&&(this.ds.has(e)||this.ds.has(s.event))&&this.vs&&((n=this.vs)==null?void 0:n.size)>0&&this.vs.forEach((r=>{this.cs(s,r)&&this.ns.emit("actionCaptured",r.name)}))}fs(e){this.onAction("actionCaptured",(s=>e(s)))}cs(e,s){if(s?.steps==null)return!1;for(var n of s.steps)if(this.ss(e,n))return!0;return!1}onAction(e,s){return this.ns.on(e,s)}ls(e,s){if(s!=null&&s.url){var n,r=e==null||(n=e.properties)==null?void 0:n.$current_url;if(!r||typeof r!="string"||!ns(r,s.url,s.url_matching||"contains"))return!1}return!0}us(e,s){return!!this.ps(e,s)&&!!this.gs(e,s)&&!!this.ys(e,s)}ps(e,s){var n;if(s==null||!s.href)return!0;var r=this.bs(e);if(r.length>0)return r.some((a=>ns(a.href,s.href,s.href_matching||"exact")));var i,o=(e==null||(n=e.properties)==null?void 0:n.$elements_chain)||"";return!!o&&ns((i=o.match(/(?::|")href="(.*?)"/))?i[1]:"",s.href,s.href_matching||"exact")}gs(e,s){var n;if(s==null||!s.text)return!0;var r=this.bs(e);if(r.length>0)return r.some((u=>ns(u.text,s.text,s.text_matching||"exact")||ns(u.$el_text,s.text,s.text_matching||"exact")));var i,o,a,l=(e==null||(n=e.properties)==null?void 0:n.$elements_chain)||"";return!!l&&(i=(function(u){for(var c,d=[],h=/(?::|")text="(.*?)"/g;!D(c=h.exec(u));)d.includes(c[1])||d.push(c[1]);return d})(l),o=s.text,a=s.text_matching||"exact",i.some((u=>ns(u,o,a))))}ys(e,s){var n,r;if(s==null||!s.selector)return!0;var i=e==null||(n=e.properties)==null?void 0:n.$element_selectors;if(i!=null&&i.includes(s.selector))return!0;var o=(e==null||(r=e.properties)==null?void 0:r.$elements_chain)||"";if(s.selector_regex&&o)try{return new RegExp(s.selector_regex).test(o)}catch{return!1}return!1}bs(e){var s;return(e==null||(s=e.properties)==null?void 0:s.$elements)==null?[]:e?.properties.$elements}hs(e,s){return s==null||!s.properties||s.properties.length===0||id(s.properties.reduce(((n,r)=>{var i=L(r.value)?r.value.map(String):r.value!=null?[String(r.value)]:[];return n[r.key]={values:i,operator:r.operator||"exact"},n}),{}),e?.properties)}}class yf{constructor(e){var s;this._s=[],this._instance=e,this.ws=new Map,this.ks=new Map,this.xs=new Map,(s=this._instance)==null||s.onSessionId==null||s.onSessionId((n=>this.Ss(n)))}Cs(e){return!1}Ms(){return null}Ts(e){}Es(){}Is(e,s){return!!e&&id(e.propertyFilters,s?.properties)}Ps(e,s){var n=new Map;return e.forEach((r=>{var i;(i=r.conditions)==null||(i=i[s])==null||(i=i.values)==null||i.forEach((o=>{if(o!=null&&o.name){var a=n.get(o.name)||[];a.push(r.id),n.set(o.name,a)}}))})),n}Rs(e,s,n){var r=(n===As.Activation?this.ws:this.ks).get(e),i=[];return this.As((o=>{i=o.filter((a=>r?.includes(a.id)))})),i.filter((o=>{var a,l=(a=o.conditions)==null||(a=a[n])==null||(a=a.values)==null?void 0:a.find((u=>u.name===e));return this.Is(l,s)}))}register(e){var s;x((s=this._instance)==null?void 0:s._addCaptureHook)||(this.Fs(e),this.Ls(e))}Ls(e){var s=e.filter((n=>{var r,i;return((r=n.conditions)==null?void 0:r.actions)&&((i=n.conditions)==null||(i=i.actions)==null||(i=i.values)==null?void 0:i.length)>0}));s.length!==0&&(this.Os==null&&(this.Os=new _f(this._instance),this.Os.init(),this.Os.fs((n=>{this.onAction(n)}))),s.forEach((n=>{var r,i,o,a,l;n.conditions&&(r=n.conditions)!=null&&r.actions&&(i=n.conditions)!=null&&(i=i.actions)!=null&&i.values&&((o=n.conditions)==null||(o=o.actions)==null||(o=o.values)==null?void 0:o.length)>0&&((a=this.Os)==null||a.register(n.conditions.actions.values),(l=n.conditions)==null||(l=l.actions)==null||(l=l.values)==null||l.forEach((u=>{if(u&&u.name){var c=this.xs.get(u.name);c&&c.push(n.id),this.xs.set(u.name,c||[n.id])}})))})))}Fs(e){var s,n=e.filter((i=>{var o,a;return((o=i.conditions)==null?void 0:o.events)&&((a=i.conditions)==null||(a=a.events)==null||(a=a.values)==null?void 0:a.length)>0})),r=e.filter((i=>{var o,a;return((o=i.conditions)==null?void 0:o.cancelEvents)&&((a=i.conditions)==null||(a=a.cancelEvents)==null||(a=a.values)==null?void 0:a.length)>0}));n.length===0&&r.length===0||((s=this._instance)==null||s._addCaptureHook(((i,o)=>{this.onEvent(i,o)})),this.ws=this.Ps(e,As.Activation),this.ks=this.Ps(e,As.Cancellation))}onEvent(e,s){var n,r,i=this.Ds(),o=(s==null||(n=s.properties)==null?void 0:n.$survey_id)||(s==null||(r=s.properties)==null?void 0:r.$product_tour_id);if(o&&this.getActivatedIds().includes(o)){var a=this.$s(e,o);if(a==="consume")return i.info("event consumed activated item, removing it",{event:e,itemId:o}),void this.Ns([o]);if(a==="persist")return i.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,s,As.Cancellation);l.length>0&&(i.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)){i.info("event name matched",{event:e,eventPayload:s,items:this.ws.get(e)});var u=this.Rs(e,s,As.Activation);this.Hs(u.map((c=>c.id)))}}onAction(e){this.xs.has(e)&&this.Hs(this.xs.get(e)||[])}Hs(e){var s;if(e.length!==0){var n=!((s=this._instance)==null||s.get_session_id==null||!s.get_session_id()),r=[];for(var i of e)n&&this.Cs(i)?this.qs(i)&&this.Us(i):r.push(i);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((n=>n!==e));var s=this.zs();return!s.includes(e)&&(this.Ws([...s,e]),this.Vs(),!0)}Ns(e){var s=new Set(e);this._s=this._s.filter((i=>!s.has(i)));var n=this.Zs(),r=n.filter((i=>!s.has(i)));r.length!==n.length&&(this.Ws(r),r.length===0&&this.Gs()),this.js(e)}Qs(){var e,s=this.Ms();if(!s)return{};var n=(e=this._instance)==null||(e=e.persistence)==null?void 0:e.props[s];return n&&typeof n=="object"?n:{}}Us(e){if(this.Ms()){var s=this.Qs();this.Ts(b({},s,{[e]:Date.now()}))}}js(e){if(this.Ms()){var s=this.Qs(),n={},r=!1;for(var i of Object.entries(s)){var o=i[0],a=i[1];e.includes(o)?r=!0:n[o]=a}r&&(mt(n)?this.Es():this.Ts(n))}}Ks(){this.Ms()&&this.Es()}getActivationTimestamp(e){if(this.zs().includes(e)){var s=this.Qs()[e];return he(s)?s:void 0}}Zs(){var e,s=this.Js();return((e=this._instance)==null||(e=e.persistence)==null?void 0:e.props[s])||[]}zs(){var e,s,n=this.Zs();if(n.length===0)return[];var r=(e=this._instance)==null||(e=e.persistence)==null?void 0:e.props[this.Ys()],i=(s=this._instance)==null||s.get_session_id==null?void 0:s.get_session_id();return i&&r===i?n:[]}Vs(){var e,s=(e=this._instance)==null||e.get_session_id==null?void 0:e.get_session_id();s&&this.Xs(s)}Gs(){this.ta()}Ss(e){var s,n=(s=this._instance)==null||(s=s.persistence)==null?void 0:s.props[this.Ys()];if(n&&n!==e){var r=this.Zs(),i=this.Qs();r.length>0&&(this.Ws([]),r.filter((o=>he(i[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 wf extends yf{constructor(e){super(e)}Js(){return Qi}Ys(){return Mn}Ms(){return Ln}Ts(e){var s;(s=this._instance)==null||(s=s.persistence)==null||s.register({[Ln]:e})}Es(){var e;(e=this._instance)==null||(e=e.persistence)==null||e.unregister(Ln)}Cs(e){var s,n;this.As((i=>{n=i.find((o=>o.id===e))}));var r=(s=n)==null||(s=s.appearance)==null?void 0:s.surveyPopupDelaySeconds;return he(r)&&r>0}ra(){return ft.SHOWN}As(e){var s;(s=this._instance)==null||s.getSurveys(e)}Bs(e){var s;(s=this._instance)==null||s.cancelPendingSurvey(e)}Ds(){return q}Ws(e){var s;(s=this._instance)==null||(s=s.persistence)==null||s.register({[Qi]:e})}Xs(e){var s;(s=this._instance)==null||(s=s.persistence)==null||s.register({[Mn]:e})}ta(){var e;(e=this._instance)==null||(e=e.persistence)==null||e.unregister(Mn)}ea(){return!1}$s(e,s){var n;this.As((i=>{n=i.find((o=>o.id===s))}));var r=!n||(function(i){var o;return od(i)&&!((o=i.conditions)==null||(o=o.events)==null||!o.repeatedActivation)||i.schedule==="always"})(n);return r?e===ft.SHOWN?"consume":"ignore":e===ft.SHOWN?"persist":e===ft.DISMISSED||e===ft.SENT?"consume":"ignore"}getSurveys(){return this.getActivatedIds()}getEventToSurveys(){return this.getEventToItemsMap()}}var $n="SDK is not enabled or survey functionality is not yet loaded",Bl="Disabled. Not loading surveys.",bf=v!=null&&v.location?dr(v.location.hash,"__posthog")||dr(location.hash,"state"):null,jl="_postHogToolbarParams",Ul=se("[Toolbar]"),Hl=se("[FeatureFlags]");class Ef{constructor(e,s){s===void 0&&(s=!1),this.na=!1,this.update(e,s)}update(e,s){this.sa=((n,r)=>{var i,o,a,l;return{bootstrap:{featureFlags:(i=n.bootstrap)==null?void 0:i.featureFlags,featureFlagPayloads:(o=n.bootstrap)==null?void 0:o.featureFlagPayloads},remoteRequestsDisabled:r,featureFlagsDisabled:!!n.advanced_disable_feature_flags,onlyEvaluateSurveyFeatureFlags:!!n.advanced_only_evaluate_survey_feature_flags,deduplicateCallsPerSession:!!n.advanced_feature_flags_dedup_per_session,cacheTtlMs:n.feature_flag_cache_ttl_ms,requestTimeoutMs:n.feature_flag_request_timeout_ms,compression:n.disable_compression?"none":"base64",evaluationContexts:(a=(l=n.evaluation_contexts)!==null&&l!==void 0?l:n.evaluation_environments)!==null&&a!==void 0?a:[],flagKeys:L(n.flag_keys)?n.flag_keys:void 0}})(e,s),!e.evaluation_environments||e.evaluation_contexts||this.na||(Hl.warn("evaluation_environments is deprecated. Use evaluation_contexts instead. evaluation_environments will be removed in a future version."),this.na=!0),x(e.flag_keys)||L(e.flag_keys)||Hl.error("Invalid flag_keys found:",e.flag_keys,"Expected array of non-empty strings")}get(){return this.sa}}var Wl=se("[FeatureFlags]"),Ot=se("[FeatureFlags]",{debugEnabled:!0}),Ci=`" failed. Feature flags didn't load in time.`,zl="connection_error",ql=t=>{for(var e={},s=0;t.length>s;s++)e[t[s]]=!0;return e},Vl=t=>{var e={};for(var s of Dn(t||{})){var n=s[1];n&&(e[s[0]]=n)}return e},Xe=se("[Error tracking]"),Gl="Refusing to render web experiment since the viewer is a likely bot",Sf={icontains:(t,e)=>e.toLowerCase().indexOf(t.toLowerCase())>-1,not_icontains:(t,e)=>e.toLowerCase().indexOf(t.toLowerCase())===-1,regex:(t,e)=>fr(e,t),not_regex:(t,e)=>!fr(e,t),exact:(t,e)=>e===t,is_not:(t,e)=>e!==t};class ye{get Ne(){return this._instance.config}constructor(e){var s=this;this.getWebExperimentsAndEvaluateDisplayLogic=function(n){n===void 0&&(n=!1),s.getWebExperiments((r=>{ye.aa("retrieved web experiments from the server"),s.oa=new Map,r.forEach((i=>{if(i.feature_flag_key){var o;s.oa&&(ye.aa("setting flag key ",i.feature_flag_key," to web experiment ",i),(o=s.oa)==null||o.set(i.feature_flag_key,i));var a=s._instance.getFeatureFlag(i.feature_flag_key);W(a)&&i.variants[a]&&s.la(i.name,a,i.variants[a].transforms)}else if(i.variants)for(var l in i.variants){var u=i.variants[l];ye.ua(u,s._instance)&&s.la(i.name,l,u.transforms)}}))}),n)},this._instance=e,this._instance.onFeatureFlags((n=>{this.onFeatureFlags(n)}))}initialize(){}onFeatureFlags(e){if(this._is_bot())ye.aa(Gl);else if(!this.Ne.disable_web_experiments){if(D(this.oa))return this.oa=new Map,this.loadIfEnabled(),void this.previewWebExperiment();ye.aa("applying feature flags",e),e.forEach((s=>{var n;if(this.oa&&(n=this.oa)!=null&&n.has(s)){var r,i=this._instance.getFeatureFlag(s),o=(r=this.oa)==null?void 0:r.get(s);i&&o!=null&&o.variants[i]&&this.la(o.name,i,o.variants[i].transforms)}}))}}previewWebExperiment(){var e=ye.getWindowLocation();if(e!=null&&e.search){var s=ms(e?.search,"__experiment_id"),n=ms(e?.search,"__experiment_variant");s&&n&&(ye.aa("previewing web experiments "+s+" && "+n),this.getWebExperiments((r=>{this.ha(parseInt(s),n,r)}),!1,!0))}}loadIfEnabled(){this.Ne.disable_web_experiments||this.getWebExperimentsAndEvaluateDisplayLogic()}getWebExperiments(e,s,n){if(this.Ne.disable_web_experiments&&!n)return e([]);var r=this._instance.get_property("$web_experiments");if(r&&!s)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:i=>e(i.statusCode===200&&i.json&&i.json.experiments||[])})}ha(e,s,n){var r=n.filter((i=>i.id===e));r&&r.length>0&&(ye.aa("Previewing web experiment ["+r[0].name+"] with variant ["+s+"]"),this.la(r[0].name,s,r[0].variants[s].transforms))}static ua(e,s){return!D(e.conditions)&&ye.da(e,s)&&ye.va(e)}static da(e,s){var n;if(D(e.conditions)||D((n=e.conditions)==null?void 0:n.url))return!0;var r=ye.getWindowLocation();if(r){var i,o,a,l=Eu(s,r.href);return(i=e.conditions)==null||!i.url||Sf[(o=(a=e.conditions)==null?void 0:a.urlMatchType)!==null&&o!==void 0?o:"icontains"](e.conditions.url,l)}return!1}static getWindowLocation(){return v?.location}static va(e){var s;if(D(e.conditions)||D((s=e.conditions)==null?void 0:s.utm))return!0;var n=Ou();if(n.utm_source){var r,i,o,a,l,u,c,d,h=(r=e.conditions)==null||(r=r.utm)==null||!r.utm_campaign||((i=e.conditions)==null||(i=i.utm)==null?void 0:i.utm_campaign)==n.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)==n.utm_source,f=(l=e.conditions)==null||(l=l.utm)==null||!l.utm_medium||((u=e.conditions)==null||(u=u.utm)==null?void 0:u.utm_medium)==n.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)==n.utm_term;return h&&f&&g&&p}return!1}static aa(e){for(var s=arguments.length,n=new Array(s>1?s-1:0),r=1;s>r;r++)n[r-1]=arguments[r];k.info("[WebExperiments] "+e,n)}la(e,s,n){this._is_bot()?ye.aa(Gl):s!=="control"?n.forEach((r=>{if(r.selector){var i;ye.aa("applying transform of variant "+s+" for experiment "+e+" ",r);var o=(i=document)==null?void 0:i.querySelectorAll(r.selector);o?.forEach((a=>{var l=a;r.html&&(l.innerHTML=r.html),r.css&&l.setAttribute("style",r.css)}))}})):ye.aa("Control variants leave the page unmodified.")}_is_bot(){return ke&&this._instance?sd(ke,this.Ne.custom_blocked_useragents):void 0}}var Ue=se("[Conversations]"),Dt="Conversations not available yet.",Kl="console",dd="__posthogHandledLogsRequestError",Fi=(t,e)=>{var s=t instanceof Error?t:new Error(e);return s[dd]=!0,s},Jl=t=>!!t&&typeof t=="object"&&t[dd]===!0,Tr={featureFlags:class{constructor(t){this.name="featureFlags",this.ca=!1,this.featureFlagEventHandlers=[],this.rt=Wl,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 Ef(t.config,t.Qi()),this.Ta=this.Ea)}updateConfig(t,e){var s;(s=this.Ea)==null||s.update(t,e)}setup(t){return this.Ia=t,this.rt=t.logger.createLogger("[FeatureFlags]"),s=()=>{this.Ia===t&&(this.Ia=void 0,this.nn=t,this.Pa(t))},(e=t.kv.initialize())!=null&&e.then?e.then(s):s();var e,s}Pa(t){if(this.nn===t)return v&&re(v,"online",this.Ca),this.Ra=t.registerDynamicEventProperties((()=>this.Aa()?this.fa:this.pa)),this.Fa(),this.initialize()}destroy(){v?.removeEventListener("online",this.Ca)}dispose(){var t;this.ba++,this.wa=!1,this.Ia=void 0,this.nn&&(this.La(),(t=this.Ra)==null||t.dispose(),this.Ra=void 0,this.ga=[],v?.removeEventListener("online",this.Ca),this.nn=void 0)}get Ne(){return this.Ta.get()}Oa(t){var e;return(e=this.nn)==null?void 0:e.kv.get(t)}F(t){this.Da((()=>{var e;return(e=this.nn)==null?void 0:e.kv.set(t)}))}q(t){this.Da((()=>{var e;return(e=this.nn)==null?void 0:e.kv.remove(t)}))}Da(t){try{t()}catch(e){this.rt.error("Failed to update feature flag persistence",e)}}Fa(){var t={};for(var e of[Us,Hs,Nn,et]){var s=this.Oa(e);x(s)||(t[e]=s)}this.fa=t;var n=b({},t),r=this.Oa(Bt);if(r)for(var i of Object.entries(r))n["$feature/"+i[0]]=i[1];this.pa=n}Aa(){var t=this.Ne.cacheTtlMs;if(!t||0>=t)return!1;var e=this.Oa(Gs);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 s=e&&typeof e=="string"&&e.trim().length>0;return s||this.rt.error("Invalid evaluation context found:",e,"Expected non-empty string"),s})):[]}qa(){var t=this.Ne.flagKeys;if(!x(t))return t.filter((e=>{var s=e&&typeof e=="string"&&e.trim().length>0;return s||this.rt.error("Invalid flag key found:",e,"Expected non-empty string"),s}))}initialize(){var t,e,s=this.Ne,n=(t=(e=s.bootstrap)==null?void 0:e.featureFlags)!==null&&t!==void 0?t:{};if(Object.keys(n).length){var r,i,o=(r=(i=s.bootstrap)==null?void 0:i.featureFlagPayloads)!==null&&r!==void 0?r:{},a=Object.keys(n).filter((u=>!!n[u])).reduce(((u,c)=>(u[c]=n[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,s){var n,r,i=s!=null&&s.merge&&(n=this.Oa(Bt))!==null&&n!==void 0?n:{},o=s!=null&&s.merge&&(r=this.Oa(Hs))!==null&&r!==void 0?r:{},a=b({},i,t),l=b({},o,e),u={};for(var c of Object.entries(a)){var d=c[0],h=c[1];u[d]={key:d,enabled:Ua(h),variant:Ha(h),reason:void 0,metadata:x(l?.[d])?void 0:{id:0,version:void 0,description:void 0,payload:l[d]}}}this.ja({flags:u})}get hasLoadedFlags(){return this.ma}getFlags(){return Object.keys(this.getFlagVariants())}getFlagsWithDetails(){var t=this.Oa(Zi),e=this.Oa(et),s=this.Oa(jt);if(!s&&!e)return t||{};var n=ee({},t||{}),r=[...new Set([...Object.keys(s||{}),...Object.keys(e||{})])];for(var i of r){var o,a,l=n[i],u=e?.[i],c=x(u)?(o=l?.enabled)!==null&&o!==void 0&&o:!!u,d=x(u)?l?.variant:typeof u=="string"?u:void 0,h=s?.[i],p=b({},l,{enabled:c,variant:c?d??l?.variant:void 0});c!==l?.enabled&&(p.original_enabled=l?.enabled),d!==l?.variant&&(p.original_variant=l?.variant),h&&(p.metadata=b({},l?.metadata,{payload:h,original_payload:l==null||(a=l.metadata)==null?void 0:a.payload})),n[i]=p}return this.ca||(this.rt.warn(" Overriding feature flag details!",{flagDetails:t,overriddenPayloads:s,finalDetails:n}),this.ca=!0),n}getAllFeatureFlags(){var t=this.getFlagVariants(),e=this.getFlagPayloads();return Object.keys(t).map((s=>{var n=t[s];return{key:s,enabled:Ua(n),variant:Ha(n),payload:ja(e[s])}}))}getFlagVariants(){var t=this.Oa(Bt),e=this.Oa(et);if(!e)return t||{};for(var s=ee({},t||{}),n=Object.keys(e),r=0;n.length>r;r++)s[n[r]]=e[n[r]];return this.ca||(this.rt.warn(" Overriding feature flags!",{enabledFlags:t,overriddenFlags:e,finalFlags:s}),this.ca=!0),s}getFlagPayloads(){var t=this.Oa(Hs),e=this.Oa(jt);if(!e)return t||{};for(var s=ee({},t||{}),n=Object.keys(e),r=0;n.length>r;r++)s[n[r]]=e[n[r]];return this.ca||(this.rt.warn(" Overriding feature flag payloads!",{flagPayloads:t,overriddenPayloads:e,finalPayloads:s}),this.ca=!0),s}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(Wt)}Ha(t){this.La();var e=this.nn;if(e&&!this.Ne.remoteRequestsDisabled&&!this.Ma())if(this.ya)this.wa=!0;else{var s={token:e.projectToken,distinct_id:e.distinctId,groups:e.groups,$anon_distinct_id:this.$anon_distinct_id,person_properties:b({},e.initialPersonProperties,this.Oa(ct)||{},{$lib:e.library.name,$lib_version:e.library.version}),group_properties:this.Oa(Ut),timezone:Wu()};x(e.deviceId)||(s.$device_id=e.deviceId),(t!=null&&t.disableFlags||this.Ne.featureFlagsDisabled)&&(s.disable_flags=!0);var n=this.Na();n.length&&(s.evaluation_contexts=n);var r=this.qa();x(r)||(s.flag_keys=r);var i=this.Ne.onlyEvaluateSurveyFeatureFlags,o="/flags/?v=2"+(i?"&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({[On]:[zl]}),this.rt.error("Feature flag request failed",c)),l()};try{e.sendRequest(o,{target:"flags",method:"POST",body:s,compression:this.Ne.compression==="base64"?xe.Base64:void 0,sentAt:"body",timeoutMs:this.Ne.requestTimeoutMs}).then((c=>{var d,h,p=(d=c.json)!==null&&d!==void 0?d:{},f=c.statusCode!==200;if(this.ya=!1,a===this.ba){if(this.Ua(c.statusCode),f||this.wa||(this.$anon_distinct_id=void 0),!s.disable_flags||this.wa){this.ka=!f;var g=[];c.error?g.push(c.error instanceof Error&&c.error.name==="AbortError"?"timeout":c.error instanceof Error?zl:"unknown_error"):c.statusCode!==200&&g.push("api_error_"+c.statusCode),p.errorsWhileComputingFlags&&g.push("errors_while_computing_flags");var m=!((h=p.quotaLimited)==null||!h.includes("feature_flags"));m&&g.push("quota_limited"),this.F({[On]: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."):s.disable_flags||this.ja(p,f,{partialResponse:i}),l()}}else l()})).catch(u)}catch(c){u(c)}}}Ma(){return Mu(this.Sa,3)}Ua(t){this.Sa=Lu(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 s;if(e===void 0&&(e={}),!e.fresh||this.ka)if(this.ma||this.getFlags()&&this.getFlags().length>0){if(!this.$a()){var n=this.getFeatureFlagResult(t,e);return(s=n?.variant)!==null&&s!==void 0?s:n?.enabled}}else this.rt.warn('getFeatureFlag for key "'+t+Ci)}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 s,n=this.getFlagVariants(),r=t in n,i=n[t],o=this.getFlagPayloads()[t],a=String(i),l=this.Oa(Nn)||void 0,u=this.Oa(Gs)||void 0,c=this.Oa(Wt)||{};if(this.Ne.deduplicateCallsPerSession){var d,h=(d=this.nn)==null?void 0:d.session.sessionId,p=this.Oa(zs);h&&h!==p&&(c={},s=h)}if(e.send_event||!("send_event"in e))if(t in c&&c[t].includes(a))s&&this.F({[Wt]:c,[zs]:s});else{var f,g,m,_,w,E,I,F,P,B;L(c[t])?c[t].push(a):c[t]=[a],this.F(b({[Wt]:c},s?{[zs]:s}:{}));var S=this.getFeatureFlagDetails(t),A=[...(f=this.Oa(On))!==null&&f!==void 0?f:[]];x(i)&&A.push("flag_missing");var R={$feature_flag:t,$feature_flag_response:i,$feature_flag_payload:o||null,$feature_flag_request_id:l,$feature_flag_evaluated_at:u,$feature_flag_bootstrapped_response:((g=this.Ne.bootstrap)==null||(g=g.featureFlags)==null?void 0:g[t])||null,$feature_flag_bootstrapped_payload:((m=this.Ne.bootstrap)==null||(m=m.featureFlagPayloads)==null?void 0:m[t])||null,$used_bootstrap_value:!this.ka};x(S==null||(_=S.metadata)==null?void 0:_.has_experiment)||(R.$feature_flag_has_experiment=S.metadata.has_experiment),x(S==null||(w=S.metadata)==null?void 0:w.version)||(R.$feature_flag_version=S.metadata.version);var N,T=(E=S==null||(I=S.reason)==null?void 0:I.description)!==null&&E!==void 0?E:S==null||(F=S.reason)==null?void 0:F.code;T&&(R.$feature_flag_reason=T),S!=null&&(P=S.metadata)!=null&&P.id&&(R.$feature_flag_id=S.metadata.id),x(S?.original_variant)&&x(S?.original_enabled)||(R.$feature_flag_original_response=x(S.original_variant)?S.original_enabled:S.original_variant),S!=null&&(B=S.metadata)!=null&&B.original_payload&&(R.$feature_flag_original_payload=S==null||(N=S.metadata)==null?void 0:N.original_payload),A.length&&(R.$feature_flag_error=A.join(",")),this.za(R)}else s&&this.F({[Wt]:c,[zs]:s});if(r)return{key:t,enabled:!!i,variant:typeof i=="string"?i:void 0,payload:ja(o)}}}else this.rt.warn('getFeatureFlagResult for key "'+t+Ci)}za(t){try{var e;(e=this.nn)==null||e.capture("$feature_flag_called",t).catch((s=>{this.rt.error("Failed to capture feature flag call",s)}))}catch(s){this.rt.error("Failed to capture feature flag call",s)}}getRemoteConfigPayload(t,e){this.Wa(t,e)}Wa(t,e){var s=this;return X((function*(){var n=s.nn;if(n){var r={distinct_id:n.distinctId,token:n.projectToken,person_properties:{$lib:n.library.name,$lib_version:n.library.version}},i=s.Na();i.length&&(r.evaluation_contexts=i);var o,a=s.qa();x(a)||(r.flag_keys=a);try{var l,u=(l=(yield n.sendRequest("/flags/?v=2",{target:"flags",method:"POST",body:r,compression:s.Ne.compression==="base64"?xe.Base64:void 0,sentAt:"body",timeoutMs:s.Ne.requestTimeoutMs})).json)==null?void 0:l.featureFlagPayloads;o=u?.[t]||void 0}catch(c){return void s.rt.error("Remote config feature flag request failed",c)}try{e(o)}catch(c){s.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+Ci),e.defaultValue;var s=this.getFeatureFlag(t,e);return x(s)?e.defaultValue:!!s}addFeatureFlagsHandler(t){this.featureFlagEventHandlers.push(t)}removeFeatureFlagsHandler(t){this.featureFlagEventHandlers=this.featureFlagEventHandlers.filter((e=>e!==t))}receivedFeatureFlags(t,e,s){this.ja(t,e,s)}ja(t,e,s){if(this.nn){this.ma=!0;var n=(function(r,i,o,a,l,u){i===void 0&&(i={}),o===void 0&&(o={}),a===void 0&&(a={}),u===void 0&&(u=Wl);var c=((P,B)=>{var S=P.flags;return S?b({},P,{featureFlags:Object.fromEntries(Object.keys(S).map((A=>{var R;return[A,(R=S[A].variant)!==null&&R!==void 0?R:S[A].enabled]}))),featureFlagPayloads:Object.fromEntries(Object.keys(S).filter((A=>S[A].enabled)).filter((A=>{var R;return(R=S[A].metadata)==null?void 0:R.payload})).map((A=>{var R;return[A,(R=S[A].metadata)==null?void 0:R.payload]})))}):(P.featureFlags&&B.warn("Using an older version of the feature flags endpoint. Please upgrade your PostHog server to the latest version"),P)})(r,u),d=c.flags,h=c.featureFlags,p=c.featureFlagPayloads;if(h){var f=r.requestId,g=r.evaluatedAt;if(L(h)){u.warn("v1 of the feature flags endpoint is deprecated. Please use the latest version.");var m={};if(h)for(var _=0;h.length>_;_++)m[h[_]]=!0;return{[Us]:h,[Bt]:m,[sr]:!1}}var w=h,E=p,I=d;if(l!=null&&l.partialResponse)w=b({},i,w),E=b({},o,E),I=b({},a,I);else if(r.errorsWhileComputingFlags)if(d){var F=new Set(Object.keys(d).filter((P=>{var B;return!((B=d[P])!=null&&B.failed)})));w=b({},i,Object.fromEntries(Object.entries(w).filter((P=>F.has(P[0]))))),E=b({},o,Object.fromEntries(Object.entries(E||{}).filter((P=>F.has(P[0]))))),I=b({},a,Object.fromEntries(Object.entries(I||{}).filter((P=>F.has(P[0])))))}else w=b({},i,w),E=b({},o,E),I=b({},a,I);return b({[Us]:Object.keys(Vl(w)),[Bt]:w||{},[Hs]:E||{},[Zi]:I||{},[sr]:r.minimalFlagCalledEvents===!0},f?{[Nn]:f}:{},g?{[Gs]:g}:{})}})(t,this.getFlagVariants(),this.getFlagPayloads(),this.getFlagsWithDetails(),s,this.rt);n&&this.F(n),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([et,jt]),this.Va(),void Ot.info("All overrides cleared");if(L(t))return this.F({[et]:ql(t)}),this.Va(),void Ot.info("Flag overrides set",{flags:t});if(t&&typeof t=="object"&&("flags"in t||"payloads"in t)){var e,s=t;this.ca=!!((e=s.suppressWarning)!==null&&e!==void 0&&e);var n={},r=s.flags,i=s.payloads;return r&&(n[et]=L(r)?ql(r):r),i&&(n[jt]=i),Object.keys(n).length&&this.F(n),r===!1&&i===!1?this.q([et,jt]):r===!1?this.q(et):i===!1&&this.q(jt),this.Va(),r===!1?Ot.info("Flag overrides cleared"):r&&Ot.info("Flag overrides set",{flags:r}),void(i===!1?Ot.info("Payload overrides cleared"):i&&Ot.info("Payload overrides set",{payloads:i}))}if(t&&typeof t=="object")return this.F({[et]:t}),this.Va(),void Ot.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(),s=e.flags,n=e.flagVariants;try{t(s,n)}catch(r){this.rt.error("Error while running feature flags callback",r)}}return()=>this.removeFeatureFlagsHandler(t)}updateEarlyAccessFeatureEnrollment(t,e,s){var n=(this.Oa(Tn)||[]).find((l=>l.flagKey===t)),r={["$feature_enrollment/"+t]:e},i={$feature_flag:t,$feature_enrollment:e,$set:r};n&&(i.$early_access_feature_name=n.name),s&&(i.$feature_enrollment_stage=s);var o=b({},this.getFlagVariants(),{[t]:e});this.F({[Us]:Object.keys(Vl(o)),[Bt]:o,[ct]:b({},this.Oa(ct)||{},r)}),this.Va();try{var a;(a=this.nn)==null||a.capture("$feature_enrollment_update",i).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,s){e===void 0&&(e=!1);var n=this.Oa(Tn);!n||e?this.Qa(t,s):t(n)}Qa(t,e){var s=this;return X((function*(){var n=s.nn;if(n){var r,i=e?"&"+e.map((a=>"stage="+a)).join("&"):"";try{var o=yield n.sendRequest("/api/early_access_features/?token="+n.projectToken+i,{target:"api",method:"GET",sentAt:"query"});if(!o.json)return;s.F({[Tn]:r=o.json.earlyAccessFeatures})}catch(a){return void s.rt.error("Early access feature request failed",a)}try{t(r)}catch(a){s.rt.error("Early access feature callback failed",a)}}}))()}Ga(){var t=this.getFlags(),e=this.getFlagVariants();return{flags:t.filter((s=>e[s])),flagVariants:Object.keys(e).filter((s=>e[s])).reduce(((s,n)=>(s[n]=e[n],s)),{})}}Va(t){this.Fa();var e=this.Ga(),s=e.flags,n=e.flagVariants;this.featureFlagEventHandlers.forEach((r=>{try{r(s,n,{errorsLoading:t})}catch(i){this.rt.error("Error while running feature flags callback",i)}}))}setPersonPropertiesForFlags(t,e){e===void 0&&(e=!0),this.Ka(t,e)}Ka(t,e){e===void 0&&(e=!0);var s=this.Oa(ct)||{},n=t?.$set||(t!=null&&t.$set_once?{}:t),r=t?.$set_once,i={};if(r)for(var o in r)({}).hasOwnProperty.call(r,o)&&(o in s||(i[o]=r[o]));this.F({[ct]:b({},s,i,n)}),e&&this.reloadFeatureFlags()}unsetPersonPropertiesForFlags(t,e){e===void 0&&(e=!0);var s=b({},this.Oa(ct)||{});t.forEach((n=>{delete s[n]})),this.F({[ct]:s}),e&&this.reloadFeatureFlags()}resetPersonPropertiesForFlags(t){t===void 0&&(t=!0),this.q(ct),t&&this.reloadFeatureFlags()}setGroupPropertiesForFlags(t,e){e===void 0&&(e=!0);var s=this.Oa(Ut)||{},n=b({},s);for(var r of Object.keys(t))n[r]=b({},s[r],t[r]);this.F({[Ut]:n}),e&&this.reloadFeatureFlags()}resetGroupPropertiesForFlags(t){if(t){var e=this.Oa(Ut)||{};this.F({[Ut]:b({},e,{[t]:{}})})}else this.q(Ut)}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}}},xf={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===Ls||this.Ya===Pn?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=Ll,this.Xa=void 0,this.eo=!1,this.io=(()=>{var e;if(C==null||!C.visibilityState||C.visibilityState==="visible")return!0;var s=v==null||(e=v.performance)==null||e.getEntriesByType==null?void 0:e.getEntriesByType("visibility-state");return!(s!=null&&s.length)||s.some((n=>n.name==="visible"))})(),this.Ie=()=>{var e;C?.visibilityState==="visible"&&(this.io=!0,(e=this.Ja)==null||e.setDocumentWasEverVisible==null||e.setDocumentWasEverVisible(!0))},this._instance=t,!this._instance.sessionManager)throw at.error("started without valid sessionManager"),new Error(mo+" started without valid sessionManager. This is a bug.");if(this.Ne.cookieless_mode===ht)throw new Error(mo+' cannot be used with cookieless_mode="always"');C!=null&&C.addEventListener&&re(C,"visibilitychange",this.Ie)}initialize(){this.startIfEnabledOrStop()}dispose(){this.eo=!0,C==null||C.removeEventListener==null||C.removeEventListener("visibilitychange",this.Ie),this.stopRecording()}get ro(){var t,e=!((t=this._instance.get_property(qt))==null||!t.enabled),s=!this.Ne.disable_session_recording,n=this.Ne.disable_session_recording||this._instance.consent.isOptedOut();return v&&e&&s&&!n}startIfEnabledOrStop(t){var e;if(!(this.eo||this.ro&&(e=this.Ja)!=null&&e.isStarted)){var s=!x(Object.assign)&&!x(Array.from);this.ro&&s?(this.no(t),at.info("starting")):(this.Ya=Ll,this.stopRecording())}}no(t){var e,s,n;this.ro&&(this.Ya!==Ls&&this.Ya!==Pn&&(this.Ya=Ol),$!=null&&(e=$.__PosthogExtensions__)!=null&&(e=e.rrweb)!=null&&e.record&&(s=$.__PosthogExtensions__)!=null&&s.initSessionRecording?this.so(t):(n=$.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,this.ao,(r=>{if(r)return at.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(Go),(e=this.Mr)==null||e.unregister(du)}uo(t,e){if(D(t))return null;var s,n=he(t)?t:parseFloat(t);return typeof(s=n)!="number"||!Number.isFinite(s)||0>s||s>1?(at.warn(e+" must be between 0 and 1. Ignoring invalid value:",t),null):n}ho(t){if(this.Mr){var e,s,n=this.Mr,r=()=>{var i,o=t.sessionRecording===!1?void 0:t.sessionRecording,a=this.uo((i=this.Ne.session_recording)==null?void 0:i.sampleRate,"session_recording.sampleRate"),l=this.uo(o?.sampleRate,"remote config sampleRate"),u=a??l;D(u)&&this.lo();var c=o?.minimumDurationMilliseconds;n.register({[qt]:b({cache_timestamp:Date.now(),enabled:!!o},o,{networkPayloadCapture:b({capturePerformance:t.capturePerformance},o?.networkPayloadCapture),canvasRecording:{enabled:o?.recordCanvas,fps:o?.canvasFps,quality:o?.canvasQuality},sampleRate:u,minimumDurationMilliseconds:x(c)?null:c,endpoint:o?.endpoint,triggerMatchType:o?.triggerMatchType,masking:o?.masking,urlTriggers:o?.urlTriggers,version:o?.version,triggerGroups:o?.triggerGroups})})};r(),(e=this.Xa)==null||e.call(this),this.Xa=(s=this._instance.sessionManager)==null?void 0:s.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===Ls&&(this.Ya=Pn,at.warn("config refresh failed, recording will not start until page reload")),void this.startIfEnabledOrStop())}log(t,e){var s;e===void 0&&(e="log"),(s=this.Ja)!=null&&s.log?this.Ja.log(t,e):at.warn("log called before recorder was ready")}get ao(){var t,e,s=(t=this._instance)==null||(t=t.persistence)==null?void 0:t.get_property(qt);return(s==null||(e=s.scriptConfig)==null?void 0:e.script)||"lazy-recorder"}do(){var t,e=this._instance.get_property(qt);if(!e)return!1;try{t=typeof e=="object"?e:JSON.parse(e)}catch(s){return at.warn("persisted remote config for session recording is invalid and will be ignored",s),!1}return!D(t.cache_timestamp)&&36e5>=Date.now()-t.cache_timestamp}so(t){var e,s,n;if(!this.eo){if((e=$.__PosthogExtensions__)==null||!e.initSessionRecording)return at.warn("Called on script loaded before session recording is available. This can be caused by adblockers."),void this._instance.register_for_session({[yu]:!0});var r;if(this.Ja||(this.Ja=(r=$.__PosthogExtensions__)==null?void 0:r.initSessionRecording(this._instance,this.io),this.Ja._forceAllowLocalhostNetworkCapture=this._forceAllowLocalhostNetworkCapture),!this.do())return this.Ya===Pn||this.Ya===Ls?void 0:(this.Ya=Ls,at.info("persisted remote config is stale, requesting fresh config before starting"),void new zu(this._instance).load());this.Ya=Ol,(s=(n=this.Ja).setDocumentWasEverVisible)==null||s.call(n,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({[pu]:!0}),(t=this.Ja)==null||t.overrideLinkedFlag()}overrideSampling(){var t,e;this.Ja||(e=this.Mr)==null||e.register({[hu]:!0}),(t=this.Ja)==null||t.overrideSampling()}overrideTrigger(t){var e,s;this.Ja||(s=this.Mr)==null||s.register({[t==="url"?fu:gu]:!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 s;return!((s=this.Ja)==null||!s.tryAddCustomEvent(t,e))}}},kf={autocapture:class{constructor(t){this.vo=!1,this.co=null,this.fo=!1,this.po=!1,this.instance=t,this.rageclicks=new Tl(t.config.rageclick),this.mo=null}initialize(){this.startIfEnabled()}get Ne(){var t,e,s=te(this.instance.config.autocapture)?this.instance.config.autocapture:{};return s.url_allowlist=(t=s.url_allowlist)==null?void 0:t.map((n=>new RegExp(n))),s.url_ignorelist=(e=s.url_ignorelist)==null?void 0:e.map((n=>new RegExp(n))),s}yo(){if(this.isBrowserSupported()){if(v&&C){var t=s=>{s=s||v?.event;try{this.bo(s)}catch(n){Si.error("Failed to capture event",n)}};if(re(C,"submit",t,{capture:!0}),re(C,"change",t,{capture:!0}),re(C,"click",t,{capture:!0}),this.Ne.capture_copied_text){var e=s=>{s=s||v?.event;try{this.bo(s,Ei)}catch(n){Si.error("Failed to capture copy/cut event",n)}};re(C,"copy",e,{capture:!0}),re(C,"cut",e,{capture:!0})}}}else Si.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 s=e.autocapture_opt_out;Ke(s)&&(this.instance.persistence&&this.instance.persistence.register({[zi]:s}),this.co=s),this.startIfEnabled()}else this.startIfEnabled()}setElementSelectors(t){this.mo=t}getElementSelectors(t){var e,s=[];return(e=this.mo)==null||e.forEach((n=>{var r=C?.querySelectorAll(n);r?.forEach((i=>{t===i&&s.push(n)}))})),s}get isEnabled(){var t,e,s=(t=this.instance.persistence)==null?void 0:t.props[zi],n=this.co,r=this.instance.Qi()&&!this.fo;if($e(n)&&!Ke(s)&&!r)return!1;var i=(e=this.co)!==null&&e!==void 0?e:!!s;return!!this.instance.config.autocapture&&!i}bo(t,e){if(e===void 0&&(e="$autocapture"),this.isEnabled){var s,n=ui(t);xu(n)&&(n=n.parentNode||null),e==="$autocapture"&&t.type==="click"&&t instanceof MouseEvent&&this.instance.config.rageclick&&(s=this.rageclicks)!=null&&s.isRageClick(t.clientX,t.clientY,t.timeStamp||new Date().getTime())&&cl(n,this.instance.config.rageclick)&&this.bo(t,"$rageclick");var r=e===Ei;if(n&&(function(d,h,p,f,g,m){var _;if(!v||Xo(d)||p!=null&&p.url_allowlist&&!ol(p.url_allowlist,m)||p!=null&&p.url_ignorelist&&ol(p.url_ignorelist,m))return!1;if(p!=null&&p.dom_event_allowlist){var w=p.dom_event_allowlist;if(w&&!w.some((S=>h.type===S)))return!1}var E=Au(d,f),I=E.parentIsUsefulElement,F=E.targetElementList;if(!(function(S,A){var R=A?.element_allowlist;if(x(R))return!0;var N,T=function(J){if(R.some((z=>J.tagName.toLowerCase()===z)))return{v:!0}};for(var O of S)if(N=T(O))return N.v;return!1})(F,p)||!oo(F,p?.css_selector_allowlist)||oo(F,(_=p?.css_selector_ignorelist)!==null&&_!==void 0?_:bp))return!1;try{var P=v.getComputedStyle(d);if(P&&P.getPropertyValue("cursor")==="pointer"&&h.type==="click")return!0}catch{}var B=d.tagName.toLowerCase();switch(B){case"html":return!1;case"form":return(g||["submit"]).indexOf(h.type)>=0;case"input":case"select":case"textarea":return(g||["change","click"]).indexOf(h.type)>=0;default:return I?(g||["click"]).indexOf(h.type)>=0:(g||["click"]).indexOf(h.type)>=0&&(Zo.indexOf(B)>-1||d.getAttribute("contenteditable")==="true")}})(n,t,this.Ne,r,r?["copy","cut"]:void 0,this.instance)){var i=ff(n,{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=i.props;if(i.explicitNoCapture)return!1;var a=this.getElementSelectors(n);if(a&&a.length>0&&(o.$element_selectors=a),e===Ei){var l,u=Cu(v==null||(l=v.getSelection())==null?void 0:l.toString()),c=t.type||"clipboard";if(!u)return!1;o.$selected_content=u,o.$copy_type=c}return this.instance.capture(e,o),!0}}}isBrowserSupported(){return Se(C?.querySelectorAll)}},historyAutocapture:class{constructor(t){var e;this._instance=t,this._o=(v==null||(e=v.location)==null?void 0:e.pathname)||""}initialize(){this.startIfEnabled()}get isEnabled(){return this._instance.config.capture_pageview==="history_change"}startIfEnabled(){this.isEnabled&&(k.info("History API monitoring enabled, starting..."),this.monitorHistoryChanges())}stop(){this.wo&&this.wo(),this.wo=void 0,k.info("History API monitoring stopped")}monitorHistoryChanges(){v&&v.history&&(this.ko("pushState"),this.ko("replaceState"),this.xo())}ko(t){var e;if(v&&((e=v.history[t])==null||!e.__posthog_wrapped__)){var s=this;(function(n,r,i){try{if(!(r in n))return Nl;var o={next:n[r]},a=i((function(){for(var l=arguments.length,u=new Array(l),c=0;l>c;c++)u[c]=arguments[c];return o.next.apply(this,u)}));return Se(a)&&(a.prototype=a.prototype||{},Object.defineProperties(a,{__posthog_wrapped__:{enumerable:!1,value:!0},__posthog_layer__:{enumerable:!1,value:o}})),n[r]=a,()=>{if(n[r]!==a)for(var l=n[r];Se(l)&&l.__posthog_layer__;){var u=l.__posthog_layer__;if(u.next===a)return void(u.next=o.next);l=u.next}else n[r]=o.next}}catch{return Nl}})(v.history,t,(n=>function(r,i,o){n.call(this,r,i,o),s.So(t)}))}}So(t){try{var e,s=v==null||(e=v.location)==null?void 0:e.pathname;if(!s)return;s!==this._o&&this.isEnabled&&this._instance.capture(is,{navigation_type:t}),this._o=s}catch(n){k.error("Error capturing "+t+" pageview",n)}}xo(){if(!this.wo){var t=()=>{this.So("popstate")};re(v,"popstate",t),this.wo=()=>{v&&v.removeEventListener("popstate",t)}}}},heatmaps:class{get Ne(){return this.instance.config}constructor(t){var e;this.Co=!1,this.vo=!1,this.Mo=null,this.instance=t,this.Co=!((e=this.instance.persistence)==null||!e.props[qi]),this.rageclicks=new Tl(t.config.rageclick)}initialize(){this.startIfEnabled()}get flushIntervalMilliseconds(){var t=5e3;return te(this.Ne.capture_heatmaps)&&this.Ne.capture_heatmaps.flush_interval_milliseconds&&(t=this.Ne.capture_heatmaps.flush_interval_milliseconds),t}get isEnabled(){return D(this.Ne.capture_heatmaps)?D(this.Ne.enable_heatmaps)?this.Co:this.Ne.enable_heatmaps:this.Ne.capture_heatmaps!==!1}startIfEnabled(){if(this.isEnabled){if(this.vo)return;mf.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 s=!!e.heatmaps;this.instance.persistence&&this.instance.persistence.register({[qi]:s}),this.Co=s,this.startIfEnabled()}}}getAndClearBuffer(){var t=this.R;return this.R=void 0,t}Io(t){ki(t.originalEvent)&&this.ke(t.originalEvent,"deadclick")}Ie(){this.Mo&&clearInterval(this.Mo),this.Mo=C?.visibilityState==="visible"?setInterval(this.cr.bind(this),this.flushIntervalMilliseconds):null}To(){v&&C&&(this.Po=this.cr.bind(this),re(v,ar,this.Po),this.Ro=t=>this.ke(t||v?.event),re(C,"click",this.Ro,{capture:!0}),this.Ao=t=>this.Fo(t||v?.event),re(C,"mousemove",this.Ao,{capture:!0}),this.Lo=new ml(this.instance,Fp,this.Io.bind(this)),this.Lo.startIfEnabledOrStop(),this.Oo=this.Ie.bind(this),re(C,or,this.Oo),this.vo=!0)}Eo(){var t;v&&C&&(this.Po&&v.removeEventListener(ar,this.Po),this.Ro&&C.removeEventListener("click",this.Ro,{capture:!0}),this.Ao&&C.removeEventListener("mousemove",this.Ao,{capture:!0}),this.Oo&&C.removeEventListener(or,this.Oo),clearTimeout(this.Do),(t=this.Lo)==null||t.stop(),this.vo=!1)}$o(t,e){var s=this.instance.scrollManager.scrollY(),n=this.instance.scrollManager.scrollX(),r=this.instance.scrollManager.scrollElement(),i=(function(o,a,l){for(var u=o;u&&Ft(u)&&!Me(u,"body");){if(u===l)return!1;var c=void 0;try{var d,h,p;c=(d=(h=(p=u.ownerDocument)==null?void 0:p.defaultView)!==null&&h!==void 0?h:v)==null?void 0:d.getComputedStyle(u).position}catch{return!1}if(M(a,c))return!0;u=Fu(u)}return!1})(ui(t),["fixed","sticky"],r);return{x:t.clientX+(i?0:n),y:t.clientY+(i?0:s),target_fixed:i,type:e}}ke(t,e){var s;if(e===void 0&&(e="click"),!il(t.target)&&ki(t)){var n=this.$o(t,e);(s=this.rageclicks)!=null&&s.isRageClick(t.clientX,t.clientY,new Date().getTime())&&cl(ui(t),this.instance.config.rageclick)&&this.Vt(b({},n,{type:"rageclick"})),this.Vt(n)}}Fo(t){!il(t.target)&&ki(t)&&(clearTimeout(this.Do),this.Do=setTimeout((()=>{this.Vt(this.$o(t,"mousemove"))}),500))}Vt(t){if(v){var e=this.Ne.disable_capture_url_hashes?Ct(v.location.href):v.location.href,s=this.Ne.custom_personal_data_properties,n=this.Ne.mask_personal_data_properties?[...vs,...s||[]]:[],r=rn(e,n,on);this.R=this.R||{},this.R[r]||(this.R[r]=[]),this.R[r].push(t)}}cr(){this.R&&!mt(this.R)&&this.instance.capture("$$heatmap",{$heatmap_data:this.getAndClearBuffer()})}},deadClicksAutocapture:ml,webVitalsAutocapture:class{constructor(t){var e;this.Co=!1,this.vo=!1,this.R={navigationKey:void 0,url:void 0,metrics:[],firstMetricTimestamp:void 0},this.No=()=>{clearTimeout(this.qo),this.qo=void 0,this.R.metrics.length!==0&&(this._instance.capture("$web_vitals",b({$current_url:this.R.url},this.R.metrics.reduce(((s,n)=>b({},s,{["$web_vitals_"+n.name+"_event"]:b({},n),["$web_vitals_"+n.name+"_value"]:n.value})),{}))),this.R={navigationKey:void 0,url:void 0,metrics:[],firstMetricTimestamp:void 0})},this.jo=s=>{var n;if(this.R=this.R||{navigationKey:void 0,url:void 0,metrics:[],firstMetricTimestamp:void 0},D(s?.name)||D(s?.value))Lt.error("Invalid metric received",s);else{var r=typeof s.navigationURL=="string"?s.navigationURL:void 0,i=this.Bo(r);if(!x(i)){var o=he(s.navigationId)||typeof s.navigationId=="string"?"navigation:"+s.navigationId:"url:"+i;if(!this.Ho||this.Ho>s.value){this.R.navigationKey!==o&&(this.No(),this.qo=setTimeout(this.No,this.flushToCaptureTimeoutMs)),x(this.R.navigationKey)&&(this.R.navigationKey=o,this.R.url=i),this.R.firstMetricTimestamp=x(this.R.firstMetricTimestamp)?Date.now():this.R.firstMetricTimestamp,s.attribution&&s.attribution.interactionTargetElement&&(s.attribution.interactionTargetElement=void 0);var a=(n=this._instance.sessionManager)==null?void 0:n.checkAndGetSessionAndWindowId(!0),l=b({},s,r?{navigationURL:i}:{},{$current_url:i,timestamp:Date.now()});x(a)||(l.$session_id=a.sessionId,l.$window_id=a.windowId),this.R.metrics.push(l),this.R.metrics.length===this.allowedMetrics.length&&this.No()}else Lt.error("Ignoring metric with value >= "+this.Ho,s)}}},this.Uo=()=>{if(!this.vo){var s,n,r,i,o=$.__PosthogExtensions__,a=o?.postHogWebVitalsCallbacksByFlavor,l=a?.[this.zo]||(this.zo==="web-vitals"&&x(a)?o?.postHogWebVitalsCallbacks:void 0);if(x(l)||(s=l.onLCP,n=l.onCLS,r=l.onFCP,i=l.onINP),s&&n&&r&&i){var u={reportSoftNavs:this.useSoftNavs};this.allowedMetrics.indexOf("LCP")>-1&&s(this.jo.bind(this),u),this.allowedMetrics.indexOf("CLS")>-1&&n(this.jo.bind(this),u),this.allowedMetrics.indexOf("FCP")>-1&&r(this.jo.bind(this),u),this.allowedMetrics.indexOf("INP")>-1&&i(this.jo.bind(this),u),this.vo=!0}else Lt.error("web vitals callbacks not loaded - not starting")}},this._instance=t,this.Co=!((e=this._instance.persistence)==null||!e.props[Ji]),this.startIfEnabled()}get Wo(){return this._instance.config.capture_performance}get allowedMetrics(){var t,e,s=te(this.Wo)?(t=this.Wo)==null?void 0:t.web_vitals_allowed_metrics:void 0;return D(s)?((e=this._instance.persistence)==null?void 0:e.props[Yi])||["CLS","FCP","INP","LCP"]:s}get flushToCaptureTimeoutMs(){return(te(this.Wo)?this.Wo.web_vitals_delayed_flush_ms:void 0)||5e3}get useAttribution(){var t=te(this.Wo)?this.Wo.web_vitals_attribution:void 0;return t!=null&&t}get useSoftNavs(){var t=te(this.Wo)?this.Wo.__preview_web_vitals_soft_navs:void 0;return t!=null&&t}get Ho(){var t=te(this.Wo)&&he(this.Wo.__web_vitals_max_value)?this.Wo.__web_vitals_max_value:Ml;return t>0&&6e4>=t?Ml:t}get isEnabled(){var t=ne?.protocol;if(t!=="http:"&&t!=="https:")return Lt.info("Web Vitals are disabled on non-http/https protocols"),!1;var e=te(this.Wo)?this.Wo.web_vitals:Ke(this.Wo)?this.Wo:void 0;return Ke(e)?e:this.Co}startIfEnabled(){this.isEnabled&&!this.vo&&(Lt.info("enabled, starting..."),this.ai(this.Uo))}onRemoteConfig(t){if(t.ok){var e=t.config;if("capturePerformance"in e){var s=te(e.capturePerformance)&&!!e.capturePerformance.web_vitals,n=te(e.capturePerformance)?e.capturePerformance.web_vitals_allowed_metrics:void 0;this._instance.persistence&&(this._instance.persistence.register({[Ji]:s}),this._instance.persistence.register({[Yi]:n})),this.Co=s,this.startIfEnabled()}}}get zo(){return this.useSoftNavs?this.useAttribution?"web-vitals-with-attribution-soft-navs":"web-vitals-soft-navs":this.useAttribution?"web-vitals-with-attribution":"web-vitals"}ai(t){var e=$.__PosthogExtensions__,s=this.zo,n=e?.postHogWebVitalsCallbacksByFlavor;n!=null&&n[s]||s==="web-vitals"&&x(n)&&e!=null&&e.postHogWebVitalsCallbacks?t():e==null||e.loadExternalDependency==null||e.loadExternalDependency(this._instance,s,(r=>{r?Lt.error("failed to load script",r):t()}))}Bo(t){var e=t||v?.location.href;if(e){var s=this._instance.config.disable_capture_url_hashes?Ct(e):e,n=this._instance.config.custom_personal_data_properties,r=this._instance.config.mask_personal_data_properties?[...vs,...n||[]]:[];return rn(s,r,on)}Lt.error("Could not determine current URL")}}},If={exceptionObserver:class{constructor(t){var e;this.Uo=()=>{var s;if(v&&this.isEnabled&&(s=$.__PosthogExtensions__)!=null&&s.errorWrappingFunctions){var n=$.__PosthogExtensions__.errorWrappingFunctions.wrapOnError,r=$.__PosthogExtensions__.errorWrappingFunctions.wrapUnhandledRejection,i=$.__PosthogExtensions__.errorWrappingFunctions.wrapConsoleError;try{!this.Vo&&this.Ne.capture_unhandled_errors&&(this.Vo=n(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=i(this.captureException.bind(this)))}catch(o){Ms.error("failed to start",o),this.Qo()}}},this._instance=t,this.Ko=!((e=this._instance.persistence)==null||!e.props[Vi]),this.Jo=new Sh(b({},(function(s){var n,r,i,o;return s===void 0&&(s={}),{refillRate:(n=(r=s.exceptionRateLimiterRefillRate)!==null&&r!==void 0?r:s.__exceptionRateLimiterRefillRate)!==null&&n!==void 0?n:1,bucketSize:(i=(o=s.exceptionRateLimiterBucketSize)!==null&&o!==void 0?o:s.__exceptionRateLimiterBucketSize)!==null&&i!==void 0?i:10}})(this._instance.config.error_tracking),{refillInterval:1e4,rt:Ms})),this.Ne=this.Yo(),this.startIfEnabledOrStop()}Yo(){var t=this._instance.config.capture_exceptions,e={capture_unhandled_errors:!1,capture_unhandled_rejections:!1,capture_console_errors:!1};return te(t)?e=b({},e,t):(x(t)?this.Ko:t)&&(e=b({},e,{capture_unhandled_errors:!0,capture_unhandled_rejections:!0})),e}get isEnabled(){return this.Ne.capture_console_errors||this.Ne.capture_unhandled_errors||this.Ne.capture_unhandled_rejections}startIfEnabledOrStop(){this.isEnabled?(Ms.info("enabled"),this.Qo(),this.ai(this.Uo)):this.Qo()}ai(t){var e,s;(e=$.__PosthogExtensions__)!=null&&e.errorWrappingFunctions?t():(s=$.__PosthogExtensions__)==null||s.loadExternalDependency==null||s.loadExternalDependency(this._instance,"exception-autocapture",(n=>{if(n)return Ms.error("failed to load script",n);t()}))}Qo(){var t,e,s;(t=this.Vo)==null||t.call(this),this.Vo=void 0,(e=this.Zo)==null||e.call(this),this.Zo=void 0,(s=this.Go)==null||s.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({[Vi]:this.Ko}),this.Ne=this.Yo(),this.startIfEnabledOrStop())}}onConfigChange(){this.Ne=this.Yo()}captureException(t){var e,s,n,r=(e=t==null||(s=t.$exception_list)==null||(s=s[0])==null?void 0:s.type)!==null&&e!==void 0?e:"Exception";this.Jo.consumeRateLimit(r)?Ms.info("Skipping exception capture because of client rate limiting.",{exception:r}):(n=this._instance.exceptions)==null||n.sendExceptionEvent(t)}},exceptions:class{constructor(t){var e,s;this.Xo=[],this.tl=new jh([new Kh,new np,new Yh,new Jh,new tp,new ep,new Xh,new sp],(function(n){for(var r=arguments.length,i=new Array(r>1?r-1:0),o=1;r>o;o++)i[o-1]=arguments[o];return function(a,l){l===void 0&&(l=0);for(var u=[],c=a.split(` +`),d=l;c.length>d;d++){var h=c[d];if(1024>=h.length){var p=tl.test(h)?h.replace(tl,"$1"):h;if(!p.match(/\S*Error: /)){for(var f of i){var g=f(p,n);if(g){u.push(g);break}}if(u.length>=50)break}}}return(function(m){if(!m.length)return[];var _=Array.from(m);return _.reverse(),_.slice(0,50).map((w=>{return b({},w,{filename:w.filename||(E=_,E[E.length-1]||{}).filename,function:w.function||gs});var E}))})(u)}})("web:javascript",zh,Gh)),this._instance=t,this.Xo=(e=(s=this._instance.persistence)==null?void 0:s.get_property(Gi))!==null&&e!==void 0?e:[],this.el=tr(this.il()),this.rl=new ip(this.el)}onConfigChange(){this.el=tr(this.il()),this.rl.setConfig(this.el)}onRemoteConfig(t){var e,s,n;if(t.ok){var r=t.config;if("errorTracking"in r){var i=(e=(s=r.errorTracking)==null?void 0:s.suppressionRules)!==null&&e!==void 0?e:[],o=(n=r.errorTracking)==null?void 0:n.captureExtensionExceptions;this.Xo=i,this._instance.persistence&&this._instance.persistence.register({[Gi]:this.Xo,[Ki]:o})}}}get nl(){var t,e=!!this._instance.get_property(Ki),s=this._instance.config.error_tracking.captureExtensionExceptions;return(t=s??e)!==null&&t!==void 0&&t}buildProperties(t,e){return this.tl.buildFromUnknown(t,{syntheticException:e?.syntheticException,mechanism:{handled:e?.handled}})}addExceptionStep(t,e){if(this.el.enabled)try{if(!W(t)||t.trim().length===0)return void Xe.warn("Ignoring exception step because message must be a non-empty string");var s=(function(i){if(!i)return{sanitizedProperties:{},droppedKeys:[]};var o=[];return{sanitizedProperties:Object.keys(i).reduce(((a,l)=>rp.has(l)?(o.push(l),a):(a[l]=i[l],a)),{}),droppedKeys:o}})(this.sl(e)),n=s.sanitizedProperties,r=s.droppedKeys;r.length>0&&Xe.warn("Ignoring reserved exception step fields",{droppedKeys:r}),this.rl.add(b({[Qn]:t,[er]:new Date().toISOString()},n))}catch(i){Xe.error("Failed to add exception step. Ignoring breadcrumb.",i)}}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 Xe.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 Xe.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 Xe.info("Skipping exception capture because it was thrown by the PostHog SDK")}var s=this.el.enabled&&D(t.$exception_steps)?this.dl(t):t,n=typeof(i=globalThis._posthogReleaseId)=="string"&&i.length>0?i:void 0;n&&(s.$release_id=n);try{var r=this._instance.capture("$exception",s,{_noTruncate:!0,_batchKey:"exceptionEvent",Wn:!0});return r&&this.rl.clear(),r}catch(o){return Xe.error("Failed to capture exception event. Dropping this exception.",o),void this.rl.clear()}}catch(o){return void Xe.error("Failed to process exception event. Ignoring this exception.",o)}var i}dl(t){try{var e=this.rl.getAttachable();return e.length===0?t:b({},t,{$exception_steps:e})}catch(s){return Xe.error("Failed to read buffered exception steps. Capturing exception without steps.",s),t}}ll(t){this.el.enabled&&this.rl.add({[Qn]:t,[er]:new Date().toISOString()})}sl(t){return te(t)?b({},t):{}}il(){var t,e;return(t=(e=this._instance.config.error_tracking)==null?void 0:e.exception_steps)!==null&&t!==void 0?t:{}}ol(t){if(t.length===0)return!1;try{var e=t.reduce(((s,n)=>{var r=n.type,i=n.value;return W(r)&&r.length>0&&s.$exception_types.push(r),W(i)&&i.length>0&&s.$exception_values.push(i),s}),{$exception_types:[],$exception_values:[]});return this.Xo.some((s=>{var n=s.values.map((r=>{var i=rd[r.operator],o=e[r.key];if(!i||!o)return!1;var a=L(r.value)?r.value:[r.value];return a.length>0&&i(a,o)}));return s.type==="OR"?n.some(Boolean):n.every(Boolean)}))}catch(s){return Xe.warn("Failed to evaluate suppression rules. Capturing the exception.",s),!1}}ul(t){return t.flatMap((e=>{var s,n;return(s=(n=e.stacktrace)==null?void 0:n.frames)!==null&&s!==void 0?s:[]})).some((e=>e.filename&&e.filename.startsWith("chrome-extension://")))}hl(t){if(t.length>0){var e,s,n,r,i=(e=(s=t[0].stacktrace)==null?void 0:s.frames)!==null&&e!==void 0?e:[],o=i[i.length-1];return(n=o==null||(r=o.filename)==null?void 0:r.includes("posthog.com/static"))!==null&&n!==void 0&&n}return!1}al(t){return!D(t)&&L(t)}}},Cf=b({productTours:class{get Mr(){return this._instance.persistence}constructor(t){this.vl=null,this.cl=null,this._instance=t}initialize(){this.loadIfEnabled()}onRemoteConfig(t){if(t.ok){var e=t.config;if("productTours"in e){var s,n;if(this.Mr&&this.Mr.register({[Vo]:!!e.productTours}),!Ii(this._instance))return!this.vl&&D((s=this.Mr)==null?void 0:s.props[Ws])||An.info("product tours disabled; stopping and clearing cached tours"),(n=this.vl)==null||n.stop(),this.vl=null,void this.clearCache();this.loadIfEnabled()}}}loadIfEnabled(){!this.vl&&Ii(this._instance)&&this.ai((()=>this.fl()))}ai(t){var e,s;(e=$.__PosthogExtensions__)!=null&&e.generateProductTours?t():(s=$.__PosthogExtensions__)==null||s.loadExternalDependency==null||s.loadExternalDependency(this._instance,"product-tours",(n=>{n?An.error("Could not load product tours script",n):t()}))}fl(){var t;!this.vl&&(t=$.__PosthogExtensions__)!=null&&t.generateProductTours&&(this.vl=$.__PosthogExtensions__.generateProductTours(this._instance,!0))}getProductTours(t,e){if(e===void 0&&(e=!1),!L(this.cl)||e){var s=this.Mr;if(s){var n=s.props[Ws];if(L(n)&&!e)return this.cl=n,void t(n,{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(Ii(this._instance)){var i=r.statusCode;if(i!==200||!r.json){var o="Product Tours API could not be loaded, status: "+i;return i===0?r.error||An.warn(o):An.error(o),void t([],{isLoaded:!1,error:o})}var a=L(r.json.product_tours)?r.json.product_tours:[];this.cl=a,s&&s.register({[Ws]:a}),t(a,{isLoaded:!0})}else t([],{isLoaded:!0})}})}else t(this.cl,{isLoaded:!0})}getActiveProductTours(t){D(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(Ws)}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)}}},Tr),Ff={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 s=this.globalsForEvent(e);this.gl.push(s),this.gl.length>1e3&&(this.gl=this.gl.slice(10))}}get siteAppLoaders(){var t;return(t=$._POSTHOG_REMOTE_CONFIG)==null||(t=t[this._instance.config.token])==null?void 0:t.siteApps}initialize(){if(this.isEnabled){var t=this._instance._addCaptureHook(this.ml.bind(this));this.yl=()=>{t(),this.gl=[],this.yl=void 0}}}globalsForEvent(t){var e,s,n,r,i,o,a;if(!t)throw new Error("Event payload is required");var l={},u=this._instance.get_property("$groups")||[],c=this._instance.get_property("$stored_group_properties")||{};for(var d of Object.entries(c)){var h=d[0];l[h]={id:u[h],type:h,properties:d[1]}}var p=t.$set_once,f=t.$set;return{event:b({},Pc(t,vf),{properties:b({},t.properties,f?{$set:b({},(e=(s=t.properties)==null?void 0:s.$set)!==null&&e!==void 0?e:{},f)}:{},p?{$set_once:b({},(n=(r=t.properties)==null?void 0:r.$set_once)!==null&&n!==void 0?n:{},p)}:{}),elements_chain:(i=(o=t.properties)==null?void 0:o.$elements_chain)!==null&&i!==void 0?i:"",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,s=(e=t.tagName)==null?void 0:e.toLowerCase();return s==="style"&&this._instance.config.prepare_external_dependency_stylesheet?this._instance.config.prepare_external_dependency_stylesheet(t)||(Ze.error("prepare_external_dependency_stylesheet returned null"),null):s==="script"&&this._instance.config.prepare_external_dependency_script?this._instance.config.prepare_external_dependency_script(t)||(Ze.error("prepare_external_dependency_script returned null"),null):t}_l(){var t,e,s,n,r,i,o,a;if(!this._instance.config.prepare_external_dependency_stylesheet&&!this._instance.config.prepare_external_dependency_script)return()=>{};var l=C?.defaultView,u=l==null||(t=l.Node)==null?void 0:t.prototype;if(!l||!u)return()=>{};if(this.pl++,this.wl)return this.kl();var c=[],d=this,h=new WeakSet,p=(m,_,w)=>{if(m!=null&&m[_]){var E=m[_];m[_]=w(E),c.push((()=>{m[_]=E}))}},f=m=>{if(h.has(m))return m;var _=d.bl(m);return _&&h.add(_),_},g=m=>m.map((_=>typeof _=="string"?_:f(_))).filter((_=>!$e(_)));return p(u,"appendChild",(m=>function(_){var w=f(_);return w?m.call(this,w):_})),p(u,"insertBefore",(m=>function(_,w){var E=f(_);return E?m.call(this,E,w):_})),p(u,"replaceChild",(m=>function(_,w){var E=f(_);return E?m.call(this,E,w):w})),[(e=l.Element)==null?void 0:e.prototype,(s=l.Document)==null?void 0:s.prototype,(n=l.DocumentFragment)==null?void 0:n.prototype].forEach((m=>{p(m,"append",(_=>function(){for(var w=arguments.length,E=new Array(w),I=0;w>I;I++)E[I]=arguments[I];return _.apply(this,g(E))})),p(m,"prepend",(_=>function(){for(var w=arguments.length,E=new Array(w),I=0;w>I;I++)E[I]=arguments[I];return _.apply(this,g(E))}))})),[(r=l.Element)==null?void 0:r.prototype,(i=l.CharacterData)==null?void 0:i.prototype,(o=l.DocumentType)==null?void 0:o.prototype].forEach((m=>{p(m,"before",(_=>function(){for(var w=arguments.length,E=new Array(w),I=0;w>I;I++)E[I]=arguments[I];return _.apply(this,g(E))})),p(m,"after",(_=>function(){for(var w=arguments.length,E=new Array(w),I=0;w>I;I++)E[I]=arguments[I];return _.apply(this,g(E))})),p(m,"replaceWith",(_=>function(){for(var w=arguments.length,E=new Array(w),I=0;w>I;I++)E[I]=arguments[I];var F=g(E);return E.length&&!F.length?void 0:_.apply(this,F)}))})),p((a=l.Element)==null?void 0:a.prototype,"insertAdjacentElement",(m=>function(_,w){var E=f(w);return E?m.call(this,_,E):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 s=this._l();try{var n=t(s);return e&&s(),n}catch(r){throw s(),r}}setupSiteApp(t){var e=this.apps[t.id],s=()=>{var o;!e.errored&&this.gl.length&&(Ze.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))},n=!1,r=o=>{e.errored=!o,e.loaded=!0,Ze.info("Site app with id "+t.id+" "+(o?"loaded":"errored")),n&&s()};try{var i=this.xl((o=>t.init({posthog:this._instance,callback(a){o(),r(a)}})),!1).processEvent;i&&(e.processEvent=i),n=!0}catch(o){Ze.error(Dl+t.id,o),r(!1)}if(n&&e.loaded)try{s()}catch(o){Ze.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 s of t)this.setupSiteApp(s)}Cl(t){var e=this;if(Object.keys(this.apps).length!==0){var s=this.globalsForEvent(t),n=function(i){try{e.xl((()=>i.processEvent==null?void 0:i.processEvent(s)))}catch(o){Ze.error("Error while processing event "+t.event+" for site app "+i.id,o)}};for(var r of Object.values(this.apps))n(r)}}onRemoteConfig(t){var e,s,n,r=this;if((e=this.siteAppLoaders)!=null&&e.length)return this.isEnabled?(this.Sl(),void this._instance.on("eventCaptured",(l=>this.Cl(l)))):void Ze.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.');if((s=this.yl)==null||s.call(this),t.ok){var i=t.config;if((n=i.siteApps)!=null&&n.length)if(this.isEnabled){var o=function(){var l,u=a.id,c=a.url;$["__$$ph_site_app_"+u]=r._instance,(l=$.__PosthogExtensions__)==null||l.loadSiteApp==null||l.loadSiteApp(r._instance,c,(d=>{if(d)return Ze.error(Dl+u,d)}))};for(var a of i.siteApps)o()}else Ze.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.')}}}},Pf={tracingHeaders:class{constructor(t){this.Ml=void 0,this.Tl=void 0,this.El=void 0,this.Uo=()=>{var e,s,n=this.Il();n?(x(this.Ml)&&(this.Ml=(e=$.__PosthogExtensions__)==null||(e=e.tracingHeadersPatchFns)==null?void 0:e._patchXHR(n,(()=>this._instance.get_distinct_id()),this._instance.sessionManager)),x(this.Tl)&&(this.Tl=(s=$.__PosthogExtensions__)==null||(s=s.tracingHeadersPatchFns)==null?void 0:s._patchFetch(n,(()=>this._instance.get_distinct_id()),this._instance.sessionManager))):this.Qo()},this._instance=t}initialize(){this.startIfEnabledOrStop()}ai(t){var e,s;(e=$.__PosthogExtensions__)!=null&&e.tracingHeadersPatchFns?t():(s=$.__PosthogExtensions__)==null||s.loadExternalDependency==null||s.loadExternalDependency(this._instance,"tracing-headers",(n=>{if(n)return gf.error("failed to load script",n);t()}))}Pl(){var t,e;return(t=(e=this._instance.config.tracing_headers)!==null&&e!==void 0?e:this._instance.config.addTracingHeaders)!==null&&t!==void 0?t:this._instance.config.__add_tracing_headers}Il(){var t=this.Pl();return L(t)?(L(this.El)?this.El.splice(0,this.El.length,...t):this.El=[...t],t.length>0?this.El:void 0):(L(this.El)&&this.El.splice(0),this.El=t||void 0,this.El)}Qo(){var t,e;(t=this.Ml)==null||t.call(this),(e=this.Tl)==null||e.call(this),this.Ml=void 0,this.Tl=void 0}startIfEnabledOrStop(){this.Il()?this.ai(this.Uo):this.Qo()}}},Af=b({surveys:class{get Ne(){return this._instance.config}constructor(t){this.Rl=void 0,this._surveyManager=null,this.Al=!1,this.Fl=[],this.Ll=null,this.Ol=null,this._instance=t,this._surveyEventReceiver=null}initialize(){this.loadIfEnabled()}onRemoteConfig(t){if(!this.Ne.disable_surveys){if(!t.ok)return q.warn("Remote config unavailable. Not loading surveys.");var e=t.config.surveys;if(D(e))return q.warn("Flags not loaded yet. Not loading surveys.");var s=L(e);this.Rl=s?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=[],s=0;slocalStorage.removeItem(r)))}catch{}}loadIfEnabled(){if(!this._surveyManager)if(this.Al)q.info("Already initializing surveys, skipping...");else if(this.Ne.disable_surveys)q.info(Bl);else if(this.Ne.cookieless_mode&&this._instance.consent.isOptedOut())q.info("Not loading surveys in cookieless mode without consent.");else{var t=$?.__PosthogExtensions__;if(t){if(!x(this.Rl)||this.Ne.advanced_enable_surveys){var e=this.Rl||this.Ne.advanced_enable_surveys;this.Al=!0;try{var s=t.generateSurveys;if(s)return void this.Dl(s,e);var n=t.loadExternalDependency;if(!n)return void this.$l(Ko);n(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 wf(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(Bl),t([]);var s,n=this._instance.get_property(Xi);if(n&&!e)return t(n,{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=>{s=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 i;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(s==null||s({surveys:[],context:l}))}this.Ol=null;var u,c=r.json.surveys||[],d=c.filter((p=>(function(f){return!(!f.start_date||f.end_date)})(p)&&(od(p)||(function(f){var g;return!((g=f.conditions)==null||(g=g.actions)==null||(g=g.values)==null||!g.length)})(p))));d.length>0&&((u=this._surveyEventReceiver)==null||u.register(d)),(i=this._instance.persistence)==null||i.register({[Xi]:c,[nr]:Date.now()});var h={isLoaded:!0};t(c,h),s?.({surveys:c,context:h})}}))}ql(){return this.jl()&&!this.Ll&&!this.Bl()}jl(){var t=this._instance.get_property(nr);return he(t)&&Date.now()-t>3e5}Bl(){return he(this.Ol)&&3e5>Date.now()-this.Ol}markSurveyAsSeen(t,e){var s,n={id:t,current_iteration:(s=e?.iteration)!==null&&s!==void 0?s:null};ld(n);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(s){q.error("Error in survey callback",s)}}getActiveMatchingSurveys(t,e){if(e===void 0&&(e=!1),!D(this._surveyManager))return this._surveyManager.getActiveMatchingSurveys(t,e);q.warn("init was not called")}Hl(t){var e=null;return this.getSurveys((s=>{var n;e=(n=s.find((r=>r.id===t)))!==null&&n!==void 0?n:null})),e}Ul(t){if(D(this._surveyManager))return{eligible:!1,reason:$n};var e=typeof t=="string"?this.Hl(t):t;return e?this._surveyManager.checkSurveyEligibility(e):{eligible:!1,reason:"Survey not found"}}zl(t){if(D(this._surveyManager))return{eligible:!1,reason:$n};var e=typeof t=="string"?this.Hl(t):t;return e?this._surveyManager.checkSurveyRenderability(e):{eligible:!1,reason:"Survey not found"}}canRenderSurvey(t){if(D(this._surveyManager))return q.warn("init was not called"),{visible:!1,disabledReason:$n};var e=this.zl(t);return{visible:e.eligible,disabledReason:e.reason}}canRenderSurveyAsync(t,e){return D(this._surveyManager)?(q.warn("init was not called"),Promise.resolve({visible:!1,disabledReason:$n})):new Promise((s=>{this.getSurveys((n=>{var r,i=(r=n.find((a=>a.id===t)))!==null&&r!==void 0?r:null;if(i){var o=this.zl(i);s({visible:o.eligible,disabledReason:o.reason})}else s({visible:!1,disabledReason:"Survey not found"})}),e)}))}renderSurvey(t,e,s){var n;if(D(this._surveyManager))q.warn("init was not called");else{var r=typeof t=="string"?this.Hl(t):t;if(r!=null&&r.id)if(tf.includes(r.type)){var i=C?.querySelector(e);if(i)return(n=r.appearance)!=null&&n.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,i,s),q.info("Survey "+r.id+" rendered")}),1e3*r.appearance.surveyPopupDelaySeconds)):void this._surveyManager.renderSurvey(r,i,s);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 s;if(D(this._surveyManager))q.warn("init was not called");else{var n=this.Hl(t);if(n){var r=n;if((s=n.appearance)!=null&&s.surveyPopupDelaySeconds&&e.ignoreDelay&&(r=b({},n,{appearance:b({},n.appearance,{surveyPopupDelaySeconds:0})})),e.displayType!==lo.Popover&&e.initialResponses&&q.warn("initialResponses is only supported for popover surveys. prefill will not be applied."),e.ignoreConditions===!1){var i=this.Ul(n);if(!i.eligible)return void q.warn("Survey is not eligible to be displayed: ",i.reason)}e.displayType!==lo.Inline?this._surveyManager.handlePopoverSurvey(r,e):this.renderSurvey(r,e.selector,e.properties)}else q.warn("Survey not found")}}cancelPendingSurvey(t){D(this._surveyManager)?q.warn("init was not called"):this._surveyManager.cancelSurvey(t)}handlePageUnload(){var t;(t=this._surveyManager)==null||t.handlePageUnload==null||t.handlePageUnload()}}},Tr),$f={toolbar:class{constructor(t){this.instance=t}Wl(t){$.ph_toolbar_state=t}Vl(){var t;return(t=$.ph_toolbar_state)!==null&&t!==void 0?t:0}initialize(){return this.maybeLoadToolbar()}maybeLoadToolbar(t,e,s){if(t===void 0&&(t=void 0),e===void 0&&(e=void 0),s===void 0&&(s=void 0),io(this.instance.config)||!v||!C)return!1;t=t??v.location,s=s??v.history;try{if(!e){try{v.localStorage.setItem("test","test"),v.localStorage.removeItem("test")}catch{return!1}e=v?.localStorage}var n,r=bf||dr(t.hash,"__posthog")||dr(t.hash,"state"),i=r?nl((()=>JSON.parse(atob(decodeURIComponent(r)))))||nl((()=>JSON.parse(decodeURIComponent(r)))):null;return i&&i.action==="ph_authorize"?((n=i).source="url",n&&Object.keys(n).length>0&&(i.desiredHash?t.hash=i.desiredHash:s?s.replaceState(s.state,"",t.pathname+t.search):t.hash="")):((n=JSON.parse(e.getItem(jl)||"{}")).source="localstorage",delete n.userIntent),!(!n.token||this.instance.config.token!==n.token||(this.loadToolbar(n),0))}catch{return!1}}Zl(t){var e=$.ph_load_toolbar||$.ph_load_editor;!D(e)&&Se(e)?e(t,this.instance):Ul.warn("No toolbar load function found")}loadToolbar(t){var e=!(C==null||!C.getElementById(Su));if(!v||e)return!1;var s=this.instance.requestRouter.region==="custom"&&this.instance.config.advanced_disable_toolbar_metrics,n=b({token:this.instance.config.token},t,{apiURL:this.instance.requestRouter.endpointFor("ui")},s?{instrument:!1}:{});if(v.localStorage.setItem(jl,JSON.stringify(b({},n,{source:void 0}))),this.Vl()===2)this.Zl(n);else if(this.Vl()===0){var r;this.Wl(1),(r=$.__PosthogExtensions__)==null||r.loadExternalDependency==null||r.loadExternalDependency(this.instance,"toolbar",(i=>{if(i)return Ul.error("[Toolbar] Failed to load",i),void this.Wl(0);this.Wl(2),this.Zl(n)})),re(v,"turbolinks:load",(()=>{this.Wl(0),this.loadToolbar(n)}))}return!0}Gl(t){return this.loadToolbar(t)}maybeLoadEditor(t,e,s){return t===void 0&&(t=void 0),e===void 0&&(e=void 0),s===void 0&&(s=void 0),this.maybeLoadToolbar(t,e,s)}}},Rf=b({experiments:ye},Tr),Tf={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;D(e)||(Ke(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||io(this._instance.config)||this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut())){var t=$?.__PosthogExtensions__;if(t&&!x(this.Ql)&&this.Ql)if(this.Jl&&this.Jl.token){this.Kl=!0;try{var e=t.initConversations;if(e)return this.tu(e),void(this.Kl=!1);var s=t.loadExternalDependency;if(!s)return void this.eu(Ko);s(this._instance,"conversations",(n=>{n||!t.initConversations?this.eu("Could not load conversations script",n):this.tu(t.initConversations),this.Kl=!1}))}catch(n){this.eu("Error initializing conversations",n),this.Kl=!1}}else Ue.error("Conversations enabled but missing token in remote config.")}}tu(t){if(this.Jl)try{this._conversationsManager=t(this.Jl,this._instance),this.Yl=!1,Ue.info("Conversations loaded successfully")}catch(e){this.eu("Error completing conversations initialization",e)}else Ue.error("Cannot complete initialization: remote config is null")}eu(t,e){Ue.error(t,e),this._conversationsManager=null,this.Kl=!1,this.Yl=!0}show(){this._conversationsManager?this._conversationsManager.show():Ue.warn("Conversations not loaded yet.")}hide(){this._conversationsManager&&this._conversationsManager.hide()}isAvailable(){return this.Ql===!0&&!$e(this._conversationsManager)}getUnavailableReason(){return this.isAvailable()?null:this._instance.config.disable_conversations?"disabled_by_config":io(this._instance.config)?"disabled_for_toolbar":this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut()?"consent_opted_out":this.Xl===!1?"remote_config_failed":x(this.Ql)?this.Xl?"disabled_in_project":"remote_config_pending":this.Ql?D(this.Jl)||!this.Jl.token?"missing_token":$!=null&&$.__PosthogExtensions__?this.Kl?"initializing":this.Yl?"load_failed":"not_loaded":"extensions_unavailable":"disabled_in_project"}isVisible(){var t,e;return(t=(e=this._conversationsManager)==null?void 0:e.isVisible())!==null&&t!==void 0&&t}sendMessage(t,e,s){var n=this;return X((function*(){return n._conversationsManager?n._conversationsManager.sendMessage(t,e,s):(Ue.warn(Dt),null)}))()}getMessages(t,e){var s=this;return X((function*(){return s._conversationsManager?s._conversationsManager.getMessages(t,e):(Ue.warn(Dt),null)}))()}markAsRead(t){var e=this;return X((function*(){return e._conversationsManager?e._conversationsManager.markAsRead(t):(Ue.warn(Dt),null)}))()}getTickets(t){var e=this;return X((function*(){return e._conversationsManager?e._conversationsManager.getTickets(t):(Ue.warn(Dt),null)}))()}requestRestoreLink(t){var e=this;return X((function*(){return e._conversationsManager?e._conversationsManager.requestRestoreLink(t):(Ue.warn(Dt),null)}))()}restoreFromToken(t){var e=this;return X((function*(){return e._conversationsManager?e._conversationsManager.restoreFromToken(t):(Ue.warn(Dt),null)}))()}restoreFromUrlToken(){var t=this;return X((function*(){return t._conversationsManager?t._conversationsManager.restoreFromUrlToken():(Ue.warn(Dt),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()}}},Nf={logs:class{constructor(t){var e,s=this;this.iu=!1,this.ru=!1,this.rt=se("[logs]"),this.nu=b({},this.rt,{error(){for(var n=arguments.length,r=new Array(n),i=0;n>i;i++)r[i]=arguments[i];r.some(Jl)||s.rt.error(...r)}}),this.tr=[],this.su=[],this.Sa=0,this.au=()=>{var n,r;this.Sa=0,(n=this.ou)==null||n.onReconnect(),(r=this.lu)==null||r.onReconnect()},this._instance=t,this._instance&&(e=this._instance.config.logs)!=null&&e.captureConsoleLogs&&(this.iu=!0),v&&re(v,"online",this.au)}uu(t,e,s,n){var r,i=(function(o,a){var l,u,c,d,h,p,f,g=(l=o?.flushIntervalMs)!==null&&l!==void 0?l:3e3,m=(u=o?.maxBufferSize)!==null&&u!==void 0?u:100,_=a!=null&&a.consoleCapture?void 0:(c=o?.maxLogsPerInterval)!==null&&c!==void 0?c:1e3,w=x(_)?Math.max(m,2048):Math.max(m,_),E=o?.resourceAttributes;return{serviceName:(d=(h=E?.["service.name"])!==null&&h!==void 0?h:o?.serviceName)!==null&&d!==void 0?d:a?.serviceNameDefault,serviceVersion:(p=E?.["service.version"])!==null&&p!==void 0?p:o?.serviceVersion,environment:(f=E?.["deployment.environment"])!==null&&f!==void 0?f:o?.environment,resourceAttributes:E,beforeSend:o?.beforeSend,flushIntervalMs:g,maxBufferSize:m,maxQueueSize:w,maxBatchRecordsPerPost:100,rateCapWindowMs:g,maxLogsPerInterval:_,backgroundFlushBudgetMs:0,terminationFlushBudgetMs:0}})((r=this._instance)==null||(r=r.config)==null?void 0:r.logs,s);return[new Oh(this.hu(t,e),i,this.nu,(()=>this.du()),(o=>o()),void 0,n),i]}vu(){var t,e=(t=this._instance)==null||(t=t.config)==null?void 0:t.logs;if(!this.ou||this.cu!==e){var s;(s=this.ou)==null||s.reset(),this.cu=e;var n=this.uu((()=>this.tr),(r=>{this.tr=r}));this.ou=n[0],this.fu=n[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 s;(s=this.lu)==null||s.reset(),this.gu=e;var n=this.uu((()=>this.su),(r=>{this.su=r}),{serviceNameDefault:"posthog-browser-logs",consoleCapture:!0},Kl);this.lu=n[0],this.mu=n[1]}return this.lu}initialize(){this.loadIfEnabled()}onRemoteConfig(t){var e;if(t.ok){var s=(e=t.config.logs)==null?void 0:e.captureConsoleLogs;!D(s)&&s&&(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){Jl(t)||this.rt.error("PostHog logs flush failed:",t)}loadIfEnabled(){if(this.iu&&!this.ru){var t=$?.__PosthogExtensions__;if(t){var e=t.loadExternalDependency;e?e(this._instance,"logs",(s=>{var n;s||(n=t.logs)==null||!n.initializeLogs?this.rt.error("Could not load logs script",s):(t.logs.initializeLogs(this._instance),this.ru=!0)})):this.rt.error(Ko)}else this.rt.error("PostHog Extensions not found.")}}hu(t,e){var s=this._instance;return{get isDisabled(){return!1},get optedOut(){return!s.is_capturing()},getPersistedProperty:n=>n===ut.LogsQueue?t():void 0,setPersistedProperty(n,r){var i;n===ut.LogsQueue&&e((i=r)!==null&&i!==void 0?i:[])},Ot:n=>this.Ot(n),getLibraryId:()=>Y.LIB_NAME,getLibraryVersion:()=>Y.LIB_VERSION}}Ot(t){return new Promise((e=>{if(Mu(this.Sa,3))e({kind:"fatal",error:Fi(void 0,"logs endpoint is unreachable, dropping batch")});else{var s=!1,n=i=>{s||(s=!0,clearTimeout(r),e(i))},r=setTimeout((()=>{this.rt.warn("Logs request timed out before receiving a response"),n({kind:"retry-later",error:Fi(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:i=>{var o=i.statusCode;if(this.ku(o),o>=200&&300>o)n({kind:"ok"});else if(o===413)n({kind:"too-large"});else if(o!==0&&o!==429&&500>o)n({kind:"fatal",error:new Error("logs request failed with status "+o)});else{var a;o===0?(i.error||this.rt.warn("Logs request failed before receiving an HTTP response"),n({kind:"retry-later",error:Fi(i.error,"logs request failed before receiving an HTTP response")})):n({kind:"retry-later",error:(a=i.error)!==null&&a!==void 0?a:new Error("logs request failed with status "+o)})}}})}}))}ku(t){(t!==0||this._instance.__loaded)&&(this.Sa=Lu(t,this.Sa,3,(()=>this.rt.warn("Log requests are failing before receiving an HTTP response; this can happen due to network issues, CORS, browser blocking, or ad blockers. Stopped sending logs; will try again when connectivity changes."))))}bu(t){this.tr.length>0&&this.xu(t,this.tr,this.fu,Y.LIB_NAME,(e=>{this.tr=e})),this.su.length>0&&this.xu(t,this.su,this.mu,Kl,(e=>{this.su=e}))}xu(t,e,s,n,r){if(e.length!==0){var i=e.map((a=>a.record));r([]);var o=ou(i,iu(s,Y.LIB_NAME,Y.LIB_VERSION),n,Y.LIB_VERSION);this._instance._send_request({method:"POST",url:this.wu(),data:o,compression:"best-available",batchKey:"logs",transport:t})}}wu(){return this._instance.requestRouter.endpointFor("api","/i/v1/logs")+"?token="+encodeURIComponent(this._instance.config.token)}du(){var t,e={};if(e.distinctId=this._instance.get_distinct_id(),this._instance.sessionManager){var s=this._instance.sessionManager.checkAndGetSessionAndWindowId(!0),n=s.windowId,r=s.sessionStartTimestamp,i=s.lastActivityTimestamp;e.sessionId=s.sessionId,e.windowId=n,D(r)||(e.sessionStartTimestamp=r),D(i)||(e.lastActivityTimestamp=i)}if($!=null&&(t=$.location)!=null&&t.href&&(e.currentUrl=this._instance.config.disable_capture_url_hashes?Ct($.location.href):$.location.href),this._instance.featureFlags){var o=this._instance.featureFlags.getFlags();o&&o.length>0&&(e.activeFeatureFlags=o)}return e}}},Mf={metrics:class{constructor(t){this.rt=se("[metrics]"),this._instance=t}initialize(){}vu(){var t,e,s=(t=this._instance)==null||(t=t.config)==null?void 0:t.metrics;return this.ou&&this.cu===s||((e=this.ou)==null||e.reset(),this.cu=s,this.ou=new Dh(this.hu(),(function(n){var r,i,o,a,l,u=n?.resourceAttributes;return{serviceName:(r=u?.["service.name"])!==null&&r!==void 0?r:n?.serviceName,serviceVersion:(i=u?.["service.version"])!==null&&i!==void 0?i:n?.serviceVersion,environment:(o=u?.["deployment.environment"])!==null&&o!==void 0?o:n?.environment,resourceAttributes:u,beforeSend:n?.beforeSend,flushIntervalMs:(a=n?.flushIntervalMs)!==null&&a!==void 0?a:1e4,maxSeriesPerFlush:(l=n?.maxSeriesPerFlush)!==null&&l!==void 0?l:1e3}})(s),this.rt)),this.ou}count(t,e,s){e===void 0&&(e=1),this.vu().count(t,e,s)}gauge(t,e,s){this.vu().gauge(t,e,s)}histogram(t,e,s){this.vu().histogram(t,e,s)}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((s=>this.rt.error("PostHog metrics flush failed:",s)))}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:s=>e.Jt(s),getLibraryId:()=>Y.LIB_NAME,getLibraryVersion:()=>Y.LIB_VERSION}}Jt(t,e){return new Promise((s=>{var n=!1,r=o=>{n||(n=!0,clearTimeout(i),s(o))},i=setTimeout((()=>r({kind:"retry-later",error:new Error("metrics request timed out")})),9e4);this._instance._send_request(b({method:"POST",url:this.Su(),data:t,compression:"best-available",batchKey:"metrics"},e&&{transport:e},{fireCallbackOnDrop:!0,callback(o){var a=o.statusCode;if(a>=200&&300>a)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)}}},Lf=b({},Tr,xf,kf,If,Cf,Ff,Af,Pf,$f,Rf,Tf,Nf,Mf);Te.__defaultExtensionClasses=b({},Lf);(function(){Y.SDK_DIST_CHANNEL="npm";var t=Ys[os]=new Te;return(function(){function e(){e.done||(e.done=!0,ud=!1,Z(Ys,(function(s){s._dom_loaded()})))}C!=null&&C.addEventListener?C.readyState==="complete"?e():re(C,"DOMContentLoaded",e,{capture:!1}):v&&k.error("Browser doesn't support `document.addEventListener` so PostHog couldn't be initialized")})(),t})();const hd="CodeFile",pd="GeneratedCode",Of={CustomAction:"A",CustomWidget:"W",CustomFunction:"F",CustomClass:"C",CodeFile:"C"};function kt(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function vo(t){return String(t||"").trim().replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function Df(t={},e=0){const s=vo(t.artifactType||t.type||hd),n=vo(t.artifactName||t.name||t.fileName||`${pd}-${e+1}`);return`${s||"artifact"}-${n||e+1}`}function fd(t={},e=0){const s=kt(t),n=s.artifactType||s.type||hd,r=s.artifactName||s.name||pd;let i=s.fileName||r;return i.endsWith(".dart")||(i+=".dart"),{id:vo(s.id)||Df({...s,artifactType:n,artifactName:r,fileName:i},e),artifactType:n,artifactName:r,fileName:i,deployPath:s.deployPath||"",description:s.description||"",code:s.code||s.content||"",dependencies:gd(s.dependencies),imports:Array.isArray(s.imports)?s.imports:[],publicApi:Array.isArray(s.publicApi)?s.publicApi:[],relationships:md(s.relationships),deployStatus:s.deployStatus||"pending",review:s.review||null,metadata:kt(s.metadata),codeType:s.codeType||Of[n]||"O"}}function gd(t){return t?Array.isArray(t)?t.map(e=>{if(typeof e=="string")return{name:e,version:null,inferred:!1};const s=kt(e),n=s.name||s.package;return n?{name:n,version:s.version||null,versionRequired:!!(s.versionRequired||s.required),inferred:!!s.inferred,...s.reason?{reason:s.reason}:{}}:null}).filter(Boolean):Object.entries(kt(t)).map(([e,s])=>({name:e,version:s||null,inferred:!1})):[]}function md(t){return t?(Array.isArray(t)?t:[t]).map(e=>{const s=kt(e);return!s.from&&!s.to?null:{from:s.from||null,to:s.to||null,type:s.type||"uses",description:s.description||""}}).filter(Boolean):[]}function _o(t){if(typeof t!="string")return null;const e=t.trim();if(!e)return null;try{return JSON.parse(e)}catch{const s=e.match(/```(?:json)?\s*([\s\S]*?)```/i);if(!s)return null;try{return JSON.parse(s[1].trim())}catch{return null}}}function an(t,e={}){const s=[],n=typeof t=="string"?_o(t):t,i=kt(n||{});!n&&typeof t=="string"&&s.push("Structured bundle parse failed; using legacy single-artifact fallback.");const o=Array.isArray(i.artifacts)?i.artifacts:[{artifactType:i.artifactType||e.artifactType,artifactName:i.artifactName||e.artifactName,fileName:i.fileName||e.fileName,description:i.description,code:i.code||e.code||(typeof t=="string"?t:""),dependencies:i.dependencies||e.dependencies,relationships:i.relationships||e.relationships}];o.forEach((d,h)=>{!d?.artifactType&&!d?.type&&s.push(`Artifact ${h+1} has no artifactType; it will deploy as a standalone code file under lib/custom_code/ root.`)});const a=o.map((d,h)=>fd(d,h)),l=new Map(o.map((d,h)=>[kt(d).id,a[h]?.id]).filter(([d,h])=>d&&h)),u=d=>l.get(d)||d,c=md(i.relationships||e.relationships).map(d=>({...d,from:d.from?u(d.from):d.from,to:d.to?u(d.to):d.to}));return{schemaVersion:i.schemaVersion||e.schemaVersion||null,id:i.id||e.id||"bundle-current",title:i.title||i.name||e.title||"Generated artifact bundle",description:i.description||e.description||"",artifacts:a,dependencies:gd(i.dependencies||e.dependencies),relationships:c,deployOrder:Array.isArray(i.deployOrder)?i.deployOrder.map(u):a.map(d=>d.id),warnings:[...s,...Array.isArray(i.warnings)?i.warnings:[]],metadata:kt(i.metadata)}}function mr(t){return an(t).artifacts[0]||fd()}function yt(t){if(typeof t!="string")return t??"";const e=t.trim();if(!e)return"";try{return JSON.parse(e)}catch{return t}}function ys(t){return JSON.stringify(t,null,2)}function Bf(t){return ys({task:"architect",userRequest:String(t??"")})}function jf(t){const e=yt(t);return e&&typeof e=="object"&&typeof e.task=="string"?ys(e):ys({task:"generate_bundle",bundleSpec:e})}function Uf(t){return ys({task:"review_bundle",generatedBundle:yt(t),outputRequirements:{bundleReview:["status","score","summary","manualActions","findings"],scoreRange:[0,100],eachArtifact:["id","review.status","review.findings"],manualActions:{definition:"Setup the developer must perform by hand in the FlutterFlow editor that FlutterFlow will NOT do for them.",exclude:["creating the Custom Action, Widget or Code File itself - deploying the code creates it","declaring parameters or return values FlutterFlow derives from the function signature","anything that resolves as a side effect of using the action or widget in the editor","generic advice such as testing, reviewing or rebuilding the app"],preferEmpty:"Return an empty array when nothing qualifies - an empty list is the expected result for most bundles."}}})}function sa(t,e=null){const s={stage:t};return e!=null&&(s.bundle=yt(e)),s}function Hf({bundleSpec:t,artifactBundle:e,bundleReview:s,artifactId:n,userFeedback:r}){return ys({task:"regenerate_artifact",artifactId:n,bundleSpec:yt(t),artifactBundle:yt(e),bundleReview:yt(s),userFeedback:String(r)})}function vd({bundleSpec:t,artifactBundle:e,bundleReview:s,userFeedback:n}){return ys({task:"regenerate_bundle",bundleSpec:yt(t),artifactBundle:yt(e),bundleReview:yt(s),userFeedback:String(n??"")})}const Yl={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"},Wf=["sanitizationResult","modelArmor","modelArmorResult","data","result","error"];function Le(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function zf(t){return Le(t)?typeof t.filterMatchState=="string"||typeof t.invocationResult=="string"||Array.isArray(t.matchedFilters)||Le(t.filterSummary)||Le(t.filterResults):!1}function _d(t,e=0){if(!Le(t)||e>3)return null;if(zf(t))return t;for(const s of Wf){const n=t[s];if(Le(n)){const r=_d(n,e+1);if(r)return r}}return null}function vr(t){return Array.isArray(t)?t.some(vr):Le(t)?t.matched===!0||t.matchState==="MATCH_FOUND"?!0:Object.values(t).some(vr):!1}function yo(t){return Array.isArray(t)?t.some(yo):Le(t)?typeof t.executionState=="string"&&t.executionState!=="EXECUTION_SUCCESS"?!0:Object.values(t).some(yo):!1}function yd(t){return{csamFilterFilterResult:"csam",maliciousUriFilterResult:"malicious_uris",piAndJailbreakFilterResult:"pi_and_jailbreak",raiFilterResult:"rai",sdpFilterResult:"sdp",virusScanFilterResult:"virus_scan"}[t]||t}function qf(t,e){if(Le(t))for(const[s,n]of Object.entries(t)){if(!Le(n))continue;const r=Le(n.categories)?n.categories:{},i=Object.entries(r).filter(([,o])=>Le(o)&&o.matched===!0).map(([o])=>o);i.length>0?i.forEach(o=>e.add(o)):n.matched===!0&&e.add(yd(s))}}function Vf(t,e){if(!t)return;const s=Array.isArray(t)?t.flatMap(n=>Le(n)?Object.entries(n):[]):Object.entries(t);for(const[n,r]of s){if(!vr(r))continue;const i=yd(n),o=r?.raiFilterResult?.raiFilterTypeResults||(i==="rai"?r?.raiFilterTypeResults:null),a=Le(o)?Object.entries(o).filter(([,l])=>vr(l)).map(([l])=>l):[];a.length>0?a.forEach(l=>e.add(l)):e.add(i)}}function Gf(t){return Yl[t]?Yl[t]:String(t).replace(/([a-z])([A-Z])/g,"$1 $2").replace(/_/g," ").toLowerCase()}function Zl(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 Kf(t){const e=_d(t);if(!e)return null;const s=new Set(Array.isArray(e.matchedFilters)?e.matchedFilters:[]);qf(e.filterSummary,s),Vf(e.filterResults,s);const n=e.blocked===!0||e.filterMatchState==="MATCH_FOUND"||s.size>0,r=e.invocationResult||null,i=yo(e.filterSummary||e.filterResults);return!n&&!i&&!["PARTIAL","FAILURE"].includes(r)?null:{kind:n?"blocked":"unavailable",invocationResult:r,matchedFilters:[...s]}}function Jf(t,e){const s=Kf(t);if(!s)return null;const n=[...new Set(s.matchedFilters.map(Gf))],r=s.kind==="blocked",i=new Error(r?`Safety screening blocked this pipeline step for ${Zl(n)}.`:"Safety screening could not be completed. Please try again.");return i.name="ModelArmorError",i.code=r?"MODEL_ARMOR_BLOCKED":"MODEL_ARMOR_UNAVAILABLE",i.isModelArmor=!0,i.pipelineStep=e,i.userTitle=r?"Request blocked for safety":"Safety check unavailable",i.userMessage=r?`The safety check detected ${Zl(n)}. 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.",i.retryExplanation=r?"Trying another model would not change this safety decision.":"A fallback model was not attempted because safety screening must complete first.",i.matchedFilters=s.matchedFilters,i}function Yf(t){return String(t||"").replace(/\/\*[\s\S]*?\*\//g,"").replace(/\/\/[^\n]*/g,"")}function Xl(t){const e=/^(import|export|part|library|class|enum|extension|typedef|mixin|abstract|const|final|var|late)\b/,s=[];for(const n of Yf(t).split(` +`)){if(!/^[A-Za-z_$]/.test(n)||e.test(n))continue;const r=n.match(/^[\w$<>,?\s[\]]+?\s([a-zA-Z_$][\w$]*)\s*\(/);r&&s.push(r[1])}return s}function na(t,e){const s=t.replace(/\.dart$/,"");if(e==="W")return s.replace(/(^|_)(\w)/g,(n,r,i)=>i.toUpperCase());if(e==="A"){const n=s.replace(/(^|_)(\w)/g,(r,i,o)=>o.toUpperCase());return n.charAt(0).toLowerCase()+n.slice(1)}return e==="F"?"CustomFunctions":e==="C"?t.endsWith(".dart")?t:`${t}.dart`:s}async function Ql(t){const e=new TextEncoder().encode(String(t||"")),s=await globalThis.crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(s),n=>n.toString(16).padStart(2,"0")).join("")}async function Zf(t,e=new Map){const s={},n=new Set;for(const[o,a]of t.entries()){if(a.type==="D"||a.type==="O")continue;const l=na(o,a.type),u={old_identifier_name:l,new_identifier_name:l,type:a.type,is_deleted:!1,current_checksum:await Ql(a.content)},c=e.get(a.path);if(c!==void 0&&(u.original_checksum=await Ql(c)),s[o]=u,a.type==="F"){const d=Xl(a.content);(d.length>0?d:[a.functionName].filter(Boolean)).forEach(p=>n.add(p))}}const r=new Set(Xl(e.get("lib/flutter_flow/custom_functions.dart")||"")),i={functions_to_rename:[],functions_to_delete:[],functions_to_add:Array.from(n).filter(o=>!r.has(o))};return{fileMapContents:JSON.stringify(s),functionsMapContents:JSON.stringify(i)}}const Xf=new Set(["CustomWidget","CustomAction","CustomFunction","CustomClass","CodeFile"]),ec={CustomWidget:"custom_code/widgets/",CustomAction:"custom_code/actions/",CustomFunction:"flutter_flow/custom_functions.dart",CustomClass:"custom_code/",CodeFile:"custom_code/"},Qf=new Set(["void","dynamic","String","int","double","num","bool","Color","DateTime","DateTimeRange","LatLng","FFPlace","FFUploadedFile","DocumentReference","List"]),eg=["Struct","Record"],tg=[{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=>Pi(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=>Pi(t).some(e=>{const s=/^\s*final\s+(?:double|int|String|bool|Color|num)\s+(\w+)\s*;/gm;let n;for(;(n=s.exec(e))!==null;){const r=n[1];if(!(new RegExp(`this\\.${r}\\s*=(?!=)`).test(e)||new RegExp(`[:,]\\s*${r}\\s*=(?!=)`).test(e)))return!0}return!1}),pos:`class W extends StatefulWidget { + const W({required this.value}); + final double value; +}`,neg:`class _P { + const _P({required this.t}); + final double t; +} +class W extends StatefulWidget { + const W({this.value = 1.0}); + final double value; +}`},{id:"asset-without-anchor",severity:"warning",message:'CustomWidget calls Image.asset with a path arriving as a String parameter. An asset reaches the build only when a FlutterFlow widget NODE references it - a filename passed as a parameter does not count, so the image renders as a broken-image icon on device. "Download Unused Project Assets" does not fix it (FlutterFlow issues 522, 2271, 3799). Keep something in the UI referencing the file, or load it over the network instead.',detect:t=>/Image\.asset\s*\(/.test(t)&&/final\s+String\??\s+\w*[Pp]ath\b/.test(t),pos:`class W extends StatefulWidget { final String? imagePath; } +var x = Image.asset(widget.imagePath);`,neg:`class W extends StatefulWidget { final String? imagePath; } +var x = Image.network(widget.imagePath);`},{id:"unsupported-param-type",severity:"error",message:"CustomWidget exposes a Flutter data type FlutterFlow cannot express as a Define Parameter: TextStyle, BoxShadow, FontWeight, FontStyle, TextDirection, TextAlign, EdgeInsets, Offset, Alignment/AlignmentGeometry, Border, BorderRadius, BoxDecoration, BoxConstraints, BorderSide, Gradient, or ThemeData. FlutterFlow's supported data types (docs.flutterflow.io/resources/data-representation/data-types) are only int, double, bool, string, Color, Image, DateTime, Json, LatLng, and the FF objects, so this parameter cannot be configured in the editor and the widget will not place or compile. Expose primitives instead (color, fontSize as double?, fontWeight via a custom enum, doubles for spacing).",detect:t=>Pi(t).some(e=>/final\s+(TextStyle|BoxShadow|FontWeight|FontStyle|TextDirection|TextAlign|EdgeInsets|Offset|Alignment(?:Geometry)?|Border(?:Radius|Side)?|BoxDecoration|BoxConstraints|Gradient|LinearGradient|RadialGradient|ThemeData)\??\s+\w+\s*;/.test(e)),pos:`class W extends StatefulWidget { + const W({this.textStyle}); + final TextStyle? textStyle; + @override _S createState() => _S(); +} +class _S extends State { @override Widget build(BuildContext c) => const SizedBox(); }`,neg:`class W extends StatefulWidget { + const W({this.width}); + final double? width; + @override _S createState() => _S(); +} +class _S extends State { @override Widget build(BuildContext c) => Padding(padding: const EdgeInsets.all(8), child: const SizedBox()); }`}];function Qe(t,e,s){return{artifactId:t.id,artifactName:t.artifactName,artifactType:t.artifactType,severity:e,message:s}}function ln(t){let e="",s=0;for(;s"&&(s--,s===0))return{inner:t.slice(e+1,n),end:n+1};return null}function ng(t,e){const s=new RegExp(`class\\s+${e}\\b[^{]*\\{`).exec(t);if(!s)return null;let n=0;for(let r=s.index+s[0].length-1;rrg(t).usable);function og(t=""){const e=ln(t);return ig.filter(s=>s.detect(e)).map(({id:s,severity:n,message:r})=>({id:s,severity:n,message:r}))}function ag(t){const e=[],s=t.matchAll(/\bFuture\b/g);for(const n of s){let r=n.index+6,i=null;const o=r;for(;ro;if(t[r]==="<"){const u=sg(t,r);if(!u||(i=u.inner.replace(/\s+/g," ").trim(),r=u.end,!/\s/.test(t[r]||"")))continue;for(;rtc(o.functionName)===n);if(r)return r;const i=o=>!o.functionName.startsWith("_");return s.find(i)||s[0]}function Nr(t=""){return Array.from(ln(t).matchAll(/\b(?:class|enum)\s+([A-Za-z_]\w*)/g),e=>e[1])}function lg(t="",e=""){return ra(t,e)?.returnType||null}function sc(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 cg(t,e){const s=Nr(e);if(s.length===0)return null;const r=String(t||"").split("/").pop().replace(/\.dart$/,"");if(s.some(l=>sc(l)===r)||s.length>1)return null;const[o]=s,a=`${sc(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 ia(t){return String(t||"").replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,"")}function ug(t,e,s=""){const n=ra(e,s)?.functionName;if(!n)return null;const r=String(t||"").split("/").pop(),i=na(r,"A");if(i===n)return null;const o=`${ia(n)}.dart`;return`File name "${r}" does not match Action "${n}". FlutterFlow derives the action from the file name, so it looks for "${i}" and reports Action "${i}" declaration not found. Rename the file to "${o}" - FlutterFlow puts an underscore before every capital - or rename the function to "${i}".`}function dg(t="",e=""){return ra(t,e)!==null}function hg(t,e=new Set){return(t?.match(/[A-Za-z_]\w*/g)||[]).filter(n=>Qf.has(n)?!1:!eg.some(i=>n.endsWith(i))||e.has(n))}function pg(t,{functionName:e="",declaredTypes:s=new Set}={}){const n=lg(t,e),r=hg(n,s);if(r.length===0)return null;const[i]=r;let o;return s.has(i)?o=`uses Code File type "${i}", which FlutterFlow cannot process as an Action Return Value`:n===i?o="is not a FlutterFlow Action Return Value":o=`uses type "${i}", which is not a FlutterFlow Action Return Value`,`CustomAction return type "${n}" ${o}. Return JSON (Future) or an existing FlutterFlow Data Type (*Struct) instead.`}function fg(t,e={}){const s=[],n=t.fileName||"",r=t.code||"";if(Xf.has(t.artifactType)||s.push(Qe(t,"error",`Unsupported artifact type "${t.artifactType}".`)),n.endsWith(".dart")||s.push(Qe(t,"error","FlutterFlow custom code artifacts must use .dart files.")),!r.trim())return s.push(Qe(t,"warning","Generated artifact has no Dart code yet.")),s;if(t.artifactType==="CustomWidget"){/class\s+\w+\s+extends\s+(StatelessWidget|StatefulWidget)/.test(r)||s.push(Qe(t,"warning","CustomWidget code should declare a widget class extending StatelessWidget or StatefulWidget."));for(const i of og(r))s.push(Qe(t,i.severity,i.message))}if(t.artifactType==="CustomAction"&&!dg(r,t.artifactName)&&s.push(Qe(t,"warning","CustomAction code should expose an async Future function callable from FlutterFlow.")),t.artifactType==="CustomAction"){const i=e.declaredTypes||new Set(Nr(r)),o=pg(r,{functionName:t.artifactName,declaredTypes:i});o&&s.push(Qe(t,"error",o));const a=ug(n,r,t.artifactName);a&&s.push(Qe(t,"error",a))}if(t.artifactType==="CustomFunction"&&/class\s+\w+\s+extends\s+(StatelessWidget|StatefulWidget)/.test(r)&&s.push(Qe(t,"warning","CustomFunction should be a callable function, not a widget class.")),t.artifactType==="CustomClass"||t.artifactType==="CodeFile"){const i=cg(n,r);i&&s.push(Qe(t,"info",i))}return s}function gg(t){const e=Array.isArray(t?.artifacts)?t.artifacts:[],s=new Set(e.flatMap(i=>Nr(i.code||""))),n=e.flatMap(i=>fg(i,{declaredTypes:s})),r=e.map(i=>({artifactId:i.id,fileName:i.fileName,pathHint:ec[i.artifactType]||ec.CodeFile}));return{valid:n.every(i=>i.severity!=="error"),findings:n,deployHints:r}}const nc="// DO NOT REMOVE OR MODIFY THE CODE ABOVE!";function rc(t){return(/^\s*import\s+['"]([^'"]+)['"]/.exec(t)||[])[1]||null}function mg(t=""){const e=t.indexOf(nc);return e===-1?t:t.slice(e+nc.length).replace(/^\s*\n/,"")}const vg=/^\s*import\s+['"][^'"]+['"]\s*;\s*(?:\/\/.*)?$/;function _g(t="",e=""){const s=mg(t),n=new Set((e.match(/^\s*import .*$/gm)||[]).map(rc).filter(Boolean)),r=s.split(` +`).filter(i=>{const o=rc(i);return o===null||!n.has(o)?!0:!vg.test(i)}).join(` +`).replace(/^\s*\/\/ Automatic FlutterFlow imports\s*$/m,"").replace(/^\s*\n+/,"");return e+r}const yg=new Set(["flutter","flutter_test","flutter_driver","flutter_localizations"]);function wd(t){let e="",s=0;for(;s{const n=s.name||s.package;if(!n||n==="flutter")return e;const r=s.versionRequired||s.required;return e[n]=r&&s.version||"",e},{})}function Sg(t){const e=new Map,s=new Map,n=[];for(const r of t)e.has(r.fileName)?n.push(`Duplicate deploy file name "${r.fileName}" for artifacts "${e.get(r.fileName)}" and "${r.artifactId}".`):e.set(r.fileName,r.artifactId),s.has(r.path)?n.push(`Duplicate deploy path "${r.path}" for artifacts "${s.get(r.path)}" and "${r.artifactId}".`):s.set(r.path,r.artifactId);return n}function xg(t,e={}){const s=Array.isArray(t?.artifacts)?t.artifacts:[],r=(e.selectedArtifactIds||t?.deployOrder||s.map(p=>p.id)).map(p=>s.find(f=>f.id===p)).filter(Boolean),i=[...t?.warnings||[]];let o=[];r.forEach(p=>{const f=Eg(p),g=p.fixedCode||p.code||"",m=p.codeType||wg[p.artifactType]||Ne.OTHER;g.trim()||i.push(`${p.artifactName||p.id} has no generated code.`),o.push({artifactId:p.id,artifactName:p.artifactName,artifactType:p.artifactType,fileName:f,content:g,type:m,path:p.deployPath||bg(f,m),deployPath:p.deployPath||"",deployMode:"customCodeSync"})});const a="lib/flutter_flow/custom_functions.dart",l=o.map((p,f)=>({entry:p,index:f})).filter(({entry:p})=>p.type===Ne.FUNCTION&&p.path===a);if(l.length>1){const p=l[0],f={...p.entry,artifactId:l.map(({entry:m})=>m.artifactId).join("+"),artifactName:p.entry.artifactName,content:l.map(({entry:m})=>`// ${m.artifactId} +${m.content}`).join(` + +`)},g=new Set(l.slice(1).map(({index:m})=>m));o=o.filter((m,_)=>!g.has(_)),o[p.index]=f}const u={...ic(t?.dependencies),...r.reduce((p,f)=>({...p,...ic(f.dependencies)}),{})},c={};r.forEach(p=>{oa(p.code||"").forEach(f=>{f in u||(c[f]="")})});const d={...c,...u},h=Sg(o);return{bundleId:t?.id||"bundle-current",title:t?.title||"Generated artifact bundle",fileEntries:o,dependencies:d,relationships:t?.relationships||[],warnings:i,errors:h}}function kg(t){return String(t||"").match(/\bclass\s+([A-Z][A-Za-z0-9_]*)\b/)?.[1]}function Ig(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 Cg(t,e){const n=[Ig(t),kg(e.content),e.artifactName].find(r=>/^[A-Z][A-Za-z0-9_]*$/.test(String(r||"")));if(!n)throw new Error(`Cannot derive a FlutterFlow custom class name for ${t}.`);return n}function Fg(t,e=new Map){const s=[];for(const[n,r]of t.entries())r.type!=="C"||e.has(r.path)||s.push({artifactId:r.artifactId||n,className:Cg(n,r),content:r.content,fileName:n,path:r.path});return s}function Pg(t,e){const s=new Set(e.map(n=>n.path));return new Map(Array.from(t.entries()).filter(([,n])=>!s.has(n.path)))}const oc={pass:0,warning:1,fail:2},Ag=["manualActions"];function De(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function gt(...t){for(const e of t){if(typeof e=="string"&&e.trim())return e.trim();if(Array.isArray(e)&&e.length>0){const s=e.filter(n=>typeof n=="string").join(` +`);if(s)return s}}return""}function tt(t){return t==null?[]:Array.isArray(t)?t:[t]}function $g(t){const e=De(t).value??t;if(e==null||typeof e=="string"&&e.trim()==="")return null;const s=Number(e);if(Number.isFinite(s))return s;const n=String(t||"").match(/\bscore\b[^\d]{0,12}(\d{1,3})(?:\s*\/\s*100)?/i);return n?Number(n[1]):null}function We(t){return String(t||"").trim().replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function aa(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 wo(...t){return t.filter(Boolean).reduce((e,s)=>oc[s]>oc[e]?s:e,"pass")}function Ed(t,e="warning",s="review"){if(typeof t=="string")return{severity:e,message:t,suggestion:"",source:s};const n=De(t),r=gt(n.message,n.title,n.issue,n.description,n.summary);return r?{severity:aa(n.severity||n.status||n.level)||e,message:r,suggestion:gt(n.suggestion,n.fix,n.recommendation,n.action),source:n.source||s}:null}function bo(t,e="review"){const s=De(t);return[["findings","warning"],["issues","warning"],["criticalIssues","fail"],["errors","fail"],["warnings","warning"],["recommendations","warning"],["requiredFixes","fail"],["suggestions","warning"]].flatMap(([r,i])=>tt(s[r]).map(o=>Ed(o,i,e)).filter(Boolean))}function Rg(t,e,s=null){if(typeof t=="string")return{id:`${s||"bundle"}-manual-${e+1}`,title:t,detail:"",location:"",timing:"unspecified",artifactId:s,source:"Code Review"};const n=De(t),r=gt(n.title,n.action,n.step,n.message,n.name,n.description);return r?{id:n.id||`${s||"bundle"}-manual-${e+1}`,title:r,detail:gt(n.detail,n.instructions,n.description),location:gt(n.location,n.flutterFlowPath,n.path),timing:gt(n.timing,n.phase)||"unspecified",artifactId:s,source:gt(n.source)||"Code Review"}:null}function Eo(t,e=null){const s=De(t);return Ag.flatMap(n=>tt(s[n])).map((n,r)=>Rg(n,r,e)).filter(Boolean)}function Tg(t){let e=typeof t=="string"?_o(t):t;if(!e&&typeof t=="string")return{rawText:t,root:{}};const s=De(e);typeof s.content=="string"&&(e=_o(s.content)||e);const n=De(e),r=De(n.reviewResult||n.codeReview||n.result);return{rawText:"",root:Object.keys(r).length?r:n}}function Ng(t,e){const s=[e.id,e.fileName,e.artifactName].map(We);return t.find(n=>{const r=De(n);return[r.id,r.fileName,r.artifactName,r.name].map(We).some(i=>i&&s.includes(i))})||null}function Mg(t,e){return tt(t?.metadata?.compatibility?.deployHints).find(r=>We(r?.artifactId)===We(e.id)||We(r?.fileName)===We(e.fileName))?.pathHint||""}function Lg(t,e){return tt(t?.relationships).filter(s=>We(s?.from)===We(e.id)||We(s?.to)===We(e.id))}function Og(t,e){return tt(t?.metadata?.compatibility?.findings).filter(s=>!s?.artifactId||We(s.artifactId)===We(e.id)).map(s=>Ed(s,"warning","Compatibility check")).filter(Boolean)}function Dg(t,e,s,n){const r=Ng(e,s),i=De(r?.review||r||s.review),o=Object.keys(i).length>0,a=[...bo(i),...Og(t,s)],l=Eo(i,s.id),u=aa(i.status||i.verdict||i.outcome||i.result),c=a.length?wo(...a.map(h=>h.severity)):null,d=wo(u,c,o?null:"warning");return{...s,index:n,status:d,statusReason:o?gt(i.summary,i.overview,i.assessment,i.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 i.fixedSource=="string"&&i.fixedSource.trim()?i.fixedSource.trim():null,pathHint:Mg(t,s),relationships:Lg(t,s)}}function Bg({status:t,score:e,artifactPresentations:s,manualSteps:n}){const r=s.length;if(r===0&&n.length===0)return e==null?"Code review returned no overall summary and no score.":`Reviewed bundle with score ${e}/100.`;const i=s.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"}: ${i.pass} pass, ${i.warning} warn, ${i.fail} fail.`),n.length&&o.push(`Do before deploy: ${n.map(a=>a.title).join("; ")}.`),e==null&&o.push("No numeric score (0-100) was returned."),o.join(" ")}function jg({bundle:t,reviewResult:e}){const s=De(t),n=tt(s.artifacts),{root:r,rawText:i}=Tg(e),o=[r.bundleReview,r.overallReview,r.overall,r.bundleSummary,r.summaryReview,r.review].map(De).find(E=>Object.keys(E).length)||{},a=tt(r.artifacts||r.files||r.reviews),l=n.map((E,I)=>Dg(s,a,E,I)),u=bo(r),d=[...bo(o),...u],h=[...Eo(o),...Eo(r),...l.flatMap(E=>E.manualSteps)].filter((E,I,F)=>F.findIndex(P=>P.title===E.title&&P.artifactId===E.artifactId)===I),p=aa(o.status||o.verdict||o.overallStatus||r.status||r.verdict||r.overallStatus||r.outcome),f=wo(p,...d.map(E=>E.severity),...l.map(E=>E.status)),g=o.score??r.score??r.overallScore??i,m=$g(g),_=gt(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,i)||Bg({status:f,score:m,artifactPresentations:l,manualSteps:h}),w=l.reduce((E,I)=>(E[I.status]+=1,E),{pass:0,warning:0,fail:0});return{title:s.title||"Generated artifact bundle",description:s.description||"",status:f,score:m,summary:_,findings:d,manualSteps:h,artifacts:l,counts:w,reviewCoverage:{reviewed:l.filter(E=>E.reviewComplete).length,total:l.length},deployOrder:tt(s.deployOrder),relationships:tt(s.relationships),warnings:tt(s.warnings),compatibility:De(s.metadata?.compatibility)}}const Ug=/^\uFEFF/;function Os(t){let e=0,s=t.length;for(;ee&&!t[s-1].trim();)s--;return t.slice(e,s).join(` +`)}function Hg(t){const e=String(t??"").replace(Ug,"");if(!e.trim())return"";const s=e.split(` +`),n=c=>{const d=c.trim();return/^`{3,}[A-Za-z0-9+#_.-]*$/.test(d)?c.length-c.trimStart().length:-1};let r=0,i=-1;const o=[];{let c=0;for(let d=0;d=0&&(r++,i<0&&(i=d),o.push(c+h)),c+=s[d].length+1}}if(r===0)return Os(s);{const c=So(e);if(!c.error&&o.every(h=>lc(h,c.commentAndStringRanges)))return Os(s)}if(r===1){const c=Os(s.slice(0,i)),d=Os(s.slice(i+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 Wg(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 Sd(t){const e=Wg(t);return Array.from(e.matchAll(/class\s+([A-Z]\w*)\s+extends\s+[A-Za-z_]\w*Widget\b/g),s=>s[1])}function xd(t){return`${ia(t)}.dart`}function zg(t){return na(t,"W")}const ac={"(":")","[":"]","{":"}"},qg={")":"(","]":"[","}":"{"},Vg=/[A-Za-z0-9_]/;function So(t){const e=[{kind:"code",opener:null,openedLine:0}],s=[];let n=1,r=0;const i=(c,d)=>{(c===` +`||c==="\r"&&d!==` +`)&&n++};let o=null;const a=()=>{for(const c of e)(c.kind==="string"||c.kind==="block-comment"||c.kind==="line-comment")&&s.push({start:c.startIndex,end:t.length})};for(;r0?t[r-1]:"",f=r>1?t[r-2]:"",g=(p==="r"||p==="R")&&!Vg.test(f);e.push({kind:"string",quote:c,triple:h,raw:g,startIndex:r,openedLine:n}),r+=h?3:1;continue}if(ac[c]){e.push({kind:"code",opener:c,openedLine:n}),r++;continue}if(qg[c]){if(d.interpolation&&c==="}"){e.pop(),r++;continue}if(d.opener&&ac[d.opener]===c){e.pop(),r++;continue}return d.opener?(a(),{error:o??`line ${n}: "${c}" closes nothing - "${d.opener}" opened on line ${d.openedLine} is still open`,commentAndStringRanges:s}):(a(),{error:o??`line ${n}: unexpected "${c}" with no matching opener`,commentAndStringRanges:s})}i(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:s}}function Gg(t){return So(String(t??"")).error}function lc(t,e){return e.some(({start:s,end:n})=>t>=s&&ttypeof s=="string"?s:s?.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 Kg=["gmail.com","googlemail.com","outlook.com","hotmail.com","live.com","msn.com"],Jg="MAGIC_LINK_SENT",Yg="PLUS_ALIAS_REJECTED",Zg="Please enter your primary email address. Plus aliases (such as {email}) are not allowed for {domain} accounts.",Mr={allowlistedDomains:Kg,successCode:Jg,validationCode:Yg,messageTemplate:Zg},Xg=new Set(Mr.allowlistedDomains),Qg=Mr.successCode,Un=Mr.validationCode;function Lr(t){return typeof t=="string"?t.trim():""}function em(t){const e=Lr(t),s=e.lastIndexOf("@");if(s<=0||s===e.length-1)return!1;const n=e.slice(0,s),r=e.slice(s+1).toLowerCase();return Xg.has(r)?n.includes("+"):!1}function tm(t,e){return Mr.messageTemplate.replaceAll("{email}",t).replaceAll("{domain}",e)}function Id(t){if(!em(t))return null;const e=Lr(t),s=e.lastIndexOf("@"),n=e.slice(s+1).toLowerCase();return tm(e,n)}function sm(t,e){return t?.code===Un?t.message||Id(e)||"Please enter your primary email address.":t?.code===Qg||!t?.code?`Check your email — we sent a link to ${Lr(e)}`:t.message||"Something went wrong. Please try again."}const nm=/^dependencies\s*:\s*(?:#.*)?$/,rm=/^(?:"([^"]+)"|'([^']+)'|([A-Za-z_][A-Za-z0-9_-]*))\s*:/;function Or(t){const e=t.match(rm);return e?e[1]??e[2]??e[3]:null}function fn(t){const e=t.trim();return e===""||e.startsWith("#")}function xs(t){const e=t.match(/^(\s*)/);return e?e[1].length:0}function la(t,e){const s=t.findIndex(i=>e.test(i));if(s===-1)return null;let n=s,r=null;for(let i=s+1;i=0.0.0"}`}function lm(t,e={}){const s=String(t||""),n=Object.entries(e).filter(([u])=>u&&u!=="flutter");if(n.length===0)return{yaml:s,added:[],alreadyPresent:[]};const r=s.split(` +`),i=new Set(Fd(s)),o=[],a=[];for(const[u,c]of n)i.has(u)?a.push(u):(o.push([u,c]),i.add(u));if(o.length===0)return{yaml:s,added:[],alreadyPresent:a};const l=ca(r);if(l){const u=o.map(([c,d])=>cc(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(cc(" ",u,c))});return{yaml:r.join(` +`),added:o.map(([u])=>u),alreadyPresent:a}}function cm(t,e={}){const s=String(t||""),n=Object.entries(e).filter(([l])=>l&&l!=="flutter");if(n.length===0)return{yaml:s,overridden:[],skipped:[]};const r=s.split(` +`),i=Br(s),o=[],a=[];for(const[l,u]of n){const c=i.get(l);if(!c||!c.isScalar||!String(u||"").trim()){a.push(l);continue}const d=" ".repeat(xs(r[c.lineIndex]));r[c.lineIndex]=`${d}${l}: ${Ad(String(u).trim())}${c.comment}`,o.push({name:l,from:c.constraint,to:u})}return{yaml:r.join(` +`),overridden:o,skipped:a}}function $d(t){const e=String(t||""),s=[];return e.trim()?(/^name:\s*\S+/m.test(e)||s.push("pubspec.yaml missing name field"),ca(e.split(` +`))||s.push("pubspec.yaml missing dependencies section"),Fd(e).includes("flutter")||s.push("pubspec.yaml missing Flutter SDK dependency"),{valid:s.length===0,errors:s}):(s.push("pubspec.yaml is empty"),{valid:!1,errors:s})}const um=">=3.0.0 <4.0.0";function xo(t){const e=String(t||"").trim(),s=e[0];return s!=="'"&&s!=='"'||e[e.length-1]!==s?e:e.slice(1,-1).replaceAll(`${s}${s}`,s)}function dm(t=""){const e=bd(t).filter(s=>!s.startsWith("dart:")&&!s.startsWith("package:"));return{selfContained:e.length===0,unresolvableImports:e}}function uc(t,e,s){const n=[];for(const[r,i]of t){if(i.isScalar){e[r]=xo(i.constraint);continue}if(i.sourceKey==="sdk"){s.add(r);continue}if(i.sourceKey===null&&i.version){e[r]=xo(i.version);continue}n.push(r)}return n}function hm(t){const e=new Set,s={},n={},r=uc(Br(t),s,e);r.push(...uc(om(t,"dependency_overrides"),n,e));const i=new Set([...Object.keys(s),...e]),{sdk:o}=Pd(t);return{sdkConstraint:xo(o)||um,dependencies:s,overrides:n,sdkPackages:[...e].sort(),availablePackages:i,unrepresentable:r}}function pm(t,e,s){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 ${s.join(", ")}, which your project's pubspec.yaml does not declare with a version constraint, so it could not be compiled before the deploy.`}function fm(t,e){return`${t} was not compiled before deploying: your project declares ${e.join(", ")} from a source that cannot be reproduced outside it, and whether the packages ${t} imports depend on one of them transitively cannot be checked before the deploy, so package resolution could not be matched exactly.`}function gm(t,e){const{sdkConstraint:s,dependencies:n,overrides:r,sdkPackages:i,availablePackages:o,unrepresentable:a}=hm(e),l={sdkConstraint:s,dependencies:n,overrides:r,sdkPackages:i},u=[],c=[];for(const d of t){const{className:h,content:p}=d,f=oa(p),g=f.filter(w=>a.includes(w));if(g.length>0){c.push({className:h,reason:`${h} was not compiled before deploying: it imports ${g.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:m}=dm(p),_=f.filter(w=>!o.has(w));if(m.length>0||_.length>0){c.push({className:h,reason:pm(h,m,_)});continue}if(a.length>0&&bd(p).some(w=>w.startsWith("package:"))){c.push({className:h,reason:fm(h,a)});continue}u.push({fileName:`${ia(h)}.dart`,content:p})}return{manifest:l,sources:u,skipped:c}}function dc(t,e){const s=`${t}${e}`.split(` +`),n=s.pop()??"",r=[];for(const i of s){const o=Rd(i);o&&r.push(o)}return{events:r,buffer:n}}function mm(t){const e=Rd(t);return e?[e]:[]}function Rd(t){const e=t.trim();if(!e)return null;try{const s=JSON.parse(e);return s&&typeof s=="object"&&!Array.isArray(s)?s:null}catch{return null}}async function vm(t,e={}){const{onPhase:s,onLog:n}=e;let r=null,i="";const o=a=>{if(a.event==="phase"){a.message&&s&&s(a.message);return}if(a.event==="log"){a.message&&n&&n(a.message);return}r=a};if(t.body?.getReader){const a=t.body.getReader(),l=new TextDecoder;for(;;){const{done:u,value:c}=await a.read();if(u)break;const d=dc(i,l.decode(c,{stream:!0}));i=d.buffer,d.events.forEach(o)}}else{const a=dc("",await t.text());i=a.buffer,a.events.forEach(o)}return mm(i).forEach(o),r?{...r,success:r.success===!0||r.success===void 0&&t.ok}:{success:!1,error:t.ok?"The FlutterFlow deploy runner closed the connection before it finished.":`FlutterFlow custom class provisioning failed (HTTP ${t.status}).`}}const _m=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;function wt(t){const e=String(t||"").trim().match(_m);return e?{major:Number(e[1]),minor:Number(e[2]),patch:Number(e[3]),prerelease:e[4]?e[4].split("."):[]}:null}function ym(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 s=0;s0)}function bm(t){const e=wt(t);return e?e.major>0?`${e.major+1}.0.0`:`0.${e.minor+1}.0`:null}function ua(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 wt(o)?{min:o,minInclusive:!0,max:bm(o),maxInclusive:!1}:null}if(wt(e))return{min:e,minInclusive:!0,max:e,maxInclusive:!0};const s={min:null,minInclusive:!1,max:null,maxInclusive:!1},n=/(>=|<=|>|<)\s*([0-9][0-9A-Za-z.+-]*)/g;let r=!1,i;for(;(i=n.exec(e))!==null;){const[,o,a]=i;if(!wt(a))return null;r=!0,o===">="||o===">"?(s.min=a,s.minInclusive=o===">="):(s.max=a,s.maxInclusive=o==="<=")}return r?s:null}function hc(t,e){const s=ua(t);if(!s||!wt(e))return!1;if(s.min!==null){const n=_r(e,s.min);if(n<0||n===0&&!s.minInclusive)return!1}if(s.max!==null){const n=_r(e,s.max);if(n>0||n===0&&!s.maxInclusive)return!1}return!0}function Em(t,e){const s=ua(t);if(!s||!wt(e))return!1;if(s.max===null)return!0;const n=_r(s.max,e);return n>0?!0:n===0&&s.maxInclusive}function rs(t){const e=ua(t);return e?e.min:null}const Sm="https://pub.dev/api/packages/",xm=8e3;function km(t,e={}){const{dartSdkFloor:s=null,flutterSdkFloor:n=null}=e,r=Array.isArray(t?.versions)?t.versions:[];let i=null;for(const o of r){const a=o?.version;if(!a||o.retracted||wm(a))continue;const l=o.pubspec?.environment||{};s&&l.sdk&&!hc(l.sdk,s)||n&&l.flutter&&!hc(l.flutter,n)||(!i||_r(a,i)>0)&&(i=a)}return i?{version:i,constraint:`^${i}`}:null}async function Im(t,e={}){const{dartSdkFloor:s=null,flutterSdkFloor:n=null,fetchImpl:r=fetch}=e;let i;try{const a=await r(`${Sm}${encodeURIComponent(t)}`,{signal:AbortSignal.timeout(xm)});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}"`};i=await a.json()}catch(a){return{name:t,constraint:null,version:null,error:`could not reach pub.dev for "${t}" (${a.message})`}}const o=km(i,{dartSdkFloor:s,flutterSdkFloor:n});return o?{name:t,...o,error:null}:{name:t,constraint:null,version:null,error:s?`no published "${t}" release supports Dart ${s}`:`no published "${t}" release could be read`}}async function Cm(t,e={}){const s=await Promise.all(t.map(n=>Im(n,e)));return new Map(s.map(({name:n,...r})=>[n,r]))}async function Fm(t,e={},s={}){const{resolveVersions:n=Cm}=s,r=Object.entries(e).filter(([c])=>c&&c!=="flutter"),i=Pd(t),o={dartSdkFloor:rs(i.sdk),flutterSdkFloor:rs(i.flutter)},a={additions:{},overrides:{},kept:[],warnings:[],sdk:o};if(r.length===0)return a;const l=Br(t),u=[];for(const[c,d]of r){const h=l.get(c);if(!h){u.push(c);continue}const p=rs(d);if(!p){a.kept.push({name:c,constraint:h.constraint});continue}if(!h.isScalar){a.warnings.push(`"${c}" is declared in your project from a git, path, or SDK source, but the generated code needs at least ${p}. Left as-is — update it yourself if the build fails.`),a.kept.push({name:c,constraint:h.constraint});continue}if(Em(h.constraint,p)){a.kept.push({name:c,constraint:h.constraint});continue}a.overrides[c]=`^${p}`,a.warnings.push(`"${c}" was pinned to ${h.constraint} in your project, which cannot resolve the ${p} the generated code needs. Raising it to ^${p} — this changes a dependency the rest of your app also uses.`)}if(u.length>0){const c=await n(u,o);for(const d of u){const h=c.get(d);if(h?.constraint){a.additions[d]=h.constraint;continue}const p=e[d]||"";if(rs(p)){a.additions[d]=`^${rs(p)}`,a.warnings.push(`Could not confirm "${d}" version on pub.dev (${h?.error||"lookup failed"}). Using ^${rs(p)} from the AI's recommendation — verify this is current.`);continue}a.additions[d]=">=0.0.0",a.warnings.push(`Could not determine a version for "${d}" (${h?.error||"lookup failed"}) and the AI supplied none. Added with a wide-open >=0.0.0 constraint — pin a concrete version in FlutterFlow before deploying.`)}}return a}const Pm={"&":"&","<":"<",">":">",'"':""","'":"'"};function bt(t){return String(t??"").replace(/[&<>"']/g,e=>Pm[e])}function j(t){return t?bt(t).replace(/\n/g,"
    "):""}function It(t){return bt(t).replace(/\r?\n/g," ")}function Am(t,e={}){const s=t?.pipelineStep;if(s!=null&&e[s]!=null)return e[s];const n=t?.message||"";return n.includes("Code Generator")?2:n.includes("Code Review")?3:1}function $m(t){const e={"Integration Audit Report":"📋","Critical Issues":"❌",Warnings:"⚠️",Recommendations:"✅","Overall Score":"📊"};for(const[s,n]of Object.entries(e))if(t.toLowerCase().includes(s.toLowerCase()))return n;return"📄"}function Rm(t){const e={critical:"❌",warning:"⚠️",recommendation:"✅",score:"📊",issue:"🔍",fix:"🔧"};for(const[s,n]of Object.entries(e))if(t.toLowerCase().includes(s.toLowerCase()))return n;return"📝"}function Tm(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 ws(t){if(!t)return"";if(typeof t!="string")return String(t);const e=/```(?:\w+)?\n?([\s\S]*?)```/,s=t.match(e);return s?s[1].trim():t.trim()}function pc(t){return t=bt(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 Td(t,e="dart",s=globalThis.hljs){if(!t)return"";const n=ws(t);try{return s.highlight(n,{language:e}).value}catch(r){console.warn("Syntax highlighting failed:",r);try{return s.highlight(n,{language:"json"}).value}catch{return bt(n)}}}function jr(t,e={}){const{highlighter:s=globalThis.hljs}=e;let n='
    ';const r=String(t??"").split(` +`);let i=!1,o="";for(const a of r){if(a.startsWith("```")){if(i){const l=Tm(o),u=Td(o.trim(),l,s);n+=`
    +
    ${u}
    +
    `,o="",i=!1}else i=!0;continue}if(i){o+=a+` +`;continue}if(a.startsWith("# ")){const l=a.substring(2).trim();n+=`
    +

    + ${$m(l)} + ${bt(l)} +

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

    + ${Rm(l)} + ${bt(l)} +

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

    ${pc(a)}

    `)}return n+="
    ",` +
    +
    +
    + Live Audit Report +
    + ${n} +
    + `}const Nm="https://ccc-ffai-runner-y5cyj3473a-uw.a.run.app/deployCustomClasses";const Je="https://4tgke4.buildship.run",Nd={professional:"price_1T2ldCKszA2slvDXatdeCpbI",power:"price_1T2le9KszA2slvDXR4mPvw7M"},yr="ccc_auth_session",fc=new WeakSet;let G={email:null,sessionToken:null,isVerified:!1};function bs(t={}){return{tier:"free",status:"none",periodEnd:null,isLoading:!1,isResolved:!1,error:null,...t}}let fe=bs({isResolved:!0});const Mm=`${Je}/service/runpipeline`,Lm="bs_user_id",Om="bs_identity_token",Dm=`${Je}/authUserCheck`;let Ge={userId:null,token:null,status:null,resolved:!1};const wr={free:2,professional:50,power:2e3},br="ccc_subscription",gc=3,Bm=new Set(["active","trialing","paid"]),cn="google/gemini-3.7-flash",Hn=["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"],jm={"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 zt(t){return jm[t]||t}const Um=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 Md(t){return Um.has(t)}const ko=4,Ai=8*1024*1024,Hm="https://4tgke4.buildship.run/service/runpipeline-image";let Pt=[];function Wm(t){return new Promise(e=>{const s=new FileReader;s.onload=()=>e(s.result),s.onerror=()=>e(null),s.readAsDataURL(t)})}async function zm(t){const e=new FormData;return e.append("file",t),(await fetch(Hm,{method:"POST",body:e})).json()}function qm(t){if(Array.isArray(t)){const e=t[0];if(e&&typeof e=="object")for(const s of Object.keys(e)){if(s==="item"||s==="index")continue;const n=e[s];if(n&&typeof n=="object"){if(typeof n.file=="string")return n.file;if(typeof n.url=="string")return n.url}if(typeof n=="string")return n}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 Vm(t){const e=Array.from(t.target.files||[]);if(!e.length)return;const s=e.filter(l=>l.size>Ai);s.length&&ue(`Skipped ${s.length} image(s) over the ${(Ai/1024/1024).toFixed(0)} MB limit.`,"warning");const n=e.filter(l=>l.size<=Ai);if(!n.length){t.target.value="";return}const r=ko-Pt.length,o=n.slice(0,r).map(async l=>{const u=await Wm(l);if(!u)return null;let c="";try{c=qm(await zm(l))}catch{c=""}return{dataUrl:u,name:l.name,url:c}}),a=(await Promise.all(o)).filter(Boolean);t.target.value="",!(a.length&&!Md(document.getElementById("code-generator-model")?.value))&&(Pt.push(...a),n.length>r&&ue(`You can attach up to ${ko} images.`,"info"),da())}function Gm(t){Pt.splice(t,1),da()}function da(){const t=document.getElementById("prompt-image-thumbnails"),e=document.getElementById("prompt-image-btn-label");t&&(t.innerHTML="",Pt.forEach((s,n)=>{const r=document.createElement("div");r.className="prompt-img-thumb",r.innerHTML=`Prompt image`,t.appendChild(r)}),e&&(e.textContent=Pt.length>=ko?"Image limit reached":"Add images"))}function Ld(){const t=document.getElementById("prompt-image-upload");if(!t)return;const e=document.getElementById("code-generator-model"),s=Md(e?.value);t.classList.toggle("hidden",!s),!s&&Pt.length&&(Pt=[],da())}const Gt="ccc_usage",Od="google/gemini-3.7-flash",Dd="google/gemini-3.7-flash",$i="google/gemini-3.7-flash",mc={professional:11,power:49},Io={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"},Wn={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 zn={...Wn};async function Km(){const t=new AbortController,e=setTimeout(()=>t.abort(),5e3);try{const s=await fetch("https://open.er-api.com/v6/latest/AUD",{signal:t.signal});if(!s.ok)return;const n=await s.json();if(n.result!=="success"||!n.rates)return;const r=n.rates,i={AUD:1},o=new Set([...Object.keys(Wn),...Object.values(Co),...Object.values(Io)]);for(const a of o)a!=="AUD"&&(typeof r[a]=="number"&&r[a]>0?i[a]=r[a]:Wn[a]&&(i[a]=Wn[a]));zn=i}catch{}finally{clearTimeout(e)}}const Co={"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 Bd(){try{const i=Intl.DateTimeFormat().resolvedOptions().timeZone;if(i&&Co[i])return Co[i]}catch{}const e=(navigator.language||"en-US").replace("-","_"),s=Io[e];if(s)return s;const n=e.split("_")[0],r=Io[n];return r||"USD"}function vc(t,e){const s=zn[e]??zn.USD,n=t*s,r=Math.round(n*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*zn.USD)}}const st="ccc_api_key_",_t="ccc_session_api_key_",it="ccc_encryption_key",un="ccc_encryption_key_scope",Jm="ccc_keystore",Er="keys",dn="ccc_encryption_key_version";let Fo=null,Sr=null,hn=!1,xr=!1,_c=!1;class kr extends Error{constructor(){super("Secure browser key storage is unavailable."),this.name="CredentialStorageUnavailableError"}}function yc(){if(_c)return;_c=!0;const t="Secure browser key storage is unavailable. Existing credentials were left untouched; new credentials will be available only in this tab session.";console.warn(t),document.body&&ue(t,"warning")}function jd(){return localStorage.getItem(dn)||""}function Po(){return crypto.randomUUID?.()||Hd(crypto.getRandomValues(new Uint8Array(16)))}function Ym(){const t=jd();if(t)return t;const e=Po();return localStorage.setItem(dn,e),e}function Es(){Fo=null,Sr=null,hn=!1,xr=!1}window.addEventListener("storage",t=>{t.key===dn&&Es()});function Zm(){return new Promise((t,e)=>{const s=indexedDB.open(Jm,1);s.onupgradeneeded=()=>{const n=s.result;n.objectStoreNames.contains(Er)||n.createObjectStore(Er)},s.onsuccess=()=>t(s.result),s.onerror=()=>e(s.error)})}async function ha(t,e){const s=await Zm();return new Promise((n,r)=>{const i=s.transaction(Er,t);let o;try{o=e(i.objectStore(Er))}catch(l){s.close(),r(l);return}let a;o.onsuccess=()=>{a=o.result},o.onerror=()=>r(o.error),i.oncomplete=()=>{s.close(),n(a)},i.onerror=()=>{s.close(),r(i.error||new Error("Encryption key transaction failed."))},i.onabort=()=>{s.close(),r(i.error||new Error("Encryption key transaction aborted."))}})}function Xm(t){return t instanceof CryptoKey&&t.algorithm?.name==="AES-GCM"&&t.extractable===!1&&t.usages.includes("encrypt")&&t.usages.includes("decrypt")}async function Qm(){const t=await ha("readonly",e=>e.get(it));return Xm(t)?t:null}async function Ud(t){await ha("readwrite",e=>e.put(t,it))}async function ev(){Es();try{await ha("readwrite",t=>t.delete(it))}catch(t){console.warn("Could not delete the stored encryption key:",t)}}async function tv(){const t=sessionStorage.getItem(it);if(!t)return null;const e=await crypto.subtle.importKey("jwk",JSON.parse(t),{name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);return await Ud(e),sessionStorage.removeItem(it),sessionStorage.removeItem(un),localStorage.removeItem(st+"salt"),e}async function wc(t){const e=sessionStorage.getItem(it);if(e)return xr=sessionStorage.getItem(un)!=="session",crypto.subtle.importKey("jwk",JSON.parse(e),{name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);if(!t)throw new kr;const s=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!0,["encrypt","decrypt"]),n=await crypto.subtle.exportKey("jwk",s);return sessionStorage.setItem(it,JSON.stringify(n)),sessionStorage.setItem(un,"session"),xr=!1,crypto.subtle.importKey("jwk",n,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}async function sv(t){if(sessionStorage.getItem(un)==="session"&&sessionStorage.getItem(it))return yc(),hn=!0,wc(t);try{const e=await Qm();if(e)return e;const s=await tv();if(s)return s;const n=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);return await Ud(n),n}catch(e){return console.warn("IndexedDB encryption-key storage failed:",e),yc(),hn=!0,wc(t)}}async function pa(t={}){const{allowSessionFallbackCreation:e=!0}=t,s=Ym();Sr!==s&&Es();const n=Fo||sv(e);Fo=n,Sr=s;try{return await n}catch(r){throw Es(),r}}async function nv(t){const e=await pa(),s=Sr,n=new TextEncoder,r=crypto.getRandomValues(new Uint8Array(12)),i=await crypto.subtle.encrypt({name:"AES-GCM",iv:r},e,n.encode(t)),o=new Uint8Array(r.length+i.byteLength);return o.set(r),o.set(new Uint8Array(i),r.length),{ciphertext:Hd(o),keyVersion:s,sessionFallback:hn}}async function rv(t,e={}){const{isSessionCredential:s=!1}=e;try{const n=await pa({allowSessionFallbackCreation:!1});if(hn&&!s&&!xr)throw new kr;const r=iv(t),i=r.slice(0,12),o=r.slice(12),a=await crypto.subtle.decrypt({name:"AES-GCM",iv:i},n,o);return new TextDecoder().decode(a)}catch(n){if(n instanceof kr)throw n;return console.error("Decryption failed:",n),null}}function Hd(t){const e=new Uint8Array(t);let s="";for(let n=0;n0}let pn="",Ir="",Zs=null,Ec=0;async function fa(){sessionStorage.getItem(it)&&await pa(),pn=await Ee("flutterflow"),Ir=await Ee("flutterflow_project_id"),uv(),Zt()}function ga(){document.getElementById("api-keys-modal").classList.add("open"),va(),pn&&Vd(pn)}function Wd(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("api-keys-modal");e&&e.classList.remove("open");const s=document.getElementById("walkthrough-modal");s&&(ma(),s.classList.add("open"))}let Et=1;function zd(){const t=document.querySelector(".wt-steps");return t?Array.from(t.querySelectorAll(".wt-step-card")):[]}function Ur(){const t=zd();t.length&&t.forEach((e,s)=>{const n=s+1;if(n===Et){e.classList.remove("opacity-60","bg-gray-50","border-gray-200"),e.classList.add("bg-blue-50","border-blue-200");const r=e.querySelector("div:first-child");r&&(r.classList.remove("bg-gray-400"),r.classList.add("bg-blue-500"),r.innerHTML=n)}else if(n0&&Et<=t&&(Et++,Ur())}function av(){const t=document.getElementById("walkthrough-modal");t&&(Et=1,Ur(),t.classList.add("open"))}function lv(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("walkthrough-modal");e&&e.classList.remove("open");const s=document.getElementById("walkthrough-dont-show");s&&s.checked&&localStorage.setItem("hasSeenWalkthrough","true")}function qd(){if(G.isVerified&&Jt()&&fe.tier!=="free")return;if(!localStorage.getItem("hasSeenWalkthrough")){const e=document.getElementById("walkthrough-modal");e&&(Et=1,Ur(),e.classList.add("open"))}}async function va(){const t=document.getElementById("flutterflow-api-key-input");pn?(t.value="",t.placeholder="Key saved (enter new to replace)"):t.placeholder="Enter your FlutterFlow API key",cv()}function cv(){Sc("flutterflow","flutterflow-key-status"),Sc("flutterflow_project_id","flutterflow-project-status")}function Sc(t,e){const s=document.getElementById(e);if(!s)return;const n=s.querySelector(".key-status-dot"),r=s.querySelector("span");as(t)?(n.className="key-status-dot configured",r.className="text-green-600",r.textContent="User key configured"):(n.className="key-status-dot missing",r.className="text-gray-500",r.textContent="Not configured")}function Zt(){const t=y.step2Result&&y.step2Result.length>0,e=document.getElementById("btn-deploy-to-ff"),s=document.getElementById("btn-run-pipeline");s&&s.classList.remove("hidden"),e&&e.classList.toggle("hidden",!t)}function uv(){const t=document.getElementById("api-keys-status");if(!t)return;const e=t.querySelectorAll(".key-status-dot"),s=["flutterflow"];e.forEach((n,r)=>{const i=s[r];i==="flutterflow"?as("flutterflow")&&as("flutterflow_project_id")?(n.className="key-status-dot configured",n.title="FlutterFlow (Fully configured)"):as("flutterflow")||as("flutterflow_project_id")?(n.className="key-status-dot env",n.title="FlutterFlow (Partially configured)"):(n.className="key-status-dot missing",n.title="FlutterFlow (Not configured)"):as(i)?(n.className="key-status-dot configured",n.title=i.charAt(0).toUpperCase()+i.slice(1)+" (User key)"):(n.className="key-status-dot missing",n.title=i.charAt(0).toUpperCase()+i.slice(1)+" (Not configured)")}),Zt()}async function dv(){const t=document.getElementById("flutterflow-api-key-input"),e=document.getElementById("flutterflow-projects-select");t.value.trim()&&await bc("flutterflow",t.value);const s=e?.value.trim()||"";if(s){if(!Hr(s)){ue("The selected FlutterFlow project has an unexpected ID format.","error"),e.focus();return}await bc("flutterflow_project_id",s)}await fa(),va();const n=document.querySelector("#api-keys-modal .bg-blue-500"),r=n.textContent;n.textContent="Saved!",n.classList.remove("bg-blue-500","hover:bg-blue-600"),n.classList.add("bg-green-500"),setTimeout(()=>{n.textContent=r,n.classList.remove("bg-green-500"),n.classList.add("bg-blue-500","hover:bg-blue-600"),Wd()},1e3)}async function hv(){if(!confirm("Are you sure you want to clear all stored API keys?"))return;localStorage.setItem(dn,Po()),Es(),localStorage.removeItem(st+"flutterflow"),localStorage.removeItem(st+"flutterflow_project_id"),sessionStorage.removeItem(_t+"flutterflow"),sessionStorage.removeItem(_t+"flutterflow_project_id"),sessionStorage.removeItem(it),sessionStorage.removeItem(un),localStorage.removeItem(st+"salt"),await ev(),localStorage.setItem(dn,Po()),localStorage.removeItem(st+"flutterflow"),localStorage.removeItem(st+"flutterflow_project_id"),sessionStorage.removeItem(_t+"flutterflow"),sessionStorage.removeItem(_t+"flutterflow_project_id"),await fa();const t=document.getElementById("flutterflow-projects-select");t&&(t.innerHTML=''),va()}function Hr(t){return!t||t.trim().length<5||t.includes(" ")?!1:/^[a-zA-Z0-9-]+$/.test(t)}function pv(t,e){const s=document.getElementById(t);s&&(s.value?e?s.style.borderColor="#22c55e":s.style.borderColor="#ef4444":s.style.borderColor="")}function fv(){const t=document.getElementById("flutterflow-api-key-input");t&&(t.addEventListener("input",e=>{const s=e.target.value.trim().length>0;pv("flutterflow-api-key-input",s)}),t.addEventListener("blur",gv(async e=>{const s=e.target.value.trim();s&&await Vd(s)},500)))}function gv(t,e){let s;return function(...r){const i=()=>{clearTimeout(s),t(...r)};clearTimeout(s),s=setTimeout(i,e)}}async function Vd(t){const e=document.getElementById("flutterflow-projects-select"),s=document.getElementById("flutterflow-projects-error");if(!e){console.error("Projects dropdown element not found");return}e.innerHTML='',s&&s.classList.add("hidden");try{const r=await new mn(t,"").listProjects();if(!r||r.length===0){e.innerHTML='';return}e.innerHTML='',r.forEach(i=>{const o=document.createElement("option");o.value=i.id||i.projectId||"",o.textContent=i.name||i.projectName||`Project ${i.id}`,e.appendChild(o)}),Ir&&(e.value=Ir)}catch(n){console.error("Failed to fetch projects:",n),e.innerHTML='',s&&(s.textContent=`Failed to load projects: ${n.message}`,s.classList.remove("hidden"))}}function mv(t){const e=document.getElementById(t),n=e.nextElementSibling.querySelector("svg");e.type==="password"?(e.type="text",n.innerHTML=` + + `):(e.type="password",n.innerHTML=` + + + `)}let y={step1Result:null,step2Result:null,step3Result:null,bundleSpec:null,artifactBundle:null,bundleReview:null,selectedArtifactId:null,resultsViewMode:"summary",currentStep:0,isRunning:!1};function vv(){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 _v(){y.bundleSpec=an(y.step1Result,{artifactType:"CustomWidget",artifactName:"GeneratedWidget"})}function Wr(){const t=mr(y.bundleSpec);y.artifactBundle=an(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=gg(y.artifactBundle);y.artifactBundle={...y.artifactBundle,warnings:[...y.artifactBundle.warnings,...e.findings.map(s=>s.message)],metadata:{...y.artifactBundle.metadata,compatibility:e}},y.selectedArtifactId=mr(y.artifactBundle).id}function zr(){const t=an(y.step3Result,{id:y.artifactBundle?.id,title:y.artifactBundle?.title}),e=new Map(t.artifacts.map(n=>[n.id,n.review])),s=new Map(t.artifacts.filter(n=>{const r=n.review;return r&&typeof r.fixedSource=="string"&&r.fixedSource.trim()}).map(n=>[n.id,n.review.fixedSource.trim()]));y.bundleReview=an({id:y.artifactBundle?.id,title:y.artifactBundle?.title,artifacts:y.artifactBundle?.artifacts?.map(n=>{const r=s.get(n.id)||null;return{...n,review:e.get(n.id)||n.review||y.step3Result||null,...r?{fixedCode:r}:{}}})||[],relationships:y.artifactBundle?.relationships,warnings:y.artifactBundle?.warnings})}function Gd(){const t=_a();return{artifactType:t.artifactType||"CustomWidget",artifactName:t.artifactName||"GeneratedWidget",fileName:t.fileName||""}}function _a(){const t=y.artifactBundle||y.bundleSpec||null;return(Array.isArray(t?.artifacts)?t.artifacts:[]).find(s=>s.id===y.selectedArtifactId)||mr(t)}function ya(){return _a().code||y.step2Result||""}async function yv(){try{await fa()}catch(t){return console.error("checkConnection: initializeApiKeys failed:",t),!1}return!0}const qn={production:"https://api.flutterflow.io/v2/",staging:"https://api.flutterflow.io/v2-staging/"};function wv(t,e){const s=e?.trim()?` (${e.trim().slice(0,200)})`:"";return t===401?`Your FlutterFlow API key was rejected (401 Unauthorized)${s}. Re-enter a current key under API Keys settings, then try again.`:`Listing FlutterFlow projects was denied (403)${s}. 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 mn{constructor(e,s,n="main",r=qn.production){this.apiKey=e,this.baseUrl=r,this._projectId=s,this._branchName=n,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 s=null;for(const n of e)try{const r=await fetch(`${this.baseUrl}exportCode`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify(n)});if(!r.ok){const a=await r.text();s=new Error(`Export failed: ${r.status} - ${a}`);continue}const i=await r.json(),o=i?.value?.project_zip||i?.project_zip;if(!o){s=new Error("Export response did not include project source.");continue}return o}catch(r){s=r}throw s||new Error("Export failed for an unknown reason.")}async fetchProjectSource(){const e=await this.exportProjectZip(),s=await JSZip.loadAsync(e,{base64:!0}),n=Object.keys(s.files).filter(a=>!s.files[a].dir&&(a==="pubspec.yaml"||a.endsWith("/pubspec.yaml"))).sort((a,l)=>a.split("/").length-l.split("/").length)[0];if(!n)throw new Error("Export did not contain a pubspec.yaml.");const r=n.slice(0,n.length-12),i=new Map,o=Object.keys(s.files).filter(a=>{if(s.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=>{i.set(a.slice(r.length),await s.files[a].async("string"))})),{pubspecYaml:await s.files[n].async("string"),files:i}}async pushCodeWithRetry(e,s=3){const n=[qn.production,qn.staging],r=Math.max(0,n.indexOf(this._endpoint));for(let i=0;isetTimeout(d,1e3*(i+1)));continue}return l}catch(l){console.warn(`Push to ${a} failed: ${l.message}, trying next...`),await new Promise(u=>setTimeout(u,1e3*(i+1)))}}throw new Error("All API endpoints failed after retries")}async pushCode(e){return this.pushCodeWithRetry(e)}parseProjectsResponse(e){if(e?.success&&typeof e.value=="string")try{const n=JSON.parse(e.value);if(n&&Array.isArray(n.entries))return n.entries.map(r=>({id:r.id,name:r.project?.name||r.id}))}catch(n){console.error("Failed to parse stringified project value:",n)}const s=e?.projects||e?.items||e?.entries||(Array.isArray(e)?e:[]);return Array.isArray(s)?s:[]}async listProjects(){console.log("Listing projects for API key");const e=[`${this.baseUrl}listProjects`,"https://api.flutterflow.io/v2/l/listProjects"];let s=0,n="";for(const r of e){const i=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify({project_type:"ALL",deserialize_response:!0})});if(i.ok)return r!==e[0]&&console.log(`listProjects answered on legacy path ${r}`),this.parseProjectsResponse(await i.json());if(s=i.status,n=await i.text(),console.warn(`listProjects via ${r} returned ${s}: ${n}`),i.status===401||i.status===403)throw new Error(wv(i.status,n));if(i.status!==404)throw new Error(`List projects failed: ${i.status} - ${n}`)}throw new Error(`List projects failed: ${s} - ${n}`)}}async function wa(t){const e=t.clone();let s;try{s=await t.json()}catch{const i=await e.text();if(!t.ok)return{success:!1,responseCode:t.status,errorMessage:i||`HTTP ${t.status}`,errorMap:new Map};throw new Error(`Invalid JSON response: ${i}`)}if(!t.ok){let r=s.message||`HTTP ${t.status}`,i=new Map;if(s.errors)i=new Map(Object.entries(s.errors));else if(!s.message&&typeof s=="object"){const o=Object.keys(s).filter(a=>a.endsWith(".dart")&&Array.isArray(s[a]));o.length>0&&(i=new Map(Object.entries(s)),r=o.flatMap(l=>s[l].map(u=>`${l}: ${u.errorMessage}`)).join(` +`)||`HTTP ${t.status}`)}return{success:!1,responseCode:t.status,errorMessage:r,errorMap:i}}let n={};if(s.value)try{n=typeof s.value=="string"?JSON.parse(s.value):s.value}catch(r){console.warn("Ignoring malformed push response value:",r)}return{success:!0,responseCode:t.status,errorMap:new Map(Object.entries(n))}}function ba(t,e){return{401:"Authentication failed. Please check your FlutterFlow API key.",403:"Access denied. You may not have permission to modify this project.",404:"Project not found. Please check your Project ID.",409:"Conflict detected. The project may have been modified elsewhere.",422:"Validation failed: Invalid request format",429:"Rate limit exceeded. Please try again in a few minutes.",500:"FlutterFlow server error. Please try again later.",503:"FlutterFlow service temporarily unavailable."}[t]||`FlutterFlow API error: ${`HTTP ${t}`}`}const U={ACTION:"A",WIDGET:"W",FUNCTION:"F",CODE_FILE:"C",DEPENDENCIES:"D",OTHER:"O"},Kd=/class\s+\w+\s+extends\s+(?:StatelessWidget|StatefulWidget)\b/,Jd=/extends\s+State<\w+>/;function bv(t,e=""){if(t==="pubspec.yaml")return U.DEPENDENCIES;if(!t.endsWith(".dart")||t.endsWith("index.dart"))return U.OTHER;if(t==="custom_functions.dart")return U.FUNCTION;if(e){const s=Kd.test(e),n=Jd.test(e);if(s||n)return U.WIDGET;if(/^\s*Future(?:<[^>]+>)?\s+\w+\s*\(/m.test(e))return U.ACTION;if(e.match(/^\s*(String|int|double|bool|List|Map|dynamic|void)\s+\w+\s*\(/m))return U.FUNCTION}return U.CODE_FILE}function Yd(t,e){switch(e){case U.ACTION:return`lib/custom_code/actions/${t}`;case U.WIDGET:return`lib/custom_code/widgets/${t}`;case U.FUNCTION:return"lib/flutter_flow/custom_functions.dart";case U.CODE_FILE:return`lib/custom_code/${t}`;case U.DEPENDENCIES:return"pubspec.yaml";case U.OTHER:return`lib/custom_code/${t}`;default:return t}}async function Ea(t,e=new Map){return Zf(t,e)}const Ao=new Map;function Zd(t){return`${t.baseUrl}|${t.projectId}|${t.branchName}`}function qr(t){Ao.delete(Zd(t))}async function Sa(t,e,s,n,r=""){const i=Fg(e,s);if(i.length===0)return{remoteFiles:s,syncFileMap:e,unverified:[]};const o=gm(i,r),a={...o.manifest,sources:o.sources},l=o.skipped.map(d=>d.reason);l.forEach(d=>console.warn(`[custom class deploy] ${d}`)),console.log(`Provisioning ${i.length} new FlutterFlow custom code file(s) before sync.`),be.set("provision");const u=await fetch(Nm,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:t.apiKey,projectId:t.projectId,baseUrl:t.baseUrl,commitMessage:n,customClasses:i,verification:a,stream:!0})}),c=await vm(u,{onPhase:d=>be.setSubstatus(d),onLog:d=>console.log(`[custom class deploy] ${d}`)});if(!c.success){const d=c.details?` ${c.details}`:"";throw new Error(`${c.error||"FlutterFlow custom class provisioning failed."}${d}`)}return qr(t),c.verificationSkipped&&(console.warn(`[custom class deploy] ${c.verificationSkipped}`),l.push(c.verificationSkipped)),{remoteFiles:s,syncFileMap:Pg(e,i),unverified:l}}async function xa(t,e={}){const s=Zd(t);let n=Ao.get(s);if(n===void 0){try{n=await t.fetchProjectSource()}catch(l){throw new Error(`Could not read your project's pubspec.yaml (${l.message}). Deploy was stopped so your existing package dependencies aren't overwritten. Check your FlutterFlow API key and project, then try again.`)}const a=$d(n.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.`);Ao.set(s,n)}const r=await Fm(n.pubspecYaml,e),i=cm(n.pubspecYaml,r.overrides),o=lm(i.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:i.overridden,warnings:r.warnings,remoteFiles:n.files}}function Ev(t){const e=[],s=[];t.content.length>5e4&&s.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 n=t.content.split(` +`).length;n>500&&s.push(`Code has ${n} lines. Consider breaking it into smaller widgets.`),t.content.includes("setState")&&t.codeType===U.ACTION&&s.push("Using setState in a Custom Action may not work as expected. Consider using a Custom Widget."),t.content.includes("dynamic")&&!t.content.includes("?")&&s.push('Code uses "dynamic" types. Consider adding explicit types for better null safety.'),t.content.match(/Color\(0xFF[0-9A-Fa-f]{6}\)/)&&s.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&&s.push(`Code contains ${r.length} print statements. Consider removing debug prints before committing.`);const i=Gg(t.content);if(i&&e.push(`FlutterFlow cannot format this code - ${i}. Fix or regenerate before committing.`),t.codeType===U.WIDGET){const o=Sd(t.content),a=zg(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=`${xd(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:s}}function Xd(t,e={}){const{artifactType:s="CustomWidget",artifactName:n="GeneratedCode",fileName:r}=e,i=Hg(t);let o=r||n;if(s==="CustomFunction")o="custom_functions.dart";else if(s==="CustomWidget"){const u=Sd(i)[0],c=u?xd(u):null;c&&o!==c?(console.warn(`Commit file name "${o}" does not match declared widget class "${u}"; renaming to "${c}" so FlutterFlow can find the widget.`),o=c):o.endsWith(".dart")||(o+=".dart")}else o.endsWith(".dart")||(o+=".dart");let a=U.CODE_FILE;switch(s){case"CustomAction":a=U.ACTION;break;case"CustomWidget":a=U.WIDGET;break;case"CustomFunction":a=U.FUNCTION;break;case"CustomClass":case"CodeFile":a=U.CODE_FILE;break}let l="";return a===U.WIDGET?l=`// Automatic FlutterFlow imports +import '/flutter_flow/flutter_flow_theme.dart'; +import '/flutter_flow/flutter_flow_util.dart'; +import 'package:flutter/material.dart'; +// Begin custom widget code +// DO NOT REMOVE OR MODIFY THE CODE ABOVE! + +`:a===U.ACTION?l=`// Automatic FlutterFlow imports +import '/flutter_flow/flutter_flow_theme.dart'; +import '/flutter_flow/flutter_flow_util.dart'; +import 'package:flutter/material.dart'; +// Begin custom action code +// DO NOT REMOVE OR MODIFY THE CODE ABOVE! + +`:a===U.FUNCTION&&(l=`// Automatic FlutterFlow imports +import 'dart:convert'; +import 'dart:math' as math; + +import 'package:flutter/material.dart'; +import 'package:google_fonts/google_fonts.dart'; +import 'package:intl/intl.dart'; +import 'package:timeago/timeago.dart' as timeago; +import '/flutter_flow/lat_lng.dart'; +import '/flutter_flow/place.dart'; +import '/flutter_flow/uploaded_file.dart'; + +`),{content:_g(i,l),fileName:o,codeType:a,artifactType:s,artifactName:n}}function Sv(t){const e={};for(const s of oa(t))e[s]="";return e}function xv(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 kv(t,e,s,n=new Set,r=""){const i=[],o=Kd.test(e),a=Jd.test(e);return s===U.WIDGET&&!o&&!a&&i.push("No widget class definition found (must extend StatelessWidget or StatefulWidget)"),{valid:i.length===0,errors:i}}function Vr(t){const e=[],s=[];if(!t||t.size===0)return e.push("No files to commit"),{valid:!1,errors:e,warnings:s};const n=new Set(Array.from(t.values()).flatMap(r=>Nr(r.content||"")));for(const[r,i]of t.entries()){if((!i.content||i.content.trim().length===0)&&e.push(`File ${r} is empty`),i.content&&i.content.length>1e5&&s.push(`File ${r} is very large (>100KB)`),r.endsWith(".dart")){const o=kv(r,i.content,i.type,n,i.artifactName);o.valid||e.push(...o.errors.map(a=>`${r}: ${a}`))}if(r==="pubspec.yaml"){const o=$d(i.content);o.valid||e.push(...o.errors)}}return{valid:e.length===0,errors:e,warnings:s}}const V={IDLE:"IDLE",PREPARING:"PREPARING",VALIDATING:"VALIDATING",PUSHING:"PUSHING",SUCCESS:"SUCCESS",ERROR:"ERROR"},K={currentState:V.IDLE,startTime:null,endTime:null,error:null,result:null,filesProcessed:0,totalFiles:0,reset(){this.currentState=V.IDLE,this.startTime=null,this.endTime=null,this.error=null,this.result=null,this.filesProcessed=0,this.totalFiles=0},setState(t){if(!Object.values(V).includes(t)){console.error(`Invalid commit state: ${t}`);return}this.currentState=t,t===V.PREPARING&&(this.startTime=Date.now()),(t===V.SUCCESS||t===V.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(V.ERROR)},setSuccess(t){this.result=t,this.setState(V.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===V.PREPARING||this.currentState===V.VALIDATING||this.currentState===V.PUSHING}};async function Iv(t,e,s={}){let{codeType:n="W"}=s;const{pubspecDeps:r={},artifactName:i=e}=s;n==="CustomWidget"&&(n=U.WIDGET),n==="CustomAction"&&(n=U.ACTION),n==="CustomFunction"&&(n=U.FUNCTION),n==="CustomClass"&&(n=U.CODE_FILE),n==="CodeFile"&&(n=U.CODE_FILE),K.reset(),K.setState(V.PREPARING);try{const o=await Ee("flutterflow"),a=await Ee("flutterflow_project_id");if(!o||!a)throw new Error("FlutterFlow credentials not configured. Please set your API key and Project ID in the API Keys settings.");if(!Hr(a))throw new Error("Invalid FlutterFlow Project ID format.");const l=gn(),u=new mn(o,a,"main",l);K.setState(V.VALIDATING);const c=new Map,d=n||bv(e,t),h=Yd(e,d);c.set(e,{artifactName:i,content:t,type:d,path:h}),K.setProgress(0,c.size);const p=Vr(c);if(!p.valid)throw new Error(`Validation failed: +${p.errors.join(` +`)}`);const f=await xa(u,r),g=f.yaml,m=await Sa(u,c,f.remoteFiles,`Provision ${i} custom class`,g),_=await Ea(m.syncFileMap,m.remoteFiles),w=new Map(m.syncFileMap);w.set("pubspec.yaml",{content:g,type:"D",path:"pubspec.yaml"}),be.set("package");const E=await ka(w),I={project_id:a,zipped_custom_code:E,uid:`web_${Date.now()}`,branch_name:u.branchName,serialized_yaml:g,file_map:_.fileMapContents,functions_map:_.functionsMapContents};K.setState(V.PUSHING),K.setProgress(1,c.size),qr(u),be.set("push");const F=await u.pushCode(I),P=await wa(F);if(P.success)K.setSuccess({fileCount:c.size,projectId:a,warnings:P.errorMap&&P.errorMap.size>0?Array.from(P.errorMap.entries()):[]});else{const B=P.errorMessage||ba(P.responseCode);throw new Error(B)}return{success:!0,message:`Successfully committed ${e} to FlutterFlow project ${a}`,addedDependencies:f.added,unverified:m.unverified,warnings:P.errorMap?Array.from(P.errorMap.entries()):[]}}catch(o){return console.error("Commit failed:",o),K.setError(o),{success:!1,error:o.message,state:K.currentState}}}async function ka(t){const e=new JSZip;for(const[s,n]of t.entries())e.file(s,n.content);return e.generateAsync({type:"base64",compression:"DEFLATE",compressionOptions:{level:6}})}async function Cv(t,e={}){const{artifactType:s,artifactName:n,fileName:r,pipelineResult:i}=e;console.log(`Starting commit for ${n} (${s})`);try{K.setState(V.PREPARING);const o=Xd(t,{artifactType:s,artifactName:n,fileName:r}),a=Sv(o.content);console.log("Detected dependencies:",a),K.setState(V.VALIDATING);const l=await Ee("flutterflow"),u=Zs||await Ee("flutterflow_project_id");if(!l)throw new Error("FlutterFlow API Key not configured. Please add it in API Keys settings.");if(!u)throw new Error("FlutterFlow Project ID not configured. Please add it in API Keys settings.");if(!Hr(u))throw new Error("Invalid FlutterFlow Project ID format.");const c=new Map;c.set(o.fileName,{artifactName:n,content:o.content,type:o.codeType,path:Yd(o.fileName,o.codeType),functionName:o.codeType===U.FUNCTION?n:void 0}),K.setProgress(0,c.size);const d=Vr(c);if(!d.valid)throw new Error(`File validation failed: +${d.errors.join(` +`)}`);d.warnings.length>0&&console.warn("Validation warnings:",d.warnings),K.setState(V.PUSHING);const h=gn(),p=new mn(l,u,"main",h),f=await xa(p,a),g=f.yaml,m=await Sa(p,c,f.remoteFiles,`Provision ${n} custom class`,g),_=await Ea(m.syncFileMap,m.remoteFiles),w=new Map(m.syncFileMap);w.set("pubspec.yaml",{content:g,type:U.DEPENDENCIES,path:"pubspec.yaml"}),be.set("package");const E=await ka(w),I={project_id:u,zipped_custom_code:E,uid:`web_${Date.now()}`,branch_name:p.branchName,serialized_yaml:g,file_map:_.fileMapContents,functions_map:_.functionsMapContents};K.setProgress(1,c.size),qr(p),be.set("push");const F=await p.pushCode(I),P=await wa(F);if(P.success){const B={...xv(o,i),projectId:u};return K.setSuccess({...B,fileCount:c.size,warnings:P.errorMap?Array.from(P.errorMap.entries()):[]}),{success:!0,message:`Successfully committed ${o.fileName} to FlutterFlow`,metadata:B,addedDependencies:f.added,unverified:m.unverified,warnings:P.errorMap?Array.from(P.errorMap.entries()):[],elapsedTime:K.getElapsedTime()}}else{const B=P.errorMessage||ba(P.responseCode),S=new Error(B);throw S.errorMap=P.errorMap,S}}catch(o){console.error("Commit execution failed:",o),K.setError(o);let a=new Map;if(o.errorMap)a=o.errorMap;else if(o.message&&o.message.includes("{"))try{const l=o.message.match(/\{[\s\S]*\}/);if(l){const u=JSON.parse(l[0]);a=new Map(Object.entries(u))}}catch(l){console.warn("Failed to parse error map from commit response:",l)}return{success:!1,error:o.message,errorMap:a,state:K.currentState,elapsedTime:K.getElapsedTime()}}}async function Fv(t,e={}){const{pipelineResult:s}=e;try{if(K.setState(V.PREPARING),t.errors?.length>0)throw new Error(`Bundle validation failed: +${t.errors.join(` +`)}`);const n=new Map(t.fileEntries.map(I=>[I.fileName,{artifactId:I.artifactId,artifactName:I.artifactName,content:I.content,type:I.type,path:I.path,functionName:I.type===U.FUNCTION?I.artifactName:void 0}]));K.setProgress(0,n.size);const r=Vr(n);if(!r.valid)throw new Error(`File validation failed: +${r.errors.join(` +`)}`);K.setState(V.VALIDATING);const i=await Ee("flutterflow"),o=Zs||await Ee("flutterflow_project_id");if(!i)throw new Error("FlutterFlow API Key not configured. Please add it in API Keys settings.");if(!o)throw new Error("FlutterFlow Project ID not configured. Please add it in API Keys settings.");if(!Hr(o))throw new Error("Invalid FlutterFlow Project ID format.");K.setState(V.PUSHING);const a=gn(),l=new mn(i,o,"main",a),u=await xa(l,t.dependencies),c=u.yaml,d=await Sa(l,n,u.remoteFiles,`Provision ${t.title} custom classes`,c),h=await Ea(d.syncFileMap,d.remoteFiles),p=new Map(d.syncFileMap);p.set("pubspec.yaml",{content:c,type:U.DEPENDENCIES,path:"pubspec.yaml"}),be.set("package");const f=await ka(p),g={project_id:o,zipped_custom_code:f,uid:`web_${Date.now()}`,branch_name:l.branchName,serialized_yaml:c,file_map:h.fileMapContents,functions_map:h.functionsMapContents};K.setProgress(1,n.size),qr(l),be.set("push");const m=await l.pushCode(g),_=await wa(m);if(_.success){const I={...s,artifactType:"Bundle",artifactName:t.title,fileName:`${t.fileEntries.length} artifacts`,codeSize:t.fileEntries.reduce((F,P)=>F+P.content.length,0),projectId:o};return K.setSuccess({...I,fileCount:n.size,warnings:_.errorMap?Array.from(_.errorMap.entries()):[]}),{success:!0,message:`Successfully committed ${t.fileEntries.length} artifacts to FlutterFlow`,metadata:I,addedDependencies:u.added,unverified:d.unverified,warnings:_.errorMap?Array.from(_.errorMap.entries()):[],elapsedTime:K.getElapsedTime()}}const w=_.errorMessage||ba(_.responseCode),E=new Error(w);throw E.errorMap=_.errorMap,E}catch(n){return console.error("Bundle commit execution failed:",n),K.setError(n),{success:!1,error:n.message,errorMap:n.errorMap||new Map,state:K.currentState,elapsedTime:K.getElapsedTime()}}}async function Pv(t,e=[]){const s=sa("architect");try{return await Cr("architect",Od,Bf(t),s,e)}catch(n){throw n.isModelArmor?n:new Error(`Prompt Architect failed: ${n.message}`)}}async function Gr(t,e,s=[]){const n=jf(t),r=sa("generator",y.bundleSpec);try{return await Cr("generator",e,n,r,s)}catch(i){if(i.isModelArmor)throw i;if(e!==$i){console.warn(`Code Generator failed with ${e}, retrying with fallback model:`,i.message);try{return await Cr("generator",$i,n,r,s)}catch(o){throw o.isModelArmor?o:new Error(`Code Generator failed: primary (${e}): ${i.message} | fallback (${$i}): ${o.message}`)}}throw new Error(`Code Generator failed: ${i.message}`)}}async function Kr(t,e=null){const s={...sa("review",y.artifactBundle||y.bundleSpec),architect_output:e};try{return await Cr("review",Dd,Uf(t),s)}catch(n){throw n.isModelArmor?n:new Error(`Code Review failed: ${n.message}`)}}function Ia(t,e){return t.isModelArmor?`${t.userTitle}: ${t.userMessage}`:`${e}: ${t.message}`}function $o(t,e){const s=document.getElementById(`step${t}-item`),n=document.getElementById(`step${t}-status`);!s||!n||(s.classList.remove("active","completed","error"),n.classList.remove("running","completed","error"),e==="active"?(s.classList.add("active"),n.classList.add("running"),n.innerHTML=` + + `):e==="completed"?(s.classList.add("completed"),n.classList.add("completed"),n.innerHTML=` + + `):e==="error"?(s.classList.add("error"),n.classList.add("error"),n.innerHTML=` + + `):n.innerHTML=` + + `)}function ve(t,e){const s=document.getElementById(`step${t}-loading`),n=document.getElementById(`step${t}-result`);e?(s.classList.remove("hidden"),n.classList.add("hidden"),$o(t,"active")):(s.classList.add("hidden"),n.classList.remove("hidden"),$o(t,"completed"))}function Av(t){const e=document.getElementById(`${t}-content`),s=document.getElementById(`${t}-chevron`);e.classList.contains("open")?(e.classList.remove("open"),s&&(s.style.transform="rotate(0deg)")):(e.classList.add("open"),s&&(s.style.transform="rotate(180deg)"))}function $v(t){ze(parseInt(t.replace("step","")))}function ze(t){for(let o=1;o<=3;o++){const a=document.getElementById(`step${o}-item`);a&&a.classList.remove("active")}const e=document.getElementById(`step${t}-item`);e&&e.classList.add("active"),Yt();const s=document.getElementById("ready-state");s&&s.classList.add("hidden");for(let o=1;o<=3;o++){const a=document.getElementById(`step${o}-content`);a&&a.classList.add("hidden")}const n=document.getElementById(`step${t}-content`);n&&n.classList.remove("hidden");const r=document.getElementById("stage-title"),i={1:"Prompt Architect",2:"Code Generator",3:"Code Review"};r&&(r.textContent=i[t]||"Active Workflow Stage")}function Rv(t){const e=document.getElementById(t);if(!e)return;const s=e.dataset.raw||e.textContent;navigator.clipboard.writeText(s).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(n=>{console.warn("Failed to copy to clipboard:",n)})}function Ro(t){const e=No(t);console.log(`Step 1 (Prompt Architect): ${zt(Od)}`),console.log(e!==t?`Step 2 (Code Generator): ${zt(t)} → ${zt(e)} (Free Tier fallback)`:`Step 2 (Code Generator): ${zt(t)}`),console.log(`Step 3 (Code Review): ${zt(Dd)}`)}async function Tv(){if(console.log("runRefinement called"),y.isRunning)return;const t=document.getElementById("code-generator-model").value;y.isRunning=!0,Ca("standardRegenerate",y.step2Result,y.step1Result);const e=document.querySelectorAll(".btn-refine-action");e.forEach(s=>{s.disabled=!0,s.innerHTML=` + + + Refining...`});try{const s=_a(),n=Hf({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,artifactId:s.id,userFeedback:"Fix the issues listed in the audit report."});Zr(),rt(2),ze(2),ve(2,!0),y.step2Result=await Gr(n,t),Wr();const r=document.getElementById("step2-output"),i=ws(y.step2Result);r.textContent=i,r.dataset.raw=i,ve(2,!1),ze(3),rt(3),ve(3,!0),y.step3Result=await Kr(y.step2Result,y.step1Result),zr();const o=document.getElementById("step3-output");o.textContent=y.step3Result,ve(3,!1),$t();const a=jr(y.step3Result);Xr(i,a)}catch(s){console.error("Refinement failed:",s),$t(),ue(Ia(s,"Refinement failed"),"error")}finally{y.isRunning=!1,e.forEach(s=>{s.disabled=!1,s.textContent="Refine & Regenerate"}),Zt()}}async function Ca(t,e,s){const n=`${Je}/connectFeedback`,r={type:t,code:e,input:s};try{const i=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!i.ok){const a=await i.text();return console.error(`callEndpoint failed: ${i.status} ${i.statusText}`,a),{success:!1,status:i.status,error:a}}const o=await i.json();return console.log("Telemetry success:",o),o}catch(i){return console.error("callEndpoint failed:",i),{success:!1,error:i.message}}}function Nv(){const t=document.getElementById("ff-error-paste-input");t&&(t.value="")}async function Mv(){const t=document.getElementById("ff-error-paste-input"),e=t?.value?.trim();if(!e){t?.focus(),t?.classList.add("ring-2","ring-red-400","border-red-300"),setTimeout(()=>t?.classList.remove("ring-2","ring-red-400","border-red-300"),2e3);return}if(!y.step2Result){ue("No generated code found. Please run the full pipeline first.","warning");return}if(y.isRunning)return;const s=document.getElementById("code-generator-model").value;y.isRunning=!0,Ca("flutterflowError",y.step2Result,e);const n=document.getElementById("btn-fix-from-errors");n&&(n.disabled=!0,n.innerHTML=` + + Fixing…`);try{const r=vd({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,userFeedback:e});dh(),Zr(),rt(2),ze(2),ve(2,!0),y.step2Result=await Gr(r,s),Wr();const i=document.getElementById("step2-output"),o=ws(y.step2Result);i.textContent=o,i.dataset.raw=o,ve(2,!1),ze(3),rt(3),ve(3,!0),y.step3Result=await Kr(y.step2Result,y.step1Result),zr();const a=document.getElementById("step3-output");a.textContent=y.step3Result,ve(3,!1),$t();const l=jr(y.step3Result);Xr(o,l),t&&(t.value="")}catch(r){console.error("Fix from errors failed:",r),$t(),ue(Ia(r,"Failed to fix errors"),"error")}finally{y.isRunning=!1,n&&(n.disabled=!1,n.textContent="Fix Errors & Regenerate"),Zt()}}async function To(){if(console.log("runThinkingPipeline called"),y.isRunning)return;localStorage.setItem("hasSeenWalkthrough","true");const t=document.getElementById("pipeline-input").value,e=document.getElementById("code-generator-model").value;if(!t.trim()){ue("Please describe your FlutterFlow widget first.","warning");return}if(!await t_())return;await Jv();const s=No(e);t.length;const n=document.getElementById("btn-run-pipeline");y.isRunning=!0,vv(),n.disabled=!0,n.innerHTML=` + + + Running...`,Ro(s);try{Yt();const r=document.getElementById("ready-state");r&&r.classList.add("hidden");const i=document.getElementById("paywall-exhausted");i&&i.classList.add("hidden"),Zr(),ze(1),rt(1),ve(1,!0);const o=Pt.filter(p=>p.url).map(p=>({url:p.url}));y.step1Result=await Pv(t,o),_v();const a=document.getElementById("step1-output"),l=ws(y.step1Result);a.textContent=l,a.dataset.raw=l,ve(1,!1),ze(2),rt(2),ve(2,!0),y.step2Result=await Gr(y.step1Result,s,o),Wr();const u=document.getElementById("step2-output"),c=ws(y.step2Result);u.textContent=c,u.dataset.raw=c,ve(2,!1),ze(3),rt(3),ve(3,!0),y.step3Result=await Kr(y.step2Result,y.step1Result),zr();const d=document.getElementById("step3-output");d.textContent=y.step3Result,ve(3,!1),$t();const h=jr(y.step3Result);Xr(c,h)}catch(r){if(console.error("Pipeline failed:",r),$t(),r.isUsageLimit){const{count:c}=Jr();Ta(c,Ra(),{openModal:!0});return}r.message,No(document.getElementById("code-generator-model").value);const o=Am(r,{architect:1,generator:2,review:3});ze(o);const a=document.getElementById(`step${o}-result`),l=document.getElementById(`step${o}-loading`),u=document.getElementById(`step${o}-output`);if(l&&l.classList.add("hidden"),a&&a.classList.remove("hidden"),u)if(r.isModelArmor)u.innerHTML=``;else{let c=r.message;r.message.includes("image input")?c=`This model doesn't support image input. Please use ${zt(cn)} for image-based requests or remove image references from your prompt.`:(r.message.includes("Load failed")||r.message.includes("CORS"))&&(c="API connection failed. This might be due to CORS restrictions or network issues. Please check your API key and try again."),u.innerHTML=`
    +

    Connection Error

    +

    ${j(c)}

    +
    +

    Check if API key is valid

    +

    Try using a different model

    +

    Ensure network allows API calls

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

    FlutterFlow Commit Failed

    +

    ${j(t.error)}

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

    Errors:

    +
      `;for(const[r,i]of e.entries()){const o=kd(i);s+=`
    • + ${j(r)}: ${j(o)} +
    • `}s+="
    "}s+="
    ",s+=`
    + +
    `;const n=document.getElementById("step3-output");n&&(n.innerHTML=s,document.getElementById("btn-regenerate-from-error")?.addEventListener("click",()=>{jv(t.error,e)}))}async function jv(t,e){if(y.isRunning)return;const s=document.getElementById("code-generator-model").value;y.isRunning=!0;const n=document.getElementById("btn-regenerate-from-error");n&&(n.disabled=!0,n.innerHTML=` + + Fixing...`);try{let r=`The previous code had the following errors when committing to FlutterFlow: + +`;if(e&&e.size>0)for(const[c,d]of e.entries()){const h=kd(d);r+=`File: ${c} +Error: ${h} + +`}else r+=`${t} +`;const i=vd({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,userFeedback:r});Zr(),rt(2),ze(2),ve(2,!0),y.step2Result=await Gr(i,s),Wr();const o=document.getElementById("step2-output"),a=ws(y.step2Result);o.textContent=a,o.dataset.raw=a,ve(2,!1),ze(3),rt(3),ve(3,!0),y.step3Result=await Kr(y.step2Result,y.step1Result),zr();const l=document.getElementById("step3-output");l.textContent=y.step3Result,ve(3,!1),$t();const u=jr(y.step3Result);Xr(a,u)}catch(r){console.error("Regeneration failed:",r),$t(),ue(Ia(r,"Regeneration failed"),"error")}finally{y.isRunning=!1,n&&(n.disabled=!1,n.textContent="Fix Errors & Regenerate"),Zt()}}async function Uv(){const t=document.getElementById("ff-status-dot"),e=document.getElementById("ff-status-text");if(!t||!e)return;const s=await Ee("flutterflow"),n=await Ee("flutterflow_project_id");s&&n?(t.className="w-2 h-2 rounded-full bg-green-500",e.textContent="FlutterFlow credentials configured",e.className="text-green-600"):s||n?(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 Hv(t){try{const e=await fetch(`${Je}/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 Wv(t){try{const s=await(await fetch(`${Je}/auth/verify-magic-link`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:t})})).json();if(s.error||!s.email||!s.sessionToken)throw new Error(s.error||"Invalid or expired link");return s}catch(e){throw console.error("verifyMagicLink failed:",{message:e.message,stack:e.stack}),e}}async function zv(t){try{const e=await fetch(`${Je}/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:`${Je}/auth/refresh-session`,status:e.status}),null;const s=await e.json();return s.error||!s.email||!s.sessionToken?(console.warn("refreshSession: validation failed",{error:s.error,hasEmail:!!s.email,hasToken:!!s.sessionToken}),null):s}catch(e){return console.error("refreshSession: fetch failed",{url:`${Je}/auth/refresh-session`,message:e.message,stack:e.stack}),null}}function xc(t,e){const s=Qd(),n=(G.email||s.email)!==t;G.email=t,G.sessionToken=e,G.isVerified=!0,fe=bs({isLoading:!0}),localStorage.setItem(yr,JSON.stringify({email:t,sessionToken:e})),n&&Na()}function Fa(){G.email=null,G.sessionToken=null,G.isVerified=!1,fe=bs({isResolved:!0}),localStorage.removeItem(yr),localStorage.removeItem(br)}function Qd(){try{const t=localStorage.getItem(yr);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(yr),{email:null,sessionToken:null}}}async function qv(){const e=new URLSearchParams(window.location.search).get("token");if(e){window.history.replaceState({},"",window.location.pathname);try{const{email:s,sessionToken:n}=await Wv(e);xc(s,n)}catch(s){ue(s.message||"Sign-in link invalid or expired.","error")}}else{const{email:s,sessionToken:n}=Qd();if(s&&n){const r=await zv(n);r?xc(r.email,r.sessionToken):Fa()}}Aa()}function Pa(){const t=document.getElementById("signin-modal");t&&t.classList.add("open")}function Vv(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("signin-modal");e&&e.classList.remove("open")}async function Gv(){const t=document.getElementById("signin-email-input"),e=document.getElementById("signin-submit-btn"),s=document.getElementById("signin-message"),n=Lr(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){s&&(s.textContent="Please enter a valid email address.");return}e&&(e.disabled=!0,e.textContent="Sending…");const i=Id(n);s&&i&&(s.textContent=i);try{const o=await Hv(n);t&&o?.code!==Un&&(t.value=""),s&&(s.textContent=sm(o,n)),e&&(e.textContent=o?.code===Un?"Send Link":"Sent!"),e&&o?.code===Un&&(e.disabled=!1)}catch(o){console.error("handleMagicLinkRequest: sendMagicLink failed",{email:n,err:o}),s&&(s.textContent="Something went wrong. Please try again."),e&&(e.disabled=!1,e.textContent="Send Link")}}function Kv(){Fa(),Na(),Aa(),Yr()}function Aa(){const t=G.isVerified&&!!G.email,e=document.getElementById("auth-signedout"),s=document.getElementById("auth-signedin"),n=document.getElementById("auth-guest-usage");e&&e.classList.toggle("hidden",t),s&&s.classList.toggle("hidden",!t),n&&n.classList.toggle("hidden",t);const r=document.getElementById("auth-user-email");r&&(r.textContent=G.email||""),Vn(),Yr()}async function eh(){try{if(typeof FingerprintJS>"u"){console.warn("resolveIdentity: FingerprintJS not loaded, skipping");return}const e=await(await FingerprintJS.load()).get(),s=e.visitorId,n=await fetch(Dm,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({fingerprint:e.visitorId,cookie_id:s})});if(!n.ok)throw new Error(`Identity check HTTP ${n.status}`);const r=await n.json();if(Ge.userId=r.user_id,Ge.token=r.identity_token||null,Ge.status=r.status,Ge.resolved=!0,sessionStorage.setItem(Lm,r.user_id),Ge.token&&sessionStorage.setItem(Om,Ge.token),r.usage_count!==void 0){const i=At(),a=(r.usage_month||i)===i?r.usage_count:0;localStorage.setItem(Gt,JSON.stringify({count:a,month:i})),Xs()}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 Ri=null;function Jv(t=5e3){return Ge.resolved?Promise.resolve():(Ri||(Ri=eh().catch(e=>{console.warn("ensureIdentityReady: identity resolution failed",e)})),Promise.race([Ri,new Promise(e=>setTimeout(e,t))]))}function th(){const t=At();try{const e=localStorage.getItem(Gt);return e?JSON.parse(e):{count:0,month:t}}catch(e){return console.warn("getUsageData: failed to parse usage storage",{key:Gt,month:t,err:e}),localStorage.removeItem(Gt),{count:0,month:t}}}function At(){const t=new Date;return`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,"0")}`}function Jr(){const t=th();return t.month!==At()?{count:0,month:At()}:t}function Yv(){const e={count:Jr().count+1,month:At()};return localStorage.setItem(Gt,JSON.stringify(e)),e}function $a(){return!!fe.isLoading}function Jt(){return!!fe.isResolved}function Zv(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(wr,e)?e:null}function Xv(t){return t&&Object.entries(Nd).find(([,e])=>e===t)?.[0]||null}function Rn(...t){return t.find(e=>e!=null&&e!=="")}function Qv(...t){return t.find(e=>e&&typeof e=="object")||{}}function e_(t){const e=t.data&&typeof t.data=="object"?t.data:t,s=Qv(e.subscription,e.stripeSubscription,e.currentSubscription,e.customer?.subscriptions?.data?.[0],e.subscriptions?.data?.[0],e.subscriptions?.[0]),n=e.metadata||s.metadata||e.customer?.metadata||{},r=Rn(e.priceId,e.price_id,e.stripePriceId,e.stripe_price_id,s.priceId,s.price_id,s.plan?.id,s.price?.id,s.items?.data?.[0]?.price?.id,s.items?.[0]?.price?.id,s.lines?.data?.[0]?.price?.id),i=Rn(e.status,e.subscriptionStatus,e.subscription_status,s.status,"none"),o=Zv(Rn(e.tier,e.plan,e.planId,e.plan_id,e.subscriptionTier,e.subscription_tier,e.product,e.productName,s.tier,s.plan,n.tier,n.plan)),a=Bm.has(String(i).toLowerCase()),l=e.active===!0||e.isSubscribed===!0||e.subscribed===!0||e.hasSubscription===!0,u=o||Xv(r)||(a||l?"professional":"free");return bs({tier:u,status:i,periodEnd:Rn(e.periodEnd,e.currentPeriodEnd,e.current_period_end,s.current_period_end,s.periodEnd,null),isResolved:!0})}function Ra(){return wr[fe.tier]??wr.free}async function t_(){if(G.isVerified&&(!Jt()||$a())&&(await sh({force:!0}),Yr()),G.isVerified&&!Jt())return ue("Could not verify your subscription. Please refresh or try Manage billing.","error"),!1;const{count:t}=Jr(),e=Ra();if(t>=e)return Ta(t,e,{openModal:!0}),!1;const s=Math.floor(e*.8);if(t>=s){const n=e-t;ue(`${n} run${n===1?"":"s"} remaining this month.`,"warning")}return!0}function Ti(){const t=document.getElementById("paywall-exhausted");t&&t.classList.add("hidden")}function Ta(t,e,s={}){const n=document.getElementById("walkthrough-modal");n&&n.classList.remove("open");const r=document.getElementById("ready-state");r&&r.classList.add("hidden");const i=document.getElementById("preview-frame-container");i&&(i.style.display="none");const o=document.getElementById("main-stage-container");o&&o.classList.add("visible");const a=document.getElementById("results-view");a&&a.classList.remove("visible"),document.body.classList.remove("results-fullscreen","results-with-sidebar");const l=document.getElementById("pipeline-progress");l&&l.classList.remove("visible");const u=document.getElementById("paywall-exhausted");if(!u){ue(`You've used all ${e} runs for this month. Upgrade to continue.`,"error"),Fr();return}const c=document.getElementById("paywall-exhausted-text");if(c){const h=fe.tier;h==="free"?c.textContent=`You've used all ${e} free generations this month. Upgrade to Pro for 50 generations/month and access to all AI models.`:c.textContent=`You've used all ${e} generations this month on your ${h} plan. Your limit resets next month.`}const d=document.getElementById("paywall-signin-btn");d&&d.classList.toggle("hidden",G.isVerified),u.classList.remove("hidden"),s.openModal&&Fr()}function No(t){return fe.tier==="free"&&Hn.includes(t)?cn:t}function s_(){const t=document.getElementById("code-options-content"),e=document.getElementById("code-generator-model");if(!t||!e)return;const s=fe.tier,r=!(G.isVerified&&!Jt())&&s==="free";Array.from(e.options).forEach(o=>{const a=zt(o.value),l=Hn.includes(o.value);o.textContent=l&&r?`${a} (PRO)`:a,o.disabled=!1}),r&&Hn.includes(e.value)&&(e.value=cn),e.disabled=!1,fc.has(e)||(e.addEventListener("change",()=>{Jt()&&fe.tier==="free"&&Hn.includes(e.value)&&(e.value=cn,Fr()),Ro(e.value),Ld()}),fc.add(e));let i=document.getElementById("model-selector-free-notice");r?(i||(i=document.createElement("p"),i.id="model-selector-free-notice",i.className="text-xs text-gray-400 mt-1",t.appendChild(i)),i.innerHTML='Free plan — Gemini only. '):i&&i.remove(),Ro(e.value)}function Xs(){const t=document.getElementById("usage-counter");if(!t)return;if(G.isVerified&&$a()){t.textContent="Checking plan…",t.className="text-xs text-gray-500",Vn(),Ti();return}if(G.isVerified&&!Jt()){t.textContent="Plan check failed",t.className="text-xs text-red-600 font-medium",Vn(),Ti();return}const{count:e}=Jr(),s=Ra();t.textContent=`${e} / ${s} runs this month`;const n=s>0?e/s:0;t.className=n>=1?"text-xs text-red-600 font-medium":n>=.8?"text-xs text-yellow-600 font-medium":"text-xs text-gray-500",Vn(),e>=s&&!y.isRunning?Ta(e,s):Ti()}function Vn(){const t=document.getElementById("guest-usage-text");if(!t)return;const e=th(),s=e.month===At()?e.count??0:0,n=wr.free;t.textContent=`${s} / ${n} generations used`}async function sh(t={}){const e=t.force===!0;if(!G.isVerified||!G.sessionToken){fe=bs({isResolved:!0});return}fe={...fe,isLoading:!0,error:null};const s=localStorage.getItem(br);if(!e&&s)try{const{data:n,email:r,ts:i,version:o}=JSON.parse(s);if(o===gc&&r===G.email&&Date.now()-i<300*1e3){fe={...n,isLoading:!1,isResolved:n.isResolved!==!1};return}}catch(n){console.warn("Failed to parse subscription cache:",n,"| raw value:",s)}try{const r=await(await fetch(`${Je}/stripe/get-subscription`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:G.sessionToken,user_id:Ge.userId})})).json();if(r.error){if(["unauthorized","invalid session","expired session"].some(o=>String(r.error).toLowerCase().includes(o))){Fa(),Aa();return}fe=bs({isResolved:!1,error:r.error});return}fe=e_(r),localStorage.setItem(br,JSON.stringify({version:gc,data:fe,email:G.email,ts:Date.now()}))}catch(n){console.error("fetchSubscription failed:",n),fe={...fe,isLoading:!1,isResolved:!1,error:n.message}}}function Na(){localStorage.removeItem(br)}async function n_(t){if(!G.isVerified||!G.sessionToken){nh(),Pa();return}if(!Nd[t]){ue("Invalid plan selected.","error");return}const e=document.getElementById(`checkout-btn-${t}`);e&&(e.disabled=!0,e.textContent="Redirecting…");try{const n=await(await fetch(`${Je}/stripe/create-checkout-session-intl`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tierId:t,sessionToken:G.sessionToken,currency:Bd()})})).json();if(n.error||!n.url)throw new Error(n.error||"Failed to create checkout session");const{url:r}=n;window.location.href=r}catch(s){console.error("startCheckout failed:",s),e&&(e.disabled=!1,e.textContent="Subscribe"),ue("Could not start checkout. Please try again.","error")}}async function r_(){if(!G.isVerified||!G.sessionToken){Pa();return}const t=document.getElementById("manage-billing-btn");t&&(t.disabled=!0,t.textContent="Loading…");try{const s=await(await fetch(`${Je}/stripe/create-portal-session`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:G.sessionToken})})).json();if(s.error||!s.url)throw new Error(s.error||"Failed to open billing portal");const{url:n}=s;window.location.href=n}catch(e){console.error("openCustomerPortal failed:",e),t&&(t.disabled=!1,t.textContent="Manage billing"),ue("Could not open billing portal. Please try again.","error")}}async function Cr(t,e,s,n={},r=[]){const o=new AbortController,a=setTimeout(()=>o.abort(),12e4);try{const l=await fetch(Mm,{method:"POST",headers:{"Content-Type":"application/json",...Ge.token?{Authorization:`Bearer ${Ge.token}`}:{}},signal:o.signal,body:JSON.stringify({user_id:Ge.userId,step:t,model:e,prompt:s,images:r,context:n})}),u=await l.text();let c={};try{c=u?JSON.parse(u):{}}catch{c={}}if(l.status===429){c.serverCount!==void 0&&(localStorage.setItem(Gt,JSON.stringify({count:c.serverCount,month:At()})),Xs());const p=new Error(c.message||"Monthly usage limit reached. Upgrade to continue.");throw p.isUsageLimit=!0,p}const d=Jf(c,t);if(d)throw d;if(console.log(`[BuildShip] ${t} response keys:`,Object.keys(c),"content type:",typeof c.content),!l.ok)throw new Error(`${c.message||c.error||"BuildShip pipeline error"} (HTTP ${l.status})`);if(t==="generator")if(c.usage_status==="success"&&Number.isFinite(c.usage_count)){const p=At();(c.usage_month||p)===p&&(localStorage.setItem(Gt,JSON.stringify({count:c.usage_count,month:p})),Xs())}else Yv(),Xs();let h=c.output||c.content;if(!h){const p=u?` (body: ${u.slice(0,120)})`:"";throw new Error(`BuildShip returned no output for step "${t}"${p}`)}return Array.isArray(h)&&(h=h.map(p=>typeof p=="string"?p:p.text||"").join("")),typeof h!="string"&&(h=JSON.stringify(h)),h}catch(l){throw l.name==="AbortError"?new Error(`BuildShip ${t} timed out after ${12e4/1e3}s`):l instanceof TypeError?new Error(`BuildShip unreachable: ${l.message}`):l}finally{clearTimeout(a)}}function i_(){const e=new URLSearchParams(window.location.search).get("checkout");e==="success"?(window.history.replaceState({},"",window.location.pathname),Na(),ue("Subscription active! Welcome aboard.","success")):e==="cancel"&&(window.history.replaceState({},"",window.location.pathname),ue("Checkout cancelled.","info"))}function Yr(){const t=G.isVerified&&!!G.email,e=fe.tier,s=t&&$a(),n=!t||Jt(),r=document.getElementById("subscription-tier-badge");if(r){const a={free:"Free",professional:"Professional",power:"Power Developer"},l={free:"bg-gray-100 text-gray-600",professional:"bg-indigo-100 text-indigo-700",power:"bg-purple-100 text-purple-700",unresolved:"bg-red-50 text-red-600"};r.textContent=s?"Checking…":n?a[e]||"Free":"Plan unavailable",r.className=`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${n?l[e]||l.free:l.unresolved}`}const i=document.getElementById("upgrade-prompt");i&&i.classList.toggle("hidden",!t||s||!n||e!=="free");const o=document.getElementById("manage-billing-btn");o&&o.classList.toggle("hidden",!t||s||n&&e==="free"),o_(n?e:null),s_(),Ld(),Xs()}function o_(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:i,defaultText:o}])=>{const a=document.getElementById(i);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 n=document.getElementById("free-tier-current");n&&n.classList.toggle("hidden",t!=="free")}function Mo(){const t=Bd(),e=document.getElementById("pro-price"),s=document.getElementById("power-price"),n=document.getElementById("pro-price-note"),r=document.getElementById("power-price-note");e&&(e.textContent=vc(mc.professional,t)),s&&(s.textContent=vc(mc.power,t));const i="billed monthly";n&&(n.textContent=i),r&&(r.textContent=i)}function Fr(){Mo();const t=document.getElementById("pricing-modal");t&&t.classList.add("open"),Km().then(()=>Mo())}function nh(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("pricing-modal");e&&e.classList.remove("open")}function ue(t,e="info"){const s={success:"bg-green-600 text-white",error:"bg-red-600 text-white",warning:"bg-amber-500 text-white",info:"bg-gray-800 text-white"},n=document.createElement("div");n.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 ${s[e]||s.info}`,n.textContent=t,document.body.appendChild(n),setTimeout(()=>{n.style.opacity="0",setTimeout(()=>n.remove(),300)},3500)}document.addEventListener("DOMContentLoaded",async()=>{hljs.configure({tabReplace:" ",classPrefix:"hljs-"}),a_(),await qv(),i_(),await sh(),Yr(),Mo(),await yv(),fv();const t=document.getElementById("flutterflow-endpoint-select");if(t){const s=gn();t.value=s}qd(),eh();const e=document.getElementById("pipeline-input");e&&(e.addEventListener("input",()=>{Et===2&&e.value.trim().length>0&&(ma(),Ur())}),e.addEventListener("blur",()=>{const s=document.getElementById("walkthrough-modal");Et===2&&s&&s.classList.add("open")}),e.addEventListener("keydown",s=>{if(s.key==="Tab"){const n=document.getElementById("walkthrough-modal");Et===2&&n&&setTimeout(()=>{n.classList.add("open")},100)}})),window.addEventListener("commitStateChange",s=>{const{state:n}=s.detail;n===V.PREPARING||n===V.VALIDATING||n===V.PUSHING?(be.phaseId||oh(),Ic(n)):(n===V.SUCCESS||n===V.ERROR)&&(Ic(n),setTimeout(Pr,1e3))})});function a_(){const t=document.getElementById("preview-frame-container");t&&(t.style.display="")}function l_(){const t=document.getElementById("welcome-video-player");t&&(t.addEventListener("click",Yt),document.addEventListener("keydown",Yt))}function Yt(){const t=document.getElementById("preview-frame-container"),e=document.getElementById("main-stage-container"),s=document.getElementById("ready-state");t&&(t.style.display="none"),e&&e.classList.add("visible"),s&&s.classList.remove("hidden");const n=document.getElementById("welcome-video-player");n&&n.removeEventListener("click",Yt),document.removeEventListener("keydown",Yt),qd()}let Qs=null;async function c_(){const t=document.getElementById("confirm-project-select");if(!t)return;const e=++Ec,s=()=>e===Ec,n=await Ee("flutterflow"),r=await Ee("flutterflow_project_id");if(s()){if(!n){t.innerHTML='',t.disabled=!0;return}t.disabled=!1,t.innerHTML='';try{const o=await new mn(n,"").listProjects();if(!s())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(i){if(!s())return;console.error("Failed to load projects for deploy:",i),t.innerHTML=''}}}function u_(){return document.getElementById("confirm-project-select")?.value?.trim()||null}function rh(t,e,s,n=null){Qs={codeInfo:t,checks:e,deps:s,bundlePlan:n},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=n?`${n.fileEntries.length} files`:t.content.split(` +`).length,c_();const r=document.getElementById("confirm-deps-list"),i=document.getElementById("confirm-deps-section");s&&Object.keys(s).length>0?(r.innerHTML=Object.entries(s).map(([u,c])=>{const d=c?`at least ${bt(c)}`:"version resolved from your project";return`
  • • ${bt(u)}: ${d}
  • `}).join(""),i.classList.remove("hidden")):i.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=>`
  • • ${bt(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&&l.classList.add("open")}function ih(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("commit-confirm-modal");e&&e.classList.remove("open"),Qs=null}function d_(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("commit-success-modal");e&&e.classList.remove("open");const s=["success-message","success-project-id","success-file-name","success-artifact-type","success-time","success-size"];for(const i of s){const o=document.getElementById(i);o&&(o.textContent="")}const n=document.getElementById("success-warnings-section");n&&n.classList.add("hidden");const r=document.getElementById("success-warnings-list");r&&(r.innerHTML="")}function Lo(t){const e=(g,m)=>{const _=document.getElementById(g);_&&(_.textContent=m||"")},s=t.metadata?.fileName||"",n=t.metadata?.projectId||"",r=t.metadata?.artifactType||"",i=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",n),e("success-file-name",s),e("success-artifact-type",r),e("success-time",i),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&&n&&(u.href=`https://app.flutterflow.io/project/${n}`);const c=document.getElementById("success-warnings-section"),d=document.getElementById("success-warnings-list"),h=t.unverified||[],p=t.warnings||[];(p.length>0||h.length>0)&&c&&d&&(d.innerHTML=[...h.map(g=>`
  • Not verified before deploying: ${j(String(g))}
  • `),...p.map(([g,m])=>`
  • ${j(g)}: ${j(String(m))}
  • `)].join(""),c.classList.remove("hidden"));const f=document.getElementById("commit-success-modal");f&&f.classList.add("open")}function Oo(t){Pr(),Bv(t)}function h_(){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 kc={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}},p_=[{after:0,text:"Starting a FlutterFlow build runner..."},{after:12,text:"Preparing the FlutterFlow AI workspace..."},{after:35,text:"Uploading your custom classes..."},{after:60,text:"FlutterFlow is applying the changes..."},{after:100,text:"Still working — this can take a couple of minutes..."}],be={sequence:[],phaseId:null,phaseStartedAt:null,timer:null,substatus:null,liveSubstatus:!1,start({withProvisioning:t=!1}={}){this.sequence=["prepare","validate","project"],t&&this.sequence.push("provision"),this.sequence.push("package","push","done");const e=document.getElementById("commit-progress-overlay");e&&e.classList.add("open"),this.set("prepare")},set(t,e=null){if(!(!kc[t]||t===this.phaseId)){if(!this.sequence.includes(t)){const s=this.sequence.indexOf("package");this.sequence.splice(s===-1?this.sequence.length:s,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=kc[this.phaseId];if(!t)return;const e=(Date.now()-this.phaseStartedAt)/1e3,s=t.start+(t.end-t.start)*(1-Math.exp(-e/25));if(this.phaseId==="provision"&&!this.liveSubstatus){const o=p_.filter(a=>e>=a.after).pop();o&&(this.substatus=o.text)}const n=this.sequence.indexOf(this.phaseId),i=[`Step ${n===-1?1:n+1} of ${this.sequence.length}`];e>=5&&i.push(f_(e)),ah(this.phaseId==="done"?100:s,t.message,i.join(" · "),this.substatus)},stop(){this.timer&&clearInterval(this.timer),this.timer=null,this.phaseId=null;const t=document.getElementById("commit-progress-overlay");t&&t.classList.remove("open")}};function f_(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 oh(t){be.start(t)}function Pr(){be.stop()}function ah(t,e,s,n=null){const r=document.getElementById("commit-progress-bar"),i=document.getElementById("progress-message"),o=document.getElementById("progress-detail"),a=document.getElementById("progress-substatus");r&&(r.style.width=`${Math.round(t*10)/10}%`),i&&(i.textContent=e),o&&(o.textContent=s),a&&(a.textContent=n||"",a.classList.toggle("hidden",!n))}function Ic(t){const e={[V.PREPARING]:"prepare",[V.VALIDATING]:"validate",[V.PUSHING]:"project",[V.SUCCESS]:"done"};if(t===V.ERROR){be.timer&&clearInterval(be.timer),be.timer=null,ah(100,"Failed","Error occurred");return}const s=e[t];s&&be.set(s)}function g_(t){return t.bundlePlan?t.bundlePlan.fileEntries.some(e=>e.type===U.CODE_FILE):t.codeInfo?.codeType===U.CODE_FILE}async function m_(){if(!Qs){console.error("No pending commit data");return}const t=Qs;if(Qs=null,Zs=u_(),ih(),oh({withProvisioning:g_(t)}),t.bundlePlan){const o=await Fv(t.bundlePlan,{pipelineResult:{step1Result:y.step1Result,selectedModel:document.getElementById("code-generator-model")?.value}});Zs=null,Pr(),o.success?Lo(o):Oo(o);return}const{codeInfo:e}=t,{artifactType:s,artifactName:n,fileName:r}=Gd(),i=await Cv(e.content,{artifactType:s,artifactName:n,fileName:r,pipelineResult:{step1Result:y.step1Result,selectedModel:document.getElementById("code-generator-model")?.value}});Zs=null,Pr(),i.success?Lo(i):Oo(i)}window.runThinkingPipeline=To;window.toggleStep=$v;window.toggleSection=Av;window.selectWorkflowStep=ze;window.copyCode=Rv;window.retryWithDifferentModel=Lv;window.openApiKeysModal=ga;window.closeApiKeysModal=Wd;window.closeWalkthroughModal=lv;window.openWalkthroughModal=av;window.advanceWalkthrough=ma;window.commitToFlutterFlow=Iv;function v_(){const t=document.getElementById("pipeline-input");t&&t.focus()}function __(){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=v_;window.openModelSelector=__;window.handlePromptImageSelect=Vm;window.removePromptImage=Gm;window.saveApiKeys=dv;window.clearAllApiKeys=hv;window.toggleKeyVisibility=mv;window.handleWelcomeVideoEnd=l_;window.dismissWelcomeVideo=Yt;window.initiateCommitToFlutterFlow=Ov;window.updateFlutterFlowCredentialStatus=Uv;window.closeCommitConfirmModal=ih;window.closeCommitSuccessModal=d_;window.showCommitSuccessModal=Lo;window.showCommitFailureModal=Oo;window.toggleCodePreview=h_;window.confirmCommitToFlutterFlow=m_;window.runRefinement=Tv;window.regenerateFromPastedErrors=Mv;window.clearErrorInput=Nv;window.setFlutterFlowEndpoint=ov;window.getFlutterFlowEndpoint=gn;window.commitProgress=be;window.openSignInModal=Pa;window.closeSignInModal=Vv;window.handleMagicLinkRequest=Gv;window.handleSignOut=Kv;window.startCheckout=n_;window.openCustomerPortal=r_;window.openPricingModal=Fr;window.closePricingModal=nh;let hs=null,lh=null;const Cc=120;function Zr(){const t=document.getElementById("pipeline-progress"),e=document.getElementById("results-view"),s=document.getElementById("ready-state");s&&s.classList.add("hidden"),e&&e.classList.remove("visible"),document.body.classList.remove("results-fullscreen","results-with-sidebar"),t&&t.classList.add("visible"),lh=Date.now();for(let n=1;n<=3;n++){const r=document.getElementById(`pdot-${n}`);r&&(r.className="progress-dot")}rt(1),y_()}function rt(t){const e={1:"Analyzing your prompt...",2:"Generating Dart code...",3:"Running code audit..."},s={1:"Step 1 of 3 — Prompt Architect",2:"Step 2 of 3 — Code Generator",3:"Step 3 of 3 — Code Review"},n=document.getElementById("progress-title-text"),r=document.getElementById("progress-substep-text");n&&(n.textContent=e[t]||e[1]),r&&(r.textContent=s[t]||s[1]);for(let i=1;i<=3;i++){const o=document.getElementById(`pdot-${i}`);o&&(i{const t=(Date.now()-lh)/1e3,e=document.getElementById("progress-elapsed"),s=document.getElementById("pipeline-progress-fill");e&&(e.textContent=`${Math.floor(t)}s`);const n=t/Cc*100,r=Math.min(95,n*(1-Math.exp(-t/(Cc*.6)))*1.2);s&&(s.style.width=`${r}%`)},250)}function $t(){hs&&(clearInterval(hs),hs=null);const t=document.getElementById("pipeline-progress-fill");t&&(t.style.width="100%");for(let e=1;e<=3;e++){const s=document.getElementById(`pdot-${e}`);s&&(s.className="progress-dot completed")}setTimeout(()=>{const e=document.getElementById("pipeline-progress");e&&e.classList.remove("visible"),t&&(t.style.width="0%")},400)}function Ss(t,e=""){const s={pass:'',warning:'',fail:'',info:''};return``}function ch(t){return{pass:"Passed review",warning:"Needs attention",fail:"Blocking issues"}[t]||"Needs attention"}function w_(){return jg({bundle:y.artifactBundle,reviewResult:y.step3Result})}function b_(t){return` +
    + ${Ss(t.severity)} +
    +
    ${j(t.message)}
    + ${t.suggestion?`
    ${j(t.suggestion)}
    `:""} + ${j(t.source)} +
    +
    + `}function E_(t){return` +
  • +
    + ${j(t.title)} + ${t.detail&&t.detail!==t.title?`

    ${j(t.detail)}

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

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

    +

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

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

    ${j(t.summary)}

    + ${o} + ${a} +
    +
    + +
    + Is the generated code correct? +
    + + +
    +
    +
    +
    + `}function x_(t){const e=t.artifacts.find(l=>l.id===y.selectedArtifactId)||t.artifacts[0];if(!e)return"";const s={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],n=e.findings.length?e.findings.map(b_).join(""):`
    ${Ss(s.icon)} ${j(s.message)}
    `,r=e.dependencies?.length?e.dependencies.map(l=>` +
  • ${j(l.name)}${l.version?` ${j(l.version)}`:""}${l.reason?`

    ${j(l.reason)}

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

    ${j(l.description)}

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

    ${j(e.artifactName)}

    + ${e.description?`

    ${j(e.description)}

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

    Code Review findings

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

    Manual FlutterFlow steps for this file

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

    Dependencies

    +
      ${r}
    +
    +
    +

    Deployment

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

    Public API

    +
    ${o}
    +
    +
    +

    Imports

    +
    ${i}
    +
    +
    +

    Relationships

    +
      ${a}
    +
    +
    + `}function k_(t){const e=document.getElementById("bundle-strip"),s=document.getElementById("results-summary-tab"),n=document.getElementById("artifact-tabs"),r=document.getElementById("results-file-count");if(s&&s.classList.toggle("active",y.resultsViewMode==="summary"),!t.artifacts.length){r&&(r.textContent="0 files"),e&&e.classList.remove("visible"),n&&(n.innerHTML="");return}if(r){const i=t.artifacts.length;r.textContent=`${i} ${i===1?"file":"files"}`}n&&(n.innerHTML=t.artifacts.map(i=>` + + `).join(""),n.onclick=i=>{const o=i.target.closest(".artifact-tab");o?.dataset?.artifactId&&uh(o.dataset.artifactId)}),e&&e.classList.add("visible")}function Ma(){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"),s=document.getElementById("results-audit-output"),n=document.getElementById("results-summary-detail"),r=document.getElementById("artifact-results-split"),i=w_(),o=ya();if(S_(i),k_(i),e&&(e.textContent=""),e){const a=Td(o);e.innerHTML=a}s&&(s.innerHTML=x_(i)),n&&n.classList.toggle("hidden",y.resultsViewMode!=="summary"),r&&r.classList.toggle("hidden",y.resultsViewMode!=="file"),t&&t.classList.add("visible")}function Xr(t,e){y.selectedArtifactId||(y.selectedArtifactId=mr(y.artifactBundle).id),y.resultsViewMode="summary",document.body.classList.add("results-fullscreen");const s=document.getElementById("step3-output");s&&(s.textContent=""),Ma(),Zt();const n=document.getElementById("btn-feedback-up"),r=document.getElementById("btn-feedback-down");n&&(n.className="feedback-btn"),r&&(r.className="feedback-btn")}function uh(t){y.selectedArtifactId=t,y.resultsViewMode="file",Ma()}function I_(){y.resultsViewMode="summary",Ma()}function C_(){const t=document.getElementById("btn-copy-results"),e=ya();navigator.clipboard.writeText(e).then(()=>{if(t){t.classList.add("copied");const s=t.querySelector("span");if(s){const n=s.textContent;s.textContent="Copied!",setTimeout(()=>{t.classList.remove("copied"),s.textContent=n},2e3)}}})}function F_(t){const e=document.getElementById("btn-feedback-up"),s=document.getElementById("btn-feedback-down");t==="up"?(e.classList.toggle("active-up"),s.classList.remove("active-down")):(s.classList.toggle("active-down"),e.classList.remove("active-up")),Ca(t==="up"?"thumbsUp":"thumbsDown",y.step2Result,y.step1Result)}function P_(){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 dh(){const t=document.getElementById("error-input-panel");t&&(t.classList.add("hidden"),t.style.display="none")}window.copyResultsCode=C_;window.selectArtifact=uh;window.selectResultsSummary=I_;window.submitResultsFeedback=F_;window.showErrorInputPanel=P_;window.hideErrorInputPanel=dh; diff --git a/dist/index.html b/dist/index.html index b8d9443..b3d09fd 100644 --- a/dist/index.html +++ b/dist/index.html @@ -2420,7 +2420,7 @@ .pm-cards { padding: 0 16px; } } - +
    diff --git a/src/authMagicLink.js b/src/authMagicLink.js index 84bcc89..a2c57e5 100644 --- a/src/authMagicLink.js +++ b/src/authMagicLink.js @@ -1,14 +1,12 @@ -const ALLOWLISTED_DOMAINS = new Set([ - 'gmail.com', - 'googlemail.com', - 'outlook.com', - 'hotmail.com', - 'live.com', - 'msn.com' -]); +// Shared contract with the backend magic-link workflow: domains, response +// codes and message wording all come from this fixture so the frontend guard +// cannot silently drift from the server. +import fixtures from './authMagicLinkFixtures.json' with { type: 'json' }; -export const MAGIC_LINK_SUCCESS_CODE = 'MAGIC_LINK_SENT'; -export const PLUS_ALIAS_REJECTED_CODE = 'PLUS_ALIAS_REJECTED'; +const ALLOWLISTED_DOMAINS = new Set(fixtures.allowlistedDomains); + +export const MAGIC_LINK_SUCCESS_CODE = fixtures.successCode; +export const PLUS_ALIAS_REJECTED_CODE = fixtures.validationCode; export function trimEmail(raw) { return typeof raw === 'string' ? raw.trim() : ''; @@ -24,12 +22,18 @@ export function isKnownProviderPlusAlias(rawEmail) { return local.includes('+'); } +function renderRejectionMessage(email, domain) { + return fixtures.messageTemplate + .replaceAll('{email}', email) + .replaceAll('{domain}', domain); +} + export function explainPlusAliasRule(rawEmail) { if (!isKnownProviderPlusAlias(rawEmail)) return null; const email = trimEmail(rawEmail); const at = email.lastIndexOf('@'); const domain = email.slice(at + 1).toLowerCase(); - return `Please enter your primary email address. Plus aliases (such as ${email}) are not allowed for ${domain} accounts.`; + return renderRejectionMessage(email, domain); } export function getMagicLinkResultMessage(data, email) { diff --git a/src/authMagicLink.test.js b/src/authMagicLink.test.js index 95f3c85..a569417 100644 --- a/src/authMagicLink.test.js +++ b/src/authMagicLink.test.js @@ -1,5 +1,6 @@ import assert from "node:assert/strict"; import test from "node:test"; +import fixtures from "./authMagicLinkFixtures.json" with { type: "json" }; import { explainPlusAliasRule, getMagicLinkResultMessage, @@ -7,68 +8,72 @@ import { trimEmail, } from "./authMagicLink.js"; +const [firstAllowlistedDomain] = fixtures.allowlistedDomains; + test("detects plus aliases on allowlisted providers (case-insensitive)", () => { - assert.ok(isKnownProviderPlusAlias("user+tag@gmail.com")); - assert.ok(isKnownProviderPlusAlias("user+tag@GMAIL.COM")); - assert.ok(isKnownProviderPlusAlias("u+alias@googlemail.com")); - assert.ok(isKnownProviderPlusAlias("me+stuff@outlook.com")); - assert.ok(isKnownProviderPlusAlias("me+stuff@hotmail.com")); - assert.ok(isKnownProviderPlusAlias("me+stuff@live.com")); - assert.ok(isKnownProviderPlusAlias("me+stuff@msn.com")); + for (const domain of fixtures.allowlistedDomains) { + assert.ok(isKnownProviderPlusAlias(`user+tag@${domain}`), `user+tag@${domain}`); + } + assert.ok( + isKnownProviderPlusAlias(`user+tag@${firstAllowlistedDomain.toUpperCase()}`) + ); }); test("does not flag untagged allowlisted addresses", () => { - assert.equal(isKnownProviderPlusAlias("user@gmail.com"), false); - assert.equal(isKnownProviderPlusAlias("user@outlook.com"), false); - assert.equal(isKnownProviderPlusAlias("user@googlemail.com"), false); + for (const domain of fixtures.allowlistedDomains) { + assert.equal(isKnownProviderPlusAlias(`user@${domain}`), false, `user@${domain}`); + } }); test("does not flag plus aliases on custom or unrelated domains", () => { assert.equal(isKnownProviderPlusAlias("user+tag@example.com"), false); assert.equal(isKnownProviderPlusAlias("user+tag@company.io"), false); - assert.equal(isKnownProviderPlusAlias("user+tag@subdomain.gmail.com"), false); + assert.equal( + isKnownProviderPlusAlias(`user+tag@subdomain.${firstAllowlistedDomain}`), + false + ); }); test("trims whitespace before checking", () => { - assert.ok(isKnownProviderPlusAlias(" user+tag@gmail.com ")); + assert.ok(isKnownProviderPlusAlias(` user+tag@${firstAllowlistedDomain} `)); assert.equal(trimEmail(" user@example.com "), "user@example.com"); }); test("explainPlusAliasRule returns an actionable message for blocked aliases", () => { - const msg = explainPlusAliasRule("user+tag@gmail.com"); + const msg = explainPlusAliasRule(`user+tag@${firstAllowlistedDomain}`); assert.ok(msg.includes("primary email address")); - assert.ok(msg.includes("gmail.com")); - assert.ok(msg.includes("user+tag@gmail.com")); + assert.ok(msg.includes(firstAllowlistedDomain)); + assert.ok(msg.includes(`user+tag@${firstAllowlistedDomain}`)); }); test("explainPlusAliasRule returns null for non-blocked addresses", () => { - assert.equal(explainPlusAliasRule("user@gmail.com"), null); + assert.equal(explainPlusAliasRule(`user@${firstAllowlistedDomain}`), null); assert.equal(explainPlusAliasRule("user+tag@example.com"), null); }); test("getMagicLinkResultMessage maps server codes to inline messages", () => { assert.equal( - getMagicLinkResultMessage({ code: "MAGIC_LINK_SENT" }, "user@gmail.com"), - "Check your email — we sent a link to user@gmail.com" + getMagicLinkResultMessage({ code: fixtures.successCode }, `user@${firstAllowlistedDomain}`), + `Check your email — we sent a link to user@${firstAllowlistedDomain}` ); - const rejection = { code: "PLUS_ALIAS_REJECTED", message: "Use primary email." }; + const rejection = { code: fixtures.validationCode, message: "Use primary email." }; assert.equal( - getMagicLinkResultMessage(rejection, "user+tag@gmail.com"), + getMagicLinkResultMessage(rejection, `user+tag@${firstAllowlistedDomain}`), "Use primary email." ); assert.ok( getMagicLinkResultMessage( - { code: "PLUS_ALIAS_REJECTED" }, - "user+tag@gmail.com" + { code: fixtures.validationCode }, + `user+tag@${firstAllowlistedDomain}` ).includes("primary email address") ); }); test("getMagicLinkResultMessage treats legacy success responses as sent", () => { assert.equal( - getMagicLinkResultMessage({ message: "Check your email" }, "user@gmail.com"), - "Check your email — we sent a link to user@gmail.com" + getMagicLinkResultMessage({ message: "Check your email" }, `user@${firstAllowlistedDomain}`), + `Check your email — we sent a link to user@${firstAllowlistedDomain}` ); }); From 842d3a72503f77c4c917db318890bddeb1df26cf Mon Sep 17 00:00:00 2001 From: Stuart Date: Tue, 22 Sep 2026 17:39:22 +1000 Subject: [PATCH 11/13] fix(auth): announce the magic-link rejection message to screen readers Greptile: the asynchronous PLUS_ALIAS_REJECTED result updated a plain paragraph while keyboard focus stayed on the submit button, so screen readers might never hear it. #signin-message now carries role="status", an implicit polite live region appropriate for a non-critical async validation result. The element exists at page load and app.js only mutates its textContent, so the updates are announced without any JS change; the codebase had no prior live-region pattern to match. dist/ rebuilt. --- dist/index.html | 2 +- index.html | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/dist/index.html b/dist/index.html index b3d09fd..05848f5 100644 --- a/dist/index.html +++ b/dist/index.html @@ -3116,7 +3116,7 @@

    Sign

    -

    +

    diff --git a/index.html b/index.html index 3356f91..9b244c1 100644 --- a/index.html +++ b/index.html @@ -3115,7 +3115,7 @@

    Sign

    -

    +

    From 303da7161d969351fb8804a0551396502af29d2b Mon Sep 17 00:00:00 2001 From: Stuart Date: Tue, 22 Sep 2026 17:39:43 +1000 Subject: [PATCH 12/13] test(auth): assert the exact rejection message instead of substrings CodeQL flags the substring assertions over the email-bearing rejection message as an incomplete URL-substring-sanitization pattern: 'gmail.com' can appear anywhere in the message, so the check proves nothing about the rendered result. Both message assertions now compare the full, deterministic string rendered from the fixture template. The pinned strings are a deliberate snapshot of the reviewed backend contract: a fixture change now breaks these tests loudly and forces a conscious update, while the fixture-driven wiring tests keep verifying that the guard honors whatever the fixture says. --- src/authMagicLink.test.js | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/src/authMagicLink.test.js b/src/authMagicLink.test.js index a569417..b876031 100644 --- a/src/authMagicLink.test.js +++ b/src/authMagicLink.test.js @@ -40,10 +40,10 @@ test("trims whitespace before checking", () => { }); test("explainPlusAliasRule returns an actionable message for blocked aliases", () => { - const msg = explainPlusAliasRule(`user+tag@${firstAllowlistedDomain}`); - assert.ok(msg.includes("primary email address")); - assert.ok(msg.includes(firstAllowlistedDomain)); - assert.ok(msg.includes(`user+tag@${firstAllowlistedDomain}`)); + assert.equal( + explainPlusAliasRule("user+tag@gmail.com"), + "Please enter your primary email address. Plus aliases (such as user+tag@gmail.com) are not allowed for gmail.com accounts." + ); }); test("explainPlusAliasRule returns null for non-blocked addresses", () => { @@ -63,11 +63,12 @@ test("getMagicLinkResultMessage maps server codes to inline messages", () => { "Use primary email." ); - assert.ok( + assert.equal( getMagicLinkResultMessage( { code: fixtures.validationCode }, - `user+tag@${firstAllowlistedDomain}` - ).includes("primary email address") + "user+tag@gmail.com" + ), + "Please enter your primary email address. Plus aliases (such as user+tag@gmail.com) are not allowed for gmail.com accounts." ); }); From 37716b39a330451c086b1ae977f4eaee19de0008 Mon Sep 17 00:00:00 2001 From: Stuart Date: Tue, 22 Sep 2026 18:01:01 +1000 Subject: [PATCH 13/13] fix: scope the verification skip to direct importers and disclose the scratch-graph approximation (cherry picked from commit e300b76b8e56463bf7a26fb0f8e4767dd0d012d8) --- app.js | 28 ++- .../{index-BsMV38gk.js => index-DxQSKill.js} | 214 +++++++++--------- dist/index.html | 2 +- src/customCodeVerification.js | 82 +++---- src/customCodeVerification.test.js | 99 +++++--- 5 files changed, 231 insertions(+), 194 deletions(-) rename dist/assets/{index-BsMV38gk.js => index-DxQSKill.js} (53%) diff --git a/app.js b/app.js index b84ac88..95baf47 100644 --- a/app.js +++ b/app.js @@ -2120,7 +2120,7 @@ async function provisionMissingCodeFiles( ) { const missingCodeFiles = findMissingCodeFiles(fileMap, remoteFiles); if (missingCodeFiles.length === 0) { - return { remoteFiles, syncFileMap: fileMap, unverified: [] }; + return { remoteFiles, syncFileMap: fileMap, unverified: [], approximate: [] }; } // The runner compiles these against the project's own package versions @@ -2144,6 +2144,14 @@ async function provisionMissingCodeFiles( const unverified = verificationPlan.skipped.map((entry) => entry.reason); unverified.forEach((reason) => console.warn(`[custom class deploy] ${reason}`)); + // Classes that do not import an unrepresentable package directly are still + // checked, but against a scratch graph that omits it. That approximation is + // disclosed here - before the push - and returned alongside `unverified`, + // so it reaches the deploy result and is never mistaken for a full-graph + // check. + const approximate = verificationPlan.approximate; + approximate.forEach((notice) => console.warn(`[custom class deploy] ${notice}`)); + console.log( `Provisioning ${missingCodeFiles.length} new FlutterFlow custom code file(s) before sync.`, ); @@ -2185,6 +2193,7 @@ async function provisionMissingCodeFiles( remoteFiles, syncFileMap: excludeProvisionedCodeFiles(fileMap, missingCodeFiles), unverified, + approximate, }; } @@ -2877,6 +2886,7 @@ async function commitToFlutterFlow(dartCode, fileName, options = {}) { message: `Successfully committed ${fileName} to FlutterFlow project ${projectId}`, addedDependencies: pubspecMerge.added, unverified: provisioning.unverified, + approximate: provisioning.approximate, warnings: result.errorMap ? Array.from(result.errorMap.entries()) : [], }; } catch (error) { @@ -3050,6 +3060,7 @@ async function executeCommit(code, options = {}) { metadata, addedDependencies: pubspecMerge.added, unverified: provisioning.unverified, + approximate: provisioning.approximate, warnings: result.errorMap ? Array.from(result.errorMap.entries()) : [], elapsedTime: commitState.getElapsedTime(), }; @@ -3214,6 +3225,7 @@ async function executeBundleCommit(bundlePlan, options = {}) { metadata, addedDependencies: pubspecMerge.added, unverified: provisioning.unverified, + approximate: provisioning.approximate, warnings: result.errorMap ? Array.from(result.errorMap.entries()) : [], elapsedTime: commitState.getElapsedTime(), }; @@ -5360,14 +5372,24 @@ function showCommitSuccessModal(result) { const warningsSection = document.getElementById("success-warnings-section"); const warningsList = document.getElementById("success-warnings-list"); // A class that could not be compiled before the push is reported here rather - // than left implicit, so "deployed" never reads as "checked". + // than left implicit, so "deployed" never reads as "checked". A class that + // was compiled against a reduced package graph is reported beside it: the + // check ran, but approximately, and that has to stay visible too. const unverified = result.unverified || []; + const approximate = result.approximate || []; const fileWarnings = result.warnings || []; - if ((fileWarnings.length > 0 || unverified.length > 0) && warningsSection && warningsList) { + if ( + (fileWarnings.length > 0 || unverified.length > 0 || approximate.length > 0) && + warningsSection && + warningsList + ) { warningsList.innerHTML = [ ...unverified.map((reason) => `
  • Not verified before deploying: ${escapeHtml(String(reason))}
  • ` ), + ...approximate.map((notice) => + `
  • Verified approximately: ${escapeHtml(String(notice))}
  • ` + ), ...fileWarnings.map(([file, errs]) => `
  • ${escapeHtml(file)}: ${escapeHtml(String(errs))}
  • ` ), diff --git a/dist/assets/index-BsMV38gk.js b/dist/assets/index-DxQSKill.js similarity index 53% rename from dist/assets/index-BsMV38gk.js rename to dist/assets/index-DxQSKill.js index 42e19a1..cf588c1 100644 --- a/dist/assets/index-BsMV38gk.js +++ b/dist/assets/index-DxQSKill.js @@ -1,8 +1,8 @@ -(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const r of document.querySelectorAll('link[rel="modulepreload"]'))n(r);new MutationObserver(r=>{for(const i of r)if(i.type==="childList")for(const o of i.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&n(o)}).observe(document,{childList:!0,subtree:!0});function s(r){const i={};return r.integrity&&(i.integrity=r.integrity),r.referrerPolicy&&(i.referrerPolicy=r.referrerPolicy),r.crossOrigin==="use-credentials"?i.credentials="include":r.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function n(r){if(r.ep)return;r.ep=!0;const i=s(r);fetch(r.href,i)}})();var v=typeof window<"u"?window:void 0,we=typeof globalThis<"u"?globalThis:v,ke=we?.navigator,C=we?.document,ne=we?.location,Do=we?.fetch,Ni=we!=null&&we.XMLHttpRequest&&"withCredentials"in new we.XMLHttpRequest?we.XMLHttpRequest:void 0,Da=we?.AbortController,hh=we?.CompressionStream,Pe=ke?.userAgent;function Fc(){return!(!v||v.navigator.onLine===!1)}var Cs=typeof globalThis<"u"?globalThis:v;Cs&&typeof self>"u"&&(Cs.self=Cs),Cs&&typeof File>"u"&&(Cs.File=function(){});var $=v??{},Y={DEBUG:!1,LIB_VERSION:"0.5.0",LIB_NAME:"browser-common"};function Ba(t,e,s,n,r,i,o){try{var a=t[i](o),l=a.value}catch(u){return void s(u)}a.done?e(l):Promise.resolve(l).then(n,r)}function X(t){return function(){var e=this,s=arguments;return new Promise((function(n,r){var i=t.apply(e,s);function o(l){Ba(i,n,r,o,a,"next",l)}function a(l){Ba(i,n,r,o,a,"throw",l)}o(void 0)}))}}function b(){return b=Object.assign?Object.assign.bind():function(t){for(var e=1;arguments.length>e;e++){var s=arguments[e];for(var n in s)({}).hasOwnProperty.call(s,n)&&(t[n]=s[n])}return t},b.apply(null,arguments)}function Pc(t,e){if(t==null)return{};var s={};for(var n in t)if({}.hasOwnProperty.call(t,n)){if(e.indexOf(n)!==-1)continue;s[n]=t[n]}return s}var ja=t=>{if(typeof t!="string")return t;try{return JSON.parse(t)}catch{return t}};function Ua(t){return typeof t=="string"||t}function Ha(t){return typeof t=="string"?t:void 0}var Fs,ph=["$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})({}),Wa=(function(t){return t.GZipJS="gzip-js",t.Base64="base64",t})({}),fh=["$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"],gh=["token"],Ac="NativeGzipValidationError",Mi=t=>t.length>=2&&t[0]===31&&t[1]===139,za=(t,e)=>t===Wa.GZipJS||e===Wa.GZipJS||e==="gzip",qa=t=>!(!t||typeof t!="object")&&("name"in t?String(t.name):"")==="NotReadableError",wn=t=>{var e=new Error("Native gzip produced invalid output: "+t);throw e.name=Ac,e},mh=(function(){var t=X((function*(e,s){18>e.size&&wn("too-short");var n=new Uint8Array(yield e.slice(0,10).arrayBuffer());Mi(n)&&n[2]===8||wn("invalid-header");var r=new DataView(yield e.slice(e.size-8).arrayBuffer());r.getUint32(0,!0)!==(o=>{for(var a=(()=>{if(Fs)return Fs;Fs=[];for(var c=0;256>c;c++){for(var d=c,h=0;8>h;h++)d=1&d?3988292384^d>>>1:d>>>1;Fs[c]=d>>>0}return Fs})(),l=4294967295,u=0;o.length>u;u++)l=a[255&(l^o[u])]^l>>>8;return(4294967295^l)>>>0})(s)&&wn("invalid-crc");var i=s.length>>>0;r.getUint32(4,!0)!==i&&wn("invalid-size")}));return function(e,s){return t.apply(this,arguments)}})();function Li(){return Li=X((function*(t,e,s){e===void 0&&(e=!0);try{var n=new TextEncoder().encode(t),r=new globalThis.CompressionStream("gzip"),i=r.writable.getWriter(),o=i.write(n).then((()=>i.close())).catch((function(){var u=X((function*(c){try{yield i.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 mh(l,n),l}catch(u){if(s!=null&&s.rethrow)throw u;return e&&console.error("Failed to gzip compress data",u),null}})),Li.apply(this,arguments)}var vh=["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"],Va=function(t,e){if(e===void 0&&(e=[]),!t)return!1;var s=t.toLowerCase();return vh.concat(e).some((n=>{var r=n.toLowerCase();return s.indexOf(r)!==-1}))};function M(t,e){return t.indexOf(e)!==-1}var Ar=function(t){return t.trim()},Oi=function(t){return t.replace(/^\$/,"")};function $c(t){var e,s=[];return(e=JSON.stringify(t,(function(n,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(;s.length>0&&s[s.length-1]!==this;)s.pop();if(s.includes(r))return"[Circular]";s.push(r)}return r}})))!==null&&e!==void 0?e:"null"}var Rc=Object.prototype,Tc=Rc.hasOwnProperty,$r=Rc.toString,L=Array.isArray||function(t){return $r.call(t)==="[object Array]"},Se=t=>typeof t=="function",te=t=>t===Object(t)&&!L(t),mt=t=>{if(te(t)){for(var e in t)if(Tc.call(t,e))return!1;return!0}return!1},x=t=>t===void 0,W=t=>$r.call(t)=="[object String]",Di=t=>W(t)&&t.trim().length===0,$e=t=>t===null,D=t=>x(t)||$e(t),he=t=>$r.call(t)=="[object Number]"&&t==t,lt=t=>he(t)&&t>0,Ke=t=>$r.call(t)==="[object Boolean]",_h=t=>t instanceof FormData,yh=t=>M(fh,t),wh=t=>M(gh,t);function Nc(t){return t===null||typeof t!="object"}function Gn(t,e){return{}.toString.call(t)==="[object "+e+"]"}function Bo(t){return typeof Event<"u"&&Mc(t,Event)}function Mc(t,e){try{return t instanceof e}catch{return!1}}var bh=[!0,"true",1,"1","yes"],ei=t=>M(bh,t),Eh=[!1,"false",0,"0","no"];function nt(t,e,s,n,r){return e>s&&(n.warn("min cannot be greater than max."),e=s),he(t)?t>s?(n.warn(" cannot be greater than max: "+s+". Using max value instead."),s):e>t?(n.warn(" cannot be less than min: "+e+". Using min value instead."),e):t:(n.warn(" must be a number. using max or fallback. max: "+s+", fallback: "+r),nt(r||s,e,s,n))}class Sh{constructor(e){this.tt={},this.et=e.et,this.it=nt(e.bucketSize,0,100,e.rt),this.nt=nt(e.refillRate,0,this.it,e.rt),this.st=nt(e.refillInterval,0,864e5,e.rt)}ot(e,s){var n=Math.floor((s-e.lastAccess)/this.st);n>0&&(e.tokens=Math.min(e.tokens+n*this.nt,this.it),e.lastAccess=e.lastAccess+n*this.st)}consumeRateLimit(e){var s,n=Date.now(),r=String(e),i=this.tt[r];return i?this.ot(i,n):this.tt[r]=i={tokens:this.it,lastAccess:n},i.tokens===0||(i.tokens--,i.tokens===0&&((s=this.et)==null||s.call(this,e)),i.tokens===0)}stop(){this.tt={}}}var Oe="Mobile",Kn="iOS",vt="Android",ps="Tablet",Lc=vt+" "+ps,Oc="iPad",Dc="Apple",Bc=Dc+" Watch",qs="Safari",fs="BlackBerry",jc="Samsung",Uc=jc+"Browser",Hc=jc+" Internet",Vt="Chrome",xh=Vt+" OS",Wc=Vt+" "+Kn,jo="Internet Explorer",zc=jo+" "+Oe,Uo="Opera",kh=Uo+" Mini",Ho="Edge",qc="Microsoft "+Ho,us="Firefox",Vc=us+" "+Kn,en="Nintendo",tn="PlayStation",ds="Xbox",Gc=vt+" "+Oe,Kc=Oe+" "+qs,Ds="Windows",Bi=Ds+" Phone",Ga="Nokia",ji="Ouya",Jc="Generic",Ih=Jc+" "+Oe.toLowerCase(),Yc=Jc+" "+ps.toLowerCase(),Ui="Konqueror",Zc="Oculus Browser",Jn="Vivaldi",Xc="Yandex",Yn="Whale",Hi="DuckDuckGo",Qc="Pale Moon",Zn="Waterfox",Vs="Brave",eu="Google Search App",le="(\\d+(\\.\\d+)?)",ti=new RegExp("Version/"+le),Ch=new RegExp(ds,"i"),Fh=new RegExp(tn+" \\w+","i"),Ph=new RegExp(en+" \\w+","i"),Wo=new RegExp(fs+"|PlayBook|BB10","i"),Ah={"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"},tu=function(t,e,s,n){e=e||"";var r=(function(i){return i!=null&&i.brave?Vs:null})(s);return r||(n!=null&&n.detectGoogleSearchApp&&M(t,"GSA/")?eu:M(t," OPR/")&&M(t,"Mini")?kh:M(t," OPR/")?Uo:Wo.test(t)?fs:M(t,"IE"+Oe)||M(t,"WPDesktop")?zc:M(t,"OculusBrowser")?Zc:M(t,Uc)?Hc:M(t,Ho)||M(t,"Edg/")?qc:M(t,Jn+"/")?Jn:M(t,"YaBrowser/")?Xc:M(t,Yn+"/")?Yn:M(t,Hi+"/")||M(t,"Ddg/")?Hi:M(t,"FBIOS")?"Facebook "+Oe:M(t,"UCWEB")||M(t,"UCBrowser")?"UC Browser":M(t,"CriOS")?Wc:M(t,"CrMo")||M(t,Vt)?Vt:M(t,vt)&&M(t,qs)?Gc:M(t,"FxiOS")?Vc:M(t.toLowerCase(),Ui.toLowerCase())?Ui:M(t,Vs+"/")?Vs:((i,o)=>o&&M(o,Dc)||(function(a){return M(a,qs)&&!M(a,Vt)&&!M(a,vt)})(i))(t,e)?M(t,Oe)?Kc:qs:M(t,"PaleMoon/")?Qc:M(t,Zn+"/")?Zn:M(t,us)?us:M(t,"MSIE")||M(t,"Trident/")?jo:M(t,"Gecko")?us:"")},$h={[zc]:[new RegExp("rv:"+le)],[qc]:[new RegExp(Ho+"?\\/"+le)],[Vt]:[new RegExp("("+Vt+"|CrMo)\\/"+le)],[Wc]:[new RegExp("CriOS\\/"+le)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+le)],[qs]:[ti],[Kc]:[ti],[Uo]:[new RegExp("(Opera|OPR)\\/"+le)],[us]:[new RegExp(us+"\\/"+le)],[Vc]:[new RegExp("FxiOS\\/"+le)],[Ui]:[new RegExp("Konqueror[:/]?"+le,"i")],[fs]:[new RegExp(fs+" "+le),ti],[Gc]:[new RegExp("android\\s"+le,"i")],[Hc]:[new RegExp(Uc+"\\/"+le)],[Zc]:[new RegExp("OculusBrowser\\/"+le)],[Jn]:[new RegExp(Jn+"\\/"+le)],[Xc]:[new RegExp("YaBrowser\\/"+le)],[Yn]:[new RegExp(Yn+"\\/"+le)],[Vs]:[new RegExp(Vs+"\\/"+le)],[Hi]:[new RegExp("(DuckDuckGo|Ddg)\\/"+le)],[Qc]:[new RegExp("PaleMoon\\/"+le)],[Zn]:[new RegExp(Zn+"\\/"+le)],[eu]:[new RegExp("GSA\\/"+le)],[jo]:[new RegExp("(rv:|MSIE )"+le)],Mozilla:[new RegExp("rv:"+le)]},Rh=function(t,e,s,n){var r=tu(t,e,s,n),i=$h[r];if(x(i))return null;for(var o=0;i.length>o;o++){var a=t.match(i[o]);if(a)return parseFloat(a[a.length-2])}return null},Ka=[[new RegExp(ds+"; "+ds+" (.*?)[);]","i"),t=>[ds,t&&t[1]||""]],[new RegExp(en,"i"),[en,""]],[new RegExp(tn,"i"),[tn,""]],[Wo,[fs,""]],[new RegExp(Ds,"i"),(t,e)=>{if(/Phone/.test(e)||/WPDesktop/.test(e))return[Bi,""];if(new RegExp(Oe).test(e)&&!/IEMobile\b/.test(e))return[Ds+" "+Oe,""];var s=/Windows NT ([0-9.]+)/i.exec(e);if(s&&s[1]){var n=Ah[s[1]]||"";return/arm/i.test(e)&&(n="RT"),[Ds,n]}return[Ds,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,t=>t&&t[3]?[Kn,[t[3],t[4],t[5]||"0"].join(".")]:[Kn,""]],[/(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i,t=>{var e="";return t&&t.length>=3&&(e=x(t[2])?t[3]:t[2]),["watchOS",e]}],[new RegExp("("+vt+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+vt+")","i"),t=>t&&t[2]?[vt,[t[2],t[3],t[4]||"0"].join(".")]:[vt,""]],[/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/,[xh,""]],[/Linux|debian/i,["Linux",""]]],Ja=function(t){return Ph.test(t)?en:Fh.test(t)?tn:Ch.test(t)?ds:new RegExp(ji,"i").test(t)?ji:new RegExp("("+Bi+"|WPDesktop)","i").test(t)?Bi:/iPad/.test(t)?Oc:/iPod/.test(t)?"iPod Touch":/iPhone/.test(t)?"iPhone":/(watch)(?: ?os[,/]|\d,\d\/)[\d.]+/i.test(t)?Bc:Wo.test(t)?fs:/(kobo)\s(ereader|touch)/i.test(t)?"Kobo":new RegExp(Ga,"i").test(t)?Ga:/(kf[a-z]{2}wi|aeo[c-r]{2})( bui|\))/i.test(t)||/(kf[a-z]+)( bui|\)).+silk\//i.test(t)?"Kindle Fire":/(Android|ZTE)/i.test(t)?new RegExp(Oe).test(t)&&!/(9138B|TB782B|Nexus [97]|pixel c|HUAWEISHT|BTV|noble nook|smart ultra 6)/i.test(t)||/pixel[\daxl ]{1,6}/i.test(t)&&!/pixel c/i.test(t)||/(huaweimed-al00|tah-|APA|SM-G92|i980|zte|U304AA)/i.test(t)||/lmy47v/i.test(t)&&!/QTAQZ3/i.test(t)?vt:Lc:new RegExp("(pda|"+Oe+")","i").test(t)?Ih:new RegExp(ps,"i").test(t)&&!new RegExp(ps+" pc","i").test(t)?Yc:""},Th=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Ya(t,e){return typeof(s=t)=="string"&&Th.test(s)?t:e();var s}function Ct(t){return t&&t.split("#")[0]}function zo(t,e){var s=setTimeout(t,e);return s?.unref&&s?.unref(),s}function Za(t,e,s){return su.apply(this,arguments)}function su(){return(su=X((function*(t,e,s){var n;try{return yield Promise.race([t,new Promise(((r,i)=>{n=zo((()=>{try{s?.(),r()}catch(o){i(o)}}),e)}))])}finally{clearTimeout(n)}}))).apply(this,arguments)}var Nh=t=>t instanceof Error,nu={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}},Mh=nu.info;function ru(t){if(Ke(t))return{boolValue:t};if(typeof t=="number")return Number.isFinite(t)?Number.isInteger(t)?{intValue:t}:{doubleValue:t}:{stringValue:String(t)};if(typeof t=="string")return{stringValue:t};if(L(t))return{arrayValue:{values:t.map((e=>ru(e)))}};try{return{stringValue:JSON.stringify(t)}}catch{return{stringValue:String(t)}}}function Xn(t){var e=[];for(var s in t){var n=t[s];$e(n)||x(n)||e.push({key:s,value:ru(n)})}return e}function Lh(t,e){var s=nu[t.level||"info"]||Mh,n=s.text,r=s.number,i=String(Date.now())+"000000",o={};e.distinctId&&(o.posthogDistinctId=e.distinctId),e.sessionId&&(o.sessionId=e.sessionId),e.windowId&&(o["window.id"]=e.windowId),D(e.sessionStartTimestamp)||(o.sessionStartTimestamp=String(e.sessionStartTimestamp)),D(e.lastActivityTimestamp)||(o.lastActivityTimestamp=String(e.lastActivityTimestamp)),e.currentUrl&&(o["url.full"]=e.currentUrl),e.screenName&&(o["screen.name"]=e.screenName),e.appState&&(o["app.state"]=e.appState),e.activeFeatureFlags&&e.activeFeatureFlags.length>0&&(o.feature_flags=e.activeFeatureFlags);var a=b({},o,t.attributes||{}),l={timeUnixNano:i,observedTimeUnixNano:i,severityNumber:r,severityText:n,body:{stringValue:t.body},attributes:Xn(a)};return t.trace_id&&(l.traceId=t.trace_id),t.span_id&&(l.spanId=t.span_id),x(t.trace_flags)||(l.flags=t.trace_flags),l}function iu(t,e,s){return b({},t.resourceAttributes,{"service.name":t.serviceName||"unknown_service"},t.environment&&{"deployment.environment":t.environment},t.serviceVersion&&{"service.version":t.serviceVersion},{"telemetry.sdk.name":e,"telemetry.sdk.version":s})}function ou(t,e,s,n){return{resourceLogs:[{resource:{attributes:Xn(e)},scopeLogs:[{scope:{name:s,version:n},logRecords:t}]}]}}let Oh=class{constructor(t,e,s,n,r,i,o){var a;i===void 0&&(i=()=>Promise.resolve()),this._instance=t,this.Ne=e,this.rt=s,this.ut=n,this.ht=r,this.dt=i,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 s={record:Lh(e,this.ut())};this.ht((()=>this.At(s)))}}else this.rt.info("Log was rejected in beforeSend function")}}Pt(t){var e=this.Ne.beforeSend;if(!e)return t;var s=L(e)?e:[e],n=t;for(var r of s)try{var i=r(n);if(!i)return this.rt.info("Log was rejected in beforeSend function"),null;n=i}catch(o){return this.rt.error("Error in beforeSend function for log:",o),null}return n}Rt(){if(this.Tt===void 0)return!0;var t=Date.now(),e=t-this.bt;return this.Mt>e&&e>=0||(this.bt=t,this._t=0,this.wt=!1),this.Tt>this._t?(this._t++,!0):(this.wt||(this.rt.warn("captureLog dropping logs: exceeded "+this.Tt+" logs per "+this.Mt+"ms"),this.wt=!0),!1)}flush(){var t=this;return X((function*(){if(!t._instance.isDisabled)return t.ct||(t.ct=t.Ft().finally((()=>{t.ct=null}))),t.ct}))()}Ft(){var t=this;return X((function*(){var e;t.Et();var s=(e=t._instance.getPersistedProperty(ut.LogsQueue))!==null&&e!==void 0?e:[];if(s.length!==0)for(var n=s.length,r=0;s.length>0&&n>r;){var i,o;t.ft=0;var a=Math.min(s.length,t.Ct),l=s.slice(0,a),u=ou(l.map((d=>d.record)),t.Lt(),(i=t.vt)!==null&&i!==void 0?i: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),s=(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 X((function*(){var s,n=Math.max(0,t-e.ft),r=(s=e._instance.getPersistedProperty(ut.LogsQueue))!==null&&s!==void 0?s:[];e._instance.setPersistedProperty(ut.LogsQueue,r.slice(n)),yield e.dt()}))()}Lt(){return iu(this.Ne,this._instance.getLibraryId(),this._instance.getLibraryVersion())}At(t){var e;if(!this._instance.optedOut){var s=(e=this._instance.getPersistedProperty(ut.LogsQueue))!==null&&e!==void 0?e:[];this.xt>s.length||(s.shift(),this.ft++,this.rt.info("Logs queue is full, dropping oldest record.")),s.push(t),this._instance.setPersistedProperty(ut.LogsQueue,s),this.kt>s.length?this.$t():this.It()}}$t(t){t===void 0&&(t=this.St),this.Nt||(this.Nt=zo((()=>{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 X((function*(){e.Et();var s=e.flush().catch((()=>{}));t!==void 0?yield Za(s,t):yield s}))()}flushWithTimeout(t){var e=this;return X((function*(){var s=e.flush();yield Za(s,t,(()=>{s.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 si=[0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4];function Xa(t){return String(t)+"000000"}function Qa(t,e,s,n){var r="";return n&&(r=Object.keys(n).sort().map((i=>JSON.stringify(i)+":"+JSON.stringify(n[i]))).join(",")),t+"\0"+e+"\0"+(s??"")+"\0"+r}let Dh=class{constructor(t,e,s){this._instance=t,this.Ne=e,this.rt=s,this.Bt=new Map,this.ct=null,this.Ht=!1,this.Ut=new Map,this.zt=new Set,this.Wt=0}count(t,e,s){e===void 0&&(e=1),this.Vt({name:t,type:"count",value:e,unit:s?.unit,attributes:s?.attributes})}gauge(t,e,s){this.Vt({name:t,type:"gauge",value:e,unit:s?.unit,attributes:s?.attributes})}histogram(t,e,s){this.Vt({name:t,type:"histogram",value:e,unit:s?.unit,attributes:s?.attributes})}flush(){var t=this,e=this.ct,s=(function(){var r=X((function*(){e&&(yield e.catch((()=>{}))),yield t.Zt()}));return function(){return r.apply(this,arguments)}})(),n=s().finally((()=>{this.ct===n&&(this.ct=null)}));return this.ct=n,n}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 s,n;try{s=e.attributes?b({},e.attributes):void 0,n=Qa(e.type,e.name,e.unit,s)}catch(o){return void this.rt.warn("Dropping metric '"+e.name+"': attributes could not be serialized",o)}var r=this.Bt.get(n);if(!r){if(!this.Qt())return;r={name:e.name,type:e.type,unit:e.unit,attributes:s,windowStartMs:Date.now()},this.Bt.set(n,r)}var i=this.Ut.get(e.name);i===void 0?this.Ut.set(e.name,e.type):i===e.type||this.zt.has(e.name)||(this.zt.add(e.name),this.rt.warn("Metric name '"+e.name+"' is already used as a "+i+"; recording it as a "+e.type+" too will blend both series in charts. Use a distinct name.")),this.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 s;switch(t.type){case"count":t.total=((s=t.total)!==null&&s!==void 0?s: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(si.length+1).fill(0)});var n=t.hist;n.count+=1,n.sum+=e,n.min=Math.min(n.min,e),n.max=Math.max(n.max,e),n.bucketCounts[(function(r,i){for(var o=0;i.length>o;o++)if(i[o]>=r)return o;return i.length})(e,si)]+=1}}Pt(t){var e=this.Ne.beforeSend;if(!e)return t;var s=L(e)?e:[e],n=t;for(var r of s)try{var i=r(n);if(!i)return this.rt.info("Metric was rejected in beforeSend function"),null;n=i}catch(o){return this.rt.error("Error in beforeSend function for metric:",o),null}return n}$t(){this.Nt||(this.Nt=zo((()=>{this.Nt=void 0,this.flush().catch((t=>{this.rt.error("Metrics flush failed:",t)}))}),this.Ne.flushIntervalMs))}Et(){this.Nt&&(clearTimeout(this.Nt),this.Nt=void 0)}Zt(){var t=this;return X((function*(){if(t.Bt.size!==0){var e=t.Bt;t.Bt=new Map,t.Ht=!1,t.Ut=new Map,t.zt=new Set;var s=t.Wt,n=yield t._instance.Jt(t.Gt(e));if(s===t.Wt)switch(n.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:",n.error)}}}))()}Gt(t){return e=this.Xt(t),s=(function(i,o,a){return b({},i.resourceAttributes,{"service.name":i.serviceName||"unknown_service"},i.environment&&{"deployment.environment":i.environment},i.serviceVersion&&{"service.version":i.serviceVersion},{"telemetry.sdk.name":o,"telemetry.sdk.version":a})})(this.Ne,this._instance.getLibraryId(),this._instance.getLibraryVersion()),n=this._instance.getLibraryId(),r=this._instance.getLibraryVersion(),{resourceMetrics:[{resource:{attributes:Xn(s)},scopeMetrics:[{scope:{name:n,version:r},metrics:e}]}]};var e,s,n,r}Xt(t){var e=Xa(Date.now()),s=new Map;for(var n of t.values()){var r,i=Qa(n.type,n.name,n.unit,void 0),o=s.get(i);o||(o=b({name:n.name},n.unit&&{unit:n.unit}),n.type==="count"?o.sum={aggregationTemporality:1,isMonotonic:!0,dataPoints:[]}:n.type==="gauge"?o.gauge={dataPoints:[]}:o.histogram={aggregationTemporality:1,dataPoints:[]},s.set(i,o));var a=Xn((r=n.attributes)!==null&&r!==void 0?r:{}),l=Xa(n.windowStartMs);if(n.type==="count"){var u,c={attributes:a,startTimeUnixNano:l,timeUnixNano:e,asDouble:(u=n.total)!==null&&u!==void 0?u:0};o.sum.dataPoints.push(c)}else if(n.type==="gauge"){var d,h={attributes:a,timeUnixNano:e,asDouble:(d=n.last)!==null&&d!==void 0?d:0};o.gauge.dataPoints.push(h)}else n.hist&&o.histogram.dataPoints.push({attributes:a,startTimeUnixNano:l,timeUnixNano:e,count:n.hist.count,sum:n.hist.sum,min:n.hist.min,max:n.hist.max,bucketCounts:n.hist.bucketCounts,explicitBounds:si})}return Array.from(s.values())}Yt(t){var e,s;for(var n of t){var r=n[0],i=n[1],o=this.Bt.get(r);if(o)switch(o.windowStartMs=Math.min(o.windowStartMs,i.windowStartMs),o.type){case"count":o.total=((e=o.total)!==null&&e!==void 0?e:0)+((s=i.total)!==null&&s!==void 0?s:0);break;case"gauge":break;case"histogram":if(i.hist)if(o.hist){o.hist.count+=i.hist.count,o.hist.sum+=i.hist.sum,o.hist.min=Math.min(o.hist.min,i.hist.min),o.hist.max=Math.max(o.hist.max,i.hist.max);for(var a=0;o.hist.bucketCounts.length>a;a++)o.hist.bucketCounts[a]+=i.hist.bucketCounts[a]}else o.hist=i.hist}else this.Qt()&&this.Bt.set(r,i)}}};var bn,el,ni;function Bh(t){var e=globalThis._posthogChunkIds;if(e){var s=Object.keys(e);return ni&&s.length===el||(el=s.length,ni=s.reduce(((n,r)=>{bn||(bn={});var i=bn[r];if(i)n[i[0]]=i[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){n[u]=c,bn[r]=[u,c];break}}return n}),{})),ni}}class jh{constructor(e,s,n){n===void 0&&(n=[]),this.coercers=e,this.stackParser=s,this.modifiers=n}buildFromUnknown(e,s){s===void 0&&(s={});var n=s&&s.mechanism||{handled:!0,type:"generic"},r=this.buildCoercingContext(n,s,0).apply(e),i=this.buildParsingContext(s),o=this.parseStacktrace(r,i);return{$exception_list:this.convertToExceptionList(o,n),$exception_level:"error"}}modifyFrames(e){var s=this;return X((function*(){for(var n of e)n.stacktrace&&n.stacktrace.frames&&L(n.stacktrace.frames)&&(n.stacktrace.frames=yield s.applyModifiers(n.stacktrace.frames));return e}))()}coerceFallback(e){var s;return{type:"Error",value:"Unknown error",stack:(s=e.syntheticException)==null?void 0:s.stack,synthetic:!0}}parseStacktrace(e,s){var n,r;return e.cause!=null&&(n=this.parseStacktrace(e.cause,s)),e.stack!=""&&e.stack!=null&&(r=this.applyChunkIds(this.stackParser(e.stack,e.synthetic?s.skipFirstLines:0),s.chunkIdMap)),b({},e,{cause:n,stack:r})}applyChunkIds(e,s){return e.map((n=>(n.filename&&s&&(n.chunk_id=s[n.filename]),n)))}applyCoercers(e,s){for(var n of this.coercers)if(n.match(e))return n.coerce(e,s);return this.coerceFallback(s)}applyModifiers(e){var s=this;return X((function*(){var n=e;for(var r of s.modifiers)n=yield r(n);return n}))()}convertToExceptionList(e,s){var n,r,i,o={type:e.type,value:e.value,mechanism:{type:(n=s.type)!==null&&n!==void 0?n:"generic",handled:(r=s.handled)===null||r===void 0||r,synthetic:(i=e.synthetic)!==null&&i!==void 0&&i}};e.stack&&(o.stacktrace={type:"raw",frames:e.stack});var a=[o];return e.cause!=null&&a.push(...this.convertToExceptionList(e.cause,b({},s,{handled:!0}))),a}buildParsingContext(e){var s;return{chunkIdMap:Bh(this.stackParser),skipFirstLines:(s=e.skipFirstLines)!==null&&s!==void 0?s:1}}buildCoercingContext(e,s,n){n===void 0&&(n=0);var r=(i,o)=>{if(4>=o){var a=this.buildCoercingContext(e,s,o);return this.applyCoercers(i,a)}};return b({},s,{syntheticException:n==0?s.syntheticException:void 0,mechanism:e,apply:i=>r(i,n),next:i=>r(i,n+1)})}}var gs="?";function Wi(t,e,s,n,r){var i={platform:t,filename:e,function:s===""?gs:s,in_app:!0};return x(n)||(i.lineno=n),x(r)||(i.colno=r),i}var au=(t,e)=>{var s=t.indexOf("safari-extension")!==-1,n=t.indexOf("safari-web-extension")!==-1;return s||n?[t.indexOf("@")!==-1?t.split("@")[0]:gs,s?"safari-extension:"+e:"safari-web-extension:"+e]:[t,e]},Uh=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,Hh=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,Wh=/\((\S*)(?::(\d+))(?::(\d+))\)/,zh=(t,e)=>{var s=Uh.exec(t);if(s)return Wi(e,s[1],gs,+s[2],+s[3]);var n=Hh.exec(t);if(n){if(n[2]&&n[2].indexOf("eval")===0){var r=Wh.exec(n[2]);r&&(n[2]=r[1],n[3]=r[2],n[4]=r[3])}var i=au(n[1]||gs,n[2]);return Wi(e,i[1],i[0],n[3]?+n[3]:void 0,n[4]?+n[4]:void 0)}},qh=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,Vh=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,Gh=(t,e)=>{var s=qh.exec(t);if(s){if(s[3]&&s[3].indexOf(" > eval")>-1){var n=Vh.exec(s[3]);n&&(s[1]=s[1]||"eval",s[3]=n[1],s[4]=n[2],s[5]="")}var r=s[3],i=s[1]||gs,o=au(i,r);return Wi(e,r=o[1],i=o[0],s[4]?+s[4]:void 0,s[5]?+s[5]:void 0)}},tl=/\(error: (.*)\)/;class Kh{match(e){return this.isDOMException(e)||this.isDOMError(e)}coerce(e,s){var n=W(e.stack);return{type:this.getType(e),value:this.getValue(e),stack:n?e.stack:void 0,cause:e.cause?s.next(e.cause):void 0,synthetic:!1}}getType(e){return this.isDOMError(e)?"DOMError":"DOMException"}getValue(e){var s=e.name||(this.isDOMError(e)?"DOMError":"DOMException");return e.message?s+": "+e.message:s}isDOMException(e){return Gn(e,"DOMException")}isDOMError(e){return Gn(e,"DOMError")}}class Jh{match(e){return(function(s){switch({}.toString.call(s)){case"[object Error]":case"[object Exception]":case"[object DOMException]":case"[object DOMError]":case"[object WebAssembly.Exception]":return!0;default:return Mc(s,Error)}})(e)}coerce(e,s){return{type:this.getType(e),value:this.getMessage(e,s),stack:this.getStack(e),cause:e.cause?s.next(e.cause):void 0,synthetic:!1}}getType(e){return e.name||e.constructor.name}getMessage(e,s){var n=e.message;return String(n.error&&typeof n.error.message=="string"?n.error.message:n)}getStack(e){return e.stacktrace||e.stack||void 0}}class Yh{constructor(){}match(e){return!!Gn(e,"ErrorEvent")&&(e.error!=null||this.fe(e))}coerce(e,s){var n;if(e.error!=null)return s.apply(e.error);var r=s.apply(e.message);return b({},r,{stack:(n=this.pe(e))!==null&&n!==void 0?n:r.stack,synthetic:!0})}fe(e){return W(e.message)&&e.message.length>0}pe(e){var s=e;if(W(s.filename)&&s.filename.length>0){var n,r,i=(n=s.lineno)!==null&&n!==void 0?n:0,o=(r=s.colno)!==null&&r!==void 0?r:0;return`Error - at `+s.filename+":"+i+":"+o}}}var Zh=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;class Xh{match(e){return typeof e=="string"}coerce(e,s){var n,r=this.getInfos(e),i=r[0],o=r[1];return{type:i??"Error",value:o??e,stack:(n=s.syntheticException)==null?void 0:n.stack,synthetic:!0}}getInfos(e){var s="Error",n=e,r=e.match(Zh);return r&&(s=r[1],n=r[2]),[s,n]}}var Qh=["fatal","error","warning","log","info","debug"];function lu(t,e){e===void 0&&(e=40);var s=Object.keys(t);if(s.sort(),!s.length)return"[object has no keys]";for(var n=s.length;n>0;n--){var r=s.slice(0,n).join(", ");if(e>=r.length)return n===s.length?r:r.length>e?r.slice(0,e)+"...":r}return""}class ep{match(e){return typeof e=="object"&&e!==null}coerce(e,s){var n,r,i=this.getErrorPropertyFromObject(e);return i?s.apply(i):{type:this.getType(e),value:this.getValue(e),stack:(n=this.getStack(e))!==null&&n!==void 0?n:(r=s.syntheticException)==null?void 0:r.stack,level:this.isSeverityLevel(e.level)?e.level:"error",synthetic:!0}}getType(e){return Bo(e)?e.constructor.name:"Error"}getValue(e){if("name"in e&&typeof e.name=="string"){var s="'"+e.name+"' captured as exception";return"message"in e&&typeof e.message=="string"&&(s+=" with message: '"+e.message+"'"),s}if("message"in e&&typeof e.message=="string")return e.message;var n=this.getObjectClassName(e);return(n&&n!=="Object"?"'"+n+"'":"Object")+" captured as exception with keys: "+lu(e)}isSeverityLevel(e){return W(e)&&!Di(e)&&Qh.indexOf(e)>=0}getStack(e){try{return W(e.stacktrace)&&e.stacktrace.length>0?e.stacktrace:W(e.stack)&&e.stack.length>0?e.stack:void 0}catch{return}}getErrorPropertyFromObject(e){for(var s in e)if({}.hasOwnProperty.call(e,s)){var n=e[s];if(Nh(n))return n}}getObjectClassName(e){try{var s=Object.getPrototypeOf(e);return s?s.constructor.name:void 0}catch{return}}}class tp{match(e){return Bo(e)}coerce(e,s){var n,r=e.constructor.name;return{type:r,value:r+" captured as exception with keys: "+lu(e),stack:(n=s.syntheticException)==null?void 0:n.stack,synthetic:!0}}}class sp{match(e){return Nc(e)}coerce(e,s){var n;return{type:"Error",value:"Primitive value captured as exception: "+String(e),stack:(n=s.syntheticException)==null?void 0:n.stack,synthetic:!0}}}class np{match(e){return Gn(e,"PromiseRejectionEvent")||this.isCustomEventWrappingRejection(e)}isCustomEventWrappingRejection(e){if(!Bo(e))return!1;try{var s=e.detail;return s!=null&&typeof s=="object"&&"reason"in s}catch{return!1}}coerce(e,s){var n,r=this.getUnhandledRejectionReason(e);return Nc(r)?{type:"UnhandledRejection",value:"Non-Error promise rejection captured with value: "+String(r),stack:(n=s.syntheticException)==null?void 0:n.stack,synthetic:!0}:s.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 Qn="$message",er="$timestamp",rp=new Set([Qn,er]),ri={enabled:!0,max_bytes:32768};function tr(t){var e;return t?{enabled:(e=t.enabled)!==null&&e!==void 0?e:ri.enabled,max_bytes:op(t.max_bytes,ri.max_bytes)}:b({},ri)}class ip{constructor(e){this.Ke=[],this.Je=0,this.Ne=tr(e)}setConfig(e){this.Ne=tr(e),this.Xe()}add(e){var s=(function(r){var i;try{i=$c(r)}catch{return}try{var o=JSON.parse(i);if(!te(o))return;var a=o,l=a[Qn],u=a[er];return!W(l)||l.trim().length===0||!W(u)&&!he(u)?void 0:{step:a,json:i}}catch{return}})(e);if(s){var n=(function(r){if(typeof TextEncoder<"u")return new TextEncoder().encode(r).length;for(var i=encodeURIComponent(r),o=0,a=0;i.length>a;a++)i[a]==="%"?(o+=1,a+=2):o+=1;return o})(s.json);n>this.Ne.max_bytes||(this.Ke.push({step:s.step,bytes:n}),this.Je+=n,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 op(t,e){if(!he(t)||t===1/0||t===-1/0)return e;var s=Math.floor(t);return 0>s?e:s}var cu=function(t,e){var s=(e===void 0?{}:e).debugEnabled,n={k(r){if(v&&(Y.DEBUG||v.POSTHOG_DEBUG||s)&&!x(v.console)&&v.console){for(var i=("__rrweb_original__"in v.console[r])?v.console[r].__rrweb_original__:v.console[r],o=arguments.length,a=new Array(o>1?o-1:0),l=1;o>l;l++)a[l-1]=arguments[l];i(t,...a)}},debug(){for(var r=arguments.length,i=new Array(r),o=0;r>o;o++)i[o]=arguments[o];n.k("debug",...i)},info(){for(var r=arguments.length,i=new Array(r),o=0;r>o;o++)i[o]=arguments[o];n.k("log",...i)},warn(){for(var r=arguments.length,i=new Array(r),o=0;r>o;o++)i[o]=arguments[o];n.k("warn",...i)},error(){for(var r=arguments.length,i=new Array(r),o=0;r>o;o++)i[o]=arguments[o];n.k("error",...i)},critical(){for(var r=arguments.length,i=new Array(r),o=0;r>o;o++)i[o]=arguments[o];console.error(t,...i)},uninitializedWarning(r){n.error("You must initialize PostHog before calling "+r)},createLogger:(r,i)=>cu(t+" "+r,i)};return n},k=cu("[PostHog.js]"),se=k.createLogger,ap=se("[ExternalScriptsLoader]"),ii=(t,e,s)=>{if(t.config.disable_external_dependency_loading)return ap.warn(e+" was requested but loading of external scripts is disabled."),s("Loading of external scripts is disabled");var n=C?.querySelectorAll("script");if(n){for(var r,i=function(){if(n[o].src===e){var l=n[o];return l.__posthog_loading_callback_fired?{v:s()}:(l.addEventListener("load",(u=>{l.__posthog_loading_callback_fired=!0,s(void 0,u)})),l.onerror=u=>s(u),{v:void 0})}},o=0;n.length>o;o++)if(r=i())return r.v}var a=()=>{if(!C)return s("document not found");var l=C.createElement("script");if(l.type="text/javascript",l.crossOrigin="anonymous",l.src=e,l.onload=d=>{l.__posthog_loading_callback_fired=!0,s(void 0,d)},l.onerror=d=>s(d),t.config.prepare_external_dependency_script&&(l=t.config.prepare_external_dependency_script(l)),!l)return s("prepare_external_dependency_script returned null");if(t.config.external_scripts_inject_target==="head")C.head.appendChild(l);else{var u,c=C.querySelectorAll("body > script");c.length>0?(u=c[0].parentNode)==null||u.insertBefore(l,c[0]):C.body.appendChild(l)}};C!=null&&C.body?a():C?.addEventListener("DOMContentLoaded",a)};$.__PosthogExtensions__=$.__PosthogExtensions__||{},$.__PosthogExtensions__.loadExternalDependency=(t,e,s)=>{if(e!=="remote-config"){var n;if(t.config.strict_script_versioning)n=t.requestRouter.endpointFor("assets","/static/"+t.version+"/"+e+".js");else{var r="/static/"+e+".js?v="+t.version;if(e==="toolbar"){var i=3e5;r=r+"&t="+Math.floor(Date.now()/i)*i}n=t.requestRouter.endpointFor("assets",r)}ii(t,n,s)}else{var o=t.requestRouter.endpointFor("assets","/array/"+t.config.token+"/config.js");ii(t,o,s)}},$.__PosthogExtensions__.loadSiteApp=(t,e,s)=>{var n=t.requestRouter.endpointFor("api",e);ii(t,n,s)};Y.DEBUG=!1,Y.LIB_VERSION="1.415.7",Y.LIB_NAME="web";var uu="$people_distinct_id",sn="$device_id",oi="$device_model",Bs="__alias",js="__timers",zi="$autocapture_disabled_server_side",qi="$heatmaps_enabled_server_side",Vi="$exception_capture_enabled_server_side",Gi="$error_tracking_suppression_rules",Ki="$error_tracking_capture_extension_exceptions",Ji="$web_vitals_enabled_server_side",qo="$dead_clicks_enabled_server_side",Vo="$product_tours_enabled_server_side",Yi="$web_vitals_allowed_metrics",qt="$session_recording_remote_config",du="$replay_sample_rate",hu="$replay_override_sampling",pu="$replay_override_linked_flag",fu="$replay_override_url_trigger",gu="$replay_override_event_trigger",ls="$sesid",Go="$session_is_sampled",Bt="$enabled_feature_flags",Us="$active_feature_flags",Tn="$early_access_features",Zi="$feature_flag_details",Hs="$feature_flag_payloads",Nn="$feature_flag_request_id",sr="$minimal_flag_called_events",et="$override_feature_flags",jt="$override_feature_flag_payloads",ct="$stored_person_properties",Ut="$stored_group_properties",Xi="$surveys",nr="$surveys_loaded_at",Qi="$surveys_activated",Mn="$surveys_activated_session",Ln="$surveys_activated_timestamps",Ws="ph_product_tours",Wt="$flag_call_reported",zs="$flag_call_reported_session_id",On="$feature_flag_errors",Gs="$feature_flag_evaluated_at",He="$user_state",eo="$client_session_props",to="$capture_rate_limit",so="$initial_campaign_params",no="$initial_referrer_info",rr="$initial_person_info",ir="$epp",En="$posthog_cookieless",mu="$cookieless_mode",vu="$sdk_debug_extensions_init_method",_u="$sdk_debug_extensions_init_time_ms",yu="$sdk_debug_recording_script_not_loaded",Ko="PostHog loadExternalDependency extension not found.",Ht="on_reject",ht="always",es="anonymous",Tt="identified",ro="identified_only",or="visibilitychange",ar="beforeunload",is="$pageview",ai="$pageleave",li="$identify",sl="$groupidentify";function Sn(t,e){L(t)&&t.forEach(e)}function Z(t,e){if(!D(t))if(L(t))t.forEach(e);else if(_h(t))t.forEach(((n,r)=>e(n,r)));else for(var s in t)Tc.call(t,s)&&e(t[s],s)}var ee=function(t){for(var e=arguments.length,s=new Array(e>1?e-1:0),n=1;e>n;n++)s[n-1]=arguments[n];for(var r of s)for(var i in r)r[i]!==void 0&&(t[i]=r[i]);return t};function Dn(t){for(var e=Object.keys(t),s=e.length,n=new Array(s);s--;)n[s]=[e[s],t[e[s]]];return n}var nl=function(t){try{return t()}catch{return}},lp=function(t){return function(){try{for(var e=arguments.length,s=new Array(e),n=0;e>n;n++)s[n]=arguments[n];return t.apply(this,s)}catch(r){k.critical("Implementation error. Please turn on debug mode and open a ticket on https://app.posthog.com/home#panel=support%3Asupport%3A."),k.critical(r)}}},Jo=function(t){var e={};return Z(t,(function(s,n){(W(s)&&s.length>0||he(s))&&(e[n]=s)})),e},cp=["herokuapp.com","vercel.app","netlify.app"];function up(t){var e=t?.hostname;if(!W(e))return!1;var s=e.split(".").slice(-2).join(".");for(var n of cp)if(s===n)return!1;return!0}function re(t,e,s,n){var r=n??{},i=r.capture,o=r.passive;t?.addEventListener(e,s,{capture:i!==void 0&&i,passive:o===void 0||o})}function io(t){return t.name==="ph_toolbar_internal"}var wu=t=>{if(C){try{for(var e=t+"=",s=C.cookie.split(";").filter((i=>i.length)),n=0;s.length>n;n++){for(var r=s[n];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 he(t)&&isFinite(t)&&Math.floor(t)===t});class lr{constructor(e){if(this.bytes=e,e.length!==16)throw new TypeError("not 128-bit length")}static fromFieldsV7(e,s,n,r){if(!Number.isInteger(e)||!Number.isInteger(s)||!Number.isInteger(n)||!Number.isInteger(r)||0>e||0>s||0>n||0>r||e>0xffffffffffff||s>4095||n>1073741823||r>4294967295)throw new RangeError("invalid field value");var i=new Uint8Array(16);return i[0]=e/Math.pow(2,40),i[1]=e/Math.pow(2,32),i[2]=e/Math.pow(2,24),i[3]=e/Math.pow(2,16),i[4]=e/256,i[5]=e,i[6]=112|s>>>8,i[7]=s,i[8]=128|n>>>24,i[9]=n>>>16,i[10]=n>>>8,i[11]=n,i[12]=r>>>24,i[13]=r>>>16,i[14]=r>>>8,i[15]=r,new lr(i)}toString(){for(var e="",s=0;this.bytes.length>s;s++)e=e+(this.bytes[s]>>>4).toString(16)+(15&this.bytes[s]).toString(16),s!==3&&s!==5&&s!==7&&s!==9||(e+="-");if(e.length!==36)throw new Error("Invalid UUIDv7 was generated");return e}clone(){return new lr(this.bytes.slice(0))}equals(e){return this.compareTo(e)===0}compareTo(e){for(var s=0;16>s;s++){var n=this.bytes[s]-e.bytes[s];if(n!==0)return Math.sign(n)}return 0}}class dp{generate(){var e=this.generateOrAbort();if(!x(e))return e;this.S=0;var s=this.generateOrAbort();if(x(s))throw new Error("Could not generate UUID after timestamp reset");return s}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 lr.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 hp}}var rl,bu=t=>{if(typeof UUIDV7_DENY_WEAK_RNG<"u"&&UUIDV7_DENY_WEAK_RNG)throw new Error("no cryptographically strong RNG available");for(var e=0;t.length>e;e++)t[e]=65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random());return t};v&&!x(v.crypto)&&crypto.getRandomValues&&(bu=t=>crypto.getRandomValues(t));class hp{nextUint32(){return this.R.length>this.O||(bu(this.R),this.O=0),this.R[this.O++]}constructor(){this.R=new Uint32Array(8),this.O=1/0}}var dt=()=>pp().toString(),pp=()=>(rl||(rl=new dp)).generate(),Ps="",fp=/[a-z0-9][a-z0-9-]+\.[a-z]{2,}$/i,pt={N:()=>!!C,j(t){k.error("cookieStore error: "+t)},P:wu,H(t){var e;try{e=JSON.parse(pt.P(t))||{}}catch{}return e},F(t,e,s,n,r){if(!C)return!1;try{var i="",o="",a=(function(c,d){if(d){var h=(function(f,g){if(g===void 0&&(g=C),Ps)return Ps;if(!g||["localhost","127.0.0.1"].includes(f))return"";for(var m=f.split("."),_=Math.min(m.length,8),w="dmn_chk_"+dt();!Ps&&_--;){var E=m.slice(_).join("."),I=w+"=1;domain=."+E+";path=/";g.cookie=I+";max-age=3",g.cookie.includes(w)&&(g.cookie=I+";max-age=0",Ps=E)}return Ps})(c);if(!h){var p=(f=>{var g=f.match(fp);return g?g[0]:""})(c);p!==h&&k.info("Warning: cookie subdomain discovery mismatch",p,h),h=p}return h?"; domain=."+h:""}return""})(C.location.hostname,n);if(s){var l=new Date;l.setTime(l.getTime()+864e5*s),i="; expires="+l.toUTCString()}r&&(o="; secure");var u=t+"="+encodeURIComponent(JSON.stringify(e))+i+"; SameSite=Lax; path=/"+a+o;return u.length>3686.4&&k.warn("cookieStore warning: large cookie, len="+u.length),C.cookie=u,!0}catch{return!1}},q(t,e){if(C!=null&&C.cookie)try{pt.F(t,"",-1,e)}catch{return}}},ci=null,Q={N(){if(!$e(ci))return ci;var t=!0;if(x(v))t=!1;else try{var e="__mplssupport__";Q.F(e,"xyz"),Q.P(e)!=='"xyz"'&&(t=!1),Q.q(e)}catch{t=!1}return t||k.error("localStorage unsupported; falling back to cookie store"),ci=t,t},j(t){k.error("localStorage error: "+t)},P(t){try{return v?.localStorage.getItem(t)}catch(e){Q.j(e)}return null},H(t){try{return JSON.parse(Q.P(t))||{}}catch{}return null},F(t,e){try{return v?.localStorage.setItem(t,JSON.stringify(e)),!0}catch(s){Q.j(s)}return!1},q(t){try{v?.localStorage.removeItem(t)}catch(e){Q.j(e)}}},gp=[sn,"distinct_id",ls,Go,ir,rr,He],xn={},mp={N:()=>!0,j(t){k.error("memoryStorage error: "+t)},P:t=>xn[t]||null,H:t=>xn[t]||null,F:(t,e)=>(xn[t]=e,!0),q(t){delete xn[t]}},Nt=null,ce={N(){if(!$e(Nt))return Nt;if(Nt=!0,x(v))Nt=!1;else try{var t="__support__";ce.F(t,"xyz"),ce.P(t)!=='"xyz"'&&(Nt=!1),ce.q(t)}catch{Nt=!1}return Nt},j(t){k.error("sessionStorage error: ",t)},P(t){try{return v?.sessionStorage.getItem(t)}catch(e){ce.j(e)}return null},H(t){try{return JSON.parse(ce.P(t))||null}catch{}return null},F(t,e){try{return v?.sessionStorage.setItem(t,JSON.stringify(e)),!0}catch(s){ce.j(s)}return!1},q(t){try{v?.sessionStorage.removeItem(t)}catch(e){ce.j(e)}}};class vp{constructor(e){this._instance=e}get Ne(){return this._instance.config}get consent(){return this.ti()?0:this.ei}isOptedOut(){return this.Ne.cookieless_mode===ht||this.isRejected()||this.consent===-1&&this.Ne.cookieless_mode===Ht}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,s=e.token,n=e.opt_out_capturing_cookie_prefix;return e.consent_persistence_name||(n?n+s:"__ph_opt_in_out_"+s)}get ei(){var e=this.ii.P(this.ri);return ei(e)?1:M(Eh,e)?0:-1}get ii(){var e=this.Ne.opt_out_capturing_persistence_type,s=e==="localStorage"?Q:pt;if(!this.ni||this.ni!==s){this.ni=s;var n=e==="localStorage"?pt:Q;n.P(this.ri)&&(this.ni.P(this.ri)||this.optInOut(ei(n.P(this.ri))),n.q(this.ri,this.Ne.cross_subdomain_cookie))}return this.ni}ti(){return!!this.Ne.respect_dnt&&[ke?.doNotTrack,ke?.msDoNotTrack,$.doNotTrack].some((e=>ei(e)))}}function Eu(t,e){var s,n=t==null||(s=t.config)==null?void 0:s.get_current_url;if(!Se(n))return e;try{var r=n(e);return W(r)&&r?r:e}catch(i){return k.error("Error in get_current_url, falling back to window.location.href",i),e}}var Su="__POSTHOG_TOOLBAR__",_p=1,yp=3,wp=11;function il(t){return t instanceof Element&&(t.id===Su||!(t.closest==null||!t.closest(".toolbar-global-fade-container")))}function Ft(t){return!!t&&t.nodeType===_p}function Me(t,e){return!!t&&!!t.tagName&&t.tagName.toLowerCase()===e.toLowerCase()}function xu(t){return!!t&&t.nodeType===yp}function ku(t){return!!t&&t.nodeType===wp&&Ft(t.host)}var Iu=1e3;function Yo(t){return t?Ar(t).split(/\s+/):[]}function ol(t,e){var s=(function(n){var r,i=v==null||(r=v.location)==null?void 0:r.href;return x(i)?void 0:Eu(n,i)})(e);return!!(s&&t&&t.some((n=>s.match(n))))}function cr(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 Yo(e)}function Cu(t){return D(t)?null:Ar(t).split(/(\s+)/).filter((e=>Ks(e))).join("").replace(/[\r\n]/g," ").replace(/[ ]+/g," ").substring(0,255)}function nn(t){var e="";return ao(t)&&!$u(t)&&t.childNodes&&t.childNodes.length&&Z(t.childNodes,(function(s){var n;xu(s)&&s.textContent&&(e+=(n=Cu(s.textContent))!==null&&n!==void 0?n:"")})),Ar(e)}function ui(t){var e;return x(t.target)?t.srcElement||null:(e=t.target)!=null&&e.shadowRoot?t.composedPath()[0]||null:t.target||null}var Zo=["a","button","form","input","select","textarea","label"];function oo(t,e){if(x(e))return!0;var s,n=function(i){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}})(i,o))))return{v:!0}};for(var r of t)if(s=n(r))return s.v;return!1}function Fu(t){var e=t.parentNode;return!(!e||!Ft(e))&&e}var bp=[".ph-no-autocapture","[data-ph-no-autocapture]"],Pu=["next","previous","prev",">","<"],Ep=[...Pu,"+","-","−","–"],al=(t,e)=>/[a-z0-9]/i.test(e)?t.includes(e):t===e,ll=[".ph-no-rageclick",".ph-no-capture"],Sp=["","text","search","email","password","url","tel","number"];function cl(t,e){if(!v||Xo(t))return!1;var s,n,r,i,o;if(Ke(e)?(s=!!e&&ll,n=void 0,r=!1):(s=(i=e?.css_selector_ignorelist)!==null&&i!==void 0?i:ll,n=e?.content_ignorelist,r=(o=e?.ignore_text_selection)!==null&&o!==void 0&&o),s===!1||r&&(function(l){return!(!l||!Ft(l))&&(!!Me(l,"textarea")||(Me(l,"input")?M(Sp,(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=Au(t,!1).targetElementList;return!(function(l,u){if(l===!1||x(l))return!1;var c;if(l===!0)c=Pu;else{if(!L(l))return!1;if(l.length>10)return k.error("[PostHog] content_ignorelist array cannot exceed 10 items. Use css_selector_ignorelist for more complex matching."),!1;c=l.map((d=>d.toLowerCase()))}return u.some((d=>{var h=d.safeText,p=d.ariaLabel;return c.some((f=>al(h,f)||al(p,f)))}))})(n,a.map((l=>{var u;return{safeText:nn(l).toLowerCase(),ariaLabel:((u=l.getAttribute("aria-label"))==null?void 0:u.toLowerCase().trim())||""}})))&&!oo(a,s)}var Xo=t=>!t||Me(t,"html")||!Ft(t),Au=(t,e)=>{if(!v||Xo(t))return{parentIsUsefulElement:!1,targetElementList:[]};for(var s=!1,n=[t],r=t;r.parentNode&&!Me(r,"body");)if(ku(r.parentNode))n.push(r.parentNode.host),r=r.parentNode.host;else{var i=Fu(r);if(!i)break;if(e||Zo.indexOf(i.tagName.toLowerCase())>-1)s=!0;else try{var o=v.getComputedStyle(i);o&&o.getPropertyValue("cursor")==="pointer"&&(s=!0)}catch{}n.push(i),r=i}return{parentIsUsefulElement:s,targetElementList:n}};function ao(t){for(var e=new Set,s=0,n=t;n.parentNode&&!Me(n,"body");n=n.parentNode){if(s++>=Iu||e.has(n))return!1;e.add(n);var r=cr(n);if(M(r,"ph-sensitive")||M(r,"ph-no-capture"))return!1}if(M(cr(t),"ph-include"))return!0;var i=t.type||"";if(W(i))switch(i.toLowerCase()){case"hidden":case"password":return!1}var o=t.name||t.id||"";return!W(o)||!/^cc|cardnum|ccnum|creditcard|csc|cvc|cvv|exp|pass|pwd|routing|seccode|securitycode|securitynum|socialsec|socsec|ssn/i.test(o.replace(/[^a-zA-Z0-9]/g,""))}function $u(t){return!!(Me(t,"input")&&!["button","checkbox","submit","reset"].includes(t.type)||Me(t,"select")||Me(t,"textarea")||t.getAttribute("contenteditable")==="true")}var ul=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}))$"),dl=/(^|[^0-9A-Za-z_])([0-9][0-9 -]*[0-9])(?=$|[^0-9A-Za-z_])/g,xp=[16,15,14,13],kp=new RegExp("^(\\d{3}-?\\d{2}-?\\d{4})$"),hl=new RegExp("(^|[^0-9])((?!000|666)[0-9]{3}-?(?!00)[0-9]{2}-?(?!0000)[0-9]{4})(?=$|([^0-9]))","g"),pl=/[0-9A-Za-z_]/;function Ip(t){for(var e=0,s=!1,n=t.length-1;n>=0;n--){var r=t.charCodeAt(n)-48;s&&(r*=2)>9&&(r-=9),e+=r,s=!s}return e%10==0}function Ks(t,e){if(e===void 0&&(e=!0),D(t))return!1;if(W(t)){t=Ar(t);var s=e?ul.test((t||"").replace(/[- ]/g,"")):(function(r){var i;for(dl.lastIndex=0;i=dl.exec(r);){var o=i[2];if(o)for(var a=o.replace(/[- ]/g,""),l=0;a.length>l;l++)for(var u of xp){var c=l+u;if(a.length>=c){var d=a.slice(l,c);if(ul.test(d)&&Ip(d))return!0}}}return!1})(t);if(s)return!1;var n=e?kp.test(t):(function(r){var i;for(hl.lastIndex=0;i=hl.exec(r);){var o=i[1],a=i[3];if(!(o&&a&&pl.test(o)&&pl.test(a)))return!0}return!1})(t);if(n)return!1}return!0}function fl(t){var e=nn(t);return Ks(e=(e+" "+Ru(t)).trim())?e:""}function Ru(t){var e="";return t&&t.childNodes&&t.childNodes.length&&Z(t.childNodes,(function(s){var n;if(s&&((n=s.tagName)==null?void 0:n.toLowerCase())==="span")try{var r=nn(s);e=(e+" "+r).trim(),s.childNodes&&s.childNodes.length&&(e=(e+" "+Ru(s)).trim())}catch(i){k.error("[AutoCapture]",i)}})),e}function gl(t){return t.replace(/"|\\"/g,'\\"')}function Cp(t){var e=t.attr__class;if(e)return L(e)?e:Yo(e)}var kn=se("[Dead Clicks]"),Fp=()=>!0,Pp=t=>{var e,s=!((e=t.instance.persistence)==null||!e.get_property(qo)),n=t.instance.config.capture_dead_clicks;return Ke(n)?n:!!te(n)||s};class ml{get lazyLoadedDeadClicksAutocapture(){return this.si}constructor(e,s,n){this.instance=e,this.isEnabled=s,this.onCapture=n,this.startIfEnabledOrStop()}onRemoteConfig(e){if(e.ok){var s=e.config;"captureDeadClicks"in s&&(this.instance.persistence&&this.instance.persistence.register({[qo]:s.captureDeadClicks}),this.startIfEnabledOrStop())}}startIfEnabledOrStop(){this.isEnabled(this)?this.ai((()=>{this.oi()})):this.stop()}ai(e){var s,n;(s=$.__PosthogExtensions__)!=null&&s.initDeadClicksAutocapture?e():(n=$.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this.instance,"dead-clicks-autocapture",(r=>{r?kn.error("failed to load script",r):e()}))}oi(){var e;if(C){if(!this.si&&(e=$.__PosthogExtensions__)!=null&&e.initDeadClicksAutocapture){var s=te(this.instance.config.capture_dead_clicks)?b({},this.instance.config.capture_dead_clicks):{};s.__onCapture=this.onCapture,this.onCapture&&(s.capture_dead_swipes=!1),this.si=$.__PosthogExtensions__.initDeadClicksAutocapture(this.instance,s),this.si.start(C),kn.info("starting...")}}else kn.error("`document` not found. Cannot start.")}stop(){this.si&&(this.si.stop(),this.si=void 0,kn.info("stopping..."))}}var di=se("[SegmentIntegration]"),Tu="posthog-js";function Nu(t,e){var s=e===void 0?{}:e,n=s.organization,r=s.projectId,i=s.prefix,o=s.severityAllowList,a=o===void 0?["error"]:o,l=s.sendExceptionsToPostHog,u=l===void 0||l;return c=>{var d,h,p,f,g;if(a!=="*"&&!a.includes(c.level)||!t.__loaded)return c;c.tags||(c.tags={});var m=t.requestRouter.endpointFor("ui","/project/"+t.config.token+"/person/"+t.get_distinct_id());c.tags["PostHog Person URL"]=m,t.sessionRecordingStarted()&&(c.tags["PostHog Recording URL"]=t.get_session_replay_url({withTimestamp:!0}));var _,w=((d=c.exception)==null?void 0:d.values)||[],E=w.map((F=>b({},F,{stacktrace:F.stacktrace?b({},F.stacktrace,{type:"raw",frames:(F.stacktrace.frames||[]).map((P=>b({},P,{platform:"web:javascript"})))}):void 0}))),I={$exception_message:((h=w[0])==null?void 0:h.value)||c.message,$exception_type:(p=w[0])==null?void 0:p.type,$exception_level:c.level,$exception_list:E,$sentry_event_id:c.event_id,$sentry_exception:c.exception,$sentry_exception_message:((f=w[0])==null?void 0:f.value)||c.message,$sentry_exception_type:(g=w[0])==null?void 0:g.type,$sentry_tags:c.tags};return n&&r&&(I.$sentry_url=(i||"https://sentry.io/organizations/")+n+"/issues/?project="+r+"&query="+c.event_id),u&&((_=t.exceptions)==null||_.sendExceptionEvent(I)),c}}class Ap{constructor(e,s,n,r,i,o){this.name=Tu,this.setupOnce=function(a){a(Nu(e,{organization:s,projectId:n,prefix:r,severityAllowList:i,sendExceptionsToPostHog:o==null||o}))}}}class vl{constructor(e){this.li=(s,n,r)=>{r&&(r.noSessionId||r.activityTimeout||r.sessionPastMaximumLength||r.crossTabAdoption)&&(k.info("[PageViewManager] Session rotated, clearing pageview state",{sessionId:s,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,s){var n,r=this.vi(e,s);return this.ui={pathname:(n=v?.location.pathname)!==null&&n!==void 0?n:"",pageViewId:s,timestamp:e},this._instance.scrollManager.resetContext(),r}doPageLeave(e){var s;return this.vi(e,(s=this.ui)==null?void 0:s.pageViewId)}doEvent(){var e;return{$pageview_id:(e=this.ui)==null?void 0:e.pageViewId}}vi(e,s){var n=this.ui;if(!n)return{$pageview_id:s};var r={$pageview_id:s,$prev_pageview_id:n.pageViewId},i=this._instance.scrollManager.getContext();if(i&&!this._instance.config.disable_scroll_properties){var o=i.maxScrollHeight,a=i.lastScrollY,l=i.maxScrollY,u=i.maxContentHeight,c=i.lastContentY,d=i.maxContentY;if(!(x(o)||x(a)||x(l)||x(u)||x(c)||x(d))){o=Math.ceil(o),a=Math.ceil(a),l=Math.ceil(l),u=Math.ceil(u),c=Math.ceil(c),d=Math.ceil(d);var h=o>1?nt(a/o,0,1,k):1,p=o>1?nt(l/o,0,1,k):1,f=u>1?nt(c/u,0,1,k):1,g=u>1?nt(d/u,0,1,k):1;r=ee(r,{$prev_pageview_last_scroll:a,$prev_pageview_last_scroll_percentage:h,$prev_pageview_max_scroll:l,$prev_pageview_max_scroll_percentage:p,$prev_pageview_last_content:c,$prev_pageview_last_content_percentage:f,$prev_pageview_max_content:d,$prev_pageview_max_content_percentage:g})}}return n.pathname&&(r.$prev_pageview_pathname=n.pathname),n.timestamp&&(r.$prev_pageview_duration=(e.getTime()-n.timestamp.getTime())/1e3),r}}var hi=["flags","surveys"],$p={[uu]:{exposure:"hidden"},[Bs]:{exposure:"hidden"},__cmpns:{exposure:"hidden"},[js]:{exposure:"hidden"},[zi]:{exposure:"event"},[qi]:{exposure:"hidden"},[Vi]:{exposure:"event"},[Gi]:{exposure:"hidden"},[Ki]:{exposure:"event"},[Ji]:{exposure:"event"},[qo]:{exposure:"event"},[Vo]:{exposure:"hidden"},[Yi]:{exposure:"event"},[qt]:{exposure:"hidden"},$session_recording_enabled_server_side:{exposure:"hidden"},[ls]:{exposure:"hidden"},[Go]:{exposure:"event"},[du]:{exposure:"event",shouldSkipFromEventProperties:t=>$e(t)},$session_past_minimum_duration:{exposure:"event"},$session_recording_url_trigger_activated_session:{exposure:"event"},$session_recording_event_trigger_activated_session:{exposure:"event"},$debug_first_full_snapshot_timestamp:{exposure:"event"},$sess_rec_flush_size:{exposure:"hidden"},[Bt]:{exposure:"hidden",storageGroup:"flags"},[Us]:{exposure:"hidden",storageGroup:"flags"},[Tn]:{exposure:"hidden"},[Zi]:{exposure:"hidden",storageGroup:"flags"},[Hs]:{exposure:"hidden",storageGroup:"flags"},[Nn]:{exposure:"hidden",storageGroup:"flags",volatile:!0},[sr]:{exposure:"hidden",storageGroup:"flags"},[et]:{exposure:"hidden"},[jt]:{exposure:"hidden"},[ct]:{exposure:"hidden"},[Ut]:{exposure:"hidden"},[Xi]:{exposure:"hidden",storageGroup:"surveys"},[nr]:{exposure:"hidden",storageGroup:"surveys",volatile:!0},[Qi]:{exposure:"event"},[Mn]:{exposure:"hidden"},[Ln]:{exposure:"hidden"},[Ws]:{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"},[Wt]:{exposure:"hidden"},[zs]:{exposure:"hidden"},[On]:{exposure:"hidden"},[Gs]:{exposure:"hidden",storageGroup:"flags",volatile:!0},[He]:{exposure:"hidden"},[eo]:{exposure:"hidden"},[to]:{exposure:"hidden"},[so]:{exposure:"hidden"},[no]:{exposure:"hidden"},[rr]:{exposure:"hidden"},[ir]:{exposure:"hidden"},[hu]:{exposure:"event"},[pu]:{exposure:"event"},[fu]:{exposure:"event"},[gu]:{exposure:"event"},[vu]:{exposure:"event"},[_u]:{exposure:"event"},[yu]:{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"}},Rp=[["$posthog_sr_group_event_trigger_",{exposure:"hidden"}],["$posthog_sr_group_url_trigger_",{exposure:"hidden"}],["$posthog_sr_group_sampling_",{exposure:"hidden"}]],Mt=t=>{var e=$p[t];if(e)return e;for(var s of Rp){var n=s[1];if(t.indexOf(s[0])===0)return n}},cs=(t,e)=>{try{return JSON.stringify(t,((s,n)=>typeof n=="bigint"?n.toString():n),e)}catch{return $c(t)}},ur=t=>{var e=C?.createElement("a");return x(e)?null:(e.href=t,e)},ms=function(t,e){for(var s,n=((t.split("#")[0]||"").split(/\?(.*)/)[1]||"").replace(/^\?+/g,"").split("&"),r=0;n.length>r;r++){var i=n[r].split("=");if(i[0]===e){s=i;break}}if(!L(s)||2>s.length)return"";var o=s[1];try{o=decodeURIComponent(o)}catch{k.error("Skipping decoding for malformed query param: "+o)}return o.replace(/\+/g," ")},rn=function(t,e,s){if(!t||!e||!e.length)return t;for(var n=t.split("#"),r=n[1],i=(n[0]||"").split("?"),o=i[1],a=i[0],l=(o||"").split("&"),u=[],c=0;l.length>c;c++){var d=l[c].split("=");L(d)&&(e.includes(d[0])?u.push(d[0]+"="+s):u.push(l[c]))}var h=a;return o!=null&&(h+="?"+u.join("&")),r!=null&&(h+="#"+r),h},dr=function(t,e){var s=t.match(new RegExp(e+"=([^&]*)"));return s?s[1]:null},Mu=(t,e)=>t>=e&&Fc(),Lu=(t,e,s,n)=>{if(t===0){if(Fc()){var r=e+1;return r===s&&n(),r}return e}return 0},In="https?://(.*)",vs=["gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","irclid","_kx"],Tp=["utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid",...vs],on="",Np=["li_fat_id"];function Ou(t,e,s){if(!C)return{};var n,r=e?[...vs,...s||[]]:[],i=Du(rn(C.URL,r,on),t),o=(n={},Z(Np,(function(a){var l=wu(a);n[a]=l||null})),n);return ee(o,i)}function Du(t,e){var s=Tp.concat(e||[]),n={};return Z(s,(function(r){var i=ms(t,r);n[r]=i||null})),n}function Bu(t){var e=(function(i){return i?i.search(In+"google.([^/?]*)")===0?"google":i.search(In+"bing.com")===0?"bing":i.search(In+"yahoo.com")===0?"yahoo":i.search(In+"duckduckgo.com")===0?"duckduckgo":null:null})(t),s=e!="yahoo"?"q":"p",n={};if(!$e(e)){n.$search_engine=e;var r=C?ms(C.referrer,s):"";r.length&&(n.ph_keyword=r)}return n}function _l(){return navigator.language||navigator.userLanguage}var hr="$direct";function ju(){return C?.referrer||hr}function Uu(t,e,s){s===void 0&&(s=!1);var n=t?[...vs,...e||[]]:[],r=s?Ct(ne?.href):ne?.href,i=r?.substring(0,1e3);return{r:ju().substring(0,1e3),u:i?rn(i,n,on):void 0}}function Hu(t,e){var s;e===void 0&&(e=!1);var n=t.r,r=t.u,i=e?Ct(r):r,o={$referrer:n,$referring_domain:n==null?void 0:n==hr?hr:(s=ur(n))==null?void 0:s.host};if(i){o.$current_url=i;var a=ur(i);o.$host=a?.host,o.$pathname=a?.pathname;var l=Du(i);ee(o,l)}if(n){var u=Bu(n);ee(o,u)}return o}function Wu(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return}}function Mp(){try{return new Date().getTimezoneOffset()}catch{return}}var Lp={flags:Gs,surveys:nr},Op=["cookie","localstorage","localstorage+cookie","sessionstorage","memory"],ts="main";class pi{constructor(e,s,n){if(n===void 0&&(n=!0),this.ci={},this.fi=!1,this.pi=!1,this.Ne=e,this.gi=n,this.props={},this.mi=void 0,this.yi=(i=>{var o="";return i.token&&(o=i.token.replace(/\+/g,"PL").replace(/\//g,"SL").replace(/=/g,"EQ")),i.persistence_name?"ph_"+i.persistence_name:"ph_"+o+"_posthog"})(e),this.ii=this.bi(e),this.pi=this.wi(e),this.load(),e.debug&&k.info("Persistence loaded",e.persistence,b({},this.props)),this.update_config(e,e,s),this.save(),v){var r=()=>this.flush();re(v,"beforeunload",r,{capture:!1}),re(v,"pagehide",r,{capture:!1})}}ki(){var e,s=(e=this.Ne)==null?void 0:e.persistence_save_debounce_ms;return he(s)&&s>0?s:0}isDisabled(){return!!this.xi}bi(e){Op.indexOf(e.persistence.toLowerCase())===-1&&(k.critical("Unknown persistence type "+e.persistence+"; falling back to localStorage+cookie"),e.persistence="localStorage+cookie");var s,n=(function(o,a){o===void 0&&(o=[]),a===void 0&&(a=!1);var l=[...gp,...o];return b({},Q,{H(u){try{var c={};try{c=pt.H(u)||{}}catch{}var d,h=JSON.parse(Q.P(u)||"{}");if(a){var p={};for(var f in c){var g=c[f];$e(g)||g===""||(p[f]=g)}d=ee(h,p)}else d=ee(c,h);return Q.F(u,d),d}catch{}return null},F(u,c,d,h,p,f){var g=Q.F(u,c,void 0,void 0,f);try{var m={};l.forEach((_=>{c[_]&&(m[_]=c[_])})),Object.keys(m).length&&pt.F(u,m,d,h,p,f)}catch(_){Q.j(_)}return g},q(u,c){try{v?.localStorage.removeItem(u),pt.q(u,c)}catch(d){Q.j(d)}}})})(e.cookie_persisted_properties||[],e.__preview_cookie_wins_on_conflict||!1),r=!1,i=e.persistence.toLowerCase();return i==="localstorage"&&Q.N()?(s=Q,r=!0):i==="localstorage+cookie"&&n.N()?(s=n,r=!0):i==="sessionstorage"&&ce.N()?s=ce:i==="memory"?s=mp:i==="cookie"?s=pt:n.N()?(s=n,r=!0):s=pt,this.fi=r,s}Si(e){return this.yi+"__"+e}wi(e){return this.fi&&!!e.split_storage}properties(){var e={};return Z(this.props,((s,n)=>{var r=Mt(n);if(!r||r.exposure==="event"){if(r!=null&&r.shouldSkipFromEventProperties!=null&&r.shouldSkipFromEventProperties(s))return;e[n]=s}})),e}load(){if(!this.xi){var e=this.ii.H(this.yi);e&&(this.props=ee({},e)),this.pi&&this.Ci()}}Ci(){for(var e of hi){var s=Q.H(this.Si(e));if(s&&!mt(s)){var n=this.Mi(e);n.persisted=!0,this.Ti(e)||(n.fingerprint=this.Ei(s,e)),this.Ii(e,s)||ee(this.props,s)}}}Ti(e){return Object.keys(this.props).some((s=>{var n;return((n=Mt(s))==null?void 0:n.storageGroup)===e}))}Ii(e,s){var n=Lp[e];if(!n)return!1;var r=s[n],i=this.props[n];return he(r)&&he(i)&&i>r}refreshKey(e){var s;if(!this.xi){var n=this.pi?(s=Mt(e))==null?void 0:s.storageGroup:void 0,r=n?Q.H(this.Si(n)):this.ii.H(this.yi);if(r&&e in r)this.Pi(e,r[e]);else{if(n){var i=this.ii.H(this.yi);if(i&&e in i)return void this.Pi(e,i[e])}this.Ri(e)}}}save(){if(!this.xi){var e=this.ki();e>0?x(this.Ai)&&(this.Ai=setTimeout((()=>{this.Ai=void 0,this.Fi()}),e)):this.Fi()}}flush(){x(this.Ai)||(clearTimeout(this.Ai),this.Ai=void 0,this.Fi())}Fi(){this.xi||(this.pi?this.Li():this.Oi(this.ii,this.yi,this.props,ts))}Li(){var e=this.Di(),s=e.main,n=e.groups;for(var r of(this.Oi(this.ii,this.yi,s,ts),hi)){var i,o=n[r];(!mt(o)||(i=this.ci[r])!=null&&i.persisted)&&this.Oi(Q,this.Si(r),o,r)}}Di(){var e={},s={flags:{},surveys:{}};return Z(this.props,((n,r)=>{var i,o=(i=Mt(r))==null?void 0:i.storageGroup;o?s[o][r]=n:e[r]=n})),{main:e,groups:s}}Ei(e,s){if(s===ts)return JSON.stringify(e)+"|"+this.$i+"|"+this.Ni+"|"+this.qi;var n={};return Z(e,((r,i)=>{var o;n[i]=(o=Mt(i))!=null&&o.volatile?"__volatile__":r})),JSON.stringify(n)}Oi(e,s,n,r){var i=this.Mi(r);if(r===ts||i.dirty||x(i.fingerprint)){var o;try{if((o=this.Ei(n,r))===i.fingerprint)return void(i.dirty=!1)}catch{o=void 0}e.F(s,n,this.$i,this.Ni,this.qi,this.Ne.debug)?(i.dirty=!1,r!==ts&&(i.persisted=!0),x(o)||(i.fingerprint=o)):this.Ne.debug&&k.warn('failed to persist storage entry "'+s+'"; will retry on next save')}}remove(e){var s=(e===void 0?{}:e).keepGroupEntries,n=s!==void 0&&s;if(x(this.Ai)||(clearTimeout(this.Ai),this.Ai=void 0),this.ii.q(this.yi,!1),this.ii.q(this.yi,!0),!n&&this.gi)for(var r of hi)Q.q(this.Si(r));n?delete this.ci[ts]:this.ci={}}clear(){this.remove(),this.props={}}register_once(e,s,n){if(te(e)){x(s)&&(s="None"),this.$i=x(n)?this.ji:n;var r=!1;if(Z(e,((i,o)=>{this.props.hasOwnProperty(o)&&this.props[o]!==s||(this.Pi(o,i),r=!0)})),r)return this.save(),!0}return!1}register(e,s){if(te(e)){this.$i=x(s)?this.ji:s;var n=!1;if(Z(e,((r,i)=>{e.hasOwnProperty(i)&&(this.props[i]!==r||te(r)||L(r))&&(this.Pi(i,r),n=!0)})),n)return this.save(),!0}return!1}unregister(e){var s=typeof e=="string"?[e]:e,n=!1;for(var r of s)r in this.props&&(this.Ri(r),n=!0);n&&this.save()}update_campaign_params(){var e=C?.URL;if(e!==this.mi){var s=Ou(this.Ne.custom_campaign_params,this.Ne.mask_personal_data_properties,this.Ne.custom_personal_data_properties);mt(Jo(s))||this.register(s),this.mi=e}}update_search_keyword(){var e;this.register((e=C?.referrer)?Bu(e):{})}update_referrer_info(){var e;this.register_once({$referrer:ju(),$referring_domain:C!=null&&C.referrer&&((e=ur(C.referrer))==null?void 0:e.host)||hr},void 0)}set_initial_person_info(){this.props[so]||this.props[no]||this.register_once({[rr]:Uu(this.Ne.mask_personal_data_properties,this.Ne.custom_personal_data_properties,this.Ne.disable_capture_url_hashes)},void 0)}get_initial_props(){var e={};Z([no,so],(r=>{var i=this.props[r];i&&Z(i,(function(o,a){e["$initial_"+Oi(a)]=o}))}));var s=this.props[rr];if(s){var n=(function(r,i){i===void 0&&(i=!1);var o=Hu(r,i),a={};return Z(o,(function(l,u){a["$initial_"+Oi(u)]=l})),a})(s,this.Ne.disable_capture_url_hashes);ee(e,n)}return e}safe_merge(e){return Z(this.props,(function(s,n){n in e||(e[n]=s)})),e}update_config(e,s,n){this.ji=this.$i=e.cookie_expiration,this.set_disabled(e.disable_persistence||!!n),this.set_cross_subdomain(e.cross_subdomain_cookie),this.set_secure(e.secure_cookie);var r=e.persistence!==s.persistence||!((l,u)=>{if(l.length!==u.length)return!1;var c=[...l].sort(),d=[...u].sort();return c.every(((h,p)=>h===d[p]))})(e.cookie_persisted_properties||[],s.cookie_persisted_properties||[]),i=r?this.bi(e):this.ii,o=this.wi(e);if(r||o!==this.pi){var a=this.props;this.clear(),this.ii=i,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,s){var n=this.props[js]||{};n[e]=s,this.Pi(js,n),this.save()}remove_event_timer(e){var s=this.props[js]||{},n=s[e];return x(n)||(delete s[e],this.Pi(js,s),this.save()),n}get_property(e){return this.props[e]}set_property(e,s){this.Pi(e,s),this.save()}Pi(e,s){var n;this.props[e]=s,(n=Mt(e))!=null&&n.volatile||this.Bi(e)}Ri(e){delete this.props[e],this.Bi(e)}Bi(e){var s,n=(s=Mt(e))==null?void 0:s.storageGroup;n&&(this.Mi(n).dirty=!0)}Mi(e){return this.ci[e]||(this.ci[e]={})}}function Cn(t){var e=!0;return{dispose(){if(e){e=!1;var s=t();s&&Se(s.then)&&s.then(void 0,(()=>{}))}}}}var xe={GZipJS:"gzip-js",Base64:"base64"},As={Activation:"events",Cancellation:"cancelEvents"},fi={Popover:"popover",API:"api",Widget:"widget"},ft={SHOWN:"survey shown",DISMISSED:"survey dismissed",SENT:"survey sent"},gi={SURVEY_ID:"$survey_id",SURVEY_ITERATION:"$survey_iteration",SURVEY_LAST_SEEN_DATE:"$survey_last_seen_date"},lo={Popover:"popover",Inline:"inline"},Dp={SHOWN:"product tour shown"},yl={TOUR_LAST_SEEN_DATE:"$product_tour_last_seen_date",TOUR_TYPE:"$product_tour_type"},wl=se("[RateLimiter]");class Bp{constructor(e){this.serverLimits={},this.lastEventRateLimited=!1,this.checkForLimiting=s=>{var n=s.text;if(n&&n.length)try{(JSON.parse(n).quota_limited||[]).forEach((r=>{wl.info((r||"events")+" is quota limited."),this.serverLimits[r]=new Date().getTime()+6e4}))}catch(r){return void wl.warn('could not rate limit - continuing. Error: "'+r?.message+'"',{text:n})}},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 s,n,r;e===void 0&&(e=!1);var i=this.captureEventsBurstLimit,o=this.captureEventsPerSecond,a=new Date().getTime(),l=(s=(n=this.instance.persistence)==null?void 0:n.get_property(to))!==null&&s!==void 0?s:{tokens:i,last:a};l.tokens+=(a-l.last)/1e3*o,l.last=a,l.tokens>i&&(l.tokens=i);var u=1>l.tokens;if(u||e||(l.tokens=Math.max(0,l.tokens-1)),u&&!e){var c=(he(l.dropped)?l.dropped:0)+1;l.dropped=c,!this.lastEventRateLimited&&this.Hi(c)&&(l.dropped=0)}return this.lastEventRateLimited=u,(r=this.instance.persistence)==null||r.set_property(to,l),{isRateLimited:u,remainingTokens:l.tokens}}Ui(e){var s=this.instance.config.property_denylist;return!L(s)||!s.includes(e)}zi(){var e;if(this.Ui("$current_url")&&this.Ui("$pathname")&&ne!=null&&ne.pathname)return""+((e=ne.origin)!==null&&e!==void 0?e:"")+ne.pathname}Hi(e){var s,n,r=this.captureEventsBurstLimit,i=this.captureEventsPerSecond,o=this.zi(),a=this.Ui("$session_id")?(s=(n=this.instance).get_session_id)==null?void 0:s.call(n):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 "+i+" events per second and "+r+" events burst limit."},{skip_client_rate_limiting:!0})}isServerRateLimited(e){var s=this.serverLimits[e||"events"]||!1;return s!==!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 xt.info("Using preloaded remote config",this.remoteConfig),this.Zi(this.remoteConfig),void this.Gi();if(this._instance.Qi())return void xt.warn("Remote config is disabled. Falling back to local config.");this.Wi((e=>{if(!e)return xt.info("No config found after loading remote JS config. Falling back to JSON."),void this.Vi((s=>{this.Zi(s.json,s),this.Gi()}));this.Zi(e),this.Gi()}))}catch(e){xt.error("Error loading remote config",e),this.Zi()}}stop(){this.Ki&&(clearInterval(this.Ki),this.Ki=void 0)}refresh(){!this._instance.Qi()&&C&&C.visibilityState!=="hidden"&&this._instance.reloadFeatureFlags()}Gi(){var e;if(!this.Ki){var s=(e=this._instance.config.remote_config_refresh_interval_ms)!==null&&e!==void 0?e:3e5;s!==0&&(this.Ki=setInterval((()=>{this.refresh()}),s))}}Zi(e,s){!e&&s&&(s.statusCode===0?s.error||xt.warn("Failed to fetch remote config from PostHog."):xt.error("Failed to fetch remote config from PostHog."));try{this._instance.Zi(e?{ok:!0,config:e}:{ok:!1})}catch(r){xt.error("Error applying remote config",r)}if(e?.hasFeatureFlags!==!1&&!this._instance.config.advanced_disable_feature_flags_on_first_load)try{var n;(n=this._instance.featureFlags)==null||n.ensureFlagsLoaded()}catch(r){xt.error("Error loading feature flags",r)}}}var qe=Uint8Array,Ae=Uint16Array,_s=Uint32Array,Qo=new qe([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),ea=new qe([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),bl=new qe([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),qu=function(t,e){for(var s=new Ae(31),n=0;31>n;++n)s[n]=e+=1<n;++n)for(var i=s[n];s[n+1]>i;++i)r[i]=i-s[n]<<5|n;return[s,r]},Vu=qu(Qo,2),co=Vu[1];Vu[0][28]=258,co[258]=28;for(var El=qu(ea,0)[1],Gu=new Ae(32768),ie=0;32768>ie;++ie){var ss=(43690&ie)>>>1|(21845&ie)<<1;Gu[ie]=((65280&(ss=(61680&(ss=(52428&ss)>>>2|(13107&ss)<<2))>>>4|(3855&ss)<<4))>>>8|(255&ss)<<8)>>>1}var Js=function(t,e,s){for(var n=t.length,r=0,i=new Ae(e);n>r;++r)++i[t[r]-1];var o,a=new Ae(e);for(r=0;e>r;++r)a[r]=a[r-1]+i[r-1]<<1;for(o=new Ae(n),r=0;n>r;++r)o[r]=Gu[a[t[r]-1]++]>>>15-t[r];return o},Kt=new qe(288);for(ie=0;144>ie;++ie)Kt[ie]=8;for(ie=144;256>ie;++ie)Kt[ie]=9;for(ie=256;280>ie;++ie)Kt[ie]=7;for(ie=280;288>ie;++ie)Kt[ie]=8;var pr=new qe(32);for(ie=0;32>ie;++ie)pr[ie]=5;var jp=Js(Kt,9),Up=Js(pr,5),Ku=function(t){return(t/8>>0)+(7&t&&1)},Ju=function(t,e,s){(s==null||s>t.length)&&(s=t.length);var n=new(t instanceof Ae?Ae:t instanceof _s?_s:qe)(s-e);return n.set(t.subarray(e,s)),n},ot=function(t,e,s){var n=e/8>>0;t[n]|=s<<=7&e,t[n+1]|=s>>>8},$s=function(t,e,s){var n=e/8>>0;t[n]|=s<<=7&e,t[n+1]|=s>>>8,t[n+2]|=s>>>16},mi=function(t,e){for(var s=[],n=0;t.length>n;++n)t[n]&&s.push({s:n,f:t[n]});var r=s.length,i=s.slice();if(!r)return[new qe(0),0];if(r==1){var o=new qe(s[0].s+1);return o[s[0].s]=1,[o,1]}s.sort((function(F,P){return F.f-P.f})),s.push({s:-1,f:25001});var a=s[0],l=s[1],u=0,c=1,d=2;for(s[0]={s:-1,f:a.f+l.f,l:a,r:l};c!=r-1;)a=s[s[d].f>s[u].f?u++:d++],l=s[u!=c&&s[d].f>s[u].f?u++:d++],s[c++]={s:-1,f:a.f+l.f,l:a,r:l};var h=i[0].s;for(n=1;r>n;++n)i[n].s>h&&(h=i[n].s);var p=new Ae(h+1),f=uo(s[c-1],p,0);if(f>e){n=0;var g=0,m=f-e,_=1<n;++n){var w=i[n].s;if(e>=p[w])break;g+=_-(1<>>=m;g>0;){var E=i[n].s;e>p[E]?g-=1<=0&&g;--n){var I=i[n].s;p[I]==e&&(--p[I],++g)}f=e}return[new qe(p),f]},uo=function(t,e,s){return t.s==-1?Math.max(uo(t.l,e,s+1),uo(t.r,e,s+1)):e[t.s]=s},Sl=function(t){for(var e=t.length;e&&!t[--e];);for(var s=new Ae(++e),n=0,r=t[0],i=1,o=function(l){s[n++]=l},a=1;e>=a;++a)if(t[a]==r&&a!=e)++i;else{if(!r&&i>2){for(;i>138;i-=138)o(32754);i>2&&(o(i>10?i-11<<5|28690:i-3<<5|12305),i=0)}else if(i>3){for(o(r),--i;i>6;i-=6)o(8304);i>2&&(o(i-3<<5|8208),i=0)}for(;i--;)o(r);i=1,r=t[a]}return[s.subarray(0,n),e]},Rs=function(t,e){for(var s=0,n=0;e.length>n;++n)s+=t[n]*e[n];return s},ho=function(t,e,s){var n=s.length,r=Ku(e+2);t[r]=255&n,t[r+1]=n>>>8,t[r+2]=255^t[r],t[r+3]=255^t[r+1];for(var i=0;n>i;++i)t[r+i+4]=s[i];return 8*(r+4+n)},xl=function(t,e,s,n,r,i,o,a,l,u,c){ot(e,c++,s),++r[256];for(var d=mi(r,15),h=d[0],p=d[1],f=mi(i,15),g=f[0],m=f[1],_=Sl(h),w=_[0],E=_[1],I=Sl(g),F=I[0],P=I[1],B=new Ae(19),S=0;w.length>S;++S)B[31&w[S]]++;for(S=0;F.length>S;++S)B[31&F[S]]++;for(var A=mi(B,7),R=A[0],N=A[1],T=19;T>4&&!R[bl[T-1]];--T);var O,J,z,H,oe=u+5<<3,pe=Rs(r,Kt)+Rs(i,pr)+o,Ie=Rs(r,h)+Rs(i,g)+o+14+3*T+Rs(B,R)+(2*B[16]+3*B[17]+7*B[18]);if(pe>=oe&&Ie>=oe)return ho(e,c,t.subarray(l,l+u));if(ot(e,c,1+(pe>Ie)),c+=2,pe>Ie){O=Js(h,p),J=h,z=Js(g,m),H=g;var _e=Js(R,N);for(ot(e,c,E-257),ot(e,c+5,P-1),ot(e,c+10,T-4),c+=14,S=0;T>S;++S)ot(e,c+3*S,R[bl[S]]);c+=3*T;for(var Ce=[w,F],Re=0;2>Re;++Re){var ae=Ce[Re];for(S=0;ae.length>S;++S)ot(e,c,_e[me=31&ae[S]]),c+=R[me],me>15&&(ot(e,c,ae[S]>>>5&127),c+=ae[S]>>>12)}}else O=jp,J=Kt,z=Up,H=pr;for(S=0;a>S;++S)if(n[S]>255){var me;$s(e,c,O[257+(me=n[S]>>>18&31)]),c+=J[me+257],me>7&&(ot(e,c,n[S]>>>23&31),c+=Qo[me]);var ge=31&n[S];$s(e,c,z[ge]),c+=H[ge],ge>3&&($s(e,c,n[S]>>>5&8191),c+=ea[ge])}else $s(e,c,O[n[S]]),c+=J[n[S]];return $s(e,c,O[256]),c+J[256]},Hp=new _s([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),Wp=(function(){for(var t=new _s(256),e=0;256>e;++e){for(var s=e,n=9;--n;)s=(1&s&&3988292384)^s>>>1;t[e]=s}return t})(),vi=function(t,e,s){for(;s;++e)t[e]=s,s>>>=8};function zp(t,e){e===void 0&&(e={});var s=(function(){var d=4294967295;return{p(h){for(var p=d,f=0;h.length>f;++f)p=Wp[255&p^h[f]]^p>>>8;d=p},d(){return 4294967295^d}}})(),n=t.length;s.p(t);var r,i,o,a,l,u=(a=10+((r=e).filename&&r.filename.length+1||0),l=8,(function(d,h,p,f,g,m){var _=d.length,w=new qe(f+_+5*(1+Math.floor(_/7e3))+g),E=w.subarray(f,w.length-g),I=0;if(!h||8>_)for(var F=0;_>=F;F+=65535){var P=F+65535;_>P?I=ho(E,I,d.subarray(F,P)):(E[F]=!0,I=ho(E,I,d.subarray(F,_)))}else{for(var B=Hp[h-1],S=B>>>13,A=8191&B,R=(1<F;++F){var me=z(F),ge=32767&F,Ye=T[me];if(N[ge]=Ye,T[me]=ge,F>=Re){var Rt=_-F;if((Ie>7e3||Ce>24576)&&Rt>423){I=xl(d,E,0,H,oe,pe,_e,Ce,ae,F-ae,I),Ce=Ie=_e=0,ae=F;for(var de=0;286>de;++de)oe[de]=0;for(de=0;30>de;++de)pe[de]=0}var Ve=2,St=0,ks=A,Be=ge-Ye&32767;if(Rt>2&&me==z(F-Be))for(var Fe=Math.min(S,Rt)-1,vn=Math.min(32767,F),_n=Math.min(258,Rt);vn>=Be&&--ks&&ge!=Ye;){if(d[F+Ve]==d[F+Ve-Be]){for(var je=0;_n>je&&d[F+je]==d[F+je-Be];++je);if(je>Ve){if(Ve=je,St=Be,je>Fe)break;var yn=Math.min(Be,je-2),Xt=0;for(de=0;yn>de;++de){var Qt=F-Be+de+32768&32767,Is=Qt-N[Qt]+32768&32767;Is>Xt&&(Xt=Is,Ye=Qt)}}}Be+=(ge=Ye)-(Ye=N[ge])+32768&32767}if(St){H[Ce++]=268435456|co[Ve]<<18|El[St];var La=31&co[Ve],Oa=31&El[St];_e+=Qo[La]+ea[Oa],++oe[257+La],++pe[Oa],Re=F+Ve,++Ie}else H[Ce++]=d[F],++oe[d[F]]}}I=xl(d,E,!0,H,oe,pe,_e,Ce,ae,F-ae,I)}return Ju(w,0,f+Ku(I)+g)})(i=t,(o=e).level==null?6:o.level,o.mem==null?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(i.length)))):12+o.mem,a,l)),c=u.length;return(function(d,h){var p=h.filename;if(d[0]=31,d[1]=139,d[2]=8,d[8]=2>h.level?4:h.level==9?2:0,d[9]=3,h.mtime!=0&&vi(d,4,Math.floor(new Date(h.mtime||Date.now())/1e3)),p){d[3]=8;for(var f=0;p.length>=f;++f)d[f+10]=p.charCodeAt(f)}})(u,e),vi(u,c-8,s.d()),vi(u,c-4,n),u}var qp=!!Ni||!!Do,Yu="text/plain",Bn=!1,Zu=(t,e)=>{var s=t.split("#"),n=s[1],r=s[0].split("?"),i=r[0],o=r[1];if(!o)return t;var a=o.split("&").filter((l=>l.split("=")[0]!==e)).join("&");return i+(a?"?"+a:"")+(n?"#"+n:"")},Rr=function(t,e,s){var n;s===void 0&&(s=!0);var r=t.split("?"),i=r[0],o=r[1],a=b({},e),l=(n=o?.split("&").map((c=>{var d,h=c.split("="),p=h[0],f=s&&(d=a[p])!==null&&d!==void 0?d:h[1];return delete a[p],p+"="+f})))!==null&&n!==void 0?n:[],u=(function(c,d){var h,p;d===void 0&&(d="&");var f=[];return Z(c,(function(g,m){x(g)||x(m)||m==="undefined"||(h=encodeURIComponent((_=>_ instanceof File)(g)?g.name:g.toString()),p=encodeURIComponent(m),f[f.length]=p+"="+h)})),f.join(d)})(a);return u&&l.push(u),l.length>0?i+"?"+l.join("&"):i},_i=t=>{if(t.Ji)return t.Ji;var e=t.data,s=t.compression;if(e){if(s===xe.GZipJS){var n=zp((function(a,l){var u=a.length;if(typeof TextEncoder<"u")return new TextEncoder().encode(a);for(var c=new qe(a.length+(a.length>>>1)),d=0,h=function(m){c[d++]=m},p=0;u>p;++p){if(d+5>c.length){var f=new qe(d+8+(u-p<<1));f.set(c),c=f}var g=a.charCodeAt(p);128>g?h(g):2048>g?(h(192|g>>>6),h(128|63&g)):g>55295&&57344>g?(h(240|(g=65536+(1047552&g)|1023&a.charCodeAt(++p))>>>18),h(128|g>>>12&63),h(128|g>>>6&63),h(128|63&g)):(h(224|g>>>12),h(128|g>>>6&63),h(128|63&g))}return Ju(c,0,d)})(cs(e)),{mtime:0});return{contentType:Yu,body:n.buffer.slice(n.byteOffset,n.byteOffset+n.byteLength),estimatedSize:n.byteLength}}if(s===xe.Base64){var r=(function(a){return a&&btoa(encodeURIComponent(a).replace(/%([0-9A-F]{2})/g,((l,u)=>String.fromCharCode(parseInt(u,16)))))})(cs(e)),i=(a=>"data="+encodeURIComponent(typeof a=="string"?a:cs(a)))(r);return{contentType:"application/x-www-form-urlencoded",body:i,estimatedSize:new Blob([i]).size}}var o=cs(e);return{contentType:"application/json",body:o,estimatedSize:new Blob([o]).size}}},Xu=t=>{var e,s,n=()=>t.transport==="sendBeacon"?{url:Rr(t.url,{compression:xe.Base64}),encodedBody:_i(b({},t,{compression:xe.Base64,Ji:void 0}))}:{url:Zu(t.url,"compression"),encodedBody:_i(b({},t,{compression:void 0,Ji:void 0}))};try{e=_i(t)}catch(r){if(za(t.compression,ms(t.url,"compression")))return k.error("Failed to gzip request body, sending uncompressed payload",r),n();throw r}return e&&za(t.compression,ms(t.url,"compression"))&&!((s=e.body)instanceof ArrayBuffer?Mi(new Uint8Array(s)):ArrayBuffer.isView(s)&&Mi(new Uint8Array(s.buffer,s.byteOffset,s.byteLength)))?(Bn=!0,n()):{url:t.url,encodedBody:e}},Qu=t=>{try{return Xu(t)}catch(e){return k.error(e),void(t.callback==null||t.callback({statusCode:0,error:e}))}},Vp=(function(){var t=X((function*(e){var s=cs(e.data),n=yield(function(i,o,a){return Li.apply(this,arguments)})(s,Y.DEBUG,{rethrow:!0});if(!n)return e;var r=yield n.arrayBuffer();return b({},e,{Ji:{contentType:Yu,body:r,estimatedSize:r.byteLength}})}));return function(e){return t.apply(this,arguments)}})(),Gp=/Failed to fetch|NetworkError|Load failed/i,ed=t=>t?.name==="TypeError"&&Gp.test(t?.message||""),td=t=>{var e=Qu(t);if(e){var s=e.url,n=e.encodedBody,r=n??{},i=r.contentType,o=r.body,a=r.estimatedSize,l=new Headers;Z(t.headers,(function(f,g){l.append(g,f)})),i&&l.append("Content-Type",i);var u=null,c=!1;if(Da){var d=new Da;u={signal:d.signal,timeout:setTimeout((()=>{var f,g;c=!0,d.abort((f=t.timeout,(g=new Error("PostHog request timed out"+(f?" after "+f+"ms":""))).name="AbortError",g))}),t.timeout)}}var h=f=>{c&&f?.name==="AbortError"||ed(f)?k.warn(f):k.error(f),t.callback==null||t.callback({statusCode:0,error:f})};try{var p;Do(s,b({method:t?.method||"GET",headers:l,keepalive:t.method==="POST"&&!t.Yi&&52428.8>(a||0),body:o,signal:(p=u)==null?void 0:p.signal},t.fetchOptions)).then((f=>f.text().then((g=>{var m={statusCode:f.status,text:g};if(f.status===200)try{m.json=JSON.parse(g)}catch(_){k.error(_)}t.callback==null||t.callback(m)})))).catch(h).finally((()=>u?clearTimeout(u.timeout):null))}catch(f){u&&clearTimeout(u.timeout),h(f)}}},po=t=>{try{var e,s=Xu(t),n=s.url,r=s.encodedBody,i=r??{},o=i.body,a=i.estimatedSize;if(!o)return;var l=o instanceof Blob?o:new Blob([o],{type:i.contentType});if(ke.sendBeacon(n,l))return;var u=L(t.data)?t.data:(e=t.data)==null?void 0:e.batch;if(L(u)&&u.length>1&&(a??0)>16384){var c=Math.ceil(u.length/2),d=h=>L(t.data)?h:b({},t.data,{batch:h});return po(b({},t,{data:d(u.slice(0,c))})),void po(b({},t,{data:d(u.slice(c))}))}k.warn("Beacon of ~"+(a??0)+" bytes was rejected by the browser, falling back to fetch"),td(b({},t,{Yi:!0}))}catch(h){k.warn("Beacon send failed",h)}},kl=(t,e,s,n)=>{var r=n==="query"?e==="POST"?"sent_at":"_":void 0;return Rr(s===xe.GZipJS?Zu(t,"compression"):t,b({},r?{[r]:Date.now().toString()}:{},s===xe.GZipJS?{}:{compression:s}))},jn=[];Do&&jn.push({transport:"fetch",method:td}),Ni&&jn.push({transport:"XHR",method(t){var e=Qu(t);if(e){var s=new Ni,n=e.encodedBody;s.open(t.method||"GET",e.url,!0);var r=n??{},i=r.contentType,o=r.body;Z(t.headers,(function(a,l){s.setRequestHeader(l,a)})),i&&s.setRequestHeader("Content-Type",i),t.timeout&&(s.timeout=t.timeout),s.onreadystatechange=()=>{if(s.readyState===4){var a={statusCode:s.status,text:s.responseText};if(s.status===200)try{a.json=JSON.parse(s.responseText)}catch{}t.callback==null||t.callback(a)}},s.send(o)}}}),ke!=null&&ke.sendBeacon&&jn.push({transport:"sendBeacon",method:po});var fo=3e3;class Kp{constructor(e,s){this.Xi=!0,this.tr=[],this.er=nt(s?.flush_interval_ms||fo,250,5e3,k.createLogger("flush interval"),fo),this.ir=e}enqueue(e){this.tr.push(e),this.rr||this.nr()}unload(){this.sr();var e=this.tr.length>0?this.ar():{},s=Object.values(e);[...s.filter((n=>n.url.indexOf("/e")===0)),...s.filter((n=>n.url.indexOf("/e")!==0))].map((n=>{this.lr(b({},n,{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 s=this.ar(),n=function(){var i=s[r],o=new Date().getTime();i.data&&L(i.data)&&Z(i.data,(a=>{a.offset=Math.abs(a.timestamp-o),delete a.timestamp})),e.lr(i)};for(var r in s)n()}}),this.er))}lr(e){try{this.ir(e)}catch(s){k.error(s)}}sr(){clearTimeout(this.rr),this.rr=void 0}ar(){var e={};return Z(this.tr,(s=>{var n,r=s,i=(r?r.batchKey:null)||r.url;x(e[i])&&(e[i]=b({},r,{data:[]})),(n=e[i].data)==null||n.push(r.data)})),this.tr=[],e}}var Jp=["retriesPerformedSoFar"];class Yp{constructor(e){this.ur=!1,this.hr=3e3,this.tr=[],this._instance=e,this.tr=[],this.dr=!0,!x(v)&&"onLine"in v.navigator&&(this.dr=v.navigator.onLine,this.vr=()=>{this.dr=!0,this.cr()},this.pr=()=>{this.dr=!1},re(v,"online",this.vr),re(v,"offline",this.pr))}get length(){return this.tr.length}retriableRequest(e){var s=e.retriesPerformedSoFar,n=Pc(e,Jp);lt(s)&&(n.url=Rr(n.url,{retry_count:s})),this._instance._send_request(b({},n,{callback:r=>{if(r.statusCode!==200&&(400>r.statusCode||r.statusCode>=500)){if((r.statusCode===0?3:10)>(s??0))return void this.At(b({retriesPerformedSoFar:s},n));r.statusCode===0&&k.warn("Request failed before receiving an HTTP response; this can happen due to network issues, CORS, browser blocking, or ad blockers. Stopped retrying after "+(s??0)+" retries.")}n.callback==null||n.callback(r)}}))}At(e){var s=e.retriesPerformedSoFar||0;e.retriesPerformedSoFar=s+1;var n=(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))})(s),r=Date.now()+n;this.tr.push({retryAt:r,requestOptions:e});var i="Enqueued failed request for retry in "+n;navigator.onLine||(i+=" (Browser is offline)"),k.warn(i),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(),s=[],n=this.tr.filter((i=>e>i.retryAt||(s.push(i),!1)));if(this.tr=s,n.length>0)for(var r of n)this.retriableRequest(r.requestOptions)}unload(){for(var e of(this.mr&&(clearTimeout(this.mr),this.mr=void 0),this.ur=!1,x(v)||(this.vr&&(v.removeEventListener("online",this.vr),this.vr=void 0),this.pr&&(v.removeEventListener("offline",this.pr),this.pr=void 0)),this.tr)){var s=e.requestOptions;try{this._instance._send_request(b({},s,{transport:"sendBeacon"}))}catch(n){k.error(n)}}this.tr=[]}}class Zp{constructor(e){this.yr=()=>{var s,n,r,i;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,(s=this.br.maxScrollY)!==null&&s!==void 0?s:0),this.br.maxScrollHeight=Math.max(l,(n=this.br.maxScrollHeight)!==null&&n!==void 0?n: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,(i=this.br.maxContentHeight)!==null&&i!==void 0?i:0)},this._instance=e}get _r(){return this._instance.config.scroll_root_selector}getContext(){return this.br}resetContext(){var e=this.br;return setTimeout(this.yr,0),e}startMeasuringScrollPosition(){re(v,"scroll",this.yr,{capture:!0}),re(v,"scrollend",this.yr,{capture:!0}),re(v,"resize",this.yr)}scrollElement(){if(!this._r)return v?.document.documentElement;var e=L(this._r)?this._r:[this._r];for(var s of e){var n=v?.document.querySelector(s);if(n)return n}}wr(e){var s=e==="y"?"scrollTop":"scrollLeft";if(this._r){var n=this.scrollElement();return n&&n[s]||0}return v?e==="y"?v.scrollY||v.pageYOffset||v.document.documentElement.scrollTop||0:v.scrollX||v.pageXOffset||v.document.documentElement.scrollLeft||0:0}scrollY(){return this.wr("y")}scrollX(){return this.wr("x")}}var Xp=t=>Uu(t?.config.mask_personal_data_properties,t?.config.custom_personal_data_properties,t?.config.disable_capture_url_hashes);class Il{constructor(e,s,n,r){this.kr=i=>{var o=this.Sr();if(!o||o.sessionId!==i){var a={sessionId:i,props:this.Cr(this._instance)};this.Mr.register({[eo]:a})}},this._instance=e,this.Tr=s,this.Mr=n,this.Cr=r||Xp,this.Tr.onSessionId(this.kr)}Sr(){return this.Mr.props[eo]}getSetOnceProps(){var e,s=(e=this.Sr())==null?void 0:e.props;return s?"r"in s?Hu(s,this._instance.config.disable_capture_url_hashes):{$referring_domain:s.referringDomain,$pathname:s.initialPathName,utm_source:s.utm_source,utm_campaign:s.utm_campaign,utm_medium:s.utm_medium,utm_content:s.utm_content,utm_term:s.utm_term}:{}}getSessionProps(){var e={};return Z(Jo(this.getSetOnceProps()),((s,n)=>{n==="$current_url"&&(n="url"),e["$session_entry_"+Oi(n)]=s})),e}}class ta{on(e,s){return this.Er[e]||(this.Er[e]=[]),this.Er[e].push(s),()=>{this.Er[e]=this.Er[e].filter((n=>n!==s))}}emit(e,s){for(var n of this.Er[e]||[])n(s);for(var r of this.Er["*"]||[])r(e,s)}constructor(){this.Er={}}}var Ts=se("[SessionId]");class Cl{on(e,s){return this.Ir.on(e,s)}constructor(e,s,n){var r;if(this.Pr=null,this.Rr=[],this.Ar=void 0,this.Fr=!1,this.Ir=new ta,this.Lr=(u,c)=>!(!lt(u)||!lt(c))&&Math.abs(u-c)>this.sessionTimeoutMs,!e.persistence)throw new Error("SessionIdManager requires a PostHogPersistence instance");if(e.config.cookieless_mode===ht)throw new Error('SessionIdManager cannot be used with cookieless_mode="always"');this.Ne=e.config,this.Mr=e.persistence,this.Or=void 0,this.Dr=void 0,this._sessionStartTimestamp=null,this._sessionActivityTimestamp=null,this.$r=s||dt,this.Nr=n||dt;var i=this.Ne.persistence_name||this.Ne.token;if(this._sessionTimeoutMs=1e3*nt(this.Ne.session_idle_timeout_seconds||1800,60,36e3,Ts.createLogger("session_idle_timeout_seconds"),1800),e.register({$configured_session_timeout_ms:this._sessionTimeoutMs}),this.qr(),this.jr="ph_"+i+"_window_id",this.Br="ph_"+i+"_primary_window_exists",this.Hr()){var o=ce.H(this.jr),a=ce.H(this.Br);o&&!a?this.Or=o:ce.q(this.jr),ce.F(this.Br,!0)}if((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){Ts.error("Invalid sessionID in bootstrap",u)}this.zr()}get sessionTimeoutMs(){return this._sessionTimeoutMs}onSessionId(e){return x(this.Rr)&&(this.Rr=[]),this.Rr.push(e),this.Dr&&e(this.Dr,this.Or),()=>{this.Rr=this.Rr.filter((s=>s!==e))}}Hr(){return this.Ne.persistence!=="memory"&&!this.Mr.xi&&ce.N()}Wr(e){e!==this.Or&&(this.Or=e,this.Hr()&&ce.F(this.jr,e))}Vr(){return this.Or?this.Or:this.Hr()?ce.H(this.jr):null}Zr(e){var s=this.Pr;return!$e(s)&&!$e(e)&&5e3>Math.abs(e-s)}Ur(e,s,n){var r=s!==this._sessionActivityTimestamp,i=!(e!==this.Dr||n!==this._sessionStartTimestamp);this._sessionStartTimestamp=n,this._sessionActivityTimestamp=s,this.Dr=e,i&&!r||i&&this.Zr(s)||(this.Pr=s,this.Mr.register({[ls]:[s,e,n]}))}Gr(){var e,s=(e=this.Ne)==null?void 0:e.persistence_save_debounce_ms;return lt(s)&&s>0}Qr(){this.Gr()?this.Mr.refreshKey(ls):(this.Mr.flush(),this.Mr.load())}Kr(){var e;if(!$e(this._sessionActivityTimestamp)&&this._sessionActivityTimestamp!==this.Pr){this.Qr();var s=this.Jr();s[1]===this.Dr&&s[2]===this._sessionStartTimestamp&&(this.Pr=this._sessionActivityTimestamp,this.Mr.register({[ls]:[this._sessionActivityTimestamp,(e=this.Dr)!==null&&e!==void 0?e:null,this._sessionStartTimestamp]}),this.Mr.flush())}}Yr(){var e=this.Jr()[0],s=lt(e)?e:0,n=lt(this._sessionActivityTimestamp)?this._sessionActivityTimestamp:0;return Math.max(s,n)}Xr(e){return this.Qr(),this.Lr(e,this.Yr())}Jr(){var e=this.Mr.props[ls];return L(e)&&e.length===2&&e.push(e[0]),e||[0,null,0]}resetSessionId(){this.Pr=null,clearTimeout(this.tn),this.tn=void 0,this.Ur(null,null,null)}destroy(){this.Fr=!0,this.Kr(),clearTimeout(this.tn),this.tn=void 0,this.Ar&&v&&(v.removeEventListener(ar,this.Ar,{capture:!1}),this.Ar=void 0),this.Rr=[]}zr(){this.Ar=()=>{this.Kr(),this.Hr()&&ce.q(this.Br)},re(v,ar,this.Ar,{capture:!1})}checkAndGetSessionAndWindowId(e,s){if(e===void 0&&(e=!1),s===void 0&&(s=null),this.Ne.cookieless_mode===ht)throw new Error('checkAndGetSessionAndWindowId should not be called with cookieless_mode="always"');var n=s||new Date().getTime(),r=this.Jr(),i=r[1],o=r[2],a=this.Yr(),l=this.Vr(),u=lt(o)&&Math.abs(n-o)>864e5,c=!1,d=!1,h=!i,p=i,f=!h&&!e&&this.Lr(n,a);if(f){(f=this.Xr(n))||Ts.info("cross-tab refresh kept the session alive",{sessionId:i});var g=this.Jr();i=g[1],o=g[2]}h||f||u?(i=this.$r(),l=this.Nr(),Ts.info("new session ID generated",{sessionId:i,windowId:l,changeReason:{noSessionId:h,activityTimeout:f,sessionPastMaximumLength:u}}),o=n,c=!0):(l||(l=this.Nr(),c=!0),(d=i!==p)&&(Ts.info("adopted cross-tab session id",{sessionId:i,windowId:l}),c=!0));var m=lt(a)&&e&&!u?a:n,_=lt(o)?o:new Date().getTime();this.Wr(l),this.Ur(i,m,_),e||this.qr();var w={noSessionId:h,activityTimeout:f,sessionPastMaximumLength:u,crossTabAdoption:d};return c&&this.Rr.forEach((E=>E(i,l,w))),{sessionId:i,windowId:l,sessionStartTimestamp:_,changeReason:c?w:void 0,lastActivityTimestamp:a}}qr(){this.Fr||(clearTimeout(this.tn),this.tn=setTimeout((()=>{if(!this.Fr)if(this.Xr(new Date().getTime())){var e=this.Dr;this.resetSessionId(),this.Ir.emit("forcedIdleReset",{idleSessionId:e})}else this.qr()}),1.1*this.sessionTimeoutMs))}}var sd=function(t,e){if(!t)return!1;var s=t.userAgent;if(s&&Va(s,e))return!0;try{var n=t?.userAgentData;if(n!=null&&n.brands&&n.brands.some((r=>Va(r?.brand,e))))return!0}catch{}return!!t.webdriver};function nd(){return(nd=X((function*(){var t=ke?.userAgentData;if(t!=null&&t.getHighEntropyValues)try{var e=yield t.getHighEntropyValues(["model"]),s=e?.model;return W(s)&&s.length>0?s:void 0}catch(n){return void k.info("Unable to resolve $device_model from userAgentData.getHighEntropyValues",n)}}))).apply(this,arguments)}var fr=function(t,e){if(!(function(s){try{new RegExp(s)}catch{return!1}return!0})(e))return!1;try{return new RegExp(e).test(t)}catch{return!1}};function yi(t,e,s){return cs({distinct_id:t,userPropertiesToSet:e,userPropertiesToSetOnce:s})}var rd={exact:(t,e)=>e.some((s=>t.some((n=>s===n)))),is_not:(t,e)=>e.every((s=>t.every((n=>s!==n)))),regex:(t,e)=>e.some((s=>t.some((n=>fr(s,n))))),not_regex:(t,e)=>e.every((s=>t.every((n=>!fr(s,n))))),icontains:(t,e)=>e.map(Fn).some((s=>t.map(Fn).some((n=>s.includes(n))))),not_icontains:(t,e)=>e.map(Fn).every((s=>t.map(Fn).every((n=>!s.includes(n))))),gt:(t,e)=>e.some((s=>{var n=parseFloat(s);return!isNaN(n)&&t.some((r=>n>parseFloat(r)))})),lt:(t,e)=>e.some((s=>{var n=parseFloat(s);return!isNaN(n)&&t.some((r=>nt.toLowerCase();function id(t,e){return!t||Object.entries(t).every((s=>{var n=s[1],r=e?.[s[0]];if(x(r)||$e(r))return!1;var i=[String(r)],o=rd[n.operator];return!!o&&o(n.values,i)}))}var go="custom",Fl="i.posthog.com",Qp=/^\/static\//;class ef{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,s=(e=this.instance.config.ui_host)==null?void 0:e.replace(/\/$/,"");return s||(s=this.apiHost.replace("."+Fl,".posthog.com")),s==="https://app.posthog.com"?"https://us.posthog.com":s}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":go),this.en[this.apiHost]}rn(e){if(Qp.test(e)){var s=this.instance.config.asset_host;if(typeof s=="string")return s.trim().replace(/\/$/,"")||void 0}}endpointFor(e,s){if(s===void 0&&(s=""),s&&(s=s[0]==="/"?s:"/"+s),e==="ui")return this.uiHost+s;if(e==="flags")return this.flagsApiHost+s;if(e==="assets"){var n=this.rn(s);if(n)return""+n+s}if(this.region===go)return this.apiHost+s;var r=Fl+s;switch(e){case"assets":return"https://"+this.region+"-assets."+r;case"api":return"https://"+this.region+"."+r}}}function od(t){var e;return!((e=t.conditions)==null||(e=e.events)==null||(e=e.values)==null||!e.length)}var q=se("[Surveys]"),ad="seenSurvey_",ld=t=>{try{var e=(s=>((n,r)=>""+ad+(function(i){return i.current_iteration&&i.current_iteration>0?i.id+"_"+i.current_iteration:i.id})(r))(0,s))(t);if(localStorage.getItem(e))return;localStorage.setItem(e,"true")}catch(s){q.error("Failed to persist survey seen state",s)}},tf=[fi.Popover,fi.Widget,fi.API],sf={ignoreConditions:!1,ignoreDelay:!1,displayType:lo.Popover},nf=se("[PostHog ExternalIntegrations]"),rf={intercom:"intercom-integration",crispChat:"crisp-chat-integration"};class of{constructor(e){this._instance=e}ai(e,s){var n;(n=$.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,e,(r=>{if(r)return nf.error("failed to load script",r);s()}))}startIfEnabledOrStop(){var e=this,s=function(){var i,o,a,l=n[0],u=n[1];!u||(i=$.__PosthogExtensions__)!=null&&(i=i.integrations)!=null&&i[l]||e.ai(rf[l],(()=>{var c;(c=$.__PosthogExtensions__)==null||(c=c.integrations)==null||(c=c[l])==null||c.start(e._instance)})),!u&&(o=$.__PosthogExtensions__)!=null&&(o=o.integrations)!=null&&o[l]&&((a=$.__PosthogExtensions__)==null||(a=a.integrations)==null||(a=a[l])==null||a.stop())};for(var n of Object.entries((r=this._instance.config.integrations)!==null&&r!==void 0?r:{})){var r;s()}}}class af{constructor(e,s){this.rt=e,this.nn=s,this.sn=new Map,this.an=!1}add(e){var s=this;return X((function*(){if(s.an)throw new Error("Cannot add an extension to a disposed ExtensionRuntime");if(s.sn.has(e.name))throw new Error('Browser extension "'+e.name+'" is already registered');s.sn.set(e.name,e);try{var n=e.setup(s.nn);n&&(yield n)}catch(i){var r=s.sn.get(e.name)===e;r&&s.sn.delete(e.name),s.rt.error('Failed to set up browser extension "'+e.name+'"',i),r&&s.ln(e)}}))()}dispose(){if(!this.an){this.an=!0;var e=Array.from(this.sn.values()).reverse();for(var s of(this.sn.clear(),e))this.ln(s)}}ln(e){try{var s=e.dispose==null?void 0:e.dispose();s&&Se(s.then)&&s.then(void 0,(n=>{this.rt.error('Failed to dispose browser extension "'+e.name+'"',n)}))}catch(n){this.rt.error('Failed to dispose browser extension "'+e.name+'"',n)}}}class lf{constructor(e){this._instance=e}initialize(){}get(e){var s=this._instance.persistence;if(typeof e=="string")return s?.get_property(e);var n={};for(var r of e){var i=s?.get_property(r);x(i)||(n[r]=i)}return n}set(e,s){var n;(n=this._instance.persistence)==null||n.register(typeof e=="string"?{[e]:s}:e)}remove(e){var s;(s=this._instance.persistence)==null||s.unregister(e)}}var Pl="extensionsRemoteConfig";class cf{constructor(e){this.an=!1,this.instance=e,this.rt=k,this.un=e.hn,this.kv=new lf(e),this.onEvent=s=>Cn(this.instance.on("eventCaptured",(n=>{try{s({event:n.event,properties:n.properties})}catch(r){this.rt.error("Browser extension event listener failed",r)}}))),this.onRemoteConfig=s=>{if(this.an)return Cn((()=>{}));var n=i=>{try{s(i)}catch(o){this.rt.error("Browser extension remote config listener failed",o)}},r=this.instance.dn.on(Pl,n);return this.un&&n(this.un),Cn(r)},this.vn=new af(k.createLogger("[BrowserExtensions]"),this)}get logger(){return this.rt}get distinctId(){return this.instance.get_distinct_id()}get anonymousId(){var e;return(e=this.instance.get_property(sn))!==null&&e!==void 0?e:this.distinctId}get deviceId(){var e=this.instance.get_property(sn);return typeof e=="string"?e:void 0}get library(){return{name:Y.LIB_NAME,version:Y.LIB_VERSION}}get initialPersonProperties(){var e,s;return(e=(s=this.instance.persistence)==null?void 0:s.get_initial_props())!==null&&e!==void 0?e:{}}get groups(){return this.instance.getGroups()}get session(){try{var e,s,n,r,i=(e=this.instance.sessionManager)==null?void 0:e.checkAndGetSessionAndWindowId(!0);return{sessionId:(s=i?.sessionId)!==null&&s!==void 0?s:"",windowId:(n=i?.windowId)!==null&&n!==void 0?n:"",sessionStartTimestamp:(r=i?.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,s,n){var r=this;return X((function*(){n?r.instance.capture(e,s,{timestamp:n.timestamp,uuid:n.uuid,$set:n.set,$set_once:n.setOnce}):r.instance.capture(e,s)}))()}registerDynamicEventProperties(e){return Cn(this.instance.cn(e))}handleRemoteConfig(e){this.an||(this.un=e,this.instance.dn.emit(Pl,e))}sendRequest(e,s){var n=this;return X((function*(){var r;s===void 0&&(s={});var i=n.instance.requestRouter.endpointFor((r=s.target)!==null&&r!==void 0?r:"api",e),o={method:s.method,url:s.query?Rr(i,s.query):i,data:s.body,headers:s.headers,timeout:s.timeoutMs,fireCallbackOnDrop:!0,transport:s.transport,compression:s.compression,timestampMode:s.sentAt};return s.transport==="sendBeacon"?(n.instance._send_request(o),{statusCode:202}):new Promise((a=>{o.callback=a,n.instance._send_request(o)}))}))()}dispose(){this.an||(this.an=!0,this.vn.dispose())}}var Ys={},wi=0,gr=()=>{},Al='Consent opt in/out is not valid with cookieless_mode="always" and will be ignored',Ns="Surveys module not available",$l="sanitize_properties is deprecated. Use before_send instead",cd="Invalid value for property_denylist config: ",uf=["token","distinct_id",mu],os="posthog",ud=!qp&&Pe?.indexOf("MSIE")===-1&&Pe?.indexOf("Mozilla")===-1,bi=t=>{var e;return b({api_host:"https://us.i.posthog.com",flags_api_host:null,ui_host:null,asset_host:null,token:"",autocapture:!0,cross_subdomain_cookie:up(C?.location),persistence:"localStorage+cookie",persistence_name:"",cookie_persisted_properties:[],loaded:gr,save_campaign_params:!0,custom_campaign_params:[],custom_blocked_useragents:[],save_referrer:!0,capture_pageleave:"if_capture_pageview",defaults:t??"unset",__preview_deferred_init_extensions:!1,__preview_external_dependency_versioned_paths:!1,__preview_cookie_wins_on_conflict:!1,debug:ne&&W(ne?.search)&&ne.search.indexOf("__posthog_debug=true")!==-1||!1,cookie_expiration:365,upgrade:!1,disable_session_recording:!1,disable_persistence:!1,disable_web_experiments:!0,disable_surveys:!1,disable_surveys_automatic_display:!1,disable_conversations:!1,disable_product_tours:!1,disableDeviceModel:!1,disable_external_dependency_loading:!1,strict_script_versioning:!1,enable_recording_console_log:void 0,secure_cookie:(v==null||(e=v.location)==null?void 0:e.protocol)==="https:",ip:!1,opt_out_capturing_by_default:!1,opt_out_persistence_by_default:!1,opt_out_useragent_filter:!1,opt_out_capturing_persistence_type:"localStorage",consent_persistence_name:null,opt_out_capturing_cookie_prefix:null,opt_in_site_apps:!1,property_denylist:[],respect_dnt:!1,sanitize_properties:null,request_headers:{},request_batching:!0,properties_string_max_length:65535,mask_all_element_attributes:!1,mask_all_text:!1,mask_personal_data_properties:!1,custom_personal_data_properties:[],advanced_disable_flags:!1,advanced_disable_decide:!1,advanced_disable_feature_flags:!1,advanced_disable_feature_flags_on_first_load:!1,advanced_only_evaluate_survey_feature_flags:!1,advanced_feature_flags_dedup_per_session:!1,advanced_enable_surveys:!1,advanced_disable_toolbar_metrics:!1,feature_flag_request_timeout_ms:3e3,surveys_request_timeout_ms:1e4,on_request_error(s){k.error("Bad HTTP status: "+s.statusCode+" "+s.text)},get_device_id:s=>s,capture_performance:void 0,name:"posthog",bootstrap:{},disable_compression:!1,session_idle_timeout_seconds:1800,person_profiles:ro,before_send:void 0,get_current_url:void 0,request_queue_config:{flush_interval_ms:fo},error_tracking:{},_onCapture:gr},(s=>({rageclick:s&&s>="2026-05-30"?{content_ignorelist:Ep,ignore_text_selection:!0}:!s||"2025-11-30">s||{content_ignorelist:!0},capture_pageview:!s||"2025-05-24">s||"history_change",session_recording:s&&s>="2026-06-25"?{strictMinimumDuration:!0,canvasCapture:{resolutionScale:.6},streamNetworkBody:!0}:s&&s>="2026-05-30"?{strictMinimumDuration:!0,canvasCapture:{resolutionScale:.6}}:s&&s>="2025-11-30"?{strictMinimumDuration:!0}:{},external_scripts_inject_target:s&&s>="2026-01-30"?"head":"body",internal_or_test_user_hostname:s&&s>="2026-01-30"?/^(localhost|127\.0\.0\.1)$/:void 0,persistence_save_debounce_ms:s&&s>="2026-05-30"?250:0,split_storage:!(!s||"2026-05-30">s),detect_google_search_app:!(!s||"2026-05-30">s),disable_capture_url_hashes:!(!s||"2026-06-25">s)}))(t))},df=[["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"]],Rl=t=>{var e={};for(var s of df){var n=s[0],r=s[1];x(t[n])||(e[r]=t[n])}var i=ee({},e,t),o=t.__preview_external_dependency_versioned_paths;return x(o)||(x(t.strict_script_versioning)&&(i.strict_script_versioning=!!o),W(o)&&x(t.asset_host)&&(i.asset_host=o)),L(t.property_blacklist)&&(x(t.property_denylist)?i.property_denylist=t.property_blacklist:L(t.property_denylist)?i.property_denylist=[...t.property_blacklist,...t.property_denylist]:k.error(cd+t.property_denylist)),i};class hf{constructor(){this.__forceAllowLocalhost=!1}get fn(){return this.__forceAllowLocalhost}set fn(e){k.error("WebPerformanceObserver is deprecated and has no impact on network capture. Use `_forceAllowLocalhostNetworkCapture` on `posthog.sessionRecording`"),this.__forceAllowLocalhost=e}}class Te{pn(e,s){if(e){var n=this.sn.indexOf(e);n!==-1&&this.sn.splice(n,1)}return this.sn.push(s),s.initialize==null||s.initialize(),s}gn(){return this.config.cookieless_mode===ht||this.config.cookieless_mode===Ht&&this.consent.isRejected()}get decideEndpointWasHit(){var e,s;return(e=(s=this.featureFlags)==null?void 0:s.hasLoadedFlags)!==null&&e!==void 0&&e}get flagsEndpointWasHit(){var e,s;return(e=(s=this.featureFlags)==null?void 0:s.hasLoadedFlags)!==null&&e!==void 0&&e}constructor(){var e;this.webPerformance=new hf,this.mn=!1,this.version=Y.LIB_VERSION,this.yn=new Set,this.bn="",this.dn=new ta,this.sn=[],this._n=[],this._calculate_event_properties=this.calculateEventProperties.bind(this),this.config=bi(),this.SentryIntegration=Ap,this.sentryIntegration=n=>(function(r,i){var o=Nu(r,i);return{name:Tu,processEvent:a=>o(a)}})(this,n),this.__request_queue=[],this.__loaded=!1,this.analyticsDefaultEndpoint="/e/",this.wn=!1,this.kn=null,this.xn=null,this.Sn=null,this.scrollManager=new Zp(this),this.pageViewManager=new vl(this),this.rateLimiter=new Bp(this),this.requestRouter=new ef(this),this.consent=new vp(this),this.externalIntegrations=new of(this);var s=(e=Te.__defaultExtensionClasses)!==null&&e!==void 0?e:{};this.featureFlags=s.featureFlags&&new s.featureFlags(this),this.toolbar=s.toolbar&&new s.toolbar(this),this.surveys=s.surveys&&new s.surveys(this),this.conversations=s.conversations&&new s.conversations(this),this.logs=s.logs&&new s.logs(this),this.metrics=s.metrics&&new s.metrics(this),this.experiments=s.experiments&&new s.experiments(this),this.exceptions=s.exceptions&&new s.exceptions(this),this.people={set:(n,r,i)=>{var o=W(n)?{[n]:r}:n;this.setPersonProperties(o),i?.({})},set_once:(n,r,i)=>{var o=W(n)?{[n]:r}:n;this.setPersonProperties(void 0,o),i?.({})}},this.on("eventCaptured",(n=>k.info('send "'+n?.event+'"',n)))}init(e,s,n){if(n&&n!==os){var r,i=(r=Ys[n])!==null&&r!==void 0?r:new Te;return i._init(e,s,n),Ys[n]=i,Ys[os][n]=i,i}return this._init(e,s,n)}_init(e,s,n){var r,i;s===void 0&&(s={});var o,a=W(e)?e.trim():"";if(!a)return k.critical("PostHog was initialized without a token. This likely indicates a misconfiguration. Please check the first argument passed to posthog.init()"),this;if(this.__loaded)return a!==((o=this.config)==null?void 0:o.token)?console.warn("[PostHog.js]","You have already initialized PostHog with a different project token! Re-initializing is a no-op, so events will keep going to the project this instance was initialized with. To capture into a second project, load PostHog once, then initialize a named instance after the SDK has loaded, e.g. posthog.init('"+a+"', { ... }, 'project2')"):console.warn("[PostHog.js]","You have already initialized PostHog! Re-initializing is a no-op"),this;this.__loaded=!0,this.config=bi(s.defaults),s.debug=this.Cn(s.debug),this.Mn=s,this.Tn=[],s.person_profiles?this.xn=s.person_profiles:s.process_person&&(this.xn=s.process_person);var l=bi(s.defaults),u=Rl(s),c=ee({},l,u,{name:n,token:a});te(l.rageclick)&&te(u.rageclick)&&(c.rageclick=ee({},l.rageclick,u.rageclick)),te(l.session_recording)&&te(u.session_recording)&&(c.session_recording=ee({},l.session_recording,u.session_recording)),this.set_config(c),this.config.on_xhr_error&&k.error("on_xhr_error is deprecated. Use on_request_error instead"),this.compression=s.disable_compression?void 0:xe.GZipJS;var d=this.En();if(this.persistence=new pi(this.config,d),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new pi(b({},this.config,{persistence:"sessionStorage"}),d,!1),this.bn="ph_"+(this.config.persistence_name||this.config.token)+"_session_registered_properties",this.config.persistence!=="memory"&&!d&&ce.N()){var h=ce.H(this.bn);L(h)&&h.forEach((P=>{W(P)&&this.yn.add(P)}))}else ce.q(this.bn);var p=b({},this.persistence.props),f=b({},this.sessionPersistence.props);this.register({$initialization_time:new Date().toISOString()}),this.In=new Kp((P=>this.Pn(P)),this.config.request_queue_config),this.Rn=new Yp(this),this.__request_queue=[];var g=this.gn();if(g||(this.sessionManager=new Cl(this),this.sessionPropsManager=new Il(this,this.sessionManager,this.persistence),this.sessionManager.onSessionId(((P,B,S)=>{(S!=null&&S.activityTimeout||S!=null&&S.sessionPastMaximumLength||S!=null&&S.crossTabAdoption)&&this.An()}))),this.Fn(),this.config.__preview_deferred_init_extensions?(k.info("Deferring extension initialization to improve startup performance"),setTimeout((()=>{this.Ln(g)}),0)):(k.info("Initializing extensions synchronously"),this.Ln(g)),Y.DEBUG=Y.DEBUG||this.config.debug,Y.DEBUG&&k.info("Starting in debug mode",{this:this,config:s,thisC:b({},this.config),p,s:f}),!this.config.identity_distinct_id||(r=s.bootstrap)!=null&&r.distinctID||(s.bootstrap=b({},s.bootstrap,{distinctID:this.config.identity_distinct_id,isIdentifiedID:!0})),((i=s.bootstrap)==null?void 0:i.distinctID)!==void 0){var m=s.bootstrap.distinctID,_=this.get_distinct_id(),w=this.persistence.get_property(He);if(s.bootstrap.isIdentifiedID&&_!=null&&_!==m&&w===es)this.identify(m);else if(s.bootstrap.isIdentifiedID&&_!=null&&_!==m&&w===Tt)k.warn("Bootstrap distinctID differs from an already-identified user. The existing identity is preserved. Call reset() before reinitializing if you intend to switch users.");else{var E=this.config.get_device_id(dt()),I=s.bootstrap.isIdentifiedID?E:m;this.persistence.set_property(He,s.bootstrap.isIdentifiedID?Tt:es),this.register({distinct_id:m,$device_id:I})}}if(g)this.register_once({distinct_id:En,$device_id:null},"");else if(!this.get_distinct_id()){var F=this.config.get_device_id(dt());this.register_once({distinct_id:F,$device_id:F},""),this.persistence.set_property(He,es)}return re(v,"onpagehide"in self?"pagehide":"unload",this._handle_unload.bind(this),{passive:!1}),s.segment?(function(P,B){var S=P.config.segment;if(!S)return B();(function(A,R){var N=A.config.segment;if(!N)return R();var T=J=>{var z=()=>J.anonymousId()||dt();A.config.get_device_id=z,J.id()&&(A.register({distinct_id:J.id(),$device_id:z()}),A.persistence.set_property(He,Tt)),R()},O=N.user();"then"in O&&Se(O.then)?O.then(T):T(O)})(P,(()=>{S.register((A=>{typeof Promise<"u"&&Promise.resolve||di.warn("This browser does not have Promise support, and can not use the segment integration");var R=(N,T)=>{if(!T)return N;N.event.userId||N.event.anonymousId===A.get_distinct_id()||(di.info("No userId set, resetting PostHog"),A.reset()),N.event.userId&&N.event.userId!==A.get_distinct_id()&&(di.info("UserId set, identifying with PostHog"),A.identify(N.event.userId));var O=A.calculateEventProperties(T,N.event.properties);return N.event.properties=Object.assign({},O,N.event.properties),N};return{name:"PostHog JS",type:"enrichment",version:"1.0.0",isLoaded:()=>!0,load:()=>Promise.resolve(),track:N=>R(N,N.event.event),page:N=>R(N,is),identify:N=>R(N,li),screen:N=>R(N,"$screen")}})(P)).then((()=>{B()}))}))})(this,(()=>this.On())):this.On(),Se(this.config._onCapture)&&this.config._onCapture!==gr&&(k.warn("onCapture is deprecated. Please use `before_send` instead"),this.on("eventCaptured",(P=>this.config._onCapture(P.event,P)))),this.config.ip&&k.warn('The `ip` config option has NO EFFECT AT ALL and has been deprecated. Use a custom transformation or "Discard IP data" project setting instead. See https://posthog.com/tutorials/web-redact-properties#hiding-customer-ip-address for more information.'),this.config.disableDeviceModel||(function(){return nd.apply(this,arguments)})().then((P=>{P&&this.register({[oi]:P})})).catch(gr),this}Fn(){var e,s,n,r,i,o,a=(e=(s=this.config.__extensionClasses)==null?void 0:s.featureFlags)!==null&&e!==void 0?e:(n=Te.__defaultExtensionClasses)==null?void 0:n.featureFlags;a&&(this.featureFlags&&this.featureFlags instanceof a||((r=this.Dn)==null||r.call(this),this.Dn=void 0,this.featureFlags=new a(this)),Se(this.featureFlags.onReloading)&&Se(this.featureFlags.setup)?this.Dn||(this.Dn=this.featureFlags.onReloading((()=>{this.dn.emit("featureFlagsReloading",!0)})),this.$n().add(this.featureFlags)):(i=(o=this.featureFlags).initialize)==null||i.call(o))}Ln(e){var s,n,r,i,o,a,l,u=performance.now(),c=b({},Te.__defaultExtensionClasses,this.config.__extensionClasses),d=[];c.exceptions&&this.sn.push(this.exceptions=(s=this.exceptions)!==null&&s!==void 0?s: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=(n=this.surveys)!==null&&n!==void 0?n: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=(i=this.metrics)!==null&&i!==void 0?i: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,Pp)),c.toolbar&&this.sn.push(this.toolbar=(a=this.toolbar)!==null&&a!==void 0?a:new c.toolbar(this)),c.experiments&&this.sn.push(this.experiments=(l=this.experiments)!==null&&l!==void 0?l:new c.experiments(this)),this.sn.forEach((h=>{h.initialize&&d.push((()=>{h.initialize==null||h.initialize()}))})),d.push((()=>{if(this.Nn){var h=this.Nn;this.Nn=void 0,this.sn.forEach((p=>p.onRemoteConfig==null?void 0:p.onRemoteConfig(h)))}})),this.qn(d,u)}qn(e,s){for(;e.length>0;){if(this.config.__preview_deferred_init_extensions&&performance.now()-s>=30&&e.length>0)return void setTimeout((()=>{this.qn(e,s)}),0);var n=e.shift();if(n)try{n()}catch(i){k.error("Error initializing extension:",i)}}var r=Math.round(performance.now()-s);this.register_for_session({[vu]:this.config.__preview_deferred_init_extensions?"deferred":"synchronous",[_u]:r}),this.config.__preview_deferred_init_extensions&&k.info("PostHog extensions initialized ("+r+"ms)")}Zi(e){var s;if(!C||!C.body)return k.info("document not ready yet, trying again in 500 milliseconds..."),void setTimeout((()=>{this.Zi(e)}),500);if(this.config.__preview_deferred_init_extensions&&(this.Nn=e),this.hn=e,this.compression=void 0,e.ok){var n,r=e.config;r.supportedCompression&&!this.config.disable_compression&&(this.compression=M(r.supportedCompression,xe.GZipJS)?xe.GZipJS:M(r.supportedCompression,xe.Base64)?xe.Base64:void 0),(n=r.analytics)!=null&&n.endpoint&&(this.analyticsDefaultEndpoint=r.analytics.endpoint)}this.set_config({person_profiles:this.xn?this.xn:ro}),(s=this.jn)==null||s.handleRemoteConfig(e),this.sn.forEach((i=>i.onRemoteConfig==null?void 0:i.onRemoteConfig(e)))}On(){try{this.config.loaded(this)}catch(n){k.critical("`loaded` function failed",n)}if(this.Bn(),this.config.internal_or_test_user_hostname&&ne!=null&&ne.hostname){var e=ne.hostname,s=this.config.internal_or_test_user_hostname;(typeof s=="string"?e===s:s.test(e))&&this.setInternalOrTestUser()}this.config.capture_pageview&&setTimeout((()=>{(this.consent.isOptedIn()||this.gn())&&this.Hn()}),1),this.Un=new zu(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()&&Sn(this.__request_queue,(e=>this.Pn(e))),this.__request_queue=[],this.Bn()}_handle_unload(){var e,s,n,r,i;(e=this.surveys)==null||e.handlePageUnload==null||e.handlePageUnload(),(s=this.metrics)==null||s.flush("sendBeacon"),this.config.request_batching?(this.zn()&&this.capture(ai),(n=this.logs)==null||n.flushLogs("sendBeacon"),(r=this.In)==null||r.unload(),(i=this.Rn)==null||i.unload()):this.zn()&&this.capture(ai,null,{transport:"sendBeacon"})}_send_request(e){this.__loaded?ud?this.__request_queue.push(e):this.rateLimiter.isServerRateLimited(e.batchKey)?e.fireCallbackOnDrop&&(e.callback==null||e.callback({statusCode:429})):(e.transport=e.transport||this.config.api_transport,e.headers=b({},this.config.request_headers,e.headers),e.compression=e.compression==="best-available"?this.compression:e.compression,(x(this.config.disable_beacon)?this.config.__preview_disable_beacon:this.config.disable_beacon)&&(e.disableTransport=["sendBeacon"]),e.fetchOptions=e.fetchOptions||this.config.fetch_options,(s=>{var n,r,i,o=b({},s);o.timeout=o.timeout||6e4;var a,l,u,c,d,h=(n=o.transport)!==null&&n!==void 0?n:"fetch";h==="sendBeacon"&&x(o.compression)&&o.data&&(o.compression=xe.Base64),o.method==="POST"&&o.data&&(o.timestampMode==="capture-body"?o.data={api_key:(l=(d=(c=L(a=o.data)?a:[a])[0])==null||(u=d.properties)==null?void 0:u.token)!==null&&l!==void 0?l:d?.token,batch:c,sent_at:new Date().toISOString()}:o.timestampMode==="body"&&(o.data=(function(m,_){return _===void 0&&(_=new Date().toISOString()),L(m)?m.map((w=>b({},w,{sent_at:_}))):b({},m,{sent_at:_})})(o.data))),o.url=kl(o.url,o.method,o.compression,o.timestampMode);var p=jn.filter((m=>!o.disableTransport||!m.transport||!o.disableTransport.includes(m.transport))),f=(r=(i=(function(m,_){for(var w=0;m.length>w;w++)if(m[w].transport===h)return m[w]})(p))==null?void 0:i.method)!==null&&r!==void 0?r:p[0].method;if(!f)throw new Error("No available transport method");var g=m=>{try{f(m)}catch(_){ed(_)?k.warn(_):k.error(_),o.callback==null||o.callback({statusCode:0,error:_})}};h!=="sendBeacon"&&o.data&&o.compression===xe.GZipJS&&hh&&typeof Promise<"u"&&!Bn?Vp(o).then((m=>{g(m)})).catch((m=>{if(qa(m))return Bn=!0,void g(b({},o,{compression:void 0,url:kl(s.url,s.method,void 0,s.timestampMode)}));(_=>{if(!_||typeof _!="object")return!1;var w="name"in _?String(_.name):"";return qa(_)||w===Ac})(m)&&(Bn=!0),g(o)})):f(o)})(b({},e,{callback:s=>{var n,r;this.rateLimiter.checkForLimiting(s),400>s.statusCode||(n=(r=this.config).on_request_error)==null||n.call(r,s),e.callback==null||e.callback(s)}}))):e.fireCallbackOnDrop&&(e.callback==null||e.callback({statusCode:0}))}Pn(e){this.Rn?this.Rn.retriableRequest(e):this._send_request(e)}_execute_array(e){wi++;try{var s,n=[],r=[],i=[];Sn(e,(a=>{if(a)if(L(s=a[0]))i.push(a);else if(Se(a))try{a.call(this)}catch(l){k.error("Error executing queued PostHog call",a,l)}else L(a)&&s==="alias"?n.push(a):L(a)&&s.indexOf("capture")!==-1&&Se(this[s])?i.push(a):r.push(a)}));var o=function(a,l){Sn(a,(function(u){try{if(L(u[0])){var c=l;Z(u,(function(d){c=c[d[0]].apply(c,d.slice(1))}))}else l[u[0]].apply(l,u.slice(1))}catch(d){k.error("Error executing queued PostHog call",u,d)}}))};o(n,this),o(r,this),o(i,this)}finally{wi--}}push(e){if(wi>0&&L(e)&&W(e[0])){var s=Te.prototype[e[0]];Se(s)&&s.apply(this,e.slice(1))}else this._execute_array([e])}capture(e,s,n){var r,i,o,a,l;if(this.__loaded&&this.persistence&&this.sessionPersistence&&this.In){if(this.is_capturing())if(!x(e)&&W(e)){var u=!this.config.opt_out_useragent_filter&&this._is_bot();if(!u||this.config.__preview_capture_bot_pageviews){var c=n!=null&&n.skip_client_rate_limiting?void 0:this.rateLimiter.clientRateLimitContext();if(c==null||!c.isRateLimited){s!=null&&s.$current_url&&!W(s?.$current_url)&&(k.error("Invalid `$current_url` property provided to `posthog.capture`. Input must be a string. Ignoring provided value."),s==null||delete s.$current_url),e!=="$exception"||n!=null&&n.Wn||k.warn("Using `posthog.capture('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureException(error)` instead, which attaches required metadata automatically."),this.sessionPersistence.update_search_keyword(),this.config.save_campaign_params&&this.sessionPersistence.update_campaign_params(),this.config.save_referrer&&this.sessionPersistence.update_referrer_info(),(this.config.save_campaign_params||this.config.save_referrer)&&this.persistence.set_initial_person_info();var d=new Date,h=n?.timestamp||d,p=Ya(n?.uuid,dt),f={uuid:p,event:e,properties:this.calculateEventProperties(e,s||{},h,p)};e===is&&this.config.__preview_capture_bot_pageviews&&u&&(f.event="$bot_pageview",f.properties.$browser_type="bot"),c&&(f.properties.$lib_rate_limit_remaining_tokens=c.remainingTokens);var g=e==="$feature_flag_called"&&f.properties.$feature_flag_has_experiment===!1&&this.get_property(sr)===!0;n?.$set&&!g&&(f.$set=n?.$set);var m=n?.$unset;m&&(f.$unset=m);var _,w,E,I=g?void 0:this.Vn(n?.$set_once,e!==sl,e===li);if(I&&(f.$set_once=I),n!=null&&n._noTruncate||(i=this.config.properties_string_max_length,o=f,a=T=>W(T)?T.slice(0,i):T,l=new Set,f=(function T(O,J){if(O!==Object(O))return a?a(O):O;if(!l.has(O)){var z;if(l.add(O),L(O))z=[],Sn(O,(oe=>{z.push(T(oe))}));else{var H={};Z(O,((oe,pe)=>{l.has(oe)||(H[pe]=T(oe))})),z=H}return z}})(o)),f.timestamp=h,x(n?.timestamp)||(f.properties.$event_time_override_provided=!0,f.properties.$event_time_override_system_time=d),g&&(f.properties=(function(T,O){O===void 0&&(O=[]);var J={},z=H=>{T[H]!==void 0&&(J[H]=T[H])};return ph.forEach(z),O.forEach(z),J})(f.properties,uf)),e===ft.DISMISSED||e===ft.SENT){var F=s?.[gi.SURVEY_ID],P=s?.[gi.SURVEY_ITERATION];ld({id:F,current_iteration:P}),f.$set=b({},f.$set,{[(_={id:F,current_iteration:P},w=e===ft.SENT?"responded":"dismissed",E="$survey_"+w+"/"+_.id,_.current_iteration&&_.current_iteration>0&&(E="$survey_"+w+"/"+_.id+"/"+_.current_iteration),E)]:!0})}else e===ft.SHOWN&&(f.$set=b({},f.$set,{[gi.SURVEY_LAST_SEEN_DATE]:new Date().toISOString()}));if(e===Dp.SHOWN){var B=s?.[yl.TOUR_TYPE];B&&(f.$set=b({},f.$set,{[yl.TOUR_LAST_SEEN_DATE+"/"+B]:new Date().toISOString()}))}var S=b({},f.properties.$set,f.$set);if(mt(S)||this.setPersonPropertiesForFlags(S),!D(this.config.before_send)){var A=this.Pt(f);if(!A)return;(f=A).uuid=Ya(f.uuid,dt)}this.dn.emit("eventCaptured",f);var R=(r=n?._url)!==null&&r!==void 0?r:this.requestRouter.endpointFor("api",this.analyticsDefaultEndpoint),N={method:"POST",url:R,data:f,compression:"best-available",timestampMode:n?._batchKey==="recordings"||/\/s\/(?:\?|$)/.test(R)?"body":"capture-body",batchKey:n?._batchKey,transport:n?.transport};return!this.config.request_batching||n&&(n==null||!n._batchKey)||n!=null&&n.send_instantly?this.Pn(N):this.In.enqueue(N),f}k.critical("This capture call is ignored due to client rate limiting.")}}else k.error("No event name provided to posthog.capture")}else k.uninitializedWarning("posthog.capture")}_addCaptureHook(e){return this.on("eventCaptured",(s=>e(s.event,s)))}$n(){var e;return(e=this.jn)!==null&&e!==void 0?e:this.jn=new cf(this)}cn(e){this._n.push(e);var s=!0;return()=>{if(s){s=!1;var n=this._n.indexOf(e);n!==-1&&this._n.splice(n,1)}}}calculateEventProperties(e,s,n,r,i){if(n=n||new Date,!this.persistence||!this.sessionPersistence)return s;var o=i?void 0:this.persistence.remove_event_timer(e),a=b({},s);if(a.token=this.config.token,a.$config_defaults=this.config.defaults,this.gn()&&(a[mu]=!0),e==="$snapshot"){var l=b({},this.persistence.properties(),this.sessionPersistence.properties());return a.distinct_id=l.distinct_id,(!W(a.distinct_id)&&!he(a.distinct_id)||Di(a.distinct_id))&&k.error("Invalid distinct_id for replay event. This indicates a bug in your implementation"),a}var u,c=(function(F,P,B,S){var A,R,N,T;if(S===void 0&&(S=!1),!Pe)return{};var O,J=F?[...vs,...P||[]]:[],z=(function(_n){for(var je=0;Ka.length>je;je++){var yn=Ka[je],Xt=yn[1],Qt=yn[0].exec(_n),Is=Qt&&(Se(Xt)?Xt(Qt,_n):Xt);if(Is)return Is}return["",""]})(Pe),H=z[0],oe=z[1],pe=(O=typeof navigator<"u"?navigator:void 0)!=null&&O.brave?{brave:!0}:{},Ie={};x(B)||(Ie.detectGoogleSearchApp=B);var _e={},Ce=(A=navigator)==null||(A=A.userAgentData)==null?void 0:A.platform,Re=(R=navigator)==null?void 0:R.maxTouchPoints,ae=v==null||(N=v.screen)==null?void 0:N.width,me=v==null||(T=v.screen)==null?void 0:T.height,ge=v?.devicePixelRatio;x(Ce)||(_e.userAgentDataPlatform=Ce),x(Re)||(_e.maxTouchPoints=Re),x(ae)||(_e.screenWidth=ae),x(me)||(_e.screenHeight=me),x(ge)||(_e.devicePixelRatio=ge);var Ye,Rt,de,Ve,St,ks,Be,Fe,vn=ee(Jo({$os:H,$os_version:oe,$browser:tu(Pe,navigator.vendor,pe,Ie),$device:Ja(Pe),$device_type:(Rt=Pe,de=_e,Fe=Ja(Rt),Fe===Oc||Fe===Lc||Fe==="Kobo"||Fe==="Kindle Fire"||Fe===Yc?ps:Fe===en||Fe===ds||Fe===tn||Fe===ji?"Console":Fe===Bc?"Wearable":Fe?Oe:de?.userAgentDataPlatform==="Android"&&((Ve=de?.maxTouchPoints)!==null&&Ve!==void 0?Ve:0)>0?600>Math.min((St=de?.screenWidth)!==null&&St!==void 0?St:0,(ks=de?.screenHeight)!==null&&ks!==void 0?ks:0)/((Be=de?.devicePixelRatio)!==null&&Be!==void 0?Be:1)?Oe:ps:"Desktop"),$timezone:Wu(),$timezone_offset:Mp()}),{$current_url:rn(S?Ct(ne?.href):ne?.href,J,on),$host:ne?.host,$pathname:ne?.pathname,$raw_user_agent:Pe.length>1e3?Pe.substring(0,997)+"...":Pe,$browser_version:Rh(Pe,navigator.vendor,pe,Ie),$browser_language:_l(),$browser_language_prefix:(Ye=_l(),typeof Ye=="string"?Ye.split("-")[0]:void 0),$screen_height:v?.screen.height,$screen_width:v?.screen.width,$viewport_height:v?.innerHeight,$viewport_width:v?.innerWidth,$lib:Y.LIB_NAME,$lib_version:Y.LIB_VERSION,$insert_id:Math.random().toString(36).substring(2,10)+Math.random().toString(36).substring(2,10),$time:Date.now()/1e3});return Y.SDK_DIST_CHANNEL&&(vn.$sdk_dist_channel=Y.SDK_DIST_CHANNEL),vn})(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(i,n.getTime()),h=d.windowId;a.$session_id=d.sessionId,a.$window_id=h}this.sessionPropsManager&&ee(a,this.sessionPropsManager.getSessionProps());try{var p;this.sessionRecording&&ee(a,this.sessionRecording.sdkDebugProperties),a.$sdk_debug_retry_queue_size=(p=this.Rn)==null?void 0:p.length}catch(F){a.$sdk_debug_error_capturing_properties=String(F)}if(this.requestRouter.region===go&&(a.$lib_custom_api_host=this.config.api_host),u=e!==is||i?e!==ai||i?this.pageViewManager.doEvent():this.pageViewManager.doPageLeave(n):this.pageViewManager.doPageView(n,r),a=ee(a,u),e===is&&C&&(a.title=C.title),!x(o)){var f=n.getTime()-o;a.$duration=parseFloat((f/1e3).toFixed(3))}Pe&&this.config.opt_out_useragent_filter&&(a.$browser_type=this._is_bot()?"bot":"browser");var g=this.persistence.properties(),m=this.sessionPersistence.properties();Z(["$referrer","$referring_domain"],(F=>{F in g&&delete m[F]}));var _={};if(this._n.length>0)for(var w of this._n.slice())try{ee(_,w())}catch(F){k.error("Failed to produce browser extension event properties",F)}(a=ee({},c,g,m,b({},_,a))).$is_identified=this._isIdentified(),L(this.config.property_denylist)?Z(this.config.property_denylist,(function(F){delete a[F]})):k.error(cd+this.config.property_denylist+" or property_blacklist config: "+this.config.property_blacklist);var E=this.config.sanitize_properties;E&&(k.error($l),a=E(a,e));var I=this.Zn();return a.$process_person_profile=I,I&&!i&&this.Gn("_calculate_event_properties"),a}Vn(e,s,n){var r;if(s===void 0&&(s=!0),n===void 0&&(n=!1),!this.persistence||!this.Zn()||this.mn&&!n)return e;var i=this.persistence.get_initial_props(),o=(r=this.sessionPropsManager)==null?void 0:r.getSetOnceProps(),a=ee({},i,o||{},e||{}),l=this.config.sanitize_properties;return l&&(k.error($l),a=l(a,"$set_once")),s&&(this.mn=!0),mt(a)?void 0:a}register(e,s){var n;(n=this.persistence)==null||n.register(e,s)}register_once(e,s,n){var r;(r=this.persistence)==null||r.register_once(e,s,n)}register_for_session(e){var s;(s=this.sessionPersistence)==null||s.register(e),Object.keys(e).forEach((n=>this.yn.add(n))),this.Qn()}unregister(e){var s;(s=this.persistence)==null||s.unregister(e)}unregister_for_session(e){var s;(s=this.sessionPersistence)==null||s.unregister(e),this.yn.delete(e),this.Qn()}Kn(e,s){this.register({[e]:s})}An(){this.yn.forEach((e=>{var s;(s=this.sessionPersistence)==null||s.unregister(e)})),this.yn.clear(),this.Qn()}Qn(){var e;if(this.bn)if(this.config.persistence==="memory"||(e=this.sessionPersistence)!=null&&e.xi||!ce.N())ce.q(this.bn);else{var s=[];this.yn.forEach((n=>s.push(n))),s.length>0?ce.F(this.bn,s):ce.q(this.bn)}}getFeatureFlag(e,s){var n;return(n=this.featureFlags)==null?void 0:n.getFeatureFlag(e,s)}getFeatureFlagPayload(e){var s;return(s=this.featureFlags)==null?void 0:s.getFeatureFlagPayload(e)}getFeatureFlagResult(e,s){var n;return(n=this.featureFlags)==null?void 0:n.getFeatureFlagResult(e,s)}getAllFeatureFlags(){var e,s;return(e=(s=this.featureFlags)==null?void 0:s.getAllFeatureFlags())!==null&&e!==void 0?e:[]}isFeatureEnabled(e,s){var n,r;return(n=(r=this.featureFlags)==null?void 0:r.isFeatureEnabled(e,s))!==null&&n!==void 0?n:s?.defaultValue}reloadFeatureFlags(){var e;(e=this.featureFlags)==null||e.reloadFeatureFlags()}updateFlags(e,s,n){var r;(r=this.featureFlags)==null||r.updateFlags(e,s,n)}updateEarlyAccessFeatureEnrollment(e,s,n){var r;(r=this.featureFlags)==null||r.updateEarlyAccessFeatureEnrollment(e,s,n)}getEarlyAccessFeatures(e,s,n){var r;return s===void 0&&(s=!1),(r=this.featureFlags)==null?void 0:r.getEarlyAccessFeatures(e,s,n)}on(e,s){return this.dn.on(e,s)}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:Ns}),()=>{})}onSessionId(e){var s,n;return(s=(n=this.sessionManager)==null?void 0:n.onSessionId(e))!==null&&s!==void 0?s:()=>{}}getSurveys(e,s){s===void 0&&(s=!1),this.surveys?this.surveys.getSurveys(e,s):e([],{isLoaded:!1,error:Ns})}getActiveMatchingSurveys(e,s){s===void 0&&(s=!1),this.surveys?this.surveys.getActiveMatchingSurveys(e,s):e([],{isLoaded:!1,error:Ns})}renderSurvey(e,s){var n;(n=this.surveys)==null||n.renderSurvey(e,s)}displaySurvey(e,s){var n;s===void 0&&(s=sf),(n=this.surveys)==null||n.displaySurvey(e,s)}cancelPendingSurvey(e){var s;(s=this.surveys)==null||s.cancelPendingSurvey(e)}canRenderSurvey(e){var s,n;return(s=(n=this.surveys)==null?void 0:n.canRenderSurvey(e))!==null&&s!==void 0?s:{visible:!1,disabledReason:Ns}}canRenderSurveyAsync(e,s){var n,r;return s===void 0&&(s=!1),(n=(r=this.surveys)==null?void 0:r.canRenderSurveyAsync(e,s))!==null&&n!==void 0?n:Promise.resolve({visible:!1,disabledReason:Ns})}Jn(e){return!e||Di(e)?(k.critical("Unique user id has not been set in posthog.identify"),!1):e===En?(k.critical('The string "'+e+'" was set in posthog.identify which indicates an error. This ID is only used as a sentinel value.'),!1):!["distinct_id","distinctid"].includes(e.toLowerCase())&&!["undefined","null"].includes(e.toLowerCase())||(k.critical('The string "'+e+'" was set in posthog.identify which indicates an error. This ID should be unique to the user and not a hardcoded string.'),!1)}identify(e,s,n){if(!this.__loaded||!this.persistence)return k.uninitializedWarning("posthog.identify");if(he(e)&&(e=e.toString(),k.warn("The first argument to posthog.identify was a number, but it should be a string. It has been converted to a string.")),this.Jn(e)&&this.Gn("posthog.identify")){var r=this.get_distinct_id();this.register({$user_id:e}),this.get_property(sn)||this.register_once({$had_persisted_distinct_id:!0,$device_id:r},""),e!==r&&e!==this.get_property(Bs)&&(this.unregister(Bs),this.register({distinct_id:e}));var i,o=(this.persistence.get_property(He)||es)===es,a=e!==r,l=!a&&o;if(a&&o)this.persistence.set_property(He,Tt),this.setPersonPropertiesForFlags({$set:s||{},$set_once:n||{}},!1),this.capture(li,{distinct_id:e,$anon_distinct_id:r},{$set:s||{},$set_once:n||{}}),this.Sn=yi(e,s,n),(i=this.featureFlags)==null||i.setAnonymousDistinctId(r);else if(l){this.persistence.set_property(He,Tt);var u=s||{},c=n||{};this.setPersonPropertiesForFlags({$set:u,$set_once:c},!1),this.capture("$set",{$set:u,$set_once:c}),this.Sn=yi(e,s,n)}else(s||n)&&this.setPersonProperties(s,n);a?(this.reloadFeatureFlags(),this.featureFlags?this.featureFlags.resetFlagCallReported():this.unregister(Wt)):l&&(s||n)&&this.reloadFeatureFlags()}}setPersonProperties(e,s){if((e||s)&&this.Gn("posthog.setPersonProperties")){var n=yi(this.get_distinct_id(),e,s);this.Sn!==n?(this.setPersonPropertiesForFlags({$set:e||{},$set_once:s||{}},!0),this.capture("$set",{$set:e||{},$set_once:s||{}}),this.Sn=n):k.info("A duplicate setPersonProperties call was made with the same properties. It has been ignored.")}}unsetPersonProperties(e){var s,n=(L(e)?e:[e]).filter((r=>W(r)&&r.length>0));n.length!==0&&this.Gn("posthog.unsetPersonProperties")&&((s=this.featureFlags)==null||s.unsetPersonPropertiesForFlags(n,!0),this.capture("$set",{$unset:n}),this.Sn=null)}group(e,s,n){if(e&&s){var r=this.getGroups(),i=r[e]!==s;if(i&&this.resetGroupPropertiesForFlags(e),this.register({$groups:b({},r,{[e]:s})}),i||n){var o={$group_type:e,$group_key:s};n&&(o.$group_set=n),this.capture(sl,o)}n&&this.setGroupPropertiesForFlags({[e]:n}),i&&!n&&this.reloadFeatureFlags()}else k.error("posthog.group requires a group type and group key")}resetGroups(){this.register({$groups:{}}),this.resetGroupPropertiesForFlags(),this.reloadFeatureFlags()}setPersonPropertiesForFlags(e,s){var n;s===void 0&&(s=!0),(n=this.featureFlags)==null||n.setPersonPropertiesForFlags(e,s)}resetPersonPropertiesForFlags(e){var s;e===void 0&&(e=!0),(s=this.featureFlags)==null||s.resetPersonPropertiesForFlags(e)}setGroupPropertiesForFlags(e,s){var n;s===void 0&&(s=!0),this.Gn("posthog.setGroupPropertiesForFlags")&&((n=this.featureFlags)==null||n.setGroupPropertiesForFlags(e,s))}resetGroupPropertiesForFlags(e){var s;(s=this.featureFlags)==null||s.resetGroupPropertiesForFlags(e)}reset(e){this.Yn(e)}Yn(e,s){var n,r,i,o,a,l,u,c,d,h;if(s===void 0&&(s=!1),k.info("reset"),!this.__loaded)return k.uninitializedWarning("posthog.reset");var p,f=this.get_property(sn),g=this.get_property(oi),m=this.get_property(qt),_=this.is_capturing();if(this.consent.reset(),s||!_||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."),(n=this.persistence)==null||n.clear(),(r=this.sessionPersistence)==null||r.clear(),this.yn.clear(),this.Qn(),x(m)||(p=this.persistence)==null||p.register({[qt]:m}),(i=this.surveys)==null||i.reset(),(o=this.Un)==null||o.stop(),(a=this.featureFlags)==null||a.reset(),(l=this.conversations)==null||l.reset(),(u=this.logs)==null||u.reset(),(c=this.metrics)==null||c.reset(),(d=this.persistence)==null||d.set_property(He,es),(h=this.sessionManager)==null||h.resetSessionId(),this.Sn=null,this.config.cookieless_mode===ht)this.register_once({distinct_id:En,$device_id:null},"");else{var w=this.config.get_device_id(dt());this.register_once({distinct_id:w,$device_id:e?w:f},""),e||x(g)||this.register({[oi]: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 s=this;return X((function*(){var n,r,i,o,a,l,u;if(s.__loaded){(n=s.Un)==null||n.stop(),(r=s.jn)==null||r.dispose(),(i=s.sessionRecording)==null||i.dispose(),(o=s.logs)==null||o.flushLogs("sendBeacon"),(a=s.metrics)==null||a.flush("sendBeacon"),(l=s.In)==null||l.unload(),(u=s.Rn)==null||u.unload();try{var c;(c=s.featureFlags)==null||c.destroy()}catch(d){k.error("Error while destroying feature flags",d)}}else k.uninitializedWarning("posthog.shutdown")}))()}setIdentity(e,s){var n;this.config.identity_distinct_id=e,this.config.identity_hash=s,this.alias(e),(n=this.conversations)==null||n.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,s;return(e=(s=this.sessionManager)==null?void 0:s.checkAndGetSessionAndWindowId(!0).sessionId)!==null&&e!==void 0?e:""}get_session_replay_url(e){if(!this.sessionManager)return"";var s=this.sessionManager.checkAndGetSessionAndWindowId(!0),n=s.sessionStartTimestamp,r=this.requestRouter.endpointFor("ui","/project/"+this.config.token+"/replay/"+s.sessionId);if(e!=null&&e.withTimestamp&&n){var i,o=(i=e.timestampLookBack)!==null&&i!==void 0?i:10;if(!n)return r;r+="?t="+Math.max(Math.floor((new Date().getTime()-n)/1e3)-o,0)}return r}alias(e,s){return e===this.get_property(uu)?(k.critical("Attempting to create alias for existing People user - aborting."),-2):this.Gn("posthog.alias")?(x(s)&&(s=this.get_distinct_id()),e!==s?(this.Kn(Bs,e),this.capture("$create_alias",{alias:e,distinct_id:s})):(k.warn("alias matches current distinct_id - skipping api call."),this.identify(e),-1)):void 0}set_config(e){var s=b({},this.config);if(te(e)){var n,r,i,o,a,l,u,c,d,h,p,f;ee(this.config,Rl(e));var g=this.En();(n=this.persistence)==null||n.update_config(this.config,s,g),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new pi(b({},this.config,{persistence:"sessionStorage"}),g,!1);var m=this.Cn(this.config.debug);Ke(m)&&(this.config.debug=m),Ke(this.config.debug)&&(this.config.debug?(Y.DEBUG=!0,Q.N()&&Q.F("ph_debug",!0),k.info("set_config",{config:e,oldConfig:s,newConfig:b({},this.config)})):(Y.DEBUG=!1,Q.N()&&Q.q("ph_debug"))),(r=this.featureFlags)==null||r.updateConfig==null||r.updateConfig(this.config,this.Qi()),(i=this.exceptionObserver)==null||i.onConfigChange(),(o=this.exceptions)==null||o.onConfigChange(),(a=this.sessionRecording)==null||a.startIfEnabledOrStop(),(l=this.tracingHeaders)==null||l.startIfEnabledOrStop(),(u=this.autocapture)==null||u.startIfEnabled(),(c=this.heatmaps)==null||c.startIfEnabled(),(d=this.exceptionObserver)==null||d.startIfEnabledOrStop(),(h=this.deadClicksAutocapture)==null||h.startIfEnabledOrStop(),(p=this.surveys)==null||p.loadIfEnabled(),this.es(),(f=this.externalIntegrations)==null||f.startIfEnabledOrStop()}}_overrideSDKInfo(e,s){Y.LIB_NAME=e,Y.LIB_VERSION=s}startSessionRecording(e){var s,n,r,i,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)&&((s=this.sessionManager)==null||s.checkAndGetSessionAndWindowId(),l.sampling&&((n=this.sessionRecording)==null||n.overrideSampling()),l.linked_flag&&((r=this.sessionRecording)==null||r.overrideLinkedFlag()),l.url_trigger&&((i=this.sessionRecording)==null||i.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,s){if(this.exceptions){var n=new Error("PostHog syntheticException"),r=this.exceptions.buildProperties(e,{handled:!0,syntheticException:n});return this.exceptions.sendExceptionEvent(b({},r,s))}}addExceptionStep(e,s){var n;(n=this.exceptions)==null||n.addExceptionStep(e,s)}captureLog(e){var s;(s=this.logs)==null||s.captureLog(e)}get logger(){var e,s;return(e=(s=this.logs)==null?void 0:s.logger)!==null&&e!==void 0?e:Te.rs}startExceptionAutocapture(e){this.set_config({capture_exceptions:e==null||e})}stopExceptionAutocapture(){this.set_config({capture_exceptions:!1})}loadToolbar(e){var s,n;return(s=(n=this.toolbar)==null?void 0:n.loadToolbar(e))!==null&&s!==void 0&&s}get_property(e){var s;return(s=this.persistence)==null?void 0:s.props[e]}getSessionProperty(e){var s;return(s=this.sessionPersistence)==null?void 0:s.props[e]}toString(){var e,s=(e=this.config.name)!==null&&e!==void 0?e:os;return s!==os&&(s=os+"."+s),s}_isIdentified(){var e,s;return((e=this.persistence)==null?void 0:e.get_property(He))===Tt||((s=this.sessionPersistence)==null?void 0:s.get_property(He))===Tt}Zn(){var e,s;return!(this.config.person_profiles==="never"||this.config.person_profiles===ro&&!this._isIdentified()&&mt(this.getGroups())&&((e=this.persistence)==null||(e=e.props)==null||!e[Bs])&&((s=this.persistence)==null||(s=s.props)==null||!s[ir]))}zn(){return this.config.capture_pageleave===!0||this.config.capture_pageleave==="if_capture_pageview"&&(this.config.capture_pageview===!0||this.config.capture_pageview==="history_change")}createPersonProfile(){this.Zn()||this.Gn("posthog.createPersonProfile")&&this.setPersonProperties({},{})}setInternalOrTestUser(){this.Gn("posthog.setInternalOrTestUser")&&this.setPersonProperties({$internal_or_test_user:!0})}Gn(e){return this.config.person_profiles==="never"?(k.error(e+' was called, but process_person is set to "never". This call will be ignored.'),!1):(this.Kn(ir,!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!==Ht)}es(){var e,s,n,r,i=this.En();return((e=this.persistence)==null?void 0:e.xi)!==i&&((n=this.persistence)==null||n.set_disabled(i)),((s=this.sessionPersistence)==null?void 0:s.xi)!==i&&((r=this.sessionPersistence)==null||r.set_disabled(i)),i&&(this.yn.clear(),this.Qn()),i}opt_in_capturing(e){var s;if(this.config.cookieless_mode!==ht){if(this.gn()){var n,r,i,o,a;this.Yn(!0,!0),(n=this.sessionManager)==null||n.destroy(),(r=this.pageViewManager)==null||r.destroy(),this.sessionManager=new Cl(this),this.pageViewManager=new vl(this),this.persistence&&(this.sessionPropsManager=new Il(this,this.sessionManager,this.persistence));var l,u=(i=(o=this.config.__extensionClasses)==null?void 0:o.sessionRecording)!==null&&i!==void 0?i:(a=Te.__defaultExtensionClasses)==null?void 0:a.sessionRecording;u&&(this.sessionRecording=this.pn(this.sessionRecording,new u(this)),this.hn&&((l=this.sessionRecording)==null||l.onRemoteConfig==null||l.onRemoteConfig(this.hn)))}var c,d;this.consent.optInOut(!0),this.es(),this.Bn(),(s=this.sessionRecording)==null||s.startIfEnabledOrStop(),this.config.cookieless_mode==Ht&&((c=this.surveys)==null||c.loadIfEnabled()),(x(e?.captureEventName)||e!=null&&e.captureEventName)&&this.capture((d=e?.captureEventName)!==null&&d!==void 0?d:"$opt_in",e?.captureProperties,{send_instantly:!0}),this.config.capture_pageview&&this.Hn()}else k.warn(Al)}opt_out_capturing(){var e,s,n;this.config.cookieless_mode!==ht?(this.config.cookieless_mode===Ht&&this.consent.isOptedIn()&&this.Yn(!0,!0),this.consent.optInOut(!1),this.es(),this.config.cookieless_mode===Ht&&(this.register({distinct_id:En,$device_id:null}),(e=this.sessionRecording)==null||e.stopRecording(),this.sessionRecording=void 0,(s=this.sessionManager)==null||s.destroy(),(n=this.pageViewManager)==null||n.destroy(),this.sessionManager=void 0,this.sessionPropsManager=void 0,this.config.capture_pageview&&this.Hn(),this.Bn())):k.warn(Al)}has_opted_in_capturing(){return this.consent.isOptedIn()}has_opted_out_capturing(){return this.consent.isOptedOut()}get_explicit_consent_status(){var e=this.consent.consent;return e===1?"granted":e===0?"denied":"pending"}is_capturing(){return this.config.cookieless_mode===ht||(this.config.cookieless_mode===Ht?this.consent.isRejected()||this.consent.isOptedIn():!this.has_opted_out_capturing())}clear_opt_in_out_capturing(){this.consent.reset(),this.es()}_is_bot(){return ke?sd(ke,this.config.custom_blocked_useragents):void 0}Hn(){C&&(C.visibilityState==="visible"?this.wn||(this.wn=!0,this.capture(is,{title:C.title},{send_instantly:!0}),this.kn&&(C.removeEventListener(or,this.kn),this.kn=null)):this.kn||(this.kn=this.Hn.bind(this),re(C,or,this.kn)))}debug(e){e===!1?(v?.console.log("You've disabled debug mode."),this.set_config({debug:!1})):(v?.console.log("You're now in debug mode. All calls to PostHog will be logged in your console.\nYou can disable this with `posthog.debug(false)`."),this.set_config({debug:!0}))}Qi(){var e=this.Mn||{};return"advanced_disable_flags"in e?!!e.advanced_disable_flags:this.config.advanced_disable_flags!==!1?!!this.config.advanced_disable_flags:this.config.advanced_disable_decide===!0?(k.warn("Config field 'advanced_disable_decide' is deprecated. Please use 'advanced_disable_flags' instead. The old field will be removed in a future major version."),!0):(function(s,n,r,i,o){var a=n in s&&!D(s[n]),l=r in s&&!D(s[r]);return a?s[n]:!!l&&(o&&o.warn("Config field '"+r+"' is deprecated. Please use '"+n+"' instead. The old field will be removed in a future major version."),s[r])})(e,"advanced_disable_flags","advanced_disable_decide",0,k)}Pt(e){var s;if(D(this.config.before_send))return e;var n=Object.keys((s=e.properties)!==null&&s!==void 0?s:{}).filter(wh),r=L(this.config.before_send)?this.config.before_send:[this.config.before_send],i=e;for(var o of r){if(i=o(i),D(i)){var a="Event '"+e.event+"' was rejected in beforeSend function";return yh(e.event)?k.warn(a+". This can cause unexpected behavior."):k.info(a),null}i.properties&&!mt(i.properties)||k.warn("Event '"+e.event+"' has no properties after beforeSend function, this is likely an error.")}for(var l of n)if(i.properties&&D(i.properties[l]))return k.warn("Event '"+e.event+"' had its '"+l+"' property removed in a beforeSend function. This property is required for ingestion, so the event will be dropped."),null;return i}getPageViewId(){var e;return(e=this.pageViewManager.ui)==null?void 0:e.pageViewId}captureTraceFeedback(e,s){this.capture("$ai_feedback",{$ai_trace_id:String(e),$ai_feedback_text:s})}captureTraceMetric(e,s,n){this.capture("$ai_metric",{$ai_trace_id:String(e),$ai_metric_name:s,$ai_metric_value:String(n)})}Cn(e){var s=Ke(e)&&!e,n=Q.N()&&Q.P("ph_debug")==="true";return!s&&(!!n||e)}}Te.__defaultExtensionClasses={},Te.rs=(()=>{var t=()=>{};return{trace:t,debug:t,info:t,warn:t,error:t,fatal:t}})(),(function(t,e){for(var s=0;e.length>s;s++)t.prototype[e[s]]=lp(t.prototype[e[s]])})(Te,["identify"]);class Tl{constructor(e){this.disabled=e===!1;var s=te(e)?e:{};this.thresholdPx=s.threshold_px||30,this.timeoutMs=s.timeout_ms||1e3,this.clickCount=s.click_count||3,this.clicks=[]}isRageClick(e,s,n){if(this.disabled)return!1;var r=this.clicks[this.clicks.length-1];if(r&&Math.abs(e-r.x)+Math.abs(s-r.y)n-r.timestamp){if(this.clicks.push({x:e,y:s,timestamp:n}),this.clicks.length===this.clickCount)return!0}else this.clicks=[{x:e,y:s,timestamp:n}];return!1}}var Ei="$copy_autocapture",Si=se("[AutoCapture]");function xi(t,e){return e.length>t?e.slice(0,t)+"...":e}function pf(t){if(t.previousElementSibling)return t.previousElementSibling;var e=t;do e=e.previousSibling;while(e&&!Ft(e));return e}function ff(t,e){var s,n,r=e.e,i=e.maskAllElementAttributes,o=e.maskAllText,a=e.elementAttributeIgnoreList,l=e.elementsChainAsString,u=e.disableCaptureUrlHashes;if(!Ft(t))return{props:{}};for(var c=[t],d=new Set([t]),h=t;h.parentNode&&!Me(h,"body")&&Iu>c.length;)if(ku(h.parentNode)){var p=h.parentNode.host;if(d.has(p))break;d.add(p),c.push(p),h=p}else{if(!Ft(h.parentNode)||d.has(h.parentNode))break;d.add(h.parentNode),c.push(h.parentNode),h=h.parentNode}var f,g,m=[],_={},w=!1,E=!1;if(Z(c,(S=>{var A=ao(S);if(Me(S,"a")){var R=S.getAttribute("href");w=!!(A&&R&&Ks(R))&&(u?Ct(R):R)}M(cr(S),"ph-no-capture")&&(E=!0),m.push((function(T,O,J,z,H){H===void 0&&(H=!1);var oe=T.tagName.toLowerCase(),pe={tag_name:oe};Zo.indexOf(oe)>-1&&!J&&(pe.$el_text=oe.toLowerCase()==="a"||oe.toLowerCase()==="button"?xi(1024,fl(T)):xi(1024,nn(T)));var Ie=cr(T);Ie.length>0&&(pe.classes=Ie.filter((function(ae){return ae!==""}))),Z(T.attributes,(function(ae){var me;if((!$u(T)||["name","id","class","aria-label"].indexOf(ae.name)!==-1)&&(z==null||!z.includes(ae.name))&&!O&&Ks(ae.value)&&(!W(me=ae.name)||me.substring(0,10)!=="_ngcontent"&&me.substring(0,7)!=="_nghost")){var ge=ae.value;ae.name==="class"&&(ge=Yo(ge).join(" ")),pe["attr__"+ae.name]=xi(1024,ae.name==="href"&&H?Ct(ge):ge)}}));for(var _e=1,Ce=1,Re=T;Re=pf(Re);)_e++,Re.tagName===T.tagName&&Ce++;return pe.nth_child=_e,pe.nth_of_type=Ce,pe})(S,i,o,a,u));var N=(function(T){if(!ao(T))return{};var O={};return Z(T.attributes,(function(J){if(J.name&&J.name.indexOf("data-ph-capture-attribute")===0){var z=J.name.replace("data-ph-capture-attribute-",""),H=J.value;z&&H&&Ks(H)&&(O[z]=H)}})),O})(S);ee(_,N)})),E)return{props:{},explicitNoCapture:E};if(o||(m[0].$el_text=Me(t,"a")||Me(t,"button")?fl(t):nn(t)),w){var I,F;m[0].attr__href=w;var P=(I=ur(w))==null?void 0:I.host,B=v==null||(F=v.location)==null?void 0:F.host;P&&B&&P!==B&&(f=w)}return{props:ee({$event_type:r.type,$ce_version:1},l?{}:{$elements:m},{$elements_chain:(g=m,(function(S){return S.map((A=>{var R,N,T="";if(A.tag_name&&(T+=A.tag_name),A.attr_class)for(var O of(A.attr_class.sort(),A.attr_class))T+="."+O.replace(/"/g,"");var J=b({},A.text?{text:A.text}:{},{"nth-child":(R=A.nth_child)!==null&&R!==void 0?R:0,"nth-of-type":(N=A.nth_of_type)!==null&&N!==void 0?N:0},A.href?{href:A.href}:{},A.attr_id?{attr_id:A.attr_id}:{},A.attributes),z={};return Dn(J).sort(((H,oe)=>H[0].localeCompare(oe[0]))).forEach((H=>{var oe=H[1];return z[gl(H[0].toString())]=gl(oe.toString())})),(T+=":")+Dn(z).map((H=>H[0]+'="'+H[1]+'"')).join("")})).join(";")})((function(S){return S.map((A=>{var R,N,T={text:(R=A.$el_text)==null?void 0:R.slice(0,400),tag_name:A.tag_name,href:(N=A.attr__href)==null?void 0:N.slice(0,2048),attr_class:Cp(A),attr_id:A.attr__id,nth_child:A.nth_child,nth_of_type:A.nth_of_type,attributes:{}};return Dn(A).filter((O=>O[0].indexOf("attr__")===0)).forEach((O=>T.attributes[O[0]]=O[1])),T}))})(g)))},(s=m[0])!=null&&s.$el_text?{$el_text:(n=m[0])==null?void 0:n.$el_text}:{},f&&r.type==="click"?{$external_click_url:f}:{},_)}}var Ms=se("[ExceptionAutocapture]"),Nl=()=>{},gf=se("[TracingHeaders]"),Lt=se("[Web Vitals]"),Ml=9e5,Ll="disabled",Ol="lazy_loading",Ls="awaiting_config",Pn="missing_config";se("[SessionRecording]"),se("[SessionRecording]");var mo="[SessionRecording]",at=se(mo),mf=se("[Heatmaps]");function ki(t){return te(t)&&"clientX"in t&&"clientY"in t&&he(t.clientX)&&he(t.clientY)}var An=se("[Product Tours]"),Ii=t=>{var e;return!t.config.disable_product_tours&&!((e=t.persistence)==null||!e.get_property(Vo))},vf=["$set_once","$set"],Ze=se("[SiteApps]"),Dl="Error while initializing PostHog app with config id ";function ns(t,e,s){if(D(t))return!1;switch(s){case"exact":return t===e;case"contains":var n=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/_/g,".").replace(/%/g,".*");return new RegExp(n,"i").test(t);case"regex":try{return new RegExp(e).test(t)}catch{return!1}default:return!1}}class _f{constructor(e){this.ns=new ta,this.ss=(s,n)=>this.os(s,n)&&this.ls(s,n)&&this.us(s,n)&&this.hs(s,n),this.os=(s,n)=>n==null||!n.event||s?.event===n?.event,this._instance=e,this.ds=new Set,this.vs=new Set}init(){var e,s;x((e=this._instance)==null?void 0:e._addCaptureHook)||(s=this._instance)==null||s._addCaptureHook(((n,r)=>{this.on(n,r)}))}register(e){var s,n;if(!x((s=this._instance)==null?void 0:s._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||"")}))})),(n=this._instance)!=null&&n.autocapture)){var r,i=new Set;e.forEach((o=>{var a;(a=o.steps)==null||a.forEach((l=>{l!=null&&l.selector&&i.add(l?.selector)}))})),(r=this._instance)==null||r.autocapture.setElementSelectors(i)}}on(e,s){var n;s!=null&&e.length!=0&&(this.ds.has(e)||this.ds.has(s.event))&&this.vs&&((n=this.vs)==null?void 0:n.size)>0&&this.vs.forEach((r=>{this.cs(s,r)&&this.ns.emit("actionCaptured",r.name)}))}fs(e){this.onAction("actionCaptured",(s=>e(s)))}cs(e,s){if(s?.steps==null)return!1;for(var n of s.steps)if(this.ss(e,n))return!0;return!1}onAction(e,s){return this.ns.on(e,s)}ls(e,s){if(s!=null&&s.url){var n,r=e==null||(n=e.properties)==null?void 0:n.$current_url;if(!r||typeof r!="string"||!ns(r,s.url,s.url_matching||"contains"))return!1}return!0}us(e,s){return!!this.ps(e,s)&&!!this.gs(e,s)&&!!this.ys(e,s)}ps(e,s){var n;if(s==null||!s.href)return!0;var r=this.bs(e);if(r.length>0)return r.some((a=>ns(a.href,s.href,s.href_matching||"exact")));var i,o=(e==null||(n=e.properties)==null?void 0:n.$elements_chain)||"";return!!o&&ns((i=o.match(/(?::|")href="(.*?)"/))?i[1]:"",s.href,s.href_matching||"exact")}gs(e,s){var n;if(s==null||!s.text)return!0;var r=this.bs(e);if(r.length>0)return r.some((u=>ns(u.text,s.text,s.text_matching||"exact")||ns(u.$el_text,s.text,s.text_matching||"exact")));var i,o,a,l=(e==null||(n=e.properties)==null?void 0:n.$elements_chain)||"";return!!l&&(i=(function(u){for(var c,d=[],h=/(?::|")text="(.*?)"/g;!D(c=h.exec(u));)d.includes(c[1])||d.push(c[1]);return d})(l),o=s.text,a=s.text_matching||"exact",i.some((u=>ns(u,o,a))))}ys(e,s){var n,r;if(s==null||!s.selector)return!0;var i=e==null||(n=e.properties)==null?void 0:n.$element_selectors;if(i!=null&&i.includes(s.selector))return!0;var o=(e==null||(r=e.properties)==null?void 0:r.$elements_chain)||"";if(s.selector_regex&&o)try{return new RegExp(s.selector_regex).test(o)}catch{return!1}return!1}bs(e){var s;return(e==null||(s=e.properties)==null?void 0:s.$elements)==null?[]:e?.properties.$elements}hs(e,s){return s==null||!s.properties||s.properties.length===0||id(s.properties.reduce(((n,r)=>{var i=L(r.value)?r.value.map(String):r.value!=null?[String(r.value)]:[];return n[r.key]={values:i,operator:r.operator||"exact"},n}),{}),e?.properties)}}class yf{constructor(e){var s;this._s=[],this._instance=e,this.ws=new Map,this.ks=new Map,this.xs=new Map,(s=this._instance)==null||s.onSessionId==null||s.onSessionId((n=>this.Ss(n)))}Cs(e){return!1}Ms(){return null}Ts(e){}Es(){}Is(e,s){return!!e&&id(e.propertyFilters,s?.properties)}Ps(e,s){var n=new Map;return e.forEach((r=>{var i;(i=r.conditions)==null||(i=i[s])==null||(i=i.values)==null||i.forEach((o=>{if(o!=null&&o.name){var a=n.get(o.name)||[];a.push(r.id),n.set(o.name,a)}}))})),n}Rs(e,s,n){var r=(n===As.Activation?this.ws:this.ks).get(e),i=[];return this.As((o=>{i=o.filter((a=>r?.includes(a.id)))})),i.filter((o=>{var a,l=(a=o.conditions)==null||(a=a[n])==null||(a=a.values)==null?void 0:a.find((u=>u.name===e));return this.Is(l,s)}))}register(e){var s;x((s=this._instance)==null?void 0:s._addCaptureHook)||(this.Fs(e),this.Ls(e))}Ls(e){var s=e.filter((n=>{var r,i;return((r=n.conditions)==null?void 0:r.actions)&&((i=n.conditions)==null||(i=i.actions)==null||(i=i.values)==null?void 0:i.length)>0}));s.length!==0&&(this.Os==null&&(this.Os=new _f(this._instance),this.Os.init(),this.Os.fs((n=>{this.onAction(n)}))),s.forEach((n=>{var r,i,o,a,l;n.conditions&&(r=n.conditions)!=null&&r.actions&&(i=n.conditions)!=null&&(i=i.actions)!=null&&i.values&&((o=n.conditions)==null||(o=o.actions)==null||(o=o.values)==null?void 0:o.length)>0&&((a=this.Os)==null||a.register(n.conditions.actions.values),(l=n.conditions)==null||(l=l.actions)==null||(l=l.values)==null||l.forEach((u=>{if(u&&u.name){var c=this.xs.get(u.name);c&&c.push(n.id),this.xs.set(u.name,c||[n.id])}})))})))}Fs(e){var s,n=e.filter((i=>{var o,a;return((o=i.conditions)==null?void 0:o.events)&&((a=i.conditions)==null||(a=a.events)==null||(a=a.values)==null?void 0:a.length)>0})),r=e.filter((i=>{var o,a;return((o=i.conditions)==null?void 0:o.cancelEvents)&&((a=i.conditions)==null||(a=a.cancelEvents)==null||(a=a.values)==null?void 0:a.length)>0}));n.length===0&&r.length===0||((s=this._instance)==null||s._addCaptureHook(((i,o)=>{this.onEvent(i,o)})),this.ws=this.Ps(e,As.Activation),this.ks=this.Ps(e,As.Cancellation))}onEvent(e,s){var n,r,i=this.Ds(),o=(s==null||(n=s.properties)==null?void 0:n.$survey_id)||(s==null||(r=s.properties)==null?void 0:r.$product_tour_id);if(o&&this.getActivatedIds().includes(o)){var a=this.$s(e,o);if(a==="consume")return i.info("event consumed activated item, removing it",{event:e,itemId:o}),void this.Ns([o]);if(a==="persist")return i.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,s,As.Cancellation);l.length>0&&(i.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)){i.info("event name matched",{event:e,eventPayload:s,items:this.ws.get(e)});var u=this.Rs(e,s,As.Activation);this.Hs(u.map((c=>c.id)))}}onAction(e){this.xs.has(e)&&this.Hs(this.xs.get(e)||[])}Hs(e){var s;if(e.length!==0){var n=!((s=this._instance)==null||s.get_session_id==null||!s.get_session_id()),r=[];for(var i of e)n&&this.Cs(i)?this.qs(i)&&this.Us(i):r.push(i);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((n=>n!==e));var s=this.zs();return!s.includes(e)&&(this.Ws([...s,e]),this.Vs(),!0)}Ns(e){var s=new Set(e);this._s=this._s.filter((i=>!s.has(i)));var n=this.Zs(),r=n.filter((i=>!s.has(i)));r.length!==n.length&&(this.Ws(r),r.length===0&&this.Gs()),this.js(e)}Qs(){var e,s=this.Ms();if(!s)return{};var n=(e=this._instance)==null||(e=e.persistence)==null?void 0:e.props[s];return n&&typeof n=="object"?n:{}}Us(e){if(this.Ms()){var s=this.Qs();this.Ts(b({},s,{[e]:Date.now()}))}}js(e){if(this.Ms()){var s=this.Qs(),n={},r=!1;for(var i of Object.entries(s)){var o=i[0],a=i[1];e.includes(o)?r=!0:n[o]=a}r&&(mt(n)?this.Es():this.Ts(n))}}Ks(){this.Ms()&&this.Es()}getActivationTimestamp(e){if(this.zs().includes(e)){var s=this.Qs()[e];return he(s)?s:void 0}}Zs(){var e,s=this.Js();return((e=this._instance)==null||(e=e.persistence)==null?void 0:e.props[s])||[]}zs(){var e,s,n=this.Zs();if(n.length===0)return[];var r=(e=this._instance)==null||(e=e.persistence)==null?void 0:e.props[this.Ys()],i=(s=this._instance)==null||s.get_session_id==null?void 0:s.get_session_id();return i&&r===i?n:[]}Vs(){var e,s=(e=this._instance)==null||e.get_session_id==null?void 0:e.get_session_id();s&&this.Xs(s)}Gs(){this.ta()}Ss(e){var s,n=(s=this._instance)==null||(s=s.persistence)==null?void 0:s.props[this.Ys()];if(n&&n!==e){var r=this.Zs(),i=this.Qs();r.length>0&&(this.Ws([]),r.filter((o=>he(i[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 wf extends yf{constructor(e){super(e)}Js(){return Qi}Ys(){return Mn}Ms(){return Ln}Ts(e){var s;(s=this._instance)==null||(s=s.persistence)==null||s.register({[Ln]:e})}Es(){var e;(e=this._instance)==null||(e=e.persistence)==null||e.unregister(Ln)}Cs(e){var s,n;this.As((i=>{n=i.find((o=>o.id===e))}));var r=(s=n)==null||(s=s.appearance)==null?void 0:s.surveyPopupDelaySeconds;return he(r)&&r>0}ra(){return ft.SHOWN}As(e){var s;(s=this._instance)==null||s.getSurveys(e)}Bs(e){var s;(s=this._instance)==null||s.cancelPendingSurvey(e)}Ds(){return q}Ws(e){var s;(s=this._instance)==null||(s=s.persistence)==null||s.register({[Qi]:e})}Xs(e){var s;(s=this._instance)==null||(s=s.persistence)==null||s.register({[Mn]:e})}ta(){var e;(e=this._instance)==null||(e=e.persistence)==null||e.unregister(Mn)}ea(){return!1}$s(e,s){var n;this.As((i=>{n=i.find((o=>o.id===s))}));var r=!n||(function(i){var o;return od(i)&&!((o=i.conditions)==null||(o=o.events)==null||!o.repeatedActivation)||i.schedule==="always"})(n);return r?e===ft.SHOWN?"consume":"ignore":e===ft.SHOWN?"persist":e===ft.DISMISSED||e===ft.SENT?"consume":"ignore"}getSurveys(){return this.getActivatedIds()}getEventToSurveys(){return this.getEventToItemsMap()}}var $n="SDK is not enabled or survey functionality is not yet loaded",Bl="Disabled. Not loading surveys.",bf=v!=null&&v.location?dr(v.location.hash,"__posthog")||dr(location.hash,"state"):null,jl="_postHogToolbarParams",Ul=se("[Toolbar]"),Hl=se("[FeatureFlags]");class Ef{constructor(e,s){s===void 0&&(s=!1),this.na=!1,this.update(e,s)}update(e,s){this.sa=((n,r)=>{var i,o,a,l;return{bootstrap:{featureFlags:(i=n.bootstrap)==null?void 0:i.featureFlags,featureFlagPayloads:(o=n.bootstrap)==null?void 0:o.featureFlagPayloads},remoteRequestsDisabled:r,featureFlagsDisabled:!!n.advanced_disable_feature_flags,onlyEvaluateSurveyFeatureFlags:!!n.advanced_only_evaluate_survey_feature_flags,deduplicateCallsPerSession:!!n.advanced_feature_flags_dedup_per_session,cacheTtlMs:n.feature_flag_cache_ttl_ms,requestTimeoutMs:n.feature_flag_request_timeout_ms,compression:n.disable_compression?"none":"base64",evaluationContexts:(a=(l=n.evaluation_contexts)!==null&&l!==void 0?l:n.evaluation_environments)!==null&&a!==void 0?a:[],flagKeys:L(n.flag_keys)?n.flag_keys:void 0}})(e,s),!e.evaluation_environments||e.evaluation_contexts||this.na||(Hl.warn("evaluation_environments is deprecated. Use evaluation_contexts instead. evaluation_environments will be removed in a future version."),this.na=!0),x(e.flag_keys)||L(e.flag_keys)||Hl.error("Invalid flag_keys found:",e.flag_keys,"Expected array of non-empty strings")}get(){return this.sa}}var Wl=se("[FeatureFlags]"),Ot=se("[FeatureFlags]",{debugEnabled:!0}),Ci=`" failed. Feature flags didn't load in time.`,zl="connection_error",ql=t=>{for(var e={},s=0;t.length>s;s++)e[t[s]]=!0;return e},Vl=t=>{var e={};for(var s of Dn(t||{})){var n=s[1];n&&(e[s[0]]=n)}return e},Xe=se("[Error tracking]"),Gl="Refusing to render web experiment since the viewer is a likely bot",Sf={icontains:(t,e)=>e.toLowerCase().indexOf(t.toLowerCase())>-1,not_icontains:(t,e)=>e.toLowerCase().indexOf(t.toLowerCase())===-1,regex:(t,e)=>fr(e,t),not_regex:(t,e)=>!fr(e,t),exact:(t,e)=>e===t,is_not:(t,e)=>e!==t};class ye{get Ne(){return this._instance.config}constructor(e){var s=this;this.getWebExperimentsAndEvaluateDisplayLogic=function(n){n===void 0&&(n=!1),s.getWebExperiments((r=>{ye.aa("retrieved web experiments from the server"),s.oa=new Map,r.forEach((i=>{if(i.feature_flag_key){var o;s.oa&&(ye.aa("setting flag key ",i.feature_flag_key," to web experiment ",i),(o=s.oa)==null||o.set(i.feature_flag_key,i));var a=s._instance.getFeatureFlag(i.feature_flag_key);W(a)&&i.variants[a]&&s.la(i.name,a,i.variants[a].transforms)}else if(i.variants)for(var l in i.variants){var u=i.variants[l];ye.ua(u,s._instance)&&s.la(i.name,l,u.transforms)}}))}),n)},this._instance=e,this._instance.onFeatureFlags((n=>{this.onFeatureFlags(n)}))}initialize(){}onFeatureFlags(e){if(this._is_bot())ye.aa(Gl);else if(!this.Ne.disable_web_experiments){if(D(this.oa))return this.oa=new Map,this.loadIfEnabled(),void this.previewWebExperiment();ye.aa("applying feature flags",e),e.forEach((s=>{var n;if(this.oa&&(n=this.oa)!=null&&n.has(s)){var r,i=this._instance.getFeatureFlag(s),o=(r=this.oa)==null?void 0:r.get(s);i&&o!=null&&o.variants[i]&&this.la(o.name,i,o.variants[i].transforms)}}))}}previewWebExperiment(){var e=ye.getWindowLocation();if(e!=null&&e.search){var s=ms(e?.search,"__experiment_id"),n=ms(e?.search,"__experiment_variant");s&&n&&(ye.aa("previewing web experiments "+s+" && "+n),this.getWebExperiments((r=>{this.ha(parseInt(s),n,r)}),!1,!0))}}loadIfEnabled(){this.Ne.disable_web_experiments||this.getWebExperimentsAndEvaluateDisplayLogic()}getWebExperiments(e,s,n){if(this.Ne.disable_web_experiments&&!n)return e([]);var r=this._instance.get_property("$web_experiments");if(r&&!s)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:i=>e(i.statusCode===200&&i.json&&i.json.experiments||[])})}ha(e,s,n){var r=n.filter((i=>i.id===e));r&&r.length>0&&(ye.aa("Previewing web experiment ["+r[0].name+"] with variant ["+s+"]"),this.la(r[0].name,s,r[0].variants[s].transforms))}static ua(e,s){return!D(e.conditions)&&ye.da(e,s)&&ye.va(e)}static da(e,s){var n;if(D(e.conditions)||D((n=e.conditions)==null?void 0:n.url))return!0;var r=ye.getWindowLocation();if(r){var i,o,a,l=Eu(s,r.href);return(i=e.conditions)==null||!i.url||Sf[(o=(a=e.conditions)==null?void 0:a.urlMatchType)!==null&&o!==void 0?o:"icontains"](e.conditions.url,l)}return!1}static getWindowLocation(){return v?.location}static va(e){var s;if(D(e.conditions)||D((s=e.conditions)==null?void 0:s.utm))return!0;var n=Ou();if(n.utm_source){var r,i,o,a,l,u,c,d,h=(r=e.conditions)==null||(r=r.utm)==null||!r.utm_campaign||((i=e.conditions)==null||(i=i.utm)==null?void 0:i.utm_campaign)==n.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)==n.utm_source,f=(l=e.conditions)==null||(l=l.utm)==null||!l.utm_medium||((u=e.conditions)==null||(u=u.utm)==null?void 0:u.utm_medium)==n.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)==n.utm_term;return h&&f&&g&&p}return!1}static aa(e){for(var s=arguments.length,n=new Array(s>1?s-1:0),r=1;s>r;r++)n[r-1]=arguments[r];k.info("[WebExperiments] "+e,n)}la(e,s,n){this._is_bot()?ye.aa(Gl):s!=="control"?n.forEach((r=>{if(r.selector){var i;ye.aa("applying transform of variant "+s+" for experiment "+e+" ",r);var o=(i=document)==null?void 0:i.querySelectorAll(r.selector);o?.forEach((a=>{var l=a;r.html&&(l.innerHTML=r.html),r.css&&l.setAttribute("style",r.css)}))}})):ye.aa("Control variants leave the page unmodified.")}_is_bot(){return ke&&this._instance?sd(ke,this.Ne.custom_blocked_useragents):void 0}}var Ue=se("[Conversations]"),Dt="Conversations not available yet.",Kl="console",dd="__posthogHandledLogsRequestError",Fi=(t,e)=>{var s=t instanceof Error?t:new Error(e);return s[dd]=!0,s},Jl=t=>!!t&&typeof t=="object"&&t[dd]===!0,Tr={featureFlags:class{constructor(t){this.name="featureFlags",this.ca=!1,this.featureFlagEventHandlers=[],this.rt=Wl,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 Ef(t.config,t.Qi()),this.Ta=this.Ea)}updateConfig(t,e){var s;(s=this.Ea)==null||s.update(t,e)}setup(t){return this.Ia=t,this.rt=t.logger.createLogger("[FeatureFlags]"),s=()=>{this.Ia===t&&(this.Ia=void 0,this.nn=t,this.Pa(t))},(e=t.kv.initialize())!=null&&e.then?e.then(s):s();var e,s}Pa(t){if(this.nn===t)return v&&re(v,"online",this.Ca),this.Ra=t.registerDynamicEventProperties((()=>this.Aa()?this.fa:this.pa)),this.Fa(),this.initialize()}destroy(){v?.removeEventListener("online",this.Ca)}dispose(){var t;this.ba++,this.wa=!1,this.Ia=void 0,this.nn&&(this.La(),(t=this.Ra)==null||t.dispose(),this.Ra=void 0,this.ga=[],v?.removeEventListener("online",this.Ca),this.nn=void 0)}get Ne(){return this.Ta.get()}Oa(t){var e;return(e=this.nn)==null?void 0:e.kv.get(t)}F(t){this.Da((()=>{var e;return(e=this.nn)==null?void 0:e.kv.set(t)}))}q(t){this.Da((()=>{var e;return(e=this.nn)==null?void 0:e.kv.remove(t)}))}Da(t){try{t()}catch(e){this.rt.error("Failed to update feature flag persistence",e)}}Fa(){var t={};for(var e of[Us,Hs,Nn,et]){var s=this.Oa(e);x(s)||(t[e]=s)}this.fa=t;var n=b({},t),r=this.Oa(Bt);if(r)for(var i of Object.entries(r))n["$feature/"+i[0]]=i[1];this.pa=n}Aa(){var t=this.Ne.cacheTtlMs;if(!t||0>=t)return!1;var e=this.Oa(Gs);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 s=e&&typeof e=="string"&&e.trim().length>0;return s||this.rt.error("Invalid evaluation context found:",e,"Expected non-empty string"),s})):[]}qa(){var t=this.Ne.flagKeys;if(!x(t))return t.filter((e=>{var s=e&&typeof e=="string"&&e.trim().length>0;return s||this.rt.error("Invalid flag key found:",e,"Expected non-empty string"),s}))}initialize(){var t,e,s=this.Ne,n=(t=(e=s.bootstrap)==null?void 0:e.featureFlags)!==null&&t!==void 0?t:{};if(Object.keys(n).length){var r,i,o=(r=(i=s.bootstrap)==null?void 0:i.featureFlagPayloads)!==null&&r!==void 0?r:{},a=Object.keys(n).filter((u=>!!n[u])).reduce(((u,c)=>(u[c]=n[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,s){var n,r,i=s!=null&&s.merge&&(n=this.Oa(Bt))!==null&&n!==void 0?n:{},o=s!=null&&s.merge&&(r=this.Oa(Hs))!==null&&r!==void 0?r:{},a=b({},i,t),l=b({},o,e),u={};for(var c of Object.entries(a)){var d=c[0],h=c[1];u[d]={key:d,enabled:Ua(h),variant:Ha(h),reason:void 0,metadata:x(l?.[d])?void 0:{id:0,version:void 0,description:void 0,payload:l[d]}}}this.ja({flags:u})}get hasLoadedFlags(){return this.ma}getFlags(){return Object.keys(this.getFlagVariants())}getFlagsWithDetails(){var t=this.Oa(Zi),e=this.Oa(et),s=this.Oa(jt);if(!s&&!e)return t||{};var n=ee({},t||{}),r=[...new Set([...Object.keys(s||{}),...Object.keys(e||{})])];for(var i of r){var o,a,l=n[i],u=e?.[i],c=x(u)?(o=l?.enabled)!==null&&o!==void 0&&o:!!u,d=x(u)?l?.variant:typeof u=="string"?u:void 0,h=s?.[i],p=b({},l,{enabled:c,variant:c?d??l?.variant:void 0});c!==l?.enabled&&(p.original_enabled=l?.enabled),d!==l?.variant&&(p.original_variant=l?.variant),h&&(p.metadata=b({},l?.metadata,{payload:h,original_payload:l==null||(a=l.metadata)==null?void 0:a.payload})),n[i]=p}return this.ca||(this.rt.warn(" Overriding feature flag details!",{flagDetails:t,overriddenPayloads:s,finalDetails:n}),this.ca=!0),n}getAllFeatureFlags(){var t=this.getFlagVariants(),e=this.getFlagPayloads();return Object.keys(t).map((s=>{var n=t[s];return{key:s,enabled:Ua(n),variant:Ha(n),payload:ja(e[s])}}))}getFlagVariants(){var t=this.Oa(Bt),e=this.Oa(et);if(!e)return t||{};for(var s=ee({},t||{}),n=Object.keys(e),r=0;n.length>r;r++)s[n[r]]=e[n[r]];return this.ca||(this.rt.warn(" Overriding feature flags!",{enabledFlags:t,overriddenFlags:e,finalFlags:s}),this.ca=!0),s}getFlagPayloads(){var t=this.Oa(Hs),e=this.Oa(jt);if(!e)return t||{};for(var s=ee({},t||{}),n=Object.keys(e),r=0;n.length>r;r++)s[n[r]]=e[n[r]];return this.ca||(this.rt.warn(" Overriding feature flag payloads!",{flagPayloads:t,overriddenPayloads:e,finalPayloads:s}),this.ca=!0),s}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(Wt)}Ha(t){this.La();var e=this.nn;if(e&&!this.Ne.remoteRequestsDisabled&&!this.Ma())if(this.ya)this.wa=!0;else{var s={token:e.projectToken,distinct_id:e.distinctId,groups:e.groups,$anon_distinct_id:this.$anon_distinct_id,person_properties:b({},e.initialPersonProperties,this.Oa(ct)||{},{$lib:e.library.name,$lib_version:e.library.version}),group_properties:this.Oa(Ut),timezone:Wu()};x(e.deviceId)||(s.$device_id=e.deviceId),(t!=null&&t.disableFlags||this.Ne.featureFlagsDisabled)&&(s.disable_flags=!0);var n=this.Na();n.length&&(s.evaluation_contexts=n);var r=this.qa();x(r)||(s.flag_keys=r);var i=this.Ne.onlyEvaluateSurveyFeatureFlags,o="/flags/?v=2"+(i?"&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({[On]:[zl]}),this.rt.error("Feature flag request failed",c)),l()};try{e.sendRequest(o,{target:"flags",method:"POST",body:s,compression:this.Ne.compression==="base64"?xe.Base64:void 0,sentAt:"body",timeoutMs:this.Ne.requestTimeoutMs}).then((c=>{var d,h,p=(d=c.json)!==null&&d!==void 0?d:{},f=c.statusCode!==200;if(this.ya=!1,a===this.ba){if(this.Ua(c.statusCode),f||this.wa||(this.$anon_distinct_id=void 0),!s.disable_flags||this.wa){this.ka=!f;var g=[];c.error?g.push(c.error instanceof Error&&c.error.name==="AbortError"?"timeout":c.error instanceof Error?zl:"unknown_error"):c.statusCode!==200&&g.push("api_error_"+c.statusCode),p.errorsWhileComputingFlags&&g.push("errors_while_computing_flags");var m=!((h=p.quotaLimited)==null||!h.includes("feature_flags"));m&&g.push("quota_limited"),this.F({[On]: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."):s.disable_flags||this.ja(p,f,{partialResponse:i}),l()}}else l()})).catch(u)}catch(c){u(c)}}}Ma(){return Mu(this.Sa,3)}Ua(t){this.Sa=Lu(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 s;if(e===void 0&&(e={}),!e.fresh||this.ka)if(this.ma||this.getFlags()&&this.getFlags().length>0){if(!this.$a()){var n=this.getFeatureFlagResult(t,e);return(s=n?.variant)!==null&&s!==void 0?s:n?.enabled}}else this.rt.warn('getFeatureFlag for key "'+t+Ci)}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 s,n=this.getFlagVariants(),r=t in n,i=n[t],o=this.getFlagPayloads()[t],a=String(i),l=this.Oa(Nn)||void 0,u=this.Oa(Gs)||void 0,c=this.Oa(Wt)||{};if(this.Ne.deduplicateCallsPerSession){var d,h=(d=this.nn)==null?void 0:d.session.sessionId,p=this.Oa(zs);h&&h!==p&&(c={},s=h)}if(e.send_event||!("send_event"in e))if(t in c&&c[t].includes(a))s&&this.F({[Wt]:c,[zs]:s});else{var f,g,m,_,w,E,I,F,P,B;L(c[t])?c[t].push(a):c[t]=[a],this.F(b({[Wt]:c},s?{[zs]:s}:{}));var S=this.getFeatureFlagDetails(t),A=[...(f=this.Oa(On))!==null&&f!==void 0?f:[]];x(i)&&A.push("flag_missing");var R={$feature_flag:t,$feature_flag_response:i,$feature_flag_payload:o||null,$feature_flag_request_id:l,$feature_flag_evaluated_at:u,$feature_flag_bootstrapped_response:((g=this.Ne.bootstrap)==null||(g=g.featureFlags)==null?void 0:g[t])||null,$feature_flag_bootstrapped_payload:((m=this.Ne.bootstrap)==null||(m=m.featureFlagPayloads)==null?void 0:m[t])||null,$used_bootstrap_value:!this.ka};x(S==null||(_=S.metadata)==null?void 0:_.has_experiment)||(R.$feature_flag_has_experiment=S.metadata.has_experiment),x(S==null||(w=S.metadata)==null?void 0:w.version)||(R.$feature_flag_version=S.metadata.version);var N,T=(E=S==null||(I=S.reason)==null?void 0:I.description)!==null&&E!==void 0?E:S==null||(F=S.reason)==null?void 0:F.code;T&&(R.$feature_flag_reason=T),S!=null&&(P=S.metadata)!=null&&P.id&&(R.$feature_flag_id=S.metadata.id),x(S?.original_variant)&&x(S?.original_enabled)||(R.$feature_flag_original_response=x(S.original_variant)?S.original_enabled:S.original_variant),S!=null&&(B=S.metadata)!=null&&B.original_payload&&(R.$feature_flag_original_payload=S==null||(N=S.metadata)==null?void 0:N.original_payload),A.length&&(R.$feature_flag_error=A.join(",")),this.za(R)}else s&&this.F({[Wt]:c,[zs]:s});if(r)return{key:t,enabled:!!i,variant:typeof i=="string"?i:void 0,payload:ja(o)}}}else this.rt.warn('getFeatureFlagResult for key "'+t+Ci)}za(t){try{var e;(e=this.nn)==null||e.capture("$feature_flag_called",t).catch((s=>{this.rt.error("Failed to capture feature flag call",s)}))}catch(s){this.rt.error("Failed to capture feature flag call",s)}}getRemoteConfigPayload(t,e){this.Wa(t,e)}Wa(t,e){var s=this;return X((function*(){var n=s.nn;if(n){var r={distinct_id:n.distinctId,token:n.projectToken,person_properties:{$lib:n.library.name,$lib_version:n.library.version}},i=s.Na();i.length&&(r.evaluation_contexts=i);var o,a=s.qa();x(a)||(r.flag_keys=a);try{var l,u=(l=(yield n.sendRequest("/flags/?v=2",{target:"flags",method:"POST",body:r,compression:s.Ne.compression==="base64"?xe.Base64:void 0,sentAt:"body",timeoutMs:s.Ne.requestTimeoutMs})).json)==null?void 0:l.featureFlagPayloads;o=u?.[t]||void 0}catch(c){return void s.rt.error("Remote config feature flag request failed",c)}try{e(o)}catch(c){s.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+Ci),e.defaultValue;var s=this.getFeatureFlag(t,e);return x(s)?e.defaultValue:!!s}addFeatureFlagsHandler(t){this.featureFlagEventHandlers.push(t)}removeFeatureFlagsHandler(t){this.featureFlagEventHandlers=this.featureFlagEventHandlers.filter((e=>e!==t))}receivedFeatureFlags(t,e,s){this.ja(t,e,s)}ja(t,e,s){if(this.nn){this.ma=!0;var n=(function(r,i,o,a,l,u){i===void 0&&(i={}),o===void 0&&(o={}),a===void 0&&(a={}),u===void 0&&(u=Wl);var c=((P,B)=>{var S=P.flags;return S?b({},P,{featureFlags:Object.fromEntries(Object.keys(S).map((A=>{var R;return[A,(R=S[A].variant)!==null&&R!==void 0?R:S[A].enabled]}))),featureFlagPayloads:Object.fromEntries(Object.keys(S).filter((A=>S[A].enabled)).filter((A=>{var R;return(R=S[A].metadata)==null?void 0:R.payload})).map((A=>{var R;return[A,(R=S[A].metadata)==null?void 0:R.payload]})))}):(P.featureFlags&&B.warn("Using an older version of the feature flags endpoint. Please upgrade your PostHog server to the latest version"),P)})(r,u),d=c.flags,h=c.featureFlags,p=c.featureFlagPayloads;if(h){var f=r.requestId,g=r.evaluatedAt;if(L(h)){u.warn("v1 of the feature flags endpoint is deprecated. Please use the latest version.");var m={};if(h)for(var _=0;h.length>_;_++)m[h[_]]=!0;return{[Us]:h,[Bt]:m,[sr]:!1}}var w=h,E=p,I=d;if(l!=null&&l.partialResponse)w=b({},i,w),E=b({},o,E),I=b({},a,I);else if(r.errorsWhileComputingFlags)if(d){var F=new Set(Object.keys(d).filter((P=>{var B;return!((B=d[P])!=null&&B.failed)})));w=b({},i,Object.fromEntries(Object.entries(w).filter((P=>F.has(P[0]))))),E=b({},o,Object.fromEntries(Object.entries(E||{}).filter((P=>F.has(P[0]))))),I=b({},a,Object.fromEntries(Object.entries(I||{}).filter((P=>F.has(P[0])))))}else w=b({},i,w),E=b({},o,E),I=b({},a,I);return b({[Us]:Object.keys(Vl(w)),[Bt]:w||{},[Hs]:E||{},[Zi]:I||{},[sr]:r.minimalFlagCalledEvents===!0},f?{[Nn]:f}:{},g?{[Gs]:g}:{})}})(t,this.getFlagVariants(),this.getFlagPayloads(),this.getFlagsWithDetails(),s,this.rt);n&&this.F(n),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([et,jt]),this.Va(),void Ot.info("All overrides cleared");if(L(t))return this.F({[et]:ql(t)}),this.Va(),void Ot.info("Flag overrides set",{flags:t});if(t&&typeof t=="object"&&("flags"in t||"payloads"in t)){var e,s=t;this.ca=!!((e=s.suppressWarning)!==null&&e!==void 0&&e);var n={},r=s.flags,i=s.payloads;return r&&(n[et]=L(r)?ql(r):r),i&&(n[jt]=i),Object.keys(n).length&&this.F(n),r===!1&&i===!1?this.q([et,jt]):r===!1?this.q(et):i===!1&&this.q(jt),this.Va(),r===!1?Ot.info("Flag overrides cleared"):r&&Ot.info("Flag overrides set",{flags:r}),void(i===!1?Ot.info("Payload overrides cleared"):i&&Ot.info("Payload overrides set",{payloads:i}))}if(t&&typeof t=="object")return this.F({[et]:t}),this.Va(),void Ot.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(),s=e.flags,n=e.flagVariants;try{t(s,n)}catch(r){this.rt.error("Error while running feature flags callback",r)}}return()=>this.removeFeatureFlagsHandler(t)}updateEarlyAccessFeatureEnrollment(t,e,s){var n=(this.Oa(Tn)||[]).find((l=>l.flagKey===t)),r={["$feature_enrollment/"+t]:e},i={$feature_flag:t,$feature_enrollment:e,$set:r};n&&(i.$early_access_feature_name=n.name),s&&(i.$feature_enrollment_stage=s);var o=b({},this.getFlagVariants(),{[t]:e});this.F({[Us]:Object.keys(Vl(o)),[Bt]:o,[ct]:b({},this.Oa(ct)||{},r)}),this.Va();try{var a;(a=this.nn)==null||a.capture("$feature_enrollment_update",i).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,s){e===void 0&&(e=!1);var n=this.Oa(Tn);!n||e?this.Qa(t,s):t(n)}Qa(t,e){var s=this;return X((function*(){var n=s.nn;if(n){var r,i=e?"&"+e.map((a=>"stage="+a)).join("&"):"";try{var o=yield n.sendRequest("/api/early_access_features/?token="+n.projectToken+i,{target:"api",method:"GET",sentAt:"query"});if(!o.json)return;s.F({[Tn]:r=o.json.earlyAccessFeatures})}catch(a){return void s.rt.error("Early access feature request failed",a)}try{t(r)}catch(a){s.rt.error("Early access feature callback failed",a)}}}))()}Ga(){var t=this.getFlags(),e=this.getFlagVariants();return{flags:t.filter((s=>e[s])),flagVariants:Object.keys(e).filter((s=>e[s])).reduce(((s,n)=>(s[n]=e[n],s)),{})}}Va(t){this.Fa();var e=this.Ga(),s=e.flags,n=e.flagVariants;this.featureFlagEventHandlers.forEach((r=>{try{r(s,n,{errorsLoading:t})}catch(i){this.rt.error("Error while running feature flags callback",i)}}))}setPersonPropertiesForFlags(t,e){e===void 0&&(e=!0),this.Ka(t,e)}Ka(t,e){e===void 0&&(e=!0);var s=this.Oa(ct)||{},n=t?.$set||(t!=null&&t.$set_once?{}:t),r=t?.$set_once,i={};if(r)for(var o in r)({}).hasOwnProperty.call(r,o)&&(o in s||(i[o]=r[o]));this.F({[ct]:b({},s,i,n)}),e&&this.reloadFeatureFlags()}unsetPersonPropertiesForFlags(t,e){e===void 0&&(e=!0);var s=b({},this.Oa(ct)||{});t.forEach((n=>{delete s[n]})),this.F({[ct]:s}),e&&this.reloadFeatureFlags()}resetPersonPropertiesForFlags(t){t===void 0&&(t=!0),this.q(ct),t&&this.reloadFeatureFlags()}setGroupPropertiesForFlags(t,e){e===void 0&&(e=!0);var s=this.Oa(Ut)||{},n=b({},s);for(var r of Object.keys(t))n[r]=b({},s[r],t[r]);this.F({[Ut]:n}),e&&this.reloadFeatureFlags()}resetGroupPropertiesForFlags(t){if(t){var e=this.Oa(Ut)||{};this.F({[Ut]:b({},e,{[t]:{}})})}else this.q(Ut)}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}}},xf={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===Ls||this.Ya===Pn?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=Ll,this.Xa=void 0,this.eo=!1,this.io=(()=>{var e;if(C==null||!C.visibilityState||C.visibilityState==="visible")return!0;var s=v==null||(e=v.performance)==null||e.getEntriesByType==null?void 0:e.getEntriesByType("visibility-state");return!(s!=null&&s.length)||s.some((n=>n.name==="visible"))})(),this.Ie=()=>{var e;C?.visibilityState==="visible"&&(this.io=!0,(e=this.Ja)==null||e.setDocumentWasEverVisible==null||e.setDocumentWasEverVisible(!0))},this._instance=t,!this._instance.sessionManager)throw at.error("started without valid sessionManager"),new Error(mo+" started without valid sessionManager. This is a bug.");if(this.Ne.cookieless_mode===ht)throw new Error(mo+' cannot be used with cookieless_mode="always"');C!=null&&C.addEventListener&&re(C,"visibilitychange",this.Ie)}initialize(){this.startIfEnabledOrStop()}dispose(){this.eo=!0,C==null||C.removeEventListener==null||C.removeEventListener("visibilitychange",this.Ie),this.stopRecording()}get ro(){var t,e=!((t=this._instance.get_property(qt))==null||!t.enabled),s=!this.Ne.disable_session_recording,n=this.Ne.disable_session_recording||this._instance.consent.isOptedOut();return v&&e&&s&&!n}startIfEnabledOrStop(t){var e;if(!(this.eo||this.ro&&(e=this.Ja)!=null&&e.isStarted)){var s=!x(Object.assign)&&!x(Array.from);this.ro&&s?(this.no(t),at.info("starting")):(this.Ya=Ll,this.stopRecording())}}no(t){var e,s,n;this.ro&&(this.Ya!==Ls&&this.Ya!==Pn&&(this.Ya=Ol),$!=null&&(e=$.__PosthogExtensions__)!=null&&(e=e.rrweb)!=null&&e.record&&(s=$.__PosthogExtensions__)!=null&&s.initSessionRecording?this.so(t):(n=$.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,this.ao,(r=>{if(r)return at.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(Go),(e=this.Mr)==null||e.unregister(du)}uo(t,e){if(D(t))return null;var s,n=he(t)?t:parseFloat(t);return typeof(s=n)!="number"||!Number.isFinite(s)||0>s||s>1?(at.warn(e+" must be between 0 and 1. Ignoring invalid value:",t),null):n}ho(t){if(this.Mr){var e,s,n=this.Mr,r=()=>{var i,o=t.sessionRecording===!1?void 0:t.sessionRecording,a=this.uo((i=this.Ne.session_recording)==null?void 0:i.sampleRate,"session_recording.sampleRate"),l=this.uo(o?.sampleRate,"remote config sampleRate"),u=a??l;D(u)&&this.lo();var c=o?.minimumDurationMilliseconds;n.register({[qt]:b({cache_timestamp:Date.now(),enabled:!!o},o,{networkPayloadCapture:b({capturePerformance:t.capturePerformance},o?.networkPayloadCapture),canvasRecording:{enabled:o?.recordCanvas,fps:o?.canvasFps,quality:o?.canvasQuality},sampleRate:u,minimumDurationMilliseconds:x(c)?null:c,endpoint:o?.endpoint,triggerMatchType:o?.triggerMatchType,masking:o?.masking,urlTriggers:o?.urlTriggers,version:o?.version,triggerGroups:o?.triggerGroups})})};r(),(e=this.Xa)==null||e.call(this),this.Xa=(s=this._instance.sessionManager)==null?void 0:s.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===Ls&&(this.Ya=Pn,at.warn("config refresh failed, recording will not start until page reload")),void this.startIfEnabledOrStop())}log(t,e){var s;e===void 0&&(e="log"),(s=this.Ja)!=null&&s.log?this.Ja.log(t,e):at.warn("log called before recorder was ready")}get ao(){var t,e,s=(t=this._instance)==null||(t=t.persistence)==null?void 0:t.get_property(qt);return(s==null||(e=s.scriptConfig)==null?void 0:e.script)||"lazy-recorder"}do(){var t,e=this._instance.get_property(qt);if(!e)return!1;try{t=typeof e=="object"?e:JSON.parse(e)}catch(s){return at.warn("persisted remote config for session recording is invalid and will be ignored",s),!1}return!D(t.cache_timestamp)&&36e5>=Date.now()-t.cache_timestamp}so(t){var e,s,n;if(!this.eo){if((e=$.__PosthogExtensions__)==null||!e.initSessionRecording)return at.warn("Called on script loaded before session recording is available. This can be caused by adblockers."),void this._instance.register_for_session({[yu]:!0});var r;if(this.Ja||(this.Ja=(r=$.__PosthogExtensions__)==null?void 0:r.initSessionRecording(this._instance,this.io),this.Ja._forceAllowLocalhostNetworkCapture=this._forceAllowLocalhostNetworkCapture),!this.do())return this.Ya===Pn||this.Ya===Ls?void 0:(this.Ya=Ls,at.info("persisted remote config is stale, requesting fresh config before starting"),void new zu(this._instance).load());this.Ya=Ol,(s=(n=this.Ja).setDocumentWasEverVisible)==null||s.call(n,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({[pu]:!0}),(t=this.Ja)==null||t.overrideLinkedFlag()}overrideSampling(){var t,e;this.Ja||(e=this.Mr)==null||e.register({[hu]:!0}),(t=this.Ja)==null||t.overrideSampling()}overrideTrigger(t){var e,s;this.Ja||(s=this.Mr)==null||s.register({[t==="url"?fu:gu]:!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 s;return!((s=this.Ja)==null||!s.tryAddCustomEvent(t,e))}}},kf={autocapture:class{constructor(t){this.vo=!1,this.co=null,this.fo=!1,this.po=!1,this.instance=t,this.rageclicks=new Tl(t.config.rageclick),this.mo=null}initialize(){this.startIfEnabled()}get Ne(){var t,e,s=te(this.instance.config.autocapture)?this.instance.config.autocapture:{};return s.url_allowlist=(t=s.url_allowlist)==null?void 0:t.map((n=>new RegExp(n))),s.url_ignorelist=(e=s.url_ignorelist)==null?void 0:e.map((n=>new RegExp(n))),s}yo(){if(this.isBrowserSupported()){if(v&&C){var t=s=>{s=s||v?.event;try{this.bo(s)}catch(n){Si.error("Failed to capture event",n)}};if(re(C,"submit",t,{capture:!0}),re(C,"change",t,{capture:!0}),re(C,"click",t,{capture:!0}),this.Ne.capture_copied_text){var e=s=>{s=s||v?.event;try{this.bo(s,Ei)}catch(n){Si.error("Failed to capture copy/cut event",n)}};re(C,"copy",e,{capture:!0}),re(C,"cut",e,{capture:!0})}}}else Si.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 s=e.autocapture_opt_out;Ke(s)&&(this.instance.persistence&&this.instance.persistence.register({[zi]:s}),this.co=s),this.startIfEnabled()}else this.startIfEnabled()}setElementSelectors(t){this.mo=t}getElementSelectors(t){var e,s=[];return(e=this.mo)==null||e.forEach((n=>{var r=C?.querySelectorAll(n);r?.forEach((i=>{t===i&&s.push(n)}))})),s}get isEnabled(){var t,e,s=(t=this.instance.persistence)==null?void 0:t.props[zi],n=this.co,r=this.instance.Qi()&&!this.fo;if($e(n)&&!Ke(s)&&!r)return!1;var i=(e=this.co)!==null&&e!==void 0?e:!!s;return!!this.instance.config.autocapture&&!i}bo(t,e){if(e===void 0&&(e="$autocapture"),this.isEnabled){var s,n=ui(t);xu(n)&&(n=n.parentNode||null),e==="$autocapture"&&t.type==="click"&&t instanceof MouseEvent&&this.instance.config.rageclick&&(s=this.rageclicks)!=null&&s.isRageClick(t.clientX,t.clientY,t.timeStamp||new Date().getTime())&&cl(n,this.instance.config.rageclick)&&this.bo(t,"$rageclick");var r=e===Ei;if(n&&(function(d,h,p,f,g,m){var _;if(!v||Xo(d)||p!=null&&p.url_allowlist&&!ol(p.url_allowlist,m)||p!=null&&p.url_ignorelist&&ol(p.url_ignorelist,m))return!1;if(p!=null&&p.dom_event_allowlist){var w=p.dom_event_allowlist;if(w&&!w.some((S=>h.type===S)))return!1}var E=Au(d,f),I=E.parentIsUsefulElement,F=E.targetElementList;if(!(function(S,A){var R=A?.element_allowlist;if(x(R))return!0;var N,T=function(J){if(R.some((z=>J.tagName.toLowerCase()===z)))return{v:!0}};for(var O of S)if(N=T(O))return N.v;return!1})(F,p)||!oo(F,p?.css_selector_allowlist)||oo(F,(_=p?.css_selector_ignorelist)!==null&&_!==void 0?_:bp))return!1;try{var P=v.getComputedStyle(d);if(P&&P.getPropertyValue("cursor")==="pointer"&&h.type==="click")return!0}catch{}var B=d.tagName.toLowerCase();switch(B){case"html":return!1;case"form":return(g||["submit"]).indexOf(h.type)>=0;case"input":case"select":case"textarea":return(g||["change","click"]).indexOf(h.type)>=0;default:return I?(g||["click"]).indexOf(h.type)>=0:(g||["click"]).indexOf(h.type)>=0&&(Zo.indexOf(B)>-1||d.getAttribute("contenteditable")==="true")}})(n,t,this.Ne,r,r?["copy","cut"]:void 0,this.instance)){var i=ff(n,{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=i.props;if(i.explicitNoCapture)return!1;var a=this.getElementSelectors(n);if(a&&a.length>0&&(o.$element_selectors=a),e===Ei){var l,u=Cu(v==null||(l=v.getSelection())==null?void 0:l.toString()),c=t.type||"clipboard";if(!u)return!1;o.$selected_content=u,o.$copy_type=c}return this.instance.capture(e,o),!0}}}isBrowserSupported(){return Se(C?.querySelectorAll)}},historyAutocapture:class{constructor(t){var e;this._instance=t,this._o=(v==null||(e=v.location)==null?void 0:e.pathname)||""}initialize(){this.startIfEnabled()}get isEnabled(){return this._instance.config.capture_pageview==="history_change"}startIfEnabled(){this.isEnabled&&(k.info("History API monitoring enabled, starting..."),this.monitorHistoryChanges())}stop(){this.wo&&this.wo(),this.wo=void 0,k.info("History API monitoring stopped")}monitorHistoryChanges(){v&&v.history&&(this.ko("pushState"),this.ko("replaceState"),this.xo())}ko(t){var e;if(v&&((e=v.history[t])==null||!e.__posthog_wrapped__)){var s=this;(function(n,r,i){try{if(!(r in n))return Nl;var o={next:n[r]},a=i((function(){for(var l=arguments.length,u=new Array(l),c=0;l>c;c++)u[c]=arguments[c];return o.next.apply(this,u)}));return Se(a)&&(a.prototype=a.prototype||{},Object.defineProperties(a,{__posthog_wrapped__:{enumerable:!1,value:!0},__posthog_layer__:{enumerable:!1,value:o}})),n[r]=a,()=>{if(n[r]!==a)for(var l=n[r];Se(l)&&l.__posthog_layer__;){var u=l.__posthog_layer__;if(u.next===a)return void(u.next=o.next);l=u.next}else n[r]=o.next}}catch{return Nl}})(v.history,t,(n=>function(r,i,o){n.call(this,r,i,o),s.So(t)}))}}So(t){try{var e,s=v==null||(e=v.location)==null?void 0:e.pathname;if(!s)return;s!==this._o&&this.isEnabled&&this._instance.capture(is,{navigation_type:t}),this._o=s}catch(n){k.error("Error capturing "+t+" pageview",n)}}xo(){if(!this.wo){var t=()=>{this.So("popstate")};re(v,"popstate",t),this.wo=()=>{v&&v.removeEventListener("popstate",t)}}}},heatmaps:class{get Ne(){return this.instance.config}constructor(t){var e;this.Co=!1,this.vo=!1,this.Mo=null,this.instance=t,this.Co=!((e=this.instance.persistence)==null||!e.props[qi]),this.rageclicks=new Tl(t.config.rageclick)}initialize(){this.startIfEnabled()}get flushIntervalMilliseconds(){var t=5e3;return te(this.Ne.capture_heatmaps)&&this.Ne.capture_heatmaps.flush_interval_milliseconds&&(t=this.Ne.capture_heatmaps.flush_interval_milliseconds),t}get isEnabled(){return D(this.Ne.capture_heatmaps)?D(this.Ne.enable_heatmaps)?this.Co:this.Ne.enable_heatmaps:this.Ne.capture_heatmaps!==!1}startIfEnabled(){if(this.isEnabled){if(this.vo)return;mf.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 s=!!e.heatmaps;this.instance.persistence&&this.instance.persistence.register({[qi]:s}),this.Co=s,this.startIfEnabled()}}}getAndClearBuffer(){var t=this.R;return this.R=void 0,t}Io(t){ki(t.originalEvent)&&this.ke(t.originalEvent,"deadclick")}Ie(){this.Mo&&clearInterval(this.Mo),this.Mo=C?.visibilityState==="visible"?setInterval(this.cr.bind(this),this.flushIntervalMilliseconds):null}To(){v&&C&&(this.Po=this.cr.bind(this),re(v,ar,this.Po),this.Ro=t=>this.ke(t||v?.event),re(C,"click",this.Ro,{capture:!0}),this.Ao=t=>this.Fo(t||v?.event),re(C,"mousemove",this.Ao,{capture:!0}),this.Lo=new ml(this.instance,Fp,this.Io.bind(this)),this.Lo.startIfEnabledOrStop(),this.Oo=this.Ie.bind(this),re(C,or,this.Oo),this.vo=!0)}Eo(){var t;v&&C&&(this.Po&&v.removeEventListener(ar,this.Po),this.Ro&&C.removeEventListener("click",this.Ro,{capture:!0}),this.Ao&&C.removeEventListener("mousemove",this.Ao,{capture:!0}),this.Oo&&C.removeEventListener(or,this.Oo),clearTimeout(this.Do),(t=this.Lo)==null||t.stop(),this.vo=!1)}$o(t,e){var s=this.instance.scrollManager.scrollY(),n=this.instance.scrollManager.scrollX(),r=this.instance.scrollManager.scrollElement(),i=(function(o,a,l){for(var u=o;u&&Ft(u)&&!Me(u,"body");){if(u===l)return!1;var c=void 0;try{var d,h,p;c=(d=(h=(p=u.ownerDocument)==null?void 0:p.defaultView)!==null&&h!==void 0?h:v)==null?void 0:d.getComputedStyle(u).position}catch{return!1}if(M(a,c))return!0;u=Fu(u)}return!1})(ui(t),["fixed","sticky"],r);return{x:t.clientX+(i?0:n),y:t.clientY+(i?0:s),target_fixed:i,type:e}}ke(t,e){var s;if(e===void 0&&(e="click"),!il(t.target)&&ki(t)){var n=this.$o(t,e);(s=this.rageclicks)!=null&&s.isRageClick(t.clientX,t.clientY,new Date().getTime())&&cl(ui(t),this.instance.config.rageclick)&&this.Vt(b({},n,{type:"rageclick"})),this.Vt(n)}}Fo(t){!il(t.target)&&ki(t)&&(clearTimeout(this.Do),this.Do=setTimeout((()=>{this.Vt(this.$o(t,"mousemove"))}),500))}Vt(t){if(v){var e=this.Ne.disable_capture_url_hashes?Ct(v.location.href):v.location.href,s=this.Ne.custom_personal_data_properties,n=this.Ne.mask_personal_data_properties?[...vs,...s||[]]:[],r=rn(e,n,on);this.R=this.R||{},this.R[r]||(this.R[r]=[]),this.R[r].push(t)}}cr(){this.R&&!mt(this.R)&&this.instance.capture("$$heatmap",{$heatmap_data:this.getAndClearBuffer()})}},deadClicksAutocapture:ml,webVitalsAutocapture:class{constructor(t){var e;this.Co=!1,this.vo=!1,this.R={navigationKey:void 0,url:void 0,metrics:[],firstMetricTimestamp:void 0},this.No=()=>{clearTimeout(this.qo),this.qo=void 0,this.R.metrics.length!==0&&(this._instance.capture("$web_vitals",b({$current_url:this.R.url},this.R.metrics.reduce(((s,n)=>b({},s,{["$web_vitals_"+n.name+"_event"]:b({},n),["$web_vitals_"+n.name+"_value"]:n.value})),{}))),this.R={navigationKey:void 0,url:void 0,metrics:[],firstMetricTimestamp:void 0})},this.jo=s=>{var n;if(this.R=this.R||{navigationKey:void 0,url:void 0,metrics:[],firstMetricTimestamp:void 0},D(s?.name)||D(s?.value))Lt.error("Invalid metric received",s);else{var r=typeof s.navigationURL=="string"?s.navigationURL:void 0,i=this.Bo(r);if(!x(i)){var o=he(s.navigationId)||typeof s.navigationId=="string"?"navigation:"+s.navigationId:"url:"+i;if(!this.Ho||this.Ho>s.value){this.R.navigationKey!==o&&(this.No(),this.qo=setTimeout(this.No,this.flushToCaptureTimeoutMs)),x(this.R.navigationKey)&&(this.R.navigationKey=o,this.R.url=i),this.R.firstMetricTimestamp=x(this.R.firstMetricTimestamp)?Date.now():this.R.firstMetricTimestamp,s.attribution&&s.attribution.interactionTargetElement&&(s.attribution.interactionTargetElement=void 0);var a=(n=this._instance.sessionManager)==null?void 0:n.checkAndGetSessionAndWindowId(!0),l=b({},s,r?{navigationURL:i}:{},{$current_url:i,timestamp:Date.now()});x(a)||(l.$session_id=a.sessionId,l.$window_id=a.windowId),this.R.metrics.push(l),this.R.metrics.length===this.allowedMetrics.length&&this.No()}else Lt.error("Ignoring metric with value >= "+this.Ho,s)}}},this.Uo=()=>{if(!this.vo){var s,n,r,i,o=$.__PosthogExtensions__,a=o?.postHogWebVitalsCallbacksByFlavor,l=a?.[this.zo]||(this.zo==="web-vitals"&&x(a)?o?.postHogWebVitalsCallbacks:void 0);if(x(l)||(s=l.onLCP,n=l.onCLS,r=l.onFCP,i=l.onINP),s&&n&&r&&i){var u={reportSoftNavs:this.useSoftNavs};this.allowedMetrics.indexOf("LCP")>-1&&s(this.jo.bind(this),u),this.allowedMetrics.indexOf("CLS")>-1&&n(this.jo.bind(this),u),this.allowedMetrics.indexOf("FCP")>-1&&r(this.jo.bind(this),u),this.allowedMetrics.indexOf("INP")>-1&&i(this.jo.bind(this),u),this.vo=!0}else Lt.error("web vitals callbacks not loaded - not starting")}},this._instance=t,this.Co=!((e=this._instance.persistence)==null||!e.props[Ji]),this.startIfEnabled()}get Wo(){return this._instance.config.capture_performance}get allowedMetrics(){var t,e,s=te(this.Wo)?(t=this.Wo)==null?void 0:t.web_vitals_allowed_metrics:void 0;return D(s)?((e=this._instance.persistence)==null?void 0:e.props[Yi])||["CLS","FCP","INP","LCP"]:s}get flushToCaptureTimeoutMs(){return(te(this.Wo)?this.Wo.web_vitals_delayed_flush_ms:void 0)||5e3}get useAttribution(){var t=te(this.Wo)?this.Wo.web_vitals_attribution:void 0;return t!=null&&t}get useSoftNavs(){var t=te(this.Wo)?this.Wo.__preview_web_vitals_soft_navs:void 0;return t!=null&&t}get Ho(){var t=te(this.Wo)&&he(this.Wo.__web_vitals_max_value)?this.Wo.__web_vitals_max_value:Ml;return t>0&&6e4>=t?Ml:t}get isEnabled(){var t=ne?.protocol;if(t!=="http:"&&t!=="https:")return Lt.info("Web Vitals are disabled on non-http/https protocols"),!1;var e=te(this.Wo)?this.Wo.web_vitals:Ke(this.Wo)?this.Wo:void 0;return Ke(e)?e:this.Co}startIfEnabled(){this.isEnabled&&!this.vo&&(Lt.info("enabled, starting..."),this.ai(this.Uo))}onRemoteConfig(t){if(t.ok){var e=t.config;if("capturePerformance"in e){var s=te(e.capturePerformance)&&!!e.capturePerformance.web_vitals,n=te(e.capturePerformance)?e.capturePerformance.web_vitals_allowed_metrics:void 0;this._instance.persistence&&(this._instance.persistence.register({[Ji]:s}),this._instance.persistence.register({[Yi]:n})),this.Co=s,this.startIfEnabled()}}}get zo(){return this.useSoftNavs?this.useAttribution?"web-vitals-with-attribution-soft-navs":"web-vitals-soft-navs":this.useAttribution?"web-vitals-with-attribution":"web-vitals"}ai(t){var e=$.__PosthogExtensions__,s=this.zo,n=e?.postHogWebVitalsCallbacksByFlavor;n!=null&&n[s]||s==="web-vitals"&&x(n)&&e!=null&&e.postHogWebVitalsCallbacks?t():e==null||e.loadExternalDependency==null||e.loadExternalDependency(this._instance,s,(r=>{r?Lt.error("failed to load script",r):t()}))}Bo(t){var e=t||v?.location.href;if(e){var s=this._instance.config.disable_capture_url_hashes?Ct(e):e,n=this._instance.config.custom_personal_data_properties,r=this._instance.config.mask_personal_data_properties?[...vs,...n||[]]:[];return rn(s,r,on)}Lt.error("Could not determine current URL")}}},If={exceptionObserver:class{constructor(t){var e;this.Uo=()=>{var s;if(v&&this.isEnabled&&(s=$.__PosthogExtensions__)!=null&&s.errorWrappingFunctions){var n=$.__PosthogExtensions__.errorWrappingFunctions.wrapOnError,r=$.__PosthogExtensions__.errorWrappingFunctions.wrapUnhandledRejection,i=$.__PosthogExtensions__.errorWrappingFunctions.wrapConsoleError;try{!this.Vo&&this.Ne.capture_unhandled_errors&&(this.Vo=n(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=i(this.captureException.bind(this)))}catch(o){Ms.error("failed to start",o),this.Qo()}}},this._instance=t,this.Ko=!((e=this._instance.persistence)==null||!e.props[Vi]),this.Jo=new Sh(b({},(function(s){var n,r,i,o;return s===void 0&&(s={}),{refillRate:(n=(r=s.exceptionRateLimiterRefillRate)!==null&&r!==void 0?r:s.__exceptionRateLimiterRefillRate)!==null&&n!==void 0?n:1,bucketSize:(i=(o=s.exceptionRateLimiterBucketSize)!==null&&o!==void 0?o:s.__exceptionRateLimiterBucketSize)!==null&&i!==void 0?i:10}})(this._instance.config.error_tracking),{refillInterval:1e4,rt:Ms})),this.Ne=this.Yo(),this.startIfEnabledOrStop()}Yo(){var t=this._instance.config.capture_exceptions,e={capture_unhandled_errors:!1,capture_unhandled_rejections:!1,capture_console_errors:!1};return te(t)?e=b({},e,t):(x(t)?this.Ko:t)&&(e=b({},e,{capture_unhandled_errors:!0,capture_unhandled_rejections:!0})),e}get isEnabled(){return this.Ne.capture_console_errors||this.Ne.capture_unhandled_errors||this.Ne.capture_unhandled_rejections}startIfEnabledOrStop(){this.isEnabled?(Ms.info("enabled"),this.Qo(),this.ai(this.Uo)):this.Qo()}ai(t){var e,s;(e=$.__PosthogExtensions__)!=null&&e.errorWrappingFunctions?t():(s=$.__PosthogExtensions__)==null||s.loadExternalDependency==null||s.loadExternalDependency(this._instance,"exception-autocapture",(n=>{if(n)return Ms.error("failed to load script",n);t()}))}Qo(){var t,e,s;(t=this.Vo)==null||t.call(this),this.Vo=void 0,(e=this.Zo)==null||e.call(this),this.Zo=void 0,(s=this.Go)==null||s.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({[Vi]:this.Ko}),this.Ne=this.Yo(),this.startIfEnabledOrStop())}}onConfigChange(){this.Ne=this.Yo()}captureException(t){var e,s,n,r=(e=t==null||(s=t.$exception_list)==null||(s=s[0])==null?void 0:s.type)!==null&&e!==void 0?e:"Exception";this.Jo.consumeRateLimit(r)?Ms.info("Skipping exception capture because of client rate limiting.",{exception:r}):(n=this._instance.exceptions)==null||n.sendExceptionEvent(t)}},exceptions:class{constructor(t){var e,s;this.Xo=[],this.tl=new jh([new Kh,new np,new Yh,new Jh,new tp,new ep,new Xh,new sp],(function(n){for(var r=arguments.length,i=new Array(r>1?r-1:0),o=1;r>o;o++)i[o-1]=arguments[o];return function(a,l){l===void 0&&(l=0);for(var u=[],c=a.split(` -`),d=l;c.length>d;d++){var h=c[d];if(1024>=h.length){var p=tl.test(h)?h.replace(tl,"$1"):h;if(!p.match(/\S*Error: /)){for(var f of i){var g=f(p,n);if(g){u.push(g);break}}if(u.length>=50)break}}}return(function(m){if(!m.length)return[];var _=Array.from(m);return _.reverse(),_.slice(0,50).map((w=>{return b({},w,{filename:w.filename||(E=_,E[E.length-1]||{}).filename,function:w.function||gs});var E}))})(u)}})("web:javascript",zh,Gh)),this._instance=t,this.Xo=(e=(s=this._instance.persistence)==null?void 0:s.get_property(Gi))!==null&&e!==void 0?e:[],this.el=tr(this.il()),this.rl=new ip(this.el)}onConfigChange(){this.el=tr(this.il()),this.rl.setConfig(this.el)}onRemoteConfig(t){var e,s,n;if(t.ok){var r=t.config;if("errorTracking"in r){var i=(e=(s=r.errorTracking)==null?void 0:s.suppressionRules)!==null&&e!==void 0?e:[],o=(n=r.errorTracking)==null?void 0:n.captureExtensionExceptions;this.Xo=i,this._instance.persistence&&this._instance.persistence.register({[Gi]:this.Xo,[Ki]:o})}}}get nl(){var t,e=!!this._instance.get_property(Ki),s=this._instance.config.error_tracking.captureExtensionExceptions;return(t=s??e)!==null&&t!==void 0&&t}buildProperties(t,e){return this.tl.buildFromUnknown(t,{syntheticException:e?.syntheticException,mechanism:{handled:e?.handled}})}addExceptionStep(t,e){if(this.el.enabled)try{if(!W(t)||t.trim().length===0)return void Xe.warn("Ignoring exception step because message must be a non-empty string");var s=(function(i){if(!i)return{sanitizedProperties:{},droppedKeys:[]};var o=[];return{sanitizedProperties:Object.keys(i).reduce(((a,l)=>rp.has(l)?(o.push(l),a):(a[l]=i[l],a)),{}),droppedKeys:o}})(this.sl(e)),n=s.sanitizedProperties,r=s.droppedKeys;r.length>0&&Xe.warn("Ignoring reserved exception step fields",{droppedKeys:r}),this.rl.add(b({[Qn]:t,[er]:new Date().toISOString()},n))}catch(i){Xe.error("Failed to add exception step. Ignoring breadcrumb.",i)}}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 Xe.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 Xe.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 Xe.info("Skipping exception capture because it was thrown by the PostHog SDK")}var s=this.el.enabled&&D(t.$exception_steps)?this.dl(t):t,n=typeof(i=globalThis._posthogReleaseId)=="string"&&i.length>0?i:void 0;n&&(s.$release_id=n);try{var r=this._instance.capture("$exception",s,{_noTruncate:!0,_batchKey:"exceptionEvent",Wn:!0});return r&&this.rl.clear(),r}catch(o){return Xe.error("Failed to capture exception event. Dropping this exception.",o),void this.rl.clear()}}catch(o){return void Xe.error("Failed to process exception event. Ignoring this exception.",o)}var i}dl(t){try{var e=this.rl.getAttachable();return e.length===0?t:b({},t,{$exception_steps:e})}catch(s){return Xe.error("Failed to read buffered exception steps. Capturing exception without steps.",s),t}}ll(t){this.el.enabled&&this.rl.add({[Qn]:t,[er]:new Date().toISOString()})}sl(t){return te(t)?b({},t):{}}il(){var t,e;return(t=(e=this._instance.config.error_tracking)==null?void 0:e.exception_steps)!==null&&t!==void 0?t:{}}ol(t){if(t.length===0)return!1;try{var e=t.reduce(((s,n)=>{var r=n.type,i=n.value;return W(r)&&r.length>0&&s.$exception_types.push(r),W(i)&&i.length>0&&s.$exception_values.push(i),s}),{$exception_types:[],$exception_values:[]});return this.Xo.some((s=>{var n=s.values.map((r=>{var i=rd[r.operator],o=e[r.key];if(!i||!o)return!1;var a=L(r.value)?r.value:[r.value];return a.length>0&&i(a,o)}));return s.type==="OR"?n.some(Boolean):n.every(Boolean)}))}catch(s){return Xe.warn("Failed to evaluate suppression rules. Capturing the exception.",s),!1}}ul(t){return t.flatMap((e=>{var s,n;return(s=(n=e.stacktrace)==null?void 0:n.frames)!==null&&s!==void 0?s:[]})).some((e=>e.filename&&e.filename.startsWith("chrome-extension://")))}hl(t){if(t.length>0){var e,s,n,r,i=(e=(s=t[0].stacktrace)==null?void 0:s.frames)!==null&&e!==void 0?e:[],o=i[i.length-1];return(n=o==null||(r=o.filename)==null?void 0:r.includes("posthog.com/static"))!==null&&n!==void 0&&n}return!1}al(t){return!D(t)&&L(t)}}},Cf=b({productTours:class{get Mr(){return this._instance.persistence}constructor(t){this.vl=null,this.cl=null,this._instance=t}initialize(){this.loadIfEnabled()}onRemoteConfig(t){if(t.ok){var e=t.config;if("productTours"in e){var s,n;if(this.Mr&&this.Mr.register({[Vo]:!!e.productTours}),!Ii(this._instance))return!this.vl&&D((s=this.Mr)==null?void 0:s.props[Ws])||An.info("product tours disabled; stopping and clearing cached tours"),(n=this.vl)==null||n.stop(),this.vl=null,void this.clearCache();this.loadIfEnabled()}}}loadIfEnabled(){!this.vl&&Ii(this._instance)&&this.ai((()=>this.fl()))}ai(t){var e,s;(e=$.__PosthogExtensions__)!=null&&e.generateProductTours?t():(s=$.__PosthogExtensions__)==null||s.loadExternalDependency==null||s.loadExternalDependency(this._instance,"product-tours",(n=>{n?An.error("Could not load product tours script",n):t()}))}fl(){var t;!this.vl&&(t=$.__PosthogExtensions__)!=null&&t.generateProductTours&&(this.vl=$.__PosthogExtensions__.generateProductTours(this._instance,!0))}getProductTours(t,e){if(e===void 0&&(e=!1),!L(this.cl)||e){var s=this.Mr;if(s){var n=s.props[Ws];if(L(n)&&!e)return this.cl=n,void t(n,{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(Ii(this._instance)){var i=r.statusCode;if(i!==200||!r.json){var o="Product Tours API could not be loaded, status: "+i;return i===0?r.error||An.warn(o):An.error(o),void t([],{isLoaded:!1,error:o})}var a=L(r.json.product_tours)?r.json.product_tours:[];this.cl=a,s&&s.register({[Ws]:a}),t(a,{isLoaded:!0})}else t([],{isLoaded:!0})}})}else t(this.cl,{isLoaded:!0})}getActiveProductTours(t){D(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(Ws)}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)}}},Tr),Ff={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 s=this.globalsForEvent(e);this.gl.push(s),this.gl.length>1e3&&(this.gl=this.gl.slice(10))}}get siteAppLoaders(){var t;return(t=$._POSTHOG_REMOTE_CONFIG)==null||(t=t[this._instance.config.token])==null?void 0:t.siteApps}initialize(){if(this.isEnabled){var t=this._instance._addCaptureHook(this.ml.bind(this));this.yl=()=>{t(),this.gl=[],this.yl=void 0}}}globalsForEvent(t){var e,s,n,r,i,o,a;if(!t)throw new Error("Event payload is required");var l={},u=this._instance.get_property("$groups")||[],c=this._instance.get_property("$stored_group_properties")||{};for(var d of Object.entries(c)){var h=d[0];l[h]={id:u[h],type:h,properties:d[1]}}var p=t.$set_once,f=t.$set;return{event:b({},Pc(t,vf),{properties:b({},t.properties,f?{$set:b({},(e=(s=t.properties)==null?void 0:s.$set)!==null&&e!==void 0?e:{},f)}:{},p?{$set_once:b({},(n=(r=t.properties)==null?void 0:r.$set_once)!==null&&n!==void 0?n:{},p)}:{}),elements_chain:(i=(o=t.properties)==null?void 0:o.$elements_chain)!==null&&i!==void 0?i:"",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,s=(e=t.tagName)==null?void 0:e.toLowerCase();return s==="style"&&this._instance.config.prepare_external_dependency_stylesheet?this._instance.config.prepare_external_dependency_stylesheet(t)||(Ze.error("prepare_external_dependency_stylesheet returned null"),null):s==="script"&&this._instance.config.prepare_external_dependency_script?this._instance.config.prepare_external_dependency_script(t)||(Ze.error("prepare_external_dependency_script returned null"),null):t}_l(){var t,e,s,n,r,i,o,a;if(!this._instance.config.prepare_external_dependency_stylesheet&&!this._instance.config.prepare_external_dependency_script)return()=>{};var l=C?.defaultView,u=l==null||(t=l.Node)==null?void 0:t.prototype;if(!l||!u)return()=>{};if(this.pl++,this.wl)return this.kl();var c=[],d=this,h=new WeakSet,p=(m,_,w)=>{if(m!=null&&m[_]){var E=m[_];m[_]=w(E),c.push((()=>{m[_]=E}))}},f=m=>{if(h.has(m))return m;var _=d.bl(m);return _&&h.add(_),_},g=m=>m.map((_=>typeof _=="string"?_:f(_))).filter((_=>!$e(_)));return p(u,"appendChild",(m=>function(_){var w=f(_);return w?m.call(this,w):_})),p(u,"insertBefore",(m=>function(_,w){var E=f(_);return E?m.call(this,E,w):_})),p(u,"replaceChild",(m=>function(_,w){var E=f(_);return E?m.call(this,E,w):w})),[(e=l.Element)==null?void 0:e.prototype,(s=l.Document)==null?void 0:s.prototype,(n=l.DocumentFragment)==null?void 0:n.prototype].forEach((m=>{p(m,"append",(_=>function(){for(var w=arguments.length,E=new Array(w),I=0;w>I;I++)E[I]=arguments[I];return _.apply(this,g(E))})),p(m,"prepend",(_=>function(){for(var w=arguments.length,E=new Array(w),I=0;w>I;I++)E[I]=arguments[I];return _.apply(this,g(E))}))})),[(r=l.Element)==null?void 0:r.prototype,(i=l.CharacterData)==null?void 0:i.prototype,(o=l.DocumentType)==null?void 0:o.prototype].forEach((m=>{p(m,"before",(_=>function(){for(var w=arguments.length,E=new Array(w),I=0;w>I;I++)E[I]=arguments[I];return _.apply(this,g(E))})),p(m,"after",(_=>function(){for(var w=arguments.length,E=new Array(w),I=0;w>I;I++)E[I]=arguments[I];return _.apply(this,g(E))})),p(m,"replaceWith",(_=>function(){for(var w=arguments.length,E=new Array(w),I=0;w>I;I++)E[I]=arguments[I];var F=g(E);return E.length&&!F.length?void 0:_.apply(this,F)}))})),p((a=l.Element)==null?void 0:a.prototype,"insertAdjacentElement",(m=>function(_,w){var E=f(w);return E?m.call(this,_,E):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 s=this._l();try{var n=t(s);return e&&s(),n}catch(r){throw s(),r}}setupSiteApp(t){var e=this.apps[t.id],s=()=>{var o;!e.errored&&this.gl.length&&(Ze.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))},n=!1,r=o=>{e.errored=!o,e.loaded=!0,Ze.info("Site app with id "+t.id+" "+(o?"loaded":"errored")),n&&s()};try{var i=this.xl((o=>t.init({posthog:this._instance,callback(a){o(),r(a)}})),!1).processEvent;i&&(e.processEvent=i),n=!0}catch(o){Ze.error(Dl+t.id,o),r(!1)}if(n&&e.loaded)try{s()}catch(o){Ze.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 s of t)this.setupSiteApp(s)}Cl(t){var e=this;if(Object.keys(this.apps).length!==0){var s=this.globalsForEvent(t),n=function(i){try{e.xl((()=>i.processEvent==null?void 0:i.processEvent(s)))}catch(o){Ze.error("Error while processing event "+t.event+" for site app "+i.id,o)}};for(var r of Object.values(this.apps))n(r)}}onRemoteConfig(t){var e,s,n,r=this;if((e=this.siteAppLoaders)!=null&&e.length)return this.isEnabled?(this.Sl(),void this._instance.on("eventCaptured",(l=>this.Cl(l)))):void Ze.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.');if((s=this.yl)==null||s.call(this),t.ok){var i=t.config;if((n=i.siteApps)!=null&&n.length)if(this.isEnabled){var o=function(){var l,u=a.id,c=a.url;$["__$$ph_site_app_"+u]=r._instance,(l=$.__PosthogExtensions__)==null||l.loadSiteApp==null||l.loadSiteApp(r._instance,c,(d=>{if(d)return Ze.error(Dl+u,d)}))};for(var a of i.siteApps)o()}else Ze.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.')}}}},Pf={tracingHeaders:class{constructor(t){this.Ml=void 0,this.Tl=void 0,this.El=void 0,this.Uo=()=>{var e,s,n=this.Il();n?(x(this.Ml)&&(this.Ml=(e=$.__PosthogExtensions__)==null||(e=e.tracingHeadersPatchFns)==null?void 0:e._patchXHR(n,(()=>this._instance.get_distinct_id()),this._instance.sessionManager)),x(this.Tl)&&(this.Tl=(s=$.__PosthogExtensions__)==null||(s=s.tracingHeadersPatchFns)==null?void 0:s._patchFetch(n,(()=>this._instance.get_distinct_id()),this._instance.sessionManager))):this.Qo()},this._instance=t}initialize(){this.startIfEnabledOrStop()}ai(t){var e,s;(e=$.__PosthogExtensions__)!=null&&e.tracingHeadersPatchFns?t():(s=$.__PosthogExtensions__)==null||s.loadExternalDependency==null||s.loadExternalDependency(this._instance,"tracing-headers",(n=>{if(n)return gf.error("failed to load script",n);t()}))}Pl(){var t,e;return(t=(e=this._instance.config.tracing_headers)!==null&&e!==void 0?e:this._instance.config.addTracingHeaders)!==null&&t!==void 0?t:this._instance.config.__add_tracing_headers}Il(){var t=this.Pl();return L(t)?(L(this.El)?this.El.splice(0,this.El.length,...t):this.El=[...t],t.length>0?this.El:void 0):(L(this.El)&&this.El.splice(0),this.El=t||void 0,this.El)}Qo(){var t,e;(t=this.Ml)==null||t.call(this),(e=this.Tl)==null||e.call(this),this.Ml=void 0,this.Tl=void 0}startIfEnabledOrStop(){this.Il()?this.ai(this.Uo):this.Qo()}}},Af=b({surveys:class{get Ne(){return this._instance.config}constructor(t){this.Rl=void 0,this._surveyManager=null,this.Al=!1,this.Fl=[],this.Ll=null,this.Ol=null,this._instance=t,this._surveyEventReceiver=null}initialize(){this.loadIfEnabled()}onRemoteConfig(t){if(!this.Ne.disable_surveys){if(!t.ok)return q.warn("Remote config unavailable. Not loading surveys.");var e=t.config.surveys;if(D(e))return q.warn("Flags not loaded yet. Not loading surveys.");var s=L(e);this.Rl=s?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=[],s=0;slocalStorage.removeItem(r)))}catch{}}loadIfEnabled(){if(!this._surveyManager)if(this.Al)q.info("Already initializing surveys, skipping...");else if(this.Ne.disable_surveys)q.info(Bl);else if(this.Ne.cookieless_mode&&this._instance.consent.isOptedOut())q.info("Not loading surveys in cookieless mode without consent.");else{var t=$?.__PosthogExtensions__;if(t){if(!x(this.Rl)||this.Ne.advanced_enable_surveys){var e=this.Rl||this.Ne.advanced_enable_surveys;this.Al=!0;try{var s=t.generateSurveys;if(s)return void this.Dl(s,e);var n=t.loadExternalDependency;if(!n)return void this.$l(Ko);n(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 wf(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(Bl),t([]);var s,n=this._instance.get_property(Xi);if(n&&!e)return t(n,{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=>{s=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 i;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(s==null||s({surveys:[],context:l}))}this.Ol=null;var u,c=r.json.surveys||[],d=c.filter((p=>(function(f){return!(!f.start_date||f.end_date)})(p)&&(od(p)||(function(f){var g;return!((g=f.conditions)==null||(g=g.actions)==null||(g=g.values)==null||!g.length)})(p))));d.length>0&&((u=this._surveyEventReceiver)==null||u.register(d)),(i=this._instance.persistence)==null||i.register({[Xi]:c,[nr]:Date.now()});var h={isLoaded:!0};t(c,h),s?.({surveys:c,context:h})}}))}ql(){return this.jl()&&!this.Ll&&!this.Bl()}jl(){var t=this._instance.get_property(nr);return he(t)&&Date.now()-t>3e5}Bl(){return he(this.Ol)&&3e5>Date.now()-this.Ol}markSurveyAsSeen(t,e){var s,n={id:t,current_iteration:(s=e?.iteration)!==null&&s!==void 0?s:null};ld(n);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(s){q.error("Error in survey callback",s)}}getActiveMatchingSurveys(t,e){if(e===void 0&&(e=!1),!D(this._surveyManager))return this._surveyManager.getActiveMatchingSurveys(t,e);q.warn("init was not called")}Hl(t){var e=null;return this.getSurveys((s=>{var n;e=(n=s.find((r=>r.id===t)))!==null&&n!==void 0?n:null})),e}Ul(t){if(D(this._surveyManager))return{eligible:!1,reason:$n};var e=typeof t=="string"?this.Hl(t):t;return e?this._surveyManager.checkSurveyEligibility(e):{eligible:!1,reason:"Survey not found"}}zl(t){if(D(this._surveyManager))return{eligible:!1,reason:$n};var e=typeof t=="string"?this.Hl(t):t;return e?this._surveyManager.checkSurveyRenderability(e):{eligible:!1,reason:"Survey not found"}}canRenderSurvey(t){if(D(this._surveyManager))return q.warn("init was not called"),{visible:!1,disabledReason:$n};var e=this.zl(t);return{visible:e.eligible,disabledReason:e.reason}}canRenderSurveyAsync(t,e){return D(this._surveyManager)?(q.warn("init was not called"),Promise.resolve({visible:!1,disabledReason:$n})):new Promise((s=>{this.getSurveys((n=>{var r,i=(r=n.find((a=>a.id===t)))!==null&&r!==void 0?r:null;if(i){var o=this.zl(i);s({visible:o.eligible,disabledReason:o.reason})}else s({visible:!1,disabledReason:"Survey not found"})}),e)}))}renderSurvey(t,e,s){var n;if(D(this._surveyManager))q.warn("init was not called");else{var r=typeof t=="string"?this.Hl(t):t;if(r!=null&&r.id)if(tf.includes(r.type)){var i=C?.querySelector(e);if(i)return(n=r.appearance)!=null&&n.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,i,s),q.info("Survey "+r.id+" rendered")}),1e3*r.appearance.surveyPopupDelaySeconds)):void this._surveyManager.renderSurvey(r,i,s);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 s;if(D(this._surveyManager))q.warn("init was not called");else{var n=this.Hl(t);if(n){var r=n;if((s=n.appearance)!=null&&s.surveyPopupDelaySeconds&&e.ignoreDelay&&(r=b({},n,{appearance:b({},n.appearance,{surveyPopupDelaySeconds:0})})),e.displayType!==lo.Popover&&e.initialResponses&&q.warn("initialResponses is only supported for popover surveys. prefill will not be applied."),e.ignoreConditions===!1){var i=this.Ul(n);if(!i.eligible)return void q.warn("Survey is not eligible to be displayed: ",i.reason)}e.displayType!==lo.Inline?this._surveyManager.handlePopoverSurvey(r,e):this.renderSurvey(r,e.selector,e.properties)}else q.warn("Survey not found")}}cancelPendingSurvey(t){D(this._surveyManager)?q.warn("init was not called"):this._surveyManager.cancelSurvey(t)}handlePageUnload(){var t;(t=this._surveyManager)==null||t.handlePageUnload==null||t.handlePageUnload()}}},Tr),$f={toolbar:class{constructor(t){this.instance=t}Wl(t){$.ph_toolbar_state=t}Vl(){var t;return(t=$.ph_toolbar_state)!==null&&t!==void 0?t:0}initialize(){return this.maybeLoadToolbar()}maybeLoadToolbar(t,e,s){if(t===void 0&&(t=void 0),e===void 0&&(e=void 0),s===void 0&&(s=void 0),io(this.instance.config)||!v||!C)return!1;t=t??v.location,s=s??v.history;try{if(!e){try{v.localStorage.setItem("test","test"),v.localStorage.removeItem("test")}catch{return!1}e=v?.localStorage}var n,r=bf||dr(t.hash,"__posthog")||dr(t.hash,"state"),i=r?nl((()=>JSON.parse(atob(decodeURIComponent(r)))))||nl((()=>JSON.parse(decodeURIComponent(r)))):null;return i&&i.action==="ph_authorize"?((n=i).source="url",n&&Object.keys(n).length>0&&(i.desiredHash?t.hash=i.desiredHash:s?s.replaceState(s.state,"",t.pathname+t.search):t.hash="")):((n=JSON.parse(e.getItem(jl)||"{}")).source="localstorage",delete n.userIntent),!(!n.token||this.instance.config.token!==n.token||(this.loadToolbar(n),0))}catch{return!1}}Zl(t){var e=$.ph_load_toolbar||$.ph_load_editor;!D(e)&&Se(e)?e(t,this.instance):Ul.warn("No toolbar load function found")}loadToolbar(t){var e=!(C==null||!C.getElementById(Su));if(!v||e)return!1;var s=this.instance.requestRouter.region==="custom"&&this.instance.config.advanced_disable_toolbar_metrics,n=b({token:this.instance.config.token},t,{apiURL:this.instance.requestRouter.endpointFor("ui")},s?{instrument:!1}:{});if(v.localStorage.setItem(jl,JSON.stringify(b({},n,{source:void 0}))),this.Vl()===2)this.Zl(n);else if(this.Vl()===0){var r;this.Wl(1),(r=$.__PosthogExtensions__)==null||r.loadExternalDependency==null||r.loadExternalDependency(this.instance,"toolbar",(i=>{if(i)return Ul.error("[Toolbar] Failed to load",i),void this.Wl(0);this.Wl(2),this.Zl(n)})),re(v,"turbolinks:load",(()=>{this.Wl(0),this.loadToolbar(n)}))}return!0}Gl(t){return this.loadToolbar(t)}maybeLoadEditor(t,e,s){return t===void 0&&(t=void 0),e===void 0&&(e=void 0),s===void 0&&(s=void 0),this.maybeLoadToolbar(t,e,s)}}},Rf=b({experiments:ye},Tr),Tf={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;D(e)||(Ke(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||io(this._instance.config)||this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut())){var t=$?.__PosthogExtensions__;if(t&&!x(this.Ql)&&this.Ql)if(this.Jl&&this.Jl.token){this.Kl=!0;try{var e=t.initConversations;if(e)return this.tu(e),void(this.Kl=!1);var s=t.loadExternalDependency;if(!s)return void this.eu(Ko);s(this._instance,"conversations",(n=>{n||!t.initConversations?this.eu("Could not load conversations script",n):this.tu(t.initConversations),this.Kl=!1}))}catch(n){this.eu("Error initializing conversations",n),this.Kl=!1}}else Ue.error("Conversations enabled but missing token in remote config.")}}tu(t){if(this.Jl)try{this._conversationsManager=t(this.Jl,this._instance),this.Yl=!1,Ue.info("Conversations loaded successfully")}catch(e){this.eu("Error completing conversations initialization",e)}else Ue.error("Cannot complete initialization: remote config is null")}eu(t,e){Ue.error(t,e),this._conversationsManager=null,this.Kl=!1,this.Yl=!0}show(){this._conversationsManager?this._conversationsManager.show():Ue.warn("Conversations not loaded yet.")}hide(){this._conversationsManager&&this._conversationsManager.hide()}isAvailable(){return this.Ql===!0&&!$e(this._conversationsManager)}getUnavailableReason(){return this.isAvailable()?null:this._instance.config.disable_conversations?"disabled_by_config":io(this._instance.config)?"disabled_for_toolbar":this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut()?"consent_opted_out":this.Xl===!1?"remote_config_failed":x(this.Ql)?this.Xl?"disabled_in_project":"remote_config_pending":this.Ql?D(this.Jl)||!this.Jl.token?"missing_token":$!=null&&$.__PosthogExtensions__?this.Kl?"initializing":this.Yl?"load_failed":"not_loaded":"extensions_unavailable":"disabled_in_project"}isVisible(){var t,e;return(t=(e=this._conversationsManager)==null?void 0:e.isVisible())!==null&&t!==void 0&&t}sendMessage(t,e,s){var n=this;return X((function*(){return n._conversationsManager?n._conversationsManager.sendMessage(t,e,s):(Ue.warn(Dt),null)}))()}getMessages(t,e){var s=this;return X((function*(){return s._conversationsManager?s._conversationsManager.getMessages(t,e):(Ue.warn(Dt),null)}))()}markAsRead(t){var e=this;return X((function*(){return e._conversationsManager?e._conversationsManager.markAsRead(t):(Ue.warn(Dt),null)}))()}getTickets(t){var e=this;return X((function*(){return e._conversationsManager?e._conversationsManager.getTickets(t):(Ue.warn(Dt),null)}))()}requestRestoreLink(t){var e=this;return X((function*(){return e._conversationsManager?e._conversationsManager.requestRestoreLink(t):(Ue.warn(Dt),null)}))()}restoreFromToken(t){var e=this;return X((function*(){return e._conversationsManager?e._conversationsManager.restoreFromToken(t):(Ue.warn(Dt),null)}))()}restoreFromUrlToken(){var t=this;return X((function*(){return t._conversationsManager?t._conversationsManager.restoreFromUrlToken():(Ue.warn(Dt),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()}}},Nf={logs:class{constructor(t){var e,s=this;this.iu=!1,this.ru=!1,this.rt=se("[logs]"),this.nu=b({},this.rt,{error(){for(var n=arguments.length,r=new Array(n),i=0;n>i;i++)r[i]=arguments[i];r.some(Jl)||s.rt.error(...r)}}),this.tr=[],this.su=[],this.Sa=0,this.au=()=>{var n,r;this.Sa=0,(n=this.ou)==null||n.onReconnect(),(r=this.lu)==null||r.onReconnect()},this._instance=t,this._instance&&(e=this._instance.config.logs)!=null&&e.captureConsoleLogs&&(this.iu=!0),v&&re(v,"online",this.au)}uu(t,e,s,n){var r,i=(function(o,a){var l,u,c,d,h,p,f,g=(l=o?.flushIntervalMs)!==null&&l!==void 0?l:3e3,m=(u=o?.maxBufferSize)!==null&&u!==void 0?u:100,_=a!=null&&a.consoleCapture?void 0:(c=o?.maxLogsPerInterval)!==null&&c!==void 0?c:1e3,w=x(_)?Math.max(m,2048):Math.max(m,_),E=o?.resourceAttributes;return{serviceName:(d=(h=E?.["service.name"])!==null&&h!==void 0?h:o?.serviceName)!==null&&d!==void 0?d:a?.serviceNameDefault,serviceVersion:(p=E?.["service.version"])!==null&&p!==void 0?p:o?.serviceVersion,environment:(f=E?.["deployment.environment"])!==null&&f!==void 0?f:o?.environment,resourceAttributes:E,beforeSend:o?.beforeSend,flushIntervalMs:g,maxBufferSize:m,maxQueueSize:w,maxBatchRecordsPerPost:100,rateCapWindowMs:g,maxLogsPerInterval:_,backgroundFlushBudgetMs:0,terminationFlushBudgetMs:0}})((r=this._instance)==null||(r=r.config)==null?void 0:r.logs,s);return[new Oh(this.hu(t,e),i,this.nu,(()=>this.du()),(o=>o()),void 0,n),i]}vu(){var t,e=(t=this._instance)==null||(t=t.config)==null?void 0:t.logs;if(!this.ou||this.cu!==e){var s;(s=this.ou)==null||s.reset(),this.cu=e;var n=this.uu((()=>this.tr),(r=>{this.tr=r}));this.ou=n[0],this.fu=n[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 s;(s=this.lu)==null||s.reset(),this.gu=e;var n=this.uu((()=>this.su),(r=>{this.su=r}),{serviceNameDefault:"posthog-browser-logs",consoleCapture:!0},Kl);this.lu=n[0],this.mu=n[1]}return this.lu}initialize(){this.loadIfEnabled()}onRemoteConfig(t){var e;if(t.ok){var s=(e=t.config.logs)==null?void 0:e.captureConsoleLogs;!D(s)&&s&&(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){Jl(t)||this.rt.error("PostHog logs flush failed:",t)}loadIfEnabled(){if(this.iu&&!this.ru){var t=$?.__PosthogExtensions__;if(t){var e=t.loadExternalDependency;e?e(this._instance,"logs",(s=>{var n;s||(n=t.logs)==null||!n.initializeLogs?this.rt.error("Could not load logs script",s):(t.logs.initializeLogs(this._instance),this.ru=!0)})):this.rt.error(Ko)}else this.rt.error("PostHog Extensions not found.")}}hu(t,e){var s=this._instance;return{get isDisabled(){return!1},get optedOut(){return!s.is_capturing()},getPersistedProperty:n=>n===ut.LogsQueue?t():void 0,setPersistedProperty(n,r){var i;n===ut.LogsQueue&&e((i=r)!==null&&i!==void 0?i:[])},Ot:n=>this.Ot(n),getLibraryId:()=>Y.LIB_NAME,getLibraryVersion:()=>Y.LIB_VERSION}}Ot(t){return new Promise((e=>{if(Mu(this.Sa,3))e({kind:"fatal",error:Fi(void 0,"logs endpoint is unreachable, dropping batch")});else{var s=!1,n=i=>{s||(s=!0,clearTimeout(r),e(i))},r=setTimeout((()=>{this.rt.warn("Logs request timed out before receiving a response"),n({kind:"retry-later",error:Fi(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:i=>{var o=i.statusCode;if(this.ku(o),o>=200&&300>o)n({kind:"ok"});else if(o===413)n({kind:"too-large"});else if(o!==0&&o!==429&&500>o)n({kind:"fatal",error:new Error("logs request failed with status "+o)});else{var a;o===0?(i.error||this.rt.warn("Logs request failed before receiving an HTTP response"),n({kind:"retry-later",error:Fi(i.error,"logs request failed before receiving an HTTP response")})):n({kind:"retry-later",error:(a=i.error)!==null&&a!==void 0?a:new Error("logs request failed with status "+o)})}}})}}))}ku(t){(t!==0||this._instance.__loaded)&&(this.Sa=Lu(t,this.Sa,3,(()=>this.rt.warn("Log requests are failing before receiving an HTTP response; this can happen due to network issues, CORS, browser blocking, or ad blockers. Stopped sending logs; will try again when connectivity changes."))))}bu(t){this.tr.length>0&&this.xu(t,this.tr,this.fu,Y.LIB_NAME,(e=>{this.tr=e})),this.su.length>0&&this.xu(t,this.su,this.mu,Kl,(e=>{this.su=e}))}xu(t,e,s,n,r){if(e.length!==0){var i=e.map((a=>a.record));r([]);var o=ou(i,iu(s,Y.LIB_NAME,Y.LIB_VERSION),n,Y.LIB_VERSION);this._instance._send_request({method:"POST",url:this.wu(),data:o,compression:"best-available",batchKey:"logs",transport:t})}}wu(){return this._instance.requestRouter.endpointFor("api","/i/v1/logs")+"?token="+encodeURIComponent(this._instance.config.token)}du(){var t,e={};if(e.distinctId=this._instance.get_distinct_id(),this._instance.sessionManager){var s=this._instance.sessionManager.checkAndGetSessionAndWindowId(!0),n=s.windowId,r=s.sessionStartTimestamp,i=s.lastActivityTimestamp;e.sessionId=s.sessionId,e.windowId=n,D(r)||(e.sessionStartTimestamp=r),D(i)||(e.lastActivityTimestamp=i)}if($!=null&&(t=$.location)!=null&&t.href&&(e.currentUrl=this._instance.config.disable_capture_url_hashes?Ct($.location.href):$.location.href),this._instance.featureFlags){var o=this._instance.featureFlags.getFlags();o&&o.length>0&&(e.activeFeatureFlags=o)}return e}}},Mf={metrics:class{constructor(t){this.rt=se("[metrics]"),this._instance=t}initialize(){}vu(){var t,e,s=(t=this._instance)==null||(t=t.config)==null?void 0:t.metrics;return this.ou&&this.cu===s||((e=this.ou)==null||e.reset(),this.cu=s,this.ou=new Dh(this.hu(),(function(n){var r,i,o,a,l,u=n?.resourceAttributes;return{serviceName:(r=u?.["service.name"])!==null&&r!==void 0?r:n?.serviceName,serviceVersion:(i=u?.["service.version"])!==null&&i!==void 0?i:n?.serviceVersion,environment:(o=u?.["deployment.environment"])!==null&&o!==void 0?o:n?.environment,resourceAttributes:u,beforeSend:n?.beforeSend,flushIntervalMs:(a=n?.flushIntervalMs)!==null&&a!==void 0?a:1e4,maxSeriesPerFlush:(l=n?.maxSeriesPerFlush)!==null&&l!==void 0?l:1e3}})(s),this.rt)),this.ou}count(t,e,s){e===void 0&&(e=1),this.vu().count(t,e,s)}gauge(t,e,s){this.vu().gauge(t,e,s)}histogram(t,e,s){this.vu().histogram(t,e,s)}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((s=>this.rt.error("PostHog metrics flush failed:",s)))}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:s=>e.Jt(s),getLibraryId:()=>Y.LIB_NAME,getLibraryVersion:()=>Y.LIB_VERSION}}Jt(t,e){return new Promise((s=>{var n=!1,r=o=>{n||(n=!0,clearTimeout(i),s(o))},i=setTimeout((()=>r({kind:"retry-later",error:new Error("metrics request timed out")})),9e4);this._instance._send_request(b({method:"POST",url:this.Su(),data:t,compression:"best-available",batchKey:"metrics"},e&&{transport:e},{fireCallbackOnDrop:!0,callback(o){var a=o.statusCode;if(a>=200&&300>a)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)}}},Lf=b({},Tr,xf,kf,If,Cf,Ff,Af,Pf,$f,Rf,Tf,Nf,Mf);Te.__defaultExtensionClasses=b({},Lf);(function(){Y.SDK_DIST_CHANNEL="npm";var t=Ys[os]=new Te;return(function(){function e(){e.done||(e.done=!0,ud=!1,Z(Ys,(function(s){s._dom_loaded()})))}C!=null&&C.addEventListener?C.readyState==="complete"?e():re(C,"DOMContentLoaded",e,{capture:!1}):v&&k.error("Browser doesn't support `document.addEventListener` so PostHog couldn't be initialized")})(),t})();const hd="CodeFile",pd="GeneratedCode",Of={CustomAction:"A",CustomWidget:"W",CustomFunction:"F",CustomClass:"C",CodeFile:"C"};function kt(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function vo(t){return String(t||"").trim().replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function Df(t={},e=0){const s=vo(t.artifactType||t.type||hd),n=vo(t.artifactName||t.name||t.fileName||`${pd}-${e+1}`);return`${s||"artifact"}-${n||e+1}`}function fd(t={},e=0){const s=kt(t),n=s.artifactType||s.type||hd,r=s.artifactName||s.name||pd;let i=s.fileName||r;return i.endsWith(".dart")||(i+=".dart"),{id:vo(s.id)||Df({...s,artifactType:n,artifactName:r,fileName:i},e),artifactType:n,artifactName:r,fileName:i,deployPath:s.deployPath||"",description:s.description||"",code:s.code||s.content||"",dependencies:gd(s.dependencies),imports:Array.isArray(s.imports)?s.imports:[],publicApi:Array.isArray(s.publicApi)?s.publicApi:[],relationships:md(s.relationships),deployStatus:s.deployStatus||"pending",review:s.review||null,metadata:kt(s.metadata),codeType:s.codeType||Of[n]||"O"}}function gd(t){return t?Array.isArray(t)?t.map(e=>{if(typeof e=="string")return{name:e,version:null,inferred:!1};const s=kt(e),n=s.name||s.package;return n?{name:n,version:s.version||null,versionRequired:!!(s.versionRequired||s.required),inferred:!!s.inferred,...s.reason?{reason:s.reason}:{}}:null}).filter(Boolean):Object.entries(kt(t)).map(([e,s])=>({name:e,version:s||null,inferred:!1})):[]}function md(t){return t?(Array.isArray(t)?t:[t]).map(e=>{const s=kt(e);return!s.from&&!s.to?null:{from:s.from||null,to:s.to||null,type:s.type||"uses",description:s.description||""}}).filter(Boolean):[]}function _o(t){if(typeof t!="string")return null;const e=t.trim();if(!e)return null;try{return JSON.parse(e)}catch{const s=e.match(/```(?:json)?\s*([\s\S]*?)```/i);if(!s)return null;try{return JSON.parse(s[1].trim())}catch{return null}}}function an(t,e={}){const s=[],n=typeof t=="string"?_o(t):t,i=kt(n||{});!n&&typeof t=="string"&&s.push("Structured bundle parse failed; using legacy single-artifact fallback.");const o=Array.isArray(i.artifacts)?i.artifacts:[{artifactType:i.artifactType||e.artifactType,artifactName:i.artifactName||e.artifactName,fileName:i.fileName||e.fileName,description:i.description,code:i.code||e.code||(typeof t=="string"?t:""),dependencies:i.dependencies||e.dependencies,relationships:i.relationships||e.relationships}];o.forEach((d,h)=>{!d?.artifactType&&!d?.type&&s.push(`Artifact ${h+1} has no artifactType; it will deploy as a standalone code file under lib/custom_code/ root.`)});const a=o.map((d,h)=>fd(d,h)),l=new Map(o.map((d,h)=>[kt(d).id,a[h]?.id]).filter(([d,h])=>d&&h)),u=d=>l.get(d)||d,c=md(i.relationships||e.relationships).map(d=>({...d,from:d.from?u(d.from):d.from,to:d.to?u(d.to):d.to}));return{schemaVersion:i.schemaVersion||e.schemaVersion||null,id:i.id||e.id||"bundle-current",title:i.title||i.name||e.title||"Generated artifact bundle",description:i.description||e.description||"",artifacts:a,dependencies:gd(i.dependencies||e.dependencies),relationships:c,deployOrder:Array.isArray(i.deployOrder)?i.deployOrder.map(u):a.map(d=>d.id),warnings:[...s,...Array.isArray(i.warnings)?i.warnings:[]],metadata:kt(i.metadata)}}function mr(t){return an(t).artifacts[0]||fd()}function yt(t){if(typeof t!="string")return t??"";const e=t.trim();if(!e)return"";try{return JSON.parse(e)}catch{return t}}function ys(t){return JSON.stringify(t,null,2)}function Bf(t){return ys({task:"architect",userRequest:String(t??"")})}function jf(t){const e=yt(t);return e&&typeof e=="object"&&typeof e.task=="string"?ys(e):ys({task:"generate_bundle",bundleSpec:e})}function Uf(t){return ys({task:"review_bundle",generatedBundle:yt(t),outputRequirements:{bundleReview:["status","score","summary","manualActions","findings"],scoreRange:[0,100],eachArtifact:["id","review.status","review.findings"],manualActions:{definition:"Setup the developer must perform by hand in the FlutterFlow editor that FlutterFlow will NOT do for them.",exclude:["creating the Custom Action, Widget or Code File itself - deploying the code creates it","declaring parameters or return values FlutterFlow derives from the function signature","anything that resolves as a side effect of using the action or widget in the editor","generic advice such as testing, reviewing or rebuilding the app"],preferEmpty:"Return an empty array when nothing qualifies - an empty list is the expected result for most bundles."}}})}function sa(t,e=null){const s={stage:t};return e!=null&&(s.bundle=yt(e)),s}function Hf({bundleSpec:t,artifactBundle:e,bundleReview:s,artifactId:n,userFeedback:r}){return ys({task:"regenerate_artifact",artifactId:n,bundleSpec:yt(t),artifactBundle:yt(e),bundleReview:yt(s),userFeedback:String(r)})}function vd({bundleSpec:t,artifactBundle:e,bundleReview:s,userFeedback:n}){return ys({task:"regenerate_bundle",bundleSpec:yt(t),artifactBundle:yt(e),bundleReview:yt(s),userFeedback:String(n??"")})}const Yl={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"},Wf=["sanitizationResult","modelArmor","modelArmorResult","data","result","error"];function Le(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function zf(t){return Le(t)?typeof t.filterMatchState=="string"||typeof t.invocationResult=="string"||Array.isArray(t.matchedFilters)||Le(t.filterSummary)||Le(t.filterResults):!1}function _d(t,e=0){if(!Le(t)||e>3)return null;if(zf(t))return t;for(const s of Wf){const n=t[s];if(Le(n)){const r=_d(n,e+1);if(r)return r}}return null}function vr(t){return Array.isArray(t)?t.some(vr):Le(t)?t.matched===!0||t.matchState==="MATCH_FOUND"?!0:Object.values(t).some(vr):!1}function yo(t){return Array.isArray(t)?t.some(yo):Le(t)?typeof t.executionState=="string"&&t.executionState!=="EXECUTION_SUCCESS"?!0:Object.values(t).some(yo):!1}function yd(t){return{csamFilterFilterResult:"csam",maliciousUriFilterResult:"malicious_uris",piAndJailbreakFilterResult:"pi_and_jailbreak",raiFilterResult:"rai",sdpFilterResult:"sdp",virusScanFilterResult:"virus_scan"}[t]||t}function qf(t,e){if(Le(t))for(const[s,n]of Object.entries(t)){if(!Le(n))continue;const r=Le(n.categories)?n.categories:{},i=Object.entries(r).filter(([,o])=>Le(o)&&o.matched===!0).map(([o])=>o);i.length>0?i.forEach(o=>e.add(o)):n.matched===!0&&e.add(yd(s))}}function Vf(t,e){if(!t)return;const s=Array.isArray(t)?t.flatMap(n=>Le(n)?Object.entries(n):[]):Object.entries(t);for(const[n,r]of s){if(!vr(r))continue;const i=yd(n),o=r?.raiFilterResult?.raiFilterTypeResults||(i==="rai"?r?.raiFilterTypeResults:null),a=Le(o)?Object.entries(o).filter(([,l])=>vr(l)).map(([l])=>l):[];a.length>0?a.forEach(l=>e.add(l)):e.add(i)}}function Gf(t){return Yl[t]?Yl[t]:String(t).replace(/([a-z])([A-Z])/g,"$1 $2").replace(/_/g," ").toLowerCase()}function Zl(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 Kf(t){const e=_d(t);if(!e)return null;const s=new Set(Array.isArray(e.matchedFilters)?e.matchedFilters:[]);qf(e.filterSummary,s),Vf(e.filterResults,s);const n=e.blocked===!0||e.filterMatchState==="MATCH_FOUND"||s.size>0,r=e.invocationResult||null,i=yo(e.filterSummary||e.filterResults);return!n&&!i&&!["PARTIAL","FAILURE"].includes(r)?null:{kind:n?"blocked":"unavailable",invocationResult:r,matchedFilters:[...s]}}function Jf(t,e){const s=Kf(t);if(!s)return null;const n=[...new Set(s.matchedFilters.map(Gf))],r=s.kind==="blocked",i=new Error(r?`Safety screening blocked this pipeline step for ${Zl(n)}.`:"Safety screening could not be completed. Please try again.");return i.name="ModelArmorError",i.code=r?"MODEL_ARMOR_BLOCKED":"MODEL_ARMOR_UNAVAILABLE",i.isModelArmor=!0,i.pipelineStep=e,i.userTitle=r?"Request blocked for safety":"Safety check unavailable",i.userMessage=r?`The safety check detected ${Zl(n)}. 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.",i.retryExplanation=r?"Trying another model would not change this safety decision.":"A fallback model was not attempted because safety screening must complete first.",i.matchedFilters=s.matchedFilters,i}function Yf(t){return String(t||"").replace(/\/\*[\s\S]*?\*\//g,"").replace(/\/\/[^\n]*/g,"")}function Xl(t){const e=/^(import|export|part|library|class|enum|extension|typedef|mixin|abstract|const|final|var|late)\b/,s=[];for(const n of Yf(t).split(` -`)){if(!/^[A-Za-z_$]/.test(n)||e.test(n))continue;const r=n.match(/^[\w$<>,?\s[\]]+?\s([a-zA-Z_$][\w$]*)\s*\(/);r&&s.push(r[1])}return s}function na(t,e){const s=t.replace(/\.dart$/,"");if(e==="W")return s.replace(/(^|_)(\w)/g,(n,r,i)=>i.toUpperCase());if(e==="A"){const n=s.replace(/(^|_)(\w)/g,(r,i,o)=>o.toUpperCase());return n.charAt(0).toLowerCase()+n.slice(1)}return e==="F"?"CustomFunctions":e==="C"?t.endsWith(".dart")?t:`${t}.dart`:s}async function Ql(t){const e=new TextEncoder().encode(String(t||"")),s=await globalThis.crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(s),n=>n.toString(16).padStart(2,"0")).join("")}async function Zf(t,e=new Map){const s={},n=new Set;for(const[o,a]of t.entries()){if(a.type==="D"||a.type==="O")continue;const l=na(o,a.type),u={old_identifier_name:l,new_identifier_name:l,type:a.type,is_deleted:!1,current_checksum:await Ql(a.content)},c=e.get(a.path);if(c!==void 0&&(u.original_checksum=await Ql(c)),s[o]=u,a.type==="F"){const d=Xl(a.content);(d.length>0?d:[a.functionName].filter(Boolean)).forEach(p=>n.add(p))}}const r=new Set(Xl(e.get("lib/flutter_flow/custom_functions.dart")||"")),i={functions_to_rename:[],functions_to_delete:[],functions_to_add:Array.from(n).filter(o=>!r.has(o))};return{fileMapContents:JSON.stringify(s),functionsMapContents:JSON.stringify(i)}}const Xf=new Set(["CustomWidget","CustomAction","CustomFunction","CustomClass","CodeFile"]),ec={CustomWidget:"custom_code/widgets/",CustomAction:"custom_code/actions/",CustomFunction:"flutter_flow/custom_functions.dart",CustomClass:"custom_code/",CodeFile:"custom_code/"},Qf=new Set(["void","dynamic","String","int","double","num","bool","Color","DateTime","DateTimeRange","LatLng","FFPlace","FFUploadedFile","DocumentReference","List"]),eg=["Struct","Record"],tg=[{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=>Pi(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=>Pi(t).some(e=>{const s=/^\s*final\s+(?:double|int|String|bool|Color|num)\s+(\w+)\s*;/gm;let n;for(;(n=s.exec(e))!==null;){const r=n[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 { +(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const n of document.querySelectorAll('link[rel="modulepreload"]'))r(n);new MutationObserver(n=>{for(const i of n)if(i.type==="childList")for(const o of i.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&r(o)}).observe(document,{childList:!0,subtree:!0});function s(n){const i={};return n.integrity&&(i.integrity=n.integrity),n.referrerPolicy&&(i.referrerPolicy=n.referrerPolicy),n.crossOrigin==="use-credentials"?i.credentials="include":n.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function r(n){if(n.ep)return;n.ep=!0;const i=s(n);fetch(n.href,i)}})();var v=typeof window<"u"?window:void 0,we=typeof globalThis<"u"?globalThis:v,ke=we?.navigator,C=we?.document,re=we?.location,Do=we?.fetch,Ni=we!=null&&we.XMLHttpRequest&&"withCredentials"in new we.XMLHttpRequest?we.XMLHttpRequest:void 0,Da=we?.AbortController,dh=we?.CompressionStream,Pe=ke?.userAgent;function Fc(){return!(!v||v.navigator.onLine===!1)}var Cs=typeof globalThis<"u"?globalThis:v;Cs&&typeof self>"u"&&(Cs.self=Cs),Cs&&typeof File>"u"&&(Cs.File=function(){});var $=v??{},Y={DEBUG:!1,LIB_VERSION:"0.5.0",LIB_NAME:"browser-common"};function Ba(t,e,s,r,n,i,o){try{var a=t[i](o),l=a.value}catch(u){return void s(u)}a.done?e(l):Promise.resolve(l).then(r,n)}function X(t){return function(){var e=this,s=arguments;return new Promise((function(r,n){var i=t.apply(e,s);function o(l){Ba(i,r,n,o,a,"next",l)}function a(l){Ba(i,r,n,o,a,"throw",l)}o(void 0)}))}}function E(){return E=Object.assign?Object.assign.bind():function(t){for(var e=1;arguments.length>e;e++){var s=arguments[e];for(var r in s)({}).hasOwnProperty.call(s,r)&&(t[r]=s[r])}return t},E.apply(null,arguments)}function Pc(t,e){if(t==null)return{};var s={};for(var r in t)if({}.hasOwnProperty.call(t,r)){if(e.indexOf(r)!==-1)continue;s[r]=t[r]}return s}var ja=t=>{if(typeof t!="string")return t;try{return JSON.parse(t)}catch{return t}};function Ua(t){return typeof t=="string"||t}function Ha(t){return typeof t=="string"?t:void 0}var Fs,hh=["$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})({}),Wa=(function(t){return t.GZipJS="gzip-js",t.Base64="base64",t})({}),ph=["$snapshot","$pageview","$pageleave","$set","survey dismissed","survey sent","survey shown","$identify","$groupidentify","$create_alias","$$client_ingestion_warning","$web_experiment_applied","$feature_enrollment_update","$feature_flag_called"],fh=["token"],Ac="NativeGzipValidationError",Mi=t=>t.length>=2&&t[0]===31&&t[1]===139,za=(t,e)=>t===Wa.GZipJS||e===Wa.GZipJS||e==="gzip",qa=t=>!(!t||typeof t!="object")&&("name"in t?String(t.name):"")==="NotReadableError",yr=t=>{var e=new Error("Native gzip produced invalid output: "+t);throw e.name=Ac,e},gh=(function(){var t=X((function*(e,s){18>e.size&&yr("too-short");var r=new Uint8Array(yield e.slice(0,10).arrayBuffer());Mi(r)&&r[2]===8||yr("invalid-header");var n=new DataView(yield e.slice(e.size-8).arrayBuffer());n.getUint32(0,!0)!==(o=>{for(var a=(()=>{if(Fs)return Fs;Fs=[];for(var c=0;256>c;c++){for(var d=c,h=0;8>h;h++)d=1&d?3988292384^d>>>1:d>>>1;Fs[c]=d>>>0}return Fs})(),l=4294967295,u=0;o.length>u;u++)l=a[255&(l^o[u])]^l>>>8;return(4294967295^l)>>>0})(s)&&yr("invalid-crc");var i=s.length>>>0;n.getUint32(4,!0)!==i&&yr("invalid-size")}));return function(e,s){return t.apply(this,arguments)}})();function Li(){return Li=X((function*(t,e,s){e===void 0&&(e=!0);try{var r=new TextEncoder().encode(t),n=new globalThis.CompressionStream("gzip"),i=n.writable.getWriter(),o=i.write(r).then((()=>i.close())).catch((function(){var u=X((function*(c){try{yield i.abort(c)}catch{}throw c}));return function(c){return u.apply(this,arguments)}})()),a=new Response(n.readable).blob(),l=(yield Promise.all([a,o]))[0];return yield gh(l,r),l}catch(u){if(s!=null&&s.rethrow)throw u;return e&&console.error("Failed to gzip compress data",u),null}})),Li.apply(this,arguments)}var mh=["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"],Va=function(t,e){if(e===void 0&&(e=[]),!t)return!1;var s=t.toLowerCase();return mh.concat(e).some((r=>{var n=r.toLowerCase();return s.indexOf(n)!==-1}))};function M(t,e){return t.indexOf(e)!==-1}var An=function(t){return t.trim()},Oi=function(t){return t.replace(/^\$/,"")};function $c(t){var e,s=[];return(e=JSON.stringify(t,(function(r,n){if(typeof n=="bigint")return n.toString();if(typeof n!="function"&&typeof n!="symbol"){if(n instanceof Error)return{name:n.name,message:n.message,stack:n.stack};if(n&&typeof n=="object"){for(;s.length>0&&s[s.length-1]!==this;)s.pop();if(s.includes(n))return"[Circular]";s.push(n)}return n}})))!==null&&e!==void 0?e:"null"}var Rc=Object.prototype,Tc=Rc.hasOwnProperty,$n=Rc.toString,L=Array.isArray||function(t){return $n.call(t)==="[object Array]"},Se=t=>typeof t=="function",te=t=>t===Object(t)&&!L(t),mt=t=>{if(te(t)){for(var e in t)if(Tc.call(t,e))return!1;return!0}return!1},x=t=>t===void 0,W=t=>$n.call(t)=="[object String]",Di=t=>W(t)&&t.trim().length===0,$e=t=>t===null,D=t=>x(t)||$e(t),he=t=>$n.call(t)=="[object Number]"&&t==t,lt=t=>he(t)&&t>0,Ke=t=>$n.call(t)==="[object Boolean]",vh=t=>t instanceof FormData,_h=t=>M(ph,t),yh=t=>M(fh,t);function Nc(t){return t===null||typeof t!="object"}function Vr(t,e){return{}.toString.call(t)==="[object "+e+"]"}function Bo(t){return typeof Event<"u"&&Mc(t,Event)}function Mc(t,e){try{return t instanceof e}catch{return!1}}var wh=[!0,"true",1,"1","yes"],ei=t=>M(wh,t),bh=[!1,"false",0,"0","no"];function rt(t,e,s,r,n){return e>s&&(r.warn("min cannot be greater than max."),e=s),he(t)?t>s?(r.warn(" cannot be greater than max: "+s+". Using max value instead."),s):e>t?(r.warn(" cannot be less than min: "+e+". Using min value instead."),e):t:(r.warn(" must be a number. using max or fallback. max: "+s+", fallback: "+n),rt(n||s,e,s,r))}class Eh{constructor(e){this.tt={},this.et=e.et,this.it=rt(e.bucketSize,0,100,e.rt),this.nt=rt(e.refillRate,0,this.it,e.rt),this.st=rt(e.refillInterval,0,864e5,e.rt)}ot(e,s){var r=Math.floor((s-e.lastAccess)/this.st);r>0&&(e.tokens=Math.min(e.tokens+r*this.nt,this.it),e.lastAccess=e.lastAccess+r*this.st)}consumeRateLimit(e){var s,r=Date.now(),n=String(e),i=this.tt[n];return i?this.ot(i,r):this.tt[n]=i={tokens:this.it,lastAccess:r},i.tokens===0||(i.tokens--,i.tokens===0&&((s=this.et)==null||s.call(this,e)),i.tokens===0)}stop(){this.tt={}}}var Oe="Mobile",Gr="iOS",vt="Android",ps="Tablet",Lc=vt+" "+ps,Oc="iPad",Dc="Apple",Bc=Dc+" Watch",qs="Safari",fs="BlackBerry",jc="Samsung",Uc=jc+"Browser",Hc=jc+" Internet",Vt="Chrome",Sh=Vt+" OS",Wc=Vt+" "+Gr,jo="Internet Explorer",zc=jo+" "+Oe,Uo="Opera",xh=Uo+" Mini",Ho="Edge",qc="Microsoft "+Ho,us="Firefox",Vc=us+" "+Gr,er="Nintendo",tr="PlayStation",ds="Xbox",Gc=vt+" "+Oe,Kc=Oe+" "+qs,Ds="Windows",Bi=Ds+" Phone",Ga="Nokia",ji="Ouya",Jc="Generic",kh=Jc+" "+Oe.toLowerCase(),Yc=Jc+" "+ps.toLowerCase(),Ui="Konqueror",Zc="Oculus Browser",Kr="Vivaldi",Xc="Yandex",Jr="Whale",Hi="DuckDuckGo",Qc="Pale Moon",Yr="Waterfox",Vs="Brave",eu="Google Search App",le="(\\d+(\\.\\d+)?)",ti=new RegExp("Version/"+le),Ih=new RegExp(ds,"i"),Ch=new RegExp(tr+" \\w+","i"),Fh=new RegExp(er+" \\w+","i"),Wo=new RegExp(fs+"|PlayBook|BB10","i"),Ph={"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"},tu=function(t,e,s,r){e=e||"";var n=(function(i){return i!=null&&i.brave?Vs:null})(s);return n||(r!=null&&r.detectGoogleSearchApp&&M(t,"GSA/")?eu:M(t," OPR/")&&M(t,"Mini")?xh:M(t," OPR/")?Uo:Wo.test(t)?fs:M(t,"IE"+Oe)||M(t,"WPDesktop")?zc:M(t,"OculusBrowser")?Zc:M(t,Uc)?Hc:M(t,Ho)||M(t,"Edg/")?qc:M(t,Kr+"/")?Kr:M(t,"YaBrowser/")?Xc:M(t,Jr+"/")?Jr:M(t,Hi+"/")||M(t,"Ddg/")?Hi:M(t,"FBIOS")?"Facebook "+Oe:M(t,"UCWEB")||M(t,"UCBrowser")?"UC Browser":M(t,"CriOS")?Wc:M(t,"CrMo")||M(t,Vt)?Vt:M(t,vt)&&M(t,qs)?Gc:M(t,"FxiOS")?Vc:M(t.toLowerCase(),Ui.toLowerCase())?Ui:M(t,Vs+"/")?Vs:((i,o)=>o&&M(o,Dc)||(function(a){return M(a,qs)&&!M(a,Vt)&&!M(a,vt)})(i))(t,e)?M(t,Oe)?Kc:qs:M(t,"PaleMoon/")?Qc:M(t,Yr+"/")?Yr:M(t,us)?us:M(t,"MSIE")||M(t,"Trident/")?jo:M(t,"Gecko")?us:"")},Ah={[zc]:[new RegExp("rv:"+le)],[qc]:[new RegExp(Ho+"?\\/"+le)],[Vt]:[new RegExp("("+Vt+"|CrMo)\\/"+le)],[Wc]:[new RegExp("CriOS\\/"+le)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+le)],[qs]:[ti],[Kc]:[ti],[Uo]:[new RegExp("(Opera|OPR)\\/"+le)],[us]:[new RegExp(us+"\\/"+le)],[Vc]:[new RegExp("FxiOS\\/"+le)],[Ui]:[new RegExp("Konqueror[:/]?"+le,"i")],[fs]:[new RegExp(fs+" "+le),ti],[Gc]:[new RegExp("android\\s"+le,"i")],[Hc]:[new RegExp(Uc+"\\/"+le)],[Zc]:[new RegExp("OculusBrowser\\/"+le)],[Kr]:[new RegExp(Kr+"\\/"+le)],[Xc]:[new RegExp("YaBrowser\\/"+le)],[Jr]:[new RegExp(Jr+"\\/"+le)],[Vs]:[new RegExp(Vs+"\\/"+le)],[Hi]:[new RegExp("(DuckDuckGo|Ddg)\\/"+le)],[Qc]:[new RegExp("PaleMoon\\/"+le)],[Yr]:[new RegExp(Yr+"\\/"+le)],[eu]:[new RegExp("GSA\\/"+le)],[jo]:[new RegExp("(rv:|MSIE )"+le)],Mozilla:[new RegExp("rv:"+le)]},$h=function(t,e,s,r){var n=tu(t,e,s,r),i=Ah[n];if(x(i))return null;for(var o=0;i.length>o;o++){var a=t.match(i[o]);if(a)return parseFloat(a[a.length-2])}return null},Ka=[[new RegExp(ds+"; "+ds+" (.*?)[);]","i"),t=>[ds,t&&t[1]||""]],[new RegExp(er,"i"),[er,""]],[new RegExp(tr,"i"),[tr,""]],[Wo,[fs,""]],[new RegExp(Ds,"i"),(t,e)=>{if(/Phone/.test(e)||/WPDesktop/.test(e))return[Bi,""];if(new RegExp(Oe).test(e)&&!/IEMobile\b/.test(e))return[Ds+" "+Oe,""];var s=/Windows NT ([0-9.]+)/i.exec(e);if(s&&s[1]){var r=Ph[s[1]]||"";return/arm/i.test(e)&&(r="RT"),[Ds,r]}return[Ds,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,t=>t&&t[3]?[Gr,[t[3],t[4],t[5]||"0"].join(".")]:[Gr,""]],[/(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i,t=>{var e="";return t&&t.length>=3&&(e=x(t[2])?t[3]:t[2]),["watchOS",e]}],[new RegExp("("+vt+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+vt+")","i"),t=>t&&t[2]?[vt,[t[2],t[3],t[4]||"0"].join(".")]:[vt,""]],[/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/,[Sh,""]],[/Linux|debian/i,["Linux",""]]],Ja=function(t){return Fh.test(t)?er:Ch.test(t)?tr:Ih.test(t)?ds:new RegExp(ji,"i").test(t)?ji:new RegExp("("+Bi+"|WPDesktop)","i").test(t)?Bi:/iPad/.test(t)?Oc:/iPod/.test(t)?"iPod Touch":/iPhone/.test(t)?"iPhone":/(watch)(?: ?os[,/]|\d,\d\/)[\d.]+/i.test(t)?Bc:Wo.test(t)?fs:/(kobo)\s(ereader|touch)/i.test(t)?"Kobo":new RegExp(Ga,"i").test(t)?Ga:/(kf[a-z]{2}wi|aeo[c-r]{2})( bui|\))/i.test(t)||/(kf[a-z]+)( bui|\)).+silk\//i.test(t)?"Kindle Fire":/(Android|ZTE)/i.test(t)?new RegExp(Oe).test(t)&&!/(9138B|TB782B|Nexus [97]|pixel c|HUAWEISHT|BTV|noble nook|smart ultra 6)/i.test(t)||/pixel[\daxl ]{1,6}/i.test(t)&&!/pixel c/i.test(t)||/(huaweimed-al00|tah-|APA|SM-G92|i980|zte|U304AA)/i.test(t)||/lmy47v/i.test(t)&&!/QTAQZ3/i.test(t)?vt:Lc:new RegExp("(pda|"+Oe+")","i").test(t)?kh:new RegExp(ps,"i").test(t)&&!new RegExp(ps+" pc","i").test(t)?Yc:""},Rh=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Ya(t,e){return typeof(s=t)=="string"&&Rh.test(s)?t:e();var s}function Ct(t){return t&&t.split("#")[0]}function zo(t,e){var s=setTimeout(t,e);return s?.unref&&s?.unref(),s}function Za(t,e,s){return su.apply(this,arguments)}function su(){return(su=X((function*(t,e,s){var r;try{return yield Promise.race([t,new Promise(((n,i)=>{r=zo((()=>{try{s?.(),n()}catch(o){i(o)}}),e)}))])}finally{clearTimeout(r)}}))).apply(this,arguments)}var Th=t=>t instanceof Error,ru={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}},Nh=ru.info;function nu(t){if(Ke(t))return{boolValue:t};if(typeof t=="number")return Number.isFinite(t)?Number.isInteger(t)?{intValue:t}:{doubleValue:t}:{stringValue:String(t)};if(typeof t=="string")return{stringValue:t};if(L(t))return{arrayValue:{values:t.map((e=>nu(e)))}};try{return{stringValue:JSON.stringify(t)}}catch{return{stringValue:String(t)}}}function Zr(t){var e=[];for(var s in t){var r=t[s];$e(r)||x(r)||e.push({key:s,value:nu(r)})}return e}function Mh(t,e){var s=ru[t.level||"info"]||Nh,r=s.text,n=s.number,i=String(Date.now())+"000000",o={};e.distinctId&&(o.posthogDistinctId=e.distinctId),e.sessionId&&(o.sessionId=e.sessionId),e.windowId&&(o["window.id"]=e.windowId),D(e.sessionStartTimestamp)||(o.sessionStartTimestamp=String(e.sessionStartTimestamp)),D(e.lastActivityTimestamp)||(o.lastActivityTimestamp=String(e.lastActivityTimestamp)),e.currentUrl&&(o["url.full"]=e.currentUrl),e.screenName&&(o["screen.name"]=e.screenName),e.appState&&(o["app.state"]=e.appState),e.activeFeatureFlags&&e.activeFeatureFlags.length>0&&(o.feature_flags=e.activeFeatureFlags);var a=E({},o,t.attributes||{}),l={timeUnixNano:i,observedTimeUnixNano:i,severityNumber:n,severityText:r,body:{stringValue:t.body},attributes:Zr(a)};return t.trace_id&&(l.traceId=t.trace_id),t.span_id&&(l.spanId=t.span_id),x(t.trace_flags)||(l.flags=t.trace_flags),l}function iu(t,e,s){return E({},t.resourceAttributes,{"service.name":t.serviceName||"unknown_service"},t.environment&&{"deployment.environment":t.environment},t.serviceVersion&&{"service.version":t.serviceVersion},{"telemetry.sdk.name":e,"telemetry.sdk.version":s})}function ou(t,e,s,r){return{resourceLogs:[{resource:{attributes:Zr(e)},scopeLogs:[{scope:{name:s,version:r},logRecords:t}]}]}}let Lh=class{constructor(t,e,s,r,n,i,o){var a;i===void 0&&(i=()=>Promise.resolve()),this._instance=t,this.Ne=e,this.rt=s,this.ut=r,this.ht=n,this.dt=i,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 s={record:Mh(e,this.ut())};this.ht((()=>this.At(s)))}}else this.rt.info("Log was rejected in beforeSend function")}}Pt(t){var e=this.Ne.beforeSend;if(!e)return t;var s=L(e)?e:[e],r=t;for(var n of s)try{var i=n(r);if(!i)return this.rt.info("Log was rejected in beforeSend function"),null;r=i}catch(o){return this.rt.error("Error in beforeSend function for log:",o),null}return r}Rt(){if(this.Tt===void 0)return!0;var t=Date.now(),e=t-this.bt;return this.Mt>e&&e>=0||(this.bt=t,this._t=0,this.wt=!1),this.Tt>this._t?(this._t++,!0):(this.wt||(this.rt.warn("captureLog dropping logs: exceeded "+this.Tt+" logs per "+this.Mt+"ms"),this.wt=!0),!1)}flush(){var t=this;return X((function*(){if(!t._instance.isDisabled)return t.ct||(t.ct=t.Ft().finally((()=>{t.ct=null}))),t.ct}))()}Ft(){var t=this;return X((function*(){var e;t.Et();var s=(e=t._instance.getPersistedProperty(ut.LogsQueue))!==null&&e!==void 0?e:[];if(s.length!==0)for(var r=s.length,n=0;s.length>0&&r>n;){var i,o;t.ft=0;var a=Math.min(s.length,t.Ct),l=s.slice(0,a),u=ou(l.map((d=>d.record)),t.Lt(),(i=t.vt)!==null&&i!==void 0?i: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),s=(o=t._instance.getPersistedProperty(ut.LogsQueue))!==null&&o!==void 0?o:[],n+=l.length,c.kind==="fatal"))throw c.error}}))()}Dt(t){var e=this;return X((function*(){var s,r=Math.max(0,t-e.ft),n=(s=e._instance.getPersistedProperty(ut.LogsQueue))!==null&&s!==void 0?s:[];e._instance.setPersistedProperty(ut.LogsQueue,n.slice(r)),yield e.dt()}))()}Lt(){return iu(this.Ne,this._instance.getLibraryId(),this._instance.getLibraryVersion())}At(t){var e;if(!this._instance.optedOut){var s=(e=this._instance.getPersistedProperty(ut.LogsQueue))!==null&&e!==void 0?e:[];this.xt>s.length||(s.shift(),this.ft++,this.rt.info("Logs queue is full, dropping oldest record.")),s.push(t),this._instance.setPersistedProperty(ut.LogsQueue,s),this.kt>s.length?this.$t():this.It()}}$t(t){t===void 0&&(t=this.St),this.Nt||(this.Nt=zo((()=>{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 X((function*(){e.Et();var s=e.flush().catch((()=>{}));t!==void 0?yield Za(s,t):yield s}))()}flushWithTimeout(t){var e=this;return X((function*(){var s=e.flush();yield Za(s,t,(()=>{s.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 si=[0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4];function Xa(t){return String(t)+"000000"}function Qa(t,e,s,r){var n="";return r&&(n=Object.keys(r).sort().map((i=>JSON.stringify(i)+":"+JSON.stringify(r[i]))).join(",")),t+"\0"+e+"\0"+(s??"")+"\0"+n}let Oh=class{constructor(t,e,s){this._instance=t,this.Ne=e,this.rt=s,this.Bt=new Map,this.ct=null,this.Ht=!1,this.Ut=new Map,this.zt=new Set,this.Wt=0}count(t,e,s){e===void 0&&(e=1),this.Vt({name:t,type:"count",value:e,unit:s?.unit,attributes:s?.attributes})}gauge(t,e,s){this.Vt({name:t,type:"gauge",value:e,unit:s?.unit,attributes:s?.attributes})}histogram(t,e,s){this.Vt({name:t,type:"histogram",value:e,unit:s?.unit,attributes:s?.attributes})}flush(){var t=this,e=this.ct,s=(function(){var n=X((function*(){e&&(yield e.catch((()=>{}))),yield t.Zt()}));return function(){return n.apply(this,arguments)}})(),r=s().finally((()=>{this.ct===r&&(this.ct=null)}));return this.ct=r,r}drainWindow(){if(this.Bt.size===0)return null;var t=this.Bt;return this.Bt=new Map,this.Ht=!1,this.Ut=new Map,this.zt=new Set,this.Gt(t)}reset(){this.Wt++,this.Et(),this.Bt=new Map,this.ct=null,this.Ht=!1,this.Ut=new Map,this.zt=new Set}Vt(t){if(!this._instance.isDisabled&&!this._instance.optedOut){var e=this.Pt(t);if(e!==null)if(e.name&&typeof e.name=="string")if(typeof e.value=="number"&&Number.isFinite(e.value))if(e.type==="count"&&0>e.value)this.rt.warn("Dropping count '"+e.name+"': counters are monotonic, value must be >= 0");else{var s,r;try{s=e.attributes?E({},e.attributes):void 0,r=Qa(e.type,e.name,e.unit,s)}catch(o){return void this.rt.warn("Dropping metric '"+e.name+"': attributes could not be serialized",o)}var n=this.Bt.get(r);if(!n){if(!this.Qt())return;n={name:e.name,type:e.type,unit:e.unit,attributes:s,windowStartMs:Date.now()},this.Bt.set(r,n)}var i=this.Ut.get(e.name);i===void 0?this.Ut.set(e.name,e.type):i===e.type||this.zt.has(e.name)||(this.zt.add(e.name),this.rt.warn("Metric name '"+e.name+"' is already used as a "+i+"; recording it as a "+e.type+" too will blend both series in charts. Use a distinct name.")),this.Kt(n,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 s;switch(t.type){case"count":t.total=((s=t.total)!==null&&s!==void 0?s: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(si.length+1).fill(0)});var r=t.hist;r.count+=1,r.sum+=e,r.min=Math.min(r.min,e),r.max=Math.max(r.max,e),r.bucketCounts[(function(n,i){for(var o=0;i.length>o;o++)if(i[o]>=n)return o;return i.length})(e,si)]+=1}}Pt(t){var e=this.Ne.beforeSend;if(!e)return t;var s=L(e)?e:[e],r=t;for(var n of s)try{var i=n(r);if(!i)return this.rt.info("Metric was rejected in beforeSend function"),null;r=i}catch(o){return this.rt.error("Error in beforeSend function for metric:",o),null}return r}$t(){this.Nt||(this.Nt=zo((()=>{this.Nt=void 0,this.flush().catch((t=>{this.rt.error("Metrics flush failed:",t)}))}),this.Ne.flushIntervalMs))}Et(){this.Nt&&(clearTimeout(this.Nt),this.Nt=void 0)}Zt(){var t=this;return X((function*(){if(t.Bt.size!==0){var e=t.Bt;t.Bt=new Map,t.Ht=!1,t.Ut=new Map,t.zt=new Set;var s=t.Wt,r=yield t._instance.Jt(t.Gt(e));if(s===t.Wt)switch(r.kind){case"ok":return;case"retry-later":return t.Yt(e),void t.$t();case"too-large":return void t.rt.warn("Metrics batch exceeded the server size limit and was dropped");case"fatal":return void t.rt.error("Failed to send metrics batch:",r.error)}}}))()}Gt(t){return e=this.Xt(t),s=(function(i,o,a){return E({},i.resourceAttributes,{"service.name":i.serviceName||"unknown_service"},i.environment&&{"deployment.environment":i.environment},i.serviceVersion&&{"service.version":i.serviceVersion},{"telemetry.sdk.name":o,"telemetry.sdk.version":a})})(this.Ne,this._instance.getLibraryId(),this._instance.getLibraryVersion()),r=this._instance.getLibraryId(),n=this._instance.getLibraryVersion(),{resourceMetrics:[{resource:{attributes:Zr(s)},scopeMetrics:[{scope:{name:r,version:n},metrics:e}]}]};var e,s,r,n}Xt(t){var e=Xa(Date.now()),s=new Map;for(var r of t.values()){var n,i=Qa(r.type,r.name,r.unit,void 0),o=s.get(i);o||(o=E({name:r.name},r.unit&&{unit:r.unit}),r.type==="count"?o.sum={aggregationTemporality:1,isMonotonic:!0,dataPoints:[]}:r.type==="gauge"?o.gauge={dataPoints:[]}:o.histogram={aggregationTemporality:1,dataPoints:[]},s.set(i,o));var a=Zr((n=r.attributes)!==null&&n!==void 0?n:{}),l=Xa(r.windowStartMs);if(r.type==="count"){var u,c={attributes:a,startTimeUnixNano:l,timeUnixNano:e,asDouble:(u=r.total)!==null&&u!==void 0?u:0};o.sum.dataPoints.push(c)}else if(r.type==="gauge"){var d,h={attributes:a,timeUnixNano:e,asDouble:(d=r.last)!==null&&d!==void 0?d:0};o.gauge.dataPoints.push(h)}else r.hist&&o.histogram.dataPoints.push({attributes:a,startTimeUnixNano:l,timeUnixNano:e,count:r.hist.count,sum:r.hist.sum,min:r.hist.min,max:r.hist.max,bucketCounts:r.hist.bucketCounts,explicitBounds:si})}return Array.from(s.values())}Yt(t){var e,s;for(var r of t){var n=r[0],i=r[1],o=this.Bt.get(n);if(o)switch(o.windowStartMs=Math.min(o.windowStartMs,i.windowStartMs),o.type){case"count":o.total=((e=o.total)!==null&&e!==void 0?e:0)+((s=i.total)!==null&&s!==void 0?s:0);break;case"gauge":break;case"histogram":if(i.hist)if(o.hist){o.hist.count+=i.hist.count,o.hist.sum+=i.hist.sum,o.hist.min=Math.min(o.hist.min,i.hist.min),o.hist.max=Math.max(o.hist.max,i.hist.max);for(var a=0;o.hist.bucketCounts.length>a;a++)o.hist.bucketCounts[a]+=i.hist.bucketCounts[a]}else o.hist=i.hist}else this.Qt()&&this.Bt.set(n,i)}}};var wr,el,ri;function Dh(t){var e=globalThis._posthogChunkIds;if(e){var s=Object.keys(e);return ri&&s.length===el||(el=s.length,ri=s.reduce(((r,n)=>{wr||(wr={});var i=wr[n];if(i)r[i[0]]=i[1];else for(var o=t(n),a=o.length-1;a>=0;a--){var l=o[a],u=l?.filename,c=e[n];if(u&&c){r[u]=c,wr[n]=[u,c];break}}return r}),{})),ri}}class Bh{constructor(e,s,r){r===void 0&&(r=[]),this.coercers=e,this.stackParser=s,this.modifiers=r}buildFromUnknown(e,s){s===void 0&&(s={});var r=s&&s.mechanism||{handled:!0,type:"generic"},n=this.buildCoercingContext(r,s,0).apply(e),i=this.buildParsingContext(s),o=this.parseStacktrace(n,i);return{$exception_list:this.convertToExceptionList(o,r),$exception_level:"error"}}modifyFrames(e){var s=this;return X((function*(){for(var r of e)r.stacktrace&&r.stacktrace.frames&&L(r.stacktrace.frames)&&(r.stacktrace.frames=yield s.applyModifiers(r.stacktrace.frames));return e}))()}coerceFallback(e){var s;return{type:"Error",value:"Unknown error",stack:(s=e.syntheticException)==null?void 0:s.stack,synthetic:!0}}parseStacktrace(e,s){var r,n;return e.cause!=null&&(r=this.parseStacktrace(e.cause,s)),e.stack!=""&&e.stack!=null&&(n=this.applyChunkIds(this.stackParser(e.stack,e.synthetic?s.skipFirstLines:0),s.chunkIdMap)),E({},e,{cause:r,stack:n})}applyChunkIds(e,s){return e.map((r=>(r.filename&&s&&(r.chunk_id=s[r.filename]),r)))}applyCoercers(e,s){for(var r of this.coercers)if(r.match(e))return r.coerce(e,s);return this.coerceFallback(s)}applyModifiers(e){var s=this;return X((function*(){var r=e;for(var n of s.modifiers)r=yield n(r);return r}))()}convertToExceptionList(e,s){var r,n,i,o={type:e.type,value:e.value,mechanism:{type:(r=s.type)!==null&&r!==void 0?r:"generic",handled:(n=s.handled)===null||n===void 0||n,synthetic:(i=e.synthetic)!==null&&i!==void 0&&i}};e.stack&&(o.stacktrace={type:"raw",frames:e.stack});var a=[o];return e.cause!=null&&a.push(...this.convertToExceptionList(e.cause,E({},s,{handled:!0}))),a}buildParsingContext(e){var s;return{chunkIdMap:Dh(this.stackParser),skipFirstLines:(s=e.skipFirstLines)!==null&&s!==void 0?s:1}}buildCoercingContext(e,s,r){r===void 0&&(r=0);var n=(i,o)=>{if(4>=o){var a=this.buildCoercingContext(e,s,o);return this.applyCoercers(i,a)}};return E({},s,{syntheticException:r==0?s.syntheticException:void 0,mechanism:e,apply:i=>n(i,r),next:i=>n(i,r+1)})}}var gs="?";function Wi(t,e,s,r,n){var i={platform:t,filename:e,function:s===""?gs:s,in_app:!0};return x(r)||(i.lineno=r),x(n)||(i.colno=n),i}var au=(t,e)=>{var s=t.indexOf("safari-extension")!==-1,r=t.indexOf("safari-web-extension")!==-1;return s||r?[t.indexOf("@")!==-1?t.split("@")[0]:gs,s?"safari-extension:"+e:"safari-web-extension:"+e]:[t,e]},jh=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,Uh=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,Hh=/\((\S*)(?::(\d+))(?::(\d+))\)/,Wh=(t,e)=>{var s=jh.exec(t);if(s)return Wi(e,s[1],gs,+s[2],+s[3]);var r=Uh.exec(t);if(r){if(r[2]&&r[2].indexOf("eval")===0){var n=Hh.exec(r[2]);n&&(r[2]=n[1],r[3]=n[2],r[4]=n[3])}var i=au(r[1]||gs,r[2]);return Wi(e,i[1],i[0],r[3]?+r[3]:void 0,r[4]?+r[4]:void 0)}},zh=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,qh=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,Vh=(t,e)=>{var s=zh.exec(t);if(s){if(s[3]&&s[3].indexOf(" > eval")>-1){var r=qh.exec(s[3]);r&&(s[1]=s[1]||"eval",s[3]=r[1],s[4]=r[2],s[5]="")}var n=s[3],i=s[1]||gs,o=au(i,n);return Wi(e,n=o[1],i=o[0],s[4]?+s[4]:void 0,s[5]?+s[5]:void 0)}},tl=/\(error: (.*)\)/;class Gh{match(e){return this.isDOMException(e)||this.isDOMError(e)}coerce(e,s){var r=W(e.stack);return{type:this.getType(e),value:this.getValue(e),stack:r?e.stack:void 0,cause:e.cause?s.next(e.cause):void 0,synthetic:!1}}getType(e){return this.isDOMError(e)?"DOMError":"DOMException"}getValue(e){var s=e.name||(this.isDOMError(e)?"DOMError":"DOMException");return e.message?s+": "+e.message:s}isDOMException(e){return Vr(e,"DOMException")}isDOMError(e){return Vr(e,"DOMError")}}class Kh{match(e){return(function(s){switch({}.toString.call(s)){case"[object Error]":case"[object Exception]":case"[object DOMException]":case"[object DOMError]":case"[object WebAssembly.Exception]":return!0;default:return Mc(s,Error)}})(e)}coerce(e,s){return{type:this.getType(e),value:this.getMessage(e,s),stack:this.getStack(e),cause:e.cause?s.next(e.cause):void 0,synthetic:!1}}getType(e){return e.name||e.constructor.name}getMessage(e,s){var r=e.message;return String(r.error&&typeof r.error.message=="string"?r.error.message:r)}getStack(e){return e.stacktrace||e.stack||void 0}}class Jh{constructor(){}match(e){return!!Vr(e,"ErrorEvent")&&(e.error!=null||this.fe(e))}coerce(e,s){var r;if(e.error!=null)return s.apply(e.error);var n=s.apply(e.message);return E({},n,{stack:(r=this.pe(e))!==null&&r!==void 0?r:n.stack,synthetic:!0})}fe(e){return W(e.message)&&e.message.length>0}pe(e){var s=e;if(W(s.filename)&&s.filename.length>0){var r,n,i=(r=s.lineno)!==null&&r!==void 0?r:0,o=(n=s.colno)!==null&&n!==void 0?n:0;return`Error + at `+s.filename+":"+i+":"+o}}}var Yh=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;class Zh{match(e){return typeof e=="string"}coerce(e,s){var r,n=this.getInfos(e),i=n[0],o=n[1];return{type:i??"Error",value:o??e,stack:(r=s.syntheticException)==null?void 0:r.stack,synthetic:!0}}getInfos(e){var s="Error",r=e,n=e.match(Yh);return n&&(s=n[1],r=n[2]),[s,r]}}var Xh=["fatal","error","warning","log","info","debug"];function lu(t,e){e===void 0&&(e=40);var s=Object.keys(t);if(s.sort(),!s.length)return"[object has no keys]";for(var r=s.length;r>0;r--){var n=s.slice(0,r).join(", ");if(e>=n.length)return r===s.length?n:n.length>e?n.slice(0,e)+"...":n}return""}class Qh{match(e){return typeof e=="object"&&e!==null}coerce(e,s){var r,n,i=this.getErrorPropertyFromObject(e);return i?s.apply(i):{type:this.getType(e),value:this.getValue(e),stack:(r=this.getStack(e))!==null&&r!==void 0?r:(n=s.syntheticException)==null?void 0:n.stack,level:this.isSeverityLevel(e.level)?e.level:"error",synthetic:!0}}getType(e){return Bo(e)?e.constructor.name:"Error"}getValue(e){if("name"in e&&typeof e.name=="string"){var s="'"+e.name+"' captured as exception";return"message"in e&&typeof e.message=="string"&&(s+=" with message: '"+e.message+"'"),s}if("message"in e&&typeof e.message=="string")return e.message;var r=this.getObjectClassName(e);return(r&&r!=="Object"?"'"+r+"'":"Object")+" captured as exception with keys: "+lu(e)}isSeverityLevel(e){return W(e)&&!Di(e)&&Xh.indexOf(e)>=0}getStack(e){try{return W(e.stacktrace)&&e.stacktrace.length>0?e.stacktrace:W(e.stack)&&e.stack.length>0?e.stack:void 0}catch{return}}getErrorPropertyFromObject(e){for(var s in e)if({}.hasOwnProperty.call(e,s)){var r=e[s];if(Th(r))return r}}getObjectClassName(e){try{var s=Object.getPrototypeOf(e);return s?s.constructor.name:void 0}catch{return}}}class ep{match(e){return Bo(e)}coerce(e,s){var r,n=e.constructor.name;return{type:n,value:n+" captured as exception with keys: "+lu(e),stack:(r=s.syntheticException)==null?void 0:r.stack,synthetic:!0}}}class tp{match(e){return Nc(e)}coerce(e,s){var r;return{type:"Error",value:"Primitive value captured as exception: "+String(e),stack:(r=s.syntheticException)==null?void 0:r.stack,synthetic:!0}}}class sp{match(e){return Vr(e,"PromiseRejectionEvent")||this.isCustomEventWrappingRejection(e)}isCustomEventWrappingRejection(e){if(!Bo(e))return!1;try{var s=e.detail;return s!=null&&typeof s=="object"&&"reason"in s}catch{return!1}}coerce(e,s){var r,n=this.getUnhandledRejectionReason(e);return Nc(n)?{type:"UnhandledRejection",value:"Non-Error promise rejection captured with value: "+String(n),stack:(r=s.syntheticException)==null?void 0:r.stack,synthetic:!0}:s.apply(n)}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 Xr="$message",Qr="$timestamp",rp=new Set([Xr,Qr]),ni={enabled:!0,max_bytes:32768};function en(t){var e;return t?{enabled:(e=t.enabled)!==null&&e!==void 0?e:ni.enabled,max_bytes:ip(t.max_bytes,ni.max_bytes)}:E({},ni)}class np{constructor(e){this.Ke=[],this.Je=0,this.Ne=en(e)}setConfig(e){this.Ne=en(e),this.Xe()}add(e){var s=(function(n){var i;try{i=$c(n)}catch{return}try{var o=JSON.parse(i);if(!te(o))return;var a=o,l=a[Xr],u=a[Qr];return!W(l)||l.trim().length===0||!W(u)&&!he(u)?void 0:{step:a,json:i}}catch{return}})(e);if(s){var r=(function(n){if(typeof TextEncoder<"u")return new TextEncoder().encode(n).length;for(var i=encodeURIComponent(n),o=0,a=0;i.length>a;a++)i[a]==="%"?(o+=1,a+=2):o+=1;return o})(s.json);r>this.Ne.max_bytes||(this.Ke.push({step:s.step,bytes:r}),this.Je+=r,this.Xe())}}getAttachable(){return this.Ke.map((e=>e.step))}clear(){this.Ke=[],this.Je=0}size(){return this.Ke.length}Xe(){for(;this.Je>this.Ne.max_bytes&&this.Ke.length>0;){var e=this.Ke.shift();e&&(this.Je-=e.bytes)}}}function ip(t,e){if(!he(t)||t===1/0||t===-1/0)return e;var s=Math.floor(t);return 0>s?e:s}var cu=function(t,e){var s=(e===void 0?{}:e).debugEnabled,r={k(n){if(v&&(Y.DEBUG||v.POSTHOG_DEBUG||s)&&!x(v.console)&&v.console){for(var i=("__rrweb_original__"in v.console[n])?v.console[n].__rrweb_original__:v.console[n],o=arguments.length,a=new Array(o>1?o-1:0),l=1;o>l;l++)a[l-1]=arguments[l];i(t,...a)}},debug(){for(var n=arguments.length,i=new Array(n),o=0;n>o;o++)i[o]=arguments[o];r.k("debug",...i)},info(){for(var n=arguments.length,i=new Array(n),o=0;n>o;o++)i[o]=arguments[o];r.k("log",...i)},warn(){for(var n=arguments.length,i=new Array(n),o=0;n>o;o++)i[o]=arguments[o];r.k("warn",...i)},error(){for(var n=arguments.length,i=new Array(n),o=0;n>o;o++)i[o]=arguments[o];r.k("error",...i)},critical(){for(var n=arguments.length,i=new Array(n),o=0;n>o;o++)i[o]=arguments[o];console.error(t,...i)},uninitializedWarning(n){r.error("You must initialize PostHog before calling "+n)},createLogger:(n,i)=>cu(t+" "+n,i)};return r},k=cu("[PostHog.js]"),se=k.createLogger,op=se("[ExternalScriptsLoader]"),ii=(t,e,s)=>{if(t.config.disable_external_dependency_loading)return op.warn(e+" was requested but loading of external scripts is disabled."),s("Loading of external scripts is disabled");var r=C?.querySelectorAll("script");if(r){for(var n,i=function(){if(r[o].src===e){var l=r[o];return l.__posthog_loading_callback_fired?{v:s()}:(l.addEventListener("load",(u=>{l.__posthog_loading_callback_fired=!0,s(void 0,u)})),l.onerror=u=>s(u),{v:void 0})}},o=0;r.length>o;o++)if(n=i())return n.v}var a=()=>{if(!C)return s("document not found");var l=C.createElement("script");if(l.type="text/javascript",l.crossOrigin="anonymous",l.src=e,l.onload=d=>{l.__posthog_loading_callback_fired=!0,s(void 0,d)},l.onerror=d=>s(d),t.config.prepare_external_dependency_script&&(l=t.config.prepare_external_dependency_script(l)),!l)return s("prepare_external_dependency_script returned null");if(t.config.external_scripts_inject_target==="head")C.head.appendChild(l);else{var u,c=C.querySelectorAll("body > script");c.length>0?(u=c[0].parentNode)==null||u.insertBefore(l,c[0]):C.body.appendChild(l)}};C!=null&&C.body?a():C?.addEventListener("DOMContentLoaded",a)};$.__PosthogExtensions__=$.__PosthogExtensions__||{},$.__PosthogExtensions__.loadExternalDependency=(t,e,s)=>{if(e!=="remote-config"){var r;if(t.config.strict_script_versioning)r=t.requestRouter.endpointFor("assets","/static/"+t.version+"/"+e+".js");else{var n="/static/"+e+".js?v="+t.version;if(e==="toolbar"){var i=3e5;n=n+"&t="+Math.floor(Date.now()/i)*i}r=t.requestRouter.endpointFor("assets",n)}ii(t,r,s)}else{var o=t.requestRouter.endpointFor("assets","/array/"+t.config.token+"/config.js");ii(t,o,s)}},$.__PosthogExtensions__.loadSiteApp=(t,e,s)=>{var r=t.requestRouter.endpointFor("api",e);ii(t,r,s)};Y.DEBUG=!1,Y.LIB_VERSION="1.415.7",Y.LIB_NAME="web";var uu="$people_distinct_id",sr="$device_id",oi="$device_model",Bs="__alias",js="__timers",zi="$autocapture_disabled_server_side",qi="$heatmaps_enabled_server_side",Vi="$exception_capture_enabled_server_side",Gi="$error_tracking_suppression_rules",Ki="$error_tracking_capture_extension_exceptions",Ji="$web_vitals_enabled_server_side",qo="$dead_clicks_enabled_server_side",Vo="$product_tours_enabled_server_side",Yi="$web_vitals_allowed_metrics",qt="$session_recording_remote_config",du="$replay_sample_rate",hu="$replay_override_sampling",pu="$replay_override_linked_flag",fu="$replay_override_url_trigger",gu="$replay_override_event_trigger",ls="$sesid",Go="$session_is_sampled",Bt="$enabled_feature_flags",Us="$active_feature_flags",Rr="$early_access_features",Zi="$feature_flag_details",Hs="$feature_flag_payloads",Tr="$feature_flag_request_id",tn="$minimal_flag_called_events",et="$override_feature_flags",jt="$override_feature_flag_payloads",ct="$stored_person_properties",Ut="$stored_group_properties",Xi="$surveys",sn="$surveys_loaded_at",Qi="$surveys_activated",Nr="$surveys_activated_session",Mr="$surveys_activated_timestamps",Ws="ph_product_tours",Wt="$flag_call_reported",zs="$flag_call_reported_session_id",Lr="$feature_flag_errors",Gs="$feature_flag_evaluated_at",He="$user_state",eo="$client_session_props",to="$capture_rate_limit",so="$initial_campaign_params",ro="$initial_referrer_info",rn="$initial_person_info",nn="$epp",br="$posthog_cookieless",mu="$cookieless_mode",vu="$sdk_debug_extensions_init_method",_u="$sdk_debug_extensions_init_time_ms",yu="$sdk_debug_recording_script_not_loaded",Ko="PostHog loadExternalDependency extension not found.",Ht="on_reject",ht="always",es="anonymous",Tt="identified",no="identified_only",on="visibilitychange",an="beforeunload",is="$pageview",ai="$pageleave",li="$identify",sl="$groupidentify";function Er(t,e){L(t)&&t.forEach(e)}function Z(t,e){if(!D(t))if(L(t))t.forEach(e);else if(vh(t))t.forEach(((r,n)=>e(r,n)));else for(var s in t)Tc.call(t,s)&&e(t[s],s)}var ee=function(t){for(var e=arguments.length,s=new Array(e>1?e-1:0),r=1;e>r;r++)s[r-1]=arguments[r];for(var n of s)for(var i in n)n[i]!==void 0&&(t[i]=n[i]);return t};function Or(t){for(var e=Object.keys(t),s=e.length,r=new Array(s);s--;)r[s]=[e[s],t[e[s]]];return r}var rl=function(t){try{return t()}catch{return}},ap=function(t){return function(){try{for(var e=arguments.length,s=new Array(e),r=0;e>r;r++)s[r]=arguments[r];return t.apply(this,s)}catch(n){k.critical("Implementation error. Please turn on debug mode and open a ticket on https://app.posthog.com/home#panel=support%3Asupport%3A."),k.critical(n)}}},Jo=function(t){var e={};return Z(t,(function(s,r){(W(s)&&s.length>0||he(s))&&(e[r]=s)})),e},lp=["herokuapp.com","vercel.app","netlify.app"];function cp(t){var e=t?.hostname;if(!W(e))return!1;var s=e.split(".").slice(-2).join(".");for(var r of lp)if(s===r)return!1;return!0}function ne(t,e,s,r){var n=r??{},i=n.capture,o=n.passive;t?.addEventListener(e,s,{capture:i!==void 0&&i,passive:o===void 0||o})}function io(t){return t.name==="ph_toolbar_internal"}var wu=t=>{if(C){try{for(var e=t+"=",s=C.cookie.split(";").filter((i=>i.length)),r=0;s.length>r;r++){for(var n=s[r];n.charAt(0)==" ";)n=n.substring(1,n.length);if(n.indexOf(e)===0)return decodeURIComponent(n.substring(e.length,n.length))}}catch{}return null}};Math.trunc||(Math.trunc=function(t){return 0>t?Math.ceil(t):Math.floor(t)}),Number.isInteger||(Number.isInteger=function(t){return he(t)&&isFinite(t)&&Math.floor(t)===t});class ln{constructor(e){if(this.bytes=e,e.length!==16)throw new TypeError("not 128-bit length")}static fromFieldsV7(e,s,r,n){if(!Number.isInteger(e)||!Number.isInteger(s)||!Number.isInteger(r)||!Number.isInteger(n)||0>e||0>s||0>r||0>n||e>0xffffffffffff||s>4095||r>1073741823||n>4294967295)throw new RangeError("invalid field value");var i=new Uint8Array(16);return i[0]=e/Math.pow(2,40),i[1]=e/Math.pow(2,32),i[2]=e/Math.pow(2,24),i[3]=e/Math.pow(2,16),i[4]=e/256,i[5]=e,i[6]=112|s>>>8,i[7]=s,i[8]=128|r>>>24,i[9]=r>>>16,i[10]=r>>>8,i[11]=r,i[12]=n>>>24,i[13]=n>>>16,i[14]=n>>>8,i[15]=n,new ln(i)}toString(){for(var e="",s=0;this.bytes.length>s;s++)e=e+(this.bytes[s]>>>4).toString(16)+(15&this.bytes[s]).toString(16),s!==3&&s!==5&&s!==7&&s!==9||(e+="-");if(e.length!==36)throw new Error("Invalid UUIDv7 was generated");return e}clone(){return new ln(this.bytes.slice(0))}equals(e){return this.compareTo(e)===0}compareTo(e){for(var s=0;16>s;s++){var r=this.bytes[s]-e.bytes[s];if(r!==0)return Math.sign(r)}return 0}}class up{generate(){var e=this.generateOrAbort();if(!x(e))return e;this.S=0;var s=this.generateOrAbort();if(x(s))throw new Error("Could not generate UUID after timestamp reset");return s}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 ln.fromFieldsV7(this.S,Math.trunc(this.I/Math.pow(2,30)),this.I&Math.pow(2,30)-1,this.A.nextUint32())}C(){this.I=1024*this.A.nextUint32()+(1023&this.A.nextUint32())}constructor(){this.S=0,this.I=0,this.A=new dp}}var nl,bu=t=>{if(typeof UUIDV7_DENY_WEAK_RNG<"u"&&UUIDV7_DENY_WEAK_RNG)throw new Error("no cryptographically strong RNG available");for(var e=0;t.length>e;e++)t[e]=65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random());return t};v&&!x(v.crypto)&&crypto.getRandomValues&&(bu=t=>crypto.getRandomValues(t));class dp{nextUint32(){return this.R.length>this.O||(bu(this.R),this.O=0),this.R[this.O++]}constructor(){this.R=new Uint32Array(8),this.O=1/0}}var dt=()=>hp().toString(),hp=()=>(nl||(nl=new up)).generate(),Ps="",pp=/[a-z0-9][a-z0-9-]+\.[a-z]{2,}$/i,pt={N:()=>!!C,j(t){k.error("cookieStore error: "+t)},P:wu,H(t){var e;try{e=JSON.parse(pt.P(t))||{}}catch{}return e},F(t,e,s,r,n){if(!C)return!1;try{var i="",o="",a=(function(c,d){if(d){var h=(function(f,m){if(m===void 0&&(m=C),Ps)return Ps;if(!m||["localhost","127.0.0.1"].includes(f))return"";for(var g=f.split("."),_=Math.min(g.length,8),w="dmn_chk_"+dt();!Ps&&_--;){var b=g.slice(_).join("."),I=w+"=1;domain=."+b+";path=/";m.cookie=I+";max-age=3",m.cookie.includes(w)&&(m.cookie=I+";max-age=0",Ps=b)}return Ps})(c);if(!h){var p=(f=>{var m=f.match(pp);return m?m[0]:""})(c);p!==h&&k.info("Warning: cookie subdomain discovery mismatch",p,h),h=p}return h?"; domain=."+h:""}return""})(C.location.hostname,r);if(s){var l=new Date;l.setTime(l.getTime()+864e5*s),i="; expires="+l.toUTCString()}n&&(o="; secure");var u=t+"="+encodeURIComponent(JSON.stringify(e))+i+"; SameSite=Lax; path=/"+a+o;return u.length>3686.4&&k.warn("cookieStore warning: large cookie, len="+u.length),C.cookie=u,!0}catch{return!1}},q(t,e){if(C!=null&&C.cookie)try{pt.F(t,"",-1,e)}catch{return}}},ci=null,Q={N(){if(!$e(ci))return ci;var t=!0;if(x(v))t=!1;else try{var e="__mplssupport__";Q.F(e,"xyz"),Q.P(e)!=='"xyz"'&&(t=!1),Q.q(e)}catch{t=!1}return t||k.error("localStorage unsupported; falling back to cookie store"),ci=t,t},j(t){k.error("localStorage error: "+t)},P(t){try{return v?.localStorage.getItem(t)}catch(e){Q.j(e)}return null},H(t){try{return JSON.parse(Q.P(t))||{}}catch{}return null},F(t,e){try{return v?.localStorage.setItem(t,JSON.stringify(e)),!0}catch(s){Q.j(s)}return!1},q(t){try{v?.localStorage.removeItem(t)}catch(e){Q.j(e)}}},fp=[sr,"distinct_id",ls,Go,nn,rn,He],Sr={},gp={N:()=>!0,j(t){k.error("memoryStorage error: "+t)},P:t=>Sr[t]||null,H:t=>Sr[t]||null,F:(t,e)=>(Sr[t]=e,!0),q(t){delete Sr[t]}},Nt=null,ce={N(){if(!$e(Nt))return Nt;if(Nt=!0,x(v))Nt=!1;else try{var t="__support__";ce.F(t,"xyz"),ce.P(t)!=='"xyz"'&&(Nt=!1),ce.q(t)}catch{Nt=!1}return Nt},j(t){k.error("sessionStorage error: ",t)},P(t){try{return v?.sessionStorage.getItem(t)}catch(e){ce.j(e)}return null},H(t){try{return JSON.parse(ce.P(t))||null}catch{}return null},F(t,e){try{return v?.sessionStorage.setItem(t,JSON.stringify(e)),!0}catch(s){ce.j(s)}return!1},q(t){try{v?.sessionStorage.removeItem(t)}catch(e){ce.j(e)}}};class mp{constructor(e){this._instance=e}get Ne(){return this._instance.config}get consent(){return this.ti()?0:this.ei}isOptedOut(){return this.Ne.cookieless_mode===ht||this.isRejected()||this.consent===-1&&this.Ne.cookieless_mode===Ht}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,s=e.token,r=e.opt_out_capturing_cookie_prefix;return e.consent_persistence_name||(r?r+s:"__ph_opt_in_out_"+s)}get ei(){var e=this.ii.P(this.ri);return ei(e)?1:M(bh,e)?0:-1}get ii(){var e=this.Ne.opt_out_capturing_persistence_type,s=e==="localStorage"?Q:pt;if(!this.ni||this.ni!==s){this.ni=s;var r=e==="localStorage"?pt:Q;r.P(this.ri)&&(this.ni.P(this.ri)||this.optInOut(ei(r.P(this.ri))),r.q(this.ri,this.Ne.cross_subdomain_cookie))}return this.ni}ti(){return!!this.Ne.respect_dnt&&[ke?.doNotTrack,ke?.msDoNotTrack,$.doNotTrack].some((e=>ei(e)))}}function Eu(t,e){var s,r=t==null||(s=t.config)==null?void 0:s.get_current_url;if(!Se(r))return e;try{var n=r(e);return W(n)&&n?n:e}catch(i){return k.error("Error in get_current_url, falling back to window.location.href",i),e}}var Su="__POSTHOG_TOOLBAR__",vp=1,_p=3,yp=11;function il(t){return t instanceof Element&&(t.id===Su||!(t.closest==null||!t.closest(".toolbar-global-fade-container")))}function Ft(t){return!!t&&t.nodeType===vp}function Me(t,e){return!!t&&!!t.tagName&&t.tagName.toLowerCase()===e.toLowerCase()}function xu(t){return!!t&&t.nodeType===_p}function ku(t){return!!t&&t.nodeType===yp&&Ft(t.host)}var Iu=1e3;function Yo(t){return t?An(t).split(/\s+/):[]}function ol(t,e){var s=(function(r){var n,i=v==null||(n=v.location)==null?void 0:n.href;return x(i)?void 0:Eu(r,i)})(e);return!!(s&&t&&t.some((r=>s.match(r))))}function cn(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 Yo(e)}function Cu(t){return D(t)?null:An(t).split(/(\s+)/).filter((e=>Ks(e))).join("").replace(/[\r\n]/g," ").replace(/[ ]+/g," ").substring(0,255)}function rr(t){var e="";return ao(t)&&!$u(t)&&t.childNodes&&t.childNodes.length&&Z(t.childNodes,(function(s){var r;xu(s)&&s.textContent&&(e+=(r=Cu(s.textContent))!==null&&r!==void 0?r:"")})),An(e)}function ui(t){var e;return x(t.target)?t.srcElement||null:(e=t.target)!=null&&e.shadowRoot?t.composedPath()[0]||null:t.target||null}var Zo=["a","button","form","input","select","textarea","label"];function oo(t,e){if(x(e))return!0;var s,r=function(i){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}})(i,o))))return{v:!0}};for(var n of t)if(s=r(n))return s.v;return!1}function Fu(t){var e=t.parentNode;return!(!e||!Ft(e))&&e}var wp=[".ph-no-autocapture","[data-ph-no-autocapture]"],Pu=["next","previous","prev",">","<"],bp=[...Pu,"+","-","−","–"],al=(t,e)=>/[a-z0-9]/i.test(e)?t.includes(e):t===e,ll=[".ph-no-rageclick",".ph-no-capture"],Ep=["","text","search","email","password","url","tel","number"];function cl(t,e){if(!v||Xo(t))return!1;var s,r,n,i,o;if(Ke(e)?(s=!!e&&ll,r=void 0,n=!1):(s=(i=e?.css_selector_ignorelist)!==null&&i!==void 0?i:ll,r=e?.content_ignorelist,n=(o=e?.ignore_text_selection)!==null&&o!==void 0&&o),s===!1||n&&(function(l){return!(!l||!Ft(l))&&(!!Me(l,"textarea")||(Me(l,"input")?M(Ep,(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=Au(t,!1).targetElementList;return!(function(l,u){if(l===!1||x(l))return!1;var c;if(l===!0)c=Pu;else{if(!L(l))return!1;if(l.length>10)return k.error("[PostHog] content_ignorelist array cannot exceed 10 items. Use css_selector_ignorelist for more complex matching."),!1;c=l.map((d=>d.toLowerCase()))}return u.some((d=>{var h=d.safeText,p=d.ariaLabel;return c.some((f=>al(h,f)||al(p,f)))}))})(r,a.map((l=>{var u;return{safeText:rr(l).toLowerCase(),ariaLabel:((u=l.getAttribute("aria-label"))==null?void 0:u.toLowerCase().trim())||""}})))&&!oo(a,s)}var Xo=t=>!t||Me(t,"html")||!Ft(t),Au=(t,e)=>{if(!v||Xo(t))return{parentIsUsefulElement:!1,targetElementList:[]};for(var s=!1,r=[t],n=t;n.parentNode&&!Me(n,"body");)if(ku(n.parentNode))r.push(n.parentNode.host),n=n.parentNode.host;else{var i=Fu(n);if(!i)break;if(e||Zo.indexOf(i.tagName.toLowerCase())>-1)s=!0;else try{var o=v.getComputedStyle(i);o&&o.getPropertyValue("cursor")==="pointer"&&(s=!0)}catch{}r.push(i),n=i}return{parentIsUsefulElement:s,targetElementList:r}};function ao(t){for(var e=new Set,s=0,r=t;r.parentNode&&!Me(r,"body");r=r.parentNode){if(s++>=Iu||e.has(r))return!1;e.add(r);var n=cn(r);if(M(n,"ph-sensitive")||M(n,"ph-no-capture"))return!1}if(M(cn(t),"ph-include"))return!0;var i=t.type||"";if(W(i))switch(i.toLowerCase()){case"hidden":case"password":return!1}var o=t.name||t.id||"";return!W(o)||!/^cc|cardnum|ccnum|creditcard|csc|cvc|cvv|exp|pass|pwd|routing|seccode|securitycode|securitynum|socialsec|socsec|ssn/i.test(o.replace(/[^a-zA-Z0-9]/g,""))}function $u(t){return!!(Me(t,"input")&&!["button","checkbox","submit","reset"].includes(t.type)||Me(t,"select")||Me(t,"textarea")||t.getAttribute("contenteditable")==="true")}var ul=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}))$"),dl=/(^|[^0-9A-Za-z_])([0-9][0-9 -]*[0-9])(?=$|[^0-9A-Za-z_])/g,Sp=[16,15,14,13],xp=new RegExp("^(\\d{3}-?\\d{2}-?\\d{4})$"),hl=new RegExp("(^|[^0-9])((?!000|666)[0-9]{3}-?(?!00)[0-9]{2}-?(?!0000)[0-9]{4})(?=$|([^0-9]))","g"),pl=/[0-9A-Za-z_]/;function kp(t){for(var e=0,s=!1,r=t.length-1;r>=0;r--){var n=t.charCodeAt(r)-48;s&&(n*=2)>9&&(n-=9),e+=n,s=!s}return e%10==0}function Ks(t,e){if(e===void 0&&(e=!0),D(t))return!1;if(W(t)){t=An(t);var s=e?ul.test((t||"").replace(/[- ]/g,"")):(function(n){var i;for(dl.lastIndex=0;i=dl.exec(n);){var o=i[2];if(o)for(var a=o.replace(/[- ]/g,""),l=0;a.length>l;l++)for(var u of Sp){var c=l+u;if(a.length>=c){var d=a.slice(l,c);if(ul.test(d)&&kp(d))return!0}}}return!1})(t);if(s)return!1;var r=e?xp.test(t):(function(n){var i;for(hl.lastIndex=0;i=hl.exec(n);){var o=i[1],a=i[3];if(!(o&&a&&pl.test(o)&&pl.test(a)))return!0}return!1})(t);if(r)return!1}return!0}function fl(t){var e=rr(t);return Ks(e=(e+" "+Ru(t)).trim())?e:""}function Ru(t){var e="";return t&&t.childNodes&&t.childNodes.length&&Z(t.childNodes,(function(s){var r;if(s&&((r=s.tagName)==null?void 0:r.toLowerCase())==="span")try{var n=rr(s);e=(e+" "+n).trim(),s.childNodes&&s.childNodes.length&&(e=(e+" "+Ru(s)).trim())}catch(i){k.error("[AutoCapture]",i)}})),e}function gl(t){return t.replace(/"|\\"/g,'\\"')}function Ip(t){var e=t.attr__class;if(e)return L(e)?e:Yo(e)}var xr=se("[Dead Clicks]"),Cp=()=>!0,Fp=t=>{var e,s=!((e=t.instance.persistence)==null||!e.get_property(qo)),r=t.instance.config.capture_dead_clicks;return Ke(r)?r:!!te(r)||s};class ml{get lazyLoadedDeadClicksAutocapture(){return this.si}constructor(e,s,r){this.instance=e,this.isEnabled=s,this.onCapture=r,this.startIfEnabledOrStop()}onRemoteConfig(e){if(e.ok){var s=e.config;"captureDeadClicks"in s&&(this.instance.persistence&&this.instance.persistence.register({[qo]:s.captureDeadClicks}),this.startIfEnabledOrStop())}}startIfEnabledOrStop(){this.isEnabled(this)?this.ai((()=>{this.oi()})):this.stop()}ai(e){var s,r;(s=$.__PosthogExtensions__)!=null&&s.initDeadClicksAutocapture?e():(r=$.__PosthogExtensions__)==null||r.loadExternalDependency==null||r.loadExternalDependency(this.instance,"dead-clicks-autocapture",(n=>{n?xr.error("failed to load script",n):e()}))}oi(){var e;if(C){if(!this.si&&(e=$.__PosthogExtensions__)!=null&&e.initDeadClicksAutocapture){var s=te(this.instance.config.capture_dead_clicks)?E({},this.instance.config.capture_dead_clicks):{};s.__onCapture=this.onCapture,this.onCapture&&(s.capture_dead_swipes=!1),this.si=$.__PosthogExtensions__.initDeadClicksAutocapture(this.instance,s),this.si.start(C),xr.info("starting...")}}else xr.error("`document` not found. Cannot start.")}stop(){this.si&&(this.si.stop(),this.si=void 0,xr.info("stopping..."))}}var di=se("[SegmentIntegration]"),Tu="posthog-js";function Nu(t,e){var s=e===void 0?{}:e,r=s.organization,n=s.projectId,i=s.prefix,o=s.severityAllowList,a=o===void 0?["error"]:o,l=s.sendExceptionsToPostHog,u=l===void 0||l;return c=>{var d,h,p,f,m;if(a!=="*"&&!a.includes(c.level)||!t.__loaded)return c;c.tags||(c.tags={});var g=t.requestRouter.endpointFor("ui","/project/"+t.config.token+"/person/"+t.get_distinct_id());c.tags["PostHog Person URL"]=g,t.sessionRecordingStarted()&&(c.tags["PostHog Recording URL"]=t.get_session_replay_url({withTimestamp:!0}));var _,w=((d=c.exception)==null?void 0:d.values)||[],b=w.map((F=>E({},F,{stacktrace:F.stacktrace?E({},F.stacktrace,{type:"raw",frames:(F.stacktrace.frames||[]).map((P=>E({},P,{platform:"web:javascript"})))}):void 0}))),I={$exception_message:((h=w[0])==null?void 0:h.value)||c.message,$exception_type:(p=w[0])==null?void 0:p.type,$exception_level:c.level,$exception_list:b,$sentry_event_id:c.event_id,$sentry_exception:c.exception,$sentry_exception_message:((f=w[0])==null?void 0:f.value)||c.message,$sentry_exception_type:(m=w[0])==null?void 0:m.type,$sentry_tags:c.tags};return r&&n&&(I.$sentry_url=(i||"https://sentry.io/organizations/")+r+"/issues/?project="+n+"&query="+c.event_id),u&&((_=t.exceptions)==null||_.sendExceptionEvent(I)),c}}class Pp{constructor(e,s,r,n,i,o){this.name=Tu,this.setupOnce=function(a){a(Nu(e,{organization:s,projectId:r,prefix:n,severityAllowList:i,sendExceptionsToPostHog:o==null||o}))}}}class vl{constructor(e){this.li=(s,r,n)=>{n&&(n.noSessionId||n.activityTimeout||n.sessionPastMaximumLength||n.crossTabAdoption)&&(k.info("[PageViewManager] Session rotated, clearing pageview state",{sessionId:s,changeReason:n}),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,s){var r,n=this.vi(e,s);return this.ui={pathname:(r=v?.location.pathname)!==null&&r!==void 0?r:"",pageViewId:s,timestamp:e},this._instance.scrollManager.resetContext(),n}doPageLeave(e){var s;return this.vi(e,(s=this.ui)==null?void 0:s.pageViewId)}doEvent(){var e;return{$pageview_id:(e=this.ui)==null?void 0:e.pageViewId}}vi(e,s){var r=this.ui;if(!r)return{$pageview_id:s};var n={$pageview_id:s,$prev_pageview_id:r.pageViewId},i=this._instance.scrollManager.getContext();if(i&&!this._instance.config.disable_scroll_properties){var o=i.maxScrollHeight,a=i.lastScrollY,l=i.maxScrollY,u=i.maxContentHeight,c=i.lastContentY,d=i.maxContentY;if(!(x(o)||x(a)||x(l)||x(u)||x(c)||x(d))){o=Math.ceil(o),a=Math.ceil(a),l=Math.ceil(l),u=Math.ceil(u),c=Math.ceil(c),d=Math.ceil(d);var h=o>1?rt(a/o,0,1,k):1,p=o>1?rt(l/o,0,1,k):1,f=u>1?rt(c/u,0,1,k):1,m=u>1?rt(d/u,0,1,k):1;n=ee(n,{$prev_pageview_last_scroll:a,$prev_pageview_last_scroll_percentage:h,$prev_pageview_max_scroll:l,$prev_pageview_max_scroll_percentage:p,$prev_pageview_last_content:c,$prev_pageview_last_content_percentage:f,$prev_pageview_max_content:d,$prev_pageview_max_content_percentage:m})}}return r.pathname&&(n.$prev_pageview_pathname=r.pathname),r.timestamp&&(n.$prev_pageview_duration=(e.getTime()-r.timestamp.getTime())/1e3),n}}var hi=["flags","surveys"],Ap={[uu]:{exposure:"hidden"},[Bs]:{exposure:"hidden"},__cmpns:{exposure:"hidden"},[js]:{exposure:"hidden"},[zi]:{exposure:"event"},[qi]:{exposure:"hidden"},[Vi]:{exposure:"event"},[Gi]:{exposure:"hidden"},[Ki]:{exposure:"event"},[Ji]:{exposure:"event"},[qo]:{exposure:"event"},[Vo]:{exposure:"hidden"},[Yi]:{exposure:"event"},[qt]:{exposure:"hidden"},$session_recording_enabled_server_side:{exposure:"hidden"},[ls]:{exposure:"hidden"},[Go]:{exposure:"event"},[du]:{exposure:"event",shouldSkipFromEventProperties:t=>$e(t)},$session_past_minimum_duration:{exposure:"event"},$session_recording_url_trigger_activated_session:{exposure:"event"},$session_recording_event_trigger_activated_session:{exposure:"event"},$debug_first_full_snapshot_timestamp:{exposure:"event"},$sess_rec_flush_size:{exposure:"hidden"},[Bt]:{exposure:"hidden",storageGroup:"flags"},[Us]:{exposure:"hidden",storageGroup:"flags"},[Rr]:{exposure:"hidden"},[Zi]:{exposure:"hidden",storageGroup:"flags"},[Hs]:{exposure:"hidden",storageGroup:"flags"},[Tr]:{exposure:"hidden",storageGroup:"flags",volatile:!0},[tn]:{exposure:"hidden",storageGroup:"flags"},[et]:{exposure:"hidden"},[jt]:{exposure:"hidden"},[ct]:{exposure:"hidden"},[Ut]:{exposure:"hidden"},[Xi]:{exposure:"hidden",storageGroup:"surveys"},[sn]:{exposure:"hidden",storageGroup:"surveys",volatile:!0},[Qi]:{exposure:"event"},[Nr]:{exposure:"hidden"},[Mr]:{exposure:"hidden"},[Ws]:{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"},[Wt]:{exposure:"hidden"},[zs]:{exposure:"hidden"},[Lr]:{exposure:"hidden"},[Gs]:{exposure:"hidden",storageGroup:"flags",volatile:!0},[He]:{exposure:"hidden"},[eo]:{exposure:"hidden"},[to]:{exposure:"hidden"},[so]:{exposure:"hidden"},[ro]:{exposure:"hidden"},[rn]:{exposure:"hidden"},[nn]:{exposure:"hidden"},[hu]:{exposure:"event"},[pu]:{exposure:"event"},[fu]:{exposure:"event"},[gu]:{exposure:"event"},[vu]:{exposure:"event"},[_u]:{exposure:"event"},[yu]:{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"}},$p=[["$posthog_sr_group_event_trigger_",{exposure:"hidden"}],["$posthog_sr_group_url_trigger_",{exposure:"hidden"}],["$posthog_sr_group_sampling_",{exposure:"hidden"}]],Mt=t=>{var e=Ap[t];if(e)return e;for(var s of $p){var r=s[1];if(t.indexOf(s[0])===0)return r}},cs=(t,e)=>{try{return JSON.stringify(t,((s,r)=>typeof r=="bigint"?r.toString():r),e)}catch{return $c(t)}},un=t=>{var e=C?.createElement("a");return x(e)?null:(e.href=t,e)},ms=function(t,e){for(var s,r=((t.split("#")[0]||"").split(/\?(.*)/)[1]||"").replace(/^\?+/g,"").split("&"),n=0;r.length>n;n++){var i=r[n].split("=");if(i[0]===e){s=i;break}}if(!L(s)||2>s.length)return"";var o=s[1];try{o=decodeURIComponent(o)}catch{k.error("Skipping decoding for malformed query param: "+o)}return o.replace(/\+/g," ")},nr=function(t,e,s){if(!t||!e||!e.length)return t;for(var r=t.split("#"),n=r[1],i=(r[0]||"").split("?"),o=i[1],a=i[0],l=(o||"").split("&"),u=[],c=0;l.length>c;c++){var d=l[c].split("=");L(d)&&(e.includes(d[0])?u.push(d[0]+"="+s):u.push(l[c]))}var h=a;return o!=null&&(h+="?"+u.join("&")),n!=null&&(h+="#"+n),h},dn=function(t,e){var s=t.match(new RegExp(e+"=([^&]*)"));return s?s[1]:null},Mu=(t,e)=>t>=e&&Fc(),Lu=(t,e,s,r)=>{if(t===0){if(Fc()){var n=e+1;return n===s&&r(),n}return e}return 0},kr="https?://(.*)",vs=["gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","irclid","_kx"],Rp=["utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid",...vs],ir="",Tp=["li_fat_id"];function Ou(t,e,s){if(!C)return{};var r,n=e?[...vs,...s||[]]:[],i=Du(nr(C.URL,n,ir),t),o=(r={},Z(Tp,(function(a){var l=wu(a);r[a]=l||null})),r);return ee(o,i)}function Du(t,e){var s=Rp.concat(e||[]),r={};return Z(s,(function(n){var i=ms(t,n);r[n]=i||null})),r}function Bu(t){var e=(function(i){return i?i.search(kr+"google.([^/?]*)")===0?"google":i.search(kr+"bing.com")===0?"bing":i.search(kr+"yahoo.com")===0?"yahoo":i.search(kr+"duckduckgo.com")===0?"duckduckgo":null:null})(t),s=e!="yahoo"?"q":"p",r={};if(!$e(e)){r.$search_engine=e;var n=C?ms(C.referrer,s):"";n.length&&(r.ph_keyword=n)}return r}function _l(){return navigator.language||navigator.userLanguage}var hn="$direct";function ju(){return C?.referrer||hn}function Uu(t,e,s){s===void 0&&(s=!1);var r=t?[...vs,...e||[]]:[],n=s?Ct(re?.href):re?.href,i=n?.substring(0,1e3);return{r:ju().substring(0,1e3),u:i?nr(i,r,ir):void 0}}function Hu(t,e){var s;e===void 0&&(e=!1);var r=t.r,n=t.u,i=e?Ct(n):n,o={$referrer:r,$referring_domain:r==null?void 0:r==hn?hn:(s=un(r))==null?void 0:s.host};if(i){o.$current_url=i;var a=un(i);o.$host=a?.host,o.$pathname=a?.pathname;var l=Du(i);ee(o,l)}if(r){var u=Bu(r);ee(o,u)}return o}function Wu(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return}}function Np(){try{return new Date().getTimezoneOffset()}catch{return}}var Mp={flags:Gs,surveys:sn},Lp=["cookie","localstorage","localstorage+cookie","sessionstorage","memory"],ts="main";class pi{constructor(e,s,r){if(r===void 0&&(r=!0),this.ci={},this.fi=!1,this.pi=!1,this.Ne=e,this.gi=r,this.props={},this.mi=void 0,this.yi=(i=>{var o="";return i.token&&(o=i.token.replace(/\+/g,"PL").replace(/\//g,"SL").replace(/=/g,"EQ")),i.persistence_name?"ph_"+i.persistence_name:"ph_"+o+"_posthog"})(e),this.ii=this.bi(e),this.pi=this.wi(e),this.load(),e.debug&&k.info("Persistence loaded",e.persistence,E({},this.props)),this.update_config(e,e,s),this.save(),v){var n=()=>this.flush();ne(v,"beforeunload",n,{capture:!1}),ne(v,"pagehide",n,{capture:!1})}}ki(){var e,s=(e=this.Ne)==null?void 0:e.persistence_save_debounce_ms;return he(s)&&s>0?s:0}isDisabled(){return!!this.xi}bi(e){Lp.indexOf(e.persistence.toLowerCase())===-1&&(k.critical("Unknown persistence type "+e.persistence+"; falling back to localStorage+cookie"),e.persistence="localStorage+cookie");var s,r=(function(o,a){o===void 0&&(o=[]),a===void 0&&(a=!1);var l=[...fp,...o];return E({},Q,{H(u){try{var c={};try{c=pt.H(u)||{}}catch{}var d,h=JSON.parse(Q.P(u)||"{}");if(a){var p={};for(var f in c){var m=c[f];$e(m)||m===""||(p[f]=m)}d=ee(h,p)}else d=ee(c,h);return Q.F(u,d),d}catch{}return null},F(u,c,d,h,p,f){var m=Q.F(u,c,void 0,void 0,f);try{var g={};l.forEach((_=>{c[_]&&(g[_]=c[_])})),Object.keys(g).length&&pt.F(u,g,d,h,p,f)}catch(_){Q.j(_)}return m},q(u,c){try{v?.localStorage.removeItem(u),pt.q(u,c)}catch(d){Q.j(d)}}})})(e.cookie_persisted_properties||[],e.__preview_cookie_wins_on_conflict||!1),n=!1,i=e.persistence.toLowerCase();return i==="localstorage"&&Q.N()?(s=Q,n=!0):i==="localstorage+cookie"&&r.N()?(s=r,n=!0):i==="sessionstorage"&&ce.N()?s=ce:i==="memory"?s=gp:i==="cookie"?s=pt:r.N()?(s=r,n=!0):s=pt,this.fi=n,s}Si(e){return this.yi+"__"+e}wi(e){return this.fi&&!!e.split_storage}properties(){var e={};return Z(this.props,((s,r)=>{var n=Mt(r);if(!n||n.exposure==="event"){if(n!=null&&n.shouldSkipFromEventProperties!=null&&n.shouldSkipFromEventProperties(s))return;e[r]=s}})),e}load(){if(!this.xi){var e=this.ii.H(this.yi);e&&(this.props=ee({},e)),this.pi&&this.Ci()}}Ci(){for(var e of hi){var s=Q.H(this.Si(e));if(s&&!mt(s)){var r=this.Mi(e);r.persisted=!0,this.Ti(e)||(r.fingerprint=this.Ei(s,e)),this.Ii(e,s)||ee(this.props,s)}}}Ti(e){return Object.keys(this.props).some((s=>{var r;return((r=Mt(s))==null?void 0:r.storageGroup)===e}))}Ii(e,s){var r=Mp[e];if(!r)return!1;var n=s[r],i=this.props[r];return he(n)&&he(i)&&i>n}refreshKey(e){var s;if(!this.xi){var r=this.pi?(s=Mt(e))==null?void 0:s.storageGroup:void 0,n=r?Q.H(this.Si(r)):this.ii.H(this.yi);if(n&&e in n)this.Pi(e,n[e]);else{if(r){var i=this.ii.H(this.yi);if(i&&e in i)return void this.Pi(e,i[e])}this.Ri(e)}}}save(){if(!this.xi){var e=this.ki();e>0?x(this.Ai)&&(this.Ai=setTimeout((()=>{this.Ai=void 0,this.Fi()}),e)):this.Fi()}}flush(){x(this.Ai)||(clearTimeout(this.Ai),this.Ai=void 0,this.Fi())}Fi(){this.xi||(this.pi?this.Li():this.Oi(this.ii,this.yi,this.props,ts))}Li(){var e=this.Di(),s=e.main,r=e.groups;for(var n of(this.Oi(this.ii,this.yi,s,ts),hi)){var i,o=r[n];(!mt(o)||(i=this.ci[n])!=null&&i.persisted)&&this.Oi(Q,this.Si(n),o,n)}}Di(){var e={},s={flags:{},surveys:{}};return Z(this.props,((r,n)=>{var i,o=(i=Mt(n))==null?void 0:i.storageGroup;o?s[o][n]=r:e[n]=r})),{main:e,groups:s}}Ei(e,s){if(s===ts)return JSON.stringify(e)+"|"+this.$i+"|"+this.Ni+"|"+this.qi;var r={};return Z(e,((n,i)=>{var o;r[i]=(o=Mt(i))!=null&&o.volatile?"__volatile__":n})),JSON.stringify(r)}Oi(e,s,r,n){var i=this.Mi(n);if(n===ts||i.dirty||x(i.fingerprint)){var o;try{if((o=this.Ei(r,n))===i.fingerprint)return void(i.dirty=!1)}catch{o=void 0}e.F(s,r,this.$i,this.Ni,this.qi,this.Ne.debug)?(i.dirty=!1,n!==ts&&(i.persisted=!0),x(o)||(i.fingerprint=o)):this.Ne.debug&&k.warn('failed to persist storage entry "'+s+'"; will retry on next save')}}remove(e){var s=(e===void 0?{}:e).keepGroupEntries,r=s!==void 0&&s;if(x(this.Ai)||(clearTimeout(this.Ai),this.Ai=void 0),this.ii.q(this.yi,!1),this.ii.q(this.yi,!0),!r&&this.gi)for(var n of hi)Q.q(this.Si(n));r?delete this.ci[ts]:this.ci={}}clear(){this.remove(),this.props={}}register_once(e,s,r){if(te(e)){x(s)&&(s="None"),this.$i=x(r)?this.ji:r;var n=!1;if(Z(e,((i,o)=>{this.props.hasOwnProperty(o)&&this.props[o]!==s||(this.Pi(o,i),n=!0)})),n)return this.save(),!0}return!1}register(e,s){if(te(e)){this.$i=x(s)?this.ji:s;var r=!1;if(Z(e,((n,i)=>{e.hasOwnProperty(i)&&(this.props[i]!==n||te(n)||L(n))&&(this.Pi(i,n),r=!0)})),r)return this.save(),!0}return!1}unregister(e){var s=typeof e=="string"?[e]:e,r=!1;for(var n of s)n in this.props&&(this.Ri(n),r=!0);r&&this.save()}update_campaign_params(){var e=C?.URL;if(e!==this.mi){var s=Ou(this.Ne.custom_campaign_params,this.Ne.mask_personal_data_properties,this.Ne.custom_personal_data_properties);mt(Jo(s))||this.register(s),this.mi=e}}update_search_keyword(){var e;this.register((e=C?.referrer)?Bu(e):{})}update_referrer_info(){var e;this.register_once({$referrer:ju(),$referring_domain:C!=null&&C.referrer&&((e=un(C.referrer))==null?void 0:e.host)||hn},void 0)}set_initial_person_info(){this.props[so]||this.props[ro]||this.register_once({[rn]:Uu(this.Ne.mask_personal_data_properties,this.Ne.custom_personal_data_properties,this.Ne.disable_capture_url_hashes)},void 0)}get_initial_props(){var e={};Z([ro,so],(n=>{var i=this.props[n];i&&Z(i,(function(o,a){e["$initial_"+Oi(a)]=o}))}));var s=this.props[rn];if(s){var r=(function(n,i){i===void 0&&(i=!1);var o=Hu(n,i),a={};return Z(o,(function(l,u){a["$initial_"+Oi(u)]=l})),a})(s,this.Ne.disable_capture_url_hashes);ee(e,r)}return e}safe_merge(e){return Z(this.props,(function(s,r){r in e||(e[r]=s)})),e}update_config(e,s,r){this.ji=this.$i=e.cookie_expiration,this.set_disabled(e.disable_persistence||!!r),this.set_cross_subdomain(e.cross_subdomain_cookie),this.set_secure(e.secure_cookie);var n=e.persistence!==s.persistence||!((l,u)=>{if(l.length!==u.length)return!1;var c=[...l].sort(),d=[...u].sort();return c.every(((h,p)=>h===d[p]))})(e.cookie_persisted_properties||[],s.cookie_persisted_properties||[]),i=n?this.bi(e):this.ii,o=this.wi(e);if(n||o!==this.pi){var a=this.props;this.clear(),this.ii=i,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,s){var r=this.props[js]||{};r[e]=s,this.Pi(js,r),this.save()}remove_event_timer(e){var s=this.props[js]||{},r=s[e];return x(r)||(delete s[e],this.Pi(js,s),this.save()),r}get_property(e){return this.props[e]}set_property(e,s){this.Pi(e,s),this.save()}Pi(e,s){var r;this.props[e]=s,(r=Mt(e))!=null&&r.volatile||this.Bi(e)}Ri(e){delete this.props[e],this.Bi(e)}Bi(e){var s,r=(s=Mt(e))==null?void 0:s.storageGroup;r&&(this.Mi(r).dirty=!0)}Mi(e){return this.ci[e]||(this.ci[e]={})}}function Ir(t){var e=!0;return{dispose(){if(e){e=!1;var s=t();s&&Se(s.then)&&s.then(void 0,(()=>{}))}}}}var xe={GZipJS:"gzip-js",Base64:"base64"},As={Activation:"events",Cancellation:"cancelEvents"},fi={Popover:"popover",API:"api",Widget:"widget"},ft={SHOWN:"survey shown",DISMISSED:"survey dismissed",SENT:"survey sent"},gi={SURVEY_ID:"$survey_id",SURVEY_ITERATION:"$survey_iteration",SURVEY_LAST_SEEN_DATE:"$survey_last_seen_date"},lo={Popover:"popover",Inline:"inline"},Op={SHOWN:"product tour shown"},yl={TOUR_LAST_SEEN_DATE:"$product_tour_last_seen_date",TOUR_TYPE:"$product_tour_type"},wl=se("[RateLimiter]");class Dp{constructor(e){this.serverLimits={},this.lastEventRateLimited=!1,this.checkForLimiting=s=>{var r=s.text;if(r&&r.length)try{(JSON.parse(r).quota_limited||[]).forEach((n=>{wl.info((n||"events")+" is quota limited."),this.serverLimits[n]=new Date().getTime()+6e4}))}catch(n){return void wl.warn('could not rate limit - continuing. Error: "'+n?.message+'"',{text:r})}},this.instance=e,this.lastEventRateLimited=this.clientRateLimitContext(!0).isRateLimited}get captureEventsPerSecond(){var e;return((e=this.instance.config.rate_limiting)==null?void 0:e.events_per_second)||10}get captureEventsBurstLimit(){var e;return Math.max(((e=this.instance.config.rate_limiting)==null?void 0:e.events_burst_limit)||10*this.captureEventsPerSecond,this.captureEventsPerSecond)}clientRateLimitContext(e){var s,r,n;e===void 0&&(e=!1);var i=this.captureEventsBurstLimit,o=this.captureEventsPerSecond,a=new Date().getTime(),l=(s=(r=this.instance.persistence)==null?void 0:r.get_property(to))!==null&&s!==void 0?s:{tokens:i,last:a};l.tokens+=(a-l.last)/1e3*o,l.last=a,l.tokens>i&&(l.tokens=i);var u=1>l.tokens;if(u||e||(l.tokens=Math.max(0,l.tokens-1)),u&&!e){var c=(he(l.dropped)?l.dropped:0)+1;l.dropped=c,!this.lastEventRateLimited&&this.Hi(c)&&(l.dropped=0)}return this.lastEventRateLimited=u,(n=this.instance.persistence)==null||n.set_property(to,l),{isRateLimited:u,remainingTokens:l.tokens}}Ui(e){var s=this.instance.config.property_denylist;return!L(s)||!s.includes(e)}zi(){var e;if(this.Ui("$current_url")&&this.Ui("$pathname")&&re!=null&&re.pathname)return""+((e=re.origin)!==null&&e!==void 0?e:"")+re.pathname}Hi(e){var s,r,n=this.captureEventsBurstLimit,i=this.captureEventsPerSecond,o=this.zi(),a=this.Ui("$session_id")?(s=(r=this.instance).get_session_id)==null?void 0:s.call(r):void 0,l=[e+" event(s) dropped since the last warning",o?"triggered on "+o:void 0,a?"session "+a:void 0].filter(Boolean).join(", ");return!!this.instance.capture("$$client_ingestion_warning",{$$client_ingestion_warning_message:"posthog-js client rate limited: "+l+". Config is set to "+i+" events per second and "+n+" events burst limit."},{skip_client_rate_limiting:!0})}isServerRateLimited(e){var s=this.serverLimits[e||"events"]||!1;return s!==!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 xt.info("Using preloaded remote config",this.remoteConfig),this.Zi(this.remoteConfig),void this.Gi();if(this._instance.Qi())return void xt.warn("Remote config is disabled. Falling back to local config.");this.Wi((e=>{if(!e)return xt.info("No config found after loading remote JS config. Falling back to JSON."),void this.Vi((s=>{this.Zi(s.json,s),this.Gi()}));this.Zi(e),this.Gi()}))}catch(e){xt.error("Error loading remote config",e),this.Zi()}}stop(){this.Ki&&(clearInterval(this.Ki),this.Ki=void 0)}refresh(){!this._instance.Qi()&&C&&C.visibilityState!=="hidden"&&this._instance.reloadFeatureFlags()}Gi(){var e;if(!this.Ki){var s=(e=this._instance.config.remote_config_refresh_interval_ms)!==null&&e!==void 0?e:3e5;s!==0&&(this.Ki=setInterval((()=>{this.refresh()}),s))}}Zi(e,s){!e&&s&&(s.statusCode===0?s.error||xt.warn("Failed to fetch remote config from PostHog."):xt.error("Failed to fetch remote config from PostHog."));try{this._instance.Zi(e?{ok:!0,config:e}:{ok:!1})}catch(n){xt.error("Error applying remote config",n)}if(e?.hasFeatureFlags!==!1&&!this._instance.config.advanced_disable_feature_flags_on_first_load)try{var r;(r=this._instance.featureFlags)==null||r.ensureFlagsLoaded()}catch(n){xt.error("Error loading feature flags",n)}}}var qe=Uint8Array,Ae=Uint16Array,_s=Uint32Array,Qo=new qe([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),ea=new qe([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),bl=new qe([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),qu=function(t,e){for(var s=new Ae(31),r=0;31>r;++r)s[r]=e+=1<r;++r)for(var i=s[r];s[r+1]>i;++i)n[i]=i-s[r]<<5|r;return[s,n]},Vu=qu(Qo,2),co=Vu[1];Vu[0][28]=258,co[258]=28;for(var El=qu(ea,0)[1],Gu=new Ae(32768),ie=0;32768>ie;++ie){var ss=(43690&ie)>>>1|(21845&ie)<<1;Gu[ie]=((65280&(ss=(61680&(ss=(52428&ss)>>>2|(13107&ss)<<2))>>>4|(3855&ss)<<4))>>>8|(255&ss)<<8)>>>1}var Js=function(t,e,s){for(var r=t.length,n=0,i=new Ae(e);r>n;++n)++i[t[n]-1];var o,a=new Ae(e);for(n=0;e>n;++n)a[n]=a[n-1]+i[n-1]<<1;for(o=new Ae(r),n=0;r>n;++n)o[n]=Gu[a[t[n]-1]++]>>>15-t[n];return o},Kt=new qe(288);for(ie=0;144>ie;++ie)Kt[ie]=8;for(ie=144;256>ie;++ie)Kt[ie]=9;for(ie=256;280>ie;++ie)Kt[ie]=7;for(ie=280;288>ie;++ie)Kt[ie]=8;var pn=new qe(32);for(ie=0;32>ie;++ie)pn[ie]=5;var Bp=Js(Kt,9),jp=Js(pn,5),Ku=function(t){return(t/8>>0)+(7&t&&1)},Ju=function(t,e,s){(s==null||s>t.length)&&(s=t.length);var r=new(t instanceof Ae?Ae:t instanceof _s?_s:qe)(s-e);return r.set(t.subarray(e,s)),r},ot=function(t,e,s){var r=e/8>>0;t[r]|=s<<=7&e,t[r+1]|=s>>>8},$s=function(t,e,s){var r=e/8>>0;t[r]|=s<<=7&e,t[r+1]|=s>>>8,t[r+2]|=s>>>16},mi=function(t,e){for(var s=[],r=0;t.length>r;++r)t[r]&&s.push({s:r,f:t[r]});var n=s.length,i=s.slice();if(!n)return[new qe(0),0];if(n==1){var o=new qe(s[0].s+1);return o[s[0].s]=1,[o,1]}s.sort((function(F,P){return F.f-P.f})),s.push({s:-1,f:25001});var a=s[0],l=s[1],u=0,c=1,d=2;for(s[0]={s:-1,f:a.f+l.f,l:a,r:l};c!=n-1;)a=s[s[d].f>s[u].f?u++:d++],l=s[u!=c&&s[d].f>s[u].f?u++:d++],s[c++]={s:-1,f:a.f+l.f,l:a,r:l};var h=i[0].s;for(r=1;n>r;++r)i[r].s>h&&(h=i[r].s);var p=new Ae(h+1),f=uo(s[c-1],p,0);if(f>e){r=0;var m=0,g=f-e,_=1<r;++r){var w=i[r].s;if(e>=p[w])break;m+=_-(1<>>=g;m>0;){var b=i[r].s;e>p[b]?m-=1<=0&&m;--r){var I=i[r].s;p[I]==e&&(--p[I],++m)}f=e}return[new qe(p),f]},uo=function(t,e,s){return t.s==-1?Math.max(uo(t.l,e,s+1),uo(t.r,e,s+1)):e[t.s]=s},Sl=function(t){for(var e=t.length;e&&!t[--e];);for(var s=new Ae(++e),r=0,n=t[0],i=1,o=function(l){s[r++]=l},a=1;e>=a;++a)if(t[a]==n&&a!=e)++i;else{if(!n&&i>2){for(;i>138;i-=138)o(32754);i>2&&(o(i>10?i-11<<5|28690:i-3<<5|12305),i=0)}else if(i>3){for(o(n),--i;i>6;i-=6)o(8304);i>2&&(o(i-3<<5|8208),i=0)}for(;i--;)o(n);i=1,n=t[a]}return[s.subarray(0,r),e]},Rs=function(t,e){for(var s=0,r=0;e.length>r;++r)s+=t[r]*e[r];return s},ho=function(t,e,s){var r=s.length,n=Ku(e+2);t[n]=255&r,t[n+1]=r>>>8,t[n+2]=255^t[n],t[n+3]=255^t[n+1];for(var i=0;r>i;++i)t[n+i+4]=s[i];return 8*(n+4+r)},xl=function(t,e,s,r,n,i,o,a,l,u,c){ot(e,c++,s),++n[256];for(var d=mi(n,15),h=d[0],p=d[1],f=mi(i,15),m=f[0],g=f[1],_=Sl(h),w=_[0],b=_[1],I=Sl(m),F=I[0],P=I[1],j=new Ae(19),S=0;w.length>S;++S)j[31&w[S]]++;for(S=0;F.length>S;++S)j[31&F[S]]++;for(var A=mi(j,7),R=A[0],N=A[1],T=19;T>4&&!R[bl[T-1]];--T);var O,J,z,H,oe=u+5<<3,pe=Rs(n,Kt)+Rs(i,pn)+o,Ie=Rs(n,h)+Rs(i,m)+o+14+3*T+Rs(j,R)+(2*j[16]+3*j[17]+7*j[18]);if(pe>=oe&&Ie>=oe)return ho(e,c,t.subarray(l,l+u));if(ot(e,c,1+(pe>Ie)),c+=2,pe>Ie){O=Js(h,p),J=h,z=Js(m,g),H=m;var _e=Js(R,N);for(ot(e,c,b-257),ot(e,c+5,P-1),ot(e,c+10,T-4),c+=14,S=0;T>S;++S)ot(e,c+3*S,R[bl[S]]);c+=3*T;for(var Ce=[w,F],Re=0;2>Re;++Re){var ae=Ce[Re];for(S=0;ae.length>S;++S)ot(e,c,_e[me=31&ae[S]]),c+=R[me],me>15&&(ot(e,c,ae[S]>>>5&127),c+=ae[S]>>>12)}}else O=Bp,J=Kt,z=jp,H=pn;for(S=0;a>S;++S)if(r[S]>255){var me;$s(e,c,O[257+(me=r[S]>>>18&31)]),c+=J[me+257],me>7&&(ot(e,c,r[S]>>>23&31),c+=Qo[me]);var ge=31&r[S];$s(e,c,z[ge]),c+=H[ge],ge>3&&($s(e,c,r[S]>>>5&8191),c+=ea[ge])}else $s(e,c,O[r[S]]),c+=J[r[S]];return $s(e,c,O[256]),c+J[256]},Up=new _s([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),Hp=(function(){for(var t=new _s(256),e=0;256>e;++e){for(var s=e,r=9;--r;)s=(1&s&&3988292384)^s>>>1;t[e]=s}return t})(),vi=function(t,e,s){for(;s;++e)t[e]=s,s>>>=8};function Wp(t,e){e===void 0&&(e={});var s=(function(){var d=4294967295;return{p(h){for(var p=d,f=0;h.length>f;++f)p=Hp[255&p^h[f]]^p>>>8;d=p},d(){return 4294967295^d}}})(),r=t.length;s.p(t);var n,i,o,a,l,u=(a=10+((n=e).filename&&n.filename.length+1||0),l=8,(function(d,h,p,f,m,g){var _=d.length,w=new qe(f+_+5*(1+Math.floor(_/7e3))+m),b=w.subarray(f,w.length-m),I=0;if(!h||8>_)for(var F=0;_>=F;F+=65535){var P=F+65535;_>P?I=ho(b,I,d.subarray(F,P)):(b[F]=!0,I=ho(b,I,d.subarray(F,_)))}else{for(var j=Up[h-1],S=j>>>13,A=8191&j,R=(1<F;++F){var me=z(F),ge=32767&F,Ye=T[me];if(N[ge]=Ye,T[me]=ge,F>=Re){var Rt=_-F;if((Ie>7e3||Ce>24576)&&Rt>423){I=xl(d,b,0,H,oe,pe,_e,Ce,ae,F-ae,I),Ce=Ie=_e=0,ae=F;for(var de=0;286>de;++de)oe[de]=0;for(de=0;30>de;++de)pe[de]=0}var Ve=2,St=0,ks=A,Be=ge-Ye&32767;if(Rt>2&&me==z(F-Be))for(var Fe=Math.min(S,Rt)-1,mr=Math.min(32767,F),vr=Math.min(258,Rt);mr>=Be&&--ks&&ge!=Ye;){if(d[F+Ve]==d[F+Ve-Be]){for(var je=0;vr>je&&d[F+je]==d[F+je-Be];++je);if(je>Ve){if(Ve=je,St=Be,je>Fe)break;var _r=Math.min(Be,je-2),Xt=0;for(de=0;_r>de;++de){var Qt=F-Be+de+32768&32767,Is=Qt-N[Qt]+32768&32767;Is>Xt&&(Xt=Is,Ye=Qt)}}}Be+=(ge=Ye)-(Ye=N[ge])+32768&32767}if(St){H[Ce++]=268435456|co[Ve]<<18|El[St];var La=31&co[Ve],Oa=31&El[St];_e+=Qo[La]+ea[Oa],++oe[257+La],++pe[Oa],Re=F+Ve,++Ie}else H[Ce++]=d[F],++oe[d[F]]}}I=xl(d,b,!0,H,oe,pe,_e,Ce,ae,F-ae,I)}return Ju(w,0,f+Ku(I)+m)})(i=t,(o=e).level==null?6:o.level,o.mem==null?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(i.length)))):12+o.mem,a,l)),c=u.length;return(function(d,h){var p=h.filename;if(d[0]=31,d[1]=139,d[2]=8,d[8]=2>h.level?4:h.level==9?2:0,d[9]=3,h.mtime!=0&&vi(d,4,Math.floor(new Date(h.mtime||Date.now())/1e3)),p){d[3]=8;for(var f=0;p.length>=f;++f)d[f+10]=p.charCodeAt(f)}})(u,e),vi(u,c-8,s.d()),vi(u,c-4,r),u}var zp=!!Ni||!!Do,Yu="text/plain",Dr=!1,Zu=(t,e)=>{var s=t.split("#"),r=s[1],n=s[0].split("?"),i=n[0],o=n[1];if(!o)return t;var a=o.split("&").filter((l=>l.split("=")[0]!==e)).join("&");return i+(a?"?"+a:"")+(r?"#"+r:"")},Rn=function(t,e,s){var r;s===void 0&&(s=!0);var n=t.split("?"),i=n[0],o=n[1],a=E({},e),l=(r=o?.split("&").map((c=>{var d,h=c.split("="),p=h[0],f=s&&(d=a[p])!==null&&d!==void 0?d:h[1];return delete a[p],p+"="+f})))!==null&&r!==void 0?r:[],u=(function(c,d){var h,p;d===void 0&&(d="&");var f=[];return Z(c,(function(m,g){x(m)||x(g)||g==="undefined"||(h=encodeURIComponent((_=>_ instanceof File)(m)?m.name:m.toString()),p=encodeURIComponent(g),f[f.length]=p+"="+h)})),f.join(d)})(a);return u&&l.push(u),l.length>0?i+"?"+l.join("&"):i},_i=t=>{if(t.Ji)return t.Ji;var e=t.data,s=t.compression;if(e){if(s===xe.GZipJS){var r=Wp((function(a,l){var u=a.length;if(typeof TextEncoder<"u")return new TextEncoder().encode(a);for(var c=new qe(a.length+(a.length>>>1)),d=0,h=function(g){c[d++]=g},p=0;u>p;++p){if(d+5>c.length){var f=new qe(d+8+(u-p<<1));f.set(c),c=f}var m=a.charCodeAt(p);128>m?h(m):2048>m?(h(192|m>>>6),h(128|63&m)):m>55295&&57344>m?(h(240|(m=65536+(1047552&m)|1023&a.charCodeAt(++p))>>>18),h(128|m>>>12&63),h(128|m>>>6&63),h(128|63&m)):(h(224|m>>>12),h(128|m>>>6&63),h(128|63&m))}return Ju(c,0,d)})(cs(e)),{mtime:0});return{contentType:Yu,body:r.buffer.slice(r.byteOffset,r.byteOffset+r.byteLength),estimatedSize:r.byteLength}}if(s===xe.Base64){var n=(function(a){return a&&btoa(encodeURIComponent(a).replace(/%([0-9A-F]{2})/g,((l,u)=>String.fromCharCode(parseInt(u,16)))))})(cs(e)),i=(a=>"data="+encodeURIComponent(typeof a=="string"?a:cs(a)))(n);return{contentType:"application/x-www-form-urlencoded",body:i,estimatedSize:new Blob([i]).size}}var o=cs(e);return{contentType:"application/json",body:o,estimatedSize:new Blob([o]).size}}},Xu=t=>{var e,s,r=()=>t.transport==="sendBeacon"?{url:Rn(t.url,{compression:xe.Base64}),encodedBody:_i(E({},t,{compression:xe.Base64,Ji:void 0}))}:{url:Zu(t.url,"compression"),encodedBody:_i(E({},t,{compression:void 0,Ji:void 0}))};try{e=_i(t)}catch(n){if(za(t.compression,ms(t.url,"compression")))return k.error("Failed to gzip request body, sending uncompressed payload",n),r();throw n}return e&&za(t.compression,ms(t.url,"compression"))&&!((s=e.body)instanceof ArrayBuffer?Mi(new Uint8Array(s)):ArrayBuffer.isView(s)&&Mi(new Uint8Array(s.buffer,s.byteOffset,s.byteLength)))?(Dr=!0,r()):{url:t.url,encodedBody:e}},Qu=t=>{try{return Xu(t)}catch(e){return k.error(e),void(t.callback==null||t.callback({statusCode:0,error:e}))}},qp=(function(){var t=X((function*(e){var s=cs(e.data),r=yield(function(i,o,a){return Li.apply(this,arguments)})(s,Y.DEBUG,{rethrow:!0});if(!r)return e;var n=yield r.arrayBuffer();return E({},e,{Ji:{contentType:Yu,body:n,estimatedSize:n.byteLength}})}));return function(e){return t.apply(this,arguments)}})(),Vp=/Failed to fetch|NetworkError|Load failed/i,ed=t=>t?.name==="TypeError"&&Vp.test(t?.message||""),td=t=>{var e=Qu(t);if(e){var s=e.url,r=e.encodedBody,n=r??{},i=n.contentType,o=n.body,a=n.estimatedSize,l=new Headers;Z(t.headers,(function(f,m){l.append(m,f)})),i&&l.append("Content-Type",i);var u=null,c=!1;if(Da){var d=new Da;u={signal:d.signal,timeout:setTimeout((()=>{var f,m;c=!0,d.abort((f=t.timeout,(m=new Error("PostHog request timed out"+(f?" after "+f+"ms":""))).name="AbortError",m))}),t.timeout)}}var h=f=>{c&&f?.name==="AbortError"||ed(f)?k.warn(f):k.error(f),t.callback==null||t.callback({statusCode:0,error:f})};try{var p;Do(s,E({method:t?.method||"GET",headers:l,keepalive:t.method==="POST"&&!t.Yi&&52428.8>(a||0),body:o,signal:(p=u)==null?void 0:p.signal},t.fetchOptions)).then((f=>f.text().then((m=>{var g={statusCode:f.status,text:m};if(f.status===200)try{g.json=JSON.parse(m)}catch(_){k.error(_)}t.callback==null||t.callback(g)})))).catch(h).finally((()=>u?clearTimeout(u.timeout):null))}catch(f){u&&clearTimeout(u.timeout),h(f)}}},po=t=>{try{var e,s=Xu(t),r=s.url,n=s.encodedBody,i=n??{},o=i.body,a=i.estimatedSize;if(!o)return;var l=o instanceof Blob?o:new Blob([o],{type:i.contentType});if(ke.sendBeacon(r,l))return;var u=L(t.data)?t.data:(e=t.data)==null?void 0:e.batch;if(L(u)&&u.length>1&&(a??0)>16384){var c=Math.ceil(u.length/2),d=h=>L(t.data)?h:E({},t.data,{batch:h});return po(E({},t,{data:d(u.slice(0,c))})),void po(E({},t,{data:d(u.slice(c))}))}k.warn("Beacon of ~"+(a??0)+" bytes was rejected by the browser, falling back to fetch"),td(E({},t,{Yi:!0}))}catch(h){k.warn("Beacon send failed",h)}},kl=(t,e,s,r)=>{var n=r==="query"?e==="POST"?"sent_at":"_":void 0;return Rn(s===xe.GZipJS?Zu(t,"compression"):t,E({},n?{[n]:Date.now().toString()}:{},s===xe.GZipJS?{}:{compression:s}))},Br=[];Do&&Br.push({transport:"fetch",method:td}),Ni&&Br.push({transport:"XHR",method(t){var e=Qu(t);if(e){var s=new Ni,r=e.encodedBody;s.open(t.method||"GET",e.url,!0);var n=r??{},i=n.contentType,o=n.body;Z(t.headers,(function(a,l){s.setRequestHeader(l,a)})),i&&s.setRequestHeader("Content-Type",i),t.timeout&&(s.timeout=t.timeout),s.onreadystatechange=()=>{if(s.readyState===4){var a={statusCode:s.status,text:s.responseText};if(s.status===200)try{a.json=JSON.parse(s.responseText)}catch{}t.callback==null||t.callback(a)}},s.send(o)}}}),ke!=null&&ke.sendBeacon&&Br.push({transport:"sendBeacon",method:po});var fo=3e3;class Gp{constructor(e,s){this.Xi=!0,this.tr=[],this.er=rt(s?.flush_interval_ms||fo,250,5e3,k.createLogger("flush interval"),fo),this.ir=e}enqueue(e){this.tr.push(e),this.rr||this.nr()}unload(){this.sr();var e=this.tr.length>0?this.ar():{},s=Object.values(e);[...s.filter((r=>r.url.indexOf("/e")===0)),...s.filter((r=>r.url.indexOf("/e")!==0))].map((r=>{this.lr(E({},r,{transport:"sendBeacon"}))}))}enable(){this.Xi=!1,this.nr()}nr(){var e=this;this.Xi||(this.rr=setTimeout((()=>{if(this.sr(),this.tr.length>0){var s=this.ar(),r=function(){var i=s[n],o=new Date().getTime();i.data&&L(i.data)&&Z(i.data,(a=>{a.offset=Math.abs(a.timestamp-o),delete a.timestamp})),e.lr(i)};for(var n in s)r()}}),this.er))}lr(e){try{this.ir(e)}catch(s){k.error(s)}}sr(){clearTimeout(this.rr),this.rr=void 0}ar(){var e={};return Z(this.tr,(s=>{var r,n=s,i=(n?n.batchKey:null)||n.url;x(e[i])&&(e[i]=E({},n,{data:[]})),(r=e[i].data)==null||r.push(n.data)})),this.tr=[],e}}var Kp=["retriesPerformedSoFar"];class Jp{constructor(e){this.ur=!1,this.hr=3e3,this.tr=[],this._instance=e,this.tr=[],this.dr=!0,!x(v)&&"onLine"in v.navigator&&(this.dr=v.navigator.onLine,this.vr=()=>{this.dr=!0,this.cr()},this.pr=()=>{this.dr=!1},ne(v,"online",this.vr),ne(v,"offline",this.pr))}get length(){return this.tr.length}retriableRequest(e){var s=e.retriesPerformedSoFar,r=Pc(e,Kp);lt(s)&&(r.url=Rn(r.url,{retry_count:s})),this._instance._send_request(E({},r,{callback:n=>{if(n.statusCode!==200&&(400>n.statusCode||n.statusCode>=500)){if((n.statusCode===0?3:10)>(s??0))return void this.At(E({retriesPerformedSoFar:s},r));n.statusCode===0&&k.warn("Request failed before receiving an HTTP response; this can happen due to network issues, CORS, browser blocking, or ad blockers. Stopped retrying after "+(s??0)+" retries.")}r.callback==null||r.callback(n)}}))}At(e){var s=e.retriesPerformedSoFar||0;e.retriesPerformedSoFar=s+1;var r=(function(o){var a=3e3*Math.pow(2,o),l=a/2,u=Math.min(18e5,a),c=Math.random()-.5;return Math.ceil(u+c*(u-l))})(s),n=Date.now()+r;this.tr.push({retryAt:n,requestOptions:e});var i="Enqueued failed request for retry in "+r;navigator.onLine||(i+=" (Browser is offline)"),k.warn(i),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(),s=[],r=this.tr.filter((i=>e>i.retryAt||(s.push(i),!1)));if(this.tr=s,r.length>0)for(var n of r)this.retriableRequest(n.requestOptions)}unload(){for(var e of(this.mr&&(clearTimeout(this.mr),this.mr=void 0),this.ur=!1,x(v)||(this.vr&&(v.removeEventListener("online",this.vr),this.vr=void 0),this.pr&&(v.removeEventListener("offline",this.pr),this.pr=void 0)),this.tr)){var s=e.requestOptions;try{this._instance._send_request(E({},s,{transport:"sendBeacon"}))}catch(r){k.error(r)}}this.tr=[]}}class Yp{constructor(e){this.yr=()=>{var s,r,n,i;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,(s=this.br.maxScrollY)!==null&&s!==void 0?s:0),this.br.maxScrollHeight=Math.max(l,(r=this.br.maxScrollHeight)!==null&&r!==void 0?r:0),this.br.lastContentY=u,this.br.maxContentY=Math.max(u,(n=this.br.maxContentY)!==null&&n!==void 0?n:0),this.br.maxContentHeight=Math.max(c,(i=this.br.maxContentHeight)!==null&&i!==void 0?i: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(){ne(v,"scroll",this.yr,{capture:!0}),ne(v,"scrollend",this.yr,{capture:!0}),ne(v,"resize",this.yr)}scrollElement(){if(!this._r)return v?.document.documentElement;var e=L(this._r)?this._r:[this._r];for(var s of e){var r=v?.document.querySelector(s);if(r)return r}}wr(e){var s=e==="y"?"scrollTop":"scrollLeft";if(this._r){var r=this.scrollElement();return r&&r[s]||0}return v?e==="y"?v.scrollY||v.pageYOffset||v.document.documentElement.scrollTop||0:v.scrollX||v.pageXOffset||v.document.documentElement.scrollLeft||0:0}scrollY(){return this.wr("y")}scrollX(){return this.wr("x")}}var Zp=t=>Uu(t?.config.mask_personal_data_properties,t?.config.custom_personal_data_properties,t?.config.disable_capture_url_hashes);class Il{constructor(e,s,r,n){this.kr=i=>{var o=this.Sr();if(!o||o.sessionId!==i){var a={sessionId:i,props:this.Cr(this._instance)};this.Mr.register({[eo]:a})}},this._instance=e,this.Tr=s,this.Mr=r,this.Cr=n||Zp,this.Tr.onSessionId(this.kr)}Sr(){return this.Mr.props[eo]}getSetOnceProps(){var e,s=(e=this.Sr())==null?void 0:e.props;return s?"r"in s?Hu(s,this._instance.config.disable_capture_url_hashes):{$referring_domain:s.referringDomain,$pathname:s.initialPathName,utm_source:s.utm_source,utm_campaign:s.utm_campaign,utm_medium:s.utm_medium,utm_content:s.utm_content,utm_term:s.utm_term}:{}}getSessionProps(){var e={};return Z(Jo(this.getSetOnceProps()),((s,r)=>{r==="$current_url"&&(r="url"),e["$session_entry_"+Oi(r)]=s})),e}}class ta{on(e,s){return this.Er[e]||(this.Er[e]=[]),this.Er[e].push(s),()=>{this.Er[e]=this.Er[e].filter((r=>r!==s))}}emit(e,s){for(var r of this.Er[e]||[])r(s);for(var n of this.Er["*"]||[])n(e,s)}constructor(){this.Er={}}}var Ts=se("[SessionId]");class Cl{on(e,s){return this.Ir.on(e,s)}constructor(e,s,r){var n;if(this.Pr=null,this.Rr=[],this.Ar=void 0,this.Fr=!1,this.Ir=new ta,this.Lr=(u,c)=>!(!lt(u)||!lt(c))&&Math.abs(u-c)>this.sessionTimeoutMs,!e.persistence)throw new Error("SessionIdManager requires a PostHogPersistence instance");if(e.config.cookieless_mode===ht)throw new Error('SessionIdManager cannot be used with cookieless_mode="always"');this.Ne=e.config,this.Mr=e.persistence,this.Or=void 0,this.Dr=void 0,this._sessionStartTimestamp=null,this._sessionActivityTimestamp=null,this.$r=s||dt,this.Nr=r||dt;var i=this.Ne.persistence_name||this.Ne.token;if(this._sessionTimeoutMs=1e3*rt(this.Ne.session_idle_timeout_seconds||1800,60,36e3,Ts.createLogger("session_idle_timeout_seconds"),1800),e.register({$configured_session_timeout_ms:this._sessionTimeoutMs}),this.qr(),this.jr="ph_"+i+"_window_id",this.Br="ph_"+i+"_primary_window_exists",this.Hr()){var o=ce.H(this.jr),a=ce.H(this.Br);o&&!a?this.Or=o:ce.q(this.jr),ce.F(this.Br,!0)}if((n=this.Ne.bootstrap)!=null&&n.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){Ts.error("Invalid sessionID in bootstrap",u)}this.zr()}get sessionTimeoutMs(){return this._sessionTimeoutMs}onSessionId(e){return x(this.Rr)&&(this.Rr=[]),this.Rr.push(e),this.Dr&&e(this.Dr,this.Or),()=>{this.Rr=this.Rr.filter((s=>s!==e))}}Hr(){return this.Ne.persistence!=="memory"&&!this.Mr.xi&&ce.N()}Wr(e){e!==this.Or&&(this.Or=e,this.Hr()&&ce.F(this.jr,e))}Vr(){return this.Or?this.Or:this.Hr()?ce.H(this.jr):null}Zr(e){var s=this.Pr;return!$e(s)&&!$e(e)&&5e3>Math.abs(e-s)}Ur(e,s,r){var n=s!==this._sessionActivityTimestamp,i=!(e!==this.Dr||r!==this._sessionStartTimestamp);this._sessionStartTimestamp=r,this._sessionActivityTimestamp=s,this.Dr=e,i&&!n||i&&this.Zr(s)||(this.Pr=s,this.Mr.register({[ls]:[s,e,r]}))}Gr(){var e,s=(e=this.Ne)==null?void 0:e.persistence_save_debounce_ms;return lt(s)&&s>0}Qr(){this.Gr()?this.Mr.refreshKey(ls):(this.Mr.flush(),this.Mr.load())}Kr(){var e;if(!$e(this._sessionActivityTimestamp)&&this._sessionActivityTimestamp!==this.Pr){this.Qr();var s=this.Jr();s[1]===this.Dr&&s[2]===this._sessionStartTimestamp&&(this.Pr=this._sessionActivityTimestamp,this.Mr.register({[ls]:[this._sessionActivityTimestamp,(e=this.Dr)!==null&&e!==void 0?e:null,this._sessionStartTimestamp]}),this.Mr.flush())}}Yr(){var e=this.Jr()[0],s=lt(e)?e:0,r=lt(this._sessionActivityTimestamp)?this._sessionActivityTimestamp:0;return Math.max(s,r)}Xr(e){return this.Qr(),this.Lr(e,this.Yr())}Jr(){var e=this.Mr.props[ls];return L(e)&&e.length===2&&e.push(e[0]),e||[0,null,0]}resetSessionId(){this.Pr=null,clearTimeout(this.tn),this.tn=void 0,this.Ur(null,null,null)}destroy(){this.Fr=!0,this.Kr(),clearTimeout(this.tn),this.tn=void 0,this.Ar&&v&&(v.removeEventListener(an,this.Ar,{capture:!1}),this.Ar=void 0),this.Rr=[]}zr(){this.Ar=()=>{this.Kr(),this.Hr()&&ce.q(this.Br)},ne(v,an,this.Ar,{capture:!1})}checkAndGetSessionAndWindowId(e,s){if(e===void 0&&(e=!1),s===void 0&&(s=null),this.Ne.cookieless_mode===ht)throw new Error('checkAndGetSessionAndWindowId should not be called with cookieless_mode="always"');var r=s||new Date().getTime(),n=this.Jr(),i=n[1],o=n[2],a=this.Yr(),l=this.Vr(),u=lt(o)&&Math.abs(r-o)>864e5,c=!1,d=!1,h=!i,p=i,f=!h&&!e&&this.Lr(r,a);if(f){(f=this.Xr(r))||Ts.info("cross-tab refresh kept the session alive",{sessionId:i});var m=this.Jr();i=m[1],o=m[2]}h||f||u?(i=this.$r(),l=this.Nr(),Ts.info("new session ID generated",{sessionId:i,windowId:l,changeReason:{noSessionId:h,activityTimeout:f,sessionPastMaximumLength:u}}),o=r,c=!0):(l||(l=this.Nr(),c=!0),(d=i!==p)&&(Ts.info("adopted cross-tab session id",{sessionId:i,windowId:l}),c=!0));var g=lt(a)&&e&&!u?a:r,_=lt(o)?o:new Date().getTime();this.Wr(l),this.Ur(i,g,_),e||this.qr();var w={noSessionId:h,activityTimeout:f,sessionPastMaximumLength:u,crossTabAdoption:d};return c&&this.Rr.forEach((b=>b(i,l,w))),{sessionId:i,windowId:l,sessionStartTimestamp:_,changeReason:c?w:void 0,lastActivityTimestamp:a}}qr(){this.Fr||(clearTimeout(this.tn),this.tn=setTimeout((()=>{if(!this.Fr)if(this.Xr(new Date().getTime())){var e=this.Dr;this.resetSessionId(),this.Ir.emit("forcedIdleReset",{idleSessionId:e})}else this.qr()}),1.1*this.sessionTimeoutMs))}}var sd=function(t,e){if(!t)return!1;var s=t.userAgent;if(s&&Va(s,e))return!0;try{var r=t?.userAgentData;if(r!=null&&r.brands&&r.brands.some((n=>Va(n?.brand,e))))return!0}catch{}return!!t.webdriver};function rd(){return(rd=X((function*(){var t=ke?.userAgentData;if(t!=null&&t.getHighEntropyValues)try{var e=yield t.getHighEntropyValues(["model"]),s=e?.model;return W(s)&&s.length>0?s:void 0}catch(r){return void k.info("Unable to resolve $device_model from userAgentData.getHighEntropyValues",r)}}))).apply(this,arguments)}var fn=function(t,e){if(!(function(s){try{new RegExp(s)}catch{return!1}return!0})(e))return!1;try{return new RegExp(e).test(t)}catch{return!1}};function yi(t,e,s){return cs({distinct_id:t,userPropertiesToSet:e,userPropertiesToSetOnce:s})}var nd={exact:(t,e)=>e.some((s=>t.some((r=>s===r)))),is_not:(t,e)=>e.every((s=>t.every((r=>s!==r)))),regex:(t,e)=>e.some((s=>t.some((r=>fn(s,r))))),not_regex:(t,e)=>e.every((s=>t.every((r=>!fn(s,r))))),icontains:(t,e)=>e.map(Cr).some((s=>t.map(Cr).some((r=>s.includes(r))))),not_icontains:(t,e)=>e.map(Cr).every((s=>t.map(Cr).every((r=>!s.includes(r))))),gt:(t,e)=>e.some((s=>{var r=parseFloat(s);return!isNaN(r)&&t.some((n=>r>parseFloat(n)))})),lt:(t,e)=>e.some((s=>{var r=parseFloat(s);return!isNaN(r)&&t.some((n=>rt.toLowerCase();function id(t,e){return!t||Object.entries(t).every((s=>{var r=s[1],n=e?.[s[0]];if(x(n)||$e(n))return!1;var i=[String(n)],o=nd[r.operator];return!!o&&o(r.values,i)}))}var go="custom",Fl="i.posthog.com",Xp=/^\/static\//;class Qp{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,s=(e=this.instance.config.ui_host)==null?void 0:e.replace(/\/$/,"");return s||(s=this.apiHost.replace("."+Fl,".posthog.com")),s==="https://app.posthog.com"?"https://us.posthog.com":s}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":go),this.en[this.apiHost]}rn(e){if(Xp.test(e)){var s=this.instance.config.asset_host;if(typeof s=="string")return s.trim().replace(/\/$/,"")||void 0}}endpointFor(e,s){if(s===void 0&&(s=""),s&&(s=s[0]==="/"?s:"/"+s),e==="ui")return this.uiHost+s;if(e==="flags")return this.flagsApiHost+s;if(e==="assets"){var r=this.rn(s);if(r)return""+r+s}if(this.region===go)return this.apiHost+s;var n=Fl+s;switch(e){case"assets":return"https://"+this.region+"-assets."+n;case"api":return"https://"+this.region+"."+n}}}function od(t){var e;return!((e=t.conditions)==null||(e=e.events)==null||(e=e.values)==null||!e.length)}var q=se("[Surveys]"),ad="seenSurvey_",ld=t=>{try{var e=(s=>((r,n)=>""+ad+(function(i){return i.current_iteration&&i.current_iteration>0?i.id+"_"+i.current_iteration:i.id})(n))(0,s))(t);if(localStorage.getItem(e))return;localStorage.setItem(e,"true")}catch(s){q.error("Failed to persist survey seen state",s)}},ef=[fi.Popover,fi.Widget,fi.API],tf={ignoreConditions:!1,ignoreDelay:!1,displayType:lo.Popover},sf=se("[PostHog ExternalIntegrations]"),rf={intercom:"intercom-integration",crispChat:"crisp-chat-integration"};class nf{constructor(e){this._instance=e}ai(e,s){var r;(r=$.__PosthogExtensions__)==null||r.loadExternalDependency==null||r.loadExternalDependency(this._instance,e,(n=>{if(n)return sf.error("failed to load script",n);s()}))}startIfEnabledOrStop(){var e=this,s=function(){var i,o,a,l=r[0],u=r[1];!u||(i=$.__PosthogExtensions__)!=null&&(i=i.integrations)!=null&&i[l]||e.ai(rf[l],(()=>{var c;(c=$.__PosthogExtensions__)==null||(c=c.integrations)==null||(c=c[l])==null||c.start(e._instance)})),!u&&(o=$.__PosthogExtensions__)!=null&&(o=o.integrations)!=null&&o[l]&&((a=$.__PosthogExtensions__)==null||(a=a.integrations)==null||(a=a[l])==null||a.stop())};for(var r of Object.entries((n=this._instance.config.integrations)!==null&&n!==void 0?n:{})){var n;s()}}}class of{constructor(e,s){this.rt=e,this.nn=s,this.sn=new Map,this.an=!1}add(e){var s=this;return X((function*(){if(s.an)throw new Error("Cannot add an extension to a disposed ExtensionRuntime");if(s.sn.has(e.name))throw new Error('Browser extension "'+e.name+'" is already registered');s.sn.set(e.name,e);try{var r=e.setup(s.nn);r&&(yield r)}catch(i){var n=s.sn.get(e.name)===e;n&&s.sn.delete(e.name),s.rt.error('Failed to set up browser extension "'+e.name+'"',i),n&&s.ln(e)}}))()}dispose(){if(!this.an){this.an=!0;var e=Array.from(this.sn.values()).reverse();for(var s of(this.sn.clear(),e))this.ln(s)}}ln(e){try{var s=e.dispose==null?void 0:e.dispose();s&&Se(s.then)&&s.then(void 0,(r=>{this.rt.error('Failed to dispose browser extension "'+e.name+'"',r)}))}catch(r){this.rt.error('Failed to dispose browser extension "'+e.name+'"',r)}}}class af{constructor(e){this._instance=e}initialize(){}get(e){var s=this._instance.persistence;if(typeof e=="string")return s?.get_property(e);var r={};for(var n of e){var i=s?.get_property(n);x(i)||(r[n]=i)}return r}set(e,s){var r;(r=this._instance.persistence)==null||r.register(typeof e=="string"?{[e]:s}:e)}remove(e){var s;(s=this._instance.persistence)==null||s.unregister(e)}}var Pl="extensionsRemoteConfig";class lf{constructor(e){this.an=!1,this.instance=e,this.rt=k,this.un=e.hn,this.kv=new af(e),this.onEvent=s=>Ir(this.instance.on("eventCaptured",(r=>{try{s({event:r.event,properties:r.properties})}catch(n){this.rt.error("Browser extension event listener failed",n)}}))),this.onRemoteConfig=s=>{if(this.an)return Ir((()=>{}));var r=i=>{try{s(i)}catch(o){this.rt.error("Browser extension remote config listener failed",o)}},n=this.instance.dn.on(Pl,r);return this.un&&r(this.un),Ir(n)},this.vn=new of(k.createLogger("[BrowserExtensions]"),this)}get logger(){return this.rt}get distinctId(){return this.instance.get_distinct_id()}get anonymousId(){var e;return(e=this.instance.get_property(sr))!==null&&e!==void 0?e:this.distinctId}get deviceId(){var e=this.instance.get_property(sr);return typeof e=="string"?e:void 0}get library(){return{name:Y.LIB_NAME,version:Y.LIB_VERSION}}get initialPersonProperties(){var e,s;return(e=(s=this.instance.persistence)==null?void 0:s.get_initial_props())!==null&&e!==void 0?e:{}}get groups(){return this.instance.getGroups()}get session(){try{var e,s,r,n,i=(e=this.instance.sessionManager)==null?void 0:e.checkAndGetSessionAndWindowId(!0);return{sessionId:(s=i?.sessionId)!==null&&s!==void 0?s:"",windowId:(r=i?.windowId)!==null&&r!==void 0?r:"",sessionStartTimestamp:(n=i?.sessionStartTimestamp)!==null&&n!==void 0?n:0}}catch{return{sessionId:"",windowId:"",sessionStartTimestamp:0}}}get projectToken(){return this.instance.config.token}add(e){return this.vn.add(e)}capture(e,s,r){var n=this;return X((function*(){r?n.instance.capture(e,s,{timestamp:r.timestamp,uuid:r.uuid,$set:r.set,$set_once:r.setOnce}):n.instance.capture(e,s)}))()}registerDynamicEventProperties(e){return Ir(this.instance.cn(e))}handleRemoteConfig(e){this.an||(this.un=e,this.instance.dn.emit(Pl,e))}sendRequest(e,s){var r=this;return X((function*(){var n;s===void 0&&(s={});var i=r.instance.requestRouter.endpointFor((n=s.target)!==null&&n!==void 0?n:"api",e),o={method:s.method,url:s.query?Rn(i,s.query):i,data:s.body,headers:s.headers,timeout:s.timeoutMs,fireCallbackOnDrop:!0,transport:s.transport,compression:s.compression,timestampMode:s.sentAt};return s.transport==="sendBeacon"?(r.instance._send_request(o),{statusCode:202}):new Promise((a=>{o.callback=a,r.instance._send_request(o)}))}))()}dispose(){this.an||(this.an=!0,this.vn.dispose())}}var Ys={},wi=0,gn=()=>{},Al='Consent opt in/out is not valid with cookieless_mode="always" and will be ignored',Ns="Surveys module not available",$l="sanitize_properties is deprecated. Use before_send instead",cd="Invalid value for property_denylist config: ",cf=["token","distinct_id",mu],os="posthog",ud=!zp&&Pe?.indexOf("MSIE")===-1&&Pe?.indexOf("Mozilla")===-1,bi=t=>{var e;return E({api_host:"https://us.i.posthog.com",flags_api_host:null,ui_host:null,asset_host:null,token:"",autocapture:!0,cross_subdomain_cookie:cp(C?.location),persistence:"localStorage+cookie",persistence_name:"",cookie_persisted_properties:[],loaded:gn,save_campaign_params:!0,custom_campaign_params:[],custom_blocked_useragents:[],save_referrer:!0,capture_pageleave:"if_capture_pageview",defaults:t??"unset",__preview_deferred_init_extensions:!1,__preview_external_dependency_versioned_paths:!1,__preview_cookie_wins_on_conflict:!1,debug:re&&W(re?.search)&&re.search.indexOf("__posthog_debug=true")!==-1||!1,cookie_expiration:365,upgrade:!1,disable_session_recording:!1,disable_persistence:!1,disable_web_experiments:!0,disable_surveys:!1,disable_surveys_automatic_display:!1,disable_conversations:!1,disable_product_tours:!1,disableDeviceModel:!1,disable_external_dependency_loading:!1,strict_script_versioning:!1,enable_recording_console_log:void 0,secure_cookie:(v==null||(e=v.location)==null?void 0:e.protocol)==="https:",ip:!1,opt_out_capturing_by_default:!1,opt_out_persistence_by_default:!1,opt_out_useragent_filter:!1,opt_out_capturing_persistence_type:"localStorage",consent_persistence_name:null,opt_out_capturing_cookie_prefix:null,opt_in_site_apps:!1,property_denylist:[],respect_dnt:!1,sanitize_properties:null,request_headers:{},request_batching:!0,properties_string_max_length:65535,mask_all_element_attributes:!1,mask_all_text:!1,mask_personal_data_properties:!1,custom_personal_data_properties:[],advanced_disable_flags:!1,advanced_disable_decide:!1,advanced_disable_feature_flags:!1,advanced_disable_feature_flags_on_first_load:!1,advanced_only_evaluate_survey_feature_flags:!1,advanced_feature_flags_dedup_per_session:!1,advanced_enable_surveys:!1,advanced_disable_toolbar_metrics:!1,feature_flag_request_timeout_ms:3e3,surveys_request_timeout_ms:1e4,on_request_error(s){k.error("Bad HTTP status: "+s.statusCode+" "+s.text)},get_device_id:s=>s,capture_performance:void 0,name:"posthog",bootstrap:{},disable_compression:!1,session_idle_timeout_seconds:1800,person_profiles:no,before_send:void 0,get_current_url:void 0,request_queue_config:{flush_interval_ms:fo},error_tracking:{},_onCapture:gn},(s=>({rageclick:s&&s>="2026-05-30"?{content_ignorelist:bp,ignore_text_selection:!0}:!s||"2025-11-30">s||{content_ignorelist:!0},capture_pageview:!s||"2025-05-24">s||"history_change",session_recording:s&&s>="2026-06-25"?{strictMinimumDuration:!0,canvasCapture:{resolutionScale:.6},streamNetworkBody:!0}:s&&s>="2026-05-30"?{strictMinimumDuration:!0,canvasCapture:{resolutionScale:.6}}:s&&s>="2025-11-30"?{strictMinimumDuration:!0}:{},external_scripts_inject_target:s&&s>="2026-01-30"?"head":"body",internal_or_test_user_hostname:s&&s>="2026-01-30"?/^(localhost|127\.0\.0\.1)$/:void 0,persistence_save_debounce_ms:s&&s>="2026-05-30"?250:0,split_storage:!(!s||"2026-05-30">s),detect_google_search_app:!(!s||"2026-05-30">s),disable_capture_url_hashes:!(!s||"2026-06-25">s)}))(t))},uf=[["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"]],Rl=t=>{var e={};for(var s of uf){var r=s[0],n=s[1];x(t[r])||(e[n]=t[r])}var i=ee({},e,t),o=t.__preview_external_dependency_versioned_paths;return x(o)||(x(t.strict_script_versioning)&&(i.strict_script_versioning=!!o),W(o)&&x(t.asset_host)&&(i.asset_host=o)),L(t.property_blacklist)&&(x(t.property_denylist)?i.property_denylist=t.property_blacklist:L(t.property_denylist)?i.property_denylist=[...t.property_blacklist,...t.property_denylist]:k.error(cd+t.property_denylist)),i};class df{constructor(){this.__forceAllowLocalhost=!1}get fn(){return this.__forceAllowLocalhost}set fn(e){k.error("WebPerformanceObserver is deprecated and has no impact on network capture. Use `_forceAllowLocalhostNetworkCapture` on `posthog.sessionRecording`"),this.__forceAllowLocalhost=e}}class Te{pn(e,s){if(e){var r=this.sn.indexOf(e);r!==-1&&this.sn.splice(r,1)}return this.sn.push(s),s.initialize==null||s.initialize(),s}gn(){return this.config.cookieless_mode===ht||this.config.cookieless_mode===Ht&&this.consent.isRejected()}get decideEndpointWasHit(){var e,s;return(e=(s=this.featureFlags)==null?void 0:s.hasLoadedFlags)!==null&&e!==void 0&&e}get flagsEndpointWasHit(){var e,s;return(e=(s=this.featureFlags)==null?void 0:s.hasLoadedFlags)!==null&&e!==void 0&&e}constructor(){var e;this.webPerformance=new df,this.mn=!1,this.version=Y.LIB_VERSION,this.yn=new Set,this.bn="",this.dn=new ta,this.sn=[],this._n=[],this._calculate_event_properties=this.calculateEventProperties.bind(this),this.config=bi(),this.SentryIntegration=Pp,this.sentryIntegration=r=>(function(n,i){var o=Nu(n,i);return{name:Tu,processEvent:a=>o(a)}})(this,r),this.__request_queue=[],this.__loaded=!1,this.analyticsDefaultEndpoint="/e/",this.wn=!1,this.kn=null,this.xn=null,this.Sn=null,this.scrollManager=new Yp(this),this.pageViewManager=new vl(this),this.rateLimiter=new Dp(this),this.requestRouter=new Qp(this),this.consent=new mp(this),this.externalIntegrations=new nf(this);var s=(e=Te.__defaultExtensionClasses)!==null&&e!==void 0?e:{};this.featureFlags=s.featureFlags&&new s.featureFlags(this),this.toolbar=s.toolbar&&new s.toolbar(this),this.surveys=s.surveys&&new s.surveys(this),this.conversations=s.conversations&&new s.conversations(this),this.logs=s.logs&&new s.logs(this),this.metrics=s.metrics&&new s.metrics(this),this.experiments=s.experiments&&new s.experiments(this),this.exceptions=s.exceptions&&new s.exceptions(this),this.people={set:(r,n,i)=>{var o=W(r)?{[r]:n}:r;this.setPersonProperties(o),i?.({})},set_once:(r,n,i)=>{var o=W(r)?{[r]:n}:r;this.setPersonProperties(void 0,o),i?.({})}},this.on("eventCaptured",(r=>k.info('send "'+r?.event+'"',r)))}init(e,s,r){if(r&&r!==os){var n,i=(n=Ys[r])!==null&&n!==void 0?n:new Te;return i._init(e,s,r),Ys[r]=i,Ys[os][r]=i,i}return this._init(e,s,r)}_init(e,s,r){var n,i;s===void 0&&(s={});var o,a=W(e)?e.trim():"";if(!a)return k.critical("PostHog was initialized without a token. This likely indicates a misconfiguration. Please check the first argument passed to posthog.init()"),this;if(this.__loaded)return a!==((o=this.config)==null?void 0:o.token)?console.warn("[PostHog.js]","You have already initialized PostHog with a different project token! Re-initializing is a no-op, so events will keep going to the project this instance was initialized with. To capture into a second project, load PostHog once, then initialize a named instance after the SDK has loaded, e.g. posthog.init('"+a+"', { ... }, 'project2')"):console.warn("[PostHog.js]","You have already initialized PostHog! Re-initializing is a no-op"),this;this.__loaded=!0,this.config=bi(s.defaults),s.debug=this.Cn(s.debug),this.Mn=s,this.Tn=[],s.person_profiles?this.xn=s.person_profiles:s.process_person&&(this.xn=s.process_person);var l=bi(s.defaults),u=Rl(s),c=ee({},l,u,{name:r,token:a});te(l.rageclick)&&te(u.rageclick)&&(c.rageclick=ee({},l.rageclick,u.rageclick)),te(l.session_recording)&&te(u.session_recording)&&(c.session_recording=ee({},l.session_recording,u.session_recording)),this.set_config(c),this.config.on_xhr_error&&k.error("on_xhr_error is deprecated. Use on_request_error instead"),this.compression=s.disable_compression?void 0:xe.GZipJS;var d=this.En();if(this.persistence=new pi(this.config,d),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new pi(E({},this.config,{persistence:"sessionStorage"}),d,!1),this.bn="ph_"+(this.config.persistence_name||this.config.token)+"_session_registered_properties",this.config.persistence!=="memory"&&!d&&ce.N()){var h=ce.H(this.bn);L(h)&&h.forEach((P=>{W(P)&&this.yn.add(P)}))}else ce.q(this.bn);var p=E({},this.persistence.props),f=E({},this.sessionPersistence.props);this.register({$initialization_time:new Date().toISOString()}),this.In=new Gp((P=>this.Pn(P)),this.config.request_queue_config),this.Rn=new Jp(this),this.__request_queue=[];var m=this.gn();if(m||(this.sessionManager=new Cl(this),this.sessionPropsManager=new Il(this,this.sessionManager,this.persistence),this.sessionManager.onSessionId(((P,j,S)=>{(S!=null&&S.activityTimeout||S!=null&&S.sessionPastMaximumLength||S!=null&&S.crossTabAdoption)&&this.An()}))),this.Fn(),this.config.__preview_deferred_init_extensions?(k.info("Deferring extension initialization to improve startup performance"),setTimeout((()=>{this.Ln(m)}),0)):(k.info("Initializing extensions synchronously"),this.Ln(m)),Y.DEBUG=Y.DEBUG||this.config.debug,Y.DEBUG&&k.info("Starting in debug mode",{this:this,config:s,thisC:E({},this.config),p,s:f}),!this.config.identity_distinct_id||(n=s.bootstrap)!=null&&n.distinctID||(s.bootstrap=E({},s.bootstrap,{distinctID:this.config.identity_distinct_id,isIdentifiedID:!0})),((i=s.bootstrap)==null?void 0:i.distinctID)!==void 0){var g=s.bootstrap.distinctID,_=this.get_distinct_id(),w=this.persistence.get_property(He);if(s.bootstrap.isIdentifiedID&&_!=null&&_!==g&&w===es)this.identify(g);else if(s.bootstrap.isIdentifiedID&&_!=null&&_!==g&&w===Tt)k.warn("Bootstrap distinctID differs from an already-identified user. The existing identity is preserved. Call reset() before reinitializing if you intend to switch users.");else{var b=this.config.get_device_id(dt()),I=s.bootstrap.isIdentifiedID?b:g;this.persistence.set_property(He,s.bootstrap.isIdentifiedID?Tt:es),this.register({distinct_id:g,$device_id:I})}}if(m)this.register_once({distinct_id:br,$device_id:null},"");else if(!this.get_distinct_id()){var F=this.config.get_device_id(dt());this.register_once({distinct_id:F,$device_id:F},""),this.persistence.set_property(He,es)}return ne(v,"onpagehide"in self?"pagehide":"unload",this._handle_unload.bind(this),{passive:!1}),s.segment?(function(P,j){var S=P.config.segment;if(!S)return j();(function(A,R){var N=A.config.segment;if(!N)return R();var T=J=>{var z=()=>J.anonymousId()||dt();A.config.get_device_id=z,J.id()&&(A.register({distinct_id:J.id(),$device_id:z()}),A.persistence.set_property(He,Tt)),R()},O=N.user();"then"in O&&Se(O.then)?O.then(T):T(O)})(P,(()=>{S.register((A=>{typeof Promise<"u"&&Promise.resolve||di.warn("This browser does not have Promise support, and can not use the segment integration");var R=(N,T)=>{if(!T)return N;N.event.userId||N.event.anonymousId===A.get_distinct_id()||(di.info("No userId set, resetting PostHog"),A.reset()),N.event.userId&&N.event.userId!==A.get_distinct_id()&&(di.info("UserId set, identifying with PostHog"),A.identify(N.event.userId));var O=A.calculateEventProperties(T,N.event.properties);return N.event.properties=Object.assign({},O,N.event.properties),N};return{name:"PostHog JS",type:"enrichment",version:"1.0.0",isLoaded:()=>!0,load:()=>Promise.resolve(),track:N=>R(N,N.event.event),page:N=>R(N,is),identify:N=>R(N,li),screen:N=>R(N,"$screen")}})(P)).then((()=>{j()}))}))})(this,(()=>this.On())):this.On(),Se(this.config._onCapture)&&this.config._onCapture!==gn&&(k.warn("onCapture is deprecated. Please use `before_send` instead"),this.on("eventCaptured",(P=>this.config._onCapture(P.event,P)))),this.config.ip&&k.warn('The `ip` config option has NO EFFECT AT ALL and has been deprecated. Use a custom transformation or "Discard IP data" project setting instead. See https://posthog.com/tutorials/web-redact-properties#hiding-customer-ip-address for more information.'),this.config.disableDeviceModel||(function(){return rd.apply(this,arguments)})().then((P=>{P&&this.register({[oi]:P})})).catch(gn),this}Fn(){var e,s,r,n,i,o,a=(e=(s=this.config.__extensionClasses)==null?void 0:s.featureFlags)!==null&&e!==void 0?e:(r=Te.__defaultExtensionClasses)==null?void 0:r.featureFlags;a&&(this.featureFlags&&this.featureFlags instanceof a||((n=this.Dn)==null||n.call(this),this.Dn=void 0,this.featureFlags=new a(this)),Se(this.featureFlags.onReloading)&&Se(this.featureFlags.setup)?this.Dn||(this.Dn=this.featureFlags.onReloading((()=>{this.dn.emit("featureFlagsReloading",!0)})),this.$n().add(this.featureFlags)):(i=(o=this.featureFlags).initialize)==null||i.call(o))}Ln(e){var s,r,n,i,o,a,l,u=performance.now(),c=E({},Te.__defaultExtensionClasses,this.config.__extensionClasses),d=[];c.exceptions&&this.sn.push(this.exceptions=(s=this.exceptions)!==null&&s!==void 0?s:new c.exceptions(this)),c.historyAutocapture&&this.sn.push(this.historyAutocapture=new c.historyAutocapture(this)),c.tracingHeaders&&this.sn.push(this.tracingHeaders=new c.tracingHeaders(this)),c.siteApps&&this.sn.push(this.siteApps=new c.siteApps(this)),c.sessionRecording&&!e&&this.sn.push(this.sessionRecording=new c.sessionRecording(this)),this.config.disable_scroll_properties||d.push((()=>{this.scrollManager.startMeasuringScrollPosition()})),c.autocapture&&this.sn.push(this.autocapture=new c.autocapture(this)),c.surveys&&this.sn.push(this.surveys=(r=this.surveys)!==null&&r!==void 0?r:new c.surveys(this)),c.logs&&this.sn.push(this.logs=(n=this.logs)!==null&&n!==void 0?n:new c.logs(this)),c.metrics&&this.sn.push(this.metrics=(i=this.metrics)!==null&&i!==void 0?i: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,Fp)),c.toolbar&&this.sn.push(this.toolbar=(a=this.toolbar)!==null&&a!==void 0?a:new c.toolbar(this)),c.experiments&&this.sn.push(this.experiments=(l=this.experiments)!==null&&l!==void 0?l:new c.experiments(this)),this.sn.forEach((h=>{h.initialize&&d.push((()=>{h.initialize==null||h.initialize()}))})),d.push((()=>{if(this.Nn){var h=this.Nn;this.Nn=void 0,this.sn.forEach((p=>p.onRemoteConfig==null?void 0:p.onRemoteConfig(h)))}})),this.qn(d,u)}qn(e,s){for(;e.length>0;){if(this.config.__preview_deferred_init_extensions&&performance.now()-s>=30&&e.length>0)return void setTimeout((()=>{this.qn(e,s)}),0);var r=e.shift();if(r)try{r()}catch(i){k.error("Error initializing extension:",i)}}var n=Math.round(performance.now()-s);this.register_for_session({[vu]:this.config.__preview_deferred_init_extensions?"deferred":"synchronous",[_u]:n}),this.config.__preview_deferred_init_extensions&&k.info("PostHog extensions initialized ("+n+"ms)")}Zi(e){var s;if(!C||!C.body)return k.info("document not ready yet, trying again in 500 milliseconds..."),void setTimeout((()=>{this.Zi(e)}),500);if(this.config.__preview_deferred_init_extensions&&(this.Nn=e),this.hn=e,this.compression=void 0,e.ok){var r,n=e.config;n.supportedCompression&&!this.config.disable_compression&&(this.compression=M(n.supportedCompression,xe.GZipJS)?xe.GZipJS:M(n.supportedCompression,xe.Base64)?xe.Base64:void 0),(r=n.analytics)!=null&&r.endpoint&&(this.analyticsDefaultEndpoint=n.analytics.endpoint)}this.set_config({person_profiles:this.xn?this.xn:no}),(s=this.jn)==null||s.handleRemoteConfig(e),this.sn.forEach((i=>i.onRemoteConfig==null?void 0:i.onRemoteConfig(e)))}On(){try{this.config.loaded(this)}catch(r){k.critical("`loaded` function failed",r)}if(this.Bn(),this.config.internal_or_test_user_hostname&&re!=null&&re.hostname){var e=re.hostname,s=this.config.internal_or_test_user_hostname;(typeof s=="string"?e===s:s.test(e))&&this.setInternalOrTestUser()}this.config.capture_pageview&&setTimeout((()=>{(this.consent.isOptedIn()||this.gn())&&this.Hn()}),1),this.Un=new zu(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()&&Er(this.__request_queue,(e=>this.Pn(e))),this.__request_queue=[],this.Bn()}_handle_unload(){var e,s,r,n,i;(e=this.surveys)==null||e.handlePageUnload==null||e.handlePageUnload(),(s=this.metrics)==null||s.flush("sendBeacon"),this.config.request_batching?(this.zn()&&this.capture(ai),(r=this.logs)==null||r.flushLogs("sendBeacon"),(n=this.In)==null||n.unload(),(i=this.Rn)==null||i.unload()):this.zn()&&this.capture(ai,null,{transport:"sendBeacon"})}_send_request(e){this.__loaded?ud?this.__request_queue.push(e):this.rateLimiter.isServerRateLimited(e.batchKey)?e.fireCallbackOnDrop&&(e.callback==null||e.callback({statusCode:429})):(e.transport=e.transport||this.config.api_transport,e.headers=E({},this.config.request_headers,e.headers),e.compression=e.compression==="best-available"?this.compression:e.compression,(x(this.config.disable_beacon)?this.config.__preview_disable_beacon:this.config.disable_beacon)&&(e.disableTransport=["sendBeacon"]),e.fetchOptions=e.fetchOptions||this.config.fetch_options,(s=>{var r,n,i,o=E({},s);o.timeout=o.timeout||6e4;var a,l,u,c,d,h=(r=o.transport)!==null&&r!==void 0?r:"fetch";h==="sendBeacon"&&x(o.compression)&&o.data&&(o.compression=xe.Base64),o.method==="POST"&&o.data&&(o.timestampMode==="capture-body"?o.data={api_key:(l=(d=(c=L(a=o.data)?a:[a])[0])==null||(u=d.properties)==null?void 0:u.token)!==null&&l!==void 0?l:d?.token,batch:c,sent_at:new Date().toISOString()}:o.timestampMode==="body"&&(o.data=(function(g,_){return _===void 0&&(_=new Date().toISOString()),L(g)?g.map((w=>E({},w,{sent_at:_}))):E({},g,{sent_at:_})})(o.data))),o.url=kl(o.url,o.method,o.compression,o.timestampMode);var p=Br.filter((g=>!o.disableTransport||!g.transport||!o.disableTransport.includes(g.transport))),f=(n=(i=(function(g,_){for(var w=0;g.length>w;w++)if(g[w].transport===h)return g[w]})(p))==null?void 0:i.method)!==null&&n!==void 0?n:p[0].method;if(!f)throw new Error("No available transport method");var m=g=>{try{f(g)}catch(_){ed(_)?k.warn(_):k.error(_),o.callback==null||o.callback({statusCode:0,error:_})}};h!=="sendBeacon"&&o.data&&o.compression===xe.GZipJS&&dh&&typeof Promise<"u"&&!Dr?qp(o).then((g=>{m(g)})).catch((g=>{if(qa(g))return Dr=!0,void m(E({},o,{compression:void 0,url:kl(s.url,s.method,void 0,s.timestampMode)}));(_=>{if(!_||typeof _!="object")return!1;var w="name"in _?String(_.name):"";return qa(_)||w===Ac})(g)&&(Dr=!0),m(o)})):f(o)})(E({},e,{callback:s=>{var r,n;this.rateLimiter.checkForLimiting(s),400>s.statusCode||(r=(n=this.config).on_request_error)==null||r.call(n,s),e.callback==null||e.callback(s)}}))):e.fireCallbackOnDrop&&(e.callback==null||e.callback({statusCode:0}))}Pn(e){this.Rn?this.Rn.retriableRequest(e):this._send_request(e)}_execute_array(e){wi++;try{var s,r=[],n=[],i=[];Er(e,(a=>{if(a)if(L(s=a[0]))i.push(a);else if(Se(a))try{a.call(this)}catch(l){k.error("Error executing queued PostHog call",a,l)}else L(a)&&s==="alias"?r.push(a):L(a)&&s.indexOf("capture")!==-1&&Se(this[s])?i.push(a):n.push(a)}));var o=function(a,l){Er(a,(function(u){try{if(L(u[0])){var c=l;Z(u,(function(d){c=c[d[0]].apply(c,d.slice(1))}))}else l[u[0]].apply(l,u.slice(1))}catch(d){k.error("Error executing queued PostHog call",u,d)}}))};o(r,this),o(n,this),o(i,this)}finally{wi--}}push(e){if(wi>0&&L(e)&&W(e[0])){var s=Te.prototype[e[0]];Se(s)&&s.apply(this,e.slice(1))}else this._execute_array([e])}capture(e,s,r){var n,i,o,a,l;if(this.__loaded&&this.persistence&&this.sessionPersistence&&this.In){if(this.is_capturing())if(!x(e)&&W(e)){var u=!this.config.opt_out_useragent_filter&&this._is_bot();if(!u||this.config.__preview_capture_bot_pageviews){var c=r!=null&&r.skip_client_rate_limiting?void 0:this.rateLimiter.clientRateLimitContext();if(c==null||!c.isRateLimited){s!=null&&s.$current_url&&!W(s?.$current_url)&&(k.error("Invalid `$current_url` property provided to `posthog.capture`. Input must be a string. Ignoring provided value."),s==null||delete s.$current_url),e!=="$exception"||r!=null&&r.Wn||k.warn("Using `posthog.capture('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureException(error)` instead, which attaches required metadata automatically."),this.sessionPersistence.update_search_keyword(),this.config.save_campaign_params&&this.sessionPersistence.update_campaign_params(),this.config.save_referrer&&this.sessionPersistence.update_referrer_info(),(this.config.save_campaign_params||this.config.save_referrer)&&this.persistence.set_initial_person_info();var d=new Date,h=r?.timestamp||d,p=Ya(r?.uuid,dt),f={uuid:p,event:e,properties:this.calculateEventProperties(e,s||{},h,p)};e===is&&this.config.__preview_capture_bot_pageviews&&u&&(f.event="$bot_pageview",f.properties.$browser_type="bot"),c&&(f.properties.$lib_rate_limit_remaining_tokens=c.remainingTokens);var m=e==="$feature_flag_called"&&f.properties.$feature_flag_has_experiment===!1&&this.get_property(tn)===!0;r?.$set&&!m&&(f.$set=r?.$set);var g=r?.$unset;g&&(f.$unset=g);var _,w,b,I=m?void 0:this.Vn(r?.$set_once,e!==sl,e===li);if(I&&(f.$set_once=I),r!=null&&r._noTruncate||(i=this.config.properties_string_max_length,o=f,a=T=>W(T)?T.slice(0,i):T,l=new Set,f=(function T(O,J){if(O!==Object(O))return a?a(O):O;if(!l.has(O)){var z;if(l.add(O),L(O))z=[],Er(O,(oe=>{z.push(T(oe))}));else{var H={};Z(O,((oe,pe)=>{l.has(oe)||(H[pe]=T(oe))})),z=H}return z}})(o)),f.timestamp=h,x(r?.timestamp)||(f.properties.$event_time_override_provided=!0,f.properties.$event_time_override_system_time=d),m&&(f.properties=(function(T,O){O===void 0&&(O=[]);var J={},z=H=>{T[H]!==void 0&&(J[H]=T[H])};return hh.forEach(z),O.forEach(z),J})(f.properties,cf)),e===ft.DISMISSED||e===ft.SENT){var F=s?.[gi.SURVEY_ID],P=s?.[gi.SURVEY_ITERATION];ld({id:F,current_iteration:P}),f.$set=E({},f.$set,{[(_={id:F,current_iteration:P},w=e===ft.SENT?"responded":"dismissed",b="$survey_"+w+"/"+_.id,_.current_iteration&&_.current_iteration>0&&(b="$survey_"+w+"/"+_.id+"/"+_.current_iteration),b)]:!0})}else e===ft.SHOWN&&(f.$set=E({},f.$set,{[gi.SURVEY_LAST_SEEN_DATE]:new Date().toISOString()}));if(e===Op.SHOWN){var j=s?.[yl.TOUR_TYPE];j&&(f.$set=E({},f.$set,{[yl.TOUR_LAST_SEEN_DATE+"/"+j]:new Date().toISOString()}))}var S=E({},f.properties.$set,f.$set);if(mt(S)||this.setPersonPropertiesForFlags(S),!D(this.config.before_send)){var A=this.Pt(f);if(!A)return;(f=A).uuid=Ya(f.uuid,dt)}this.dn.emit("eventCaptured",f);var R=(n=r?._url)!==null&&n!==void 0?n:this.requestRouter.endpointFor("api",this.analyticsDefaultEndpoint),N={method:"POST",url:R,data:f,compression:"best-available",timestampMode:r?._batchKey==="recordings"||/\/s\/(?:\?|$)/.test(R)?"body":"capture-body",batchKey:r?._batchKey,transport:r?.transport};return!this.config.request_batching||r&&(r==null||!r._batchKey)||r!=null&&r.send_instantly?this.Pn(N):this.In.enqueue(N),f}k.critical("This capture call is ignored due to client rate limiting.")}}else k.error("No event name provided to posthog.capture")}else k.uninitializedWarning("posthog.capture")}_addCaptureHook(e){return this.on("eventCaptured",(s=>e(s.event,s)))}$n(){var e;return(e=this.jn)!==null&&e!==void 0?e:this.jn=new lf(this)}cn(e){this._n.push(e);var s=!0;return()=>{if(s){s=!1;var r=this._n.indexOf(e);r!==-1&&this._n.splice(r,1)}}}calculateEventProperties(e,s,r,n,i){if(r=r||new Date,!this.persistence||!this.sessionPersistence)return s;var o=i?void 0:this.persistence.remove_event_timer(e),a=E({},s);if(a.token=this.config.token,a.$config_defaults=this.config.defaults,this.gn()&&(a[mu]=!0),e==="$snapshot"){var l=E({},this.persistence.properties(),this.sessionPersistence.properties());return a.distinct_id=l.distinct_id,(!W(a.distinct_id)&&!he(a.distinct_id)||Di(a.distinct_id))&&k.error("Invalid distinct_id for replay event. This indicates a bug in your implementation"),a}var u,c=(function(F,P,j,S){var A,R,N,T;if(S===void 0&&(S=!1),!Pe)return{};var O,J=F?[...vs,...P||[]]:[],z=(function(vr){for(var je=0;Ka.length>je;je++){var _r=Ka[je],Xt=_r[1],Qt=_r[0].exec(vr),Is=Qt&&(Se(Xt)?Xt(Qt,vr):Xt);if(Is)return Is}return["",""]})(Pe),H=z[0],oe=z[1],pe=(O=typeof navigator<"u"?navigator:void 0)!=null&&O.brave?{brave:!0}:{},Ie={};x(j)||(Ie.detectGoogleSearchApp=j);var _e={},Ce=(A=navigator)==null||(A=A.userAgentData)==null?void 0:A.platform,Re=(R=navigator)==null?void 0:R.maxTouchPoints,ae=v==null||(N=v.screen)==null?void 0:N.width,me=v==null||(T=v.screen)==null?void 0:T.height,ge=v?.devicePixelRatio;x(Ce)||(_e.userAgentDataPlatform=Ce),x(Re)||(_e.maxTouchPoints=Re),x(ae)||(_e.screenWidth=ae),x(me)||(_e.screenHeight=me),x(ge)||(_e.devicePixelRatio=ge);var Ye,Rt,de,Ve,St,ks,Be,Fe,mr=ee(Jo({$os:H,$os_version:oe,$browser:tu(Pe,navigator.vendor,pe,Ie),$device:Ja(Pe),$device_type:(Rt=Pe,de=_e,Fe=Ja(Rt),Fe===Oc||Fe===Lc||Fe==="Kobo"||Fe==="Kindle Fire"||Fe===Yc?ps:Fe===er||Fe===ds||Fe===tr||Fe===ji?"Console":Fe===Bc?"Wearable":Fe?Oe:de?.userAgentDataPlatform==="Android"&&((Ve=de?.maxTouchPoints)!==null&&Ve!==void 0?Ve:0)>0?600>Math.min((St=de?.screenWidth)!==null&&St!==void 0?St:0,(ks=de?.screenHeight)!==null&&ks!==void 0?ks:0)/((Be=de?.devicePixelRatio)!==null&&Be!==void 0?Be:1)?Oe:ps:"Desktop"),$timezone:Wu(),$timezone_offset:Np()}),{$current_url:nr(S?Ct(re?.href):re?.href,J,ir),$host:re?.host,$pathname:re?.pathname,$raw_user_agent:Pe.length>1e3?Pe.substring(0,997)+"...":Pe,$browser_version:$h(Pe,navigator.vendor,pe,Ie),$browser_language:_l(),$browser_language_prefix:(Ye=_l(),typeof Ye=="string"?Ye.split("-")[0]:void 0),$screen_height:v?.screen.height,$screen_width:v?.screen.width,$viewport_height:v?.innerHeight,$viewport_width:v?.innerWidth,$lib:Y.LIB_NAME,$lib_version:Y.LIB_VERSION,$insert_id:Math.random().toString(36).substring(2,10)+Math.random().toString(36).substring(2,10),$time:Date.now()/1e3});return Y.SDK_DIST_CHANNEL&&(mr.$sdk_dist_channel=Y.SDK_DIST_CHANNEL),mr})(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(i,r.getTime()),h=d.windowId;a.$session_id=d.sessionId,a.$window_id=h}this.sessionPropsManager&&ee(a,this.sessionPropsManager.getSessionProps());try{var p;this.sessionRecording&&ee(a,this.sessionRecording.sdkDebugProperties),a.$sdk_debug_retry_queue_size=(p=this.Rn)==null?void 0:p.length}catch(F){a.$sdk_debug_error_capturing_properties=String(F)}if(this.requestRouter.region===go&&(a.$lib_custom_api_host=this.config.api_host),u=e!==is||i?e!==ai||i?this.pageViewManager.doEvent():this.pageViewManager.doPageLeave(r):this.pageViewManager.doPageView(r,n),a=ee(a,u),e===is&&C&&(a.title=C.title),!x(o)){var f=r.getTime()-o;a.$duration=parseFloat((f/1e3).toFixed(3))}Pe&&this.config.opt_out_useragent_filter&&(a.$browser_type=this._is_bot()?"bot":"browser");var m=this.persistence.properties(),g=this.sessionPersistence.properties();Z(["$referrer","$referring_domain"],(F=>{F in m&&delete g[F]}));var _={};if(this._n.length>0)for(var w of this._n.slice())try{ee(_,w())}catch(F){k.error("Failed to produce browser extension event properties",F)}(a=ee({},c,m,g,E({},_,a))).$is_identified=this._isIdentified(),L(this.config.property_denylist)?Z(this.config.property_denylist,(function(F){delete a[F]})):k.error(cd+this.config.property_denylist+" or property_blacklist config: "+this.config.property_blacklist);var b=this.config.sanitize_properties;b&&(k.error($l),a=b(a,e));var I=this.Zn();return a.$process_person_profile=I,I&&!i&&this.Gn("_calculate_event_properties"),a}Vn(e,s,r){var n;if(s===void 0&&(s=!0),r===void 0&&(r=!1),!this.persistence||!this.Zn()||this.mn&&!r)return e;var i=this.persistence.get_initial_props(),o=(n=this.sessionPropsManager)==null?void 0:n.getSetOnceProps(),a=ee({},i,o||{},e||{}),l=this.config.sanitize_properties;return l&&(k.error($l),a=l(a,"$set_once")),s&&(this.mn=!0),mt(a)?void 0:a}register(e,s){var r;(r=this.persistence)==null||r.register(e,s)}register_once(e,s,r){var n;(n=this.persistence)==null||n.register_once(e,s,r)}register_for_session(e){var s;(s=this.sessionPersistence)==null||s.register(e),Object.keys(e).forEach((r=>this.yn.add(r))),this.Qn()}unregister(e){var s;(s=this.persistence)==null||s.unregister(e)}unregister_for_session(e){var s;(s=this.sessionPersistence)==null||s.unregister(e),this.yn.delete(e),this.Qn()}Kn(e,s){this.register({[e]:s})}An(){this.yn.forEach((e=>{var s;(s=this.sessionPersistence)==null||s.unregister(e)})),this.yn.clear(),this.Qn()}Qn(){var e;if(this.bn)if(this.config.persistence==="memory"||(e=this.sessionPersistence)!=null&&e.xi||!ce.N())ce.q(this.bn);else{var s=[];this.yn.forEach((r=>s.push(r))),s.length>0?ce.F(this.bn,s):ce.q(this.bn)}}getFeatureFlag(e,s){var r;return(r=this.featureFlags)==null?void 0:r.getFeatureFlag(e,s)}getFeatureFlagPayload(e){var s;return(s=this.featureFlags)==null?void 0:s.getFeatureFlagPayload(e)}getFeatureFlagResult(e,s){var r;return(r=this.featureFlags)==null?void 0:r.getFeatureFlagResult(e,s)}getAllFeatureFlags(){var e,s;return(e=(s=this.featureFlags)==null?void 0:s.getAllFeatureFlags())!==null&&e!==void 0?e:[]}isFeatureEnabled(e,s){var r,n;return(r=(n=this.featureFlags)==null?void 0:n.isFeatureEnabled(e,s))!==null&&r!==void 0?r:s?.defaultValue}reloadFeatureFlags(){var e;(e=this.featureFlags)==null||e.reloadFeatureFlags()}updateFlags(e,s,r){var n;(n=this.featureFlags)==null||n.updateFlags(e,s,r)}updateEarlyAccessFeatureEnrollment(e,s,r){var n;(n=this.featureFlags)==null||n.updateEarlyAccessFeatureEnrollment(e,s,r)}getEarlyAccessFeatures(e,s,r){var n;return s===void 0&&(s=!1),(n=this.featureFlags)==null?void 0:n.getEarlyAccessFeatures(e,s,r)}on(e,s){return this.dn.on(e,s)}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:Ns}),()=>{})}onSessionId(e){var s,r;return(s=(r=this.sessionManager)==null?void 0:r.onSessionId(e))!==null&&s!==void 0?s:()=>{}}getSurveys(e,s){s===void 0&&(s=!1),this.surveys?this.surveys.getSurveys(e,s):e([],{isLoaded:!1,error:Ns})}getActiveMatchingSurveys(e,s){s===void 0&&(s=!1),this.surveys?this.surveys.getActiveMatchingSurveys(e,s):e([],{isLoaded:!1,error:Ns})}renderSurvey(e,s){var r;(r=this.surveys)==null||r.renderSurvey(e,s)}displaySurvey(e,s){var r;s===void 0&&(s=tf),(r=this.surveys)==null||r.displaySurvey(e,s)}cancelPendingSurvey(e){var s;(s=this.surveys)==null||s.cancelPendingSurvey(e)}canRenderSurvey(e){var s,r;return(s=(r=this.surveys)==null?void 0:r.canRenderSurvey(e))!==null&&s!==void 0?s:{visible:!1,disabledReason:Ns}}canRenderSurveyAsync(e,s){var r,n;return s===void 0&&(s=!1),(r=(n=this.surveys)==null?void 0:n.canRenderSurveyAsync(e,s))!==null&&r!==void 0?r:Promise.resolve({visible:!1,disabledReason:Ns})}Jn(e){return!e||Di(e)?(k.critical("Unique user id has not been set in posthog.identify"),!1):e===br?(k.critical('The string "'+e+'" was set in posthog.identify which indicates an error. This ID is only used as a sentinel value.'),!1):!["distinct_id","distinctid"].includes(e.toLowerCase())&&!["undefined","null"].includes(e.toLowerCase())||(k.critical('The string "'+e+'" was set in posthog.identify which indicates an error. This ID should be unique to the user and not a hardcoded string.'),!1)}identify(e,s,r){if(!this.__loaded||!this.persistence)return k.uninitializedWarning("posthog.identify");if(he(e)&&(e=e.toString(),k.warn("The first argument to posthog.identify was a number, but it should be a string. It has been converted to a string.")),this.Jn(e)&&this.Gn("posthog.identify")){var n=this.get_distinct_id();this.register({$user_id:e}),this.get_property(sr)||this.register_once({$had_persisted_distinct_id:!0,$device_id:n},""),e!==n&&e!==this.get_property(Bs)&&(this.unregister(Bs),this.register({distinct_id:e}));var i,o=(this.persistence.get_property(He)||es)===es,a=e!==n,l=!a&&o;if(a&&o)this.persistence.set_property(He,Tt),this.setPersonPropertiesForFlags({$set:s||{},$set_once:r||{}},!1),this.capture(li,{distinct_id:e,$anon_distinct_id:n},{$set:s||{},$set_once:r||{}}),this.Sn=yi(e,s,r),(i=this.featureFlags)==null||i.setAnonymousDistinctId(n);else if(l){this.persistence.set_property(He,Tt);var u=s||{},c=r||{};this.setPersonPropertiesForFlags({$set:u,$set_once:c},!1),this.capture("$set",{$set:u,$set_once:c}),this.Sn=yi(e,s,r)}else(s||r)&&this.setPersonProperties(s,r);a?(this.reloadFeatureFlags(),this.featureFlags?this.featureFlags.resetFlagCallReported():this.unregister(Wt)):l&&(s||r)&&this.reloadFeatureFlags()}}setPersonProperties(e,s){if((e||s)&&this.Gn("posthog.setPersonProperties")){var r=yi(this.get_distinct_id(),e,s);this.Sn!==r?(this.setPersonPropertiesForFlags({$set:e||{},$set_once:s||{}},!0),this.capture("$set",{$set:e||{},$set_once:s||{}}),this.Sn=r):k.info("A duplicate setPersonProperties call was made with the same properties. It has been ignored.")}}unsetPersonProperties(e){var s,r=(L(e)?e:[e]).filter((n=>W(n)&&n.length>0));r.length!==0&&this.Gn("posthog.unsetPersonProperties")&&((s=this.featureFlags)==null||s.unsetPersonPropertiesForFlags(r,!0),this.capture("$set",{$unset:r}),this.Sn=null)}group(e,s,r){if(e&&s){var n=this.getGroups(),i=n[e]!==s;if(i&&this.resetGroupPropertiesForFlags(e),this.register({$groups:E({},n,{[e]:s})}),i||r){var o={$group_type:e,$group_key:s};r&&(o.$group_set=r),this.capture(sl,o)}r&&this.setGroupPropertiesForFlags({[e]:r}),i&&!r&&this.reloadFeatureFlags()}else k.error("posthog.group requires a group type and group key")}resetGroups(){this.register({$groups:{}}),this.resetGroupPropertiesForFlags(),this.reloadFeatureFlags()}setPersonPropertiesForFlags(e,s){var r;s===void 0&&(s=!0),(r=this.featureFlags)==null||r.setPersonPropertiesForFlags(e,s)}resetPersonPropertiesForFlags(e){var s;e===void 0&&(e=!0),(s=this.featureFlags)==null||s.resetPersonPropertiesForFlags(e)}setGroupPropertiesForFlags(e,s){var r;s===void 0&&(s=!0),this.Gn("posthog.setGroupPropertiesForFlags")&&((r=this.featureFlags)==null||r.setGroupPropertiesForFlags(e,s))}resetGroupPropertiesForFlags(e){var s;(s=this.featureFlags)==null||s.resetGroupPropertiesForFlags(e)}reset(e){this.Yn(e)}Yn(e,s){var r,n,i,o,a,l,u,c,d,h;if(s===void 0&&(s=!1),k.info("reset"),!this.__loaded)return k.uninitializedWarning("posthog.reset");var p,f=this.get_property(sr),m=this.get_property(oi),g=this.get_property(qt),_=this.is_capturing();if(this.consent.reset(),s||!_||this.is_capturing()||console.warn("[PostHog.js]","reset() cleared the stored consent, and capturing is now off because of `opt_out_capturing_by_default`. Call opt_in_capturing() again, and prefer calling reset() before opting in rather than after."),(r=this.persistence)==null||r.clear(),(n=this.sessionPersistence)==null||n.clear(),this.yn.clear(),this.Qn(),x(g)||(p=this.persistence)==null||p.register({[qt]:g}),(i=this.surveys)==null||i.reset(),(o=this.Un)==null||o.stop(),(a=this.featureFlags)==null||a.reset(),(l=this.conversations)==null||l.reset(),(u=this.logs)==null||u.reset(),(c=this.metrics)==null||c.reset(),(d=this.persistence)==null||d.set_property(He,es),(h=this.sessionManager)==null||h.resetSessionId(),this.Sn=null,this.config.cookieless_mode===ht)this.register_once({distinct_id:br,$device_id:null},"");else{var w=this.config.get_device_id(dt());this.register_once({distinct_id:w,$device_id:e?w:f},""),e||x(m)||this.register({[oi]:m})}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 s=this;return X((function*(){var r,n,i,o,a,l,u;if(s.__loaded){(r=s.Un)==null||r.stop(),(n=s.jn)==null||n.dispose(),(i=s.sessionRecording)==null||i.dispose(),(o=s.logs)==null||o.flushLogs("sendBeacon"),(a=s.metrics)==null||a.flush("sendBeacon"),(l=s.In)==null||l.unload(),(u=s.Rn)==null||u.unload();try{var c;(c=s.featureFlags)==null||c.destroy()}catch(d){k.error("Error while destroying feature flags",d)}}else k.uninitializedWarning("posthog.shutdown")}))()}setIdentity(e,s){var r;this.config.identity_distinct_id=e,this.config.identity_hash=s,this.alias(e),(r=this.conversations)==null||r.Xn()}clearIdentity(){var e;delete this.config.identity_distinct_id,delete this.config.identity_hash,(e=this.conversations)==null||e.ts()}get_distinct_id(){return this.get_property("distinct_id")}getGroups(){return this.get_property("$groups")||{}}get_session_id(){var e,s;return(e=(s=this.sessionManager)==null?void 0:s.checkAndGetSessionAndWindowId(!0).sessionId)!==null&&e!==void 0?e:""}get_session_replay_url(e){if(!this.sessionManager)return"";var s=this.sessionManager.checkAndGetSessionAndWindowId(!0),r=s.sessionStartTimestamp,n=this.requestRouter.endpointFor("ui","/project/"+this.config.token+"/replay/"+s.sessionId);if(e!=null&&e.withTimestamp&&r){var i,o=(i=e.timestampLookBack)!==null&&i!==void 0?i:10;if(!r)return n;n+="?t="+Math.max(Math.floor((new Date().getTime()-r)/1e3)-o,0)}return n}alias(e,s){return e===this.get_property(uu)?(k.critical("Attempting to create alias for existing People user - aborting."),-2):this.Gn("posthog.alias")?(x(s)&&(s=this.get_distinct_id()),e!==s?(this.Kn(Bs,e),this.capture("$create_alias",{alias:e,distinct_id:s})):(k.warn("alias matches current distinct_id - skipping api call."),this.identify(e),-1)):void 0}set_config(e){var s=E({},this.config);if(te(e)){var r,n,i,o,a,l,u,c,d,h,p,f;ee(this.config,Rl(e));var m=this.En();(r=this.persistence)==null||r.update_config(this.config,s,m),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new pi(E({},this.config,{persistence:"sessionStorage"}),m,!1);var g=this.Cn(this.config.debug);Ke(g)&&(this.config.debug=g),Ke(this.config.debug)&&(this.config.debug?(Y.DEBUG=!0,Q.N()&&Q.F("ph_debug",!0),k.info("set_config",{config:e,oldConfig:s,newConfig:E({},this.config)})):(Y.DEBUG=!1,Q.N()&&Q.q("ph_debug"))),(n=this.featureFlags)==null||n.updateConfig==null||n.updateConfig(this.config,this.Qi()),(i=this.exceptionObserver)==null||i.onConfigChange(),(o=this.exceptions)==null||o.onConfigChange(),(a=this.sessionRecording)==null||a.startIfEnabledOrStop(),(l=this.tracingHeaders)==null||l.startIfEnabledOrStop(),(u=this.autocapture)==null||u.startIfEnabled(),(c=this.heatmaps)==null||c.startIfEnabled(),(d=this.exceptionObserver)==null||d.startIfEnabledOrStop(),(h=this.deadClicksAutocapture)==null||h.startIfEnabledOrStop(),(p=this.surveys)==null||p.loadIfEnabled(),this.es(),(f=this.externalIntegrations)==null||f.startIfEnabledOrStop()}}_overrideSDKInfo(e,s){Y.LIB_NAME=e,Y.LIB_VERSION=s}startSessionRecording(e){var s,r,n,i,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)&&((s=this.sessionManager)==null||s.checkAndGetSessionAndWindowId(),l.sampling&&((r=this.sessionRecording)==null||r.overrideSampling()),l.linked_flag&&((n=this.sessionRecording)==null||n.overrideLinkedFlag()),l.url_trigger&&((i=this.sessionRecording)==null||i.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,s){if(this.exceptions){var r=new Error("PostHog syntheticException"),n=this.exceptions.buildProperties(e,{handled:!0,syntheticException:r});return this.exceptions.sendExceptionEvent(E({},n,s))}}addExceptionStep(e,s){var r;(r=this.exceptions)==null||r.addExceptionStep(e,s)}captureLog(e){var s;(s=this.logs)==null||s.captureLog(e)}get logger(){var e,s;return(e=(s=this.logs)==null?void 0:s.logger)!==null&&e!==void 0?e:Te.rs}startExceptionAutocapture(e){this.set_config({capture_exceptions:e==null||e})}stopExceptionAutocapture(){this.set_config({capture_exceptions:!1})}loadToolbar(e){var s,r;return(s=(r=this.toolbar)==null?void 0:r.loadToolbar(e))!==null&&s!==void 0&&s}get_property(e){var s;return(s=this.persistence)==null?void 0:s.props[e]}getSessionProperty(e){var s;return(s=this.sessionPersistence)==null?void 0:s.props[e]}toString(){var e,s=(e=this.config.name)!==null&&e!==void 0?e:os;return s!==os&&(s=os+"."+s),s}_isIdentified(){var e,s;return((e=this.persistence)==null?void 0:e.get_property(He))===Tt||((s=this.sessionPersistence)==null?void 0:s.get_property(He))===Tt}Zn(){var e,s;return!(this.config.person_profiles==="never"||this.config.person_profiles===no&&!this._isIdentified()&&mt(this.getGroups())&&((e=this.persistence)==null||(e=e.props)==null||!e[Bs])&&((s=this.persistence)==null||(s=s.props)==null||!s[nn]))}zn(){return this.config.capture_pageleave===!0||this.config.capture_pageleave==="if_capture_pageview"&&(this.config.capture_pageview===!0||this.config.capture_pageview==="history_change")}createPersonProfile(){this.Zn()||this.Gn("posthog.createPersonProfile")&&this.setPersonProperties({},{})}setInternalOrTestUser(){this.Gn("posthog.setInternalOrTestUser")&&this.setPersonProperties({$internal_or_test_user:!0})}Gn(e){return this.config.person_profiles==="never"?(k.error(e+' was called, but process_person is set to "never". This call will be ignored.'),!1):(this.Kn(nn,!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!==Ht)}es(){var e,s,r,n,i=this.En();return((e=this.persistence)==null?void 0:e.xi)!==i&&((r=this.persistence)==null||r.set_disabled(i)),((s=this.sessionPersistence)==null?void 0:s.xi)!==i&&((n=this.sessionPersistence)==null||n.set_disabled(i)),i&&(this.yn.clear(),this.Qn()),i}opt_in_capturing(e){var s;if(this.config.cookieless_mode!==ht){if(this.gn()){var r,n,i,o,a;this.Yn(!0,!0),(r=this.sessionManager)==null||r.destroy(),(n=this.pageViewManager)==null||n.destroy(),this.sessionManager=new Cl(this),this.pageViewManager=new vl(this),this.persistence&&(this.sessionPropsManager=new Il(this,this.sessionManager,this.persistence));var l,u=(i=(o=this.config.__extensionClasses)==null?void 0:o.sessionRecording)!==null&&i!==void 0?i:(a=Te.__defaultExtensionClasses)==null?void 0:a.sessionRecording;u&&(this.sessionRecording=this.pn(this.sessionRecording,new u(this)),this.hn&&((l=this.sessionRecording)==null||l.onRemoteConfig==null||l.onRemoteConfig(this.hn)))}var c,d;this.consent.optInOut(!0),this.es(),this.Bn(),(s=this.sessionRecording)==null||s.startIfEnabledOrStop(),this.config.cookieless_mode==Ht&&((c=this.surveys)==null||c.loadIfEnabled()),(x(e?.captureEventName)||e!=null&&e.captureEventName)&&this.capture((d=e?.captureEventName)!==null&&d!==void 0?d:"$opt_in",e?.captureProperties,{send_instantly:!0}),this.config.capture_pageview&&this.Hn()}else k.warn(Al)}opt_out_capturing(){var e,s,r;this.config.cookieless_mode!==ht?(this.config.cookieless_mode===Ht&&this.consent.isOptedIn()&&this.Yn(!0,!0),this.consent.optInOut(!1),this.es(),this.config.cookieless_mode===Ht&&(this.register({distinct_id:br,$device_id:null}),(e=this.sessionRecording)==null||e.stopRecording(),this.sessionRecording=void 0,(s=this.sessionManager)==null||s.destroy(),(r=this.pageViewManager)==null||r.destroy(),this.sessionManager=void 0,this.sessionPropsManager=void 0,this.config.capture_pageview&&this.Hn(),this.Bn())):k.warn(Al)}has_opted_in_capturing(){return this.consent.isOptedIn()}has_opted_out_capturing(){return this.consent.isOptedOut()}get_explicit_consent_status(){var e=this.consent.consent;return e===1?"granted":e===0?"denied":"pending"}is_capturing(){return this.config.cookieless_mode===ht||(this.config.cookieless_mode===Ht?this.consent.isRejected()||this.consent.isOptedIn():!this.has_opted_out_capturing())}clear_opt_in_out_capturing(){this.consent.reset(),this.es()}_is_bot(){return ke?sd(ke,this.config.custom_blocked_useragents):void 0}Hn(){C&&(C.visibilityState==="visible"?this.wn||(this.wn=!0,this.capture(is,{title:C.title},{send_instantly:!0}),this.kn&&(C.removeEventListener(on,this.kn),this.kn=null)):this.kn||(this.kn=this.Hn.bind(this),ne(C,on,this.kn)))}debug(e){e===!1?(v?.console.log("You've disabled debug mode."),this.set_config({debug:!1})):(v?.console.log("You're now in debug mode. All calls to PostHog will be logged in your console.\nYou can disable this with `posthog.debug(false)`."),this.set_config({debug:!0}))}Qi(){var e=this.Mn||{};return"advanced_disable_flags"in e?!!e.advanced_disable_flags:this.config.advanced_disable_flags!==!1?!!this.config.advanced_disable_flags:this.config.advanced_disable_decide===!0?(k.warn("Config field 'advanced_disable_decide' is deprecated. Please use 'advanced_disable_flags' instead. The old field will be removed in a future major version."),!0):(function(s,r,n,i,o){var a=r in s&&!D(s[r]),l=n in s&&!D(s[n]);return a?s[r]:!!l&&(o&&o.warn("Config field '"+n+"' is deprecated. Please use '"+r+"' instead. The old field will be removed in a future major version."),s[n])})(e,"advanced_disable_flags","advanced_disable_decide",0,k)}Pt(e){var s;if(D(this.config.before_send))return e;var r=Object.keys((s=e.properties)!==null&&s!==void 0?s:{}).filter(yh),n=L(this.config.before_send)?this.config.before_send:[this.config.before_send],i=e;for(var o of n){if(i=o(i),D(i)){var a="Event '"+e.event+"' was rejected in beforeSend function";return _h(e.event)?k.warn(a+". This can cause unexpected behavior."):k.info(a),null}i.properties&&!mt(i.properties)||k.warn("Event '"+e.event+"' has no properties after beforeSend function, this is likely an error.")}for(var l of r)if(i.properties&&D(i.properties[l]))return k.warn("Event '"+e.event+"' had its '"+l+"' property removed in a beforeSend function. This property is required for ingestion, so the event will be dropped."),null;return i}getPageViewId(){var e;return(e=this.pageViewManager.ui)==null?void 0:e.pageViewId}captureTraceFeedback(e,s){this.capture("$ai_feedback",{$ai_trace_id:String(e),$ai_feedback_text:s})}captureTraceMetric(e,s,r){this.capture("$ai_metric",{$ai_trace_id:String(e),$ai_metric_name:s,$ai_metric_value:String(r)})}Cn(e){var s=Ke(e)&&!e,r=Q.N()&&Q.P("ph_debug")==="true";return!s&&(!!r||e)}}Te.__defaultExtensionClasses={},Te.rs=(()=>{var t=()=>{};return{trace:t,debug:t,info:t,warn:t,error:t,fatal:t}})(),(function(t,e){for(var s=0;e.length>s;s++)t.prototype[e[s]]=ap(t.prototype[e[s]])})(Te,["identify"]);class Tl{constructor(e){this.disabled=e===!1;var s=te(e)?e:{};this.thresholdPx=s.threshold_px||30,this.timeoutMs=s.timeout_ms||1e3,this.clickCount=s.click_count||3,this.clicks=[]}isRageClick(e,s,r){if(this.disabled)return!1;var n=this.clicks[this.clicks.length-1];if(n&&Math.abs(e-n.x)+Math.abs(s-n.y)r-n.timestamp){if(this.clicks.push({x:e,y:s,timestamp:r}),this.clicks.length===this.clickCount)return!0}else this.clicks=[{x:e,y:s,timestamp:r}];return!1}}var Ei="$copy_autocapture",Si=se("[AutoCapture]");function xi(t,e){return e.length>t?e.slice(0,t)+"...":e}function hf(t){if(t.previousElementSibling)return t.previousElementSibling;var e=t;do e=e.previousSibling;while(e&&!Ft(e));return e}function pf(t,e){var s,r,n=e.e,i=e.maskAllElementAttributes,o=e.maskAllText,a=e.elementAttributeIgnoreList,l=e.elementsChainAsString,u=e.disableCaptureUrlHashes;if(!Ft(t))return{props:{}};for(var c=[t],d=new Set([t]),h=t;h.parentNode&&!Me(h,"body")&&Iu>c.length;)if(ku(h.parentNode)){var p=h.parentNode.host;if(d.has(p))break;d.add(p),c.push(p),h=p}else{if(!Ft(h.parentNode)||d.has(h.parentNode))break;d.add(h.parentNode),c.push(h.parentNode),h=h.parentNode}var f,m,g=[],_={},w=!1,b=!1;if(Z(c,(S=>{var A=ao(S);if(Me(S,"a")){var R=S.getAttribute("href");w=!!(A&&R&&Ks(R))&&(u?Ct(R):R)}M(cn(S),"ph-no-capture")&&(b=!0),g.push((function(T,O,J,z,H){H===void 0&&(H=!1);var oe=T.tagName.toLowerCase(),pe={tag_name:oe};Zo.indexOf(oe)>-1&&!J&&(pe.$el_text=oe.toLowerCase()==="a"||oe.toLowerCase()==="button"?xi(1024,fl(T)):xi(1024,rr(T)));var Ie=cn(T);Ie.length>0&&(pe.classes=Ie.filter((function(ae){return ae!==""}))),Z(T.attributes,(function(ae){var me;if((!$u(T)||["name","id","class","aria-label"].indexOf(ae.name)!==-1)&&(z==null||!z.includes(ae.name))&&!O&&Ks(ae.value)&&(!W(me=ae.name)||me.substring(0,10)!=="_ngcontent"&&me.substring(0,7)!=="_nghost")){var ge=ae.value;ae.name==="class"&&(ge=Yo(ge).join(" ")),pe["attr__"+ae.name]=xi(1024,ae.name==="href"&&H?Ct(ge):ge)}}));for(var _e=1,Ce=1,Re=T;Re=hf(Re);)_e++,Re.tagName===T.tagName&&Ce++;return pe.nth_child=_e,pe.nth_of_type=Ce,pe})(S,i,o,a,u));var N=(function(T){if(!ao(T))return{};var O={};return Z(T.attributes,(function(J){if(J.name&&J.name.indexOf("data-ph-capture-attribute")===0){var z=J.name.replace("data-ph-capture-attribute-",""),H=J.value;z&&H&&Ks(H)&&(O[z]=H)}})),O})(S);ee(_,N)})),b)return{props:{},explicitNoCapture:b};if(o||(g[0].$el_text=Me(t,"a")||Me(t,"button")?fl(t):rr(t)),w){var I,F;g[0].attr__href=w;var P=(I=un(w))==null?void 0:I.host,j=v==null||(F=v.location)==null?void 0:F.host;P&&j&&P!==j&&(f=w)}return{props:ee({$event_type:n.type,$ce_version:1},l?{}:{$elements:g},{$elements_chain:(m=g,(function(S){return S.map((A=>{var R,N,T="";if(A.tag_name&&(T+=A.tag_name),A.attr_class)for(var O of(A.attr_class.sort(),A.attr_class))T+="."+O.replace(/"/g,"");var J=E({},A.text?{text:A.text}:{},{"nth-child":(R=A.nth_child)!==null&&R!==void 0?R:0,"nth-of-type":(N=A.nth_of_type)!==null&&N!==void 0?N:0},A.href?{href:A.href}:{},A.attr_id?{attr_id:A.attr_id}:{},A.attributes),z={};return Or(J).sort(((H,oe)=>H[0].localeCompare(oe[0]))).forEach((H=>{var oe=H[1];return z[gl(H[0].toString())]=gl(oe.toString())})),(T+=":")+Or(z).map((H=>H[0]+'="'+H[1]+'"')).join("")})).join(";")})((function(S){return S.map((A=>{var R,N,T={text:(R=A.$el_text)==null?void 0:R.slice(0,400),tag_name:A.tag_name,href:(N=A.attr__href)==null?void 0:N.slice(0,2048),attr_class:Ip(A),attr_id:A.attr__id,nth_child:A.nth_child,nth_of_type:A.nth_of_type,attributes:{}};return Or(A).filter((O=>O[0].indexOf("attr__")===0)).forEach((O=>T.attributes[O[0]]=O[1])),T}))})(m)))},(s=g[0])!=null&&s.$el_text?{$el_text:(r=g[0])==null?void 0:r.$el_text}:{},f&&n.type==="click"?{$external_click_url:f}:{},_)}}var Ms=se("[ExceptionAutocapture]"),Nl=()=>{},ff=se("[TracingHeaders]"),Lt=se("[Web Vitals]"),Ml=9e5,Ll="disabled",Ol="lazy_loading",Ls="awaiting_config",Fr="missing_config";se("[SessionRecording]"),se("[SessionRecording]");var mo="[SessionRecording]",at=se(mo),gf=se("[Heatmaps]");function ki(t){return te(t)&&"clientX"in t&&"clientY"in t&&he(t.clientX)&&he(t.clientY)}var Pr=se("[Product Tours]"),Ii=t=>{var e;return!t.config.disable_product_tours&&!((e=t.persistence)==null||!e.get_property(Vo))},mf=["$set_once","$set"],Ze=se("[SiteApps]"),Dl="Error while initializing PostHog app with config id ";function rs(t,e,s){if(D(t))return!1;switch(s){case"exact":return t===e;case"contains":var r=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/_/g,".").replace(/%/g,".*");return new RegExp(r,"i").test(t);case"regex":try{return new RegExp(e).test(t)}catch{return!1}default:return!1}}class vf{constructor(e){this.ns=new ta,this.ss=(s,r)=>this.os(s,r)&&this.ls(s,r)&&this.us(s,r)&&this.hs(s,r),this.os=(s,r)=>r==null||!r.event||s?.event===r?.event,this._instance=e,this.ds=new Set,this.vs=new Set}init(){var e,s;x((e=this._instance)==null?void 0:e._addCaptureHook)||(s=this._instance)==null||s._addCaptureHook(((r,n)=>{this.on(r,n)}))}register(e){var s,r;if(!x((s=this._instance)==null?void 0:s._addCaptureHook)&&(e.forEach((o=>{var a,l;(a=this.vs)==null||a.add(o),(l=o.steps)==null||l.forEach((u=>{var c;(c=this.ds)==null||c.add(u?.event||"")}))})),(r=this._instance)!=null&&r.autocapture)){var n,i=new Set;e.forEach((o=>{var a;(a=o.steps)==null||a.forEach((l=>{l!=null&&l.selector&&i.add(l?.selector)}))})),(n=this._instance)==null||n.autocapture.setElementSelectors(i)}}on(e,s){var r;s!=null&&e.length!=0&&(this.ds.has(e)||this.ds.has(s.event))&&this.vs&&((r=this.vs)==null?void 0:r.size)>0&&this.vs.forEach((n=>{this.cs(s,n)&&this.ns.emit("actionCaptured",n.name)}))}fs(e){this.onAction("actionCaptured",(s=>e(s)))}cs(e,s){if(s?.steps==null)return!1;for(var r of s.steps)if(this.ss(e,r))return!0;return!1}onAction(e,s){return this.ns.on(e,s)}ls(e,s){if(s!=null&&s.url){var r,n=e==null||(r=e.properties)==null?void 0:r.$current_url;if(!n||typeof n!="string"||!rs(n,s.url,s.url_matching||"contains"))return!1}return!0}us(e,s){return!!this.ps(e,s)&&!!this.gs(e,s)&&!!this.ys(e,s)}ps(e,s){var r;if(s==null||!s.href)return!0;var n=this.bs(e);if(n.length>0)return n.some((a=>rs(a.href,s.href,s.href_matching||"exact")));var i,o=(e==null||(r=e.properties)==null?void 0:r.$elements_chain)||"";return!!o&&rs((i=o.match(/(?::|")href="(.*?)"/))?i[1]:"",s.href,s.href_matching||"exact")}gs(e,s){var r;if(s==null||!s.text)return!0;var n=this.bs(e);if(n.length>0)return n.some((u=>rs(u.text,s.text,s.text_matching||"exact")||rs(u.$el_text,s.text,s.text_matching||"exact")));var i,o,a,l=(e==null||(r=e.properties)==null?void 0:r.$elements_chain)||"";return!!l&&(i=(function(u){for(var c,d=[],h=/(?::|")text="(.*?)"/g;!D(c=h.exec(u));)d.includes(c[1])||d.push(c[1]);return d})(l),o=s.text,a=s.text_matching||"exact",i.some((u=>rs(u,o,a))))}ys(e,s){var r,n;if(s==null||!s.selector)return!0;var i=e==null||(r=e.properties)==null?void 0:r.$element_selectors;if(i!=null&&i.includes(s.selector))return!0;var o=(e==null||(n=e.properties)==null?void 0:n.$elements_chain)||"";if(s.selector_regex&&o)try{return new RegExp(s.selector_regex).test(o)}catch{return!1}return!1}bs(e){var s;return(e==null||(s=e.properties)==null?void 0:s.$elements)==null?[]:e?.properties.$elements}hs(e,s){return s==null||!s.properties||s.properties.length===0||id(s.properties.reduce(((r,n)=>{var i=L(n.value)?n.value.map(String):n.value!=null?[String(n.value)]:[];return r[n.key]={values:i,operator:n.operator||"exact"},r}),{}),e?.properties)}}class _f{constructor(e){var s;this._s=[],this._instance=e,this.ws=new Map,this.ks=new Map,this.xs=new Map,(s=this._instance)==null||s.onSessionId==null||s.onSessionId((r=>this.Ss(r)))}Cs(e){return!1}Ms(){return null}Ts(e){}Es(){}Is(e,s){return!!e&&id(e.propertyFilters,s?.properties)}Ps(e,s){var r=new Map;return e.forEach((n=>{var i;(i=n.conditions)==null||(i=i[s])==null||(i=i.values)==null||i.forEach((o=>{if(o!=null&&o.name){var a=r.get(o.name)||[];a.push(n.id),r.set(o.name,a)}}))})),r}Rs(e,s,r){var n=(r===As.Activation?this.ws:this.ks).get(e),i=[];return this.As((o=>{i=o.filter((a=>n?.includes(a.id)))})),i.filter((o=>{var a,l=(a=o.conditions)==null||(a=a[r])==null||(a=a.values)==null?void 0:a.find((u=>u.name===e));return this.Is(l,s)}))}register(e){var s;x((s=this._instance)==null?void 0:s._addCaptureHook)||(this.Fs(e),this.Ls(e))}Ls(e){var s=e.filter((r=>{var n,i;return((n=r.conditions)==null?void 0:n.actions)&&((i=r.conditions)==null||(i=i.actions)==null||(i=i.values)==null?void 0:i.length)>0}));s.length!==0&&(this.Os==null&&(this.Os=new vf(this._instance),this.Os.init(),this.Os.fs((r=>{this.onAction(r)}))),s.forEach((r=>{var n,i,o,a,l;r.conditions&&(n=r.conditions)!=null&&n.actions&&(i=r.conditions)!=null&&(i=i.actions)!=null&&i.values&&((o=r.conditions)==null||(o=o.actions)==null||(o=o.values)==null?void 0:o.length)>0&&((a=this.Os)==null||a.register(r.conditions.actions.values),(l=r.conditions)==null||(l=l.actions)==null||(l=l.values)==null||l.forEach((u=>{if(u&&u.name){var c=this.xs.get(u.name);c&&c.push(r.id),this.xs.set(u.name,c||[r.id])}})))})))}Fs(e){var s,r=e.filter((i=>{var o,a;return((o=i.conditions)==null?void 0:o.events)&&((a=i.conditions)==null||(a=a.events)==null||(a=a.values)==null?void 0:a.length)>0})),n=e.filter((i=>{var o,a;return((o=i.conditions)==null?void 0:o.cancelEvents)&&((a=i.conditions)==null||(a=a.cancelEvents)==null||(a=a.values)==null?void 0:a.length)>0}));r.length===0&&n.length===0||((s=this._instance)==null||s._addCaptureHook(((i,o)=>{this.onEvent(i,o)})),this.ws=this.Ps(e,As.Activation),this.ks=this.Ps(e,As.Cancellation))}onEvent(e,s){var r,n,i=this.Ds(),o=(s==null||(r=s.properties)==null?void 0:r.$survey_id)||(s==null||(n=s.properties)==null?void 0:n.$product_tour_id);if(o&&this.getActivatedIds().includes(o)){var a=this.$s(e,o);if(a==="consume")return i.info("event consumed activated item, removing it",{event:e,itemId:o}),void this.Ns([o]);if(a==="persist")return i.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,s,As.Cancellation);l.length>0&&(i.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)){i.info("event name matched",{event:e,eventPayload:s,items:this.ws.get(e)});var u=this.Rs(e,s,As.Activation);this.Hs(u.map((c=>c.id)))}}onAction(e){this.xs.has(e)&&this.Hs(this.xs.get(e)||[])}Hs(e){var s;if(e.length!==0){var r=!((s=this._instance)==null||s.get_session_id==null||!s.get_session_id()),n=[];for(var i of e)r&&this.Cs(i)?this.qs(i)&&this.Us(i):n.push(i);n.length>0&&(this._s=[...new Set([...this._s,...n])]),this.Ds().info("updating activated items",{activatedItems:this.getActivatedIds()})}}qs(e){this._s=this._s.filter((r=>r!==e));var s=this.zs();return!s.includes(e)&&(this.Ws([...s,e]),this.Vs(),!0)}Ns(e){var s=new Set(e);this._s=this._s.filter((i=>!s.has(i)));var r=this.Zs(),n=r.filter((i=>!s.has(i)));n.length!==r.length&&(this.Ws(n),n.length===0&&this.Gs()),this.js(e)}Qs(){var e,s=this.Ms();if(!s)return{};var r=(e=this._instance)==null||(e=e.persistence)==null?void 0:e.props[s];return r&&typeof r=="object"?r:{}}Us(e){if(this.Ms()){var s=this.Qs();this.Ts(E({},s,{[e]:Date.now()}))}}js(e){if(this.Ms()){var s=this.Qs(),r={},n=!1;for(var i of Object.entries(s)){var o=i[0],a=i[1];e.includes(o)?n=!0:r[o]=a}n&&(mt(r)?this.Es():this.Ts(r))}}Ks(){this.Ms()&&this.Es()}getActivationTimestamp(e){if(this.zs().includes(e)){var s=this.Qs()[e];return he(s)?s:void 0}}Zs(){var e,s=this.Js();return((e=this._instance)==null||(e=e.persistence)==null?void 0:e.props[s])||[]}zs(){var e,s,r=this.Zs();if(r.length===0)return[];var n=(e=this._instance)==null||(e=e.persistence)==null?void 0:e.props[this.Ys()],i=(s=this._instance)==null||s.get_session_id==null?void 0:s.get_session_id();return i&&n===i?r:[]}Vs(){var e,s=(e=this._instance)==null||e.get_session_id==null?void 0:e.get_session_id();s&&this.Xs(s)}Gs(){this.ta()}Ss(e){var s,r=(s=this._instance)==null||(s=s.persistence)==null?void 0:s.props[this.Ys()];if(r&&r!==e){var n=this.Zs(),i=this.Qs();n.length>0&&(this.Ws([]),n.filter((o=>he(i[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 yf extends _f{constructor(e){super(e)}Js(){return Qi}Ys(){return Nr}Ms(){return Mr}Ts(e){var s;(s=this._instance)==null||(s=s.persistence)==null||s.register({[Mr]:e})}Es(){var e;(e=this._instance)==null||(e=e.persistence)==null||e.unregister(Mr)}Cs(e){var s,r;this.As((i=>{r=i.find((o=>o.id===e))}));var n=(s=r)==null||(s=s.appearance)==null?void 0:s.surveyPopupDelaySeconds;return he(n)&&n>0}ra(){return ft.SHOWN}As(e){var s;(s=this._instance)==null||s.getSurveys(e)}Bs(e){var s;(s=this._instance)==null||s.cancelPendingSurvey(e)}Ds(){return q}Ws(e){var s;(s=this._instance)==null||(s=s.persistence)==null||s.register({[Qi]:e})}Xs(e){var s;(s=this._instance)==null||(s=s.persistence)==null||s.register({[Nr]:e})}ta(){var e;(e=this._instance)==null||(e=e.persistence)==null||e.unregister(Nr)}ea(){return!1}$s(e,s){var r;this.As((i=>{r=i.find((o=>o.id===s))}));var n=!r||(function(i){var o;return od(i)&&!((o=i.conditions)==null||(o=o.events)==null||!o.repeatedActivation)||i.schedule==="always"})(r);return n?e===ft.SHOWN?"consume":"ignore":e===ft.SHOWN?"persist":e===ft.DISMISSED||e===ft.SENT?"consume":"ignore"}getSurveys(){return this.getActivatedIds()}getEventToSurveys(){return this.getEventToItemsMap()}}var Ar="SDK is not enabled or survey functionality is not yet loaded",Bl="Disabled. Not loading surveys.",wf=v!=null&&v.location?dn(v.location.hash,"__posthog")||dn(location.hash,"state"):null,jl="_postHogToolbarParams",Ul=se("[Toolbar]"),Hl=se("[FeatureFlags]");class bf{constructor(e,s){s===void 0&&(s=!1),this.na=!1,this.update(e,s)}update(e,s){this.sa=((r,n)=>{var i,o,a,l;return{bootstrap:{featureFlags:(i=r.bootstrap)==null?void 0:i.featureFlags,featureFlagPayloads:(o=r.bootstrap)==null?void 0:o.featureFlagPayloads},remoteRequestsDisabled:n,featureFlagsDisabled:!!r.advanced_disable_feature_flags,onlyEvaluateSurveyFeatureFlags:!!r.advanced_only_evaluate_survey_feature_flags,deduplicateCallsPerSession:!!r.advanced_feature_flags_dedup_per_session,cacheTtlMs:r.feature_flag_cache_ttl_ms,requestTimeoutMs:r.feature_flag_request_timeout_ms,compression:r.disable_compression?"none":"base64",evaluationContexts:(a=(l=r.evaluation_contexts)!==null&&l!==void 0?l:r.evaluation_environments)!==null&&a!==void 0?a:[],flagKeys:L(r.flag_keys)?r.flag_keys:void 0}})(e,s),!e.evaluation_environments||e.evaluation_contexts||this.na||(Hl.warn("evaluation_environments is deprecated. Use evaluation_contexts instead. evaluation_environments will be removed in a future version."),this.na=!0),x(e.flag_keys)||L(e.flag_keys)||Hl.error("Invalid flag_keys found:",e.flag_keys,"Expected array of non-empty strings")}get(){return this.sa}}var Wl=se("[FeatureFlags]"),Ot=se("[FeatureFlags]",{debugEnabled:!0}),Ci=`" failed. Feature flags didn't load in time.`,zl="connection_error",ql=t=>{for(var e={},s=0;t.length>s;s++)e[t[s]]=!0;return e},Vl=t=>{var e={};for(var s of Or(t||{})){var r=s[1];r&&(e[s[0]]=r)}return e},Xe=se("[Error tracking]"),Gl="Refusing to render web experiment since the viewer is a likely bot",Ef={icontains:(t,e)=>e.toLowerCase().indexOf(t.toLowerCase())>-1,not_icontains:(t,e)=>e.toLowerCase().indexOf(t.toLowerCase())===-1,regex:(t,e)=>fn(e,t),not_regex:(t,e)=>!fn(e,t),exact:(t,e)=>e===t,is_not:(t,e)=>e!==t};class ye{get Ne(){return this._instance.config}constructor(e){var s=this;this.getWebExperimentsAndEvaluateDisplayLogic=function(r){r===void 0&&(r=!1),s.getWebExperiments((n=>{ye.aa("retrieved web experiments from the server"),s.oa=new Map,n.forEach((i=>{if(i.feature_flag_key){var o;s.oa&&(ye.aa("setting flag key ",i.feature_flag_key," to web experiment ",i),(o=s.oa)==null||o.set(i.feature_flag_key,i));var a=s._instance.getFeatureFlag(i.feature_flag_key);W(a)&&i.variants[a]&&s.la(i.name,a,i.variants[a].transforms)}else if(i.variants)for(var l in i.variants){var u=i.variants[l];ye.ua(u,s._instance)&&s.la(i.name,l,u.transforms)}}))}),r)},this._instance=e,this._instance.onFeatureFlags((r=>{this.onFeatureFlags(r)}))}initialize(){}onFeatureFlags(e){if(this._is_bot())ye.aa(Gl);else if(!this.Ne.disable_web_experiments){if(D(this.oa))return this.oa=new Map,this.loadIfEnabled(),void this.previewWebExperiment();ye.aa("applying feature flags",e),e.forEach((s=>{var r;if(this.oa&&(r=this.oa)!=null&&r.has(s)){var n,i=this._instance.getFeatureFlag(s),o=(n=this.oa)==null?void 0:n.get(s);i&&o!=null&&o.variants[i]&&this.la(o.name,i,o.variants[i].transforms)}}))}}previewWebExperiment(){var e=ye.getWindowLocation();if(e!=null&&e.search){var s=ms(e?.search,"__experiment_id"),r=ms(e?.search,"__experiment_variant");s&&r&&(ye.aa("previewing web experiments "+s+" && "+r),this.getWebExperiments((n=>{this.ha(parseInt(s),r,n)}),!1,!0))}}loadIfEnabled(){this.Ne.disable_web_experiments||this.getWebExperimentsAndEvaluateDisplayLogic()}getWebExperiments(e,s,r){if(this.Ne.disable_web_experiments&&!r)return e([]);var n=this._instance.get_property("$web_experiments");if(n&&!s)return e(n);this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/web_experiments/?token="+this.Ne.token),method:"GET",timestampMode:"query",callback:i=>e(i.statusCode===200&&i.json&&i.json.experiments||[])})}ha(e,s,r){var n=r.filter((i=>i.id===e));n&&n.length>0&&(ye.aa("Previewing web experiment ["+n[0].name+"] with variant ["+s+"]"),this.la(n[0].name,s,n[0].variants[s].transforms))}static ua(e,s){return!D(e.conditions)&&ye.da(e,s)&&ye.va(e)}static da(e,s){var r;if(D(e.conditions)||D((r=e.conditions)==null?void 0:r.url))return!0;var n=ye.getWindowLocation();if(n){var i,o,a,l=Eu(s,n.href);return(i=e.conditions)==null||!i.url||Ef[(o=(a=e.conditions)==null?void 0:a.urlMatchType)!==null&&o!==void 0?o:"icontains"](e.conditions.url,l)}return!1}static getWindowLocation(){return v?.location}static va(e){var s;if(D(e.conditions)||D((s=e.conditions)==null?void 0:s.utm))return!0;var r=Ou();if(r.utm_source){var n,i,o,a,l,u,c,d,h=(n=e.conditions)==null||(n=n.utm)==null||!n.utm_campaign||((i=e.conditions)==null||(i=i.utm)==null?void 0:i.utm_campaign)==r.utm_campaign,p=(o=e.conditions)==null||(o=o.utm)==null||!o.utm_source||((a=e.conditions)==null||(a=a.utm)==null?void 0:a.utm_source)==r.utm_source,f=(l=e.conditions)==null||(l=l.utm)==null||!l.utm_medium||((u=e.conditions)==null||(u=u.utm)==null?void 0:u.utm_medium)==r.utm_medium,m=(c=e.conditions)==null||(c=c.utm)==null||!c.utm_term||((d=e.conditions)==null||(d=d.utm)==null?void 0:d.utm_term)==r.utm_term;return h&&f&&m&&p}return!1}static aa(e){for(var s=arguments.length,r=new Array(s>1?s-1:0),n=1;s>n;n++)r[n-1]=arguments[n];k.info("[WebExperiments] "+e,r)}la(e,s,r){this._is_bot()?ye.aa(Gl):s!=="control"?r.forEach((n=>{if(n.selector){var i;ye.aa("applying transform of variant "+s+" for experiment "+e+" ",n);var o=(i=document)==null?void 0:i.querySelectorAll(n.selector);o?.forEach((a=>{var l=a;n.html&&(l.innerHTML=n.html),n.css&&l.setAttribute("style",n.css)}))}})):ye.aa("Control variants leave the page unmodified.")}_is_bot(){return ke&&this._instance?sd(ke,this.Ne.custom_blocked_useragents):void 0}}var Ue=se("[Conversations]"),Dt="Conversations not available yet.",Kl="console",dd="__posthogHandledLogsRequestError",Fi=(t,e)=>{var s=t instanceof Error?t:new Error(e);return s[dd]=!0,s},Jl=t=>!!t&&typeof t=="object"&&t[dd]===!0,Tn={featureFlags:class{constructor(t){this.name="featureFlags",this.ca=!1,this.featureFlagEventHandlers=[],this.rt=Wl,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 bf(t.config,t.Qi()),this.Ta=this.Ea)}updateConfig(t,e){var s;(s=this.Ea)==null||s.update(t,e)}setup(t){return this.Ia=t,this.rt=t.logger.createLogger("[FeatureFlags]"),s=()=>{this.Ia===t&&(this.Ia=void 0,this.nn=t,this.Pa(t))},(e=t.kv.initialize())!=null&&e.then?e.then(s):s();var e,s}Pa(t){if(this.nn===t)return v&&ne(v,"online",this.Ca),this.Ra=t.registerDynamicEventProperties((()=>this.Aa()?this.fa:this.pa)),this.Fa(),this.initialize()}destroy(){v?.removeEventListener("online",this.Ca)}dispose(){var t;this.ba++,this.wa=!1,this.Ia=void 0,this.nn&&(this.La(),(t=this.Ra)==null||t.dispose(),this.Ra=void 0,this.ga=[],v?.removeEventListener("online",this.Ca),this.nn=void 0)}get Ne(){return this.Ta.get()}Oa(t){var e;return(e=this.nn)==null?void 0:e.kv.get(t)}F(t){this.Da((()=>{var e;return(e=this.nn)==null?void 0:e.kv.set(t)}))}q(t){this.Da((()=>{var e;return(e=this.nn)==null?void 0:e.kv.remove(t)}))}Da(t){try{t()}catch(e){this.rt.error("Failed to update feature flag persistence",e)}}Fa(){var t={};for(var e of[Us,Hs,Tr,et]){var s=this.Oa(e);x(s)||(t[e]=s)}this.fa=t;var r=E({},t),n=this.Oa(Bt);if(n)for(var i of Object.entries(n))r["$feature/"+i[0]]=i[1];this.pa=r}Aa(){var t=this.Ne.cacheTtlMs;if(!t||0>=t)return!1;var e=this.Oa(Gs);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 s=e&&typeof e=="string"&&e.trim().length>0;return s||this.rt.error("Invalid evaluation context found:",e,"Expected non-empty string"),s})):[]}qa(){var t=this.Ne.flagKeys;if(!x(t))return t.filter((e=>{var s=e&&typeof e=="string"&&e.trim().length>0;return s||this.rt.error("Invalid flag key found:",e,"Expected non-empty string"),s}))}initialize(){var t,e,s=this.Ne,r=(t=(e=s.bootstrap)==null?void 0:e.featureFlags)!==null&&t!==void 0?t:{};if(Object.keys(r).length){var n,i,o=(n=(i=s.bootstrap)==null?void 0:i.featureFlagPayloads)!==null&&n!==void 0?n:{},a=Object.keys(r).filter((u=>!!r[u])).reduce(((u,c)=>(u[c]=r[c]||!1,u)),{}),l=Object.keys(o).filter((u=>a[u])).reduce(((u,c)=>(o[c]&&(u[c]=o[c]),u)),{});return this.ja({featureFlags:a,featureFlagPayloads:l})}}updateFlags(t,e,s){var r,n,i=s!=null&&s.merge&&(r=this.Oa(Bt))!==null&&r!==void 0?r:{},o=s!=null&&s.merge&&(n=this.Oa(Hs))!==null&&n!==void 0?n:{},a=E({},i,t),l=E({},o,e),u={};for(var c of Object.entries(a)){var d=c[0],h=c[1];u[d]={key:d,enabled:Ua(h),variant:Ha(h),reason:void 0,metadata:x(l?.[d])?void 0:{id:0,version:void 0,description:void 0,payload:l[d]}}}this.ja({flags:u})}get hasLoadedFlags(){return this.ma}getFlags(){return Object.keys(this.getFlagVariants())}getFlagsWithDetails(){var t=this.Oa(Zi),e=this.Oa(et),s=this.Oa(jt);if(!s&&!e)return t||{};var r=ee({},t||{}),n=[...new Set([...Object.keys(s||{}),...Object.keys(e||{})])];for(var i of n){var o,a,l=r[i],u=e?.[i],c=x(u)?(o=l?.enabled)!==null&&o!==void 0&&o:!!u,d=x(u)?l?.variant:typeof u=="string"?u:void 0,h=s?.[i],p=E({},l,{enabled:c,variant:c?d??l?.variant:void 0});c!==l?.enabled&&(p.original_enabled=l?.enabled),d!==l?.variant&&(p.original_variant=l?.variant),h&&(p.metadata=E({},l?.metadata,{payload:h,original_payload:l==null||(a=l.metadata)==null?void 0:a.payload})),r[i]=p}return this.ca||(this.rt.warn(" Overriding feature flag details!",{flagDetails:t,overriddenPayloads:s,finalDetails:r}),this.ca=!0),r}getAllFeatureFlags(){var t=this.getFlagVariants(),e=this.getFlagPayloads();return Object.keys(t).map((s=>{var r=t[s];return{key:s,enabled:Ua(r),variant:Ha(r),payload:ja(e[s])}}))}getFlagVariants(){var t=this.Oa(Bt),e=this.Oa(et);if(!e)return t||{};for(var s=ee({},t||{}),r=Object.keys(e),n=0;r.length>n;n++)s[r[n]]=e[r[n]];return this.ca||(this.rt.warn(" Overriding feature flags!",{enabledFlags:t,overriddenFlags:e,finalFlags:s}),this.ca=!0),s}getFlagPayloads(){var t=this.Oa(Hs),e=this.Oa(jt);if(!e)return t||{};for(var s=ee({},t||{}),r=Object.keys(e),n=0;r.length>n;n++)s[r[n]]=e[r[n]];return this.ca||(this.rt.warn(" Overriding feature flag payloads!",{flagPayloads:t,overriddenPayloads:e,finalPayloads:s}),this.ca=!0),s}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(Wt)}Ha(t){this.La();var e=this.nn;if(e&&!this.Ne.remoteRequestsDisabled&&!this.Ma())if(this.ya)this.wa=!0;else{var s={token:e.projectToken,distinct_id:e.distinctId,groups:e.groups,$anon_distinct_id:this.$anon_distinct_id,person_properties:E({},e.initialPersonProperties,this.Oa(ct)||{},{$lib:e.library.name,$lib_version:e.library.version}),group_properties:this.Oa(Ut),timezone:Wu()};x(e.deviceId)||(s.$device_id=e.deviceId),(t!=null&&t.disableFlags||this.Ne.featureFlagsDisabled)&&(s.disable_flags=!0);var r=this.Na();r.length&&(s.evaluation_contexts=r);var n=this.qa();x(n)||(s.flag_keys=n);var i=this.Ne.onlyEvaluateSurveyFeatureFlags,o="/flags/?v=2"+(i?"&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({[Lr]:[zl]}),this.rt.error("Feature flag request failed",c)),l()};try{e.sendRequest(o,{target:"flags",method:"POST",body:s,compression:this.Ne.compression==="base64"?xe.Base64:void 0,sentAt:"body",timeoutMs:this.Ne.requestTimeoutMs}).then((c=>{var d,h,p=(d=c.json)!==null&&d!==void 0?d:{},f=c.statusCode!==200;if(this.ya=!1,a===this.ba){if(this.Ua(c.statusCode),f||this.wa||(this.$anon_distinct_id=void 0),!s.disable_flags||this.wa){this.ka=!f;var m=[];c.error?m.push(c.error instanceof Error&&c.error.name==="AbortError"?"timeout":c.error instanceof Error?zl:"unknown_error"):c.statusCode!==200&&m.push("api_error_"+c.statusCode),p.errorsWhileComputingFlags&&m.push("errors_while_computing_flags");var g=!((h=p.quotaLimited)==null||!h.includes("feature_flags"));g&&m.push("quota_limited"),this.F({[Lr]:m}),g?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."):s.disable_flags||this.ja(p,f,{partialResponse:i}),l()}}else l()})).catch(u)}catch(c){u(c)}}}Ma(){return Mu(this.Sa,3)}Ua(t){this.Sa=Lu(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 s;if(e===void 0&&(e={}),!e.fresh||this.ka)if(this.ma||this.getFlags()&&this.getFlags().length>0){if(!this.$a()){var r=this.getFeatureFlagResult(t,e);return(s=r?.variant)!==null&&s!==void 0?s:r?.enabled}}else this.rt.warn('getFeatureFlag for key "'+t+Ci)}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 s,r=this.getFlagVariants(),n=t in r,i=r[t],o=this.getFlagPayloads()[t],a=String(i),l=this.Oa(Tr)||void 0,u=this.Oa(Gs)||void 0,c=this.Oa(Wt)||{};if(this.Ne.deduplicateCallsPerSession){var d,h=(d=this.nn)==null?void 0:d.session.sessionId,p=this.Oa(zs);h&&h!==p&&(c={},s=h)}if(e.send_event||!("send_event"in e))if(t in c&&c[t].includes(a))s&&this.F({[Wt]:c,[zs]:s});else{var f,m,g,_,w,b,I,F,P,j;L(c[t])?c[t].push(a):c[t]=[a],this.F(E({[Wt]:c},s?{[zs]:s}:{}));var S=this.getFeatureFlagDetails(t),A=[...(f=this.Oa(Lr))!==null&&f!==void 0?f:[]];x(i)&&A.push("flag_missing");var R={$feature_flag:t,$feature_flag_response:i,$feature_flag_payload:o||null,$feature_flag_request_id:l,$feature_flag_evaluated_at:u,$feature_flag_bootstrapped_response:((m=this.Ne.bootstrap)==null||(m=m.featureFlags)==null?void 0:m[t])||null,$feature_flag_bootstrapped_payload:((g=this.Ne.bootstrap)==null||(g=g.featureFlagPayloads)==null?void 0:g[t])||null,$used_bootstrap_value:!this.ka};x(S==null||(_=S.metadata)==null?void 0:_.has_experiment)||(R.$feature_flag_has_experiment=S.metadata.has_experiment),x(S==null||(w=S.metadata)==null?void 0:w.version)||(R.$feature_flag_version=S.metadata.version);var N,T=(b=S==null||(I=S.reason)==null?void 0:I.description)!==null&&b!==void 0?b:S==null||(F=S.reason)==null?void 0:F.code;T&&(R.$feature_flag_reason=T),S!=null&&(P=S.metadata)!=null&&P.id&&(R.$feature_flag_id=S.metadata.id),x(S?.original_variant)&&x(S?.original_enabled)||(R.$feature_flag_original_response=x(S.original_variant)?S.original_enabled:S.original_variant),S!=null&&(j=S.metadata)!=null&&j.original_payload&&(R.$feature_flag_original_payload=S==null||(N=S.metadata)==null?void 0:N.original_payload),A.length&&(R.$feature_flag_error=A.join(",")),this.za(R)}else s&&this.F({[Wt]:c,[zs]:s});if(n)return{key:t,enabled:!!i,variant:typeof i=="string"?i:void 0,payload:ja(o)}}}else this.rt.warn('getFeatureFlagResult for key "'+t+Ci)}za(t){try{var e;(e=this.nn)==null||e.capture("$feature_flag_called",t).catch((s=>{this.rt.error("Failed to capture feature flag call",s)}))}catch(s){this.rt.error("Failed to capture feature flag call",s)}}getRemoteConfigPayload(t,e){this.Wa(t,e)}Wa(t,e){var s=this;return X((function*(){var r=s.nn;if(r){var n={distinct_id:r.distinctId,token:r.projectToken,person_properties:{$lib:r.library.name,$lib_version:r.library.version}},i=s.Na();i.length&&(n.evaluation_contexts=i);var o,a=s.qa();x(a)||(n.flag_keys=a);try{var l,u=(l=(yield r.sendRequest("/flags/?v=2",{target:"flags",method:"POST",body:n,compression:s.Ne.compression==="base64"?xe.Base64:void 0,sentAt:"body",timeoutMs:s.Ne.requestTimeoutMs})).json)==null?void 0:l.featureFlagPayloads;o=u?.[t]||void 0}catch(c){return void s.rt.error("Remote config feature flag request failed",c)}try{e(o)}catch(c){s.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+Ci),e.defaultValue;var s=this.getFeatureFlag(t,e);return x(s)?e.defaultValue:!!s}addFeatureFlagsHandler(t){this.featureFlagEventHandlers.push(t)}removeFeatureFlagsHandler(t){this.featureFlagEventHandlers=this.featureFlagEventHandlers.filter((e=>e!==t))}receivedFeatureFlags(t,e,s){this.ja(t,e,s)}ja(t,e,s){if(this.nn){this.ma=!0;var r=(function(n,i,o,a,l,u){i===void 0&&(i={}),o===void 0&&(o={}),a===void 0&&(a={}),u===void 0&&(u=Wl);var c=((P,j)=>{var S=P.flags;return S?E({},P,{featureFlags:Object.fromEntries(Object.keys(S).map((A=>{var R;return[A,(R=S[A].variant)!==null&&R!==void 0?R:S[A].enabled]}))),featureFlagPayloads:Object.fromEntries(Object.keys(S).filter((A=>S[A].enabled)).filter((A=>{var R;return(R=S[A].metadata)==null?void 0:R.payload})).map((A=>{var R;return[A,(R=S[A].metadata)==null?void 0:R.payload]})))}):(P.featureFlags&&j.warn("Using an older version of the feature flags endpoint. Please upgrade your PostHog server to the latest version"),P)})(n,u),d=c.flags,h=c.featureFlags,p=c.featureFlagPayloads;if(h){var f=n.requestId,m=n.evaluatedAt;if(L(h)){u.warn("v1 of the feature flags endpoint is deprecated. Please use the latest version.");var g={};if(h)for(var _=0;h.length>_;_++)g[h[_]]=!0;return{[Us]:h,[Bt]:g,[tn]:!1}}var w=h,b=p,I=d;if(l!=null&&l.partialResponse)w=E({},i,w),b=E({},o,b),I=E({},a,I);else if(n.errorsWhileComputingFlags)if(d){var F=new Set(Object.keys(d).filter((P=>{var j;return!((j=d[P])!=null&&j.failed)})));w=E({},i,Object.fromEntries(Object.entries(w).filter((P=>F.has(P[0]))))),b=E({},o,Object.fromEntries(Object.entries(b||{}).filter((P=>F.has(P[0]))))),I=E({},a,Object.fromEntries(Object.entries(I||{}).filter((P=>F.has(P[0])))))}else w=E({},i,w),b=E({},o,b),I=E({},a,I);return E({[Us]:Object.keys(Vl(w)),[Bt]:w||{},[Hs]:b||{},[Zi]:I||{},[tn]:n.minimalFlagCalledEvents===!0},f?{[Tr]:f}:{},m?{[Gs]:m}:{})}})(t,this.getFlagVariants(),this.getFlagPayloads(),this.getFlagsWithDetails(),s,this.rt);r&&this.F(r),e||(this.xa=!1),this.Va(e)}}override(t,e){e===void 0&&(e=!1),this.rt.warn("override is deprecated. Please use overrideFeatureFlags instead."),this.overrideFeatureFlags({flags:t,suppressWarning:e})}overrideFeatureFlags(t){this.Za(t)}Za(t){if(this.nn){if(t===!1)return this.q([et,jt]),this.Va(),void Ot.info("All overrides cleared");if(L(t))return this.F({[et]:ql(t)}),this.Va(),void Ot.info("Flag overrides set",{flags:t});if(t&&typeof t=="object"&&("flags"in t||"payloads"in t)){var e,s=t;this.ca=!!((e=s.suppressWarning)!==null&&e!==void 0&&e);var r={},n=s.flags,i=s.payloads;return n&&(r[et]=L(n)?ql(n):n),i&&(r[jt]=i),Object.keys(r).length&&this.F(r),n===!1&&i===!1?this.q([et,jt]):n===!1?this.q(et):i===!1&&this.q(jt),this.Va(),n===!1?Ot.info("Flag overrides cleared"):n&&Ot.info("Flag overrides set",{flags:n}),void(i===!1?Ot.info("Payload overrides cleared"):i&&Ot.info("Payload overrides set",{payloads:i}))}if(t&&typeof t=="object")return this.F({[et]:t}),this.Va(),void Ot.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(),s=e.flags,r=e.flagVariants;try{t(s,r)}catch(n){this.rt.error("Error while running feature flags callback",n)}}return()=>this.removeFeatureFlagsHandler(t)}updateEarlyAccessFeatureEnrollment(t,e,s){var r=(this.Oa(Rr)||[]).find((l=>l.flagKey===t)),n={["$feature_enrollment/"+t]:e},i={$feature_flag:t,$feature_enrollment:e,$set:n};r&&(i.$early_access_feature_name=r.name),s&&(i.$feature_enrollment_stage=s);var o=E({},this.getFlagVariants(),{[t]:e});this.F({[Us]:Object.keys(Vl(o)),[Bt]:o,[ct]:E({},this.Oa(ct)||{},n)}),this.Va();try{var a;(a=this.nn)==null||a.capture("$feature_enrollment_update",i).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,s){e===void 0&&(e=!1);var r=this.Oa(Rr);!r||e?this.Qa(t,s):t(r)}Qa(t,e){var s=this;return X((function*(){var r=s.nn;if(r){var n,i=e?"&"+e.map((a=>"stage="+a)).join("&"):"";try{var o=yield r.sendRequest("/api/early_access_features/?token="+r.projectToken+i,{target:"api",method:"GET",sentAt:"query"});if(!o.json)return;s.F({[Rr]:n=o.json.earlyAccessFeatures})}catch(a){return void s.rt.error("Early access feature request failed",a)}try{t(n)}catch(a){s.rt.error("Early access feature callback failed",a)}}}))()}Ga(){var t=this.getFlags(),e=this.getFlagVariants();return{flags:t.filter((s=>e[s])),flagVariants:Object.keys(e).filter((s=>e[s])).reduce(((s,r)=>(s[r]=e[r],s)),{})}}Va(t){this.Fa();var e=this.Ga(),s=e.flags,r=e.flagVariants;this.featureFlagEventHandlers.forEach((n=>{try{n(s,r,{errorsLoading:t})}catch(i){this.rt.error("Error while running feature flags callback",i)}}))}setPersonPropertiesForFlags(t,e){e===void 0&&(e=!0),this.Ka(t,e)}Ka(t,e){e===void 0&&(e=!0);var s=this.Oa(ct)||{},r=t?.$set||(t!=null&&t.$set_once?{}:t),n=t?.$set_once,i={};if(n)for(var o in n)({}).hasOwnProperty.call(n,o)&&(o in s||(i[o]=n[o]));this.F({[ct]:E({},s,i,r)}),e&&this.reloadFeatureFlags()}unsetPersonPropertiesForFlags(t,e){e===void 0&&(e=!0);var s=E({},this.Oa(ct)||{});t.forEach((r=>{delete s[r]})),this.F({[ct]:s}),e&&this.reloadFeatureFlags()}resetPersonPropertiesForFlags(t){t===void 0&&(t=!0),this.q(ct),t&&this.reloadFeatureFlags()}setGroupPropertiesForFlags(t,e){e===void 0&&(e=!0);var s=this.Oa(Ut)||{},r=E({},s);for(var n of Object.keys(t))r[n]=E({},s[n],t[n]);this.F({[Ut]:r}),e&&this.reloadFeatureFlags()}resetGroupPropertiesForFlags(t){if(t){var e=this.Oa(Ut)||{};this.F({[Ut]:E({},e,{[t]:{}})})}else this.q(Ut)}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}}},Sf={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===Ls||this.Ya===Fr?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=Ll,this.Xa=void 0,this.eo=!1,this.io=(()=>{var e;if(C==null||!C.visibilityState||C.visibilityState==="visible")return!0;var s=v==null||(e=v.performance)==null||e.getEntriesByType==null?void 0:e.getEntriesByType("visibility-state");return!(s!=null&&s.length)||s.some((r=>r.name==="visible"))})(),this.Ie=()=>{var e;C?.visibilityState==="visible"&&(this.io=!0,(e=this.Ja)==null||e.setDocumentWasEverVisible==null||e.setDocumentWasEverVisible(!0))},this._instance=t,!this._instance.sessionManager)throw at.error("started without valid sessionManager"),new Error(mo+" started without valid sessionManager. This is a bug.");if(this.Ne.cookieless_mode===ht)throw new Error(mo+' cannot be used with cookieless_mode="always"');C!=null&&C.addEventListener&&ne(C,"visibilitychange",this.Ie)}initialize(){this.startIfEnabledOrStop()}dispose(){this.eo=!0,C==null||C.removeEventListener==null||C.removeEventListener("visibilitychange",this.Ie),this.stopRecording()}get ro(){var t,e=!((t=this._instance.get_property(qt))==null||!t.enabled),s=!this.Ne.disable_session_recording,r=this.Ne.disable_session_recording||this._instance.consent.isOptedOut();return v&&e&&s&&!r}startIfEnabledOrStop(t){var e;if(!(this.eo||this.ro&&(e=this.Ja)!=null&&e.isStarted)){var s=!x(Object.assign)&&!x(Array.from);this.ro&&s?(this.no(t),at.info("starting")):(this.Ya=Ll,this.stopRecording())}}no(t){var e,s,r;this.ro&&(this.Ya!==Ls&&this.Ya!==Fr&&(this.Ya=Ol),$!=null&&(e=$.__PosthogExtensions__)!=null&&(e=e.rrweb)!=null&&e.record&&(s=$.__PosthogExtensions__)!=null&&s.initSessionRecording?this.so(t):(r=$.__PosthogExtensions__)==null||r.loadExternalDependency==null||r.loadExternalDependency(this._instance,this.ao,(n=>{if(n)return at.error("could not load recorder",n);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(Go),(e=this.Mr)==null||e.unregister(du)}uo(t,e){if(D(t))return null;var s,r=he(t)?t:parseFloat(t);return typeof(s=r)!="number"||!Number.isFinite(s)||0>s||s>1?(at.warn(e+" must be between 0 and 1. Ignoring invalid value:",t),null):r}ho(t){if(this.Mr){var e,s,r=this.Mr,n=()=>{var i,o=t.sessionRecording===!1?void 0:t.sessionRecording,a=this.uo((i=this.Ne.session_recording)==null?void 0:i.sampleRate,"session_recording.sampleRate"),l=this.uo(o?.sampleRate,"remote config sampleRate"),u=a??l;D(u)&&this.lo();var c=o?.minimumDurationMilliseconds;r.register({[qt]:E({cache_timestamp:Date.now(),enabled:!!o},o,{networkPayloadCapture:E({capturePerformance:t.capturePerformance},o?.networkPayloadCapture),canvasRecording:{enabled:o?.recordCanvas,fps:o?.canvasFps,quality:o?.canvasQuality},sampleRate:u,minimumDurationMilliseconds:x(c)?null:c,endpoint:o?.endpoint,triggerMatchType:o?.triggerMatchType,masking:o?.masking,urlTriggers:o?.urlTriggers,version:o?.version,triggerGroups:o?.triggerGroups})})};n(),(e=this.Xa)==null||e.call(this),this.Xa=(s=this._instance.sessionManager)==null?void 0:s.onSessionId(n)}}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===Ls&&(this.Ya=Fr,at.warn("config refresh failed, recording will not start until page reload")),void this.startIfEnabledOrStop())}log(t,e){var s;e===void 0&&(e="log"),(s=this.Ja)!=null&&s.log?this.Ja.log(t,e):at.warn("log called before recorder was ready")}get ao(){var t,e,s=(t=this._instance)==null||(t=t.persistence)==null?void 0:t.get_property(qt);return(s==null||(e=s.scriptConfig)==null?void 0:e.script)||"lazy-recorder"}do(){var t,e=this._instance.get_property(qt);if(!e)return!1;try{t=typeof e=="object"?e:JSON.parse(e)}catch(s){return at.warn("persisted remote config for session recording is invalid and will be ignored",s),!1}return!D(t.cache_timestamp)&&36e5>=Date.now()-t.cache_timestamp}so(t){var e,s,r;if(!this.eo){if((e=$.__PosthogExtensions__)==null||!e.initSessionRecording)return at.warn("Called on script loaded before session recording is available. This can be caused by adblockers."),void this._instance.register_for_session({[yu]:!0});var n;if(this.Ja||(this.Ja=(n=$.__PosthogExtensions__)==null?void 0:n.initSessionRecording(this._instance,this.io),this.Ja._forceAllowLocalhostNetworkCapture=this._forceAllowLocalhostNetworkCapture),!this.do())return this.Ya===Fr||this.Ya===Ls?void 0:(this.Ya=Ls,at.info("persisted remote config is stale, requesting fresh config before starting"),void new zu(this._instance).load());this.Ya=Ol,(s=(r=this.Ja).setDocumentWasEverVisible)==null||s.call(r,this.io),this.Ja.start(t)}}onRRwebEmit(t){var e;(e=this.Ja)==null||e.onRRwebEmit==null||e.onRRwebEmit(t)}overrideLinkedFlag(){var t,e;this.Ja||(e=this.Mr)==null||e.register({[pu]:!0}),(t=this.Ja)==null||t.overrideLinkedFlag()}overrideSampling(){var t,e;this.Ja||(e=this.Mr)==null||e.register({[hu]:!0}),(t=this.Ja)==null||t.overrideSampling()}overrideTrigger(t){var e,s;this.Ja||(s=this.Mr)==null||s.register({[t==="url"?fu:gu]:!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 s;return!((s=this.Ja)==null||!s.tryAddCustomEvent(t,e))}}},xf={autocapture:class{constructor(t){this.vo=!1,this.co=null,this.fo=!1,this.po=!1,this.instance=t,this.rageclicks=new Tl(t.config.rageclick),this.mo=null}initialize(){this.startIfEnabled()}get Ne(){var t,e,s=te(this.instance.config.autocapture)?this.instance.config.autocapture:{};return s.url_allowlist=(t=s.url_allowlist)==null?void 0:t.map((r=>new RegExp(r))),s.url_ignorelist=(e=s.url_ignorelist)==null?void 0:e.map((r=>new RegExp(r))),s}yo(){if(this.isBrowserSupported()){if(v&&C){var t=s=>{s=s||v?.event;try{this.bo(s)}catch(r){Si.error("Failed to capture event",r)}};if(ne(C,"submit",t,{capture:!0}),ne(C,"change",t,{capture:!0}),ne(C,"click",t,{capture:!0}),this.Ne.capture_copied_text){var e=s=>{s=s||v?.event;try{this.bo(s,Ei)}catch(r){Si.error("Failed to capture copy/cut event",r)}};ne(C,"copy",e,{capture:!0}),ne(C,"cut",e,{capture:!0})}}}else Si.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 s=e.autocapture_opt_out;Ke(s)&&(this.instance.persistence&&this.instance.persistence.register({[zi]:s}),this.co=s),this.startIfEnabled()}else this.startIfEnabled()}setElementSelectors(t){this.mo=t}getElementSelectors(t){var e,s=[];return(e=this.mo)==null||e.forEach((r=>{var n=C?.querySelectorAll(r);n?.forEach((i=>{t===i&&s.push(r)}))})),s}get isEnabled(){var t,e,s=(t=this.instance.persistence)==null?void 0:t.props[zi],r=this.co,n=this.instance.Qi()&&!this.fo;if($e(r)&&!Ke(s)&&!n)return!1;var i=(e=this.co)!==null&&e!==void 0?e:!!s;return!!this.instance.config.autocapture&&!i}bo(t,e){if(e===void 0&&(e="$autocapture"),this.isEnabled){var s,r=ui(t);xu(r)&&(r=r.parentNode||null),e==="$autocapture"&&t.type==="click"&&t instanceof MouseEvent&&this.instance.config.rageclick&&(s=this.rageclicks)!=null&&s.isRageClick(t.clientX,t.clientY,t.timeStamp||new Date().getTime())&&cl(r,this.instance.config.rageclick)&&this.bo(t,"$rageclick");var n=e===Ei;if(r&&(function(d,h,p,f,m,g){var _;if(!v||Xo(d)||p!=null&&p.url_allowlist&&!ol(p.url_allowlist,g)||p!=null&&p.url_ignorelist&&ol(p.url_ignorelist,g))return!1;if(p!=null&&p.dom_event_allowlist){var w=p.dom_event_allowlist;if(w&&!w.some((S=>h.type===S)))return!1}var b=Au(d,f),I=b.parentIsUsefulElement,F=b.targetElementList;if(!(function(S,A){var R=A?.element_allowlist;if(x(R))return!0;var N,T=function(J){if(R.some((z=>J.tagName.toLowerCase()===z)))return{v:!0}};for(var O of S)if(N=T(O))return N.v;return!1})(F,p)||!oo(F,p?.css_selector_allowlist)||oo(F,(_=p?.css_selector_ignorelist)!==null&&_!==void 0?_:wp))return!1;try{var P=v.getComputedStyle(d);if(P&&P.getPropertyValue("cursor")==="pointer"&&h.type==="click")return!0}catch{}var j=d.tagName.toLowerCase();switch(j){case"html":return!1;case"form":return(m||["submit"]).indexOf(h.type)>=0;case"input":case"select":case"textarea":return(m||["change","click"]).indexOf(h.type)>=0;default:return I?(m||["click"]).indexOf(h.type)>=0:(m||["click"]).indexOf(h.type)>=0&&(Zo.indexOf(j)>-1||d.getAttribute("contenteditable")==="true")}})(r,t,this.Ne,n,n?["copy","cut"]:void 0,this.instance)){var i=pf(r,{e:t,maskAllElementAttributes:this.instance.config.mask_all_element_attributes,maskAllText:this.instance.config.mask_all_text,elementAttributeIgnoreList:this.Ne.element_attribute_ignorelist,elementsChainAsString:this.po,disableCaptureUrlHashes:this.instance.config.disable_capture_url_hashes}),o=i.props;if(i.explicitNoCapture)return!1;var a=this.getElementSelectors(r);if(a&&a.length>0&&(o.$element_selectors=a),e===Ei){var l,u=Cu(v==null||(l=v.getSelection())==null?void 0:l.toString()),c=t.type||"clipboard";if(!u)return!1;o.$selected_content=u,o.$copy_type=c}return this.instance.capture(e,o),!0}}}isBrowserSupported(){return Se(C?.querySelectorAll)}},historyAutocapture:class{constructor(t){var e;this._instance=t,this._o=(v==null||(e=v.location)==null?void 0:e.pathname)||""}initialize(){this.startIfEnabled()}get isEnabled(){return this._instance.config.capture_pageview==="history_change"}startIfEnabled(){this.isEnabled&&(k.info("History API monitoring enabled, starting..."),this.monitorHistoryChanges())}stop(){this.wo&&this.wo(),this.wo=void 0,k.info("History API monitoring stopped")}monitorHistoryChanges(){v&&v.history&&(this.ko("pushState"),this.ko("replaceState"),this.xo())}ko(t){var e;if(v&&((e=v.history[t])==null||!e.__posthog_wrapped__)){var s=this;(function(r,n,i){try{if(!(n in r))return Nl;var o={next:r[n]},a=i((function(){for(var l=arguments.length,u=new Array(l),c=0;l>c;c++)u[c]=arguments[c];return o.next.apply(this,u)}));return Se(a)&&(a.prototype=a.prototype||{},Object.defineProperties(a,{__posthog_wrapped__:{enumerable:!1,value:!0},__posthog_layer__:{enumerable:!1,value:o}})),r[n]=a,()=>{if(r[n]!==a)for(var l=r[n];Se(l)&&l.__posthog_layer__;){var u=l.__posthog_layer__;if(u.next===a)return void(u.next=o.next);l=u.next}else r[n]=o.next}}catch{return Nl}})(v.history,t,(r=>function(n,i,o){r.call(this,n,i,o),s.So(t)}))}}So(t){try{var e,s=v==null||(e=v.location)==null?void 0:e.pathname;if(!s)return;s!==this._o&&this.isEnabled&&this._instance.capture(is,{navigation_type:t}),this._o=s}catch(r){k.error("Error capturing "+t+" pageview",r)}}xo(){if(!this.wo){var t=()=>{this.So("popstate")};ne(v,"popstate",t),this.wo=()=>{v&&v.removeEventListener("popstate",t)}}}},heatmaps:class{get Ne(){return this.instance.config}constructor(t){var e;this.Co=!1,this.vo=!1,this.Mo=null,this.instance=t,this.Co=!((e=this.instance.persistence)==null||!e.props[qi]),this.rageclicks=new Tl(t.config.rageclick)}initialize(){this.startIfEnabled()}get flushIntervalMilliseconds(){var t=5e3;return te(this.Ne.capture_heatmaps)&&this.Ne.capture_heatmaps.flush_interval_milliseconds&&(t=this.Ne.capture_heatmaps.flush_interval_milliseconds),t}get isEnabled(){return D(this.Ne.capture_heatmaps)?D(this.Ne.enable_heatmaps)?this.Co:this.Ne.enable_heatmaps:this.Ne.capture_heatmaps!==!1}startIfEnabled(){if(this.isEnabled){if(this.vo)return;gf.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 s=!!e.heatmaps;this.instance.persistence&&this.instance.persistence.register({[qi]:s}),this.Co=s,this.startIfEnabled()}}}getAndClearBuffer(){var t=this.R;return this.R=void 0,t}Io(t){ki(t.originalEvent)&&this.ke(t.originalEvent,"deadclick")}Ie(){this.Mo&&clearInterval(this.Mo),this.Mo=C?.visibilityState==="visible"?setInterval(this.cr.bind(this),this.flushIntervalMilliseconds):null}To(){v&&C&&(this.Po=this.cr.bind(this),ne(v,an,this.Po),this.Ro=t=>this.ke(t||v?.event),ne(C,"click",this.Ro,{capture:!0}),this.Ao=t=>this.Fo(t||v?.event),ne(C,"mousemove",this.Ao,{capture:!0}),this.Lo=new ml(this.instance,Cp,this.Io.bind(this)),this.Lo.startIfEnabledOrStop(),this.Oo=this.Ie.bind(this),ne(C,on,this.Oo),this.vo=!0)}Eo(){var t;v&&C&&(this.Po&&v.removeEventListener(an,this.Po),this.Ro&&C.removeEventListener("click",this.Ro,{capture:!0}),this.Ao&&C.removeEventListener("mousemove",this.Ao,{capture:!0}),this.Oo&&C.removeEventListener(on,this.Oo),clearTimeout(this.Do),(t=this.Lo)==null||t.stop(),this.vo=!1)}$o(t,e){var s=this.instance.scrollManager.scrollY(),r=this.instance.scrollManager.scrollX(),n=this.instance.scrollManager.scrollElement(),i=(function(o,a,l){for(var u=o;u&&Ft(u)&&!Me(u,"body");){if(u===l)return!1;var c=void 0;try{var d,h,p;c=(d=(h=(p=u.ownerDocument)==null?void 0:p.defaultView)!==null&&h!==void 0?h:v)==null?void 0:d.getComputedStyle(u).position}catch{return!1}if(M(a,c))return!0;u=Fu(u)}return!1})(ui(t),["fixed","sticky"],n);return{x:t.clientX+(i?0:r),y:t.clientY+(i?0:s),target_fixed:i,type:e}}ke(t,e){var s;if(e===void 0&&(e="click"),!il(t.target)&&ki(t)){var r=this.$o(t,e);(s=this.rageclicks)!=null&&s.isRageClick(t.clientX,t.clientY,new Date().getTime())&&cl(ui(t),this.instance.config.rageclick)&&this.Vt(E({},r,{type:"rageclick"})),this.Vt(r)}}Fo(t){!il(t.target)&&ki(t)&&(clearTimeout(this.Do),this.Do=setTimeout((()=>{this.Vt(this.$o(t,"mousemove"))}),500))}Vt(t){if(v){var e=this.Ne.disable_capture_url_hashes?Ct(v.location.href):v.location.href,s=this.Ne.custom_personal_data_properties,r=this.Ne.mask_personal_data_properties?[...vs,...s||[]]:[],n=nr(e,r,ir);this.R=this.R||{},this.R[n]||(this.R[n]=[]),this.R[n].push(t)}}cr(){this.R&&!mt(this.R)&&this.instance.capture("$$heatmap",{$heatmap_data:this.getAndClearBuffer()})}},deadClicksAutocapture:ml,webVitalsAutocapture:class{constructor(t){var e;this.Co=!1,this.vo=!1,this.R={navigationKey:void 0,url:void 0,metrics:[],firstMetricTimestamp:void 0},this.No=()=>{clearTimeout(this.qo),this.qo=void 0,this.R.metrics.length!==0&&(this._instance.capture("$web_vitals",E({$current_url:this.R.url},this.R.metrics.reduce(((s,r)=>E({},s,{["$web_vitals_"+r.name+"_event"]:E({},r),["$web_vitals_"+r.name+"_value"]:r.value})),{}))),this.R={navigationKey:void 0,url:void 0,metrics:[],firstMetricTimestamp:void 0})},this.jo=s=>{var r;if(this.R=this.R||{navigationKey:void 0,url:void 0,metrics:[],firstMetricTimestamp:void 0},D(s?.name)||D(s?.value))Lt.error("Invalid metric received",s);else{var n=typeof s.navigationURL=="string"?s.navigationURL:void 0,i=this.Bo(n);if(!x(i)){var o=he(s.navigationId)||typeof s.navigationId=="string"?"navigation:"+s.navigationId:"url:"+i;if(!this.Ho||this.Ho>s.value){this.R.navigationKey!==o&&(this.No(),this.qo=setTimeout(this.No,this.flushToCaptureTimeoutMs)),x(this.R.navigationKey)&&(this.R.navigationKey=o,this.R.url=i),this.R.firstMetricTimestamp=x(this.R.firstMetricTimestamp)?Date.now():this.R.firstMetricTimestamp,s.attribution&&s.attribution.interactionTargetElement&&(s.attribution.interactionTargetElement=void 0);var a=(r=this._instance.sessionManager)==null?void 0:r.checkAndGetSessionAndWindowId(!0),l=E({},s,n?{navigationURL:i}:{},{$current_url:i,timestamp:Date.now()});x(a)||(l.$session_id=a.sessionId,l.$window_id=a.windowId),this.R.metrics.push(l),this.R.metrics.length===this.allowedMetrics.length&&this.No()}else Lt.error("Ignoring metric with value >= "+this.Ho,s)}}},this.Uo=()=>{if(!this.vo){var s,r,n,i,o=$.__PosthogExtensions__,a=o?.postHogWebVitalsCallbacksByFlavor,l=a?.[this.zo]||(this.zo==="web-vitals"&&x(a)?o?.postHogWebVitalsCallbacks:void 0);if(x(l)||(s=l.onLCP,r=l.onCLS,n=l.onFCP,i=l.onINP),s&&r&&n&&i){var u={reportSoftNavs:this.useSoftNavs};this.allowedMetrics.indexOf("LCP")>-1&&s(this.jo.bind(this),u),this.allowedMetrics.indexOf("CLS")>-1&&r(this.jo.bind(this),u),this.allowedMetrics.indexOf("FCP")>-1&&n(this.jo.bind(this),u),this.allowedMetrics.indexOf("INP")>-1&&i(this.jo.bind(this),u),this.vo=!0}else Lt.error("web vitals callbacks not loaded - not starting")}},this._instance=t,this.Co=!((e=this._instance.persistence)==null||!e.props[Ji]),this.startIfEnabled()}get Wo(){return this._instance.config.capture_performance}get allowedMetrics(){var t,e,s=te(this.Wo)?(t=this.Wo)==null?void 0:t.web_vitals_allowed_metrics:void 0;return D(s)?((e=this._instance.persistence)==null?void 0:e.props[Yi])||["CLS","FCP","INP","LCP"]:s}get flushToCaptureTimeoutMs(){return(te(this.Wo)?this.Wo.web_vitals_delayed_flush_ms:void 0)||5e3}get useAttribution(){var t=te(this.Wo)?this.Wo.web_vitals_attribution:void 0;return t!=null&&t}get useSoftNavs(){var t=te(this.Wo)?this.Wo.__preview_web_vitals_soft_navs:void 0;return t!=null&&t}get Ho(){var t=te(this.Wo)&&he(this.Wo.__web_vitals_max_value)?this.Wo.__web_vitals_max_value:Ml;return t>0&&6e4>=t?Ml:t}get isEnabled(){var t=re?.protocol;if(t!=="http:"&&t!=="https:")return Lt.info("Web Vitals are disabled on non-http/https protocols"),!1;var e=te(this.Wo)?this.Wo.web_vitals:Ke(this.Wo)?this.Wo:void 0;return Ke(e)?e:this.Co}startIfEnabled(){this.isEnabled&&!this.vo&&(Lt.info("enabled, starting..."),this.ai(this.Uo))}onRemoteConfig(t){if(t.ok){var e=t.config;if("capturePerformance"in e){var s=te(e.capturePerformance)&&!!e.capturePerformance.web_vitals,r=te(e.capturePerformance)?e.capturePerformance.web_vitals_allowed_metrics:void 0;this._instance.persistence&&(this._instance.persistence.register({[Ji]:s}),this._instance.persistence.register({[Yi]:r})),this.Co=s,this.startIfEnabled()}}}get zo(){return this.useSoftNavs?this.useAttribution?"web-vitals-with-attribution-soft-navs":"web-vitals-soft-navs":this.useAttribution?"web-vitals-with-attribution":"web-vitals"}ai(t){var e=$.__PosthogExtensions__,s=this.zo,r=e?.postHogWebVitalsCallbacksByFlavor;r!=null&&r[s]||s==="web-vitals"&&x(r)&&e!=null&&e.postHogWebVitalsCallbacks?t():e==null||e.loadExternalDependency==null||e.loadExternalDependency(this._instance,s,(n=>{n?Lt.error("failed to load script",n):t()}))}Bo(t){var e=t||v?.location.href;if(e){var s=this._instance.config.disable_capture_url_hashes?Ct(e):e,r=this._instance.config.custom_personal_data_properties,n=this._instance.config.mask_personal_data_properties?[...vs,...r||[]]:[];return nr(s,n,ir)}Lt.error("Could not determine current URL")}}},kf={exceptionObserver:class{constructor(t){var e;this.Uo=()=>{var s;if(v&&this.isEnabled&&(s=$.__PosthogExtensions__)!=null&&s.errorWrappingFunctions){var r=$.__PosthogExtensions__.errorWrappingFunctions.wrapOnError,n=$.__PosthogExtensions__.errorWrappingFunctions.wrapUnhandledRejection,i=$.__PosthogExtensions__.errorWrappingFunctions.wrapConsoleError;try{!this.Vo&&this.Ne.capture_unhandled_errors&&(this.Vo=r(this.captureException.bind(this))),!this.Zo&&this.Ne.capture_unhandled_rejections&&(this.Zo=n(this.captureException.bind(this))),!this.Go&&this.Ne.capture_console_errors&&(this.Go=i(this.captureException.bind(this)))}catch(o){Ms.error("failed to start",o),this.Qo()}}},this._instance=t,this.Ko=!((e=this._instance.persistence)==null||!e.props[Vi]),this.Jo=new Eh(E({},(function(s){var r,n,i,o;return s===void 0&&(s={}),{refillRate:(r=(n=s.exceptionRateLimiterRefillRate)!==null&&n!==void 0?n:s.__exceptionRateLimiterRefillRate)!==null&&r!==void 0?r:1,bucketSize:(i=(o=s.exceptionRateLimiterBucketSize)!==null&&o!==void 0?o:s.__exceptionRateLimiterBucketSize)!==null&&i!==void 0?i:10}})(this._instance.config.error_tracking),{refillInterval:1e4,rt:Ms})),this.Ne=this.Yo(),this.startIfEnabledOrStop()}Yo(){var t=this._instance.config.capture_exceptions,e={capture_unhandled_errors:!1,capture_unhandled_rejections:!1,capture_console_errors:!1};return te(t)?e=E({},e,t):(x(t)?this.Ko:t)&&(e=E({},e,{capture_unhandled_errors:!0,capture_unhandled_rejections:!0})),e}get isEnabled(){return this.Ne.capture_console_errors||this.Ne.capture_unhandled_errors||this.Ne.capture_unhandled_rejections}startIfEnabledOrStop(){this.isEnabled?(Ms.info("enabled"),this.Qo(),this.ai(this.Uo)):this.Qo()}ai(t){var e,s;(e=$.__PosthogExtensions__)!=null&&e.errorWrappingFunctions?t():(s=$.__PosthogExtensions__)==null||s.loadExternalDependency==null||s.loadExternalDependency(this._instance,"exception-autocapture",(r=>{if(r)return Ms.error("failed to load script",r);t()}))}Qo(){var t,e,s;(t=this.Vo)==null||t.call(this),this.Vo=void 0,(e=this.Zo)==null||e.call(this),this.Zo=void 0,(s=this.Go)==null||s.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({[Vi]:this.Ko}),this.Ne=this.Yo(),this.startIfEnabledOrStop())}}onConfigChange(){this.Ne=this.Yo()}captureException(t){var e,s,r,n=(e=t==null||(s=t.$exception_list)==null||(s=s[0])==null?void 0:s.type)!==null&&e!==void 0?e:"Exception";this.Jo.consumeRateLimit(n)?Ms.info("Skipping exception capture because of client rate limiting.",{exception:n}):(r=this._instance.exceptions)==null||r.sendExceptionEvent(t)}},exceptions:class{constructor(t){var e,s;this.Xo=[],this.tl=new Bh([new Gh,new sp,new Jh,new Kh,new ep,new Qh,new Zh,new tp],(function(r){for(var n=arguments.length,i=new Array(n>1?n-1:0),o=1;n>o;o++)i[o-1]=arguments[o];return function(a,l){l===void 0&&(l=0);for(var u=[],c=a.split(` +`),d=l;c.length>d;d++){var h=c[d];if(1024>=h.length){var p=tl.test(h)?h.replace(tl,"$1"):h;if(!p.match(/\S*Error: /)){for(var f of i){var m=f(p,r);if(m){u.push(m);break}}if(u.length>=50)break}}}return(function(g){if(!g.length)return[];var _=Array.from(g);return _.reverse(),_.slice(0,50).map((w=>{return E({},w,{filename:w.filename||(b=_,b[b.length-1]||{}).filename,function:w.function||gs});var b}))})(u)}})("web:javascript",Wh,Vh)),this._instance=t,this.Xo=(e=(s=this._instance.persistence)==null?void 0:s.get_property(Gi))!==null&&e!==void 0?e:[],this.el=en(this.il()),this.rl=new np(this.el)}onConfigChange(){this.el=en(this.il()),this.rl.setConfig(this.el)}onRemoteConfig(t){var e,s,r;if(t.ok){var n=t.config;if("errorTracking"in n){var i=(e=(s=n.errorTracking)==null?void 0:s.suppressionRules)!==null&&e!==void 0?e:[],o=(r=n.errorTracking)==null?void 0:r.captureExtensionExceptions;this.Xo=i,this._instance.persistence&&this._instance.persistence.register({[Gi]:this.Xo,[Ki]:o})}}}get nl(){var t,e=!!this._instance.get_property(Ki),s=this._instance.config.error_tracking.captureExtensionExceptions;return(t=s??e)!==null&&t!==void 0&&t}buildProperties(t,e){return this.tl.buildFromUnknown(t,{syntheticException:e?.syntheticException,mechanism:{handled:e?.handled}})}addExceptionStep(t,e){if(this.el.enabled)try{if(!W(t)||t.trim().length===0)return void Xe.warn("Ignoring exception step because message must be a non-empty string");var s=(function(i){if(!i)return{sanitizedProperties:{},droppedKeys:[]};var o=[];return{sanitizedProperties:Object.keys(i).reduce(((a,l)=>rp.has(l)?(o.push(l),a):(a[l]=i[l],a)),{}),droppedKeys:o}})(this.sl(e)),r=s.sanitizedProperties,n=s.droppedKeys;n.length>0&&Xe.warn("Ignoring reserved exception step fields",{droppedKeys:n}),this.rl.add(E({[Xr]:t,[Qr]:new Date().toISOString()},r))}catch(i){Xe.error("Failed to add exception step. Ignoring breadcrumb.",i)}}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 Xe.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 Xe.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 Xe.info("Skipping exception capture because it was thrown by the PostHog SDK")}var s=this.el.enabled&&D(t.$exception_steps)?this.dl(t):t,r=typeof(i=globalThis._posthogReleaseId)=="string"&&i.length>0?i:void 0;r&&(s.$release_id=r);try{var n=this._instance.capture("$exception",s,{_noTruncate:!0,_batchKey:"exceptionEvent",Wn:!0});return n&&this.rl.clear(),n}catch(o){return Xe.error("Failed to capture exception event. Dropping this exception.",o),void this.rl.clear()}}catch(o){return void Xe.error("Failed to process exception event. Ignoring this exception.",o)}var i}dl(t){try{var e=this.rl.getAttachable();return e.length===0?t:E({},t,{$exception_steps:e})}catch(s){return Xe.error("Failed to read buffered exception steps. Capturing exception without steps.",s),t}}ll(t){this.el.enabled&&this.rl.add({[Xr]:t,[Qr]:new Date().toISOString()})}sl(t){return te(t)?E({},t):{}}il(){var t,e;return(t=(e=this._instance.config.error_tracking)==null?void 0:e.exception_steps)!==null&&t!==void 0?t:{}}ol(t){if(t.length===0)return!1;try{var e=t.reduce(((s,r)=>{var n=r.type,i=r.value;return W(n)&&n.length>0&&s.$exception_types.push(n),W(i)&&i.length>0&&s.$exception_values.push(i),s}),{$exception_types:[],$exception_values:[]});return this.Xo.some((s=>{var r=s.values.map((n=>{var i=nd[n.operator],o=e[n.key];if(!i||!o)return!1;var a=L(n.value)?n.value:[n.value];return a.length>0&&i(a,o)}));return s.type==="OR"?r.some(Boolean):r.every(Boolean)}))}catch(s){return Xe.warn("Failed to evaluate suppression rules. Capturing the exception.",s),!1}}ul(t){return t.flatMap((e=>{var s,r;return(s=(r=e.stacktrace)==null?void 0:r.frames)!==null&&s!==void 0?s:[]})).some((e=>e.filename&&e.filename.startsWith("chrome-extension://")))}hl(t){if(t.length>0){var e,s,r,n,i=(e=(s=t[0].stacktrace)==null?void 0:s.frames)!==null&&e!==void 0?e:[],o=i[i.length-1];return(r=o==null||(n=o.filename)==null?void 0:n.includes("posthog.com/static"))!==null&&r!==void 0&&r}return!1}al(t){return!D(t)&&L(t)}}},If=E({productTours:class{get Mr(){return this._instance.persistence}constructor(t){this.vl=null,this.cl=null,this._instance=t}initialize(){this.loadIfEnabled()}onRemoteConfig(t){if(t.ok){var e=t.config;if("productTours"in e){var s,r;if(this.Mr&&this.Mr.register({[Vo]:!!e.productTours}),!Ii(this._instance))return!this.vl&&D((s=this.Mr)==null?void 0:s.props[Ws])||Pr.info("product tours disabled; stopping and clearing cached tours"),(r=this.vl)==null||r.stop(),this.vl=null,void this.clearCache();this.loadIfEnabled()}}}loadIfEnabled(){!this.vl&&Ii(this._instance)&&this.ai((()=>this.fl()))}ai(t){var e,s;(e=$.__PosthogExtensions__)!=null&&e.generateProductTours?t():(s=$.__PosthogExtensions__)==null||s.loadExternalDependency==null||s.loadExternalDependency(this._instance,"product-tours",(r=>{r?Pr.error("Could not load product tours script",r):t()}))}fl(){var t;!this.vl&&(t=$.__PosthogExtensions__)!=null&&t.generateProductTours&&(this.vl=$.__PosthogExtensions__.generateProductTours(this._instance,!0))}getProductTours(t,e){if(e===void 0&&(e=!1),!L(this.cl)||e){var s=this.Mr;if(s){var r=s.props[Ws];if(L(r)&&!e)return this.cl=r,void t(r,{isLoaded:!0})}this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/product_tours/?token="+this._instance.config.token),method:"GET",timestampMode:"query",callback:n=>{if(Ii(this._instance)){var i=n.statusCode;if(i!==200||!n.json){var o="Product Tours API could not be loaded, status: "+i;return i===0?n.error||Pr.warn(o):Pr.error(o),void t([],{isLoaded:!1,error:o})}var a=L(n.json.product_tours)?n.json.product_tours:[];this.cl=a,s&&s.register({[Ws]:a}),t(a,{isLoaded:!0})}else t([],{isLoaded:!0})}})}else t(this.cl,{isLoaded:!0})}getActiveProductTours(t){D(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(Ws)}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)}}},Tn),Cf={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 s=this.globalsForEvent(e);this.gl.push(s),this.gl.length>1e3&&(this.gl=this.gl.slice(10))}}get siteAppLoaders(){var t;return(t=$._POSTHOG_REMOTE_CONFIG)==null||(t=t[this._instance.config.token])==null?void 0:t.siteApps}initialize(){if(this.isEnabled){var t=this._instance._addCaptureHook(this.ml.bind(this));this.yl=()=>{t(),this.gl=[],this.yl=void 0}}}globalsForEvent(t){var e,s,r,n,i,o,a;if(!t)throw new Error("Event payload is required");var l={},u=this._instance.get_property("$groups")||[],c=this._instance.get_property("$stored_group_properties")||{};for(var d of Object.entries(c)){var h=d[0];l[h]={id:u[h],type:h,properties:d[1]}}var p=t.$set_once,f=t.$set;return{event:E({},Pc(t,mf),{properties:E({},t.properties,f?{$set:E({},(e=(s=t.properties)==null?void 0:s.$set)!==null&&e!==void 0?e:{},f)}:{},p?{$set_once:E({},(r=(n=t.properties)==null?void 0:n.$set_once)!==null&&r!==void 0?r:{},p)}:{}),elements_chain:(i=(o=t.properties)==null?void 0:o.$elements_chain)!==null&&i!==void 0?i:"",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,s=(e=t.tagName)==null?void 0:e.toLowerCase();return s==="style"&&this._instance.config.prepare_external_dependency_stylesheet?this._instance.config.prepare_external_dependency_stylesheet(t)||(Ze.error("prepare_external_dependency_stylesheet returned null"),null):s==="script"&&this._instance.config.prepare_external_dependency_script?this._instance.config.prepare_external_dependency_script(t)||(Ze.error("prepare_external_dependency_script returned null"),null):t}_l(){var t,e,s,r,n,i,o,a;if(!this._instance.config.prepare_external_dependency_stylesheet&&!this._instance.config.prepare_external_dependency_script)return()=>{};var l=C?.defaultView,u=l==null||(t=l.Node)==null?void 0:t.prototype;if(!l||!u)return()=>{};if(this.pl++,this.wl)return this.kl();var c=[],d=this,h=new WeakSet,p=(g,_,w)=>{if(g!=null&&g[_]){var b=g[_];g[_]=w(b),c.push((()=>{g[_]=b}))}},f=g=>{if(h.has(g))return g;var _=d.bl(g);return _&&h.add(_),_},m=g=>g.map((_=>typeof _=="string"?_:f(_))).filter((_=>!$e(_)));return p(u,"appendChild",(g=>function(_){var w=f(_);return w?g.call(this,w):_})),p(u,"insertBefore",(g=>function(_,w){var b=f(_);return b?g.call(this,b,w):_})),p(u,"replaceChild",(g=>function(_,w){var b=f(_);return b?g.call(this,b,w):w})),[(e=l.Element)==null?void 0:e.prototype,(s=l.Document)==null?void 0:s.prototype,(r=l.DocumentFragment)==null?void 0:r.prototype].forEach((g=>{p(g,"append",(_=>function(){for(var w=arguments.length,b=new Array(w),I=0;w>I;I++)b[I]=arguments[I];return _.apply(this,m(b))})),p(g,"prepend",(_=>function(){for(var w=arguments.length,b=new Array(w),I=0;w>I;I++)b[I]=arguments[I];return _.apply(this,m(b))}))})),[(n=l.Element)==null?void 0:n.prototype,(i=l.CharacterData)==null?void 0:i.prototype,(o=l.DocumentType)==null?void 0:o.prototype].forEach((g=>{p(g,"before",(_=>function(){for(var w=arguments.length,b=new Array(w),I=0;w>I;I++)b[I]=arguments[I];return _.apply(this,m(b))})),p(g,"after",(_=>function(){for(var w=arguments.length,b=new Array(w),I=0;w>I;I++)b[I]=arguments[I];return _.apply(this,m(b))})),p(g,"replaceWith",(_=>function(){for(var w=arguments.length,b=new Array(w),I=0;w>I;I++)b[I]=arguments[I];var F=m(b);return b.length&&!F.length?void 0:_.apply(this,F)}))})),p((a=l.Element)==null?void 0:a.prototype,"insertAdjacentElement",(g=>function(_,w){var b=f(w);return b?g.call(this,_,b):null})),this.wl=()=>{c.forEach((g=>g())),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 s=this._l();try{var r=t(s);return e&&s(),r}catch(n){throw s(),n}}setupSiteApp(t){var e=this.apps[t.id],s=()=>{var o;!e.errored&&this.gl.length&&(Ze.info("Processing "+this.gl.length+" events for site app with id "+t.id),this.gl.forEach((a=>this.xl((()=>e.processEvent==null?void 0:e.processEvent(a))))),e.processedBuffer=!0),Object.values(this.apps).every((a=>a.processedBuffer||a.errored))&&((o=this.yl)==null||o.call(this))},r=!1,n=o=>{e.errored=!o,e.loaded=!0,Ze.info("Site app with id "+t.id+" "+(o?"loaded":"errored")),r&&s()};try{var i=this.xl((o=>t.init({posthog:this._instance,callback(a){o(),n(a)}})),!1).processEvent;i&&(e.processEvent=i),r=!0}catch(o){Ze.error(Dl+t.id,o),n(!1)}if(r&&e.loaded)try{s()}catch(o){Ze.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 s of t)this.setupSiteApp(s)}Cl(t){var e=this;if(Object.keys(this.apps).length!==0){var s=this.globalsForEvent(t),r=function(i){try{e.xl((()=>i.processEvent==null?void 0:i.processEvent(s)))}catch(o){Ze.error("Error while processing event "+t.event+" for site app "+i.id,o)}};for(var n of Object.values(this.apps))r(n)}}onRemoteConfig(t){var e,s,r,n=this;if((e=this.siteAppLoaders)!=null&&e.length)return this.isEnabled?(this.Sl(),void this._instance.on("eventCaptured",(l=>this.Cl(l)))):void Ze.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.');if((s=this.yl)==null||s.call(this),t.ok){var i=t.config;if((r=i.siteApps)!=null&&r.length)if(this.isEnabled){var o=function(){var l,u=a.id,c=a.url;$["__$$ph_site_app_"+u]=n._instance,(l=$.__PosthogExtensions__)==null||l.loadSiteApp==null||l.loadSiteApp(n._instance,c,(d=>{if(d)return Ze.error(Dl+u,d)}))};for(var a of i.siteApps)o()}else Ze.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.')}}}},Ff={tracingHeaders:class{constructor(t){this.Ml=void 0,this.Tl=void 0,this.El=void 0,this.Uo=()=>{var e,s,r=this.Il();r?(x(this.Ml)&&(this.Ml=(e=$.__PosthogExtensions__)==null||(e=e.tracingHeadersPatchFns)==null?void 0:e._patchXHR(r,(()=>this._instance.get_distinct_id()),this._instance.sessionManager)),x(this.Tl)&&(this.Tl=(s=$.__PosthogExtensions__)==null||(s=s.tracingHeadersPatchFns)==null?void 0:s._patchFetch(r,(()=>this._instance.get_distinct_id()),this._instance.sessionManager))):this.Qo()},this._instance=t}initialize(){this.startIfEnabledOrStop()}ai(t){var e,s;(e=$.__PosthogExtensions__)!=null&&e.tracingHeadersPatchFns?t():(s=$.__PosthogExtensions__)==null||s.loadExternalDependency==null||s.loadExternalDependency(this._instance,"tracing-headers",(r=>{if(r)return ff.error("failed to load script",r);t()}))}Pl(){var t,e;return(t=(e=this._instance.config.tracing_headers)!==null&&e!==void 0?e:this._instance.config.addTracingHeaders)!==null&&t!==void 0?t:this._instance.config.__add_tracing_headers}Il(){var t=this.Pl();return L(t)?(L(this.El)?this.El.splice(0,this.El.length,...t):this.El=[...t],t.length>0?this.El:void 0):(L(this.El)&&this.El.splice(0),this.El=t||void 0,this.El)}Qo(){var t,e;(t=this.Ml)==null||t.call(this),(e=this.Tl)==null||e.call(this),this.Ml=void 0,this.Tl=void 0}startIfEnabledOrStop(){this.Il()?this.ai(this.Uo):this.Qo()}}},Pf=E({surveys:class{get Ne(){return this._instance.config}constructor(t){this.Rl=void 0,this._surveyManager=null,this.Al=!1,this.Fl=[],this.Ll=null,this.Ol=null,this._instance=t,this._surveyEventReceiver=null}initialize(){this.loadIfEnabled()}onRemoteConfig(t){if(!this.Ne.disable_surveys){if(!t.ok)return q.warn("Remote config unavailable. Not loading surveys.");var e=t.config.surveys;if(D(e))return q.warn("Flags not loaded yet. Not loading surveys.");var s=L(e);this.Rl=s?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=[],s=0;slocalStorage.removeItem(n)))}catch{}}loadIfEnabled(){if(!this._surveyManager)if(this.Al)q.info("Already initializing surveys, skipping...");else if(this.Ne.disable_surveys)q.info(Bl);else if(this.Ne.cookieless_mode&&this._instance.consent.isOptedOut())q.info("Not loading surveys in cookieless mode without consent.");else{var t=$?.__PosthogExtensions__;if(t){if(!x(this.Rl)||this.Ne.advanced_enable_surveys){var e=this.Rl||this.Ne.advanced_enable_surveys;this.Al=!0;try{var s=t.generateSurveys;if(s)return void this.Dl(s,e);var r=t.loadExternalDependency;if(!r)return void this.$l(Ko);r(this._instance,"surveys",(n=>{n||!t.generateSurveys?this.$l("Could not load surveys script",n):this.Dl(t.generateSurveys,e)}))}catch(n){throw this.$l("Error initializing surveys",n),n}finally{this.Al=!1}}}else q.error("PostHog Extensions not found.")}}Dl(t,e){this._surveyManager=t(this._instance,e),this._surveyEventReceiver=new yf(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(Bl),t([]);var s,r=this._instance.get_property(Xi);if(r&&!e)return t(r,{isLoaded:!0}),void(this.ql()&&this.getSurveys((()=>{}),!0));typeof Promise<"u"&&this.Ll?this.Ll.then((n=>t(n.surveys,n.context))):(typeof Promise<"u"&&(this.Ll=new Promise((n=>{s=n}))),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:n=>{var i;this.Ll=null;var o=n.statusCode;if(o!==200||!n.json){var a="Surveys API could not be loaded, status: "+o;o!==0?q.error(a):n.error||q.warn(a),this.Ol=Date.now();var l={isLoaded:!1,error:a};return t([],l),void(s==null||s({surveys:[],context:l}))}this.Ol=null;var u,c=n.json.surveys||[],d=c.filter((p=>(function(f){return!(!f.start_date||f.end_date)})(p)&&(od(p)||(function(f){var m;return!((m=f.conditions)==null||(m=m.actions)==null||(m=m.values)==null||!m.length)})(p))));d.length>0&&((u=this._surveyEventReceiver)==null||u.register(d)),(i=this._instance.persistence)==null||i.register({[Xi]:c,[sn]:Date.now()});var h={isLoaded:!0};t(c,h),s?.({surveys:c,context:h})}}))}ql(){return this.jl()&&!this.Ll&&!this.Bl()}jl(){var t=this._instance.get_property(sn);return he(t)&&Date.now()-t>3e5}Bl(){return he(this.Ol)&&3e5>Date.now()-this.Ol}markSurveyAsSeen(t,e){var s,r={id:t,current_iteration:(s=e?.iteration)!==null&&s!==void 0?s:null};ld(r);try{localStorage.setItem("lastSeenSurveyDate",new Date().toISOString())}catch{}}Nl(t){for(var e of this.Fl)try{if(!t.isLoaded)return e([],t);this.getSurveys(e)}catch(s){q.error("Error in survey callback",s)}}getActiveMatchingSurveys(t,e){if(e===void 0&&(e=!1),!D(this._surveyManager))return this._surveyManager.getActiveMatchingSurveys(t,e);q.warn("init was not called")}Hl(t){var e=null;return this.getSurveys((s=>{var r;e=(r=s.find((n=>n.id===t)))!==null&&r!==void 0?r:null})),e}Ul(t){if(D(this._surveyManager))return{eligible:!1,reason:Ar};var e=typeof t=="string"?this.Hl(t):t;return e?this._surveyManager.checkSurveyEligibility(e):{eligible:!1,reason:"Survey not found"}}zl(t){if(D(this._surveyManager))return{eligible:!1,reason:Ar};var e=typeof t=="string"?this.Hl(t):t;return e?this._surveyManager.checkSurveyRenderability(e):{eligible:!1,reason:"Survey not found"}}canRenderSurvey(t){if(D(this._surveyManager))return q.warn("init was not called"),{visible:!1,disabledReason:Ar};var e=this.zl(t);return{visible:e.eligible,disabledReason:e.reason}}canRenderSurveyAsync(t,e){return D(this._surveyManager)?(q.warn("init was not called"),Promise.resolve({visible:!1,disabledReason:Ar})):new Promise((s=>{this.getSurveys((r=>{var n,i=(n=r.find((a=>a.id===t)))!==null&&n!==void 0?n:null;if(i){var o=this.zl(i);s({visible:o.eligible,disabledReason:o.reason})}else s({visible:!1,disabledReason:"Survey not found"})}),e)}))}renderSurvey(t,e,s){var r;if(D(this._surveyManager))q.warn("init was not called");else{var n=typeof t=="string"?this.Hl(t):t;if(n!=null&&n.id)if(ef.includes(n.type)){var i=C?.querySelector(e);if(i)return(r=n.appearance)!=null&&r.surveyPopupDelaySeconds?(q.info("Rendering survey "+n.id+" with delay of "+n.appearance.surveyPopupDelaySeconds+" seconds"),void setTimeout((()=>{var o,a;q.info("Rendering survey "+n.id+" with delay of "+((o=n.appearance)==null?void 0:o.surveyPopupDelaySeconds)+" seconds"),(a=this._surveyManager)==null||a.renderSurvey(n,i,s),q.info("Survey "+n.id+" rendered")}),1e3*n.appearance.surveyPopupDelaySeconds)):void this._surveyManager.renderSurvey(n,i,s);q.warn("Survey element not found")}else q.warn("Surveys of type "+n.type+" cannot be rendered in the app");else q.warn("Survey not found")}}displaySurvey(t,e){var s;if(D(this._surveyManager))q.warn("init was not called");else{var r=this.Hl(t);if(r){var n=r;if((s=r.appearance)!=null&&s.surveyPopupDelaySeconds&&e.ignoreDelay&&(n=E({},r,{appearance:E({},r.appearance,{surveyPopupDelaySeconds:0})})),e.displayType!==lo.Popover&&e.initialResponses&&q.warn("initialResponses is only supported for popover surveys. prefill will not be applied."),e.ignoreConditions===!1){var i=this.Ul(r);if(!i.eligible)return void q.warn("Survey is not eligible to be displayed: ",i.reason)}e.displayType!==lo.Inline?this._surveyManager.handlePopoverSurvey(n,e):this.renderSurvey(n,e.selector,e.properties)}else q.warn("Survey not found")}}cancelPendingSurvey(t){D(this._surveyManager)?q.warn("init was not called"):this._surveyManager.cancelSurvey(t)}handlePageUnload(){var t;(t=this._surveyManager)==null||t.handlePageUnload==null||t.handlePageUnload()}}},Tn),Af={toolbar:class{constructor(t){this.instance=t}Wl(t){$.ph_toolbar_state=t}Vl(){var t;return(t=$.ph_toolbar_state)!==null&&t!==void 0?t:0}initialize(){return this.maybeLoadToolbar()}maybeLoadToolbar(t,e,s){if(t===void 0&&(t=void 0),e===void 0&&(e=void 0),s===void 0&&(s=void 0),io(this.instance.config)||!v||!C)return!1;t=t??v.location,s=s??v.history;try{if(!e){try{v.localStorage.setItem("test","test"),v.localStorage.removeItem("test")}catch{return!1}e=v?.localStorage}var r,n=wf||dn(t.hash,"__posthog")||dn(t.hash,"state"),i=n?rl((()=>JSON.parse(atob(decodeURIComponent(n)))))||rl((()=>JSON.parse(decodeURIComponent(n)))):null;return i&&i.action==="ph_authorize"?((r=i).source="url",r&&Object.keys(r).length>0&&(i.desiredHash?t.hash=i.desiredHash:s?s.replaceState(s.state,"",t.pathname+t.search):t.hash="")):((r=JSON.parse(e.getItem(jl)||"{}")).source="localstorage",delete r.userIntent),!(!r.token||this.instance.config.token!==r.token||(this.loadToolbar(r),0))}catch{return!1}}Zl(t){var e=$.ph_load_toolbar||$.ph_load_editor;!D(e)&&Se(e)?e(t,this.instance):Ul.warn("No toolbar load function found")}loadToolbar(t){var e=!(C==null||!C.getElementById(Su));if(!v||e)return!1;var s=this.instance.requestRouter.region==="custom"&&this.instance.config.advanced_disable_toolbar_metrics,r=E({token:this.instance.config.token},t,{apiURL:this.instance.requestRouter.endpointFor("ui")},s?{instrument:!1}:{});if(v.localStorage.setItem(jl,JSON.stringify(E({},r,{source:void 0}))),this.Vl()===2)this.Zl(r);else if(this.Vl()===0){var n;this.Wl(1),(n=$.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this.instance,"toolbar",(i=>{if(i)return Ul.error("[Toolbar] Failed to load",i),void this.Wl(0);this.Wl(2),this.Zl(r)})),ne(v,"turbolinks:load",(()=>{this.Wl(0),this.loadToolbar(r)}))}return!0}Gl(t){return this.loadToolbar(t)}maybeLoadEditor(t,e,s){return t===void 0&&(t=void 0),e===void 0&&(e=void 0),s===void 0&&(s=void 0),this.maybeLoadToolbar(t,e,s)}}},$f=E({experiments:ye},Tn),Rf={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;D(e)||(Ke(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||io(this._instance.config)||this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut())){var t=$?.__PosthogExtensions__;if(t&&!x(this.Ql)&&this.Ql)if(this.Jl&&this.Jl.token){this.Kl=!0;try{var e=t.initConversations;if(e)return this.tu(e),void(this.Kl=!1);var s=t.loadExternalDependency;if(!s)return void this.eu(Ko);s(this._instance,"conversations",(r=>{r||!t.initConversations?this.eu("Could not load conversations script",r):this.tu(t.initConversations),this.Kl=!1}))}catch(r){this.eu("Error initializing conversations",r),this.Kl=!1}}else Ue.error("Conversations enabled but missing token in remote config.")}}tu(t){if(this.Jl)try{this._conversationsManager=t(this.Jl,this._instance),this.Yl=!1,Ue.info("Conversations loaded successfully")}catch(e){this.eu("Error completing conversations initialization",e)}else Ue.error("Cannot complete initialization: remote config is null")}eu(t,e){Ue.error(t,e),this._conversationsManager=null,this.Kl=!1,this.Yl=!0}show(){this._conversationsManager?this._conversationsManager.show():Ue.warn("Conversations not loaded yet.")}hide(){this._conversationsManager&&this._conversationsManager.hide()}isAvailable(){return this.Ql===!0&&!$e(this._conversationsManager)}getUnavailableReason(){return this.isAvailable()?null:this._instance.config.disable_conversations?"disabled_by_config":io(this._instance.config)?"disabled_for_toolbar":this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut()?"consent_opted_out":this.Xl===!1?"remote_config_failed":x(this.Ql)?this.Xl?"disabled_in_project":"remote_config_pending":this.Ql?D(this.Jl)||!this.Jl.token?"missing_token":$!=null&&$.__PosthogExtensions__?this.Kl?"initializing":this.Yl?"load_failed":"not_loaded":"extensions_unavailable":"disabled_in_project"}isVisible(){var t,e;return(t=(e=this._conversationsManager)==null?void 0:e.isVisible())!==null&&t!==void 0&&t}sendMessage(t,e,s){var r=this;return X((function*(){return r._conversationsManager?r._conversationsManager.sendMessage(t,e,s):(Ue.warn(Dt),null)}))()}getMessages(t,e){var s=this;return X((function*(){return s._conversationsManager?s._conversationsManager.getMessages(t,e):(Ue.warn(Dt),null)}))()}markAsRead(t){var e=this;return X((function*(){return e._conversationsManager?e._conversationsManager.markAsRead(t):(Ue.warn(Dt),null)}))()}getTickets(t){var e=this;return X((function*(){return e._conversationsManager?e._conversationsManager.getTickets(t):(Ue.warn(Dt),null)}))()}requestRestoreLink(t){var e=this;return X((function*(){return e._conversationsManager?e._conversationsManager.requestRestoreLink(t):(Ue.warn(Dt),null)}))()}restoreFromToken(t){var e=this;return X((function*(){return e._conversationsManager?e._conversationsManager.restoreFromToken(t):(Ue.warn(Dt),null)}))()}restoreFromUrlToken(){var t=this;return X((function*(){return t._conversationsManager?t._conversationsManager.restoreFromUrlToken():(Ue.warn(Dt),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()}}},Tf={logs:class{constructor(t){var e,s=this;this.iu=!1,this.ru=!1,this.rt=se("[logs]"),this.nu=E({},this.rt,{error(){for(var r=arguments.length,n=new Array(r),i=0;r>i;i++)n[i]=arguments[i];n.some(Jl)||s.rt.error(...n)}}),this.tr=[],this.su=[],this.Sa=0,this.au=()=>{var r,n;this.Sa=0,(r=this.ou)==null||r.onReconnect(),(n=this.lu)==null||n.onReconnect()},this._instance=t,this._instance&&(e=this._instance.config.logs)!=null&&e.captureConsoleLogs&&(this.iu=!0),v&&ne(v,"online",this.au)}uu(t,e,s,r){var n,i=(function(o,a){var l,u,c,d,h,p,f,m=(l=o?.flushIntervalMs)!==null&&l!==void 0?l:3e3,g=(u=o?.maxBufferSize)!==null&&u!==void 0?u:100,_=a!=null&&a.consoleCapture?void 0:(c=o?.maxLogsPerInterval)!==null&&c!==void 0?c:1e3,w=x(_)?Math.max(g,2048):Math.max(g,_),b=o?.resourceAttributes;return{serviceName:(d=(h=b?.["service.name"])!==null&&h!==void 0?h:o?.serviceName)!==null&&d!==void 0?d:a?.serviceNameDefault,serviceVersion:(p=b?.["service.version"])!==null&&p!==void 0?p:o?.serviceVersion,environment:(f=b?.["deployment.environment"])!==null&&f!==void 0?f:o?.environment,resourceAttributes:b,beforeSend:o?.beforeSend,flushIntervalMs:m,maxBufferSize:g,maxQueueSize:w,maxBatchRecordsPerPost:100,rateCapWindowMs:m,maxLogsPerInterval:_,backgroundFlushBudgetMs:0,terminationFlushBudgetMs:0}})((n=this._instance)==null||(n=n.config)==null?void 0:n.logs,s);return[new Lh(this.hu(t,e),i,this.nu,(()=>this.du()),(o=>o()),void 0,r),i]}vu(){var t,e=(t=this._instance)==null||(t=t.config)==null?void 0:t.logs;if(!this.ou||this.cu!==e){var s;(s=this.ou)==null||s.reset(),this.cu=e;var r=this.uu((()=>this.tr),(n=>{this.tr=n}));this.ou=r[0],this.fu=r[1]}return this.ou}pu(){var t,e=(t=this._instance)==null||(t=t.config)==null?void 0:t.logs;if(!this.lu||this.gu!==e){var s;(s=this.lu)==null||s.reset(),this.gu=e;var r=this.uu((()=>this.su),(n=>{this.su=n}),{serviceNameDefault:"posthog-browser-logs",consoleCapture:!0},Kl);this.lu=r[0],this.mu=r[1]}return this.lu}initialize(){this.loadIfEnabled()}onRemoteConfig(t){var e;if(t.ok){var s=(e=t.config.logs)==null?void 0:e.captureConsoleLogs;!D(s)&&s&&(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){Jl(t)||this.rt.error("PostHog logs flush failed:",t)}loadIfEnabled(){if(this.iu&&!this.ru){var t=$?.__PosthogExtensions__;if(t){var e=t.loadExternalDependency;e?e(this._instance,"logs",(s=>{var r;s||(r=t.logs)==null||!r.initializeLogs?this.rt.error("Could not load logs script",s):(t.logs.initializeLogs(this._instance),this.ru=!0)})):this.rt.error(Ko)}else this.rt.error("PostHog Extensions not found.")}}hu(t,e){var s=this._instance;return{get isDisabled(){return!1},get optedOut(){return!s.is_capturing()},getPersistedProperty:r=>r===ut.LogsQueue?t():void 0,setPersistedProperty(r,n){var i;r===ut.LogsQueue&&e((i=n)!==null&&i!==void 0?i:[])},Ot:r=>this.Ot(r),getLibraryId:()=>Y.LIB_NAME,getLibraryVersion:()=>Y.LIB_VERSION}}Ot(t){return new Promise((e=>{if(Mu(this.Sa,3))e({kind:"fatal",error:Fi(void 0,"logs endpoint is unreachable, dropping batch")});else{var s=!1,r=i=>{s||(s=!0,clearTimeout(n),e(i))},n=setTimeout((()=>{this.rt.warn("Logs request timed out before receiving a response"),r({kind:"retry-later",error:Fi(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:i=>{var o=i.statusCode;if(this.ku(o),o>=200&&300>o)r({kind:"ok"});else if(o===413)r({kind:"too-large"});else if(o!==0&&o!==429&&500>o)r({kind:"fatal",error:new Error("logs request failed with status "+o)});else{var a;o===0?(i.error||this.rt.warn("Logs request failed before receiving an HTTP response"),r({kind:"retry-later",error:Fi(i.error,"logs request failed before receiving an HTTP response")})):r({kind:"retry-later",error:(a=i.error)!==null&&a!==void 0?a:new Error("logs request failed with status "+o)})}}})}}))}ku(t){(t!==0||this._instance.__loaded)&&(this.Sa=Lu(t,this.Sa,3,(()=>this.rt.warn("Log requests are failing before receiving an HTTP response; this can happen due to network issues, CORS, browser blocking, or ad blockers. Stopped sending logs; will try again when connectivity changes."))))}bu(t){this.tr.length>0&&this.xu(t,this.tr,this.fu,Y.LIB_NAME,(e=>{this.tr=e})),this.su.length>0&&this.xu(t,this.su,this.mu,Kl,(e=>{this.su=e}))}xu(t,e,s,r,n){if(e.length!==0){var i=e.map((a=>a.record));n([]);var o=ou(i,iu(s,Y.LIB_NAME,Y.LIB_VERSION),r,Y.LIB_VERSION);this._instance._send_request({method:"POST",url:this.wu(),data:o,compression:"best-available",batchKey:"logs",transport:t})}}wu(){return this._instance.requestRouter.endpointFor("api","/i/v1/logs")+"?token="+encodeURIComponent(this._instance.config.token)}du(){var t,e={};if(e.distinctId=this._instance.get_distinct_id(),this._instance.sessionManager){var s=this._instance.sessionManager.checkAndGetSessionAndWindowId(!0),r=s.windowId,n=s.sessionStartTimestamp,i=s.lastActivityTimestamp;e.sessionId=s.sessionId,e.windowId=r,D(n)||(e.sessionStartTimestamp=n),D(i)||(e.lastActivityTimestamp=i)}if($!=null&&(t=$.location)!=null&&t.href&&(e.currentUrl=this._instance.config.disable_capture_url_hashes?Ct($.location.href):$.location.href),this._instance.featureFlags){var o=this._instance.featureFlags.getFlags();o&&o.length>0&&(e.activeFeatureFlags=o)}return e}}},Nf={metrics:class{constructor(t){this.rt=se("[metrics]"),this._instance=t}initialize(){}vu(){var t,e,s=(t=this._instance)==null||(t=t.config)==null?void 0:t.metrics;return this.ou&&this.cu===s||((e=this.ou)==null||e.reset(),this.cu=s,this.ou=new Oh(this.hu(),(function(r){var n,i,o,a,l,u=r?.resourceAttributes;return{serviceName:(n=u?.["service.name"])!==null&&n!==void 0?n:r?.serviceName,serviceVersion:(i=u?.["service.version"])!==null&&i!==void 0?i:r?.serviceVersion,environment:(o=u?.["deployment.environment"])!==null&&o!==void 0?o:r?.environment,resourceAttributes:u,beforeSend:r?.beforeSend,flushIntervalMs:(a=r?.flushIntervalMs)!==null&&a!==void 0?a:1e4,maxSeriesPerFlush:(l=r?.maxSeriesPerFlush)!==null&&l!==void 0?l:1e3}})(s),this.rt)),this.ou}count(t,e,s){e===void 0&&(e=1),this.vu().count(t,e,s)}gauge(t,e,s){this.vu().gauge(t,e,s)}histogram(t,e,s){this.vu().histogram(t,e,s)}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((s=>this.rt.error("PostHog metrics flush failed:",s)))}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:s=>e.Jt(s),getLibraryId:()=>Y.LIB_NAME,getLibraryVersion:()=>Y.LIB_VERSION}}Jt(t,e){return new Promise((s=>{var r=!1,n=o=>{r||(r=!0,clearTimeout(i),s(o))},i=setTimeout((()=>n({kind:"retry-later",error:new Error("metrics request timed out")})),9e4);this._instance._send_request(E({method:"POST",url:this.Su(),data:t,compression:"best-available",batchKey:"metrics"},e&&{transport:e},{fireCallbackOnDrop:!0,callback(o){var a=o.statusCode;if(a>=200&&300>a)n({kind:"ok"});else if(a===413)n({kind:"too-large"});else if(a!==0&&a!==429&&500>a)n({kind:"fatal",error:new Error("metrics request failed with status "+a)});else{var l;n({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)}}},Mf=E({},Tn,Sf,xf,kf,If,Cf,Pf,Ff,Af,$f,Rf,Tf,Nf);Te.__defaultExtensionClasses=E({},Mf);(function(){Y.SDK_DIST_CHANNEL="npm";var t=Ys[os]=new Te;return(function(){function e(){e.done||(e.done=!0,ud=!1,Z(Ys,(function(s){s._dom_loaded()})))}C!=null&&C.addEventListener?C.readyState==="complete"?e():ne(C,"DOMContentLoaded",e,{capture:!1}):v&&k.error("Browser doesn't support `document.addEventListener` so PostHog couldn't be initialized")})(),t})();const hd="CodeFile",pd="GeneratedCode",Lf={CustomAction:"A",CustomWidget:"W",CustomFunction:"F",CustomClass:"C",CodeFile:"C"};function kt(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function vo(t){return String(t||"").trim().replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function Of(t={},e=0){const s=vo(t.artifactType||t.type||hd),r=vo(t.artifactName||t.name||t.fileName||`${pd}-${e+1}`);return`${s||"artifact"}-${r||e+1}`}function fd(t={},e=0){const s=kt(t),r=s.artifactType||s.type||hd,n=s.artifactName||s.name||pd;let i=s.fileName||n;return i.endsWith(".dart")||(i+=".dart"),{id:vo(s.id)||Of({...s,artifactType:r,artifactName:n,fileName:i},e),artifactType:r,artifactName:n,fileName:i,deployPath:s.deployPath||"",description:s.description||"",code:s.code||s.content||"",dependencies:gd(s.dependencies),imports:Array.isArray(s.imports)?s.imports:[],publicApi:Array.isArray(s.publicApi)?s.publicApi:[],relationships:md(s.relationships),deployStatus:s.deployStatus||"pending",review:s.review||null,metadata:kt(s.metadata),codeType:s.codeType||Lf[r]||"O"}}function gd(t){return t?Array.isArray(t)?t.map(e=>{if(typeof e=="string")return{name:e,version:null,inferred:!1};const s=kt(e),r=s.name||s.package;return r?{name:r,version:s.version||null,versionRequired:!!(s.versionRequired||s.required),inferred:!!s.inferred,...s.reason?{reason:s.reason}:{}}:null}).filter(Boolean):Object.entries(kt(t)).map(([e,s])=>({name:e,version:s||null,inferred:!1})):[]}function md(t){return t?(Array.isArray(t)?t:[t]).map(e=>{const s=kt(e);return!s.from&&!s.to?null:{from:s.from||null,to:s.to||null,type:s.type||"uses",description:s.description||""}}).filter(Boolean):[]}function _o(t){if(typeof t!="string")return null;const e=t.trim();if(!e)return null;try{return JSON.parse(e)}catch{const s=e.match(/```(?:json)?\s*([\s\S]*?)```/i);if(!s)return null;try{return JSON.parse(s[1].trim())}catch{return null}}}function or(t,e={}){const s=[],r=typeof t=="string"?_o(t):t,i=kt(r||{});!r&&typeof t=="string"&&s.push("Structured bundle parse failed; using legacy single-artifact fallback.");const o=Array.isArray(i.artifacts)?i.artifacts:[{artifactType:i.artifactType||e.artifactType,artifactName:i.artifactName||e.artifactName,fileName:i.fileName||e.fileName,description:i.description,code:i.code||e.code||(typeof t=="string"?t:""),dependencies:i.dependencies||e.dependencies,relationships:i.relationships||e.relationships}];o.forEach((d,h)=>{!d?.artifactType&&!d?.type&&s.push(`Artifact ${h+1} has no artifactType; it will deploy as a standalone code file under lib/custom_code/ root.`)});const a=o.map((d,h)=>fd(d,h)),l=new Map(o.map((d,h)=>[kt(d).id,a[h]?.id]).filter(([d,h])=>d&&h)),u=d=>l.get(d)||d,c=md(i.relationships||e.relationships).map(d=>({...d,from:d.from?u(d.from):d.from,to:d.to?u(d.to):d.to}));return{schemaVersion:i.schemaVersion||e.schemaVersion||null,id:i.id||e.id||"bundle-current",title:i.title||i.name||e.title||"Generated artifact bundle",description:i.description||e.description||"",artifacts:a,dependencies:gd(i.dependencies||e.dependencies),relationships:c,deployOrder:Array.isArray(i.deployOrder)?i.deployOrder.map(u):a.map(d=>d.id),warnings:[...s,...Array.isArray(i.warnings)?i.warnings:[]],metadata:kt(i.metadata)}}function mn(t){return or(t).artifacts[0]||fd()}function yt(t){if(typeof t!="string")return t??"";const e=t.trim();if(!e)return"";try{return JSON.parse(e)}catch{return t}}function ys(t){return JSON.stringify(t,null,2)}function Df(t){return ys({task:"architect",userRequest:String(t??"")})}function Bf(t){const e=yt(t);return e&&typeof e=="object"&&typeof e.task=="string"?ys(e):ys({task:"generate_bundle",bundleSpec:e})}function jf(t){return ys({task:"review_bundle",generatedBundle:yt(t),outputRequirements:{bundleReview:["status","score","summary","manualActions","findings"],scoreRange:[0,100],eachArtifact:["id","review.status","review.findings"],manualActions:{definition:"Setup the developer must perform by hand in the FlutterFlow editor that FlutterFlow will NOT do for them.",exclude:["creating the Custom Action, Widget or Code File itself - deploying the code creates it","declaring parameters or return values FlutterFlow derives from the function signature","anything that resolves as a side effect of using the action or widget in the editor","generic advice such as testing, reviewing or rebuilding the app"],preferEmpty:"Return an empty array when nothing qualifies - an empty list is the expected result for most bundles."}}})}function sa(t,e=null){const s={stage:t};return e!=null&&(s.bundle=yt(e)),s}function Uf({bundleSpec:t,artifactBundle:e,bundleReview:s,artifactId:r,userFeedback:n}){return ys({task:"regenerate_artifact",artifactId:r,bundleSpec:yt(t),artifactBundle:yt(e),bundleReview:yt(s),userFeedback:String(n)})}function vd({bundleSpec:t,artifactBundle:e,bundleReview:s,userFeedback:r}){return ys({task:"regenerate_bundle",bundleSpec:yt(t),artifactBundle:yt(e),bundleReview:yt(s),userFeedback:String(r??"")})}const Yl={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"},Hf=["sanitizationResult","modelArmor","modelArmorResult","data","result","error"];function Le(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function Wf(t){return Le(t)?typeof t.filterMatchState=="string"||typeof t.invocationResult=="string"||Array.isArray(t.matchedFilters)||Le(t.filterSummary)||Le(t.filterResults):!1}function _d(t,e=0){if(!Le(t)||e>3)return null;if(Wf(t))return t;for(const s of Hf){const r=t[s];if(Le(r)){const n=_d(r,e+1);if(n)return n}}return null}function vn(t){return Array.isArray(t)?t.some(vn):Le(t)?t.matched===!0||t.matchState==="MATCH_FOUND"?!0:Object.values(t).some(vn):!1}function yo(t){return Array.isArray(t)?t.some(yo):Le(t)?typeof t.executionState=="string"&&t.executionState!=="EXECUTION_SUCCESS"?!0:Object.values(t).some(yo):!1}function yd(t){return{csamFilterFilterResult:"csam",maliciousUriFilterResult:"malicious_uris",piAndJailbreakFilterResult:"pi_and_jailbreak",raiFilterResult:"rai",sdpFilterResult:"sdp",virusScanFilterResult:"virus_scan"}[t]||t}function zf(t,e){if(Le(t))for(const[s,r]of Object.entries(t)){if(!Le(r))continue;const n=Le(r.categories)?r.categories:{},i=Object.entries(n).filter(([,o])=>Le(o)&&o.matched===!0).map(([o])=>o);i.length>0?i.forEach(o=>e.add(o)):r.matched===!0&&e.add(yd(s))}}function qf(t,e){if(!t)return;const s=Array.isArray(t)?t.flatMap(r=>Le(r)?Object.entries(r):[]):Object.entries(t);for(const[r,n]of s){if(!vn(n))continue;const i=yd(r),o=n?.raiFilterResult?.raiFilterTypeResults||(i==="rai"?n?.raiFilterTypeResults:null),a=Le(o)?Object.entries(o).filter(([,l])=>vn(l)).map(([l])=>l):[];a.length>0?a.forEach(l=>e.add(l)):e.add(i)}}function Vf(t){return Yl[t]?Yl[t]:String(t).replace(/([a-z])([A-Z])/g,"$1 $2").replace(/_/g," ").toLowerCase()}function Zl(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 Gf(t){const e=_d(t);if(!e)return null;const s=new Set(Array.isArray(e.matchedFilters)?e.matchedFilters:[]);zf(e.filterSummary,s),qf(e.filterResults,s);const r=e.blocked===!0||e.filterMatchState==="MATCH_FOUND"||s.size>0,n=e.invocationResult||null,i=yo(e.filterSummary||e.filterResults);return!r&&!i&&!["PARTIAL","FAILURE"].includes(n)?null:{kind:r?"blocked":"unavailable",invocationResult:n,matchedFilters:[...s]}}function Kf(t,e){const s=Gf(t);if(!s)return null;const r=[...new Set(s.matchedFilters.map(Vf))],n=s.kind==="blocked",i=new Error(n?`Safety screening blocked this pipeline step for ${Zl(r)}.`:"Safety screening could not be completed. Please try again.");return i.name="ModelArmorError",i.code=n?"MODEL_ARMOR_BLOCKED":"MODEL_ARMOR_UNAVAILABLE",i.isModelArmor=!0,i.pipelineStep=e,i.userTitle=n?"Request blocked for safety":"Safety check unavailable",i.userMessage=n?`The safety check detected ${Zl(r)}. Edit your request to remove or rephrase the flagged content, then run the pipeline again.`:"The safety service did not finish all of its checks. Please wait a moment and run the pipeline again.",i.retryExplanation=n?"Trying another model would not change this safety decision.":"A fallback model was not attempted because safety screening must complete first.",i.matchedFilters=s.matchedFilters,i}function Jf(t){return String(t||"").replace(/\/\*[\s\S]*?\*\//g,"").replace(/\/\/[^\n]*/g,"")}function Xl(t){const e=/^(import|export|part|library|class|enum|extension|typedef|mixin|abstract|const|final|var|late)\b/,s=[];for(const r of Jf(t).split(` +`)){if(!/^[A-Za-z_$]/.test(r)||e.test(r))continue;const n=r.match(/^[\w$<>,?\s[\]]+?\s([a-zA-Z_$][\w$]*)\s*\(/);n&&s.push(n[1])}return s}function ra(t,e){const s=t.replace(/\.dart$/,"");if(e==="W")return s.replace(/(^|_)(\w)/g,(r,n,i)=>i.toUpperCase());if(e==="A"){const r=s.replace(/(^|_)(\w)/g,(n,i,o)=>o.toUpperCase());return r.charAt(0).toLowerCase()+r.slice(1)}return e==="F"?"CustomFunctions":e==="C"?t.endsWith(".dart")?t:`${t}.dart`:s}async function Ql(t){const e=new TextEncoder().encode(String(t||"")),s=await globalThis.crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(s),r=>r.toString(16).padStart(2,"0")).join("")}async function Yf(t,e=new Map){const s={},r=new Set;for(const[o,a]of t.entries()){if(a.type==="D"||a.type==="O")continue;const l=ra(o,a.type),u={old_identifier_name:l,new_identifier_name:l,type:a.type,is_deleted:!1,current_checksum:await Ql(a.content)},c=e.get(a.path);if(c!==void 0&&(u.original_checksum=await Ql(c)),s[o]=u,a.type==="F"){const d=Xl(a.content);(d.length>0?d:[a.functionName].filter(Boolean)).forEach(p=>r.add(p))}}const n=new Set(Xl(e.get("lib/flutter_flow/custom_functions.dart")||"")),i={functions_to_rename:[],functions_to_delete:[],functions_to_add:Array.from(r).filter(o=>!n.has(o))};return{fileMapContents:JSON.stringify(s),functionsMapContents:JSON.stringify(i)}}const Zf=new Set(["CustomWidget","CustomAction","CustomFunction","CustomClass","CodeFile"]),ec={CustomWidget:"custom_code/widgets/",CustomAction:"custom_code/actions/",CustomFunction:"flutter_flow/custom_functions.dart",CustomClass:"custom_code/",CodeFile:"custom_code/"},Xf=new Set(["void","dynamic","String","int","double","num","bool","Color","DateTime","DateTimeRange","LatLng","FFPlace","FFUploadedFile","DocumentReference","List"]),Qf=["Struct","Record"],eg=[{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=>Pi(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=>Pi(t).some(e=>{const s=/^\s*final\s+(?:double|int|String|bool|Color|num)\s+(\w+)\s*;/gm;let r;for(;(r=s.exec(e))!==null;){const n=r[1];if(!(new RegExp(`this\\.${n}\\s*=(?!=)`).test(e)||new RegExp(`[:,]\\s*${n}\\s*=(?!=)`).test(e)))return!0}return!1}),pos:`class W extends StatefulWidget { const W({required this.value}); final double value; }`,neg:`class _P { @@ -24,66 +24,66 @@ class _S extends State { @override Widget build(BuildContext c) => const Size final double? width; @override _S createState() => _S(); } -class _S extends State { @override Widget build(BuildContext c) => Padding(padding: const EdgeInsets.all(8), child: const SizedBox()); }`}];function Qe(t,e,s){return{artifactId:t.id,artifactName:t.artifactName,artifactType:t.artifactType,severity:e,message:s}}function ln(t){let e="",s=0;for(;s"&&(s--,s===0))return{inner:t.slice(e+1,n),end:n+1};return null}function ng(t,e){const s=new RegExp(`class\\s+${e}\\b[^{]*\\{`).exec(t);if(!s)return null;let n=0;for(let r=s.index+s[0].length-1;rrg(t).usable);function og(t=""){const e=ln(t);return ig.filter(s=>s.detect(e)).map(({id:s,severity:n,message:r})=>({id:s,severity:n,message:r}))}function ag(t){const e=[],s=t.matchAll(/\bFuture\b/g);for(const n of s){let r=n.index+6,i=null;const o=r;for(;ro;if(t[r]==="<"){const u=sg(t,r);if(!u||(i=u.inner.replace(/\s+/g," ").trim(),r=u.end,!/\s/.test(t[r]||"")))continue;for(;rtc(o.functionName)===n);if(r)return r;const i=o=>!o.functionName.startsWith("_");return s.find(i)||s[0]}function Nr(t=""){return Array.from(ln(t).matchAll(/\b(?:class|enum)\s+([A-Za-z_]\w*)/g),e=>e[1])}function lg(t="",e=""){return ra(t,e)?.returnType||null}function sc(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 cg(t,e){const s=Nr(e);if(s.length===0)return null;const r=String(t||"").split("/").pop().replace(/\.dart$/,"");if(s.some(l=>sc(l)===r)||s.length>1)return null;const[o]=s,a=`${sc(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 ia(t){return String(t||"").replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,"")}function ug(t,e,s=""){const n=ra(e,s)?.functionName;if(!n)return null;const r=String(t||"").split("/").pop(),i=na(r,"A");if(i===n)return null;const o=`${ia(n)}.dart`;return`File name "${r}" does not match Action "${n}". FlutterFlow derives the action from the file name, so it looks for "${i}" and reports Action "${i}" declaration not found. Rename the file to "${o}" - FlutterFlow puts an underscore before every capital - or rename the function to "${i}".`}function dg(t="",e=""){return ra(t,e)!==null}function hg(t,e=new Set){return(t?.match(/[A-Za-z_]\w*/g)||[]).filter(n=>Qf.has(n)?!1:!eg.some(i=>n.endsWith(i))||e.has(n))}function pg(t,{functionName:e="",declaredTypes:s=new Set}={}){const n=lg(t,e),r=hg(n,s);if(r.length===0)return null;const[i]=r;let o;return s.has(i)?o=`uses Code File type "${i}", which FlutterFlow cannot process as an Action Return Value`:n===i?o="is not a FlutterFlow Action Return Value":o=`uses type "${i}", which is not a FlutterFlow Action Return Value`,`CustomAction return type "${n}" ${o}. Return JSON (Future) or an existing FlutterFlow Data Type (*Struct) instead.`}function fg(t,e={}){const s=[],n=t.fileName||"",r=t.code||"";if(Xf.has(t.artifactType)||s.push(Qe(t,"error",`Unsupported artifact type "${t.artifactType}".`)),n.endsWith(".dart")||s.push(Qe(t,"error","FlutterFlow custom code artifacts must use .dart files.")),!r.trim())return s.push(Qe(t,"warning","Generated artifact has no Dart code yet.")),s;if(t.artifactType==="CustomWidget"){/class\s+\w+\s+extends\s+(StatelessWidget|StatefulWidget)/.test(r)||s.push(Qe(t,"warning","CustomWidget code should declare a widget class extending StatelessWidget or StatefulWidget."));for(const i of og(r))s.push(Qe(t,i.severity,i.message))}if(t.artifactType==="CustomAction"&&!dg(r,t.artifactName)&&s.push(Qe(t,"warning","CustomAction code should expose an async Future function callable from FlutterFlow.")),t.artifactType==="CustomAction"){const i=e.declaredTypes||new Set(Nr(r)),o=pg(r,{functionName:t.artifactName,declaredTypes:i});o&&s.push(Qe(t,"error",o));const a=ug(n,r,t.artifactName);a&&s.push(Qe(t,"error",a))}if(t.artifactType==="CustomFunction"&&/class\s+\w+\s+extends\s+(StatelessWidget|StatefulWidget)/.test(r)&&s.push(Qe(t,"warning","CustomFunction should be a callable function, not a widget class.")),t.artifactType==="CustomClass"||t.artifactType==="CodeFile"){const i=cg(n,r);i&&s.push(Qe(t,"info",i))}return s}function gg(t){const e=Array.isArray(t?.artifacts)?t.artifacts:[],s=new Set(e.flatMap(i=>Nr(i.code||""))),n=e.flatMap(i=>fg(i,{declaredTypes:s})),r=e.map(i=>({artifactId:i.id,fileName:i.fileName,pathHint:ec[i.artifactType]||ec.CodeFile}));return{valid:n.every(i=>i.severity!=="error"),findings:n,deployHints:r}}const nc="// DO NOT REMOVE OR MODIFY THE CODE ABOVE!";function rc(t){return(/^\s*import\s+['"]([^'"]+)['"]/.exec(t)||[])[1]||null}function mg(t=""){const e=t.indexOf(nc);return e===-1?t:t.slice(e+nc.length).replace(/^\s*\n/,"")}const vg=/^\s*import\s+['"][^'"]+['"]\s*;\s*(?:\/\/.*)?$/;function _g(t="",e=""){const s=mg(t),n=new Set((e.match(/^\s*import .*$/gm)||[]).map(rc).filter(Boolean)),r=s.split(` -`).filter(i=>{const o=rc(i);return o===null||!n.has(o)?!0:!vg.test(i)}).join(` -`).replace(/^\s*\/\/ Automatic FlutterFlow imports\s*$/m,"").replace(/^\s*\n+/,"");return e+r}const yg=new Set(["flutter","flutter_test","flutter_driver","flutter_localizations"]);function wd(t){let e="",s=0;for(;s{const n=s.name||s.package;if(!n||n==="flutter")return e;const r=s.versionRequired||s.required;return e[n]=r&&s.version||"",e},{})}function Sg(t){const e=new Map,s=new Map,n=[];for(const r of t)e.has(r.fileName)?n.push(`Duplicate deploy file name "${r.fileName}" for artifacts "${e.get(r.fileName)}" and "${r.artifactId}".`):e.set(r.fileName,r.artifactId),s.has(r.path)?n.push(`Duplicate deploy path "${r.path}" for artifacts "${s.get(r.path)}" and "${r.artifactId}".`):s.set(r.path,r.artifactId);return n}function xg(t,e={}){const s=Array.isArray(t?.artifacts)?t.artifacts:[],r=(e.selectedArtifactIds||t?.deployOrder||s.map(p=>p.id)).map(p=>s.find(f=>f.id===p)).filter(Boolean),i=[...t?.warnings||[]];let o=[];r.forEach(p=>{const f=Eg(p),g=p.fixedCode||p.code||"",m=p.codeType||wg[p.artifactType]||Ne.OTHER;g.trim()||i.push(`${p.artifactName||p.id} has no generated code.`),o.push({artifactId:p.id,artifactName:p.artifactName,artifactType:p.artifactType,fileName:f,content:g,type:m,path:p.deployPath||bg(f,m),deployPath:p.deployPath||"",deployMode:"customCodeSync"})});const a="lib/flutter_flow/custom_functions.dart",l=o.map((p,f)=>({entry:p,index:f})).filter(({entry:p})=>p.type===Ne.FUNCTION&&p.path===a);if(l.length>1){const p=l[0],f={...p.entry,artifactId:l.map(({entry:m})=>m.artifactId).join("+"),artifactName:p.entry.artifactName,content:l.map(({entry:m})=>`// ${m.artifactId} -${m.content}`).join(` +class _S extends State { @override Widget build(BuildContext c) => Padding(padding: const EdgeInsets.all(8), child: const SizedBox()); }`}];function Qe(t,e,s){return{artifactId:t.id,artifactName:t.artifactName,artifactType:t.artifactType,severity:e,message:s}}function ar(t){let e="",s=0;for(;s"&&(s--,s===0))return{inner:t.slice(e+1,r),end:r+1};return null}function sg(t,e){const s=new RegExp(`class\\s+${e}\\b[^{]*\\{`).exec(t);if(!s)return null;let r=0;for(let n=s.index+s[0].length-1;nrg(t).usable);function ig(t=""){const e=ar(t);return ng.filter(s=>s.detect(e)).map(({id:s,severity:r,message:n})=>({id:s,severity:r,message:n}))}function og(t){const e=[],s=t.matchAll(/\bFuture\b/g);for(const r of s){let n=r.index+6,i=null;const o=n;for(;no;if(t[n]==="<"){const u=tg(t,n);if(!u||(i=u.inner.replace(/\s+/g," ").trim(),n=u.end,!/\s/.test(t[n]||"")))continue;for(;ntc(o.functionName)===r);if(n)return n;const i=o=>!o.functionName.startsWith("_");return s.find(i)||s[0]}function Nn(t=""){return Array.from(ar(t).matchAll(/\b(?:class|enum)\s+([A-Za-z_]\w*)/g),e=>e[1])}function ag(t="",e=""){return na(t,e)?.returnType||null}function sc(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 lg(t,e){const s=Nn(e);if(s.length===0)return null;const n=String(t||"").split("/").pop().replace(/\.dart$/,"");if(s.some(l=>sc(l)===n)||s.length>1)return null;const[o]=s,a=`${sc(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 ia(t){return String(t||"").replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,"")}function cg(t,e,s=""){const r=na(e,s)?.functionName;if(!r)return null;const n=String(t||"").split("/").pop(),i=ra(n,"A");if(i===r)return null;const o=`${ia(r)}.dart`;return`File name "${n}" does not match Action "${r}". FlutterFlow derives the action from the file name, so it looks for "${i}" and reports Action "${i}" declaration not found. Rename the file to "${o}" - FlutterFlow puts an underscore before every capital - or rename the function to "${i}".`}function ug(t="",e=""){return na(t,e)!==null}function dg(t,e=new Set){return(t?.match(/[A-Za-z_]\w*/g)||[]).filter(r=>Xf.has(r)?!1:!Qf.some(i=>r.endsWith(i))||e.has(r))}function hg(t,{functionName:e="",declaredTypes:s=new Set}={}){const r=ag(t,e),n=dg(r,s);if(n.length===0)return null;const[i]=n;let o;return s.has(i)?o=`uses Code File type "${i}", which FlutterFlow cannot process as an Action Return Value`:r===i?o="is not a FlutterFlow Action Return Value":o=`uses type "${i}", which is not a FlutterFlow Action Return Value`,`CustomAction return type "${r}" ${o}. Return JSON (Future) or an existing FlutterFlow Data Type (*Struct) instead.`}function pg(t,e={}){const s=[],r=t.fileName||"",n=t.code||"";if(Zf.has(t.artifactType)||s.push(Qe(t,"error",`Unsupported artifact type "${t.artifactType}".`)),r.endsWith(".dart")||s.push(Qe(t,"error","FlutterFlow custom code artifacts must use .dart files.")),!n.trim())return s.push(Qe(t,"warning","Generated artifact has no Dart code yet.")),s;if(t.artifactType==="CustomWidget"){/class\s+\w+\s+extends\s+(StatelessWidget|StatefulWidget)/.test(n)||s.push(Qe(t,"warning","CustomWidget code should declare a widget class extending StatelessWidget or StatefulWidget."));for(const i of ig(n))s.push(Qe(t,i.severity,i.message))}if(t.artifactType==="CustomAction"&&!ug(n,t.artifactName)&&s.push(Qe(t,"warning","CustomAction code should expose an async Future function callable from FlutterFlow.")),t.artifactType==="CustomAction"){const i=e.declaredTypes||new Set(Nn(n)),o=hg(n,{functionName:t.artifactName,declaredTypes:i});o&&s.push(Qe(t,"error",o));const a=cg(r,n,t.artifactName);a&&s.push(Qe(t,"error",a))}if(t.artifactType==="CustomFunction"&&/class\s+\w+\s+extends\s+(StatelessWidget|StatefulWidget)/.test(n)&&s.push(Qe(t,"warning","CustomFunction should be a callable function, not a widget class.")),t.artifactType==="CustomClass"||t.artifactType==="CodeFile"){const i=lg(r,n);i&&s.push(Qe(t,"info",i))}return s}function fg(t){const e=Array.isArray(t?.artifacts)?t.artifacts:[],s=new Set(e.flatMap(i=>Nn(i.code||""))),r=e.flatMap(i=>pg(i,{declaredTypes:s})),n=e.map(i=>({artifactId:i.id,fileName:i.fileName,pathHint:ec[i.artifactType]||ec.CodeFile}));return{valid:r.every(i=>i.severity!=="error"),findings:r,deployHints:n}}const rc="// DO NOT REMOVE OR MODIFY THE CODE ABOVE!";function nc(t){return(/^\s*import\s+['"]([^'"]+)['"]/.exec(t)||[])[1]||null}function gg(t=""){const e=t.indexOf(rc);return e===-1?t:t.slice(e+rc.length).replace(/^\s*\n/,"")}const mg=/^\s*import\s+['"][^'"]+['"]\s*;\s*(?:\/\/.*)?$/;function vg(t="",e=""){const s=gg(t),r=new Set((e.match(/^\s*import .*$/gm)||[]).map(nc).filter(Boolean)),n=s.split(` +`).filter(i=>{const o=nc(i);return o===null||!r.has(o)?!0:!mg.test(i)}).join(` +`).replace(/^\s*\/\/ Automatic FlutterFlow imports\s*$/m,"").replace(/^\s*\n+/,"");return e+n}const _g=new Set(["flutter","flutter_test","flutter_driver","flutter_localizations"]);function wd(t){let e="",s=0;for(;s{const r=s.name||s.package;if(!r||r==="flutter")return e;const n=s.versionRequired||s.required;return e[r]=n&&s.version||"",e},{})}function Sg(t){const e=new Map,s=new Map,r=[];for(const n of t)e.has(n.fileName)?r.push(`Duplicate deploy file name "${n.fileName}" for artifacts "${e.get(n.fileName)}" and "${n.artifactId}".`):e.set(n.fileName,n.artifactId),s.has(n.path)?r.push(`Duplicate deploy path "${n.path}" for artifacts "${s.get(n.path)}" and "${n.artifactId}".`):s.set(n.path,n.artifactId);return r}function xg(t,e={}){const s=Array.isArray(t?.artifacts)?t.artifacts:[],n=(e.selectedArtifactIds||t?.deployOrder||s.map(p=>p.id)).map(p=>s.find(f=>f.id===p)).filter(Boolean),i=[...t?.warnings||[]];let o=[];n.forEach(p=>{const f=Eg(p),m=p.fixedCode||p.code||"",g=p.codeType||wg[p.artifactType]||Ne.OTHER;m.trim()||i.push(`${p.artifactName||p.id} has no generated code.`),o.push({artifactId:p.id,artifactName:p.artifactName,artifactType:p.artifactType,fileName:f,content:m,type:g,path:p.deployPath||bg(f,g),deployPath:p.deployPath||"",deployMode:"customCodeSync"})});const a="lib/flutter_flow/custom_functions.dart",l=o.map((p,f)=>({entry:p,index:f})).filter(({entry:p})=>p.type===Ne.FUNCTION&&p.path===a);if(l.length>1){const p=l[0],f={...p.entry,artifactId:l.map(({entry:g})=>g.artifactId).join("+"),artifactName:p.entry.artifactName,content:l.map(({entry:g})=>`// ${g.artifactId} +${g.content}`).join(` -`)},g=new Set(l.slice(1).map(({index:m})=>m));o=o.filter((m,_)=>!g.has(_)),o[p.index]=f}const u={...ic(t?.dependencies),...r.reduce((p,f)=>({...p,...ic(f.dependencies)}),{})},c={};r.forEach(p=>{oa(p.code||"").forEach(f=>{f in u||(c[f]="")})});const d={...c,...u},h=Sg(o);return{bundleId:t?.id||"bundle-current",title:t?.title||"Generated artifact bundle",fileEntries:o,dependencies:d,relationships:t?.relationships||[],warnings:i,errors:h}}function kg(t){return String(t||"").match(/\bclass\s+([A-Z][A-Za-z0-9_]*)\b/)?.[1]}function Ig(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 Cg(t,e){const n=[Ig(t),kg(e.content),e.artifactName].find(r=>/^[A-Z][A-Za-z0-9_]*$/.test(String(r||"")));if(!n)throw new Error(`Cannot derive a FlutterFlow custom class name for ${t}.`);return n}function Fg(t,e=new Map){const s=[];for(const[n,r]of t.entries())r.type!=="C"||e.has(r.path)||s.push({artifactId:r.artifactId||n,className:Cg(n,r),content:r.content,fileName:n,path:r.path});return s}function Pg(t,e){const s=new Set(e.map(n=>n.path));return new Map(Array.from(t.entries()).filter(([,n])=>!s.has(n.path)))}const oc={pass:0,warning:1,fail:2},Ag=["manualActions"];function De(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function gt(...t){for(const e of t){if(typeof e=="string"&&e.trim())return e.trim();if(Array.isArray(e)&&e.length>0){const s=e.filter(n=>typeof n=="string").join(` -`);if(s)return s}}return""}function tt(t){return t==null?[]:Array.isArray(t)?t:[t]}function $g(t){const e=De(t).value??t;if(e==null||typeof e=="string"&&e.trim()==="")return null;const s=Number(e);if(Number.isFinite(s))return s;const n=String(t||"").match(/\bscore\b[^\d]{0,12}(\d{1,3})(?:\s*\/\s*100)?/i);return n?Number(n[1]):null}function We(t){return String(t||"").trim().replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function aa(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 wo(...t){return t.filter(Boolean).reduce((e,s)=>oc[s]>oc[e]?s:e,"pass")}function Ed(t,e="warning",s="review"){if(typeof t=="string")return{severity:e,message:t,suggestion:"",source:s};const n=De(t),r=gt(n.message,n.title,n.issue,n.description,n.summary);return r?{severity:aa(n.severity||n.status||n.level)||e,message:r,suggestion:gt(n.suggestion,n.fix,n.recommendation,n.action),source:n.source||s}:null}function bo(t,e="review"){const s=De(t);return[["findings","warning"],["issues","warning"],["criticalIssues","fail"],["errors","fail"],["warnings","warning"],["recommendations","warning"],["requiredFixes","fail"],["suggestions","warning"]].flatMap(([r,i])=>tt(s[r]).map(o=>Ed(o,i,e)).filter(Boolean))}function Rg(t,e,s=null){if(typeof t=="string")return{id:`${s||"bundle"}-manual-${e+1}`,title:t,detail:"",location:"",timing:"unspecified",artifactId:s,source:"Code Review"};const n=De(t),r=gt(n.title,n.action,n.step,n.message,n.name,n.description);return r?{id:n.id||`${s||"bundle"}-manual-${e+1}`,title:r,detail:gt(n.detail,n.instructions,n.description),location:gt(n.location,n.flutterFlowPath,n.path),timing:gt(n.timing,n.phase)||"unspecified",artifactId:s,source:gt(n.source)||"Code Review"}:null}function Eo(t,e=null){const s=De(t);return Ag.flatMap(n=>tt(s[n])).map((n,r)=>Rg(n,r,e)).filter(Boolean)}function Tg(t){let e=typeof t=="string"?_o(t):t;if(!e&&typeof t=="string")return{rawText:t,root:{}};const s=De(e);typeof s.content=="string"&&(e=_o(s.content)||e);const n=De(e),r=De(n.reviewResult||n.codeReview||n.result);return{rawText:"",root:Object.keys(r).length?r:n}}function Ng(t,e){const s=[e.id,e.fileName,e.artifactName].map(We);return t.find(n=>{const r=De(n);return[r.id,r.fileName,r.artifactName,r.name].map(We).some(i=>i&&s.includes(i))})||null}function Mg(t,e){return tt(t?.metadata?.compatibility?.deployHints).find(r=>We(r?.artifactId)===We(e.id)||We(r?.fileName)===We(e.fileName))?.pathHint||""}function Lg(t,e){return tt(t?.relationships).filter(s=>We(s?.from)===We(e.id)||We(s?.to)===We(e.id))}function Og(t,e){return tt(t?.metadata?.compatibility?.findings).filter(s=>!s?.artifactId||We(s.artifactId)===We(e.id)).map(s=>Ed(s,"warning","Compatibility check")).filter(Boolean)}function Dg(t,e,s,n){const r=Ng(e,s),i=De(r?.review||r||s.review),o=Object.keys(i).length>0,a=[...bo(i),...Og(t,s)],l=Eo(i,s.id),u=aa(i.status||i.verdict||i.outcome||i.result),c=a.length?wo(...a.map(h=>h.severity)):null,d=wo(u,c,o?null:"warning");return{...s,index:n,status:d,statusReason:o?gt(i.summary,i.overview,i.assessment,i.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 i.fixedSource=="string"&&i.fixedSource.trim()?i.fixedSource.trim():null,pathHint:Mg(t,s),relationships:Lg(t,s)}}function Bg({status:t,score:e,artifactPresentations:s,manualSteps:n}){const r=s.length;if(r===0&&n.length===0)return e==null?"Code review returned no overall summary and no score.":`Reviewed bundle with score ${e}/100.`;const i=s.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"}: ${i.pass} pass, ${i.warning} warn, ${i.fail} fail.`),n.length&&o.push(`Do before deploy: ${n.map(a=>a.title).join("; ")}.`),e==null&&o.push("No numeric score (0-100) was returned."),o.join(" ")}function jg({bundle:t,reviewResult:e}){const s=De(t),n=tt(s.artifacts),{root:r,rawText:i}=Tg(e),o=[r.bundleReview,r.overallReview,r.overall,r.bundleSummary,r.summaryReview,r.review].map(De).find(E=>Object.keys(E).length)||{},a=tt(r.artifacts||r.files||r.reviews),l=n.map((E,I)=>Dg(s,a,E,I)),u=bo(r),d=[...bo(o),...u],h=[...Eo(o),...Eo(r),...l.flatMap(E=>E.manualSteps)].filter((E,I,F)=>F.findIndex(P=>P.title===E.title&&P.artifactId===E.artifactId)===I),p=aa(o.status||o.verdict||o.overallStatus||r.status||r.verdict||r.overallStatus||r.outcome),f=wo(p,...d.map(E=>E.severity),...l.map(E=>E.status)),g=o.score??r.score??r.overallScore??i,m=$g(g),_=gt(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,i)||Bg({status:f,score:m,artifactPresentations:l,manualSteps:h}),w=l.reduce((E,I)=>(E[I.status]+=1,E),{pass:0,warning:0,fail:0});return{title:s.title||"Generated artifact bundle",description:s.description||"",status:f,score:m,summary:_,findings:d,manualSteps:h,artifacts:l,counts:w,reviewCoverage:{reviewed:l.filter(E=>E.reviewComplete).length,total:l.length},deployOrder:tt(s.deployOrder),relationships:tt(s.relationships),warnings:tt(s.warnings),compatibility:De(s.metadata?.compatibility)}}const Ug=/^\uFEFF/;function Os(t){let e=0,s=t.length;for(;ee&&!t[s-1].trim();)s--;return t.slice(e,s).join(` +`)},m=new Set(l.slice(1).map(({index:g})=>g));o=o.filter((g,_)=>!m.has(_)),o[p.index]=f}const u={...ic(t?.dependencies),...n.reduce((p,f)=>({...p,...ic(f.dependencies)}),{})},c={};n.forEach(p=>{oa(p.code||"").forEach(f=>{f in u||(c[f]="")})});const d={...c,...u},h=Sg(o);return{bundleId:t?.id||"bundle-current",title:t?.title||"Generated artifact bundle",fileEntries:o,dependencies:d,relationships:t?.relationships||[],warnings:i,errors:h}}function kg(t){return String(t||"").match(/\bclass\s+([A-Z][A-Za-z0-9_]*)\b/)?.[1]}function Ig(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 Cg(t,e){const r=[Ig(t),kg(e.content),e.artifactName].find(n=>/^[A-Z][A-Za-z0-9_]*$/.test(String(n||"")));if(!r)throw new Error(`Cannot derive a FlutterFlow custom class name for ${t}.`);return r}function Fg(t,e=new Map){const s=[];for(const[r,n]of t.entries())n.type!=="C"||e.has(n.path)||s.push({artifactId:n.artifactId||r,className:Cg(r,n),content:n.content,fileName:r,path:n.path});return s}function Pg(t,e){const s=new Set(e.map(r=>r.path));return new Map(Array.from(t.entries()).filter(([,r])=>!s.has(r.path)))}const oc={pass:0,warning:1,fail:2},Ag=["manualActions"];function De(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function gt(...t){for(const e of t){if(typeof e=="string"&&e.trim())return e.trim();if(Array.isArray(e)&&e.length>0){const s=e.filter(r=>typeof r=="string").join(` +`);if(s)return s}}return""}function tt(t){return t==null?[]:Array.isArray(t)?t:[t]}function $g(t){const e=De(t).value??t;if(e==null||typeof e=="string"&&e.trim()==="")return null;const s=Number(e);if(Number.isFinite(s))return s;const r=String(t||"").match(/\bscore\b[^\d]{0,12}(\d{1,3})(?:\s*\/\s*100)?/i);return r?Number(r[1]):null}function We(t){return String(t||"").trim().replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function aa(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 wo(...t){return t.filter(Boolean).reduce((e,s)=>oc[s]>oc[e]?s:e,"pass")}function bd(t,e="warning",s="review"){if(typeof t=="string")return{severity:e,message:t,suggestion:"",source:s};const r=De(t),n=gt(r.message,r.title,r.issue,r.description,r.summary);return n?{severity:aa(r.severity||r.status||r.level)||e,message:n,suggestion:gt(r.suggestion,r.fix,r.recommendation,r.action),source:r.source||s}:null}function bo(t,e="review"){const s=De(t);return[["findings","warning"],["issues","warning"],["criticalIssues","fail"],["errors","fail"],["warnings","warning"],["recommendations","warning"],["requiredFixes","fail"],["suggestions","warning"]].flatMap(([n,i])=>tt(s[n]).map(o=>bd(o,i,e)).filter(Boolean))}function Rg(t,e,s=null){if(typeof t=="string")return{id:`${s||"bundle"}-manual-${e+1}`,title:t,detail:"",location:"",timing:"unspecified",artifactId:s,source:"Code Review"};const r=De(t),n=gt(r.title,r.action,r.step,r.message,r.name,r.description);return n?{id:r.id||`${s||"bundle"}-manual-${e+1}`,title:n,detail:gt(r.detail,r.instructions,r.description),location:gt(r.location,r.flutterFlowPath,r.path),timing:gt(r.timing,r.phase)||"unspecified",artifactId:s,source:gt(r.source)||"Code Review"}:null}function Eo(t,e=null){const s=De(t);return Ag.flatMap(r=>tt(s[r])).map((r,n)=>Rg(r,n,e)).filter(Boolean)}function Tg(t){let e=typeof t=="string"?_o(t):t;if(!e&&typeof t=="string")return{rawText:t,root:{}};const s=De(e);typeof s.content=="string"&&(e=_o(s.content)||e);const r=De(e),n=De(r.reviewResult||r.codeReview||r.result);return{rawText:"",root:Object.keys(n).length?n:r}}function Ng(t,e){const s=[e.id,e.fileName,e.artifactName].map(We);return t.find(r=>{const n=De(r);return[n.id,n.fileName,n.artifactName,n.name].map(We).some(i=>i&&s.includes(i))})||null}function Mg(t,e){return tt(t?.metadata?.compatibility?.deployHints).find(n=>We(n?.artifactId)===We(e.id)||We(n?.fileName)===We(e.fileName))?.pathHint||""}function Lg(t,e){return tt(t?.relationships).filter(s=>We(s?.from)===We(e.id)||We(s?.to)===We(e.id))}function Og(t,e){return tt(t?.metadata?.compatibility?.findings).filter(s=>!s?.artifactId||We(s.artifactId)===We(e.id)).map(s=>bd(s,"warning","Compatibility check")).filter(Boolean)}function Dg(t,e,s,r){const n=Ng(e,s),i=De(n?.review||n||s.review),o=Object.keys(i).length>0,a=[...bo(i),...Og(t,s)],l=Eo(i,s.id),u=aa(i.status||i.verdict||i.outcome||i.result),c=a.length?wo(...a.map(h=>h.severity)):null,d=wo(u,c,o?null:"warning");return{...s,index:r,status:d,statusReason:o?gt(i.summary,i.overview,i.assessment,i.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 i.fixedSource=="string"&&i.fixedSource.trim()?i.fixedSource.trim():null,pathHint:Mg(t,s),relationships:Lg(t,s)}}function Bg({status:t,score:e,artifactPresentations:s,manualSteps:r}){const n=s.length;if(n===0&&r.length===0)return e==null?"Code review returned no overall summary and no score.":`Reviewed bundle with score ${e}/100.`;const i=s.reduce((a,l)=>(a[l.status]+=1,a),{pass:0,warning:0,fail:0}),o=[];return t&&o.push(`Overall verdict: ${t}.`),n&&o.push(`${n} artifact${n===1?"":"s"}: ${i.pass} pass, ${i.warning} warn, ${i.fail} fail.`),r.length&&o.push(`Do before deploy: ${r.map(a=>a.title).join("; ")}.`),e==null&&o.push("No numeric score (0-100) was returned."),o.join(" ")}function jg({bundle:t,reviewResult:e}){const s=De(t),r=tt(s.artifacts),{root:n,rawText:i}=Tg(e),o=[n.bundleReview,n.overallReview,n.overall,n.bundleSummary,n.summaryReview,n.review].map(De).find(b=>Object.keys(b).length)||{},a=tt(n.artifacts||n.files||n.reviews),l=r.map((b,I)=>Dg(s,a,b,I)),u=bo(n),d=[...bo(o),...u],h=[...Eo(o),...Eo(n),...l.flatMap(b=>b.manualSteps)].filter((b,I,F)=>F.findIndex(P=>P.title===b.title&&P.artifactId===b.artifactId)===I),p=aa(o.status||o.verdict||o.overallStatus||n.status||n.verdict||n.overallStatus||n.outcome),f=wo(p,...d.map(b=>b.severity),...l.map(b=>b.status)),m=o.score??n.score??n.overallScore??i,g=$g(m),_=gt(o.headline,o.summary,o.executiveSummary,o.overview,o.assessment,o.conclusion,n.overallSummary,n.headline,n.summary,n.executiveSummary,n.overview,n.assessment,n.conclusion,i)||Bg({status:f,score:g,artifactPresentations:l,manualSteps:h}),w=l.reduce((b,I)=>(b[I.status]+=1,b),{pass:0,warning:0,fail:0});return{title:s.title||"Generated artifact bundle",description:s.description||"",status:f,score:g,summary:_,findings:d,manualSteps:h,artifacts:l,counts:w,reviewCoverage:{reviewed:l.filter(b=>b.reviewComplete).length,total:l.length},deployOrder:tt(s.deployOrder),relationships:tt(s.relationships),warnings:tt(s.warnings),compatibility:De(s.metadata?.compatibility)}}const Ug=/^\uFEFF/;function Os(t){let e=0,s=t.length;for(;ee&&!t[s-1].trim();)s--;return t.slice(e,s).join(` `)}function Hg(t){const e=String(t??"").replace(Ug,"");if(!e.trim())return"";const s=e.split(` -`),n=c=>{const d=c.trim();return/^`{3,}[A-Za-z0-9+#_.-]*$/.test(d)?c.length-c.trimStart().length:-1};let r=0,i=-1;const o=[];{let c=0;for(let d=0;d=0&&(r++,i<0&&(i=d),o.push(c+h)),c+=s[d].length+1}}if(r===0)return Os(s);{const c=So(e);if(!c.error&&o.every(h=>lc(h,c.commentAndStringRanges)))return Os(s)}if(r===1){const c=Os(s.slice(0,i)),d=Os(s.slice(i+1));return d.length>=c.length?d:c}const a=[];let l=null;for(let c=0;c{const d=c.trim();return/^`{3,}[A-Za-z0-9+#_.-]*$/.test(d)?c.length-c.trimStart().length:-1};let n=0,i=-1;const o=[];{let c=0;for(let d=0;d=0&&(n++,i<0&&(i=d),o.push(c+h)),c+=s[d].length+1}}if(n===0)return Os(s);{const c=So(e);if(!c.error&&o.every(h=>lc(h,c.commentAndStringRanges)))return Os(s)}if(n===1){const c=Os(s.slice(0,i)),d=Os(s.slice(i+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(` +${d}`,{commentAndStringRanges:m}=So(f),g=p.length+1+h;if(lc(g,m)){l.push(d);continue}a.push(Os(l)),l=null}const u=a.filter(c=>c.length>0);return u.length===0?"":u.join(` -`)}function Wg(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 Sd(t){const e=Wg(t);return Array.from(e.matchAll(/class\s+([A-Z]\w*)\s+extends\s+[A-Za-z_]\w*Widget\b/g),s=>s[1])}function xd(t){return`${ia(t)}.dart`}function zg(t){return na(t,"W")}const ac={"(":")","[":"]","{":"}"},qg={")":"(","]":"[","}":"{"},Vg=/[A-Za-z0-9_]/;function So(t){const e=[{kind:"code",opener:null,openedLine:0}],s=[];let n=1,r=0;const i=(c,d)=>{(c===` +`)}function Wg(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 Ed(t){const e=Wg(t);return Array.from(e.matchAll(/class\s+([A-Z]\w*)\s+extends\s+[A-Za-z_]\w*Widget\b/g),s=>s[1])}function Sd(t){return`${ia(t)}.dart`}function zg(t){return ra(t,"W")}const ac={"(":")","[":"]","{":"}"},qg={")":"(","]":"[","}":"{"},Vg=/[A-Za-z0-9_]/;function So(t){const e=[{kind:"code",opener:null,openedLine:0}],s=[];let r=1,n=0;const i=(c,d)=>{(c===` `||c==="\r"&&d!==` -`)&&n++};let o=null;const a=()=>{for(const c of e)(c.kind==="string"||c.kind==="block-comment"||c.kind==="line-comment")&&s.push({start:c.startIndex,end:t.length})};for(;r0?t[r-1]:"",f=r>1?t[r-2]:"",g=(p==="r"||p==="R")&&!Vg.test(f);e.push({kind:"string",quote:c,triple:h,raw:g,startIndex:r,openedLine:n}),r+=h?3:1;continue}if(ac[c]){e.push({kind:"code",opener:c,openedLine:n}),r++;continue}if(qg[c]){if(d.interpolation&&c==="}"){e.pop(),r++;continue}if(d.opener&&ac[d.opener]===c){e.pop(),r++;continue}return d.opener?(a(),{error:o??`line ${n}: "${c}" closes nothing - "${d.opener}" opened on line ${d.openedLine} is still open`,commentAndStringRanges:s}):(a(),{error:o??`line ${n}: unexpected "${c}" with no matching opener`,commentAndStringRanges:s})}i(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:s}}function Gg(t){return So(String(t??"")).error}function lc(t,e){return e.some(({start:s,end:n})=>t>=s&&ttypeof s=="string"?s:s?.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 Kg=["gmail.com","googlemail.com","outlook.com","hotmail.com","live.com","msn.com"],Jg="MAGIC_LINK_SENT",Yg="PLUS_ALIAS_REJECTED",Zg="Please enter your primary email address. Plus aliases (such as {email}) are not allowed for {domain} accounts.",Mr={allowlistedDomains:Kg,successCode:Jg,validationCode:Yg,messageTemplate:Zg},Xg=new Set(Mr.allowlistedDomains),Qg=Mr.successCode,Un=Mr.validationCode;function Lr(t){return typeof t=="string"?t.trim():""}function em(t){const e=Lr(t),s=e.lastIndexOf("@");if(s<=0||s===e.length-1)return!1;const n=e.slice(0,s),r=e.slice(s+1).toLowerCase();return Xg.has(r)?n.includes("+"):!1}function tm(t,e){return Mr.messageTemplate.replaceAll("{email}",t).replaceAll("{domain}",e)}function Id(t){if(!em(t))return null;const e=Lr(t),s=e.lastIndexOf("@"),n=e.slice(s+1).toLowerCase();return tm(e,n)}function sm(t,e){return t?.code===Un?t.message||Id(e)||"Please enter your primary email address.":t?.code===Qg||!t?.code?`Check your email — we sent a link to ${Lr(e)}`:t.message||"Something went wrong. Please try again."}const nm=/^dependencies\s*:\s*(?:#.*)?$/,rm=/^(?:"([^"]+)"|'([^']+)'|([A-Za-z_][A-Za-z0-9_-]*))\s*:/;function Or(t){const e=t.match(rm);return e?e[1]??e[2]??e[3]:null}function fn(t){const e=t.trim();return e===""||e.startsWith("#")}function xs(t){const e=t.match(/^(\s*)/);return e?e[1].length:0}function la(t,e){const s=t.findIndex(i=>e.test(i));if(s===-1)return null;let n=s,r=null;for(let i=s+1;i=0.0.0"}`}function lm(t,e={}){const s=String(t||""),n=Object.entries(e).filter(([u])=>u&&u!=="flutter");if(n.length===0)return{yaml:s,added:[],alreadyPresent:[]};const r=s.split(` -`),i=new Set(Fd(s)),o=[],a=[];for(const[u,c]of n)i.has(u)?a.push(u):(o.push([u,c]),i.add(u));if(o.length===0)return{yaml:s,added:[],alreadyPresent:a};const l=ca(r);if(l){const u=o.map(([c,d])=>cc(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(cc(" ",u,c))});return{yaml:r.join(` -`),added:o.map(([u])=>u),alreadyPresent:a}}function cm(t,e={}){const s=String(t||""),n=Object.entries(e).filter(([l])=>l&&l!=="flutter");if(n.length===0)return{yaml:s,overridden:[],skipped:[]};const r=s.split(` -`),i=Br(s),o=[],a=[];for(const[l,u]of n){const c=i.get(l);if(!c||!c.isScalar||!String(u||"").trim()){a.push(l);continue}const d=" ".repeat(xs(r[c.lineIndex]));r[c.lineIndex]=`${d}${l}: ${Ad(String(u).trim())}${c.comment}`,o.push({name:l,from:c.constraint,to:u})}return{yaml:r.join(` -`),overridden:o,skipped:a}}function $d(t){const e=String(t||""),s=[];return e.trim()?(/^name:\s*\S+/m.test(e)||s.push("pubspec.yaml missing name field"),ca(e.split(` -`))||s.push("pubspec.yaml missing dependencies section"),Fd(e).includes("flutter")||s.push("pubspec.yaml missing Flutter SDK dependency"),{valid:s.length===0,errors:s}):(s.push("pubspec.yaml is empty"),{valid:!1,errors:s})}const um=">=3.0.0 <4.0.0";function xo(t){const e=String(t||"").trim(),s=e[0];return s!=="'"&&s!=='"'||e[e.length-1]!==s?e:e.slice(1,-1).replaceAll(`${s}${s}`,s)}function dm(t=""){const e=bd(t).filter(s=>!s.startsWith("dart:")&&!s.startsWith("package:"));return{selfContained:e.length===0,unresolvableImports:e}}function uc(t,e,s){const n=[];for(const[r,i]of t){if(i.isScalar){e[r]=xo(i.constraint);continue}if(i.sourceKey==="sdk"){s.add(r);continue}if(i.sourceKey===null&&i.version){e[r]=xo(i.version);continue}n.push(r)}return n}function hm(t){const e=new Set,s={},n={},r=uc(Br(t),s,e);r.push(...uc(om(t,"dependency_overrides"),n,e));const i=new Set([...Object.keys(s),...e]),{sdk:o}=Pd(t);return{sdkConstraint:xo(o)||um,dependencies:s,overrides:n,sdkPackages:[...e].sort(),availablePackages:i,unrepresentable:r}}function pm(t,e,s){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 ${s.join(", ")}, which your project's pubspec.yaml does not declare with a version constraint, so it could not be compiled before the deploy.`}function fm(t,e){return`${t} was not compiled before deploying: your project declares ${e.join(", ")} from a source that cannot be reproduced outside it, and whether the packages ${t} imports depend on one of them transitively cannot be checked before the deploy, so package resolution could not be matched exactly.`}function gm(t,e){const{sdkConstraint:s,dependencies:n,overrides:r,sdkPackages:i,availablePackages:o,unrepresentable:a}=hm(e),l={sdkConstraint:s,dependencies:n,overrides:r,sdkPackages:i},u=[],c=[];for(const d of t){const{className:h,content:p}=d,f=oa(p),g=f.filter(w=>a.includes(w));if(g.length>0){c.push({className:h,reason:`${h} was not compiled before deploying: it imports ${g.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:m}=dm(p),_=f.filter(w=>!o.has(w));if(m.length>0||_.length>0){c.push({className:h,reason:pm(h,m,_)});continue}if(a.length>0&&bd(p).some(w=>w.startsWith("package:"))){c.push({className:h,reason:fm(h,a)});continue}u.push({fileName:`${ia(h)}.dart`,content:p})}return{manifest:l,sources:u,skipped:c}}function dc(t,e){const s=`${t}${e}`.split(` -`),n=s.pop()??"",r=[];for(const i of s){const o=Rd(i);o&&r.push(o)}return{events:r,buffer:n}}function mm(t){const e=Rd(t);return e?[e]:[]}function Rd(t){const e=t.trim();if(!e)return null;try{const s=JSON.parse(e);return s&&typeof s=="object"&&!Array.isArray(s)?s:null}catch{return null}}async function vm(t,e={}){const{onPhase:s,onLog:n}=e;let r=null,i="";const o=a=>{if(a.event==="phase"){a.message&&s&&s(a.message);return}if(a.event==="log"){a.message&&n&&n(a.message);return}r=a};if(t.body?.getReader){const a=t.body.getReader(),l=new TextDecoder;for(;;){const{done:u,value:c}=await a.read();if(u)break;const d=dc(i,l.decode(c,{stream:!0}));i=d.buffer,d.events.forEach(o)}}else{const a=dc("",await t.text());i=a.buffer,a.events.forEach(o)}return mm(i).forEach(o),r?{...r,success:r.success===!0||r.success===void 0&&t.ok}:{success:!1,error:t.ok?"The FlutterFlow deploy runner closed the connection before it finished.":`FlutterFlow custom class provisioning failed (HTTP ${t.status}).`}}const _m=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;function wt(t){const e=String(t||"").trim().match(_m);return e?{major:Number(e[1]),minor:Number(e[2]),patch:Number(e[3]),prerelease:e[4]?e[4].split("."):[]}:null}function ym(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 s=0;s0)}function bm(t){const e=wt(t);return e?e.major>0?`${e.major+1}.0.0`:`0.${e.minor+1}.0`:null}function ua(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 wt(o)?{min:o,minInclusive:!0,max:bm(o),maxInclusive:!1}:null}if(wt(e))return{min:e,minInclusive:!0,max:e,maxInclusive:!0};const s={min:null,minInclusive:!1,max:null,maxInclusive:!1},n=/(>=|<=|>|<)\s*([0-9][0-9A-Za-z.+-]*)/g;let r=!1,i;for(;(i=n.exec(e))!==null;){const[,o,a]=i;if(!wt(a))return null;r=!0,o===">="||o===">"?(s.min=a,s.minInclusive=o===">="):(s.max=a,s.maxInclusive=o==="<=")}return r?s:null}function hc(t,e){const s=ua(t);if(!s||!wt(e))return!1;if(s.min!==null){const n=_r(e,s.min);if(n<0||n===0&&!s.minInclusive)return!1}if(s.max!==null){const n=_r(e,s.max);if(n>0||n===0&&!s.maxInclusive)return!1}return!0}function Em(t,e){const s=ua(t);if(!s||!wt(e))return!1;if(s.max===null)return!0;const n=_r(s.max,e);return n>0?!0:n===0&&s.maxInclusive}function rs(t){const e=ua(t);return e?e.min:null}const Sm="https://pub.dev/api/packages/",xm=8e3;function km(t,e={}){const{dartSdkFloor:s=null,flutterSdkFloor:n=null}=e,r=Array.isArray(t?.versions)?t.versions:[];let i=null;for(const o of r){const a=o?.version;if(!a||o.retracted||wm(a))continue;const l=o.pubspec?.environment||{};s&&l.sdk&&!hc(l.sdk,s)||n&&l.flutter&&!hc(l.flutter,n)||(!i||_r(a,i)>0)&&(i=a)}return i?{version:i,constraint:`^${i}`}:null}async function Im(t,e={}){const{dartSdkFloor:s=null,flutterSdkFloor:n=null,fetchImpl:r=fetch}=e;let i;try{const a=await r(`${Sm}${encodeURIComponent(t)}`,{signal:AbortSignal.timeout(xm)});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}"`};i=await a.json()}catch(a){return{name:t,constraint:null,version:null,error:`could not reach pub.dev for "${t}" (${a.message})`}}const o=km(i,{dartSdkFloor:s,flutterSdkFloor:n});return o?{name:t,...o,error:null}:{name:t,constraint:null,version:null,error:s?`no published "${t}" release supports Dart ${s}`:`no published "${t}" release could be read`}}async function Cm(t,e={}){const s=await Promise.all(t.map(n=>Im(n,e)));return new Map(s.map(({name:n,...r})=>[n,r]))}async function Fm(t,e={},s={}){const{resolveVersions:n=Cm}=s,r=Object.entries(e).filter(([c])=>c&&c!=="flutter"),i=Pd(t),o={dartSdkFloor:rs(i.sdk),flutterSdkFloor:rs(i.flutter)},a={additions:{},overrides:{},kept:[],warnings:[],sdk:o};if(r.length===0)return a;const l=Br(t),u=[];for(const[c,d]of r){const h=l.get(c);if(!h){u.push(c);continue}const p=rs(d);if(!p){a.kept.push({name:c,constraint:h.constraint});continue}if(!h.isScalar){a.warnings.push(`"${c}" is declared in your project from a git, path, or SDK source, but the generated code needs at least ${p}. Left as-is — update it yourself if the build fails.`),a.kept.push({name:c,constraint:h.constraint});continue}if(Em(h.constraint,p)){a.kept.push({name:c,constraint:h.constraint});continue}a.overrides[c]=`^${p}`,a.warnings.push(`"${c}" was pinned to ${h.constraint} in your project, which cannot resolve the ${p} the generated code needs. Raising it to ^${p} — this changes a dependency the rest of your app also uses.`)}if(u.length>0){const c=await n(u,o);for(const d of u){const h=c.get(d);if(h?.constraint){a.additions[d]=h.constraint;continue}const p=e[d]||"";if(rs(p)){a.additions[d]=`^${rs(p)}`,a.warnings.push(`Could not confirm "${d}" version on pub.dev (${h?.error||"lookup failed"}). Using ^${rs(p)} from the AI's recommendation — verify this is current.`);continue}a.additions[d]=">=0.0.0",a.warnings.push(`Could not determine a version for "${d}" (${h?.error||"lookup failed"}) and the AI supplied none. Added with a wide-open >=0.0.0 constraint — pin a concrete version in FlutterFlow before deploying.`)}}return a}const Pm={"&":"&","<":"<",">":">",'"':""","'":"'"};function bt(t){return String(t??"").replace(/[&<>"']/g,e=>Pm[e])}function j(t){return t?bt(t).replace(/\n/g,"
    "):""}function It(t){return bt(t).replace(/\r?\n/g," ")}function Am(t,e={}){const s=t?.pipelineStep;if(s!=null&&e[s]!=null)return e[s];const n=t?.message||"";return n.includes("Code Generator")?2:n.includes("Code Review")?3:1}function $m(t){const e={"Integration Audit Report":"📋","Critical Issues":"❌",Warnings:"⚠️",Recommendations:"✅","Overall Score":"📊"};for(const[s,n]of Object.entries(e))if(t.toLowerCase().includes(s.toLowerCase()))return n;return"📄"}function Rm(t){const e={critical:"❌",warning:"⚠️",recommendation:"✅",score:"📊",issue:"🔍",fix:"🔧"};for(const[s,n]of Object.entries(e))if(t.toLowerCase().includes(s.toLowerCase()))return n;return"📝"}function Tm(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 ws(t){if(!t)return"";if(typeof t!="string")return String(t);const e=/```(?:\w+)?\n?([\s\S]*?)```/,s=t.match(e);return s?s[1].trim():t.trim()}function pc(t){return t=bt(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 Td(t,e="dart",s=globalThis.hljs){if(!t)return"";const n=ws(t);try{return s.highlight(n,{language:e}).value}catch(r){console.warn("Syntax highlighting failed:",r);try{return s.highlight(n,{language:"json"}).value}catch{return bt(n)}}}function jr(t,e={}){const{highlighter:s=globalThis.hljs}=e;let n='
    ';const r=String(t??"").split(` -`);let i=!1,o="";for(const a of r){if(a.startsWith("```")){if(i){const l=Tm(o),u=Td(o.trim(),l,s);n+=`
    +`)&&r++};let o=null;const a=()=>{for(const c of e)(c.kind==="string"||c.kind==="block-comment"||c.kind==="line-comment")&&s.push({start:c.startIndex,end:t.length})};for(;n0?t[n-1]:"",f=n>1?t[n-2]:"",m=(p==="r"||p==="R")&&!Vg.test(f);e.push({kind:"string",quote:c,triple:h,raw:m,startIndex:n,openedLine:r}),n+=h?3:1;continue}if(ac[c]){e.push({kind:"code",opener:c,openedLine:r}),n++;continue}if(qg[c]){if(d.interpolation&&c==="}"){e.pop(),n++;continue}if(d.opener&&ac[d.opener]===c){e.pop(),n++;continue}return d.opener?(a(),{error:o??`line ${r}: "${c}" closes nothing - "${d.opener}" opened on line ${d.openedLine} is still open`,commentAndStringRanges:s}):(a(),{error:o??`line ${r}: unexpected "${c}" with no matching opener`,commentAndStringRanges:s})}i(c,t[n+1]),n++}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:s}}function Gg(t){return So(String(t??"")).error}function lc(t,e){return e.some(({start:s,end:r})=>t>=s&&ttypeof s=="string"?s:s?.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 Kg=["gmail.com","googlemail.com","outlook.com","hotmail.com","live.com","msn.com"],Jg="MAGIC_LINK_SENT",Yg="PLUS_ALIAS_REJECTED",Zg="Please enter your primary email address. Plus aliases (such as {email}) are not allowed for {domain} accounts.",Mn={allowlistedDomains:Kg,successCode:Jg,validationCode:Yg,messageTemplate:Zg},Xg=new Set(Mn.allowlistedDomains),Qg=Mn.successCode,jr=Mn.validationCode;function Ln(t){return typeof t=="string"?t.trim():""}function em(t){const e=Ln(t),s=e.lastIndexOf("@");if(s<=0||s===e.length-1)return!1;const r=e.slice(0,s),n=e.slice(s+1).toLowerCase();return Xg.has(n)?r.includes("+"):!1}function tm(t,e){return Mn.messageTemplate.replaceAll("{email}",t).replaceAll("{domain}",e)}function kd(t){if(!em(t))return null;const e=Ln(t),s=e.lastIndexOf("@"),r=e.slice(s+1).toLowerCase();return tm(e,r)}function sm(t,e){return t?.code===jr?t.message||kd(e)||"Please enter your primary email address.":t?.code===Qg||!t?.code?`Check your email — we sent a link to ${Ln(e)}`:t.message||"Something went wrong. Please try again."}const rm=/^dependencies\s*:\s*(?:#.*)?$/,nm=/^(?:"([^"]+)"|'([^']+)'|([A-Za-z_][A-Za-z0-9_-]*))\s*:/;function On(t){const e=t.match(nm);return e?e[1]??e[2]??e[3]:null}function pr(t){const e=t.trim();return e===""||e.startsWith("#")}function xs(t){const e=t.match(/^(\s*)/);return e?e[1].length:0}function la(t,e){const s=t.findIndex(i=>e.test(i));if(s===-1)return null;let r=s,n=null;for(let i=s+1;i=0.0.0"}`}function lm(t,e={}){const s=String(t||""),r=Object.entries(e).filter(([u])=>u&&u!=="flutter");if(r.length===0)return{yaml:s,added:[],alreadyPresent:[]};const n=s.split(` +`),i=new Set(Cd(s)),o=[],a=[];for(const[u,c]of r)i.has(u)?a.push(u):(o.push([u,c]),i.add(u));if(o.length===0)return{yaml:s,added:[],alreadyPresent:a};const l=ca(n);if(l){const u=o.map(([c,d])=>cc(l.childIndent,c,d));n.splice(l.endIndex,0,...u)}else n.length>0&&n[n.length-1].trim()!==""&&n.push(""),n.push("dependencies:"),o.forEach(([u,c])=>{n.push(cc(" ",u,c))});return{yaml:n.join(` +`),added:o.map(([u])=>u),alreadyPresent:a}}function cm(t,e={}){const s=String(t||""),r=Object.entries(e).filter(([l])=>l&&l!=="flutter");if(r.length===0)return{yaml:s,overridden:[],skipped:[]};const n=s.split(` +`),i=Bn(s),o=[],a=[];for(const[l,u]of r){const c=i.get(l);if(!c||!c.isScalar||!String(u||"").trim()){a.push(l);continue}const d=" ".repeat(xs(n[c.lineIndex]));n[c.lineIndex]=`${d}${l}: ${Pd(String(u).trim())}${c.comment}`,o.push({name:l,from:c.constraint,to:u})}return{yaml:n.join(` +`),overridden:o,skipped:a}}function Ad(t){const e=String(t||""),s=[];return e.trim()?(/^name:\s*\S+/m.test(e)||s.push("pubspec.yaml missing name field"),ca(e.split(` +`))||s.push("pubspec.yaml missing dependencies section"),Cd(e).includes("flutter")||s.push("pubspec.yaml missing Flutter SDK dependency"),{valid:s.length===0,errors:s}):(s.push("pubspec.yaml is empty"),{valid:!1,errors:s})}const um=">=3.0.0 <4.0.0";function xo(t){const e=String(t||"").trim(),s=e[0];return s!=="'"&&s!=='"'||e[e.length-1]!==s?e:e.slice(1,-1).replaceAll(`${s}${s}`,s)}function dm(t=""){const e=yg(t).filter(s=>!s.startsWith("dart:")&&!s.startsWith("package:"));return{selfContained:e.length===0,unresolvableImports:e}}function uc(t,e,s){const r=[];for(const[n,i]of t){if(i.isScalar){e[n]=xo(i.constraint);continue}if(i.sourceKey==="sdk"){s.add(n);continue}if(i.sourceKey===null&&i.version){e[n]=xo(i.version);continue}r.push(n)}return r}function hm(t){const e=new Set,s={},r={},n=uc(Bn(t),s,e);n.push(...uc(om(t,"dependency_overrides"),r,e));const i=new Set([...Object.keys(s),...e]),{sdk:o}=Fd(t);return{sdkConstraint:xo(o)||um,dependencies:s,overrides:r,sdkPackages:[...e].sort(),availablePackages:i,unrepresentable:n}}function pm(t,e,s){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 ${s.join(", ")}, which your project's pubspec.yaml does not declare with a version constraint, so it could not be compiled before the deploy.`}function fm(t,e){const{sdkConstraint:s,dependencies:r,overrides:n,sdkPackages:i,availablePackages:o,unrepresentable:a}=hm(e),l={sdkConstraint:s,dependencies:r,overrides:n,sdkPackages:i},u=[],c=[],d=a.map(h=>`Your project declares ${h} from a source that cannot be reproduced outside it, so the pre-deploy compile check runs against a scratch package graph that omits ${h}. Classes that do not import ${h} directly are still checked, but against that reduced graph, so their transitive package resolution may differ from your project's and the check is approximate for them.`);for(const h of t){const{className:p,content:f}=h,m=oa(f),g=m.filter(b=>a.includes(b));if(g.length>0){c.push({className:p,reason:`${p} was not compiled before deploying: it imports ${g.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:_}=dm(f),w=m.filter(b=>!o.has(b));if(_.length>0||w.length>0){c.push({className:p,reason:pm(p,_,w)});continue}u.push({fileName:`${ia(p)}.dart`,content:f})}return{manifest:l,sources:u,skipped:c,approximate:d}}function dc(t,e){const s=`${t}${e}`.split(` +`),r=s.pop()??"",n=[];for(const i of s){const o=$d(i);o&&n.push(o)}return{events:n,buffer:r}}function gm(t){const e=$d(t);return e?[e]:[]}function $d(t){const e=t.trim();if(!e)return null;try{const s=JSON.parse(e);return s&&typeof s=="object"&&!Array.isArray(s)?s:null}catch{return null}}async function mm(t,e={}){const{onPhase:s,onLog:r}=e;let n=null,i="";const o=a=>{if(a.event==="phase"){a.message&&s&&s(a.message);return}if(a.event==="log"){a.message&&r&&r(a.message);return}n=a};if(t.body?.getReader){const a=t.body.getReader(),l=new TextDecoder;for(;;){const{done:u,value:c}=await a.read();if(u)break;const d=dc(i,l.decode(c,{stream:!0}));i=d.buffer,d.events.forEach(o)}}else{const a=dc("",await t.text());i=a.buffer,a.events.forEach(o)}return gm(i).forEach(o),n?{...n,success:n.success===!0||n.success===void 0&&t.ok}:{success:!1,error:t.ok?"The FlutterFlow deploy runner closed the connection before it finished.":`FlutterFlow custom class provisioning failed (HTTP ${t.status}).`}}const vm=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;function wt(t){const e=String(t||"").trim().match(vm);return e?{major:Number(e[1]),minor:Number(e[2]),patch:Number(e[3]),prerelease:e[4]?e[4].split("."):[]}:null}function _m(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 s=0;s0)}function wm(t){const e=wt(t);return e?e.major>0?`${e.major+1}.0.0`:`0.${e.minor+1}.0`:null}function ua(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 wt(o)?{min:o,minInclusive:!0,max:wm(o),maxInclusive:!1}:null}if(wt(e))return{min:e,minInclusive:!0,max:e,maxInclusive:!0};const s={min:null,minInclusive:!1,max:null,maxInclusive:!1},r=/(>=|<=|>|<)\s*([0-9][0-9A-Za-z.+-]*)/g;let n=!1,i;for(;(i=r.exec(e))!==null;){const[,o,a]=i;if(!wt(a))return null;n=!0,o===">="||o===">"?(s.min=a,s.minInclusive=o===">="):(s.max=a,s.maxInclusive=o==="<=")}return n?s:null}function hc(t,e){const s=ua(t);if(!s||!wt(e))return!1;if(s.min!==null){const r=_n(e,s.min);if(r<0||r===0&&!s.minInclusive)return!1}if(s.max!==null){const r=_n(e,s.max);if(r>0||r===0&&!s.maxInclusive)return!1}return!0}function bm(t,e){const s=ua(t);if(!s||!wt(e))return!1;if(s.max===null)return!0;const r=_n(s.max,e);return r>0?!0:r===0&&s.maxInclusive}function ns(t){const e=ua(t);return e?e.min:null}const Em="https://pub.dev/api/packages/",Sm=8e3;function xm(t,e={}){const{dartSdkFloor:s=null,flutterSdkFloor:r=null}=e,n=Array.isArray(t?.versions)?t.versions:[];let i=null;for(const o of n){const a=o?.version;if(!a||o.retracted||ym(a))continue;const l=o.pubspec?.environment||{};s&&l.sdk&&!hc(l.sdk,s)||r&&l.flutter&&!hc(l.flutter,r)||(!i||_n(a,i)>0)&&(i=a)}return i?{version:i,constraint:`^${i}`}:null}async function km(t,e={}){const{dartSdkFloor:s=null,flutterSdkFloor:r=null,fetchImpl:n=fetch}=e;let i;try{const a=await n(`${Em}${encodeURIComponent(t)}`,{signal:AbortSignal.timeout(Sm)});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}"`};i=await a.json()}catch(a){return{name:t,constraint:null,version:null,error:`could not reach pub.dev for "${t}" (${a.message})`}}const o=xm(i,{dartSdkFloor:s,flutterSdkFloor:r});return o?{name:t,...o,error:null}:{name:t,constraint:null,version:null,error:s?`no published "${t}" release supports Dart ${s}`:`no published "${t}" release could be read`}}async function Im(t,e={}){const s=await Promise.all(t.map(r=>km(r,e)));return new Map(s.map(({name:r,...n})=>[r,n]))}async function Cm(t,e={},s={}){const{resolveVersions:r=Im}=s,n=Object.entries(e).filter(([c])=>c&&c!=="flutter"),i=Fd(t),o={dartSdkFloor:ns(i.sdk),flutterSdkFloor:ns(i.flutter)},a={additions:{},overrides:{},kept:[],warnings:[],sdk:o};if(n.length===0)return a;const l=Bn(t),u=[];for(const[c,d]of n){const h=l.get(c);if(!h){u.push(c);continue}const p=ns(d);if(!p){a.kept.push({name:c,constraint:h.constraint});continue}if(!h.isScalar){a.warnings.push(`"${c}" is declared in your project from a git, path, or SDK source, but the generated code needs at least ${p}. Left as-is — update it yourself if the build fails.`),a.kept.push({name:c,constraint:h.constraint});continue}if(bm(h.constraint,p)){a.kept.push({name:c,constraint:h.constraint});continue}a.overrides[c]=`^${p}`,a.warnings.push(`"${c}" was pinned to ${h.constraint} in your project, which cannot resolve the ${p} the generated code needs. Raising it to ^${p} — this changes a dependency the rest of your app also uses.`)}if(u.length>0){const c=await r(u,o);for(const d of u){const h=c.get(d);if(h?.constraint){a.additions[d]=h.constraint;continue}const p=e[d]||"";if(ns(p)){a.additions[d]=`^${ns(p)}`,a.warnings.push(`Could not confirm "${d}" version on pub.dev (${h?.error||"lookup failed"}). Using ^${ns(p)} from the AI's recommendation — verify this is current.`);continue}a.additions[d]=">=0.0.0",a.warnings.push(`Could not determine a version for "${d}" (${h?.error||"lookup failed"}) and the AI supplied none. Added with a wide-open >=0.0.0 constraint — pin a concrete version in FlutterFlow before deploying.`)}}return a}const Fm={"&":"&","<":"<",">":">",'"':""","'":"'"};function bt(t){return String(t??"").replace(/[&<>"']/g,e=>Fm[e])}function B(t){return t?bt(t).replace(/\n/g,"
    "):""}function It(t){return bt(t).replace(/\r?\n/g," ")}function Pm(t,e={}){const s=t?.pipelineStep;if(s!=null&&e[s]!=null)return e[s];const r=t?.message||"";return r.includes("Code Generator")?2:r.includes("Code Review")?3:1}function Am(t){const e={"Integration Audit Report":"📋","Critical Issues":"❌",Warnings:"⚠️",Recommendations:"✅","Overall Score":"📊"};for(const[s,r]of Object.entries(e))if(t.toLowerCase().includes(s.toLowerCase()))return r;return"📄"}function $m(t){const e={critical:"❌",warning:"⚠️",recommendation:"✅",score:"📊",issue:"🔍",fix:"🔧"};for(const[s,r]of Object.entries(e))if(t.toLowerCase().includes(s.toLowerCase()))return r;return"📝"}function Rm(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 ws(t){if(!t)return"";if(typeof t!="string")return String(t);const e=/```(?:\w+)?\n?([\s\S]*?)```/,s=t.match(e);return s?s[1].trim():t.trim()}function pc(t){return t=bt(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 Rd(t,e="dart",s=globalThis.hljs){if(!t)return"";const r=ws(t);try{return s.highlight(r,{language:e}).value}catch(n){console.warn("Syntax highlighting failed:",n);try{return s.highlight(r,{language:"json"}).value}catch{return bt(r)}}}function jn(t,e={}){const{highlighter:s=globalThis.hljs}=e;let r='
    ';const n=String(t??"").split(` +`);let i=!1,o="";for(const a of n){if(a.startsWith("```")){if(i){const l=Rm(o),u=Rd(o.trim(),l,s);r+=`
    ${u}
    `,o="",i=!1}else i=!0;continue}if(i){o+=a+` -`;continue}if(a.startsWith("# ")){const l=a.substring(2).trim();n+=`
    +`;continue}if(a.startsWith("# ")){const l=a.substring(2).trim();r+=`

    - ${$m(l)} + ${Am(l)} ${bt(l)}

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

    - ${Rm(l)} + ${$m(l)} ${bt(l)}

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

    ${pc(a)}

    `)}return n+="
    ",` +
    `;continue}a.trim()!==""&&(r+=`

    ${pc(a)}

    `)}return r+="
    ",`
    Live Audit Report
    - ${n} + ${r}
    - `}const Nm="https://ccc-ffai-runner-y5cyj3473a-uw.a.run.app/deployCustomClasses";const Je="https://4tgke4.buildship.run",Nd={professional:"price_1T2ldCKszA2slvDXatdeCpbI",power:"price_1T2le9KszA2slvDXR4mPvw7M"},yr="ccc_auth_session",fc=new WeakSet;let G={email:null,sessionToken:null,isVerified:!1};function bs(t={}){return{tier:"free",status:"none",periodEnd:null,isLoading:!1,isResolved:!1,error:null,...t}}let fe=bs({isResolved:!0});const Mm=`${Je}/service/runpipeline`,Lm="bs_user_id",Om="bs_identity_token",Dm=`${Je}/authUserCheck`;let Ge={userId:null,token:null,status:null,resolved:!1};const wr={free:2,professional:50,power:2e3},br="ccc_subscription",gc=3,Bm=new Set(["active","trialing","paid"]),cn="google/gemini-3.7-flash",Hn=["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"],jm={"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 zt(t){return jm[t]||t}const Um=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 Md(t){return Um.has(t)}const ko=4,Ai=8*1024*1024,Hm="https://4tgke4.buildship.run/service/runpipeline-image";let Pt=[];function Wm(t){return new Promise(e=>{const s=new FileReader;s.onload=()=>e(s.result),s.onerror=()=>e(null),s.readAsDataURL(t)})}async function zm(t){const e=new FormData;return e.append("file",t),(await fetch(Hm,{method:"POST",body:e})).json()}function qm(t){if(Array.isArray(t)){const e=t[0];if(e&&typeof e=="object")for(const s of Object.keys(e)){if(s==="item"||s==="index")continue;const n=e[s];if(n&&typeof n=="object"){if(typeof n.file=="string")return n.file;if(typeof n.url=="string")return n.url}if(typeof n=="string")return n}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 Vm(t){const e=Array.from(t.target.files||[]);if(!e.length)return;const s=e.filter(l=>l.size>Ai);s.length&&ue(`Skipped ${s.length} image(s) over the ${(Ai/1024/1024).toFixed(0)} MB limit.`,"warning");const n=e.filter(l=>l.size<=Ai);if(!n.length){t.target.value="";return}const r=ko-Pt.length,o=n.slice(0,r).map(async l=>{const u=await Wm(l);if(!u)return null;let c="";try{c=qm(await zm(l))}catch{c=""}return{dataUrl:u,name:l.name,url:c}}),a=(await Promise.all(o)).filter(Boolean);t.target.value="",!(a.length&&!Md(document.getElementById("code-generator-model")?.value))&&(Pt.push(...a),n.length>r&&ue(`You can attach up to ${ko} images.`,"info"),da())}function Gm(t){Pt.splice(t,1),da()}function da(){const t=document.getElementById("prompt-image-thumbnails"),e=document.getElementById("prompt-image-btn-label");t&&(t.innerHTML="",Pt.forEach((s,n)=>{const r=document.createElement("div");r.className="prompt-img-thumb",r.innerHTML=`Prompt image`,t.appendChild(r)}),e&&(e.textContent=Pt.length>=ko?"Image limit reached":"Add images"))}function Ld(){const t=document.getElementById("prompt-image-upload");if(!t)return;const e=document.getElementById("code-generator-model"),s=Md(e?.value);t.classList.toggle("hidden",!s),!s&&Pt.length&&(Pt=[],da())}const Gt="ccc_usage",Od="google/gemini-3.7-flash",Dd="google/gemini-3.7-flash",$i="google/gemini-3.7-flash",mc={professional:11,power:49},Io={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"},Wn={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 zn={...Wn};async function Km(){const t=new AbortController,e=setTimeout(()=>t.abort(),5e3);try{const s=await fetch("https://open.er-api.com/v6/latest/AUD",{signal:t.signal});if(!s.ok)return;const n=await s.json();if(n.result!=="success"||!n.rates)return;const r=n.rates,i={AUD:1},o=new Set([...Object.keys(Wn),...Object.values(Co),...Object.values(Io)]);for(const a of o)a!=="AUD"&&(typeof r[a]=="number"&&r[a]>0?i[a]=r[a]:Wn[a]&&(i[a]=Wn[a]));zn=i}catch{}finally{clearTimeout(e)}}const Co={"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 Bd(){try{const i=Intl.DateTimeFormat().resolvedOptions().timeZone;if(i&&Co[i])return Co[i]}catch{}const e=(navigator.language||"en-US").replace("-","_"),s=Io[e];if(s)return s;const n=e.split("_")[0],r=Io[n];return r||"USD"}function vc(t,e){const s=zn[e]??zn.USD,n=t*s,r=Math.round(n*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*zn.USD)}}const st="ccc_api_key_",_t="ccc_session_api_key_",it="ccc_encryption_key",un="ccc_encryption_key_scope",Jm="ccc_keystore",Er="keys",dn="ccc_encryption_key_version";let Fo=null,Sr=null,hn=!1,xr=!1,_c=!1;class kr extends Error{constructor(){super("Secure browser key storage is unavailable."),this.name="CredentialStorageUnavailableError"}}function yc(){if(_c)return;_c=!0;const t="Secure browser key storage is unavailable. Existing credentials were left untouched; new credentials will be available only in this tab session.";console.warn(t),document.body&&ue(t,"warning")}function jd(){return localStorage.getItem(dn)||""}function Po(){return crypto.randomUUID?.()||Hd(crypto.getRandomValues(new Uint8Array(16)))}function Ym(){const t=jd();if(t)return t;const e=Po();return localStorage.setItem(dn,e),e}function Es(){Fo=null,Sr=null,hn=!1,xr=!1}window.addEventListener("storage",t=>{t.key===dn&&Es()});function Zm(){return new Promise((t,e)=>{const s=indexedDB.open(Jm,1);s.onupgradeneeded=()=>{const n=s.result;n.objectStoreNames.contains(Er)||n.createObjectStore(Er)},s.onsuccess=()=>t(s.result),s.onerror=()=>e(s.error)})}async function ha(t,e){const s=await Zm();return new Promise((n,r)=>{const i=s.transaction(Er,t);let o;try{o=e(i.objectStore(Er))}catch(l){s.close(),r(l);return}let a;o.onsuccess=()=>{a=o.result},o.onerror=()=>r(o.error),i.oncomplete=()=>{s.close(),n(a)},i.onerror=()=>{s.close(),r(i.error||new Error("Encryption key transaction failed."))},i.onabort=()=>{s.close(),r(i.error||new Error("Encryption key transaction aborted."))}})}function Xm(t){return t instanceof CryptoKey&&t.algorithm?.name==="AES-GCM"&&t.extractable===!1&&t.usages.includes("encrypt")&&t.usages.includes("decrypt")}async function Qm(){const t=await ha("readonly",e=>e.get(it));return Xm(t)?t:null}async function Ud(t){await ha("readwrite",e=>e.put(t,it))}async function ev(){Es();try{await ha("readwrite",t=>t.delete(it))}catch(t){console.warn("Could not delete the stored encryption key:",t)}}async function tv(){const t=sessionStorage.getItem(it);if(!t)return null;const e=await crypto.subtle.importKey("jwk",JSON.parse(t),{name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);return await Ud(e),sessionStorage.removeItem(it),sessionStorage.removeItem(un),localStorage.removeItem(st+"salt"),e}async function wc(t){const e=sessionStorage.getItem(it);if(e)return xr=sessionStorage.getItem(un)!=="session",crypto.subtle.importKey("jwk",JSON.parse(e),{name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);if(!t)throw new kr;const s=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!0,["encrypt","decrypt"]),n=await crypto.subtle.exportKey("jwk",s);return sessionStorage.setItem(it,JSON.stringify(n)),sessionStorage.setItem(un,"session"),xr=!1,crypto.subtle.importKey("jwk",n,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}async function sv(t){if(sessionStorage.getItem(un)==="session"&&sessionStorage.getItem(it))return yc(),hn=!0,wc(t);try{const e=await Qm();if(e)return e;const s=await tv();if(s)return s;const n=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);return await Ud(n),n}catch(e){return console.warn("IndexedDB encryption-key storage failed:",e),yc(),hn=!0,wc(t)}}async function pa(t={}){const{allowSessionFallbackCreation:e=!0}=t,s=Ym();Sr!==s&&Es();const n=Fo||sv(e);Fo=n,Sr=s;try{return await n}catch(r){throw Es(),r}}async function nv(t){const e=await pa(),s=Sr,n=new TextEncoder,r=crypto.getRandomValues(new Uint8Array(12)),i=await crypto.subtle.encrypt({name:"AES-GCM",iv:r},e,n.encode(t)),o=new Uint8Array(r.length+i.byteLength);return o.set(r),o.set(new Uint8Array(i),r.length),{ciphertext:Hd(o),keyVersion:s,sessionFallback:hn}}async function rv(t,e={}){const{isSessionCredential:s=!1}=e;try{const n=await pa({allowSessionFallbackCreation:!1});if(hn&&!s&&!xr)throw new kr;const r=iv(t),i=r.slice(0,12),o=r.slice(12),a=await crypto.subtle.decrypt({name:"AES-GCM",iv:i},n,o);return new TextDecoder().decode(a)}catch(n){if(n instanceof kr)throw n;return console.error("Decryption failed:",n),null}}function Hd(t){const e=new Uint8Array(t);let s="";for(let n=0;n0}let pn="",Ir="",Zs=null,Ec=0;async function fa(){sessionStorage.getItem(it)&&await pa(),pn=await Ee("flutterflow"),Ir=await Ee("flutterflow_project_id"),uv(),Zt()}function ga(){document.getElementById("api-keys-modal").classList.add("open"),va(),pn&&Vd(pn)}function Wd(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("api-keys-modal");e&&e.classList.remove("open");const s=document.getElementById("walkthrough-modal");s&&(ma(),s.classList.add("open"))}let Et=1;function zd(){const t=document.querySelector(".wt-steps");return t?Array.from(t.querySelectorAll(".wt-step-card")):[]}function Ur(){const t=zd();t.length&&t.forEach((e,s)=>{const n=s+1;if(n===Et){e.classList.remove("opacity-60","bg-gray-50","border-gray-200"),e.classList.add("bg-blue-50","border-blue-200");const r=e.querySelector("div:first-child");r&&(r.classList.remove("bg-gray-400"),r.classList.add("bg-blue-500"),r.innerHTML=n)}else if(n0&&Et<=t&&(Et++,Ur())}function av(){const t=document.getElementById("walkthrough-modal");t&&(Et=1,Ur(),t.classList.add("open"))}function lv(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("walkthrough-modal");e&&e.classList.remove("open");const s=document.getElementById("walkthrough-dont-show");s&&s.checked&&localStorage.setItem("hasSeenWalkthrough","true")}function qd(){if(G.isVerified&&Jt()&&fe.tier!=="free")return;if(!localStorage.getItem("hasSeenWalkthrough")){const e=document.getElementById("walkthrough-modal");e&&(Et=1,Ur(),e.classList.add("open"))}}async function va(){const t=document.getElementById("flutterflow-api-key-input");pn?(t.value="",t.placeholder="Key saved (enter new to replace)"):t.placeholder="Enter your FlutterFlow API key",cv()}function cv(){Sc("flutterflow","flutterflow-key-status"),Sc("flutterflow_project_id","flutterflow-project-status")}function Sc(t,e){const s=document.getElementById(e);if(!s)return;const n=s.querySelector(".key-status-dot"),r=s.querySelector("span");as(t)?(n.className="key-status-dot configured",r.className="text-green-600",r.textContent="User key configured"):(n.className="key-status-dot missing",r.className="text-gray-500",r.textContent="Not configured")}function Zt(){const t=y.step2Result&&y.step2Result.length>0,e=document.getElementById("btn-deploy-to-ff"),s=document.getElementById("btn-run-pipeline");s&&s.classList.remove("hidden"),e&&e.classList.toggle("hidden",!t)}function uv(){const t=document.getElementById("api-keys-status");if(!t)return;const e=t.querySelectorAll(".key-status-dot"),s=["flutterflow"];e.forEach((n,r)=>{const i=s[r];i==="flutterflow"?as("flutterflow")&&as("flutterflow_project_id")?(n.className="key-status-dot configured",n.title="FlutterFlow (Fully configured)"):as("flutterflow")||as("flutterflow_project_id")?(n.className="key-status-dot env",n.title="FlutterFlow (Partially configured)"):(n.className="key-status-dot missing",n.title="FlutterFlow (Not configured)"):as(i)?(n.className="key-status-dot configured",n.title=i.charAt(0).toUpperCase()+i.slice(1)+" (User key)"):(n.className="key-status-dot missing",n.title=i.charAt(0).toUpperCase()+i.slice(1)+" (Not configured)")}),Zt()}async function dv(){const t=document.getElementById("flutterflow-api-key-input"),e=document.getElementById("flutterflow-projects-select");t.value.trim()&&await bc("flutterflow",t.value);const s=e?.value.trim()||"";if(s){if(!Hr(s)){ue("The selected FlutterFlow project has an unexpected ID format.","error"),e.focus();return}await bc("flutterflow_project_id",s)}await fa(),va();const n=document.querySelector("#api-keys-modal .bg-blue-500"),r=n.textContent;n.textContent="Saved!",n.classList.remove("bg-blue-500","hover:bg-blue-600"),n.classList.add("bg-green-500"),setTimeout(()=>{n.textContent=r,n.classList.remove("bg-green-500"),n.classList.add("bg-blue-500","hover:bg-blue-600"),Wd()},1e3)}async function hv(){if(!confirm("Are you sure you want to clear all stored API keys?"))return;localStorage.setItem(dn,Po()),Es(),localStorage.removeItem(st+"flutterflow"),localStorage.removeItem(st+"flutterflow_project_id"),sessionStorage.removeItem(_t+"flutterflow"),sessionStorage.removeItem(_t+"flutterflow_project_id"),sessionStorage.removeItem(it),sessionStorage.removeItem(un),localStorage.removeItem(st+"salt"),await ev(),localStorage.setItem(dn,Po()),localStorage.removeItem(st+"flutterflow"),localStorage.removeItem(st+"flutterflow_project_id"),sessionStorage.removeItem(_t+"flutterflow"),sessionStorage.removeItem(_t+"flutterflow_project_id"),await fa();const t=document.getElementById("flutterflow-projects-select");t&&(t.innerHTML=''),va()}function Hr(t){return!t||t.trim().length<5||t.includes(" ")?!1:/^[a-zA-Z0-9-]+$/.test(t)}function pv(t,e){const s=document.getElementById(t);s&&(s.value?e?s.style.borderColor="#22c55e":s.style.borderColor="#ef4444":s.style.borderColor="")}function fv(){const t=document.getElementById("flutterflow-api-key-input");t&&(t.addEventListener("input",e=>{const s=e.target.value.trim().length>0;pv("flutterflow-api-key-input",s)}),t.addEventListener("blur",gv(async e=>{const s=e.target.value.trim();s&&await Vd(s)},500)))}function gv(t,e){let s;return function(...r){const i=()=>{clearTimeout(s),t(...r)};clearTimeout(s),s=setTimeout(i,e)}}async function Vd(t){const e=document.getElementById("flutterflow-projects-select"),s=document.getElementById("flutterflow-projects-error");if(!e){console.error("Projects dropdown element not found");return}e.innerHTML='',s&&s.classList.add("hidden");try{const r=await new mn(t,"").listProjects();if(!r||r.length===0){e.innerHTML='';return}e.innerHTML='',r.forEach(i=>{const o=document.createElement("option");o.value=i.id||i.projectId||"",o.textContent=i.name||i.projectName||`Project ${i.id}`,e.appendChild(o)}),Ir&&(e.value=Ir)}catch(n){console.error("Failed to fetch projects:",n),e.innerHTML='',s&&(s.textContent=`Failed to load projects: ${n.message}`,s.classList.remove("hidden"))}}function mv(t){const e=document.getElementById(t),n=e.nextElementSibling.querySelector("svg");e.type==="password"?(e.type="text",n.innerHTML=` + `}const Tm="https://ccc-ffai-runner-y5cyj3473a-uw.a.run.app/deployCustomClasses";const Je="https://4tgke4.buildship.run",Td={professional:"price_1T2ldCKszA2slvDXatdeCpbI",power:"price_1T2le9KszA2slvDXR4mPvw7M"},yn="ccc_auth_session",fc=new WeakSet;let G={email:null,sessionToken:null,isVerified:!1};function bs(t={}){return{tier:"free",status:"none",periodEnd:null,isLoading:!1,isResolved:!1,error:null,...t}}let fe=bs({isResolved:!0});const Nm=`${Je}/service/runpipeline`,Mm="bs_user_id",Lm="bs_identity_token",Om=`${Je}/authUserCheck`;let Ge={userId:null,token:null,status:null,resolved:!1};const wn={free:2,professional:50,power:2e3},bn="ccc_subscription",gc=3,Dm=new Set(["active","trialing","paid"]),lr="google/gemini-3.7-flash",Ur=["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"],Bm={"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 zt(t){return Bm[t]||t}const jm=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 Nd(t){return jm.has(t)}const ko=4,Ai=8*1024*1024,Um="https://4tgke4.buildship.run/service/runpipeline-image";let Pt=[];function Hm(t){return new Promise(e=>{const s=new FileReader;s.onload=()=>e(s.result),s.onerror=()=>e(null),s.readAsDataURL(t)})}async function Wm(t){const e=new FormData;return e.append("file",t),(await fetch(Um,{method:"POST",body:e})).json()}function zm(t){if(Array.isArray(t)){const e=t[0];if(e&&typeof e=="object")for(const s of Object.keys(e)){if(s==="item"||s==="index")continue;const r=e[s];if(r&&typeof r=="object"){if(typeof r.file=="string")return r.file;if(typeof r.url=="string")return r.url}if(typeof r=="string")return r}return""}return typeof t=="string"?t:t&&typeof t=="object"&&(t.url||t.fileUrl||t.file_url||t.downloadUrl||t.imageUrl||t.image_url||t.file)||""}async function qm(t){const e=Array.from(t.target.files||[]);if(!e.length)return;const s=e.filter(l=>l.size>Ai);s.length&&ue(`Skipped ${s.length} image(s) over the ${(Ai/1024/1024).toFixed(0)} MB limit.`,"warning");const r=e.filter(l=>l.size<=Ai);if(!r.length){t.target.value="";return}const n=ko-Pt.length,o=r.slice(0,n).map(async l=>{const u=await Hm(l);if(!u)return null;let c="";try{c=zm(await Wm(l))}catch{c=""}return{dataUrl:u,name:l.name,url:c}}),a=(await Promise.all(o)).filter(Boolean);t.target.value="",!(a.length&&!Nd(document.getElementById("code-generator-model")?.value))&&(Pt.push(...a),r.length>n&&ue(`You can attach up to ${ko} images.`,"info"),da())}function Vm(t){Pt.splice(t,1),da()}function da(){const t=document.getElementById("prompt-image-thumbnails"),e=document.getElementById("prompt-image-btn-label");t&&(t.innerHTML="",Pt.forEach((s,r)=>{const n=document.createElement("div");n.className="prompt-img-thumb",n.innerHTML=`Prompt image`,t.appendChild(n)}),e&&(e.textContent=Pt.length>=ko?"Image limit reached":"Add images"))}function Md(){const t=document.getElementById("prompt-image-upload");if(!t)return;const e=document.getElementById("code-generator-model"),s=Nd(e?.value);t.classList.toggle("hidden",!s),!s&&Pt.length&&(Pt=[],da())}const Gt="ccc_usage",Ld="google/gemini-3.7-flash",Od="google/gemini-3.7-flash",$i="google/gemini-3.7-flash",mc={professional:11,power:49},Io={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"},Hr={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 Wr={...Hr};async function Gm(){const t=new AbortController,e=setTimeout(()=>t.abort(),5e3);try{const s=await fetch("https://open.er-api.com/v6/latest/AUD",{signal:t.signal});if(!s.ok)return;const r=await s.json();if(r.result!=="success"||!r.rates)return;const n=r.rates,i={AUD:1},o=new Set([...Object.keys(Hr),...Object.values(Co),...Object.values(Io)]);for(const a of o)a!=="AUD"&&(typeof n[a]=="number"&&n[a]>0?i[a]=n[a]:Hr[a]&&(i[a]=Hr[a]));Wr=i}catch{}finally{clearTimeout(e)}}const Co={"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 Dd(){try{const i=Intl.DateTimeFormat().resolvedOptions().timeZone;if(i&&Co[i])return Co[i]}catch{}const e=(navigator.language||"en-US").replace("-","_"),s=Io[e];if(s)return s;const r=e.split("_")[0],n=Io[r];return n||"USD"}function vc(t,e){const s=Wr[e]??Wr.USD,r=t*s,n=Math.round(r*100)/100;try{return new Intl.NumberFormat("en-US",{style:"currency",currency:e,minimumFractionDigits:0,maximumFractionDigits:n>=100||n%1===0?0:2}).format(n)}catch{return new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",minimumFractionDigits:0,maximumFractionDigits:2}).format(t*Wr.USD)}}const st="ccc_api_key_",_t="ccc_session_api_key_",it="ccc_encryption_key",cr="ccc_encryption_key_scope",Km="ccc_keystore",En="keys",ur="ccc_encryption_key_version";let Fo=null,Sn=null,dr=!1,xn=!1,_c=!1;class kn extends Error{constructor(){super("Secure browser key storage is unavailable."),this.name="CredentialStorageUnavailableError"}}function yc(){if(_c)return;_c=!0;const t="Secure browser key storage is unavailable. Existing credentials were left untouched; new credentials will be available only in this tab session.";console.warn(t),document.body&&ue(t,"warning")}function Bd(){return localStorage.getItem(ur)||""}function Po(){return crypto.randomUUID?.()||Ud(crypto.getRandomValues(new Uint8Array(16)))}function Jm(){const t=Bd();if(t)return t;const e=Po();return localStorage.setItem(ur,e),e}function Es(){Fo=null,Sn=null,dr=!1,xn=!1}window.addEventListener("storage",t=>{t.key===ur&&Es()});function Ym(){return new Promise((t,e)=>{const s=indexedDB.open(Km,1);s.onupgradeneeded=()=>{const r=s.result;r.objectStoreNames.contains(En)||r.createObjectStore(En)},s.onsuccess=()=>t(s.result),s.onerror=()=>e(s.error)})}async function ha(t,e){const s=await Ym();return new Promise((r,n)=>{const i=s.transaction(En,t);let o;try{o=e(i.objectStore(En))}catch(l){s.close(),n(l);return}let a;o.onsuccess=()=>{a=o.result},o.onerror=()=>n(o.error),i.oncomplete=()=>{s.close(),r(a)},i.onerror=()=>{s.close(),n(i.error||new Error("Encryption key transaction failed."))},i.onabort=()=>{s.close(),n(i.error||new Error("Encryption key transaction aborted."))}})}function Zm(t){return t instanceof CryptoKey&&t.algorithm?.name==="AES-GCM"&&t.extractable===!1&&t.usages.includes("encrypt")&&t.usages.includes("decrypt")}async function Xm(){const t=await ha("readonly",e=>e.get(it));return Zm(t)?t:null}async function jd(t){await ha("readwrite",e=>e.put(t,it))}async function Qm(){Es();try{await ha("readwrite",t=>t.delete(it))}catch(t){console.warn("Could not delete the stored encryption key:",t)}}async function ev(){const t=sessionStorage.getItem(it);if(!t)return null;const e=await crypto.subtle.importKey("jwk",JSON.parse(t),{name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);return await jd(e),sessionStorage.removeItem(it),sessionStorage.removeItem(cr),localStorage.removeItem(st+"salt"),e}async function wc(t){const e=sessionStorage.getItem(it);if(e)return xn=sessionStorage.getItem(cr)!=="session",crypto.subtle.importKey("jwk",JSON.parse(e),{name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);if(!t)throw new kn;const s=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!0,["encrypt","decrypt"]),r=await crypto.subtle.exportKey("jwk",s);return sessionStorage.setItem(it,JSON.stringify(r)),sessionStorage.setItem(cr,"session"),xn=!1,crypto.subtle.importKey("jwk",r,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}async function tv(t){if(sessionStorage.getItem(cr)==="session"&&sessionStorage.getItem(it))return yc(),dr=!0,wc(t);try{const e=await Xm();if(e)return e;const s=await ev();if(s)return s;const r=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);return await jd(r),r}catch(e){return console.warn("IndexedDB encryption-key storage failed:",e),yc(),dr=!0,wc(t)}}async function pa(t={}){const{allowSessionFallbackCreation:e=!0}=t,s=Jm();Sn!==s&&Es();const r=Fo||tv(e);Fo=r,Sn=s;try{return await r}catch(n){throw Es(),n}}async function sv(t){const e=await pa(),s=Sn,r=new TextEncoder,n=crypto.getRandomValues(new Uint8Array(12)),i=await crypto.subtle.encrypt({name:"AES-GCM",iv:n},e,r.encode(t)),o=new Uint8Array(n.length+i.byteLength);return o.set(n),o.set(new Uint8Array(i),n.length),{ciphertext:Ud(o),keyVersion:s,sessionFallback:dr}}async function rv(t,e={}){const{isSessionCredential:s=!1}=e;try{const r=await pa({allowSessionFallbackCreation:!1});if(dr&&!s&&!xn)throw new kn;const n=nv(t),i=n.slice(0,12),o=n.slice(12),a=await crypto.subtle.decrypt({name:"AES-GCM",iv:i},r,o);return new TextDecoder().decode(a)}catch(r){if(r instanceof kn)throw r;return console.error("Decryption failed:",r),null}}function Ud(t){const e=new Uint8Array(t);let s="";for(let r=0;r0}let hr="",In="",Zs=null,Ec=0;async function fa(){sessionStorage.getItem(it)&&await pa(),hr=await Ee("flutterflow"),In=await Ee("flutterflow_project_id"),cv(),Zt()}function ga(){document.getElementById("api-keys-modal").classList.add("open"),va(),hr&&qd(hr)}function Hd(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("api-keys-modal");e&&e.classList.remove("open");const s=document.getElementById("walkthrough-modal");s&&(ma(),s.classList.add("open"))}let Et=1;function Wd(){const t=document.querySelector(".wt-steps");return t?Array.from(t.querySelectorAll(".wt-step-card")):[]}function Un(){const t=Wd();t.length&&t.forEach((e,s)=>{const r=s+1;if(r===Et){e.classList.remove("opacity-60","bg-gray-50","border-gray-200"),e.classList.add("bg-blue-50","border-blue-200");const n=e.querySelector("div:first-child");n&&(n.classList.remove("bg-gray-400"),n.classList.add("bg-blue-500"),n.innerHTML=r)}else if(r0&&Et<=t&&(Et++,Un())}function ov(){const t=document.getElementById("walkthrough-modal");t&&(Et=1,Un(),t.classList.add("open"))}function av(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("walkthrough-modal");e&&e.classList.remove("open");const s=document.getElementById("walkthrough-dont-show");s&&s.checked&&localStorage.setItem("hasSeenWalkthrough","true")}function zd(){if(G.isVerified&&Jt()&&fe.tier!=="free")return;if(!localStorage.getItem("hasSeenWalkthrough")){const e=document.getElementById("walkthrough-modal");e&&(Et=1,Un(),e.classList.add("open"))}}async function va(){const t=document.getElementById("flutterflow-api-key-input");hr?(t.value="",t.placeholder="Key saved (enter new to replace)"):t.placeholder="Enter your FlutterFlow API key",lv()}function lv(){Sc("flutterflow","flutterflow-key-status"),Sc("flutterflow_project_id","flutterflow-project-status")}function Sc(t,e){const s=document.getElementById(e);if(!s)return;const r=s.querySelector(".key-status-dot"),n=s.querySelector("span");as(t)?(r.className="key-status-dot configured",n.className="text-green-600",n.textContent="User key configured"):(r.className="key-status-dot missing",n.className="text-gray-500",n.textContent="Not configured")}function Zt(){const t=y.step2Result&&y.step2Result.length>0,e=document.getElementById("btn-deploy-to-ff"),s=document.getElementById("btn-run-pipeline");s&&s.classList.remove("hidden"),e&&e.classList.toggle("hidden",!t)}function cv(){const t=document.getElementById("api-keys-status");if(!t)return;const e=t.querySelectorAll(".key-status-dot"),s=["flutterflow"];e.forEach((r,n)=>{const i=s[n];i==="flutterflow"?as("flutterflow")&&as("flutterflow_project_id")?(r.className="key-status-dot configured",r.title="FlutterFlow (Fully configured)"):as("flutterflow")||as("flutterflow_project_id")?(r.className="key-status-dot env",r.title="FlutterFlow (Partially configured)"):(r.className="key-status-dot missing",r.title="FlutterFlow (Not configured)"):as(i)?(r.className="key-status-dot configured",r.title=i.charAt(0).toUpperCase()+i.slice(1)+" (User key)"):(r.className="key-status-dot missing",r.title=i.charAt(0).toUpperCase()+i.slice(1)+" (Not configured)")}),Zt()}async function uv(){const t=document.getElementById("flutterflow-api-key-input"),e=document.getElementById("flutterflow-projects-select");t.value.trim()&&await bc("flutterflow",t.value);const s=e?.value.trim()||"";if(s){if(!Hn(s)){ue("The selected FlutterFlow project has an unexpected ID format.","error"),e.focus();return}await bc("flutterflow_project_id",s)}await fa(),va();const r=document.querySelector("#api-keys-modal .bg-blue-500"),n=r.textContent;r.textContent="Saved!",r.classList.remove("bg-blue-500","hover:bg-blue-600"),r.classList.add("bg-green-500"),setTimeout(()=>{r.textContent=n,r.classList.remove("bg-green-500"),r.classList.add("bg-blue-500","hover:bg-blue-600"),Hd()},1e3)}async function dv(){if(!confirm("Are you sure you want to clear all stored API keys?"))return;localStorage.setItem(ur,Po()),Es(),localStorage.removeItem(st+"flutterflow"),localStorage.removeItem(st+"flutterflow_project_id"),sessionStorage.removeItem(_t+"flutterflow"),sessionStorage.removeItem(_t+"flutterflow_project_id"),sessionStorage.removeItem(it),sessionStorage.removeItem(cr),localStorage.removeItem(st+"salt"),await Qm(),localStorage.setItem(ur,Po()),localStorage.removeItem(st+"flutterflow"),localStorage.removeItem(st+"flutterflow_project_id"),sessionStorage.removeItem(_t+"flutterflow"),sessionStorage.removeItem(_t+"flutterflow_project_id"),await fa();const t=document.getElementById("flutterflow-projects-select");t&&(t.innerHTML=''),va()}function Hn(t){return!t||t.trim().length<5||t.includes(" ")?!1:/^[a-zA-Z0-9-]+$/.test(t)}function hv(t,e){const s=document.getElementById(t);s&&(s.value?e?s.style.borderColor="#22c55e":s.style.borderColor="#ef4444":s.style.borderColor="")}function pv(){const t=document.getElementById("flutterflow-api-key-input");t&&(t.addEventListener("input",e=>{const s=e.target.value.trim().length>0;hv("flutterflow-api-key-input",s)}),t.addEventListener("blur",fv(async e=>{const s=e.target.value.trim();s&&await qd(s)},500)))}function fv(t,e){let s;return function(...n){const i=()=>{clearTimeout(s),t(...n)};clearTimeout(s),s=setTimeout(i,e)}}async function qd(t){const e=document.getElementById("flutterflow-projects-select"),s=document.getElementById("flutterflow-projects-error");if(!e){console.error("Projects dropdown element not found");return}e.innerHTML='',s&&s.classList.add("hidden");try{const n=await new gr(t,"").listProjects();if(!n||n.length===0){e.innerHTML='';return}e.innerHTML='',n.forEach(i=>{const o=document.createElement("option");o.value=i.id||i.projectId||"",o.textContent=i.name||i.projectName||`Project ${i.id}`,e.appendChild(o)}),In&&(e.value=In)}catch(r){console.error("Failed to fetch projects:",r),e.innerHTML='',s&&(s.textContent=`Failed to load projects: ${r.message}`,s.classList.remove("hidden"))}}function gv(t){const e=document.getElementById(t),r=e.nextElementSibling.querySelector("svg");e.type==="password"?(e.type="text",r.innerHTML=` - `):(e.type="password",n.innerHTML=` + `):(e.type="password",r.innerHTML=` - `)}let y={step1Result:null,step2Result:null,step3Result:null,bundleSpec:null,artifactBundle:null,bundleReview:null,selectedArtifactId:null,resultsViewMode:"summary",currentStep:0,isRunning:!1};function vv(){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 _v(){y.bundleSpec=an(y.step1Result,{artifactType:"CustomWidget",artifactName:"GeneratedWidget"})}function Wr(){const t=mr(y.bundleSpec);y.artifactBundle=an(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=gg(y.artifactBundle);y.artifactBundle={...y.artifactBundle,warnings:[...y.artifactBundle.warnings,...e.findings.map(s=>s.message)],metadata:{...y.artifactBundle.metadata,compatibility:e}},y.selectedArtifactId=mr(y.artifactBundle).id}function zr(){const t=an(y.step3Result,{id:y.artifactBundle?.id,title:y.artifactBundle?.title}),e=new Map(t.artifacts.map(n=>[n.id,n.review])),s=new Map(t.artifacts.filter(n=>{const r=n.review;return r&&typeof r.fixedSource=="string"&&r.fixedSource.trim()}).map(n=>[n.id,n.review.fixedSource.trim()]));y.bundleReview=an({id:y.artifactBundle?.id,title:y.artifactBundle?.title,artifacts:y.artifactBundle?.artifacts?.map(n=>{const r=s.get(n.id)||null;return{...n,review:e.get(n.id)||n.review||y.step3Result||null,...r?{fixedCode:r}:{}}})||[],relationships:y.artifactBundle?.relationships,warnings:y.artifactBundle?.warnings})}function Gd(){const t=_a();return{artifactType:t.artifactType||"CustomWidget",artifactName:t.artifactName||"GeneratedWidget",fileName:t.fileName||""}}function _a(){const t=y.artifactBundle||y.bundleSpec||null;return(Array.isArray(t?.artifacts)?t.artifacts:[]).find(s=>s.id===y.selectedArtifactId)||mr(t)}function ya(){return _a().code||y.step2Result||""}async function yv(){try{await fa()}catch(t){return console.error("checkConnection: initializeApiKeys failed:",t),!1}return!0}const qn={production:"https://api.flutterflow.io/v2/",staging:"https://api.flutterflow.io/v2-staging/"};function wv(t,e){const s=e?.trim()?` (${e.trim().slice(0,200)})`:"";return t===401?`Your FlutterFlow API key was rejected (401 Unauthorized)${s}. Re-enter a current key under API Keys settings, then try again.`:`Listing FlutterFlow projects was denied (403)${s}. 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 mn{constructor(e,s,n="main",r=qn.production){this.apiKey=e,this.baseUrl=r,this._projectId=s,this._branchName=n,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 s=null;for(const n of e)try{const r=await fetch(`${this.baseUrl}exportCode`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify(n)});if(!r.ok){const a=await r.text();s=new Error(`Export failed: ${r.status} - ${a}`);continue}const i=await r.json(),o=i?.value?.project_zip||i?.project_zip;if(!o){s=new Error("Export response did not include project source.");continue}return o}catch(r){s=r}throw s||new Error("Export failed for an unknown reason.")}async fetchProjectSource(){const e=await this.exportProjectZip(),s=await JSZip.loadAsync(e,{base64:!0}),n=Object.keys(s.files).filter(a=>!s.files[a].dir&&(a==="pubspec.yaml"||a.endsWith("/pubspec.yaml"))).sort((a,l)=>a.split("/").length-l.split("/").length)[0];if(!n)throw new Error("Export did not contain a pubspec.yaml.");const r=n.slice(0,n.length-12),i=new Map,o=Object.keys(s.files).filter(a=>{if(s.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=>{i.set(a.slice(r.length),await s.files[a].async("string"))})),{pubspecYaml:await s.files[n].async("string"),files:i}}async pushCodeWithRetry(e,s=3){const n=[qn.production,qn.staging],r=Math.max(0,n.indexOf(this._endpoint));for(let i=0;isetTimeout(d,1e3*(i+1)));continue}return l}catch(l){console.warn(`Push to ${a} failed: ${l.message}, trying next...`),await new Promise(u=>setTimeout(u,1e3*(i+1)))}}throw new Error("All API endpoints failed after retries")}async pushCode(e){return this.pushCodeWithRetry(e)}parseProjectsResponse(e){if(e?.success&&typeof e.value=="string")try{const n=JSON.parse(e.value);if(n&&Array.isArray(n.entries))return n.entries.map(r=>({id:r.id,name:r.project?.name||r.id}))}catch(n){console.error("Failed to parse stringified project value:",n)}const s=e?.projects||e?.items||e?.entries||(Array.isArray(e)?e:[]);return Array.isArray(s)?s:[]}async listProjects(){console.log("Listing projects for API key");const e=[`${this.baseUrl}listProjects`,"https://api.flutterflow.io/v2/l/listProjects"];let s=0,n="";for(const r of e){const i=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify({project_type:"ALL",deserialize_response:!0})});if(i.ok)return r!==e[0]&&console.log(`listProjects answered on legacy path ${r}`),this.parseProjectsResponse(await i.json());if(s=i.status,n=await i.text(),console.warn(`listProjects via ${r} returned ${s}: ${n}`),i.status===401||i.status===403)throw new Error(wv(i.status,n));if(i.status!==404)throw new Error(`List projects failed: ${i.status} - ${n}`)}throw new Error(`List projects failed: ${s} - ${n}`)}}async function wa(t){const e=t.clone();let s;try{s=await t.json()}catch{const i=await e.text();if(!t.ok)return{success:!1,responseCode:t.status,errorMessage:i||`HTTP ${t.status}`,errorMap:new Map};throw new Error(`Invalid JSON response: ${i}`)}if(!t.ok){let r=s.message||`HTTP ${t.status}`,i=new Map;if(s.errors)i=new Map(Object.entries(s.errors));else if(!s.message&&typeof s=="object"){const o=Object.keys(s).filter(a=>a.endsWith(".dart")&&Array.isArray(s[a]));o.length>0&&(i=new Map(Object.entries(s)),r=o.flatMap(l=>s[l].map(u=>`${l}: ${u.errorMessage}`)).join(` -`)||`HTTP ${t.status}`)}return{success:!1,responseCode:t.status,errorMessage:r,errorMap:i}}let n={};if(s.value)try{n=typeof s.value=="string"?JSON.parse(s.value):s.value}catch(r){console.warn("Ignoring malformed push response value:",r)}return{success:!0,responseCode:t.status,errorMap:new Map(Object.entries(n))}}function ba(t,e){return{401:"Authentication failed. Please check your FlutterFlow API key.",403:"Access denied. You may not have permission to modify this project.",404:"Project not found. Please check your Project ID.",409:"Conflict detected. The project may have been modified elsewhere.",422:"Validation failed: Invalid request format",429:"Rate limit exceeded. Please try again in a few minutes.",500:"FlutterFlow server error. Please try again later.",503:"FlutterFlow service temporarily unavailable."}[t]||`FlutterFlow API error: ${`HTTP ${t}`}`}const U={ACTION:"A",WIDGET:"W",FUNCTION:"F",CODE_FILE:"C",DEPENDENCIES:"D",OTHER:"O"},Kd=/class\s+\w+\s+extends\s+(?:StatelessWidget|StatefulWidget)\b/,Jd=/extends\s+State<\w+>/;function bv(t,e=""){if(t==="pubspec.yaml")return U.DEPENDENCIES;if(!t.endsWith(".dart")||t.endsWith("index.dart"))return U.OTHER;if(t==="custom_functions.dart")return U.FUNCTION;if(e){const s=Kd.test(e),n=Jd.test(e);if(s||n)return U.WIDGET;if(/^\s*Future(?:<[^>]+>)?\s+\w+\s*\(/m.test(e))return U.ACTION;if(e.match(/^\s*(String|int|double|bool|List|Map|dynamic|void)\s+\w+\s*\(/m))return U.FUNCTION}return U.CODE_FILE}function Yd(t,e){switch(e){case U.ACTION:return`lib/custom_code/actions/${t}`;case U.WIDGET:return`lib/custom_code/widgets/${t}`;case U.FUNCTION:return"lib/flutter_flow/custom_functions.dart";case U.CODE_FILE:return`lib/custom_code/${t}`;case U.DEPENDENCIES:return"pubspec.yaml";case U.OTHER:return`lib/custom_code/${t}`;default:return t}}async function Ea(t,e=new Map){return Zf(t,e)}const Ao=new Map;function Zd(t){return`${t.baseUrl}|${t.projectId}|${t.branchName}`}function qr(t){Ao.delete(Zd(t))}async function Sa(t,e,s,n,r=""){const i=Fg(e,s);if(i.length===0)return{remoteFiles:s,syncFileMap:e,unverified:[]};const o=gm(i,r),a={...o.manifest,sources:o.sources},l=o.skipped.map(d=>d.reason);l.forEach(d=>console.warn(`[custom class deploy] ${d}`)),console.log(`Provisioning ${i.length} new FlutterFlow custom code file(s) before sync.`),be.set("provision");const u=await fetch(Nm,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:t.apiKey,projectId:t.projectId,baseUrl:t.baseUrl,commitMessage:n,customClasses:i,verification:a,stream:!0})}),c=await vm(u,{onPhase:d=>be.setSubstatus(d),onLog:d=>console.log(`[custom class deploy] ${d}`)});if(!c.success){const d=c.details?` ${c.details}`:"";throw new Error(`${c.error||"FlutterFlow custom class provisioning failed."}${d}`)}return qr(t),c.verificationSkipped&&(console.warn(`[custom class deploy] ${c.verificationSkipped}`),l.push(c.verificationSkipped)),{remoteFiles:s,syncFileMap:Pg(e,i),unverified:l}}async function xa(t,e={}){const s=Zd(t);let n=Ao.get(s);if(n===void 0){try{n=await t.fetchProjectSource()}catch(l){throw new Error(`Could not read your project's pubspec.yaml (${l.message}). Deploy was stopped so your existing package dependencies aren't overwritten. Check your FlutterFlow API key and project, then try again.`)}const a=$d(n.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.`);Ao.set(s,n)}const r=await Fm(n.pubspecYaml,e),i=cm(n.pubspecYaml,r.overrides),o=lm(i.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:i.overridden,warnings:r.warnings,remoteFiles:n.files}}function Ev(t){const e=[],s=[];t.content.length>5e4&&s.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 n=t.content.split(` -`).length;n>500&&s.push(`Code has ${n} lines. Consider breaking it into smaller widgets.`),t.content.includes("setState")&&t.codeType===U.ACTION&&s.push("Using setState in a Custom Action may not work as expected. Consider using a Custom Widget."),t.content.includes("dynamic")&&!t.content.includes("?")&&s.push('Code uses "dynamic" types. Consider adding explicit types for better null safety.'),t.content.match(/Color\(0xFF[0-9A-Fa-f]{6}\)/)&&s.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&&s.push(`Code contains ${r.length} print statements. Consider removing debug prints before committing.`);const i=Gg(t.content);if(i&&e.push(`FlutterFlow cannot format this code - ${i}. Fix or regenerate before committing.`),t.codeType===U.WIDGET){const o=Sd(t.content),a=zg(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=`${xd(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:s}}function Xd(t,e={}){const{artifactType:s="CustomWidget",artifactName:n="GeneratedCode",fileName:r}=e,i=Hg(t);let o=r||n;if(s==="CustomFunction")o="custom_functions.dart";else if(s==="CustomWidget"){const u=Sd(i)[0],c=u?xd(u):null;c&&o!==c?(console.warn(`Commit file name "${o}" does not match declared widget class "${u}"; renaming to "${c}" so FlutterFlow can find the widget.`),o=c):o.endsWith(".dart")||(o+=".dart")}else o.endsWith(".dart")||(o+=".dart");let a=U.CODE_FILE;switch(s){case"CustomAction":a=U.ACTION;break;case"CustomWidget":a=U.WIDGET;break;case"CustomFunction":a=U.FUNCTION;break;case"CustomClass":case"CodeFile":a=U.CODE_FILE;break}let l="";return a===U.WIDGET?l=`// Automatic FlutterFlow imports + `)}let y={step1Result:null,step2Result:null,step3Result:null,bundleSpec:null,artifactBundle:null,bundleReview:null,selectedArtifactId:null,resultsViewMode:"summary",currentStep:0,isRunning:!1};function mv(){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 vv(){y.bundleSpec=or(y.step1Result,{artifactType:"CustomWidget",artifactName:"GeneratedWidget"})}function Wn(){const t=mn(y.bundleSpec);y.artifactBundle=or(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=fg(y.artifactBundle);y.artifactBundle={...y.artifactBundle,warnings:[...y.artifactBundle.warnings,...e.findings.map(s=>s.message)],metadata:{...y.artifactBundle.metadata,compatibility:e}},y.selectedArtifactId=mn(y.artifactBundle).id}function zn(){const t=or(y.step3Result,{id:y.artifactBundle?.id,title:y.artifactBundle?.title}),e=new Map(t.artifacts.map(r=>[r.id,r.review])),s=new Map(t.artifacts.filter(r=>{const n=r.review;return n&&typeof n.fixedSource=="string"&&n.fixedSource.trim()}).map(r=>[r.id,r.review.fixedSource.trim()]));y.bundleReview=or({id:y.artifactBundle?.id,title:y.artifactBundle?.title,artifacts:y.artifactBundle?.artifacts?.map(r=>{const n=s.get(r.id)||null;return{...r,review:e.get(r.id)||r.review||y.step3Result||null,...n?{fixedCode:n}:{}}})||[],relationships:y.artifactBundle?.relationships,warnings:y.artifactBundle?.warnings})}function Vd(){const t=_a();return{artifactType:t.artifactType||"CustomWidget",artifactName:t.artifactName||"GeneratedWidget",fileName:t.fileName||""}}function _a(){const t=y.artifactBundle||y.bundleSpec||null;return(Array.isArray(t?.artifacts)?t.artifacts:[]).find(s=>s.id===y.selectedArtifactId)||mn(t)}function ya(){return _a().code||y.step2Result||""}async function _v(){try{await fa()}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 yv(t,e){const s=e?.trim()?` (${e.trim().slice(0,200)})`:"";return t===401?`Your FlutterFlow API key was rejected (401 Unauthorized)${s}. Re-enter a current key under API Keys settings, then try again.`:`Listing FlutterFlow projects was denied (403)${s}. 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 gr{constructor(e,s,r="main",n=zr.production){this.apiKey=e,this.baseUrl=n,this._projectId=s,this._branchName=r,this._endpoint=n}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 s=null;for(const r of e)try{const n=await fetch(`${this.baseUrl}exportCode`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify(r)});if(!n.ok){const a=await n.text();s=new Error(`Export failed: ${n.status} - ${a}`);continue}const i=await n.json(),o=i?.value?.project_zip||i?.project_zip;if(!o){s=new Error("Export response did not include project source.");continue}return o}catch(n){s=n}throw s||new Error("Export failed for an unknown reason.")}async fetchProjectSource(){const e=await this.exportProjectZip(),s=await JSZip.loadAsync(e,{base64:!0}),r=Object.keys(s.files).filter(a=>!s.files[a].dir&&(a==="pubspec.yaml"||a.endsWith("/pubspec.yaml"))).sort((a,l)=>a.split("/").length-l.split("/").length)[0];if(!r)throw new Error("Export did not contain a pubspec.yaml.");const n=r.slice(0,r.length-12),i=new Map,o=Object.keys(s.files).filter(a=>{if(s.files[a].dir||!a.startsWith(n))return!1;const l=a.slice(n.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=>{i.set(a.slice(n.length),await s.files[a].async("string"))})),{pubspecYaml:await s.files[r].async("string"),files:i}}async pushCodeWithRetry(e,s=3){const r=[zr.production,zr.staging],n=Math.max(0,r.indexOf(this._endpoint));for(let i=0;isetTimeout(d,1e3*(i+1)));continue}return l}catch(l){console.warn(`Push to ${a} failed: ${l.message}, trying next...`),await new Promise(u=>setTimeout(u,1e3*(i+1)))}}throw new Error("All API endpoints failed after retries")}async pushCode(e){return this.pushCodeWithRetry(e)}parseProjectsResponse(e){if(e?.success&&typeof e.value=="string")try{const r=JSON.parse(e.value);if(r&&Array.isArray(r.entries))return r.entries.map(n=>({id:n.id,name:n.project?.name||n.id}))}catch(r){console.error("Failed to parse stringified project value:",r)}const s=e?.projects||e?.items||e?.entries||(Array.isArray(e)?e:[]);return Array.isArray(s)?s:[]}async listProjects(){console.log("Listing projects for API key");const e=[`${this.baseUrl}listProjects`,"https://api.flutterflow.io/v2/l/listProjects"];let s=0,r="";for(const n of e){const i=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify({project_type:"ALL",deserialize_response:!0})});if(i.ok)return n!==e[0]&&console.log(`listProjects answered on legacy path ${n}`),this.parseProjectsResponse(await i.json());if(s=i.status,r=await i.text(),console.warn(`listProjects via ${n} returned ${s}: ${r}`),i.status===401||i.status===403)throw new Error(yv(i.status,r));if(i.status!==404)throw new Error(`List projects failed: ${i.status} - ${r}`)}throw new Error(`List projects failed: ${s} - ${r}`)}}async function wa(t){const e=t.clone();let s;try{s=await t.json()}catch{const i=await e.text();if(!t.ok)return{success:!1,responseCode:t.status,errorMessage:i||`HTTP ${t.status}`,errorMap:new Map};throw new Error(`Invalid JSON response: ${i}`)}if(!t.ok){let n=s.message||`HTTP ${t.status}`,i=new Map;if(s.errors)i=new Map(Object.entries(s.errors));else if(!s.message&&typeof s=="object"){const o=Object.keys(s).filter(a=>a.endsWith(".dart")&&Array.isArray(s[a]));o.length>0&&(i=new Map(Object.entries(s)),n=o.flatMap(l=>s[l].map(u=>`${l}: ${u.errorMessage}`)).join(` +`)||`HTTP ${t.status}`)}return{success:!1,responseCode:t.status,errorMessage:n,errorMap:i}}let r={};if(s.value)try{r=typeof s.value=="string"?JSON.parse(s.value):s.value}catch(n){console.warn("Ignoring malformed push response value:",n)}return{success:!0,responseCode:t.status,errorMap:new Map(Object.entries(r))}}function ba(t,e){return{401:"Authentication failed. Please check your FlutterFlow API key.",403:"Access denied. You may not have permission to modify this project.",404:"Project not found. Please check your Project ID.",409:"Conflict detected. The project may have been modified elsewhere.",422:"Validation failed: Invalid request format",429:"Rate limit exceeded. Please try again in a few minutes.",500:"FlutterFlow server error. Please try again later.",503:"FlutterFlow service temporarily unavailable."}[t]||`FlutterFlow API error: ${`HTTP ${t}`}`}const U={ACTION:"A",WIDGET:"W",FUNCTION:"F",CODE_FILE:"C",DEPENDENCIES:"D",OTHER:"O"},Gd=/class\s+\w+\s+extends\s+(?:StatelessWidget|StatefulWidget)\b/,Kd=/extends\s+State<\w+>/;function wv(t,e=""){if(t==="pubspec.yaml")return U.DEPENDENCIES;if(!t.endsWith(".dart")||t.endsWith("index.dart"))return U.OTHER;if(t==="custom_functions.dart")return U.FUNCTION;if(e){const s=Gd.test(e),r=Kd.test(e);if(s||r)return U.WIDGET;if(/^\s*Future(?:<[^>]+>)?\s+\w+\s*\(/m.test(e))return U.ACTION;if(e.match(/^\s*(String|int|double|bool|List|Map|dynamic|void)\s+\w+\s*\(/m))return U.FUNCTION}return U.CODE_FILE}function Jd(t,e){switch(e){case U.ACTION:return`lib/custom_code/actions/${t}`;case U.WIDGET:return`lib/custom_code/widgets/${t}`;case U.FUNCTION:return"lib/flutter_flow/custom_functions.dart";case U.CODE_FILE:return`lib/custom_code/${t}`;case U.DEPENDENCIES:return"pubspec.yaml";case U.OTHER:return`lib/custom_code/${t}`;default:return t}}async function Ea(t,e=new Map){return Yf(t,e)}const Ao=new Map;function Yd(t){return`${t.baseUrl}|${t.projectId}|${t.branchName}`}function qn(t){Ao.delete(Yd(t))}async function Sa(t,e,s,r,n=""){const i=Fg(e,s);if(i.length===0)return{remoteFiles:s,syncFileMap:e,unverified:[],approximate:[]};const o=fm(i,n),a={...o.manifest,sources:o.sources},l=o.skipped.map(h=>h.reason);l.forEach(h=>console.warn(`[custom class deploy] ${h}`));const u=o.approximate;u.forEach(h=>console.warn(`[custom class deploy] ${h}`)),console.log(`Provisioning ${i.length} new FlutterFlow custom code file(s) before sync.`),be.set("provision");const c=await fetch(Tm,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:t.apiKey,projectId:t.projectId,baseUrl:t.baseUrl,commitMessage:r,customClasses:i,verification:a,stream:!0})}),d=await mm(c,{onPhase:h=>be.setSubstatus(h),onLog:h=>console.log(`[custom class deploy] ${h}`)});if(!d.success){const h=d.details?` ${d.details}`:"";throw new Error(`${d.error||"FlutterFlow custom class provisioning failed."}${h}`)}return qn(t),d.verificationSkipped&&(console.warn(`[custom class deploy] ${d.verificationSkipped}`),l.push(d.verificationSkipped)),{remoteFiles:s,syncFileMap:Pg(e,i),unverified:l,approximate:u}}async function xa(t,e={}){const s=Yd(t);let r=Ao.get(s);if(r===void 0){try{r=await t.fetchProjectSource()}catch(l){throw new Error(`Could not read your project's pubspec.yaml (${l.message}). Deploy was stopped so your existing package dependencies aren't overwritten. Check your FlutterFlow API key and project, then try again.`)}const a=Ad(r.pubspecYaml);if(!a.valid)throw new Error(`Your project's pubspec.yaml could not be read reliably (${a.errors.join("; ")}). Deploy was stopped so your existing package dependencies aren't overwritten.`);Ao.set(s,r)}const n=await Cm(r.pubspecYaml,e),i=cm(r.pubspecYaml,n.overrides),o=lm(i.yaml,n.additions);return n.warnings.forEach(a=>console.warn(`[pubspec] ${a}`)),o.added.length>0&&console.log("Adding dependencies:",o.added.map(a=>`${a}: ${n.additions[a]||"any"}`).join(", "),n.sdk.dartSdkFloor?`(resolved for Dart ${n.sdk.dartSdkFloor})`:""),n.kept.forEach(({name:a,constraint:l})=>console.log(`Keeping your existing ${a}: ${l||"(non-version source)"}`)),{...o,overridden:i.overridden,warnings:n.warnings,remoteFiles:r.files}}function bv(t){const e=[],s=[];t.content.length>5e4&&s.push("Code file is large (>50KB). This may take longer to commit."),t.content.length>1e5&&e.push("Code file is too large (>100KB). Consider splitting into smaller components.");const r=t.content.split(` +`).length;r>500&&s.push(`Code has ${r} lines. Consider breaking it into smaller widgets.`),t.content.includes("setState")&&t.codeType===U.ACTION&&s.push("Using setState in a Custom Action may not work as expected. Consider using a Custom Widget."),t.content.includes("dynamic")&&!t.content.includes("?")&&s.push('Code uses "dynamic" types. Consider adding explicit types for better null safety.'),t.content.match(/Color\(0xFF[0-9A-Fa-f]{6}\)/)&&s.push("Code contains hardcoded colors. Consider using FlutterFlowTheme.of(context) for theme consistency.");const n=t.content.match(/print\s*\(/g);n&&n.length>3&&s.push(`Code contains ${n.length} print statements. Consider removing debug prints before committing.`);const i=Gg(t.content);if(i&&e.push(`FlutterFlow cannot format this code - ${i}. Fix or regenerate before committing.`),t.codeType===U.WIDGET){const o=Ed(t.content),a=zg(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=`${Sd(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:s}}function Zd(t,e={}){const{artifactType:s="CustomWidget",artifactName:r="GeneratedCode",fileName:n}=e,i=Hg(t);let o=n||r;if(s==="CustomFunction")o="custom_functions.dart";else if(s==="CustomWidget"){const u=Ed(i)[0],c=u?Sd(u):null;c&&o!==c?(console.warn(`Commit file name "${o}" does not match declared widget class "${u}"; renaming to "${c}" so FlutterFlow can find the widget.`),o=c):o.endsWith(".dart")||(o+=".dart")}else o.endsWith(".dart")||(o+=".dart");let a=U.CODE_FILE;switch(s){case"CustomAction":a=U.ACTION;break;case"CustomWidget":a=U.WIDGET;break;case"CustomFunction":a=U.FUNCTION;break;case"CustomClass":case"CodeFile":a=U.CODE_FILE;break}let l="";return a===U.WIDGET?l=`// Automatic FlutterFlow imports import '/flutter_flow/flutter_flow_theme.dart'; import '/flutter_flow/flutter_flow_util.dart'; import 'package:flutter/material.dart'; @@ -109,46 +109,46 @@ import '/flutter_flow/lat_lng.dart'; import '/flutter_flow/place.dart'; import '/flutter_flow/uploaded_file.dart'; -`),{content:_g(i,l),fileName:o,codeType:a,artifactType:s,artifactName:n}}function Sv(t){const e={};for(const s of oa(t))e[s]="";return e}function xv(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 kv(t,e,s,n=new Set,r=""){const i=[],o=Kd.test(e),a=Jd.test(e);return s===U.WIDGET&&!o&&!a&&i.push("No widget class definition found (must extend StatelessWidget or StatefulWidget)"),{valid:i.length===0,errors:i}}function Vr(t){const e=[],s=[];if(!t||t.size===0)return e.push("No files to commit"),{valid:!1,errors:e,warnings:s};const n=new Set(Array.from(t.values()).flatMap(r=>Nr(r.content||"")));for(const[r,i]of t.entries()){if((!i.content||i.content.trim().length===0)&&e.push(`File ${r} is empty`),i.content&&i.content.length>1e5&&s.push(`File ${r} is very large (>100KB)`),r.endsWith(".dart")){const o=kv(r,i.content,i.type,n,i.artifactName);o.valid||e.push(...o.errors.map(a=>`${r}: ${a}`))}if(r==="pubspec.yaml"){const o=$d(i.content);o.valid||e.push(...o.errors)}}return{valid:e.length===0,errors:e,warnings:s}}const V={IDLE:"IDLE",PREPARING:"PREPARING",VALIDATING:"VALIDATING",PUSHING:"PUSHING",SUCCESS:"SUCCESS",ERROR:"ERROR"},K={currentState:V.IDLE,startTime:null,endTime:null,error:null,result:null,filesProcessed:0,totalFiles:0,reset(){this.currentState=V.IDLE,this.startTime=null,this.endTime=null,this.error=null,this.result=null,this.filesProcessed=0,this.totalFiles=0},setState(t){if(!Object.values(V).includes(t)){console.error(`Invalid commit state: ${t}`);return}this.currentState=t,t===V.PREPARING&&(this.startTime=Date.now()),(t===V.SUCCESS||t===V.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(V.ERROR)},setSuccess(t){this.result=t,this.setState(V.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===V.PREPARING||this.currentState===V.VALIDATING||this.currentState===V.PUSHING}};async function Iv(t,e,s={}){let{codeType:n="W"}=s;const{pubspecDeps:r={},artifactName:i=e}=s;n==="CustomWidget"&&(n=U.WIDGET),n==="CustomAction"&&(n=U.ACTION),n==="CustomFunction"&&(n=U.FUNCTION),n==="CustomClass"&&(n=U.CODE_FILE),n==="CodeFile"&&(n=U.CODE_FILE),K.reset(),K.setState(V.PREPARING);try{const o=await Ee("flutterflow"),a=await Ee("flutterflow_project_id");if(!o||!a)throw new Error("FlutterFlow credentials not configured. Please set your API key and Project ID in the API Keys settings.");if(!Hr(a))throw new Error("Invalid FlutterFlow Project ID format.");const l=gn(),u=new mn(o,a,"main",l);K.setState(V.VALIDATING);const c=new Map,d=n||bv(e,t),h=Yd(e,d);c.set(e,{artifactName:i,content:t,type:d,path:h}),K.setProgress(0,c.size);const p=Vr(c);if(!p.valid)throw new Error(`Validation failed: +`),{content:vg(i,l),fileName:o,codeType:a,artifactType:s,artifactName:r}}function Ev(t){const e={};for(const s of oa(t))e[s]="";return e}function Sv(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 xv(t,e,s,r=new Set,n=""){const i=[],o=Gd.test(e),a=Kd.test(e);return s===U.WIDGET&&!o&&!a&&i.push("No widget class definition found (must extend StatelessWidget or StatefulWidget)"),{valid:i.length===0,errors:i}}function Vn(t){const e=[],s=[];if(!t||t.size===0)return e.push("No files to commit"),{valid:!1,errors:e,warnings:s};const r=new Set(Array.from(t.values()).flatMap(n=>Nn(n.content||"")));for(const[n,i]of t.entries()){if((!i.content||i.content.trim().length===0)&&e.push(`File ${n} is empty`),i.content&&i.content.length>1e5&&s.push(`File ${n} is very large (>100KB)`),n.endsWith(".dart")){const o=xv(n,i.content,i.type,r,i.artifactName);o.valid||e.push(...o.errors.map(a=>`${n}: ${a}`))}if(n==="pubspec.yaml"){const o=Ad(i.content);o.valid||e.push(...o.errors)}}return{valid:e.length===0,errors:e,warnings:s}}const V={IDLE:"IDLE",PREPARING:"PREPARING",VALIDATING:"VALIDATING",PUSHING:"PUSHING",SUCCESS:"SUCCESS",ERROR:"ERROR"},K={currentState:V.IDLE,startTime:null,endTime:null,error:null,result:null,filesProcessed:0,totalFiles:0,reset(){this.currentState=V.IDLE,this.startTime=null,this.endTime=null,this.error=null,this.result=null,this.filesProcessed=0,this.totalFiles=0},setState(t){if(!Object.values(V).includes(t)){console.error(`Invalid commit state: ${t}`);return}this.currentState=t,t===V.PREPARING&&(this.startTime=Date.now()),(t===V.SUCCESS||t===V.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(V.ERROR)},setSuccess(t){this.result=t,this.setState(V.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===V.PREPARING||this.currentState===V.VALIDATING||this.currentState===V.PUSHING}};async function kv(t,e,s={}){let{codeType:r="W"}=s;const{pubspecDeps:n={},artifactName:i=e}=s;r==="CustomWidget"&&(r=U.WIDGET),r==="CustomAction"&&(r=U.ACTION),r==="CustomFunction"&&(r=U.FUNCTION),r==="CustomClass"&&(r=U.CODE_FILE),r==="CodeFile"&&(r=U.CODE_FILE),K.reset(),K.setState(V.PREPARING);try{const o=await Ee("flutterflow"),a=await Ee("flutterflow_project_id");if(!o||!a)throw new Error("FlutterFlow credentials not configured. Please set your API key and Project ID in the API Keys settings.");if(!Hn(a))throw new Error("Invalid FlutterFlow Project ID format.");const l=fr(),u=new gr(o,a,"main",l);K.setState(V.VALIDATING);const c=new Map,d=r||wv(e,t),h=Jd(e,d);c.set(e,{artifactName:i,content:t,type:d,path:h}),K.setProgress(0,c.size);const p=Vn(c);if(!p.valid)throw new Error(`Validation failed: ${p.errors.join(` -`)}`);const f=await xa(u,r),g=f.yaml,m=await Sa(u,c,f.remoteFiles,`Provision ${i} custom class`,g),_=await Ea(m.syncFileMap,m.remoteFiles),w=new Map(m.syncFileMap);w.set("pubspec.yaml",{content:g,type:"D",path:"pubspec.yaml"}),be.set("package");const E=await ka(w),I={project_id:a,zipped_custom_code:E,uid:`web_${Date.now()}`,branch_name:u.branchName,serialized_yaml:g,file_map:_.fileMapContents,functions_map:_.functionsMapContents};K.setState(V.PUSHING),K.setProgress(1,c.size),qr(u),be.set("push");const F=await u.pushCode(I),P=await wa(F);if(P.success)K.setSuccess({fileCount:c.size,projectId:a,warnings:P.errorMap&&P.errorMap.size>0?Array.from(P.errorMap.entries()):[]});else{const B=P.errorMessage||ba(P.responseCode);throw new Error(B)}return{success:!0,message:`Successfully committed ${e} to FlutterFlow project ${a}`,addedDependencies:f.added,unverified:m.unverified,warnings:P.errorMap?Array.from(P.errorMap.entries()):[]}}catch(o){return console.error("Commit failed:",o),K.setError(o),{success:!1,error:o.message,state:K.currentState}}}async function ka(t){const e=new JSZip;for(const[s,n]of t.entries())e.file(s,n.content);return e.generateAsync({type:"base64",compression:"DEFLATE",compressionOptions:{level:6}})}async function Cv(t,e={}){const{artifactType:s,artifactName:n,fileName:r,pipelineResult:i}=e;console.log(`Starting commit for ${n} (${s})`);try{K.setState(V.PREPARING);const o=Xd(t,{artifactType:s,artifactName:n,fileName:r}),a=Sv(o.content);console.log("Detected dependencies:",a),K.setState(V.VALIDATING);const l=await Ee("flutterflow"),u=Zs||await Ee("flutterflow_project_id");if(!l)throw new Error("FlutterFlow API Key not configured. Please add it in API Keys settings.");if(!u)throw new Error("FlutterFlow Project ID not configured. Please add it in API Keys settings.");if(!Hr(u))throw new Error("Invalid FlutterFlow Project ID format.");const c=new Map;c.set(o.fileName,{artifactName:n,content:o.content,type:o.codeType,path:Yd(o.fileName,o.codeType),functionName:o.codeType===U.FUNCTION?n:void 0}),K.setProgress(0,c.size);const d=Vr(c);if(!d.valid)throw new Error(`File validation failed: +`)}`);const f=await xa(u,n),m=f.yaml,g=await Sa(u,c,f.remoteFiles,`Provision ${i} custom class`,m),_=await Ea(g.syncFileMap,g.remoteFiles),w=new Map(g.syncFileMap);w.set("pubspec.yaml",{content:m,type:"D",path:"pubspec.yaml"}),be.set("package");const b=await ka(w),I={project_id:a,zipped_custom_code:b,uid:`web_${Date.now()}`,branch_name:u.branchName,serialized_yaml:m,file_map:_.fileMapContents,functions_map:_.functionsMapContents};K.setState(V.PUSHING),K.setProgress(1,c.size),qn(u),be.set("push");const F=await u.pushCode(I),P=await wa(F);if(P.success)K.setSuccess({fileCount:c.size,projectId:a,warnings:P.errorMap&&P.errorMap.size>0?Array.from(P.errorMap.entries()):[]});else{const j=P.errorMessage||ba(P.responseCode);throw new Error(j)}return{success:!0,message:`Successfully committed ${e} to FlutterFlow project ${a}`,addedDependencies:f.added,unverified:g.unverified,approximate:g.approximate,warnings:P.errorMap?Array.from(P.errorMap.entries()):[]}}catch(o){return console.error("Commit failed:",o),K.setError(o),{success:!1,error:o.message,state:K.currentState}}}async function ka(t){const e=new JSZip;for(const[s,r]of t.entries())e.file(s,r.content);return e.generateAsync({type:"base64",compression:"DEFLATE",compressionOptions:{level:6}})}async function Iv(t,e={}){const{artifactType:s,artifactName:r,fileName:n,pipelineResult:i}=e;console.log(`Starting commit for ${r} (${s})`);try{K.setState(V.PREPARING);const o=Zd(t,{artifactType:s,artifactName:r,fileName:n}),a=Ev(o.content);console.log("Detected dependencies:",a),K.setState(V.VALIDATING);const l=await Ee("flutterflow"),u=Zs||await Ee("flutterflow_project_id");if(!l)throw new Error("FlutterFlow API Key not configured. Please add it in API Keys settings.");if(!u)throw new Error("FlutterFlow Project ID not configured. Please add it in API Keys settings.");if(!Hn(u))throw new Error("Invalid FlutterFlow Project ID format.");const c=new Map;c.set(o.fileName,{artifactName:r,content:o.content,type:o.codeType,path:Jd(o.fileName,o.codeType),functionName:o.codeType===U.FUNCTION?r:void 0}),K.setProgress(0,c.size);const d=Vn(c);if(!d.valid)throw new Error(`File validation failed: ${d.errors.join(` -`)}`);d.warnings.length>0&&console.warn("Validation warnings:",d.warnings),K.setState(V.PUSHING);const h=gn(),p=new mn(l,u,"main",h),f=await xa(p,a),g=f.yaml,m=await Sa(p,c,f.remoteFiles,`Provision ${n} custom class`,g),_=await Ea(m.syncFileMap,m.remoteFiles),w=new Map(m.syncFileMap);w.set("pubspec.yaml",{content:g,type:U.DEPENDENCIES,path:"pubspec.yaml"}),be.set("package");const E=await ka(w),I={project_id:u,zipped_custom_code:E,uid:`web_${Date.now()}`,branch_name:p.branchName,serialized_yaml:g,file_map:_.fileMapContents,functions_map:_.functionsMapContents};K.setProgress(1,c.size),qr(p),be.set("push");const F=await p.pushCode(I),P=await wa(F);if(P.success){const B={...xv(o,i),projectId:u};return K.setSuccess({...B,fileCount:c.size,warnings:P.errorMap?Array.from(P.errorMap.entries()):[]}),{success:!0,message:`Successfully committed ${o.fileName} to FlutterFlow`,metadata:B,addedDependencies:f.added,unverified:m.unverified,warnings:P.errorMap?Array.from(P.errorMap.entries()):[],elapsedTime:K.getElapsedTime()}}else{const B=P.errorMessage||ba(P.responseCode),S=new Error(B);throw S.errorMap=P.errorMap,S}}catch(o){console.error("Commit execution failed:",o),K.setError(o);let a=new Map;if(o.errorMap)a=o.errorMap;else if(o.message&&o.message.includes("{"))try{const l=o.message.match(/\{[\s\S]*\}/);if(l){const u=JSON.parse(l[0]);a=new Map(Object.entries(u))}}catch(l){console.warn("Failed to parse error map from commit response:",l)}return{success:!1,error:o.message,errorMap:a,state:K.currentState,elapsedTime:K.getElapsedTime()}}}async function Fv(t,e={}){const{pipelineResult:s}=e;try{if(K.setState(V.PREPARING),t.errors?.length>0)throw new Error(`Bundle validation failed: +`)}`);d.warnings.length>0&&console.warn("Validation warnings:",d.warnings),K.setState(V.PUSHING);const h=fr(),p=new gr(l,u,"main",h),f=await xa(p,a),m=f.yaml,g=await Sa(p,c,f.remoteFiles,`Provision ${r} custom class`,m),_=await Ea(g.syncFileMap,g.remoteFiles),w=new Map(g.syncFileMap);w.set("pubspec.yaml",{content:m,type:U.DEPENDENCIES,path:"pubspec.yaml"}),be.set("package");const b=await ka(w),I={project_id:u,zipped_custom_code:b,uid:`web_${Date.now()}`,branch_name:p.branchName,serialized_yaml:m,file_map:_.fileMapContents,functions_map:_.functionsMapContents};K.setProgress(1,c.size),qn(p),be.set("push");const F=await p.pushCode(I),P=await wa(F);if(P.success){const j={...Sv(o,i),projectId:u};return K.setSuccess({...j,fileCount:c.size,warnings:P.errorMap?Array.from(P.errorMap.entries()):[]}),{success:!0,message:`Successfully committed ${o.fileName} to FlutterFlow`,metadata:j,addedDependencies:f.added,unverified:g.unverified,approximate:g.approximate,warnings:P.errorMap?Array.from(P.errorMap.entries()):[],elapsedTime:K.getElapsedTime()}}else{const j=P.errorMessage||ba(P.responseCode),S=new Error(j);throw S.errorMap=P.errorMap,S}}catch(o){console.error("Commit execution failed:",o),K.setError(o);let a=new Map;if(o.errorMap)a=o.errorMap;else if(o.message&&o.message.includes("{"))try{const l=o.message.match(/\{[\s\S]*\}/);if(l){const u=JSON.parse(l[0]);a=new Map(Object.entries(u))}}catch(l){console.warn("Failed to parse error map from commit response:",l)}return{success:!1,error:o.message,errorMap:a,state:K.currentState,elapsedTime:K.getElapsedTime()}}}async function Cv(t,e={}){const{pipelineResult:s}=e;try{if(K.setState(V.PREPARING),t.errors?.length>0)throw new Error(`Bundle validation failed: ${t.errors.join(` -`)}`);const n=new Map(t.fileEntries.map(I=>[I.fileName,{artifactId:I.artifactId,artifactName:I.artifactName,content:I.content,type:I.type,path:I.path,functionName:I.type===U.FUNCTION?I.artifactName:void 0}]));K.setProgress(0,n.size);const r=Vr(n);if(!r.valid)throw new Error(`File validation failed: -${r.errors.join(` -`)}`);K.setState(V.VALIDATING);const i=await Ee("flutterflow"),o=Zs||await Ee("flutterflow_project_id");if(!i)throw new Error("FlutterFlow API Key not configured. Please add it in API Keys settings.");if(!o)throw new Error("FlutterFlow Project ID not configured. Please add it in API Keys settings.");if(!Hr(o))throw new Error("Invalid FlutterFlow Project ID format.");K.setState(V.PUSHING);const a=gn(),l=new mn(i,o,"main",a),u=await xa(l,t.dependencies),c=u.yaml,d=await Sa(l,n,u.remoteFiles,`Provision ${t.title} custom classes`,c),h=await Ea(d.syncFileMap,d.remoteFiles),p=new Map(d.syncFileMap);p.set("pubspec.yaml",{content:c,type:U.DEPENDENCIES,path:"pubspec.yaml"}),be.set("package");const f=await ka(p),g={project_id:o,zipped_custom_code:f,uid:`web_${Date.now()}`,branch_name:l.branchName,serialized_yaml:c,file_map:h.fileMapContents,functions_map:h.functionsMapContents};K.setProgress(1,n.size),qr(l),be.set("push");const m=await l.pushCode(g),_=await wa(m);if(_.success){const I={...s,artifactType:"Bundle",artifactName:t.title,fileName:`${t.fileEntries.length} artifacts`,codeSize:t.fileEntries.reduce((F,P)=>F+P.content.length,0),projectId:o};return K.setSuccess({...I,fileCount:n.size,warnings:_.errorMap?Array.from(_.errorMap.entries()):[]}),{success:!0,message:`Successfully committed ${t.fileEntries.length} artifacts to FlutterFlow`,metadata:I,addedDependencies:u.added,unverified:d.unverified,warnings:_.errorMap?Array.from(_.errorMap.entries()):[],elapsedTime:K.getElapsedTime()}}const w=_.errorMessage||ba(_.responseCode),E=new Error(w);throw E.errorMap=_.errorMap,E}catch(n){return console.error("Bundle commit execution failed:",n),K.setError(n),{success:!1,error:n.message,errorMap:n.errorMap||new Map,state:K.currentState,elapsedTime:K.getElapsedTime()}}}async function Pv(t,e=[]){const s=sa("architect");try{return await Cr("architect",Od,Bf(t),s,e)}catch(n){throw n.isModelArmor?n:new Error(`Prompt Architect failed: ${n.message}`)}}async function Gr(t,e,s=[]){const n=jf(t),r=sa("generator",y.bundleSpec);try{return await Cr("generator",e,n,r,s)}catch(i){if(i.isModelArmor)throw i;if(e!==$i){console.warn(`Code Generator failed with ${e}, retrying with fallback model:`,i.message);try{return await Cr("generator",$i,n,r,s)}catch(o){throw o.isModelArmor?o:new Error(`Code Generator failed: primary (${e}): ${i.message} | fallback (${$i}): ${o.message}`)}}throw new Error(`Code Generator failed: ${i.message}`)}}async function Kr(t,e=null){const s={...sa("review",y.artifactBundle||y.bundleSpec),architect_output:e};try{return await Cr("review",Dd,Uf(t),s)}catch(n){throw n.isModelArmor?n:new Error(`Code Review failed: ${n.message}`)}}function Ia(t,e){return t.isModelArmor?`${t.userTitle}: ${t.userMessage}`:`${e}: ${t.message}`}function $o(t,e){const s=document.getElementById(`step${t}-item`),n=document.getElementById(`step${t}-status`);!s||!n||(s.classList.remove("active","completed","error"),n.classList.remove("running","completed","error"),e==="active"?(s.classList.add("active"),n.classList.add("running"),n.innerHTML=` +`)}`);const r=new Map(t.fileEntries.map(I=>[I.fileName,{artifactId:I.artifactId,artifactName:I.artifactName,content:I.content,type:I.type,path:I.path,functionName:I.type===U.FUNCTION?I.artifactName:void 0}]));K.setProgress(0,r.size);const n=Vn(r);if(!n.valid)throw new Error(`File validation failed: +${n.errors.join(` +`)}`);K.setState(V.VALIDATING);const i=await Ee("flutterflow"),o=Zs||await Ee("flutterflow_project_id");if(!i)throw new Error("FlutterFlow API Key not configured. Please add it in API Keys settings.");if(!o)throw new Error("FlutterFlow Project ID not configured. Please add it in API Keys settings.");if(!Hn(o))throw new Error("Invalid FlutterFlow Project ID format.");K.setState(V.PUSHING);const a=fr(),l=new gr(i,o,"main",a),u=await xa(l,t.dependencies),c=u.yaml,d=await Sa(l,r,u.remoteFiles,`Provision ${t.title} custom classes`,c),h=await Ea(d.syncFileMap,d.remoteFiles),p=new Map(d.syncFileMap);p.set("pubspec.yaml",{content:c,type:U.DEPENDENCIES,path:"pubspec.yaml"}),be.set("package");const f=await ka(p),m={project_id:o,zipped_custom_code:f,uid:`web_${Date.now()}`,branch_name:l.branchName,serialized_yaml:c,file_map:h.fileMapContents,functions_map:h.functionsMapContents};K.setProgress(1,r.size),qn(l),be.set("push");const g=await l.pushCode(m),_=await wa(g);if(_.success){const I={...s,artifactType:"Bundle",artifactName:t.title,fileName:`${t.fileEntries.length} artifacts`,codeSize:t.fileEntries.reduce((F,P)=>F+P.content.length,0),projectId:o};return K.setSuccess({...I,fileCount:r.size,warnings:_.errorMap?Array.from(_.errorMap.entries()):[]}),{success:!0,message:`Successfully committed ${t.fileEntries.length} artifacts to FlutterFlow`,metadata:I,addedDependencies:u.added,unverified:d.unverified,approximate:d.approximate,warnings:_.errorMap?Array.from(_.errorMap.entries()):[],elapsedTime:K.getElapsedTime()}}const w=_.errorMessage||ba(_.responseCode),b=new Error(w);throw b.errorMap=_.errorMap,b}catch(r){return console.error("Bundle commit execution failed:",r),K.setError(r),{success:!1,error:r.message,errorMap:r.errorMap||new Map,state:K.currentState,elapsedTime:K.getElapsedTime()}}}async function Fv(t,e=[]){const s=sa("architect");try{return await Cn("architect",Ld,Df(t),s,e)}catch(r){throw r.isModelArmor?r:new Error(`Prompt Architect failed: ${r.message}`)}}async function Gn(t,e,s=[]){const r=Bf(t),n=sa("generator",y.bundleSpec);try{return await Cn("generator",e,r,n,s)}catch(i){if(i.isModelArmor)throw i;if(e!==$i){console.warn(`Code Generator failed with ${e}, retrying with fallback model:`,i.message);try{return await Cn("generator",$i,r,n,s)}catch(o){throw o.isModelArmor?o:new Error(`Code Generator failed: primary (${e}): ${i.message} | fallback (${$i}): ${o.message}`)}}throw new Error(`Code Generator failed: ${i.message}`)}}async function Kn(t,e=null){const s={...sa("review",y.artifactBundle||y.bundleSpec),architect_output:e};try{return await Cn("review",Od,jf(t),s)}catch(r){throw r.isModelArmor?r:new Error(`Code Review failed: ${r.message}`)}}function Ia(t,e){return t.isModelArmor?`${t.userTitle}: ${t.userMessage}`:`${e}: ${t.message}`}function $o(t,e){const s=document.getElementById(`step${t}-item`),r=document.getElementById(`step${t}-status`);!s||!r||(s.classList.remove("active","completed","error"),r.classList.remove("running","completed","error"),e==="active"?(s.classList.add("active"),r.classList.add("running"),r.innerHTML=` - `):e==="completed"?(s.classList.add("completed"),n.classList.add("completed"),n.innerHTML=` + `):e==="completed"?(s.classList.add("completed"),r.classList.add("completed"),r.innerHTML=` - `):e==="error"?(s.classList.add("error"),n.classList.add("error"),n.innerHTML=` + `):e==="error"?(s.classList.add("error"),r.classList.add("error"),r.innerHTML=` - `):n.innerHTML=` + `):r.innerHTML=` - `)}function ve(t,e){const s=document.getElementById(`step${t}-loading`),n=document.getElementById(`step${t}-result`);e?(s.classList.remove("hidden"),n.classList.add("hidden"),$o(t,"active")):(s.classList.add("hidden"),n.classList.remove("hidden"),$o(t,"completed"))}function Av(t){const e=document.getElementById(`${t}-content`),s=document.getElementById(`${t}-chevron`);e.classList.contains("open")?(e.classList.remove("open"),s&&(s.style.transform="rotate(0deg)")):(e.classList.add("open"),s&&(s.style.transform="rotate(180deg)"))}function $v(t){ze(parseInt(t.replace("step","")))}function ze(t){for(let o=1;o<=3;o++){const a=document.getElementById(`step${o}-item`);a&&a.classList.remove("active")}const e=document.getElementById(`step${t}-item`);e&&e.classList.add("active"),Yt();const s=document.getElementById("ready-state");s&&s.classList.add("hidden");for(let o=1;o<=3;o++){const a=document.getElementById(`step${o}-content`);a&&a.classList.add("hidden")}const n=document.getElementById(`step${t}-content`);n&&n.classList.remove("hidden");const r=document.getElementById("stage-title"),i={1:"Prompt Architect",2:"Code Generator",3:"Code Review"};r&&(r.textContent=i[t]||"Active Workflow Stage")}function Rv(t){const e=document.getElementById(t);if(!e)return;const s=e.dataset.raw||e.textContent;navigator.clipboard.writeText(s).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(n=>{console.warn("Failed to copy to clipboard:",n)})}function Ro(t){const e=No(t);console.log(`Step 1 (Prompt Architect): ${zt(Od)}`),console.log(e!==t?`Step 2 (Code Generator): ${zt(t)} → ${zt(e)} (Free Tier fallback)`:`Step 2 (Code Generator): ${zt(t)}`),console.log(`Step 3 (Code Review): ${zt(Dd)}`)}async function Tv(){if(console.log("runRefinement called"),y.isRunning)return;const t=document.getElementById("code-generator-model").value;y.isRunning=!0,Ca("standardRegenerate",y.step2Result,y.step1Result);const e=document.querySelectorAll(".btn-refine-action");e.forEach(s=>{s.disabled=!0,s.innerHTML=` + `)}function ve(t,e){const s=document.getElementById(`step${t}-loading`),r=document.getElementById(`step${t}-result`);e?(s.classList.remove("hidden"),r.classList.add("hidden"),$o(t,"active")):(s.classList.add("hidden"),r.classList.remove("hidden"),$o(t,"completed"))}function Pv(t){const e=document.getElementById(`${t}-content`),s=document.getElementById(`${t}-chevron`);e.classList.contains("open")?(e.classList.remove("open"),s&&(s.style.transform="rotate(0deg)")):(e.classList.add("open"),s&&(s.style.transform="rotate(180deg)"))}function Av(t){ze(parseInt(t.replace("step","")))}function ze(t){for(let o=1;o<=3;o++){const a=document.getElementById(`step${o}-item`);a&&a.classList.remove("active")}const e=document.getElementById(`step${t}-item`);e&&e.classList.add("active"),Yt();const s=document.getElementById("ready-state");s&&s.classList.add("hidden");for(let o=1;o<=3;o++){const a=document.getElementById(`step${o}-content`);a&&a.classList.add("hidden")}const r=document.getElementById(`step${t}-content`);r&&r.classList.remove("hidden");const n=document.getElementById("stage-title"),i={1:"Prompt Architect",2:"Code Generator",3:"Code Review"};n&&(n.textContent=i[t]||"Active Workflow Stage")}function $v(t){const e=document.getElementById(t);if(!e)return;const s=e.dataset.raw||e.textContent;navigator.clipboard.writeText(s).then(()=>{const n=e.closest(".code-container")?.querySelector(".copy-btn");n&&(n.classList.add("copied"),n.innerHTML=' Copied!',setTimeout(()=>{n.classList.remove("copied"),n.innerHTML=' Copy'},2e3))}).catch(r=>{console.warn("Failed to copy to clipboard:",r)})}function Ro(t){const e=No(t);console.log(`Step 1 (Prompt Architect): ${zt(Ld)}`),console.log(e!==t?`Step 2 (Code Generator): ${zt(t)} → ${zt(e)} (Free Tier fallback)`:`Step 2 (Code Generator): ${zt(t)}`),console.log(`Step 3 (Code Review): ${zt(Od)}`)}async function Rv(){if(console.log("runRefinement called"),y.isRunning)return;const t=document.getElementById("code-generator-model").value;y.isRunning=!0,Ca("standardRegenerate",y.step2Result,y.step1Result);const e=document.querySelectorAll(".btn-refine-action");e.forEach(s=>{s.disabled=!0,s.innerHTML=` - Refining...`});try{const s=_a(),n=Hf({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,artifactId:s.id,userFeedback:"Fix the issues listed in the audit report."});Zr(),rt(2),ze(2),ve(2,!0),y.step2Result=await Gr(n,t),Wr();const r=document.getElementById("step2-output"),i=ws(y.step2Result);r.textContent=i,r.dataset.raw=i,ve(2,!1),ze(3),rt(3),ve(3,!0),y.step3Result=await Kr(y.step2Result,y.step1Result),zr();const o=document.getElementById("step3-output");o.textContent=y.step3Result,ve(3,!1),$t();const a=jr(y.step3Result);Xr(i,a)}catch(s){console.error("Refinement failed:",s),$t(),ue(Ia(s,"Refinement failed"),"error")}finally{y.isRunning=!1,e.forEach(s=>{s.disabled=!1,s.textContent="Refine & Regenerate"}),Zt()}}async function Ca(t,e,s){const n=`${Je}/connectFeedback`,r={type:t,code:e,input:s};try{const i=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!i.ok){const a=await i.text();return console.error(`callEndpoint failed: ${i.status} ${i.statusText}`,a),{success:!1,status:i.status,error:a}}const o=await i.json();return console.log("Telemetry success:",o),o}catch(i){return console.error("callEndpoint failed:",i),{success:!1,error:i.message}}}function Nv(){const t=document.getElementById("ff-error-paste-input");t&&(t.value="")}async function Mv(){const t=document.getElementById("ff-error-paste-input"),e=t?.value?.trim();if(!e){t?.focus(),t?.classList.add("ring-2","ring-red-400","border-red-300"),setTimeout(()=>t?.classList.remove("ring-2","ring-red-400","border-red-300"),2e3);return}if(!y.step2Result){ue("No generated code found. Please run the full pipeline first.","warning");return}if(y.isRunning)return;const s=document.getElementById("code-generator-model").value;y.isRunning=!0,Ca("flutterflowError",y.step2Result,e);const n=document.getElementById("btn-fix-from-errors");n&&(n.disabled=!0,n.innerHTML=` + Refining...`});try{const s=_a(),r=Uf({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,artifactId:s.id,userFeedback:"Fix the issues listed in the audit report."});Zn(),nt(2),ze(2),ve(2,!0),y.step2Result=await Gn(r,t),Wn();const n=document.getElementById("step2-output"),i=ws(y.step2Result);n.textContent=i,n.dataset.raw=i,ve(2,!1),ze(3),nt(3),ve(3,!0),y.step3Result=await Kn(y.step2Result,y.step1Result),zn();const o=document.getElementById("step3-output");o.textContent=y.step3Result,ve(3,!1),$t();const a=jn(y.step3Result);Xn(i,a)}catch(s){console.error("Refinement failed:",s),$t(),ue(Ia(s,"Refinement failed"),"error")}finally{y.isRunning=!1,e.forEach(s=>{s.disabled=!1,s.textContent="Refine & Regenerate"}),Zt()}}async function Ca(t,e,s){const r=`${Je}/connectFeedback`,n={type:t,code:e,input:s};try{const i=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!i.ok){const a=await i.text();return console.error(`callEndpoint failed: ${i.status} ${i.statusText}`,a),{success:!1,status:i.status,error:a}}const o=await i.json();return console.log("Telemetry success:",o),o}catch(i){return console.error("callEndpoint failed:",i),{success:!1,error:i.message}}}function Tv(){const t=document.getElementById("ff-error-paste-input");t&&(t.value="")}async function Nv(){const t=document.getElementById("ff-error-paste-input"),e=t?.value?.trim();if(!e){t?.focus(),t?.classList.add("ring-2","ring-red-400","border-red-300"),setTimeout(()=>t?.classList.remove("ring-2","ring-red-400","border-red-300"),2e3);return}if(!y.step2Result){ue("No generated code found. Please run the full pipeline first.","warning");return}if(y.isRunning)return;const s=document.getElementById("code-generator-model").value;y.isRunning=!0,Ca("flutterflowError",y.step2Result,e);const r=document.getElementById("btn-fix-from-errors");r&&(r.disabled=!0,r.innerHTML=` - Fixing…`);try{const r=vd({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,userFeedback:e});dh(),Zr(),rt(2),ze(2),ve(2,!0),y.step2Result=await Gr(r,s),Wr();const i=document.getElementById("step2-output"),o=ws(y.step2Result);i.textContent=o,i.dataset.raw=o,ve(2,!1),ze(3),rt(3),ve(3,!0),y.step3Result=await Kr(y.step2Result,y.step1Result),zr();const a=document.getElementById("step3-output");a.textContent=y.step3Result,ve(3,!1),$t();const l=jr(y.step3Result);Xr(o,l),t&&(t.value="")}catch(r){console.error("Fix from errors failed:",r),$t(),ue(Ia(r,"Failed to fix errors"),"error")}finally{y.isRunning=!1,n&&(n.disabled=!1,n.textContent="Fix Errors & Regenerate"),Zt()}}async function To(){if(console.log("runThinkingPipeline called"),y.isRunning)return;localStorage.setItem("hasSeenWalkthrough","true");const t=document.getElementById("pipeline-input").value,e=document.getElementById("code-generator-model").value;if(!t.trim()){ue("Please describe your FlutterFlow widget first.","warning");return}if(!await t_())return;await Jv();const s=No(e);t.length;const n=document.getElementById("btn-run-pipeline");y.isRunning=!0,vv(),n.disabled=!0,n.innerHTML=` + Fixing…`);try{const n=vd({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,userFeedback:e});uh(),Zn(),nt(2),ze(2),ve(2,!0),y.step2Result=await Gn(n,s),Wn();const i=document.getElementById("step2-output"),o=ws(y.step2Result);i.textContent=o,i.dataset.raw=o,ve(2,!1),ze(3),nt(3),ve(3,!0),y.step3Result=await Kn(y.step2Result,y.step1Result),zn();const a=document.getElementById("step3-output");a.textContent=y.step3Result,ve(3,!1),$t();const l=jn(y.step3Result);Xn(o,l),t&&(t.value="")}catch(n){console.error("Fix from errors failed:",n),$t(),ue(Ia(n,"Failed to fix errors"),"error")}finally{y.isRunning=!1,r&&(r.disabled=!1,r.textContent="Fix Errors & Regenerate"),Zt()}}async function To(){if(console.log("runThinkingPipeline called"),y.isRunning)return;localStorage.setItem("hasSeenWalkthrough","true");const t=document.getElementById("pipeline-input").value,e=document.getElementById("code-generator-model").value;if(!t.trim()){ue("Please describe your FlutterFlow widget first.","warning");return}if(!await e_())return;await Kv();const s=No(e);t.length;const r=document.getElementById("btn-run-pipeline");y.isRunning=!0,mv(),r.disabled=!0,r.innerHTML=` - Running...`,Ro(s);try{Yt();const r=document.getElementById("ready-state");r&&r.classList.add("hidden");const i=document.getElementById("paywall-exhausted");i&&i.classList.add("hidden"),Zr(),ze(1),rt(1),ve(1,!0);const o=Pt.filter(p=>p.url).map(p=>({url:p.url}));y.step1Result=await Pv(t,o),_v();const a=document.getElementById("step1-output"),l=ws(y.step1Result);a.textContent=l,a.dataset.raw=l,ve(1,!1),ze(2),rt(2),ve(2,!0),y.step2Result=await Gr(y.step1Result,s,o),Wr();const u=document.getElementById("step2-output"),c=ws(y.step2Result);u.textContent=c,u.dataset.raw=c,ve(2,!1),ze(3),rt(3),ve(3,!0),y.step3Result=await Kr(y.step2Result,y.step1Result),zr();const d=document.getElementById("step3-output");d.textContent=y.step3Result,ve(3,!1),$t();const h=jr(y.step3Result);Xr(c,h)}catch(r){if(console.error("Pipeline failed:",r),$t(),r.isUsageLimit){const{count:c}=Jr();Ta(c,Ra(),{openModal:!0});return}r.message,No(document.getElementById("code-generator-model").value);const o=Am(r,{architect:1,generator:2,review:3});ze(o);const a=document.getElementById(`step${o}-result`),l=document.getElementById(`step${o}-loading`),u=document.getElementById(`step${o}-output`);if(l&&l.classList.add("hidden"),a&&a.classList.remove("hidden"),u)if(r.isModelArmor)u.innerHTML=``;else{let c=r.message;r.message.includes("image input")?c=`This model doesn't support image input. Please use ${zt(cn)} for image-based requests or remove image references from your prompt.`:(r.message.includes("Load failed")||r.message.includes("CORS"))&&(c="API connection failed. This might be due to CORS restrictions or network issues. Please check your API key and try again."),u.innerHTML=`
    + Running...`,Ro(s);try{Yt();const n=document.getElementById("ready-state");n&&n.classList.add("hidden");const i=document.getElementById("paywall-exhausted");i&&i.classList.add("hidden"),Zn(),ze(1),nt(1),ve(1,!0);const o=Pt.filter(p=>p.url).map(p=>({url:p.url}));y.step1Result=await Fv(t,o),vv();const a=document.getElementById("step1-output"),l=ws(y.step1Result);a.textContent=l,a.dataset.raw=l,ve(1,!1),ze(2),nt(2),ve(2,!0),y.step2Result=await Gn(y.step1Result,s,o),Wn();const u=document.getElementById("step2-output"),c=ws(y.step2Result);u.textContent=c,u.dataset.raw=c,ve(2,!1),ze(3),nt(3),ve(3,!0),y.step3Result=await Kn(y.step2Result,y.step1Result),zn();const d=document.getElementById("step3-output");d.textContent=y.step3Result,ve(3,!1),$t();const h=jn(y.step3Result);Xn(c,h)}catch(n){if(console.error("Pipeline failed:",n),$t(),n.isUsageLimit){const{count:c}=Jn();Ta(c,Ra(),{openModal:!0});return}n.message,No(document.getElementById("code-generator-model").value);const o=Pm(n,{architect:1,generator:2,review:3});ze(o);const a=document.getElementById(`step${o}-result`),l=document.getElementById(`step${o}-loading`),u=document.getElementById(`step${o}-output`);if(l&&l.classList.add("hidden"),a&&a.classList.remove("hidden"),u)if(n.isModelArmor)u.innerHTML=``;else{let c=n.message;n.message.includes("image input")?c=`This model doesn't support image input. Please use ${zt(lr)} for image-based requests or remove image references from your prompt.`:(n.message.includes("Load failed")||n.message.includes("CORS"))&&(c="API connection failed. This might be due to CORS restrictions or network issues. Please check your API key and try again."),u.innerHTML=`

    Connection Error

    -

    ${j(c)}

    +

    ${B(c)}

    Check if API key is valid

    Try using a different model

    Ensure network allows API calls

    -
    `}$o(o,"error")}finally{y.isRunning=!1,n.disabled=!1,n.innerHTML=` +
    `}$o(o,"error")}finally{y.isRunning=!1,r.disabled=!1,r.innerHTML=` - Run Pipeline`,Zt()}}function Lv(){const t=document.getElementById("code-generator-model").value,e=[cn,"anthropic/claude-opus-5","openai/gpt-5.6-sol"].filter(n=>n!==t),s=prompt(`Retry with different model? + Run Pipeline`,Zt()}}function Mv(){const t=document.getElementById("code-generator-model").value,e=[lr,"anthropic/claude-opus-5","openai/gpt-5.6-sol"].filter(r=>r!==t),s=prompt(`Retry with different model? Current: ${t} @@ -156,15 +156,15 @@ Options: 1. ${e[0]} 2. ${e[1]} -Enter 1 or 2:`);s==="1"?(document.getElementById("code-generator-model").value=e[0],To()):s==="2"&&(document.getElementById("code-generator-model").value=e[1],To())}async function Ov(){const t=ya();if(!t){ue("No code to commit. Please run the pipeline first.","warning");return}const e=await Ee("flutterflow"),s=await Ee("flutterflow_project_id");if(!e||!s){ue("FlutterFlow credentials not configured. Add your API Key and Project ID in settings.","warning"),ga();return}if(y.artifactBundle?.artifacts?.length>1){await Dv();return}const{artifactType:n,artifactName:r,fileName:i}=Gd(),o=Xd(t,{artifactType:n,artifactName:r,fileName:i}),a=Ev(o);if(!a.canProceed){ue(`Pre-commit checks failed: ${a.issues.join("; ")}`,"error");return}rh(o,a,null,null)}async function Dv(){const t=await Ee("flutterflow"),e=await Ee("flutterflow_project_id");if(!t||!e){ue("FlutterFlow credentials not configured. Add your API Key and Project ID in settings.","warning"),ga();return}const s=xg(y.artifactBundle);if(s.errors.length>0){ue(`Bundle validation failed: ${s.errors.join("; ")}`,"error");return}const n=new Map(s.fileEntries.map(a=>[a.fileName,{content:a.content,type:a.type,path:a.path}])),r=Vr(n),i={canProceed:r.valid&&s.errors.length===0,issues:[...s.errors,...r.errors],warnings:[...s.warnings,...r.warnings]};if(!i.canProceed){ue(`Bundle validation failed: ${i.issues.join("; ")}`,"error");return}const o={content:s.fileEntries.map(a=>`// ${a.fileName} +Enter 1 or 2:`);s==="1"?(document.getElementById("code-generator-model").value=e[0],To()):s==="2"&&(document.getElementById("code-generator-model").value=e[1],To())}async function Lv(){const t=ya();if(!t){ue("No code to commit. Please run the pipeline first.","warning");return}const e=await Ee("flutterflow"),s=await Ee("flutterflow_project_id");if(!e||!s){ue("FlutterFlow credentials not configured. Add your API Key and Project ID in settings.","warning"),ga();return}if(y.artifactBundle?.artifacts?.length>1){await Ov();return}const{artifactType:r,artifactName:n,fileName:i}=Vd(),o=Zd(t,{artifactType:r,artifactName:n,fileName:i}),a=bv(o);if(!a.canProceed){ue(`Pre-commit checks failed: ${a.issues.join("; ")}`,"error");return}rh(o,a,null,null)}async function Ov(){const t=await Ee("flutterflow"),e=await Ee("flutterflow_project_id");if(!t||!e){ue("FlutterFlow credentials not configured. Add your API Key and Project ID in settings.","warning"),ga();return}const s=xg(y.artifactBundle);if(s.errors.length>0){ue(`Bundle validation failed: ${s.errors.join("; ")}`,"error");return}const r=new Map(s.fileEntries.map(a=>[a.fileName,{content:a.content,type:a.type,path:a.path}])),n=Vn(r),i={canProceed:n.valid&&s.errors.length===0,issues:[...s.errors,...n.errors],warnings:[...s.warnings,...n.warnings]};if(!i.canProceed){ue(`Bundle validation failed: ${i.issues.join("; ")}`,"error");return}const o={content:s.fileEntries.map(a=>`// ${a.fileName} ${a.content}`).join(` -`),fileName:`${s.fileEntries.length} files`,codeType:"bundle",artifactType:"Bundle",artifactName:s.title};rh(o,i,s.dependencies,s)}function Bv(t){let e=t.errorMap||new Map;!(e instanceof Map)&&typeof e=="object"&&(e=new Map(Object.entries(e)));let s=`
    +`),fileName:`${s.fileEntries.length} files`,codeType:"bundle",artifactType:"Bundle",artifactName:s.title};rh(o,i,s.dependencies,s)}function Dv(t){let e=t.errorMap||new Map;!(e instanceof Map)&&typeof e=="object"&&(e=new Map(Object.entries(e)));let s=`

    FlutterFlow Commit Failed

    -

    ${j(t.error)}

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

    ${B(t.error)}

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

    Errors:

    -
      `;for(const[r,i]of e.entries()){const o=kd(i);s+=`
    • - ${j(r)}: ${j(o)} +
        `;for(const[n,i]of e.entries()){const o=xd(i);s+=`
      • + ${B(n)}: ${B(o)}
      • `}s+="
    "}s+="
    ",s+=`
    -
    `;const n=document.getElementById("step3-output");n&&(n.innerHTML=s,document.getElementById("btn-regenerate-from-error")?.addEventListener("click",()=>{jv(t.error,e)}))}async function jv(t,e){if(y.isRunning)return;const s=document.getElementById("code-generator-model").value;y.isRunning=!0;const n=document.getElementById("btn-regenerate-from-error");n&&(n.disabled=!0,n.innerHTML=` +
    `;const r=document.getElementById("step3-output");r&&(r.innerHTML=s,document.getElementById("btn-regenerate-from-error")?.addEventListener("click",()=>{Bv(t.error,e)}))}async function Bv(t,e){if(y.isRunning)return;const s=document.getElementById("code-generator-model").value;y.isRunning=!0;const r=document.getElementById("btn-regenerate-from-error");r&&(r.disabled=!0,r.innerHTML=` - Fixing...`);try{let r=`The previous code had the following errors when committing to FlutterFlow: + Fixing...`);try{let n=`The previous code had the following errors when committing to FlutterFlow: -`;if(e&&e.size>0)for(const[c,d]of e.entries()){const h=kd(d);r+=`File: ${c} +`;if(e&&e.size>0)for(const[c,d]of e.entries()){const h=xd(d);n+=`File: ${c} Error: ${h} -`}else r+=`${t} -`;const i=vd({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,userFeedback:r});Zr(),rt(2),ze(2),ve(2,!0),y.step2Result=await Gr(i,s),Wr();const o=document.getElementById("step2-output"),a=ws(y.step2Result);o.textContent=a,o.dataset.raw=a,ve(2,!1),ze(3),rt(3),ve(3,!0),y.step3Result=await Kr(y.step2Result,y.step1Result),zr();const l=document.getElementById("step3-output");l.textContent=y.step3Result,ve(3,!1),$t();const u=jr(y.step3Result);Xr(a,u)}catch(r){console.error("Regeneration failed:",r),$t(),ue(Ia(r,"Regeneration failed"),"error")}finally{y.isRunning=!1,n&&(n.disabled=!1,n.textContent="Fix Errors & Regenerate"),Zt()}}async function Uv(){const t=document.getElementById("ff-status-dot"),e=document.getElementById("ff-status-text");if(!t||!e)return;const s=await Ee("flutterflow"),n=await Ee("flutterflow_project_id");s&&n?(t.className="w-2 h-2 rounded-full bg-green-500",e.textContent="FlutterFlow credentials configured",e.className="text-green-600"):s||n?(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 Hv(t){try{const e=await fetch(`${Je}/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 Wv(t){try{const s=await(await fetch(`${Je}/auth/verify-magic-link`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:t})})).json();if(s.error||!s.email||!s.sessionToken)throw new Error(s.error||"Invalid or expired link");return s}catch(e){throw console.error("verifyMagicLink failed:",{message:e.message,stack:e.stack}),e}}async function zv(t){try{const e=await fetch(`${Je}/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:`${Je}/auth/refresh-session`,status:e.status}),null;const s=await e.json();return s.error||!s.email||!s.sessionToken?(console.warn("refreshSession: validation failed",{error:s.error,hasEmail:!!s.email,hasToken:!!s.sessionToken}),null):s}catch(e){return console.error("refreshSession: fetch failed",{url:`${Je}/auth/refresh-session`,message:e.message,stack:e.stack}),null}}function xc(t,e){const s=Qd(),n=(G.email||s.email)!==t;G.email=t,G.sessionToken=e,G.isVerified=!0,fe=bs({isLoading:!0}),localStorage.setItem(yr,JSON.stringify({email:t,sessionToken:e})),n&&Na()}function Fa(){G.email=null,G.sessionToken=null,G.isVerified=!1,fe=bs({isResolved:!0}),localStorage.removeItem(yr),localStorage.removeItem(br)}function Qd(){try{const t=localStorage.getItem(yr);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(yr),{email:null,sessionToken:null}}}async function qv(){const e=new URLSearchParams(window.location.search).get("token");if(e){window.history.replaceState({},"",window.location.pathname);try{const{email:s,sessionToken:n}=await Wv(e);xc(s,n)}catch(s){ue(s.message||"Sign-in link invalid or expired.","error")}}else{const{email:s,sessionToken:n}=Qd();if(s&&n){const r=await zv(n);r?xc(r.email,r.sessionToken):Fa()}}Aa()}function Pa(){const t=document.getElementById("signin-modal");t&&t.classList.add("open")}function Vv(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("signin-modal");e&&e.classList.remove("open")}async function Gv(){const t=document.getElementById("signin-email-input"),e=document.getElementById("signin-submit-btn"),s=document.getElementById("signin-message"),n=Lr(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){s&&(s.textContent="Please enter a valid email address.");return}e&&(e.disabled=!0,e.textContent="Sending…");const i=Id(n);s&&i&&(s.textContent=i);try{const o=await Hv(n);t&&o?.code!==Un&&(t.value=""),s&&(s.textContent=sm(o,n)),e&&(e.textContent=o?.code===Un?"Send Link":"Sent!"),e&&o?.code===Un&&(e.disabled=!1)}catch(o){console.error("handleMagicLinkRequest: sendMagicLink failed",{email:n,err:o}),s&&(s.textContent="Something went wrong. Please try again."),e&&(e.disabled=!1,e.textContent="Send Link")}}function Kv(){Fa(),Na(),Aa(),Yr()}function Aa(){const t=G.isVerified&&!!G.email,e=document.getElementById("auth-signedout"),s=document.getElementById("auth-signedin"),n=document.getElementById("auth-guest-usage");e&&e.classList.toggle("hidden",t),s&&s.classList.toggle("hidden",!t),n&&n.classList.toggle("hidden",t);const r=document.getElementById("auth-user-email");r&&(r.textContent=G.email||""),Vn(),Yr()}async function eh(){try{if(typeof FingerprintJS>"u"){console.warn("resolveIdentity: FingerprintJS not loaded, skipping");return}const e=await(await FingerprintJS.load()).get(),s=e.visitorId,n=await fetch(Dm,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({fingerprint:e.visitorId,cookie_id:s})});if(!n.ok)throw new Error(`Identity check HTTP ${n.status}`);const r=await n.json();if(Ge.userId=r.user_id,Ge.token=r.identity_token||null,Ge.status=r.status,Ge.resolved=!0,sessionStorage.setItem(Lm,r.user_id),Ge.token&&sessionStorage.setItem(Om,Ge.token),r.usage_count!==void 0){const i=At(),a=(r.usage_month||i)===i?r.usage_count:0;localStorage.setItem(Gt,JSON.stringify({count:a,month:i})),Xs()}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 Ri=null;function Jv(t=5e3){return Ge.resolved?Promise.resolve():(Ri||(Ri=eh().catch(e=>{console.warn("ensureIdentityReady: identity resolution failed",e)})),Promise.race([Ri,new Promise(e=>setTimeout(e,t))]))}function th(){const t=At();try{const e=localStorage.getItem(Gt);return e?JSON.parse(e):{count:0,month:t}}catch(e){return console.warn("getUsageData: failed to parse usage storage",{key:Gt,month:t,err:e}),localStorage.removeItem(Gt),{count:0,month:t}}}function At(){const t=new Date;return`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,"0")}`}function Jr(){const t=th();return t.month!==At()?{count:0,month:At()}:t}function Yv(){const e={count:Jr().count+1,month:At()};return localStorage.setItem(Gt,JSON.stringify(e)),e}function $a(){return!!fe.isLoading}function Jt(){return!!fe.isResolved}function Zv(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(wr,e)?e:null}function Xv(t){return t&&Object.entries(Nd).find(([,e])=>e===t)?.[0]||null}function Rn(...t){return t.find(e=>e!=null&&e!=="")}function Qv(...t){return t.find(e=>e&&typeof e=="object")||{}}function e_(t){const e=t.data&&typeof t.data=="object"?t.data:t,s=Qv(e.subscription,e.stripeSubscription,e.currentSubscription,e.customer?.subscriptions?.data?.[0],e.subscriptions?.data?.[0],e.subscriptions?.[0]),n=e.metadata||s.metadata||e.customer?.metadata||{},r=Rn(e.priceId,e.price_id,e.stripePriceId,e.stripe_price_id,s.priceId,s.price_id,s.plan?.id,s.price?.id,s.items?.data?.[0]?.price?.id,s.items?.[0]?.price?.id,s.lines?.data?.[0]?.price?.id),i=Rn(e.status,e.subscriptionStatus,e.subscription_status,s.status,"none"),o=Zv(Rn(e.tier,e.plan,e.planId,e.plan_id,e.subscriptionTier,e.subscription_tier,e.product,e.productName,s.tier,s.plan,n.tier,n.plan)),a=Bm.has(String(i).toLowerCase()),l=e.active===!0||e.isSubscribed===!0||e.subscribed===!0||e.hasSubscription===!0,u=o||Xv(r)||(a||l?"professional":"free");return bs({tier:u,status:i,periodEnd:Rn(e.periodEnd,e.currentPeriodEnd,e.current_period_end,s.current_period_end,s.periodEnd,null),isResolved:!0})}function Ra(){return wr[fe.tier]??wr.free}async function t_(){if(G.isVerified&&(!Jt()||$a())&&(await sh({force:!0}),Yr()),G.isVerified&&!Jt())return ue("Could not verify your subscription. Please refresh or try Manage billing.","error"),!1;const{count:t}=Jr(),e=Ra();if(t>=e)return Ta(t,e,{openModal:!0}),!1;const s=Math.floor(e*.8);if(t>=s){const n=e-t;ue(`${n} run${n===1?"":"s"} remaining this month.`,"warning")}return!0}function Ti(){const t=document.getElementById("paywall-exhausted");t&&t.classList.add("hidden")}function Ta(t,e,s={}){const n=document.getElementById("walkthrough-modal");n&&n.classList.remove("open");const r=document.getElementById("ready-state");r&&r.classList.add("hidden");const i=document.getElementById("preview-frame-container");i&&(i.style.display="none");const o=document.getElementById("main-stage-container");o&&o.classList.add("visible");const a=document.getElementById("results-view");a&&a.classList.remove("visible"),document.body.classList.remove("results-fullscreen","results-with-sidebar");const l=document.getElementById("pipeline-progress");l&&l.classList.remove("visible");const u=document.getElementById("paywall-exhausted");if(!u){ue(`You've used all ${e} runs for this month. Upgrade to continue.`,"error"),Fr();return}const c=document.getElementById("paywall-exhausted-text");if(c){const h=fe.tier;h==="free"?c.textContent=`You've used all ${e} free generations this month. Upgrade to Pro for 50 generations/month and access to all AI models.`:c.textContent=`You've used all ${e} generations this month on your ${h} plan. Your limit resets next month.`}const d=document.getElementById("paywall-signin-btn");d&&d.classList.toggle("hidden",G.isVerified),u.classList.remove("hidden"),s.openModal&&Fr()}function No(t){return fe.tier==="free"&&Hn.includes(t)?cn:t}function s_(){const t=document.getElementById("code-options-content"),e=document.getElementById("code-generator-model");if(!t||!e)return;const s=fe.tier,r=!(G.isVerified&&!Jt())&&s==="free";Array.from(e.options).forEach(o=>{const a=zt(o.value),l=Hn.includes(o.value);o.textContent=l&&r?`${a} (PRO)`:a,o.disabled=!1}),r&&Hn.includes(e.value)&&(e.value=cn),e.disabled=!1,fc.has(e)||(e.addEventListener("change",()=>{Jt()&&fe.tier==="free"&&Hn.includes(e.value)&&(e.value=cn,Fr()),Ro(e.value),Ld()}),fc.add(e));let i=document.getElementById("model-selector-free-notice");r?(i||(i=document.createElement("p"),i.id="model-selector-free-notice",i.className="text-xs text-gray-400 mt-1",t.appendChild(i)),i.innerHTML='Free plan — Gemini only. '):i&&i.remove(),Ro(e.value)}function Xs(){const t=document.getElementById("usage-counter");if(!t)return;if(G.isVerified&&$a()){t.textContent="Checking plan…",t.className="text-xs text-gray-500",Vn(),Ti();return}if(G.isVerified&&!Jt()){t.textContent="Plan check failed",t.className="text-xs text-red-600 font-medium",Vn(),Ti();return}const{count:e}=Jr(),s=Ra();t.textContent=`${e} / ${s} runs this month`;const n=s>0?e/s:0;t.className=n>=1?"text-xs text-red-600 font-medium":n>=.8?"text-xs text-yellow-600 font-medium":"text-xs text-gray-500",Vn(),e>=s&&!y.isRunning?Ta(e,s):Ti()}function Vn(){const t=document.getElementById("guest-usage-text");if(!t)return;const e=th(),s=e.month===At()?e.count??0:0,n=wr.free;t.textContent=`${s} / ${n} generations used`}async function sh(t={}){const e=t.force===!0;if(!G.isVerified||!G.sessionToken){fe=bs({isResolved:!0});return}fe={...fe,isLoading:!0,error:null};const s=localStorage.getItem(br);if(!e&&s)try{const{data:n,email:r,ts:i,version:o}=JSON.parse(s);if(o===gc&&r===G.email&&Date.now()-i<300*1e3){fe={...n,isLoading:!1,isResolved:n.isResolved!==!1};return}}catch(n){console.warn("Failed to parse subscription cache:",n,"| raw value:",s)}try{const r=await(await fetch(`${Je}/stripe/get-subscription`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:G.sessionToken,user_id:Ge.userId})})).json();if(r.error){if(["unauthorized","invalid session","expired session"].some(o=>String(r.error).toLowerCase().includes(o))){Fa(),Aa();return}fe=bs({isResolved:!1,error:r.error});return}fe=e_(r),localStorage.setItem(br,JSON.stringify({version:gc,data:fe,email:G.email,ts:Date.now()}))}catch(n){console.error("fetchSubscription failed:",n),fe={...fe,isLoading:!1,isResolved:!1,error:n.message}}}function Na(){localStorage.removeItem(br)}async function n_(t){if(!G.isVerified||!G.sessionToken){nh(),Pa();return}if(!Nd[t]){ue("Invalid plan selected.","error");return}const e=document.getElementById(`checkout-btn-${t}`);e&&(e.disabled=!0,e.textContent="Redirecting…");try{const n=await(await fetch(`${Je}/stripe/create-checkout-session-intl`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tierId:t,sessionToken:G.sessionToken,currency:Bd()})})).json();if(n.error||!n.url)throw new Error(n.error||"Failed to create checkout session");const{url:r}=n;window.location.href=r}catch(s){console.error("startCheckout failed:",s),e&&(e.disabled=!1,e.textContent="Subscribe"),ue("Could not start checkout. Please try again.","error")}}async function r_(){if(!G.isVerified||!G.sessionToken){Pa();return}const t=document.getElementById("manage-billing-btn");t&&(t.disabled=!0,t.textContent="Loading…");try{const s=await(await fetch(`${Je}/stripe/create-portal-session`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:G.sessionToken})})).json();if(s.error||!s.url)throw new Error(s.error||"Failed to open billing portal");const{url:n}=s;window.location.href=n}catch(e){console.error("openCustomerPortal failed:",e),t&&(t.disabled=!1,t.textContent="Manage billing"),ue("Could not open billing portal. Please try again.","error")}}async function Cr(t,e,s,n={},r=[]){const o=new AbortController,a=setTimeout(()=>o.abort(),12e4);try{const l=await fetch(Mm,{method:"POST",headers:{"Content-Type":"application/json",...Ge.token?{Authorization:`Bearer ${Ge.token}`}:{}},signal:o.signal,body:JSON.stringify({user_id:Ge.userId,step:t,model:e,prompt:s,images:r,context:n})}),u=await l.text();let c={};try{c=u?JSON.parse(u):{}}catch{c={}}if(l.status===429){c.serverCount!==void 0&&(localStorage.setItem(Gt,JSON.stringify({count:c.serverCount,month:At()})),Xs());const p=new Error(c.message||"Monthly usage limit reached. Upgrade to continue.");throw p.isUsageLimit=!0,p}const d=Jf(c,t);if(d)throw d;if(console.log(`[BuildShip] ${t} response keys:`,Object.keys(c),"content type:",typeof c.content),!l.ok)throw new Error(`${c.message||c.error||"BuildShip pipeline error"} (HTTP ${l.status})`);if(t==="generator")if(c.usage_status==="success"&&Number.isFinite(c.usage_count)){const p=At();(c.usage_month||p)===p&&(localStorage.setItem(Gt,JSON.stringify({count:c.usage_count,month:p})),Xs())}else Yv(),Xs();let h=c.output||c.content;if(!h){const p=u?` (body: ${u.slice(0,120)})`:"";throw new Error(`BuildShip returned no output for step "${t}"${p}`)}return Array.isArray(h)&&(h=h.map(p=>typeof p=="string"?p:p.text||"").join("")),typeof h!="string"&&(h=JSON.stringify(h)),h}catch(l){throw l.name==="AbortError"?new Error(`BuildShip ${t} timed out after ${12e4/1e3}s`):l instanceof TypeError?new Error(`BuildShip unreachable: ${l.message}`):l}finally{clearTimeout(a)}}function i_(){const e=new URLSearchParams(window.location.search).get("checkout");e==="success"?(window.history.replaceState({},"",window.location.pathname),Na(),ue("Subscription active! Welcome aboard.","success")):e==="cancel"&&(window.history.replaceState({},"",window.location.pathname),ue("Checkout cancelled.","info"))}function Yr(){const t=G.isVerified&&!!G.email,e=fe.tier,s=t&&$a(),n=!t||Jt(),r=document.getElementById("subscription-tier-badge");if(r){const a={free:"Free",professional:"Professional",power:"Power Developer"},l={free:"bg-gray-100 text-gray-600",professional:"bg-indigo-100 text-indigo-700",power:"bg-purple-100 text-purple-700",unresolved:"bg-red-50 text-red-600"};r.textContent=s?"Checking…":n?a[e]||"Free":"Plan unavailable",r.className=`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${n?l[e]||l.free:l.unresolved}`}const i=document.getElementById("upgrade-prompt");i&&i.classList.toggle("hidden",!t||s||!n||e!=="free");const o=document.getElementById("manage-billing-btn");o&&o.classList.toggle("hidden",!t||s||n&&e==="free"),o_(n?e:null),s_(),Ld(),Xs()}function o_(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:i,defaultText:o}])=>{const a=document.getElementById(i);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 n=document.getElementById("free-tier-current");n&&n.classList.toggle("hidden",t!=="free")}function Mo(){const t=Bd(),e=document.getElementById("pro-price"),s=document.getElementById("power-price"),n=document.getElementById("pro-price-note"),r=document.getElementById("power-price-note");e&&(e.textContent=vc(mc.professional,t)),s&&(s.textContent=vc(mc.power,t));const i="billed monthly";n&&(n.textContent=i),r&&(r.textContent=i)}function Fr(){Mo();const t=document.getElementById("pricing-modal");t&&t.classList.add("open"),Km().then(()=>Mo())}function nh(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("pricing-modal");e&&e.classList.remove("open")}function ue(t,e="info"){const s={success:"bg-green-600 text-white",error:"bg-red-600 text-white",warning:"bg-amber-500 text-white",info:"bg-gray-800 text-white"},n=document.createElement("div");n.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 ${s[e]||s.info}`,n.textContent=t,document.body.appendChild(n),setTimeout(()=>{n.style.opacity="0",setTimeout(()=>n.remove(),300)},3500)}document.addEventListener("DOMContentLoaded",async()=>{hljs.configure({tabReplace:" ",classPrefix:"hljs-"}),a_(),await qv(),i_(),await sh(),Yr(),Mo(),await yv(),fv();const t=document.getElementById("flutterflow-endpoint-select");if(t){const s=gn();t.value=s}qd(),eh();const e=document.getElementById("pipeline-input");e&&(e.addEventListener("input",()=>{Et===2&&e.value.trim().length>0&&(ma(),Ur())}),e.addEventListener("blur",()=>{const s=document.getElementById("walkthrough-modal");Et===2&&s&&s.classList.add("open")}),e.addEventListener("keydown",s=>{if(s.key==="Tab"){const n=document.getElementById("walkthrough-modal");Et===2&&n&&setTimeout(()=>{n.classList.add("open")},100)}})),window.addEventListener("commitStateChange",s=>{const{state:n}=s.detail;n===V.PREPARING||n===V.VALIDATING||n===V.PUSHING?(be.phaseId||oh(),Ic(n)):(n===V.SUCCESS||n===V.ERROR)&&(Ic(n),setTimeout(Pr,1e3))})});function a_(){const t=document.getElementById("preview-frame-container");t&&(t.style.display="")}function l_(){const t=document.getElementById("welcome-video-player");t&&(t.addEventListener("click",Yt),document.addEventListener("keydown",Yt))}function Yt(){const t=document.getElementById("preview-frame-container"),e=document.getElementById("main-stage-container"),s=document.getElementById("ready-state");t&&(t.style.display="none"),e&&e.classList.add("visible"),s&&s.classList.remove("hidden");const n=document.getElementById("welcome-video-player");n&&n.removeEventListener("click",Yt),document.removeEventListener("keydown",Yt),qd()}let Qs=null;async function c_(){const t=document.getElementById("confirm-project-select");if(!t)return;const e=++Ec,s=()=>e===Ec,n=await Ee("flutterflow"),r=await Ee("flutterflow_project_id");if(s()){if(!n){t.innerHTML='',t.disabled=!0;return}t.disabled=!1,t.innerHTML='';try{const o=await new mn(n,"").listProjects();if(!s())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(i){if(!s())return;console.error("Failed to load projects for deploy:",i),t.innerHTML=''}}}function u_(){return document.getElementById("confirm-project-select")?.value?.trim()||null}function rh(t,e,s,n=null){Qs={codeInfo:t,checks:e,deps:s,bundlePlan:n},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=n?`${n.fileEntries.length} files`:t.content.split(` -`).length,c_();const r=document.getElementById("confirm-deps-list"),i=document.getElementById("confirm-deps-section");s&&Object.keys(s).length>0?(r.innerHTML=Object.entries(s).map(([u,c])=>{const d=c?`at least ${bt(c)}`:"version resolved from your project";return`
  • • ${bt(u)}: ${d}
  • `}).join(""),i.classList.remove("hidden")):i.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=>`
  • • ${bt(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&&l.classList.add("open")}function ih(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("commit-confirm-modal");e&&e.classList.remove("open"),Qs=null}function d_(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("commit-success-modal");e&&e.classList.remove("open");const s=["success-message","success-project-id","success-file-name","success-artifact-type","success-time","success-size"];for(const i of s){const o=document.getElementById(i);o&&(o.textContent="")}const n=document.getElementById("success-warnings-section");n&&n.classList.add("hidden");const r=document.getElementById("success-warnings-list");r&&(r.innerHTML="")}function Lo(t){const e=(g,m)=>{const _=document.getElementById(g);_&&(_.textContent=m||"")},s=t.metadata?.fileName||"",n=t.metadata?.projectId||"",r=t.metadata?.artifactType||"",i=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",n),e("success-file-name",s),e("success-artifact-type",r),e("success-time",i),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&&n&&(u.href=`https://app.flutterflow.io/project/${n}`);const c=document.getElementById("success-warnings-section"),d=document.getElementById("success-warnings-list"),h=t.unverified||[],p=t.warnings||[];(p.length>0||h.length>0)&&c&&d&&(d.innerHTML=[...h.map(g=>`
  • Not verified before deploying: ${j(String(g))}
  • `),...p.map(([g,m])=>`
  • ${j(g)}: ${j(String(m))}
  • `)].join(""),c.classList.remove("hidden"));const f=document.getElementById("commit-success-modal");f&&f.classList.add("open")}function Oo(t){Pr(),Bv(t)}function h_(){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 kc={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}},p_=[{after:0,text:"Starting a FlutterFlow build runner..."},{after:12,text:"Preparing the FlutterFlow AI workspace..."},{after:35,text:"Uploading your custom classes..."},{after:60,text:"FlutterFlow is applying the changes..."},{after:100,text:"Still working — this can take a couple of minutes..."}],be={sequence:[],phaseId:null,phaseStartedAt:null,timer:null,substatus:null,liveSubstatus:!1,start({withProvisioning:t=!1}={}){this.sequence=["prepare","validate","project"],t&&this.sequence.push("provision"),this.sequence.push("package","push","done");const e=document.getElementById("commit-progress-overlay");e&&e.classList.add("open"),this.set("prepare")},set(t,e=null){if(!(!kc[t]||t===this.phaseId)){if(!this.sequence.includes(t)){const s=this.sequence.indexOf("package");this.sequence.splice(s===-1?this.sequence.length:s,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=kc[this.phaseId];if(!t)return;const e=(Date.now()-this.phaseStartedAt)/1e3,s=t.start+(t.end-t.start)*(1-Math.exp(-e/25));if(this.phaseId==="provision"&&!this.liveSubstatus){const o=p_.filter(a=>e>=a.after).pop();o&&(this.substatus=o.text)}const n=this.sequence.indexOf(this.phaseId),i=[`Step ${n===-1?1:n+1} of ${this.sequence.length}`];e>=5&&i.push(f_(e)),ah(this.phaseId==="done"?100:s,t.message,i.join(" · "),this.substatus)},stop(){this.timer&&clearInterval(this.timer),this.timer=null,this.phaseId=null;const t=document.getElementById("commit-progress-overlay");t&&t.classList.remove("open")}};function f_(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 oh(t){be.start(t)}function Pr(){be.stop()}function ah(t,e,s,n=null){const r=document.getElementById("commit-progress-bar"),i=document.getElementById("progress-message"),o=document.getElementById("progress-detail"),a=document.getElementById("progress-substatus");r&&(r.style.width=`${Math.round(t*10)/10}%`),i&&(i.textContent=e),o&&(o.textContent=s),a&&(a.textContent=n||"",a.classList.toggle("hidden",!n))}function Ic(t){const e={[V.PREPARING]:"prepare",[V.VALIDATING]:"validate",[V.PUSHING]:"project",[V.SUCCESS]:"done"};if(t===V.ERROR){be.timer&&clearInterval(be.timer),be.timer=null,ah(100,"Failed","Error occurred");return}const s=e[t];s&&be.set(s)}function g_(t){return t.bundlePlan?t.bundlePlan.fileEntries.some(e=>e.type===U.CODE_FILE):t.codeInfo?.codeType===U.CODE_FILE}async function m_(){if(!Qs){console.error("No pending commit data");return}const t=Qs;if(Qs=null,Zs=u_(),ih(),oh({withProvisioning:g_(t)}),t.bundlePlan){const o=await Fv(t.bundlePlan,{pipelineResult:{step1Result:y.step1Result,selectedModel:document.getElementById("code-generator-model")?.value}});Zs=null,Pr(),o.success?Lo(o):Oo(o);return}const{codeInfo:e}=t,{artifactType:s,artifactName:n,fileName:r}=Gd(),i=await Cv(e.content,{artifactType:s,artifactName:n,fileName:r,pipelineResult:{step1Result:y.step1Result,selectedModel:document.getElementById("code-generator-model")?.value}});Zs=null,Pr(),i.success?Lo(i):Oo(i)}window.runThinkingPipeline=To;window.toggleStep=$v;window.toggleSection=Av;window.selectWorkflowStep=ze;window.copyCode=Rv;window.retryWithDifferentModel=Lv;window.openApiKeysModal=ga;window.closeApiKeysModal=Wd;window.closeWalkthroughModal=lv;window.openWalkthroughModal=av;window.advanceWalkthrough=ma;window.commitToFlutterFlow=Iv;function v_(){const t=document.getElementById("pipeline-input");t&&t.focus()}function __(){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=v_;window.openModelSelector=__;window.handlePromptImageSelect=Vm;window.removePromptImage=Gm;window.saveApiKeys=dv;window.clearAllApiKeys=hv;window.toggleKeyVisibility=mv;window.handleWelcomeVideoEnd=l_;window.dismissWelcomeVideo=Yt;window.initiateCommitToFlutterFlow=Ov;window.updateFlutterFlowCredentialStatus=Uv;window.closeCommitConfirmModal=ih;window.closeCommitSuccessModal=d_;window.showCommitSuccessModal=Lo;window.showCommitFailureModal=Oo;window.toggleCodePreview=h_;window.confirmCommitToFlutterFlow=m_;window.runRefinement=Tv;window.regenerateFromPastedErrors=Mv;window.clearErrorInput=Nv;window.setFlutterFlowEndpoint=ov;window.getFlutterFlowEndpoint=gn;window.commitProgress=be;window.openSignInModal=Pa;window.closeSignInModal=Vv;window.handleMagicLinkRequest=Gv;window.handleSignOut=Kv;window.startCheckout=n_;window.openCustomerPortal=r_;window.openPricingModal=Fr;window.closePricingModal=nh;let hs=null,lh=null;const Cc=120;function Zr(){const t=document.getElementById("pipeline-progress"),e=document.getElementById("results-view"),s=document.getElementById("ready-state");s&&s.classList.add("hidden"),e&&e.classList.remove("visible"),document.body.classList.remove("results-fullscreen","results-with-sidebar"),t&&t.classList.add("visible"),lh=Date.now();for(let n=1;n<=3;n++){const r=document.getElementById(`pdot-${n}`);r&&(r.className="progress-dot")}rt(1),y_()}function rt(t){const e={1:"Analyzing your prompt...",2:"Generating Dart code...",3:"Running code audit..."},s={1:"Step 1 of 3 — Prompt Architect",2:"Step 2 of 3 — Code Generator",3:"Step 3 of 3 — Code Review"},n=document.getElementById("progress-title-text"),r=document.getElementById("progress-substep-text");n&&(n.textContent=e[t]||e[1]),r&&(r.textContent=s[t]||s[1]);for(let i=1;i<=3;i++){const o=document.getElementById(`pdot-${i}`);o&&(i{const t=(Date.now()-lh)/1e3,e=document.getElementById("progress-elapsed"),s=document.getElementById("pipeline-progress-fill");e&&(e.textContent=`${Math.floor(t)}s`);const n=t/Cc*100,r=Math.min(95,n*(1-Math.exp(-t/(Cc*.6)))*1.2);s&&(s.style.width=`${r}%`)},250)}function $t(){hs&&(clearInterval(hs),hs=null);const t=document.getElementById("pipeline-progress-fill");t&&(t.style.width="100%");for(let e=1;e<=3;e++){const s=document.getElementById(`pdot-${e}`);s&&(s.className="progress-dot completed")}setTimeout(()=>{const e=document.getElementById("pipeline-progress");e&&e.classList.remove("visible"),t&&(t.style.width="0%")},400)}function Ss(t,e=""){const s={pass:'',warning:'',fail:'',info:''};return``}function ch(t){return{pass:"Passed review",warning:"Needs attention",fail:"Blocking issues"}[t]||"Needs attention"}function w_(){return jg({bundle:y.artifactBundle,reviewResult:y.step3Result})}function b_(t){return` +`}else n+=`${t} +`;const i=vd({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,userFeedback:n});Zn(),nt(2),ze(2),ve(2,!0),y.step2Result=await Gn(i,s),Wn();const o=document.getElementById("step2-output"),a=ws(y.step2Result);o.textContent=a,o.dataset.raw=a,ve(2,!1),ze(3),nt(3),ve(3,!0),y.step3Result=await Kn(y.step2Result,y.step1Result),zn();const l=document.getElementById("step3-output");l.textContent=y.step3Result,ve(3,!1),$t();const u=jn(y.step3Result);Xn(a,u)}catch(n){console.error("Regeneration failed:",n),$t(),ue(Ia(n,"Regeneration failed"),"error")}finally{y.isRunning=!1,r&&(r.disabled=!1,r.textContent="Fix Errors & Regenerate"),Zt()}}async function jv(){const t=document.getElementById("ff-status-dot"),e=document.getElementById("ff-status-text");if(!t||!e)return;const s=await Ee("flutterflow"),r=await Ee("flutterflow_project_id");s&&r?(t.className="w-2 h-2 rounded-full bg-green-500",e.textContent="FlutterFlow credentials configured",e.className="text-green-600"):s||r?(t.className="w-2 h-2 rounded-full bg-yellow-500",e.textContent="FlutterFlow credentials incomplete",e.className="text-yellow-600"):(t.className="w-2 h-2 rounded-full bg-red-500",e.textContent="FlutterFlow credentials not configured",e.className="text-red-600")}async function Uv(t){try{const e=await fetch(`${Je}/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 Hv(t){try{const s=await(await fetch(`${Je}/auth/verify-magic-link`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:t})})).json();if(s.error||!s.email||!s.sessionToken)throw new Error(s.error||"Invalid or expired link");return s}catch(e){throw console.error("verifyMagicLink failed:",{message:e.message,stack:e.stack}),e}}async function Wv(t){try{const e=await fetch(`${Je}/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:`${Je}/auth/refresh-session`,status:e.status}),null;const s=await e.json();return s.error||!s.email||!s.sessionToken?(console.warn("refreshSession: validation failed",{error:s.error,hasEmail:!!s.email,hasToken:!!s.sessionToken}),null):s}catch(e){return console.error("refreshSession: fetch failed",{url:`${Je}/auth/refresh-session`,message:e.message,stack:e.stack}),null}}function xc(t,e){const s=Xd(),r=(G.email||s.email)!==t;G.email=t,G.sessionToken=e,G.isVerified=!0,fe=bs({isLoading:!0}),localStorage.setItem(yn,JSON.stringify({email:t,sessionToken:e})),r&&Na()}function Fa(){G.email=null,G.sessionToken=null,G.isVerified=!1,fe=bs({isResolved:!0}),localStorage.removeItem(yn),localStorage.removeItem(bn)}function Xd(){try{const t=localStorage.getItem(yn);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(yn),{email:null,sessionToken:null}}}async function zv(){const e=new URLSearchParams(window.location.search).get("token");if(e){window.history.replaceState({},"",window.location.pathname);try{const{email:s,sessionToken:r}=await Hv(e);xc(s,r)}catch(s){ue(s.message||"Sign-in link invalid or expired.","error")}}else{const{email:s,sessionToken:r}=Xd();if(s&&r){const n=await Wv(r);n?xc(n.email,n.sessionToken):Fa()}}Aa()}function Pa(){const t=document.getElementById("signin-modal");t&&t.classList.add("open")}function qv(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("signin-modal");e&&e.classList.remove("open")}async function Vv(){const t=document.getElementById("signin-email-input"),e=document.getElementById("signin-submit-btn"),s=document.getElementById("signin-message"),r=Ln(t?.value);if(!r||!/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/.test(r)||r.length>254){s&&(s.textContent="Please enter a valid email address.");return}e&&(e.disabled=!0,e.textContent="Sending…");const i=kd(r);s&&i&&(s.textContent=i);try{const o=await Uv(r);t&&o?.code!==jr&&(t.value=""),s&&(s.textContent=sm(o,r)),e&&(e.textContent=o?.code===jr?"Send Link":"Sent!"),e&&o?.code===jr&&(e.disabled=!1)}catch(o){console.error("handleMagicLinkRequest: sendMagicLink failed",{email:r,err:o}),s&&(s.textContent="Something went wrong. Please try again."),e&&(e.disabled=!1,e.textContent="Send Link")}}function Gv(){Fa(),Na(),Aa(),Yn()}function Aa(){const t=G.isVerified&&!!G.email,e=document.getElementById("auth-signedout"),s=document.getElementById("auth-signedin"),r=document.getElementById("auth-guest-usage");e&&e.classList.toggle("hidden",t),s&&s.classList.toggle("hidden",!t),r&&r.classList.toggle("hidden",t);const n=document.getElementById("auth-user-email");n&&(n.textContent=G.email||""),qr(),Yn()}async function Qd(){try{if(typeof FingerprintJS>"u"){console.warn("resolveIdentity: FingerprintJS not loaded, skipping");return}const e=await(await FingerprintJS.load()).get(),s=e.visitorId,r=await fetch(Om,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({fingerprint:e.visitorId,cookie_id:s})});if(!r.ok)throw new Error(`Identity check HTTP ${r.status}`);const n=await r.json();if(Ge.userId=n.user_id,Ge.token=n.identity_token||null,Ge.status=n.status,Ge.resolved=!0,sessionStorage.setItem(Mm,n.user_id),Ge.token&&sessionStorage.setItem(Lm,Ge.token),n.usage_count!==void 0){const i=At(),a=(n.usage_month||i)===i?n.usage_count:0;localStorage.setItem(Gt,JSON.stringify({count:a,month:i})),Xs()}console.log(`Identity resolved: ${n.status} (${n.user_id.slice(0,8)}...) usage: ${n.usage_count??"n/a"}`)}catch(t){console.error("resolveIdentity failed:",t)}}let Ri=null;function Kv(t=5e3){return Ge.resolved?Promise.resolve():(Ri||(Ri=Qd().catch(e=>{console.warn("ensureIdentityReady: identity resolution failed",e)})),Promise.race([Ri,new Promise(e=>setTimeout(e,t))]))}function eh(){const t=At();try{const e=localStorage.getItem(Gt);return e?JSON.parse(e):{count:0,month:t}}catch(e){return console.warn("getUsageData: failed to parse usage storage",{key:Gt,month:t,err:e}),localStorage.removeItem(Gt),{count:0,month:t}}}function At(){const t=new Date;return`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,"0")}`}function Jn(){const t=eh();return t.month!==At()?{count:0,month:At()}:t}function Jv(){const e={count:Jn().count+1,month:At()};return localStorage.setItem(Gt,JSON.stringify(e)),e}function $a(){return!!fe.isLoading}function Jt(){return!!fe.isResolved}function Yv(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(wn,e)?e:null}function Zv(t){return t&&Object.entries(Td).find(([,e])=>e===t)?.[0]||null}function $r(...t){return t.find(e=>e!=null&&e!=="")}function Xv(...t){return t.find(e=>e&&typeof e=="object")||{}}function Qv(t){const e=t.data&&typeof t.data=="object"?t.data:t,s=Xv(e.subscription,e.stripeSubscription,e.currentSubscription,e.customer?.subscriptions?.data?.[0],e.subscriptions?.data?.[0],e.subscriptions?.[0]),r=e.metadata||s.metadata||e.customer?.metadata||{},n=$r(e.priceId,e.price_id,e.stripePriceId,e.stripe_price_id,s.priceId,s.price_id,s.plan?.id,s.price?.id,s.items?.data?.[0]?.price?.id,s.items?.[0]?.price?.id,s.lines?.data?.[0]?.price?.id),i=$r(e.status,e.subscriptionStatus,e.subscription_status,s.status,"none"),o=Yv($r(e.tier,e.plan,e.planId,e.plan_id,e.subscriptionTier,e.subscription_tier,e.product,e.productName,s.tier,s.plan,r.tier,r.plan)),a=Dm.has(String(i).toLowerCase()),l=e.active===!0||e.isSubscribed===!0||e.subscribed===!0||e.hasSubscription===!0,u=o||Zv(n)||(a||l?"professional":"free");return bs({tier:u,status:i,periodEnd:$r(e.periodEnd,e.currentPeriodEnd,e.current_period_end,s.current_period_end,s.periodEnd,null),isResolved:!0})}function Ra(){return wn[fe.tier]??wn.free}async function e_(){if(G.isVerified&&(!Jt()||$a())&&(await th({force:!0}),Yn()),G.isVerified&&!Jt())return ue("Could not verify your subscription. Please refresh or try Manage billing.","error"),!1;const{count:t}=Jn(),e=Ra();if(t>=e)return Ta(t,e,{openModal:!0}),!1;const s=Math.floor(e*.8);if(t>=s){const r=e-t;ue(`${r} run${r===1?"":"s"} remaining this month.`,"warning")}return!0}function Ti(){const t=document.getElementById("paywall-exhausted");t&&t.classList.add("hidden")}function Ta(t,e,s={}){const r=document.getElementById("walkthrough-modal");r&&r.classList.remove("open");const n=document.getElementById("ready-state");n&&n.classList.add("hidden");const i=document.getElementById("preview-frame-container");i&&(i.style.display="none");const o=document.getElementById("main-stage-container");o&&o.classList.add("visible");const a=document.getElementById("results-view");a&&a.classList.remove("visible"),document.body.classList.remove("results-fullscreen","results-with-sidebar");const l=document.getElementById("pipeline-progress");l&&l.classList.remove("visible");const u=document.getElementById("paywall-exhausted");if(!u){ue(`You've used all ${e} runs for this month. Upgrade to continue.`,"error"),Fn();return}const c=document.getElementById("paywall-exhausted-text");if(c){const h=fe.tier;h==="free"?c.textContent=`You've used all ${e} free generations this month. Upgrade to Pro for 50 generations/month and access to all AI models.`:c.textContent=`You've used all ${e} generations this month on your ${h} plan. Your limit resets next month.`}const d=document.getElementById("paywall-signin-btn");d&&d.classList.toggle("hidden",G.isVerified),u.classList.remove("hidden"),s.openModal&&Fn()}function No(t){return fe.tier==="free"&&Ur.includes(t)?lr:t}function t_(){const t=document.getElementById("code-options-content"),e=document.getElementById("code-generator-model");if(!t||!e)return;const s=fe.tier,n=!(G.isVerified&&!Jt())&&s==="free";Array.from(e.options).forEach(o=>{const a=zt(o.value),l=Ur.includes(o.value);o.textContent=l&&n?`${a} (PRO)`:a,o.disabled=!1}),n&&Ur.includes(e.value)&&(e.value=lr),e.disabled=!1,fc.has(e)||(e.addEventListener("change",()=>{Jt()&&fe.tier==="free"&&Ur.includes(e.value)&&(e.value=lr,Fn()),Ro(e.value),Md()}),fc.add(e));let i=document.getElementById("model-selector-free-notice");n?(i||(i=document.createElement("p"),i.id="model-selector-free-notice",i.className="text-xs text-gray-400 mt-1",t.appendChild(i)),i.innerHTML='Free plan — Gemini only. '):i&&i.remove(),Ro(e.value)}function Xs(){const t=document.getElementById("usage-counter");if(!t)return;if(G.isVerified&&$a()){t.textContent="Checking plan…",t.className="text-xs text-gray-500",qr(),Ti();return}if(G.isVerified&&!Jt()){t.textContent="Plan check failed",t.className="text-xs text-red-600 font-medium",qr(),Ti();return}const{count:e}=Jn(),s=Ra();t.textContent=`${e} / ${s} runs this month`;const r=s>0?e/s:0;t.className=r>=1?"text-xs text-red-600 font-medium":r>=.8?"text-xs text-yellow-600 font-medium":"text-xs text-gray-500",qr(),e>=s&&!y.isRunning?Ta(e,s):Ti()}function qr(){const t=document.getElementById("guest-usage-text");if(!t)return;const e=eh(),s=e.month===At()?e.count??0:0,r=wn.free;t.textContent=`${s} / ${r} generations used`}async function th(t={}){const e=t.force===!0;if(!G.isVerified||!G.sessionToken){fe=bs({isResolved:!0});return}fe={...fe,isLoading:!0,error:null};const s=localStorage.getItem(bn);if(!e&&s)try{const{data:r,email:n,ts:i,version:o}=JSON.parse(s);if(o===gc&&n===G.email&&Date.now()-i<300*1e3){fe={...r,isLoading:!1,isResolved:r.isResolved!==!1};return}}catch(r){console.warn("Failed to parse subscription cache:",r,"| raw value:",s)}try{const n=await(await fetch(`${Je}/stripe/get-subscription`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:G.sessionToken,user_id:Ge.userId})})).json();if(n.error){if(["unauthorized","invalid session","expired session"].some(o=>String(n.error).toLowerCase().includes(o))){Fa(),Aa();return}fe=bs({isResolved:!1,error:n.error});return}fe=Qv(n),localStorage.setItem(bn,JSON.stringify({version:gc,data:fe,email:G.email,ts:Date.now()}))}catch(r){console.error("fetchSubscription failed:",r),fe={...fe,isLoading:!1,isResolved:!1,error:r.message}}}function Na(){localStorage.removeItem(bn)}async function s_(t){if(!G.isVerified||!G.sessionToken){sh(),Pa();return}if(!Td[t]){ue("Invalid plan selected.","error");return}const e=document.getElementById(`checkout-btn-${t}`);e&&(e.disabled=!0,e.textContent="Redirecting…");try{const r=await(await fetch(`${Je}/stripe/create-checkout-session-intl`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tierId:t,sessionToken:G.sessionToken,currency:Dd()})})).json();if(r.error||!r.url)throw new Error(r.error||"Failed to create checkout session");const{url:n}=r;window.location.href=n}catch(s){console.error("startCheckout failed:",s),e&&(e.disabled=!1,e.textContent="Subscribe"),ue("Could not start checkout. Please try again.","error")}}async function r_(){if(!G.isVerified||!G.sessionToken){Pa();return}const t=document.getElementById("manage-billing-btn");t&&(t.disabled=!0,t.textContent="Loading…");try{const s=await(await fetch(`${Je}/stripe/create-portal-session`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:G.sessionToken})})).json();if(s.error||!s.url)throw new Error(s.error||"Failed to open billing portal");const{url:r}=s;window.location.href=r}catch(e){console.error("openCustomerPortal failed:",e),t&&(t.disabled=!1,t.textContent="Manage billing"),ue("Could not open billing portal. Please try again.","error")}}async function Cn(t,e,s,r={},n=[]){const o=new AbortController,a=setTimeout(()=>o.abort(),12e4);try{const l=await fetch(Nm,{method:"POST",headers:{"Content-Type":"application/json",...Ge.token?{Authorization:`Bearer ${Ge.token}`}:{}},signal:o.signal,body:JSON.stringify({user_id:Ge.userId,step:t,model:e,prompt:s,images:n,context:r})}),u=await l.text();let c={};try{c=u?JSON.parse(u):{}}catch{c={}}if(l.status===429){c.serverCount!==void 0&&(localStorage.setItem(Gt,JSON.stringify({count:c.serverCount,month:At()})),Xs());const p=new Error(c.message||"Monthly usage limit reached. Upgrade to continue.");throw p.isUsageLimit=!0,p}const d=Kf(c,t);if(d)throw d;if(console.log(`[BuildShip] ${t} response keys:`,Object.keys(c),"content type:",typeof c.content),!l.ok)throw new Error(`${c.message||c.error||"BuildShip pipeline error"} (HTTP ${l.status})`);if(t==="generator")if(c.usage_status==="success"&&Number.isFinite(c.usage_count)){const p=At();(c.usage_month||p)===p&&(localStorage.setItem(Gt,JSON.stringify({count:c.usage_count,month:p})),Xs())}else Jv(),Xs();let h=c.output||c.content;if(!h){const p=u?` (body: ${u.slice(0,120)})`:"";throw new Error(`BuildShip returned no output for step "${t}"${p}`)}return Array.isArray(h)&&(h=h.map(p=>typeof p=="string"?p:p.text||"").join("")),typeof h!="string"&&(h=JSON.stringify(h)),h}catch(l){throw l.name==="AbortError"?new Error(`BuildShip ${t} timed out after ${12e4/1e3}s`):l instanceof TypeError?new Error(`BuildShip unreachable: ${l.message}`):l}finally{clearTimeout(a)}}function n_(){const e=new URLSearchParams(window.location.search).get("checkout");e==="success"?(window.history.replaceState({},"",window.location.pathname),Na(),ue("Subscription active! Welcome aboard.","success")):e==="cancel"&&(window.history.replaceState({},"",window.location.pathname),ue("Checkout cancelled.","info"))}function Yn(){const t=G.isVerified&&!!G.email,e=fe.tier,s=t&&$a(),r=!t||Jt(),n=document.getElementById("subscription-tier-badge");if(n){const a={free:"Free",professional:"Professional",power:"Power Developer"},l={free:"bg-gray-100 text-gray-600",professional:"bg-indigo-100 text-indigo-700",power:"bg-purple-100 text-purple-700",unresolved:"bg-red-50 text-red-600"};n.textContent=s?"Checking…":r?a[e]||"Free":"Plan unavailable",n.className=`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${r?l[e]||l.free:l.unresolved}`}const i=document.getElementById("upgrade-prompt");i&&i.classList.toggle("hidden",!t||s||!r||e!=="free");const o=document.getElementById("manage-billing-btn");o&&o.classList.toggle("hidden",!t||s||r&&e==="free"),i_(r?e:null),t_(),Md(),Xs()}function i_(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(([n,{btnId:i,defaultText:o}])=>{const a=document.getElementById(i);a&&(n===t?(a.disabled=!0,a.textContent="Current plan",a.classList.add(...e)):(a.disabled=!1,a.textContent=o,a.classList.remove(...e)))});const r=document.getElementById("free-tier-current");r&&r.classList.toggle("hidden",t!=="free")}function Mo(){const t=Dd(),e=document.getElementById("pro-price"),s=document.getElementById("power-price"),r=document.getElementById("pro-price-note"),n=document.getElementById("power-price-note");e&&(e.textContent=vc(mc.professional,t)),s&&(s.textContent=vc(mc.power,t));const i="billed monthly";r&&(r.textContent=i),n&&(n.textContent=i)}function Fn(){Mo();const t=document.getElementById("pricing-modal");t&&t.classList.add("open"),Gm().then(()=>Mo())}function sh(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("pricing-modal");e&&e.classList.remove("open")}function ue(t,e="info"){const s={success:"bg-green-600 text-white",error:"bg-red-600 text-white",warning:"bg-amber-500 text-white",info:"bg-gray-800 text-white"},r=document.createElement("div");r.className=`fixed bottom-6 left-1/2 -translate-x-1/2 px-5 py-3 rounded-lg text-sm font-medium shadow-lg z-50 transition-opacity duration-300 ${s[e]||s.info}`,r.textContent=t,document.body.appendChild(r),setTimeout(()=>{r.style.opacity="0",setTimeout(()=>r.remove(),300)},3500)}document.addEventListener("DOMContentLoaded",async()=>{hljs.configure({tabReplace:" ",classPrefix:"hljs-"}),o_(),await zv(),n_(),await th(),Yn(),Mo(),await _v(),pv();const t=document.getElementById("flutterflow-endpoint-select");if(t){const s=fr();t.value=s}zd(),Qd();const e=document.getElementById("pipeline-input");e&&(e.addEventListener("input",()=>{Et===2&&e.value.trim().length>0&&(ma(),Un())}),e.addEventListener("blur",()=>{const s=document.getElementById("walkthrough-modal");Et===2&&s&&s.classList.add("open")}),e.addEventListener("keydown",s=>{if(s.key==="Tab"){const r=document.getElementById("walkthrough-modal");Et===2&&r&&setTimeout(()=>{r.classList.add("open")},100)}})),window.addEventListener("commitStateChange",s=>{const{state:r}=s.detail;r===V.PREPARING||r===V.VALIDATING||r===V.PUSHING?(be.phaseId||ih(),Ic(r)):(r===V.SUCCESS||r===V.ERROR)&&(Ic(r),setTimeout(Pn,1e3))})});function o_(){const t=document.getElementById("preview-frame-container");t&&(t.style.display="")}function a_(){const t=document.getElementById("welcome-video-player");t&&(t.addEventListener("click",Yt),document.addEventListener("keydown",Yt))}function Yt(){const t=document.getElementById("preview-frame-container"),e=document.getElementById("main-stage-container"),s=document.getElementById("ready-state");t&&(t.style.display="none"),e&&e.classList.add("visible"),s&&s.classList.remove("hidden");const r=document.getElementById("welcome-video-player");r&&r.removeEventListener("click",Yt),document.removeEventListener("keydown",Yt),zd()}let Qs=null;async function l_(){const t=document.getElementById("confirm-project-select");if(!t)return;const e=++Ec,s=()=>e===Ec,r=await Ee("flutterflow"),n=await Ee("flutterflow_project_id");if(s()){if(!r){t.innerHTML='',t.disabled=!0;return}t.disabled=!1,t.innerHTML='';try{const o=await new gr(r,"").listProjects();if(!s())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)}),n&&(t.value=n)}catch(i){if(!s())return;console.error("Failed to load projects for deploy:",i),t.innerHTML=''}}}function c_(){return document.getElementById("confirm-project-select")?.value?.trim()||null}function rh(t,e,s,r=null){Qs={codeInfo:t,checks:e,deps:s,bundlePlan:r},document.getElementById("confirm-file-name").textContent=t.fileName,document.getElementById("confirm-artifact-type").textContent=t.artifactType,document.getElementById("confirm-file-size").textContent=`${(t.content.length/1024).toFixed(1)} KB`,document.getElementById("confirm-line-count").textContent=r?`${r.fileEntries.length} files`:t.content.split(` +`).length,l_();const n=document.getElementById("confirm-deps-list"),i=document.getElementById("confirm-deps-section");s&&Object.keys(s).length>0?(n.innerHTML=Object.entries(s).map(([u,c])=>{const d=c?`at least ${bt(c)}`:"version resolved from your project";return`
  • • ${bt(u)}: ${d}
  • `}).join(""),i.classList.remove("hidden")):i.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=>`
  • • ${bt(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&&l.classList.add("open")}function nh(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("commit-confirm-modal");e&&e.classList.remove("open"),Qs=null}function u_(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("commit-success-modal");e&&e.classList.remove("open");const s=["success-message","success-project-id","success-file-name","success-artifact-type","success-time","success-size"];for(const i of s){const o=document.getElementById(i);o&&(o.textContent="")}const r=document.getElementById("success-warnings-section");r&&r.classList.add("hidden");const n=document.getElementById("success-warnings-list");n&&(n.innerHTML="")}function Lo(t){const e=(g,_)=>{const w=document.getElementById(g);w&&(w.textContent=_||"")},s=t.metadata?.fileName||"",r=t.metadata?.projectId||"",n=t.metadata?.artifactType||"",i=t.elapsedTime?`${(t.elapsedTime/1e3).toFixed(1)}s`:"",o=t.metadata?.codeSize?`${(t.metadata.codeSize/1024).toFixed(1)} KB`:"";e("success-message",t.message||"Code committed successfully!"),e("success-project-id",r),e("success-file-name",s),e("success-artifact-type",n),e("success-time",i),e("success-size",o);const a=t.addedDependencies||[],l=document.getElementById("success-deps-row");l&&l.classList.toggle("hidden",a.length===0),e("success-deps",a.join(", "));const u=document.getElementById("success-open-ff-link");u&&r&&(u.href=`https://app.flutterflow.io/project/${r}`);const c=document.getElementById("success-warnings-section"),d=document.getElementById("success-warnings-list"),h=t.unverified||[],p=t.approximate||[],f=t.warnings||[];(f.length>0||h.length>0||p.length>0)&&c&&d&&(d.innerHTML=[...h.map(g=>`
  • Not verified before deploying: ${B(String(g))}
  • `),...p.map(g=>`
  • Verified approximately: ${B(String(g))}
  • `),...f.map(([g,_])=>`
  • ${B(g)}: ${B(String(_))}
  • `)].join(""),c.classList.remove("hidden"));const m=document.getElementById("commit-success-modal");m&&m.classList.add("open")}function Oo(t){Pn(),Dv(t)}function d_(){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 kc={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}},h_=[{after:0,text:"Starting a FlutterFlow build runner..."},{after:12,text:"Preparing the FlutterFlow AI workspace..."},{after:35,text:"Uploading your custom classes..."},{after:60,text:"FlutterFlow is applying the changes..."},{after:100,text:"Still working — this can take a couple of minutes..."}],be={sequence:[],phaseId:null,phaseStartedAt:null,timer:null,substatus:null,liveSubstatus:!1,start({withProvisioning:t=!1}={}){this.sequence=["prepare","validate","project"],t&&this.sequence.push("provision"),this.sequence.push("package","push","done");const e=document.getElementById("commit-progress-overlay");e&&e.classList.add("open"),this.set("prepare")},set(t,e=null){if(!(!kc[t]||t===this.phaseId)){if(!this.sequence.includes(t)){const s=this.sequence.indexOf("package");this.sequence.splice(s===-1?this.sequence.length:s,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=kc[this.phaseId];if(!t)return;const e=(Date.now()-this.phaseStartedAt)/1e3,s=t.start+(t.end-t.start)*(1-Math.exp(-e/25));if(this.phaseId==="provision"&&!this.liveSubstatus){const o=h_.filter(a=>e>=a.after).pop();o&&(this.substatus=o.text)}const r=this.sequence.indexOf(this.phaseId),i=[`Step ${r===-1?1:r+1} of ${this.sequence.length}`];e>=5&&i.push(p_(e)),oh(this.phaseId==="done"?100:s,t.message,i.join(" · "),this.substatus)},stop(){this.timer&&clearInterval(this.timer),this.timer=null,this.phaseId=null;const t=document.getElementById("commit-progress-overlay");t&&t.classList.remove("open")}};function p_(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 ih(t){be.start(t)}function Pn(){be.stop()}function oh(t,e,s,r=null){const n=document.getElementById("commit-progress-bar"),i=document.getElementById("progress-message"),o=document.getElementById("progress-detail"),a=document.getElementById("progress-substatus");n&&(n.style.width=`${Math.round(t*10)/10}%`),i&&(i.textContent=e),o&&(o.textContent=s),a&&(a.textContent=r||"",a.classList.toggle("hidden",!r))}function Ic(t){const e={[V.PREPARING]:"prepare",[V.VALIDATING]:"validate",[V.PUSHING]:"project",[V.SUCCESS]:"done"};if(t===V.ERROR){be.timer&&clearInterval(be.timer),be.timer=null,oh(100,"Failed","Error occurred");return}const s=e[t];s&&be.set(s)}function f_(t){return t.bundlePlan?t.bundlePlan.fileEntries.some(e=>e.type===U.CODE_FILE):t.codeInfo?.codeType===U.CODE_FILE}async function g_(){if(!Qs){console.error("No pending commit data");return}const t=Qs;if(Qs=null,Zs=c_(),nh(),ih({withProvisioning:f_(t)}),t.bundlePlan){const o=await Cv(t.bundlePlan,{pipelineResult:{step1Result:y.step1Result,selectedModel:document.getElementById("code-generator-model")?.value}});Zs=null,Pn(),o.success?Lo(o):Oo(o);return}const{codeInfo:e}=t,{artifactType:s,artifactName:r,fileName:n}=Vd(),i=await Iv(e.content,{artifactType:s,artifactName:r,fileName:n,pipelineResult:{step1Result:y.step1Result,selectedModel:document.getElementById("code-generator-model")?.value}});Zs=null,Pn(),i.success?Lo(i):Oo(i)}window.runThinkingPipeline=To;window.toggleStep=Av;window.toggleSection=Pv;window.selectWorkflowStep=ze;window.copyCode=$v;window.retryWithDifferentModel=Mv;window.openApiKeysModal=ga;window.closeApiKeysModal=Hd;window.closeWalkthroughModal=av;window.openWalkthroughModal=ov;window.advanceWalkthrough=ma;window.commitToFlutterFlow=kv;function m_(){const t=document.getElementById("pipeline-input");t&&t.focus()}function v_(){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=m_;window.openModelSelector=v_;window.handlePromptImageSelect=qm;window.removePromptImage=Vm;window.saveApiKeys=uv;window.clearAllApiKeys=dv;window.toggleKeyVisibility=gv;window.handleWelcomeVideoEnd=a_;window.dismissWelcomeVideo=Yt;window.initiateCommitToFlutterFlow=Lv;window.updateFlutterFlowCredentialStatus=jv;window.closeCommitConfirmModal=nh;window.closeCommitSuccessModal=u_;window.showCommitSuccessModal=Lo;window.showCommitFailureModal=Oo;window.toggleCodePreview=d_;window.confirmCommitToFlutterFlow=g_;window.runRefinement=Rv;window.regenerateFromPastedErrors=Nv;window.clearErrorInput=Tv;window.setFlutterFlowEndpoint=iv;window.getFlutterFlowEndpoint=fr;window.commitProgress=be;window.openSignInModal=Pa;window.closeSignInModal=qv;window.handleMagicLinkRequest=Vv;window.handleSignOut=Gv;window.startCheckout=s_;window.openCustomerPortal=r_;window.openPricingModal=Fn;window.closePricingModal=sh;let hs=null,ah=null;const Cc=120;function Zn(){const t=document.getElementById("pipeline-progress"),e=document.getElementById("results-view"),s=document.getElementById("ready-state");s&&s.classList.add("hidden"),e&&e.classList.remove("visible"),document.body.classList.remove("results-fullscreen","results-with-sidebar"),t&&t.classList.add("visible"),ah=Date.now();for(let r=1;r<=3;r++){const n=document.getElementById(`pdot-${r}`);n&&(n.className="progress-dot")}nt(1),__()}function nt(t){const e={1:"Analyzing your prompt...",2:"Generating Dart code...",3:"Running code audit..."},s={1:"Step 1 of 3 — Prompt Architect",2:"Step 2 of 3 — Code Generator",3:"Step 3 of 3 — Code Review"},r=document.getElementById("progress-title-text"),n=document.getElementById("progress-substep-text");r&&(r.textContent=e[t]||e[1]),n&&(n.textContent=s[t]||s[1]);for(let i=1;i<=3;i++){const o=document.getElementById(`pdot-${i}`);o&&(i{const t=(Date.now()-ah)/1e3,e=document.getElementById("progress-elapsed"),s=document.getElementById("pipeline-progress-fill");e&&(e.textContent=`${Math.floor(t)}s`);const r=t/Cc*100,n=Math.min(95,r*(1-Math.exp(-t/(Cc*.6)))*1.2);s&&(s.style.width=`${n}%`)},250)}function $t(){hs&&(clearInterval(hs),hs=null);const t=document.getElementById("pipeline-progress-fill");t&&(t.style.width="100%");for(let e=1;e<=3;e++){const s=document.getElementById(`pdot-${e}`);s&&(s.className="progress-dot completed")}setTimeout(()=>{const e=document.getElementById("pipeline-progress");e&&e.classList.remove("visible"),t&&(t.style.width="0%")},400)}function Ss(t,e=""){const s={pass:'',warning:'',fail:'',info:''};return``}function lh(t){return{pass:"Passed review",warning:"Needs attention",fail:"Blocking issues"}[t]||"Needs attention"}function y_(){return jg({bundle:y.artifactBundle,reviewResult:y.step3Result})}function w_(t){return`
    ${Ss(t.severity)}
    -
    ${j(t.message)}
    - ${t.suggestion?`
    ${j(t.suggestion)}
    `:""} - ${j(t.source)} +
    ${B(t.message)}
    + ${t.suggestion?`
    ${B(t.suggestion)}
    `:""} + ${B(t.source)}
    - `}function E_(t){return` + `}function b_(t){return`
  • - ${j(t.title)} - ${t.detail&&t.detail!==t.title?`

    ${j(t.detail)}

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

    ${B(t.detail)}

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

      ${j(t.summary)}

      +

      ${B(t.summary)}

      ${o} ${a}
      -
      - `}function x_(t){const e=t.artifacts.find(l=>l.id===y.selectedArtifactId)||t.artifacts[0];if(!e)return"";const s={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],n=e.findings.length?e.findings.map(b_).join(""):`
      ${Ss(s.icon)} ${j(s.message)}
      `,r=e.dependencies?.length?e.dependencies.map(l=>` -
    • ${j(l.name)}${l.version?` ${j(l.version)}`:""}${l.reason?`

      ${j(l.reason)}

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

      ${j(l.description)}

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

      ${B(l.reason)}

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

      ${B(l.description)}

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

      ${j(e.artifactName)}

      - ${e.description?`

      ${j(e.description)}

      `:""} + ${Ss(e.status)} ${B(lh(e.status))} +

      ${B(e.artifactName)}

      + ${e.description?`

      ${B(e.description)}

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

      Code Review findings

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

      Manual FlutterFlow steps for this file

      -
        ${e.manualSteps.map(E_).join("")}
      +
        ${e.manualSteps.map(b_).join("")}
      `:""}
      @@ -280,14 +280,14 @@ Error: ${h}

      Dependencies

      -
        ${r}
      +
        ${n}

      Deployment

      -
      Status
      ${j(e.deployStatus||"pending")}
      +
      Status
      ${B(e.deployStatus||"pending")}
      Order
      ${e.index+1} of ${t.artifacts.length}
      -
      Path hint
      ${j(e.pathHint||"Not returned")}
      +
      Path hint
      ${B(e.pathHint||"Not returned")}
      @@ -304,17 +304,17 @@ Error: ${h}
        ${a}
      - `}function k_(t){const e=document.getElementById("bundle-strip"),s=document.getElementById("results-summary-tab"),n=document.getElementById("artifact-tabs"),r=document.getElementById("results-file-count");if(s&&s.classList.toggle("active",y.resultsViewMode==="summary"),!t.artifacts.length){r&&(r.textContent="0 files"),e&&e.classList.remove("visible"),n&&(n.innerHTML="");return}if(r){const i=t.artifacts.length;r.textContent=`${i} ${i===1?"file":"files"}`}n&&(n.innerHTML=t.artifacts.map(i=>` + `}function x_(t){const e=document.getElementById("bundle-strip"),s=document.getElementById("results-summary-tab"),r=document.getElementById("artifact-tabs"),n=document.getElementById("results-file-count");if(s&&s.classList.toggle("active",y.resultsViewMode==="summary"),!t.artifacts.length){n&&(n.textContent="0 files"),e&&e.classList.remove("visible"),r&&(r.innerHTML="");return}if(n){const i=t.artifacts.length;n.textContent=`${i} ${i===1?"file":"files"}`}r&&(r.innerHTML=t.artifacts.map(i=>` - `).join(""),n.onclick=i=>{const o=i.target.closest(".artifact-tab");o?.dataset?.artifactId&&uh(o.dataset.artifactId)}),e&&e.classList.add("visible")}function Ma(){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"),s=document.getElementById("results-audit-output"),n=document.getElementById("results-summary-detail"),r=document.getElementById("artifact-results-split"),i=w_(),o=ya();if(S_(i),k_(i),e&&(e.textContent=""),e){const a=Td(o);e.innerHTML=a}s&&(s.innerHTML=x_(i)),n&&n.classList.toggle("hidden",y.resultsViewMode!=="summary"),r&&r.classList.toggle("hidden",y.resultsViewMode!=="file"),t&&t.classList.add("visible")}function Xr(t,e){y.selectedArtifactId||(y.selectedArtifactId=mr(y.artifactBundle).id),y.resultsViewMode="summary",document.body.classList.add("results-fullscreen");const s=document.getElementById("step3-output");s&&(s.textContent=""),Ma(),Zt();const n=document.getElementById("btn-feedback-up"),r=document.getElementById("btn-feedback-down");n&&(n.className="feedback-btn"),r&&(r.className="feedback-btn")}function uh(t){y.selectedArtifactId=t,y.resultsViewMode="file",Ma()}function I_(){y.resultsViewMode="summary",Ma()}function C_(){const t=document.getElementById("btn-copy-results"),e=ya();navigator.clipboard.writeText(e).then(()=>{if(t){t.classList.add("copied");const s=t.querySelector("span");if(s){const n=s.textContent;s.textContent="Copied!",setTimeout(()=>{t.classList.remove("copied"),s.textContent=n},2e3)}}})}function F_(t){const e=document.getElementById("btn-feedback-up"),s=document.getElementById("btn-feedback-down");t==="up"?(e.classList.toggle("active-up"),s.classList.remove("active-down")):(s.classList.toggle("active-down"),e.classList.remove("active-up")),Ca(t==="up"?"thumbsUp":"thumbsDown",y.step2Result,y.step1Result)}function P_(){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 dh(){const t=document.getElementById("error-input-panel");t&&(t.classList.add("hidden"),t.style.display="none")}window.copyResultsCode=C_;window.selectArtifact=uh;window.selectResultsSummary=I_;window.submitResultsFeedback=F_;window.showErrorInputPanel=P_;window.hideErrorInputPanel=dh; + `).join(""),r.onclick=i=>{const o=i.target.closest(".artifact-tab");o?.dataset?.artifactId&&ch(o.dataset.artifactId)}),e&&e.classList.add("visible")}function Ma(){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"),s=document.getElementById("results-audit-output"),r=document.getElementById("results-summary-detail"),n=document.getElementById("artifact-results-split"),i=y_(),o=ya();if(E_(i),x_(i),e&&(e.textContent=""),e){const a=Rd(o);e.innerHTML=a}s&&(s.innerHTML=S_(i)),r&&r.classList.toggle("hidden",y.resultsViewMode!=="summary"),n&&n.classList.toggle("hidden",y.resultsViewMode!=="file"),t&&t.classList.add("visible")}function Xn(t,e){y.selectedArtifactId||(y.selectedArtifactId=mn(y.artifactBundle).id),y.resultsViewMode="summary",document.body.classList.add("results-fullscreen");const s=document.getElementById("step3-output");s&&(s.textContent=""),Ma(),Zt();const r=document.getElementById("btn-feedback-up"),n=document.getElementById("btn-feedback-down");r&&(r.className="feedback-btn"),n&&(n.className="feedback-btn")}function ch(t){y.selectedArtifactId=t,y.resultsViewMode="file",Ma()}function k_(){y.resultsViewMode="summary",Ma()}function I_(){const t=document.getElementById("btn-copy-results"),e=ya();navigator.clipboard.writeText(e).then(()=>{if(t){t.classList.add("copied");const s=t.querySelector("span");if(s){const r=s.textContent;s.textContent="Copied!",setTimeout(()=>{t.classList.remove("copied"),s.textContent=r},2e3)}}})}function C_(t){const e=document.getElementById("btn-feedback-up"),s=document.getElementById("btn-feedback-down");t==="up"?(e.classList.toggle("active-up"),s.classList.remove("active-down")):(s.classList.toggle("active-down"),e.classList.remove("active-up")),Ca(t==="up"?"thumbsUp":"thumbsDown",y.step2Result,y.step1Result)}function F_(){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 uh(){const t=document.getElementById("error-input-panel");t&&(t.classList.add("hidden"),t.style.display="none")}window.copyResultsCode=I_;window.selectArtifact=ch;window.selectResultsSummary=k_;window.submitResultsFeedback=C_;window.showErrorInputPanel=F_;window.hideErrorInputPanel=uh; diff --git a/dist/index.html b/dist/index.html index 05848f5..7f9d8fb 100644 --- a/dist/index.html +++ b/dist/index.html @@ -2420,7 +2420,7 @@ .pm-cards { padding: 0 16px; } } - +
      diff --git a/src/customCodeVerification.js b/src/customCodeVerification.js index 5fc19a3..6813705 100644 --- a/src/customCodeVerification.js +++ b/src/customCodeVerification.js @@ -159,18 +159,6 @@ function skipReason(className, unresolvableImports, missingPackages) { return `${className} imports ${missingPackages.join(", ")}, which your project's pubspec.yaml does not declare with a version constraint, so it could not be compiled before the deploy.`; } -/** - * The reason a class is skipped over a package it never names itself. - * - * @param {string} className - The class being skipped - * @param {string[]} unrepresentablePackages - Packages the project declares - * from sources the manifest cannot express - * @returns {string} User-facing reason naming both - */ -function transitiveSkipReason(className, unrepresentablePackages) { - return `${className} was not compiled before deploying: your project declares ${unrepresentablePackages.join(", ")} from a source that cannot be reproduced outside it, and whether the packages ${className} imports depend on one of them transitively cannot be checked before the deploy, so package resolution could not be matched exactly.`; -} - /** * Plans the compile check that runs before custom classes are pushed. * @@ -181,28 +169,31 @@ function transitiveSkipReason(className, unrepresentablePackages) { * `skipped` so the deploy can say plainly what it did not verify. * * A dependency that cannot be reproduced outside the project - a `git:`, - * `path:`, or custom-`hosted:` source - stops any class whose compilation - * shares a package graph with it. Importing it directly is the clear case and - * names itself in `skipped`. But a class that imports only representable - * packages can still be affected: pub resolution is one shared graph, so a - * representable import may depend on the unrepresentable package transitively, - * and whether it does is knowable only by resolving the graph, which cannot - * happen here. The scratch manifest omits the package, so `pub get` resolves - * that transitive slot differently there and the check could report a result - * that does not describe what ships. When the project declares any - * unrepresentable source, every class that imports a `package:` URI is - * therefore skipped and named with that reason; a class compiled from - * `dart:` alone does not touch package resolution and verifies normally. + * `path:`, or custom-`hosted:` source - cannot be expressed in the scratch + * manifest, which carries names and version constraints only. Such a + * dependency is handled by scope, not by breadth: + * + * - A class that imports it directly cannot compile without it at all, so it + * is skipped and `skipped` names the import as this class's own problem. + * - Every other class is still verified, against a scratch graph that omits + * the unrepresentable package. A representable import may reach that + * package transitively - knowable only by resolving the graph, which + * cannot happen here - so for those classes the check is approximate. + * `approximate` carries one notice per unrepresentable package stating + * exactly that, so the limitation is disclosed rather than silently + * trusted, and the result is never mistaken for full graph fidelity. A + * class importing only `dart:` never touches package resolution, so the + * approximation does not reach it. * - * A project with no unrepresentable sources verifies exactly as before, and - * the class that directly imports such a package is still told so plainly. - * The earlier scoping - skipping only the classes that directly imported it - - * kept classes compiling that shared a graph with a package they never named, - * which was not a check on what ships. + * Skipping every class with a `package:` import instead was rejected: one + * unrelated git or path dependency would disable the compile check for + * nearly the whole deployment, and invalid custom code would land unopposed. + * Verifying with a disclosed approximation keeps the check on the code that + * ships while saying plainly what it could not reproduce. * * @param {Array<{className: string, content: string}>} classes - Classes to deploy * @param {string} projectPubspecYaml - The project's merged pubspec.yaml - * @returns {{manifest: Object, sources: Array<{fileName: string, content: string}>, skipped: Array<{className: string, reason: string}>}} + * @returns {{manifest: Object, sources: Array<{fileName: string, content: string}>, skipped: Array<{className: string, reason: string}>, approximate: string[]}} */ export function planCustomCodeVerification(classes, projectPubspecYaml) { const { @@ -218,6 +209,16 @@ export function planCustomCodeVerification(classes, projectPubspecYaml) { const sources = []; const skipped = []; + // The scratch manifest omits every unrepresentable package, so any class + // that does not import one directly is checked against a reduced graph. + // Disclosing that per package - rather than skipping those classes or + // silently trusting the scratch - keeps the check running and the human + // told what it could not reproduce. + const approximate = unrepresentable.map( + (name) => + `Your project declares ${name} from a source that cannot be reproduced outside it, so the pre-deploy compile check runs against a scratch package graph that omits ${name}. Classes that do not import ${name} directly are still checked, but against that reduced graph, so their transitive package resolution may differ from your project's and the check is approximate for them.`, + ); + for (const entry of classes) { const { className, content } = entry; @@ -250,30 +251,11 @@ export function planCustomCodeVerification(classes, projectPubspecYaml) { continue; } - // The transitive hole: pub resolves one shared graph, so even a class - // whose every import is representable may reach a package the manifest - // omits through the dependencies of what it does import. Reachability is - // knowable only by resolving the graph, so while the project declares - // any unrepresentable source the class is skipped rather than compiled - // against a graph that differs from the project's. A class importing - // nothing from `package:` never touches pub resolution and compiles - // against exactly what the project will. - if ( - unrepresentable.length > 0 && - extractImportUris(content).some((uri) => uri.startsWith("package:")) - ) { - skipped.push({ - className, - reason: transitiveSkipReason(className, unrepresentable), - }); - continue; - } - sources.push({ fileName: `${identifierToFlutterFlowFileStem(className)}.dart`, content, }); } - return { manifest, sources, skipped }; + return { manifest, sources, skipped, approximate }; } diff --git a/src/customCodeVerification.test.js b/src/customCodeVerification.test.js index 4179e57..baaff8c 100644 --- a/src/customCodeVerification.test.js +++ b/src/customCodeVerification.test.js @@ -145,22 +145,28 @@ dependencies: assert.equal("hosted_thing" in manifest.dependencies, false); }); -test("a git dependency stops even a class that never imports it, because resolution is shared", () => { +test("a representable import verifies beside an unrelated git dependency, and the plan discloses the approximation", () => { const plan = planCustomCodeVerification( [{ className: "BackgroundDownloaderService", content: SELF_CONTAINED }], PROJECT_PUBSPEC, ); // The project declares `private_thing` from git, which the scratch manifest - // cannot express. `background_downloader` may depend on it transitively - - // knowable only by resolving the graph - so compiling this class elsewhere - // could report a result that does not describe what ships. The skip says - // that instead of silently compiling against a differently-resolved graph. - assert.deepEqual(plan.sources, []); - assert.equal(plan.skipped.length, 1); - assert.equal(plan.skipped[0].className, "BackgroundDownloaderService"); - assert.match(plan.skipped[0].reason, /private_thing/); - assert.match(plan.skipped[0].reason, /BackgroundDownloaderService/); + // cannot express - but this class never imports it, so it is still compiled + // and checked. The check is approximate (whether what it does import + // reaches `private_thing` transitively is knowable only by resolving the + // graph), so `approximate` says so per package instead of skipping the + // class, which would have disabled the check for nearly the whole deploy. + assert.deepEqual(plan.sources, [ + { + fileName: "background_downloader_service.dart", + content: SELF_CONTAINED, + }, + ]); + assert.deepEqual(plan.skipped, []); + assert.equal(plan.approximate.length, 1); + assert.match(plan.approximate[0], /private_thing/); + assert.match(plan.approximate[0], /approximate/); }); test("a class that imports the unreproducible dependency is skipped, and named as the reason", () => { @@ -177,20 +183,22 @@ class UsesPrivateThing {} PROJECT_PUBSPEC, ); - // The direct import keeps its own reason: it names this class's own import, - // so it says what to do about this class. - assert.deepEqual(plan.sources, []); - assert.equal(plan.skipped.length, 2); + // The direct import keeps its own reason: it names this class's own + // import, so it says what to do about this class. + assert.deepEqual( + plan.sources.map((source) => source.fileName), + ["background_downloader_service.dart"], + ); + assert.equal(plan.skipped.length, 1); assert.equal(plan.skipped[0].className, "UsesPrivateThing"); assert.match(plan.skipped[0].reason, /it imports private_thing/); - // The sibling never imports it, but the shared graph still cannot be - // reproduced, so it is skipped with the transitive reason rather than - // compiled against a graph that differs from the project's. - assert.equal(plan.skipped[1].className, "BackgroundDownloaderService"); - assert.match(plan.skipped[1].reason, /private_thing/); + // The sibling never imports the git package, so it is checked rather than + // skipped - approximately, and the plan-level notice discloses that. + assert.equal(plan.approximate.length, 1); + assert.match(plan.approximate[0], /private_thing/); }); -test("a representable import is skipped when an override elsewhere is unrepresentable", () => { +test("a representable import verifies when an override elsewhere is unrepresentable, and the notice names it", () => { const pubspec = `name: my_app environment: @@ -212,16 +220,22 @@ dependency_overrides: pubspec, ); - // The class imports `background_downloader`, which the manifest can express, - // and never touches `intl` - but the git override of `intl` cannot be - // carried, and whether `background_downloader` depends on `intl` - // transitively is knowable only by resolving the graph. The conservative - // skip names the package and the class truthfully. - assert.deepEqual(plan.sources, []); - assert.equal(plan.skipped.length, 1); - assert.equal(plan.skipped[0].className, "BackgroundDownloaderService"); - assert.match(plan.skipped[0].reason, /intl/); - assert.match(plan.skipped[0].reason, /BackgroundDownloaderService/); + // The class imports `background_downloader`, which the manifest can + // express, and never touches `intl` - but the git override of `intl` + // cannot be carried, and whether `background_downloader` depends on + // `intl` transitively is knowable only by resolving the graph. The class + // is therefore checked rather than skipped, and the plan-level notice + // discloses the approximation the check ran with. + assert.deepEqual(plan.sources, [ + { + fileName: "background_downloader_service.dart", + content: SELF_CONTAINED, + }, + ]); + assert.deepEqual(plan.skipped, []); + assert.equal(plan.approximate.length, 1); + assert.match(plan.approximate[0], /intl/); + assert.match(plan.approximate[0], /approximate/); }); test("a class compiled from dart: alone still verifies beside a git dependency", () => { @@ -235,14 +249,33 @@ test("a class compiled from dart: alone still verifies beside a git dependency", PROJECT_PUBSPEC, ); - // `dart:` libraries come from the SDK rather than pub resolution, so a class - // importing nothing from `package:` compiles against exactly what the - // project will, whatever the project's sources are. + // `dart:` libraries come from the SDK rather than pub resolution, so a + // class importing nothing from `package:` compiles against exactly what + // the project will, whatever the project's sources are. `approximate` is + // plan-level, so it still carries the notice for the package-importing + // classes this deploy could contain - but nothing about this class's own + // check is approximate. assert.deepEqual( plan.sources.map((source) => source.fileName), ["pure_dart_service.dart"], ); assert.deepEqual(plan.skipped, []); + assert.equal(plan.approximate.length, 1); + assert.match(plan.approximate[0], /private_thing/); +}); + +test("a project whose sources are all representable verifies with nothing to disclose", () => { + const plan = planCustomCodeVerification( + [{ className: "BackgroundDownloaderService", content: SELF_CONTAINED }], + REPRESENTABLE_PUBSPEC, + ); + + // Every dependency the project declares can be expressed in the scratch + // manifest, so the check runs against the project's own graph and there is + // no approximation to warn about. + assert.equal(plan.sources.length, 1); + assert.deepEqual(plan.skipped, []); + assert.deepEqual(plan.approximate, []); }); test("an SDK package no list has heard of is reproduced from its pubspec source", () => {