From 9acab4f805659f00321d0e24b3e92128076ffcd1 Mon Sep 17 00:00:00 2001 From: Stuart Date: Sun, 26 Jul 2026 12:27:13 +1000 Subject: [PATCH 1/8] fix: enforce FlutterFlow action return types --- app.js | 54 +- dist/assets/index-B5FTuKa7.js | 188 ------ dist/assets/index-BLDY07Z-.js | 304 +++++++++ dist/index.html | 767 ++++++++++++++++++---- scripts/deploy_cloud_run_ffai.sh | 4 +- src/cloudRunRunner.test.js | 11 + src/flutterFlowArtifactValidation.js | 68 +- src/flutterFlowArtifactValidation.test.js | 61 ++ 8 files changed, 1147 insertions(+), 310 deletions(-) delete mode 100644 dist/assets/index-B5FTuKa7.js create mode 100644 dist/assets/index-BLDY07Z-.js diff --git a/app.js b/app.js index 986b1bd..00bf784 100644 --- a/app.js +++ b/app.js @@ -12,7 +12,11 @@ import { createBuildShipContext, } from "./src/pipelineContracts.js"; import { createModelArmorError } from "./src/modelArmorResponse.js"; -import { validateBundleCompatibility } from "./src/flutterFlowArtifactValidation.js"; +import { + getCustomActionReturnTypeError, + getDeclaredDartTypes, + validateBundleCompatibility, +} from "./src/flutterFlowArtifactValidation.js"; import { buildBundleDeployPlan } from "./src/bundleDeployPlanner.js"; import { excludeProvisionedCodeFiles, @@ -308,6 +312,11 @@ const FF_ARTIFACT_TYPES = `## THE FOUR ARTIFACT SURFACES ### B) Custom Actions (Async/Side Effects Silo) - **Purpose:** API calls, complex logic, third-party libraries - **Return type:** ALWAYS Future +- **Supported Return Values:** Use only types exposed by FlutterFlow's Custom Action Return Value selector. +- **Structured results:** Default to JSON with \`Future\` or \`Future>\`, and return a JSON-compatible Map/List (for example, \`result.toJson()\`). +- **FlutterFlow Data Types:** \`Future\` is allowed only when that Data Type already exists in the project. +- **Forbidden:** Never return an arbitrary CustomClass, Code File class, or CustomEnum from a Custom Action. FlutterFlow supports those in state/parameters, but not as Custom Action return values. +- **State workaround:** Write to App/Page State and return \`bool\` only when the user explicitly requests it and the required state variable is documented. Never assume state exists. - **Imports:** - External packages: include (e.g., \`import 'package:flutter_tts/flutter_tts.dart';\`) - FlutterFlow imports: DO NOT include - added at commit @@ -382,7 +391,7 @@ Page State variables (local to a single page) support everything App State does, - When the user needs to store byte data: use a callback to pass bytes back to FlutterFlow (user can store in Page State), or convert to base64 String for App State storage, or upload to storage and store the resulting URL as ImagePath. - NEVER generate code that writes FFUploadedFile or Uint8List to FFAppState — it will not compile. -**IMPORTANT:** Custom Dart classes for data exchange are now allowed via "Code Files", but Structs are still preferred for parameters visible in the UI builder.`; +**IMPORTANT:** Custom Dart classes are allowed through Code Files for state and supported parameters. They are NOT valid Custom Action return values; use JSON or an existing FlutterFlow Struct instead.`; const FF_STATE_PATTERNS = `## STATE & DATA: FFAppState Patterns @@ -444,6 +453,7 @@ const FF_FORBIDDEN_PATTERNS = `## FORBIDDEN PATTERNS (Will cause build failures) - Adding custom imports to Custom Functions (strictly forbidden). - Using complex parameter types (EdgeInsets, Duration, TextStyle) in Widgets/Actions. - Using generics or function-typed fields in Code Files. +- Returning a CustomClass, Code File class, or CustomEnum from a Custom Action. Use JSON or an existing FlutterFlow Data Type (\`*Struct\`). ### ⛔ CRITICAL: RESERVED PARAMETER NAMES (INSTANT COMPILATION FAILURE) @@ -1821,7 +1831,15 @@ class FlutterFlowApiClient { console.log( `Push attempt ${attempt + 1} to ${baseUrl}syncCustomCodeChanges`, ); - console.log("Request:", JSON.stringify(pushCodeRequest, null, 2)); + console.log("Request metadata:", { + project_id: pushCodeRequest.project_id, + branch_name: pushCodeRequest.branch_name, + uid: pushCodeRequest.uid, + zipped_custom_code_length: + pushCodeRequest.zipped_custom_code?.length || 0, + file_map_length: pushCodeRequest.file_map?.length || 0, + functions_map_length: pushCodeRequest.functions_map?.length || 0, + }); const response = await fetch(`${baseUrl}syncCustomCodeChanges`, { method: "POST", headers: { @@ -2588,7 +2606,13 @@ function buildCommitMetadata(codeInfo, pipelineResult = {}) { * @param {string} content - File content * @returns {Object} Validation result { valid: boolean, errors: string[] } */ -function validateDartFile(fileName, content, codeType) { +function validateDartFile( + fileName, + content, + codeType, + declaredTypes = new Set(), + artifactName = "", +) { const errors = []; const hasWidgetClass = WIDGET_CLASS_REGEX.test(content); const hasStateClass = STATE_CLASS_REGEX.test(content); @@ -2660,6 +2684,14 @@ function validateDartFile(fileName, content, codeType) { ); } + if (codeType === CodeType.ACTION) { + const returnTypeError = getCustomActionReturnTypeError(content, { + functionName: artifactName, + declaredTypes, + }); + if (returnTypeError) errors.push(returnTypeError); + } + return { valid: errors.length === 0, errors, @@ -2680,6 +2712,12 @@ function validateFileMap(fileMap) { return { valid: false, errors, warnings }; } + const declaredTypes = new Set( + Array.from(fileMap.values()).flatMap((fileInfo) => + getDeclaredDartTypes(fileInfo.content || "") + ), + ); + for (const [path, fileInfo] of fileMap.entries()) { // Check for empty files if (!fileInfo.content || fileInfo.content.trim().length === 0) { @@ -2693,7 +2731,13 @@ function validateFileMap(fileMap) { // Validate Dart files if (path.endsWith(".dart")) { - const result = validateDartFile(path, fileInfo.content, fileInfo.type); + const result = validateDartFile( + path, + fileInfo.content, + fileInfo.type, + declaredTypes, + fileInfo.artifactName, + ); if (!result.valid) { errors.push(...result.errors.map((e) => `${path}: ${e}`)); } diff --git a/dist/assets/index-B5FTuKa7.js b/dist/assets/index-B5FTuKa7.js deleted file mode 100644 index f6adcc0..0000000 --- a/dist/assets/index-B5FTuKa7.js +++ /dev/null @@ -1,188 +0,0 @@ -(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const s of document.querySelectorAll('link[rel="modulepreload"]'))n(s);new MutationObserver(s=>{for(const i of s)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 t(s){const i={};return s.integrity&&(i.integrity=s.integrity),s.referrerPolicy&&(i.referrerPolicy=s.referrerPolicy),s.crossOrigin==="use-credentials"?i.credentials="include":s.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function n(s){if(s.ep)return;s.ep=!0;const i=t(s);fetch(s.href,i)}})();var f=typeof window<"u"?window:void 0,te=typeof globalThis<"u"?globalThis:f;typeof self>"u"&&(te.self=te),typeof File>"u"&&(te.File=function(){});var Jo=Array.prototype,Ri=Jo.forEach,Ai=Jo.indexOf,fe=te==null?void 0:te.navigator,y=te==null?void 0:te.document,Q=te==null?void 0:te.location,rs=te==null?void 0:te.fetch,ns=te!=null&&te.XMLHttpRequest&&"withCredentials"in new te.XMLHttpRequest?te.XMLHttpRequest:void 0,Pi=te==null?void 0:te.AbortController,ce=fe==null?void 0:fe.userAgent,C=f??{},Le={DEBUG:!1,LIB_VERSION:"1.353.0"};function Fi(r,e,t,n,s,i,o){try{var a=r[i](o),l=a.value}catch(c){return void t(c)}a.done?e(l):Promise.resolve(l).then(n,s)}function Ne(r){return function(){var e=this,t=arguments;return new Promise(function(n,s){var i=r.apply(e,t);function o(l){Fi(i,n,s,o,a,"next",l)}function a(l){Fi(i,n,s,o,a,"throw",l)}o(void 0)})}}function S(){return S=Object.assign?Object.assign.bind():function(r){for(var e=1;e{var s=n.toLowerCase();return t.indexOf(s)!==-1})};function F(r,e){return r.indexOf(e)!==-1}var mn=function(r){return r.trim()},ss=function(r){return r.replace(/^\$/,"")},Xl=Array.isArray,Xo=Object.prototype,Qo=Xo.hasOwnProperty,_n=Xo.toString,L=Xl||function(r){return _n.call(r)==="[object Array]"},je=r=>typeof r=="function",J=r=>r===Object(r)&&!L(r),kt=r=>{if(J(r)){for(var e in r)if(Qo.call(r,e))return!1;return!0}return!1},b=r=>r===void 0,K=r=>_n.call(r)=="[object String]",is=r=>K(r)&&r.trim().length===0,Ie=r=>r===null,$=r=>b(r)||Ie(r),Ke=r=>_n.call(r)=="[object Number]"&&r==r,St=r=>Ke(r)&&r>0,We=r=>_n.call(r)==="[object Boolean]",Ql=r=>r instanceof FormData,ec=r=>F(Jl,r);function os(r){return r===null||typeof r!="object"}function jr(r,e){return Object.prototype.toString.call(r)==="[object "+e+"]"}function ea(r){return!b(Event)&&function(e,t){try{return e instanceof t}catch{return!1}}(r,Event)}var tc=[!0,"true",1,"1","yes"],Ln=r=>F(tc,r),rc=[!1,"false",0,"0","no"];function Fe(r,e,t,n,s){return e>t&&(n.warn("min cannot be greater than max."),e=t),Ke(r)?r>t?(n.warn(" cannot be greater than max: "+t+". Using max value instead."),t):r0){var i=s*this.m;e.tokens=Math.min(e.tokens+i,this.o),e.lastAccess=e.lastAccess+s*this.$}}consumeRateLimit(e){var t,n=Date.now(),s=String(e),i=this.t[s];return i?this.S(i,n):(i={tokens:this.o,lastAccess:n},this.t[s]=i),i.tokens===0||(i.tokens--,i.tokens===0&&((t=this.i)==null||t.call(this,e)),i.tokens===0)}stop(){this.t={}}}var be="Mobile",Ur="iOS",Ue="Android",lr="Tablet",ta=Ue+" "+lr,ra="iPad",na="Apple",sa=na+" Watch",cr="Safari",Pt="BlackBerry",ia="Samsung",oa=ia+"Browser",aa=ia+" Internet",dt="Chrome",sc=dt+" OS",la=dt+" "+Ur,Hs="Internet Explorer",ca=Hs+" "+be,Ws="Opera",ic=Ws+" Mini",zs="Edge",ua="Microsoft "+zs,xt="Firefox",da=xt+" "+Ur,ur="Nintendo",dr="PlayStation",Tt="Xbox",pa=Ue+" "+be,fa=be+" "+cr,Zt="Windows",as=Zt+" Phone",Mi="Nokia",ls="Ouya",ha="Generic",oc=ha+" "+be.toLowerCase(),ga=ha+" "+lr.toLowerCase(),cs="Konqueror",ae="(\\d+(\\.\\d+)?)",Nn=new RegExp("Version/"+ae),ac=new RegExp(Tt,"i"),lc=new RegExp(dr+" \\w+","i"),cc=new RegExp(ur+" \\w+","i"),Gs=new RegExp(Pt+"|PlayBook|BB10","i"),uc={"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"},kr,Oi,Dn,dc=(r,e)=>e&&F(e,na)||function(t){return F(t,cr)&&!F(t,dt)&&!F(t,Ue)}(r),ma=function(r,e){return e=e||"",F(r," OPR/")&&F(r,"Mini")?ic:F(r," OPR/")?Ws:Gs.test(r)?Pt:F(r,"IE"+be)||F(r,"WPDesktop")?ca:F(r,oa)?aa:F(r,zs)||F(r,"Edg/")?ua:F(r,"FBIOS")?"Facebook "+be:F(r,"UCWEB")||F(r,"UCBrowser")?"UC Browser":F(r,"CriOS")?la:F(r,"CrMo")||F(r,dt)?dt:F(r,Ue)&&F(r,cr)?pa:F(r,"FxiOS")?da:F(r.toLowerCase(),cs.toLowerCase())?cs:dc(r,e)?F(r,be)?fa:cr:F(r,xt)?xt:F(r,"MSIE")||F(r,"Trident/")?Hs:F(r,"Gecko")?xt:""},pc={[ca]:[new RegExp("rv:"+ae)],[ua]:[new RegExp(zs+"?\\/"+ae)],[dt]:[new RegExp("("+dt+"|CrMo)\\/"+ae)],[la]:[new RegExp("CriOS\\/"+ae)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+ae)],[cr]:[Nn],[fa]:[Nn],[Ws]:[new RegExp("(Opera|OPR)\\/"+ae)],[xt]:[new RegExp(xt+"\\/"+ae)],[da]:[new RegExp("FxiOS\\/"+ae)],[cs]:[new RegExp("Konqueror[:/]?"+ae,"i")],[Pt]:[new RegExp(Pt+" "+ae),Nn],[pa]:[new RegExp("android\\s"+ae,"i")],[aa]:[new RegExp(oa+"\\/"+ae)],[Hs]:[new RegExp("(rv:|MSIE )"+ae)],Mozilla:[new RegExp("rv:"+ae)]},fc=function(r,e){var t=ma(r,e),n=pc[t];if(b(n))return null;for(var s=0;s[Tt,r&&r[1]||""]],[new RegExp(ur,"i"),[ur,""]],[new RegExp(dr,"i"),[dr,""]],[Gs,[Pt,""]],[new RegExp(Zt,"i"),(r,e)=>{if(/Phone/.test(e)||/WPDesktop/.test(e))return[as,""];if(new RegExp(be).test(e)&&!/IEMobile\b/.test(e))return[Zt+" "+be,""];var t=/Windows NT ([0-9.]+)/i.exec(e);if(t&&t[1]){var n=t[1],s=uc[n]||"";return/arm/i.test(e)&&(s="RT"),[Zt,s]}return[Zt,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,r=>{if(r&&r[3]){var e=[r[3],r[4],r[5]||"0"];return[Ur,e.join(".")]}return[Ur,""]}],[/(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i,r=>{var e="";return r&&r.length>=3&&(e=b(r[2])?r[3]:r[2]),["watchOS",e]}],[new RegExp("("+Ue+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+Ue+")","i"),r=>{if(r&&r[2]){var e=[r[2],r[3],r[4]||"0"];return[Ue,e.join(".")]}return[Ue,""]}],[/Mac OS X (\d+)[_.](\d+)[_.]?(\d+)?/i,r=>{var e=["Mac OS X",""];if(r&&r[1]){var t=[r[1],r[2],r[3]||"0"];e[1]=t.join(".")}return e}],[/Mac/i,["Mac OS X",""]],[/CrOS/,[sc,""]],[/Linux|debian/i,["Linux",""]]],Ni=function(r){return cc.test(r)?ur:lc.test(r)?dr:ac.test(r)?Tt:new RegExp(ls,"i").test(r)?ls:new RegExp("("+as+"|WPDesktop)","i").test(r)?as:/iPad/.test(r)?ra:/iPod/.test(r)?"iPod Touch":/iPhone/.test(r)?"iPhone":/(watch)(?: ?os[,/]|\d,\d\/)[\d.]+/i.test(r)?sa:Gs.test(r)?Pt:/(kobo)\s(ereader|touch)/i.test(r)?"Kobo":new RegExp(Mi,"i").test(r)?Mi:/(kf[a-z]{2}wi|aeo[c-r]{2})( bui|\))/i.test(r)||/(kf[a-z]+)( bui|\)).+silk\//i.test(r)?"Kindle Fire":/(Android|ZTE)/i.test(r)?new RegExp(be).test(r)&&!/(9138B|TB782B|Nexus [97]|pixel c|HUAWEISHT|BTV|noble nook|smart ultra 6)/i.test(r)||/pixel[\daxl ]{1,6}/i.test(r)&&!/pixel c/i.test(r)||/(huaweimed-al00|tah-|APA|SM-G92|i980|zte|U304AA)/i.test(r)||/lmy47v/i.test(r)&&!/QTAQZ3/i.test(r)?Ue:ta:new RegExp("(pda|"+be+")","i").test(r)?oc:new RegExp(lr,"i").test(r)&&!new RegExp(lr+" pc","i").test(r)?ga:""},hc=r=>r instanceof Error;function gc(r){var e=globalThis._posthogChunkIds;if(e){var t=Object.keys(e);return Dn&&t.length===Oi||(Oi=t.length,Dn=t.reduce((n,s)=>{kr||(kr={});var i=kr[s];if(i)n[i[0]]=i[1];else for(var o=r(s),a=o.length-1;a>=0;a--){var l=o[a],c=l==null?void 0:l.filename,u=e[s];if(c&&u){n[c]=u,kr[s]=[c,u];break}}return n},{})),Dn}}class mc{constructor(e,t,n){n===void 0&&(n=[]),this.coercers=e,this.stackParser=t,this.modifiers=n}buildFromUnknown(e,t){t===void 0&&(t={});var n=t&&t.mechanism||{handled:!0,type:"generic"},s=this.buildCoercingContext(n,t,0).apply(e),i=this.buildParsingContext(t),o=this.parseStacktrace(s,i);return{$exception_list:this.convertToExceptionList(o,n),$exception_level:"error"}}modifyFrames(e){var t=this;return Ne(function*(){for(var n of e)n.stacktrace&&n.stacktrace.frames&&L(n.stacktrace.frames)&&(n.stacktrace.frames=yield t.applyModifiers(n.stacktrace.frames));return e})()}coerceFallback(e){var t;return{type:"Error",value:"Unknown error",stack:(t=e.syntheticException)==null?void 0:t.stack,synthetic:!0}}parseStacktrace(e,t){var n,s;return e.cause!=null&&(n=this.parseStacktrace(e.cause,t)),e.stack!=""&&e.stack!=null&&(s=this.applyChunkIds(this.stackParser(e.stack,e.synthetic?t.skipFirstLines:0),t.chunkIdMap)),S({},e,{cause:n,stack:s})}applyChunkIds(e,t){return e.map(n=>(n.filename&&t&&(n.chunk_id=t[n.filename]),n))}applyCoercers(e,t){for(var n of this.coercers)if(n.match(e))return n.coerce(e,t);return this.coerceFallback(t)}applyModifiers(e){var t=this;return Ne(function*(){var n=e;for(var s of t.modifiers)n=yield s(n);return n})()}convertToExceptionList(e,t){var n,s,i,o={type:e.type,value:e.value,mechanism:{type:(n=t.type)!==null&&n!==void 0?n:"generic",handled:(s=t.handled)===null||s===void 0||s,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,S({},t,{handled:!0}))),a}buildParsingContext(e){var t;return{chunkIdMap:gc(this.stackParser),skipFirstLines:(t=e.skipFirstLines)!==null&&t!==void 0?t:1}}buildCoercingContext(e,t,n){n===void 0&&(n=0);var s=(i,o)=>{if(o<=4){var a=this.buildCoercingContext(e,t,o);return this.applyCoercers(i,a)}};return S({},t,{syntheticException:n==0?t.syntheticException:void 0,mechanism:e,apply:i=>s(i,n),next:i=>s(i,n+1)})}}var Ft="?";function us(r,e,t,n,s){var i={platform:r,filename:e,function:t===""?Ft:t,in_app:!0};return b(n)||(i.lineno=n),b(s)||(i.colno=s),i}var _a=(r,e)=>{var t=r.indexOf("safari-extension")!==-1,n=r.indexOf("safari-web-extension")!==-1;return t||n?[r.indexOf("@")!==-1?r.split("@")[0]:Ft,t?"safari-extension:"+e:"safari-web-extension:"+e]:[r,e]},_c=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,vc=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,yc=/\((\S*)(?::(\d+))(?::(\d+))\)/,wc=(r,e)=>{var t=_c.exec(r);if(t){var[,n,s,i]=t;return us(e,n,Ft,+s,+i)}var o=vc.exec(r);if(o){if(o[2]&&o[2].indexOf("eval")===0){var a=yc.exec(o[2]);a&&(o[2]=a[1],o[3]=a[2],o[4]=a[3])}var[l,c]=_a(o[1]||Ft,o[2]);return us(e,c,l,o[3]?+o[3]:void 0,o[4]?+o[4]:void 0)}},bc=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,Ec=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,Sc=(r,e)=>{var t=bc.exec(r);if(t){if(t[3]&&t[3].indexOf(" > eval")>-1){var n=Ec.exec(t[3]);n&&(t[1]=t[1]||"eval",t[3]=n[1],t[4]=n[2],t[5]="")}var s=t[3],i=t[1]||Ft;return[i,s]=_a(i,s),us(e,s,i,t[4]?+t[4]:void 0,t[5]?+t[5]:void 0)}},Di=/\(error: (.*)\)/,Bi=50;function Ic(){return function(r){for(var e=arguments.length,t=new Array(e>1?e-1:0),n=1;n1024)){var u=Di.test(c)?c.replace(Di,"$1"):c;if(!u.match(/\S*Error: /)){for(var d of t){var p=d(u,r);if(p){o.push(p);break}}if(o.length>=Bi)break}}}return function(h){if(!h.length)return[];var m=Array.from(h);return m.reverse(),m.slice(0,Bi).map(_=>{return S({},_,{filename:_.filename||(v=m,v[v.length-1]||{}).filename,function:_.function||Ft});var v})}(o)}}("web:javascript",wc,Sc)}class kc{match(e){return this.isDOMException(e)||this.isDOMError(e)}coerce(e,t){var n=K(e.stack);return{type:this.getType(e),value:this.getValue(e),stack:n?e.stack:void 0,cause:e.cause?t.next(e.cause):void 0,synthetic:!1}}getType(e){return this.isDOMError(e)?"DOMError":"DOMException"}getValue(e){var t=e.name||(this.isDOMError(e)?"DOMError":"DOMException");return e.message?t+": "+e.message:t}isDOMException(e){return jr(e,"DOMException")}isDOMError(e){return jr(e,"DOMError")}}class Cc{match(e){return(t=>t instanceof Error)(e)}coerce(e,t){return{type:this.getType(e),value:this.getMessage(e,t),stack:this.getStack(e),cause:e.cause?t.next(e.cause):void 0,synthetic:!1}}getType(e){return e.name||e.constructor.name}getMessage(e,t){var n=e.message;return n.error&&typeof n.error.message=="string"?String(n.error.message):String(n)}getStack(e){return e.stacktrace||e.stack||void 0}}class xc{constructor(){}match(e){return jr(e,"ErrorEvent")&&e.error!=null}coerce(e,t){var n,s=t.apply(e.error);return s||{type:"ErrorEvent",value:e.message,stack:(n=t.syntheticException)==null?void 0:n.stack,synthetic:!0}}}var Tc=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;class Rc{match(e){return typeof e=="string"}coerce(e,t){var n,[s,i]=this.getInfos(e);return{type:s??"Error",value:i??e,stack:(n=t.syntheticException)==null?void 0:n.stack,synthetic:!0}}getInfos(e){var t="Error",n=e,s=e.match(Tc);return s&&(t=s[1],n=s[2]),[t,n]}}var Ac=["fatal","error","warning","log","info","debug"];function va(r,e){e===void 0&&(e=40);var t=Object.keys(r);if(t.sort(),!t.length)return"[object has no keys]";for(var n=t.length;n>0;n--){var s=t.slice(0,n).join(", ");if(!(s.length>e))return n===t.length||s.length<=e?s:s.slice(0,e)+"..."}return""}class Pc{match(e){return typeof e=="object"&&e!==null}coerce(e,t){var n,s=this.getErrorPropertyFromObject(e);return s?t.apply(s):{type:this.getType(e),value:this.getValue(e),stack:(n=t.syntheticException)==null?void 0:n.stack,level:this.isSeverityLevel(e.level)?e.level:"error",synthetic:!0}}getType(e){return ea(e)?e.constructor.name:"Error"}getValue(e){if("name"in e&&typeof e.name=="string"){var t="'"+e.name+"' captured as exception";return"message"in e&&typeof e.message=="string"&&(t+=" with message: '"+e.message+"'"),t}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: "+va(e)}isSeverityLevel(e){return K(e)&&!is(e)&&Ac.indexOf(e)>=0}getErrorPropertyFromObject(e){for(var t in e)if(Object.prototype.hasOwnProperty.call(e,t)){var n=e[t];if(hc(n))return n}}getObjectClassName(e){try{var t=Object.getPrototypeOf(e);return t?t.constructor.name:void 0}catch{return}}}class Fc{match(e){return ea(e)}coerce(e,t){var n,s=e.constructor.name;return{type:s,value:s+" captured as exception with keys: "+va(e),stack:(n=t.syntheticException)==null?void 0:n.stack,synthetic:!0}}}class $c{match(e){return os(e)}coerce(e,t){var n;return{type:"Error",value:"Primitive value captured as exception: "+String(e),stack:(n=t.syntheticException)==null?void 0:n.stack,synthetic:!0}}}class Mc{match(e){return jr(e,"PromiseRejectionEvent")}coerce(e,t){var n,s=this.getUnhandledRejectionReason(e);return os(s)?{type:"UnhandledRejection",value:"Non-Error promise rejection captured with value: "+String(s),stack:(n=t.syntheticException)==null?void 0:n.stack,synthetic:!0}:t.apply(s)}getUnhandledRejectionReason(e){if(os(e))return e;try{if("reason"in e)return e.reason;if("detail"in e&&"reason"in e.detail)return e.detail.reason}catch{}return e}}var ya=function(r,e){var{debugEnabled:t}=e===void 0?{}:e,n={k:function(s){if(f&&(Le.DEBUG||C.POSTHOG_DEBUG||t)&&!b(f.console)&&f.console){for(var i=("__rrweb_original__"in f.console[s])?f.console[s].__rrweb_original__:f.console[s],o=arguments.length,a=new Array(o>1?o-1:0),l=1;l{n.error("You must initialize PostHog before calling "+s)},createLogger:(s,i)=>ya(r+" "+s,i)};return n},E=ya("[PostHog.js]"),W=E.createLogger,Oc=W("[ExternalScriptsLoader]"),ji=(r,e,t)=>{if(r.config.disable_external_dependency_loading)return Oc.warn(e+" was requested but loading of external scripts is disabled."),t("Loading of external scripts is disabled");var n=y==null?void 0:y.querySelectorAll("script");if(n){for(var s,i=function(){if(n[o].src===e){var l=n[o];return l.__posthog_loading_callback_fired?{v:t()}:(l.addEventListener("load",c=>{l.__posthog_loading_callback_fired=!0,t(void 0,c)}),l.onerror=c=>t(c),{v:void 0})}},o=0;o{if(!y)return t("document not found");var l=y.createElement("script");if(l.type="text/javascript",l.crossOrigin="anonymous",l.src=e,l.onload=d=>{l.__posthog_loading_callback_fired=!0,t(void 0,d)},l.onerror=d=>t(d),r.config.prepare_external_dependency_script&&(l=r.config.prepare_external_dependency_script(l)),!l)return t("prepare_external_dependency_script returned null");if(r.config.external_scripts_inject_target==="head")y.head.appendChild(l);else{var c,u=y.querySelectorAll("body > script");u.length>0?(c=u[0].parentNode)==null||c.insertBefore(l,u[0]):y.body.appendChild(l)}};y!=null&&y.body?a():y==null||y.addEventListener("DOMContentLoaded",a)};C.__PosthogExtensions__=C.__PosthogExtensions__||{},C.__PosthogExtensions__.loadExternalDependency=(r,e,t)=>{var n="/static/"+e+".js?v="+r.version;if(e==="remote-config"&&(n="/array/"+r.config.token+"/config.js"),e==="toolbar"){var s=3e5;n=n+"&t="+Math.floor(Date.now()/s)*s}var i=r.requestRouter.endpointFor("assets",n);ji(r,i,t)},C.__PosthogExtensions__.loadSiteApp=(r,e,t)=>{var n=r.requestRouter.endpointFor("api",e);ji(r,n,t)};var Hr={};function nt(r,e,t){if(L(r)){if(Ri&&r.forEach===Ri)r.forEach(e,t);else if("length"in r&&r.length===+r.length){for(var n=0,s=r.length;n1?e-1:0),n=1;n1?e-1:0),n=1;n0||Ke(t))&&(e[n]=t)}),e};function Nc(r,e){return t=r,n=i=>K(i)&&!Ie(e)?i.slice(0,e):i,s=new Set,function i(o,a){return o!==Object(o)?n?n(o,a):o:s.has(o)?void 0:(s.add(o),L(o)?(l=[],nt(o,c=>{l.push(i(c))})):(l={},j(o,(c,u)=>{s.has(c)||(l[u]=i(c,u))})),l);var l}(t);var t,n,s}var Dc=["herokuapp.com","vercel.app","netlify.app"];function Bc(r){var e=r==null?void 0:r.hostname;if(!K(e))return!1;var t=e.split(".").slice(-2).join(".");for(var n of Dc)if(t===n)return!1;return!0}function wa(r,e){for(var t=0;te.match(t)))}function Kr(r){var e="";switch(typeof r.className){case"string":e=r.className;break;case"object":e=(r.className&&"baseVal"in r.className?r.className.baseVal:null)||r.getAttribute("class")||"";break;default:e=""}return Ks(e)}function Ta(r){return $(r)?null:mn(r).split(/(\s+)/).filter(e=>pr(e)).join("").replace(/[\r\n]/g," ").replace(/[ ]+/g," ").substring(0,255)}function br(r){var e="";return ws(r)&&!$a(r)&&r.childNodes&&r.childNodes.length&&j(r.childNodes,function(t){var n;Ca(t)&&t.textContent&&(e+=(n=Ta(t.textContent))!==null&&n!==void 0?n:"")}),mn(e)}function Ra(r){return b(r.target)?r.srcElement||null:(e=r.target)!=null&&e.shadowRoot?r.composedPath()[0]||null:r.target||null;var e}var Vs=["a","button","form","input","select","textarea","label"];function Aa(r,e){if(b(e))return!0;var t,n=function(i){if(e.some(o=>i.matches(o)))return{v:!0}};for(var s of r)if(t=n(s))return t.v;return!1}function Pa(r){var e=r.parentNode;return!(!e||!vn(e))&&e}var Uc=["next","previous","prev",">","<"],Ji=10,Zi=[".ph-no-rageclick",".ph-no-capture"];function Hc(r,e){if(!f||Ys(r))return!1;var t,n,s;if(We(e)?(t=!!e&&Zi,n=void 0):(t=(s=e==null?void 0:e.css_selector_ignorelist)!==null&&s!==void 0?s:Zi,n=e==null?void 0:e.content_ignorelist),t===!1)return!1;var{targetElementList:i}=Fa(r,!1);return!function(o,a){if(o===!1||b(o))return!1;var l;if(o===!0)l=Uc;else{if(!L(o))return!1;if(o.length>Ji)return E.error("[PostHog] content_ignorelist array cannot exceed "+Ji+" items. Use css_selector_ignorelist for more complex matching."),!1;l=o.map(c=>c.toLowerCase())}return a.some(c=>{var{safeText:u,ariaLabel:d}=c;return l.some(p=>u.includes(p)||d.includes(p))})}(n,i.map(o=>{var a;return{safeText:br(o).toLowerCase(),ariaLabel:((a=o.getAttribute("aria-label"))==null?void 0:a.toLowerCase().trim())||""}}))&&!Aa(i,t)}var Ys=r=>!r||st(r,"html")||!vn(r),Fa=(r,e)=>{if(!f||Ys(r))return{parentIsUsefulElement:!1,targetElementList:[]};for(var t=!1,n=[r],s=r;s.parentNode&&!st(s,"body");)if(xa(s.parentNode))n.push(s.parentNode.host),s=s.parentNode.host;else{var i=Pa(s);if(!i)break;if(e||Vs.indexOf(i.tagName.toLowerCase())>-1)t=!0;else{var o=f.getComputedStyle(i);o&&o.getPropertyValue("cursor")==="pointer"&&(t=!0)}n.push(i),s=i}return{parentIsUsefulElement:t,targetElementList:n}};function Wc(r,e,t,n,s){var i,o,a,l;if(t===void 0&&(t=void 0),!f||Ys(r)||(i=t)!=null&&i.url_allowlist&&!Yi(t.url_allowlist)||(o=t)!=null&&o.url_ignorelist&&Yi(t.url_ignorelist))return!1;if((a=t)!=null&&a.dom_event_allowlist){var c=t.dom_event_allowlist;if(c&&!c.some(m=>e.type===m))return!1}var{parentIsUsefulElement:u,targetElementList:d}=Fa(r,n);if(!function(m,_){var v=_==null?void 0:_.element_allowlist;if(b(v))return!0;var k,I=function(T){if(v.some(w=>T.tagName.toLowerCase()===w))return{v:!0}};for(var R of m)if(k=I(R))return k.v;return!1}(d,t)||!Aa(d,(l=t)==null?void 0:l.css_selector_allowlist))return!1;var p=f.getComputedStyle(r);if(p&&p.getPropertyValue("cursor")==="pointer"&&e.type==="click")return!0;var h=r.tagName.toLowerCase();switch(h){case"html":return!1;case"form":return(s||["submit"]).indexOf(e.type)>=0;case"input":case"select":case"textarea":return(s||["change","click"]).indexOf(e.type)>=0;default:return u?(s||["click"]).indexOf(e.type)>=0:(s||["click"]).indexOf(e.type)>=0&&(Vs.indexOf(h)>-1||r.getAttribute("contenteditable")==="true")}}function ws(r){for(var e=r;e.parentNode&&!st(e,"body");e=e.parentNode){var t=Kr(e);if(F(t,"ph-sensitive")||F(t,"ph-no-capture"))return!1}if(F(Kr(r),"ph-include"))return!0;var n=r.type||"";if(K(n))switch(n.toLowerCase()){case"hidden":case"password":return!1}var s=r.name||r.id||"";return!(K(s)&&/^cc|cardnum|ccnum|creditcard|csc|cvc|cvv|exp|pass|pwd|routing|seccode|securitycode|securitynum|socialsec|socsec|ssn/i.test(s.replace(/[^a-zA-Z0-9]/g,"")))}function $a(r){return!!(st(r,"input")&&!["button","checkbox","submit","reset"].includes(r.type)||st(r,"select")||st(r,"textarea")||r.getAttribute("contenteditable")==="true")}var Ma="(4[0-9]{12}(?:[0-9]{3})?)|(5[1-5][0-9]{14})|(6(?:011|5[0-9]{2})[0-9]{12})|(3[47][0-9]{13})|(3(?:0[0-5]|[68][0-9])[0-9]{11})|((?:2131|1800|35[0-9]{3})[0-9]{11})",zc=new RegExp("^(?:"+Ma+")$"),Gc=new RegExp(Ma),Oa="\\d{3}-?\\d{2}-?\\d{4}",qc=new RegExp("^("+Oa+")$"),Kc=new RegExp("("+Oa+")");function pr(r,e){return e===void 0&&(e=!0),!($(r)||K(r)&&(r=mn(r),(e?zc:Gc).test((r||"").replace(/[- ]/g,""))||(e?qc:Kc).test(r)))}function La(r){var e=br(r);return pr(e=(e+" "+Na(r)).trim())?e:""}function Na(r){var e="";return r&&r.childNodes&&r.childNodes.length&&j(r.childNodes,function(t){var n;if(t&&((n=t.tagName)==null?void 0:n.toLowerCase())==="span")try{var s=br(t);e=(e+" "+s).trim(),t.childNodes&&t.childNodes.length&&(e=(e+" "+Na(t)).trim())}catch(i){E.error("[AutoCapture]",i)}}),e}function Vc(r){return function(e){var t=e.map(n=>{var s,i,o="";if(n.tag_name&&(o+=n.tag_name),n.attr_class)for(var a of(n.attr_class.sort(),n.attr_class))o+="."+a.replace(/"/g,"");var l=S({},n.text?{text:n.text}:{},{"nth-child":(s=n.nth_child)!==null&&s!==void 0?s:0,"nth-of-type":(i=n.nth_of_type)!==null&&i!==void 0?i:0},n.href?{href:n.href}:{},n.attr_id?{attr_id:n.attr_id}:{},n.attributes),c={};return Fr(l).sort((u,d)=>{var[p]=u,[h]=d;return p.localeCompare(h)}).forEach(u=>{var[d,p]=u;return c[Xi(d.toString())]=Xi(p.toString())}),o+=":",o+=Fr(c).map(u=>{var[d,p]=u;return d+'="'+p+'"'}).join("")});return t.join(";")}(function(e){return e.map(t=>{var n,s,i={text:(n=t.$el_text)==null?void 0:n.slice(0,400),tag_name:t.tag_name,href:(s=t.attr__href)==null?void 0:s.slice(0,2048),attr_class:Yc(t),attr_id:t.attr__id,nth_child:t.nth_child,nth_of_type:t.nth_of_type,attributes:{}};return Fr(t).filter(o=>{var[a]=o;return a.indexOf("attr__")===0}).forEach(o=>{var[a,l]=o;return i.attributes[a]=l}),i})}(r))}function Xi(r){return r.replace(/"|\\"/g,'\\"')}function Yc(r){var e=r.attr__class;return e?L(e)?e:Ks(e):void 0}class Da{constructor(e){this.disabled=e===!1;var t=J(e)?e:{};this.thresholdPx=t.threshold_px||30,this.timeoutMs=t.timeout_ms||1e3,this.clickCount=t.click_count||3,this.clicks=[]}isRageClick(e,t,n){if(this.disabled)return!1;var s=this.clicks[this.clicks.length-1];if(s&&Math.abs(e-s.x)+Math.abs(t-s.y){var e=y==null?void 0:y.createElement("a");return b(e)?null:(e.href=r,e)},Jc=function(r,e){var t,n;e===void 0&&(e="&");var s=[];return j(r,function(i,o){b(i)||b(o)||o==="undefined"||(t=encodeURIComponent((a=>a instanceof File)(i)?i.name:i.toString()),n=encodeURIComponent(o),s[s.length]=n+"="+t)}),s.join(e)},Yr=function(r,e){for(var t,n=((r.split("#")[0]||"").split(/\?(.*)/)[1]||"").replace(/^\?+/g,"").split("&"),s=0;sr?e.slice(0,r)+"...":e}function Zc(r){if(r.previousElementSibling)return r.previousElementSibling;var e=r;do e=e.previousSibling;while(e&&!vn(e));return e}function Xc(r,e,t,n){var s=r.tagName.toLowerCase(),i={tag_name:s};Vs.indexOf(s)>-1&&!t&&(s.toLowerCase()==="a"||s.toLowerCase()==="button"?i.$el_text=jn(1024,La(r)):i.$el_text=jn(1024,br(r)));var o=Kr(r);o.length>0&&(i.classes=o.filter(function(u){return u!==""})),j(r.attributes,function(u){var d;if((!$a(r)||["name","id","class","aria-label"].indexOf(u.name)!==-1)&&(n==null||!n.includes(u.name))&&!e&&pr(u.value)&&(d=u.name,!K(d)||d.substring(0,10)!=="_ngcontent"&&d.substring(0,7)!=="_nghost")){var p=u.value;u.name==="class"&&(p=Ks(p).join(" ")),i["attr__"+u.name]=jn(1024,p)}});for(var a=1,l=1,c=r;c=Zc(c);)a++,c.tagName===r.tagName&&l++;return i.nth_child=a,i.nth_of_type=l,i}function Qc(r,e){for(var t,n,{e:s,maskAllElementAttributes:i,maskAllText:o,elementAttributeIgnoreList:a,elementsChainAsString:l}=e,c=[r],u=r;u.parentNode&&!st(u,"body");)xa(u.parentNode)?(c.push(u.parentNode.host),u=u.parentNode.host):(c.push(u.parentNode),u=u.parentNode);var d,p=[],h={},m=!1,_=!1;if(j(c,T=>{var w=ws(T);T.tagName.toLowerCase()==="a"&&(m=T.getAttribute("href"),m=w&&m&&pr(m)&&m),F(Kr(T),"ph-no-capture")&&(_=!0),p.push(Xc(T,i,o,a));var P=function(A){if(!ws(A))return{};var x={};return j(A.attributes,function(re){if(re.name&&re.name.indexOf("data-ph-capture-attribute")===0){var Y=re.name.replace("data-ph-capture-attribute-",""),se=re.value;Y&&se&&pr(se)&&(x[Y]=se)}}),x}(T);z(h,P)}),_)return{props:{},explicitNoCapture:_};if(o||(r.tagName.toLowerCase()==="a"||r.tagName.toLowerCase()==="button"?p[0].$el_text=La(r):p[0].$el_text=br(r)),m){var v,k;p[0].attr__href=m;var I=(v=Vr(m))==null?void 0:v.host,R=f==null||(k=f.location)==null?void 0:k.host;I&&R&&I!==R&&(d=m)}return{props:z({$event_type:s.type,$ce_version:1},l?{}:{$elements:p},{$elements_chain:Vc(p)},(t=p[0])!=null&&t.$el_text?{$el_text:(n=p[0])==null?void 0:n.$el_text}:{},d&&s.type==="click"?{$external_click_url:d}:{},h)}}class eu{constructor(e){this.P=!1,this.T=null,this.I=!1,this.instance=e,this.rageclicks=new Da(e.config.rageclick),this.C=null}get R(){var e,t,n=J(this.instance.config.autocapture)?this.instance.config.autocapture:{};return n.url_allowlist=(e=n.url_allowlist)==null?void 0:e.map(s=>new RegExp(s)),n.url_ignorelist=(t=n.url_ignorelist)==null?void 0:t.map(s=>new RegExp(s)),n}F(){if(this.isBrowserSupported()){if(f&&y){var e=n=>{n=n||(f==null?void 0:f.event);try{this.O(n)}catch(s){Qi.error("Failed to capture event",s)}};if(V(y,"submit",e,{capture:!0}),V(y,"change",e,{capture:!0}),V(y,"click",e,{capture:!0}),this.R.capture_copied_text){var t=n=>{n=n||(f==null?void 0:f.event),this.O(n,Bn)};V(y,"copy",t,{capture:!0}),V(y,"cut",t,{capture:!0})}}}else Qi.info("Disabling Automatic Event Collection because this browser is not supported")}startIfEnabled(){this.isEnabled&&!this.P&&(this.F(),this.P=!0)}onRemoteConfig(e){e.elementsChainAsString&&(this.I=e.elementsChainAsString),this.instance.persistence&&this.instance.persistence.register({[Hi]:!!e.autocapture_opt_out}),this.T=!!e.autocapture_opt_out,this.startIfEnabled()}setElementSelectors(e){this.C=e}getElementSelectors(e){var t,n=[];return(t=this.C)==null||t.forEach(s=>{var i=y==null?void 0:y.querySelectorAll(s);i==null||i.forEach(o=>{e===o&&n.push(s)})}),n}get isEnabled(){var e,t,n=(e=this.instance.persistence)==null?void 0:e.props[Hi],s=this.T;if(Ie(s)&&!We(n)&&!this.instance.M())return!1;var i=(t=this.T)!==null&&t!==void 0?t:!!n;return!!this.instance.config.autocapture&&!i}O(e,t){if(t===void 0&&(t="$autocapture"),this.isEnabled){var n,s=Ra(e);Ca(s)&&(s=s.parentNode||null),t==="$autocapture"&&e.type==="click"&&e instanceof MouseEvent&&this.instance.config.rageclick&&(n=this.rageclicks)!=null&&n.isRageClick(e.clientX,e.clientY,e.timeStamp||new Date().getTime())&&Hc(s,this.instance.config.rageclick)&&this.O(e,"$rageclick");var i=t===Bn;if(s&&Wc(s,e,this.R,i,i?["copy","cut"]:void 0)){var{props:o,explicitNoCapture:a}=Qc(s,{e,maskAllElementAttributes:this.instance.config.mask_all_element_attributes,maskAllText:this.instance.config.mask_all_text,elementAttributeIgnoreList:this.R.element_attribute_ignorelist,elementsChainAsString:this.I});if(a)return!1;var l=this.getElementSelectors(s);if(l&&l.length>0&&(o.$element_selectors=l),t===Bn){var c,u=Ta(f==null||(c=f.getSelection())==null?void 0:c.toString()),d=e.type||"clipboard";if(!u)return!1;o.$selected_content=u,o.$copy_type=d}return this.instance.capture(t,o),!0}}}isBrowserSupported(){return je(y==null?void 0:y.querySelectorAll)}}Math.trunc||(Math.trunc=function(r){return r<0?Math.ceil(r):Math.floor(r)}),Number.isInteger||(Number.isInteger=function(r){return Ke(r)&&isFinite(r)&&Math.floor(r)===r});var eo="0123456789abcdef";class Zr{constructor(e){if(this.bytes=e,e.length!==16)throw new TypeError("not 128-bit length")}static fromFieldsV7(e,t,n,s){if(!Number.isInteger(e)||!Number.isInteger(t)||!Number.isInteger(n)||!Number.isInteger(s)||e<0||t<0||n<0||s<0||e>0xffffffffffff||t>4095||n>1073741823||s>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/Math.pow(2,8),i[5]=e,i[6]=112|t>>>8,i[7]=t,i[8]=128|n>>>24,i[9]=n>>>16,i[10]=n>>>8,i[11]=n,i[12]=s>>>24,i[13]=s>>>16,i[14]=s>>>8,i[15]=s,new Zr(i)}toString(){for(var e="",t=0;t>>4)+eo.charAt(15&this.bytes[t]),t!==3&&t!==5&&t!==7&&t!==9||(e+="-");if(e.length!==36)throw new Error("Invalid UUIDv7 was generated");return e}clone(){return new Zr(this.bytes.slice(0))}equals(e){return this.compareTo(e)===0}compareTo(e){for(var t=0;t<16;t++){var n=this.bytes[t]-e.bytes[t];if(n!==0)return Math.sign(n)}return 0}}class tu{constructor(){this.A=0,this.j=0,this.D=new ru}generate(){var e=this.generateOrAbort();if(b(e)){this.A=0;var t=this.generateOrAbort();if(b(t))throw new Error("Could not generate UUID after timestamp reset");return t}return e}generateOrAbort(){var e=Date.now();if(e>this.A)this.A=e,this.L();else{if(!(e+1e4>this.A))return;this.j++,this.j>4398046511103&&(this.A++,this.L())}return Zr.fromFieldsV7(this.A,Math.trunc(this.j/Math.pow(2,30)),this.j&Math.pow(2,30)-1,this.D.nextUint32())}L(){this.j=1024*this.D.nextUint32()+(1023&this.D.nextUint32())}}var to,Ba=r=>{if(typeof UUIDV7_DENY_WEAK_RNG<"u"&&UUIDV7_DENY_WEAK_RNG)throw new Error("no cryptographically strong RNG available");for(var e=0;ecrypto.getRandomValues(r));class ru{constructor(){this.N=new Uint32Array(8),this.U=1/0}nextUint32(){return this.U>=this.N.length&&(Ba(this.N),this.U=0),this.N[this.U++]}}var rt=()=>nu().toString(),nu=()=>(to||(to=new tu)).generate(),Wt="",su=/[a-z0-9][a-z0-9-]+\.[a-z]{2,}$/i;function iu(r,e){if(e){var t=function(s,i){if(i===void 0&&(i=y),Wt)return Wt;if(!i||["localhost","127.0.0.1"].includes(s))return"";for(var o=s.split("."),a=Math.min(o.length,8),l="dmn_chk_"+rt();!Wt&&a--;){var c=o.slice(a).join("."),u=l+"=1;domain=."+c+";path=/";i.cookie=u+";max-age=3",i.cookie.includes(l)&&(i.cookie=u+";max-age=0",Wt=c)}return Wt}(r);if(!t){var n=(s=>{var i=s.match(su);return i?i[0]:""})(r);n!==t&&E.info("Warning: cookie subdomain discovery mismatch",n,t),t=n}return t?"; domain=."+t:""}return""}var Re={H:()=>!!y,B:function(r){E.error("cookieStore error: "+r)},q:function(r){if(y){try{for(var e=r+"=",t=y.cookie.split(";").filter(i=>i.length),n=0;n3686.4&&E.warn("cookieStore warning: large cookie, len="+c.length),y.cookie=c,c}catch{return}},V:function(r,e){if(y!=null&&y.cookie)try{Re.G(r,"",-1,e)}catch{return}}},Un=null,H={H:function(){if(!Ie(Un))return Un;var r=!0;if(b(f))r=!1;else try{var e="__mplssupport__";H.G(e,"xyz"),H.q(e)!=='"xyz"'&&(r=!1),H.V(e)}catch{r=!1}return r||E.error("localStorage unsupported; falling back to cookie store"),Un=r,r},B:function(r){E.error("localStorage error: "+r)},q:function(r){try{return f==null?void 0:f.localStorage.getItem(r)}catch(e){H.B(e)}return null},W:function(r){try{return JSON.parse(H.q(r))||{}}catch{}return null},G:function(r,e){try{f==null||f.localStorage.setItem(r,JSON.stringify(e))}catch(t){H.B(t)}},V:function(r){try{f==null||f.localStorage.removeItem(r)}catch(e){H.B(e)}}},ou=["$device_id","distinct_id",Wr,Ia,qr,Gr,Te],xr={},au={H:function(){return!0},B:function(r){E.error("memoryStorage error: "+r)},q:function(r){return xr[r]||null},W:function(r){return xr[r]||null},G:function(r,e){xr[r]=e},V:function(r){delete xr[r]}},lt=null,X={H:function(){if(!Ie(lt))return lt;if(lt=!0,b(f))lt=!1;else try{var r="__support__";X.G(r,"xyz"),X.q(r)!=='"xyz"'&&(lt=!1),X.V(r)}catch{lt=!1}return lt},B:function(r){E.error("sessionStorage error: ",r)},q:function(r){try{return f==null?void 0:f.sessionStorage.getItem(r)}catch(e){X.B(e)}return null},W:function(r){try{return JSON.parse(X.q(r))||null}catch{}return null},G:function(r,e){try{f==null||f.sessionStorage.setItem(r,JSON.stringify(e))}catch(t){X.B(t)}},V:function(r){try{f==null||f.sessionStorage.removeItem(r)}catch(e){X.B(e)}}},De=function(r){return r[r.PENDING=-1]="PENDING",r[r.DENIED=0]="DENIED",r[r.GRANTED=1]="GRANTED",r}({});class lu{constructor(e){this._instance=e}get R(){return this._instance.config}get consent(){return this.J()?De.DENIED:this.K}isOptedOut(){return this.R.cookieless_mode==="always"||this.consent===De.DENIED||this.consent===De.PENDING&&(this.R.opt_out_capturing_by_default||this.R.cookieless_mode==="on_reject")}isOptedIn(){return!this.isOptedOut()}isExplicitlyOptedOut(){return this.consent===De.DENIED}optInOut(e){this.Y.G(this.X,e?1:0,this.R.cookie_expiration,this.R.cross_subdomain_cookie,this.R.secure_cookie)}reset(){this.Y.V(this.X,this.R.cross_subdomain_cookie)}get X(){var{token:e,opt_out_capturing_cookie_prefix:t,consent_persistence_name:n}=this._instance.config;return n||(t?t+e:"__ph_opt_in_out_"+e)}get K(){var e=this.Y.q(this.X);return Ln(e)?De.GRANTED:F(rc,e)?De.DENIED:De.PENDING}get Y(){if(!this.Z){var e=this.R.opt_out_capturing_persistence_type;this.Z=e==="localStorage"?H:Re;var t=e==="localStorage"?Re:H;t.q(this.X)&&(this.Z.q(this.X)||this.optInOut(Ln(t.q(this.X))),t.V(this.X,this.R.cross_subdomain_cookie))}return this.Z}J(){return!!this.R.respect_dnt&&!!wa([fe==null?void 0:fe.doNotTrack,fe==null?void 0:fe.msDoNotTrack,C.doNotTrack],e=>Ln(e))}}var Tr=W("[Dead Clicks]"),cu=()=>!0,uu=r=>{var e,t=!((e=r.instance.persistence)==null||!e.get_property(Sa)),n=r.instance.config.capture_dead_clicks;return We(n)?n:!!J(n)||t};class ja{get lazyLoadedDeadClicksAutocapture(){return this.tt}constructor(e,t,n){this.instance=e,this.isEnabled=t,this.onCapture=n,this.startIfEnabledOrStop()}onRemoteConfig(e){"captureDeadClicks"in e&&(this.instance.persistence&&this.instance.persistence.register({[Sa]:e.captureDeadClicks}),this.startIfEnabledOrStop())}startIfEnabledOrStop(){this.isEnabled(this)?this.it(()=>{this.et()}):this.stop()}it(e){var t,n;(t=C.__PosthogExtensions__)!=null&&t.initDeadClicksAutocapture&&e(),(n=C.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this.instance,"dead-clicks-autocapture",s=>{s?Tr.error("failed to load script",s):e()})}et(){var e;if(y){if(!this.tt&&(e=C.__PosthogExtensions__)!=null&&e.initDeadClicksAutocapture){var t=J(this.instance.config.capture_dead_clicks)?this.instance.config.capture_dead_clicks:{};t.__onCapture=this.onCapture,this.tt=C.__PosthogExtensions__.initDeadClicksAutocapture(this.instance,t),this.tt.start(y),Tr.info("starting...")}}else Tr.error("`document` not found. Cannot start.")}stop(){this.tt&&(this.tt.stop(),this.tt=void 0,Tr.info("stopping..."))}}var zt=W("[ExceptionAutocapture]");class du{constructor(e){var t,n,s;this.rt=()=>{var i;if(f&&this.isEnabled&&(i=C.__PosthogExtensions__)!=null&&i.errorWrappingFunctions){var o=C.__PosthogExtensions__.errorWrappingFunctions.wrapOnError,a=C.__PosthogExtensions__.errorWrappingFunctions.wrapUnhandledRejection,l=C.__PosthogExtensions__.errorWrappingFunctions.wrapConsoleError;try{!this.st&&this.R.capture_unhandled_errors&&(this.st=o(this.captureException.bind(this))),!this.nt&&this.R.capture_unhandled_rejections&&(this.nt=a(this.captureException.bind(this))),!this.ot&&this.R.capture_console_errors&&(this.ot=l(this.captureException.bind(this)))}catch(c){zt.error("failed to start",c),this.ut()}}},this._instance=e,this.ht=!((t=this._instance.persistence)==null||!t.props[Wi]),this.dt=new nc({refillRate:(n=this._instance.config.error_tracking.__exceptionRateLimiterRefillRate)!==null&&n!==void 0?n:1,bucketSize:(s=this._instance.config.error_tracking.__exceptionRateLimiterBucketSize)!==null&&s!==void 0?s:10,refillInterval:1e4,h:zt}),this.R=this.vt(),this.startIfEnabledOrStop()}vt(){var e=this._instance.config.capture_exceptions,t={capture_unhandled_errors:!1,capture_unhandled_rejections:!1,capture_console_errors:!1};return J(e)?t=S({},t,e):(b(e)?this.ht:e)&&(t=S({},t,{capture_unhandled_errors:!0,capture_unhandled_rejections:!0})),t}get isEnabled(){return this.R.capture_console_errors||this.R.capture_unhandled_errors||this.R.capture_unhandled_rejections}startIfEnabledOrStop(){this.isEnabled?(zt.info("enabled"),this.ut(),this.it(this.rt)):this.ut()}it(e){var t,n;(t=C.__PosthogExtensions__)!=null&&t.errorWrappingFunctions&&e(),(n=C.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,"exception-autocapture",s=>{if(s)return zt.error("failed to load script",s);e()})}ut(){var e,t,n;(e=this.st)==null||e.call(this),this.st=void 0,(t=this.nt)==null||t.call(this),this.nt=void 0,(n=this.ot)==null||n.call(this),this.ot=void 0}onRemoteConfig(e){if("autocaptureExceptions"in e){var t=e.autocaptureExceptions;this.ht=!!t||!1,this._instance.persistence&&this._instance.persistence.register({[Wi]:this.ht}),this.R=this.vt(),this.startIfEnabledOrStop()}}onConfigChange(){this.R=this.vt()}captureException(e){var t,n,s=(t=e==null||(n=e.$exception_list)==null||(n=n[0])==null?void 0:n.type)!==null&&t!==void 0?t:"Exception";this.dt.consumeRateLimit(s)?zt.info("Skipping exception capture because of client rate limiting.",{exception:s}):this._instance.exceptions.sendExceptionEvent(e)}}function ro(r,e,t){try{if(!(e in r))return()=>{};var n=r[e],s=t(n);return je(s)&&(s.prototype=s.prototype||{},Object.defineProperties(s,{__posthog_wrapped__:{enumerable:!1,value:!0}})),r[e]=s,()=>{r[e]=n}}catch{return()=>{}}}class pu{constructor(e){var t;this._instance=e,this.ct=(f==null||(t=f.location)==null?void 0:t.pathname)||""}get isEnabled(){return this._instance.config.capture_pageview==="history_change"}startIfEnabled(){this.isEnabled&&(E.info("History API monitoring enabled, starting..."),this.monitorHistoryChanges())}stop(){this.ft&&this.ft(),this.ft=void 0,E.info("History API monitoring stopped")}monitorHistoryChanges(){var e,t;if(f&&f.history){var n=this;(e=f.history.pushState)!=null&&e.__posthog_wrapped__||ro(f.history,"pushState",s=>function(i,o,a){s.call(this,i,o,a),n._t("pushState")}),(t=f.history.replaceState)!=null&&t.__posthog_wrapped__||ro(f.history,"replaceState",s=>function(i,o,a){s.call(this,i,o,a),n._t("replaceState")}),this.bt()}}_t(e){try{var t,n=f==null||(t=f.location)==null?void 0:t.pathname;if(!n)return;n!==this.ct&&this.isEnabled&&this._instance.capture("$pageview",{navigation_type:e}),this.ct=n}catch(s){E.error("Error capturing "+e+" pageview",s)}}bt(){if(!this.ft){var e=()=>{this._t("popstate")};V(f,"popstate",e),this.ft=()=>{f&&f.removeEventListener("popstate",e)}}}}var Hn=W("[SegmentIntegration]");function fu(r,e){var t=r.config.segment;if(!t)return e();(function(n,s){var i=n.config.segment;if(!i)return s();var o=l=>{var c=()=>l.anonymousId()||rt();n.config.get_device_id=c,l.id()&&(n.register({distinct_id:l.id(),$device_id:c()}),n.persistence.set_property(Te,"identified")),s()},a=i.user();"then"in a&&je(a.then)?a.then(o):o(a)})(r,()=>{t.register((n=>{Promise&&Promise.resolve||Hn.warn("This browser does not have Promise support, and can not use the segment integration");var s=(i,o)=>{if(!o)return i;i.event.userId||i.event.anonymousId===n.get_distinct_id()||(Hn.info("No userId set, resetting PostHog"),n.reset()),i.event.userId&&i.event.userId!==n.get_distinct_id()&&(Hn.info("UserId set, identifying with PostHog"),n.identify(i.event.userId));var a=n.calculateEventProperties(o,i.event.properties);return i.event.properties=Object.assign({},a,i.event.properties),i};return{name:"PostHog JS",type:"enrichment",version:"1.0.0",isLoaded:()=>!0,load:()=>Promise.resolve(),track:i=>s(i,i.event.event),page:i=>s(i,"$pageview"),identify:i=>s(i,"$identify"),screen:i=>s(i,"$screen")}})(r)).then(()=>{e()})})}var Ua="posthog-js";function Ha(r,e){var{organization:t,projectId:n,prefix:s,severityAllowList:i=["error"],sendExceptionsToPostHog:o=!0}=e===void 0?{}:e;return a=>{var l,c,u,d,p;if(!(i==="*"||i.includes(a.level))||!r.__loaded)return a;a.tags||(a.tags={});var h=r.requestRouter.endpointFor("ui","/project/"+r.config.token+"/person/"+r.get_distinct_id());a.tags["PostHog Person URL"]=h,r.sessionRecordingStarted()&&(a.tags["PostHog Recording URL"]=r.get_session_replay_url({withTimestamp:!0}));var m=((l=a.exception)==null?void 0:l.values)||[],_=m.map(k=>S({},k,{stacktrace:k.stacktrace?S({},k.stacktrace,{type:"raw",frames:(k.stacktrace.frames||[]).map(I=>S({},I,{platform:"web:javascript"}))}):void 0})),v={$exception_message:((c=m[0])==null?void 0:c.value)||a.message,$exception_type:(u=m[0])==null?void 0:u.type,$exception_level:a.level,$exception_list:_,$sentry_event_id:a.event_id,$sentry_exception:a.exception,$sentry_exception_message:((d=m[0])==null?void 0:d.value)||a.message,$sentry_exception_type:(p=m[0])==null?void 0:p.type,$sentry_tags:a.tags};return t&&n&&(v.$sentry_url=(s||"https://sentry.io/organizations/")+t+"/issues/?project="+n+"&query="+a.event_id),o&&r.exceptions.sendExceptionEvent(v),a}}class hu{constructor(e,t,n,s,i,o){this.name=Ua,this.setupOnce=function(a){a(Ha(e,{organization:t,projectId:n,prefix:s,severityAllowList:i,sendExceptionsToPostHog:o==null||o}))}}}var gu=f!=null&&f.location?Jr(f.location.hash,"__posthog")||Jr(location.hash,"state"):null,no="_postHogToolbarParams",so=W("[Toolbar]"),et=function(r){return r[r.UNINITIALIZED=0]="UNINITIALIZED",r[r.LOADING=1]="LOADING",r[r.LOADED=2]="LOADED",r}(et||{});class mu{constructor(e){this.instance=e}yt(e){C.ph_toolbar_state=e}wt(){var e;return(e=C.ph_toolbar_state)!==null&&e!==void 0?e:et.UNINITIALIZED}maybeLoadToolbar(e,t,n){if(e===void 0&&(e=void 0),t===void 0&&(t=void 0),n===void 0&&(n=void 0),ba(this.instance.config)||!f||!y)return!1;e=e??f.location,n=n??f.history;try{if(!t){try{f.localStorage.setItem("test","test"),f.localStorage.removeItem("test")}catch{return!1}t=f==null?void 0:f.localStorage}var s,i=gu||Jr(e.hash,"__posthog")||Jr(e.hash,"state"),o=i?Ui(()=>JSON.parse(atob(decodeURIComponent(i))))||Ui(()=>JSON.parse(decodeURIComponent(i))):null;return o&&o.action==="ph_authorize"?((s=o).source="url",s&&Object.keys(s).length>0&&(o.desiredHash?e.hash=o.desiredHash:n?n.replaceState(n.state,"",e.pathname+e.search):e.hash="")):((s=JSON.parse(t.getItem(no)||"{}")).source="localstorage",delete s.userIntent),!(!s.token||this.instance.config.token!==s.token)&&(this.loadToolbar(s),!0)}catch{return!1}}xt(e){var t=C.ph_load_toolbar||C.ph_load_editor;!$(t)&&je(t)?t(e,this.instance):so.warn("No toolbar load function found")}loadToolbar(e){var t=!(y==null||!y.getElementById(ka));if(!f||t)return!1;var n=this.instance.requestRouter.region==="custom"&&this.instance.config.advanced_disable_toolbar_metrics,s=S({token:this.instance.config.token},e,{apiURL:this.instance.requestRouter.endpointFor("ui")},n?{instrument:!1}:{});if(f.localStorage.setItem(no,JSON.stringify(S({},s,{source:void 0}))),this.wt()===et.LOADED)this.xt(s);else if(this.wt()===et.UNINITIALIZED){var i;this.yt(et.LOADING),(i=C.__PosthogExtensions__)==null||i.loadExternalDependency==null||i.loadExternalDependency(this.instance,"toolbar",o=>{if(o)return so.error("[Toolbar] Failed to load",o),void this.yt(et.UNINITIALIZED);this.yt(et.LOADED),this.xt(s)}),V(f,"turbolinks:load",()=>{this.yt(et.UNINITIALIZED),this.loadToolbar(s)})}return!0}$t(e){return this.loadToolbar(e)}maybeLoadEditor(e,t,n){return e===void 0&&(e=void 0),t===void 0&&(t=void 0),n===void 0&&(n=void 0),this.maybeLoadToolbar(e,t,n)}}var _u=W("[TracingHeaders]");class vu{constructor(e){this.Et=void 0,this.St=void 0,this.rt=()=>{var t,n;b(this.Et)&&((t=C.__PosthogExtensions__)==null||(t=t.tracingHeadersPatchFns)==null||t._patchXHR(this._instance.config.__add_tracing_headers||[],this._instance.get_distinct_id(),this._instance.sessionManager)),b(this.St)&&((n=C.__PosthogExtensions__)==null||(n=n.tracingHeadersPatchFns)==null||n._patchFetch(this._instance.config.__add_tracing_headers||[],this._instance.get_distinct_id(),this._instance.sessionManager))},this._instance=e}it(e){var t,n;(t=C.__PosthogExtensions__)!=null&&t.tracingHeadersPatchFns&&e(),(n=C.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,"tracing-headers",s=>{if(s)return _u.error("failed to load script",s);e()})}startIfEnabledOrStop(){var e,t;this._instance.config.__add_tracing_headers?this.it(this.rt):((e=this.Et)==null||e.call(this),(t=this.St)==null||t.call(this),this.Et=void 0,this.St=void 0)}}var Rr="https?://(.*)",Bt=["gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","irclid","_kx"],yu=Dt(["utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid"],Bt),Sr="",wu=["li_fat_id"];function Wa(r,e,t){if(!y)return{};var n,s=e?Dt([],Bt,t||[]):[],i=za(Er(y.URL,s,Sr),r),o=(n={},j(wu,function(a){var l=Re.q(a);n[a]=l||null}),n);return z(o,i)}function za(r,e){var t=yu.concat(e||[]),n={};return j(t,function(s){var i=Yr(r,s);n[s]=i||null}),n}function Ga(r){var e=function(i){return i?i.search(Rr+"google.([^/?]*)")===0?"google":i.search(Rr+"bing.com")===0?"bing":i.search(Rr+"yahoo.com")===0?"yahoo":i.search(Rr+"duckduckgo.com")===0?"duckduckgo":null:null}(r),t=e!="yahoo"?"q":"p",n={};if(!Ie(e)){n.$search_engine=e;var s=y?Yr(y.referrer,t):"";s.length&&(n.ph_keyword=s)}return n}function io(){return navigator.language||navigator.userLanguage}function qa(){return(y==null?void 0:y.referrer)||"$direct"}function Ka(r,e){var t=r?Dt([],Bt,e||[]):[],n=Q==null?void 0:Q.href.substring(0,1e3);return{r:qa().substring(0,1e3),u:n?Er(n,t,Sr):void 0}}function Va(r){var e,{r:t,u:n}=r,s={$referrer:t,$referring_domain:t==null?void 0:t=="$direct"?"$direct":(e=Vr(t))==null?void 0:e.host};if(n){s.$current_url=n;var i=Vr(n);s.$host=i==null?void 0:i.host,s.$pathname=i==null?void 0:i.pathname;var o=za(n);z(s,o)}if(t){var a=Ga(t);z(s,a)}return s}function Ya(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return}}function bu(){try{return new Date().getTimezoneOffset()}catch{return}}function Eu(r,e){if(!ce)return{};var t,n,s,i=r?Dt([],Bt,e||[]):[],[o,a]=function(l){for(var c=0;c1e3?ce.substring(0,997)+"...":ce,$browser_version:fc(ce,navigator.vendor),$browser_language:io(),$browser_language_prefix:(t=io(),typeof t=="string"?t.split("-")[0]:void 0),$screen_height:f==null?void 0:f.screen.height,$screen_width:f==null?void 0:f.screen.width,$viewport_height:f==null?void 0:f.innerHeight,$viewport_width:f==null?void 0:f.innerWidth,$lib:"web",$lib_version:Le.LIB_VERSION,$insert_id:Math.random().toString(36).substring(2,10)+Math.random().toString(36).substring(2,10),$time:Date.now()/1e3})}var Xe=W("[Web Vitals]"),oo=9e5;class Su{constructor(e){var t;this.kt=!1,this.P=!1,this.N={url:void 0,metrics:[],firstMetricTimestamp:void 0},this.Pt=()=>{clearTimeout(this.Tt),this.N.metrics.length!==0&&(this._instance.capture("$web_vitals",this.N.metrics.reduce((n,s)=>S({},n,{["$web_vitals_"+s.name+"_event"]:S({},s),["$web_vitals_"+s.name+"_value"]:s.value}),{})),this.N={url:void 0,metrics:[],firstMetricTimestamp:void 0})},this.It=n=>{var s,i=(s=this._instance.sessionManager)==null?void 0:s.checkAndGetSessionAndWindowId(!0);if(b(i))Xe.error("Could not read session ID. Dropping metrics!");else{this.N=this.N||{url:void 0,metrics:[],firstMetricTimestamp:void 0};var o=this.Ct();b(o)||($(n==null?void 0:n.name)||$(n==null?void 0:n.value)?Xe.error("Invalid metric received",n):this.Rt&&n.value>=this.Rt?Xe.error("Ignoring metric with value >= "+this.Rt,n):(this.N.url!==o&&(this.Pt(),this.Tt=setTimeout(this.Pt,this.flushToCaptureTimeoutMs)),b(this.N.url)&&(this.N.url=o),this.N.firstMetricTimestamp=b(this.N.firstMetricTimestamp)?Date.now():this.N.firstMetricTimestamp,n.attribution&&n.attribution.interactionTargetElement&&(n.attribution.interactionTargetElement=void 0),this.N.metrics.push(S({},n,{$current_url:o,$session_id:i.sessionId,$window_id:i.windowId,timestamp:Date.now()})),this.N.metrics.length===this.allowedMetrics.length&&this.Pt()))}},this.rt=()=>{if(!this.P){var n,s,i,o,a=C.__PosthogExtensions__;b(a)||b(a.postHogWebVitalsCallbacks)||({onLCP:n,onCLS:s,onFCP:i,onINP:o}=a.postHogWebVitalsCallbacks),n&&s&&i&&o?(this.allowedMetrics.indexOf("LCP")>-1&&n(this.It.bind(this)),this.allowedMetrics.indexOf("CLS")>-1&&s(this.It.bind(this)),this.allowedMetrics.indexOf("FCP")>-1&&i(this.It.bind(this)),this.allowedMetrics.indexOf("INP")>-1&&o(this.It.bind(this)),this.P=!0):Xe.error("web vitals callbacks not loaded - not starting")}},this._instance=e,this.kt=!((t=this._instance.persistence)==null||!t.props[Gi]),this.startIfEnabled()}get allowedMetrics(){var e,t,n=J(this._instance.config.capture_performance)?(e=this._instance.config.capture_performance)==null?void 0:e.web_vitals_allowed_metrics:void 0;return $(n)?((t=this._instance.persistence)==null?void 0:t.props[Ki])||["CLS","FCP","INP","LCP"]:n}get flushToCaptureTimeoutMs(){return(J(this._instance.config.capture_performance)?this._instance.config.capture_performance.web_vitals_delayed_flush_ms:void 0)||5e3}get useAttribution(){var e=J(this._instance.config.capture_performance)?this._instance.config.capture_performance.web_vitals_attribution:void 0;return e!=null&&e}get Rt(){var e=J(this._instance.config.capture_performance)&&Ke(this._instance.config.capture_performance.__web_vitals_max_value)?this._instance.config.capture_performance.__web_vitals_max_value:oo;return 0{i?Xe.error("failed to load script",i):e()})}}Ct(){var e=f?f.location.href:void 0;if(e){var t=this._instance.config.mask_personal_data_properties,n=this._instance.config.custom_personal_data_properties,s=t?Dt([],Bt,n||[]):[];return Er(e,s,Sr)}Xe.error("Could not determine current URL")}}var Iu=W("[Heatmaps]");function ao(r){return J(r)&&"clientX"in r&&"clientY"in r&&Ke(r.clientX)&&Ke(r.clientY)}class ku{constructor(e){var t;this.kt=!1,this.P=!1,this.Ft=null,this.instance=e,this.kt=!((t=this.instance.persistence)==null||!t.props[ds]),this.rageclicks=new Da(e.config.rageclick)}get flushIntervalMilliseconds(){var e=5e3;return J(this.instance.config.capture_heatmaps)&&this.instance.config.capture_heatmaps.flush_interval_milliseconds&&(e=this.instance.config.capture_heatmaps.flush_interval_milliseconds),e}get isEnabled(){return $(this.instance.config.capture_heatmaps)?$(this.instance.config.enable_heatmaps)?this.kt:this.instance.config.enable_heatmaps:this.instance.config.capture_heatmaps!==!1}startIfEnabled(){if(this.isEnabled){if(this.P)return;Iu.info("starting..."),this.Ot(),this.Mt()}else{var e;clearInterval((e=this.Ft)!==null&&e!==void 0?e:void 0),this.At(),this.getAndClearBuffer()}}onRemoteConfig(e){if("heatmaps"in e){var t=!!e.heatmaps;this.instance.persistence&&this.instance.persistence.register({[ds]:t}),this.kt=t,this.startIfEnabled()}}getAndClearBuffer(){var e=this.N;return this.N=void 0,e}jt(e){this.Dt(e.originalEvent,"deadclick")}Mt(){this.Ft&&clearInterval(this.Ft),this.Ft=function(e){return(e==null?void 0:e.visibilityState)==="visible"}(y)?setInterval(this.Lt.bind(this),this.flushIntervalMilliseconds):null}Ot(){f&&y&&(this.Nt=this.Lt.bind(this),V(f,"beforeunload",this.Nt),this.Ut=e=>this.Dt(e||(f==null?void 0:f.event)),V(y,"click",this.Ut,{capture:!0}),this.zt=e=>this.Ht(e||(f==null?void 0:f.event)),V(y,"mousemove",this.zt,{capture:!0}),this.Bt=new ja(this.instance,cu,this.jt.bind(this)),this.Bt.startIfEnabledOrStop(),this.qt=this.Mt.bind(this),V(y,"visibilitychange",this.qt),this.P=!0)}At(){var e;f&&y&&(this.Nt&&f.removeEventListener("beforeunload",this.Nt),this.Ut&&y.removeEventListener("click",this.Ut,{capture:!0}),this.zt&&y.removeEventListener("mousemove",this.zt,{capture:!0}),this.qt&&y.removeEventListener("visibilitychange",this.qt),clearTimeout(this.Wt),(e=this.Bt)==null||e.stop(),this.P=!1)}Gt(e,t){var n=this.instance.scrollManager.scrollY(),s=this.instance.scrollManager.scrollX(),i=this.instance.scrollManager.scrollElement(),o=function(a,l,c){for(var u=a;u&&vn(u)&&!st(u,"body");){if(u===c)return!1;if(F(l,f==null?void 0:f.getComputedStyle(u).position))return!0;u=Pa(u)}return!1}(Ra(e),["fixed","sticky"],i);return{x:e.clientX+(o?0:s),y:e.clientY+(o?0:n),target_fixed:o,type:t}}Dt(e,t){var n;if(t===void 0&&(t="click"),!Vi(e.target)&&ao(e)){var s=this.Gt(e,t);(n=this.rageclicks)!=null&&n.isRageClick(e.clientX,e.clientY,new Date().getTime())&&this.Vt(S({},s,{type:"rageclick"})),this.Vt(s)}}Ht(e){!Vi(e.target)&&ao(e)&&(clearTimeout(this.Wt),this.Wt=setTimeout(()=>{this.Vt(this.Gt(e,"mousemove"))},500))}Vt(e){if(f){var t=f.location.href,n=this.instance.config.mask_personal_data_properties,s=this.instance.config.custom_personal_data_properties,i=n?Dt([],Bt,s||[]):[],o=Er(t,i,Sr);this.N=this.N||{},this.N[o]||(this.N[o]=[]),this.N[o].push(e)}}Lt(){this.N&&!kt(this.N)&&this.instance.capture("$$heatmap",{$heatmap_data:this.getAndClearBuffer()})}}class lo{constructor(e){this.Jt=(t,n,s)=>{s&&(s.noSessionId||s.activityTimeout||s.sessionPastMaximumLength)&&(E.info("[PageViewManager] Session rotated, clearing pageview state",{sessionId:t,changeReason:s}),this.Kt=void 0,this._instance.scrollManager.resetContext())},this._instance=e,this.Yt()}Yt(){var e;this.Xt=(e=this._instance.sessionManager)==null?void 0:e.onSessionId(this.Jt)}destroy(){var e;(e=this.Xt)==null||e.call(this),this.Xt=void 0}doPageView(e,t){var n,s=this.Qt(e,t);return this.Kt={pathname:(n=f==null?void 0:f.location.pathname)!==null&&n!==void 0?n:"",pageViewId:t,timestamp:e},this._instance.scrollManager.resetContext(),s}doPageLeave(e){var t;return this.Qt(e,(t=this.Kt)==null?void 0:t.pageViewId)}doEvent(){var e;return{$pageview_id:(e=this.Kt)==null?void 0:e.pageViewId}}Qt(e,t){var n=this.Kt;if(!n)return{$pageview_id:t};var s={$pageview_id:t,$prev_pageview_id:n.pageViewId},i=this._instance.scrollManager.getContext();if(i&&!this._instance.config.disable_scroll_properties){var{maxScrollHeight:o,lastScrollY:a,maxScrollY:l,maxContentHeight:c,lastContentY:u,maxContentY:d}=i;if(!(b(o)||b(a)||b(l)||b(c)||b(u)||b(d))){o=Math.ceil(o),a=Math.ceil(a),l=Math.ceil(l),c=Math.ceil(c),u=Math.ceil(u),d=Math.ceil(d);var p=o<=1?1:Fe(a/o,0,1,E),h=o<=1?1:Fe(l/o,0,1,E),m=c<=1?1:Fe(u/c,0,1,E),_=c<=1?1:Fe(d/c,0,1,E);s=z(s,{$prev_pageview_last_scroll:a,$prev_pageview_last_scroll_percentage:p,$prev_pageview_max_scroll:l,$prev_pageview_max_scroll_percentage:h,$prev_pageview_last_content:u,$prev_pageview_last_content_percentage:m,$prev_pageview_max_content:d,$prev_pageview_max_content_percentage:_})}}return n.pathname&&(s.$prev_pageview_pathname=n.pathname),n.timestamp&&(s.$prev_pageview_duration=(e.getTime()-n.timestamp.getTime())/1e3),s}}var Be=function(r){return r.GZipJS="gzip-js",r.Base64="base64",r}({}),Ee=Uint8Array,ue=Uint16Array,$t=Uint32Array,Js=new Ee([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]),Zs=new Ee([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]),co=new Ee([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Ja=function(r,e){for(var t=new ue(31),n=0;n<31;++n)t[n]=e+=1<>>1|(21845&U)<<1;ct=(61680&(ct=(52428&ct)>>>2|(13107&ct)<<2))>>>4|(3855&ct)<<4,Xa[U]=((65280&ct)>>>8|(255&ct)<<8)>>>1}var ir=function(r,e,t){for(var n=r.length,s=0,i=new ue(e);s>>15-r[s];return o},pt=new Ee(288);for(U=0;U<144;++U)pt[U]=8;for(U=144;U<256;++U)pt[U]=9;for(U=256;U<280;++U)pt[U]=7;for(U=280;U<288;++U)pt[U]=8;var Xr=new Ee(32);for(U=0;U<32;++U)Xr[U]=5;var xu=ir(pt,9),Tu=ir(Xr,5),Qa=function(r){return(r/8>>0)+(7&r&&1)},el=function(r,e,t){(t==null||t>r.length)&&(t=r.length);var n=new(r instanceof ue?ue:r instanceof $t?$t:Ee)(t-e);return n.set(r.subarray(e,t)),n},Oe=function(r,e,t){t<<=7&e;var n=e/8>>0;r[n]|=t,r[n+1]|=t>>>8},Gt=function(r,e,t){t<<=7&e;var n=e/8>>0;r[n]|=t,r[n+1]|=t>>>8,r[n+2]|=t>>>16},Wn=function(r,e){for(var t=[],n=0;np&&(p=i[n].s);var h=new ue(p+1),m=Es(t[u-1],h,0);if(m>e){n=0;var _=0,v=m-e,k=1<e))break;_+=k-(1<>>=v;_>0;){var R=i[n].s;h[R]=0&&_;--n){var T=i[n].s;h[T]==e&&(--h[T],++_)}m=e}return[new Ee(h),m]},Es=function(r,e,t){return r.s==-1?Math.max(Es(r.l,e,t+1),Es(r.r,e,t+1)):e[r.s]=t},po=function(r){for(var e=r.length;e&&!r[--e];);for(var t=new ue(++e),n=0,s=r[0],i=1,o=function(l){t[n++]=l},a=1;a<=e;++a)if(r[a]==s&&a!=e)++i;else{if(!s&&i>2){for(;i>138;i-=138)o(32754);i>2&&(o(i>10?i-11<<5|28690:i-3<<5|12305),i=0)}else if(i>3){for(o(s),--i;i>6;i-=6)o(8304);i>2&&(o(i-3<<5|8208),i=0)}for(;i--;)o(s);i=1,s=r[a]}return[t.subarray(0,n),e]},qt=function(r,e){for(var t=0,n=0;n>>8,r[s+2]=255^r[s],r[s+3]=255^r[s+1];for(var i=0;i4&&!Y[co[ie-1]];--ie);var ge,ke,Ce,mt,Ve=c+5<<3,at=qt(s,pt)+qt(i,Xr)+o,xe=qt(s,p)+qt(i,_)+o+14+3*ie+qt(A,Y)+(2*A[16]+3*A[17]+7*A[18]);if(Ve<=at&&Ve<=xe)return Ss(e,u,r.subarray(l,l+c));if(Oe(e,u,1+(xe15&&(Oe(e,u,me[x]>>>5&127),u+=me[x]>>>12)}}}else ge=xu,ke=pt,Ce=Tu,mt=Xr;for(x=0;x255){de=n[x]>>>18&31,Gt(e,u,ge[de+257]),u+=ke[de+257],de>7&&(Oe(e,u,n[x]>>>23&31),u+=Js[de]);var vt=31&n[x];Gt(e,u,Ce[vt]),u+=mt[vt],vt>3&&(Gt(e,u,n[x]>>>5&8191),u+=Zs[vt])}else Gt(e,u,ge[n[x]]),u+=ke[n[x]];return Gt(e,u,ge[256]),u+ke[256]},Ru=new $t([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),Au=function(){for(var r=new $t(256),e=0;e<256;++e){for(var t=e,n=9;--n;)t=(1&t&&3988292384)^t>>>1;r[e]=t}return r}(),Pu=function(r,e,t,n,s){return function(i,o,a,l,c,u){var d=i.length,p=new Ee(l+d+5*(1+Math.floor(d/7e3))+c),h=p.subarray(l,p.length-c),m=0;if(!o||d<8)for(var _=0;_<=d;_+=65535){var v=_+65535;v>>13,R=8191&k,T=(1<7e3||Ce>24576)&&_t>423){m=fo(i,h,0,Y,se,ie,ke,Ce,Ve,_-Ve,m),Ce=ge=ke=0,Ve=_;for(var oe=0;oe<286;++oe)se[oe]=0;for(oe=0;oe<30;++oe)ie[oe]=0}var me=2,de=0,vt=R,Je=xe-Ye&32767;if(_t>2&&at==re(_-Je))for(var ql=Math.min(I,_t)-1,Kl=Math.min(32767,_),Vl=Math.min(258,_t);Je<=Kl&&--vt&&xe!=Ye;){if(i[_+me]==i[_+me-Je]){for(var Ze=0;Zeme){if(me=Ze,de=Je,Ze>ql)break;var Yl=Math.min(Je,Ze-2),ki=0;for(oe=0;oeki&&(ki=Ci,Ye=Mn)}}}Je+=(xe=Ye)-(Ye=w[xe])+32768&32767}if(de){Y[Ce++]=268435456|bs[me]<<18|uo[de];var xi=31&bs[me],Ti=31&uo[de];ke+=Js[xi]+Zs[Ti],++se[257+xi],++ie[Ti],mt=_+me,++ge}else Y[Ce++]=i[_],++se[i[_]]}}m=fo(i,h,u,Y,se,ie,ke,Ce,Ve,_-Ve,m)}return el(p,0,l+Qa(m)+c)}(r,e.level==null?6:e.level,e.mem==null?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(r.length)))):12+e.mem,t,n,!0)},zn=function(r,e,t){for(;t;++e)r[e]=t,t>>>=8};function Fu(r,e){e===void 0&&(e={});var t=function(){var a=4294967295;return{p:function(l){for(var c=a,u=0;u>>8;a=c},d:function(){return 4294967295^a}}}(),n=r.length;t.p(r);var s,i=Pu(r,e,10+((s=e).filename&&s.filename.length+1||0),8),o=i.length;return function(a,l){var c=l.filename;if(a[0]=31,a[1]=139,a[2]=8,a[8]=l.level<2?4:l.level==9?2:0,a[9]=3,l.mtime!=0&&zn(a,4,Math.floor(new Date(l.mtime||Date.now())/1e3)),c){a[3]=8;for(var u=0;u<=c.length;++u)a[u+10]=c.charCodeAt(u)}}(i,e),zn(i,o-8,t.d()),zn(i,o-4,n),i}var $u=function(r){var e,t,n,s,i="";for(e=t=0,n=(r=(r+"").replace(/\r\n/g,` -`).replace(/\r/g,` -`)).length,s=0;s127&&o<2048?String.fromCharCode(o>>6|192,63&o|128):String.fromCharCode(o>>12|224,o>>6&63|128,63&o|128),Ie(a)||(t>e&&(i+=r.substring(e,t)),i+=a,e=t=s+1)}return t>e&&(i+=r.substring(e,r.length)),i},Mu=!!ns||!!rs,ho="text/plain",Qr=function(r,e,t){var n;t===void 0&&(t=!0);var[s,i]=r.split("?"),o=S({},e),a=(n=i==null?void 0:i.split("&").map(c=>{var u,[d,p]=c.split("="),h=t&&(u=o[d])!==null&&u!==void 0?u:p;return delete o[d],d+"="+h}))!==null&&n!==void 0?n:[],l=Jc(o);return l&&a.push(l),s+"?"+a.join("&")},rr=(r,e)=>JSON.stringify(r,(t,n)=>typeof n=="bigint"?n.toString():n,e),Gn=r=>{var{data:e,compression:t}=r;if(e){if(t===Be.GZipJS){var n=Fu(function(l,c){var u=l.length;if(typeof TextEncoder<"u")return new TextEncoder().encode(l);for(var d=new Ee(l.length+(l.length>>>1)),p=0,h=function(k){d[p++]=k},m=0;md.length){var _=new Ee(p+8+(u-m<<1));_.set(d),d=_}var v=l.charCodeAt(m);v<128||c?h(v):v<2048?(h(192|v>>>6),h(128|63&v)):v>55295&&v<57344?(h(240|(v=65536+(1047552&v)|1023&l.charCodeAt(++m))>>>18),h(128|v>>>12&63),h(128|v>>>6&63),h(128|63&v)):(h(224|v>>>12),h(128|v>>>6&63),h(128|63&v))}return el(d,0,p)}(rr(e)),{mtime:0}),s=new Blob([n],{type:ho});return{contentType:ho,body:s,estimatedSize:s.size}}if(t===Be.Base64){var i=function(l){var c,u,d,p,h,m="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",_=0,v=0,k="",I=[];if(!l)return l;l=$u(l);do c=(h=l.charCodeAt(_++)<<16|l.charCodeAt(_++)<<8|l.charCodeAt(_++))>>18&63,u=h>>12&63,d=h>>6&63,p=63&h,I[v++]=m.charAt(c)+m.charAt(u)+m.charAt(d)+m.charAt(p);while(_"data="+encodeURIComponent(typeof l=="string"?l:rr(l)))(i);return{contentType:"application/x-www-form-urlencoded",body:o,estimatedSize:new Blob([o]).size}}var a=rr(e);return{contentType:"application/json",body:a,estimatedSize:new Blob([a]).size}}},$r=[];rs&&$r.push({transport:"fetch",method:r=>{var e,t,{contentType:n,body:s,estimatedSize:i}=(e=Gn(r))!==null&&e!==void 0?e:{},o=new Headers;j(r.headers,function(u,d){o.append(d,u)}),n&&o.append("Content-Type",n);var a=r.url,l=null;if(Pi){var c=new Pi;l={signal:c.signal,timeout:setTimeout(()=>c.abort(),r.timeout)}}rs(a,S({method:(r==null?void 0:r.method)||"GET",headers:o,keepalive:r.method==="POST"&&(i||0)<52428.8,body:s,signal:(t=l)==null?void 0:t.signal},r.fetchOptions)).then(u=>u.text().then(d=>{var p={statusCode:u.status,text:d};if(u.status===200)try{p.json=JSON.parse(d)}catch(h){E.error(h)}r.callback==null||r.callback(p)})).catch(u=>{E.error(u),r.callback==null||r.callback({statusCode:0,error:u})}).finally(()=>l?clearTimeout(l.timeout):null)}}),ns&&$r.push({transport:"XHR",method:r=>{var e,t=new ns;t.open(r.method||"GET",r.url,!0);var{contentType:n,body:s}=(e=Gn(r))!==null&&e!==void 0?e:{};j(r.headers,function(i,o){t.setRequestHeader(o,i)}),n&&t.setRequestHeader("Content-Type",n),r.timeout&&(t.timeout=r.timeout),r.disableXHRCredentials||(t.withCredentials=!0),t.onreadystatechange=()=>{if(t.readyState===4){var i={statusCode:t.status,text:t.responseText};if(t.status===200)try{i.json=JSON.parse(t.responseText)}catch{}r.callback==null||r.callback(i)}},t.send(s)}}),fe!=null&&fe.sendBeacon&&$r.push({transport:"sendBeacon",method:r=>{var e=Qr(r.url,{beacon:"1"});try{var t,{contentType:n,body:s}=(t=Gn(r))!==null&&t!==void 0?t:{},i=typeof s=="string"?new Blob([s],{type:n}):s;fe.sendBeacon(e,i)}catch{}}});var en=function(r,e){if(!function(t){try{new RegExp(t)}catch{return!1}return!0}(e))return!1;try{return new RegExp(e).test(r)}catch{return!1}};function go(r,e,t){return rr({distinct_id:r,userPropertiesToSet:e,userPropertiesToSetOnce:t})}var tl={exact:(r,e)=>e.some(t=>r.some(n=>t===n)),is_not:(r,e)=>e.every(t=>r.every(n=>t!==n)),regex:(r,e)=>e.some(t=>r.some(n=>en(t,n))),not_regex:(r,e)=>e.every(t=>r.every(n=>!en(t,n))),icontains:(r,e)=>e.map(Ar).some(t=>r.map(Ar).some(n=>t.includes(n))),not_icontains:(r,e)=>e.map(Ar).every(t=>r.map(Ar).every(n=>!t.includes(n))),gt:(r,e)=>e.some(t=>{var n=parseFloat(t);return!isNaN(n)&&r.some(s=>n>parseFloat(s))}),lt:(r,e)=>e.some(t=>{var n=parseFloat(t);return!isNaN(n)&&r.some(s=>nr.toLowerCase();function rl(r,e){return!r||Object.entries(r).every(t=>{var[n,s]=t,i=e==null?void 0:e[n];if(b(i)||Ie(i))return!1;var o=[String(i)],a=tl[s.operator];return!!a&&a(s.values,o)})}var qn=W("[Error tracking]");class Ou{constructor(e){var t,n;this.Zt=[],this.ti=new mc([new kc,new Mc,new xc,new Cc,new Fc,new Pc,new Rc,new $c],Ic()),this._instance=e,this.Zt=(t=(n=this._instance.persistence)==null?void 0:n.get_property(ps))!==null&&t!==void 0?t:[]}onRemoteConfig(e){var t,n,s;if("errorTracking"in e){var i=(t=(n=e.errorTracking)==null?void 0:n.suppressionRules)!==null&&t!==void 0?t:[],o=(s=e.errorTracking)==null?void 0:s.captureExtensionExceptions;this.Zt=i,this._instance.persistence&&this._instance.persistence.register({[ps]:this.Zt,[zi]:o})}}get ii(){var e,t=!!this._instance.get_property(zi),n=this._instance.config.error_tracking.captureExtensionExceptions;return(e=n??t)!==null&&e!==void 0&&e}buildProperties(e,t){return this.ti.buildFromUnknown(e,{syntheticException:t==null?void 0:t.syntheticException,mechanism:{handled:t==null?void 0:t.handled}})}sendExceptionEvent(e){var t=e.$exception_list;if(this.ei(t)){if(this.ri(t))return void qn.info("Skipping exception capture because a suppression rule matched");if(!this.ii&&this.si(t))return void qn.info("Skipping exception capture because it was thrown by an extension");if(!this._instance.config.error_tracking.__capturePostHogExceptions&&this.ni(t))return void qn.info("Skipping exception capture because it was thrown by the PostHog SDK")}return this._instance.capture("$exception",e,{_noTruncate:!0,_batchKey:"exceptionEvent",oi:!0})}ri(e){if(e.length===0)return!1;var t=e.reduce((n,s)=>{var{type:i,value:o}=s;return K(i)&&i.length>0&&n.$exception_types.push(i),K(o)&&o.length>0&&n.$exception_values.push(o),n},{$exception_types:[],$exception_values:[]});return this.Zt.some(n=>{var s=n.values.map(i=>{var o,a=tl[i.operator],l=L(i.value)?i.value:[i.value],c=(o=t[i.key])!==null&&o!==void 0?o:[];return l.length>0&&a(l,c)});return n.type==="OR"?s.some(Boolean):s.every(Boolean)})}si(e){return e.flatMap(t=>{var n,s;return(n=(s=t.stacktrace)==null?void 0:s.frames)!==null&&n!==void 0?n:[]}).some(t=>t.filename&&t.filename.startsWith("chrome-extension://"))}ni(e){if(e.length>0){var t,n,s,i,o=(t=(n=e[0].stacktrace)==null?void 0:n.frames)!==null&&t!==void 0?t:[],a=o[o.length-1];return(s=a==null||(i=a.filename)==null?void 0:i.includes("posthog.com/static"))!==null&&s!==void 0&&s}return!1}ei(e){return!$(e)&&L(e)}}var pe=W("[FeatureFlags]"),Kt=W("[FeatureFlags]",{debugEnabled:!0}),Lu="errors_while_computing_flags",Nu="flag_missing",Du="quota_limited",Bu="timeout",ju="connection_error",Uu="unknown_error",Hu=r=>"api_error_"+r,Kn="$active_feature_flags",yt="$override_feature_flags",mo="$feature_flag_payloads",Vt="$override_feature_flag_payloads",_o="$feature_flag_request_id",vo="$feature_flag_evaluated_at",yo=r=>{var e={};for(var[t,n]of Fr(r||{}))n&&(e[t]=n);return e},Wu=r=>{var e=r.flags;return e?(r.featureFlags=Object.fromEntries(Object.keys(e).map(t=>{var n;return[t,(n=e[t].variant)!==null&&n!==void 0?n:e[t].enabled]})),r.featureFlagPayloads=Object.fromEntries(Object.keys(e).filter(t=>e[t].enabled).filter(t=>{var n;return(n=e[t].metadata)==null?void 0:n.payload}).map(t=>{var n;return[t,(n=e[t].metadata)==null?void 0:n.payload]}))):pe.warn("Using an older version of the feature flags endpoint. Please upgrade your PostHog server to the latest version"),r},zu=function(r){return r.FeatureFlags="feature_flags",r.Recordings="recordings",r}({});class Gu{constructor(e){this.ai=!1,this.li=!1,this.ui=!1,this.hi=!1,this.di=!1,this.vi=!1,this.ci=!1,this._instance=e,this.featureFlagEventHandlers=[]}fi(){var e,t=(e=this._instance.config.evaluation_contexts)!==null&&e!==void 0?e:this._instance.config.evaluation_environments;return!this._instance.config.evaluation_environments||this._instance.config.evaluation_contexts||this.ci||(pe.warn("evaluation_environments is deprecated. Use evaluation_contexts instead. evaluation_environments will be removed in a future version."),this.ci=!0),t!=null&&t.length?t.filter(n=>{var s=n&&typeof n=="string"&&n.trim().length>0;return s||pe.error("Invalid evaluation context found:",n,"Expected non-empty string"),s}):[]}pi(){return this.fi().length>0}get hasLoadedFlags(){return this.li}getFlags(){return Object.keys(this.getFlagVariants())}getFlagsWithDetails(){var e=this._instance.get_property(fs),t=this._instance.get_property(yt),n=this._instance.get_property(Vt);if(!n&&!t)return e||{};var s=z({},e||{}),i=[...new Set([...Object.keys(n||{}),...Object.keys(t||{})])];for(var o of i){var a,l,c=s[o],u=t==null?void 0:t[o],d=b(u)?(a=c==null?void 0:c.enabled)!==null&&a!==void 0&&a:!!u,p=b(u)?c.variant:typeof u=="string"?u:void 0,h=n==null?void 0:n[o],m=S({},c,{enabled:d,variant:d?p??(c==null?void 0:c.variant):void 0});d!==(c==null?void 0:c.enabled)&&(m.original_enabled=c==null?void 0:c.enabled),p!==(c==null?void 0:c.variant)&&(m.original_variant=c==null?void 0:c.variant),h&&(m.metadata=S({},c==null?void 0:c.metadata,{payload:h,original_payload:c==null||(l=c.metadata)==null?void 0:l.payload})),s[o]=m}return this.ai||(pe.warn(" Overriding feature flag details!",{flagDetails:e,overriddenPayloads:n,finalDetails:s}),this.ai=!0),s}getFlagVariants(){var e=this._instance.get_property(Ct),t=this._instance.get_property(yt);if(!t)return e||{};for(var n=z({},e),s=Object.keys(t),i=0;i{this.bi()},5))}yi(){clearTimeout(this.gi),this.gi=void 0}ensureFlagsLoaded(){this.li||this.ui||this.gi||this.reloadFeatureFlags()}setAnonymousDistinctId(e){this.$anon_distinct_id=e}setReloadingPaused(e){this.hi=e}bi(e){var t;if(this.yi(),!this._instance.M())if(this.ui)this.di=!0;else{var n=this._instance.config.token,s=this._instance.get_property("$device_id"),i={token:n,distinct_id:this._instance.get_distinct_id(),groups:this._instance.getGroups(),$anon_distinct_id:this.$anon_distinct_id,person_properties:S({},((t=this._instance.persistence)==null?void 0:t.get_initial_props())||{},this._instance.get_property(tr)||{}),group_properties:this._instance.get_property(ut),timezone:Ya()};Ie(s)||b(s)||(i.$device_id=s),(e!=null&&e.disableFlags||this._instance.config.advanced_disable_feature_flags)&&(i.disable_flags=!0),this.pi()&&(i.evaluation_contexts=this.fi());var o=this._instance.config.advanced_only_evaluate_survey_feature_flags?"&only_evaluate_survey_feature_flags=true":"",a=this._instance.requestRouter.endpointFor("flags","/flags/?v=2"+o);this.ui=!0,this._instance._send_request({method:"POST",url:a,data:i,compression:this._instance.config.disable_compression?void 0:Be.Base64,timeout:this._instance.config.feature_flag_request_timeout_ms,callback:l=>{var c,u,d,p=!0;if(l.statusCode===200&&(this.di||(this.$anon_distinct_id=void 0),p=!1),this.ui=!1,!i.disable_flags||this.di){this.vi=!p;var h=[];l.error?l.error instanceof Error?h.push(l.error.name==="AbortError"?Bu:ju):h.push(Uu):l.statusCode!==200&&h.push(Hu(l.statusCode)),(c=l.json)!=null&&c.errorsWhileComputingFlags&&h.push(Lu);var m=!((u=l.json)==null||(u=u.quotaLimited)==null||!u.includes(zu.FeatureFlags));if(m&&h.push(Du),(d=this._instance.persistence)==null||d.register({[gs]:h}),m)pe.warn("You have hit your feature flags quota limit, and will not be able to load feature flags until the quota is reset. Please visit https://posthog.com/docs/billing/limits-alerts to learn more.");else{var _;i.disable_flags||this.receivedFeatureFlags((_=l.json)!==null&&_!==void 0?_:{},p),this.di&&(this.di=!1,this.bi())}}}})}}getFeatureFlag(e,t){var n;if(t===void 0&&(t={}),!t.fresh||this.vi){if(this.li||this.getFlags()&&this.getFlags().length>0){var s=this.getFeatureFlagResult(e,t);return(n=s==null?void 0:s.variant)!==null&&n!==void 0?n:s==null?void 0:s.enabled}pe.warn('getFeatureFlag for key "'+e+`" failed. Feature flags didn't load in time.`)}}getFeatureFlagDetails(e){return this.getFlagsWithDetails()[e]}getFeatureFlagPayload(e){var t=this.getFeatureFlagResult(e,{send_event:!1});return t==null?void 0:t.payload}getFeatureFlagResult(e,t){if(t===void 0&&(t={}),!t.fresh||this.vi)if(this.li||this.getFlags()&&this.getFlags().length>0){var n=this.getFlagVariants(),s=e in n,i=n[e],o=this.getFlagPayloads()[e],a=String(i),l=this._instance.get_property(_o)||void 0,c=this._instance.get_property(vo)||void 0,u=this._instance.get_property(zr)||{};if((t.send_event||!("send_event"in t))&&(!(e in u)||!u[e].includes(a))){var d,p,h,m,_,v,k,I,R,T;L(u[e])?u[e].push(a):u[e]=[a],(d=this._instance.persistence)==null||d.register({[zr]:u});var w=this.getFeatureFlagDetails(e),P=[...(p=this._instance.get_property(gs))!==null&&p!==void 0?p:[]];b(i)&&P.push(Nu);var A={$feature_flag:e,$feature_flag_response:i,$feature_flag_payload:o||null,$feature_flag_request_id:l,$feature_flag_evaluated_at:c,$feature_flag_bootstrapped_response:((h=this._instance.config.bootstrap)==null||(h=h.featureFlags)==null?void 0:h[e])||null,$feature_flag_bootstrapped_payload:((m=this._instance.config.bootstrap)==null||(m=m.featureFlagPayloads)==null?void 0:m[e])||null,$used_bootstrap_value:!this.vi};b(w==null||(_=w.metadata)==null?void 0:_.version)||(A.$feature_flag_version=w.metadata.version);var x,re=(v=w==null||(k=w.reason)==null?void 0:k.description)!==null&&v!==void 0?v:w==null||(I=w.reason)==null?void 0:I.code;re&&(A.$feature_flag_reason=re),w!=null&&(R=w.metadata)!=null&&R.id&&(A.$feature_flag_id=w.metadata.id),b(w==null?void 0:w.original_variant)&&b(w==null?void 0:w.original_enabled)||(A.$feature_flag_original_response=b(w.original_variant)?w.original_enabled:w.original_variant),w!=null&&(T=w.metadata)!=null&&T.original_payload&&(A.$feature_flag_original_payload=w==null||(x=w.metadata)==null?void 0:x.original_payload),P.length&&(A.$feature_flag_error=P.join(",")),this._instance.capture("$feature_flag_called",A)}if(s){var Y=o;if(!b(o))try{Y=JSON.parse(o)}catch{}return{key:e,enabled:!!i,variant:typeof i=="string"?i:void 0,payload:Y}}}else pe.warn('getFeatureFlagResult for key "'+e+`" failed. Feature flags didn't load in time.`)}getRemoteConfigPayload(e,t){var n=this._instance.config.token,s={distinct_id:this._instance.get_distinct_id(),token:n};this.pi()&&(s.evaluation_contexts=this.fi()),this._instance._send_request({method:"POST",url:this._instance.requestRouter.endpointFor("flags","/flags/?v=2"),data:s,compression:this._instance.config.disable_compression?void 0:Be.Base64,timeout:this._instance.config.feature_flag_request_timeout_ms,callback:i=>{var o,a=(o=i.json)==null?void 0:o.featureFlagPayloads;t((a==null?void 0:a[e])||void 0)}})}isFeatureEnabled(e,t){if(t===void 0&&(t={}),!t.fresh||this.vi){if(this.li||this.getFlags()&&this.getFlags().length>0){var n=this.getFeatureFlag(e,t);return b(n)?void 0:!!n}pe.warn('isFeatureEnabled for key "'+e+`" failed. Feature flags didn't load in time.`)}}addFeatureFlagsHandler(e){this.featureFlagEventHandlers.push(e)}removeFeatureFlagsHandler(e){this.featureFlagEventHandlers=this.featureFlagEventHandlers.filter(t=>t!==e)}receivedFeatureFlags(e,t){if(this._instance.persistence){this.li=!0;var n=this.getFlagVariants(),s=this.getFlagPayloads(),i=this.getFlagsWithDetails();(function(o,a,l,c,u){l===void 0&&(l={}),c===void 0&&(c={}),u===void 0&&(u={});var d=Wu(o),p=d.flags,h=d.featureFlags,m=d.featureFlagPayloads;if(h){var _=o.requestId,v=o.evaluatedAt;if(L(h)){pe.warn("v1 of the feature flags endpoint is deprecated. Please use the latest version.");var k={};if(h)for(var I=0;I{var x;return!((x=p[A])!=null&&x.failed)}));R=S({},l,Object.fromEntries(Object.entries(R).filter(A=>{var[x]=A;return P.has(x)}))),T=S({},c,Object.fromEntries(Object.entries(T||{}).filter(A=>{var[x]=A;return P.has(x)}))),w=S({},u,Object.fromEntries(Object.entries(w||{}).filter(A=>{var[x]=A;return P.has(x)})))}else R=S({},l,R),T=S({},c,T),w=S({},u,w);a&&a.register(S({[Kn]:Object.keys(yo(R)),[Ct]:R||{},[mo]:T||{},[fs]:w||{}},_?{[_o]:_}:{},v?{[vo]:v}:{}))}}})(e,this._instance.persistence,n,s,i),this.wi(t)}}override(e,t){t===void 0&&(t=!1),pe.warn("override is deprecated. Please use overrideFeatureFlags instead."),this.overrideFeatureFlags({flags:e,suppressWarning:t})}overrideFeatureFlags(e){if(!this._instance.__loaded||!this._instance.persistence)return pe.uninitializedWarning("posthog.featureFlags.overrideFeatureFlags");if(e===!1)return this._instance.persistence.unregister(yt),this._instance.persistence.unregister(Vt),this.wi(),Kt.info("All overrides cleared");if(e&&typeof e=="object"&&("flags"in e||"payloads"in e)){var t,n=e;if(this.ai=!!((t=n.suppressWarning)!==null&&t!==void 0&&t),"flags"in n){if(n.flags===!1)this._instance.persistence.unregister(yt),Kt.info("Flag overrides cleared");else if(n.flags){if(L(n.flags)){for(var s={},i=0;ithis.removeFeatureFlagsHandler(e)}updateEarlyAccessFeatureEnrollment(e,t,n){var s,i=(this._instance.get_property(er)||[]).find(c=>c.flagKey===e),o={["$feature_enrollment/"+e]:t},a={$feature_flag:e,$feature_enrollment:t,$set:o};i&&(a.$early_access_feature_name=i.name),n&&(a.$feature_enrollment_stage=n),this._instance.capture("$feature_enrollment_update",a),this.setPersonPropertiesForFlags(o,!1);var l=S({},this.getFlagVariants(),{[e]:t});(s=this._instance.persistence)==null||s.register({[Kn]:Object.keys(yo(l)),[Ct]:l}),this.wi()}getEarlyAccessFeatures(e,t,n){t===void 0&&(t=!1);var s=this._instance.get_property(er),i=n?"&"+n.map(o=>"stage="+o).join("&"):"";if(s&&!t)return e(s);this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/early_access_features/?token="+this._instance.config.token+i),method:"GET",callback:o=>{var a,l;if(o.json){var c=o.json.earlyAccessFeatures;return(a=this._instance.persistence)==null||a.unregister(er),(l=this._instance.persistence)==null||l.register({[er]:c}),e(c)}}})}xi(){var e=this.getFlags(),t=this.getFlagVariants();return{flags:e.filter(n=>t[n]),flagVariants:Object.keys(t).filter(n=>t[n]).reduce((n,s)=>(n[s]=t[s],n),{})}}wi(e){var{flags:t,flagVariants:n}=this.xi();this.featureFlagEventHandlers.forEach(s=>s(t,n,{errorsLoading:e}))}setPersonPropertiesForFlags(e,t){t===void 0&&(t=!0);var n=this._instance.get_property(tr)||{};this._instance.register({[tr]:S({},n,e)}),t&&this._instance.reloadFeatureFlags()}resetPersonPropertiesForFlags(){this._instance.unregister(tr)}setGroupPropertiesForFlags(e,t){t===void 0&&(t=!0);var n=this._instance.get_property(ut)||{};Object.keys(n).length!==0&&Object.keys(n).forEach(s=>{n[s]=S({},n[s],e[s]),delete e[s]}),this._instance.register({[ut]:S({},n,e)}),t&&this._instance.reloadFeatureFlags()}resetGroupPropertiesForFlags(e){if(e){var t=this._instance.get_property(ut)||{};this._instance.register({[ut]:S({},t,{[e]:{}})})}else this._instance.unregister(ut)}reset(){this.li=!1,this.ui=!1,this.hi=!1,this.di=!1,this.vi=!1,this.$anon_distinct_id=void 0,this.yi(),this.ai=!1}}var qu=["cookie","localstorage","localstorage+cookie","sessionstorage","memory"];class Vn{constructor(e,t){this.R=e,this.props={},this.$i=!1,this.Ei=(n=>{var s="";return n.token&&(s=n.token.replace(/\+/g,"PL").replace(/\//g,"SL").replace(/=/g,"EQ")),n.persistence_name?"ph_"+n.persistence_name:"ph_"+s+"_posthog"})(e),this.Y=this.Si(e),this.load(),e.debug&&E.info("Persistence loaded",e.persistence,S({},this.props)),this.update_config(e,e,t),this.save()}isDisabled(){return!!this.ki}Si(e){qu.indexOf(e.persistence.toLowerCase())===-1&&(E.critical("Unknown persistence type "+e.persistence+"; falling back to localStorage+cookie"),e.persistence="localStorage+cookie");var t=function(s){s===void 0&&(s=[]);var i=[...ou,...s];return S({},H,{W:function(o){try{var a={};try{a=Re.W(o)||{}}catch{}var l=z(a,JSON.parse(H.q(o)||"{}"));return H.G(o,l),l}catch{}return null},G:function(o,a,l,c,u,d){try{H.G(o,a,void 0,void 0,d);var p={};i.forEach(h=>{a[h]&&(p[h]=a[h])}),Object.keys(p).length&&Re.G(o,p,l,c,u,d)}catch(h){H.B(h)}},V:function(o,a){try{f==null||f.localStorage.removeItem(o),Re.V(o,a)}catch(l){H.B(l)}}})}(e.cookie_persisted_properties||[]),n=e.persistence.toLowerCase();return n==="localstorage"&&H.H()?H:n==="localstorage+cookie"&&t.H()?t:n==="sessionstorage"&&X.H()?X:n==="memory"?au:n==="cookie"?Re:t.H()?t:Re}properties(){var e={};return j(this.props,function(t,n){if(n===Ct&&J(t))for(var s=Object.keys(t),i=0;i{this.props.hasOwnProperty(o)&&this.props[o]!==t||(this.props[o]=i,s=!0)}),s)return this.save(),!0}return!1}register(e,t){if(J(e)){this.Pi=b(t)?this.Ci:t;var n=!1;if(j(e,(s,i)=>{e.hasOwnProperty(i)&&this.props[i]!==s&&(this.props[i]=s,n=!0)}),n)return this.save(),!0}return!1}unregister(e){e in this.props&&(delete this.props[e],this.save())}update_campaign_params(){if(!this.$i){var e=Wa(this.R.custom_campaign_params,this.R.mask_personal_data_properties,this.R.custom_personal_data_properties);kt(qs(e))||this.register(e),this.$i=!0}}update_search_keyword(){var e;this.register((e=y==null?void 0:y.referrer)?Ga(e):{})}update_referrer_info(){var e;this.register_once({$referrer:qa(),$referring_domain:y!=null&&y.referrer&&((e=Vr(y.referrer))==null?void 0:e.host)||"$direct"},void 0)}set_initial_person_info(){this.props[vs]||this.props[ys]||this.register_once({[Gr]:Ka(this.R.mask_personal_data_properties,this.R.custom_personal_data_properties)},void 0)}get_initial_props(){var e={};j([ys,vs],o=>{var a=this.props[o];a&&j(a,function(l,c){e["$initial_"+ss(c)]=l})});var t,n,s=this.props[Gr];if(s){var i=(t=Va(s),n={},j(t,function(o,a){n["$initial_"+ss(a)]=o}),n);z(e,i)}return e}safe_merge(e){return j(this.props,function(t,n){n in e||(e[n]=t)}),e}update_config(e,t,n){if(this.Ci=this.Pi=e.cookie_expiration,this.set_disabled(e.disable_persistence||!!n),this.set_cross_subdomain(e.cross_subdomain_cookie),this.set_secure(e.secure_cookie),e.persistence!==t.persistence||!((o,a)=>{if(o.length!==a.length)return!1;var l=[...o].sort(),c=[...a].sort();return l.every((u,d)=>u===c[d])})(e.cookie_persisted_properties||[],t.cookie_persisted_properties||[])){var s=this.Si(e),i=this.props;this.clear(),this.Y=s,this.props=i,this.save()}}set_disabled(e){this.ki=e,this.ki?this.remove():this.save()}set_cross_subdomain(e){e!==this.Ti&&(this.Ti=e,this.remove(),this.save())}set_secure(e){e!==this.Ii&&(this.Ii=e,this.remove(),this.save())}set_event_timer(e,t){var n=this.props[Qt]||{};n[e]=t,this.props[Qt]=n,this.save()}remove_event_timer(e){var t=(this.props[Qt]||{})[e];return b(t)||(delete this.props[Qt][e],this.save()),t}get_property(e){return this.props[e]}set_property(e,t){this.props[e]=t,this.save()}}var wo=W("[Product Tours]"),Yn="ph_product_tours";class Ku{constructor(e){this.Ri=null,this.Fi=null,this._instance=e}onRemoteConfig(e){"productTours"in e&&(this._instance.persistence&&this._instance.persistence.register({[qi]:!!e.productTours}),this.loadIfEnabled())}loadIfEnabled(){var e,t;this.Ri||(e=this._instance).config.disable_product_tours||(t=e.persistence)==null||!t.get_property(qi)||this.it(()=>this.Oi())}it(e){var t,n;(t=C.__PosthogExtensions__)!=null&&t.generateProductTours?e():(n=C.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,"product-tours",s=>{s?wo.error("Could not load product tours script",s):e()})}Oi(){var e;!this.Ri&&(e=C.__PosthogExtensions__)!=null&&e.generateProductTours&&(this.Ri=C.__PosthogExtensions__.generateProductTours(this._instance,!0))}getProductTours(e,t){if(t===void 0&&(t=!1),!L(this.Fi)||t){var n=this._instance.persistence;if(n){var s=n.props[Yn];if(L(s)&&!t)return this.Fi=s,void e(s,{isLoaded:!0})}this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/product_tours/?token="+this._instance.config.token),method:"GET",callback:i=>{var o=i.statusCode;if(o!==200||!i.json){var a="Product Tours API could not be loaded, status: "+o;return wo.error(a),void e([],{isLoaded:!1,error:a})}var l=L(i.json.product_tours)?i.json.product_tours:[];this.Fi=l,n&&n.register({[Yn]:l}),e(l,{isLoaded:!0})}})}else e(this.Fi,{isLoaded:!0})}getActiveProductTours(e){$(this.Ri)?e([],{isLoaded:!1,error:"Product tours not loaded"}):this.Ri.getActiveProductTours(e)}showProductTour(e){var t;(t=this.Ri)==null||t.showTourById(e)}previewTour(e){this.Ri?this.Ri.previewTour(e):this.it(()=>{var t;this.Oi(),(t=this.Ri)==null||t.previewTour(e)})}dismissProductTour(){var e;(e=this.Ri)==null||e.dismissTour("user_clicked_skip")}nextStep(){var e;(e=this.Ri)==null||e.nextStep()}previousStep(){var e;(e=this.Ri)==null||e.previousStep()}clearCache(){var e;this.Fi=null,(e=this._instance.persistence)==null||e.unregister(Yn)}resetTour(e){var t;(t=this.Ri)==null||t.resetTour(e)}resetAllTours(){var e;(e=this.Ri)==null||e.resetAllTours()}cancelPendingTour(e){var t;(t=this.Ri)==null||t.cancelPendingTour(e)}}var Yt=function(r){return r.Activation="events",r.Cancellation="cancelEvents",r}({});(function(r){return r.Button="button",r.Tab="tab",r.Selector="selector",r})({});(function(r){return r.TopLeft="top_left",r.TopRight="top_right",r.TopCenter="top_center",r.MiddleLeft="middle_left",r.MiddleRight="middle_right",r.MiddleCenter="middle_center",r.Left="left",r.Center="center",r.Right="right",r.NextToTrigger="next_to_trigger",r})({});(function(r){return r.Top="top",r.Left="left",r.Right="right",r.Bottom="bottom",r})({});var Jn=function(r){return r.Popover="popover",r.API="api",r.Widget="widget",r.ExternalSurvey="external_survey",r}({});(function(r){return r.Open="open",r.MultipleChoice="multiple_choice",r.SingleChoice="single_choice",r.Rating="rating",r.Link="link",r})({});(function(r){return r.NextQuestion="next_question",r.End="end",r.ResponseBased="response_based",r.SpecificQuestion="specific_question",r})({});(function(r){return r.Once="once",r.Recurring="recurring",r.Always="always",r})({});var nr=function(r){return r.SHOWN="survey shown",r.DISMISSED="survey dismissed",r.SENT="survey sent",r.ABANDONED="survey abandoned",r}({}),Zn=function(r){return r.SURVEY_ID="$survey_id",r.SURVEY_NAME="$survey_name",r.SURVEY_RESPONSE="$survey_response",r.SURVEY_ITERATION="$survey_iteration",r.SURVEY_ITERATION_START_DATE="$survey_iteration_start_date",r.SURVEY_PARTIALLY_COMPLETED="$survey_partially_completed",r.SURVEY_SUBMISSION_ID="$survey_submission_id",r.SURVEY_QUESTIONS="$survey_questions",r.SURVEY_COMPLETED="$survey_completed",r.PRODUCT_TOUR_ID="$product_tour_id",r.SURVEY_LAST_SEEN_DATE="$survey_last_seen_date",r}({}),Is=function(r){return r.Popover="popover",r.Inline="inline",r}({}),B=W("[Surveys]"),nl="seenSurvey_",Vu=(r,e)=>{var t="$survey_"+e+"/"+r.id;return r.current_iteration&&r.current_iteration>0&&(t="$survey_"+e+"/"+r.id+"/"+r.current_iteration),t},bo=r=>((e,t)=>{var n=""+e+t.id;return t.current_iteration&&t.current_iteration>0&&(n=""+e+t.id+"_"+t.current_iteration),n})(nl,r),Yu=[Jn.Popover,Jn.Widget,Jn.API],Ju={ignoreConditions:!1,ignoreDelay:!1,displayType:Is.Popover};class Xs{constructor(){this.Mi={},this.Mi={}}on(e,t){return this.Mi[e]||(this.Mi[e]=[]),this.Mi[e].push(t),()=>{this.Mi[e]=this.Mi[e].filter(n=>n!==t)}}emit(e,t){for(var n of this.Mi[e]||[])n(t);for(var s of this.Mi["*"]||[])s(e,t)}}function wt(r,e,t){if($(r))return!1;switch(t){case"exact":return r===e;case"contains":var n=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/_/g,".").replace(/%/g,".*");return new RegExp(n,"i").test(r);case"regex":try{return new RegExp(e).test(r)}catch{return!1}default:return!1}}class Zu{constructor(e){this.Ai=new Xs,this.ji=(t,n)=>this.Di(t,n)&&this.Li(t,n)&&this.Ni(t,n)&&this.Ui(t,n),this.Di=(t,n)=>n==null||!n.event||(t==null?void 0:t.event)===(n==null?void 0:n.event),this._instance=e,this.zi=new Set,this.Hi=new Set}init(){var e;if(!b((e=this._instance)==null?void 0:e._addCaptureHook)){var t;(t=this._instance)==null||t._addCaptureHook((n,s)=>{this.on(n,s)})}}register(e){var t,n;if(!b((t=this._instance)==null?void 0:t._addCaptureHook)&&(e.forEach(o=>{var a,l;(a=this.Hi)==null||a.add(o),(l=o.steps)==null||l.forEach(c=>{var u;(u=this.zi)==null||u.add((c==null?void 0:c.event)||"")})}),(n=this._instance)!=null&&n.autocapture)){var s,i=new Set;e.forEach(o=>{var a;(a=o.steps)==null||a.forEach(l=>{l!=null&&l.selector&&i.add(l==null?void 0:l.selector)})}),(s=this._instance)==null||s.autocapture.setElementSelectors(i)}}on(e,t){var n;t!=null&&e.length!=0&&(this.zi.has(e)||this.zi.has(t==null?void 0:t.event))&&this.Hi&&((n=this.Hi)==null?void 0:n.size)>0&&this.Hi.forEach(s=>{this.Bi(t,s)&&this.Ai.emit("actionCaptured",s.name)})}qi(e){this.onAction("actionCaptured",t=>e(t))}Bi(e,t){if((t==null?void 0:t.steps)==null)return!1;for(var n of t.steps)if(this.ji(e,n))return!0;return!1}onAction(e,t){return this.Ai.on(e,t)}Li(e,t){if(t!=null&&t.url){var n,s=e==null||(n=e.properties)==null?void 0:n.$current_url;if(!s||typeof s!="string"||!wt(s,t.url,t.url_matching||"contains"))return!1}return!0}Ni(e,t){return!!this.Wi(e,t)&&!!this.Gi(e,t)&&!!this.Vi(e,t)}Wi(e,t){var n;if(t==null||!t.href)return!0;var s=this.Ji(e);if(s.length>0)return s.some(a=>wt(a.href,t.href,t.href_matching||"exact"));var i,o=(e==null||(n=e.properties)==null?void 0:n.$elements_chain)||"";return!!o&&wt((i=o.match(/(?::|")href="(.*?)"/))?i[1]:"",t.href,t.href_matching||"exact")}Gi(e,t){var n;if(t==null||!t.text)return!0;var s=this.Ji(e);if(s.length>0)return s.some(c=>wt(c.text,t.text,t.text_matching||"exact")||wt(c.$el_text,t.text,t.text_matching||"exact"));var i,o,a,l=(e==null||(n=e.properties)==null?void 0:n.$elements_chain)||"";return!!l&&(i=function(c){for(var u,d=[],p=/(?::|")text="(.*?)"/g;!$(u=p.exec(c));)d.includes(u[1])||d.push(u[1]);return d}(l),o=t.text,a=t.text_matching||"exact",i.some(c=>wt(c,o,a)))}Vi(e,t){var n,s;if(t==null||!t.selector)return!0;var i=e==null||(n=e.properties)==null?void 0:n.$element_selectors;if(i!=null&&i.includes(t.selector))return!0;var o=(e==null||(s=e.properties)==null?void 0:s.$elements_chain)||"";if(t.selector_regex&&o)try{return new RegExp(t.selector_regex).test(o)}catch{return!1}return!1}Ji(e){var t;return(e==null||(t=e.properties)==null?void 0:t.$elements)==null?[]:e==null?void 0:e.properties.$elements}Ui(e,t){return t==null||!t.properties||t.properties.length===0||rl(t.properties.reduce((n,s)=>{var i=L(s.value)?s.value.map(String):s.value!=null?[String(s.value)]:[];return n[s.key]={values:i,operator:s.operator||"exact"},n},{}),e==null?void 0:e.properties)}}class Xu{constructor(e){this._instance=e,this.Ki=new Map,this.Yi=new Map,this.Xi=new Map}Qi(e,t){return!!e&&rl(e.propertyFilters,t==null?void 0:t.properties)}Zi(e,t){var n=new Map;return e.forEach(s=>{var i;(i=s.conditions)==null||(i=i[t])==null||(i=i.values)==null||i.forEach(o=>{if(o!=null&&o.name){var a=n.get(o.name)||[];a.push(s.id),n.set(o.name,a)}})}),n}te(e,t,n){var s=(n===Yt.Activation?this.Ki:this.Yi).get(e),i=[];return this.ie(o=>{i=o.filter(a=>s==null?void 0:s.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(c=>c.name===e);return this.Qi(l,t)})}register(e){var t;b((t=this._instance)==null?void 0:t._addCaptureHook)||(this.ee(e),this.re(e))}re(e){var t=e.filter(n=>{var s,i;return((s=n.conditions)==null?void 0:s.actions)&&((i=n.conditions)==null||(i=i.actions)==null||(i=i.values)==null?void 0:i.length)>0});t.length!==0&&(this.se==null&&(this.se=new Zu(this._instance),this.se.init(),this.se.qi(n=>{this.onAction(n)})),t.forEach(n=>{var s,i,o,a,l;n.conditions&&(s=n.conditions)!=null&&s.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.se)==null||a.register(n.conditions.actions.values),(l=n.conditions)==null||(l=l.actions)==null||(l=l.values)==null||l.forEach(c=>{if(c&&c.name){var u=this.Xi.get(c.name);u&&u.push(n.id),this.Xi.set(c.name,u||[n.id])}}))}))}ee(e){var t,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}),s=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||s.length!==0)&&((t=this._instance)==null||t._addCaptureHook((i,o)=>{this.onEvent(i,o)}),this.Ki=this.Zi(e,Yt.Activation),this.Yi=this.Zi(e,Yt.Cancellation))}onEvent(e,t){var n,s=this.ne(),i=this.oe(),o=this.ae(),a=((n=this._instance)==null||(n=n.persistence)==null?void 0:n.props[i])||[];if(o===e&&t&&a.length>0){var l,c;s.info("event matched, removing item from activated items",{event:e,eventPayload:t,existingActivatedItems:a});var u=(t==null||(l=t.properties)==null?void 0:l.$survey_id)||(t==null||(c=t.properties)==null?void 0:c.$product_tour_id);if(u){var d=a.indexOf(u);d>=0&&(a.splice(d,1),this.le(a))}}else{if(this.Yi.has(e)){var p=this.te(e,t,Yt.Cancellation);p.length>0&&(s.info("cancel event matched, cancelling items",{event:e,itemsToCancel:p.map(m=>m.id)}),p.forEach(m=>{var _=a.indexOf(m.id);_>=0&&a.splice(_,1),this.ue(m.id)}),this.le(a))}if(this.Ki.has(e)){s.info("event name matched",{event:e,eventPayload:t,items:this.Ki.get(e)});var h=this.te(e,t,Yt.Activation);this.le(a.concat(h.map(m=>m.id)||[]))}}}onAction(e){var t,n=this.oe(),s=((t=this._instance)==null||(t=t.persistence)==null?void 0:t.props[n])||[];this.Xi.has(e)&&this.le(s.concat(this.Xi.get(e)||[]))}le(e){var t,n=this.ne(),s=this.oe(),i=[...new Set(e)].filter(o=>!this.he(o));n.info("updating activated items",{activatedItems:i}),(t=this._instance)==null||(t=t.persistence)==null||t.register({[s]:i})}getActivatedIds(){var e,t=this.oe(),n=(e=this._instance)==null||(e=e.persistence)==null?void 0:e.props[t];return n||[]}getEventToItemsMap(){return this.Ki}de(){return this.se}}class Qu extends Xu{constructor(e){super(e)}oe(){return"$surveys_activated"}ae(){return nr.SHOWN}ie(e){var t;(t=this._instance)==null||t.getSurveys(e)}ue(e){var t;(t=this._instance)==null||t.cancelPendingSurvey(e)}ne(){return B}he(){return!1}getSurveys(){return this.getActivatedIds()}getEventToSurveys(){return this.getEventToItemsMap()}}class ed{constructor(e){this.ve=void 0,this._surveyManager=null,this.ce=!1,this.fe=[],this.pe=null,this._instance=e,this._surveyEventReceiver=null}onRemoteConfig(e){if(!this._instance.config.disable_surveys){var t=e.surveys;if($(t))return B.warn("Flags not loaded yet. Not loading surveys.");var n=L(t);this.ve=n?t.length>0:t,B.info("flags response received, isSurveysEnabled: "+this.ve),this.loadIfEnabled()}}reset(){localStorage.removeItem("lastSeenSurveyDate");for(var e=[],t=0;tlocalStorage.removeItem(s))}loadIfEnabled(){if(!this._surveyManager)if(this.ce)B.info("Already initializing surveys, skipping...");else if(this._instance.config.disable_surveys)B.info("Disabled. Not loading surveys.");else if(this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut())B.info("Not loading surveys in cookieless mode without consent.");else{var e=C==null?void 0:C.__PosthogExtensions__;if(e){if(!b(this.ve)||this._instance.config.advanced_enable_surveys){var t=this.ve||this._instance.config.advanced_enable_surveys;this.ce=!0;try{var n=e.generateSurveys;if(n)return void this._e(n,t);var s=e.loadExternalDependency;if(!s)return void this.ge("PostHog loadExternalDependency extension not found.");s(this._instance,"surveys",i=>{i||!e.generateSurveys?this.ge("Could not load surveys script",i):this._e(e.generateSurveys,t)})}catch(i){throw this.ge("Error initializing surveys",i),i}finally{this.ce=!1}}}else B.error("PostHog Extensions not found.")}}_e(e,t){this._surveyManager=e(this._instance,t),this._surveyEventReceiver=new Qu(this._instance),B.info("Surveys loaded successfully"),this.me({isLoaded:!0})}ge(e,t){B.error(e,t),this.me({isLoaded:!1,error:e})}onSurveysLoaded(e){return this.fe.push(e),this._surveyManager&&this.me({isLoaded:!0}),()=>{this.fe=this.fe.filter(t=>t!==e)}}getSurveys(e,t){if(t===void 0&&(t=!1),this._instance.config.disable_surveys)return B.info("Disabled. Not loading surveys."),e([]);var n,s=this._instance.get_property(hs);if(s&&!t)return e(s,{isLoaded:!0});typeof Promise<"u"&&this.pe?this.pe.then(i=>{var{surveys:o,context:a}=i;return e(o,a)}):(typeof Promise<"u"&&(this.pe=new Promise(i=>{n=i})),this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/surveys/?token="+this._instance.config.token),method:"GET",timeout:this._instance.config.surveys_request_timeout_ms,callback:i=>{var o;this.pe=null;var a=i.statusCode;if(a!==200||!i.json){var l="Surveys API could not be loaded, status: "+a;B.error(l);var c={isLoaded:!1,error:l};return e([],c),void(n==null||n({surveys:[],context:c}))}var u,d=i.json.surveys||[],p=d.filter(m=>function(_){return!(!_.start_date||_.end_date)}(m)&&(function(_){var v;return!((v=_.conditions)==null||(v=v.events)==null||(v=v.values)==null||!v.length)}(m)||function(_){var v;return!((v=_.conditions)==null||(v=v.actions)==null||(v=v.values)==null||!v.length)}(m)));p.length>0&&((u=this._surveyEventReceiver)==null||u.register(p)),(o=this._instance.persistence)==null||o.register({[hs]:d});var h={isLoaded:!0};e(d,h),n==null||n({surveys:d,context:h})}}))}me(e){for(var t of this.fe)try{if(!e.isLoaded)return t([],e);this.getSurveys(t)}catch(n){B.error("Error in survey callback",n)}}getActiveMatchingSurveys(e,t){if(t===void 0&&(t=!1),!$(this._surveyManager))return this._surveyManager.getActiveMatchingSurveys(e,t);B.warn("init was not called")}be(e){var t=null;return this.getSurveys(n=>{var s;t=(s=n.find(i=>i.id===e))!==null&&s!==void 0?s:null}),t}ye(e){if($(this._surveyManager))return{eligible:!1,reason:"SDK is not enabled or survey functionality is not yet loaded"};var t=typeof e=="string"?this.be(e):e;return t?this._surveyManager.checkSurveyEligibility(t):{eligible:!1,reason:"Survey not found"}}canRenderSurvey(e){if($(this._surveyManager))return B.warn("init was not called"),{visible:!1,disabledReason:"SDK is not enabled or survey functionality is not yet loaded"};var t=this.ye(e);return{visible:t.eligible,disabledReason:t.reason}}canRenderSurveyAsync(e,t){return $(this._surveyManager)?(B.warn("init was not called"),Promise.resolve({visible:!1,disabledReason:"SDK is not enabled or survey functionality is not yet loaded"})):new Promise(n=>{this.getSurveys(s=>{var i,o=(i=s.find(l=>l.id===e))!==null&&i!==void 0?i:null;if(o){var a=this.ye(o);n({visible:a.eligible,disabledReason:a.reason})}else n({visible:!1,disabledReason:"Survey not found"})},t)})}renderSurvey(e,t,n){var s;if($(this._surveyManager))B.warn("init was not called");else{var i=typeof e=="string"?this.be(e):e;if(i!=null&&i.id)if(Yu.includes(i.type)){var o=y==null?void 0:y.querySelector(t);if(o)return(s=i.appearance)!=null&&s.surveyPopupDelaySeconds?(B.info("Rendering survey "+i.id+" with delay of "+i.appearance.surveyPopupDelaySeconds+" seconds"),void setTimeout(()=>{var a,l;B.info("Rendering survey "+i.id+" with delay of "+((a=i.appearance)==null?void 0:a.surveyPopupDelaySeconds)+" seconds"),(l=this._surveyManager)==null||l.renderSurvey(i,o,n),B.info("Survey "+i.id+" rendered")},1e3*i.appearance.surveyPopupDelaySeconds)):void this._surveyManager.renderSurvey(i,o,n);B.warn("Survey element not found")}else B.warn("Surveys of type "+i.type+" cannot be rendered in the app");else B.warn("Survey not found")}}displaySurvey(e,t){var n;if($(this._surveyManager))B.warn("init was not called");else{var s=this.be(e);if(s){var i=s;if((n=s.appearance)!=null&&n.surveyPopupDelaySeconds&&t.ignoreDelay&&(i=S({},s,{appearance:S({},s.appearance,{surveyPopupDelaySeconds:0})})),t.displayType!==Is.Popover&&t.initialResponses&&B.warn("initialResponses is only supported for popover surveys. prefill will not be applied."),t.ignoreConditions===!1){var o=this.canRenderSurvey(s);if(!o.visible)return void B.warn("Survey is not eligible to be displayed: ",o.disabledReason)}t.displayType!==Is.Inline?this._surveyManager.handlePopoverSurvey(i,t):this.renderSurvey(i,t.selector,t.properties)}else B.warn("Survey not found")}}cancelPendingSurvey(e){$(this._surveyManager)?B.warn("init was not called"):this._surveyManager.cancelSurvey(e)}handlePageUnload(){var e;(e=this._surveyManager)==null||e.handlePageUnload()}}var _e=W("[Conversations]");class td{constructor(e){this.we=void 0,this._conversationsManager=null,this.xe=!1,this.$e=null,this._instance=e}onRemoteConfig(e){if(!this._instance.config.disable_conversations){var t=e.conversations;$(t)||(We(t)?this.we=t:(this.we=t.enabled,this.$e=t),this.loadIfEnabled())}}reset(){var e;(e=this._conversationsManager)==null||e.reset(),this._conversationsManager=null,this.we=void 0,this.$e=null}loadIfEnabled(){if(!(this._conversationsManager||this.xe||this._instance.config.disable_conversations||ba(this._instance.config)||this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut())){var e=C==null?void 0:C.__PosthogExtensions__;if(e&&!b(this.we)&&this.we)if(this.$e&&this.$e.token){this.xe=!0;try{var t=e.initConversations;if(t)return this.Ee(t),void(this.xe=!1);var n=e.loadExternalDependency;if(!n)return void this.Se("PostHog loadExternalDependency extension not found.");n(this._instance,"conversations",s=>{s||!e.initConversations?this.Se("Could not load conversations script",s):this.Ee(e.initConversations),this.xe=!1})}catch(s){this.Se("Error initializing conversations",s),this.xe=!1}}else _e.error("Conversations enabled but missing token in remote config.")}}Ee(e){if(this.$e)try{this._conversationsManager=e(this.$e,this._instance),_e.info("Conversations loaded successfully")}catch(t){this.Se("Error completing conversations initialization",t)}else _e.error("Cannot complete initialization: remote config is null")}Se(e,t){_e.error(e,t),this._conversationsManager=null,this.xe=!1}show(){this._conversationsManager?this._conversationsManager.show():_e.warn("Conversations not loaded yet.")}hide(){this._conversationsManager&&this._conversationsManager.hide()}isAvailable(){return this.we===!0&&!Ie(this._conversationsManager)}isVisible(){var e,t;return(e=(t=this._conversationsManager)==null?void 0:t.isVisible())!==null&&e!==void 0&&e}sendMessage(e,t,n){var s=this;return Ne(function*(){return s._conversationsManager?s._conversationsManager.sendMessage(e,t,n):(_e.warn("Conversations not available yet."),null)})()}getMessages(e,t){var n=this;return Ne(function*(){return n._conversationsManager?n._conversationsManager.getMessages(e,t):(_e.warn("Conversations not available yet."),null)})()}markAsRead(e){var t=this;return Ne(function*(){return t._conversationsManager?t._conversationsManager.markAsRead(e):(_e.warn("Conversations not available yet."),null)})()}getTickets(e){var t=this;return Ne(function*(){return t._conversationsManager?t._conversationsManager.getTickets(e):(_e.warn("Conversations not available yet."),null)})()}requestRestoreLink(e){var t=this;return Ne(function*(){return t._conversationsManager?t._conversationsManager.requestRestoreLink(e):(_e.warn("Conversations not available yet."),null)})()}restoreFromToken(e){var t=this;return Ne(function*(){return t._conversationsManager?t._conversationsManager.restoreFromToken(e):(_e.warn("Conversations not available yet."),null)})()}restoreFromUrlToken(){var e=this;return Ne(function*(){return e._conversationsManager?e._conversationsManager.restoreFromUrlToken():(_e.warn("Conversations not available yet."),null)})()}getCurrentTicketId(){var e,t;return(e=(t=this._conversationsManager)==null?void 0:t.getCurrentTicketId())!==null&&e!==void 0?e:null}getWidgetSessionId(){var e,t;return(e=(t=this._conversationsManager)==null?void 0:t.getWidgetSessionId())!==null&&e!==void 0?e:null}}class rd{constructor(e){var t;this.ke=!1,this.Pe=!1,this._instance=e,this._instance&&(t=this._instance.config.logs)!=null&&t.captureConsoleLogs&&(this.ke=!0)}onRemoteConfig(e){var t,n=(t=e.logs)==null?void 0:t.captureConsoleLogs;!$(n)&&n&&(this.ke=!0,this.loadIfEnabled())}reset(){}loadIfEnabled(){if(this.ke&&!this.Pe){var e=W("[logs]"),t=C==null?void 0:C.__PosthogExtensions__;if(t){var n=t.loadExternalDependency;n?n(this._instance,"logs",s=>{var i;s||(i=t.logs)==null||!i.initializeLogs?e.error("Could not load logs script",s):(t.logs.initializeLogs(this._instance),this.Pe=!0)}):e.error("PostHog loadExternalDependency extension not found.")}else e.error("PostHog Extensions not found.")}}}var Eo=W("[RateLimiter]");class nd{constructor(e){this.serverLimits={},this.lastEventRateLimited=!1,this.checkForLimiting=t=>{var n=t.text;if(n&&n.length)try{(JSON.parse(n).quota_limited||[]).forEach(s=>{Eo.info((s||"events")+" is quota limited."),this.serverLimits[s]=new Date().getTime()+6e4})}catch(s){return void Eo.warn('could not rate limit - continuing. Error: "'+(s==null?void 0:s.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 t,n,s;e===void 0&&(e=!1);var{captureEventsBurstLimit:i,captureEventsPerSecond:o}=this,a=new Date().getTime(),l=(t=(n=this.instance.persistence)==null?void 0:n.get_property(_s))!==null&&t!==void 0?t:{tokens:i,last:a};l.tokens+=(a-l.last)/1e3*o,l.last=a,l.tokens>i&&(l.tokens=i);var c=l.tokens<1;return c||e||(l.tokens=Math.max(0,l.tokens-1)),!c||this.lastEventRateLimited||e||this.instance.capture("$$client_ingestion_warning",{$$client_ingestion_warning_message:"posthog-js client rate limited. Config is set to "+o+" events per second and "+i+" events burst limit."},{skip_client_rate_limiting:!0}),this.lastEventRateLimited=c,(s=this.instance.persistence)==null||s.set_property(_s,l),{isRateLimited:c,remainingTokens:l.tokens}}isServerRateLimited(e){var t=this.serverLimits[e||"events"]||!1;return t!==!1&&new Date().getTime()e(this.remoteConfig)):e()}Ie(e){this._instance._send_request({method:"GET",url:this._instance.requestRouter.endpointFor("assets","/array/"+this._instance.config.token+"/config"),callback:t=>{e(t.json)}})}load(){try{if(this.remoteConfig)return Jt.info("Using preloaded remote config",this.remoteConfig),this.Ce(this.remoteConfig),void this.Re();if(this._instance.M())return void Jt.warn("Remote config is disabled. Falling back to local config.");this.Te(e=>{if(!e)return Jt.info("No config found after loading remote JS config. Falling back to JSON."),void this.Ie(t=>{this.Ce(t),this.Re()});this.Ce(e),this.Re()})}catch(e){Jt.error("Error loading remote config",e)}}stop(){this.Fe&&(clearInterval(this.Fe),this.Fe=void 0)}refresh(){this._instance.M()||(y==null?void 0:y.visibilityState)==="hidden"||this._instance.featureFlags.reloadFeatureFlags()}Re(){this.Fe||(this.Fe=setInterval(()=>{this.refresh()},3e5))}Ce(e){e||Jt.error("Failed to fetch remote config from PostHog."),this._instance.Ce(e??{}),(e==null?void 0:e.hasFeatureFlags)!==!1&&(this._instance.config.advanced_disable_feature_flags_on_first_load||this._instance.featureFlags.ensureFlagsLoaded())}}var ks=3e3;class sd{constructor(e,t){this.Oe=!0,this.Me=[],this.Ae=Fe((t==null?void 0:t.flush_interval_ms)||ks,250,5e3,E.createLogger("flush interval"),ks),this.je=e}enqueue(e){this.Me.push(e),this.De||this.Le()}unload(){this.Ne();var e=this.Me.length>0?this.Ue():{},t=Object.values(e);[...t.filter(n=>n.url.indexOf("/e")===0),...t.filter(n=>n.url.indexOf("/e")!==0)].map(n=>{this.je(S({},n,{transport:"sendBeacon"}))})}enable(){this.Oe=!1,this.Le()}Le(){var e=this;this.Oe||(this.De=setTimeout(()=>{if(this.Ne(),this.Me.length>0){var t=this.Ue(),n=function(){var i=t[s],o=new Date().getTime();i.data&&L(i.data)&&j(i.data,a=>{a.offset=Math.abs(a.timestamp-o),delete a.timestamp}),e.je(i)};for(var s in t)n()}},this.Ae))}Ne(){clearTimeout(this.De),this.De=void 0}Ue(){var e={};return j(this.Me,t=>{var n,s=t,i=(s?s.batchKey:null)||s.url;b(e[i])&&(e[i]=S({},s,{data:[]})),(n=e[i].data)==null||n.push(s.data)}),this.Me=[],e}}var id=["retriesPerformedSoFar"];class od{constructor(e){this.ze=!1,this.He=3e3,this.Me=[],this._instance=e,this.Me=[],this.Be=!0,!b(f)&&"onLine"in f.navigator&&(this.Be=f.navigator.onLine,this.qe=()=>{this.Be=!0,this.Lt()},this.We=()=>{this.Be=!1},V(f,"online",this.qe),V(f,"offline",this.We))}get length(){return this.Me.length}retriableRequest(e){var{retriesPerformedSoFar:t}=e,n=Zo(e,id);St(t)&&(n.url=Qr(n.url,{retry_count:t})),this._instance._send_request(S({},n,{callback:s=>{s.statusCode!==200&&(s.statusCode<400||s.statusCode>=500)&&(t??0)<10?this.Ge(S({retriesPerformedSoFar:t},n)):n.callback==null||n.callback(s)}}))}Ge(e){var t=e.retriesPerformedSoFar||0;e.retriesPerformedSoFar=t+1;var n=function(o){var a=3e3*Math.pow(2,o),l=a/2,c=Math.min(18e5,a),u=(Math.random()-.5)*(c-l);return Math.ceil(c+u)}(t),s=Date.now()+n;this.Me.push({retryAt:s,requestOptions:e});var i="Enqueued failed request for retry in "+n;navigator.onLine||(i+=" (Browser is offline)"),E.warn(i),this.ze||(this.ze=!0,this.Ve())}Ve(){if(this.Je&&clearTimeout(this.Je),this.Me.length===0)return this.ze=!1,void(this.Je=void 0);this.Je=setTimeout(()=>{this.Be&&this.Me.length>0&&this.Lt(),this.Ve()},this.He)}Lt(){var e=Date.now(),t=[],n=this.Me.filter(i=>i.retryAt0)for(var{requestOptions:s}of n)this.retriableRequest(s)}unload(){for(var{requestOptions:e}of(this.Je&&(clearTimeout(this.Je),this.Je=void 0),this.ze=!1,b(f)||(this.qe&&(f.removeEventListener("online",this.qe),this.qe=void 0),this.We&&(f.removeEventListener("offline",this.We),this.We=void 0)),this.Me))try{this._instance._send_request(S({},e,{transport:"sendBeacon"}))}catch(t){E.error(t)}this.Me=[]}}class ad{constructor(e){this.Ke=()=>{var t,n,s,i;this.Ye||(this.Ye={});var o=this.scrollElement(),a=this.scrollY(),l=o?Math.max(0,o.scrollHeight-o.clientHeight):0,c=a+((o==null?void 0:o.clientHeight)||0),u=(o==null?void 0:o.scrollHeight)||0;this.Ye.lastScrollY=Math.ceil(a),this.Ye.maxScrollY=Math.max(a,(t=this.Ye.maxScrollY)!==null&&t!==void 0?t:0),this.Ye.maxScrollHeight=Math.max(l,(n=this.Ye.maxScrollHeight)!==null&&n!==void 0?n:0),this.Ye.lastContentY=c,this.Ye.maxContentY=Math.max(c,(s=this.Ye.maxContentY)!==null&&s!==void 0?s:0),this.Ye.maxContentHeight=Math.max(u,(i=this.Ye.maxContentHeight)!==null&&i!==void 0?i:0)},this._instance=e}getContext(){return this.Ye}resetContext(){var e=this.Ye;return setTimeout(this.Ke,0),e}startMeasuringScrollPosition(){V(f,"scroll",this.Ke,{capture:!0}),V(f,"scrollend",this.Ke,{capture:!0}),V(f,"resize",this.Ke)}scrollElement(){if(!this._instance.config.scroll_root_selector)return f==null?void 0:f.document.documentElement;var e=L(this._instance.config.scroll_root_selector)?this._instance.config.scroll_root_selector:[this._instance.config.scroll_root_selector];for(var t of e){var n=f==null?void 0:f.document.querySelector(t);if(n)return n}}scrollY(){if(this._instance.config.scroll_root_selector){var e=this.scrollElement();return e&&e.scrollTop||0}return f&&(f.scrollY||f.pageYOffset||f.document.documentElement.scrollTop)||0}scrollX(){if(this._instance.config.scroll_root_selector){var e=this.scrollElement();return e&&e.scrollLeft||0}return f&&(f.scrollX||f.pageXOffset||f.document.documentElement.scrollLeft)||0}}var ld=r=>Ka(r==null?void 0:r.config.mask_personal_data_properties,r==null?void 0:r.config.custom_personal_data_properties);class So{constructor(e,t,n,s){this.Xe=i=>{var o=this.Qe();if(!o||o.sessionId!==i){var a={sessionId:i,props:this.Ze(this._instance)};this.tr.register({[ms]:a})}},this._instance=e,this.ir=t,this.tr=n,this.Ze=s||ld,this.ir.onSessionId(this.Xe)}Qe(){return this.tr.props[ms]}getSetOnceProps(){var e,t=(e=this.Qe())==null?void 0:e.props;return t?"r"in t?Va(t):{$referring_domain:t.referringDomain,$pathname:t.initialPathName,utm_source:t.utm_source,utm_campaign:t.utm_campaign,utm_medium:t.utm_medium,utm_content:t.utm_content,utm_term:t.utm_term}:{}}getSessionProps(){var e={};return j(qs(this.getSetOnceProps()),(t,n)=>{n==="$current_url"&&(n="url"),e["$session_entry_"+ss(n)]=t}),e}}var Xn=W("[SessionId]");class Io{on(e,t){return this.er.on(e,t)}constructor(e,t,n){var s;if(this.rr=[],this.sr=void 0,this.er=new Xs,this.nr=(u,d)=>!(!St(u)||!St(d))&&Math.abs(u-d)>this.sessionTimeoutMs,!e.persistence)throw new Error("SessionIdManager requires a PostHogPersistence instance");if(e.config.cookieless_mode==="always")throw new Error('SessionIdManager cannot be used with cookieless_mode="always"');this.R=e.config,this.tr=e.persistence,this.ar=void 0,this.lr=void 0,this._sessionStartTimestamp=null,this._sessionActivityTimestamp=null,this.ur=t||rt,this.hr=n||rt;var i=this.R.persistence_name||this.R.token,o=this.R.session_idle_timeout_seconds||1800;if(this._sessionTimeoutMs=1e3*Fe(o,60,36e3,Xn.createLogger("session_idle_timeout_seconds"),1800),e.register({$configured_session_timeout_ms:this._sessionTimeoutMs}),this.dr(),this.vr="ph_"+i+"_window_id",this.cr="ph_"+i+"_primary_window_exists",this.pr()){var a=X.W(this.vr),l=X.W(this.cr);a&&!l?this.ar=a:X.V(this.vr),X.G(this.cr,!0)}if((s=this.R.bootstrap)!=null&&s.sessionID)try{var c=(u=>{var d=u.replace(/-/g,"");if(d.length!==32)throw new Error("Not a valid UUID");if(d[12]!=="7")throw new Error("Not a UUIDv7");return parseInt(d.substring(0,12),16)})(this.R.bootstrap.sessionID);this._r(this.R.bootstrap.sessionID,new Date().getTime(),c)}catch(u){Xn.error("Invalid sessionID in bootstrap",u)}this.gr()}get sessionTimeoutMs(){return this._sessionTimeoutMs}onSessionId(e){return b(this.rr)&&(this.rr=[]),this.rr.push(e),this.lr&&e(this.lr,this.ar),()=>{this.rr=this.rr.filter(t=>t!==e)}}pr(){return this.R.persistence!=="memory"&&!this.tr.ki&&X.H()}mr(e){e!==this.ar&&(this.ar=e,this.pr()&&X.G(this.vr,e))}br(){return this.ar?this.ar:this.pr()?X.W(this.vr):null}_r(e,t,n){e===this.lr&&t===this._sessionActivityTimestamp&&n===this._sessionStartTimestamp||(this._sessionStartTimestamp=n,this._sessionActivityTimestamp=t,this.lr=e,this.tr.register({[Wr]:[t,e,n]}))}yr(){var e=this.tr.props[Wr];return L(e)&&e.length===2&&e.push(e[0]),e||[0,null,0]}resetSessionId(){this._r(null,null,null)}destroy(){clearTimeout(this.wr),this.wr=void 0,this.sr&&f&&(f.removeEventListener("beforeunload",this.sr,{capture:!1}),this.sr=void 0),this.rr=[]}gr(){this.sr=()=>{this.pr()&&X.V(this.cr)},V(f,"beforeunload",this.sr,{capture:!1})}checkAndGetSessionAndWindowId(e,t){if(e===void 0&&(e=!1),t===void 0&&(t=null),this.R.cookieless_mode==="always")throw new Error('checkAndGetSessionAndWindowId should not be called with cookieless_mode="always"');var n=t||new Date().getTime(),[s,i,o]=this.yr(),a=this.br(),l=St(o)&&Math.abs(n-o)>864e5,c=!1,u=!i,d=!u&&!e&&this.nr(n,s);u||d||l?(i=this.ur(),a=this.hr(),Xn.info("new session ID generated",{sessionId:i,windowId:a,changeReason:{noSessionId:u,activityTimeout:d,sessionPastMaximumLength:l}}),o=n,c=!0):a||(a=this.hr(),c=!0);var p=St(s)&&e&&!l?s:n,h=St(o)?o:new Date().getTime();return this.mr(a),this._r(i,p,h),e||this.dr(),c&&this.rr.forEach(m=>m(i,a,c?{noSessionId:u,activityTimeout:d,sessionPastMaximumLength:l}:void 0)),{sessionId:i,windowId:a,sessionStartTimestamp:h,changeReason:c?{noSessionId:u,activityTimeout:d,sessionPastMaximumLength:l}:void 0,lastActivityTimestamp:s}}dr(){clearTimeout(this.wr),this.wr=setTimeout(()=>{var[e]=this.yr();if(this.nr(new Date().getTime(),e)){var t=this.lr;this.resetSessionId(),this.er.emit("forcedIdleReset",{idleSessionId:t})}},1.1*this.sessionTimeoutMs)}}var cd=["$set_once","$set"],Qe=W("[SiteApps]");class ud{constructor(e){this._instance=e,this.$r=[],this.apps={}}get isEnabled(){return!!this._instance.config.opt_in_site_apps}Er(e,t){if(t){var n=this.globalsForEvent(t);this.$r.push(n),this.$r.length>1e3&&(this.$r=this.$r.slice(10))}}get siteAppLoaders(){var e;return(e=C._POSTHOG_REMOTE_CONFIG)==null||(e=e[this._instance.config.token])==null?void 0:e.siteApps}init(){if(this.isEnabled){var e=this._instance._addCaptureHook(this.Er.bind(this));this.Sr=()=>{e(),this.$r=[],this.Sr=void 0}}}globalsForEvent(e){var t,n,s,i,o,a,l;if(!e)throw new Error("Event payload is required");var c={},u=this._instance.get_property("$groups")||[],d=this._instance.get_property("$stored_group_properties")||{};for(var[p,h]of Object.entries(d))c[p]={id:u[p],type:p,properties:h};var{$set_once:m,$set:_}=e;return{event:S({},Zo(e,cd),{properties:S({},e.properties,_?{$set:S({},(t=(n=e.properties)==null?void 0:n.$set)!==null&&t!==void 0?t:{},_)}:{},m?{$set_once:S({},(s=(i=e.properties)==null?void 0:i.$set_once)!==null&&s!==void 0?s:{},m)}:{}),elements_chain:(o=(a=e.properties)==null?void 0:a.$elements_chain)!==null&&o!==void 0?o:"",distinct_id:(l=e.properties)==null?void 0:l.distinct_id}),person:{properties:this._instance.get_property("$stored_person_properties")},groups:c}}setupSiteApp(e){var t=this.apps[e.id],n=()=>{var a;!t.errored&&this.$r.length&&(Qe.info("Processing "+this.$r.length+" events for site app with id "+e.id),this.$r.forEach(l=>t.processEvent==null?void 0:t.processEvent(l)),t.processedBuffer=!0),Object.values(this.apps).every(l=>l.processedBuffer||l.errored)&&((a=this.Sr)==null||a.call(this))},s=!1,i=a=>{t.errored=!a,t.loaded=!0,Qe.info("Site app with id "+e.id+" "+(a?"loaded":"errored")),s&&n()};try{var{processEvent:o}=e.init({posthog:this._instance,callback:a=>{i(a)}});o&&(t.processEvent=o),s=!0}catch(a){Qe.error("Error while initializing PostHog app with config id "+e.id,a),i(!1)}if(s&&t.loaded)try{n()}catch(a){Qe.error("Error while processing buffered events PostHog app with config id "+e.id,a),t.errored=!0}}kr(){var e=this.siteAppLoaders||[];for(var t of e)this.apps[t.id]={id:t.id,loaded:!1,errored:!1,processedBuffer:!1};for(var n of e)this.setupSiteApp(n)}Pr(e){if(Object.keys(this.apps).length!==0){var t=this.globalsForEvent(e);for(var n of Object.values(this.apps))try{n.processEvent==null||n.processEvent(t)}catch(s){Qe.error("Error while processing event "+e.event+" for site app "+n.id,s)}}}onRemoteConfig(e){var t,n,s,i=this;if((t=this.siteAppLoaders)!=null&&t.length)return this.isEnabled?(this.kr(),void this._instance.on("eventCaptured",c=>this.Pr(c))):void Qe.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.');if((n=this.Sr)==null||n.call(this),(s=e.siteApps)!=null&&s.length)if(this.isEnabled){var o=function(c){var u;C["__$$ph_site_app_"+c]=i._instance,(u=C.__PosthogExtensions__)==null||u.loadSiteApp==null||u.loadSiteApp(i._instance,l,d=>{if(d)return Qe.error("Error while initializing PostHog app with config id "+c,d)})};for(var{id:a,url:l}of e.siteApps)o(a)}else Qe.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.')}}var il=function(r,e){if(!r)return!1;var t=r.userAgent;if(t&&$i(t,e))return!0;try{var n=r==null?void 0:r.userAgentData;if(n!=null&&n.brands&&n.brands.some(s=>$i(s==null?void 0:s.brand,e)))return!0}catch{}return!!r.webdriver},sr=function(r){return r.US="us",r.EU="eu",r.CUSTOM="custom",r}({}),ko="i.posthog.com";class dd{constructor(e){this.Tr={},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,t=(e=this.instance.config.ui_host)==null?void 0:e.replace(/\/$/,"");return t||(t=this.apiHost.replace("."+ko,".posthog.com")),t==="https://app.posthog.com"?"https://us.posthog.com":t}get region(){return this.Tr[this.apiHost]||(/https:\/\/(app|us|us-assets)(\.i)?\.posthog\.com/i.test(this.apiHost)?this.Tr[this.apiHost]=sr.US:/https:\/\/(eu|eu-assets)(\.i)?\.posthog\.com/i.test(this.apiHost)?this.Tr[this.apiHost]=sr.EU:this.Tr[this.apiHost]=sr.CUSTOM),this.Tr[this.apiHost]}endpointFor(e,t){if(t===void 0&&(t=""),t&&(t=t[0]==="/"?t:"/"+t),e==="ui")return this.uiHost+t;if(e==="flags")return this.flagsApiHost+t;if(this.region===sr.CUSTOM)return this.apiHost+t;var n=ko+t;switch(e){case"assets":return"https://"+this.region+"-assets."+n;case"api":return"https://"+this.region+"."+n}}}var pd={icontains:(r,e)=>!!f&&e.href.toLowerCase().indexOf(r.toLowerCase())>-1,not_icontains:(r,e)=>!!f&&e.href.toLowerCase().indexOf(r.toLowerCase())===-1,regex:(r,e)=>!!f&&en(e.href,r),not_regex:(r,e)=>!!f&&!en(e.href,r),exact:(r,e)=>e.href===r,is_not:(r,e)=>e.href!==r};class ne{constructor(e){var t=this;this.getWebExperimentsAndEvaluateDisplayLogic=function(n){n===void 0&&(n=!1),t.getWebExperiments(s=>{ne.Ir("retrieved web experiments from the server"),t.Cr=new Map,s.forEach(i=>{if(i.feature_flag_key){var o;t.Cr&&(ne.Ir("setting flag key ",i.feature_flag_key," to web experiment ",i),(o=t.Cr)==null||o.set(i.feature_flag_key,i));var a=t._instance.getFeatureFlag(i.feature_flag_key);K(a)&&i.variants[a]&&t.Rr(i.name,a,i.variants[a].transforms)}else if(i.variants)for(var l in i.variants){var c=i.variants[l];ne.Fr(c)&&t.Rr(i.name,l,c.transforms)}})},n)},this._instance=e,this._instance.onFeatureFlags(n=>{this.onFeatureFlags(n)})}onFeatureFlags(e){if(this._is_bot())ne.Ir("Refusing to render web experiment since the viewer is a likely bot");else if(!this._instance.config.disable_web_experiments){if($(this.Cr))return this.Cr=new Map,this.loadIfEnabled(),void this.previewWebExperiment();ne.Ir("applying feature flags",e),e.forEach(t=>{var n;if(this.Cr&&(n=this.Cr)!=null&&n.has(t)){var s,i=this._instance.getFeatureFlag(t),o=(s=this.Cr)==null?void 0:s.get(t);i&&o!=null&&o.variants[i]&&this.Rr(o.name,i,o.variants[i].transforms)}})}}previewWebExperiment(){var e=ne.getWindowLocation();if(e!=null&&e.search){var t=Yr(e==null?void 0:e.search,"__experiment_id"),n=Yr(e==null?void 0:e.search,"__experiment_variant");t&&n&&(ne.Ir("previewing web experiments "+t+" && "+n),this.getWebExperiments(s=>{this.Or(parseInt(t),n,s)},!1,!0))}}loadIfEnabled(){this._instance.config.disable_web_experiments||this.getWebExperimentsAndEvaluateDisplayLogic()}getWebExperiments(e,t,n){if(this._instance.config.disable_web_experiments&&!n)return e([]);var s=this._instance.get_property("$web_experiments");if(s&&!t)return e(s);this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/web_experiments/?token="+this._instance.config.token),method:"GET",callback:i=>{if(i.statusCode!==200||!i.json)return e([]);var o=i.json.experiments||[];return e(o)}})}Or(e,t,n){var s=n.filter(i=>i.id===e);s&&s.length>0&&(ne.Ir("Previewing web experiment ["+s[0].name+"] with variant ["+t+"]"),this.Rr(s[0].name,t,s[0].variants[t].transforms))}static Fr(e){return!$(e.conditions)&&ne.Mr(e)&&ne.Ar(e)}static Mr(e){var t;if($(e.conditions)||$((t=e.conditions)==null?void 0:t.url))return!0;var n,s,i,o=ne.getWindowLocation();return!!o&&((n=e.conditions)==null||!n.url||pd[(s=(i=e.conditions)==null?void 0:i.urlMatchType)!==null&&s!==void 0?s:"icontains"](e.conditions.url,o))}static getWindowLocation(){return f==null?void 0:f.location}static Ar(e){var t;if($(e.conditions)||$((t=e.conditions)==null?void 0:t.utm))return!0;var n=Wa();if(n.utm_source){var s,i,o,a,l,c,u,d,p=(s=e.conditions)==null||(s=s.utm)==null||!s.utm_campaign||((i=e.conditions)==null||(i=i.utm)==null?void 0:i.utm_campaign)==n.utm_campaign,h=(o=e.conditions)==null||(o=o.utm)==null||!o.utm_source||((a=e.conditions)==null||(a=a.utm)==null?void 0:a.utm_source)==n.utm_source,m=(l=e.conditions)==null||(l=l.utm)==null||!l.utm_medium||((c=e.conditions)==null||(c=c.utm)==null?void 0:c.utm_medium)==n.utm_medium,_=(u=e.conditions)==null||(u=u.utm)==null||!u.utm_term||((d=e.conditions)==null||(d=d.utm)==null?void 0:d.utm_term)==n.utm_term;return p&&m&&_&&h}return!1}static Ir(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),s=1;s{if(s.selector){var i;ne.Ir("applying transform of variant "+t+" for experiment "+e+" ",s);var o=(i=document)==null?void 0:i.querySelectorAll(s.selector);o==null||o.forEach(a=>{var l=a;s.html&&(l.innerHTML=s.html),s.css&&l.setAttribute("style",s.css)})}}):ne.Ir("Control variants leave the page unmodified.")}_is_bot(){return fe&&this._instance?il(fe,this._instance.config.custom_blocked_useragents):void 0}}var fd=W("[PostHog ExternalIntegrations]"),hd={intercom:"intercom-integration",crispChat:"crisp-chat-integration"};class gd{constructor(e){this._instance=e}it(e,t){var n;(n=C.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,e,s=>{if(s)return fd.error("failed to load script",s);t()})}startIfEnabledOrStop(){var e=this,t=function(o){var a,l,c;!s||(a=C.__PosthogExtensions__)!=null&&(a=a.integrations)!=null&&a[o]||e.it(hd[o],()=>{var u;(u=C.__PosthogExtensions__)==null||(u=u.integrations)==null||(u=u[o])==null||u.start(e._instance)}),!s&&(l=C.__PosthogExtensions__)!=null&&(l=l.integrations)!=null&&l[o]&&((c=C.__PosthogExtensions__)==null||(c=c.integrations)==null||(c=c[o])==null||c.stop())};for(var[n,s]of Object.entries((i=this._instance.config.integrations)!==null&&i!==void 0?i:{})){var i;t(n)}}}W("[SessionRecording]");var Cs="[SessionRecording]",bt=W(Cs);class Co{get started(){var e;return!((e=this.jr)==null||!e.isStarted)}get status(){return this.jr?this.jr.status:this.Dr&&!this.Lr?"disabled":"lazy_loading"}constructor(e){if(this._forceAllowLocalhostNetworkCapture=!1,this.Dr=!1,this.Nr=!1,this.Ur=void 0,this._instance=e,!this._instance.sessionManager)throw bt.error("started without valid sessionManager"),new Error(Cs+" started without valid sessionManager. This is a bug.");if(this._instance.config.cookieless_mode==="always")throw new Error(Cs+' cannot be used with cookieless_mode="always"')}get Lr(){var e,t=!((e=this._instance.get_property(Cr))==null||!e.enabled),n=!this._instance.config.disable_session_recording,s=this._instance.config.disable_session_recording||this._instance.consent.isOptedOut();return f&&t&&n&&!s}startIfEnabledOrStop(e){var t;if(!this.Lr||(t=this.jr)==null||!t.isStarted){var n=!b(Object.assign)&&!b(Array.from);this.Lr&&n?(this.zr(e),bt.info("starting")):this.stopRecording()}}zr(e){var t,n,s;this.Lr&&(C!=null&&(t=C.__PosthogExtensions__)!=null&&(t=t.rrweb)!=null&&t.record&&(n=C.__PosthogExtensions__)!=null&&n.initSessionRecording?this.Hr(e):(s=C.__PosthogExtensions__)==null||s.loadExternalDependency==null||s.loadExternalDependency(this._instance,this.Br,i=>{if(i)return bt.error("could not load recorder",i);this.Hr(e)}))}stopRecording(){var e,t;(e=this.Ur)==null||e.call(this),this.Ur=void 0,(t=this.jr)==null||t.stop()}qr(){var e;(e=this._instance.persistence)==null||e.unregister(Ia)}Wr(e){if(this._instance.persistence){var t,n,s=this._instance.persistence,i=()=>{var o=e.sessionRecording===!1?void 0:e.sessionRecording,a=o==null?void 0:o.sampleRate,l=$(a)?null:parseFloat(a);$(l)&&this.qr();var c=o==null?void 0:o.minimumDurationMilliseconds;s.register({[Cr]:S({cache_timestamp:Date.now(),enabled:!!o},o,{networkPayloadCapture:S({capturePerformance:e.capturePerformance},o==null?void 0:o.networkPayloadCapture),canvasRecording:{enabled:o==null?void 0:o.recordCanvas,fps:o==null?void 0:o.canvasFps,quality:o==null?void 0:o.canvasQuality},sampleRate:l,minimumDurationMilliseconds:b(c)?null:c,endpoint:o==null?void 0:o.endpoint,triggerMatchType:o==null?void 0:o.triggerMatchType,masking:o==null?void 0:o.masking,urlTriggers:o==null?void 0:o.urlTriggers})})};i(),(t=this.Ur)==null||t.call(this),this.Ur=(n=this._instance.sessionManager)==null?void 0:n.onSessionId(i)}}onRemoteConfig(e){"sessionRecording"in e?e.sessionRecording!==!1?(this.Nr=!1,this.Wr(e),this.Dr=!0,this.startIfEnabledOrStop()):this.Dr=!0:bt.info("skipping remote config with no sessionRecording",e)}log(e,t){var n;t===void 0&&(t="log"),(n=this.jr)!=null&&n.log?this.jr.log(e,t):bt.warn("log called before recorder was ready")}get Br(){var e,t,n=(e=this._instance)==null||(e=e.persistence)==null?void 0:e.get_property(Cr);return(n==null||(t=n.scriptConfig)==null?void 0:t.script)||"lazy-recorder"}Gr(){var e,t=this._instance.get_property(Cr);if(!t)return!1;var n=(e=(typeof t=="object"?t:JSON.parse(t)).cache_timestamp)!==null&&e!==void 0?e:Date.now();return Date.now()-n<=3e5}Hr(e){var t,n;if((t=C.__PosthogExtensions__)==null||!t.initSessionRecording)throw Error("Called on script loaded before session recording is available");this.jr||(this.jr=(n=C.__PosthogExtensions__)==null?void 0:n.initSessionRecording(this._instance),this.jr._forceAllowLocalhostNetworkCapture=this._forceAllowLocalhostNetworkCapture),this.Gr()?this.jr.start(e):this.Nr||(this.Nr=!0,bt.info("persisted remote config is stale, requesting fresh config before starting"),new sl(this._instance).load())}onRRwebEmit(e){var t;(t=this.jr)==null||t.onRRwebEmit==null||t.onRRwebEmit(e)}overrideLinkedFlag(){var e,t;this.jr||(t=this._instance.persistence)==null||t.register({$replay_override_linked_flag:!0}),(e=this.jr)==null||e.overrideLinkedFlag()}overrideSampling(){var e,t;this.jr||(t=this._instance.persistence)==null||t.register({$replay_override_sampling:!0}),(e=this.jr)==null||e.overrideSampling()}overrideTrigger(e){var t,n;this.jr||(n=this._instance.persistence)==null||n.register({[e==="url"?"$replay_override_url_trigger":"$replay_override_event_trigger"]:!0}),(t=this.jr)==null||t.overrideTrigger(e)}get sdkDebugProperties(){var e;return((e=this.jr)==null?void 0:e.sdkDebugProperties)||{$recording_status:this.status}}tryAddCustomEvent(e,t){var n;return!((n=this.jr)==null||!n.tryAddCustomEvent(e,t))}}var or={},Qn=0,xs=()=>{},It="posthog",ol=!Mu&&(ce==null?void 0:ce.indexOf("MSIE"))===-1&&(ce==null?void 0:ce.indexOf("Mozilla"))===-1,xo=r=>{var e;return S({api_host:"https://us.i.posthog.com",flags_api_host:null,ui_host:null,token:"",autocapture:!0,cross_subdomain_cookie:Bc(y==null?void 0:y.location),persistence:"localStorage+cookie",persistence_name:"",cookie_persisted_properties:[],loaded:xs,save_campaign_params:!0,custom_campaign_params:[],custom_blocked_useragents:[],save_referrer:!0,capture_pageleave:"if_capture_pageview",defaults:r??"unset",__preview_deferred_init_extensions:!1,debug:Q&&K(Q==null?void 0:Q.search)&&Q.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,disable_external_dependency_loading:!1,enable_recording_console_log:void 0,secure_cookie:(f==null||(e=f.location)==null?void 0:e.protocol)==="https:",ip:!1,opt_out_capturing_by_default:!1,opt_out_persistence_by_default:!1,opt_out_useragent_filter:!1,opt_out_capturing_persistence_type:"localStorage",consent_persistence_name:null,opt_out_capturing_cookie_prefix:null,opt_in_site_apps:!1,property_denylist:[],respect_dnt:!1,sanitize_properties:null,request_headers:{},request_batching:!0,properties_string_max_length:65535,mask_all_element_attributes:!1,mask_all_text:!1,mask_personal_data_properties:!1,custom_personal_data_properties:[],advanced_disable_flags:!1,advanced_disable_decide:!1,advanced_disable_feature_flags:!1,advanced_disable_feature_flags_on_first_load:!1,advanced_only_evaluate_survey_feature_flags:!1,advanced_enable_surveys:!1,advanced_disable_toolbar_metrics:!1,feature_flag_request_timeout_ms:3e3,surveys_request_timeout_ms:1e4,on_request_error:t=>{var n="Bad HTTP status: "+t.statusCode+" "+t.text;E.error(n)},get_device_id:t=>t,capture_performance:void 0,name:"posthog",bootstrap:{},disable_compression:!1,session_idle_timeout_seconds:1800,person_profiles:"identified_only",before_send:void 0,request_queue_config:{flush_interval_ms:ks},error_tracking:{},_onCapture:xs,__preview_eager_load_replay:!1},(t=>({rageclick:!(t&&t>="2025-11-30")||{content_ignorelist:!0},capture_pageview:!(t&&t>="2025-05-24")||"history_change",session_recording:t&&t>="2025-11-30"?{strictMinimumDuration:!0}:{},external_scripts_inject_target:t&&t>="2026-01-30"?"head":"body",internal_or_test_user_hostname:t&&t>="2026-01-30"?/^(localhost|127\.0\.0\.1)$/:void 0}))(r))},To=r=>{var e={};b(r.process_person)||(e.person_profiles=r.process_person),b(r.xhr_headers)||(e.request_headers=r.xhr_headers),b(r.cookie_name)||(e.persistence_name=r.cookie_name),b(r.disable_cookie)||(e.disable_persistence=r.disable_cookie),b(r.store_google)||(e.save_campaign_params=r.store_google),b(r.verbose)||(e.debug=r.verbose);var t=z({},e,r);return L(r.property_blacklist)&&(b(r.property_denylist)?t.property_denylist=r.property_blacklist:L(r.property_denylist)?t.property_denylist=[...r.property_blacklist,...r.property_denylist]:E.error("Invalid value for property_denylist config: "+r.property_denylist)),t};class md{constructor(){this.__forceAllowLocalhost=!1}get Vr(){return this.__forceAllowLocalhost}set Vr(e){E.error("WebPerformanceObserver is deprecated and has no impact on network capture. Use `_forceAllowLocalhostNetworkCapture` on `posthog.sessionRecording`"),this.__forceAllowLocalhost=e}}class fr{get decideEndpointWasHit(){var e,t;return(e=(t=this.featureFlags)==null?void 0:t.hasLoadedFlags)!==null&&e!==void 0&&e}get flagsEndpointWasHit(){var e,t;return(e=(t=this.featureFlags)==null?void 0:t.hasLoadedFlags)!==null&&e!==void 0&&e}constructor(){this.webPerformance=new md,this.Jr=!1,this.version=Le.LIB_VERSION,this.mi=new Xs,this._calculate_event_properties=this.calculateEventProperties.bind(this),this.config=xo(),this.SentryIntegration=hu,this.sentryIntegration=e=>function(t,n){var s=Ha(t,n);return{name:Ua,processEvent:i=>s(i)}}(this,e),this.__request_queue=[],this.__loaded=!1,this.analyticsDefaultEndpoint="/e/",this.Kr=!1,this.Yr=null,this.Xr=null,this.Qr=null,this.featureFlags=new Gu(this),this.toolbar=new mu(this),this.scrollManager=new ad(this),this.pageViewManager=new lo(this),this.surveys=new ed(this),this.conversations=new td(this),this.logs=new rd(this),this.experiments=new ne(this),this.exceptions=new Ou(this),this.rateLimiter=new nd(this),this.requestRouter=new dd(this),this.consent=new lu(this),this.externalIntegrations=new gd(this),this.people={set:(e,t,n)=>{var s=K(e)?{[e]:t}:e;this.setPersonProperties(s),n==null||n({})},set_once:(e,t,n)=>{var s=K(e)?{[e]:t}:e;this.setPersonProperties(void 0,s),n==null||n({})}},this.on("eventCaptured",e=>E.info('send "'+(e==null?void 0:e.event)+'"',e))}init(e,t,n){if(n&&n!==It){var s,i=(s=or[n])!==null&&s!==void 0?s:new fr;return i._init(e,t,n),or[n]=i,or[It][n]=i,i}return this._init(e,t,n)}_init(e,t,n){var s;if(t===void 0&&(t={}),b(e)||is(e))return E.critical("PostHog was initialized without a token. This likely indicates a misconfiguration. Please check the first argument passed to posthog.init()"),this;if(this.__loaded)return console.warn("[PostHog.js]","You have already initialized PostHog! Re-initializing is a no-op"),this;this.__loaded=!0,this.config={},t.debug=this.Zr(t.debug),this.ts=t,this.es=[],t.person_profiles?this.Xr=t.person_profiles:t.process_person&&(this.Xr=t.process_person),this.set_config(z({},xo(t.defaults),To(t),{name:n,token:e})),this.config.on_xhr_error&&E.error("on_xhr_error is deprecated. Use on_request_error instead"),this.compression=t.disable_compression?void 0:Be.GZipJS;var i=this.rs();this.persistence=new Vn(this.config,i),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new Vn(S({},this.config,{persistence:"sessionStorage"}),i);var o=S({},this.persistence.props),a=S({},this.sessionPersistence.props);this.register({$initialization_time:new Date().toISOString()}),this.ss=new sd(I=>this.ns(I),this.config.request_queue_config),this.os=new od(this),this.__request_queue=[];var l=this.config.cookieless_mode==="always"||this.config.cookieless_mode==="on_reject"&&this.consent.isExplicitlyOptedOut();if(l||(this.sessionManager=new Io(this),this.sessionPropsManager=new So(this,this.sessionManager,this.persistence)),this.config.__preview_deferred_init_extensions?(E.info("Deferring extension initialization to improve startup performance"),setTimeout(()=>{this.ls(l)},0)):(E.info("Initializing extensions synchronously"),this.ls(l)),Le.DEBUG=Le.DEBUG||this.config.debug,Le.DEBUG&&E.info("Starting in debug mode",{this:this,config:t,thisC:S({},this.config),p:o,s:a}),((s=t.bootstrap)==null?void 0:s.distinctID)!==void 0){var c,u,d=this.config.get_device_id(rt()),p=(c=t.bootstrap)!=null&&c.isIdentifiedID?d:t.bootstrap.distinctID;this.persistence.set_property(Te,(u=t.bootstrap)!=null&&u.isIdentifiedID?"identified":"anonymous"),this.register({distinct_id:t.bootstrap.distinctID,$device_id:p})}if(this.us()){var h,m,_=Object.keys(((h=t.bootstrap)==null?void 0:h.featureFlags)||{}).filter(I=>{var R;return!((R=t.bootstrap)==null||(R=R.featureFlags)==null||!R[I])}).reduce((I,R)=>{var T;return I[R]=((T=t.bootstrap)==null||(T=T.featureFlags)==null?void 0:T[R])||!1,I},{}),v=Object.keys(((m=t.bootstrap)==null?void 0:m.featureFlagPayloads)||{}).filter(I=>_[I]).reduce((I,R)=>{var T,w;return(T=t.bootstrap)!=null&&(T=T.featureFlagPayloads)!=null&&T[R]&&(I[R]=(w=t.bootstrap)==null||(w=w.featureFlagPayloads)==null?void 0:w[R]),I},{});this.featureFlags.receivedFeatureFlags({featureFlags:_,featureFlagPayloads:v})}if(l)this.register_once({distinct_id:Ht,$device_id:null},"");else if(!this.get_distinct_id()){var k=this.config.get_device_id(rt());this.register_once({distinct_id:k,$device_id:k},""),this.persistence.set_property(Te,"anonymous")}return V(f,"onpagehide"in self?"pagehide":"unload",this._handle_unload.bind(this),{passive:!1}),this.toolbar.maybeLoadToolbar(),t.segment?fu(this,()=>this.hs()):this.hs(),je(this.config._onCapture)&&this.config._onCapture!==xs&&(E.warn("onCapture is deprecated. Please use `before_send` instead"),this.on("eventCaptured",I=>this.config._onCapture(I.event,I))),this.config.ip&&E.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}ls(e){var t=performance.now();this.historyAutocapture=new pu(this),this.historyAutocapture.startIfEnabled();var n=[];n.push(()=>{new vu(this).startIfEnabledOrStop()}),n.push(()=>{var s;this.siteApps=new ud(this),(s=this.siteApps)==null||s.init()}),e||n.push(()=>{this.sessionRecording=new Co(this),this.sessionRecording.startIfEnabledOrStop()}),this.config.disable_scroll_properties||n.push(()=>{this.scrollManager.startMeasuringScrollPosition()}),n.push(()=>{this.autocapture=new eu(this),this.autocapture.startIfEnabled()}),n.push(()=>{this.surveys.loadIfEnabled()}),n.push(()=>{this.logs.loadIfEnabled()}),n.push(()=>{this.conversations.loadIfEnabled()}),n.push(()=>{this.productTours=new Ku(this),this.productTours.loadIfEnabled()}),n.push(()=>{this.heatmaps=new ku(this),this.heatmaps.startIfEnabled()}),n.push(()=>{this.webVitalsAutocapture=new Su(this)}),n.push(()=>{this.exceptionObserver=new du(this),this.exceptionObserver.startIfEnabledOrStop()}),n.push(()=>{this.deadClicksAutocapture=new ja(this,uu),this.deadClicksAutocapture.startIfEnabledOrStop()}),n.push(()=>{if(this.ds){var s=this.ds;this.ds=void 0,this.Ce(s)}}),this.vs(n,t)}vs(e,t){for(;e.length>0;){if(this.config.__preview_deferred_init_extensions&&performance.now()-t>=30&&e.length>0)return void setTimeout(()=>{this.vs(e,t)},0);var n=e.shift();if(n)try{n()}catch(i){E.error("Error initializing extension:",i)}}var s=Math.round(performance.now()-t);this.register_for_session({$sdk_debug_extensions_init_method:this.config.__preview_deferred_init_extensions?"deferred":"synchronous",$sdk_debug_extensions_init_time_ms:s}),this.config.__preview_deferred_init_extensions&&E.info("PostHog extensions initialized ("+s+"ms)")}Ce(e){var t,n,s,i,o,a,l,c,u;if(!y||!y.body)return E.info("document not ready yet, trying again in 500 milliseconds..."),void setTimeout(()=>{this.Ce(e)},500);this.config.__preview_deferred_init_extensions&&(this.ds=e),this.compression=void 0,e.supportedCompression&&!this.config.disable_compression&&(this.compression=F(e.supportedCompression,Be.GZipJS)?Be.GZipJS:F(e.supportedCompression,Be.Base64)?Be.Base64:void 0),(t=e.analytics)!=null&&t.endpoint&&(this.analyticsDefaultEndpoint=e.analytics.endpoint),this.set_config({person_profiles:this.Xr?this.Xr:"identified_only"}),(n=this.siteApps)==null||n.onRemoteConfig(e),(s=this.sessionRecording)==null||s.onRemoteConfig(e),(i=this.autocapture)==null||i.onRemoteConfig(e),(o=this.heatmaps)==null||o.onRemoteConfig(e),this.surveys.onRemoteConfig(e),this.logs.onRemoteConfig(e),this.conversations.onRemoteConfig(e),(a=this.productTours)==null||a.onRemoteConfig(e),(l=this.webVitalsAutocapture)==null||l.onRemoteConfig(e),(c=this.exceptionObserver)==null||c.onRemoteConfig(e),this.exceptions.onRemoteConfig(e),(u=this.deadClicksAutocapture)==null||u.onRemoteConfig(e)}hs(){try{this.config.loaded(this)}catch(n){E.critical("`loaded` function failed",n)}if(this.cs(),this.config.internal_or_test_user_hostname&&Q!=null&&Q.hostname){var e=Q.hostname,t=this.config.internal_or_test_user_hostname;(typeof t=="string"?e===t:t.test(e))&&this.setInternalOrTestUser()}this.config.capture_pageview&&setTimeout(()=>{(this.consent.isOptedIn()||this.config.cookieless_mode==="always")&&this.fs()},1),this.ps=new sl(this),this.ps.load()}cs(){var e;this.is_capturing()&&this.config.request_batching&&((e=this.ss)==null||e.enable())}_dom_loaded(){this.is_capturing()&&nt(this.__request_queue,e=>this.ns(e)),this.__request_queue=[],this.cs()}_handle_unload(){var e,t;this.surveys.handlePageUnload(),this.config.request_batching?(this._s()&&this.capture("$pageleave"),(e=this.ss)==null||e.unload(),(t=this.os)==null||t.unload()):this._s()&&this.capture("$pageleave",null,{transport:"sendBeacon"})}_send_request(e){this.__loaded&&(ol?this.__request_queue.push(e):this.rateLimiter.isServerRateLimited(e.batchKey)||(e.transport=e.transport||this.config.api_transport,e.url=Qr(e.url,{ip:this.config.ip?1:0}),e.headers=S({},this.config.request_headers,e.headers),e.compression=e.compression==="best-available"?this.compression:e.compression,e.disableXHRCredentials=this.config.__preview_disable_xhr_credentials,this.config.__preview_disable_beacon&&(e.disableTransport=["sendBeacon"]),e.fetchOptions=e.fetchOptions||this.config.fetch_options,(t=>{var n,s,i,o=S({},t);o.timeout=o.timeout||6e4,o.url=Qr(o.url,{_:new Date().getTime().toString(),ver:Le.LIB_VERSION,compression:o.compression});var a=(n=o.transport)!==null&&n!==void 0?n:"fetch",l=$r.filter(u=>!o.disableTransport||!u.transport||!o.disableTransport.includes(u.transport)),c=(s=(i=wa(l,u=>u.transport===a))==null?void 0:i.method)!==null&&s!==void 0?s:l[0].method;if(!c)throw new Error("No available transport method");c(o)})(S({},e,{callback:t=>{var n,s;this.rateLimiter.checkForLimiting(t),t.statusCode>=400&&((n=(s=this.config).on_request_error)==null||n.call(s,t)),e.callback==null||e.callback(t)}}))))}ns(e){this.os?this.os.retriableRequest(e):this._send_request(e)}_execute_array(e){Qn++;try{var t,n=[],s=[],i=[];nt(e,a=>{a&&(t=a[0],L(t)?i.push(a):je(a)?a.call(this):L(a)&&t==="alias"?n.push(a):L(a)&&t.indexOf("capture")!==-1&&je(this[t])?i.push(a):s.push(a))});var o=function(a,l){nt(a,function(c){if(L(c[0])){var u=l;j(c,function(d){u=u[d[0]].apply(u,d.slice(1))})}else this[c[0]].apply(this,c.slice(1))},l)};o(n,this),o(s,this),o(i,this)}finally{Qn--}}us(){var e,t;return((e=this.config.bootstrap)==null?void 0:e.featureFlags)&&Object.keys((t=this.config.bootstrap)==null?void 0:t.featureFlags).length>0||!1}push(e){if(Qn>0&&L(e)&&K(e[0])){var t=fr.prototype[e[0]];je(t)&&t.apply(this,e.slice(1))}else this._execute_array([e])}capture(e,t,n){var s;if(this.__loaded&&this.persistence&&this.sessionPersistence&&this.ss){if(this.is_capturing())if(!b(e)&&K(e)){var i=!this.config.opt_out_useragent_filter&&this._is_bot();if(!(i&&!this.config.__preview_capture_bot_pageviews)){var o=n!=null&&n.skip_client_rate_limiting?void 0:this.rateLimiter.clientRateLimitContext();if(o==null||!o.isRateLimited){t!=null&&t.$current_url&&!K(t==null?void 0:t.$current_url)&&(E.error("Invalid `$current_url` property provided to `posthog.capture`. Input must be a string. Ignoring provided value."),t==null||delete t.$current_url),e!=="$exception"||n!=null&&n.oi||E.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 a=new Date,l=(n==null?void 0:n.timestamp)||a,c=rt(),u={uuid:c,event:e,properties:this.calculateEventProperties(e,t||{},l,c)};e==="$pageview"&&this.config.__preview_capture_bot_pageviews&&i&&(u.event="$bot_pageview",u.properties.$browser_type="bot"),o&&(u.properties.$lib_rate_limit_remaining_tokens=o.remainingTokens),n!=null&&n.$set&&(u.$set=n==null?void 0:n.$set);var d,p=e!=="$groupidentify",h=this.gs(n==null?void 0:n.$set_once,p);if(h&&(u.$set_once=h),(u=Nc(u,n!=null&&n._noTruncate?null:this.config.properties_string_max_length)).timestamp=l,b(n==null?void 0:n.timestamp)||(u.properties.$event_time_override_provided=!0,u.properties.$event_time_override_system_time=a),e===nr.DISMISSED||e===nr.SENT){var m=t==null?void 0:t[Zn.SURVEY_ID],_=t==null?void 0:t[Zn.SURVEY_ITERATION];d={id:m,current_iteration:_},localStorage.getItem(bo(d))||localStorage.setItem(bo(d),"true"),u.$set=S({},u.$set,{[Vu({id:m,current_iteration:_},e===nr.SENT?"responded":"dismissed")]:!0})}else e===nr.SHOWN&&(u.$set=S({},u.$set,{[Zn.SURVEY_LAST_SEEN_DATE]:new Date().toISOString()}));var v=S({},u.properties.$set,u.$set);if(kt(v)||this.setPersonPropertiesForFlags(v),!$(this.config.before_send)){var k=this.bs(u);if(!k)return;u=k}this.mi.emit("eventCaptured",u);var I={method:"POST",url:(s=n==null?void 0:n._url)!==null&&s!==void 0?s:this.requestRouter.endpointFor("api",this.analyticsDefaultEndpoint),data:u,compression:"best-available",batchKey:n==null?void 0:n._batchKey};return!this.config.request_batching||n&&(n==null||!n._batchKey)||n!=null&&n.send_instantly?this.ns(I):this.ss.enqueue(I),u}E.critical("This capture call is ignored due to client rate limiting.")}}else E.error("No event name provided to posthog.capture")}else E.uninitializedWarning("posthog.capture")}_addCaptureHook(e){return this.on("eventCaptured",t=>e(t.event,t))}calculateEventProperties(e,t,n,s,i){if(n=n||new Date,!this.persistence||!this.sessionPersistence)return t;var o=i?void 0:this.persistence.remove_event_timer(e),a=S({},t);if(a.token=this.config.token,a.$config_defaults=this.config.defaults,(this.config.cookieless_mode=="always"||this.config.cookieless_mode=="on_reject"&&this.consent.isExplicitlyOptedOut())&&(a.$cookieless_mode=!0),e==="$snapshot"){var l=S({},this.persistence.properties(),this.sessionPersistence.properties());return a.distinct_id=l.distinct_id,(!K(a.distinct_id)&&!Ke(a.distinct_id)||is(a.distinct_id))&&E.error("Invalid distinct_id for replay event. This indicates a bug in your implementation"),a}var c,u=Eu(this.config.mask_personal_data_properties,this.config.custom_personal_data_properties);if(this.sessionManager){var{sessionId:d,windowId:p}=this.sessionManager.checkAndGetSessionAndWindowId(i,n.getTime());a.$session_id=d,a.$window_id=p}this.sessionPropsManager&&z(a,this.sessionPropsManager.getSessionProps());try{var h;this.sessionRecording&&z(a,this.sessionRecording.sdkDebugProperties),a.$sdk_debug_retry_queue_size=(h=this.os)==null?void 0:h.length}catch(k){a.$sdk_debug_error_capturing_properties=String(k)}if(this.requestRouter.region===sr.CUSTOM&&(a.$lib_custom_api_host=this.config.api_host),c=e!=="$pageview"||i?e!=="$pageleave"||i?this.pageViewManager.doEvent():this.pageViewManager.doPageLeave(n):this.pageViewManager.doPageView(n,s),a=z(a,c),e==="$pageview"&&y&&(a.title=y.title),!b(o)){var m=n.getTime()-o;a.$duration=parseFloat((m/1e3).toFixed(3))}ce&&this.config.opt_out_useragent_filter&&(a.$browser_type=this._is_bot()?"bot":"browser"),(a=z({},u,this.persistence.properties(),this.sessionPersistence.properties(),a)).$is_identified=this._isIdentified(),L(this.config.property_denylist)?j(this.config.property_denylist,function(k){delete a[k]}):E.error("Invalid value for property_denylist config: "+this.config.property_denylist+" or property_blacklist config: "+this.config.property_blacklist);var _=this.config.sanitize_properties;_&&(E.error("sanitize_properties is deprecated. Use before_send instead"),a=_(a,e));var v=this.ys();return a.$process_person_profile=v,v&&!i&&this.ws("_calculate_event_properties"),a}gs(e,t){var n;if(t===void 0&&(t=!0),!this.persistence||!this.ys()||this.Jr)return e;var s=this.persistence.get_initial_props(),i=(n=this.sessionPropsManager)==null?void 0:n.getSetOnceProps(),o=z({},s,i||{},e||{}),a=this.config.sanitize_properties;return a&&(E.error("sanitize_properties is deprecated. Use before_send instead"),o=a(o,"$set_once")),t&&(this.Jr=!0),kt(o)?void 0:o}register(e,t){var n;(n=this.persistence)==null||n.register(e,t)}register_once(e,t,n){var s;(s=this.persistence)==null||s.register_once(e,t,n)}register_for_session(e){var t;(t=this.sessionPersistence)==null||t.register(e)}unregister(e){var t;(t=this.persistence)==null||t.unregister(e)}unregister_for_session(e){var t;(t=this.sessionPersistence)==null||t.unregister(e)}xs(e,t){this.register({[e]:t})}getFeatureFlag(e,t){return this.featureFlags.getFeatureFlag(e,t)}getFeatureFlagPayload(e){return this.featureFlags.getFeatureFlagPayload(e)}getFeatureFlagResult(e,t){return this.featureFlags.getFeatureFlagResult(e,t)}isFeatureEnabled(e,t){return this.featureFlags.isFeatureEnabled(e,t)}reloadFeatureFlags(){this.featureFlags.reloadFeatureFlags()}updateFlags(e,t,n){var s=n!=null&&n.merge?this.featureFlags.getFlagVariants():{},i=n!=null&&n.merge?this.featureFlags.getFlagPayloads():{},o=S({},s,e),a=S({},i,t),l={};for(var[c,u]of Object.entries(o)){var d=typeof u=="string";l[c]={key:c,enabled:!!d||!!u,variant:d?u:void 0,reason:void 0,metadata:b(a==null?void 0:a[c])?void 0:{id:0,version:void 0,description:void 0,payload:a[c]}}}this.featureFlags.receivedFeatureFlags({flags:l})}updateEarlyAccessFeatureEnrollment(e,t,n){this.featureFlags.updateEarlyAccessFeatureEnrollment(e,t,n)}getEarlyAccessFeatures(e,t,n){return t===void 0&&(t=!1),this.featureFlags.getEarlyAccessFeatures(e,t,n)}on(e,t){return this.mi.on(e,t)}onFeatureFlags(e){return this.featureFlags.onFeatureFlags(e)}onSurveysLoaded(e){return this.surveys.onSurveysLoaded(e)}onSessionId(e){var t,n;return(t=(n=this.sessionManager)==null?void 0:n.onSessionId(e))!==null&&t!==void 0?t:()=>{}}getSurveys(e,t){t===void 0&&(t=!1),this.surveys.getSurveys(e,t)}getActiveMatchingSurveys(e,t){t===void 0&&(t=!1),this.surveys.getActiveMatchingSurveys(e,t)}renderSurvey(e,t){this.surveys.renderSurvey(e,t)}displaySurvey(e,t){t===void 0&&(t=Ju),this.surveys.displaySurvey(e,t)}cancelPendingSurvey(e){this.surveys.cancelPendingSurvey(e)}canRenderSurvey(e){return this.surveys.canRenderSurvey(e)}canRenderSurveyAsync(e,t){return t===void 0&&(t=!1),this.surveys.canRenderSurveyAsync(e,t)}identify(e,t,n){if(!this.__loaded||!this.persistence)return E.uninitializedWarning("posthog.identify");if(Ke(e)&&(e=e.toString(),E.warn("The first argument to posthog.identify was a number, but it should be a string. It has been converted to a string.")),e)if(["distinct_id","distinctid"].includes(e.toLowerCase()))E.critical('The string "'+e+'" was set in posthog.identify which indicates an error. This ID should be unique to the user and not a hardcoded string.');else if(e!==Ht){if(this.ws("posthog.identify")){var s=this.get_distinct_id();if(this.register({$user_id:e}),!this.get_property("$device_id")){var i=s;this.register_once({$had_persisted_distinct_id:!0,$device_id:i},"")}e!==s&&e!==this.get_property(Xt)&&(this.unregister(Xt),this.register({distinct_id:e}));var o=(this.persistence.get_property(Te)||"anonymous")==="anonymous";e!==s&&o?(this.persistence.set_property(Te,"identified"),this.setPersonPropertiesForFlags(S({},n||{},t||{}),!1),this.capture("$identify",{distinct_id:e,$anon_distinct_id:s},{$set:t||{},$set_once:n||{}}),this.Qr=go(e,t,n),this.featureFlags.setAnonymousDistinctId(s)):(t||n)&&this.setPersonProperties(t,n),e!==s&&(this.reloadFeatureFlags(),this.unregister(zr))}}else E.critical('The string "'+Ht+'" was set in posthog.identify which indicates an error. This ID is only used as a sentinel value.');else E.error("Unique user id has not been set in posthog.identify")}setPersonProperties(e,t){if((e||t)&&this.ws("posthog.setPersonProperties")){var n=go(this.get_distinct_id(),e,t);this.Qr!==n?(this.setPersonPropertiesForFlags(S({},t||{},e||{})),this.capture("$set",{$set:e||{},$set_once:t||{}}),this.Qr=n):E.info("A duplicate setPersonProperties call was made with the same properties. It has been ignored.")}}group(e,t,n){if(e&&t){var s=this.getGroups();s[e]!==t&&this.resetGroupPropertiesForFlags(e),this.register({$groups:S({},s,{[e]:t})}),n&&(this.capture("$groupidentify",{$group_type:e,$group_key:t,$group_set:n}),this.setGroupPropertiesForFlags({[e]:n})),s[e]===t||n||this.reloadFeatureFlags()}else E.error("posthog.group requires a group type and group key")}resetGroups(){this.register({$groups:{}}),this.resetGroupPropertiesForFlags(),this.reloadFeatureFlags()}setPersonPropertiesForFlags(e,t){t===void 0&&(t=!0),this.featureFlags.setPersonPropertiesForFlags(e,t)}resetPersonPropertiesForFlags(){this.featureFlags.resetPersonPropertiesForFlags()}setGroupPropertiesForFlags(e,t){t===void 0&&(t=!0),this.ws("posthog.setGroupPropertiesForFlags")&&this.featureFlags.setGroupPropertiesForFlags(e,t)}resetGroupPropertiesForFlags(e){this.featureFlags.resetGroupPropertiesForFlags(e)}reset(e){var t,n,s,i,o;if(E.info("reset"),!this.__loaded)return E.uninitializedWarning("posthog.reset");var a=this.get_property("$device_id");if(this.consent.reset(),(t=this.persistence)==null||t.clear(),(n=this.sessionPersistence)==null||n.clear(),this.surveys.reset(),(s=this.ps)==null||s.stop(),this.featureFlags.reset(),(i=this.persistence)==null||i.set_property(Te,"anonymous"),(o=this.sessionManager)==null||o.resetSessionId(),this.Qr=null,this.config.cookieless_mode==="always")this.register_once({distinct_id:Ht,$device_id:null},"");else{var l=this.config.get_device_id(rt());this.register_once({distinct_id:l,$device_id:e?l:a},"")}this.register({$last_posthog_reset:new Date().toISOString()},1)}get_distinct_id(){return this.get_property("distinct_id")}getGroups(){return this.get_property("$groups")||{}}get_session_id(){var e,t;return(e=(t=this.sessionManager)==null?void 0:t.checkAndGetSessionAndWindowId(!0).sessionId)!==null&&e!==void 0?e:""}get_session_replay_url(e){if(!this.sessionManager)return"";var{sessionId:t,sessionStartTimestamp:n}=this.sessionManager.checkAndGetSessionAndWindowId(!0),s=this.requestRouter.endpointFor("ui","/project/"+this.config.token+"/replay/"+t);if(e!=null&&e.withTimestamp&&n){var i,o=(i=e.timestampLookBack)!==null&&i!==void 0?i:10;if(!n)return s;s+="?t="+Math.max(Math.floor((new Date().getTime()-n)/1e3)-o,0)}return s}alias(e,t){return e===this.get_property(Ea)?(E.critical("Attempting to create alias for existing People user - aborting."),-2):this.ws("posthog.alias")?(b(t)&&(t=this.get_distinct_id()),e!==t?(this.xs(Xt,e),this.capture("$create_alias",{alias:e,distinct_id:t})):(E.warn("alias matches current distinct_id - skipping api call."),this.identify(e),-1)):void 0}set_config(e){var t=S({},this.config);if(J(e)){var n,s,i,o,a,l,c,u;z(this.config,To(e));var d=this.rs();(n=this.persistence)==null||n.update_config(this.config,t,d),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new Vn(S({},this.config,{persistence:"sessionStorage"}),d);var p=this.Zr(this.config.debug);We(p)&&(this.config.debug=p),We(this.config.debug)&&(this.config.debug?(Le.DEBUG=!0,H.H()&&H.G("ph_debug","true"),E.info("set_config",{config:e,oldConfig:t,newConfig:S({},this.config)})):(Le.DEBUG=!1,H.H()&&H.V("ph_debug"))),(s=this.exceptionObserver)==null||s.onConfigChange(),(i=this.sessionRecording)==null||i.startIfEnabledOrStop(),(o=this.autocapture)==null||o.startIfEnabled(),(a=this.heatmaps)==null||a.startIfEnabled(),(l=this.exceptionObserver)==null||l.startIfEnabledOrStop(),(c=this.deadClicksAutocapture)==null||c.startIfEnabledOrStop(),this.surveys.loadIfEnabled(),this.$s(),(u=this.externalIntegrations)==null||u.startIfEnabledOrStop()}}startSessionRecording(e){var t=e===!0,n={sampling:t||!(e==null||!e.sampling),linked_flag:t||!(e==null||!e.linked_flag),url_trigger:t||!(e==null||!e.url_trigger),event_trigger:t||!(e==null||!e.event_trigger)};if(Object.values(n).some(Boolean)){var s,i,o,a,l;(s=this.sessionManager)==null||s.checkAndGetSessionAndWindowId(),n.sampling&&((i=this.sessionRecording)==null||i.overrideSampling()),n.linked_flag&&((o=this.sessionRecording)==null||o.overrideLinkedFlag()),n.url_trigger&&((a=this.sessionRecording)==null||a.overrideTrigger("url")),n.event_trigger&&((l=this.sessionRecording)==null||l.overrideTrigger("event"))}this.set_config({disable_session_recording:!1})}stopSessionRecording(){this.set_config({disable_session_recording:!0})}sessionRecordingStarted(){var e;return!((e=this.sessionRecording)==null||!e.started)}captureException(e,t){var n=new Error("PostHog syntheticException"),s=this.exceptions.buildProperties(e,{handled:!0,syntheticException:n});return this.exceptions.sendExceptionEvent(S({},s,t))}startExceptionAutocapture(e){this.set_config({capture_exceptions:e==null||e})}stopExceptionAutocapture(){this.set_config({capture_exceptions:!1})}loadToolbar(e){return this.toolbar.loadToolbar(e)}get_property(e){var t;return(t=this.persistence)==null?void 0:t.props[e]}getSessionProperty(e){var t;return(t=this.sessionPersistence)==null?void 0:t.props[e]}toString(){var e,t=(e=this.config.name)!==null&&e!==void 0?e:It;return t!==It&&(t=It+"."+t),t}_isIdentified(){var e,t;return((e=this.persistence)==null?void 0:e.get_property(Te))==="identified"||((t=this.sessionPersistence)==null?void 0:t.get_property(Te))==="identified"}ys(){var e,t;return!(this.config.person_profiles==="never"||this.config.person_profiles==="identified_only"&&!this._isIdentified()&&kt(this.getGroups())&&((e=this.persistence)==null||(e=e.props)==null||!e[Xt])&&((t=this.persistence)==null||(t=t.props)==null||!t[qr]))}_s(){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.ys()||this.ws("posthog.createPersonProfile")&&this.setPersonProperties({},{})}setInternalOrTestUser(){this.ws("posthog.setInternalOrTestUser")&&this.setPersonProperties({$internal_or_test_user:!0})}ws(e){return this.config.person_profiles==="never"?(E.error(e+' was called, but process_person is set to "never". This call will be ignored.'),!1):(this.xs(qr,!0),!0)}rs(){if(this.config.cookieless_mode==="always")return!0;var e=this.consent.isOptedOut(),t=this.config.opt_out_persistence_by_default||this.config.cookieless_mode==="on_reject";return this.config.disable_persistence||e&&!!t}$s(){var e,t,n,s,i=this.rs();return((e=this.persistence)==null?void 0:e.ki)!==i&&((n=this.persistence)==null||n.set_disabled(i)),((t=this.sessionPersistence)==null?void 0:t.ki)!==i&&((s=this.sessionPersistence)==null||s.set_disabled(i)),i}opt_in_capturing(e){var t;if(this.config.cookieless_mode!=="always"){var n,s,i;this.config.cookieless_mode==="on_reject"&&this.consent.isExplicitlyOptedOut()&&(this.reset(!0),(n=this.sessionManager)==null||n.destroy(),(s=this.pageViewManager)==null||s.destroy(),this.sessionManager=new Io(this),this.pageViewManager=new lo(this),this.persistence&&(this.sessionPropsManager=new So(this,this.sessionManager,this.persistence)),this.sessionRecording=new Co(this),this.sessionRecording.startIfEnabledOrStop()),this.consent.optInOut(!0),this.$s(),this.cs(),(t=this.sessionRecording)==null||t.startIfEnabledOrStop(),this.config.cookieless_mode=="on_reject"&&this.surveys.loadIfEnabled(),(b(e==null?void 0:e.captureEventName)||e!=null&&e.captureEventName)&&this.capture((i=e==null?void 0:e.captureEventName)!==null&&i!==void 0?i:"$opt_in",e==null?void 0:e.captureProperties,{send_instantly:!0}),this.config.capture_pageview&&this.fs()}else E.warn('Consent opt in/out is not valid with cookieless_mode="always" and will be ignored')}opt_out_capturing(){var e,t,n;this.config.cookieless_mode!=="always"?(this.config.cookieless_mode==="on_reject"&&this.consent.isOptedIn()&&this.reset(!0),this.consent.optInOut(!1),this.$s(),this.config.cookieless_mode==="on_reject"&&(this.register({distinct_id:Ht,$device_id:null}),(e=this.sessionManager)==null||e.destroy(),(t=this.pageViewManager)==null||t.destroy(),this.sessionManager=void 0,this.sessionPropsManager=void 0,(n=this.sessionRecording)==null||n.stopRecording(),this.sessionRecording=void 0,this.fs())):E.warn('Consent opt in/out is not valid with cookieless_mode="always" and will be ignored')}has_opted_in_capturing(){return this.consent.isOptedIn()}has_opted_out_capturing(){return this.consent.isOptedOut()}get_explicit_consent_status(){var e=this.consent.consent;return e===De.GRANTED?"granted":e===De.DENIED?"denied":"pending"}is_capturing(){return this.config.cookieless_mode==="always"||(this.config.cookieless_mode==="on_reject"?this.consent.isExplicitlyOptedOut()||this.consent.isOptedIn():!this.has_opted_out_capturing())}clear_opt_in_out_capturing(){this.consent.reset(),this.$s()}_is_bot(){return fe?il(fe,this.config.custom_blocked_useragents):void 0}fs(){y&&(y.visibilityState==="visible"?this.Kr||(this.Kr=!0,this.capture("$pageview",{title:y.title},{send_instantly:!0}),this.Yr&&(y.removeEventListener("visibilitychange",this.Yr),this.Yr=null)):this.Yr||(this.Yr=this.fs.bind(this),V(y,"visibilitychange",this.Yr)))}debug(e){e===!1?(f==null||f.console.log("You've disabled debug mode."),this.set_config({debug:!1})):(f==null||f.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}))}M(){var e,t,n,s,i,o,a,l=this.ts||{};return"advanced_disable_flags"in l?!!l.advanced_disable_flags:this.config.advanced_disable_flags!==!1?!!this.config.advanced_disable_flags:this.config.advanced_disable_decide===!0?(E.warn("Config field 'advanced_disable_decide' is deprecated. Please use 'advanced_disable_flags' instead. The old field will be removed in a future major version."),!0):(n="advanced_disable_decide",s=!1,i=E,o=(t="advanced_disable_flags")in(e=l)&&!$(e[t]),a=n in e&&!$(e[n]),o?e[t]:a?(i&&i.warn("Config field '"+n+"' is deprecated. Please use '"+t+"' instead. The old field will be removed in a future major version."),e[n]):s)}bs(e){if($(this.config.before_send))return e;var t=L(this.config.before_send)?this.config.before_send:[this.config.before_send],n=e;for(var s of t){if(n=s(n),$(n)){var i="Event '"+e.event+"' was rejected in beforeSend function";return ec(e.event)?E.warn(i+". This can cause unexpected behavior."):E.info(i),null}n.properties&&!kt(n.properties)||E.warn("Event '"+e.event+"' has no properties after beforeSend function, this is likely an error.")}return n}getPageViewId(){var e;return(e=this.pageViewManager.Kt)==null?void 0:e.pageViewId}captureTraceFeedback(e,t){this.capture("$ai_feedback",{$ai_trace_id:String(e),$ai_feedback_text:t})}captureTraceMetric(e,t,n){this.capture("$ai_metric",{$ai_trace_id:String(e),$ai_metric_name:t,$ai_metric_value:String(n)})}Zr(e){var t=We(e)&&!e,n=H.H()&&H.q("ph_debug")==="true";return!t&&(!!n||e)}}(function(r,e){for(var t=0;t{if(typeof e=="string")return{name:e,version:null,inferred:!1};const t=it(e),n=t.name||t.package;return n?{name:n,version:t.version||null,inferred:!!t.inferred}:null}).filter(Boolean):Object.entries(it(r)).map(([e,t])=>({name:e,version:t||null,inferred:!1})):[]}function pl(r){return r?(Array.isArray(r)?r:[r]).map(e=>{const t=it(e);return!t.from&&!t.to?null:{from:t.from||null,to:t.to||null,type:t.type||"uses",description:t.description||""}}).filter(Boolean):[]}function yd(r){if(typeof r!="string")return null;const e=r.trim();if(!e)return null;try{return JSON.parse(e)}catch{const t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);if(!t)return null;try{return JSON.parse(t[1].trim())}catch{return null}}}function hr(r,e={}){const t=[],n=typeof r=="string"?yd(r):r,i=it(n||{});!n&&typeof r=="string"&&t.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 r=="string"?r:""),dependencies:i.dependencies||e.dependencies,relationships:i.relationships||e.relationships}],a=o.map((d,p)=>ul(d,p)),l=new Map(o.map((d,p)=>{var h;return[it(d).id,(h=a[p])==null?void 0:h.id]}).filter(([d,p])=>d&&p)),c=d=>l.get(d)||d,u=pl(i.relationships||e.relationships).map(d=>({...d,from:d.from?c(d.from):d.from,to:d.to?c(d.to):d.to}));return{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:dl(i.dependencies||e.dependencies),relationships:u,deployOrder:Array.isArray(i.deployOrder)?i.deployOrder.map(c):a.map(d=>d.id),warnings:[...t,...Array.isArray(i.warnings)?i.warnings:[]],metadata:it(i.metadata)}}function tn(r){return hr(r).artifacts[0]||ul()}function ze(r){if(typeof r!="string")return r??"";const e=r.trim();if(!e)return"";try{return JSON.parse(e)}catch{return r}}function Mt(r){return JSON.stringify(r,null,2)}function wd(r){return Mt({task:"architect",userRequest:String(r??"")})}function bd(r){const e=ze(r);return e&&typeof e=="object"&&typeof e.task=="string"?Mt(e):Mt({task:"generate_bundle",bundleSpec:e})}function Ed(r){return Mt({task:"review_bundle",generatedBundle:ze(r)})}function Qs(r,e=null){const t={stage:r};return e!=null&&(t.bundle=ze(e)),t}function Sd({bundleSpec:r,artifactBundle:e,bundleReview:t,artifactId:n,userFeedback:s}){return Mt({task:"regenerate_artifact",artifactId:n,bundleSpec:ze(r),artifactBundle:ze(e),bundleReview:ze(t),userFeedback:String(s)})}function fl({bundleSpec:r,artifactBundle:e,bundleReview:t,userFeedback:n}){return Mt({task:"regenerate_bundle",bundleSpec:ze(r),artifactBundle:ze(e),bundleReview:ze(t),userFeedback:String(n??"")})}const Ao={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"},Id=["sanitizationResult","modelArmor","modelArmorResult","data","result","error"];function he(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}function kd(r){return he(r)?typeof r.filterMatchState=="string"||typeof r.invocationResult=="string"||Array.isArray(r.matchedFilters)||he(r.filterSummary)||he(r.filterResults):!1}function hl(r,e=0){if(!he(r)||e>3)return null;if(kd(r))return r;for(const t of Id){const n=r[t];if(he(n)){const s=hl(n,e+1);if(s)return s}}return null}function rn(r){return Array.isArray(r)?r.some(rn):he(r)?r.matched===!0||r.matchState==="MATCH_FOUND"?!0:Object.values(r).some(rn):!1}function Rs(r){return Array.isArray(r)?r.some(Rs):he(r)?typeof r.executionState=="string"&&r.executionState!=="EXECUTION_SUCCESS"?!0:Object.values(r).some(Rs):!1}function gl(r){return{csamFilterFilterResult:"csam",maliciousUriFilterResult:"malicious_uris",piAndJailbreakFilterResult:"pi_and_jailbreak",raiFilterResult:"rai",sdpFilterResult:"sdp",virusScanFilterResult:"virus_scan"}[r]||r}function Cd(r,e){if(he(r))for(const[t,n]of Object.entries(r)){if(!he(n))continue;const s=he(n.categories)?n.categories:{},i=Object.entries(s).filter(([,o])=>he(o)&&o.matched===!0).map(([o])=>o);i.length>0?i.forEach(o=>e.add(o)):n.matched===!0&&e.add(gl(t))}}function xd(r,e){var n;if(!r)return;const t=Array.isArray(r)?r.flatMap(s=>he(s)?Object.entries(s):[]):Object.entries(r);for(const[s,i]of t){if(!rn(i))continue;const o=gl(s),a=((n=i==null?void 0:i.raiFilterResult)==null?void 0:n.raiFilterTypeResults)||(o==="rai"?i==null?void 0:i.raiFilterTypeResults:null),l=he(a)?Object.entries(a).filter(([,c])=>rn(c)).map(([c])=>c):[];l.length>0?l.forEach(c=>e.add(c)):e.add(o)}}function Td(r){return Ao[r]?Ao[r]:String(r).replace(/([a-z])([A-Z])/g,"$1 $2").replace(/_/g," ").toLowerCase()}function Po(r){return r.length<=1?r[0]||"content that did not pass":r.length===2?`${r[0]} and ${r[1]}`:`${r.slice(0,-1).join(", ")}, and ${r.at(-1)}`}function Rd(r){const e=hl(r);if(!e)return null;const t=new Set(Array.isArray(e.matchedFilters)?e.matchedFilters:[]);Cd(e.filterSummary,t),xd(e.filterResults,t);const n=e.blocked===!0||e.filterMatchState==="MATCH_FOUND"||t.size>0,s=e.invocationResult||null,i=Rs(e.filterSummary||e.filterResults);return!n&&!i&&!["PARTIAL","FAILURE"].includes(s)?null:{kind:n?"blocked":"unavailable",invocationResult:s,matchedFilters:[...t]}}function Ad(r,e){const t=Rd(r);if(!t)return null;const n=[...new Set(t.matchedFilters.map(Td))],s=t.kind==="blocked",i=new Error(s?`Safety screening blocked this pipeline step for ${Po(n)}.`:"Safety screening could not be completed. Please try again.");return i.name="ModelArmorError",i.code=s?"MODEL_ARMOR_BLOCKED":"MODEL_ARMOR_UNAVAILABLE",i.isModelArmor=!0,i.pipelineStep=e,i.userTitle=s?"Request blocked for safety":"Safety check unavailable",i.userMessage=s?`The safety check detected ${Po(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=s?"Trying another model would not change this safety decision.":"A fallback model was not attempted because safety screening must complete first.",i.matchedFilters=t.matchedFilters,i}const Pd=new Set(["CustomWidget","CustomAction","CustomFunction","CustomClass","CodeFile"]),Fo={CustomWidget:"custom_widgets/",CustomAction:"actions/",CustomFunction:"custom_functions/",CustomClass:"custom_code/",CodeFile:"custom_code/"};function Et(r,e,t){return{artifactId:r.id,artifactName:r.artifactName,artifactType:r.artifactType,severity:e,message:t}}function Fd(r){const e=[],t=r.fileName||"",n=r.code||"";return Pd.has(r.artifactType)||e.push(Et(r,"error",`Unsupported artifact type "${r.artifactType}".`)),t.endsWith(".dart")||e.push(Et(r,"error","FlutterFlow custom code artifacts must use .dart files.")),n.trim()?(r.artifactType==="CustomWidget"&&!/class\s+\w+\s+extends\s+(StatelessWidget|StatefulWidget)/.test(n)&&e.push(Et(r,"warning","CustomWidget code should declare a widget class extending StatelessWidget or StatefulWidget.")),r.artifactType==="CustomAction"&&!/Future(?:<[^>]+>)?\s+\w+\s*\(|Future\s+\w+\s*\(/.test(n)&&e.push(Et(r,"warning","CustomAction code should expose an async Future function callable from FlutterFlow.")),r.artifactType==="CustomFunction"&&/class\s+\w+\s+extends\s+(StatelessWidget|StatefulWidget)/.test(n)&&e.push(Et(r,"warning","CustomFunction should be a callable function, not a widget class.")),e):(e.push(Et(r,"warning","Generated artifact has no Dart code yet.")),e)}function $d(r){const e=Array.isArray(r==null?void 0:r.artifacts)?r.artifacts:[],t=e.flatMap(Fd),n=e.map(s=>({artifactId:s.id,fileName:s.fileName,pathHint:Fo[s.artifactType]||Fo.CodeFile}));return{valid:t.every(s=>s.severity!=="error"),findings:t,deployHints:n}}const ye={ACTION:"A",WIDGET:"W",FUNCTION:"F",CODE_FILE:"C",DEPENDENCIES:"D",OTHER:"O"},Md={CustomAction:ye.ACTION,CustomWidget:ye.WIDGET,CustomFunction:ye.FUNCTION,CustomClass:ye.CODE_FILE,CodeFile:ye.CODE_FILE};function Od(r,e){switch(e){case ye.ACTION:return`lib/custom_code/actions/${r}`;case ye.WIDGET:return`lib/custom_code/widgets/${r}`;case ye.FUNCTION:return"lib/flutter_flow/custom_functions.dart";case ye.CODE_FILE:return`lib/custom_code/${r}`;case ye.DEPENDENCIES:return"pubspec.yaml";case ye.OTHER:return`lib/custom_code/${r}`;default:return r}}function Ld(r){if(r.artifactType==="CustomFunction")return"custom_functions.dart";const e=r.fileName||r.artifactName||r.id||"generated_code";return e.endsWith(".dart")?e:`${e}.dart`}function $o(r=[]){return r.reduce((e,t)=>{const n=t.name||t.package;return!n||n==="flutter"||(e[n]=t.version||""),e},{})}function Nd(r){const e=new Map,t=new Map,n=[];for(const s of r)e.has(s.fileName)?n.push(`Duplicate deploy file name "${s.fileName}" for artifacts "${e.get(s.fileName)}" and "${s.artifactId}".`):e.set(s.fileName,s.artifactId),t.has(s.path)?n.push(`Duplicate deploy path "${s.path}" for artifacts "${t.get(s.path)}" and "${s.artifactId}".`):t.set(s.path,s.artifactId);return n}function Dd(r,e={}){const t=Array.isArray(r==null?void 0:r.artifacts)?r.artifacts:[],s=(e.selectedArtifactIds||(r==null?void 0:r.deployOrder)||t.map(c=>c.id)).map(c=>t.find(u=>u.id===c)).filter(Boolean),i=[...(r==null?void 0:r.warnings)||[]],o=[];s.forEach(c=>{const u=Ld(c),d=c.code||"",p=c.codeType||Md[c.artifactType]||ye.OTHER;d.trim()||i.push(`${c.artifactName||c.id} has no generated code.`),o.push({artifactId:c.id,artifactName:c.artifactName,artifactType:c.artifactType,fileName:u,content:d,type:p,path:Od(u,p),deployMode:"customCodeSync"})});const a={...$o(r==null?void 0:r.dependencies),...s.reduce((c,u)=>({...c,...$o(u.dependencies)}),{})};s.forEach(c=>{(c.dependencies||[]).forEach(u=>{const d=u.name||u.package;d&&!u.version&&i.push(`${c.artifactName||c.id} dependency "${d}" has no explicit version.`)})});const l=Nd(o);return{bundleId:(r==null?void 0:r.id)||"bundle-current",title:(r==null?void 0:r.title)||"Generated artifact bundle",fileEntries:o,dependencies:a,relationships:(r==null?void 0:r.relationships)||[],warnings:i,errors:l}}function Bd(r){var e;return(e=String(r||"").match(/\bclass\s+([A-Z][A-Za-z0-9_]*)\b/))==null?void 0:e[1]}function jd(r){return String(r||"").split("/").pop().replace(/\.dart$/,"").split(/[^A-Za-z0-9]+/).filter(Boolean).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join("")}function Ud(r,e){const n=[jd(r),Bd(e.content),e.artifactName].find(s=>/^[A-Z][A-Za-z0-9_]*$/.test(String(s||"")));if(!n)throw new Error(`Cannot derive a FlutterFlow custom class name for ${r}.`);return n}function Hd(r,e=new Map){const t=[];for(const[n,s]of r.entries())s.type!=="C"||e.has(s.path)||t.push({artifactId:s.artifactId||n,className:Ud(n,s),content:s.content,fileName:n,path:s.path});return t}function Wd(r,e){const t=new Set(e.map(n=>n.path));return new Map(Array.from(r.entries()).filter(([,n])=>!t.has(n.path)))}function zd(r){return String(r||"").replace(/\/\*[\s\S]*?\*\//g,"").replace(/\/\/[^\n]*/g,"")}function Mo(r){const e=/^(import|export|part|library|class|enum|extension|typedef|mixin|abstract|const|final|var|late)\b/,t=[];for(const n of zd(r).split(` -`)){if(!/^[A-Za-z_$]/.test(n)||e.test(n))continue;const s=n.match(/^[\w$<>,?\s[\]]+?\s([a-zA-Z_$][\w$]*)\s*\(/);s&&t.push(s[1])}return t}function Gd(r,e){const t=r.replace(/\.dart$/,"");if(e==="W")return t.replace(/(^|_)(\w)/g,(n,s,i)=>i.toUpperCase());if(e==="A"){const n=t.replace(/(^|_)(\w)/g,(s,i,o)=>o.toUpperCase());return n.charAt(0).toLowerCase()+n.slice(1)}return e==="F"?"CustomFunctions":e==="C"?r.endsWith(".dart")?r:`${r}.dart`:t}async function Oo(r){const e=new TextEncoder().encode(String(r||"")),t=await globalThis.crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(t),n=>n.toString(16).padStart(2,"0")).join("")}async function qd(r,e=new Map){const t={},n=new Set;for(const[o,a]of r.entries()){if(a.type==="D"||a.type==="O")continue;const l=Gd(o,a.type),c={old_identifier_name:l,new_identifier_name:l,type:a.type,is_deleted:!1,current_checksum:await Oo(a.content)},u=e.get(a.path);if(u!==void 0&&(c.original_checksum=await Oo(u)),t[o]=c,a.type==="F"){const d=Mo(a.content);(d.length>0?d:[a.functionName].filter(Boolean)).forEach(h=>n.add(h))}}const s=new Set(Mo(e.get("lib/flutter_flow/custom_functions.dart")||"")),i={functions_to_rename:[],functions_to_delete:[],functions_to_add:Array.from(n).filter(o=>!s.has(o))};return{fileMapContents:JSON.stringify(t),functionsMapContents:JSON.stringify(i)}}const Kd=/^dependencies\s*:\s*(?:#.*)?$/,Vd=/^(?:"([^"]+)"|'([^']+)'|([A-Za-z_][A-Za-z0-9_-]*))\s*:/;function Yd(r){const e=r.match(Vd);return e?e[1]??e[2]??e[3]:null}function ml(r){const e=r.trim();return e===""||e.startsWith("#")}function _l(r){const e=r.match(/^(\s*)/);return e?e[1].length:0}function ei(r){const e=r.findIndex(s=>Kd.test(s));if(e===-1)return null;let t=e,n=null;for(let s=e+1;sc&&c!=="flutter");if(n.length===0)return{yaml:t,added:[],alreadyPresent:[]};const s=t.split(` -`),i=new Set(vl(t)),o=[],a=[];for(const[c,u]of n)i.has(c)?a.push(c):(o.push([c,u]),i.add(c));if(o.length===0)return{yaml:t,added:[],alreadyPresent:a};const l=ei(s);if(l){const c=o.map(([u,d])=>Lo(l.childIndent,u,d));s.splice(l.endIndex,0,...c)}else s.length>0&&s[s.length-1].trim()!==""&&s.push(""),s.push("dependencies:"),o.forEach(([c,u])=>{s.push(Lo(" ",c,u))});return{yaml:s.join(` -`),added:o.map(([c])=>c),alreadyPresent:a}}function yl(r){const e=String(r||""),t=[];return e.trim()?(/^name:\s*\S+/m.test(e)||t.push("pubspec.yaml missing name field"),ei(e.split(` -`))||t.push("pubspec.yaml missing dependencies section"),vl(e).includes("flutter")||t.push("pubspec.yaml missing Flutter SDK dependency"),{valid:t.length===0,errors:t}):(t.push("pubspec.yaml is empty"),{valid:!1,errors:t})}const Xd={"&":"&","<":"<",">":">",'"':""","'":"'"};function Ge(r){return String(r??"").replace(/[&<>"']/g,e=>Xd[e])}function ee(r){return r?Ge(r).replace(/\n/g,"
"):""}function No(r){return Ge(r).replace(/\r?\n/g," ")}function Qd(r){const e={"Integration Audit Report":"📋","Critical Issues":"❌",Warnings:"⚠️",Recommendations:"✅","Overall Score":"📊"};for(const[t,n]of Object.entries(e))if(r.toLowerCase().includes(t.toLowerCase()))return n;return"📄"}function ep(r){const e={critical:"❌",warning:"⚠️",recommendation:"✅",score:"📊",issue:"🔍",fix:"🔧"};for(const[t,n]of Object.entries(e))if(r.toLowerCase().includes(t.toLowerCase()))return n;return"📝"}function tp(r){return r.includes("class ")&&r.includes("extends ")||r.includes("StatelessWidget")||r.includes("StatefulWidget")||r.includes("import 'package:flutter/")?"dart":r.includes("def ")||r.includes("import ")||r.includes("print(")?"python":r.includes("function ")||r.includes("const ")||r.includes("console.")?"javascript":"dart"}function Ot(r){if(!r)return"";if(typeof r!="string")return String(r);const e=/```(?:\w+)?\n?([\s\S]*?)```/,t=r.match(e);return t?t[1].trim():r.trim()}function Do(r){return r=Ge(r),r=r.replace(/\*\*(.*?)\*\*/g,'$1'),r=r.replace(/\*(.*?)\*/g,'$1'),r=r.replace(/`(.*?)`/g,'$1'),r=r.replace(/\b(FAIL|ERROR|CRITICAL)\b/g,'$1'),r=r.replace(/\b(WARN|WARNING)\b/g,'$1'),r=r.replace(/\b(PASS|SUCCESS|OK)\b/g,'$1'),r}function wl(r,e="dart",t=globalThis.hljs){if(!r)return"";const n=Ot(r);try{return t.highlight(n,{language:e}).value}catch(s){console.warn("Syntax highlighting failed:",s);try{return t.highlight(n,{language:"json"}).value}catch{return Ge(n)}}}function jt(r,e={}){const{highlighter:t=globalThis.hljs}=e;let n='
';const s=String(r??"").split(` -`);let i=!1,o="";for(const a of s){if(a.startsWith("```")){if(i){const l=tp(o),c=wl(o.trim(),l,t);n+=`
-
${c}
-
`,o="",i=!1}else i=!0;continue}if(i){o+=a+` -`;continue}if(a.startsWith("# ")){const l=a.substring(2).trim();n+=`
-

- ${Qd(l)} - ${Ge(l)} -

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

- ${ep(l)} - ${Ge(l)} -

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

${Do(a)}

`)}return n+="
",` -
-
-
- Live Audit Report -
- ${n} -
- `}const rp="https://ccc-ffai-runner-y5cyj3473a-uw.a.run.app/deployCustomClasses",np="phc_KoqpBJCIiWMW5I6HKBM092DVXZbMmE4KkPHqI518pF3",sp="https://us.i.posthog.com";al.init(np,{api_host:sp,person_profiles:"identified_only"});function Ae(r,e={}){try{al.capture(r,e)}catch(t){console.error("PostHog tracking failed",t)}}const Se="https://4tgke4.buildship.run",bl={professional:"price_1T2ldCKszA2slvDXatdeCpbI",power:"price_1T2le9KszA2slvDXR4mPvw7M"},nn="ccc_auth_session",Bo=new WeakSet;let N={email:null,sessionToken:null,isVerified:!1};function Lt(r={}){return{tier:"free",status:"none",periodEnd:null,isLoading:!1,isResolved:!1,error:null,...r}}let q=Lt({isResolved:!0});const ip=`${Se}/service/runpipeline`,op="bs_user_id",ap=`${Se}/authUserCheck`;let Mr={userId:null,status:null,resolved:!1};const sn={free:2,professional:50,power:2e3},on="ccc_subscription",jo=3,lp=new Set(["active","trialing","paid"]),gr="google/gemini-3.6-flash",Or=["anthropic/claude-opus-5","openai/gpt-5.6-sol","z-ai/glm-5.2","moonshotai/kimi-k3","openrouter/auto","openrouter/free","openrouter/deepseek/deepseek-v4-pro"],cp={"google/gemini-3.6-flash":"Gemini 3.6 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":"OpenRouter: Auto Router","openrouter/free":"OpenRouter: Free Models","openrouter/deepseek/deepseek-v4-pro":"DeepSeek v4 Pro"};function ve(r){return cp[r]||r}const Rt="ccc_usage",As="google/gemini-3.6-flash",Ps="google/gemini-3.6-flash",es="google/gemini-3.6-flash",Uo={professional:11,power:49},Fs={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"},Lr={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 Nr={...Lr};async function up(){const r=new AbortController,e=setTimeout(()=>r.abort(),5e3);try{const t=await fetch("https://open.er-api.com/v6/latest/AUD",{signal:r.signal});if(!t.ok)return;const n=await t.json();if(n.result!=="success"||!n.rates)return;const s=n.rates,i={AUD:1},o=new Set([...Object.keys(Lr),...Object.values($s),...Object.values(Fs)]);for(const a of o)a!=="AUD"&&(typeof s[a]=="number"&&s[a]>0?i[a]=s[a]:Lr[a]&&(i[a]=Lr[a]));Nr=i}catch{}finally{clearTimeout(e)}}const $s={"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 El(){try{const i=Intl.DateTimeFormat().resolvedOptions().timeZone;if(i&&$s[i])return $s[i]}catch{}const e=(navigator.language||"en-US").replace("-","_"),t=Fs[e];if(t)return t;const n=e.split("_")[0],s=Fs[n];return s||"USD"}function Ho(r,e){const t=Nr[e]??Nr.USD,n=r*t,s=Math.round(n*100)/100;try{return new Intl.NumberFormat("en-US",{style:"currency",currency:e,minimumFractionDigits:0,maximumFractionDigits:s>=100||s%1===0?0:2}).format(s)}catch{return new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",minimumFractionDigits:0,maximumFractionDigits:2}).format(r*Nr.USD)}}const Pe="ccc_api_key_",He="ccc_session_api_key_",Me="ccc_encryption_key",mr="ccc_encryption_key_scope",dp="ccc_keystore",an="keys",_r="ccc_encryption_key_version";let Ms=null,ln=null,vr=!1,cn=!1,Wo=!1;class un extends Error{constructor(){super("Secure browser key storage is unavailable."),this.name="CredentialStorageUnavailableError"}}function zo(){if(Wo)return;Wo=!0;const r="Secure browser key storage is unavailable. Existing credentials were left untouched; new credentials will be available only in this tab session.";console.warn(r),document.body&&G(r,"warning")}function Sl(){return localStorage.getItem(_r)||""}function Os(){var r;return((r=crypto.randomUUID)==null?void 0:r.call(crypto))||kl(crypto.getRandomValues(new Uint8Array(16)))}function pp(){const r=Sl();if(r)return r;const e=Os();return localStorage.setItem(_r,e),e}function Nt(){Ms=null,ln=null,vr=!1,cn=!1}window.addEventListener("storage",r=>{r.key===_r&&Nt()});function fp(){return new Promise((r,e)=>{const t=indexedDB.open(dp,1);t.onupgradeneeded=()=>{const n=t.result;n.objectStoreNames.contains(an)||n.createObjectStore(an)},t.onsuccess=()=>r(t.result),t.onerror=()=>e(t.error)})}async function ti(r,e){const t=await fp();return new Promise((n,s)=>{const i=t.transaction(an,r);let o;try{o=e(i.objectStore(an))}catch(l){t.close(),s(l);return}let a;o.onsuccess=()=>{a=o.result},o.onerror=()=>s(o.error),i.oncomplete=()=>{t.close(),n(a)},i.onerror=()=>{t.close(),s(i.error||new Error("Encryption key transaction failed."))},i.onabort=()=>{t.close(),s(i.error||new Error("Encryption key transaction aborted."))}})}function hp(r){var e;return r instanceof CryptoKey&&((e=r.algorithm)==null?void 0:e.name)==="AES-GCM"&&r.extractable===!1&&r.usages.includes("encrypt")&&r.usages.includes("decrypt")}async function gp(){const r=await ti("readonly",e=>e.get(Me));return hp(r)?r:null}async function Il(r){await ti("readwrite",e=>e.put(r,Me))}async function mp(){Nt();try{await ti("readwrite",r=>r.delete(Me))}catch(r){console.warn("Could not delete the stored encryption key:",r)}}async function _p(){const r=sessionStorage.getItem(Me);if(!r)return null;const e=await crypto.subtle.importKey("jwk",JSON.parse(r),{name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);return await Il(e),sessionStorage.removeItem(Me),sessionStorage.removeItem(mr),localStorage.removeItem(Pe+"salt"),e}async function Go(r){const e=sessionStorage.getItem(Me);if(e)return cn=sessionStorage.getItem(mr)!=="session",crypto.subtle.importKey("jwk",JSON.parse(e),{name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);if(!r)throw new un;const t=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!0,["encrypt","decrypt"]),n=await crypto.subtle.exportKey("jwk",t);return sessionStorage.setItem(Me,JSON.stringify(n)),sessionStorage.setItem(mr,"session"),cn=!1,crypto.subtle.importKey("jwk",n,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}async function vp(r){if(sessionStorage.getItem(mr)==="session"&&sessionStorage.getItem(Me))return zo(),vr=!0,Go(r);try{const e=await gp();if(e)return e;const t=await _p();if(t)return t;const n=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);return await Il(n),n}catch(e){return console.warn("IndexedDB encryption-key storage failed:",e),zo(),vr=!0,Go(r)}}async function ri(r={}){const{allowSessionFallbackCreation:e=!0}=r,t=pp();ln!==t&&Nt();const n=Ms||vp(e);Ms=n,ln=t;try{return await n}catch(s){throw Nt(),s}}async function yp(r){const e=await ri(),t=ln,n=new TextEncoder,s=crypto.getRandomValues(new Uint8Array(12)),i=await crypto.subtle.encrypt({name:"AES-GCM",iv:s},e,n.encode(r)),o=new Uint8Array(s.length+i.byteLength);return o.set(s),o.set(new Uint8Array(i),s.length),{ciphertext:kl(o),keyVersion:t,sessionFallback:vr}}async function wp(r,e={}){const{isSessionCredential:t=!1}=e;try{const n=await ri({allowSessionFallbackCreation:!1});if(vr&&!t&&!cn)throw new un;const s=bp(r),i=s.slice(0,12),o=s.slice(12),a=await crypto.subtle.decrypt({name:"AES-GCM",iv:i},n,o);return new TextDecoder().decode(a)}catch(n){if(n instanceof un)throw n;return console.error("Decryption failed:",n),null}}function kl(r){const e=new Uint8Array(r);let t="";for(let n=0;n0}let yr="",dn="";async function ni(){sessionStorage.getItem(Me)&&await ri(),yr=await le("flutterflow"),dn=await le("flutterflow_project_id"),Cp(),Ut()}function si(){document.getElementById("api-keys-modal").classList.add("open"),oi(),yr&&Rl(yr)}function Cl(r){if(r&&r.target!==r.currentTarget)return;const e=document.getElementById("api-keys-modal");e&&e.classList.remove("open");const t=document.getElementById("walkthrough-modal");t&&(ii(),t.classList.add("open"))}let qe=1;function xl(){const r=document.querySelector(".wt-steps");return r?Array.from(r.querySelectorAll(".wt-step-card")):[]}function yn(){const r=xl();r.length&&r.forEach((e,t)=>{const n=t+1;if(n===qe){e.classList.remove("opacity-60","bg-gray-50","border-gray-200"),e.classList.add("bg-blue-50","border-blue-200");const s=e.querySelector("div:first-child");s&&(s.classList.remove("bg-gray-400"),s.classList.add("bg-blue-500"),s.innerHTML=n)}else if(n0&&qe<=r&&(qe++,yn())}function Sp(){const r=document.getElementById("walkthrough-modal");r&&(qe=1,yn(),r.classList.add("open"))}function Ip(r){if(r&&r.target!==r.currentTarget)return;const e=document.getElementById("walkthrough-modal");e&&e.classList.remove("open");const t=document.getElementById("walkthrough-dont-show");t&&t.checked&&localStorage.setItem("hasSeenWalkthrough","true")}function Tl(){if(N.isVerified&&ht()&&q.tier!=="free")return;if(!localStorage.getItem("hasSeenWalkthrough")){const e=document.getElementById("walkthrough-modal");e&&(qe=1,yn(),e.classList.add("open"))}}async function oi(){const r=document.getElementById("flutterflow-api-key-input");yr?(r.value="",r.placeholder="Key saved (enter new to replace)"):r.placeholder="Enter your FlutterFlow API key",kp()}function kp(){Ko("flutterflow","flutterflow-key-status"),Ko("flutterflow_project_id","flutterflow-project-status")}function Ko(r,e){const t=document.getElementById(e);if(!t)return;const n=t.querySelector(".key-status-dot"),s=t.querySelector("span");tt(r)?(n.className="key-status-dot configured",s.className="text-green-600",s.textContent="User key configured"):(n.className="key-status-dot missing",s.className="text-gray-500",s.textContent="Not configured")}function Ut(){const r=tt("flutterflow")&&tt("flutterflow_project_id"),e=g.step2Result&&g.step2Result.length>0,t=document.getElementById("btn-deploy-to-ff"),n=document.getElementById("btn-run-pipeline");n&&n.classList.remove("hidden"),t&&t.classList.toggle("hidden",!(r&&e))}function Cp(){const r=document.getElementById("api-keys-status");if(!r)return;const e=r.querySelectorAll(".key-status-dot"),t=["flutterflow"];e.forEach((n,s)=>{const i=t[s];i==="flutterflow"?tt("flutterflow")&&tt("flutterflow_project_id")?(n.className="key-status-dot configured",n.title="FlutterFlow (Fully configured)"):tt("flutterflow")||tt("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)"):tt(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)")}),Ut()}async function xp(){const r=document.getElementById("flutterflow-api-key-input"),e=document.getElementById("flutterflow-projects-select");r.value.trim()&&await qo("flutterflow",r.value);const t=(e==null?void 0:e.value.trim())||"";if(t){if(!wn(t)){G("The selected FlutterFlow project has an unexpected ID format.","error"),e.focus();return}await qo("flutterflow_project_id",t)}await ni(),oi();const n=document.querySelector("#api-keys-modal .bg-blue-500"),s=n.textContent;n.textContent="Saved!",n.classList.remove("bg-blue-500","hover:bg-blue-600"),n.classList.add("bg-green-500"),setTimeout(()=>{n.textContent=s,n.classList.remove("bg-green-500"),n.classList.add("bg-blue-500","hover:bg-blue-600"),Cl()},1e3)}async function Tp(){if(!confirm("Are you sure you want to clear all stored API keys?"))return;localStorage.setItem(_r,Os()),Nt(),localStorage.removeItem(Pe+"flutterflow"),localStorage.removeItem(Pe+"flutterflow_project_id"),sessionStorage.removeItem(He+"flutterflow"),sessionStorage.removeItem(He+"flutterflow_project_id"),sessionStorage.removeItem(Me),sessionStorage.removeItem(mr),localStorage.removeItem(Pe+"salt"),await mp(),localStorage.setItem(_r,Os()),localStorage.removeItem(Pe+"flutterflow"),localStorage.removeItem(Pe+"flutterflow_project_id"),sessionStorage.removeItem(He+"flutterflow"),sessionStorage.removeItem(He+"flutterflow_project_id"),await ni();const r=document.getElementById("flutterflow-projects-select");r&&(r.innerHTML=''),oi()}function wn(r){return!r||r.trim().length<5||r.includes(" ")?!1:/^[a-zA-Z0-9-]+$/.test(r)}function Rp(r,e){const t=document.getElementById(r);t&&(t.value?e?t.style.borderColor="#22c55e":t.style.borderColor="#ef4444":t.style.borderColor="")}function Ap(){const r=document.getElementById("flutterflow-api-key-input");r&&(r.addEventListener("input",e=>{const t=e.target.value.trim().length>0;Rp("flutterflow-api-key-input",t)}),r.addEventListener("blur",Pp(async e=>{const t=e.target.value.trim();t&&await Rl(t)},500)))}function Pp(r,e){let t;return function(...s){const i=()=>{clearTimeout(t),r(...s)};clearTimeout(t),t=setTimeout(i,e)}}async function Rl(r){const e=document.getElementById("flutterflow-projects-select"),t=document.getElementById("flutterflow-projects-error");if(!e){console.error("Projects dropdown element not found");return}e.innerHTML='',t&&t.classList.add("hidden");try{const s=await new In(r,"").listProjects();if(!s||s.length===0){e.innerHTML='';return}e.innerHTML='',s.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)}),dn&&(e.value=dn)}catch(n){console.error("Failed to fetch projects:",n),e.innerHTML='',t&&(t.textContent=`Failed to load projects: ${n.message}`,t.classList.remove("hidden"))}}function Fp(r){const e=document.getElementById(r),n=e.nextElementSibling.querySelector("svg");e.type==="password"?(e.type="text",n.innerHTML=` - - `):(e.type="password",n.innerHTML=` - - - `)}let g={step1Result:null,step2Result:null,step3Result:null,bundleSpec:null,artifactBundle:null,bundleReview:null,selectedArtifactId:null,currentStep:0,isRunning:!1};function $p(){g.step1Result=null,g.step2Result=null,g.step3Result=null,g.bundleSpec=null,g.artifactBundle=null,g.bundleReview=null,g.selectedArtifactId=null}function Mp(){g.bundleSpec=hr(g.step1Result,{artifactType:"CustomWidget",artifactName:"GeneratedWidget"})}function bn(){var t,n,s,i;const r=tn(g.bundleSpec);g.artifactBundle=hr(g.step2Result,{id:(t=g.bundleSpec)==null?void 0:t.id,title:(n=g.bundleSpec)==null?void 0:n.title,description:(s=g.bundleSpec)==null?void 0:s.description,artifactType:r.artifactType,artifactName:r.artifactName,fileName:r.fileName,dependencies:r.dependencies,relationships:(i=g.bundleSpec)==null?void 0:i.relationships,code:g.step2Result||""});const e=$d(g.artifactBundle);g.artifactBundle={...g.artifactBundle,warnings:[...g.artifactBundle.warnings,...e.findings.map(o=>o.message)],metadata:{...g.artifactBundle.metadata,compatibility:e}},g.selectedArtifactId=tn(g.artifactBundle).id}function En(){var t,n,s,i,o,a,l,c;const r=hr(g.step3Result,{id:(t=g.artifactBundle)==null?void 0:t.id,title:(n=g.artifactBundle)==null?void 0:n.title}),e=new Map(r.artifacts.map(u=>[u.id,u.review]));g.bundleReview=hr({id:(s=g.artifactBundle)==null?void 0:s.id,title:(i=g.artifactBundle)==null?void 0:i.title,artifacts:((a=(o=g.artifactBundle)==null?void 0:o.artifacts)==null?void 0:a.map(u=>({...u,review:e.get(u.id)||u.review||g.step3Result||null})))||[],relationships:(l=g.artifactBundle)==null?void 0:l.relationships,warnings:(c=g.artifactBundle)==null?void 0:c.warnings})}function Al(){const r=Sn();return{artifactType:r.artifactType||"CustomWidget",artifactName:r.artifactName||"GeneratedWidget"}}function Sn(){const r=g.artifactBundle||g.bundleSpec||null;return(Array.isArray(r==null?void 0:r.artifacts)?r.artifacts:[]).find(t=>t.id===g.selectedArtifactId)||tn(r)}function ai(){return Sn().code||g.step2Result||""}async function Op(){try{await ni()}catch(r){return console.error("checkConnection: initializeApiKeys failed:",r),!1}return!0}const Dr={production:"https://api.flutterflow.io/v2/",staging:"https://api.flutterflow.io/v2-staging/"};class In{constructor(e,t,n="main",s=Dr.production){this.apiKey=e,this.baseUrl=s,this._projectId=t,this._branchName=n,this._endpoint=s}get projectId(){return this._projectId}get branchName(){return this._branchName==="main"?"":this._branchName}async exportProjectZip(){var n;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 t=null;for(const s of e)try{const i=await fetch(`${this.baseUrl}exportCode`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify(s)});if(!i.ok){const l=await i.text();t=new Error(`Export failed: ${i.status} - ${l}`);continue}const o=await i.json(),a=((n=o==null?void 0:o.value)==null?void 0:n.project_zip)||(o==null?void 0:o.project_zip);if(!a){t=new Error("Export response did not include project source.");continue}return a}catch(i){t=i}throw t||new Error("Export failed for an unknown reason.")}async fetchProjectSource(){const e=await this.exportProjectZip(),t=await JSZip.loadAsync(e,{base64:!0}),n=Object.keys(t.files).filter(a=>!t.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 s=n.slice(0,n.length-12),i=new Map,o=Object.keys(t.files).filter(a=>{if(t.files[a].dir||!a.startsWith(s))return!1;const l=a.slice(s.length);return l==="lib/flutter_flow/custom_functions.dart"||l.startsWith("lib/custom_code/")&&l.endsWith(".dart")});return await Promise.all(o.map(async a=>{i.set(a.slice(s.length),await t.files[a].async("string"))})),{pubspecYaml:await t.files[n].async("string"),files:i}}async pushCodeWithRetry(e,t=3){const n=[Dr.production,Dr.staging],s=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(c=>setTimeout(c,1e3*(i+1)))}}throw new Error("All API endpoints failed after retries")}async pushCode(e){return this.pushCodeWithRetry(e)}async listProjects(e={}){const{page:t=1,limit:n=100}=e;console.log("Listing projects for API key via V2 endpoint");try{const s=await fetch("https://api.flutterflow.io/v2/l/listProjects",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify({project_type:"ALL",deserialize_response:!0})});if(!s.ok){const a=await s.text();throw new Error(`List projects failed: ${s.status} - ${a}`)}const i=await s.json();if(i.success&&typeof i.value=="string")try{const a=JSON.parse(i.value);if(a&&Array.isArray(a.entries))return a.entries.map(l=>{var c;return{id:l.id,name:((c=l.project)==null?void 0:c.name)||l.id}})}catch(a){console.error("Failed to parse stringified project value:",a)}const o=i.projects||i.items||i.entries||(Array.isArray(i)?i:[]);return Array.isArray(o)?o:[]}catch(s){throw console.error("Error listing projects:",s),s}}}async function li(r){const e=r.clone();let t;try{t=await r.json()}catch{const i=await e.text();if(!r.ok)return{success:!1,responseCode:r.status,errorMessage:i||`HTTP ${r.status}`,errorMap:new Map};throw new Error(`Invalid JSON response: ${i}`)}if(!r.ok){let s=t.message||`HTTP ${r.status}`,i=new Map;if(t.errors)i=new Map(Object.entries(t.errors));else if(!t.message&&typeof t=="object"){const o=Object.keys(t).filter(a=>a.endsWith(".dart")&&Array.isArray(t[a]));o.length>0&&(i=new Map(Object.entries(t)),s=o.flatMap(l=>t[l].map(c=>`${l}: ${c.errorMessage}`)).join(` -`)||`HTTP ${r.status}`)}return{success:!1,responseCode:r.status,errorMessage:s,errorMap:i}}const n=t.value?JSON.parse(t.value):{};return{success:!0,responseCode:r.status,errorMap:new Map(Object.entries(n))}}function ci(r,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."}[r]||`FlutterFlow API error: ${`HTTP ${r}`}`}const M={ACTION:"A",WIDGET:"W",FUNCTION:"F",CODE_FILE:"C",DEPENDENCIES:"D",OTHER:"O"},Pl=/class\s+\w+\s+extends\s+(?:StatelessWidget|StatefulWidget)\b/,Fl=/extends\s+State<\w+>/;function Lp(r,e=""){if(r==="pubspec.yaml")return M.DEPENDENCIES;if(!r.endsWith(".dart")||r.endsWith("index.dart"))return M.OTHER;if(r==="custom_functions.dart")return M.FUNCTION;if(e){const t=Pl.test(e),n=Fl.test(e);if(t||n)return M.WIDGET;if(/^\s*Future(?:<[^>]+>)?\s+\w+\s*\(/m.test(e))return M.ACTION;if(e.match(/^\s*(String|int|double|bool|List|Map|dynamic|void)\s+\w+\s*\(/m))return M.FUNCTION}return M.CODE_FILE}function $l(r,e){switch(e){case M.ACTION:return`lib/custom_code/actions/${r}`;case M.WIDGET:return`lib/custom_code/widgets/${r}`;case M.FUNCTION:return"lib/flutter_flow/custom_functions.dart";case M.CODE_FILE:return`lib/custom_code/${r}`;case M.DEPENDENCIES:return"pubspec.yaml";case M.OTHER:return`lib/custom_code/${r}`;default:return r}}async function ui(r,e=new Map){return qd(r,e)}const Ls=new Map;function Ml(r){return`${r.baseUrl}|${r.projectId}|${r.branchName}`}function kn(r){Ls.delete(Ml(r))}async function di(r,e,t,n){const s=Hd(e,t);if(s.length===0)return{remoteFiles:t,syncFileMap:e};console.log(`Provisioning ${s.length} new FlutterFlow custom code file(s) before sync.`);const i=await fetch(rp,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:r.apiKey,projectId:r.projectId,baseUrl:r.baseUrl,commitMessage:n,customClasses:s})}),o=await i.text();let a={};try{a=o?JSON.parse(o):{}}catch{a={}}if(!i.ok||a.success===!1){const l=a.details?` ${a.details}`:"";throw new Error(`${a.error||"FlutterFlow custom class provisioning failed."}${l}`)}return kn(r),{remoteFiles:t,syncFileMap:Wd(e,s)}}async function pi(r,e={}){const t=Ml(r);let n=Ls.get(t);if(n===void 0){try{n=await r.fetchProjectSource()}catch(i){throw new Error(`Could not read your project's pubspec.yaml (${i.message}). Deploy was stopped so your existing package dependencies aren't overwritten. Check your FlutterFlow API key and project, then try again.`)}const s=yl(n.pubspecYaml);if(!s.valid)throw new Error(`Your project's pubspec.yaml could not be read reliably (${s.errors.join("; ")}). Deploy was stopped so your existing package dependencies aren't overwritten.`);Ls.set(t,n)}return{...Zd(n.pubspecYaml,e),remoteFiles:n.files}}function Np(r){const e=[],t=[];r.content.length>5e4&&t.push("Code file is large (>50KB). This may take longer to commit."),r.content.length>1e5&&e.push("Code file is too large (>100KB). Consider splitting into smaller components.");const n=r.content.split(` -`).length;n>500&&t.push(`Code has ${n} lines. Consider breaking it into smaller widgets.`),r.content.includes("setState")&&r.codeType===M.ACTION&&t.push("Using setState in a Custom Action may not work as expected. Consider using a Custom Widget."),r.content.includes("dynamic")&&!r.content.includes("?")&&t.push('Code uses "dynamic" types. Consider adding explicit types for better null safety.'),r.content.match(/Color\(0xFF[0-9A-Fa-f]{6}\)/)&&t.push("Code contains hardcoded colors. Consider using FlutterFlowTheme.of(context) for theme consistency.");const s=r.content.match(/print\s*\(/g);return s&&s.length>3&&t.push(`Code contains ${s.length} print statements. Consider removing debug prints before committing.`),{canProceed:e.length===0,issues:e,warnings:t}}async function Dp(r,e){let t=` -
-
-

Commit Summary

-

- File: ${r.fileName}
- Type: ${r.artifactType}
- Size: ${(r.content.length/1024).toFixed(1)} KB
- Lines: ${r.content.split(` -`).length} -

-
- `;return e.warnings.length>0&&(t+=` -
-

Warnings (${e.warnings.length})

-
    - ${e.warnings.map(n=>`
  • • ${n}
  • `).join("")} -
-
- `),e.issues.length>0&&(t+=` -
-

Issues (${e.issues.length})

-
    - ${e.issues.map(n=>`
  • • ${n}
  • `).join("")} -
-
- `),t+="
",console.log("Pre-commit summary:",t),e.canProceed?e.warnings.length>0?confirm(`Found ${e.warnings.length} warning(s). Proceed with commit? - -${e.warnings.join(` -`)}`):!0:!1}function Ol(r,e={}){const{artifactType:t="CustomWidget",artifactName:n="GeneratedCode"}=e;let s=r.trim();s.startsWith("```dart")?s=s.replace(/^```dart\n/,""):s.startsWith("```")&&(s=s.replace(/^```\n/,"")),s.endsWith("```")&&(s=s.replace(/\n```$/,""));let i=n;i.endsWith(".dart")||(i+=".dart");let o=M.CODE_FILE;switch(t){case"CustomAction":o=M.ACTION;break;case"CustomWidget":o=M.WIDGET;break;case"CustomFunction":o=M.FUNCTION,i="custom_functions.dart";break;case"CustomClass":case"CodeFile":o=M.CODE_FILE;break}let a="";return o===M.WIDGET?a=`// 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! - -`:o===M.ACTION?a=`// 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! - -`:o===M.FUNCTION&&(a=`// 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:a+s,fileName:i,codeType:o,artifactType:t,artifactName:n}}function Bp(r){const e={},t=[{name:"flutter_animate",pattern:/flutter_animate/},{name:"google_fonts",pattern:/google_fonts/},{name:"flutter_svg",pattern:/flutter_svg/},{name:"http",pattern:/package:http\b/},{name:"intl",pattern:/package:intl\b/},{name:"collection",pattern:/package:collection\b/},{name:"rxdart",pattern:/package:rxdart\b/},{name:"timeago",pattern:/package:timeago\b/},{name:"url_launcher",pattern:/package:url_launcher\b/},{name:"cloud_firestore",pattern:/package:cloud_firestore\b/},{name:"firebase_auth",pattern:/package:firebase_auth\b/},{name:"flutter_tts",pattern:/package:flutter_tts\b/},{name:"percent_indicator",pattern:/package:percent_indicator\b/},{name:"fl_chart",pattern:/package:fl_chart\b/},{name:"cached_network_image",pattern:/package:cached_network_image\b/},{name:"image_picker",pattern:/package:image_picker\b/},{name:"file_picker",pattern:/package:file_picker\b/},{name:"shared_preferences",pattern:/package:shared_preferences\b/},{name:"sqflite",pattern:/package:sqflite\b/},{name:"path_provider",pattern:/package:path_provider\b/},{name:"uuid",pattern:/package:uuid\b/},{name:"xml",pattern:/package:xml\b/},{name:"html",pattern:/package:html\b/},{name:"csv",pattern:/package:csv\b/},{name:"pdf",pattern:/package:pdf\b/},{name:"printing",pattern:/package:printing\b/},{name:"flutter_local_notifications",pattern:/package:flutter_local_notifications\b/},{name:"geolocator",pattern:/package:geolocator\b/},{name:"geocoding",pattern:/package:geocoding\b/},{name:"firebase_core",pattern:/package:firebase_core\b/},{name:"firebase_storage",pattern:/package:firebase_storage\b/},{name:"firebase_messaging",pattern:/package:firebase_messaging\b/},{name:"cloud_functions",pattern:/package:cloud_functions\b/},{name:"firebase_analytics",pattern:/package:firebase_analytics\b/},{name:"stripe_checkout",pattern:/package:stripe_checkout\b/},{name:"pay",pattern:/package:pay\b/},{name:"in_app_purchase",pattern:/package:in_app_purchase\b/},{name:"audioplayers",pattern:/package:audioplayers\b/},{name:"just_audio",pattern:/package:just_audio\b/},{name:"video_player",pattern:/package:video_player\b/},{name:"chewie",pattern:/package:chewie\b/},{name:"flutter_rating_bar",pattern:/package:flutter_rating_bar\b/},{name:"shimmer",pattern:/package:shimmer\b/},{name:"carousel_slider",pattern:/package:carousel_slider\b/},{name:"flutter_staggered_grid_view",pattern:/package:flutter_staggered_grid_view\b/},{name:"smooth_page_indicator",pattern:/package:smooth_page_indicator\b/},{name:"qr_flutter",pattern:/package:qr_flutter\b/},{name:"barcode_widget",pattern:/package:barcode_widget\b/},{name:"qr_code_scanner",pattern:/package:qr_code_scanner\b/},{name:"lottie",pattern:/package:lottie\b/},{name:"rive",pattern:/package:rive\b/}];for(const{name:n,pattern:s}of t)s.test(r)&&(e[n]="^1.0.0");return e}function jp(r,e={}){return{timestamp:new Date().toISOString(),artifactType:r.artifactType,artifactName:r.artifactName,codeType:r.codeType,fileName:r.fileName,generatedFrom:e.step1Result?"pipeline":"direct",model:e.selectedModel||"unknown",codeSize:r.content.length}}function Up(r,e,t){const n=[],s=Pl.test(e),i=Fl.test(e),o=[{pattern:/void\s+main\s*\(/,message:"Contains main() function - not allowed in FlutterFlow"},{pattern:/runApp\s*\(/,message:"Contains runApp() - not allowed in FlutterFlow"},{pattern:/MaterialApp\s*\(/,message:"Contains MaterialApp - not allowed in FlutterFlow"},{pattern:/Scaffold\s*\(/,message:"Contains Scaffold - usually not needed in FlutterFlow widgets"}],a=r.includes("custom_functions")||r.includes("functions"),l=/^\s*import\s+['"]([^'"]+)['"]/gm;let c;for(;(c=l.exec(e))!==null;){const u=c[1],d=u.startsWith("/flutter_flow/")||u.startsWith("/backend/")||u.startsWith("/custom_code/")||u==="index.dart"||u==="package:flutter/material.dart"||u==="package:flutter/services.dart",p=u.startsWith("dart:")||u.startsWith("package:");a?u.startsWith("dart:")||n.push(`Custom Functions cannot use '${u}' - only Dart SDK imports allowed`):!d&&!p&&n.push(`Unknown import '${u}' - use FlutterFlow managed imports`)}for(const{pattern:u,message:d}of o)u.test(e)&&n.push(d);return t===M.WIDGET&&!s&&!i&&n.push("No widget class definition found (must extend StatelessWidget or StatefulWidget)"),{valid:n.length===0,errors:n}}function Cn(r){const e=[],t=[];if(!r||r.size===0)return e.push("No files to commit"),{valid:!1,errors:e,warnings:t};for(const[n,s]of r.entries()){if((!s.content||s.content.trim().length===0)&&e.push(`File ${n} is empty`),s.content&&s.content.length>1e5&&t.push(`File ${n} is very large (>100KB)`),n.endsWith(".dart")){const i=Up(n,s.content,s.type);i.valid||e.push(...i.errors.map(o=>`${n}: ${o}`))}if(n==="pubspec.yaml"){const i=yl(s.content);i.valid||e.push(...i.errors)}}return{valid:e.length===0,errors:e,warnings:t}}const O={IDLE:"IDLE",PREPARING:"PREPARING",VALIDATING:"VALIDATING",PUSHING:"PUSHING",SUCCESS:"SUCCESS",ERROR:"ERROR"},D={currentState:O.IDLE,startTime:null,endTime:null,error:null,result:null,filesProcessed:0,totalFiles:0,reset(){this.currentState=O.IDLE,this.startTime=null,this.endTime=null,this.error=null,this.result=null,this.filesProcessed=0,this.totalFiles=0},setState(r){if(!Object.values(O).includes(r)){console.error(`Invalid commit state: ${r}`);return}this.currentState=r,r===O.PREPARING&&(this.startTime=Date.now()),(r===O.SUCCESS||r===O.ERROR)&&(this.endTime=Date.now()),typeof window<"u"&&window.dispatchEvent&&window.dispatchEvent(new CustomEvent("commitStateChange",{detail:{state:r,commitState:this}})),console.log(`Commit state changed to: ${r}`)},setError(r){this.error=r,this.setState(O.ERROR)},setSuccess(r){this.result=r,this.setState(O.SUCCESS)},setProgress(r,e){this.filesProcessed=r,this.totalFiles=e},getElapsedTime(){return this.startTime?(this.endTime||Date.now())-this.startTime:null},isInProgress(){return this.currentState===O.PREPARING||this.currentState===O.VALIDATING||this.currentState===O.PUSHING}};async function Hp(r,e,t={}){let{codeType:n="W"}=t;const{pubspecDeps:s={},artifactName:i=e}=t;n==="CustomWidget"&&(n=M.WIDGET),n==="CustomAction"&&(n=M.ACTION),n==="CustomFunction"&&(n=M.FUNCTION),n==="CustomClass"&&(n=M.CODE_FILE),n==="CodeFile"&&(n=M.CODE_FILE),D.reset(),D.setState(O.PREPARING);try{const o=await le("flutterflow"),a=await le("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(!wn(a))throw new Error("Invalid FlutterFlow Project ID format.");const l=Ir(),c=new In(o,a,"main",l);D.setState(O.VALIDATING);const u=new Map,d=n||Lp(e,r),p=$l(e,d);u.set(e,{artifactName:i,content:r,type:d,path:p}),D.setProgress(0,u.size);const h=Cn(u);if(!h.valid)throw new Error(`Validation failed: -${h.errors.join(` -`)}`);const m=await pi(c,s),_=m.yaml,v=await di(c,u,m.remoteFiles,`Provision ${i} custom class`),k=await ui(v.syncFileMap,v.remoteFiles),I=new Map(v.syncFileMap);I.set("pubspec.yaml",{content:_,type:"D",path:"pubspec.yaml"});const R=await fi(I),T={project_id:a,zipped_custom_code:R,uid:`web_${Date.now()}`,branch_name:c.branchName,serialized_yaml:_,file_map:k.fileMapContents,functions_map:k.functionsMapContents};D.setState(O.PUSHING),D.setProgress(1,u.size),kn(c);const w=await c.pushCode(T),P=await li(w);if(P.success)D.setSuccess({fileCount:u.size,projectId:a,warnings:P.errorMap&&P.errorMap.size>0?Array.from(P.errorMap.entries()):[]});else{const A=P.errorMessage||ci(P.responseCode);throw new Error(A)}return{success:!0,message:`Successfully committed ${e} to FlutterFlow project ${a}`,addedDependencies:m.added,warnings:P.errorMap?Array.from(P.errorMap.entries()):[]}}catch(o){return console.error("Commit failed:",o),D.setError(o),{success:!1,error:o.message,state:D.currentState}}}async function fi(r){try{const e=new JSZip;for(const[n,s]of r.entries())e.file(n,s.content);return await e.generateAsync({type:"base64",compression:"DEFLATE",compressionOptions:{level:6}})}catch(e){return console.error("Error creating zip:",e),""}}async function Ll(r,e={}){const{artifactType:t,artifactName:n,pipelineResult:s}=e;console.log(`Starting commit for ${n} (${t})`);try{D.setState(O.PREPARING);const i=Ol(r,{artifactType:t,artifactName:n}),o=Bp(i.content);console.log("Detected dependencies:",o),D.setState(O.VALIDATING);const a=await le("flutterflow"),l=await le("flutterflow_project_id");if(!a)throw new Error("FlutterFlow API Key not configured. Please add it in API Keys settings.");if(!l)throw new Error("FlutterFlow Project ID not configured. Please add it in API Keys settings.");if(!wn(l))throw new Error("Invalid FlutterFlow Project ID format.");const c=new Map;c.set(i.fileName,{artifactName:n,content:i.content,type:i.codeType,path:$l(i.fileName,i.codeType),functionName:i.codeType===M.FUNCTION?n:void 0}),D.setProgress(0,c.size);const u=Cn(c);if(!u.valid)throw new Error(`File validation failed: -${u.errors.join(` -`)}`);u.warnings.length>0&&console.warn("Validation warnings:",u.warnings),D.setState(O.PUSHING);const d=Ir(),p=new In(a,l,"main",d),h=await pi(p,o),m=h.yaml,_=await di(p,c,h.remoteFiles,`Provision ${n} custom class`),v=await ui(_.syncFileMap,_.remoteFiles),k=new Map(_.syncFileMap);k.set("pubspec.yaml",{content:m,type:M.DEPENDENCIES,path:"pubspec.yaml"});const I=await fi(k),R={project_id:l,zipped_custom_code:I,uid:`web_${Date.now()}`,branch_name:p.branchName,serialized_yaml:m,file_map:v.fileMapContents,functions_map:v.functionsMapContents};D.setProgress(1,c.size),kn(p);const T=await p.pushCode(R),w=await li(T);if(w.success){const P={...jp(i,s),projectId:l};return D.setSuccess({...P,fileCount:c.size,warnings:w.errorMap?Array.from(w.errorMap.entries()):[]}),{success:!0,message:`Successfully committed ${i.fileName} to FlutterFlow`,metadata:P,addedDependencies:h.added,warnings:w.errorMap?Array.from(w.errorMap.entries()):[],elapsedTime:D.getElapsedTime()}}else{const P=w.errorMessage||ci(w.responseCode),A=new Error(P);throw A.errorMap=w.errorMap,A}}catch(i){console.error("Commit execution failed:",i),D.setError(i);let o=new Map;if(i.errorMap)o=i.errorMap;else if(i.message&&i.message.includes("{"))try{const a=i.message.match(/\{[\s\S]*\}/);if(a){const l=JSON.parse(a[0]);o=new Map(Object.entries(l))}}catch{}return{success:!1,error:i.message,errorMap:o,state:D.currentState,elapsedTime:D.getElapsedTime()}}}async function Wp(r,e={}){var n;const{pipelineResult:t}=e;try{if(D.setState(O.PREPARING),((n=r.errors)==null?void 0:n.length)>0)throw new Error(`Bundle validation failed: -${r.errors.join(` -`)}`);const s=new Map(r.fileEntries.map(w=>[w.fileName,{artifactId:w.artifactId,artifactName:w.artifactName,content:w.content,type:w.type,path:w.path,functionName:w.type===M.FUNCTION?w.artifactName:void 0}]));D.setProgress(0,s.size);const i=Cn(s);if(!i.valid)throw new Error(`File validation failed: -${i.errors.join(` -`)}`);D.setState(O.VALIDATING);const o=await le("flutterflow"),a=await le("flutterflow_project_id");if(!o)throw new Error("FlutterFlow API Key not configured. Please add it in API Keys settings.");if(!a)throw new Error("FlutterFlow Project ID not configured. Please add it in API Keys settings.");if(!wn(a))throw new Error("Invalid FlutterFlow Project ID format.");D.setState(O.PUSHING);const l=Ir(),c=new In(o,a,"main",l),u=await pi(c,r.dependencies),d=u.yaml,p=await di(c,s,u.remoteFiles,`Provision ${r.title} custom classes`),h=await ui(p.syncFileMap,p.remoteFiles),m=new Map(p.syncFileMap);m.set("pubspec.yaml",{content:d,type:M.DEPENDENCIES,path:"pubspec.yaml"});const _=await fi(m),v={project_id:a,zipped_custom_code:_,uid:`web_${Date.now()}`,branch_name:c.branchName,serialized_yaml:d,file_map:h.fileMapContents,functions_map:h.functionsMapContents};D.setProgress(1,s.size),kn(c);const k=await c.pushCode(v),I=await li(k);if(I.success){const w={...t,artifactType:"Bundle",artifactName:r.title,fileName:`${r.fileEntries.length} artifacts`,codeSize:r.fileEntries.reduce((P,A)=>P+A.content.length,0),projectId:a};return D.setSuccess({...w,fileCount:s.size,warnings:I.errorMap?Array.from(I.errorMap.entries()):[]}),{success:!0,message:`Successfully committed ${r.fileEntries.length} artifacts to FlutterFlow`,metadata:w,addedDependencies:u.added,warnings:I.errorMap?Array.from(I.errorMap.entries()):[],elapsedTime:D.getElapsedTime()}}const R=I.errorMessage||ci(I.responseCode),T=new Error(R);throw T.errorMap=I.errorMap,T}catch(s){return console.error("Bundle commit execution failed:",s),D.setError(s),{success:!1,error:s.message,errorMap:s.errorMap||new Map,state:D.currentState,elapsedTime:D.getElapsedTime()}}}async function zp(r){try{return await pn("architect",As,wd(r),Qs("architect"))}catch(e){throw e.isModelArmor?e:new Error(`Prompt Architect failed: ${e.message}`)}}async function xn(r,e){const t=bd(r),n=Qs("generator",g.bundleSpec);try{return await pn("generator",e,t,n)}catch(s){if(s.isModelArmor)throw s;if(e!==es){console.warn(`Code Generator failed with ${e}, retrying with fallback model:`,s.message);try{return await pn("generator",es,t,n)}catch(i){throw i.isModelArmor?i:new Error(`Code Generator failed: primary (${e}): ${s.message} | fallback (${es}): ${i.message}`)}}throw new Error(`Code Generator failed: ${s.message}`)}}async function Tn(r,e=null){const t={...Qs("review",g.artifactBundle||g.bundleSpec),architect_output:e};try{return await pn("review",Ps,Ed(r),t)}catch(n){throw n.isModelArmor?n:new Error(`Code Review failed: ${n.message}`)}}function hi(r,e){return r.isModelArmor?`${r.userTitle}: ${r.userMessage}`:`${e}: ${r.message}`}function Ns(r,e){const t=document.getElementById(`step${r}-item`),n=document.getElementById(`step${r}-status`);!t||!n||(t.classList.remove("active","completed","error"),n.classList.remove("running","completed","error"),e==="active"?(t.classList.add("active"),n.classList.add("running"),n.innerHTML=` - - `):e==="completed"?(t.classList.add("completed"),n.classList.add("completed"),n.innerHTML=` - - `):e==="error"?(t.classList.add("error"),n.classList.add("error"),n.innerHTML=` - - `):n.innerHTML=` - - `)}function Z(r,e){const t=document.getElementById(`step${r}-loading`),n=document.getElementById(`step${r}-result`);e?(t.classList.remove("hidden"),n.classList.add("hidden"),Ns(r,"active")):(t.classList.add("hidden"),n.classList.remove("hidden"),Ns(r,"completed"))}function Gp(r){const e=document.getElementById(`${r}-content`),t=document.getElementById(`${r}-chevron`);e.classList.contains("open")?(e.classList.remove("open"),t&&(t.style.transform="rotate(0deg)")):(e.classList.add("open"),t&&(t.style.transform="rotate(180deg)"))}function qp(r){we(parseInt(r.replace("step","")))}function we(r){for(let o=1;o<=3;o++){const a=document.getElementById(`step${o}-item`);a&&a.classList.remove("active")}const e=document.getElementById(`step${r}-item`);e&&e.classList.add("active"),gt();const t=document.getElementById("ready-state");t&&t.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${r}-content`);n&&n.classList.remove("hidden");const s=document.getElementById("stage-title"),i={1:"Prompt Architect",2:"Code Generator",3:"Code Review"};s&&(s.textContent=i[r]||"Active Workflow Stage")}function Kp(r){const e=document.getElementById(r);if(!e)return;const t=e.dataset.raw||e.textContent;navigator.clipboard.writeText(t).then(()=>{Ae("Code Copied",{elementId:r});const n=e.closest(".code-container"),s=n==null?void 0:n.querySelector(".copy-btn");s&&(s.classList.add("copied"),s.innerHTML=' Copied!',setTimeout(()=>{s.classList.remove("copied"),s.innerHTML=' Copy'},2e3))}).catch(n=>{console.warn("Failed to copy to clipboard:",n)})}function Ds(r){const e=document.getElementById("step1-model-label");e&&(e.textContent=ve(As));const t=js(r),n=document.getElementById("step2-model-label");n&&(t!==r?n.textContent=`${ve(r)} → ${ve(t)} (Free Tier)`:n.textContent=ve(r));const s=document.getElementById("step3-model-label");s&&(s.textContent=ve(Ps)),console.log(`Step 1 (Prompt Architect): ${ve(As)}`),console.log(t!==r?`Step 2 (Code Generator): ${ve(r)} → ${ve(t)} (Free Tier fallback)`:`Step 2 (Code Generator): ${ve(r)}`),console.log(`Step 3 (Code Review): ${ve(Ps)}`)}async function Vp(){if(console.log("runRefinement called"),g.isRunning)return;const r=document.getElementById("code-generator-model").value;g.isRunning=!0,gi("standardRegenerate",g.step2Result,g.step1Result);const e=document.querySelectorAll(".btn-refine-action");e.forEach(t=>{t.disabled=!0,t.innerHTML=` - - - Refining...`});try{const t=Sn(),n=Sd({bundleSpec:g.step1Result,artifactBundle:JSON.stringify(g.artifactBundle||g.step2Result),bundleReview:g.step3Result,artifactId:t.id,userFeedback:"Fix the issues listed in the audit report."});Fn(),$e(2),we(2),Z(2,!0),g.step2Result=await xn(n,r),bn();const s=document.getElementById("step2-output"),i=Ot(g.step2Result);s.textContent=i,s.dataset.raw=i,Z(2,!1),we(3),$e(3),Z(3,!0),g.step3Result=await Tn(g.step2Result,g.step1Result),En();const o=document.getElementById("step3-output");o.textContent=g.step3Result,Z(3,!1),ot();const a=jt(g.step3Result);$n(i,a)}catch(t){console.error("Refinement failed:",t),ot(),G(hi(t,"Refinement failed"),"error")}finally{g.isRunning=!1,e.forEach(t=>{t.disabled=!1,t.textContent="Refine & Regenerate"}),Ut()}}async function gi(r,e,t){const n=`${Se}/connectFeedback`,s={type:r,code:e,input:t};try{const i=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)});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 Yp(){const r=document.getElementById("ff-error-paste-input");r&&(r.value="")}async function Jp(){var s;const r=document.getElementById("ff-error-paste-input"),e=(s=r==null?void 0:r.value)==null?void 0:s.trim();if(!e){r==null||r.focus(),r==null||r.classList.add("ring-2","ring-red-400","border-red-300"),setTimeout(()=>r==null?void 0:r.classList.remove("ring-2","ring-red-400","border-red-300"),2e3);return}if(!g.step2Result){G("No generated code found. Please run the full pipeline first.","warning");return}if(g.isRunning)return;const t=document.getElementById("code-generator-model").value;g.isRunning=!0,gi("flutterflowError",g.step2Result,e);const n=document.getElementById("btn-fix-from-errors");n&&(n.disabled=!0,n.innerHTML=` - - Fixing…`);try{const i=fl({bundleSpec:g.step1Result,artifactBundle:JSON.stringify(g.artifactBundle||g.step2Result),bundleReview:g.step3Result,userFeedback:e});Gl(),Fn(),$e(2),we(2),Z(2,!0),g.step2Result=await xn(i,t),bn();const o=document.getElementById("step2-output"),a=Ot(g.step2Result);o.textContent=a,o.dataset.raw=a,Z(2,!1),we(3),$e(3),Z(3,!0),g.step3Result=await Tn(g.step2Result,g.step1Result),En();const l=document.getElementById("step3-output");l.textContent=g.step3Result,Z(3,!1),ot();const c=jt(g.step3Result);$n(a,c),r&&(r.value="")}catch(i){console.error("Fix from errors failed:",i),ot(),G(hi(i,"Failed to fix errors"),"error")}finally{g.isRunning=!1,n&&(n.disabled=!1,n.textContent="Fix Errors & Regenerate"),Ut()}}async function Bs(){if(console.log("runThinkingPipeline called"),g.isRunning)return;localStorage.setItem("hasSeenWalkthrough","true");const r=document.getElementById("pipeline-input").value,e=document.getElementById("code-generator-model").value;if(!r.trim()){G("Please describe your FlutterFlow widget first.","warning");return}if(!await _f())return;const t=js(e);Ae("Pipeline Started",{selectedModel:e,effectiveModel:t,inputLength:r.length});const n=document.getElementById("btn-run-pipeline");g.isRunning=!0,$p(),n.disabled=!0,n.innerHTML=` - - - Running...`,Ds(t);try{gt();const s=document.getElementById("ready-state");s&&s.classList.add("hidden");const i=document.getElementById("paywall-exhausted");i&&i.classList.add("hidden"),Fn(),we(1),$e(1),Z(1,!0),g.step1Result=await zp(r),Mp(),Ae("Prompt Architect Completed");const o=document.getElementById("step1-output"),a=Ot(g.step1Result);o.textContent=a,o.dataset.raw=a,Z(1,!1),we(2),$e(2),Z(2,!0),g.step2Result=await xn(g.step1Result,t),bn(),Ae("Code Generator Completed");const l=document.getElementById("step2-output"),c=Ot(g.step2Result);l.textContent=c,l.dataset.raw=c,Z(2,!1),we(3),$e(3),Z(3,!0),g.step3Result=await Tn(g.step2Result,g.step1Result),En(),Ae("Code Review Completed");const u=document.getElementById("step3-output");u.textContent=g.step3Result,Z(3,!1),ot();const d=jt(g.step3Result);$n(c,d),pf(),An()}catch(s){if(console.error("Pipeline failed:",s),ot(),s.isUsageLimit){const{count:u}=Rn();Ei(u,bi(),{openModal:!0});return}Ae("Pipeline Failed",{error:s.message,effectiveModel:js(document.getElementById("code-generator-model").value)});let o={architect:1,generator:2,review:3}[s.pipelineStep]||1;!s.pipelineStep&&(s.message.includes("Claude")||s.message.includes("OpenAI")||s.message.includes("Code Generator"))?o=2:!s.pipelineStep&&s.message.includes("Code Review")&&(o=3),we(o);const a=document.getElementById(`step${o}-result`),l=document.getElementById(`step${o}-loading`),c=document.getElementById(`step${o}-output`);if(l&&l.classList.add("hidden"),a&&a.classList.remove("hidden"),c)if(s.isModelArmor)c.innerHTML=``;else{let u=s.message;s.message.includes("image input")?u=`This model doesn't support image input. Please use ${ve(gr)} for image-based requests or remove image references from your prompt.`:(s.message.includes("Load failed")||s.message.includes("CORS"))&&(u="API connection failed. This might be due to CORS restrictions or network issues. Please check your API key and try again."),c.innerHTML=`
-

Connection Error

-

${ee(u)}

-
-

Check if API key is valid

-

Try using a different model

-

Ensure network allows API calls

-
-
`}Ns(o,"error")}finally{g.isRunning=!1,n.disabled=!1,n.innerHTML=` - - - Run Pipeline`,Ut()}}function Zp(){const r=document.getElementById("code-generator-model").value,e=[gr,"anthropic/claude-opus-5","openai/gpt-5.6-sol"].filter(n=>n!==r),t=prompt(`Retry with different model? - -Current: ${r} - -Options: -1. ${e[0]} -2. ${e[1]} - -Enter 1 or 2:`);t==="1"?(document.getElementById("code-generator-model").value=e[0],Bs()):t==="2"&&(document.getElementById("code-generator-model").value=e[1],Bs())}async function Xp(){var c,u,d;const r=ai();if(!r){G("No code to commit. Please run the pipeline first.","warning");return}const e=await le("flutterflow"),t=await le("flutterflow_project_id");if(!e||!t){G("FlutterFlow credentials not configured. Add your API Key and Project ID in settings.","warning"),si();return}if(((u=(c=g.artifactBundle)==null?void 0:c.artifacts)==null?void 0:u.length)>1){await Qp();return}const{artifactType:n,artifactName:s}=Al(),i=Ol(r,{artifactType:n,artifactName:s}),o=Np(i);if(!await Dp(i,o)){console.log("User cancelled commit");return}Ii(),Ae("Deploy to FlutterFlow Started",{artifactType:n,artifactName:s});const l=await Ll(r,{artifactType:n,artifactName:s,pipelineResult:{step1Result:g.step1Result,selectedModel:(d=document.getElementById("code-generator-model"))==null?void 0:d.value}});wr(),l.success?(Ae("Deploy to FlutterFlow Success",{artifactType:n,artifactName:s}),hn(l)):(Ae("Deploy to FlutterFlow Failed",{artifactType:n,artifactName:s,error:l.error}),gn(l))}async function Qp(){const r=await le("flutterflow"),e=await le("flutterflow_project_id");if(!r||!e){G("FlutterFlow credentials not configured. Add your API Key and Project ID in settings.","warning"),si();return}const t=Dd(g.artifactBundle);if(t.errors.length>0){G(`Bundle validation failed: ${t.errors.join("; ")}`,"error");return}const n=new Map(t.fileEntries.map(a=>[a.fileName,{content:a.content,type:a.type,path:a.path}])),s=Cn(n),i={canProceed:s.valid&&t.errors.length===0,issues:[...t.errors,...s.errors],warnings:[...t.warnings,...s.warnings]};if(!i.canProceed){G(`Bundle validation failed: ${i.issues.join("; ")}`,"error");return}const o={content:t.fileEntries.map(a=>`// ${a.fileName} -${a.content}`).join(` - -`),fileName:`${t.fileEntries.length} files`,codeType:"bundle",artifactType:"Bundle",artifactName:t.title};kf(o,i,t.dependencies,t)}function ef(r){var s;let e=r.errorMap||new Map;!(e instanceof Map)&&typeof e=="object"&&(e=new Map(Object.entries(e)));let t=`
-

FlutterFlow Commit Failed

-

${ee(r.error)}

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

Errors:

-
    `;for(const[i,o]of e.entries()){const a=o.errorMessage||o;t+=`
  • - ${ee(i)}: ${ee(a)} -
  • `}t+="
"}t+="
",t+=`
- -
`;const n=document.getElementById("step3-output");n&&(n.innerHTML=t,(s=document.getElementById("btn-regenerate-from-error"))==null||s.addEventListener("click",()=>{tf(r.error,e)}))}async function tf(r,e){if(g.isRunning)return;const t=document.getElementById("code-generator-model").value;g.isRunning=!0;const n=document.getElementById("btn-regenerate-from-error");n&&(n.disabled=!0,n.innerHTML=` - - Fixing...`);try{let s=`The previous code had the following errors when committing to FlutterFlow: - -`;if(e&&e.size>0)for(const[u,d]of e.entries()){const p=d.errorMessage||d;s+=`File: ${u} -Error: ${p} - -`}else s+=`${r} -`;const i=fl({bundleSpec:g.step1Result,artifactBundle:JSON.stringify(g.artifactBundle||g.step2Result),bundleReview:g.step3Result,userFeedback:s});Fn(),$e(2),we(2),Z(2,!0),g.step2Result=await xn(i,t),bn();const o=document.getElementById("step2-output"),a=Ot(g.step2Result);o.textContent=a,o.dataset.raw=a,Z(2,!1),we(3),$e(3),Z(3,!0),g.step3Result=await Tn(g.step2Result,g.step1Result),En();const l=document.getElementById("step3-output");l.textContent=g.step3Result,Z(3,!1),ot();const c=jt(g.step3Result);$n(a,c)}catch(s){console.error("Regeneration failed:",s),ot(),G(hi(s,"Regeneration failed"),"error")}finally{g.isRunning=!1,n&&(n.disabled=!1,n.textContent="Fix Errors & Regenerate"),Ut()}}async function rf(){const r=document.getElementById("ff-status-dot"),e=document.getElementById("ff-status-text");if(!r||!e)return;const t=await le("flutterflow"),n=await le("flutterflow_project_id");t&&n?(r.className="w-2 h-2 rounded-full bg-green-500",e.textContent="FlutterFlow credentials configured",e.className="text-green-600"):t||n?(r.className="w-2 h-2 rounded-full bg-yellow-500",e.textContent="FlutterFlow credentials incomplete",e.className="text-yellow-600"):(r.className="w-2 h-2 rounded-full bg-red-500",e.textContent="FlutterFlow credentials not configured",e.className="text-red-600")}async function nf(r){try{const e=await fetch(`${Se}/auth/send-magic-link`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:r})});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:r,message:e.message,stack:e.stack}),e}}async function sf(r){try{const t=await(await fetch(`${Se}/auth/verify-magic-link`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:r})})).json();if(t.error||!t.email||!t.sessionToken)throw new Error(t.error||"Invalid or expired link");return t}catch(e){throw console.error("verifyMagicLink failed:",{message:e.message,stack:e.stack}),e}}async function of(r){try{const e=await fetch(`${Se}/auth/refresh-session`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:r})});if(!e.ok)return console.error("refreshSession: non-OK response",{url:`${Se}/auth/refresh-session`,status:e.status}),null;const t=await e.json();return t.error||!t.email||!t.sessionToken?(console.warn("refreshSession: validation failed",{error:t.error,hasEmail:!!t.email,hasToken:!!t.sessionToken}),null):t}catch(e){return console.error("refreshSession: fetch failed",{url:`${Se}/auth/refresh-session`,message:e.message,stack:e.stack}),null}}function Vo(r,e){const t=Nl(),n=(N.email||t.email)!==r;N.email=r,N.sessionToken=e,N.isVerified=!0,q=Lt({isLoading:!0}),localStorage.setItem(nn,JSON.stringify({email:r,sessionToken:e})),n&&Si()}function mi(){N.email=null,N.sessionToken=null,N.isVerified=!1,q=Lt({isResolved:!0}),localStorage.removeItem(nn),localStorage.removeItem(on)}function Nl(){try{const r=localStorage.getItem(nn);if(!r)return{email:null,sessionToken:null};const e=JSON.parse(r);return!e.email||!e.sessionToken?{email:null,sessionToken:null}:e}catch(r){return console.warn("getStoredSession: failed to parse auth session:",r),localStorage.removeItem(nn),{email:null,sessionToken:null}}}async function af(){const e=new URLSearchParams(window.location.search).get("token");if(e){window.history.replaceState({},"",window.location.pathname);try{const{email:t,sessionToken:n}=await sf(e);Vo(t,n)}catch(t){G(t.message||"Sign-in link invalid or expired.","error")}}else{const{email:t,sessionToken:n}=Nl();if(t&&n){const s=await of(n);s?Vo(s.email,s.sessionToken):mi()}}vi()}function _i(){const r=document.getElementById("signin-modal");r&&r.classList.add("open")}function lf(r){if(r&&r.target!==r.currentTarget)return;const e=document.getElementById("signin-modal");e&&e.classList.remove("open")}async function cf(){var i;const r=document.getElementById("signin-email-input"),e=document.getElementById("signin-submit-btn"),t=document.getElementById("signin-message"),n=(i=r==null?void 0:r.value)==null?void 0:i.trim();if(!n||!/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/.test(n)||n.length>254){t&&(t.textContent="Please enter a valid email address.");return}e&&(e.disabled=!0,e.textContent="Sending…"),t&&(t.textContent="");try{await nf(n),r&&(r.value=""),t&&(t.textContent=`Check your email — we sent a link to ${n}`),e&&(e.textContent="Sent!")}catch(o){console.error("handleMagicLinkRequest: sendMagicLink failed",{email:n,err:o}),t&&(t.textContent="Something went wrong. Please try again."),e&&(e.disabled=!1,e.textContent="Send Link")}}function uf(){mi(),Si(),vi(),Pn()}function vi(){const r=N.isVerified&&!!N.email,e=document.getElementById("auth-signedout"),t=document.getElementById("auth-signedin"),n=document.getElementById("auth-guest-usage");e&&e.classList.toggle("hidden",r),t&&t.classList.toggle("hidden",!r),n&&n.classList.toggle("hidden",r);const s=document.getElementById("auth-user-email");s&&(s.textContent=N.email||""),Br(),Pn()}async function df(){try{if(typeof FingerprintJS>"u"){console.warn("resolveIdentity: FingerprintJS not loaded, skipping");return}const e=await(await FingerprintJS.load()).get(),t=e.visitorId,n=await fetch(ap,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({fingerprint:e.visitorId,cookie_id:t})});if(!n.ok)throw new Error(`Identity check HTTP ${n.status}`);const s=await n.json();if(Mr.userId=s.user_id,Mr.status=s.status,Mr.resolved=!0,sessionStorage.setItem(op,s.user_id),s.usage_count!==void 0){const i=ft(),o=s.usage_month||i,a=o===i?s.usage_count:0,l=yi(),c=l.month===i?l.count:0;(a>=c||o>l.month)&&localStorage.setItem(Rt,JSON.stringify({count:a,month:i})),An()}console.log(`Identity resolved: ${s.status} (${s.user_id.slice(0,8)}...) usage: ${s.usage_count??"n/a"}`)}catch(r){console.error("resolveIdentity failed:",r)}}function yi(){const r=ft();try{const e=localStorage.getItem(Rt);return e?JSON.parse(e):{count:0,month:r}}catch(e){return console.warn("getUsageData: failed to parse usage storage",{key:Rt,month:r,err:e}),localStorage.removeItem(Rt),{count:0,month:r}}}function ft(){const r=new Date;return`${r.getFullYear()}-${String(r.getMonth()+1).padStart(2,"0")}`}function Rn(){const r=yi();return r.month!==ft()?{count:0,month:ft()}:r}function pf(){const e={count:Rn().count+1,month:ft()};return localStorage.setItem(Rt,JSON.stringify(e)),e}function wi(){return!!q.isLoading}function ht(){return!!q.isResolved}function ff(r){if(!r)return null;const e=String(r).toLowerCase().replace(/[^a-z0-9]+/g,"_");return e==="pro"||e==="professional_plan"?"professional":e==="power_developer"||e==="power_plan"?"power":Object.prototype.hasOwnProperty.call(sn,e)?e:null}function hf(r){var e;return r&&((e=Object.entries(bl).find(([,t])=>t===r))==null?void 0:e[0])||null}function Pr(...r){return r.find(e=>e!=null&&e!=="")}function gf(...r){return r.find(e=>e&&typeof e=="object")||{}}function mf(r){var u,d,p,h,m,_,v,k,I,R,T,w,P,A,x,re,Y,se,ie,ge;const e=r.data&&typeof r.data=="object"?r.data:r,t=gf(e.subscription,e.stripeSubscription,e.currentSubscription,(p=(d=(u=e.customer)==null?void 0:u.subscriptions)==null?void 0:d.data)==null?void 0:p[0],(m=(h=e.subscriptions)==null?void 0:h.data)==null?void 0:m[0],(_=e.subscriptions)==null?void 0:_[0]),n=e.metadata||t.metadata||((v=e.customer)==null?void 0:v.metadata)||{},s=Pr(e.priceId,e.price_id,e.stripePriceId,e.stripe_price_id,t.priceId,t.price_id,(k=t.plan)==null?void 0:k.id,(I=t.price)==null?void 0:I.id,(P=(w=(T=(R=t.items)==null?void 0:R.data)==null?void 0:T[0])==null?void 0:w.price)==null?void 0:P.id,(re=(x=(A=t.items)==null?void 0:A[0])==null?void 0:x.price)==null?void 0:re.id,(ge=(ie=(se=(Y=t.lines)==null?void 0:Y.data)==null?void 0:se[0])==null?void 0:ie.price)==null?void 0:ge.id),i=Pr(e.status,e.subscriptionStatus,e.subscription_status,t.status,"none"),o=ff(Pr(e.tier,e.plan,e.planId,e.plan_id,e.subscriptionTier,e.subscription_tier,e.product,e.productName,t.tier,t.plan,n.tier,n.plan)),a=lp.has(String(i).toLowerCase()),l=e.active===!0||e.isSubscribed===!0||e.subscribed===!0||e.hasSubscription===!0,c=o||hf(s)||(a||l?"professional":"free");return Lt({tier:c,status:i,periodEnd:Pr(e.periodEnd,e.currentPeriodEnd,e.current_period_end,t.current_period_end,t.periodEnd,null),isResolved:!0})}function bi(){return sn[q.tier]??sn.free}async function _f(){if(N.isVerified&&(!ht()||wi())&&(await Dl({force:!0}),Pn()),N.isVerified&&!ht())return G("Could not verify your subscription. Please refresh or try Manage billing.","error"),!1;const{count:r}=Rn(),e=bi();if(r>=e)return Ei(r,e,{openModal:!0}),!1;const t=Math.floor(e*.8);if(r>=t){const n=e-r;G(`${n} run${n===1?"":"s"} remaining this month.`,"warning")}return!0}function ts(){const r=document.getElementById("paywall-exhausted");r&&r.classList.add("hidden")}function Ei(r,e,t={}){const n=document.getElementById("walkthrough-modal");n&&n.classList.remove("open");const s=document.getElementById("ready-state");s&&s.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");const l=document.getElementById("pipeline-progress");l&&l.classList.remove("visible");const c=document.getElementById("paywall-exhausted");if(!c){G(`You've used all ${e} runs for this month. Upgrade to continue.`,"error"),fn();return}const u=document.getElementById("paywall-exhausted-text");if(u){const p=q.tier;p==="free"?u.textContent=`You've used all ${e} free generations this month. Upgrade to Pro for 50 generations/month and access to all AI models.`:u.textContent=`You've used all ${e} generations this month on your ${p} plan. Your limit resets next month.`}const d=document.getElementById("paywall-signin-btn");d&&d.classList.toggle("hidden",N.isVerified),c.classList.remove("hidden"),t.openModal&&fn()}function js(r){return q.tier==="free"&&Or.includes(r)?gr:r}function vf(){const r=document.getElementById("code-options-content"),e=document.getElementById("code-generator-model");if(!r||!e)return;const t=q.tier,s=!(N.isVerified&&!ht())&&t==="free";Array.from(e.options).forEach(o=>{const a=ve(o.value),l=Or.includes(o.value);o.textContent=l&&s?`${a} (PRO)`:a,o.disabled=!1}),s&&Or.includes(e.value)&&(e.value=gr),e.disabled=!1,Bo.has(e)||(e.addEventListener("change",()=>{ht()&&q.tier==="free"&&Or.includes(e.value)&&(e.value=gr,fn()),Ds(e.value)}),Bo.add(e));let i=document.getElementById("model-selector-free-notice");s?(i||(i=document.createElement("p"),i.id="model-selector-free-notice",i.className="text-xs text-gray-400 mt-1",r.appendChild(i)),i.innerHTML='Free plan — Gemini only. '):i&&i.remove(),Ds(e.value)}function An(){const r=document.getElementById("usage-counter");if(!r)return;if(N.isVerified&&wi()){r.textContent="Checking plan…",r.className="text-xs text-gray-500",Br(),ts();return}if(N.isVerified&&!ht()){r.textContent="Plan check failed",r.className="text-xs text-red-600 font-medium",Br(),ts();return}const{count:e}=Rn(),t=bi();r.textContent=`${e} / ${t} runs this month`;const n=t>0?e/t:0;r.className=n>=1?"text-xs text-red-600 font-medium":n>=.8?"text-xs text-yellow-600 font-medium":"text-xs text-gray-500",Br(),e>=t&&!g.isRunning?Ei(e,t):ts()}function Br(){const r=document.getElementById("guest-usage-text");if(!r)return;const e=yi(),t=e.month===ft()?e.count??0:0,n=sn.free;r.textContent=`${t} / ${n} generations used`}async function Dl(r={}){const e=r.force===!0;if(!N.isVerified||!N.sessionToken){q=Lt({isResolved:!0});return}q={...q,isLoading:!0,error:null};const t=localStorage.getItem(on);if(!e&&t)try{const{data:n,email:s,ts:i,version:o}=JSON.parse(t);if(o===jo&&s===N.email&&Date.now()-i<5*60*1e3){q={...n,isLoading:!1,isResolved:n.isResolved!==!1};return}}catch(n){console.warn("Failed to parse subscription cache:",n,"| raw value:",t)}try{const s=await(await fetch(`${Se}/stripe/get-subscription`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:N.sessionToken,email:N.email})})).json();if(s.error){if(["unauthorized","invalid session","expired session"].some(o=>String(s.error).toLowerCase().includes(o))){mi(),vi();return}q=Lt({isResolved:!1,error:s.error});return}q=mf(s),localStorage.setItem(on,JSON.stringify({version:jo,data:q,email:N.email,ts:Date.now()}))}catch(n){console.error("fetchSubscription failed:",n),q={...q,isLoading:!1,isResolved:!1,error:n.message}}}function Si(){localStorage.removeItem(on)}async function yf(r){if(!N.isVerified||!N.sessionToken){Bl(),_i();return}if(!bl[r]){G("Invalid plan selected.","error");return}const e=document.getElementById(`checkout-btn-${r}`);e&&(e.disabled=!0,e.textContent="Redirecting…");try{const n=await(await fetch(`${Se}/stripe/create-checkout-session-intl`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tierId:r,sessionToken:N.sessionToken,currency:El()})})).json();if(n.error||!n.url)throw new Error(n.error||"Failed to create checkout session");const{url:s}=n;window.location.href=s}catch(t){console.error("startCheckout failed:",t),e&&(e.disabled=!1,e.textContent="Subscribe"),G("Could not start checkout. Please try again.","error")}}async function wf(){if(!N.isVerified||!N.sessionToken){_i();return}const r=document.getElementById("manage-billing-btn");r&&(r.disabled=!0,r.textContent="Loading…");try{const t=await(await fetch(`${Se}/stripe/create-portal-session`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:N.sessionToken})})).json();if(t.error||!t.url)throw new Error(t.error||"Failed to open billing portal");const{url:n}=t;window.location.href=n}catch(e){console.error("openCustomerPortal failed:",e),r&&(r.disabled=!1,r.textContent="Manage billing"),G("Could not open billing portal. Please try again.","error")}}async function pn(r,e,t,n={}){const i=new AbortController,o=setTimeout(()=>i.abort(),12e4);try{const a=await fetch(ip,{method:"POST",headers:{"Content-Type":"application/json"},signal:i.signal,body:JSON.stringify({user_id:Mr.userId,step:r,model:e,prompt:t,context:n})}),l=await a.json();if(a.status===429){l.serverCount!==void 0&&(localStorage.setItem(Rt,JSON.stringify({count:l.serverCount,month:ft()})),An());const d=new Error(l.message||"Monthly usage limit reached. Upgrade to continue.");throw d.isUsageLimit=!0,d}const c=Ad(l,r);if(c)throw c;if(console.log(`[BuildShip] ${r} response keys:`,Object.keys(l),"content type:",typeof l.content),!a.ok)throw new Error(`${l.message||l.error||"BuildShip pipeline error"} (HTTP ${a.status})`);let u=l.output||l.content;if(!u)throw new Error(`BuildShip returned no output for step "${r}"`);return Array.isArray(u)&&(u=u.map(d=>typeof d=="string"?d:d.text||"").join("")),typeof u!="string"&&(u=JSON.stringify(u)),u}catch(a){throw a.name==="AbortError"?new Error(`BuildShip ${r} timed out after ${12e4/1e3}s`):a instanceof TypeError?new Error(`BuildShip unreachable: ${a.message}`):a}finally{clearTimeout(o)}}function bf(){const e=new URLSearchParams(window.location.search).get("checkout");e==="success"?(window.history.replaceState({},"",window.location.pathname),Si(),G("Subscription active! Welcome aboard.","success")):e==="cancel"&&(window.history.replaceState({},"",window.location.pathname),G("Checkout cancelled.","info"))}function Pn(){const r=N.isVerified&&!!N.email,e=q.tier,t=r&&wi(),n=!r||ht(),s=document.getElementById("subscription-tier-badge");if(s){const a={free:"Free",professional:"Professional",power:"Power Developer"},l={free:"bg-gray-100 text-gray-600",professional:"bg-indigo-100 text-indigo-700",power:"bg-purple-100 text-purple-700",unresolved:"bg-red-50 text-red-600"};s.textContent=t?"Checking…":n?a[e]||"Free":"Plan unavailable",s.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",!r||t||!n||e!=="free");const o=document.getElementById("manage-billing-btn");o&&o.classList.toggle("hidden",!r||t||n&&e==="free"),Ef(n?e:null),vf(),An()}function Ef(r){const e=["bg-gray-100","text-gray-500","cursor-default"];Object.entries({professional:{btnId:"checkout-btn-professional",defaultText:"Subscribe"},power:{btnId:"checkout-btn-power",defaultText:"Subscribe"}}).forEach(([s,{btnId:i,defaultText:o}])=>{const a=document.getElementById(i);a&&(s===r?(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",r!=="free")}function Us(){const r=El(),e=document.getElementById("pro-price"),t=document.getElementById("power-price"),n=document.getElementById("pro-price-note"),s=document.getElementById("power-price-note");e&&(e.textContent=Ho(Uo.professional,r)),t&&(t.textContent=Ho(Uo.power,r));const i="billed monthly";n&&(n.textContent=i),s&&(s.textContent=i)}function fn(){Us();const r=document.getElementById("pricing-modal");r&&r.classList.add("open"),up().then(()=>Us())}function Bl(r){if(r&&r.target!==r.currentTarget)return;const e=document.getElementById("pricing-modal");e&&e.classList.remove("open")}function G(r,e="info"){const t={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 ${t[e]||t.info}`,n.textContent=r,document.body.appendChild(n),setTimeout(()=>{n.style.opacity="0",setTimeout(()=>n.remove(),300)},3500)}document.addEventListener("DOMContentLoaded",async()=>{hljs.configure({tabReplace:" ",classPrefix:"hljs-"}),Sf(),await af(),bf(),await Dl(),Pn(),Us(),await Op(),Ap();const r=document.getElementById("flutterflow-endpoint-select");if(r){const t=Ir();r.value=t}Tl(),df();const e=document.getElementById("pipeline-input");e&&(e.addEventListener("input",()=>{qe===2&&e.value.trim().length>0&&(ii(),yn())}),e.addEventListener("blur",()=>{const t=document.getElementById("walkthrough-modal");qe===2&&t&&t.classList.add("open")}),e.addEventListener("keydown",t=>{if(t.key==="Tab"){const n=document.getElementById("walkthrough-modal");qe===2&&n&&setTimeout(()=>{n.classList.add("open")},100)}})),window.addEventListener("commitStateChange",t=>{const{state:n}=t.detail;Tf(n),n===O.PREPARING||n===O.VALIDATING||n===O.PUSHING?Ii():(n===O.SUCCESS||n===O.ERROR)&&setTimeout(wr,1e3)})});function Sf(){const r=document.getElementById("preview-frame-container");r&&(r.style.display="")}function If(){const r=document.getElementById("welcome-video-player");r&&(r.addEventListener("click",gt),document.addEventListener("keydown",gt))}function gt(){const r=document.getElementById("preview-frame-container"),e=document.getElementById("main-stage-container"),t=document.getElementById("ready-state");r&&(r.style.display="none"),e&&e.classList.add("visible"),t&&t.classList.remove("hidden");const n=document.getElementById("welcome-video-player");n&&n.removeEventListener("click",gt),document.removeEventListener("keydown",gt),Tl()}let ar=null;function kf(r,e,t,n=null){ar={codeInfo:r,checks:e,deps:t,bundlePlan:n},document.getElementById("confirm-file-name").textContent=r.fileName,document.getElementById("confirm-artifact-type").textContent=r.artifactType,document.getElementById("confirm-file-size").textContent=`${(r.content.length/1024).toFixed(1)} KB`,document.getElementById("confirm-line-count").textContent=n?`${n.fileEntries.length} files`:r.content.split(` -`).length,le("flutterflow_project_id").then(c=>{document.getElementById("confirm-project-id").textContent=c||"Not configured"});const s=document.getElementById("confirm-deps-list"),i=document.getElementById("confirm-deps-section");t&&Object.keys(t).length>0?(s.innerHTML=Object.entries(t).map(([c,u])=>`
  • • ${Ge(c)}: ${Ge(u)}
  • `).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(c=>`
  • • ${Ge(c)}
  • `).join(""),a.classList.remove("hidden")):a.classList.add("hidden"),document.getElementById("confirm-code-preview").textContent=r.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 jl(r){if(r&&r.target!==r.currentTarget)return;const e=document.getElementById("commit-confirm-modal");e&&e.classList.remove("open"),ar=null}function Cf(r){if(r&&r.target!==r.currentTarget)return;const e=document.getElementById("commit-success-modal");e&&e.classList.remove("open");const t=["success-message","success-project-id","success-file-name","success-artifact-type","success-time","success-size"];for(const i of t){const o=document.getElementById(i);o&&(o.textContent="")}const n=document.getElementById("success-warnings-section");n&&n.classList.add("hidden");const s=document.getElementById("success-warnings-list");s&&(s.innerHTML="")}function hn(r){var h,m,_,v;const e=(k,I)=>{const R=document.getElementById(k);R&&(R.textContent=I||"")},t=((h=r.metadata)==null?void 0:h.fileName)||"",n=((m=r.metadata)==null?void 0:m.projectId)||"",s=((_=r.metadata)==null?void 0:_.artifactType)||"",i=r.elapsedTime?`${(r.elapsedTime/1e3).toFixed(1)}s`:"",o=(v=r.metadata)!=null&&v.codeSize?`${(r.metadata.codeSize/1024).toFixed(1)} KB`:"";e("success-message",r.message||"Code committed successfully!"),e("success-project-id",n),e("success-file-name",t),e("success-artifact-type",s),e("success-time",i),e("success-size",o);const a=r.addedDependencies||[],l=document.getElementById("success-deps-row");l&&l.classList.toggle("hidden",a.length===0),e("success-deps",a.join(", "));const c=document.getElementById("success-open-ff-link");c&&n&&(c.href=`https://app.flutterflow.io/project/${n}`);const u=document.getElementById("success-warnings-section"),d=document.getElementById("success-warnings-list");r.warnings&&r.warnings.length>0&&u&&d&&(d.innerHTML=r.warnings.map(([k,I])=>`
  • ${ee(k)}: ${ee(String(I))}
  • `).join(""),u.classList.remove("hidden"));const p=document.getElementById("commit-success-modal");p&&p.classList.add("open")}function gn(r){wr(),ef(r)}function xf(){const r=document.getElementById("code-preview-content"),e=document.getElementById("code-preview-chevron");r.classList.contains("hidden")?(r.classList.remove("hidden"),e.style.transform="rotate(90deg)"):(r.classList.add("hidden"),e.style.transform="rotate(0deg)")}function Ii(){const r=document.getElementById("commit-progress-overlay");r&&(r.classList.add("open"),Ul(25,"Preparing code...","Step 1 of 4"))}function wr(){const r=document.getElementById("commit-progress-overlay");r&&r.classList.remove("open")}function Ul(r,e,t){const n=document.getElementById("commit-progress-bar"),s=document.getElementById("progress-message"),i=document.getElementById("progress-detail");n&&(n.style.width=`${r}%`),s&&(s.textContent=e),i&&(i.textContent=t)}function Tf(r){const t={[O.IDLE]:{percent:0,message:"Ready",detail:""},[O.PREPARING]:{percent:25,message:"Preparing code...",detail:"Step 1 of 4"},[O.VALIDATING]:{percent:50,message:"Validating...",detail:"Step 2 of 4"},[O.PUSHING]:{percent:75,message:"Pushing to FlutterFlow...",detail:"Step 3 of 4"},[O.SUCCESS]:{percent:100,message:"Complete!",detail:"Step 4 of 4"},[O.ERROR]:{percent:100,message:"Failed",detail:"Error occurred"}}[r];t&&Ul(t.percent,t.message,t.detail)}async function Rf(){var i,o;if(!ar){console.error("No pending commit data");return}const r=ar;if(jl(),Ii(),r.bundlePlan){const a=await Wp(r.bundlePlan,{pipelineResult:{step1Result:g.step1Result,selectedModel:(i=document.getElementById("code-generator-model"))==null?void 0:i.value}});wr(),a.success?hn(a):gn(a);return}const{codeInfo:e}=r,{artifactType:t,artifactName:n}=Al(),s=await Ll(e.content,{artifactType:t,artifactName:n,pipelineResult:{step1Result:g.step1Result,selectedModel:(o=document.getElementById("code-generator-model"))==null?void 0:o.value}});wr(),s.success?hn(s):gn(s),ar=null}window.runThinkingPipeline=Bs;window.toggleStep=qp;window.toggleSection=Gp;window.selectWorkflowStep=we;window.copyCode=Kp;window.retryWithDifferentModel=Zp;window.openApiKeysModal=si;window.closeApiKeysModal=Cl;window.closeWalkthroughModal=Ip;window.openWalkthroughModal=Sp;window.advanceWalkthrough=ii;window.commitToFlutterFlow=Hp;function Af(){const r=document.getElementById("pipeline-input");r&&r.focus()}function Pf(){const r=document.getElementById("advanced-settings");r&&(r.open=!0);const e=document.getElementById("code-generator-model");e&&(e.scrollIntoView({behavior:"smooth",block:"center"}),e.focus(),e.click())}window.focusPromptInput=Af;window.openModelSelector=Pf;window.saveApiKeys=xp;window.clearAllApiKeys=Tp;window.toggleKeyVisibility=Fp;window.handleWelcomeVideoEnd=If;window.dismissWelcomeVideo=gt;window.initiateCommitToFlutterFlow=Xp;window.updateFlutterFlowCredentialStatus=rf;window.closeCommitConfirmModal=jl;window.closeCommitSuccessModal=Cf;window.showCommitSuccessModal=hn;window.showCommitFailureModal=gn;window.toggleCodePreview=xf;window.confirmCommitToFlutterFlow=Rf;window.runRefinement=Vp;window.regenerateFromPastedErrors=Jp;window.clearErrorInput=Yp;window.setFlutterFlowEndpoint=Ep;window.getFlutterFlowEndpoint=Ir;window.openSignInModal=_i;window.closeSignInModal=lf;window.handleMagicLinkRequest=cf;window.handleSignOut=uf;window.startCheckout=yf;window.openCustomerPortal=wf;window.openPricingModal=fn;window.closePricingModal=Bl;let At=null,Hl=null;const Yo=120;function Fn(){const r=document.getElementById("pipeline-progress"),e=document.getElementById("results-view"),t=document.getElementById("ready-state");t&&t.classList.add("hidden"),e&&e.classList.remove("visible"),r&&r.classList.add("visible"),Hl=Date.now();for(let n=1;n<=3;n++){const s=document.getElementById(`pdot-${n}`);s&&(s.className="progress-dot")}$e(1),Ff()}function $e(r){const e={1:"Analyzing your prompt...",2:"Generating Dart code...",3:"Running code audit..."},t={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"),s=document.getElementById("progress-substep-text");n&&(n.textContent=e[r]||e[1]),s&&(s.textContent=t[r]||t[1]);for(let i=1;i<=3;i++){const o=document.getElementById(`pdot-${i}`);o&&(i{const r=(Date.now()-Hl)/1e3,e=document.getElementById("progress-elapsed"),t=document.getElementById("pipeline-progress-fill");e&&(e.textContent=`${Math.floor(r)}s`);const n=r/Yo*100,s=Math.min(95,n*(1-Math.exp(-r/(Yo*.6)))*1.2);t&&(t.style.width=`${s}%`)},250)}function ot(){At&&(clearInterval(At),At=null);const r=document.getElementById("pipeline-progress-fill");r&&(r.style.width="100%");for(let e=1;e<=3;e++){const t=document.getElementById(`pdot-${e}`);t&&(t.className="progress-dot completed")}setTimeout(()=>{const e=document.getElementById("pipeline-progress");e&&e.classList.remove("visible"),r&&(r.style.width="0%")},400)}function $f(r=""){var a,l;const e=Sn(),t=(l=(a=g.bundleReview)==null?void 0:a.artifacts)==null?void 0:l.find(c=>c.id===e.id),n=(t==null?void 0:t.review)||e.review;if(!n||typeof n=="string")return typeof n=="string"?jt(n):r;const s=Array.isArray(n.findings)?n.findings:[],i=n.status||"pending",o=s.length>0?s.map(c=>` -
    - ${ee(c.severity||"info")}: ${ee(c.message||"")} - ${c.suggestion?`
    ${ee(c.suggestion)}`:""} -
    - `).join(""):'
    No artifact-specific findings.
    ';return` -
    -

    ${ee(e.artifactName)} review: ${ee(i)}

    - ${o} -
    - `}function Mf(){var l,c;const r=g.artifactBundle,e=document.getElementById("bundle-strip"),t=document.getElementById("artifact-tabs"),n=document.getElementById("bundle-artifact-count"),s=document.getElementById("bundle-deployable-count"),i=document.getElementById("bundle-warning-count");if(!r||!Array.isArray(r.artifacts)||r.artifacts.length<=1){e&&e.classList.remove("visible"),t&&(t.innerHTML="");return}const o=((c=(l=r.metadata)==null?void 0:l.compatibility)==null?void 0:c.findings)||[],a=new Set(o.filter(u=>u.severity==="error").map(u=>u.artifactId));n&&(n.textContent=String(r.artifacts.length)),s&&(s.textContent=String(r.artifacts.filter(u=>!a.has(u.id)).length)),i&&(i.textContent=String((r.warnings||[]).length+o.filter(u=>u.severity!=="error").length)),t&&(t.innerHTML=r.artifacts.map(u=>` - - `).join(""),t.onclick=u=>{var p;const d=u.target.closest(".artifact-tab");(p=d==null?void 0:d.dataset)!=null&&p.artifactId&&zl(d.dataset.artifactId)}),e&&e.classList.add("visible")}function Wl(r=""){const e=document.getElementById("results-view"),t=document.getElementById("results-code-output"),n=document.getElementById("results-audit-output"),s=ai();if(t&&(t.textContent=""),t){const i=wl(s);t.innerHTML=i}n&&(n.innerHTML=$f(r)),e&&e.classList.add("visible"),Mf()}function $n(r,e){g.selectedArtifactId||(g.selectedArtifactId=tn(g.artifactBundle).id),Wl(e);const t=document.getElementById("btn-feedback-up"),n=document.getElementById("btn-feedback-down");t&&(t.className="feedback-btn"),n&&(n.className="feedback-btn")}function zl(r){g.selectedArtifactId=r,Wl(jt(g.step3Result||""))}function Of(){const r=document.getElementById("btn-copy-results"),e=ai();navigator.clipboard.writeText(e).then(()=>{if(r){r.classList.add("copied");const t=r.querySelector("span");if(t){const n=t.textContent;t.textContent="Copied!",setTimeout(()=>{r.classList.remove("copied"),t.textContent=n},2e3)}}})}function Lf(r){const e=document.getElementById("btn-feedback-up"),t=document.getElementById("btn-feedback-down");r==="up"?(e.classList.toggle("active-up"),t.classList.remove("active-down")):(t.classList.toggle("active-down"),e.classList.remove("active-up"));const n=r==="up"?"thumbsUp":"thumbsDown";gi(n,g.step2Result,g.step1Result),Ae("Generation Feedback",{feedback:n})}function Nf(){const r=document.getElementById("error-input-panel");if(r){r.classList.remove("hidden"),r.style.display="flex";const e=document.getElementById("ff-error-paste-input");e&&setTimeout(()=>e.focus(),100)}}function Gl(){const r=document.getElementById("error-input-panel");r&&(r.classList.add("hidden"),r.style.display="none")}window.copyResultsCode=Of;window.selectArtifact=zl;window.submitResultsFeedback=Lf;window.showErrorInputPanel=Nf;window.hideErrorInputPanel=Gl; diff --git a/dist/assets/index-BLDY07Z-.js b/dist/assets/index-BLDY07Z-.js new file mode 100644 index 0000000..58d2249 --- /dev/null +++ b/dist/assets/index-BLDY07Z-.js @@ -0,0 +1,304 @@ +(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const s of document.querySelectorAll('link[rel="modulepreload"]'))r(s);new MutationObserver(s=>{for(const i of s)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 t(s){const i={};return s.integrity&&(i.integrity=s.integrity),s.referrerPolicy&&(i.referrerPolicy=s.referrerPolicy),s.crossOrigin==="use-credentials"?i.credentials="include":s.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function r(s){if(s.ep)return;s.ep=!0;const i=t(s);fetch(s.href,i)}})();var h=typeof window<"u"?window:void 0,te=typeof globalThis<"u"?globalThis:h;typeof self>"u"&&(te.self=te),typeof File>"u"&&(te.File=function(){});var ca=Array.prototype,Hi=ca.forEach,Wi=ca.indexOf,fe=te==null?void 0:te.navigator,w=te==null?void 0:te.document,ee=te==null?void 0:te.location,as=te==null?void 0:te.fetch,ls=te!=null&&te.XMLHttpRequest&&"withCredentials"in new te.XMLHttpRequest?te.XMLHttpRequest:void 0,zi=te==null?void 0:te.AbortController,ce=fe==null?void 0:fe.userAgent,x=h??{},Be={DEBUG:!1,LIB_VERSION:"1.353.0"};function Gi(n,e,t,r,s,i,o){try{var a=n[i](o),l=a.value}catch(c){return void t(c)}a.done?e(l):Promise.resolve(l).then(r,s)}function je(n){return function(){var e=this,t=arguments;return new Promise(function(r,s){var i=n.apply(e,t);function o(l){Gi(i,r,s,o,a,"next",l)}function a(l){Gi(i,r,s,o,a,"throw",l)}o(void 0)})}}function S(){return S=Object.assign?Object.assign.bind():function(n){for(var e=1;e{var s=r.toLowerCase();return t.indexOf(s)!==-1})};function F(n,e){return n.indexOf(e)!==-1}var br=function(n){return n.trim()},cs=function(n){return n.replace(/^\$/,"")},fc=Array.isArray,da=Object.prototype,pa=da.hasOwnProperty,Er=da.toString,L=fc||function(n){return Er.call(n)==="[object Array]"},ze=n=>typeof n=="function",Z=n=>n===Object(n)&&!L(n),Pt=n=>{if(Z(n)){for(var e in n)if(pa.call(n,e))return!1;return!0}return!1},b=n=>n===void 0,K=n=>Er.call(n)=="[object String]",us=n=>K(n)&&n.trim().length===0,Ce=n=>n===null,M=n=>b(n)||Ce(n),Ze=n=>Er.call(n)=="[object Number]"&&n==n,Tt=n=>Ze(n)&&n>0,qe=n=>Er.call(n)==="[object Boolean]",hc=n=>n instanceof FormData,gc=n=>F(dc,n);function ds(n){return n===null||typeof n!="object"}function Vn(n,e){return Object.prototype.toString.call(n)==="[object "+e+"]"}function fa(n){return!b(Event)&&function(e,t){try{return e instanceof t}catch{return!1}}(n,Event)}var mc=[!0,"true",1,"1","yes"],Ur=n=>F(mc,n),vc=[!1,"false",0,"0","no"];function Oe(n,e,t,r,s){return e>t&&(r.warn("min cannot be greater than max."),e=t),Ze(n)?n>t?(r.warn(" cannot be greater than max: "+t+". Using max value instead."),t):n0){var i=s*this.m;e.tokens=Math.min(e.tokens+i,this.o),e.lastAccess=e.lastAccess+s*this.$}}consumeRateLimit(e){var t,r=Date.now(),s=String(e),i=this.t[s];return i?this.S(i,r):(i={tokens:this.o,lastAccess:r},this.t[s]=i),i.tokens===0||(i.tokens--,i.tokens===0&&((t=this.i)==null||t.call(this,e)),i.tokens===0)}stop(){this.t={}}}var Se="Mobile",qn="iOS",Ge="Android",hn="Tablet",ha=Ge+" "+hn,ga="iPad",ma="Apple",va=ma+" Watch",gn="Safari",Lt="BlackBerry",_a="Samsung",ya=_a+"Browser",wa=_a+" Internet",mt="Chrome",yc=mt+" OS",ba=mt+" "+qn,Zs="Internet Explorer",Ea=Zs+" "+Se,Xs="Opera",wc=Xs+" Mini",Qs="Edge",Sa="Microsoft "+Qs,Ft="Firefox",ka=Ft+" "+qn,mn="Nintendo",vn="PlayStation",Mt="Xbox",Ia=Ge+" "+Se,Ca=Se+" "+gn,nn="Windows",ps=nn+" Phone",qi="Nokia",fs="Ouya",xa="Generic",bc=xa+" "+Se.toLowerCase(),Ta=xa+" "+hn.toLowerCase(),hs="Konqueror",ae="(\\d+(\\.\\d+)?)",Hr=new RegExp("Version/"+ae),Ec=new RegExp(Mt,"i"),Sc=new RegExp(vn+" \\w+","i"),kc=new RegExp(mn+" \\w+","i"),ei=new RegExp(Lt+"|PlayBook|BB10","i"),Ic={"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"},Pn,Ki,Wr,Cc=(n,e)=>e&&F(e,ma)||function(t){return F(t,gn)&&!F(t,mt)&&!F(t,Ge)}(n),Ra=function(n,e){return e=e||"",F(n," OPR/")&&F(n,"Mini")?wc:F(n," OPR/")?Xs:ei.test(n)?Lt:F(n,"IE"+Se)||F(n,"WPDesktop")?Ea:F(n,ya)?wa:F(n,Qs)||F(n,"Edg/")?Sa:F(n,"FBIOS")?"Facebook "+Se:F(n,"UCWEB")||F(n,"UCBrowser")?"UC Browser":F(n,"CriOS")?ba:F(n,"CrMo")||F(n,mt)?mt:F(n,Ge)&&F(n,gn)?Ia:F(n,"FxiOS")?ka:F(n.toLowerCase(),hs.toLowerCase())?hs:Cc(n,e)?F(n,Se)?Ca:gn:F(n,Ft)?Ft:F(n,"MSIE")||F(n,"Trident/")?Zs:F(n,"Gecko")?Ft:""},xc={[Ea]:[new RegExp("rv:"+ae)],[Sa]:[new RegExp(Qs+"?\\/"+ae)],[mt]:[new RegExp("("+mt+"|CrMo)\\/"+ae)],[ba]:[new RegExp("CriOS\\/"+ae)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+ae)],[gn]:[Hr],[Ca]:[Hr],[Xs]:[new RegExp("(Opera|OPR)\\/"+ae)],[Ft]:[new RegExp(Ft+"\\/"+ae)],[ka]:[new RegExp("FxiOS\\/"+ae)],[hs]:[new RegExp("Konqueror[:/]?"+ae,"i")],[Lt]:[new RegExp(Lt+" "+ae),Hr],[Ia]:[new RegExp("android\\s"+ae,"i")],[wa]:[new RegExp(ya+"\\/"+ae)],[Zs]:[new RegExp("(rv:|MSIE )"+ae)],Mozilla:[new RegExp("rv:"+ae)]},Tc=function(n,e){var t=Ra(n,e),r=xc[t];if(b(r))return null;for(var s=0;s[Mt,n&&n[1]||""]],[new RegExp(mn,"i"),[mn,""]],[new RegExp(vn,"i"),[vn,""]],[ei,[Lt,""]],[new RegExp(nn,"i"),(n,e)=>{if(/Phone/.test(e)||/WPDesktop/.test(e))return[ps,""];if(new RegExp(Se).test(e)&&!/IEMobile\b/.test(e))return[nn+" "+Se,""];var t=/Windows NT ([0-9.]+)/i.exec(e);if(t&&t[1]){var r=t[1],s=Ic[r]||"";return/arm/i.test(e)&&(s="RT"),[nn,s]}return[nn,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,n=>{if(n&&n[3]){var e=[n[3],n[4],n[5]||"0"];return[qn,e.join(".")]}return[qn,""]}],[/(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i,n=>{var e="";return n&&n.length>=3&&(e=b(n[2])?n[3]:n[2]),["watchOS",e]}],[new RegExp("("+Ge+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+Ge+")","i"),n=>{if(n&&n[2]){var e=[n[2],n[3],n[4]||"0"];return[Ge,e.join(".")]}return[Ge,""]}],[/Mac OS X (\d+)[_.](\d+)[_.]?(\d+)?/i,n=>{var e=["Mac OS X",""];if(n&&n[1]){var t=[n[1],n[2],n[3]||"0"];e[1]=t.join(".")}return e}],[/Mac/i,["Mac OS X",""]],[/CrOS/,[yc,""]],[/Linux|debian/i,["Linux",""]]],Ji=function(n){return kc.test(n)?mn:Sc.test(n)?vn:Ec.test(n)?Mt:new RegExp(fs,"i").test(n)?fs:new RegExp("("+ps+"|WPDesktop)","i").test(n)?ps:/iPad/.test(n)?ga:/iPod/.test(n)?"iPod Touch":/iPhone/.test(n)?"iPhone":/(watch)(?: ?os[,/]|\d,\d\/)[\d.]+/i.test(n)?va:ei.test(n)?Lt:/(kobo)\s(ereader|touch)/i.test(n)?"Kobo":new RegExp(qi,"i").test(n)?qi:/(kf[a-z]{2}wi|aeo[c-r]{2})( bui|\))/i.test(n)||/(kf[a-z]+)( bui|\)).+silk\//i.test(n)?"Kindle Fire":/(Android|ZTE)/i.test(n)?new RegExp(Se).test(n)&&!/(9138B|TB782B|Nexus [97]|pixel c|HUAWEISHT|BTV|noble nook|smart ultra 6)/i.test(n)||/pixel[\daxl ]{1,6}/i.test(n)&&!/pixel c/i.test(n)||/(huaweimed-al00|tah-|APA|SM-G92|i980|zte|U304AA)/i.test(n)||/lmy47v/i.test(n)&&!/QTAQZ3/i.test(n)?Ge:ha:new RegExp("(pda|"+Se+")","i").test(n)?bc:new RegExp(hn,"i").test(n)&&!new RegExp(hn+" pc","i").test(n)?Ta:""},Rc=n=>n instanceof Error;function Ac(n){var e=globalThis._posthogChunkIds;if(e){var t=Object.keys(e);return Wr&&t.length===Ki||(Ki=t.length,Wr=t.reduce((r,s)=>{Pn||(Pn={});var i=Pn[s];if(i)r[i[0]]=i[1];else for(var o=n(s),a=o.length-1;a>=0;a--){var l=o[a],c=l==null?void 0:l.filename,u=e[s];if(c&&u){r[c]=u,Pn[s]=[c,u];break}}return r},{})),Wr}}class Pc{constructor(e,t,r){r===void 0&&(r=[]),this.coercers=e,this.stackParser=t,this.modifiers=r}buildFromUnknown(e,t){t===void 0&&(t={});var r=t&&t.mechanism||{handled:!0,type:"generic"},s=this.buildCoercingContext(r,t,0).apply(e),i=this.buildParsingContext(t),o=this.parseStacktrace(s,i);return{$exception_list:this.convertToExceptionList(o,r),$exception_level:"error"}}modifyFrames(e){var t=this;return je(function*(){for(var r of e)r.stacktrace&&r.stacktrace.frames&&L(r.stacktrace.frames)&&(r.stacktrace.frames=yield t.applyModifiers(r.stacktrace.frames));return e})()}coerceFallback(e){var t;return{type:"Error",value:"Unknown error",stack:(t=e.syntheticException)==null?void 0:t.stack,synthetic:!0}}parseStacktrace(e,t){var r,s;return e.cause!=null&&(r=this.parseStacktrace(e.cause,t)),e.stack!=""&&e.stack!=null&&(s=this.applyChunkIds(this.stackParser(e.stack,e.synthetic?t.skipFirstLines:0),t.chunkIdMap)),S({},e,{cause:r,stack:s})}applyChunkIds(e,t){return e.map(r=>(r.filename&&t&&(r.chunk_id=t[r.filename]),r))}applyCoercers(e,t){for(var r of this.coercers)if(r.match(e))return r.coerce(e,t);return this.coerceFallback(t)}applyModifiers(e){var t=this;return je(function*(){var r=e;for(var s of t.modifiers)r=yield s(r);return r})()}convertToExceptionList(e,t){var r,s,i,o={type:e.type,value:e.value,mechanism:{type:(r=t.type)!==null&&r!==void 0?r:"generic",handled:(s=t.handled)===null||s===void 0||s,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,S({},t,{handled:!0}))),a}buildParsingContext(e){var t;return{chunkIdMap:Ac(this.stackParser),skipFirstLines:(t=e.skipFirstLines)!==null&&t!==void 0?t:1}}buildCoercingContext(e,t,r){r===void 0&&(r=0);var s=(i,o)=>{if(o<=4){var a=this.buildCoercingContext(e,t,o);return this.applyCoercers(i,a)}};return S({},t,{syntheticException:r==0?t.syntheticException:void 0,mechanism:e,apply:i=>s(i,r),next:i=>s(i,r+1)})}}var Dt="?";function gs(n,e,t,r,s){var i={platform:n,filename:e,function:t===""?Dt:t,in_app:!0};return b(r)||(i.lineno=r),b(s)||(i.colno=s),i}var Aa=(n,e)=>{var t=n.indexOf("safari-extension")!==-1,r=n.indexOf("safari-web-extension")!==-1;return t||r?[n.indexOf("@")!==-1?n.split("@")[0]:Dt,t?"safari-extension:"+e:"safari-web-extension:"+e]:[n,e]},$c=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,Fc=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,Mc=/\((\S*)(?::(\d+))(?::(\d+))\)/,Oc=(n,e)=>{var t=$c.exec(n);if(t){var[,r,s,i]=t;return gs(e,r,Dt,+s,+i)}var o=Fc.exec(n);if(o){if(o[2]&&o[2].indexOf("eval")===0){var a=Mc.exec(o[2]);a&&(o[2]=a[1],o[3]=a[2],o[4]=a[3])}var[l,c]=Aa(o[1]||Dt,o[2]);return gs(e,c,l,o[3]?+o[3]:void 0,o[4]?+o[4]:void 0)}},Nc=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,Lc=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,Dc=(n,e)=>{var t=Nc.exec(n);if(t){if(t[3]&&t[3].indexOf(" > eval")>-1){var r=Lc.exec(t[3]);r&&(t[1]=t[1]||"eval",t[3]=r[1],t[4]=r[2],t[5]="")}var s=t[3],i=t[1]||Dt;return[i,s]=Aa(i,s),gs(e,s,i,t[4]?+t[4]:void 0,t[5]?+t[5]:void 0)}},Zi=/\(error: (.*)\)/,Xi=50;function Bc(){return function(n){for(var e=arguments.length,t=new Array(e>1?e-1:0),r=1;r1024)){var u=Zi.test(c)?c.replace(Zi,"$1"):c;if(!u.match(/\S*Error: /)){for(var d of t){var p=d(u,n);if(p){o.push(p);break}}if(o.length>=Xi)break}}}return function(f){if(!f.length)return[];var m=Array.from(f);return m.reverse(),m.slice(0,Xi).map(v=>{return S({},v,{filename:v.filename||(_=m,_[_.length-1]||{}).filename,function:v.function||Dt});var _})}(o)}}("web:javascript",Oc,Dc)}class jc{match(e){return this.isDOMException(e)||this.isDOMError(e)}coerce(e,t){var r=K(e.stack);return{type:this.getType(e),value:this.getValue(e),stack:r?e.stack:void 0,cause:e.cause?t.next(e.cause):void 0,synthetic:!1}}getType(e){return this.isDOMError(e)?"DOMError":"DOMException"}getValue(e){var t=e.name||(this.isDOMError(e)?"DOMError":"DOMException");return e.message?t+": "+e.message:t}isDOMException(e){return Vn(e,"DOMException")}isDOMError(e){return Vn(e,"DOMError")}}class Uc{match(e){return(t=>t instanceof Error)(e)}coerce(e,t){return{type:this.getType(e),value:this.getMessage(e,t),stack:this.getStack(e),cause:e.cause?t.next(e.cause):void 0,synthetic:!1}}getType(e){return e.name||e.constructor.name}getMessage(e,t){var r=e.message;return r.error&&typeof r.error.message=="string"?String(r.error.message):String(r)}getStack(e){return e.stacktrace||e.stack||void 0}}class Hc{constructor(){}match(e){return Vn(e,"ErrorEvent")&&e.error!=null}coerce(e,t){var r,s=t.apply(e.error);return s||{type:"ErrorEvent",value:e.message,stack:(r=t.syntheticException)==null?void 0:r.stack,synthetic:!0}}}var Wc=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;class zc{match(e){return typeof e=="string"}coerce(e,t){var r,[s,i]=this.getInfos(e);return{type:s??"Error",value:i??e,stack:(r=t.syntheticException)==null?void 0:r.stack,synthetic:!0}}getInfos(e){var t="Error",r=e,s=e.match(Wc);return s&&(t=s[1],r=s[2]),[t,r]}}var Gc=["fatal","error","warning","log","info","debug"];function Pa(n,e){e===void 0&&(e=40);var t=Object.keys(n);if(t.sort(),!t.length)return"[object has no keys]";for(var r=t.length;r>0;r--){var s=t.slice(0,r).join(", ");if(!(s.length>e))return r===t.length||s.length<=e?s:s.slice(0,e)+"..."}return""}class Vc{match(e){return typeof e=="object"&&e!==null}coerce(e,t){var r,s=this.getErrorPropertyFromObject(e);return s?t.apply(s):{type:this.getType(e),value:this.getValue(e),stack:(r=t.syntheticException)==null?void 0:r.stack,level:this.isSeverityLevel(e.level)?e.level:"error",synthetic:!0}}getType(e){return fa(e)?e.constructor.name:"Error"}getValue(e){if("name"in e&&typeof e.name=="string"){var t="'"+e.name+"' captured as exception";return"message"in e&&typeof e.message=="string"&&(t+=" with message: '"+e.message+"'"),t}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: "+Pa(e)}isSeverityLevel(e){return K(e)&&!us(e)&&Gc.indexOf(e)>=0}getErrorPropertyFromObject(e){for(var t in e)if(Object.prototype.hasOwnProperty.call(e,t)){var r=e[t];if(Rc(r))return r}}getObjectClassName(e){try{var t=Object.getPrototypeOf(e);return t?t.constructor.name:void 0}catch{return}}}class qc{match(e){return fa(e)}coerce(e,t){var r,s=e.constructor.name;return{type:s,value:s+" captured as exception with keys: "+Pa(e),stack:(r=t.syntheticException)==null?void 0:r.stack,synthetic:!0}}}class Kc{match(e){return ds(e)}coerce(e,t){var r;return{type:"Error",value:"Primitive value captured as exception: "+String(e),stack:(r=t.syntheticException)==null?void 0:r.stack,synthetic:!0}}}class Yc{match(e){return Vn(e,"PromiseRejectionEvent")}coerce(e,t){var r,s=this.getUnhandledRejectionReason(e);return ds(s)?{type:"UnhandledRejection",value:"Non-Error promise rejection captured with value: "+String(s),stack:(r=t.syntheticException)==null?void 0:r.stack,synthetic:!0}:t.apply(s)}getUnhandledRejectionReason(e){if(ds(e))return e;try{if("reason"in e)return e.reason;if("detail"in e&&"reason"in e.detail)return e.detail.reason}catch{}return e}}var $a=function(n,e){var{debugEnabled:t}=e===void 0?{}:e,r={k:function(s){if(h&&(Be.DEBUG||x.POSTHOG_DEBUG||t)&&!b(h.console)&&h.console){for(var i=("__rrweb_original__"in h.console[s])?h.console[s].__rrweb_original__:h.console[s],o=arguments.length,a=new Array(o>1?o-1:0),l=1;l{r.error("You must initialize PostHog before calling "+s)},createLogger:(s,i)=>$a(n+" "+s,i)};return r},E=$a("[PostHog.js]"),z=E.createLogger,Jc=z("[ExternalScriptsLoader]"),Qi=(n,e,t)=>{if(n.config.disable_external_dependency_loading)return Jc.warn(e+" was requested but loading of external scripts is disabled."),t("Loading of external scripts is disabled");var r=w==null?void 0:w.querySelectorAll("script");if(r){for(var s,i=function(){if(r[o].src===e){var l=r[o];return l.__posthog_loading_callback_fired?{v:t()}:(l.addEventListener("load",c=>{l.__posthog_loading_callback_fired=!0,t(void 0,c)}),l.onerror=c=>t(c),{v:void 0})}},o=0;o{if(!w)return t("document not found");var l=w.createElement("script");if(l.type="text/javascript",l.crossOrigin="anonymous",l.src=e,l.onload=d=>{l.__posthog_loading_callback_fired=!0,t(void 0,d)},l.onerror=d=>t(d),n.config.prepare_external_dependency_script&&(l=n.config.prepare_external_dependency_script(l)),!l)return t("prepare_external_dependency_script returned null");if(n.config.external_scripts_inject_target==="head")w.head.appendChild(l);else{var c,u=w.querySelectorAll("body > script");u.length>0?(c=u[0].parentNode)==null||c.insertBefore(l,u[0]):w.body.appendChild(l)}};w!=null&&w.body?a():w==null||w.addEventListener("DOMContentLoaded",a)};x.__PosthogExtensions__=x.__PosthogExtensions__||{},x.__PosthogExtensions__.loadExternalDependency=(n,e,t)=>{var r="/static/"+e+".js?v="+n.version;if(e==="remote-config"&&(r="/array/"+n.config.token+"/config.js"),e==="toolbar"){var s=3e5;r=r+"&t="+Math.floor(Date.now()/s)*s}var i=n.requestRouter.endpointFor("assets",r);Qi(n,i,t)},x.__PosthogExtensions__.loadSiteApp=(n,e,t)=>{var r=n.requestRouter.endpointFor("api",e);Qi(n,r,t)};var Kn={};function ot(n,e,t){if(L(n)){if(Hi&&n.forEach===Hi)n.forEach(e,t);else if("length"in n&&n.length===+n.length){for(var r=0,s=n.length;r1?e-1:0),r=1;r1?e-1:0),r=1;r0||Ze(t))&&(e[r]=t)}),e};function Xc(n,e){return t=n,r=i=>K(i)&&!Ce(e)?i.slice(0,e):i,s=new Set,function i(o,a){return o!==Object(o)?r?r(o,a):o:s.has(o)?void 0:(s.add(o),L(o)?(l=[],ot(o,c=>{l.push(i(c))})):(l={},U(o,(c,u)=>{s.has(c)||(l[u]=i(c,u))})),l);var l}(t);var t,r,s}var Qc=["herokuapp.com","vercel.app","netlify.app"];function eu(n){var e=n==null?void 0:n.hostname;if(!K(e))return!1;var t=e.split(".").slice(-2).join(".");for(var r of Qc)if(t===r)return!1;return!0}function Fa(n,e){for(var t=0;te.match(t)))}function Qn(n){var e="";switch(typeof n.className){case"string":e=n.className;break;case"object":e=(n.className&&"baseVal"in n.className?n.className.baseVal:null)||n.getAttribute("class")||"";break;default:e=""}return ni(e)}function Ua(n){return M(n)?null:br(n).split(/(\s+)/).filter(e=>_n(e)).join("").replace(/[\r\n]/g," ").replace(/[ ]+/g," ").substring(0,255)}function xn(n){var e="";return Is(n)&&!Va(n)&&n.childNodes&&n.childNodes.length&&U(n.childNodes,function(t){var r;Ba(t)&&t.textContent&&(e+=(r=Ua(t.textContent))!==null&&r!==void 0?r:"")}),br(e)}function Ha(n){return b(n.target)?n.srcElement||null:(e=n.target)!=null&&e.shadowRoot?n.composedPath()[0]||null:n.target||null;var e}var ri=["a","button","form","input","select","textarea","label"];function Wa(n,e){if(b(e))return!0;var t,r=function(i){if(e.some(o=>i.matches(o)))return{v:!0}};for(var s of n)if(t=r(s))return t.v;return!1}function za(n){var e=n.parentNode;return!(!e||!Sr(e))&&e}var nu=["next","previous","prev",">","<"],co=10,uo=[".ph-no-rageclick",".ph-no-capture"];function ru(n,e){if(!h||si(n))return!1;var t,r,s;if(qe(e)?(t=!!e&&uo,r=void 0):(t=(s=e==null?void 0:e.css_selector_ignorelist)!==null&&s!==void 0?s:uo,r=e==null?void 0:e.content_ignorelist),t===!1)return!1;var{targetElementList:i}=Ga(n,!1);return!function(o,a){if(o===!1||b(o))return!1;var l;if(o===!0)l=nu;else{if(!L(o))return!1;if(o.length>co)return E.error("[PostHog] content_ignorelist array cannot exceed "+co+" items. Use css_selector_ignorelist for more complex matching."),!1;l=o.map(c=>c.toLowerCase())}return a.some(c=>{var{safeText:u,ariaLabel:d}=c;return l.some(p=>u.includes(p)||d.includes(p))})}(r,i.map(o=>{var a;return{safeText:xn(o).toLowerCase(),ariaLabel:((a=o.getAttribute("aria-label"))==null?void 0:a.toLowerCase().trim())||""}}))&&!Wa(i,t)}var si=n=>!n||at(n,"html")||!Sr(n),Ga=(n,e)=>{if(!h||si(n))return{parentIsUsefulElement:!1,targetElementList:[]};for(var t=!1,r=[n],s=n;s.parentNode&&!at(s,"body");)if(ja(s.parentNode))r.push(s.parentNode.host),s=s.parentNode.host;else{var i=za(s);if(!i)break;if(e||ri.indexOf(i.tagName.toLowerCase())>-1)t=!0;else{var o=h.getComputedStyle(i);o&&o.getPropertyValue("cursor")==="pointer"&&(t=!0)}r.push(i),s=i}return{parentIsUsefulElement:t,targetElementList:r}};function su(n,e,t,r,s){var i,o,a,l;if(t===void 0&&(t=void 0),!h||si(n)||(i=t)!=null&&i.url_allowlist&&!lo(t.url_allowlist)||(o=t)!=null&&o.url_ignorelist&&lo(t.url_ignorelist))return!1;if((a=t)!=null&&a.dom_event_allowlist){var c=t.dom_event_allowlist;if(c&&!c.some(m=>e.type===m))return!1}var{parentIsUsefulElement:u,targetElementList:d}=Ga(n,r);if(!function(m,v){var _=v==null?void 0:v.element_allowlist;if(b(_))return!0;var C,k=function(I){if(_.some(y=>I.tagName.toLowerCase()===y))return{v:!0}};for(var T of m)if(C=k(T))return C.v;return!1}(d,t)||!Wa(d,(l=t)==null?void 0:l.css_selector_allowlist))return!1;var p=h.getComputedStyle(n);if(p&&p.getPropertyValue("cursor")==="pointer"&&e.type==="click")return!0;var f=n.tagName.toLowerCase();switch(f){case"html":return!1;case"form":return(s||["submit"]).indexOf(e.type)>=0;case"input":case"select":case"textarea":return(s||["change","click"]).indexOf(e.type)>=0;default:return u?(s||["click"]).indexOf(e.type)>=0:(s||["click"]).indexOf(e.type)>=0&&(ri.indexOf(f)>-1||n.getAttribute("contenteditable")==="true")}}function Is(n){for(var e=n;e.parentNode&&!at(e,"body");e=e.parentNode){var t=Qn(e);if(F(t,"ph-sensitive")||F(t,"ph-no-capture"))return!1}if(F(Qn(n),"ph-include"))return!0;var r=n.type||"";if(K(r))switch(r.toLowerCase()){case"hidden":case"password":return!1}var s=n.name||n.id||"";return!(K(s)&&/^cc|cardnum|ccnum|creditcard|csc|cvc|cvv|exp|pass|pwd|routing|seccode|securitycode|securitynum|socialsec|socsec|ssn/i.test(s.replace(/[^a-zA-Z0-9]/g,"")))}function Va(n){return!!(at(n,"input")&&!["button","checkbox","submit","reset"].includes(n.type)||at(n,"select")||at(n,"textarea")||n.getAttribute("contenteditable")==="true")}var qa="(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})",iu=new RegExp("^(?:"+qa+")$"),ou=new RegExp(qa),Ka="\\d{3}-?\\d{2}-?\\d{4}",au=new RegExp("^("+Ka+")$"),lu=new RegExp("("+Ka+")");function _n(n,e){return e===void 0&&(e=!0),!(M(n)||K(n)&&(n=br(n),(e?iu:ou).test((n||"").replace(/[- ]/g,""))||(e?au:lu).test(n)))}function Ya(n){var e=xn(n);return _n(e=(e+" "+Ja(n)).trim())?e:""}function Ja(n){var e="";return n&&n.childNodes&&n.childNodes.length&&U(n.childNodes,function(t){var r;if(t&&((r=t.tagName)==null?void 0:r.toLowerCase())==="span")try{var s=xn(t);e=(e+" "+s).trim(),t.childNodes&&t.childNodes.length&&(e=(e+" "+Ja(t)).trim())}catch(i){E.error("[AutoCapture]",i)}}),e}function cu(n){return function(e){var t=e.map(r=>{var s,i,o="";if(r.tag_name&&(o+=r.tag_name),r.attr_class)for(var a of(r.attr_class.sort(),r.attr_class))o+="."+a.replace(/"/g,"");var l=S({},r.text?{text:r.text}:{},{"nth-child":(s=r.nth_child)!==null&&s!==void 0?s:0,"nth-of-type":(i=r.nth_of_type)!==null&&i!==void 0?i:0},r.href?{href:r.href}:{},r.attr_id?{attr_id:r.attr_id}:{},r.attributes),c={};return Dn(l).sort((u,d)=>{var[p]=u,[f]=d;return p.localeCompare(f)}).forEach(u=>{var[d,p]=u;return c[po(d.toString())]=po(p.toString())}),o+=":",o+=Dn(c).map(u=>{var[d,p]=u;return d+'="'+p+'"'}).join("")});return t.join(";")}(function(e){return e.map(t=>{var r,s,i={text:(r=t.$el_text)==null?void 0:r.slice(0,400),tag_name:t.tag_name,href:(s=t.attr__href)==null?void 0:s.slice(0,2048),attr_class:uu(t),attr_id:t.attr__id,nth_child:t.nth_child,nth_of_type:t.nth_of_type,attributes:{}};return Dn(t).filter(o=>{var[a]=o;return a.indexOf("attr__")===0}).forEach(o=>{var[a,l]=o;return i.attributes[a]=l}),i})}(n))}function po(n){return n.replace(/"|\\"/g,'\\"')}function uu(n){var e=n.attr__class;return e?L(e)?e:ni(e):void 0}class Za{constructor(e){this.disabled=e===!1;var t=Z(e)?e:{};this.thresholdPx=t.threshold_px||30,this.timeoutMs=t.timeout_ms||1e3,this.clickCount=t.click_count||3,this.clicks=[]}isRageClick(e,t,r){if(this.disabled)return!1;var s=this.clicks[this.clicks.length-1];if(s&&Math.abs(e-s.x)+Math.abs(t-s.y){var e=w==null?void 0:w.createElement("a");return b(e)?null:(e.href=n,e)},du=function(n,e){var t,r;e===void 0&&(e="&");var s=[];return U(n,function(i,o){b(i)||b(o)||o==="undefined"||(t=encodeURIComponent((a=>a instanceof File)(i)?i.name:i.toString()),r=encodeURIComponent(o),s[s.length]=r+"="+t)}),s.join(e)},tr=function(n,e){for(var t,r=((n.split("#")[0]||"").split(/\?(.*)/)[1]||"").replace(/^\?+/g,"").split("&"),s=0;sn?e.slice(0,n)+"...":e}function pu(n){if(n.previousElementSibling)return n.previousElementSibling;var e=n;do e=e.previousSibling;while(e&&!Sr(e));return e}function fu(n,e,t,r){var s=n.tagName.toLowerCase(),i={tag_name:s};ri.indexOf(s)>-1&&!t&&(s.toLowerCase()==="a"||s.toLowerCase()==="button"?i.$el_text=Gr(1024,Ya(n)):i.$el_text=Gr(1024,xn(n)));var o=Qn(n);o.length>0&&(i.classes=o.filter(function(u){return u!==""})),U(n.attributes,function(u){var d;if((!Va(n)||["name","id","class","aria-label"].indexOf(u.name)!==-1)&&(r==null||!r.includes(u.name))&&!e&&_n(u.value)&&(d=u.name,!K(d)||d.substring(0,10)!=="_ngcontent"&&d.substring(0,7)!=="_nghost")){var p=u.value;u.name==="class"&&(p=ni(p).join(" ")),i["attr__"+u.name]=Gr(1024,p)}});for(var a=1,l=1,c=n;c=pu(c);)a++,c.tagName===n.tagName&&l++;return i.nth_child=a,i.nth_of_type=l,i}function hu(n,e){for(var t,r,{e:s,maskAllElementAttributes:i,maskAllText:o,elementAttributeIgnoreList:a,elementsChainAsString:l}=e,c=[n],u=n;u.parentNode&&!at(u,"body");)ja(u.parentNode)?(c.push(u.parentNode.host),u=u.parentNode.host):(c.push(u.parentNode),u=u.parentNode);var d,p=[],f={},m=!1,v=!1;if(U(c,I=>{var y=Is(I);I.tagName.toLowerCase()==="a"&&(m=I.getAttribute("href"),m=y&&m&&_n(m)&&m),F(Qn(I),"ph-no-capture")&&(v=!0),p.push(fu(I,i,o,a));var P=function(A){if(!Is(A))return{};var R={};return U(A.attributes,function(ne){if(ne.name&&ne.name.indexOf("data-ph-capture-attribute")===0){var J=ne.name.replace("data-ph-capture-attribute-",""),se=ne.value;J&&se&&_n(se)&&(R[J]=se)}}),R}(I);G(f,P)}),v)return{props:{},explicitNoCapture:v};if(o||(n.tagName.toLowerCase()==="a"||n.tagName.toLowerCase()==="button"?p[0].$el_text=Ya(n):p[0].$el_text=xn(n)),m){var _,C;p[0].attr__href=m;var k=(_=er(m))==null?void 0:_.host,T=h==null||(C=h.location)==null?void 0:C.host;k&&T&&k!==T&&(d=m)}return{props:G({$event_type:s.type,$ce_version:1},l?{}:{$elements:p},{$elements_chain:cu(p)},(t=p[0])!=null&&t.$el_text?{$el_text:(r=p[0])==null?void 0:r.$el_text}:{},d&&s.type==="click"?{$external_click_url:d}:{},f)}}class gu{constructor(e){this.P=!1,this.T=null,this.I=!1,this.instance=e,this.rageclicks=new Za(e.config.rageclick),this.C=null}get R(){var e,t,r=Z(this.instance.config.autocapture)?this.instance.config.autocapture:{};return r.url_allowlist=(e=r.url_allowlist)==null?void 0:e.map(s=>new RegExp(s)),r.url_ignorelist=(t=r.url_ignorelist)==null?void 0:t.map(s=>new RegExp(s)),r}F(){if(this.isBrowserSupported()){if(h&&w){var e=r=>{r=r||(h==null?void 0:h.event);try{this.O(r)}catch(s){fo.error("Failed to capture event",s)}};if(Y(w,"submit",e,{capture:!0}),Y(w,"change",e,{capture:!0}),Y(w,"click",e,{capture:!0}),this.R.capture_copied_text){var t=r=>{r=r||(h==null?void 0:h.event),this.O(r,zr)};Y(w,"copy",t,{capture:!0}),Y(w,"cut",t,{capture:!0})}}}else fo.info("Disabling Automatic Event Collection because this browser is not supported")}startIfEnabled(){this.isEnabled&&!this.P&&(this.F(),this.P=!0)}onRemoteConfig(e){e.elementsChainAsString&&(this.I=e.elementsChainAsString),this.instance.persistence&&this.instance.persistence.register({[to]:!!e.autocapture_opt_out}),this.T=!!e.autocapture_opt_out,this.startIfEnabled()}setElementSelectors(e){this.C=e}getElementSelectors(e){var t,r=[];return(t=this.C)==null||t.forEach(s=>{var i=w==null?void 0:w.querySelectorAll(s);i==null||i.forEach(o=>{e===o&&r.push(s)})}),r}get isEnabled(){var e,t,r=(e=this.instance.persistence)==null?void 0:e.props[to],s=this.T;if(Ce(s)&&!qe(r)&&!this.instance.M())return!1;var i=(t=this.T)!==null&&t!==void 0?t:!!r;return!!this.instance.config.autocapture&&!i}O(e,t){if(t===void 0&&(t="$autocapture"),this.isEnabled){var r,s=Ha(e);Ba(s)&&(s=s.parentNode||null),t==="$autocapture"&&e.type==="click"&&e instanceof MouseEvent&&this.instance.config.rageclick&&(r=this.rageclicks)!=null&&r.isRageClick(e.clientX,e.clientY,e.timeStamp||new Date().getTime())&&ru(s,this.instance.config.rageclick)&&this.O(e,"$rageclick");var i=t===zr;if(s&&su(s,e,this.R,i,i?["copy","cut"]:void 0)){var{props:o,explicitNoCapture:a}=hu(s,{e,maskAllElementAttributes:this.instance.config.mask_all_element_attributes,maskAllText:this.instance.config.mask_all_text,elementAttributeIgnoreList:this.R.element_attribute_ignorelist,elementsChainAsString:this.I});if(a)return!1;var l=this.getElementSelectors(s);if(l&&l.length>0&&(o.$element_selectors=l),t===zr){var c,u=Ua(h==null||(c=h.getSelection())==null?void 0:c.toString()),d=e.type||"clipboard";if(!u)return!1;o.$selected_content=u,o.$copy_type=d}return this.instance.capture(t,o),!0}}}isBrowserSupported(){return ze(w==null?void 0:w.querySelectorAll)}}Math.trunc||(Math.trunc=function(n){return n<0?Math.ceil(n):Math.floor(n)}),Number.isInteger||(Number.isInteger=function(n){return Ze(n)&&isFinite(n)&&Math.floor(n)===n});var ho="0123456789abcdef";class rr{constructor(e){if(this.bytes=e,e.length!==16)throw new TypeError("not 128-bit length")}static fromFieldsV7(e,t,r,s){if(!Number.isInteger(e)||!Number.isInteger(t)||!Number.isInteger(r)||!Number.isInteger(s)||e<0||t<0||r<0||s<0||e>0xffffffffffff||t>4095||r>1073741823||s>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/Math.pow(2,8),i[5]=e,i[6]=112|t>>>8,i[7]=t,i[8]=128|r>>>24,i[9]=r>>>16,i[10]=r>>>8,i[11]=r,i[12]=s>>>24,i[13]=s>>>16,i[14]=s>>>8,i[15]=s,new rr(i)}toString(){for(var e="",t=0;t>>4)+ho.charAt(15&this.bytes[t]),t!==3&&t!==5&&t!==7&&t!==9||(e+="-");if(e.length!==36)throw new Error("Invalid UUIDv7 was generated");return e}clone(){return new rr(this.bytes.slice(0))}equals(e){return this.compareTo(e)===0}compareTo(e){for(var t=0;t<16;t++){var r=this.bytes[t]-e.bytes[t];if(r!==0)return Math.sign(r)}return 0}}class mu{constructor(){this.A=0,this.j=0,this.D=new vu}generate(){var e=this.generateOrAbort();if(b(e)){this.A=0;var t=this.generateOrAbort();if(b(t))throw new Error("Could not generate UUID after timestamp reset");return t}return e}generateOrAbort(){var e=Date.now();if(e>this.A)this.A=e,this.L();else{if(!(e+1e4>this.A))return;this.j++,this.j>4398046511103&&(this.A++,this.L())}return rr.fromFieldsV7(this.A,Math.trunc(this.j/Math.pow(2,30)),this.j&Math.pow(2,30)-1,this.D.nextUint32())}L(){this.j=1024*this.D.nextUint32()+(1023&this.D.nextUint32())}}var go,Xa=n=>{if(typeof UUIDV7_DENY_WEAK_RNG<"u"&&UUIDV7_DENY_WEAK_RNG)throw new Error("no cryptographically strong RNG available");for(var e=0;ecrypto.getRandomValues(n));class vu{constructor(){this.N=new Uint32Array(8),this.U=1/0}nextUint32(){return this.U>=this.N.length&&(Xa(this.N),this.U=0),this.N[this.U++]}}var it=()=>_u().toString(),_u=()=>(go||(go=new mu)).generate(),Kt="",yu=/[a-z0-9][a-z0-9-]+\.[a-z]{2,}$/i;function wu(n,e){if(e){var t=function(s,i){if(i===void 0&&(i=w),Kt)return Kt;if(!i||["localhost","127.0.0.1"].includes(s))return"";for(var o=s.split("."),a=Math.min(o.length,8),l="dmn_chk_"+it();!Kt&&a--;){var c=o.slice(a).join("."),u=l+"=1;domain=."+c+";path=/";i.cookie=u+";max-age=3",i.cookie.includes(l)&&(i.cookie=u+";max-age=0",Kt=c)}return Kt}(n);if(!t){var r=(s=>{var i=s.match(yu);return i?i[0]:""})(n);r!==t&&E.info("Warning: cookie subdomain discovery mismatch",r,t),t=r}return t?"; domain=."+t:""}return""}var Pe={H:()=>!!w,B:function(n){E.error("cookieStore error: "+n)},q:function(n){if(w){try{for(var e=n+"=",t=w.cookie.split(";").filter(i=>i.length),r=0;r3686.4&&E.warn("cookieStore warning: large cookie, len="+c.length),w.cookie=c,c}catch{return}},V:function(n,e){if(w!=null&&w.cookie)try{Pe.G(n,"",-1,e)}catch{return}}},Vr=null,W={H:function(){if(!Ce(Vr))return Vr;var n=!0;if(b(h))n=!1;else try{var e="__mplssupport__";W.G(e,"xyz"),W.q(e)!=='"xyz"'&&(n=!1),W.V(e)}catch{n=!1}return n||E.error("localStorage unsupported; falling back to cookie store"),Vr=n,n},B:function(n){E.error("localStorage error: "+n)},q:function(n){try{return h==null?void 0:h.localStorage.getItem(n)}catch(e){W.B(e)}return null},W:function(n){try{return JSON.parse(W.q(n))||{}}catch{}return null},G:function(n,e){try{h==null||h.localStorage.setItem(n,JSON.stringify(e))}catch(t){W.B(t)}},V:function(n){try{h==null||h.localStorage.removeItem(n)}catch(e){W.B(e)}}},bu=["$device_id","distinct_id",Yn,La,Xn,Zn,Ae],Fn={},Eu={H:function(){return!0},B:function(n){E.error("memoryStorage error: "+n)},q:function(n){return Fn[n]||null},W:function(n){return Fn[n]||null},G:function(n,e){Fn[n]=e},V:function(n){delete Fn[n]}},dt=null,Q={H:function(){if(!Ce(dt))return dt;if(dt=!0,b(h))dt=!1;else try{var n="__support__";Q.G(n,"xyz"),Q.q(n)!=='"xyz"'&&(dt=!1),Q.V(n)}catch{dt=!1}return dt},B:function(n){E.error("sessionStorage error: ",n)},q:function(n){try{return h==null?void 0:h.sessionStorage.getItem(n)}catch(e){Q.B(e)}return null},W:function(n){try{return JSON.parse(Q.q(n))||null}catch{}return null},G:function(n,e){try{h==null||h.sessionStorage.setItem(n,JSON.stringify(e))}catch(t){Q.B(t)}},V:function(n){try{h==null||h.sessionStorage.removeItem(n)}catch(e){Q.B(e)}}},Ue=function(n){return n[n.PENDING=-1]="PENDING",n[n.DENIED=0]="DENIED",n[n.GRANTED=1]="GRANTED",n}({});class Su{constructor(e){this._instance=e}get R(){return this._instance.config}get consent(){return this.J()?Ue.DENIED:this.K}isOptedOut(){return this.R.cookieless_mode==="always"||this.consent===Ue.DENIED||this.consent===Ue.PENDING&&(this.R.opt_out_capturing_by_default||this.R.cookieless_mode==="on_reject")}isOptedIn(){return!this.isOptedOut()}isExplicitlyOptedOut(){return this.consent===Ue.DENIED}optInOut(e){this.Y.G(this.X,e?1:0,this.R.cookie_expiration,this.R.cross_subdomain_cookie,this.R.secure_cookie)}reset(){this.Y.V(this.X,this.R.cross_subdomain_cookie)}get X(){var{token:e,opt_out_capturing_cookie_prefix:t,consent_persistence_name:r}=this._instance.config;return r||(t?t+e:"__ph_opt_in_out_"+e)}get K(){var e=this.Y.q(this.X);return Ur(e)?Ue.GRANTED:F(vc,e)?Ue.DENIED:Ue.PENDING}get Y(){if(!this.Z){var e=this.R.opt_out_capturing_persistence_type;this.Z=e==="localStorage"?W:Pe;var t=e==="localStorage"?Pe:W;t.q(this.X)&&(this.Z.q(this.X)||this.optInOut(Ur(t.q(this.X))),t.V(this.X,this.R.cross_subdomain_cookie))}return this.Z}J(){return!!this.R.respect_dnt&&!!Fa([fe==null?void 0:fe.doNotTrack,fe==null?void 0:fe.msDoNotTrack,x.doNotTrack],e=>Ur(e))}}var Mn=z("[Dead Clicks]"),ku=()=>!0,Iu=n=>{var e,t=!((e=n.instance.persistence)==null||!e.get_property(Na)),r=n.instance.config.capture_dead_clicks;return qe(r)?r:!!Z(r)||t};class Qa{get lazyLoadedDeadClicksAutocapture(){return this.tt}constructor(e,t,r){this.instance=e,this.isEnabled=t,this.onCapture=r,this.startIfEnabledOrStop()}onRemoteConfig(e){"captureDeadClicks"in e&&(this.instance.persistence&&this.instance.persistence.register({[Na]:e.captureDeadClicks}),this.startIfEnabledOrStop())}startIfEnabledOrStop(){this.isEnabled(this)?this.it(()=>{this.et()}):this.stop()}it(e){var t,r;(t=x.__PosthogExtensions__)!=null&&t.initDeadClicksAutocapture&&e(),(r=x.__PosthogExtensions__)==null||r.loadExternalDependency==null||r.loadExternalDependency(this.instance,"dead-clicks-autocapture",s=>{s?Mn.error("failed to load script",s):e()})}et(){var e;if(w){if(!this.tt&&(e=x.__PosthogExtensions__)!=null&&e.initDeadClicksAutocapture){var t=Z(this.instance.config.capture_dead_clicks)?this.instance.config.capture_dead_clicks:{};t.__onCapture=this.onCapture,this.tt=x.__PosthogExtensions__.initDeadClicksAutocapture(this.instance,t),this.tt.start(w),Mn.info("starting...")}}else Mn.error("`document` not found. Cannot start.")}stop(){this.tt&&(this.tt.stop(),this.tt=void 0,Mn.info("stopping..."))}}var Yt=z("[ExceptionAutocapture]");class Cu{constructor(e){var t,r,s;this.rt=()=>{var i;if(h&&this.isEnabled&&(i=x.__PosthogExtensions__)!=null&&i.errorWrappingFunctions){var o=x.__PosthogExtensions__.errorWrappingFunctions.wrapOnError,a=x.__PosthogExtensions__.errorWrappingFunctions.wrapUnhandledRejection,l=x.__PosthogExtensions__.errorWrappingFunctions.wrapConsoleError;try{!this.st&&this.R.capture_unhandled_errors&&(this.st=o(this.captureException.bind(this))),!this.nt&&this.R.capture_unhandled_rejections&&(this.nt=a(this.captureException.bind(this))),!this.ot&&this.R.capture_console_errors&&(this.ot=l(this.captureException.bind(this)))}catch(c){Yt.error("failed to start",c),this.ut()}}},this._instance=e,this.ht=!((t=this._instance.persistence)==null||!t.props[no]),this.dt=new _c({refillRate:(r=this._instance.config.error_tracking.__exceptionRateLimiterRefillRate)!==null&&r!==void 0?r:1,bucketSize:(s=this._instance.config.error_tracking.__exceptionRateLimiterBucketSize)!==null&&s!==void 0?s:10,refillInterval:1e4,h:Yt}),this.R=this.vt(),this.startIfEnabledOrStop()}vt(){var e=this._instance.config.capture_exceptions,t={capture_unhandled_errors:!1,capture_unhandled_rejections:!1,capture_console_errors:!1};return Z(e)?t=S({},t,e):(b(e)?this.ht:e)&&(t=S({},t,{capture_unhandled_errors:!0,capture_unhandled_rejections:!0})),t}get isEnabled(){return this.R.capture_console_errors||this.R.capture_unhandled_errors||this.R.capture_unhandled_rejections}startIfEnabledOrStop(){this.isEnabled?(Yt.info("enabled"),this.ut(),this.it(this.rt)):this.ut()}it(e){var t,r;(t=x.__PosthogExtensions__)!=null&&t.errorWrappingFunctions&&e(),(r=x.__PosthogExtensions__)==null||r.loadExternalDependency==null||r.loadExternalDependency(this._instance,"exception-autocapture",s=>{if(s)return Yt.error("failed to load script",s);e()})}ut(){var e,t,r;(e=this.st)==null||e.call(this),this.st=void 0,(t=this.nt)==null||t.call(this),this.nt=void 0,(r=this.ot)==null||r.call(this),this.ot=void 0}onRemoteConfig(e){if("autocaptureExceptions"in e){var t=e.autocaptureExceptions;this.ht=!!t||!1,this._instance.persistence&&this._instance.persistence.register({[no]:this.ht}),this.R=this.vt(),this.startIfEnabledOrStop()}}onConfigChange(){this.R=this.vt()}captureException(e){var t,r,s=(t=e==null||(r=e.$exception_list)==null||(r=r[0])==null?void 0:r.type)!==null&&t!==void 0?t:"Exception";this.dt.consumeRateLimit(s)?Yt.info("Skipping exception capture because of client rate limiting.",{exception:s}):this._instance.exceptions.sendExceptionEvent(e)}}function mo(n,e,t){try{if(!(e in n))return()=>{};var r=n[e],s=t(r);return ze(s)&&(s.prototype=s.prototype||{},Object.defineProperties(s,{__posthog_wrapped__:{enumerable:!1,value:!0}})),n[e]=s,()=>{n[e]=r}}catch{return()=>{}}}class xu{constructor(e){var t;this._instance=e,this.ct=(h==null||(t=h.location)==null?void 0:t.pathname)||""}get isEnabled(){return this._instance.config.capture_pageview==="history_change"}startIfEnabled(){this.isEnabled&&(E.info("History API monitoring enabled, starting..."),this.monitorHistoryChanges())}stop(){this.ft&&this.ft(),this.ft=void 0,E.info("History API monitoring stopped")}monitorHistoryChanges(){var e,t;if(h&&h.history){var r=this;(e=h.history.pushState)!=null&&e.__posthog_wrapped__||mo(h.history,"pushState",s=>function(i,o,a){s.call(this,i,o,a),r._t("pushState")}),(t=h.history.replaceState)!=null&&t.__posthog_wrapped__||mo(h.history,"replaceState",s=>function(i,o,a){s.call(this,i,o,a),r._t("replaceState")}),this.bt()}}_t(e){try{var t,r=h==null||(t=h.location)==null?void 0:t.pathname;if(!r)return;r!==this.ct&&this.isEnabled&&this._instance.capture("$pageview",{navigation_type:e}),this.ct=r}catch(s){E.error("Error capturing "+e+" pageview",s)}}bt(){if(!this.ft){var e=()=>{this._t("popstate")};Y(h,"popstate",e),this.ft=()=>{h&&h.removeEventListener("popstate",e)}}}}var qr=z("[SegmentIntegration]");function Tu(n,e){var t=n.config.segment;if(!t)return e();(function(r,s){var i=r.config.segment;if(!i)return s();var o=l=>{var c=()=>l.anonymousId()||it();r.config.get_device_id=c,l.id()&&(r.register({distinct_id:l.id(),$device_id:c()}),r.persistence.set_property(Ae,"identified")),s()},a=i.user();"then"in a&&ze(a.then)?a.then(o):o(a)})(n,()=>{t.register((r=>{Promise&&Promise.resolve||qr.warn("This browser does not have Promise support, and can not use the segment integration");var s=(i,o)=>{if(!o)return i;i.event.userId||i.event.anonymousId===r.get_distinct_id()||(qr.info("No userId set, resetting PostHog"),r.reset()),i.event.userId&&i.event.userId!==r.get_distinct_id()&&(qr.info("UserId set, identifying with PostHog"),r.identify(i.event.userId));var a=r.calculateEventProperties(o,i.event.properties);return i.event.properties=Object.assign({},a,i.event.properties),i};return{name:"PostHog JS",type:"enrichment",version:"1.0.0",isLoaded:()=>!0,load:()=>Promise.resolve(),track:i=>s(i,i.event.event),page:i=>s(i,"$pageview"),identify:i=>s(i,"$identify"),screen:i=>s(i,"$screen")}})(n)).then(()=>{e()})})}var el="posthog-js";function tl(n,e){var{organization:t,projectId:r,prefix:s,severityAllowList:i=["error"],sendExceptionsToPostHog:o=!0}=e===void 0?{}:e;return a=>{var l,c,u,d,p;if(!(i==="*"||i.includes(a.level))||!n.__loaded)return a;a.tags||(a.tags={});var f=n.requestRouter.endpointFor("ui","/project/"+n.config.token+"/person/"+n.get_distinct_id());a.tags["PostHog Person URL"]=f,n.sessionRecordingStarted()&&(a.tags["PostHog Recording URL"]=n.get_session_replay_url({withTimestamp:!0}));var m=((l=a.exception)==null?void 0:l.values)||[],v=m.map(C=>S({},C,{stacktrace:C.stacktrace?S({},C.stacktrace,{type:"raw",frames:(C.stacktrace.frames||[]).map(k=>S({},k,{platform:"web:javascript"}))}):void 0})),_={$exception_message:((c=m[0])==null?void 0:c.value)||a.message,$exception_type:(u=m[0])==null?void 0:u.type,$exception_level:a.level,$exception_list:v,$sentry_event_id:a.event_id,$sentry_exception:a.exception,$sentry_exception_message:((d=m[0])==null?void 0:d.value)||a.message,$sentry_exception_type:(p=m[0])==null?void 0:p.type,$sentry_tags:a.tags};return t&&r&&(_.$sentry_url=(s||"https://sentry.io/organizations/")+t+"/issues/?project="+r+"&query="+a.event_id),o&&n.exceptions.sendExceptionEvent(_),a}}class Ru{constructor(e,t,r,s,i,o){this.name=el,this.setupOnce=function(a){a(tl(e,{organization:t,projectId:r,prefix:s,severityAllowList:i,sendExceptionsToPostHog:o==null||o}))}}}var Au=h!=null&&h.location?nr(h.location.hash,"__posthog")||nr(location.hash,"state"):null,vo="_postHogToolbarParams",_o=z("[Toolbar]"),st=function(n){return n[n.UNINITIALIZED=0]="UNINITIALIZED",n[n.LOADING=1]="LOADING",n[n.LOADED=2]="LOADED",n}(st||{});class Pu{constructor(e){this.instance=e}yt(e){x.ph_toolbar_state=e}wt(){var e;return(e=x.ph_toolbar_state)!==null&&e!==void 0?e:st.UNINITIALIZED}maybeLoadToolbar(e,t,r){if(e===void 0&&(e=void 0),t===void 0&&(t=void 0),r===void 0&&(r=void 0),Ma(this.instance.config)||!h||!w)return!1;e=e??h.location,r=r??h.history;try{if(!t){try{h.localStorage.setItem("test","test"),h.localStorage.removeItem("test")}catch{return!1}t=h==null?void 0:h.localStorage}var s,i=Au||nr(e.hash,"__posthog")||nr(e.hash,"state"),o=i?eo(()=>JSON.parse(atob(decodeURIComponent(i))))||eo(()=>JSON.parse(decodeURIComponent(i))):null;return o&&o.action==="ph_authorize"?((s=o).source="url",s&&Object.keys(s).length>0&&(o.desiredHash?e.hash=o.desiredHash:r?r.replaceState(r.state,"",e.pathname+e.search):e.hash="")):((s=JSON.parse(t.getItem(vo)||"{}")).source="localstorage",delete s.userIntent),!(!s.token||this.instance.config.token!==s.token)&&(this.loadToolbar(s),!0)}catch{return!1}}xt(e){var t=x.ph_load_toolbar||x.ph_load_editor;!M(t)&&ze(t)?t(e,this.instance):_o.warn("No toolbar load function found")}loadToolbar(e){var t=!(w==null||!w.getElementById(Da));if(!h||t)return!1;var r=this.instance.requestRouter.region==="custom"&&this.instance.config.advanced_disable_toolbar_metrics,s=S({token:this.instance.config.token},e,{apiURL:this.instance.requestRouter.endpointFor("ui")},r?{instrument:!1}:{});if(h.localStorage.setItem(vo,JSON.stringify(S({},s,{source:void 0}))),this.wt()===st.LOADED)this.xt(s);else if(this.wt()===st.UNINITIALIZED){var i;this.yt(st.LOADING),(i=x.__PosthogExtensions__)==null||i.loadExternalDependency==null||i.loadExternalDependency(this.instance,"toolbar",o=>{if(o)return _o.error("[Toolbar] Failed to load",o),void this.yt(st.UNINITIALIZED);this.yt(st.LOADED),this.xt(s)}),Y(h,"turbolinks:load",()=>{this.yt(st.UNINITIALIZED),this.loadToolbar(s)})}return!0}$t(e){return this.loadToolbar(e)}maybeLoadEditor(e,t,r){return e===void 0&&(e=void 0),t===void 0&&(t=void 0),r===void 0&&(r=void 0),this.maybeLoadToolbar(e,t,r)}}var $u=z("[TracingHeaders]");class Fu{constructor(e){this.Et=void 0,this.St=void 0,this.rt=()=>{var t,r;b(this.Et)&&((t=x.__PosthogExtensions__)==null||(t=t.tracingHeadersPatchFns)==null||t._patchXHR(this._instance.config.__add_tracing_headers||[],this._instance.get_distinct_id(),this._instance.sessionManager)),b(this.St)&&((r=x.__PosthogExtensions__)==null||(r=r.tracingHeadersPatchFns)==null||r._patchFetch(this._instance.config.__add_tracing_headers||[],this._instance.get_distinct_id(),this._instance.sessionManager))},this._instance=e}it(e){var t,r;(t=x.__PosthogExtensions__)!=null&&t.tracingHeadersPatchFns&&e(),(r=x.__PosthogExtensions__)==null||r.loadExternalDependency==null||r.loadExternalDependency(this._instance,"tracing-headers",s=>{if(s)return $u.error("failed to load script",s);e()})}startIfEnabledOrStop(){var e,t;this._instance.config.__add_tracing_headers?this.it(this.rt):((e=this.Et)==null||e.call(this),(t=this.St)==null||t.call(this),this.Et=void 0,this.St=void 0)}}var On="https?://(.*)",Vt=["gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","irclid","_kx"],Mu=Gt(["utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid"],Vt),Rn="",Ou=["li_fat_id"];function nl(n,e,t){if(!w)return{};var r,s=e?Gt([],Vt,t||[]):[],i=rl(Tn(w.URL,s,Rn),n),o=(r={},U(Ou,function(a){var l=Pe.q(a);r[a]=l||null}),r);return G(o,i)}function rl(n,e){var t=Mu.concat(e||[]),r={};return U(t,function(s){var i=tr(n,s);r[s]=i||null}),r}function sl(n){var e=function(i){return i?i.search(On+"google.([^/?]*)")===0?"google":i.search(On+"bing.com")===0?"bing":i.search(On+"yahoo.com")===0?"yahoo":i.search(On+"duckduckgo.com")===0?"duckduckgo":null:null}(n),t=e!="yahoo"?"q":"p",r={};if(!Ce(e)){r.$search_engine=e;var s=w?tr(w.referrer,t):"";s.length&&(r.ph_keyword=s)}return r}function yo(){return navigator.language||navigator.userLanguage}function il(){return(w==null?void 0:w.referrer)||"$direct"}function ol(n,e){var t=n?Gt([],Vt,e||[]):[],r=ee==null?void 0:ee.href.substring(0,1e3);return{r:il().substring(0,1e3),u:r?Tn(r,t,Rn):void 0}}function al(n){var e,{r:t,u:r}=n,s={$referrer:t,$referring_domain:t==null?void 0:t=="$direct"?"$direct":(e=er(t))==null?void 0:e.host};if(r){s.$current_url=r;var i=er(r);s.$host=i==null?void 0:i.host,s.$pathname=i==null?void 0:i.pathname;var o=rl(r);G(s,o)}if(t){var a=sl(t);G(s,a)}return s}function ll(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return}}function Nu(){try{return new Date().getTimezoneOffset()}catch{return}}function Lu(n,e){if(!ce)return{};var t,r,s,i=n?Gt([],Vt,e||[]):[],[o,a]=function(l){for(var c=0;c1e3?ce.substring(0,997)+"...":ce,$browser_version:Tc(ce,navigator.vendor),$browser_language:yo(),$browser_language_prefix:(t=yo(),typeof t=="string"?t.split("-")[0]:void 0),$screen_height:h==null?void 0:h.screen.height,$screen_width:h==null?void 0:h.screen.width,$viewport_height:h==null?void 0:h.innerHeight,$viewport_width:h==null?void 0:h.innerWidth,$lib:"web",$lib_version:Be.LIB_VERSION,$insert_id:Math.random().toString(36).substring(2,10)+Math.random().toString(36).substring(2,10),$time:Date.now()/1e3})}var nt=z("[Web Vitals]"),wo=9e5;class Du{constructor(e){var t;this.kt=!1,this.P=!1,this.N={url:void 0,metrics:[],firstMetricTimestamp:void 0},this.Pt=()=>{clearTimeout(this.Tt),this.N.metrics.length!==0&&(this._instance.capture("$web_vitals",this.N.metrics.reduce((r,s)=>S({},r,{["$web_vitals_"+s.name+"_event"]:S({},s),["$web_vitals_"+s.name+"_value"]:s.value}),{})),this.N={url:void 0,metrics:[],firstMetricTimestamp:void 0})},this.It=r=>{var s,i=(s=this._instance.sessionManager)==null?void 0:s.checkAndGetSessionAndWindowId(!0);if(b(i))nt.error("Could not read session ID. Dropping metrics!");else{this.N=this.N||{url:void 0,metrics:[],firstMetricTimestamp:void 0};var o=this.Ct();b(o)||(M(r==null?void 0:r.name)||M(r==null?void 0:r.value)?nt.error("Invalid metric received",r):this.Rt&&r.value>=this.Rt?nt.error("Ignoring metric with value >= "+this.Rt,r):(this.N.url!==o&&(this.Pt(),this.Tt=setTimeout(this.Pt,this.flushToCaptureTimeoutMs)),b(this.N.url)&&(this.N.url=o),this.N.firstMetricTimestamp=b(this.N.firstMetricTimestamp)?Date.now():this.N.firstMetricTimestamp,r.attribution&&r.attribution.interactionTargetElement&&(r.attribution.interactionTargetElement=void 0),this.N.metrics.push(S({},r,{$current_url:o,$session_id:i.sessionId,$window_id:i.windowId,timestamp:Date.now()})),this.N.metrics.length===this.allowedMetrics.length&&this.Pt()))}},this.rt=()=>{if(!this.P){var r,s,i,o,a=x.__PosthogExtensions__;b(a)||b(a.postHogWebVitalsCallbacks)||({onLCP:r,onCLS:s,onFCP:i,onINP:o}=a.postHogWebVitalsCallbacks),r&&s&&i&&o?(this.allowedMetrics.indexOf("LCP")>-1&&r(this.It.bind(this)),this.allowedMetrics.indexOf("CLS")>-1&&s(this.It.bind(this)),this.allowedMetrics.indexOf("FCP")>-1&&i(this.It.bind(this)),this.allowedMetrics.indexOf("INP")>-1&&o(this.It.bind(this)),this.P=!0):nt.error("web vitals callbacks not loaded - not starting")}},this._instance=e,this.kt=!((t=this._instance.persistence)==null||!t.props[so]),this.startIfEnabled()}get allowedMetrics(){var e,t,r=Z(this._instance.config.capture_performance)?(e=this._instance.config.capture_performance)==null?void 0:e.web_vitals_allowed_metrics:void 0;return M(r)?((t=this._instance.persistence)==null?void 0:t.props[oo])||["CLS","FCP","INP","LCP"]:r}get flushToCaptureTimeoutMs(){return(Z(this._instance.config.capture_performance)?this._instance.config.capture_performance.web_vitals_delayed_flush_ms:void 0)||5e3}get useAttribution(){var e=Z(this._instance.config.capture_performance)?this._instance.config.capture_performance.web_vitals_attribution:void 0;return e!=null&&e}get Rt(){var e=Z(this._instance.config.capture_performance)&&Ze(this._instance.config.capture_performance.__web_vitals_max_value)?this._instance.config.capture_performance.__web_vitals_max_value:wo;return 0{i?nt.error("failed to load script",i):e()})}}Ct(){var e=h?h.location.href:void 0;if(e){var t=this._instance.config.mask_personal_data_properties,r=this._instance.config.custom_personal_data_properties,s=t?Gt([],Vt,r||[]):[];return Tn(e,s,Rn)}nt.error("Could not determine current URL")}}var Bu=z("[Heatmaps]");function bo(n){return Z(n)&&"clientX"in n&&"clientY"in n&&Ze(n.clientX)&&Ze(n.clientY)}class ju{constructor(e){var t;this.kt=!1,this.P=!1,this.Ft=null,this.instance=e,this.kt=!((t=this.instance.persistence)==null||!t.props[ms]),this.rageclicks=new Za(e.config.rageclick)}get flushIntervalMilliseconds(){var e=5e3;return Z(this.instance.config.capture_heatmaps)&&this.instance.config.capture_heatmaps.flush_interval_milliseconds&&(e=this.instance.config.capture_heatmaps.flush_interval_milliseconds),e}get isEnabled(){return M(this.instance.config.capture_heatmaps)?M(this.instance.config.enable_heatmaps)?this.kt:this.instance.config.enable_heatmaps:this.instance.config.capture_heatmaps!==!1}startIfEnabled(){if(this.isEnabled){if(this.P)return;Bu.info("starting..."),this.Ot(),this.Mt()}else{var e;clearInterval((e=this.Ft)!==null&&e!==void 0?e:void 0),this.At(),this.getAndClearBuffer()}}onRemoteConfig(e){if("heatmaps"in e){var t=!!e.heatmaps;this.instance.persistence&&this.instance.persistence.register({[ms]:t}),this.kt=t,this.startIfEnabled()}}getAndClearBuffer(){var e=this.N;return this.N=void 0,e}jt(e){this.Dt(e.originalEvent,"deadclick")}Mt(){this.Ft&&clearInterval(this.Ft),this.Ft=function(e){return(e==null?void 0:e.visibilityState)==="visible"}(w)?setInterval(this.Lt.bind(this),this.flushIntervalMilliseconds):null}Ot(){h&&w&&(this.Nt=this.Lt.bind(this),Y(h,"beforeunload",this.Nt),this.Ut=e=>this.Dt(e||(h==null?void 0:h.event)),Y(w,"click",this.Ut,{capture:!0}),this.zt=e=>this.Ht(e||(h==null?void 0:h.event)),Y(w,"mousemove",this.zt,{capture:!0}),this.Bt=new Qa(this.instance,ku,this.jt.bind(this)),this.Bt.startIfEnabledOrStop(),this.qt=this.Mt.bind(this),Y(w,"visibilitychange",this.qt),this.P=!0)}At(){var e;h&&w&&(this.Nt&&h.removeEventListener("beforeunload",this.Nt),this.Ut&&w.removeEventListener("click",this.Ut,{capture:!0}),this.zt&&w.removeEventListener("mousemove",this.zt,{capture:!0}),this.qt&&w.removeEventListener("visibilitychange",this.qt),clearTimeout(this.Wt),(e=this.Bt)==null||e.stop(),this.P=!1)}Gt(e,t){var r=this.instance.scrollManager.scrollY(),s=this.instance.scrollManager.scrollX(),i=this.instance.scrollManager.scrollElement(),o=function(a,l,c){for(var u=a;u&&Sr(u)&&!at(u,"body");){if(u===c)return!1;if(F(l,h==null?void 0:h.getComputedStyle(u).position))return!0;u=za(u)}return!1}(Ha(e),["fixed","sticky"],i);return{x:e.clientX+(o?0:s),y:e.clientY+(o?0:r),target_fixed:o,type:t}}Dt(e,t){var r;if(t===void 0&&(t="click"),!ao(e.target)&&bo(e)){var s=this.Gt(e,t);(r=this.rageclicks)!=null&&r.isRageClick(e.clientX,e.clientY,new Date().getTime())&&this.Vt(S({},s,{type:"rageclick"})),this.Vt(s)}}Ht(e){!ao(e.target)&&bo(e)&&(clearTimeout(this.Wt),this.Wt=setTimeout(()=>{this.Vt(this.Gt(e,"mousemove"))},500))}Vt(e){if(h){var t=h.location.href,r=this.instance.config.mask_personal_data_properties,s=this.instance.config.custom_personal_data_properties,i=r?Gt([],Vt,s||[]):[],o=Tn(t,i,Rn);this.N=this.N||{},this.N[o]||(this.N[o]=[]),this.N[o].push(e)}}Lt(){this.N&&!Pt(this.N)&&this.instance.capture("$$heatmap",{$heatmap_data:this.getAndClearBuffer()})}}class Eo{constructor(e){this.Jt=(t,r,s)=>{s&&(s.noSessionId||s.activityTimeout||s.sessionPastMaximumLength)&&(E.info("[PageViewManager] Session rotated, clearing pageview state",{sessionId:t,changeReason:s}),this.Kt=void 0,this._instance.scrollManager.resetContext())},this._instance=e,this.Yt()}Yt(){var e;this.Xt=(e=this._instance.sessionManager)==null?void 0:e.onSessionId(this.Jt)}destroy(){var e;(e=this.Xt)==null||e.call(this),this.Xt=void 0}doPageView(e,t){var r,s=this.Qt(e,t);return this.Kt={pathname:(r=h==null?void 0:h.location.pathname)!==null&&r!==void 0?r:"",pageViewId:t,timestamp:e},this._instance.scrollManager.resetContext(),s}doPageLeave(e){var t;return this.Qt(e,(t=this.Kt)==null?void 0:t.pageViewId)}doEvent(){var e;return{$pageview_id:(e=this.Kt)==null?void 0:e.pageViewId}}Qt(e,t){var r=this.Kt;if(!r)return{$pageview_id:t};var s={$pageview_id:t,$prev_pageview_id:r.pageViewId},i=this._instance.scrollManager.getContext();if(i&&!this._instance.config.disable_scroll_properties){var{maxScrollHeight:o,lastScrollY:a,maxScrollY:l,maxContentHeight:c,lastContentY:u,maxContentY:d}=i;if(!(b(o)||b(a)||b(l)||b(c)||b(u)||b(d))){o=Math.ceil(o),a=Math.ceil(a),l=Math.ceil(l),c=Math.ceil(c),u=Math.ceil(u),d=Math.ceil(d);var p=o<=1?1:Oe(a/o,0,1,E),f=o<=1?1:Oe(l/o,0,1,E),m=c<=1?1:Oe(u/c,0,1,E),v=c<=1?1:Oe(d/c,0,1,E);s=G(s,{$prev_pageview_last_scroll:a,$prev_pageview_last_scroll_percentage:p,$prev_pageview_max_scroll:l,$prev_pageview_max_scroll_percentage:f,$prev_pageview_last_content:u,$prev_pageview_last_content_percentage:m,$prev_pageview_max_content:d,$prev_pageview_max_content_percentage:v})}}return r.pathname&&(s.$prev_pageview_pathname=r.pathname),r.timestamp&&(s.$prev_pageview_duration=(e.getTime()-r.timestamp.getTime())/1e3),s}}var He=function(n){return n.GZipJS="gzip-js",n.Base64="base64",n}({}),ke=Uint8Array,ue=Uint16Array,Bt=Uint32Array,ii=new ke([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]),oi=new ke([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]),So=new ke([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),cl=function(n,e){for(var t=new ue(31),r=0;r<31;++r)t[r]=e+=1<>>1|(21845&H)<<1;pt=(61680&(pt=(52428&pt)>>>2|(13107&pt)<<2))>>>4|(3855&pt)<<4,dl[H]=((65280&pt)>>>8|(255&pt)<<8)>>>1}var dn=function(n,e,t){for(var r=n.length,s=0,i=new ue(e);s>>15-n[s];return o},vt=new ke(288);for(H=0;H<144;++H)vt[H]=8;for(H=144;H<256;++H)vt[H]=9;for(H=256;H<280;++H)vt[H]=7;for(H=280;H<288;++H)vt[H]=8;var sr=new ke(32);for(H=0;H<32;++H)sr[H]=5;var Hu=dn(vt,9),Wu=dn(sr,5),pl=function(n){return(n/8>>0)+(7&n&&1)},fl=function(n,e,t){(t==null||t>n.length)&&(t=n.length);var r=new(n instanceof ue?ue:n instanceof Bt?Bt:ke)(t-e);return r.set(n.subarray(e,t)),r},De=function(n,e,t){t<<=7&e;var r=e/8>>0;n[r]|=t,n[r+1]|=t>>>8},Jt=function(n,e,t){t<<=7&e;var r=e/8>>0;n[r]|=t,n[r+1]|=t>>>8,n[r+2]|=t>>>16},Kr=function(n,e){for(var t=[],r=0;rp&&(p=i[r].s);var f=new ue(p+1),m=xs(t[u-1],f,0);if(m>e){r=0;var v=0,_=m-e,C=1<<_;for(i.sort(function(y,P){return f[P.s]-f[y.s]||y.f-P.f});re))break;v+=C-(1<>>=_;v>0;){var T=i[r].s;f[T]=0&&v;--r){var I=i[r].s;f[I]==e&&(--f[I],++v)}m=e}return[new ke(f),m]},xs=function(n,e,t){return n.s==-1?Math.max(xs(n.l,e,t+1),xs(n.r,e,t+1)):e[n.s]=t},Io=function(n){for(var e=n.length;e&&!n[--e];);for(var t=new ue(++e),r=0,s=n[0],i=1,o=function(l){t[r++]=l},a=1;a<=e;++a)if(n[a]==s&&a!=e)++i;else{if(!s&&i>2){for(;i>138;i-=138)o(32754);i>2&&(o(i>10?i-11<<5|28690:i-3<<5|12305),i=0)}else if(i>3){for(o(s),--i;i>6;i-=6)o(8304);i>2&&(o(i-3<<5|8208),i=0)}for(;i--;)o(s);i=1,s=n[a]}return[t.subarray(0,r),e]},Zt=function(n,e){for(var t=0,r=0;r>>8,n[s+2]=255^n[s],n[s+3]=255^n[s+1];for(var i=0;i4&&!J[So[ie-1]];--ie);var me,xe,Te,Et,Xe=c+5<<3,ut=Zt(s,vt)+Zt(i,sr)+o,Re=Zt(s,p)+Zt(i,v)+o+14+3*ie+Zt(A,J)+(2*A[16]+3*A[17]+7*A[18]);if(Xe<=ut&&Xe<=Re)return Ts(e,u,n.subarray(l,l+c));if(De(e,u,1+(Re15&&(De(e,u,ve[R]>>>5&127),u+=ve[R]>>>12)}}}else me=Hu,xe=vt,Te=Wu,Et=sr;for(R=0;R255){de=r[R]>>>18&31,Jt(e,u,me[de+257]),u+=xe[de+257],de>7&&(De(e,u,r[R]>>>23&31),u+=ii[de]);var kt=31&r[R];Jt(e,u,Te[kt]),u+=Et[kt],kt>3&&(Jt(e,u,r[R]>>>5&8191),u+=oi[kt])}else Jt(e,u,me[r[R]]),u+=xe[r[R]];return Jt(e,u,me[256]),u+xe[256]},zu=new Bt([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),Gu=function(){for(var n=new Bt(256),e=0;e<256;++e){for(var t=e,r=9;--r;)t=(1&t&&3988292384)^t>>>1;n[e]=t}return n}(),Vu=function(n,e,t,r,s){return function(i,o,a,l,c,u){var d=i.length,p=new ke(l+d+5*(1+Math.floor(d/7e3))+c),f=p.subarray(l,p.length-c),m=0;if(!o||d<8)for(var v=0;v<=d;v+=65535){var _=v+65535;_>>13,T=8191&C,I=(1<7e3||Te>24576)&&St>423){m=Co(i,f,0,J,se,ie,xe,Te,Xe,v-Xe,m),Te=me=xe=0,Xe=v;for(var oe=0;oe<286;++oe)se[oe]=0;for(oe=0;oe<30;++oe)ie[oe]=0}var ve=2,de=0,kt=T,et=Re-Qe&32767;if(St>2&&ut==ne(v-et))for(var ac=Math.min(k,St)-1,lc=Math.min(32767,v),cc=Math.min(258,St);et<=lc&&--kt&&Re!=Qe;){if(i[v+ve]==i[v+ve-et]){for(var tt=0;ttve){if(ve=tt,de=et,tt>ac)break;var uc=Math.min(et,tt-2),Di=0;for(oe=0;oeDi&&(Di=Bi,Qe=Br)}}}et+=(Re=Qe)-(Qe=y[Re])+32768&32767}if(de){J[Te++]=268435456|Cs[ve]<<18|ko[de];var ji=31&Cs[ve],Ui=31&ko[de];xe+=ii[ji]+oi[Ui],++se[257+ji],++ie[Ui],Et=v+ve,++me}else J[Te++]=i[v],++se[i[v]]}}m=Co(i,f,u,J,se,ie,xe,Te,Xe,v-Xe,m)}return fl(p,0,l+pl(m)+c)}(n,e.level==null?6:e.level,e.mem==null?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(n.length)))):12+e.mem,t,r,!0)},Yr=function(n,e,t){for(;t;++e)n[e]=t,t>>>=8};function qu(n,e){e===void 0&&(e={});var t=function(){var a=4294967295;return{p:function(l){for(var c=a,u=0;u>>8;a=c},d:function(){return 4294967295^a}}}(),r=n.length;t.p(n);var s,i=Vu(n,e,10+((s=e).filename&&s.filename.length+1||0),8),o=i.length;return function(a,l){var c=l.filename;if(a[0]=31,a[1]=139,a[2]=8,a[8]=l.level<2?4:l.level==9?2:0,a[9]=3,l.mtime!=0&&Yr(a,4,Math.floor(new Date(l.mtime||Date.now())/1e3)),c){a[3]=8;for(var u=0;u<=c.length;++u)a[u+10]=c.charCodeAt(u)}}(i,e),Yr(i,o-8,t.d()),Yr(i,o-4,r),i}var Ku=function(n){var e,t,r,s,i="";for(e=t=0,r=(n=(n+"").replace(/\r\n/g,` +`).replace(/\r/g,` +`)).length,s=0;s127&&o<2048?String.fromCharCode(o>>6|192,63&o|128):String.fromCharCode(o>>12|224,o>>6&63|128,63&o|128),Ce(a)||(t>e&&(i+=n.substring(e,t)),i+=a,e=t=s+1)}return t>e&&(i+=n.substring(e,n.length)),i},Yu=!!ls||!!as,xo="text/plain",ir=function(n,e,t){var r;t===void 0&&(t=!0);var[s,i]=n.split("?"),o=S({},e),a=(r=i==null?void 0:i.split("&").map(c=>{var u,[d,p]=c.split("="),f=t&&(u=o[d])!==null&&u!==void 0?u:p;return delete o[d],d+"="+f}))!==null&&r!==void 0?r:[],l=du(o);return l&&a.push(l),s+"?"+a.join("&")},ln=(n,e)=>JSON.stringify(n,(t,r)=>typeof r=="bigint"?r.toString():r,e),Jr=n=>{var{data:e,compression:t}=n;if(e){if(t===He.GZipJS){var r=qu(function(l,c){var u=l.length;if(typeof TextEncoder<"u")return new TextEncoder().encode(l);for(var d=new ke(l.length+(l.length>>>1)),p=0,f=function(C){d[p++]=C},m=0;md.length){var v=new ke(p+8+(u-m<<1));v.set(d),d=v}var _=l.charCodeAt(m);_<128||c?f(_):_<2048?(f(192|_>>>6),f(128|63&_)):_>55295&&_<57344?(f(240|(_=65536+(1047552&_)|1023&l.charCodeAt(++m))>>>18),f(128|_>>>12&63),f(128|_>>>6&63),f(128|63&_)):(f(224|_>>>12),f(128|_>>>6&63),f(128|63&_))}return fl(d,0,p)}(ln(e)),{mtime:0}),s=new Blob([r],{type:xo});return{contentType:xo,body:s,estimatedSize:s.size}}if(t===He.Base64){var i=function(l){var c,u,d,p,f,m="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",v=0,_=0,C="",k=[];if(!l)return l;l=Ku(l);do c=(f=l.charCodeAt(v++)<<16|l.charCodeAt(v++)<<8|l.charCodeAt(v++))>>18&63,u=f>>12&63,d=f>>6&63,p=63&f,k[_++]=m.charAt(c)+m.charAt(u)+m.charAt(d)+m.charAt(p);while(v"data="+encodeURIComponent(typeof l=="string"?l:ln(l)))(i);return{contentType:"application/x-www-form-urlencoded",body:o,estimatedSize:new Blob([o]).size}}var a=ln(e);return{contentType:"application/json",body:a,estimatedSize:new Blob([a]).size}}},Bn=[];as&&Bn.push({transport:"fetch",method:n=>{var e,t,{contentType:r,body:s,estimatedSize:i}=(e=Jr(n))!==null&&e!==void 0?e:{},o=new Headers;U(n.headers,function(u,d){o.append(d,u)}),r&&o.append("Content-Type",r);var a=n.url,l=null;if(zi){var c=new zi;l={signal:c.signal,timeout:setTimeout(()=>c.abort(),n.timeout)}}as(a,S({method:(n==null?void 0:n.method)||"GET",headers:o,keepalive:n.method==="POST"&&(i||0)<52428.8,body:s,signal:(t=l)==null?void 0:t.signal},n.fetchOptions)).then(u=>u.text().then(d=>{var p={statusCode:u.status,text:d};if(u.status===200)try{p.json=JSON.parse(d)}catch(f){E.error(f)}n.callback==null||n.callback(p)})).catch(u=>{E.error(u),n.callback==null||n.callback({statusCode:0,error:u})}).finally(()=>l?clearTimeout(l.timeout):null)}}),ls&&Bn.push({transport:"XHR",method:n=>{var e,t=new ls;t.open(n.method||"GET",n.url,!0);var{contentType:r,body:s}=(e=Jr(n))!==null&&e!==void 0?e:{};U(n.headers,function(i,o){t.setRequestHeader(o,i)}),r&&t.setRequestHeader("Content-Type",r),n.timeout&&(t.timeout=n.timeout),n.disableXHRCredentials||(t.withCredentials=!0),t.onreadystatechange=()=>{if(t.readyState===4){var i={statusCode:t.status,text:t.responseText};if(t.status===200)try{i.json=JSON.parse(t.responseText)}catch{}n.callback==null||n.callback(i)}},t.send(s)}}),fe!=null&&fe.sendBeacon&&Bn.push({transport:"sendBeacon",method:n=>{var e=ir(n.url,{beacon:"1"});try{var t,{contentType:r,body:s}=(t=Jr(n))!==null&&t!==void 0?t:{},i=typeof s=="string"?new Blob([s],{type:r}):s;fe.sendBeacon(e,i)}catch{}}});var or=function(n,e){if(!function(t){try{new RegExp(t)}catch{return!1}return!0}(e))return!1;try{return new RegExp(e).test(n)}catch{return!1}};function To(n,e,t){return ln({distinct_id:n,userPropertiesToSet:e,userPropertiesToSetOnce:t})}var hl={exact:(n,e)=>e.some(t=>n.some(r=>t===r)),is_not:(n,e)=>e.every(t=>n.every(r=>t!==r)),regex:(n,e)=>e.some(t=>n.some(r=>or(t,r))),not_regex:(n,e)=>e.every(t=>n.every(r=>!or(t,r))),icontains:(n,e)=>e.map(Nn).some(t=>n.map(Nn).some(r=>t.includes(r))),not_icontains:(n,e)=>e.map(Nn).every(t=>n.map(Nn).every(r=>!t.includes(r))),gt:(n,e)=>e.some(t=>{var r=parseFloat(t);return!isNaN(r)&&n.some(s=>r>parseFloat(s))}),lt:(n,e)=>e.some(t=>{var r=parseFloat(t);return!isNaN(r)&&n.some(s=>rn.toLowerCase();function gl(n,e){return!n||Object.entries(n).every(t=>{var[r,s]=t,i=e==null?void 0:e[r];if(b(i)||Ce(i))return!1;var o=[String(i)],a=hl[s.operator];return!!a&&a(s.values,o)})}var Zr=z("[Error tracking]");class Ju{constructor(e){var t,r;this.Zt=[],this.ti=new Pc([new jc,new Yc,new Hc,new Uc,new qc,new Vc,new zc,new Kc],Bc()),this._instance=e,this.Zt=(t=(r=this._instance.persistence)==null?void 0:r.get_property(vs))!==null&&t!==void 0?t:[]}onRemoteConfig(e){var t,r,s;if("errorTracking"in e){var i=(t=(r=e.errorTracking)==null?void 0:r.suppressionRules)!==null&&t!==void 0?t:[],o=(s=e.errorTracking)==null?void 0:s.captureExtensionExceptions;this.Zt=i,this._instance.persistence&&this._instance.persistence.register({[vs]:this.Zt,[ro]:o})}}get ii(){var e,t=!!this._instance.get_property(ro),r=this._instance.config.error_tracking.captureExtensionExceptions;return(e=r??t)!==null&&e!==void 0&&e}buildProperties(e,t){return this.ti.buildFromUnknown(e,{syntheticException:t==null?void 0:t.syntheticException,mechanism:{handled:t==null?void 0:t.handled}})}sendExceptionEvent(e){var t=e.$exception_list;if(this.ei(t)){if(this.ri(t))return void Zr.info("Skipping exception capture because a suppression rule matched");if(!this.ii&&this.si(t))return void Zr.info("Skipping exception capture because it was thrown by an extension");if(!this._instance.config.error_tracking.__capturePostHogExceptions&&this.ni(t))return void Zr.info("Skipping exception capture because it was thrown by the PostHog SDK")}return this._instance.capture("$exception",e,{_noTruncate:!0,_batchKey:"exceptionEvent",oi:!0})}ri(e){if(e.length===0)return!1;var t=e.reduce((r,s)=>{var{type:i,value:o}=s;return K(i)&&i.length>0&&r.$exception_types.push(i),K(o)&&o.length>0&&r.$exception_values.push(o),r},{$exception_types:[],$exception_values:[]});return this.Zt.some(r=>{var s=r.values.map(i=>{var o,a=hl[i.operator],l=L(i.value)?i.value:[i.value],c=(o=t[i.key])!==null&&o!==void 0?o:[];return l.length>0&&a(l,c)});return r.type==="OR"?s.some(Boolean):s.every(Boolean)})}si(e){return e.flatMap(t=>{var r,s;return(r=(s=t.stacktrace)==null?void 0:s.frames)!==null&&r!==void 0?r:[]}).some(t=>t.filename&&t.filename.startsWith("chrome-extension://"))}ni(e){if(e.length>0){var t,r,s,i,o=(t=(r=e[0].stacktrace)==null?void 0:r.frames)!==null&&t!==void 0?t:[],a=o[o.length-1];return(s=a==null||(i=a.filename)==null?void 0:i.includes("posthog.com/static"))!==null&&s!==void 0&&s}return!1}ei(e){return!M(e)&&L(e)}}var pe=z("[FeatureFlags]"),Xt=z("[FeatureFlags]",{debugEnabled:!0}),Zu="errors_while_computing_flags",Xu="flag_missing",Qu="quota_limited",ed="timeout",td="connection_error",nd="unknown_error",rd=n=>"api_error_"+n,Xr="$active_feature_flags",It="$override_feature_flags",Ro="$feature_flag_payloads",Qt="$override_feature_flag_payloads",Ao="$feature_flag_request_id",Po="$feature_flag_evaluated_at",$o=n=>{var e={};for(var[t,r]of Dn(n||{}))r&&(e[t]=r);return e},sd=n=>{var e=n.flags;return e?(n.featureFlags=Object.fromEntries(Object.keys(e).map(t=>{var r;return[t,(r=e[t].variant)!==null&&r!==void 0?r:e[t].enabled]})),n.featureFlagPayloads=Object.fromEntries(Object.keys(e).filter(t=>e[t].enabled).filter(t=>{var r;return(r=e[t].metadata)==null?void 0:r.payload}).map(t=>{var r;return[t,(r=e[t].metadata)==null?void 0:r.payload]}))):pe.warn("Using an older version of the feature flags endpoint. Please upgrade your PostHog server to the latest version"),n},id=function(n){return n.FeatureFlags="feature_flags",n.Recordings="recordings",n}({});class od{constructor(e){this.ai=!1,this.li=!1,this.ui=!1,this.hi=!1,this.di=!1,this.vi=!1,this.ci=!1,this._instance=e,this.featureFlagEventHandlers=[]}fi(){var e,t=(e=this._instance.config.evaluation_contexts)!==null&&e!==void 0?e:this._instance.config.evaluation_environments;return!this._instance.config.evaluation_environments||this._instance.config.evaluation_contexts||this.ci||(pe.warn("evaluation_environments is deprecated. Use evaluation_contexts instead. evaluation_environments will be removed in a future version."),this.ci=!0),t!=null&&t.length?t.filter(r=>{var s=r&&typeof r=="string"&&r.trim().length>0;return s||pe.error("Invalid evaluation context found:",r,"Expected non-empty string"),s}):[]}pi(){return this.fi().length>0}get hasLoadedFlags(){return this.li}getFlags(){return Object.keys(this.getFlagVariants())}getFlagsWithDetails(){var e=this._instance.get_property(_s),t=this._instance.get_property(It),r=this._instance.get_property(Qt);if(!r&&!t)return e||{};var s=G({},e||{}),i=[...new Set([...Object.keys(r||{}),...Object.keys(t||{})])];for(var o of i){var a,l,c=s[o],u=t==null?void 0:t[o],d=b(u)?(a=c==null?void 0:c.enabled)!==null&&a!==void 0&&a:!!u,p=b(u)?c.variant:typeof u=="string"?u:void 0,f=r==null?void 0:r[o],m=S({},c,{enabled:d,variant:d?p??(c==null?void 0:c.variant):void 0});d!==(c==null?void 0:c.enabled)&&(m.original_enabled=c==null?void 0:c.enabled),p!==(c==null?void 0:c.variant)&&(m.original_variant=c==null?void 0:c.variant),f&&(m.metadata=S({},c==null?void 0:c.metadata,{payload:f,original_payload:c==null||(l=c.metadata)==null?void 0:l.payload})),s[o]=m}return this.ai||(pe.warn(" Overriding feature flag details!",{flagDetails:e,overriddenPayloads:r,finalDetails:s}),this.ai=!0),s}getFlagVariants(){var e=this._instance.get_property($t),t=this._instance.get_property(It);if(!t)return e||{};for(var r=G({},e),s=Object.keys(t),i=0;i{this.bi()},5))}yi(){clearTimeout(this.gi),this.gi=void 0}ensureFlagsLoaded(){this.li||this.ui||this.gi||this.reloadFeatureFlags()}setAnonymousDistinctId(e){this.$anon_distinct_id=e}setReloadingPaused(e){this.hi=e}bi(e){var t;if(this.yi(),!this._instance.M())if(this.ui)this.di=!0;else{var r=this._instance.config.token,s=this._instance.get_property("$device_id"),i={token:r,distinct_id:this._instance.get_distinct_id(),groups:this._instance.getGroups(),$anon_distinct_id:this.$anon_distinct_id,person_properties:S({},((t=this._instance.persistence)==null?void 0:t.get_initial_props())||{},this._instance.get_property(an)||{}),group_properties:this._instance.get_property(ht),timezone:ll()};Ce(s)||b(s)||(i.$device_id=s),(e!=null&&e.disableFlags||this._instance.config.advanced_disable_feature_flags)&&(i.disable_flags=!0),this.pi()&&(i.evaluation_contexts=this.fi());var o=this._instance.config.advanced_only_evaluate_survey_feature_flags?"&only_evaluate_survey_feature_flags=true":"",a=this._instance.requestRouter.endpointFor("flags","/flags/?v=2"+o);this.ui=!0,this._instance._send_request({method:"POST",url:a,data:i,compression:this._instance.config.disable_compression?void 0:He.Base64,timeout:this._instance.config.feature_flag_request_timeout_ms,callback:l=>{var c,u,d,p=!0;if(l.statusCode===200&&(this.di||(this.$anon_distinct_id=void 0),p=!1),this.ui=!1,!i.disable_flags||this.di){this.vi=!p;var f=[];l.error?l.error instanceof Error?f.push(l.error.name==="AbortError"?ed:td):f.push(nd):l.statusCode!==200&&f.push(rd(l.statusCode)),(c=l.json)!=null&&c.errorsWhileComputingFlags&&f.push(Zu);var m=!((u=l.json)==null||(u=u.quotaLimited)==null||!u.includes(id.FeatureFlags));if(m&&f.push(Qu),(d=this._instance.persistence)==null||d.register({[ws]:f}),m)pe.warn("You have hit your feature flags quota limit, and will not be able to load feature flags until the quota is reset. Please visit https://posthog.com/docs/billing/limits-alerts to learn more.");else{var v;i.disable_flags||this.receivedFeatureFlags((v=l.json)!==null&&v!==void 0?v:{},p),this.di&&(this.di=!1,this.bi())}}}})}}getFeatureFlag(e,t){var r;if(t===void 0&&(t={}),!t.fresh||this.vi){if(this.li||this.getFlags()&&this.getFlags().length>0){var s=this.getFeatureFlagResult(e,t);return(r=s==null?void 0:s.variant)!==null&&r!==void 0?r:s==null?void 0:s.enabled}pe.warn('getFeatureFlag for key "'+e+`" failed. Feature flags didn't load in time.`)}}getFeatureFlagDetails(e){return this.getFlagsWithDetails()[e]}getFeatureFlagPayload(e){var t=this.getFeatureFlagResult(e,{send_event:!1});return t==null?void 0:t.payload}getFeatureFlagResult(e,t){if(t===void 0&&(t={}),!t.fresh||this.vi)if(this.li||this.getFlags()&&this.getFlags().length>0){var r=this.getFlagVariants(),s=e in r,i=r[e],o=this.getFlagPayloads()[e],a=String(i),l=this._instance.get_property(Ao)||void 0,c=this._instance.get_property(Po)||void 0,u=this._instance.get_property(Jn)||{};if((t.send_event||!("send_event"in t))&&(!(e in u)||!u[e].includes(a))){var d,p,f,m,v,_,C,k,T,I;L(u[e])?u[e].push(a):u[e]=[a],(d=this._instance.persistence)==null||d.register({[Jn]:u});var y=this.getFeatureFlagDetails(e),P=[...(p=this._instance.get_property(ws))!==null&&p!==void 0?p:[]];b(i)&&P.push(Xu);var A={$feature_flag:e,$feature_flag_response:i,$feature_flag_payload:o||null,$feature_flag_request_id:l,$feature_flag_evaluated_at:c,$feature_flag_bootstrapped_response:((f=this._instance.config.bootstrap)==null||(f=f.featureFlags)==null?void 0:f[e])||null,$feature_flag_bootstrapped_payload:((m=this._instance.config.bootstrap)==null||(m=m.featureFlagPayloads)==null?void 0:m[e])||null,$used_bootstrap_value:!this.vi};b(y==null||(v=y.metadata)==null?void 0:v.version)||(A.$feature_flag_version=y.metadata.version);var R,ne=(_=y==null||(C=y.reason)==null?void 0:C.description)!==null&&_!==void 0?_:y==null||(k=y.reason)==null?void 0:k.code;ne&&(A.$feature_flag_reason=ne),y!=null&&(T=y.metadata)!=null&&T.id&&(A.$feature_flag_id=y.metadata.id),b(y==null?void 0:y.original_variant)&&b(y==null?void 0:y.original_enabled)||(A.$feature_flag_original_response=b(y.original_variant)?y.original_enabled:y.original_variant),y!=null&&(I=y.metadata)!=null&&I.original_payload&&(A.$feature_flag_original_payload=y==null||(R=y.metadata)==null?void 0:R.original_payload),P.length&&(A.$feature_flag_error=P.join(",")),this._instance.capture("$feature_flag_called",A)}if(s){var J=o;if(!b(o))try{J=JSON.parse(o)}catch{}return{key:e,enabled:!!i,variant:typeof i=="string"?i:void 0,payload:J}}}else pe.warn('getFeatureFlagResult for key "'+e+`" failed. Feature flags didn't load in time.`)}getRemoteConfigPayload(e,t){var r=this._instance.config.token,s={distinct_id:this._instance.get_distinct_id(),token:r};this.pi()&&(s.evaluation_contexts=this.fi()),this._instance._send_request({method:"POST",url:this._instance.requestRouter.endpointFor("flags","/flags/?v=2"),data:s,compression:this._instance.config.disable_compression?void 0:He.Base64,timeout:this._instance.config.feature_flag_request_timeout_ms,callback:i=>{var o,a=(o=i.json)==null?void 0:o.featureFlagPayloads;t((a==null?void 0:a[e])||void 0)}})}isFeatureEnabled(e,t){if(t===void 0&&(t={}),!t.fresh||this.vi){if(this.li||this.getFlags()&&this.getFlags().length>0){var r=this.getFeatureFlag(e,t);return b(r)?void 0:!!r}pe.warn('isFeatureEnabled for key "'+e+`" failed. Feature flags didn't load in time.`)}}addFeatureFlagsHandler(e){this.featureFlagEventHandlers.push(e)}removeFeatureFlagsHandler(e){this.featureFlagEventHandlers=this.featureFlagEventHandlers.filter(t=>t!==e)}receivedFeatureFlags(e,t){if(this._instance.persistence){this.li=!0;var r=this.getFlagVariants(),s=this.getFlagPayloads(),i=this.getFlagsWithDetails();(function(o,a,l,c,u){l===void 0&&(l={}),c===void 0&&(c={}),u===void 0&&(u={});var d=sd(o),p=d.flags,f=d.featureFlags,m=d.featureFlagPayloads;if(f){var v=o.requestId,_=o.evaluatedAt;if(L(f)){pe.warn("v1 of the feature flags endpoint is deprecated. Please use the latest version.");var C={};if(f)for(var k=0;k{var R;return!((R=p[A])!=null&&R.failed)}));T=S({},l,Object.fromEntries(Object.entries(T).filter(A=>{var[R]=A;return P.has(R)}))),I=S({},c,Object.fromEntries(Object.entries(I||{}).filter(A=>{var[R]=A;return P.has(R)}))),y=S({},u,Object.fromEntries(Object.entries(y||{}).filter(A=>{var[R]=A;return P.has(R)})))}else T=S({},l,T),I=S({},c,I),y=S({},u,y);a&&a.register(S({[Xr]:Object.keys($o(T)),[$t]:T||{},[Ro]:I||{},[_s]:y||{}},v?{[Ao]:v}:{},_?{[Po]:_}:{}))}}})(e,this._instance.persistence,r,s,i),this.wi(t)}}override(e,t){t===void 0&&(t=!1),pe.warn("override is deprecated. Please use overrideFeatureFlags instead."),this.overrideFeatureFlags({flags:e,suppressWarning:t})}overrideFeatureFlags(e){if(!this._instance.__loaded||!this._instance.persistence)return pe.uninitializedWarning("posthog.featureFlags.overrideFeatureFlags");if(e===!1)return this._instance.persistence.unregister(It),this._instance.persistence.unregister(Qt),this.wi(),Xt.info("All overrides cleared");if(e&&typeof e=="object"&&("flags"in e||"payloads"in e)){var t,r=e;if(this.ai=!!((t=r.suppressWarning)!==null&&t!==void 0&&t),"flags"in r){if(r.flags===!1)this._instance.persistence.unregister(It),Xt.info("Flag overrides cleared");else if(r.flags){if(L(r.flags)){for(var s={},i=0;ithis.removeFeatureFlagsHandler(e)}updateEarlyAccessFeatureEnrollment(e,t,r){var s,i=(this._instance.get_property(on)||[]).find(c=>c.flagKey===e),o={["$feature_enrollment/"+e]:t},a={$feature_flag:e,$feature_enrollment:t,$set:o};i&&(a.$early_access_feature_name=i.name),r&&(a.$feature_enrollment_stage=r),this._instance.capture("$feature_enrollment_update",a),this.setPersonPropertiesForFlags(o,!1);var l=S({},this.getFlagVariants(),{[e]:t});(s=this._instance.persistence)==null||s.register({[Xr]:Object.keys($o(l)),[$t]:l}),this.wi()}getEarlyAccessFeatures(e,t,r){t===void 0&&(t=!1);var s=this._instance.get_property(on),i=r?"&"+r.map(o=>"stage="+o).join("&"):"";if(s&&!t)return e(s);this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/early_access_features/?token="+this._instance.config.token+i),method:"GET",callback:o=>{var a,l;if(o.json){var c=o.json.earlyAccessFeatures;return(a=this._instance.persistence)==null||a.unregister(on),(l=this._instance.persistence)==null||l.register({[on]:c}),e(c)}}})}xi(){var e=this.getFlags(),t=this.getFlagVariants();return{flags:e.filter(r=>t[r]),flagVariants:Object.keys(t).filter(r=>t[r]).reduce((r,s)=>(r[s]=t[s],r),{})}}wi(e){var{flags:t,flagVariants:r}=this.xi();this.featureFlagEventHandlers.forEach(s=>s(t,r,{errorsLoading:e}))}setPersonPropertiesForFlags(e,t){t===void 0&&(t=!0);var r=this._instance.get_property(an)||{};this._instance.register({[an]:S({},r,e)}),t&&this._instance.reloadFeatureFlags()}resetPersonPropertiesForFlags(){this._instance.unregister(an)}setGroupPropertiesForFlags(e,t){t===void 0&&(t=!0);var r=this._instance.get_property(ht)||{};Object.keys(r).length!==0&&Object.keys(r).forEach(s=>{r[s]=S({},r[s],e[s]),delete e[s]}),this._instance.register({[ht]:S({},r,e)}),t&&this._instance.reloadFeatureFlags()}resetGroupPropertiesForFlags(e){if(e){var t=this._instance.get_property(ht)||{};this._instance.register({[ht]:S({},t,{[e]:{}})})}else this._instance.unregister(ht)}reset(){this.li=!1,this.ui=!1,this.hi=!1,this.di=!1,this.vi=!1,this.$anon_distinct_id=void 0,this.yi(),this.ai=!1}}var ad=["cookie","localstorage","localstorage+cookie","sessionstorage","memory"];class Qr{constructor(e,t){this.R=e,this.props={},this.$i=!1,this.Ei=(r=>{var s="";return r.token&&(s=r.token.replace(/\+/g,"PL").replace(/\//g,"SL").replace(/=/g,"EQ")),r.persistence_name?"ph_"+r.persistence_name:"ph_"+s+"_posthog"})(e),this.Y=this.Si(e),this.load(),e.debug&&E.info("Persistence loaded",e.persistence,S({},this.props)),this.update_config(e,e,t),this.save()}isDisabled(){return!!this.ki}Si(e){ad.indexOf(e.persistence.toLowerCase())===-1&&(E.critical("Unknown persistence type "+e.persistence+"; falling back to localStorage+cookie"),e.persistence="localStorage+cookie");var t=function(s){s===void 0&&(s=[]);var i=[...bu,...s];return S({},W,{W:function(o){try{var a={};try{a=Pe.W(o)||{}}catch{}var l=G(a,JSON.parse(W.q(o)||"{}"));return W.G(o,l),l}catch{}return null},G:function(o,a,l,c,u,d){try{W.G(o,a,void 0,void 0,d);var p={};i.forEach(f=>{a[f]&&(p[f]=a[f])}),Object.keys(p).length&&Pe.G(o,p,l,c,u,d)}catch(f){W.B(f)}},V:function(o,a){try{h==null||h.localStorage.removeItem(o),Pe.V(o,a)}catch(l){W.B(l)}}})}(e.cookie_persisted_properties||[]),r=e.persistence.toLowerCase();return r==="localstorage"&&W.H()?W:r==="localstorage+cookie"&&t.H()?t:r==="sessionstorage"&&Q.H()?Q:r==="memory"?Eu:r==="cookie"?Pe:t.H()?t:Pe}properties(){var e={};return U(this.props,function(t,r){if(r===$t&&Z(t))for(var s=Object.keys(t),i=0;i{this.props.hasOwnProperty(o)&&this.props[o]!==t||(this.props[o]=i,s=!0)}),s)return this.save(),!0}return!1}register(e,t){if(Z(e)){this.Pi=b(t)?this.Ci:t;var r=!1;if(U(e,(s,i)=>{e.hasOwnProperty(i)&&this.props[i]!==s&&(this.props[i]=s,r=!0)}),r)return this.save(),!0}return!1}unregister(e){e in this.props&&(delete this.props[e],this.save())}update_campaign_params(){if(!this.$i){var e=nl(this.R.custom_campaign_params,this.R.mask_personal_data_properties,this.R.custom_personal_data_properties);Pt(ti(e))||this.register(e),this.$i=!0}}update_search_keyword(){var e;this.register((e=w==null?void 0:w.referrer)?sl(e):{})}update_referrer_info(){var e;this.register_once({$referrer:il(),$referring_domain:w!=null&&w.referrer&&((e=er(w.referrer))==null?void 0:e.host)||"$direct"},void 0)}set_initial_person_info(){this.props[Ss]||this.props[ks]||this.register_once({[Zn]:ol(this.R.mask_personal_data_properties,this.R.custom_personal_data_properties)},void 0)}get_initial_props(){var e={};U([ks,Ss],o=>{var a=this.props[o];a&&U(a,function(l,c){e["$initial_"+cs(c)]=l})});var t,r,s=this.props[Zn];if(s){var i=(t=al(s),r={},U(t,function(o,a){r["$initial_"+cs(a)]=o}),r);G(e,i)}return e}safe_merge(e){return U(this.props,function(t,r){r in e||(e[r]=t)}),e}update_config(e,t,r){if(this.Ci=this.Pi=e.cookie_expiration,this.set_disabled(e.disable_persistence||!!r),this.set_cross_subdomain(e.cross_subdomain_cookie),this.set_secure(e.secure_cookie),e.persistence!==t.persistence||!((o,a)=>{if(o.length!==a.length)return!1;var l=[...o].sort(),c=[...a].sort();return l.every((u,d)=>u===c[d])})(e.cookie_persisted_properties||[],t.cookie_persisted_properties||[])){var s=this.Si(e),i=this.props;this.clear(),this.Y=s,this.props=i,this.save()}}set_disabled(e){this.ki=e,this.ki?this.remove():this.save()}set_cross_subdomain(e){e!==this.Ti&&(this.Ti=e,this.remove(),this.save())}set_secure(e){e!==this.Ii&&(this.Ii=e,this.remove(),this.save())}set_event_timer(e,t){var r=this.props[sn]||{};r[e]=t,this.props[sn]=r,this.save()}remove_event_timer(e){var t=(this.props[sn]||{})[e];return b(t)||(delete this.props[sn][e],this.save()),t}get_property(e){return this.props[e]}set_property(e,t){this.props[e]=t,this.save()}}var Fo=z("[Product Tours]"),es="ph_product_tours";class ld{constructor(e){this.Ri=null,this.Fi=null,this._instance=e}onRemoteConfig(e){"productTours"in e&&(this._instance.persistence&&this._instance.persistence.register({[io]:!!e.productTours}),this.loadIfEnabled())}loadIfEnabled(){var e,t;this.Ri||(e=this._instance).config.disable_product_tours||(t=e.persistence)==null||!t.get_property(io)||this.it(()=>this.Oi())}it(e){var t,r;(t=x.__PosthogExtensions__)!=null&&t.generateProductTours?e():(r=x.__PosthogExtensions__)==null||r.loadExternalDependency==null||r.loadExternalDependency(this._instance,"product-tours",s=>{s?Fo.error("Could not load product tours script",s):e()})}Oi(){var e;!this.Ri&&(e=x.__PosthogExtensions__)!=null&&e.generateProductTours&&(this.Ri=x.__PosthogExtensions__.generateProductTours(this._instance,!0))}getProductTours(e,t){if(t===void 0&&(t=!1),!L(this.Fi)||t){var r=this._instance.persistence;if(r){var s=r.props[es];if(L(s)&&!t)return this.Fi=s,void e(s,{isLoaded:!0})}this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/product_tours/?token="+this._instance.config.token),method:"GET",callback:i=>{var o=i.statusCode;if(o!==200||!i.json){var a="Product Tours API could not be loaded, status: "+o;return Fo.error(a),void e([],{isLoaded:!1,error:a})}var l=L(i.json.product_tours)?i.json.product_tours:[];this.Fi=l,r&&r.register({[es]:l}),e(l,{isLoaded:!0})}})}else e(this.Fi,{isLoaded:!0})}getActiveProductTours(e){M(this.Ri)?e([],{isLoaded:!1,error:"Product tours not loaded"}):this.Ri.getActiveProductTours(e)}showProductTour(e){var t;(t=this.Ri)==null||t.showTourById(e)}previewTour(e){this.Ri?this.Ri.previewTour(e):this.it(()=>{var t;this.Oi(),(t=this.Ri)==null||t.previewTour(e)})}dismissProductTour(){var e;(e=this.Ri)==null||e.dismissTour("user_clicked_skip")}nextStep(){var e;(e=this.Ri)==null||e.nextStep()}previousStep(){var e;(e=this.Ri)==null||e.previousStep()}clearCache(){var e;this.Fi=null,(e=this._instance.persistence)==null||e.unregister(es)}resetTour(e){var t;(t=this.Ri)==null||t.resetTour(e)}resetAllTours(){var e;(e=this.Ri)==null||e.resetAllTours()}cancelPendingTour(e){var t;(t=this.Ri)==null||t.cancelPendingTour(e)}}var en=function(n){return n.Activation="events",n.Cancellation="cancelEvents",n}({});(function(n){return n.Button="button",n.Tab="tab",n.Selector="selector",n})({});(function(n){return n.TopLeft="top_left",n.TopRight="top_right",n.TopCenter="top_center",n.MiddleLeft="middle_left",n.MiddleRight="middle_right",n.MiddleCenter="middle_center",n.Left="left",n.Center="center",n.Right="right",n.NextToTrigger="next_to_trigger",n})({});(function(n){return n.Top="top",n.Left="left",n.Right="right",n.Bottom="bottom",n})({});var ts=function(n){return n.Popover="popover",n.API="api",n.Widget="widget",n.ExternalSurvey="external_survey",n}({});(function(n){return n.Open="open",n.MultipleChoice="multiple_choice",n.SingleChoice="single_choice",n.Rating="rating",n.Link="link",n})({});(function(n){return n.NextQuestion="next_question",n.End="end",n.ResponseBased="response_based",n.SpecificQuestion="specific_question",n})({});(function(n){return n.Once="once",n.Recurring="recurring",n.Always="always",n})({});var cn=function(n){return n.SHOWN="survey shown",n.DISMISSED="survey dismissed",n.SENT="survey sent",n.ABANDONED="survey abandoned",n}({}),ns=function(n){return n.SURVEY_ID="$survey_id",n.SURVEY_NAME="$survey_name",n.SURVEY_RESPONSE="$survey_response",n.SURVEY_ITERATION="$survey_iteration",n.SURVEY_ITERATION_START_DATE="$survey_iteration_start_date",n.SURVEY_PARTIALLY_COMPLETED="$survey_partially_completed",n.SURVEY_SUBMISSION_ID="$survey_submission_id",n.SURVEY_QUESTIONS="$survey_questions",n.SURVEY_COMPLETED="$survey_completed",n.PRODUCT_TOUR_ID="$product_tour_id",n.SURVEY_LAST_SEEN_DATE="$survey_last_seen_date",n}({}),Rs=function(n){return n.Popover="popover",n.Inline="inline",n}({}),j=z("[Surveys]"),ml="seenSurvey_",cd=(n,e)=>{var t="$survey_"+e+"/"+n.id;return n.current_iteration&&n.current_iteration>0&&(t="$survey_"+e+"/"+n.id+"/"+n.current_iteration),t},Mo=n=>((e,t)=>{var r=""+e+t.id;return t.current_iteration&&t.current_iteration>0&&(r=""+e+t.id+"_"+t.current_iteration),r})(ml,n),ud=[ts.Popover,ts.Widget,ts.API],dd={ignoreConditions:!1,ignoreDelay:!1,displayType:Rs.Popover};class ai{constructor(){this.Mi={},this.Mi={}}on(e,t){return this.Mi[e]||(this.Mi[e]=[]),this.Mi[e].push(t),()=>{this.Mi[e]=this.Mi[e].filter(r=>r!==t)}}emit(e,t){for(var r of this.Mi[e]||[])r(t);for(var s of this.Mi["*"]||[])s(e,t)}}function Ct(n,e,t){if(M(n))return!1;switch(t){case"exact":return n===e;case"contains":var r=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/_/g,".").replace(/%/g,".*");return new RegExp(r,"i").test(n);case"regex":try{return new RegExp(e).test(n)}catch{return!1}default:return!1}}class pd{constructor(e){this.Ai=new ai,this.ji=(t,r)=>this.Di(t,r)&&this.Li(t,r)&&this.Ni(t,r)&&this.Ui(t,r),this.Di=(t,r)=>r==null||!r.event||(t==null?void 0:t.event)===(r==null?void 0:r.event),this._instance=e,this.zi=new Set,this.Hi=new Set}init(){var e;if(!b((e=this._instance)==null?void 0:e._addCaptureHook)){var t;(t=this._instance)==null||t._addCaptureHook((r,s)=>{this.on(r,s)})}}register(e){var t,r;if(!b((t=this._instance)==null?void 0:t._addCaptureHook)&&(e.forEach(o=>{var a,l;(a=this.Hi)==null||a.add(o),(l=o.steps)==null||l.forEach(c=>{var u;(u=this.zi)==null||u.add((c==null?void 0:c.event)||"")})}),(r=this._instance)!=null&&r.autocapture)){var s,i=new Set;e.forEach(o=>{var a;(a=o.steps)==null||a.forEach(l=>{l!=null&&l.selector&&i.add(l==null?void 0:l.selector)})}),(s=this._instance)==null||s.autocapture.setElementSelectors(i)}}on(e,t){var r;t!=null&&e.length!=0&&(this.zi.has(e)||this.zi.has(t==null?void 0:t.event))&&this.Hi&&((r=this.Hi)==null?void 0:r.size)>0&&this.Hi.forEach(s=>{this.Bi(t,s)&&this.Ai.emit("actionCaptured",s.name)})}qi(e){this.onAction("actionCaptured",t=>e(t))}Bi(e,t){if((t==null?void 0:t.steps)==null)return!1;for(var r of t.steps)if(this.ji(e,r))return!0;return!1}onAction(e,t){return this.Ai.on(e,t)}Li(e,t){if(t!=null&&t.url){var r,s=e==null||(r=e.properties)==null?void 0:r.$current_url;if(!s||typeof s!="string"||!Ct(s,t.url,t.url_matching||"contains"))return!1}return!0}Ni(e,t){return!!this.Wi(e,t)&&!!this.Gi(e,t)&&!!this.Vi(e,t)}Wi(e,t){var r;if(t==null||!t.href)return!0;var s=this.Ji(e);if(s.length>0)return s.some(a=>Ct(a.href,t.href,t.href_matching||"exact"));var i,o=(e==null||(r=e.properties)==null?void 0:r.$elements_chain)||"";return!!o&&Ct((i=o.match(/(?::|")href="(.*?)"/))?i[1]:"",t.href,t.href_matching||"exact")}Gi(e,t){var r;if(t==null||!t.text)return!0;var s=this.Ji(e);if(s.length>0)return s.some(c=>Ct(c.text,t.text,t.text_matching||"exact")||Ct(c.$el_text,t.text,t.text_matching||"exact"));var i,o,a,l=(e==null||(r=e.properties)==null?void 0:r.$elements_chain)||"";return!!l&&(i=function(c){for(var u,d=[],p=/(?::|")text="(.*?)"/g;!M(u=p.exec(c));)d.includes(u[1])||d.push(u[1]);return d}(l),o=t.text,a=t.text_matching||"exact",i.some(c=>Ct(c,o,a)))}Vi(e,t){var r,s;if(t==null||!t.selector)return!0;var i=e==null||(r=e.properties)==null?void 0:r.$element_selectors;if(i!=null&&i.includes(t.selector))return!0;var o=(e==null||(s=e.properties)==null?void 0:s.$elements_chain)||"";if(t.selector_regex&&o)try{return new RegExp(t.selector_regex).test(o)}catch{return!1}return!1}Ji(e){var t;return(e==null||(t=e.properties)==null?void 0:t.$elements)==null?[]:e==null?void 0:e.properties.$elements}Ui(e,t){return t==null||!t.properties||t.properties.length===0||gl(t.properties.reduce((r,s)=>{var i=L(s.value)?s.value.map(String):s.value!=null?[String(s.value)]:[];return r[s.key]={values:i,operator:s.operator||"exact"},r},{}),e==null?void 0:e.properties)}}class fd{constructor(e){this._instance=e,this.Ki=new Map,this.Yi=new Map,this.Xi=new Map}Qi(e,t){return!!e&&gl(e.propertyFilters,t==null?void 0:t.properties)}Zi(e,t){var r=new Map;return e.forEach(s=>{var i;(i=s.conditions)==null||(i=i[t])==null||(i=i.values)==null||i.forEach(o=>{if(o!=null&&o.name){var a=r.get(o.name)||[];a.push(s.id),r.set(o.name,a)}})}),r}te(e,t,r){var s=(r===en.Activation?this.Ki:this.Yi).get(e),i=[];return this.ie(o=>{i=o.filter(a=>s==null?void 0:s.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(c=>c.name===e);return this.Qi(l,t)})}register(e){var t;b((t=this._instance)==null?void 0:t._addCaptureHook)||(this.ee(e),this.re(e))}re(e){var t=e.filter(r=>{var s,i;return((s=r.conditions)==null?void 0:s.actions)&&((i=r.conditions)==null||(i=i.actions)==null||(i=i.values)==null?void 0:i.length)>0});t.length!==0&&(this.se==null&&(this.se=new pd(this._instance),this.se.init(),this.se.qi(r=>{this.onAction(r)})),t.forEach(r=>{var s,i,o,a,l;r.conditions&&(s=r.conditions)!=null&&s.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.se)==null||a.register(r.conditions.actions.values),(l=r.conditions)==null||(l=l.actions)==null||(l=l.values)==null||l.forEach(c=>{if(c&&c.name){var u=this.Xi.get(c.name);u&&u.push(r.id),this.Xi.set(c.name,u||[r.id])}}))}))}ee(e){var t,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}),s=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||s.length!==0)&&((t=this._instance)==null||t._addCaptureHook((i,o)=>{this.onEvent(i,o)}),this.Ki=this.Zi(e,en.Activation),this.Yi=this.Zi(e,en.Cancellation))}onEvent(e,t){var r,s=this.ne(),i=this.oe(),o=this.ae(),a=((r=this._instance)==null||(r=r.persistence)==null?void 0:r.props[i])||[];if(o===e&&t&&a.length>0){var l,c;s.info("event matched, removing item from activated items",{event:e,eventPayload:t,existingActivatedItems:a});var u=(t==null||(l=t.properties)==null?void 0:l.$survey_id)||(t==null||(c=t.properties)==null?void 0:c.$product_tour_id);if(u){var d=a.indexOf(u);d>=0&&(a.splice(d,1),this.le(a))}}else{if(this.Yi.has(e)){var p=this.te(e,t,en.Cancellation);p.length>0&&(s.info("cancel event matched, cancelling items",{event:e,itemsToCancel:p.map(m=>m.id)}),p.forEach(m=>{var v=a.indexOf(m.id);v>=0&&a.splice(v,1),this.ue(m.id)}),this.le(a))}if(this.Ki.has(e)){s.info("event name matched",{event:e,eventPayload:t,items:this.Ki.get(e)});var f=this.te(e,t,en.Activation);this.le(a.concat(f.map(m=>m.id)||[]))}}}onAction(e){var t,r=this.oe(),s=((t=this._instance)==null||(t=t.persistence)==null?void 0:t.props[r])||[];this.Xi.has(e)&&this.le(s.concat(this.Xi.get(e)||[]))}le(e){var t,r=this.ne(),s=this.oe(),i=[...new Set(e)].filter(o=>!this.he(o));r.info("updating activated items",{activatedItems:i}),(t=this._instance)==null||(t=t.persistence)==null||t.register({[s]:i})}getActivatedIds(){var e,t=this.oe(),r=(e=this._instance)==null||(e=e.persistence)==null?void 0:e.props[t];return r||[]}getEventToItemsMap(){return this.Ki}de(){return this.se}}class hd extends fd{constructor(e){super(e)}oe(){return"$surveys_activated"}ae(){return cn.SHOWN}ie(e){var t;(t=this._instance)==null||t.getSurveys(e)}ue(e){var t;(t=this._instance)==null||t.cancelPendingSurvey(e)}ne(){return j}he(){return!1}getSurveys(){return this.getActivatedIds()}getEventToSurveys(){return this.getEventToItemsMap()}}class gd{constructor(e){this.ve=void 0,this._surveyManager=null,this.ce=!1,this.fe=[],this.pe=null,this._instance=e,this._surveyEventReceiver=null}onRemoteConfig(e){if(!this._instance.config.disable_surveys){var t=e.surveys;if(M(t))return j.warn("Flags not loaded yet. Not loading surveys.");var r=L(t);this.ve=r?t.length>0:t,j.info("flags response received, isSurveysEnabled: "+this.ve),this.loadIfEnabled()}}reset(){localStorage.removeItem("lastSeenSurveyDate");for(var e=[],t=0;tlocalStorage.removeItem(s))}loadIfEnabled(){if(!this._surveyManager)if(this.ce)j.info("Already initializing surveys, skipping...");else if(this._instance.config.disable_surveys)j.info("Disabled. Not loading surveys.");else if(this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut())j.info("Not loading surveys in cookieless mode without consent.");else{var e=x==null?void 0:x.__PosthogExtensions__;if(e){if(!b(this.ve)||this._instance.config.advanced_enable_surveys){var t=this.ve||this._instance.config.advanced_enable_surveys;this.ce=!0;try{var r=e.generateSurveys;if(r)return void this._e(r,t);var s=e.loadExternalDependency;if(!s)return void this.ge("PostHog loadExternalDependency extension not found.");s(this._instance,"surveys",i=>{i||!e.generateSurveys?this.ge("Could not load surveys script",i):this._e(e.generateSurveys,t)})}catch(i){throw this.ge("Error initializing surveys",i),i}finally{this.ce=!1}}}else j.error("PostHog Extensions not found.")}}_e(e,t){this._surveyManager=e(this._instance,t),this._surveyEventReceiver=new hd(this._instance),j.info("Surveys loaded successfully"),this.me({isLoaded:!0})}ge(e,t){j.error(e,t),this.me({isLoaded:!1,error:e})}onSurveysLoaded(e){return this.fe.push(e),this._surveyManager&&this.me({isLoaded:!0}),()=>{this.fe=this.fe.filter(t=>t!==e)}}getSurveys(e,t){if(t===void 0&&(t=!1),this._instance.config.disable_surveys)return j.info("Disabled. Not loading surveys."),e([]);var r,s=this._instance.get_property(ys);if(s&&!t)return e(s,{isLoaded:!0});typeof Promise<"u"&&this.pe?this.pe.then(i=>{var{surveys:o,context:a}=i;return e(o,a)}):(typeof Promise<"u"&&(this.pe=new Promise(i=>{r=i})),this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/surveys/?token="+this._instance.config.token),method:"GET",timeout:this._instance.config.surveys_request_timeout_ms,callback:i=>{var o;this.pe=null;var a=i.statusCode;if(a!==200||!i.json){var l="Surveys API could not be loaded, status: "+a;j.error(l);var c={isLoaded:!1,error:l};return e([],c),void(r==null||r({surveys:[],context:c}))}var u,d=i.json.surveys||[],p=d.filter(m=>function(v){return!(!v.start_date||v.end_date)}(m)&&(function(v){var _;return!((_=v.conditions)==null||(_=_.events)==null||(_=_.values)==null||!_.length)}(m)||function(v){var _;return!((_=v.conditions)==null||(_=_.actions)==null||(_=_.values)==null||!_.length)}(m)));p.length>0&&((u=this._surveyEventReceiver)==null||u.register(p)),(o=this._instance.persistence)==null||o.register({[ys]:d});var f={isLoaded:!0};e(d,f),r==null||r({surveys:d,context:f})}}))}me(e){for(var t of this.fe)try{if(!e.isLoaded)return t([],e);this.getSurveys(t)}catch(r){j.error("Error in survey callback",r)}}getActiveMatchingSurveys(e,t){if(t===void 0&&(t=!1),!M(this._surveyManager))return this._surveyManager.getActiveMatchingSurveys(e,t);j.warn("init was not called")}be(e){var t=null;return this.getSurveys(r=>{var s;t=(s=r.find(i=>i.id===e))!==null&&s!==void 0?s:null}),t}ye(e){if(M(this._surveyManager))return{eligible:!1,reason:"SDK is not enabled or survey functionality is not yet loaded"};var t=typeof e=="string"?this.be(e):e;return t?this._surveyManager.checkSurveyEligibility(t):{eligible:!1,reason:"Survey not found"}}canRenderSurvey(e){if(M(this._surveyManager))return j.warn("init was not called"),{visible:!1,disabledReason:"SDK is not enabled or survey functionality is not yet loaded"};var t=this.ye(e);return{visible:t.eligible,disabledReason:t.reason}}canRenderSurveyAsync(e,t){return M(this._surveyManager)?(j.warn("init was not called"),Promise.resolve({visible:!1,disabledReason:"SDK is not enabled or survey functionality is not yet loaded"})):new Promise(r=>{this.getSurveys(s=>{var i,o=(i=s.find(l=>l.id===e))!==null&&i!==void 0?i:null;if(o){var a=this.ye(o);r({visible:a.eligible,disabledReason:a.reason})}else r({visible:!1,disabledReason:"Survey not found"})},t)})}renderSurvey(e,t,r){var s;if(M(this._surveyManager))j.warn("init was not called");else{var i=typeof e=="string"?this.be(e):e;if(i!=null&&i.id)if(ud.includes(i.type)){var o=w==null?void 0:w.querySelector(t);if(o)return(s=i.appearance)!=null&&s.surveyPopupDelaySeconds?(j.info("Rendering survey "+i.id+" with delay of "+i.appearance.surveyPopupDelaySeconds+" seconds"),void setTimeout(()=>{var a,l;j.info("Rendering survey "+i.id+" with delay of "+((a=i.appearance)==null?void 0:a.surveyPopupDelaySeconds)+" seconds"),(l=this._surveyManager)==null||l.renderSurvey(i,o,r),j.info("Survey "+i.id+" rendered")},1e3*i.appearance.surveyPopupDelaySeconds)):void this._surveyManager.renderSurvey(i,o,r);j.warn("Survey element not found")}else j.warn("Surveys of type "+i.type+" cannot be rendered in the app");else j.warn("Survey not found")}}displaySurvey(e,t){var r;if(M(this._surveyManager))j.warn("init was not called");else{var s=this.be(e);if(s){var i=s;if((r=s.appearance)!=null&&r.surveyPopupDelaySeconds&&t.ignoreDelay&&(i=S({},s,{appearance:S({},s.appearance,{surveyPopupDelaySeconds:0})})),t.displayType!==Rs.Popover&&t.initialResponses&&j.warn("initialResponses is only supported for popover surveys. prefill will not be applied."),t.ignoreConditions===!1){var o=this.canRenderSurvey(s);if(!o.visible)return void j.warn("Survey is not eligible to be displayed: ",o.disabledReason)}t.displayType!==Rs.Inline?this._surveyManager.handlePopoverSurvey(i,t):this.renderSurvey(i,t.selector,t.properties)}else j.warn("Survey not found")}}cancelPendingSurvey(e){M(this._surveyManager)?j.warn("init was not called"):this._surveyManager.cancelSurvey(e)}handlePageUnload(){var e;(e=this._surveyManager)==null||e.handlePageUnload()}}var _e=z("[Conversations]");class md{constructor(e){this.we=void 0,this._conversationsManager=null,this.xe=!1,this.$e=null,this._instance=e}onRemoteConfig(e){if(!this._instance.config.disable_conversations){var t=e.conversations;M(t)||(qe(t)?this.we=t:(this.we=t.enabled,this.$e=t),this.loadIfEnabled())}}reset(){var e;(e=this._conversationsManager)==null||e.reset(),this._conversationsManager=null,this.we=void 0,this.$e=null}loadIfEnabled(){if(!(this._conversationsManager||this.xe||this._instance.config.disable_conversations||Ma(this._instance.config)||this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut())){var e=x==null?void 0:x.__PosthogExtensions__;if(e&&!b(this.we)&&this.we)if(this.$e&&this.$e.token){this.xe=!0;try{var t=e.initConversations;if(t)return this.Ee(t),void(this.xe=!1);var r=e.loadExternalDependency;if(!r)return void this.Se("PostHog loadExternalDependency extension not found.");r(this._instance,"conversations",s=>{s||!e.initConversations?this.Se("Could not load conversations script",s):this.Ee(e.initConversations),this.xe=!1})}catch(s){this.Se("Error initializing conversations",s),this.xe=!1}}else _e.error("Conversations enabled but missing token in remote config.")}}Ee(e){if(this.$e)try{this._conversationsManager=e(this.$e,this._instance),_e.info("Conversations loaded successfully")}catch(t){this.Se("Error completing conversations initialization",t)}else _e.error("Cannot complete initialization: remote config is null")}Se(e,t){_e.error(e,t),this._conversationsManager=null,this.xe=!1}show(){this._conversationsManager?this._conversationsManager.show():_e.warn("Conversations not loaded yet.")}hide(){this._conversationsManager&&this._conversationsManager.hide()}isAvailable(){return this.we===!0&&!Ce(this._conversationsManager)}isVisible(){var e,t;return(e=(t=this._conversationsManager)==null?void 0:t.isVisible())!==null&&e!==void 0&&e}sendMessage(e,t,r){var s=this;return je(function*(){return s._conversationsManager?s._conversationsManager.sendMessage(e,t,r):(_e.warn("Conversations not available yet."),null)})()}getMessages(e,t){var r=this;return je(function*(){return r._conversationsManager?r._conversationsManager.getMessages(e,t):(_e.warn("Conversations not available yet."),null)})()}markAsRead(e){var t=this;return je(function*(){return t._conversationsManager?t._conversationsManager.markAsRead(e):(_e.warn("Conversations not available yet."),null)})()}getTickets(e){var t=this;return je(function*(){return t._conversationsManager?t._conversationsManager.getTickets(e):(_e.warn("Conversations not available yet."),null)})()}requestRestoreLink(e){var t=this;return je(function*(){return t._conversationsManager?t._conversationsManager.requestRestoreLink(e):(_e.warn("Conversations not available yet."),null)})()}restoreFromToken(e){var t=this;return je(function*(){return t._conversationsManager?t._conversationsManager.restoreFromToken(e):(_e.warn("Conversations not available yet."),null)})()}restoreFromUrlToken(){var e=this;return je(function*(){return e._conversationsManager?e._conversationsManager.restoreFromUrlToken():(_e.warn("Conversations not available yet."),null)})()}getCurrentTicketId(){var e,t;return(e=(t=this._conversationsManager)==null?void 0:t.getCurrentTicketId())!==null&&e!==void 0?e:null}getWidgetSessionId(){var e,t;return(e=(t=this._conversationsManager)==null?void 0:t.getWidgetSessionId())!==null&&e!==void 0?e:null}}class vd{constructor(e){var t;this.ke=!1,this.Pe=!1,this._instance=e,this._instance&&(t=this._instance.config.logs)!=null&&t.captureConsoleLogs&&(this.ke=!0)}onRemoteConfig(e){var t,r=(t=e.logs)==null?void 0:t.captureConsoleLogs;!M(r)&&r&&(this.ke=!0,this.loadIfEnabled())}reset(){}loadIfEnabled(){if(this.ke&&!this.Pe){var e=z("[logs]"),t=x==null?void 0:x.__PosthogExtensions__;if(t){var r=t.loadExternalDependency;r?r(this._instance,"logs",s=>{var i;s||(i=t.logs)==null||!i.initializeLogs?e.error("Could not load logs script",s):(t.logs.initializeLogs(this._instance),this.Pe=!0)}):e.error("PostHog loadExternalDependency extension not found.")}else e.error("PostHog Extensions not found.")}}}var Oo=z("[RateLimiter]");class _d{constructor(e){this.serverLimits={},this.lastEventRateLimited=!1,this.checkForLimiting=t=>{var r=t.text;if(r&&r.length)try{(JSON.parse(r).quota_limited||[]).forEach(s=>{Oo.info((s||"events")+" is quota limited."),this.serverLimits[s]=new Date().getTime()+6e4})}catch(s){return void Oo.warn('could not rate limit - continuing. Error: "'+(s==null?void 0:s.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 t,r,s;e===void 0&&(e=!1);var{captureEventsBurstLimit:i,captureEventsPerSecond:o}=this,a=new Date().getTime(),l=(t=(r=this.instance.persistence)==null?void 0:r.get_property(Es))!==null&&t!==void 0?t:{tokens:i,last:a};l.tokens+=(a-l.last)/1e3*o,l.last=a,l.tokens>i&&(l.tokens=i);var c=l.tokens<1;return c||e||(l.tokens=Math.max(0,l.tokens-1)),!c||this.lastEventRateLimited||e||this.instance.capture("$$client_ingestion_warning",{$$client_ingestion_warning_message:"posthog-js client rate limited. Config is set to "+o+" events per second and "+i+" events burst limit."},{skip_client_rate_limiting:!0}),this.lastEventRateLimited=c,(s=this.instance.persistence)==null||s.set_property(Es,l),{isRateLimited:c,remainingTokens:l.tokens}}isServerRateLimited(e){var t=this.serverLimits[e||"events"]||!1;return t!==!1&&new Date().getTime()e(this.remoteConfig)):e()}Ie(e){this._instance._send_request({method:"GET",url:this._instance.requestRouter.endpointFor("assets","/array/"+this._instance.config.token+"/config"),callback:t=>{e(t.json)}})}load(){try{if(this.remoteConfig)return tn.info("Using preloaded remote config",this.remoteConfig),this.Ce(this.remoteConfig),void this.Re();if(this._instance.M())return void tn.warn("Remote config is disabled. Falling back to local config.");this.Te(e=>{if(!e)return tn.info("No config found after loading remote JS config. Falling back to JSON."),void this.Ie(t=>{this.Ce(t),this.Re()});this.Ce(e),this.Re()})}catch(e){tn.error("Error loading remote config",e)}}stop(){this.Fe&&(clearInterval(this.Fe),this.Fe=void 0)}refresh(){this._instance.M()||(w==null?void 0:w.visibilityState)==="hidden"||this._instance.featureFlags.reloadFeatureFlags()}Re(){this.Fe||(this.Fe=setInterval(()=>{this.refresh()},3e5))}Ce(e){e||tn.error("Failed to fetch remote config from PostHog."),this._instance.Ce(e??{}),(e==null?void 0:e.hasFeatureFlags)!==!1&&(this._instance.config.advanced_disable_feature_flags_on_first_load||this._instance.featureFlags.ensureFlagsLoaded())}}var As=3e3;class yd{constructor(e,t){this.Oe=!0,this.Me=[],this.Ae=Oe((t==null?void 0:t.flush_interval_ms)||As,250,5e3,E.createLogger("flush interval"),As),this.je=e}enqueue(e){this.Me.push(e),this.De||this.Le()}unload(){this.Ne();var e=this.Me.length>0?this.Ue():{},t=Object.values(e);[...t.filter(r=>r.url.indexOf("/e")===0),...t.filter(r=>r.url.indexOf("/e")!==0)].map(r=>{this.je(S({},r,{transport:"sendBeacon"}))})}enable(){this.Oe=!1,this.Le()}Le(){var e=this;this.Oe||(this.De=setTimeout(()=>{if(this.Ne(),this.Me.length>0){var t=this.Ue(),r=function(){var i=t[s],o=new Date().getTime();i.data&&L(i.data)&&U(i.data,a=>{a.offset=Math.abs(a.timestamp-o),delete a.timestamp}),e.je(i)};for(var s in t)r()}},this.Ae))}Ne(){clearTimeout(this.De),this.De=void 0}Ue(){var e={};return U(this.Me,t=>{var r,s=t,i=(s?s.batchKey:null)||s.url;b(e[i])&&(e[i]=S({},s,{data:[]})),(r=e[i].data)==null||r.push(s.data)}),this.Me=[],e}}var wd=["retriesPerformedSoFar"];class bd{constructor(e){this.ze=!1,this.He=3e3,this.Me=[],this._instance=e,this.Me=[],this.Be=!0,!b(h)&&"onLine"in h.navigator&&(this.Be=h.navigator.onLine,this.qe=()=>{this.Be=!0,this.Lt()},this.We=()=>{this.Be=!1},Y(h,"online",this.qe),Y(h,"offline",this.We))}get length(){return this.Me.length}retriableRequest(e){var{retriesPerformedSoFar:t}=e,r=ua(e,wd);Tt(t)&&(r.url=ir(r.url,{retry_count:t})),this._instance._send_request(S({},r,{callback:s=>{s.statusCode!==200&&(s.statusCode<400||s.statusCode>=500)&&(t??0)<10?this.Ge(S({retriesPerformedSoFar:t},r)):r.callback==null||r.callback(s)}}))}Ge(e){var t=e.retriesPerformedSoFar||0;e.retriesPerformedSoFar=t+1;var r=function(o){var a=3e3*Math.pow(2,o),l=a/2,c=Math.min(18e5,a),u=(Math.random()-.5)*(c-l);return Math.ceil(c+u)}(t),s=Date.now()+r;this.Me.push({retryAt:s,requestOptions:e});var i="Enqueued failed request for retry in "+r;navigator.onLine||(i+=" (Browser is offline)"),E.warn(i),this.ze||(this.ze=!0,this.Ve())}Ve(){if(this.Je&&clearTimeout(this.Je),this.Me.length===0)return this.ze=!1,void(this.Je=void 0);this.Je=setTimeout(()=>{this.Be&&this.Me.length>0&&this.Lt(),this.Ve()},this.He)}Lt(){var e=Date.now(),t=[],r=this.Me.filter(i=>i.retryAt0)for(var{requestOptions:s}of r)this.retriableRequest(s)}unload(){for(var{requestOptions:e}of(this.Je&&(clearTimeout(this.Je),this.Je=void 0),this.ze=!1,b(h)||(this.qe&&(h.removeEventListener("online",this.qe),this.qe=void 0),this.We&&(h.removeEventListener("offline",this.We),this.We=void 0)),this.Me))try{this._instance._send_request(S({},e,{transport:"sendBeacon"}))}catch(t){E.error(t)}this.Me=[]}}class Ed{constructor(e){this.Ke=()=>{var t,r,s,i;this.Ye||(this.Ye={});var o=this.scrollElement(),a=this.scrollY(),l=o?Math.max(0,o.scrollHeight-o.clientHeight):0,c=a+((o==null?void 0:o.clientHeight)||0),u=(o==null?void 0:o.scrollHeight)||0;this.Ye.lastScrollY=Math.ceil(a),this.Ye.maxScrollY=Math.max(a,(t=this.Ye.maxScrollY)!==null&&t!==void 0?t:0),this.Ye.maxScrollHeight=Math.max(l,(r=this.Ye.maxScrollHeight)!==null&&r!==void 0?r:0),this.Ye.lastContentY=c,this.Ye.maxContentY=Math.max(c,(s=this.Ye.maxContentY)!==null&&s!==void 0?s:0),this.Ye.maxContentHeight=Math.max(u,(i=this.Ye.maxContentHeight)!==null&&i!==void 0?i:0)},this._instance=e}getContext(){return this.Ye}resetContext(){var e=this.Ye;return setTimeout(this.Ke,0),e}startMeasuringScrollPosition(){Y(h,"scroll",this.Ke,{capture:!0}),Y(h,"scrollend",this.Ke,{capture:!0}),Y(h,"resize",this.Ke)}scrollElement(){if(!this._instance.config.scroll_root_selector)return h==null?void 0:h.document.documentElement;var e=L(this._instance.config.scroll_root_selector)?this._instance.config.scroll_root_selector:[this._instance.config.scroll_root_selector];for(var t of e){var r=h==null?void 0:h.document.querySelector(t);if(r)return r}}scrollY(){if(this._instance.config.scroll_root_selector){var e=this.scrollElement();return e&&e.scrollTop||0}return h&&(h.scrollY||h.pageYOffset||h.document.documentElement.scrollTop)||0}scrollX(){if(this._instance.config.scroll_root_selector){var e=this.scrollElement();return e&&e.scrollLeft||0}return h&&(h.scrollX||h.pageXOffset||h.document.documentElement.scrollLeft)||0}}var Sd=n=>ol(n==null?void 0:n.config.mask_personal_data_properties,n==null?void 0:n.config.custom_personal_data_properties);class No{constructor(e,t,r,s){this.Xe=i=>{var o=this.Qe();if(!o||o.sessionId!==i){var a={sessionId:i,props:this.Ze(this._instance)};this.tr.register({[bs]:a})}},this._instance=e,this.ir=t,this.tr=r,this.Ze=s||Sd,this.ir.onSessionId(this.Xe)}Qe(){return this.tr.props[bs]}getSetOnceProps(){var e,t=(e=this.Qe())==null?void 0:e.props;return t?"r"in t?al(t):{$referring_domain:t.referringDomain,$pathname:t.initialPathName,utm_source:t.utm_source,utm_campaign:t.utm_campaign,utm_medium:t.utm_medium,utm_content:t.utm_content,utm_term:t.utm_term}:{}}getSessionProps(){var e={};return U(ti(this.getSetOnceProps()),(t,r)=>{r==="$current_url"&&(r="url"),e["$session_entry_"+cs(r)]=t}),e}}var rs=z("[SessionId]");class Lo{on(e,t){return this.er.on(e,t)}constructor(e,t,r){var s;if(this.rr=[],this.sr=void 0,this.er=new ai,this.nr=(u,d)=>!(!Tt(u)||!Tt(d))&&Math.abs(u-d)>this.sessionTimeoutMs,!e.persistence)throw new Error("SessionIdManager requires a PostHogPersistence instance");if(e.config.cookieless_mode==="always")throw new Error('SessionIdManager cannot be used with cookieless_mode="always"');this.R=e.config,this.tr=e.persistence,this.ar=void 0,this.lr=void 0,this._sessionStartTimestamp=null,this._sessionActivityTimestamp=null,this.ur=t||it,this.hr=r||it;var i=this.R.persistence_name||this.R.token,o=this.R.session_idle_timeout_seconds||1800;if(this._sessionTimeoutMs=1e3*Oe(o,60,36e3,rs.createLogger("session_idle_timeout_seconds"),1800),e.register({$configured_session_timeout_ms:this._sessionTimeoutMs}),this.dr(),this.vr="ph_"+i+"_window_id",this.cr="ph_"+i+"_primary_window_exists",this.pr()){var a=Q.W(this.vr),l=Q.W(this.cr);a&&!l?this.ar=a:Q.V(this.vr),Q.G(this.cr,!0)}if((s=this.R.bootstrap)!=null&&s.sessionID)try{var c=(u=>{var d=u.replace(/-/g,"");if(d.length!==32)throw new Error("Not a valid UUID");if(d[12]!=="7")throw new Error("Not a UUIDv7");return parseInt(d.substring(0,12),16)})(this.R.bootstrap.sessionID);this._r(this.R.bootstrap.sessionID,new Date().getTime(),c)}catch(u){rs.error("Invalid sessionID in bootstrap",u)}this.gr()}get sessionTimeoutMs(){return this._sessionTimeoutMs}onSessionId(e){return b(this.rr)&&(this.rr=[]),this.rr.push(e),this.lr&&e(this.lr,this.ar),()=>{this.rr=this.rr.filter(t=>t!==e)}}pr(){return this.R.persistence!=="memory"&&!this.tr.ki&&Q.H()}mr(e){e!==this.ar&&(this.ar=e,this.pr()&&Q.G(this.vr,e))}br(){return this.ar?this.ar:this.pr()?Q.W(this.vr):null}_r(e,t,r){e===this.lr&&t===this._sessionActivityTimestamp&&r===this._sessionStartTimestamp||(this._sessionStartTimestamp=r,this._sessionActivityTimestamp=t,this.lr=e,this.tr.register({[Yn]:[t,e,r]}))}yr(){var e=this.tr.props[Yn];return L(e)&&e.length===2&&e.push(e[0]),e||[0,null,0]}resetSessionId(){this._r(null,null,null)}destroy(){clearTimeout(this.wr),this.wr=void 0,this.sr&&h&&(h.removeEventListener("beforeunload",this.sr,{capture:!1}),this.sr=void 0),this.rr=[]}gr(){this.sr=()=>{this.pr()&&Q.V(this.cr)},Y(h,"beforeunload",this.sr,{capture:!1})}checkAndGetSessionAndWindowId(e,t){if(e===void 0&&(e=!1),t===void 0&&(t=null),this.R.cookieless_mode==="always")throw new Error('checkAndGetSessionAndWindowId should not be called with cookieless_mode="always"');var r=t||new Date().getTime(),[s,i,o]=this.yr(),a=this.br(),l=Tt(o)&&Math.abs(r-o)>864e5,c=!1,u=!i,d=!u&&!e&&this.nr(r,s);u||d||l?(i=this.ur(),a=this.hr(),rs.info("new session ID generated",{sessionId:i,windowId:a,changeReason:{noSessionId:u,activityTimeout:d,sessionPastMaximumLength:l}}),o=r,c=!0):a||(a=this.hr(),c=!0);var p=Tt(s)&&e&&!l?s:r,f=Tt(o)?o:new Date().getTime();return this.mr(a),this._r(i,p,f),e||this.dr(),c&&this.rr.forEach(m=>m(i,a,c?{noSessionId:u,activityTimeout:d,sessionPastMaximumLength:l}:void 0)),{sessionId:i,windowId:a,sessionStartTimestamp:f,changeReason:c?{noSessionId:u,activityTimeout:d,sessionPastMaximumLength:l}:void 0,lastActivityTimestamp:s}}dr(){clearTimeout(this.wr),this.wr=setTimeout(()=>{var[e]=this.yr();if(this.nr(new Date().getTime(),e)){var t=this.lr;this.resetSessionId(),this.er.emit("forcedIdleReset",{idleSessionId:t})}},1.1*this.sessionTimeoutMs)}}var kd=["$set_once","$set"],rt=z("[SiteApps]");class Id{constructor(e){this._instance=e,this.$r=[],this.apps={}}get isEnabled(){return!!this._instance.config.opt_in_site_apps}Er(e,t){if(t){var r=this.globalsForEvent(t);this.$r.push(r),this.$r.length>1e3&&(this.$r=this.$r.slice(10))}}get siteAppLoaders(){var e;return(e=x._POSTHOG_REMOTE_CONFIG)==null||(e=e[this._instance.config.token])==null?void 0:e.siteApps}init(){if(this.isEnabled){var e=this._instance._addCaptureHook(this.Er.bind(this));this.Sr=()=>{e(),this.$r=[],this.Sr=void 0}}}globalsForEvent(e){var t,r,s,i,o,a,l;if(!e)throw new Error("Event payload is required");var c={},u=this._instance.get_property("$groups")||[],d=this._instance.get_property("$stored_group_properties")||{};for(var[p,f]of Object.entries(d))c[p]={id:u[p],type:p,properties:f};var{$set_once:m,$set:v}=e;return{event:S({},ua(e,kd),{properties:S({},e.properties,v?{$set:S({},(t=(r=e.properties)==null?void 0:r.$set)!==null&&t!==void 0?t:{},v)}:{},m?{$set_once:S({},(s=(i=e.properties)==null?void 0:i.$set_once)!==null&&s!==void 0?s:{},m)}:{}),elements_chain:(o=(a=e.properties)==null?void 0:a.$elements_chain)!==null&&o!==void 0?o:"",distinct_id:(l=e.properties)==null?void 0:l.distinct_id}),person:{properties:this._instance.get_property("$stored_person_properties")},groups:c}}setupSiteApp(e){var t=this.apps[e.id],r=()=>{var a;!t.errored&&this.$r.length&&(rt.info("Processing "+this.$r.length+" events for site app with id "+e.id),this.$r.forEach(l=>t.processEvent==null?void 0:t.processEvent(l)),t.processedBuffer=!0),Object.values(this.apps).every(l=>l.processedBuffer||l.errored)&&((a=this.Sr)==null||a.call(this))},s=!1,i=a=>{t.errored=!a,t.loaded=!0,rt.info("Site app with id "+e.id+" "+(a?"loaded":"errored")),s&&r()};try{var{processEvent:o}=e.init({posthog:this._instance,callback:a=>{i(a)}});o&&(t.processEvent=o),s=!0}catch(a){rt.error("Error while initializing PostHog app with config id "+e.id,a),i(!1)}if(s&&t.loaded)try{r()}catch(a){rt.error("Error while processing buffered events PostHog app with config id "+e.id,a),t.errored=!0}}kr(){var e=this.siteAppLoaders||[];for(var t of e)this.apps[t.id]={id:t.id,loaded:!1,errored:!1,processedBuffer:!1};for(var r of e)this.setupSiteApp(r)}Pr(e){if(Object.keys(this.apps).length!==0){var t=this.globalsForEvent(e);for(var r of Object.values(this.apps))try{r.processEvent==null||r.processEvent(t)}catch(s){rt.error("Error while processing event "+e.event+" for site app "+r.id,s)}}}onRemoteConfig(e){var t,r,s,i=this;if((t=this.siteAppLoaders)!=null&&t.length)return this.isEnabled?(this.kr(),void this._instance.on("eventCaptured",c=>this.Pr(c))):void rt.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.');if((r=this.Sr)==null||r.call(this),(s=e.siteApps)!=null&&s.length)if(this.isEnabled){var o=function(c){var u;x["__$$ph_site_app_"+c]=i._instance,(u=x.__PosthogExtensions__)==null||u.loadSiteApp==null||u.loadSiteApp(i._instance,l,d=>{if(d)return rt.error("Error while initializing PostHog app with config id "+c,d)})};for(var{id:a,url:l}of e.siteApps)o(a)}else rt.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.')}}var _l=function(n,e){if(!n)return!1;var t=n.userAgent;if(t&&Vi(t,e))return!0;try{var r=n==null?void 0:n.userAgentData;if(r!=null&&r.brands&&r.brands.some(s=>Vi(s==null?void 0:s.brand,e)))return!0}catch{}return!!n.webdriver},un=function(n){return n.US="us",n.EU="eu",n.CUSTOM="custom",n}({}),Do="i.posthog.com";class Cd{constructor(e){this.Tr={},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,t=(e=this.instance.config.ui_host)==null?void 0:e.replace(/\/$/,"");return t||(t=this.apiHost.replace("."+Do,".posthog.com")),t==="https://app.posthog.com"?"https://us.posthog.com":t}get region(){return this.Tr[this.apiHost]||(/https:\/\/(app|us|us-assets)(\.i)?\.posthog\.com/i.test(this.apiHost)?this.Tr[this.apiHost]=un.US:/https:\/\/(eu|eu-assets)(\.i)?\.posthog\.com/i.test(this.apiHost)?this.Tr[this.apiHost]=un.EU:this.Tr[this.apiHost]=un.CUSTOM),this.Tr[this.apiHost]}endpointFor(e,t){if(t===void 0&&(t=""),t&&(t=t[0]==="/"?t:"/"+t),e==="ui")return this.uiHost+t;if(e==="flags")return this.flagsApiHost+t;if(this.region===un.CUSTOM)return this.apiHost+t;var r=Do+t;switch(e){case"assets":return"https://"+this.region+"-assets."+r;case"api":return"https://"+this.region+"."+r}}}var xd={icontains:(n,e)=>!!h&&e.href.toLowerCase().indexOf(n.toLowerCase())>-1,not_icontains:(n,e)=>!!h&&e.href.toLowerCase().indexOf(n.toLowerCase())===-1,regex:(n,e)=>!!h&&or(e.href,n),not_regex:(n,e)=>!!h&&!or(e.href,n),exact:(n,e)=>e.href===n,is_not:(n,e)=>e.href!==n};class re{constructor(e){var t=this;this.getWebExperimentsAndEvaluateDisplayLogic=function(r){r===void 0&&(r=!1),t.getWebExperiments(s=>{re.Ir("retrieved web experiments from the server"),t.Cr=new Map,s.forEach(i=>{if(i.feature_flag_key){var o;t.Cr&&(re.Ir("setting flag key ",i.feature_flag_key," to web experiment ",i),(o=t.Cr)==null||o.set(i.feature_flag_key,i));var a=t._instance.getFeatureFlag(i.feature_flag_key);K(a)&&i.variants[a]&&t.Rr(i.name,a,i.variants[a].transforms)}else if(i.variants)for(var l in i.variants){var c=i.variants[l];re.Fr(c)&&t.Rr(i.name,l,c.transforms)}})},r)},this._instance=e,this._instance.onFeatureFlags(r=>{this.onFeatureFlags(r)})}onFeatureFlags(e){if(this._is_bot())re.Ir("Refusing to render web experiment since the viewer is a likely bot");else if(!this._instance.config.disable_web_experiments){if(M(this.Cr))return this.Cr=new Map,this.loadIfEnabled(),void this.previewWebExperiment();re.Ir("applying feature flags",e),e.forEach(t=>{var r;if(this.Cr&&(r=this.Cr)!=null&&r.has(t)){var s,i=this._instance.getFeatureFlag(t),o=(s=this.Cr)==null?void 0:s.get(t);i&&o!=null&&o.variants[i]&&this.Rr(o.name,i,o.variants[i].transforms)}})}}previewWebExperiment(){var e=re.getWindowLocation();if(e!=null&&e.search){var t=tr(e==null?void 0:e.search,"__experiment_id"),r=tr(e==null?void 0:e.search,"__experiment_variant");t&&r&&(re.Ir("previewing web experiments "+t+" && "+r),this.getWebExperiments(s=>{this.Or(parseInt(t),r,s)},!1,!0))}}loadIfEnabled(){this._instance.config.disable_web_experiments||this.getWebExperimentsAndEvaluateDisplayLogic()}getWebExperiments(e,t,r){if(this._instance.config.disable_web_experiments&&!r)return e([]);var s=this._instance.get_property("$web_experiments");if(s&&!t)return e(s);this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/web_experiments/?token="+this._instance.config.token),method:"GET",callback:i=>{if(i.statusCode!==200||!i.json)return e([]);var o=i.json.experiments||[];return e(o)}})}Or(e,t,r){var s=r.filter(i=>i.id===e);s&&s.length>0&&(re.Ir("Previewing web experiment ["+s[0].name+"] with variant ["+t+"]"),this.Rr(s[0].name,t,s[0].variants[t].transforms))}static Fr(e){return!M(e.conditions)&&re.Mr(e)&&re.Ar(e)}static Mr(e){var t;if(M(e.conditions)||M((t=e.conditions)==null?void 0:t.url))return!0;var r,s,i,o=re.getWindowLocation();return!!o&&((r=e.conditions)==null||!r.url||xd[(s=(i=e.conditions)==null?void 0:i.urlMatchType)!==null&&s!==void 0?s:"icontains"](e.conditions.url,o))}static getWindowLocation(){return h==null?void 0:h.location}static Ar(e){var t;if(M(e.conditions)||M((t=e.conditions)==null?void 0:t.utm))return!0;var r=nl();if(r.utm_source){var s,i,o,a,l,c,u,d,p=(s=e.conditions)==null||(s=s.utm)==null||!s.utm_campaign||((i=e.conditions)==null||(i=i.utm)==null?void 0:i.utm_campaign)==r.utm_campaign,f=(o=e.conditions)==null||(o=o.utm)==null||!o.utm_source||((a=e.conditions)==null||(a=a.utm)==null?void 0:a.utm_source)==r.utm_source,m=(l=e.conditions)==null||(l=l.utm)==null||!l.utm_medium||((c=e.conditions)==null||(c=c.utm)==null?void 0:c.utm_medium)==r.utm_medium,v=(u=e.conditions)==null||(u=u.utm)==null||!u.utm_term||((d=e.conditions)==null||(d=d.utm)==null?void 0:d.utm_term)==r.utm_term;return p&&m&&v&&f}return!1}static Ir(e){for(var t=arguments.length,r=new Array(t>1?t-1:0),s=1;s{if(s.selector){var i;re.Ir("applying transform of variant "+t+" for experiment "+e+" ",s);var o=(i=document)==null?void 0:i.querySelectorAll(s.selector);o==null||o.forEach(a=>{var l=a;s.html&&(l.innerHTML=s.html),s.css&&l.setAttribute("style",s.css)})}}):re.Ir("Control variants leave the page unmodified.")}_is_bot(){return fe&&this._instance?_l(fe,this._instance.config.custom_blocked_useragents):void 0}}var Td=z("[PostHog ExternalIntegrations]"),Rd={intercom:"intercom-integration",crispChat:"crisp-chat-integration"};class Ad{constructor(e){this._instance=e}it(e,t){var r;(r=x.__PosthogExtensions__)==null||r.loadExternalDependency==null||r.loadExternalDependency(this._instance,e,s=>{if(s)return Td.error("failed to load script",s);t()})}startIfEnabledOrStop(){var e=this,t=function(o){var a,l,c;!s||(a=x.__PosthogExtensions__)!=null&&(a=a.integrations)!=null&&a[o]||e.it(Rd[o],()=>{var u;(u=x.__PosthogExtensions__)==null||(u=u.integrations)==null||(u=u[o])==null||u.start(e._instance)}),!s&&(l=x.__PosthogExtensions__)!=null&&(l=l.integrations)!=null&&l[o]&&((c=x.__PosthogExtensions__)==null||(c=c.integrations)==null||(c=c[o])==null||c.stop())};for(var[r,s]of Object.entries((i=this._instance.config.integrations)!==null&&i!==void 0?i:{})){var i;t(r)}}}z("[SessionRecording]");var Ps="[SessionRecording]",xt=z(Ps);class Bo{get started(){var e;return!((e=this.jr)==null||!e.isStarted)}get status(){return this.jr?this.jr.status:this.Dr&&!this.Lr?"disabled":"lazy_loading"}constructor(e){if(this._forceAllowLocalhostNetworkCapture=!1,this.Dr=!1,this.Nr=!1,this.Ur=void 0,this._instance=e,!this._instance.sessionManager)throw xt.error("started without valid sessionManager"),new Error(Ps+" started without valid sessionManager. This is a bug.");if(this._instance.config.cookieless_mode==="always")throw new Error(Ps+' cannot be used with cookieless_mode="always"')}get Lr(){var e,t=!((e=this._instance.get_property($n))==null||!e.enabled),r=!this._instance.config.disable_session_recording,s=this._instance.config.disable_session_recording||this._instance.consent.isOptedOut();return h&&t&&r&&!s}startIfEnabledOrStop(e){var t;if(!this.Lr||(t=this.jr)==null||!t.isStarted){var r=!b(Object.assign)&&!b(Array.from);this.Lr&&r?(this.zr(e),xt.info("starting")):this.stopRecording()}}zr(e){var t,r,s;this.Lr&&(x!=null&&(t=x.__PosthogExtensions__)!=null&&(t=t.rrweb)!=null&&t.record&&(r=x.__PosthogExtensions__)!=null&&r.initSessionRecording?this.Hr(e):(s=x.__PosthogExtensions__)==null||s.loadExternalDependency==null||s.loadExternalDependency(this._instance,this.Br,i=>{if(i)return xt.error("could not load recorder",i);this.Hr(e)}))}stopRecording(){var e,t;(e=this.Ur)==null||e.call(this),this.Ur=void 0,(t=this.jr)==null||t.stop()}qr(){var e;(e=this._instance.persistence)==null||e.unregister(La)}Wr(e){if(this._instance.persistence){var t,r,s=this._instance.persistence,i=()=>{var o=e.sessionRecording===!1?void 0:e.sessionRecording,a=o==null?void 0:o.sampleRate,l=M(a)?null:parseFloat(a);M(l)&&this.qr();var c=o==null?void 0:o.minimumDurationMilliseconds;s.register({[$n]:S({cache_timestamp:Date.now(),enabled:!!o},o,{networkPayloadCapture:S({capturePerformance:e.capturePerformance},o==null?void 0:o.networkPayloadCapture),canvasRecording:{enabled:o==null?void 0:o.recordCanvas,fps:o==null?void 0:o.canvasFps,quality:o==null?void 0:o.canvasQuality},sampleRate:l,minimumDurationMilliseconds:b(c)?null:c,endpoint:o==null?void 0:o.endpoint,triggerMatchType:o==null?void 0:o.triggerMatchType,masking:o==null?void 0:o.masking,urlTriggers:o==null?void 0:o.urlTriggers})})};i(),(t=this.Ur)==null||t.call(this),this.Ur=(r=this._instance.sessionManager)==null?void 0:r.onSessionId(i)}}onRemoteConfig(e){"sessionRecording"in e?e.sessionRecording!==!1?(this.Nr=!1,this.Wr(e),this.Dr=!0,this.startIfEnabledOrStop()):this.Dr=!0:xt.info("skipping remote config with no sessionRecording",e)}log(e,t){var r;t===void 0&&(t="log"),(r=this.jr)!=null&&r.log?this.jr.log(e,t):xt.warn("log called before recorder was ready")}get Br(){var e,t,r=(e=this._instance)==null||(e=e.persistence)==null?void 0:e.get_property($n);return(r==null||(t=r.scriptConfig)==null?void 0:t.script)||"lazy-recorder"}Gr(){var e,t=this._instance.get_property($n);if(!t)return!1;var r=(e=(typeof t=="object"?t:JSON.parse(t)).cache_timestamp)!==null&&e!==void 0?e:Date.now();return Date.now()-r<=3e5}Hr(e){var t,r;if((t=x.__PosthogExtensions__)==null||!t.initSessionRecording)throw Error("Called on script loaded before session recording is available");this.jr||(this.jr=(r=x.__PosthogExtensions__)==null?void 0:r.initSessionRecording(this._instance),this.jr._forceAllowLocalhostNetworkCapture=this._forceAllowLocalhostNetworkCapture),this.Gr()?this.jr.start(e):this.Nr||(this.Nr=!0,xt.info("persisted remote config is stale, requesting fresh config before starting"),new vl(this._instance).load())}onRRwebEmit(e){var t;(t=this.jr)==null||t.onRRwebEmit==null||t.onRRwebEmit(e)}overrideLinkedFlag(){var e,t;this.jr||(t=this._instance.persistence)==null||t.register({$replay_override_linked_flag:!0}),(e=this.jr)==null||e.overrideLinkedFlag()}overrideSampling(){var e,t;this.jr||(t=this._instance.persistence)==null||t.register({$replay_override_sampling:!0}),(e=this.jr)==null||e.overrideSampling()}overrideTrigger(e){var t,r;this.jr||(r=this._instance.persistence)==null||r.register({[e==="url"?"$replay_override_url_trigger":"$replay_override_event_trigger"]:!0}),(t=this.jr)==null||t.overrideTrigger(e)}get sdkDebugProperties(){var e;return((e=this.jr)==null?void 0:e.sdkDebugProperties)||{$recording_status:this.status}}tryAddCustomEvent(e,t){var r;return!((r=this.jr)==null||!r.tryAddCustomEvent(e,t))}}var pn={},ss=0,$s=()=>{},Rt="posthog",yl=!Yu&&(ce==null?void 0:ce.indexOf("MSIE"))===-1&&(ce==null?void 0:ce.indexOf("Mozilla"))===-1,jo=n=>{var e;return S({api_host:"https://us.i.posthog.com",flags_api_host:null,ui_host:null,token:"",autocapture:!0,cross_subdomain_cookie:eu(w==null?void 0:w.location),persistence:"localStorage+cookie",persistence_name:"",cookie_persisted_properties:[],loaded:$s,save_campaign_params:!0,custom_campaign_params:[],custom_blocked_useragents:[],save_referrer:!0,capture_pageleave:"if_capture_pageview",defaults:n??"unset",__preview_deferred_init_extensions:!1,debug:ee&&K(ee==null?void 0:ee.search)&&ee.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,disable_external_dependency_loading:!1,enable_recording_console_log:void 0,secure_cookie:(h==null||(e=h.location)==null?void 0:e.protocol)==="https:",ip:!1,opt_out_capturing_by_default:!1,opt_out_persistence_by_default:!1,opt_out_useragent_filter:!1,opt_out_capturing_persistence_type:"localStorage",consent_persistence_name:null,opt_out_capturing_cookie_prefix:null,opt_in_site_apps:!1,property_denylist:[],respect_dnt:!1,sanitize_properties:null,request_headers:{},request_batching:!0,properties_string_max_length:65535,mask_all_element_attributes:!1,mask_all_text:!1,mask_personal_data_properties:!1,custom_personal_data_properties:[],advanced_disable_flags:!1,advanced_disable_decide:!1,advanced_disable_feature_flags:!1,advanced_disable_feature_flags_on_first_load:!1,advanced_only_evaluate_survey_feature_flags:!1,advanced_enable_surveys:!1,advanced_disable_toolbar_metrics:!1,feature_flag_request_timeout_ms:3e3,surveys_request_timeout_ms:1e4,on_request_error:t=>{var r="Bad HTTP status: "+t.statusCode+" "+t.text;E.error(r)},get_device_id:t=>t,capture_performance:void 0,name:"posthog",bootstrap:{},disable_compression:!1,session_idle_timeout_seconds:1800,person_profiles:"identified_only",before_send:void 0,request_queue_config:{flush_interval_ms:As},error_tracking:{},_onCapture:$s,__preview_eager_load_replay:!1},(t=>({rageclick:!(t&&t>="2025-11-30")||{content_ignorelist:!0},capture_pageview:!(t&&t>="2025-05-24")||"history_change",session_recording:t&&t>="2025-11-30"?{strictMinimumDuration:!0}:{},external_scripts_inject_target:t&&t>="2026-01-30"?"head":"body",internal_or_test_user_hostname:t&&t>="2026-01-30"?/^(localhost|127\.0\.0\.1)$/:void 0}))(n))},Uo=n=>{var e={};b(n.process_person)||(e.person_profiles=n.process_person),b(n.xhr_headers)||(e.request_headers=n.xhr_headers),b(n.cookie_name)||(e.persistence_name=n.cookie_name),b(n.disable_cookie)||(e.disable_persistence=n.disable_cookie),b(n.store_google)||(e.save_campaign_params=n.store_google),b(n.verbose)||(e.debug=n.verbose);var t=G({},e,n);return L(n.property_blacklist)&&(b(n.property_denylist)?t.property_denylist=n.property_blacklist:L(n.property_denylist)?t.property_denylist=[...n.property_blacklist,...n.property_denylist]:E.error("Invalid value for property_denylist config: "+n.property_denylist)),t};class Pd{constructor(){this.__forceAllowLocalhost=!1}get Vr(){return this.__forceAllowLocalhost}set Vr(e){E.error("WebPerformanceObserver is deprecated and has no impact on network capture. Use `_forceAllowLocalhostNetworkCapture` on `posthog.sessionRecording`"),this.__forceAllowLocalhost=e}}class yn{get decideEndpointWasHit(){var e,t;return(e=(t=this.featureFlags)==null?void 0:t.hasLoadedFlags)!==null&&e!==void 0&&e}get flagsEndpointWasHit(){var e,t;return(e=(t=this.featureFlags)==null?void 0:t.hasLoadedFlags)!==null&&e!==void 0&&e}constructor(){this.webPerformance=new Pd,this.Jr=!1,this.version=Be.LIB_VERSION,this.mi=new ai,this._calculate_event_properties=this.calculateEventProperties.bind(this),this.config=jo(),this.SentryIntegration=Ru,this.sentryIntegration=e=>function(t,r){var s=tl(t,r);return{name:el,processEvent:i=>s(i)}}(this,e),this.__request_queue=[],this.__loaded=!1,this.analyticsDefaultEndpoint="/e/",this.Kr=!1,this.Yr=null,this.Xr=null,this.Qr=null,this.featureFlags=new od(this),this.toolbar=new Pu(this),this.scrollManager=new Ed(this),this.pageViewManager=new Eo(this),this.surveys=new gd(this),this.conversations=new md(this),this.logs=new vd(this),this.experiments=new re(this),this.exceptions=new Ju(this),this.rateLimiter=new _d(this),this.requestRouter=new Cd(this),this.consent=new Su(this),this.externalIntegrations=new Ad(this),this.people={set:(e,t,r)=>{var s=K(e)?{[e]:t}:e;this.setPersonProperties(s),r==null||r({})},set_once:(e,t,r)=>{var s=K(e)?{[e]:t}:e;this.setPersonProperties(void 0,s),r==null||r({})}},this.on("eventCaptured",e=>E.info('send "'+(e==null?void 0:e.event)+'"',e))}init(e,t,r){if(r&&r!==Rt){var s,i=(s=pn[r])!==null&&s!==void 0?s:new yn;return i._init(e,t,r),pn[r]=i,pn[Rt][r]=i,i}return this._init(e,t,r)}_init(e,t,r){var s;if(t===void 0&&(t={}),b(e)||us(e))return E.critical("PostHog was initialized without a token. This likely indicates a misconfiguration. Please check the first argument passed to posthog.init()"),this;if(this.__loaded)return console.warn("[PostHog.js]","You have already initialized PostHog! Re-initializing is a no-op"),this;this.__loaded=!0,this.config={},t.debug=this.Zr(t.debug),this.ts=t,this.es=[],t.person_profiles?this.Xr=t.person_profiles:t.process_person&&(this.Xr=t.process_person),this.set_config(G({},jo(t.defaults),Uo(t),{name:r,token:e})),this.config.on_xhr_error&&E.error("on_xhr_error is deprecated. Use on_request_error instead"),this.compression=t.disable_compression?void 0:He.GZipJS;var i=this.rs();this.persistence=new Qr(this.config,i),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new Qr(S({},this.config,{persistence:"sessionStorage"}),i);var o=S({},this.persistence.props),a=S({},this.sessionPersistence.props);this.register({$initialization_time:new Date().toISOString()}),this.ss=new yd(k=>this.ns(k),this.config.request_queue_config),this.os=new bd(this),this.__request_queue=[];var l=this.config.cookieless_mode==="always"||this.config.cookieless_mode==="on_reject"&&this.consent.isExplicitlyOptedOut();if(l||(this.sessionManager=new Lo(this),this.sessionPropsManager=new No(this,this.sessionManager,this.persistence)),this.config.__preview_deferred_init_extensions?(E.info("Deferring extension initialization to improve startup performance"),setTimeout(()=>{this.ls(l)},0)):(E.info("Initializing extensions synchronously"),this.ls(l)),Be.DEBUG=Be.DEBUG||this.config.debug,Be.DEBUG&&E.info("Starting in debug mode",{this:this,config:t,thisC:S({},this.config),p:o,s:a}),((s=t.bootstrap)==null?void 0:s.distinctID)!==void 0){var c,u,d=this.config.get_device_id(it()),p=(c=t.bootstrap)!=null&&c.isIdentifiedID?d:t.bootstrap.distinctID;this.persistence.set_property(Ae,(u=t.bootstrap)!=null&&u.isIdentifiedID?"identified":"anonymous"),this.register({distinct_id:t.bootstrap.distinctID,$device_id:p})}if(this.us()){var f,m,v=Object.keys(((f=t.bootstrap)==null?void 0:f.featureFlags)||{}).filter(k=>{var T;return!((T=t.bootstrap)==null||(T=T.featureFlags)==null||!T[k])}).reduce((k,T)=>{var I;return k[T]=((I=t.bootstrap)==null||(I=I.featureFlags)==null?void 0:I[T])||!1,k},{}),_=Object.keys(((m=t.bootstrap)==null?void 0:m.featureFlagPayloads)||{}).filter(k=>v[k]).reduce((k,T)=>{var I,y;return(I=t.bootstrap)!=null&&(I=I.featureFlagPayloads)!=null&&I[T]&&(k[T]=(y=t.bootstrap)==null||(y=y.featureFlagPayloads)==null?void 0:y[T]),k},{});this.featureFlags.receivedFeatureFlags({featureFlags:v,featureFlagPayloads:_})}if(l)this.register_once({distinct_id:qt,$device_id:null},"");else if(!this.get_distinct_id()){var C=this.config.get_device_id(it());this.register_once({distinct_id:C,$device_id:C},""),this.persistence.set_property(Ae,"anonymous")}return Y(h,"onpagehide"in self?"pagehide":"unload",this._handle_unload.bind(this),{passive:!1}),this.toolbar.maybeLoadToolbar(),t.segment?Tu(this,()=>this.hs()):this.hs(),ze(this.config._onCapture)&&this.config._onCapture!==$s&&(E.warn("onCapture is deprecated. Please use `before_send` instead"),this.on("eventCaptured",k=>this.config._onCapture(k.event,k))),this.config.ip&&E.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}ls(e){var t=performance.now();this.historyAutocapture=new xu(this),this.historyAutocapture.startIfEnabled();var r=[];r.push(()=>{new Fu(this).startIfEnabledOrStop()}),r.push(()=>{var s;this.siteApps=new Id(this),(s=this.siteApps)==null||s.init()}),e||r.push(()=>{this.sessionRecording=new Bo(this),this.sessionRecording.startIfEnabledOrStop()}),this.config.disable_scroll_properties||r.push(()=>{this.scrollManager.startMeasuringScrollPosition()}),r.push(()=>{this.autocapture=new gu(this),this.autocapture.startIfEnabled()}),r.push(()=>{this.surveys.loadIfEnabled()}),r.push(()=>{this.logs.loadIfEnabled()}),r.push(()=>{this.conversations.loadIfEnabled()}),r.push(()=>{this.productTours=new ld(this),this.productTours.loadIfEnabled()}),r.push(()=>{this.heatmaps=new ju(this),this.heatmaps.startIfEnabled()}),r.push(()=>{this.webVitalsAutocapture=new Du(this)}),r.push(()=>{this.exceptionObserver=new Cu(this),this.exceptionObserver.startIfEnabledOrStop()}),r.push(()=>{this.deadClicksAutocapture=new Qa(this,Iu),this.deadClicksAutocapture.startIfEnabledOrStop()}),r.push(()=>{if(this.ds){var s=this.ds;this.ds=void 0,this.Ce(s)}}),this.vs(r,t)}vs(e,t){for(;e.length>0;){if(this.config.__preview_deferred_init_extensions&&performance.now()-t>=30&&e.length>0)return void setTimeout(()=>{this.vs(e,t)},0);var r=e.shift();if(r)try{r()}catch(i){E.error("Error initializing extension:",i)}}var s=Math.round(performance.now()-t);this.register_for_session({$sdk_debug_extensions_init_method:this.config.__preview_deferred_init_extensions?"deferred":"synchronous",$sdk_debug_extensions_init_time_ms:s}),this.config.__preview_deferred_init_extensions&&E.info("PostHog extensions initialized ("+s+"ms)")}Ce(e){var t,r,s,i,o,a,l,c,u;if(!w||!w.body)return E.info("document not ready yet, trying again in 500 milliseconds..."),void setTimeout(()=>{this.Ce(e)},500);this.config.__preview_deferred_init_extensions&&(this.ds=e),this.compression=void 0,e.supportedCompression&&!this.config.disable_compression&&(this.compression=F(e.supportedCompression,He.GZipJS)?He.GZipJS:F(e.supportedCompression,He.Base64)?He.Base64:void 0),(t=e.analytics)!=null&&t.endpoint&&(this.analyticsDefaultEndpoint=e.analytics.endpoint),this.set_config({person_profiles:this.Xr?this.Xr:"identified_only"}),(r=this.siteApps)==null||r.onRemoteConfig(e),(s=this.sessionRecording)==null||s.onRemoteConfig(e),(i=this.autocapture)==null||i.onRemoteConfig(e),(o=this.heatmaps)==null||o.onRemoteConfig(e),this.surveys.onRemoteConfig(e),this.logs.onRemoteConfig(e),this.conversations.onRemoteConfig(e),(a=this.productTours)==null||a.onRemoteConfig(e),(l=this.webVitalsAutocapture)==null||l.onRemoteConfig(e),(c=this.exceptionObserver)==null||c.onRemoteConfig(e),this.exceptions.onRemoteConfig(e),(u=this.deadClicksAutocapture)==null||u.onRemoteConfig(e)}hs(){try{this.config.loaded(this)}catch(r){E.critical("`loaded` function failed",r)}if(this.cs(),this.config.internal_or_test_user_hostname&&ee!=null&&ee.hostname){var e=ee.hostname,t=this.config.internal_or_test_user_hostname;(typeof t=="string"?e===t:t.test(e))&&this.setInternalOrTestUser()}this.config.capture_pageview&&setTimeout(()=>{(this.consent.isOptedIn()||this.config.cookieless_mode==="always")&&this.fs()},1),this.ps=new vl(this),this.ps.load()}cs(){var e;this.is_capturing()&&this.config.request_batching&&((e=this.ss)==null||e.enable())}_dom_loaded(){this.is_capturing()&&ot(this.__request_queue,e=>this.ns(e)),this.__request_queue=[],this.cs()}_handle_unload(){var e,t;this.surveys.handlePageUnload(),this.config.request_batching?(this._s()&&this.capture("$pageleave"),(e=this.ss)==null||e.unload(),(t=this.os)==null||t.unload()):this._s()&&this.capture("$pageleave",null,{transport:"sendBeacon"})}_send_request(e){this.__loaded&&(yl?this.__request_queue.push(e):this.rateLimiter.isServerRateLimited(e.batchKey)||(e.transport=e.transport||this.config.api_transport,e.url=ir(e.url,{ip:this.config.ip?1:0}),e.headers=S({},this.config.request_headers,e.headers),e.compression=e.compression==="best-available"?this.compression:e.compression,e.disableXHRCredentials=this.config.__preview_disable_xhr_credentials,this.config.__preview_disable_beacon&&(e.disableTransport=["sendBeacon"]),e.fetchOptions=e.fetchOptions||this.config.fetch_options,(t=>{var r,s,i,o=S({},t);o.timeout=o.timeout||6e4,o.url=ir(o.url,{_:new Date().getTime().toString(),ver:Be.LIB_VERSION,compression:o.compression});var a=(r=o.transport)!==null&&r!==void 0?r:"fetch",l=Bn.filter(u=>!o.disableTransport||!u.transport||!o.disableTransport.includes(u.transport)),c=(s=(i=Fa(l,u=>u.transport===a))==null?void 0:i.method)!==null&&s!==void 0?s:l[0].method;if(!c)throw new Error("No available transport method");c(o)})(S({},e,{callback:t=>{var r,s;this.rateLimiter.checkForLimiting(t),t.statusCode>=400&&((r=(s=this.config).on_request_error)==null||r.call(s,t)),e.callback==null||e.callback(t)}}))))}ns(e){this.os?this.os.retriableRequest(e):this._send_request(e)}_execute_array(e){ss++;try{var t,r=[],s=[],i=[];ot(e,a=>{a&&(t=a[0],L(t)?i.push(a):ze(a)?a.call(this):L(a)&&t==="alias"?r.push(a):L(a)&&t.indexOf("capture")!==-1&&ze(this[t])?i.push(a):s.push(a))});var o=function(a,l){ot(a,function(c){if(L(c[0])){var u=l;U(c,function(d){u=u[d[0]].apply(u,d.slice(1))})}else this[c[0]].apply(this,c.slice(1))},l)};o(r,this),o(s,this),o(i,this)}finally{ss--}}us(){var e,t;return((e=this.config.bootstrap)==null?void 0:e.featureFlags)&&Object.keys((t=this.config.bootstrap)==null?void 0:t.featureFlags).length>0||!1}push(e){if(ss>0&&L(e)&&K(e[0])){var t=yn.prototype[e[0]];ze(t)&&t.apply(this,e.slice(1))}else this._execute_array([e])}capture(e,t,r){var s;if(this.__loaded&&this.persistence&&this.sessionPersistence&&this.ss){if(this.is_capturing())if(!b(e)&&K(e)){var i=!this.config.opt_out_useragent_filter&&this._is_bot();if(!(i&&!this.config.__preview_capture_bot_pageviews)){var o=r!=null&&r.skip_client_rate_limiting?void 0:this.rateLimiter.clientRateLimitContext();if(o==null||!o.isRateLimited){t!=null&&t.$current_url&&!K(t==null?void 0:t.$current_url)&&(E.error("Invalid `$current_url` property provided to `posthog.capture`. Input must be a string. Ignoring provided value."),t==null||delete t.$current_url),e!=="$exception"||r!=null&&r.oi||E.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 a=new Date,l=(r==null?void 0:r.timestamp)||a,c=it(),u={uuid:c,event:e,properties:this.calculateEventProperties(e,t||{},l,c)};e==="$pageview"&&this.config.__preview_capture_bot_pageviews&&i&&(u.event="$bot_pageview",u.properties.$browser_type="bot"),o&&(u.properties.$lib_rate_limit_remaining_tokens=o.remainingTokens),r!=null&&r.$set&&(u.$set=r==null?void 0:r.$set);var d,p=e!=="$groupidentify",f=this.gs(r==null?void 0:r.$set_once,p);if(f&&(u.$set_once=f),(u=Xc(u,r!=null&&r._noTruncate?null:this.config.properties_string_max_length)).timestamp=l,b(r==null?void 0:r.timestamp)||(u.properties.$event_time_override_provided=!0,u.properties.$event_time_override_system_time=a),e===cn.DISMISSED||e===cn.SENT){var m=t==null?void 0:t[ns.SURVEY_ID],v=t==null?void 0:t[ns.SURVEY_ITERATION];d={id:m,current_iteration:v},localStorage.getItem(Mo(d))||localStorage.setItem(Mo(d),"true"),u.$set=S({},u.$set,{[cd({id:m,current_iteration:v},e===cn.SENT?"responded":"dismissed")]:!0})}else e===cn.SHOWN&&(u.$set=S({},u.$set,{[ns.SURVEY_LAST_SEEN_DATE]:new Date().toISOString()}));var _=S({},u.properties.$set,u.$set);if(Pt(_)||this.setPersonPropertiesForFlags(_),!M(this.config.before_send)){var C=this.bs(u);if(!C)return;u=C}this.mi.emit("eventCaptured",u);var k={method:"POST",url:(s=r==null?void 0:r._url)!==null&&s!==void 0?s:this.requestRouter.endpointFor("api",this.analyticsDefaultEndpoint),data:u,compression:"best-available",batchKey:r==null?void 0:r._batchKey};return!this.config.request_batching||r&&(r==null||!r._batchKey)||r!=null&&r.send_instantly?this.ns(k):this.ss.enqueue(k),u}E.critical("This capture call is ignored due to client rate limiting.")}}else E.error("No event name provided to posthog.capture")}else E.uninitializedWarning("posthog.capture")}_addCaptureHook(e){return this.on("eventCaptured",t=>e(t.event,t))}calculateEventProperties(e,t,r,s,i){if(r=r||new Date,!this.persistence||!this.sessionPersistence)return t;var o=i?void 0:this.persistence.remove_event_timer(e),a=S({},t);if(a.token=this.config.token,a.$config_defaults=this.config.defaults,(this.config.cookieless_mode=="always"||this.config.cookieless_mode=="on_reject"&&this.consent.isExplicitlyOptedOut())&&(a.$cookieless_mode=!0),e==="$snapshot"){var l=S({},this.persistence.properties(),this.sessionPersistence.properties());return a.distinct_id=l.distinct_id,(!K(a.distinct_id)&&!Ze(a.distinct_id)||us(a.distinct_id))&&E.error("Invalid distinct_id for replay event. This indicates a bug in your implementation"),a}var c,u=Lu(this.config.mask_personal_data_properties,this.config.custom_personal_data_properties);if(this.sessionManager){var{sessionId:d,windowId:p}=this.sessionManager.checkAndGetSessionAndWindowId(i,r.getTime());a.$session_id=d,a.$window_id=p}this.sessionPropsManager&&G(a,this.sessionPropsManager.getSessionProps());try{var f;this.sessionRecording&&G(a,this.sessionRecording.sdkDebugProperties),a.$sdk_debug_retry_queue_size=(f=this.os)==null?void 0:f.length}catch(C){a.$sdk_debug_error_capturing_properties=String(C)}if(this.requestRouter.region===un.CUSTOM&&(a.$lib_custom_api_host=this.config.api_host),c=e!=="$pageview"||i?e!=="$pageleave"||i?this.pageViewManager.doEvent():this.pageViewManager.doPageLeave(r):this.pageViewManager.doPageView(r,s),a=G(a,c),e==="$pageview"&&w&&(a.title=w.title),!b(o)){var m=r.getTime()-o;a.$duration=parseFloat((m/1e3).toFixed(3))}ce&&this.config.opt_out_useragent_filter&&(a.$browser_type=this._is_bot()?"bot":"browser"),(a=G({},u,this.persistence.properties(),this.sessionPersistence.properties(),a)).$is_identified=this._isIdentified(),L(this.config.property_denylist)?U(this.config.property_denylist,function(C){delete a[C]}):E.error("Invalid value for property_denylist config: "+this.config.property_denylist+" or property_blacklist config: "+this.config.property_blacklist);var v=this.config.sanitize_properties;v&&(E.error("sanitize_properties is deprecated. Use before_send instead"),a=v(a,e));var _=this.ys();return a.$process_person_profile=_,_&&!i&&this.ws("_calculate_event_properties"),a}gs(e,t){var r;if(t===void 0&&(t=!0),!this.persistence||!this.ys()||this.Jr)return e;var s=this.persistence.get_initial_props(),i=(r=this.sessionPropsManager)==null?void 0:r.getSetOnceProps(),o=G({},s,i||{},e||{}),a=this.config.sanitize_properties;return a&&(E.error("sanitize_properties is deprecated. Use before_send instead"),o=a(o,"$set_once")),t&&(this.Jr=!0),Pt(o)?void 0:o}register(e,t){var r;(r=this.persistence)==null||r.register(e,t)}register_once(e,t,r){var s;(s=this.persistence)==null||s.register_once(e,t,r)}register_for_session(e){var t;(t=this.sessionPersistence)==null||t.register(e)}unregister(e){var t;(t=this.persistence)==null||t.unregister(e)}unregister_for_session(e){var t;(t=this.sessionPersistence)==null||t.unregister(e)}xs(e,t){this.register({[e]:t})}getFeatureFlag(e,t){return this.featureFlags.getFeatureFlag(e,t)}getFeatureFlagPayload(e){return this.featureFlags.getFeatureFlagPayload(e)}getFeatureFlagResult(e,t){return this.featureFlags.getFeatureFlagResult(e,t)}isFeatureEnabled(e,t){return this.featureFlags.isFeatureEnabled(e,t)}reloadFeatureFlags(){this.featureFlags.reloadFeatureFlags()}updateFlags(e,t,r){var s=r!=null&&r.merge?this.featureFlags.getFlagVariants():{},i=r!=null&&r.merge?this.featureFlags.getFlagPayloads():{},o=S({},s,e),a=S({},i,t),l={};for(var[c,u]of Object.entries(o)){var d=typeof u=="string";l[c]={key:c,enabled:!!d||!!u,variant:d?u:void 0,reason:void 0,metadata:b(a==null?void 0:a[c])?void 0:{id:0,version:void 0,description:void 0,payload:a[c]}}}this.featureFlags.receivedFeatureFlags({flags:l})}updateEarlyAccessFeatureEnrollment(e,t,r){this.featureFlags.updateEarlyAccessFeatureEnrollment(e,t,r)}getEarlyAccessFeatures(e,t,r){return t===void 0&&(t=!1),this.featureFlags.getEarlyAccessFeatures(e,t,r)}on(e,t){return this.mi.on(e,t)}onFeatureFlags(e){return this.featureFlags.onFeatureFlags(e)}onSurveysLoaded(e){return this.surveys.onSurveysLoaded(e)}onSessionId(e){var t,r;return(t=(r=this.sessionManager)==null?void 0:r.onSessionId(e))!==null&&t!==void 0?t:()=>{}}getSurveys(e,t){t===void 0&&(t=!1),this.surveys.getSurveys(e,t)}getActiveMatchingSurveys(e,t){t===void 0&&(t=!1),this.surveys.getActiveMatchingSurveys(e,t)}renderSurvey(e,t){this.surveys.renderSurvey(e,t)}displaySurvey(e,t){t===void 0&&(t=dd),this.surveys.displaySurvey(e,t)}cancelPendingSurvey(e){this.surveys.cancelPendingSurvey(e)}canRenderSurvey(e){return this.surveys.canRenderSurvey(e)}canRenderSurveyAsync(e,t){return t===void 0&&(t=!1),this.surveys.canRenderSurveyAsync(e,t)}identify(e,t,r){if(!this.__loaded||!this.persistence)return E.uninitializedWarning("posthog.identify");if(Ze(e)&&(e=e.toString(),E.warn("The first argument to posthog.identify was a number, but it should be a string. It has been converted to a string.")),e)if(["distinct_id","distinctid"].includes(e.toLowerCase()))E.critical('The string "'+e+'" was set in posthog.identify which indicates an error. This ID should be unique to the user and not a hardcoded string.');else if(e!==qt){if(this.ws("posthog.identify")){var s=this.get_distinct_id();if(this.register({$user_id:e}),!this.get_property("$device_id")){var i=s;this.register_once({$had_persisted_distinct_id:!0,$device_id:i},"")}e!==s&&e!==this.get_property(rn)&&(this.unregister(rn),this.register({distinct_id:e}));var o=(this.persistence.get_property(Ae)||"anonymous")==="anonymous";e!==s&&o?(this.persistence.set_property(Ae,"identified"),this.setPersonPropertiesForFlags(S({},r||{},t||{}),!1),this.capture("$identify",{distinct_id:e,$anon_distinct_id:s},{$set:t||{},$set_once:r||{}}),this.Qr=To(e,t,r),this.featureFlags.setAnonymousDistinctId(s)):(t||r)&&this.setPersonProperties(t,r),e!==s&&(this.reloadFeatureFlags(),this.unregister(Jn))}}else E.critical('The string "'+qt+'" was set in posthog.identify which indicates an error. This ID is only used as a sentinel value.');else E.error("Unique user id has not been set in posthog.identify")}setPersonProperties(e,t){if((e||t)&&this.ws("posthog.setPersonProperties")){var r=To(this.get_distinct_id(),e,t);this.Qr!==r?(this.setPersonPropertiesForFlags(S({},t||{},e||{})),this.capture("$set",{$set:e||{},$set_once:t||{}}),this.Qr=r):E.info("A duplicate setPersonProperties call was made with the same properties. It has been ignored.")}}group(e,t,r){if(e&&t){var s=this.getGroups();s[e]!==t&&this.resetGroupPropertiesForFlags(e),this.register({$groups:S({},s,{[e]:t})}),r&&(this.capture("$groupidentify",{$group_type:e,$group_key:t,$group_set:r}),this.setGroupPropertiesForFlags({[e]:r})),s[e]===t||r||this.reloadFeatureFlags()}else E.error("posthog.group requires a group type and group key")}resetGroups(){this.register({$groups:{}}),this.resetGroupPropertiesForFlags(),this.reloadFeatureFlags()}setPersonPropertiesForFlags(e,t){t===void 0&&(t=!0),this.featureFlags.setPersonPropertiesForFlags(e,t)}resetPersonPropertiesForFlags(){this.featureFlags.resetPersonPropertiesForFlags()}setGroupPropertiesForFlags(e,t){t===void 0&&(t=!0),this.ws("posthog.setGroupPropertiesForFlags")&&this.featureFlags.setGroupPropertiesForFlags(e,t)}resetGroupPropertiesForFlags(e){this.featureFlags.resetGroupPropertiesForFlags(e)}reset(e){var t,r,s,i,o;if(E.info("reset"),!this.__loaded)return E.uninitializedWarning("posthog.reset");var a=this.get_property("$device_id");if(this.consent.reset(),(t=this.persistence)==null||t.clear(),(r=this.sessionPersistence)==null||r.clear(),this.surveys.reset(),(s=this.ps)==null||s.stop(),this.featureFlags.reset(),(i=this.persistence)==null||i.set_property(Ae,"anonymous"),(o=this.sessionManager)==null||o.resetSessionId(),this.Qr=null,this.config.cookieless_mode==="always")this.register_once({distinct_id:qt,$device_id:null},"");else{var l=this.config.get_device_id(it());this.register_once({distinct_id:l,$device_id:e?l:a},"")}this.register({$last_posthog_reset:new Date().toISOString()},1)}get_distinct_id(){return this.get_property("distinct_id")}getGroups(){return this.get_property("$groups")||{}}get_session_id(){var e,t;return(e=(t=this.sessionManager)==null?void 0:t.checkAndGetSessionAndWindowId(!0).sessionId)!==null&&e!==void 0?e:""}get_session_replay_url(e){if(!this.sessionManager)return"";var{sessionId:t,sessionStartTimestamp:r}=this.sessionManager.checkAndGetSessionAndWindowId(!0),s=this.requestRouter.endpointFor("ui","/project/"+this.config.token+"/replay/"+t);if(e!=null&&e.withTimestamp&&r){var i,o=(i=e.timestampLookBack)!==null&&i!==void 0?i:10;if(!r)return s;s+="?t="+Math.max(Math.floor((new Date().getTime()-r)/1e3)-o,0)}return s}alias(e,t){return e===this.get_property(Oa)?(E.critical("Attempting to create alias for existing People user - aborting."),-2):this.ws("posthog.alias")?(b(t)&&(t=this.get_distinct_id()),e!==t?(this.xs(rn,e),this.capture("$create_alias",{alias:e,distinct_id:t})):(E.warn("alias matches current distinct_id - skipping api call."),this.identify(e),-1)):void 0}set_config(e){var t=S({},this.config);if(Z(e)){var r,s,i,o,a,l,c,u;G(this.config,Uo(e));var d=this.rs();(r=this.persistence)==null||r.update_config(this.config,t,d),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new Qr(S({},this.config,{persistence:"sessionStorage"}),d);var p=this.Zr(this.config.debug);qe(p)&&(this.config.debug=p),qe(this.config.debug)&&(this.config.debug?(Be.DEBUG=!0,W.H()&&W.G("ph_debug","true"),E.info("set_config",{config:e,oldConfig:t,newConfig:S({},this.config)})):(Be.DEBUG=!1,W.H()&&W.V("ph_debug"))),(s=this.exceptionObserver)==null||s.onConfigChange(),(i=this.sessionRecording)==null||i.startIfEnabledOrStop(),(o=this.autocapture)==null||o.startIfEnabled(),(a=this.heatmaps)==null||a.startIfEnabled(),(l=this.exceptionObserver)==null||l.startIfEnabledOrStop(),(c=this.deadClicksAutocapture)==null||c.startIfEnabledOrStop(),this.surveys.loadIfEnabled(),this.$s(),(u=this.externalIntegrations)==null||u.startIfEnabledOrStop()}}startSessionRecording(e){var t=e===!0,r={sampling:t||!(e==null||!e.sampling),linked_flag:t||!(e==null||!e.linked_flag),url_trigger:t||!(e==null||!e.url_trigger),event_trigger:t||!(e==null||!e.event_trigger)};if(Object.values(r).some(Boolean)){var s,i,o,a,l;(s=this.sessionManager)==null||s.checkAndGetSessionAndWindowId(),r.sampling&&((i=this.sessionRecording)==null||i.overrideSampling()),r.linked_flag&&((o=this.sessionRecording)==null||o.overrideLinkedFlag()),r.url_trigger&&((a=this.sessionRecording)==null||a.overrideTrigger("url")),r.event_trigger&&((l=this.sessionRecording)==null||l.overrideTrigger("event"))}this.set_config({disable_session_recording:!1})}stopSessionRecording(){this.set_config({disable_session_recording:!0})}sessionRecordingStarted(){var e;return!((e=this.sessionRecording)==null||!e.started)}captureException(e,t){var r=new Error("PostHog syntheticException"),s=this.exceptions.buildProperties(e,{handled:!0,syntheticException:r});return this.exceptions.sendExceptionEvent(S({},s,t))}startExceptionAutocapture(e){this.set_config({capture_exceptions:e==null||e})}stopExceptionAutocapture(){this.set_config({capture_exceptions:!1})}loadToolbar(e){return this.toolbar.loadToolbar(e)}get_property(e){var t;return(t=this.persistence)==null?void 0:t.props[e]}getSessionProperty(e){var t;return(t=this.sessionPersistence)==null?void 0:t.props[e]}toString(){var e,t=(e=this.config.name)!==null&&e!==void 0?e:Rt;return t!==Rt&&(t=Rt+"."+t),t}_isIdentified(){var e,t;return((e=this.persistence)==null?void 0:e.get_property(Ae))==="identified"||((t=this.sessionPersistence)==null?void 0:t.get_property(Ae))==="identified"}ys(){var e,t;return!(this.config.person_profiles==="never"||this.config.person_profiles==="identified_only"&&!this._isIdentified()&&Pt(this.getGroups())&&((e=this.persistence)==null||(e=e.props)==null||!e[rn])&&((t=this.persistence)==null||(t=t.props)==null||!t[Xn]))}_s(){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.ys()||this.ws("posthog.createPersonProfile")&&this.setPersonProperties({},{})}setInternalOrTestUser(){this.ws("posthog.setInternalOrTestUser")&&this.setPersonProperties({$internal_or_test_user:!0})}ws(e){return this.config.person_profiles==="never"?(E.error(e+' was called, but process_person is set to "never". This call will be ignored.'),!1):(this.xs(Xn,!0),!0)}rs(){if(this.config.cookieless_mode==="always")return!0;var e=this.consent.isOptedOut(),t=this.config.opt_out_persistence_by_default||this.config.cookieless_mode==="on_reject";return this.config.disable_persistence||e&&!!t}$s(){var e,t,r,s,i=this.rs();return((e=this.persistence)==null?void 0:e.ki)!==i&&((r=this.persistence)==null||r.set_disabled(i)),((t=this.sessionPersistence)==null?void 0:t.ki)!==i&&((s=this.sessionPersistence)==null||s.set_disabled(i)),i}opt_in_capturing(e){var t;if(this.config.cookieless_mode!=="always"){var r,s,i;this.config.cookieless_mode==="on_reject"&&this.consent.isExplicitlyOptedOut()&&(this.reset(!0),(r=this.sessionManager)==null||r.destroy(),(s=this.pageViewManager)==null||s.destroy(),this.sessionManager=new Lo(this),this.pageViewManager=new Eo(this),this.persistence&&(this.sessionPropsManager=new No(this,this.sessionManager,this.persistence)),this.sessionRecording=new Bo(this),this.sessionRecording.startIfEnabledOrStop()),this.consent.optInOut(!0),this.$s(),this.cs(),(t=this.sessionRecording)==null||t.startIfEnabledOrStop(),this.config.cookieless_mode=="on_reject"&&this.surveys.loadIfEnabled(),(b(e==null?void 0:e.captureEventName)||e!=null&&e.captureEventName)&&this.capture((i=e==null?void 0:e.captureEventName)!==null&&i!==void 0?i:"$opt_in",e==null?void 0:e.captureProperties,{send_instantly:!0}),this.config.capture_pageview&&this.fs()}else E.warn('Consent opt in/out is not valid with cookieless_mode="always" and will be ignored')}opt_out_capturing(){var e,t,r;this.config.cookieless_mode!=="always"?(this.config.cookieless_mode==="on_reject"&&this.consent.isOptedIn()&&this.reset(!0),this.consent.optInOut(!1),this.$s(),this.config.cookieless_mode==="on_reject"&&(this.register({distinct_id:qt,$device_id:null}),(e=this.sessionManager)==null||e.destroy(),(t=this.pageViewManager)==null||t.destroy(),this.sessionManager=void 0,this.sessionPropsManager=void 0,(r=this.sessionRecording)==null||r.stopRecording(),this.sessionRecording=void 0,this.fs())):E.warn('Consent opt in/out is not valid with cookieless_mode="always" and will be ignored')}has_opted_in_capturing(){return this.consent.isOptedIn()}has_opted_out_capturing(){return this.consent.isOptedOut()}get_explicit_consent_status(){var e=this.consent.consent;return e===Ue.GRANTED?"granted":e===Ue.DENIED?"denied":"pending"}is_capturing(){return this.config.cookieless_mode==="always"||(this.config.cookieless_mode==="on_reject"?this.consent.isExplicitlyOptedOut()||this.consent.isOptedIn():!this.has_opted_out_capturing())}clear_opt_in_out_capturing(){this.consent.reset(),this.$s()}_is_bot(){return fe?_l(fe,this.config.custom_blocked_useragents):void 0}fs(){w&&(w.visibilityState==="visible"?this.Kr||(this.Kr=!0,this.capture("$pageview",{title:w.title},{send_instantly:!0}),this.Yr&&(w.removeEventListener("visibilitychange",this.Yr),this.Yr=null)):this.Yr||(this.Yr=this.fs.bind(this),Y(w,"visibilitychange",this.Yr)))}debug(e){e===!1?(h==null||h.console.log("You've disabled debug mode."),this.set_config({debug:!1})):(h==null||h.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}))}M(){var e,t,r,s,i,o,a,l=this.ts||{};return"advanced_disable_flags"in l?!!l.advanced_disable_flags:this.config.advanced_disable_flags!==!1?!!this.config.advanced_disable_flags:this.config.advanced_disable_decide===!0?(E.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):(r="advanced_disable_decide",s=!1,i=E,o=(t="advanced_disable_flags")in(e=l)&&!M(e[t]),a=r in e&&!M(e[r]),o?e[t]:a?(i&&i.warn("Config field '"+r+"' is deprecated. Please use '"+t+"' instead. The old field will be removed in a future major version."),e[r]):s)}bs(e){if(M(this.config.before_send))return e;var t=L(this.config.before_send)?this.config.before_send:[this.config.before_send],r=e;for(var s of t){if(r=s(r),M(r)){var i="Event '"+e.event+"' was rejected in beforeSend function";return gc(e.event)?E.warn(i+". This can cause unexpected behavior."):E.info(i),null}r.properties&&!Pt(r.properties)||E.warn("Event '"+e.event+"' has no properties after beforeSend function, this is likely an error.")}return r}getPageViewId(){var e;return(e=this.pageViewManager.Kt)==null?void 0:e.pageViewId}captureTraceFeedback(e,t){this.capture("$ai_feedback",{$ai_trace_id:String(e),$ai_feedback_text:t})}captureTraceMetric(e,t,r){this.capture("$ai_metric",{$ai_trace_id:String(e),$ai_metric_name:t,$ai_metric_value:String(r)})}Zr(e){var t=qe(e)&&!e,r=W.H()&&W.q("ph_debug")==="true";return!t&&(!!r||e)}}(function(n,e){for(var t=0;t{if(typeof e=="string")return{name:e,version:null,inferred:!1};const t=lt(e),r=t.name||t.package;return r?{name:r,version:t.version||null,inferred:!!t.inferred,...t.reason?{reason:t.reason}:{}}:null}).filter(Boolean):Object.entries(lt(n)).map(([e,t])=>({name:e,version:t||null,inferred:!1})):[]}function Il(n){return n?(Array.isArray(n)?n:[n]).map(e=>{const t=lt(e);return!t.from&&!t.to?null:{from:t.from||null,to:t.to||null,type:t.type||"uses",description:t.description||""}}).filter(Boolean):[]}function Ms(n){if(typeof n!="string")return null;const e=n.trim();if(!e)return null;try{return JSON.parse(e)}catch{const t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);if(!t)return null;try{return JSON.parse(t[1].trim())}catch{return null}}}function wn(n,e={}){const t=[],r=typeof n=="string"?Ms(n):n,i=lt(r||{});!r&&typeof n=="string"&&t.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 n=="string"?n:""),dependencies:i.dependencies||e.dependencies,relationships:i.relationships||e.relationships}],a=o.map((d,p)=>Sl(d,p)),l=new Map(o.map((d,p)=>{var f;return[lt(d).id,(f=a[p])==null?void 0:f.id]}).filter(([d,p])=>d&&p)),c=d=>l.get(d)||d,u=Il(i.relationships||e.relationships).map(d=>({...d,from:d.from?c(d.from):d.from,to:d.to?c(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:kl(i.dependencies||e.dependencies),relationships:u,deployOrder:Array.isArray(i.deployOrder)?i.deployOrder.map(c):a.map(d=>d.id),warnings:[...t,...Array.isArray(i.warnings)?i.warnings:[]],metadata:lt(i.metadata)}}function ar(n){return wn(n).artifacts[0]||Sl()}function Ke(n){if(typeof n!="string")return n??"";const e=n.trim();if(!e)return"";try{return JSON.parse(e)}catch{return n}}function jt(n){return JSON.stringify(n,null,2)}function Md(n){return jt({task:"architect",userRequest:String(n??"")})}function Od(n){const e=Ke(n);return e&&typeof e=="object"&&typeof e.task=="string"?jt(e):jt({task:"generate_bundle",bundleSpec:e})}function Nd(n){return jt({task:"review_bundle",generatedBundle:Ke(n),outputRequirements:{overall:["status","score","summary","findings"],scoreRange:[0,100],eachArtifact:["id","review.status","review.findings"]}})}function li(n,e=null){const t={stage:n};return e!=null&&(t.bundle=Ke(e)),t}function Ld({bundleSpec:n,artifactBundle:e,bundleReview:t,artifactId:r,userFeedback:s}){return jt({task:"regenerate_artifact",artifactId:r,bundleSpec:Ke(n),artifactBundle:Ke(e),bundleReview:Ke(t),userFeedback:String(s)})}function Cl({bundleSpec:n,artifactBundle:e,bundleReview:t,userFeedback:r}){return jt({task:"regenerate_bundle",bundleSpec:Ke(n),artifactBundle:Ke(e),bundleReview:Ke(t),userFeedback:String(r??"")})}const Wo={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"},Dd=["sanitizationResult","modelArmor","modelArmorResult","data","result","error"];function he(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)}function Bd(n){return he(n)?typeof n.filterMatchState=="string"||typeof n.invocationResult=="string"||Array.isArray(n.matchedFilters)||he(n.filterSummary)||he(n.filterResults):!1}function xl(n,e=0){if(!he(n)||e>3)return null;if(Bd(n))return n;for(const t of Dd){const r=n[t];if(he(r)){const s=xl(r,e+1);if(s)return s}}return null}function lr(n){return Array.isArray(n)?n.some(lr):he(n)?n.matched===!0||n.matchState==="MATCH_FOUND"?!0:Object.values(n).some(lr):!1}function Os(n){return Array.isArray(n)?n.some(Os):he(n)?typeof n.executionState=="string"&&n.executionState!=="EXECUTION_SUCCESS"?!0:Object.values(n).some(Os):!1}function Tl(n){return{csamFilterFilterResult:"csam",maliciousUriFilterResult:"malicious_uris",piAndJailbreakFilterResult:"pi_and_jailbreak",raiFilterResult:"rai",sdpFilterResult:"sdp",virusScanFilterResult:"virus_scan"}[n]||n}function jd(n,e){if(he(n))for(const[t,r]of Object.entries(n)){if(!he(r))continue;const s=he(r.categories)?r.categories:{},i=Object.entries(s).filter(([,o])=>he(o)&&o.matched===!0).map(([o])=>o);i.length>0?i.forEach(o=>e.add(o)):r.matched===!0&&e.add(Tl(t))}}function Ud(n,e){var r;if(!n)return;const t=Array.isArray(n)?n.flatMap(s=>he(s)?Object.entries(s):[]):Object.entries(n);for(const[s,i]of t){if(!lr(i))continue;const o=Tl(s),a=((r=i==null?void 0:i.raiFilterResult)==null?void 0:r.raiFilterTypeResults)||(o==="rai"?i==null?void 0:i.raiFilterTypeResults:null),l=he(a)?Object.entries(a).filter(([,c])=>lr(c)).map(([c])=>c):[];l.length>0?l.forEach(c=>e.add(c)):e.add(o)}}function Hd(n){return Wo[n]?Wo[n]:String(n).replace(/([a-z])([A-Z])/g,"$1 $2").replace(/_/g," ").toLowerCase()}function zo(n){return n.length<=1?n[0]||"content that did not pass":n.length===2?`${n[0]} and ${n[1]}`:`${n.slice(0,-1).join(", ")}, and ${n.at(-1)}`}function Wd(n){const e=xl(n);if(!e)return null;const t=new Set(Array.isArray(e.matchedFilters)?e.matchedFilters:[]);jd(e.filterSummary,t),Ud(e.filterResults,t);const r=e.blocked===!0||e.filterMatchState==="MATCH_FOUND"||t.size>0,s=e.invocationResult||null,i=Os(e.filterSummary||e.filterResults);return!r&&!i&&!["PARTIAL","FAILURE"].includes(s)?null:{kind:r?"blocked":"unavailable",invocationResult:s,matchedFilters:[...t]}}function zd(n,e){const t=Wd(n);if(!t)return null;const r=[...new Set(t.matchedFilters.map(Hd))],s=t.kind==="blocked",i=new Error(s?`Safety screening blocked this pipeline step for ${zo(r)}.`:"Safety screening could not be completed. Please try again.");return i.name="ModelArmorError",i.code=s?"MODEL_ARMOR_BLOCKED":"MODEL_ARMOR_UNAVAILABLE",i.isModelArmor=!0,i.pipelineStep=e,i.userTitle=s?"Request blocked for safety":"Safety check unavailable",i.userMessage=s?`The safety check detected ${zo(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=s?"Trying another model would not change this safety decision.":"A fallback model was not attempted because safety screening must complete first.",i.matchedFilters=t.matchedFilters,i}const Gd=new Set(["CustomWidget","CustomAction","CustomFunction","CustomClass","CodeFile"]),Go={CustomWidget:"custom_widgets/",CustomAction:"actions/",CustomFunction:"custom_functions/",CustomClass:"custom_code/",CodeFile:"custom_code/"};function ft(n,e,t){return{artifactId:n.id,artifactName:n.artifactName,artifactType:n.artifactType,severity:e,message:t}}function ci(n=""){return Array.from(n.matchAll(/\b(?:class|enum)\s+([A-Za-z_]\w*)/g),e=>e[1])}function Vd(n="",e=""){var o;const t=String.raw`((?:[^<>]|<[^<>]*>)+)`,s=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")||String.raw`[A-Za-z_]\w*`,i=n.match(new RegExp(String.raw`\bFuture\s*(?:<\s*${t}\s*>)?\s+${s}\s*\(`));return((o=i==null?void 0:i[1])==null?void 0:o.replace(/\s+/g," ").trim())||null}function qd(n="",e=""){const r=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")||String.raw`[A-Za-z_]\w*`;return new RegExp(String.raw`\bFuture\s*(?:<(?:[^<>]|<[^<>]*>)+>)?\s+${r}\s*\(`).test(n)}function Kd(n,e){return((n==null?void 0:n.match(/[A-Za-z_]\w*/g))||[]).find(r=>e.has(r))||null}function Rl(n,{functionName:e="",declaredTypes:t=new Set}={}){const r=Vd(n,e),s=Kd(r,t);return s?`CustomAction return type "${r}" uses Code File type "${s}", which FlutterFlow cannot process as an Action Return Value. Return JSON (Future or Future>) or an existing FlutterFlow Data Type (*Struct) instead.`:null}function Yd(n,e={}){const t=[],r=n.fileName||"",s=n.code||"";if(Gd.has(n.artifactType)||t.push(ft(n,"error",`Unsupported artifact type "${n.artifactType}".`)),r.endsWith(".dart")||t.push(ft(n,"error","FlutterFlow custom code artifacts must use .dart files.")),!s.trim())return t.push(ft(n,"warning","Generated artifact has no Dart code yet.")),t;if(n.artifactType==="CustomWidget"&&!/class\s+\w+\s+extends\s+(StatelessWidget|StatefulWidget)/.test(s)&&t.push(ft(n,"warning","CustomWidget code should declare a widget class extending StatelessWidget or StatefulWidget.")),n.artifactType==="CustomAction"&&!qd(s,n.artifactName)&&t.push(ft(n,"warning","CustomAction code should expose an async Future function callable from FlutterFlow.")),n.artifactType==="CustomAction"){const i=e.declaredTypes||new Set(ci(s)),o=Rl(s,{functionName:n.artifactName,declaredTypes:i});o&&t.push(ft(n,"error",o))}return n.artifactType==="CustomFunction"&&/class\s+\w+\s+extends\s+(StatelessWidget|StatefulWidget)/.test(s)&&t.push(ft(n,"warning","CustomFunction should be a callable function, not a widget class.")),t}function Jd(n){const e=Array.isArray(n==null?void 0:n.artifacts)?n.artifacts:[],t=new Set(e.flatMap(i=>ci(i.code||""))),r=e.flatMap(i=>Yd(i,{declaredTypes:t})),s=e.map(i=>({artifactId:i.id,fileName:i.fileName,pathHint:Go[i.artifactType]||Go.CodeFile}));return{valid:r.every(i=>i.severity!=="error"),findings:r,deployHints:s}}const we={ACTION:"A",WIDGET:"W",FUNCTION:"F",CODE_FILE:"C",DEPENDENCIES:"D",OTHER:"O"},Zd={CustomAction:we.ACTION,CustomWidget:we.WIDGET,CustomFunction:we.FUNCTION,CustomClass:we.CODE_FILE,CodeFile:we.CODE_FILE};function Xd(n,e){switch(e){case we.ACTION:return`lib/custom_code/actions/${n}`;case we.WIDGET:return`lib/custom_code/widgets/${n}`;case we.FUNCTION:return"lib/flutter_flow/custom_functions.dart";case we.CODE_FILE:return`lib/custom_code/${n}`;case we.DEPENDENCIES:return"pubspec.yaml";case we.OTHER:return`lib/custom_code/${n}`;default:return n}}function Qd(n){if(n.artifactType==="CustomFunction")return"custom_functions.dart";const e=n.fileName||n.artifactName||n.id||"generated_code";return e.endsWith(".dart")?e:`${e}.dart`}function Vo(n=[]){return n.reduce((e,t)=>{const r=t.name||t.package;return!r||r==="flutter"||(e[r]=t.version||""),e},{})}function ep(n){const e=new Map,t=new Map,r=[];for(const s of n)e.has(s.fileName)?r.push(`Duplicate deploy file name "${s.fileName}" for artifacts "${e.get(s.fileName)}" and "${s.artifactId}".`):e.set(s.fileName,s.artifactId),t.has(s.path)?r.push(`Duplicate deploy path "${s.path}" for artifacts "${t.get(s.path)}" and "${s.artifactId}".`):t.set(s.path,s.artifactId);return r}function tp(n,e={}){const t=Array.isArray(n==null?void 0:n.artifacts)?n.artifacts:[],s=(e.selectedArtifactIds||(n==null?void 0:n.deployOrder)||t.map(c=>c.id)).map(c=>t.find(u=>u.id===c)).filter(Boolean),i=[...(n==null?void 0:n.warnings)||[]],o=[];s.forEach(c=>{const u=Qd(c),d=c.code||"",p=c.codeType||Zd[c.artifactType]||we.OTHER;d.trim()||i.push(`${c.artifactName||c.id} has no generated code.`),o.push({artifactId:c.id,artifactName:c.artifactName,artifactType:c.artifactType,fileName:u,content:d,type:p,path:Xd(u,p),deployMode:"customCodeSync"})});const a={...Vo(n==null?void 0:n.dependencies),...s.reduce((c,u)=>({...c,...Vo(u.dependencies)}),{})};s.forEach(c=>{(c.dependencies||[]).forEach(u=>{const d=u.name||u.package;d&&!u.version&&i.push(`${c.artifactName||c.id} dependency "${d}" has no explicit version.`)})});const l=ep(o);return{bundleId:(n==null?void 0:n.id)||"bundle-current",title:(n==null?void 0:n.title)||"Generated artifact bundle",fileEntries:o,dependencies:a,relationships:(n==null?void 0:n.relationships)||[],warnings:i,errors:l}}function np(n){var e;return(e=String(n||"").match(/\bclass\s+([A-Z][A-Za-z0-9_]*)\b/))==null?void 0:e[1]}function rp(n){return String(n||"").split("/").pop().replace(/\.dart$/,"").split(/[^A-Za-z0-9]+/).filter(Boolean).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join("")}function sp(n,e){const r=[rp(n),np(e.content),e.artifactName].find(s=>/^[A-Z][A-Za-z0-9_]*$/.test(String(s||"")));if(!r)throw new Error(`Cannot derive a FlutterFlow custom class name for ${n}.`);return r}function ip(n,e=new Map){const t=[];for(const[r,s]of n.entries())s.type!=="C"||e.has(s.path)||t.push({artifactId:s.artifactId||r,className:sp(r,s),content:s.content,fileName:r,path:s.path});return t}function op(n,e){const t=new Set(e.map(r=>r.path));return new Map(Array.from(n.entries()).filter(([,r])=>!t.has(r.path)))}const qo={pass:0,warning:1,fail:2},ap=["manualSteps","manualActions","requiredActions","flutterFlowSteps","flutterFlowActions","requiredUserActions","requiredFlutterFlowActions","flutterFlowSetup","userActions","nextSteps"];function ge(n){return n&&typeof n=="object"&&!Array.isArray(n)?n:{}}function We(...n){for(const e of n){if(typeof e=="string"&&e.trim())return e.trim();if(Array.isArray(e)&&e.length>0){const t=e.filter(r=>typeof r=="string").join(` +`);if(t)return t}}return""}function $e(n){return n==null?[]:Array.isArray(n)?n:[n]}function lp(n){const e=ge(n).value??n;if(e==null||typeof e=="string"&&e.trim()==="")return null;const t=Number(e);if(Number.isFinite(t))return t;const r=String(n||"").match(/\bscore\b[^\d]{0,12}(\d{1,3})(?:\s*\/\s*100)?/i);return r?Number(r[1]):null}function be(n){return String(n||"").trim().replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function ui(n){const e=String(n||"").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 Ns(...n){return n.filter(Boolean).reduce((e,t)=>qo[t]>qo[e]?t:e,"pass")}function Al(n,e="warning",t="review"){if(typeof n=="string")return{severity:e,message:n,suggestion:"",source:t};const r=ge(n),s=We(r.message,r.title,r.issue,r.description,r.summary);return s?{severity:ui(r.severity||r.status||r.level)||e,message:s,suggestion:We(r.suggestion,r.fix,r.recommendation,r.action),source:r.source||t}:null}function Ls(n,e="review"){const t=ge(n);return[["findings","warning"],["issues","warning"],["criticalIssues","fail"],["errors","fail"],["warnings","warning"],["recommendations","warning"],["requiredFixes","fail"],["suggestions","warning"]].flatMap(([s,i])=>$e(t[s]).map(o=>Al(o,i,e)).filter(Boolean))}function cp(n,e,t=null){if(typeof n=="string")return{id:`${t||"bundle"}-manual-${e+1}`,title:n,detail:"",location:"",timing:"unspecified",artifactId:t,source:"Code Review"};const r=ge(n),s=We(r.title,r.action,r.step,r.message,r.name,r.description);return s?{id:r.id||`${t||"bundle"}-manual-${e+1}`,title:s,detail:We(r.detail,r.instructions,r.description),location:We(r.location,r.flutterFlowPath,r.path),timing:We(r.timing,r.phase)||"unspecified",artifactId:t,source:We(r.source)||"Code Review"}:null}function Ds(n,e=null){const t=ge(n);return ap.flatMap(r=>$e(t[r])).map((r,s)=>cp(r,s,e)).filter(Boolean)}function up(n){let e=typeof n=="string"?Ms(n):n;if(!e&&typeof n=="string")return{rawText:n,root:{}};const t=ge(e);typeof t.content=="string"&&(e=Ms(t.content)||e);const r=ge(e),s=ge(r.reviewResult||r.codeReview||r.result);return{rawText:"",root:Object.keys(s).length?s:r}}function dp(n,e){const t=[e.id,e.fileName,e.artifactName].map(be);return n.find(r=>{const s=ge(r);return[s.id,s.fileName,s.artifactName,s.name].map(be).some(i=>i&&t.includes(i))})||null}function pp(n,e){var s,i;const r=$e((i=(s=n==null?void 0:n.metadata)==null?void 0:s.compatibility)==null?void 0:i.deployHints).find(o=>be(o==null?void 0:o.artifactId)===be(e.id)||be(o==null?void 0:o.fileName)===be(e.fileName));return(r==null?void 0:r.pathHint)||""}function fp(n,e){return $e(n==null?void 0:n.relationships).filter(t=>be(t==null?void 0:t.from)===be(e.id)||be(t==null?void 0:t.to)===be(e.id))}function hp(n,e){var t,r;return $e((r=(t=n==null?void 0:n.metadata)==null?void 0:t.compatibility)==null?void 0:r.findings).filter(s=>!(s!=null&&s.artifactId)||be(s.artifactId)===be(e.id)).map(s=>Al(s,"warning","Compatibility check")).filter(Boolean)}function gp(n,e,t,r){const s=dp(e,t),i=ge((s==null?void 0:s.review)||s||t.review),o=Object.keys(i).length>0,a=[...Ls(i),...hp(n,t)],l=Ds(i,t.id),c=ui(i.status||i.verdict||i.outcome||i.result),u=a.length?Ns(...a.map(p=>p.severity)):null,d=Ns(c,u,o?null:"warning");return{...t,index:r,status:d,statusReason:o?We(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,pathHint:pp(n,t),relationships:fp(n,t)}}function mp({bundle:n,reviewResult:e}){var T;const t=ge(n),r=$e(t.artifacts),{root:s,rawText:i}=up(e),o=[s.bundleReview,s.overallReview,s.overall,s.bundleSummary,s.summaryReview,s.review].map(ge).find(I=>Object.keys(I).length)||{},a=$e(s.artifacts||s.files||s.reviews),l=r.map((I,y)=>gp(t,a,I,y)),c=Ls(s),d=[...Ls(o),...c],p=[...Ds(o),...Ds(s),...l.flatMap(I=>I.manualSteps)].filter((I,y,P)=>P.findIndex(A=>A.title===I.title&&A.artifactId===I.artifactId)===y),f=ui(o.status||o.verdict||o.overallStatus||s.status||s.verdict||s.overallStatus||s.outcome),m=Ns(f,...d.map(I=>I.severity),...l.map(I=>I.status)),v=o.score??s.score??s.overallScore??i,_=lp(v),C=We(o.headline,o.summary,o.executiveSummary,o.overview,o.assessment,o.conclusion,s.overallSummary,s.headline,s.summary,s.executiveSummary,s.overview,s.assessment,s.conclusion,i,t.description)||"Code Review completed without an overarching written summary.",k=l.reduce((I,y)=>(I[y.status]+=1,I),{pass:0,warning:0,fail:0});return{title:t.title||"Generated artifact bundle",description:t.description||"",status:m,score:_,summary:C,findings:d,manualSteps:p,artifacts:l,counts:k,reviewCoverage:{reviewed:l.filter(I=>I.reviewComplete).length,total:l.length},deployOrder:$e(t.deployOrder),relationships:$e(t.relationships),warnings:$e(t.warnings),compatibility:ge((T=t.metadata)==null?void 0:T.compatibility)}}function vp(n){return String(n||"").replace(/\/\*[\s\S]*?\*\//g,"").replace(/\/\/[^\n]*/g,"")}function Ko(n){const e=/^(import|export|part|library|class|enum|extension|typedef|mixin|abstract|const|final|var|late)\b/,t=[];for(const r of vp(n).split(` +`)){if(!/^[A-Za-z_$]/.test(r)||e.test(r))continue;const s=r.match(/^[\w$<>,?\s[\]]+?\s([a-zA-Z_$][\w$]*)\s*\(/);s&&t.push(s[1])}return t}function _p(n,e){const t=n.replace(/\.dart$/,"");if(e==="W")return t.replace(/(^|_)(\w)/g,(r,s,i)=>i.toUpperCase());if(e==="A"){const r=t.replace(/(^|_)(\w)/g,(s,i,o)=>o.toUpperCase());return r.charAt(0).toLowerCase()+r.slice(1)}return e==="F"?"CustomFunctions":e==="C"?n.endsWith(".dart")?n:`${n}.dart`:t}async function Yo(n){const e=new TextEncoder().encode(String(n||"")),t=await globalThis.crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(t),r=>r.toString(16).padStart(2,"0")).join("")}async function yp(n,e=new Map){const t={},r=new Set;for(const[o,a]of n.entries()){if(a.type==="D"||a.type==="O")continue;const l=_p(o,a.type),c={old_identifier_name:l,new_identifier_name:l,type:a.type,is_deleted:!1,current_checksum:await Yo(a.content)},u=e.get(a.path);if(u!==void 0&&(c.original_checksum=await Yo(u)),t[o]=c,a.type==="F"){const d=Ko(a.content);(d.length>0?d:[a.functionName].filter(Boolean)).forEach(f=>r.add(f))}}const s=new Set(Ko(e.get("lib/flutter_flow/custom_functions.dart")||"")),i={functions_to_rename:[],functions_to_delete:[],functions_to_add:Array.from(r).filter(o=>!s.has(o))};return{fileMapContents:JSON.stringify(t),functionsMapContents:JSON.stringify(i)}}const wp=/^dependencies\s*:\s*(?:#.*)?$/,bp=/^(?:"([^"]+)"|'([^']+)'|([A-Za-z_][A-Za-z0-9_-]*))\s*:/;function Ep(n){const e=n.match(bp);return e?e[1]??e[2]??e[3]:null}function Pl(n){const e=n.trim();return e===""||e.startsWith("#")}function $l(n){const e=n.match(/^(\s*)/);return e?e[1].length:0}function di(n){const e=n.findIndex(s=>wp.test(s));if(e===-1)return null;let t=e,r=null;for(let s=e+1;sc&&c!=="flutter");if(r.length===0)return{yaml:t,added:[],alreadyPresent:[]};const s=t.split(` +`),i=new Set(Fl(t)),o=[],a=[];for(const[c,u]of r)i.has(c)?a.push(c):(o.push([c,u]),i.add(c));if(o.length===0)return{yaml:t,added:[],alreadyPresent:a};const l=di(s);if(l){const c=o.map(([u,d])=>Jo(l.childIndent,u,d));s.splice(l.endIndex,0,...c)}else s.length>0&&s[s.length-1].trim()!==""&&s.push(""),s.push("dependencies:"),o.forEach(([c,u])=>{s.push(Jo(" ",c,u))});return{yaml:s.join(` +`),added:o.map(([c])=>c),alreadyPresent:a}}function Ml(n){const e=String(n||""),t=[];return e.trim()?(/^name:\s*\S+/m.test(e)||t.push("pubspec.yaml missing name field"),di(e.split(` +`))||t.push("pubspec.yaml missing dependencies section"),Fl(e).includes("flutter")||t.push("pubspec.yaml missing Flutter SDK dependency"),{valid:t.length===0,errors:t}):(t.push("pubspec.yaml is empty"),{valid:!1,errors:t})}const Ip={"&":"&","<":"<",">":">",'"':""","'":"'"};function Ye(n){return String(n??"").replace(/[&<>"']/g,e=>Ip[e])}function $(n){return n?Ye(n).replace(/\n/g,"
    "):""}function gt(n){return Ye(n).replace(/\r?\n/g," ")}function Cp(n){const e={"Integration Audit Report":"📋","Critical Issues":"❌",Warnings:"⚠️",Recommendations:"✅","Overall Score":"📊"};for(const[t,r]of Object.entries(e))if(n.toLowerCase().includes(t.toLowerCase()))return r;return"📄"}function xp(n){const e={critical:"❌",warning:"⚠️",recommendation:"✅",score:"📊",issue:"🔍",fix:"🔧"};for(const[t,r]of Object.entries(e))if(n.toLowerCase().includes(t.toLowerCase()))return r;return"📝"}function Tp(n){return n.includes("class ")&&n.includes("extends ")||n.includes("StatelessWidget")||n.includes("StatefulWidget")||n.includes("import 'package:flutter/")?"dart":n.includes("def ")||n.includes("import ")||n.includes("print(")?"python":n.includes("function ")||n.includes("const ")||n.includes("console.")?"javascript":"dart"}function Ut(n){if(!n)return"";if(typeof n!="string")return String(n);const e=/```(?:\w+)?\n?([\s\S]*?)```/,t=n.match(e);return t?t[1].trim():n.trim()}function Zo(n){return n=Ye(n),n=n.replace(/\*\*(.*?)\*\*/g,'$1'),n=n.replace(/\*(.*?)\*/g,'$1'),n=n.replace(/`(.*?)`/g,'$1'),n=n.replace(/\b(FAIL|ERROR|CRITICAL)\b/g,'$1'),n=n.replace(/\b(WARN|WARNING)\b/g,'$1'),n=n.replace(/\b(PASS|SUCCESS|OK)\b/g,'$1'),n}function Ol(n,e="dart",t=globalThis.hljs){if(!n)return"";const r=Ut(n);try{return t.highlight(r,{language:e}).value}catch(s){console.warn("Syntax highlighting failed:",s);try{return t.highlight(r,{language:"json"}).value}catch{return Ye(r)}}}function kr(n,e={}){const{highlighter:t=globalThis.hljs}=e;let r='
    ';const s=String(n??"").split(` +`);let i=!1,o="";for(const a of s){if(a.startsWith("```")){if(i){const l=Tp(o),c=Ol(o.trim(),l,t);r+=`
    +
    ${c}
    +
    `,o="",i=!1}else i=!0;continue}if(i){o+=a+` +`;continue}if(a.startsWith("# ")){const l=a.substring(2).trim();r+=`
    +

    + ${Cp(l)} + ${Ye(l)} +

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

    + ${xp(l)} + ${Ye(l)} +

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

    ${Zo(a)}

    `)}return r+="
    ",` +
    +
    +
    + Live Audit Report +
    + ${r} +
    + `}const Rp="https://ccc-ffai-runner-y5cyj3473a-uw.a.run.app/deployCustomClasses",Ap="phc_KoqpBJCIiWMW5I6HKBM092DVXZbMmE4KkPHqI518pF3",Pp="https://us.i.posthog.com";wl.init(Ap,{api_host:Pp,person_profiles:"identified_only"});function Fe(n,e={}){try{wl.capture(n,e)}catch(t){console.error("PostHog tracking failed",t)}}const Ie="https://4tgke4.buildship.run",Nl={professional:"price_1T2ldCKszA2slvDXatdeCpbI",power:"price_1T2le9KszA2slvDXR4mPvw7M"},cr="ccc_auth_session",Xo=new WeakSet;let D={email:null,sessionToken:null,isVerified:!1};function Ht(n={}){return{tier:"free",status:"none",periodEnd:null,isLoading:!1,isResolved:!1,error:null,...n}}let q=Ht({isResolved:!0});const $p=`${Ie}/service/runpipeline`,Fp="bs_user_id",Mp=`${Ie}/authUserCheck`;let jn={userId:null,status:null,resolved:!1};const ur={free:2,professional:50,power:2e3},dr="ccc_subscription",Qo=3,Op=new Set(["active","trialing","paid"]),bn="google/gemini-3.6-flash",Un=["anthropic/claude-opus-5","openai/gpt-5.6-sol","z-ai/glm-5.2","moonshotai/kimi-k3","openrouter/auto","openrouter/free","openrouter/deepseek/deepseek-v4-pro"],Np={"google/gemini-3.6-flash":"Gemini 3.6 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":"OpenRouter: Auto Router","openrouter/free":"OpenRouter: Free Models","openrouter/deepseek/deepseek-v4-pro":"DeepSeek v4 Pro"};function ye(n){return Np[n]||n}const Ot="ccc_usage",Bs="google/gemini-3.6-flash",js="google/gemini-3.6-flash",is="google/gemini-3.6-flash",ea={professional:11,power:49},Us={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"},Hn={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 Wn={...Hn};async function Lp(){const n=new AbortController,e=setTimeout(()=>n.abort(),5e3);try{const t=await fetch("https://open.er-api.com/v6/latest/AUD",{signal:n.signal});if(!t.ok)return;const r=await t.json();if(r.result!=="success"||!r.rates)return;const s=r.rates,i={AUD:1},o=new Set([...Object.keys(Hn),...Object.values(Hs),...Object.values(Us)]);for(const a of o)a!=="AUD"&&(typeof s[a]=="number"&&s[a]>0?i[a]=s[a]:Hn[a]&&(i[a]=Hn[a]));Wn=i}catch{}finally{clearTimeout(e)}}const Hs={"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 Ll(){try{const i=Intl.DateTimeFormat().resolvedOptions().timeZone;if(i&&Hs[i])return Hs[i]}catch{}const e=(navigator.language||"en-US").replace("-","_"),t=Us[e];if(t)return t;const r=e.split("_")[0],s=Us[r];return s||"USD"}function ta(n,e){const t=Wn[e]??Wn.USD,r=n*t,s=Math.round(r*100)/100;try{return new Intl.NumberFormat("en-US",{style:"currency",currency:e,minimumFractionDigits:0,maximumFractionDigits:s>=100||s%1===0?0:2}).format(s)}catch{return new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",minimumFractionDigits:0,maximumFractionDigits:2}).format(n*Wn.USD)}}const Me="ccc_api_key_",Ve="ccc_session_api_key_",Le="ccc_encryption_key",En="ccc_encryption_key_scope",Dp="ccc_keystore",pr="keys",Sn="ccc_encryption_key_version";let Ws=null,fr=null,kn=!1,hr=!1,na=!1;class gr extends Error{constructor(){super("Secure browser key storage is unavailable."),this.name="CredentialStorageUnavailableError"}}function ra(){if(na)return;na=!0;const n="Secure browser key storage is unavailable. Existing credentials were left untouched; new credentials will be available only in this tab session.";console.warn(n),document.body&&V(n,"warning")}function Dl(){return localStorage.getItem(Sn)||""}function zs(){var n;return((n=crypto.randomUUID)==null?void 0:n.call(crypto))||jl(crypto.getRandomValues(new Uint8Array(16)))}function Bp(){const n=Dl();if(n)return n;const e=zs();return localStorage.setItem(Sn,e),e}function Wt(){Ws=null,fr=null,kn=!1,hr=!1}window.addEventListener("storage",n=>{n.key===Sn&&Wt()});function jp(){return new Promise((n,e)=>{const t=indexedDB.open(Dp,1);t.onupgradeneeded=()=>{const r=t.result;r.objectStoreNames.contains(pr)||r.createObjectStore(pr)},t.onsuccess=()=>n(t.result),t.onerror=()=>e(t.error)})}async function pi(n,e){const t=await jp();return new Promise((r,s)=>{const i=t.transaction(pr,n);let o;try{o=e(i.objectStore(pr))}catch(l){t.close(),s(l);return}let a;o.onsuccess=()=>{a=o.result},o.onerror=()=>s(o.error),i.oncomplete=()=>{t.close(),r(a)},i.onerror=()=>{t.close(),s(i.error||new Error("Encryption key transaction failed."))},i.onabort=()=>{t.close(),s(i.error||new Error("Encryption key transaction aborted."))}})}function Up(n){var e;return n instanceof CryptoKey&&((e=n.algorithm)==null?void 0:e.name)==="AES-GCM"&&n.extractable===!1&&n.usages.includes("encrypt")&&n.usages.includes("decrypt")}async function Hp(){const n=await pi("readonly",e=>e.get(Le));return Up(n)?n:null}async function Bl(n){await pi("readwrite",e=>e.put(n,Le))}async function Wp(){Wt();try{await pi("readwrite",n=>n.delete(Le))}catch(n){console.warn("Could not delete the stored encryption key:",n)}}async function zp(){const n=sessionStorage.getItem(Le);if(!n)return null;const e=await crypto.subtle.importKey("jwk",JSON.parse(n),{name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);return await Bl(e),sessionStorage.removeItem(Le),sessionStorage.removeItem(En),localStorage.removeItem(Me+"salt"),e}async function sa(n){const e=sessionStorage.getItem(Le);if(e)return hr=sessionStorage.getItem(En)!=="session",crypto.subtle.importKey("jwk",JSON.parse(e),{name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);if(!n)throw new gr;const t=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!0,["encrypt","decrypt"]),r=await crypto.subtle.exportKey("jwk",t);return sessionStorage.setItem(Le,JSON.stringify(r)),sessionStorage.setItem(En,"session"),hr=!1,crypto.subtle.importKey("jwk",r,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}async function Gp(n){if(sessionStorage.getItem(En)==="session"&&sessionStorage.getItem(Le))return ra(),kn=!0,sa(n);try{const e=await Hp();if(e)return e;const t=await zp();if(t)return t;const r=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);return await Bl(r),r}catch(e){return console.warn("IndexedDB encryption-key storage failed:",e),ra(),kn=!0,sa(n)}}async function fi(n={}){const{allowSessionFallbackCreation:e=!0}=n,t=Bp();fr!==t&&Wt();const r=Ws||Gp(e);Ws=r,fr=t;try{return await r}catch(s){throw Wt(),s}}async function Vp(n){const e=await fi(),t=fr,r=new TextEncoder,s=crypto.getRandomValues(new Uint8Array(12)),i=await crypto.subtle.encrypt({name:"AES-GCM",iv:s},e,r.encode(n)),o=new Uint8Array(s.length+i.byteLength);return o.set(s),o.set(new Uint8Array(i),s.length),{ciphertext:jl(o),keyVersion:t,sessionFallback:kn}}async function qp(n,e={}){const{isSessionCredential:t=!1}=e;try{const r=await fi({allowSessionFallbackCreation:!1});if(kn&&!t&&!hr)throw new gr;const s=Kp(n),i=s.slice(0,12),o=s.slice(12),a=await crypto.subtle.decrypt({name:"AES-GCM",iv:i},r,o);return new TextDecoder().decode(a)}catch(r){if(r instanceof gr)throw r;return console.error("Decryption failed:",r),null}}function jl(n){const e=new Uint8Array(n);let t="";for(let r=0;r0}let In="",mr="";async function hi(){sessionStorage.getItem(Le)&&await fi(),In=await le("flutterflow"),mr=await le("flutterflow_project_id"),Qp(),bt()}function gi(){document.getElementById("api-keys-modal").classList.add("open"),vi(),In&&zl(In)}function Ul(n){if(n&&n.target!==n.currentTarget)return;const e=document.getElementById("api-keys-modal");e&&e.classList.remove("open");const t=document.getElementById("walkthrough-modal");t&&(mi(),t.classList.add("open"))}let Je=1;function Hl(){const n=document.querySelector(".wt-steps");return n?Array.from(n.querySelectorAll(".wt-step-card")):[]}function Ir(){const n=Hl();n.length&&n.forEach((e,t)=>{const r=t+1;if(r===Je){e.classList.remove("opacity-60","bg-gray-50","border-gray-200"),e.classList.add("bg-blue-50","border-blue-200");const s=e.querySelector("div:first-child");s&&(s.classList.remove("bg-gray-400"),s.classList.add("bg-blue-500"),s.innerHTML=r)}else if(r0&&Je<=n&&(Je++,Ir())}function Jp(){const n=document.getElementById("walkthrough-modal");n&&(Je=1,Ir(),n.classList.add("open"))}function Zp(n){if(n&&n.target!==n.currentTarget)return;const e=document.getElementById("walkthrough-modal");e&&e.classList.remove("open");const t=document.getElementById("walkthrough-dont-show");t&&t.checked&&localStorage.setItem("hasSeenWalkthrough","true")}function Wl(){if(D.isVerified&&yt()&&q.tier!=="free")return;if(!localStorage.getItem("hasSeenWalkthrough")){const e=document.getElementById("walkthrough-modal");e&&(Je=1,Ir(),e.classList.add("open"))}}async function vi(){const n=document.getElementById("flutterflow-api-key-input");In?(n.value="",n.placeholder="Key saved (enter new to replace)"):n.placeholder="Enter your FlutterFlow API key",Xp()}function Xp(){oa("flutterflow","flutterflow-key-status"),oa("flutterflow_project_id","flutterflow-project-status")}function oa(n,e){const t=document.getElementById(e);if(!t)return;const r=t.querySelector(".key-status-dot"),s=t.querySelector("span");At(n)?(r.className="key-status-dot configured",s.className="text-green-600",s.textContent="User key configured"):(r.className="key-status-dot missing",s.className="text-gray-500",s.textContent="Not configured")}function bt(){const n=g.step2Result&&g.step2Result.length>0,e=document.getElementById("btn-deploy-to-ff"),t=document.getElementById("btn-run-pipeline");t&&t.classList.remove("hidden"),e&&e.classList.toggle("hidden",!n)}function Qp(){const n=document.getElementById("api-keys-status");if(!n)return;const e=n.querySelectorAll(".key-status-dot"),t=["flutterflow"];e.forEach((r,s)=>{const i=t[s];i==="flutterflow"?At("flutterflow")&&At("flutterflow_project_id")?(r.className="key-status-dot configured",r.title="FlutterFlow (Fully configured)"):At("flutterflow")||At("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)"):At(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)")}),bt()}async function ef(){const n=document.getElementById("flutterflow-api-key-input"),e=document.getElementById("flutterflow-projects-select");n.value.trim()&&await ia("flutterflow",n.value);const t=(e==null?void 0:e.value.trim())||"";if(t){if(!Cr(t)){V("The selected FlutterFlow project has an unexpected ID format.","error"),e.focus();return}await ia("flutterflow_project_id",t)}await hi(),vi();const r=document.querySelector("#api-keys-modal .bg-blue-500"),s=r.textContent;r.textContent="Saved!",r.classList.remove("bg-blue-500","hover:bg-blue-600"),r.classList.add("bg-green-500"),setTimeout(()=>{r.textContent=s,r.classList.remove("bg-green-500"),r.classList.add("bg-blue-500","hover:bg-blue-600"),Ul()},1e3)}async function tf(){if(!confirm("Are you sure you want to clear all stored API keys?"))return;localStorage.setItem(Sn,zs()),Wt(),localStorage.removeItem(Me+"flutterflow"),localStorage.removeItem(Me+"flutterflow_project_id"),sessionStorage.removeItem(Ve+"flutterflow"),sessionStorage.removeItem(Ve+"flutterflow_project_id"),sessionStorage.removeItem(Le),sessionStorage.removeItem(En),localStorage.removeItem(Me+"salt"),await Wp(),localStorage.setItem(Sn,zs()),localStorage.removeItem(Me+"flutterflow"),localStorage.removeItem(Me+"flutterflow_project_id"),sessionStorage.removeItem(Ve+"flutterflow"),sessionStorage.removeItem(Ve+"flutterflow_project_id"),await hi();const n=document.getElementById("flutterflow-projects-select");n&&(n.innerHTML=''),vi()}function Cr(n){return!n||n.trim().length<5||n.includes(" ")?!1:/^[a-zA-Z0-9-]+$/.test(n)}function nf(n,e){const t=document.getElementById(n);t&&(t.value?e?t.style.borderColor="#22c55e":t.style.borderColor="#ef4444":t.style.borderColor="")}function rf(){const n=document.getElementById("flutterflow-api-key-input");n&&(n.addEventListener("input",e=>{const t=e.target.value.trim().length>0;nf("flutterflow-api-key-input",t)}),n.addEventListener("blur",sf(async e=>{const t=e.target.value.trim();t&&await zl(t)},500)))}function sf(n,e){let t;return function(...s){const i=()=>{clearTimeout(t),n(...s)};clearTimeout(t),t=setTimeout(i,e)}}async function zl(n){const e=document.getElementById("flutterflow-projects-select"),t=document.getElementById("flutterflow-projects-error");if(!e){console.error("Projects dropdown element not found");return}e.innerHTML='',t&&t.classList.add("hidden");try{const s=await new Rr(n,"").listProjects();if(!s||s.length===0){e.innerHTML='';return}e.innerHTML='',s.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)}),mr&&(e.value=mr)}catch(r){console.error("Failed to fetch projects:",r),e.innerHTML='',t&&(t.textContent=`Failed to load projects: ${r.message}`,t.classList.remove("hidden"))}}function of(n){const e=document.getElementById(n),r=e.nextElementSibling.querySelector("svg");e.type==="password"?(e.type="text",r.innerHTML=` + + `):(e.type="password",r.innerHTML=` + + + `)}let g={step1Result:null,step2Result:null,step3Result:null,bundleSpec:null,artifactBundle:null,bundleReview:null,selectedArtifactId:null,resultsViewMode:"summary",currentStep:0,isRunning:!1};function af(){g.step1Result=null,g.step2Result=null,g.step3Result=null,g.bundleSpec=null,g.artifactBundle=null,g.bundleReview=null,g.selectedArtifactId=null,g.resultsViewMode="summary"}function lf(){g.bundleSpec=wn(g.step1Result,{artifactType:"CustomWidget",artifactName:"GeneratedWidget"})}function xr(){var t,r,s,i;const n=ar(g.bundleSpec);g.artifactBundle=wn(g.step2Result,{id:(t=g.bundleSpec)==null?void 0:t.id,title:(r=g.bundleSpec)==null?void 0:r.title,description:(s=g.bundleSpec)==null?void 0:s.description,artifactType:n.artifactType,artifactName:n.artifactName,fileName:n.fileName,dependencies:n.dependencies,relationships:(i=g.bundleSpec)==null?void 0:i.relationships,code:g.step2Result||""});const e=Jd(g.artifactBundle);g.artifactBundle={...g.artifactBundle,warnings:[...g.artifactBundle.warnings,...e.findings.map(o=>o.message)],metadata:{...g.artifactBundle.metadata,compatibility:e}},g.selectedArtifactId=ar(g.artifactBundle).id}function Tr(){var t,r,s,i,o,a,l,c;const n=wn(g.step3Result,{id:(t=g.artifactBundle)==null?void 0:t.id,title:(r=g.artifactBundle)==null?void 0:r.title}),e=new Map(n.artifacts.map(u=>[u.id,u.review]));g.bundleReview=wn({id:(s=g.artifactBundle)==null?void 0:s.id,title:(i=g.artifactBundle)==null?void 0:i.title,artifacts:((a=(o=g.artifactBundle)==null?void 0:o.artifacts)==null?void 0:a.map(u=>({...u,review:e.get(u.id)||u.review||g.step3Result||null})))||[],relationships:(l=g.artifactBundle)==null?void 0:l.relationships,warnings:(c=g.artifactBundle)==null?void 0:c.warnings})}function Gl(){const n=_i();return{artifactType:n.artifactType||"CustomWidget",artifactName:n.artifactName||"GeneratedWidget"}}function _i(){const n=g.artifactBundle||g.bundleSpec||null;return(Array.isArray(n==null?void 0:n.artifacts)?n.artifacts:[]).find(t=>t.id===g.selectedArtifactId)||ar(n)}function yi(){return _i().code||g.step2Result||""}async function cf(){try{await hi()}catch(n){return console.error("checkConnection: initializeApiKeys failed:",n),!1}return!0}const zn={production:"https://api.flutterflow.io/v2/",staging:"https://api.flutterflow.io/v2-staging/"};class Rr{constructor(e,t,r="main",s=zn.production){this.apiKey=e,this.baseUrl=s,this._projectId=t,this._branchName=r,this._endpoint=s}get projectId(){return this._projectId}get branchName(){return this._branchName==="main"?"":this._branchName}async exportProjectZip(){var r;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 t=null;for(const s of e)try{const i=await fetch(`${this.baseUrl}exportCode`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify(s)});if(!i.ok){const l=await i.text();t=new Error(`Export failed: ${i.status} - ${l}`);continue}const o=await i.json(),a=((r=o==null?void 0:o.value)==null?void 0:r.project_zip)||(o==null?void 0:o.project_zip);if(!a){t=new Error("Export response did not include project source.");continue}return a}catch(i){t=i}throw t||new Error("Export failed for an unknown reason.")}async fetchProjectSource(){const e=await this.exportProjectZip(),t=await JSZip.loadAsync(e,{base64:!0}),r=Object.keys(t.files).filter(a=>!t.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 s=r.slice(0,r.length-12),i=new Map,o=Object.keys(t.files).filter(a=>{if(t.files[a].dir||!a.startsWith(s))return!1;const l=a.slice(s.length);return l==="lib/flutter_flow/custom_functions.dart"||l.startsWith("lib/custom_code/")&&l.endsWith(".dart")});return await Promise.all(o.map(async a=>{i.set(a.slice(s.length),await t.files[a].async("string"))})),{pubspecYaml:await t.files[r].async("string"),files:i}}async pushCodeWithRetry(e,t=3){var i,o,a;const r=[zn.production,zn.staging],s=Math.max(0,r.indexOf(this._endpoint));for(let l=0;lsetTimeout(m,1e3*(l+1)));continue}return d}catch(d){console.warn(`Push to ${u} failed: ${d.message}, trying next...`),await new Promise(p=>setTimeout(p,1e3*(l+1)))}}throw new Error("All API endpoints failed after retries")}async pushCode(e){return this.pushCodeWithRetry(e)}async listProjects(e={}){const{page:t=1,limit:r=100}=e;console.log("Listing projects for API key via V2 endpoint");try{const s=await fetch("https://api.flutterflow.io/v2/l/listProjects",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify({project_type:"ALL",deserialize_response:!0})});if(!s.ok){const a=await s.text();throw new Error(`List projects failed: ${s.status} - ${a}`)}const i=await s.json();if(i.success&&typeof i.value=="string")try{const a=JSON.parse(i.value);if(a&&Array.isArray(a.entries))return a.entries.map(l=>{var c;return{id:l.id,name:((c=l.project)==null?void 0:c.name)||l.id}})}catch(a){console.error("Failed to parse stringified project value:",a)}const o=i.projects||i.items||i.entries||(Array.isArray(i)?i:[]);return Array.isArray(o)?o:[]}catch(s){throw console.error("Error listing projects:",s),s}}}async function wi(n){const e=n.clone();let t;try{t=await n.json()}catch{const i=await e.text();if(!n.ok)return{success:!1,responseCode:n.status,errorMessage:i||`HTTP ${n.status}`,errorMap:new Map};throw new Error(`Invalid JSON response: ${i}`)}if(!n.ok){let s=t.message||`HTTP ${n.status}`,i=new Map;if(t.errors)i=new Map(Object.entries(t.errors));else if(!t.message&&typeof t=="object"){const o=Object.keys(t).filter(a=>a.endsWith(".dart")&&Array.isArray(t[a]));o.length>0&&(i=new Map(Object.entries(t)),s=o.flatMap(l=>t[l].map(c=>`${l}: ${c.errorMessage}`)).join(` +`)||`HTTP ${n.status}`)}return{success:!1,responseCode:n.status,errorMessage:s,errorMap:i}}const r=t.value?JSON.parse(t.value):{};return{success:!0,responseCode:n.status,errorMap:new Map(Object.entries(r))}}function bi(n,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."}[n]||`FlutterFlow API error: ${`HTTP ${n}`}`}const O={ACTION:"A",WIDGET:"W",FUNCTION:"F",CODE_FILE:"C",DEPENDENCIES:"D",OTHER:"O"},Vl=/class\s+\w+\s+extends\s+(?:StatelessWidget|StatefulWidget)\b/,ql=/extends\s+State<\w+>/;function uf(n,e=""){if(n==="pubspec.yaml")return O.DEPENDENCIES;if(!n.endsWith(".dart")||n.endsWith("index.dart"))return O.OTHER;if(n==="custom_functions.dart")return O.FUNCTION;if(e){const t=Vl.test(e),r=ql.test(e);if(t||r)return O.WIDGET;if(/^\s*Future(?:<[^>]+>)?\s+\w+\s*\(/m.test(e))return O.ACTION;if(e.match(/^\s*(String|int|double|bool|List|Map|dynamic|void)\s+\w+\s*\(/m))return O.FUNCTION}return O.CODE_FILE}function Kl(n,e){switch(e){case O.ACTION:return`lib/custom_code/actions/${n}`;case O.WIDGET:return`lib/custom_code/widgets/${n}`;case O.FUNCTION:return"lib/flutter_flow/custom_functions.dart";case O.CODE_FILE:return`lib/custom_code/${n}`;case O.DEPENDENCIES:return"pubspec.yaml";case O.OTHER:return`lib/custom_code/${n}`;default:return n}}async function Ei(n,e=new Map){return yp(n,e)}const Gs=new Map;function Yl(n){return`${n.baseUrl}|${n.projectId}|${n.branchName}`}function Ar(n){Gs.delete(Yl(n))}async function Si(n,e,t,r){const s=ip(e,t);if(s.length===0)return{remoteFiles:t,syncFileMap:e};console.log(`Provisioning ${s.length} new FlutterFlow custom code file(s) before sync.`);const i=await fetch(Rp,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:n.apiKey,projectId:n.projectId,baseUrl:n.baseUrl,commitMessage:r,customClasses:s})}),o=await i.text();let a={};try{a=o?JSON.parse(o):{}}catch{a={}}if(!i.ok||a.success===!1){const l=a.details?` ${a.details}`:"";throw new Error(`${a.error||"FlutterFlow custom class provisioning failed."}${l}`)}return Ar(n),{remoteFiles:t,syncFileMap:op(e,s)}}async function ki(n,e={}){const t=Yl(n);let r=Gs.get(t);if(r===void 0){try{r=await n.fetchProjectSource()}catch(i){throw new Error(`Could not read your project's pubspec.yaml (${i.message}). Deploy was stopped so your existing package dependencies aren't overwritten. Check your FlutterFlow API key and project, then try again.`)}const s=Ml(r.pubspecYaml);if(!s.valid)throw new Error(`Your project's pubspec.yaml could not be read reliably (${s.errors.join("; ")}). Deploy was stopped so your existing package dependencies aren't overwritten.`);Gs.set(t,r)}return{...kp(r.pubspecYaml,e),remoteFiles:r.files}}function df(n){const e=[],t=[];n.content.length>5e4&&t.push("Code file is large (>50KB). This may take longer to commit."),n.content.length>1e5&&e.push("Code file is too large (>100KB). Consider splitting into smaller components.");const r=n.content.split(` +`).length;r>500&&t.push(`Code has ${r} lines. Consider breaking it into smaller widgets.`),n.content.includes("setState")&&n.codeType===O.ACTION&&t.push("Using setState in a Custom Action may not work as expected. Consider using a Custom Widget."),n.content.includes("dynamic")&&!n.content.includes("?")&&t.push('Code uses "dynamic" types. Consider adding explicit types for better null safety.'),n.content.match(/Color\(0xFF[0-9A-Fa-f]{6}\)/)&&t.push("Code contains hardcoded colors. Consider using FlutterFlowTheme.of(context) for theme consistency.");const s=n.content.match(/print\s*\(/g);return s&&s.length>3&&t.push(`Code contains ${s.length} print statements. Consider removing debug prints before committing.`),{canProceed:e.length===0,issues:e,warnings:t}}async function pf(n,e){let t=` +
    +
    +

    Commit Summary

    +

    + File: ${n.fileName}
    + Type: ${n.artifactType}
    + Size: ${(n.content.length/1024).toFixed(1)} KB
    + Lines: ${n.content.split(` +`).length} +

    +
    + `;return e.warnings.length>0&&(t+=` +
    +

    Warnings (${e.warnings.length})

    +
      + ${e.warnings.map(r=>`
    • • ${r}
    • `).join("")} +
    +
    + `),e.issues.length>0&&(t+=` +
    +

    Issues (${e.issues.length})

    +
      + ${e.issues.map(r=>`
    • • ${r}
    • `).join("")} +
    +
    + `),t+="
    ",console.log("Pre-commit summary:",t),e.canProceed?e.warnings.length>0?confirm(`Found ${e.warnings.length} warning(s). Proceed with commit? + +${e.warnings.join(` +`)}`):!0:!1}function Jl(n,e={}){const{artifactType:t="CustomWidget",artifactName:r="GeneratedCode"}=e;let s=n.trim();s.startsWith("```dart")?s=s.replace(/^```dart\n/,""):s.startsWith("```")&&(s=s.replace(/^```\n/,"")),s.endsWith("```")&&(s=s.replace(/\n```$/,""));let i=r;i.endsWith(".dart")||(i+=".dart");let o=O.CODE_FILE;switch(t){case"CustomAction":o=O.ACTION;break;case"CustomWidget":o=O.WIDGET;break;case"CustomFunction":o=O.FUNCTION,i="custom_functions.dart";break;case"CustomClass":case"CodeFile":o=O.CODE_FILE;break}let a="";return o===O.WIDGET?a=`// 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! + +`:o===O.ACTION?a=`// 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! + +`:o===O.FUNCTION&&(a=`// 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:a+s,fileName:i,codeType:o,artifactType:t,artifactName:r}}function ff(n){const e={},t=[{name:"flutter_animate",pattern:/flutter_animate/},{name:"google_fonts",pattern:/google_fonts/},{name:"flutter_svg",pattern:/flutter_svg/},{name:"http",pattern:/package:http\b/},{name:"intl",pattern:/package:intl\b/},{name:"collection",pattern:/package:collection\b/},{name:"rxdart",pattern:/package:rxdart\b/},{name:"timeago",pattern:/package:timeago\b/},{name:"url_launcher",pattern:/package:url_launcher\b/},{name:"cloud_firestore",pattern:/package:cloud_firestore\b/},{name:"firebase_auth",pattern:/package:firebase_auth\b/},{name:"flutter_tts",pattern:/package:flutter_tts\b/},{name:"percent_indicator",pattern:/package:percent_indicator\b/},{name:"fl_chart",pattern:/package:fl_chart\b/},{name:"cached_network_image",pattern:/package:cached_network_image\b/},{name:"image_picker",pattern:/package:image_picker\b/},{name:"file_picker",pattern:/package:file_picker\b/},{name:"shared_preferences",pattern:/package:shared_preferences\b/},{name:"sqflite",pattern:/package:sqflite\b/},{name:"path_provider",pattern:/package:path_provider\b/},{name:"uuid",pattern:/package:uuid\b/},{name:"xml",pattern:/package:xml\b/},{name:"html",pattern:/package:html\b/},{name:"csv",pattern:/package:csv\b/},{name:"pdf",pattern:/package:pdf\b/},{name:"printing",pattern:/package:printing\b/},{name:"flutter_local_notifications",pattern:/package:flutter_local_notifications\b/},{name:"geolocator",pattern:/package:geolocator\b/},{name:"geocoding",pattern:/package:geocoding\b/},{name:"firebase_core",pattern:/package:firebase_core\b/},{name:"firebase_storage",pattern:/package:firebase_storage\b/},{name:"firebase_messaging",pattern:/package:firebase_messaging\b/},{name:"cloud_functions",pattern:/package:cloud_functions\b/},{name:"firebase_analytics",pattern:/package:firebase_analytics\b/},{name:"stripe_checkout",pattern:/package:stripe_checkout\b/},{name:"pay",pattern:/package:pay\b/},{name:"in_app_purchase",pattern:/package:in_app_purchase\b/},{name:"audioplayers",pattern:/package:audioplayers\b/},{name:"just_audio",pattern:/package:just_audio\b/},{name:"video_player",pattern:/package:video_player\b/},{name:"chewie",pattern:/package:chewie\b/},{name:"flutter_rating_bar",pattern:/package:flutter_rating_bar\b/},{name:"shimmer",pattern:/package:shimmer\b/},{name:"carousel_slider",pattern:/package:carousel_slider\b/},{name:"flutter_staggered_grid_view",pattern:/package:flutter_staggered_grid_view\b/},{name:"smooth_page_indicator",pattern:/package:smooth_page_indicator\b/},{name:"qr_flutter",pattern:/package:qr_flutter\b/},{name:"barcode_widget",pattern:/package:barcode_widget\b/},{name:"qr_code_scanner",pattern:/package:qr_code_scanner\b/},{name:"lottie",pattern:/package:lottie\b/},{name:"rive",pattern:/package:rive\b/}];for(const{name:r,pattern:s}of t)s.test(n)&&(e[r]="^1.0.0");return e}function hf(n,e={}){return{timestamp:new Date().toISOString(),artifactType:n.artifactType,artifactName:n.artifactName,codeType:n.codeType,fileName:n.fileName,generatedFrom:e.step1Result?"pipeline":"direct",model:e.selectedModel||"unknown",codeSize:n.content.length}}function gf(n,e,t,r=new Set,s=""){const i=[],o=Vl.test(e),a=ql.test(e),l=[{pattern:/void\s+main\s*\(/,message:"Contains main() function - not allowed in FlutterFlow"},{pattern:/runApp\s*\(/,message:"Contains runApp() - not allowed in FlutterFlow"},{pattern:/MaterialApp\s*\(/,message:"Contains MaterialApp - not allowed in FlutterFlow"},{pattern:/Scaffold\s*\(/,message:"Contains Scaffold - usually not needed in FlutterFlow widgets"}],c=n.includes("custom_functions")||n.includes("functions"),u=/^\s*import\s+['"]([^'"]+)['"]/gm;let d;for(;(d=u.exec(e))!==null;){const p=d[1],f=p.startsWith("/flutter_flow/")||p.startsWith("/backend/")||p.startsWith("/custom_code/")||p==="index.dart"||p==="package:flutter/material.dart"||p==="package:flutter/services.dart",m=p.startsWith("dart:")||p.startsWith("package:");c?p.startsWith("dart:")||i.push(`Custom Functions cannot use '${p}' - only Dart SDK imports allowed`):!f&&!m&&i.push(`Unknown import '${p}' - use FlutterFlow managed imports`)}for(const{pattern:p,message:f}of l)p.test(e)&&i.push(f);if(t===O.WIDGET&&!o&&!a&&i.push("No widget class definition found (must extend StatelessWidget or StatefulWidget)"),t===O.ACTION){const p=Rl(e,{functionName:s,declaredTypes:r});p&&i.push(p)}return{valid:i.length===0,errors:i}}function Pr(n){const e=[],t=[];if(!n||n.size===0)return e.push("No files to commit"),{valid:!1,errors:e,warnings:t};const r=new Set(Array.from(n.values()).flatMap(s=>ci(s.content||"")));for(const[s,i]of n.entries()){if((!i.content||i.content.trim().length===0)&&e.push(`File ${s} is empty`),i.content&&i.content.length>1e5&&t.push(`File ${s} is very large (>100KB)`),s.endsWith(".dart")){const o=gf(s,i.content,i.type,r,i.artifactName);o.valid||e.push(...o.errors.map(a=>`${s}: ${a}`))}if(s==="pubspec.yaml"){const o=Ml(i.content);o.valid||e.push(...o.errors)}}return{valid:e.length===0,errors:e,warnings:t}}const N={IDLE:"IDLE",PREPARING:"PREPARING",VALIDATING:"VALIDATING",PUSHING:"PUSHING",SUCCESS:"SUCCESS",ERROR:"ERROR"},B={currentState:N.IDLE,startTime:null,endTime:null,error:null,result:null,filesProcessed:0,totalFiles:0,reset(){this.currentState=N.IDLE,this.startTime=null,this.endTime=null,this.error=null,this.result=null,this.filesProcessed=0,this.totalFiles=0},setState(n){if(!Object.values(N).includes(n)){console.error(`Invalid commit state: ${n}`);return}this.currentState=n,n===N.PREPARING&&(this.startTime=Date.now()),(n===N.SUCCESS||n===N.ERROR)&&(this.endTime=Date.now()),typeof window<"u"&&window.dispatchEvent&&window.dispatchEvent(new CustomEvent("commitStateChange",{detail:{state:n,commitState:this}})),console.log(`Commit state changed to: ${n}`)},setError(n){this.error=n,this.setState(N.ERROR)},setSuccess(n){this.result=n,this.setState(N.SUCCESS)},setProgress(n,e){this.filesProcessed=n,this.totalFiles=e},getElapsedTime(){return this.startTime?(this.endTime||Date.now())-this.startTime:null},isInProgress(){return this.currentState===N.PREPARING||this.currentState===N.VALIDATING||this.currentState===N.PUSHING}};async function mf(n,e,t={}){let{codeType:r="W"}=t;const{pubspecDeps:s={},artifactName:i=e}=t;r==="CustomWidget"&&(r=O.WIDGET),r==="CustomAction"&&(r=O.ACTION),r==="CustomFunction"&&(r=O.FUNCTION),r==="CustomClass"&&(r=O.CODE_FILE),r==="CodeFile"&&(r=O.CODE_FILE),B.reset(),B.setState(N.PREPARING);try{const o=await le("flutterflow"),a=await le("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(!Cr(a))throw new Error("Invalid FlutterFlow Project ID format.");const l=An(),c=new Rr(o,a,"main",l);B.setState(N.VALIDATING);const u=new Map,d=r||uf(e,n),p=Kl(e,d);u.set(e,{artifactName:i,content:n,type:d,path:p}),B.setProgress(0,u.size);const f=Pr(u);if(!f.valid)throw new Error(`Validation failed: +${f.errors.join(` +`)}`);const m=await ki(c,s),v=m.yaml,_=await Si(c,u,m.remoteFiles,`Provision ${i} custom class`),C=await Ei(_.syncFileMap,_.remoteFiles),k=new Map(_.syncFileMap);k.set("pubspec.yaml",{content:v,type:"D",path:"pubspec.yaml"});const T=await Ii(k),I={project_id:a,zipped_custom_code:T,uid:`web_${Date.now()}`,branch_name:c.branchName,serialized_yaml:v,file_map:C.fileMapContents,functions_map:C.functionsMapContents};B.setState(N.PUSHING),B.setProgress(1,u.size),Ar(c);const y=await c.pushCode(I),P=await wi(y);if(P.success)B.setSuccess({fileCount:u.size,projectId:a,warnings:P.errorMap&&P.errorMap.size>0?Array.from(P.errorMap.entries()):[]});else{const A=P.errorMessage||bi(P.responseCode);throw new Error(A)}return{success:!0,message:`Successfully committed ${e} to FlutterFlow project ${a}`,addedDependencies:m.added,warnings:P.errorMap?Array.from(P.errorMap.entries()):[]}}catch(o){return console.error("Commit failed:",o),B.setError(o),{success:!1,error:o.message,state:B.currentState}}}async function Ii(n){try{const e=new JSZip;for(const[r,s]of n.entries())e.file(r,s.content);return await e.generateAsync({type:"base64",compression:"DEFLATE",compressionOptions:{level:6}})}catch(e){return console.error("Error creating zip:",e),""}}async function Zl(n,e={}){const{artifactType:t,artifactName:r,pipelineResult:s}=e;console.log(`Starting commit for ${r} (${t})`);try{B.setState(N.PREPARING);const i=Jl(n,{artifactType:t,artifactName:r}),o=ff(i.content);console.log("Detected dependencies:",o),B.setState(N.VALIDATING);const a=await le("flutterflow"),l=await le("flutterflow_project_id");if(!a)throw new Error("FlutterFlow API Key not configured. Please add it in API Keys settings.");if(!l)throw new Error("FlutterFlow Project ID not configured. Please add it in API Keys settings.");if(!Cr(l))throw new Error("Invalid FlutterFlow Project ID format.");const c=new Map;c.set(i.fileName,{artifactName:r,content:i.content,type:i.codeType,path:Kl(i.fileName,i.codeType),functionName:i.codeType===O.FUNCTION?r:void 0}),B.setProgress(0,c.size);const u=Pr(c);if(!u.valid)throw new Error(`File validation failed: +${u.errors.join(` +`)}`);u.warnings.length>0&&console.warn("Validation warnings:",u.warnings),B.setState(N.PUSHING);const d=An(),p=new Rr(a,l,"main",d),f=await ki(p,o),m=f.yaml,v=await Si(p,c,f.remoteFiles,`Provision ${r} custom class`),_=await Ei(v.syncFileMap,v.remoteFiles),C=new Map(v.syncFileMap);C.set("pubspec.yaml",{content:m,type:O.DEPENDENCIES,path:"pubspec.yaml"});const k=await Ii(C),T={project_id:l,zipped_custom_code:k,uid:`web_${Date.now()}`,branch_name:p.branchName,serialized_yaml:m,file_map:_.fileMapContents,functions_map:_.functionsMapContents};B.setProgress(1,c.size),Ar(p);const I=await p.pushCode(T),y=await wi(I);if(y.success){const P={...hf(i,s),projectId:l};return B.setSuccess({...P,fileCount:c.size,warnings:y.errorMap?Array.from(y.errorMap.entries()):[]}),{success:!0,message:`Successfully committed ${i.fileName} to FlutterFlow`,metadata:P,addedDependencies:f.added,warnings:y.errorMap?Array.from(y.errorMap.entries()):[],elapsedTime:B.getElapsedTime()}}else{const P=y.errorMessage||bi(y.responseCode),A=new Error(P);throw A.errorMap=y.errorMap,A}}catch(i){console.error("Commit execution failed:",i),B.setError(i);let o=new Map;if(i.errorMap)o=i.errorMap;else if(i.message&&i.message.includes("{"))try{const a=i.message.match(/\{[\s\S]*\}/);if(a){const l=JSON.parse(a[0]);o=new Map(Object.entries(l))}}catch{}return{success:!1,error:i.message,errorMap:o,state:B.currentState,elapsedTime:B.getElapsedTime()}}}async function vf(n,e={}){var r;const{pipelineResult:t}=e;try{if(B.setState(N.PREPARING),((r=n.errors)==null?void 0:r.length)>0)throw new Error(`Bundle validation failed: +${n.errors.join(` +`)}`);const s=new Map(n.fileEntries.map(y=>[y.fileName,{artifactId:y.artifactId,artifactName:y.artifactName,content:y.content,type:y.type,path:y.path,functionName:y.type===O.FUNCTION?y.artifactName:void 0}]));B.setProgress(0,s.size);const i=Pr(s);if(!i.valid)throw new Error(`File validation failed: +${i.errors.join(` +`)}`);B.setState(N.VALIDATING);const o=await le("flutterflow"),a=await le("flutterflow_project_id");if(!o)throw new Error("FlutterFlow API Key not configured. Please add it in API Keys settings.");if(!a)throw new Error("FlutterFlow Project ID not configured. Please add it in API Keys settings.");if(!Cr(a))throw new Error("Invalid FlutterFlow Project ID format.");B.setState(N.PUSHING);const l=An(),c=new Rr(o,a,"main",l),u=await ki(c,n.dependencies),d=u.yaml,p=await Si(c,s,u.remoteFiles,`Provision ${n.title} custom classes`),f=await Ei(p.syncFileMap,p.remoteFiles),m=new Map(p.syncFileMap);m.set("pubspec.yaml",{content:d,type:O.DEPENDENCIES,path:"pubspec.yaml"});const v=await Ii(m),_={project_id:a,zipped_custom_code:v,uid:`web_${Date.now()}`,branch_name:c.branchName,serialized_yaml:d,file_map:f.fileMapContents,functions_map:f.functionsMapContents};B.setProgress(1,s.size),Ar(c);const C=await c.pushCode(_),k=await wi(C);if(k.success){const y={...t,artifactType:"Bundle",artifactName:n.title,fileName:`${n.fileEntries.length} artifacts`,codeSize:n.fileEntries.reduce((P,A)=>P+A.content.length,0),projectId:a};return B.setSuccess({...y,fileCount:s.size,warnings:k.errorMap?Array.from(k.errorMap.entries()):[]}),{success:!0,message:`Successfully committed ${n.fileEntries.length} artifacts to FlutterFlow`,metadata:y,addedDependencies:u.added,warnings:k.errorMap?Array.from(k.errorMap.entries()):[],elapsedTime:B.getElapsedTime()}}const T=k.errorMessage||bi(k.responseCode),I=new Error(T);throw I.errorMap=k.errorMap,I}catch(s){return console.error("Bundle commit execution failed:",s),B.setError(s),{success:!1,error:s.message,errorMap:s.errorMap||new Map,state:B.currentState,elapsedTime:B.getElapsedTime()}}}async function _f(n){try{return await vr("architect",Bs,Md(n),li("architect"))}catch(e){throw e.isModelArmor?e:new Error(`Prompt Architect failed: ${e.message}`)}}async function $r(n,e){const t=Od(n),r=li("generator",g.bundleSpec);try{return await vr("generator",e,t,r)}catch(s){if(s.isModelArmor)throw s;if(e!==is){console.warn(`Code Generator failed with ${e}, retrying with fallback model:`,s.message);try{return await vr("generator",is,t,r)}catch(i){throw i.isModelArmor?i:new Error(`Code Generator failed: primary (${e}): ${s.message} | fallback (${is}): ${i.message}`)}}throw new Error(`Code Generator failed: ${s.message}`)}}async function Fr(n,e=null){const t={...li("review",g.artifactBundle||g.bundleSpec),architect_output:e};try{return await vr("review",js,Nd(n),t)}catch(r){throw r.isModelArmor?r:new Error(`Code Review failed: ${r.message}`)}}function Ci(n,e){return n.isModelArmor?`${n.userTitle}: ${n.userMessage}`:`${e}: ${n.message}`}function Vs(n,e){const t=document.getElementById(`step${n}-item`),r=document.getElementById(`step${n}-status`);!t||!r||(t.classList.remove("active","completed","error"),r.classList.remove("running","completed","error"),e==="active"?(t.classList.add("active"),r.classList.add("running"),r.innerHTML=` + + `):e==="completed"?(t.classList.add("completed"),r.classList.add("completed"),r.innerHTML=` + + `):e==="error"?(t.classList.add("error"),r.classList.add("error"),r.innerHTML=` + + `):r.innerHTML=` + + `)}function X(n,e){const t=document.getElementById(`step${n}-loading`),r=document.getElementById(`step${n}-result`);e?(t.classList.remove("hidden"),r.classList.add("hidden"),Vs(n,"active")):(t.classList.add("hidden"),r.classList.remove("hidden"),Vs(n,"completed"))}function yf(n){const e=document.getElementById(`${n}-content`),t=document.getElementById(`${n}-chevron`);e.classList.contains("open")?(e.classList.remove("open"),t&&(t.style.transform="rotate(0deg)")):(e.classList.add("open"),t&&(t.style.transform="rotate(180deg)"))}function wf(n){Ee(parseInt(n.replace("step","")))}function Ee(n){for(let o=1;o<=3;o++){const a=document.getElementById(`step${o}-item`);a&&a.classList.remove("active")}const e=document.getElementById(`step${n}-item`);e&&e.classList.add("active"),wt();const t=document.getElementById("ready-state");t&&t.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${n}-content`);r&&r.classList.remove("hidden");const s=document.getElementById("stage-title"),i={1:"Prompt Architect",2:"Code Generator",3:"Code Review"};s&&(s.textContent=i[n]||"Active Workflow Stage")}function bf(n){const e=document.getElementById(n);if(!e)return;const t=e.dataset.raw||e.textContent;navigator.clipboard.writeText(t).then(()=>{Fe("Code Copied",{elementId:n});const r=e.closest(".code-container"),s=r==null?void 0:r.querySelector(".copy-btn");s&&(s.classList.add("copied"),s.innerHTML=' Copied!',setTimeout(()=>{s.classList.remove("copied"),s.innerHTML=' Copy'},2e3))}).catch(r=>{console.warn("Failed to copy to clipboard:",r)})}function qs(n){const e=document.getElementById("step1-model-label");e&&(e.textContent=ye(Bs));const t=Ys(n),r=document.getElementById("step2-model-label");r&&(t!==n?r.textContent=`${ye(n)} → ${ye(t)} (Free Tier)`:r.textContent=ye(n));const s=document.getElementById("step3-model-label");s&&(s.textContent=ye(js)),console.log(`Step 1 (Prompt Architect): ${ye(Bs)}`),console.log(t!==n?`Step 2 (Code Generator): ${ye(n)} → ${ye(t)} (Free Tier fallback)`:`Step 2 (Code Generator): ${ye(n)}`),console.log(`Step 3 (Code Review): ${ye(js)}`)}async function Ef(){if(console.log("runRefinement called"),g.isRunning)return;const n=document.getElementById("code-generator-model").value;g.isRunning=!0,xi("standardRegenerate",g.step2Result,g.step1Result);const e=document.querySelectorAll(".btn-refine-action");e.forEach(t=>{t.disabled=!0,t.innerHTML=` + + + Refining...`});try{const t=_i(),r=Ld({bundleSpec:g.step1Result,artifactBundle:JSON.stringify(g.artifactBundle||g.step2Result),bundleReview:g.step3Result,artifactId:t.id,userFeedback:"Fix the issues listed in the audit report."});Lr(),Ne(2),Ee(2),X(2,!0),g.step2Result=await $r(r,n),xr();const s=document.getElementById("step2-output"),i=Ut(g.step2Result);s.textContent=i,s.dataset.raw=i,X(2,!1),Ee(3),Ne(3),X(3,!0),g.step3Result=await Fr(g.step2Result,g.step1Result),Tr();const o=document.getElementById("step3-output");o.textContent=g.step3Result,X(3,!1),ct();const a=kr(g.step3Result);Dr(i,a)}catch(t){console.error("Refinement failed:",t),ct(),V(Ci(t,"Refinement failed"),"error")}finally{g.isRunning=!1,e.forEach(t=>{t.disabled=!1,t.textContent="Refine & Regenerate"}),bt()}}async function xi(n,e,t){const r=`${Ie}/connectFeedback`,s={type:n,code:e,input:t};try{const i=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)});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 Sf(){const n=document.getElementById("ff-error-paste-input");n&&(n.value="")}async function kf(){var s;const n=document.getElementById("ff-error-paste-input"),e=(s=n==null?void 0:n.value)==null?void 0:s.trim();if(!e){n==null||n.focus(),n==null||n.classList.add("ring-2","ring-red-400","border-red-300"),setTimeout(()=>n==null?void 0:n.classList.remove("ring-2","ring-red-400","border-red-300"),2e3);return}if(!g.step2Result){V("No generated code found. Please run the full pipeline first.","warning");return}if(g.isRunning)return;const t=document.getElementById("code-generator-model").value;g.isRunning=!0,xi("flutterflowError",g.step2Result,e);const r=document.getElementById("btn-fix-from-errors");r&&(r.disabled=!0,r.innerHTML=` + + Fixing…`);try{const i=Cl({bundleSpec:g.step1Result,artifactBundle:JSON.stringify(g.artifactBundle||g.step2Result),bundleReview:g.step3Result,userFeedback:e});oc(),Lr(),Ne(2),Ee(2),X(2,!0),g.step2Result=await $r(i,t),xr();const o=document.getElementById("step2-output"),a=Ut(g.step2Result);o.textContent=a,o.dataset.raw=a,X(2,!1),Ee(3),Ne(3),X(3,!0),g.step3Result=await Fr(g.step2Result,g.step1Result),Tr();const l=document.getElementById("step3-output");l.textContent=g.step3Result,X(3,!1),ct();const c=kr(g.step3Result);Dr(a,c),n&&(n.value="")}catch(i){console.error("Fix from errors failed:",i),ct(),V(Ci(i,"Failed to fix errors"),"error")}finally{g.isRunning=!1,r&&(r.disabled=!1,r.textContent="Fix Errors & Regenerate"),bt()}}async function Ks(){if(console.log("runThinkingPipeline called"),g.isRunning)return;localStorage.setItem("hasSeenWalkthrough","true");const n=document.getElementById("pipeline-input").value,e=document.getElementById("code-generator-model").value;if(!n.trim()){V("Please describe your FlutterFlow widget first.","warning");return}if(!await zf())return;const t=Ys(e);Fe("Pipeline Started",{selectedModel:e,effectiveModel:t,inputLength:n.length});const r=document.getElementById("btn-run-pipeline");g.isRunning=!0,af(),r.disabled=!0,r.innerHTML=` + + + Running...`,qs(t);try{wt();const s=document.getElementById("ready-state");s&&s.classList.add("hidden");const i=document.getElementById("paywall-exhausted");i&&i.classList.add("hidden"),Lr(),Ee(1),Ne(1),X(1,!0),g.step1Result=await _f(n),lf(),Fe("Prompt Architect Completed");const o=document.getElementById("step1-output"),a=Ut(g.step1Result);o.textContent=a,o.dataset.raw=a,X(1,!1),Ee(2),Ne(2),X(2,!0),g.step2Result=await $r(g.step1Result,t),xr(),Fe("Code Generator Completed");const l=document.getElementById("step2-output"),c=Ut(g.step2Result);l.textContent=c,l.dataset.raw=c,X(2,!1),Ee(3),Ne(3),X(3,!0),g.step3Result=await Fr(g.step2Result,g.step1Result),Tr(),Fe("Code Review Completed");const u=document.getElementById("step3-output");u.textContent=g.step3Result,X(3,!1),ct();const d=kr(g.step3Result);Dr(c,d),Bf(),Or()}catch(s){if(console.error("Pipeline failed:",s),ct(),s.isUsageLimit){const{count:u}=Mr();Mi(u,Fi(),{openModal:!0});return}Fe("Pipeline Failed",{error:s.message,effectiveModel:Ys(document.getElementById("code-generator-model").value)});let o={architect:1,generator:2,review:3}[s.pipelineStep]||1;!s.pipelineStep&&(s.message.includes("Claude")||s.message.includes("OpenAI")||s.message.includes("Code Generator"))?o=2:!s.pipelineStep&&s.message.includes("Code Review")&&(o=3),Ee(o);const a=document.getElementById(`step${o}-result`),l=document.getElementById(`step${o}-loading`),c=document.getElementById(`step${o}-output`);if(l&&l.classList.add("hidden"),a&&a.classList.remove("hidden"),c)if(s.isModelArmor)c.innerHTML=``;else{let u=s.message;s.message.includes("image input")?u=`This model doesn't support image input. Please use ${ye(bn)} for image-based requests or remove image references from your prompt.`:(s.message.includes("Load failed")||s.message.includes("CORS"))&&(u="API connection failed. This might be due to CORS restrictions or network issues. Please check your API key and try again."),c.innerHTML=`
    +

    Connection Error

    +

    ${$(u)}

    +
    +

    Check if API key is valid

    +

    Try using a different model

    +

    Ensure network allows API calls

    +
    +
    `}Vs(o,"error")}finally{g.isRunning=!1,r.disabled=!1,r.innerHTML=` + + + Run Pipeline`,bt()}}function If(){const n=document.getElementById("code-generator-model").value,e=[bn,"anthropic/claude-opus-5","openai/gpt-5.6-sol"].filter(r=>r!==n),t=prompt(`Retry with different model? + +Current: ${n} + +Options: +1. ${e[0]} +2. ${e[1]} + +Enter 1 or 2:`);t==="1"?(document.getElementById("code-generator-model").value=e[0],Ks()):t==="2"&&(document.getElementById("code-generator-model").value=e[1],Ks())}async function Cf(){var c,u,d;const n=yi();if(!n){V("No code to commit. Please run the pipeline first.","warning");return}const e=await le("flutterflow"),t=await le("flutterflow_project_id");if(!e||!t){V("FlutterFlow credentials not configured. Add your API Key and Project ID in settings.","warning"),gi();return}if(((u=(c=g.artifactBundle)==null?void 0:c.artifacts)==null?void 0:u.length)>1){await xf();return}const{artifactType:r,artifactName:s}=Gl(),i=Jl(n,{artifactType:r,artifactName:s}),o=df(i);if(!await pf(i,o)){console.log("User cancelled commit");return}Ni(),Fe("Deploy to FlutterFlow Started",{artifactType:r,artifactName:s});const l=await Zl(n,{artifactType:r,artifactName:s,pipelineResult:{step1Result:g.step1Result,selectedModel:(d=document.getElementById("code-generator-model"))==null?void 0:d.value}});Cn(),l.success?(Fe("Deploy to FlutterFlow Success",{artifactType:r,artifactName:s}),yr(l)):(Fe("Deploy to FlutterFlow Failed",{artifactType:r,artifactName:s,error:l.error}),wr(l))}async function xf(){const n=await le("flutterflow"),e=await le("flutterflow_project_id");if(!n||!e){V("FlutterFlow credentials not configured. Add your API Key and Project ID in settings.","warning"),gi();return}const t=tp(g.artifactBundle);if(t.errors.length>0){V(`Bundle validation failed: ${t.errors.join("; ")}`,"error");return}const r=new Map(t.fileEntries.map(a=>[a.fileName,{content:a.content,type:a.type,path:a.path}])),s=Pr(r),i={canProceed:s.valid&&t.errors.length===0,issues:[...t.errors,...s.errors],warnings:[...t.warnings,...s.warnings]};if(!i.canProceed){V(`Bundle validation failed: ${i.issues.join("; ")}`,"error");return}const o={content:t.fileEntries.map(a=>`// ${a.fileName} +${a.content}`).join(` + +`),fileName:`${t.fileEntries.length} files`,codeType:"bundle",artifactType:"Bundle",artifactName:t.title};Xf(o,i,t.dependencies,t)}function Tf(n){var s;let e=n.errorMap||new Map;!(e instanceof Map)&&typeof e=="object"&&(e=new Map(Object.entries(e)));let t=`
    +

    FlutterFlow Commit Failed

    +

    ${$(n.error)}

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

    Errors:

    +
      `;for(const[i,o]of e.entries()){const a=o.errorMessage||o;t+=`
    • + ${$(i)}: ${$(a)} +
    • `}t+="
    "}t+="
    ",t+=`
    + +
    `;const r=document.getElementById("step3-output");r&&(r.innerHTML=t,(s=document.getElementById("btn-regenerate-from-error"))==null||s.addEventListener("click",()=>{Rf(n.error,e)}))}async function Rf(n,e){if(g.isRunning)return;const t=document.getElementById("code-generator-model").value;g.isRunning=!0;const r=document.getElementById("btn-regenerate-from-error");r&&(r.disabled=!0,r.innerHTML=` + + Fixing...`);try{let s=`The previous code had the following errors when committing to FlutterFlow: + +`;if(e&&e.size>0)for(const[u,d]of e.entries()){const p=d.errorMessage||d;s+=`File: ${u} +Error: ${p} + +`}else s+=`${n} +`;const i=Cl({bundleSpec:g.step1Result,artifactBundle:JSON.stringify(g.artifactBundle||g.step2Result),bundleReview:g.step3Result,userFeedback:s});Lr(),Ne(2),Ee(2),X(2,!0),g.step2Result=await $r(i,t),xr();const o=document.getElementById("step2-output"),a=Ut(g.step2Result);o.textContent=a,o.dataset.raw=a,X(2,!1),Ee(3),Ne(3),X(3,!0),g.step3Result=await Fr(g.step2Result,g.step1Result),Tr();const l=document.getElementById("step3-output");l.textContent=g.step3Result,X(3,!1),ct();const c=kr(g.step3Result);Dr(a,c)}catch(s){console.error("Regeneration failed:",s),ct(),V(Ci(s,"Regeneration failed"),"error")}finally{g.isRunning=!1,r&&(r.disabled=!1,r.textContent="Fix Errors & Regenerate"),bt()}}async function Af(){const n=document.getElementById("ff-status-dot"),e=document.getElementById("ff-status-text");if(!n||!e)return;const t=await le("flutterflow"),r=await le("flutterflow_project_id");t&&r?(n.className="w-2 h-2 rounded-full bg-green-500",e.textContent="FlutterFlow credentials configured",e.className="text-green-600"):t||r?(n.className="w-2 h-2 rounded-full bg-yellow-500",e.textContent="FlutterFlow credentials incomplete",e.className="text-yellow-600"):(n.className="w-2 h-2 rounded-full bg-red-500",e.textContent="FlutterFlow credentials not configured",e.className="text-red-600")}async function Pf(n){try{const e=await fetch(`${Ie}/auth/send-magic-link`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:n})});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:n,message:e.message,stack:e.stack}),e}}async function $f(n){try{const t=await(await fetch(`${Ie}/auth/verify-magic-link`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:n})})).json();if(t.error||!t.email||!t.sessionToken)throw new Error(t.error||"Invalid or expired link");return t}catch(e){throw console.error("verifyMagicLink failed:",{message:e.message,stack:e.stack}),e}}async function Ff(n){try{const e=await fetch(`${Ie}/auth/refresh-session`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:n})});if(!e.ok)return console.error("refreshSession: non-OK response",{url:`${Ie}/auth/refresh-session`,status:e.status}),null;const t=await e.json();return t.error||!t.email||!t.sessionToken?(console.warn("refreshSession: validation failed",{error:t.error,hasEmail:!!t.email,hasToken:!!t.sessionToken}),null):t}catch(e){return console.error("refreshSession: fetch failed",{url:`${Ie}/auth/refresh-session`,message:e.message,stack:e.stack}),null}}function aa(n,e){const t=Xl(),r=(D.email||t.email)!==n;D.email=n,D.sessionToken=e,D.isVerified=!0,q=Ht({isLoading:!0}),localStorage.setItem(cr,JSON.stringify({email:n,sessionToken:e})),r&&Oi()}function Ti(){D.email=null,D.sessionToken=null,D.isVerified=!1,q=Ht({isResolved:!0}),localStorage.removeItem(cr),localStorage.removeItem(dr)}function Xl(){try{const n=localStorage.getItem(cr);if(!n)return{email:null,sessionToken:null};const e=JSON.parse(n);return!e.email||!e.sessionToken?{email:null,sessionToken:null}:e}catch(n){return console.warn("getStoredSession: failed to parse auth session:",n),localStorage.removeItem(cr),{email:null,sessionToken:null}}}async function Mf(){const e=new URLSearchParams(window.location.search).get("token");if(e){window.history.replaceState({},"",window.location.pathname);try{const{email:t,sessionToken:r}=await $f(e);aa(t,r)}catch(t){V(t.message||"Sign-in link invalid or expired.","error")}}else{const{email:t,sessionToken:r}=Xl();if(t&&r){const s=await Ff(r);s?aa(s.email,s.sessionToken):Ti()}}Ai()}function Ri(){const n=document.getElementById("signin-modal");n&&n.classList.add("open")}function Of(n){if(n&&n.target!==n.currentTarget)return;const e=document.getElementById("signin-modal");e&&e.classList.remove("open")}async function Nf(){var i;const n=document.getElementById("signin-email-input"),e=document.getElementById("signin-submit-btn"),t=document.getElementById("signin-message"),r=(i=n==null?void 0:n.value)==null?void 0:i.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){t&&(t.textContent="Please enter a valid email address.");return}e&&(e.disabled=!0,e.textContent="Sending…"),t&&(t.textContent="");try{await Pf(r),n&&(n.value=""),t&&(t.textContent=`Check your email — we sent a link to ${r}`),e&&(e.textContent="Sent!")}catch(o){console.error("handleMagicLinkRequest: sendMagicLink failed",{email:r,err:o}),t&&(t.textContent="Something went wrong. Please try again."),e&&(e.disabled=!1,e.textContent="Send Link")}}function Lf(){Ti(),Oi(),Ai(),Nr()}function Ai(){const n=D.isVerified&&!!D.email,e=document.getElementById("auth-signedout"),t=document.getElementById("auth-signedin"),r=document.getElementById("auth-guest-usage");e&&e.classList.toggle("hidden",n),t&&t.classList.toggle("hidden",!n),r&&r.classList.toggle("hidden",n);const s=document.getElementById("auth-user-email");s&&(s.textContent=D.email||""),Gn(),Nr()}async function Df(){try{if(typeof FingerprintJS>"u"){console.warn("resolveIdentity: FingerprintJS not loaded, skipping");return}const e=await(await FingerprintJS.load()).get(),t=e.visitorId,r=await fetch(Mp,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({fingerprint:e.visitorId,cookie_id:t})});if(!r.ok)throw new Error(`Identity check HTTP ${r.status}`);const s=await r.json();if(jn.userId=s.user_id,jn.status=s.status,jn.resolved=!0,sessionStorage.setItem(Fp,s.user_id),s.usage_count!==void 0){const i=_t(),o=s.usage_month||i,a=o===i?s.usage_count:0,l=Pi(),c=l.month===i?l.count:0;(a>=c||o>l.month)&&localStorage.setItem(Ot,JSON.stringify({count:a,month:i})),Or()}console.log(`Identity resolved: ${s.status} (${s.user_id.slice(0,8)}...) usage: ${s.usage_count??"n/a"}`)}catch(n){console.error("resolveIdentity failed:",n)}}function Pi(){const n=_t();try{const e=localStorage.getItem(Ot);return e?JSON.parse(e):{count:0,month:n}}catch(e){return console.warn("getUsageData: failed to parse usage storage",{key:Ot,month:n,err:e}),localStorage.removeItem(Ot),{count:0,month:n}}}function _t(){const n=new Date;return`${n.getFullYear()}-${String(n.getMonth()+1).padStart(2,"0")}`}function Mr(){const n=Pi();return n.month!==_t()?{count:0,month:_t()}:n}function Bf(){const e={count:Mr().count+1,month:_t()};return localStorage.setItem(Ot,JSON.stringify(e)),e}function $i(){return!!q.isLoading}function yt(){return!!q.isResolved}function jf(n){if(!n)return null;const e=String(n).toLowerCase().replace(/[^a-z0-9]+/g,"_");return e==="pro"||e==="professional_plan"?"professional":e==="power_developer"||e==="power_plan"?"power":Object.prototype.hasOwnProperty.call(ur,e)?e:null}function Uf(n){var e;return n&&((e=Object.entries(Nl).find(([,t])=>t===n))==null?void 0:e[0])||null}function Ln(...n){return n.find(e=>e!=null&&e!=="")}function Hf(...n){return n.find(e=>e&&typeof e=="object")||{}}function Wf(n){var u,d,p,f,m,v,_,C,k,T,I,y,P,A,R,ne,J,se,ie,me;const e=n.data&&typeof n.data=="object"?n.data:n,t=Hf(e.subscription,e.stripeSubscription,e.currentSubscription,(p=(d=(u=e.customer)==null?void 0:u.subscriptions)==null?void 0:d.data)==null?void 0:p[0],(m=(f=e.subscriptions)==null?void 0:f.data)==null?void 0:m[0],(v=e.subscriptions)==null?void 0:v[0]),r=e.metadata||t.metadata||((_=e.customer)==null?void 0:_.metadata)||{},s=Ln(e.priceId,e.price_id,e.stripePriceId,e.stripe_price_id,t.priceId,t.price_id,(C=t.plan)==null?void 0:C.id,(k=t.price)==null?void 0:k.id,(P=(y=(I=(T=t.items)==null?void 0:T.data)==null?void 0:I[0])==null?void 0:y.price)==null?void 0:P.id,(ne=(R=(A=t.items)==null?void 0:A[0])==null?void 0:R.price)==null?void 0:ne.id,(me=(ie=(se=(J=t.lines)==null?void 0:J.data)==null?void 0:se[0])==null?void 0:ie.price)==null?void 0:me.id),i=Ln(e.status,e.subscriptionStatus,e.subscription_status,t.status,"none"),o=jf(Ln(e.tier,e.plan,e.planId,e.plan_id,e.subscriptionTier,e.subscription_tier,e.product,e.productName,t.tier,t.plan,r.tier,r.plan)),a=Op.has(String(i).toLowerCase()),l=e.active===!0||e.isSubscribed===!0||e.subscribed===!0||e.hasSubscription===!0,c=o||Uf(s)||(a||l?"professional":"free");return Ht({tier:c,status:i,periodEnd:Ln(e.periodEnd,e.currentPeriodEnd,e.current_period_end,t.current_period_end,t.periodEnd,null),isResolved:!0})}function Fi(){return ur[q.tier]??ur.free}async function zf(){if(D.isVerified&&(!yt()||$i())&&(await Ql({force:!0}),Nr()),D.isVerified&&!yt())return V("Could not verify your subscription. Please refresh or try Manage billing.","error"),!1;const{count:n}=Mr(),e=Fi();if(n>=e)return Mi(n,e,{openModal:!0}),!1;const t=Math.floor(e*.8);if(n>=t){const r=e-n;V(`${r} run${r===1?"":"s"} remaining this month.`,"warning")}return!0}function os(){const n=document.getElementById("paywall-exhausted");n&&n.classList.add("hidden")}function Mi(n,e,t={}){const r=document.getElementById("walkthrough-modal");r&&r.classList.remove("open");const s=document.getElementById("ready-state");s&&s.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 c=document.getElementById("paywall-exhausted");if(!c){V(`You've used all ${e} runs for this month. Upgrade to continue.`,"error"),_r();return}const u=document.getElementById("paywall-exhausted-text");if(u){const p=q.tier;p==="free"?u.textContent=`You've used all ${e} free generations this month. Upgrade to Pro for 50 generations/month and access to all AI models.`:u.textContent=`You've used all ${e} generations this month on your ${p} plan. Your limit resets next month.`}const d=document.getElementById("paywall-signin-btn");d&&d.classList.toggle("hidden",D.isVerified),c.classList.remove("hidden"),t.openModal&&_r()}function Ys(n){return q.tier==="free"&&Un.includes(n)?bn:n}function Gf(){const n=document.getElementById("code-options-content"),e=document.getElementById("code-generator-model");if(!n||!e)return;const t=q.tier,s=!(D.isVerified&&!yt())&&t==="free";Array.from(e.options).forEach(o=>{const a=ye(o.value),l=Un.includes(o.value);o.textContent=l&&s?`${a} (PRO)`:a,o.disabled=!1}),s&&Un.includes(e.value)&&(e.value=bn),e.disabled=!1,Xo.has(e)||(e.addEventListener("change",()=>{yt()&&q.tier==="free"&&Un.includes(e.value)&&(e.value=bn,_r()),qs(e.value)}),Xo.add(e));let i=document.getElementById("model-selector-free-notice");s?(i||(i=document.createElement("p"),i.id="model-selector-free-notice",i.className="text-xs text-gray-400 mt-1",n.appendChild(i)),i.innerHTML='Free plan — Gemini only. '):i&&i.remove(),qs(e.value)}function Or(){const n=document.getElementById("usage-counter");if(!n)return;if(D.isVerified&&$i()){n.textContent="Checking plan…",n.className="text-xs text-gray-500",Gn(),os();return}if(D.isVerified&&!yt()){n.textContent="Plan check failed",n.className="text-xs text-red-600 font-medium",Gn(),os();return}const{count:e}=Mr(),t=Fi();n.textContent=`${e} / ${t} runs this month`;const r=t>0?e/t:0;n.className=r>=1?"text-xs text-red-600 font-medium":r>=.8?"text-xs text-yellow-600 font-medium":"text-xs text-gray-500",Gn(),e>=t&&!g.isRunning?Mi(e,t):os()}function Gn(){const n=document.getElementById("guest-usage-text");if(!n)return;const e=Pi(),t=e.month===_t()?e.count??0:0,r=ur.free;n.textContent=`${t} / ${r} generations used`}async function Ql(n={}){const e=n.force===!0;if(!D.isVerified||!D.sessionToken){q=Ht({isResolved:!0});return}q={...q,isLoading:!0,error:null};const t=localStorage.getItem(dr);if(!e&&t)try{const{data:r,email:s,ts:i,version:o}=JSON.parse(t);if(o===Qo&&s===D.email&&Date.now()-i<5*60*1e3){q={...r,isLoading:!1,isResolved:r.isResolved!==!1};return}}catch(r){console.warn("Failed to parse subscription cache:",r,"| raw value:",t)}try{const s=await(await fetch(`${Ie}/stripe/get-subscription`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:D.sessionToken,email:D.email})})).json();if(s.error){if(["unauthorized","invalid session","expired session"].some(o=>String(s.error).toLowerCase().includes(o))){Ti(),Ai();return}q=Ht({isResolved:!1,error:s.error});return}q=Wf(s),localStorage.setItem(dr,JSON.stringify({version:Qo,data:q,email:D.email,ts:Date.now()}))}catch(r){console.error("fetchSubscription failed:",r),q={...q,isLoading:!1,isResolved:!1,error:r.message}}}function Oi(){localStorage.removeItem(dr)}async function Vf(n){if(!D.isVerified||!D.sessionToken){ec(),Ri();return}if(!Nl[n]){V("Invalid plan selected.","error");return}const e=document.getElementById(`checkout-btn-${n}`);e&&(e.disabled=!0,e.textContent="Redirecting…");try{const r=await(await fetch(`${Ie}/stripe/create-checkout-session-intl`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tierId:n,sessionToken:D.sessionToken,currency:Ll()})})).json();if(r.error||!r.url)throw new Error(r.error||"Failed to create checkout session");const{url:s}=r;window.location.href=s}catch(t){console.error("startCheckout failed:",t),e&&(e.disabled=!1,e.textContent="Subscribe"),V("Could not start checkout. Please try again.","error")}}async function qf(){if(!D.isVerified||!D.sessionToken){Ri();return}const n=document.getElementById("manage-billing-btn");n&&(n.disabled=!0,n.textContent="Loading…");try{const t=await(await fetch(`${Ie}/stripe/create-portal-session`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:D.sessionToken})})).json();if(t.error||!t.url)throw new Error(t.error||"Failed to open billing portal");const{url:r}=t;window.location.href=r}catch(e){console.error("openCustomerPortal failed:",e),n&&(n.disabled=!1,n.textContent="Manage billing"),V("Could not open billing portal. Please try again.","error")}}async function vr(n,e,t,r={}){const i=new AbortController,o=setTimeout(()=>i.abort(),12e4);try{const a=await fetch($p,{method:"POST",headers:{"Content-Type":"application/json"},signal:i.signal,body:JSON.stringify({user_id:jn.userId,step:n,model:e,prompt:t,context:r})}),l=await a.json();if(a.status===429){l.serverCount!==void 0&&(localStorage.setItem(Ot,JSON.stringify({count:l.serverCount,month:_t()})),Or());const d=new Error(l.message||"Monthly usage limit reached. Upgrade to continue.");throw d.isUsageLimit=!0,d}const c=zd(l,n);if(c)throw c;if(console.log(`[BuildShip] ${n} response keys:`,Object.keys(l),"content type:",typeof l.content),!a.ok)throw new Error(`${l.message||l.error||"BuildShip pipeline error"} (HTTP ${a.status})`);let u=l.output||l.content;if(!u)throw new Error(`BuildShip returned no output for step "${n}"`);return Array.isArray(u)&&(u=u.map(d=>typeof d=="string"?d:d.text||"").join("")),typeof u!="string"&&(u=JSON.stringify(u)),u}catch(a){throw a.name==="AbortError"?new Error(`BuildShip ${n} timed out after ${12e4/1e3}s`):a instanceof TypeError?new Error(`BuildShip unreachable: ${a.message}`):a}finally{clearTimeout(o)}}function Kf(){const e=new URLSearchParams(window.location.search).get("checkout");e==="success"?(window.history.replaceState({},"",window.location.pathname),Oi(),V("Subscription active! Welcome aboard.","success")):e==="cancel"&&(window.history.replaceState({},"",window.location.pathname),V("Checkout cancelled.","info"))}function Nr(){const n=D.isVerified&&!!D.email,e=q.tier,t=n&&$i(),r=!n||yt(),s=document.getElementById("subscription-tier-badge");if(s){const a={free:"Free",professional:"Professional",power:"Power Developer"},l={free:"bg-gray-100 text-gray-600",professional:"bg-indigo-100 text-indigo-700",power:"bg-purple-100 text-purple-700",unresolved:"bg-red-50 text-red-600"};s.textContent=t?"Checking…":r?a[e]||"Free":"Plan unavailable",s.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",!n||t||!r||e!=="free");const o=document.getElementById("manage-billing-btn");o&&o.classList.toggle("hidden",!n||t||r&&e==="free"),Yf(r?e:null),Gf(),Or()}function Yf(n){const e=["bg-gray-100","text-gray-500","cursor-default"];Object.entries({professional:{btnId:"checkout-btn-professional",defaultText:"Subscribe"},power:{btnId:"checkout-btn-power",defaultText:"Subscribe"}}).forEach(([s,{btnId:i,defaultText:o}])=>{const a=document.getElementById(i);a&&(s===n?(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",n!=="free")}function Js(){const n=Ll(),e=document.getElementById("pro-price"),t=document.getElementById("power-price"),r=document.getElementById("pro-price-note"),s=document.getElementById("power-price-note");e&&(e.textContent=ta(ea.professional,n)),t&&(t.textContent=ta(ea.power,n));const i="billed monthly";r&&(r.textContent=i),s&&(s.textContent=i)}function _r(){Js();const n=document.getElementById("pricing-modal");n&&n.classList.add("open"),Lp().then(()=>Js())}function ec(n){if(n&&n.target!==n.currentTarget)return;const e=document.getElementById("pricing-modal");e&&e.classList.remove("open")}function V(n,e="info"){const t={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 ${t[e]||t.info}`,r.textContent=n,document.body.appendChild(r),setTimeout(()=>{r.style.opacity="0",setTimeout(()=>r.remove(),300)},3500)}document.addEventListener("DOMContentLoaded",async()=>{hljs.configure({tabReplace:" ",classPrefix:"hljs-"}),Jf(),await Mf(),Kf(),await Ql(),Nr(),Js(),await cf(),rf();const n=document.getElementById("flutterflow-endpoint-select");if(n){const t=An();n.value=t}Wl(),Df();const e=document.getElementById("pipeline-input");e&&(e.addEventListener("input",()=>{Je===2&&e.value.trim().length>0&&(mi(),Ir())}),e.addEventListener("blur",()=>{const t=document.getElementById("walkthrough-modal");Je===2&&t&&t.classList.add("open")}),e.addEventListener("keydown",t=>{if(t.key==="Tab"){const r=document.getElementById("walkthrough-modal");Je===2&&r&&setTimeout(()=>{r.classList.add("open")},100)}})),window.addEventListener("commitStateChange",t=>{const{state:r}=t.detail;th(r),r===N.PREPARING||r===N.VALIDATING||r===N.PUSHING?Ni():(r===N.SUCCESS||r===N.ERROR)&&setTimeout(Cn,1e3)})});function Jf(){const n=document.getElementById("preview-frame-container");n&&(n.style.display="")}function Zf(){const n=document.getElementById("welcome-video-player");n&&(n.addEventListener("click",wt),document.addEventListener("keydown",wt))}function wt(){const n=document.getElementById("preview-frame-container"),e=document.getElementById("main-stage-container"),t=document.getElementById("ready-state");n&&(n.style.display="none"),e&&e.classList.add("visible"),t&&t.classList.remove("hidden");const r=document.getElementById("welcome-video-player");r&&r.removeEventListener("click",wt),document.removeEventListener("keydown",wt),Wl()}let fn=null;function Xf(n,e,t,r=null){fn={codeInfo:n,checks:e,deps:t,bundlePlan:r},document.getElementById("confirm-file-name").textContent=n.fileName,document.getElementById("confirm-artifact-type").textContent=n.artifactType,document.getElementById("confirm-file-size").textContent=`${(n.content.length/1024).toFixed(1)} KB`,document.getElementById("confirm-line-count").textContent=r?`${r.fileEntries.length} files`:n.content.split(` +`).length,le("flutterflow_project_id").then(c=>{document.getElementById("confirm-project-id").textContent=c||"Not configured"});const s=document.getElementById("confirm-deps-list"),i=document.getElementById("confirm-deps-section");t&&Object.keys(t).length>0?(s.innerHTML=Object.entries(t).map(([c,u])=>`
  • • ${Ye(c)}: ${Ye(u)}
  • `).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(c=>`
  • • ${Ye(c)}
  • `).join(""),a.classList.remove("hidden")):a.classList.add("hidden"),document.getElementById("confirm-code-preview").textContent=n.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 tc(n){if(n&&n.target!==n.currentTarget)return;const e=document.getElementById("commit-confirm-modal");e&&e.classList.remove("open"),fn=null}function Qf(n){if(n&&n.target!==n.currentTarget)return;const e=document.getElementById("commit-success-modal");e&&e.classList.remove("open");const t=["success-message","success-project-id","success-file-name","success-artifact-type","success-time","success-size"];for(const i of t){const o=document.getElementById(i);o&&(o.textContent="")}const r=document.getElementById("success-warnings-section");r&&r.classList.add("hidden");const s=document.getElementById("success-warnings-list");s&&(s.innerHTML="")}function yr(n){var f,m,v,_;const e=(C,k)=>{const T=document.getElementById(C);T&&(T.textContent=k||"")},t=((f=n.metadata)==null?void 0:f.fileName)||"",r=((m=n.metadata)==null?void 0:m.projectId)||"",s=((v=n.metadata)==null?void 0:v.artifactType)||"",i=n.elapsedTime?`${(n.elapsedTime/1e3).toFixed(1)}s`:"",o=(_=n.metadata)!=null&&_.codeSize?`${(n.metadata.codeSize/1024).toFixed(1)} KB`:"";e("success-message",n.message||"Code committed successfully!"),e("success-project-id",r),e("success-file-name",t),e("success-artifact-type",s),e("success-time",i),e("success-size",o);const a=n.addedDependencies||[],l=document.getElementById("success-deps-row");l&&l.classList.toggle("hidden",a.length===0),e("success-deps",a.join(", "));const c=document.getElementById("success-open-ff-link");c&&r&&(c.href=`https://app.flutterflow.io/project/${r}`);const u=document.getElementById("success-warnings-section"),d=document.getElementById("success-warnings-list");n.warnings&&n.warnings.length>0&&u&&d&&(d.innerHTML=n.warnings.map(([C,k])=>`
  • ${$(C)}: ${$(String(k))}
  • `).join(""),u.classList.remove("hidden"));const p=document.getElementById("commit-success-modal");p&&p.classList.add("open")}function wr(n){Cn(),Tf(n)}function eh(){const n=document.getElementById("code-preview-content"),e=document.getElementById("code-preview-chevron");n.classList.contains("hidden")?(n.classList.remove("hidden"),e.style.transform="rotate(90deg)"):(n.classList.add("hidden"),e.style.transform="rotate(0deg)")}function Ni(){const n=document.getElementById("commit-progress-overlay");n&&(n.classList.add("open"),nc(25,"Preparing code...","Step 1 of 4"))}function Cn(){const n=document.getElementById("commit-progress-overlay");n&&n.classList.remove("open")}function nc(n,e,t){const r=document.getElementById("commit-progress-bar"),s=document.getElementById("progress-message"),i=document.getElementById("progress-detail");r&&(r.style.width=`${n}%`),s&&(s.textContent=e),i&&(i.textContent=t)}function th(n){const t={[N.IDLE]:{percent:0,message:"Ready",detail:""},[N.PREPARING]:{percent:25,message:"Preparing code...",detail:"Step 1 of 4"},[N.VALIDATING]:{percent:50,message:"Validating...",detail:"Step 2 of 4"},[N.PUSHING]:{percent:75,message:"Pushing to FlutterFlow...",detail:"Step 3 of 4"},[N.SUCCESS]:{percent:100,message:"Complete!",detail:"Step 4 of 4"},[N.ERROR]:{percent:100,message:"Failed",detail:"Error occurred"}}[n];t&&nc(t.percent,t.message,t.detail)}async function nh(){var i,o;if(!fn){console.error("No pending commit data");return}const n=fn;if(tc(),Ni(),n.bundlePlan){const a=await vf(n.bundlePlan,{pipelineResult:{step1Result:g.step1Result,selectedModel:(i=document.getElementById("code-generator-model"))==null?void 0:i.value}});Cn(),a.success?yr(a):wr(a);return}const{codeInfo:e}=n,{artifactType:t,artifactName:r}=Gl(),s=await Zl(e.content,{artifactType:t,artifactName:r,pipelineResult:{step1Result:g.step1Result,selectedModel:(o=document.getElementById("code-generator-model"))==null?void 0:o.value}});Cn(),s.success?yr(s):wr(s),fn=null}window.runThinkingPipeline=Ks;window.toggleStep=wf;window.toggleSection=yf;window.selectWorkflowStep=Ee;window.copyCode=bf;window.retryWithDifferentModel=If;window.openApiKeysModal=gi;window.closeApiKeysModal=Ul;window.closeWalkthroughModal=Zp;window.openWalkthroughModal=Jp;window.advanceWalkthrough=mi;window.commitToFlutterFlow=mf;function rh(){const n=document.getElementById("pipeline-input");n&&n.focus()}function sh(){const n=document.getElementById("advanced-settings");n&&(n.open=!0);const e=document.getElementById("code-generator-model");e&&(e.scrollIntoView({behavior:"smooth",block:"center"}),e.focus(),e.click())}window.focusPromptInput=rh;window.openModelSelector=sh;window.saveApiKeys=ef;window.clearAllApiKeys=tf;window.toggleKeyVisibility=of;window.handleWelcomeVideoEnd=Zf;window.dismissWelcomeVideo=wt;window.initiateCommitToFlutterFlow=Cf;window.updateFlutterFlowCredentialStatus=Af;window.closeCommitConfirmModal=tc;window.closeCommitSuccessModal=Qf;window.showCommitSuccessModal=yr;window.showCommitFailureModal=wr;window.toggleCodePreview=eh;window.confirmCommitToFlutterFlow=nh;window.runRefinement=Ef;window.regenerateFromPastedErrors=kf;window.clearErrorInput=Sf;window.setFlutterFlowEndpoint=Yp;window.getFlutterFlowEndpoint=An;window.openSignInModal=Ri;window.closeSignInModal=Of;window.handleMagicLinkRequest=Nf;window.handleSignOut=Lf;window.startCheckout=Vf;window.openCustomerPortal=qf;window.openPricingModal=_r;window.closePricingModal=ec;let Nt=null,rc=null;const la=120;function Lr(){const n=document.getElementById("pipeline-progress"),e=document.getElementById("results-view"),t=document.getElementById("ready-state");t&&t.classList.add("hidden"),e&&e.classList.remove("visible"),document.body.classList.remove("results-fullscreen","results-with-sidebar"),n&&n.classList.add("visible"),rc=Date.now();for(let r=1;r<=3;r++){const s=document.getElementById(`pdot-${r}`);s&&(s.className="progress-dot")}Ne(1),ih()}function Ne(n){const e={1:"Analyzing your prompt...",2:"Generating Dart code...",3:"Running code audit..."},t={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"),s=document.getElementById("progress-substep-text");r&&(r.textContent=e[n]||e[1]),s&&(s.textContent=t[n]||t[1]);for(let i=1;i<=3;i++){const o=document.getElementById(`pdot-${i}`);o&&(i{const n=(Date.now()-rc)/1e3,e=document.getElementById("progress-elapsed"),t=document.getElementById("pipeline-progress-fill");e&&(e.textContent=`${Math.floor(n)}s`);const r=n/la*100,s=Math.min(95,r*(1-Math.exp(-n/(la*.6)))*1.2);t&&(t.style.width=`${s}%`)},250)}function ct(){Nt&&(clearInterval(Nt),Nt=null);const n=document.getElementById("pipeline-progress-fill");n&&(n.style.width="100%");for(let e=1;e<=3;e++){const t=document.getElementById(`pdot-${e}`);t&&(t.className="progress-dot completed")}setTimeout(()=>{const e=document.getElementById("pipeline-progress");e&&e.classList.remove("visible"),n&&(n.style.width="0%")},400)}function zt(n,e=""){const t={pass:'',warning:'',fail:''};return``}function sc(n){return{pass:"Passed review",warning:"Needs attention",fail:"Blocking issues"}[n]||"Needs attention"}function oh(){return mp({bundle:g.artifactBundle,reviewResult:g.step3Result})}function ah(n){return` +
    + ${zt(n.severity)} +
    +
    ${$(n.message)}
    + ${n.suggestion?`
    ${$(n.suggestion)}
    `:""} + ${$(n.source)} +
    +
    + `}function lh(n){return` +
  • +
    + ${$(n.title)} + ${n.detail&&n.detail!==n.title?`

    ${$(n.detail)}

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

    ${zt("warning")} Complete in FlutterFlow

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

    ${$(n.summary)}

    + ${o} + ${a} +
    +
    + +
    + Is the generated code correct? +
    + + +
    +
    +
    +
    + `}function uh(n){var l,c,u;const e=n.artifacts.find(d=>d.id===g.selectedArtifactId)||n.artifacts[0];if(!e)return"";const t={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(ah).join(""):`
    ${zt(t.icon)} ${$(t.message)}
    `,s=(l=e.dependencies)!=null&&l.length?e.dependencies.map(d=>` +
  • ${$(d.name)}${d.version?` ${$(d.version)}`:""}${d.reason?`

    ${$(d.reason)}

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

    ${$(d.description)}

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

    ${$(e.artifactName)}

    + ${e.description?`

    ${$(e.description)}

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

    Code Review findings

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

    Manual FlutterFlow steps for this file

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

    Dependencies

    +
      ${s}
    +
    +
    +

    Deployment

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

    Public API

    +
    ${o}
    +
    +
    +

    Imports

    +
    ${i}
    +
    +
    +

    Relationships

    +
      ${a}
    +
    +
    + `}function dh(n){const e=document.getElementById("bundle-strip"),t=document.getElementById("results-summary-tab"),r=document.getElementById("artifact-tabs"),s=document.getElementById("results-file-count");if(t&&t.classList.toggle("active",g.resultsViewMode==="summary"),!n.artifacts.length){s&&(s.textContent="0 files"),e&&e.classList.remove("visible"),r&&(r.innerHTML="");return}if(s){const i=n.artifacts.length;s.textContent=`${i} ${i===1?"file":"files"}`}r&&(r.innerHTML=n.artifacts.map(i=>` + + `).join(""),r.onclick=i=>{var a;const o=i.target.closest(".artifact-tab");(a=o==null?void 0:o.dataset)!=null&&a.artifactId&&ic(o.dataset.artifactId)}),e&&e.classList.add("visible")}function Li(){document.body.classList.add("results-fullscreen"),document.body.classList.add("results-with-sidebar");const n=document.getElementById("results-view"),e=document.getElementById("results-code-output"),t=document.getElementById("results-audit-output"),r=document.getElementById("results-summary-detail"),s=document.getElementById("artifact-results-split"),i=oh(),o=yi();if(ch(i),dh(i),e&&(e.textContent=""),e){const a=Ol(o);e.innerHTML=a}t&&(t.innerHTML=uh(i)),r&&r.classList.toggle("hidden",g.resultsViewMode!=="summary"),s&&s.classList.toggle("hidden",g.resultsViewMode!=="file"),n&&n.classList.add("visible")}function Dr(n,e){g.selectedArtifactId||(g.selectedArtifactId=ar(g.artifactBundle).id),g.resultsViewMode="summary",document.body.classList.add("results-fullscreen");const t=document.getElementById("step3-output");t&&(t.textContent=""),Li(),bt();const r=document.getElementById("btn-feedback-up"),s=document.getElementById("btn-feedback-down");r&&(r.className="feedback-btn"),s&&(s.className="feedback-btn")}function ic(n){g.selectedArtifactId=n,g.resultsViewMode="file",Li()}function ph(){g.resultsViewMode="summary",Li()}function fh(){const n=document.getElementById("btn-copy-results"),e=yi();navigator.clipboard.writeText(e).then(()=>{if(n){n.classList.add("copied");const t=n.querySelector("span");if(t){const r=t.textContent;t.textContent="Copied!",setTimeout(()=>{n.classList.remove("copied"),t.textContent=r},2e3)}}})}function hh(n){const e=document.getElementById("btn-feedback-up"),t=document.getElementById("btn-feedback-down");n==="up"?(e.classList.toggle("active-up"),t.classList.remove("active-down")):(t.classList.toggle("active-down"),e.classList.remove("active-up"));const r=n==="up"?"thumbsUp":"thumbsDown";xi(r,g.step2Result,g.step1Result),Fe("Generation Feedback",{feedback:r})}function gh(){const n=document.getElementById("error-input-panel");if(n){n.classList.remove("hidden"),n.style.display="flex";const e=document.getElementById("ff-error-paste-input");e&&setTimeout(()=>e.focus(),100)}}function oc(){const n=document.getElementById("error-input-panel");n&&(n.classList.add("hidden"),n.style.display="none")}window.copyResultsCode=fh;window.selectArtifact=ic;window.selectResultsSummary=ph;window.submitResultsFeedback=hh;window.showErrorInputPanel=gh;window.hideErrorInputPanel=oc; diff --git a/dist/index.html b/dist/index.html index 7f20bf9..2e46430 100644 --- a/dist/index.html +++ b/dist/index.html @@ -4,6 +4,7 @@ FlutterFlow Custom Code Connect + @@ -640,43 +641,13 @@ } .bundle-strip { display: none; - grid-template-columns: minmax(220px, 0.7fr) minmax(0, 1.3fr); - gap: 16px; - padding: 14px 24px; + padding: 12px 24px; border-bottom: 1px solid var(--border); - background: #fff; + background: #f8fafc; flex-shrink: 0; } .bundle-strip.visible { - display: grid; - } - .bundle-summary { - display: grid; - grid-template-columns: repeat(3, minmax(0, 1fr)); - gap: 8px; - } - .bundle-stat { - min-width: 0; - padding: 10px; - border: 1px solid var(--border); - border-radius: 8px; - background: #fafbfc; - } - .bundle-stat-value { display: block; - font-size: 18px; - font-weight: 700; - color: var(--navy); - line-height: 1.1; - } - .bundle-stat-label { - display: block; - margin-top: 4px; - font-size: 10px; - font-weight: 700; - color: var(--sublabel); - text-transform: uppercase; - letter-spacing: 0.08em; } .artifact-tabs { display: flex; @@ -685,17 +656,20 @@ padding-bottom: 2px; } .artifact-tab { + display: flex; flex: 0 0 auto; min-width: 168px; max-width: 240px; text-align: left; padding: 10px 12px; border: 1px solid var(--border); - border-radius: 8px; + border-radius: 10px; background: #fff; color: var(--navy); cursor: pointer; transition: border-color 0.15s ease, background 0.15s ease, box-shadow 0.15s ease; + align-items: center; + gap: 9px; } .artifact-tab:hover { border-color: #cbd5e1; @@ -706,6 +680,17 @@ background: #eef2ff; box-shadow: inset 0 0 0 1px #6366f1; } + .artifact-tab-status { + width: 26px; + height: 26px; + display: grid; + place-items: center; + flex: 0 0 26px; + border-radius: 8px; + } + .artifact-tab-status.status-pass { color: #15803d; background: #dcfce7; } + .artifact-tab-status.status-warning { color: #b45309; background: #fef3c7; } + .artifact-tab-status.status-fail { color: #b91c1c; background: #fee2e2; } .artifact-tab-name { display: block; overflow: hidden; @@ -723,6 +708,124 @@ font-size: 11px; color: var(--sublabel); } + .review-status-icon { + width: 16px; + height: 16px; + flex: 0 0 16px; + } + .manual-step { + display: flex; + align-items: flex-start; + gap: 9px; + color: #78350f; + font-size: 12px; + } + .manual-step p { margin-top: 3px; color: #92400e; line-height: 1.45; } + .results-summary-detail { + flex: 1; + min-height: 0; + overflow-y: auto; + padding: 20px 24px; + background: #fff; + } + .file-review-section h4 { + margin-bottom: 9px; + color: #475569; + font-size: 10px; + font-weight: 800; + letter-spacing: 0.07em; + text-transform: uppercase; + } + .review-finding { + display: grid; + grid-template-columns: 18px minmax(0, 1fr); + gap: 9px; + padding: 10px 11px; + border: 1px solid #e2e8f0; + border-radius: 9px; + font-size: 12px; + } + .review-finding + .review-finding { margin-top: 8px; } + .review-finding-pass { color: #15803d; border-color: #bbf7d0; background: #f0fdf4; } + .review-finding-warning { color: #b45309; border-color: #fde68a; background: #fffbeb; } + .review-finding-fail { color: #b91c1c; border-color: #fecaca; background: #fef2f2; } + .review-finding-message { color: #334155; font-weight: 700; line-height: 1.4; } + .review-finding-suggestion { margin-top: 4px; color: #64748b; line-height: 1.45; } + .review-source { + display: inline-block; + margin-top: 5px; + color: #94a3b8; + font-size: 9px; + font-weight: 700; + text-transform: uppercase; + } + .review-empty-state { + display: flex; + align-items: center; + gap: 8px; + padding: 12px; + border-radius: 9px; + color: #166534; + background: #f0fdf4; + font-size: 12px; + font-weight: 700; + } + .review-empty-warning { + color: #92400e; + background: #fffbeb; + } + .review-empty-fail { + color: #b91c1c; + background: #fef2f2; + } + .review-muted { color: #94a3b8; font-size: 11px; } + .deploy-order-list, + .relationship-list, + .dependency-list, + .file-relationship-list { + margin: 0; + padding: 0; + list-style: none; + } + .deploy-order-list { display: flex; flex-wrap: wrap; gap: 7px; } + .deploy-order-list li { + display: flex; + align-items: center; + gap: 6px; + padding: 6px 8px; + border-radius: 7px; + background: #eef2ff; + color: #4338ca; + font-size: 10px; + font-weight: 700; + } + .deploy-order-list li span { + display: grid; + width: 17px; + height: 17px; + place-items: center; + border-radius: 5px; + color: #fff; + background: #6366f1; + font-size: 9px; + } + .relationship-list { display: flex; flex-direction: column; gap: 7px; } + .relationship-list li { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 6px; + color: #475569; + font-size: 11px; + } + .relationship-list li > span { + padding: 2px 5px; + border-radius: 5px; + background: #f1f5f9; + color: #64748b; + font-size: 9px; + } + .relationship-list li p { width: 100%; color: #94a3b8; } .btn-header-action { display: flex; align-items: center; @@ -750,12 +853,12 @@ box-shadow: 0 4px 14px -2px rgba(245,158,11,0.5); } .btn-refine-regen { - background: linear-gradient(135deg, #6366f1 0%, #4f46e5 100%); + background: linear-gradient(135deg, #f97316 0%, #ea580c 100%); color: #fff; - box-shadow: 0 2px 8px -2px rgba(99,102,241,0.4); + box-shadow: 0 2px 8px -2px rgba(249,115,22,0.4); } .btn-refine-regen:hover:not(:disabled) { - box-shadow: 0 4px 14px -2px rgba(99,102,241,0.5); + box-shadow: 0 4px 14px -2px rgba(249,115,22,0.5); } .results-action-bar { @@ -777,12 +880,20 @@ flex-grow: 1.45; } .btn-deploy-results { - background: linear-gradient(135deg, #f97316 0%, #ea580c 100%); + background: linear-gradient(135deg, #6366f1 0%, #4f46e5 100%); color: #fff; - box-shadow: 0 2px 8px -2px rgba(249,115,22,0.4); + box-shadow: 0 2px 8px -2px rgba(99,102,241,0.4); } .btn-deploy-results:hover:not(:disabled) { - box-shadow: 0 4px 14px -2px rgba(249,115,22,0.5); + box-shadow: 0 4px 14px -2px rgba(99,102,241,0.5); + } + .flutterflow-deploy-icon { + width: 18px; + height: 18px; + flex: 0 0 18px; + object-fit: contain; + filter: grayscale(1) invert(1) contrast(10); + mix-blend-mode: screen; } .results-split { @@ -853,62 +964,512 @@ color: #e2e8f0; } .panel-audit-wrap { - padding: 24px; + padding: 18px; } - - .results-footer { + .file-review-header { + display: flex; + align-items: flex-start; + justify-content: space-between; + gap: 16px; + padding: 15px; + border: 1px solid #e2e8f0; + border-left-width: 4px; + border-radius: 11px; + background: #f8fafc; + } + .file-review-pass { border-left-color: #22c55e; } + .file-review-warning { border-left-color: #f59e0b; } + .file-review-fail { border-left-color: #ef4444; } + .file-review-status { display: flex; align-items: center; + gap: 5px; + color: #64748b; + font-size: 9px; + font-weight: 800; + letter-spacing: 0.07em; + text-transform: uppercase; + } + .file-review-header h3 { + margin-top: 5px; + color: var(--navy); + font-size: 15px; + font-weight: 800; + } + .file-review-header p { + margin-top: 5px; + color: #64748b; + font-size: 11px; + line-height: 1.45; + } + .file-review-meta { + display: flex; + flex-direction: column; + align-items: flex-end; + gap: 4px; + color: #64748b; + font-size: 9px; + font-weight: 700; + } + .file-review-meta span { + max-width: 220px; + overflow: hidden; + padding: 3px 6px; + border-radius: 5px; + background: #fff; + text-overflow: ellipsis; + white-space: nowrap; + } + .file-review-section { + margin-top: 14px; + padding: 14px; + border: 1px solid #e2e8f0; + border-radius: 11px; + background: #fff; + } + .file-manual-section { + border-color: #fde68a; + background: #fffbeb; + } + .file-manual-section ol { + display: flex; + flex-direction: column; + gap: 9px; + margin: 0; + padding: 0; + list-style: none; + } + .file-detail-grid { + display: grid; + grid-template-columns: 1fr 1fr; + gap: 12px; + } + .dependency-list { display: flex; flex-direction: column; gap: 7px; } + .dependency-list li { + color: #475569; + font-size: 11px; + } + .dependency-list code, + .code-chip-list code { + display: inline-block; + padding: 4px 6px; + border: 1px solid #e2e8f0; + border-radius: 6px; + color: #4338ca; + background: #f8fafc; + font-family: "DM Mono", monospace; + font-size: 10px; + } + .dependency-list p { margin-top: 4px; color: #64748b; line-height: 1.4; } + .file-deploy-facts { display: flex; flex-direction: column; gap: 7px; } + .file-deploy-facts div { + display: flex; justify-content: space-between; - padding: 16px 24px; + gap: 12px; + color: #64748b; + font-size: 10px; + } + .file-deploy-facts dt { font-weight: 700; } + .file-deploy-facts dd { color: #334155; text-align: right; } + .code-chip-list { display: flex; flex-wrap: wrap; gap: 6px; } + .file-relationship-list { display: flex; flex-direction: column; gap: 7px; } + .file-relationship-list li { color: #475569; font-size: 11px; } + .file-relationship-list li p { margin-top: 3px; color: #94a3b8; } + body.results-fullscreen .sidebar { + display: flex; + } + body.results-fullscreen .main-content { + display: block; + width: auto; + height: 100dvh; + padding: 0; + } + body.results-fullscreen .main-stage { + inset: 0; + border-radius: 0; + box-shadow: none; + } + body.results-fullscreen.results-with-sidebar .sidebar { + display: flex; + } + body.results-fullscreen.results-with-sidebar .main-content { + width: auto; + height: 100dvh; + padding: 0; + } + body.results-fullscreen.results-with-sidebar .main-stage { + inset: 0; + border-radius: 0; + box-shadow: none; + } + body.results-fullscreen .results-header { + padding: 14px 28px; + } + .results-header-left { + display: flex; + align-items: center; + } + body.results-fullscreen .bundle-strip { + padding: 10px 28px; + } + body.results-fullscreen .artifact-tab { + min-width: 0; + max-width: 260px; + padding: 8px 11px; + border-radius: 8px; + } + body.results-fullscreen .artifact-tab-status { + width: 22px; + height: 22px; + flex-basis: 22px; + border-radius: 6px; + } + body.results-fullscreen .artifact-tab-name { font-size: 12px; } + body.results-fullscreen .artifact-tab-meta { margin-top: 1px; font-size: 9px; } + .file-technical-details { + margin-top: 18px; border-top: 1px solid var(--border); + } + .file-technical-details > summary { + padding: 14px 0; + color: #64748b; + cursor: pointer; + font-size: 11px; + font-weight: 700; + } + .file-technical-details .file-review-section:first-of-type { margin-top: 0; } + + /* Results hierarchy: review first, files second. */ + body.results-fullscreen .results-header { + min-height: 72px; + padding: 14px 36px; + } + body.results-fullscreen .results-header-left { + display: flex; + align-items: center; + gap: 16px; + } + body.results-fullscreen .results-header-left h2 { + color: #111827; + font-family: "Delight", "Outfit", sans-serif; + font-size: 28px; + font-weight: 650; + letter-spacing: -0.025em; + } + body.results-fullscreen .results-summary-detail { + flex: 1 1 auto; + max-height: none; + padding: 28px 36px; + overflow-y: auto; + border-bottom: 1px solid #e5e7eb; + background: #f8fafc; + } + .review-summary { + display: grid; + grid-template-columns: minmax(0, 1fr) 184px; + gap: 36px; + width: 100%; + max-width: none; + margin: 0 auto; + padding: 24px; + border: 1px solid #e2e8f0; + border-radius: 12px; background: #fff; - flex-shrink: 0; + box-shadow: 0 8px 24px -20px rgba(15, 23, 42, 0.28); + } + .review-summary-copy { min-width: 0; } + .results-file-count { + padding: 6px 9px; + border-radius: 6px; + color: #6b7280; + background: #f3f4f6; + font-size: 12px; + font-weight: 700; + } + .review-summary-text { + max-width: 900px; + margin-top: 0; + color: #374151; + font-size: 14px; + line-height: 1.65; + white-space: pre-line; } - .results-footer-left { + .review-score { display: flex; - gap: 10px; + width: 100%; + min-height: 164px; + padding: 18px 16px; + flex-direction: column; + align-items: center; + justify-content: center; + align-self: start; + border: 1px solid; + border-radius: 10px; + text-align: center; + } + .review-score-column { + width: 184px; + align-self: start; + } + .review-score-pass { color: #166534; border-color: #86efac; background: #f0fdf4; } + .review-score-warning { color: #9a3412; border-color: #fdba74; background: #fff7ed; } + .review-score-fail { color: #991b1b; border-color: #fca5a5; background: #fef2f2; } + .review-score-neutral { color: #475569; border-color: #cbd5e1; background: #f8fafc; } + .review-score-label { + font-size: 11px; + font-weight: 800; + letter-spacing: 0.1em; + text-transform: uppercase; + } + .review-score strong { + margin-top: 3px; + font-family: "Delight", "Outfit", sans-serif; + font-size: 58px; + font-weight: 700; + line-height: 0.95; + letter-spacing: -0.05em; + } + .review-score-total { + margin-top: 5px; + font-size: 11px; + font-weight: 600; + opacity: 0.72; + } + .review-score-status { + margin-top: 12px; + font-size: 11px; + font-weight: 800; + text-transform: uppercase; + } + .summary-manual-callout { + margin-top: 18px; + padding: 13px 15px; + border: 1px solid #fed7aa; + border-radius: 8px; + background: #fff7ed; } - .results-footer-right { + .summary-manual-callout h3 { display: flex; align-items: center; - gap: 16px; + gap: 7px; + color: #9a3412; + font-size: 13px; + font-weight: 750; + } + .summary-manual-callout h3 .review-status-icon { + width: 16px; + height: 16px; + } + .summary-manual-callout ul { + display: grid; + gap: 7px; + margin: 10px 0 0; + padding: 0 0 0 23px; + list-style: disc; + } + .summary-manual-callout li { + color: #7c2d12; + font-size: 14px; + line-height: 1.45; } - .results-footer-right .feedback-label { + .summary-manual-callout li strong { font-weight: 700; } + .summary-manual-callout li span { display: block; margin-top: 2px; color: #9a3412; } + .summary-findings { + display: grid; + gap: 7px; + margin: 14px 0 0; + padding: 0; + list-style: none; + } + .summary-findings li { + display: flex; + align-items: flex-start; + gap: 8px; + color: #374151; + font-size: 14px; + line-height: 1.45; + } + .summary-findings li > span { + display: grid; + gap: 3px; + } + .summary-findings li strong { + color: #334155; + font-weight: 700; + } + .summary-findings li small { + color: #64748b; font-size: 12px; - color: var(--sublabel); - font-weight: 500; + line-height: 1.45; } - - .btn-footer { + .summary-findings .review-status-icon { margin-top: 2px; } + .review-score-feedback { + width: 100%; + margin-top: 10px; + color: #6b7280; + font-size: 11px; + font-weight: 650; + text-align: center; + } + .review-score-feedback-controls { display: flex; + justify-content: center; + gap: 7px; + margin-top: 7px; + } + .review-score-feedback .feedback-btn { + width: 30px; + height: 30px; + border-radius: 6px; + opacity: 1; + } + .review-score-feedback .feedback-btn svg { width: 14px; height: 14px; } + body.results-fullscreen .bundle-strip { + grid-template-columns: auto 1px minmax(0, 1fr); + align-items: center; + gap: 16px; + padding: 10px 36px; + background: #f9fafb; + } + body.results-fullscreen .bundle-strip.visible { display: grid; } + .results-summary-tab { + display: inline-flex; align-items: center; gap: 8px; - padding: 10px 20px; - border-radius: 10px; - border: none; + min-height: 38px; + padding: 0 13px; + border: 1px solid #d1d5db; + border-radius: 7px; + color: #374151; + background: #fff; cursor: pointer; - font-size: 13px; - font-weight: 600; - font-family: "Delight", "DM Sans", sans-serif; - transition: all 0.2s ease; + font: 750 13px "Delight", "DM Sans", sans-serif; + } + .results-summary-tab:hover { color: #111827; border-color: #9ca3af; } + .results-summary-tab.active { + color: #fff; + border-color: #111827; + background: #111827; + } + .results-summary-tab svg { width: 16px; height: 16px; } + .results-nav-divider { + width: 1px; + height: 34px; + background: #d1d5db; + } + body.results-fullscreen .artifact-tab { + min-width: 148px; + padding: 8px 10px; + border-color: #e5e7eb; + border-radius: 7px; + } + body.results-fullscreen .artifact-tab.active { + border-color: #111827; + background: #fff; + box-shadow: inset 0 0 0 1px #111827; + } + body.results-fullscreen .artifact-tab-name { font-size: 13px; font-weight: 700; } + body.results-fullscreen .artifact-tab-meta { font-size: 11px; } + .panel-code-wrap { position: relative; } + .code-copy-button { + position: absolute; + z-index: 2; + top: 12px; + right: 12px; + display: inline-flex; + align-items: center; + gap: 6px; + padding: 7px 10px; + border: 1px solid #4b5563; + border-radius: 6px; + color: #d1d5db; + background: #272936; + cursor: pointer; + font: 700 11px "Delight", "DM Sans", sans-serif; + } + .code-copy-button:hover { color: #fff; border-color: #6b7280; background: #333544; } + .code-copy-button.copied { color: #bbf7d0; border-color: #166534; background: #14532d; } + body.results-fullscreen .panel-code-wrap pre { padding-top: 56px; } + body.results-fullscreen .results-action-bar { + display: grid; + grid-template-columns: repeat(3, minmax(0, 1fr)); + margin-top: auto; + padding: 10px 36px; + background: #fff; + } + body.results-fullscreen .results-action-bar .btn-header-action { + width: 100%; + min-height: 44px; + justify-content: center; + } + body.results-fullscreen .file-review-header h3 { font-size: 16px; } + body.results-fullscreen .file-review-header p, + body.results-fullscreen .review-finding, + body.results-fullscreen .dependency-list li, + body.results-fullscreen .file-relationship-list li { + font-size: 14px; + } + .results-view button:focus-visible, + .results-view summary:focus-visible { + outline: 2px solid #f97316; + outline-offset: 2px; } - .btn-footer:hover { transform: translateY(-1px); } - .btn-footer:active { transform: scale(0.97); } - .btn-footer:disabled { opacity: 0.5; cursor: not-allowed; transform: none; } - .btn-copy-footer { - background: #f1f5f9; - color: var(--navy); - border: 1px solid var(--border); + @media (max-width: 760px) { + .review-summary { grid-template-columns: 1fr; gap: 20px; } + .review-score-column { width: 100%; } + .review-score { width: 100%; min-height: 130px; } + body.results-fullscreen .results-summary-detail { max-height: 430px; padding: 22px 18px; } + body.results-fullscreen .bundle-strip { + grid-template-columns: auto 1px minmax(0, 1fr); + padding: 10px 18px; + } + body.results-fullscreen .artifact-tabs { grid-column: 1 / -1; width: 100%; } + body.results-fullscreen .results-header { padding: 12px 18px; } + body.results-fullscreen .results-header-left h2 { font-size: 22px; } + body.results-fullscreen .results-action-bar { grid-template-columns: 1fr; } } - .btn-copy-footer:hover:not(:disabled) { - background: #e2e8f0; + @media (max-width: 768px) { + body.results-fullscreen .sidebar, + body.results-fullscreen.results-with-sidebar .sidebar { + display: none; + } } - .btn-copy-footer.copied { - background: #065f46; - color: #a7f3d0; - border-color: #065f46; + @media (prefers-reduced-motion: reduce) { + .results-view *, + .results-view *::before, + .results-view *::after { + scroll-behavior: auto !important; + transition-duration: 0.01ms !important; + animation-duration: 0.01ms !important; + animation-iteration-count: 1 !important; + } + } + .hidden { + display: none !important; + } + + @media (max-width: 980px) { + .results-split { grid-template-columns: minmax(0, 1fr); overflow-y: auto; } + .results-panel { min-height: 420px; } + .results-panel + .results-panel { + border-top: 1px solid var(--border); + border-left: none; + } + } + + @media (max-width: 640px) { + .results-header, + .bundle-strip, + .results-summary-detail, + .results-action-bar { + padding-left: 14px; + padding-right: 14px; + } + .artifact-tab { min-width: 150px; } + .file-detail-grid { grid-template-columns: 1fr; } + .file-review-header { flex-direction: column; } + .file-review-meta { align-items: flex-start; } } .feedback-btn { @@ -1797,7 +2358,7 @@ .pm-cards { padding: 0 16px; } } - +
    @@ -2076,30 +2637,26 @@

    Generating your code...

    -

    Generation Results

    -

    Review the generated code and audit report below

    +

    Generation Results

    + 0 files
    -
    -
    - 1 - Artifacts -
    -
    - 1 - Ready -
    -
    - 0 - Warnings -
    -
    + +
    -
    +
    + +